<?php
ini_set('display_errors', '1');
/*
Plugin Name: Kronet connect Server
Plugin URI: http://www.irontec.com
Description: Kronet connect adapter.
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 db version
define( 'KRONET_CONNECT_SERVER', '0.1' );
define( 'KRONET_CONNECT_SERVER_DB_VERSION', '0.1' );

// Activation hook
register_activation_hook( __FILE__, 'kronet_connect_activation' );
// Deactivation hook
register_deactivation_hook( __FILE__, 'kronet_connect_deactivation' );

// DEFINIMOS SLUG: OAUTHCONNECT
// ESTO ES PARA PODER USAR KRONET CONNECT SIN TENER TWITCONNECT ACTIVADO
if ( !defined( 'BP_IRON_OUATHCONNECT_SLUG' ) ) {

	define( 'BP_IRON_OUATHCONNECT_SLUG', 'oauth' );

	function my_setup_root_oauthconnect () {
		bp_core_add_root_component( BP_IRON_OUATHCONNECT_SLUG );
	}

	add_action( 'bp_setup_root_components', 'my_setup_root_oauthconnect' );

	function my_action_iron_oauthconnect() {
		global $bp;

		if ( $bp->current_component == BP_IRON_OUATHCONNECT_SLUG ) {
			do_action( 'my_action_iron_oauthconnect' );
			bp_core_load_template( apply_filters( 'bp_core_template_iron_oauthconnect', 'registration/oauth/register' ) );
		}
	}
	add_action( 'wp', 'my_action_iron_oauthconnect', 1 );
}

/*
Activation of the plugin.
*/
function kronet_connect_activation() {

    global $wpdb;

    $table = $wpdb->get_results("show tables like '".$wpdb->prefix."kconnect_satellites'");

    if(count($table) == 0) {

        $createTable = "CREATE TABLE `".$wpdb->prefix."kconnect_satellites` (
                        `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                        `siteName` varchar(100) NOT NULL,
                        `domain` varchar(150) NOT NULL,
                        `logo` varchar(200) NUll,
                        `Key` varchar(200) NOT NULL,
                        `status` int(11) NOT NULL,
                        PRIMARY KEY (`id`)
                        )";

        $wpdb->query($createTable);
    }

    if (get_option( "kconnect_status")) {

        update_option( "kconnect_enabled", "1");
    }

	return true;
}

/*
Deactivation of the plugin.
*/
function kronet_connect_deactivation() {

    update_option( "kconnect_enabled", 0 );
	return true;
}

/****************************************************
 ****************** Admin Page **********************
 ****************************************************/

/*
 * Tell WP about the Admin page
 */

function kronet_admin_page()
{
    add_options_page("kronet connect Options", 'kronet connect server', 'administrator', "wp-kronet-connect", 'kronet_connect_admin_page');
}
add_action('admin_menu', 'kronet_admin_page');

/**
  * Link to Settings on Plugins page
  */
add_filter('plugin_action_links', 'kronet_connect_add_plugin_links', 10, 2);
function kronet_connect_add_plugin_links($links, $file)
{
    if( dirname(plugin_basename( __FILE__ )) == dirname($file) )
        $links[] = '<a href="options-general.php?page=' . "wp-kronet-connect" .'">' . __('Settings','sitemap') . '</a>';
    return $links;
}

/***
 * handle admin page posts
 */
 function kronet_connect_admin_page_post_handler () {

    global $wpdb;

    //Activo [Si|No]
    if ( isset($_POST["enabled"]) and $_POST["enabled"] != "") {

        update_option( "kconnect_enabled", $_POST["enabled"] );
    }

    //Añadir nuevo site
    if (isset($_POST["action"]) and $_POST["action"] == "addSite") {

        $sitexx = $wpdb->get_results('select * from wp_kconnect_satellites');

        //validaciones
        foreach ($sitexx as $addsitees)
        {
        	if($addsitees->siteName!=$_POST["siteName"])
        	{
        		if($addsitees->domain!=$_POST["siteUrl"])
        		{
			        $logo = "";

			        if (isset($_FILES["logo"]["name"]) and $_FILES["logo"]["name"] != "") {

			            $logo = $_FILES["logo"]["name"];

			            while (file_exists("images/".$logo)) {

			                $logo = rand(0,9).$logo;
			            }

			            move_uploaded_file($_FILES["logo"]["tmp_name"], dirname(__FILE__)."/images/".$logo);
			        }

			        $data = array(
			            "siteName" => $_POST["siteName"],
			            "domain" => $_POST["siteUrl"],
			            "key" => "",
			            "status" => "0",
			            "logo" => $logo
			        );

			        $errors = array();

			        if (empty($data["siteName"])) {

			            $errors[] = "Nombre incorrecto";
			        }

			        if (empty($data["domain"])) {

			            $errors[] = "Dominio incorrecto";
			        }

			        if (count($errors) > 0) {

			            return array("addError" => implode("<br />", $errors));
			        }

			        if (substr($data["domain"], strlen($data["domain"])-1) != "/") {

			            $data["domain"] .= "/";
			        }

        		} else {

        		    echo '<span style="color:red">El Dominio Ya Existe</span><br />';
        		    return;
        		}

        	} else {

        	    echo '<span style="color:red">El Nombre Ya Existe</span><br />';
        	    return;
        	}
        }

        /***
         * Los datos parecen correctos, procedemos a la guardarlo en base de datos
         */
        $logo = "";

        if (isset($_FILES["logo"]["name"]) and $_FILES["logo"]["name"] != "") {

            $logo = $_FILES["logo"]["name"];

            while (file_exists("images/".$logo)) {

                $logo = rand(0,9).$logo;
            }

            move_uploaded_file($_FILES["logo"]["tmp_name"], dirname(__FILE__)."/images/".$logo);
        }

        $data = array(
            "siteName" => $_POST["siteName"],
            "domain" => $_POST["siteUrl"],
            "key" => "",
            "status" => "0",
            "logo" => $logo
        );

        if (substr($data["domain"], strlen($data["domain"])-1) != "/") {

            $data["domain"] .= "/";
        }

        $id = $wpdb->insert($wpdb->prefix."kconnect_satellites", $data);
    }


     //Editar site
    if (isset($_POST["Submit"]) and $_POST["Submit"] == "Edit") {

        $logo = "";

        if (isset($_FILES["logo"]["name"]) and $_FILES["logo"]["name"] != "") {

            $logo = $_FILES["logo"]["name"];

            while (file_exists("images/".$logo)) {

                $logo = rand(0,9).$logo;
            }

            move_uploaded_file($_FILES["logo"]["tmp_name"], dirname(__FILE__)."/images/".$logo);
        }

        $data = array(
            "siteName" => $_POST["siteName"],
            "domain" => $_POST["siteUrl"],
            "key" => "",
            "logo" => $logo
        );

        $errors = array();

        if(empty($data["siteName"])) {

            $errors[] = "Nombre incorrecto";
        }

        if(empty($data["domain"])) {

            $errors[] = "Dominio incorrecto";
        }

        if (count($errors) > 0) {

            return array("addError" => implode("<br />", $errors));
        }

        if (substr($data["domain"], strlen($data["domain"])-1) != "/") {

            $data["domain"] .= "/";
        }

        $where = array("id" => $_POST["id"]);

        global $wpdb;
        $wpdb->update($wpdb->prefix."kconnect_satellites", $data, $where);

    }

 }

 function kronet_connect_admin_page_get_handler() {

    //Eliminar registro
    if (isset($_GET["delete"])) {

        global $wpdb;
        $query = "delete from ".$wpdb->prefix."kconnect_satellites where id ='".$_GET["delete"]."' limit 1";
        $wpdb->query($query);
    }

    /***
     * Activar un plugin.
     * Connectarse a cliente e intercambio de claves
     */
    if (isset($_GET["activate"])) {

        $data = array(
            "signature" => $_SERVER["SERVER_SIGNATURE"],
            "date" => strtotime(date("d-m-Y")),
            "src" => $_SERVER["SCRIPT_FILENAME"]
        );

        $data = preg_replace("/[^0-9a-zA-Z]/", "", base64_encode(implode("", $data)));

        $length = rand(8,10);
        $pos = rand(0, strlen($data)-$length);
        $data = substr($data, $pos, $length);

        require_once("utilities.php");
        $blowfish = new Blowfish(array("key" => "1234"));

        global $wpdb;
        $query = "Select * from `".$wpdb->prefix."kconnect_satellites` where id = ".$_GET["activate"];
        $site = array_shift($wpdb->get_results($query));

        $postdata = http_build_query(
            array(
                'k1' => base64_encode($blowfish->encrypt($data)),
                'sid' => $site->id
            )
        );

        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context  = stream_context_create($opts);

        if (substr($site->domain, strlen($site->domain)-1) != "/") {

            $site->domain .= "/";
        }

        $domain = trim($site->domain."wp-content/plugins/kronet-connect/handshake.php");

        $result = file_get_contents($domain, false, $context);

        $blowfish->key = $data;

        $k2 = $blowfish->decrypt(base64_decode($result));

        if($k2{0} == "o") {

            if(substr($k2,-1) == "k") {

                $k2 = substr($k2,1,-1);
                $ktest = preg_replace("/[^0-9a-zA-Z]/", "", $k2);

                if ($k2 == $ktest) {

                    $query = "update ".$wpdb->prefix."kconnect_satellites set `status`='1', `Key`='".$data.$k2."' where id ='".$_GET["activate"]."' limit 1";
                    $wpdb->query($query);

                    return array(
                        "message" => "Portal activado correctamente!"
                    );
                }
            }
        }

        return array(
            "message" => "Respuesta inesperada: ".$result
        );
    }
 }

/*
 * Output the Admin page
 */
function kronet_connect_admin_page()
{

    if (count($_POST) > 0) {

        $resp = kronet_connect_admin_page_post_handler();
    }

    if (count($_GET) > 1) {

        $resp = kronet_connect_admin_page_get_handler();
    }

    ?>
    <div class="wrap">

     <h2><?php echo __("kronikoensarea connect Options","budypress");?></h2>
    <?php

        if(version_compare('5', PHP_VERSION, ">"))
        {
            ?><div class="error"><p><?php echo __("Sorry,  kronikoensarea connect requires PHP5."); ?></p></div><?php
            die();
        }

        $status = get_option("kconnect_enabled");
/*
	?>
    <style>
        .form-table input {

            cursor:text;
        }

    </style>

    <form name="formFacebook" method="post" action="options-general.php?page=wp-kronet-connect">
        <table class="form-table">
            <tbody>
                <tr>
                    <th>Activo: </th>
                    <td>
                        <select name="enabled" style="width:60px;">
                            <option value="1" <?php if($status == 1) { echo "selected"; } ?>>Si</option>
                            <option value="2" <?php if($status == 0) { echo "selected"; } ?>>No</option>
                        </select>
                    </td>
                </tr>
            </tbody>
        </table>
        <input type="submit" class="button-primary" name="Submit" value="Save" />

    </form>
    <hr />
     <?php
     */
        if (isset($resp["message"])) {
     ?>
        <div style="background-color: rgb(238, 238, 238); border-bottom: 1px solid red;"><?php echo $resp["message"]; ?></div>
     <?php
        }
     ?>
    <h2>Sites registrados</h2>
    <?php
        global $wpdb;
        $query = "Select * from `".$wpdb->prefix."kconnect_satellites`";
        $sites = $wpdb->get_results($query);
    ?>
    <table class="wp-list-table widefat plugins" cellspacing="0">
    <thead>
        <tr>
            <th class="manage-column column-cb">Nombre</th>
            <th class="manage-column column-name">Url</th>
            <th class="manage-column column-name">Estado</th>
            <th width="160px" class="manage-column column-description"></th>
        </tr>
    </thead>
    <tbody>
    <?php
    foreach ($sites as $site) {
    ?>
    <tr>
        <td><?php echo $site->siteName; ?></td>
        <td><?php echo $site->domain; ?></td>
        <td><?php echo $site->status == 0 ? "desactivado" : "activado"; ?></td>
        <td>
            <a href="options-general.php?page=wp-kronet-connect&activate=<?php echo $site->id; ?>">
                <input type="submit" class="button-primary" value="<?php echo $site->status == 0 ? "Activar" : "Renovar clave"; ?>"  />
            </a>
            <a href="options-general.php?page=wp-kronet-connect&delete=<?php echo $site->id; ?>">
                <input type="button" class="button-primary" value="Eliminar"  />
           	<a href="options-general.php?page=wp-kronet-connect&edit=<?php echo $site->id; ?>">
                <input type="button" class="button-primary" value="Editar"  />
            </a>
        </td>
    </tr>
    <?php
    }

    if (count($sites) == 0) {
    ?>
    <tr>
        <td colspan="4"><center>Ningún site añadido</center></td>
    </tr>
    <?php
    }
    ?>
    </tbody>
    </table>
    <hr />

    <h2>
    <?php
    if (!isset($_GET["edit"])){
    ?>
    Añadir site
    <?php }
	if (isset($_GET["edit"])){
    ?>
    Editar Site
    <?php } ?>
    </h2>
     <?php
        if (isset($resp["addError"])) {
     ?>
        <div style="background-color: rgb(238, 238, 238); border-bottom: 1px solid red;"><?php echo $resp["addError"]; ?></div>
     <?php
        }


if (!isset($_GET["edit"]))
        {
    ?>
    <form name="formFacebook" method="post" action="options-general.php?page=wp-kronet-connect" enctype="multipart/form-data">
        <input type="hidden" name="action" value="addSite" />
        <div class="submit">
            <table class="form-table">
            <tbody>
                <tr>
                    <th>Nombre: </th>
                    <td><input type="text" name="siteName" value="" /></td>
                </tr>
                <tr>
                    <th>Url: </th>
                    <td><input type="text" name="siteUrl" value="" /></td>
                </tr>
                <tr>
                    <th>Logo: </th>
                    <td><input type="file" name="logo" value="" size="11px" /></td>
                </tr>
            </tbody>
            </table>
            <input class="button-primary" type="submit" name="Submit" value="Save" />
        </div>
    </form>
<?php
}
if (isset($_GET["edit"])) {


	$editsites = $wpdb->get_results('select *from wp_kconnect_satellites where id="'.$_GET["edit"].'"');

	foreach ($editsites as $editsite)
	{
		?>

<form name="formFacebook" method="post" action="options-general.php?page=wp-kronet-connect" enctype="multipart/form-data">
        <input type="hidden" name="action" value="editSite" />
        <input type="hidden" name="id" value="<?php echo $_GET["edit"]; ?>" />
        <div class="submit">
            <table class="form-table">

            <tbody>
                <tr>
                    <th>Nombre: </th>
                    <td><input type="text" name="siteName" value="<?php echo $editsite->siteName; ?>" /></td>
                </tr>
                <tr>
                    <th>Url: </th>
                    <td><input type="text" name="siteUrl" value="<?php echo $editsite->domain; ?>" /></td>
                </tr>
                <tr>
                    <th>Logo: </th>
                    <td><input type="file" name="logo" value="<?php echo $editsite->logo; ?>" size="11px" /></td>
                </tr>
            </tbody>
            </table>
            <input class="button-primary" type="submit" name="Submit" value="Edit" />
        </div>
    </form>

<?php
	}
?>

<?php }?>

   </div><?php
}

