<?php
/*
Plugin Name: Irontec - Private Site
Plugin URI: http://code.irontec.com
Description: Make your site private, excluding the pages you want. Invitations system included.
Version: 0.1
Author: Irontec
Author URI: http://www.irontec.com
License: GNU General Public License 2.0 (GPL) http://www.gnu.org/licenses/gpl.html
*/

// Define plugin version and plugin url
define( 'IRON_PRIVATESITE_VERSION', '0.1' );
define( 'IRON_PRIVATESITE_URL', WP_PLUGIN_URL . '/irontec-privatesite' );

// Enqueue plugin basic style
wp_enqueue_style('iron-privatesite-css-style', IRON_PRIVATESITE_URL .'/css/style.css');

// Add the plugin Administration Menu
add_action('admin_menu', 'iron_privatesite_create_menu');

/**
 * Add the Hook into the header
 * Use wp_head so that the plugin works with and without buddypress installed
 * 
 */
//add_action('wp_head', 'iron_privatesite_display');
add_action('bp_head', 'iron_privatesite_display');

/**
 * Display/Execute
 */
function iron_privatesite_display ($content='') {
    
    global $bp;
    
    if ( get_site_option('iron_privatesite_enabled') == 1) {
        // Logged in users
        if (is_user_logged_in()) {
            
            // Redirect logged in users from the front_page
            if ( bp_is_front_page() ) {
                wp_redirect( site_url() . "/activity" );
            }
            
            // Redirect logged in users from the activation page
            if ( $bp->current_component == "activate" ) {
                wp_redirect( site_url() . "/activity" );
            }
            
            // Redirect logged in users from the registration page
            if ( $bp->current_component == "register" ) {
                wp_redirect( site_url() . "/activity" );
            }
            // We redirect to /profile if in members home
            elseif ( $bp->current_component == "activity" && $bp->current_action != "" ) {
                //wp_redirect( site_url() . "/members/". bp_get_displayed_user_username() ."/profile" );
            }
            
        }
        // Logged out users will be redirected to the landing page
        else {
            // Page exclude list
            $excludelist=get_site_option(iron_privatesite_excludelist);
            
            // If not front page
            if ( !bp_is_front_page() ) {
            
                // Excludelist
                $isprivate = 1;
                for ($i=0; $i<sizeof($excludelist); $i++) {
                    if ( is_page ($excludelist[$i])== 1 ) $isprivate=0;
                }
                
                // By default, these are always public
                if ($bp->current_component == "register") $isprivate=0;
                if ($bp->current_component == "oauth") $isprivate=0;
                if ($bp->current_component == "activate") $isprivate=0;
                if ($bp->current_component == "passreset") $isprivate=0;
                if (strpos($_SERVER["SCRIPT_FILENAME"], "wp-login.php") !== false) $isprivate=0;
                if (strpos($_SERVER["SCRIPT_FILENAME"], "kronet-login.php") !== false) $isprivate=0;
                
                // If after all the checks, the section is private, redirect
                if ($isprivate == 1) wp_redirect( site_url() );
                
            }
        }
    }
}

/**
 * Administration Menu
 */
function iron_privatesite_create_menu() {

    //create new top-level menu
    add_menu_page('Private Site', 'Private Site', 'manage_options', 'iron-privatesite-menu', 'iron_privatesite_settings_page', plugins_url('/images/irontec.gif', __FILE__));
    //add_submenu_page( 'iron-privatesite-menu', 'Settings', 'Settings', 'manage_options', 'iron_privatesite_submenu_settings', 'iron_privatesite_settings_page',0);

    //call register settings function
    add_action( 'admin_init', 'iron_privatesite_settings' );
}

/**
 * Administration Settings
 */
function iron_privatesite_settings() {
    // These options are global
    register_setting( 'iron-privatesite-settings-group', 'iron_privatesite_enabled' );
    register_setting( 'iron-privatesite-settings-group', 'iron_privatesite_excludelist' );
    register_setting( 'iron-privatesite-settings-group', 'iron_privatesite_registration' );
}

/**
 * Administration Settings page
 */
