<?php

$query = "SELECT `value` FROM `setting` WHERE `name` = 'Domain Passwords are Encrypted'";
$result = mysql_query($query) or die("ERROR in query: $query");
list($encrypted) = mysql_fetch_row($result);

if($encrypted == 1){

    require_once 'encrypted/Clientexec.php';
    require_once 'newedge/classes/NE_PluginCollection.php';
    $plugins = new NE_PluginCollection("server", $this->user);
    $encryptable = array();
    while ($plugin = $plugins->getNext()){
        $vars = $plugin->getVariables();
        $val =$this->db->escape_string($plugin->getInternalName());
        foreach ($vars as $key => $var){
            $tKey = str_replace(" ","_",$key);
            $tKey =$this->db->escape_string($tKey);
            if(isset($var["encryptable"]) && $var["encryptable"] == true){
                $encryptable[]= "plugin_".$val."_$tKey";
            }
        }
    }
    
    $query2 = "SELECT `serverid`, `optionname`, `value` FROM `serverplugin_options` WHERE `optionname` IN ('".implode("','", $encryptable)."')";
    $result2 = mysql_query($query2) or die("ERROR in query: $query2");

    $originalValuesArray = array();
    while (list($serverid, $optionname, $value) = mysql_fetch_row($result2)) {
        $decryptedValue = Clientexec::decryptString($value);
        
        $originalValuesArray[] = array('serverid'       => $serverid,
                                       'optionname'     => $optionname,
                                       'decryptedValue' => $decryptedValue,
                                      );
    }

    # ---------------------------------------------------------
    # CHANGED TYPE OF FIELD `VALUE` IN THE TABLE `SERVERPLUGIN_OPTIONS` TO FIX AN ISSUE WITH ENCRYPTING/DECRYPTING SERVER PLUGIN PASSWORDS WHEN USING A DIFFERENT CHARACTER SET
    # ---------------------------------------------------------
    $alterTable = "ALTER TABLE `serverplugin_options` CHANGE `value` `value` LONGBLOB NOT NULL";
    mysql_query($alterTable) or die("ERROR in query: $alterTable");

    foreach($originalValuesArray AS $originalValues){
        $encryptedValue = Clientexec::encryptString($originalValues['decryptedValue']);

        $update = "UPDATE `serverplugin_options` SET `value` = '".mysql_real_escape_string($encryptedValue)."' WHERE `serverid` = ".$originalValues['serverid']." AND `optionname` = '".mysql_real_escape_string($originalValues['optionname'])."'";
        mysql_query($update) or die("ERROR in query: $update");
    }

}

?>