function iron_privatesite_settings_page() {

    // TABBER
    wp_deregister_script( 'tabber' );
    wp_register_script( 'tabber', get_stylesheet_directory_uri() .'/_inc/tabber/tabber.js' );
    wp_print_scripts( 'tabber' );
    wp_deregister_style('tabber-css');
    wp_enqueue_style('tabber-css', get_stylesheet_directory_uri() . '/_inc/tabber/tabber.css');
    wp_print_styles('tabber-css');
    ?>
    <div id="iron-privatesite" class="admindiv wrap">

        <img style="float: left; margin: 13px;" src="<?php echo IRON_PRIVATESITE_URL; ?>/images/logo_irontec_2.0.png" />
        <h2>Private Site</h2>

        <div class="tabber">
    
            <div class="tabbertab">
              <h2>Invitations</h2>
    
              <form id="iron-privatesite-form-invite" method="post" action="">
                <fieldset style="padding-top: 10px;">
                    <legend><b>&nbsp;Send Invitations&nbsp;</b></legend>
    
                    <input type="text" name="Invitation" value="<?php if ($_POST['Invitation']) { echo $_POST['Invitation']; } ?>" style="width: 200px;">
                    <input type="submit" value="Send Invitation">
                    <input type="hidden" name="confirm" value="true">
    
                    <?php
                    global $wpdb;
                    $InvitationEmail=sanitize_email ($_POST['Invitation']);
    
                    if ($InvitationEmail && $_POST['confirm']==true) {
    
                        // Check exists
                        $table_name = 'iron_invitations';
                        $exists = $wpdb->get_results( "SELECT id FROM ".$table_name."
                        WHERE email LIKE '".$InvitationEmail."'");
    
                        // If not exist
                        if (!$exists[0]->id) {
    
                            // Generamos el pass y obtenemos el username
                            // Hacemos la misma limpieza que hace bp_core_signup_user
                            $Email = explode('@', $InvitationEmail);
                            $Username = sanitize_title($Email[0]);
                            $Password = IronGenPassword(8,2);
    
                            // Verificamos que el user no este en wp (ni con el email ni con el usuario)!
                            $user_id = username_exists( $Username );
                            if (!$user_id) $user_id = email_exists($InvitationEmail);
    
                            // If does not exist in wp
                            if (!$user_id) {
    
                                // Insert invitation
                                $table_name = 'iron_invitations';
                                $wpdb->query('INSERT INTO '.$table_name.' (email) VALUES ("'.$InvitationEmail.'")');
                                $new_id=$wpdb->insert_id;
    
                                // Si todo ha ido bien
                                if ($new_id && $Username && $Password) {
    
                                    // Create user
                                    $user_id=bp_core_signup_user($Username, $Password, $InvitationEmail, '' );
                                    update_user_meta( $user_id, 'activation_key', wp_hash( $user_id ) );
    
                                    // Add User meta
                                    update_user_meta( $user_id, 'first_name', $Username);
                                    update_user_meta( $user_id, 'bp_profile_privacy', 's:49:"a:5:{i:0;s:0:"";i:2;i:0;i:3;i:0;i:4;i:0;i:5;i:0;}";');
    
                                    // Profile data
                                    if ( function_exists( 'xprofile_set_field_data' ) ) {
                                        if ( !empty( $signup_profile_field_ids ) ) {
                                            $profile_field_ids = explode( ',', $signup_profile_field_ids );
    
                                            foreach( (array)$profile_field_ids as $field_id ) {
    
                                                //Xprofile Field IDs
                                                //nombrecompleto= 1
                                                //apellidos= 2
                                                //poblacion= 3
                                                //patologia= 4
                                                //estadoanimo= 5
                                                //categoria= 10
                                                //privacidad= 15
                                                if ($field_id == 1) $current_field_data=$NombreCompleto;
                                                elseif ($field_id == 2) $current_field_data=' ';
                                                elseif ($field_id == 3) $current_field_data=' ';
                                                elseif ($field_id == 4) $current_field_data=' ';
                                                elseif ($field_id == 5) $current_field_data='sintomaticos';
                                                elseif ($field_id == 10) $current_field_data='sintomaticos';
                                                elseif ($field_id == 15) $current_field_data=' ';
    
                                                if ( !empty( $current_field_data ) )
                                                    xprofile_set_field_data( $field_id, $user_id, $current_field_data );
                                            }
                                        }
                                    }
    
                                    // Obtain the activation key for the user
                                    $actkey = get_user_meta ($user_id, 'activation_key');
    
                                    // Email subject
                                    $asunto = 'Invitacion a kronikoensarea.net';
    
                                    // Email data
                                    $mensaje = '
                                    <p>Hola !</p>
                                    <p>Has sido invitado a participar en la versi&oacute;n <i>beta</i> de la red <b>kronikoensarea.net</b>.</p>
                                    <p>Para acceder, pincha <b><a href="'. site_url() .'/activate/?key='. $actkey[0] .'">aqu&iacute;</a></b></p>
                                    <p>y una vez activada, podr&aacute;s acceder con los siguientes datos de acceso:</p>
                                    <p>
                                    <b>usuario:</b> '. $Username .'<br />
                                    <b>clave:</b> '. $Password .'</p>
                                    ';
    
                                    // Send email with activation key
                                    wp_mail ($_POST['Invitation'], $asunto, $mensaje);
    
                                    echo '<div class="clear">&nbsp;</div>';
                                    echo '&nbsp;<i>Se ha enviado un Email a:&nbsp;'. $InvitationEmail .'</i>';
                                }
                                else {
                                    echo '<div class="clear">&nbsp;</div>';
                                    echo '&nbsp;<i>Ya existe un usuario con este email o login:&nbsp;'. $InvitationEmail .' o '. $Username .'</i>';
                                }
                            }
                            else {
                                echo '<div class="clear">&nbsp;</div>';
                                echo '&nbsp;<i>Ya existe un usuario con este email o login:&nbsp;'. $InvitationEmail .' o '. $Username .'</i>';
                            }
                        }
                        else {
                            echo '<div class="clear">&nbsp;</div>';
                            echo '&nbsp;<i>Ya existe una invitaci&oacute;n con este email:&nbsp;'. $InvitationEmail .'</i>';
                        }
                    }
                    else {
                        if ($InvitationEmail) {
                            echo '<div class="clear">&nbsp;</div>';
                            echo '&nbsp;<i>No has introducido un email v&aacute;lido.</i>';
                        }
                    }
                    ?>
    
                </fieldset>
            </form>
    
            <fieldset style="padding-top: 10px;">
            <form id="iron-privatesite-form-invite" method="post" action="">
                <legend><b>&nbsp;Invitations&nbsp;</b></legend>
                <?php
                
                if (isset($_POST['Del'])) {
                    $table_name = "iron_invitations";
                    $wpdb->query("DELETE FROM ".$table_name." WHERE id = '". $_POST['Del'] ."'");
                    echo '<div class="clear">&nbsp;</div>';
                    echo '&nbsp;<i>Invitaci&oacute;n eliminada</i><br />';
                }
                
                if (isset($_POST['Resend'])) {
                    
                    $table_name = "iron_invitations";
                    
                    $user = $wpdb->get_row("select * FROM ".$table_name." WHERE id = '". $_POST['Resend'] ."'");
                                    
                    $news_pass = IronGenPassword(8,2);
                    $new_pass_code = md5($news_pass);
                    $user_login = $wpdb->get_row("select * FROM " . $wpdb->prefix . "users WHERE user_email = '". $user->email ."'");
                    $wpdb->get_col('update '.$wpdb->prefix.'users set user_pass="' . $new_pass_code .'" where user_email="'. $user->email .'"');
                    
                    echo '<div class="clear">&nbsp;</div>';
                    echo '&nbsp;<i>Invitaci&oacute;n Reenviada a: ' . $user->email . '</i><br />';
    
                    $codigo_act = $wpdb->get_row("select * FROM " . $wpdb->prefix . "usermeta WHERE user_id = '". $user_login->ID ."' and meta_key='activation_key'");
                    
                    $asunto = 'Invitacion a kronikoensarea.net';
    
                    // Email data
                    $mensaje = '
                    <p>Hola !</p>
                    <p>Has sido invitado a participar en la versi&oacute;n <i>beta</i> de la red <b>kronikoensarea.net</b>.</p>
                    <p>Para acceder, pincha <b><a href="'. site_url() .'/activate/?key='. $codigo_act->meta_value .'">aqu&iacute;</a></b></p>
                    <p>y una vez activada, podr&aacute;s acceder con los siguientes datos de acceso:</p>
                    <p>
                    <b>usuario:</b> '. $user_login->user_login .'<br />
                    <b>Password:</b> '. $news_pass .'</p>
                    ';
                    
                    // Send email with activation key
                    wp_mail ($user->email, $asunto, $mensaje);
                    
                }
    
                $table_name = "iron_invitations";
                $results = $wpdb->get_results( "SELECT * FROM ".$table_name." ORDER BY email" );
                if (sizeof($results)>0) { ?>
    
                    <table width="700" cellspacing="2">
                    <tr>
                        <td align="left"><b>Email</b></td>
                        <td align="center" width="250"><b>Actions</b></td>
                    </tr>
                    <?php
                    foreach ($results as $invit) {
                        echo '<tr>';
                        echo '<td align="left">'. $invit->email .'</td>';
                        echo '<td align="center">';
                        echo '<button name="Resend" value="'. $invit->id.'">Resend Invitation</button>';
                        echo '&nbsp;|&nbsp;';
                        echo '<button name="Del" value="'. $invit->id.'">Delete</button>';
                        echo '</td>';
                        echo '</tr>';
                    }
                    echo '</table>';
                }
                else
                    _e('No invitations pending.','buddypress');
                ?>
                </form>
            </fieldset>
    
            </div> <!-- .tabbertab -->
    
            <div class="tabbertab">
              <h2>General Settings</h2>
    
              <form id="iron-privatesite-form" method="post" action="options.php">
                <fieldset>
                <legend><b>&nbsp;Global Settings&nbsp;</b></legend>
                <?php settings_fields( 'iron-privatesite-settings-group' ); ?>
                <table id="iron-settings-table" class="form-table">
                    <tr valign="top">
                    <td class="iron-td">Make this site Private</td>
                    <td style="width: 150px;">
                    <input type="checkbox" name="iron_privatesite_enabled" value="1" <?php if (get_option('iron_privatesite_enabled')== "1") echo "checked"; ?>>
                    </td>
                    </tr>
                    </tr>
                    <tr valign="top">
                    <td class="iron-td">Registration mode</td>
                    <td style="width: 150px;">
                    <input type="radio" name="iron_privatesite_registration" value="1" <?php if (get_option('iron_privatesite_registration')== "1") echo "checked"; ?>> Open Registration<br />
                    <input type="radio" name="iron_privatesite_registration" value="2" <?php if (get_option('iron_privatesite_registration')== "2") echo "checked"; ?>> Invitation only
                    </td>
                    </tr>
                    <tr valign="top">
                    <td class="iron-td">Exclude this pages<br />
                    <i>The pages you check here will be displayed to all users.</i>
                    </td>
                    <td style="width: 150px;">
                    <select multiple name="iron_privatesite_excludelist[]" style="height: 100px; width: 140px;">
                    <?php
                    $excludelist=get_site_option(iron_privatesite_excludelist);
                    $page_list = get_pages();
                    foreach ($page_list as $pag) {
                        $selected="";
                        if (in_array($pag->post_title, $excludelist)) $selected=" selected";
                        echo '<option value="'.$pag->post_title.'" '.$selected.'>'.$pag->post_title.'</option>';
                    }
                    ?>
                    </select>
                    </td>
                </table>
    
                <p class="submit">
                <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
                </p>
    
                </fieldset>
            </form>
    
            </div> <!-- .tabberab -->
    
        </div> <!-- .tabber -->

    </div> <!-- .admindiv wrap -->
<?php }

/**
 * IRONTEC solo entra el usuario admin a wp-admin
 */

function restrict_admin(){
    //if not administrator, kill WordPress execution and provide a message
    
    if ( !current_user_can('administrator') ) {
    
        if ($_SERVER['REQUEST_URI'] != '/wp-admin/admin-ajax.php' and $_SERVER['REQUEST_URI'] != '/wp-admin/media-upload.php?type=image&tab=type&post_id=0') {
            
        if ($_SERVER['REQUEST_URI'] != '/wp-admin/async-upload.php') {
            
        if ($_SERVER['REQUEST_URI'] != '/wp-admin/media-upload.php?post_id=0&tab=type_url' and $_SERVER['REQUEST_URI'] != '/wp-admin/media-upload.php?post_id=0&tab=library') {
            
        if ($_SERVER['REQUEST_URI'] != '/wp-admin/media-upload.php?type=file&tab=library&post_id=0') {
            
        if ('/wp-admin/media-upload.php?post_id=0&' != $_SERVER['REQUEST_URI'] and '/wp-admin/media-upload.php?post_id=0&tab=type' != $_SERVER['REQUEST_URI'] ) {
            
        if ( $_SERVER['SCRIPT_NAME'] != "/wp-admin/admin-ajax.php" ){
                //var_dump($_SERVER['REQUEST_URI']);die();
                wp_redirect (site_url());
                //wp_die( __('You are not allowed to access this part of the site', 'wordpress') );
        }
        
        }
        
        }
        
        }
        
        }
        
        }
    }
}
add_action( 'admin_init', 'restrict_admin', 1 );
?>