<?php

/*
# ------------------------------------------------------
# Remove email from queue when user does not exist in DB
# ------------------------------------------------------
*/

$query1 = "SELECT DISTINCT eqa.userid FROM email_queue_addressees eqa LEFT JOIN users u ON eqa.userid = u.id WHERE u.id IS NULL";
$result1 = mysql_query($query1) or die("ERROR in query: $query1");
while ($row1 = mysql_fetch_array($result1)) {
    $query2 = "SELECT eqa1.email_queue_id, COUNT(eqa2.email_queue_id) AS `count` FROM email_queue_addressees eqa1, email_queue_addressees eqa2 WHERE eqa1.userid = ".$row1['userid']." AND eqa1.email_queue_id = eqa2.email_queue_id GROUP BY eqa2.email_queue_id";
    $result2 = mysql_query($query2) or die("ERROR in query: $query2");
    while ($row2 = mysql_fetch_array($result2)) {
        if($row2['count'] == 1){
            $query3 = "DELETE FROM email_queue WHERE id = ".$row2['email_queue_id'];
            mysql_query($query3) or die("ERROR in query: $query3");
        }
    }
    $query4 = "DELETE FROM email_queue_addressees WHERE userid = ".$row1['userid'];
    mysql_query($query4) or die("ERROR in query: $query4");
}


$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){

    /*
     * --------------------------------------
     * PASSWORDS ENCRYPTION OF SERVER PLUGINS
     * --------------------------------------
     */
    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");

    while (list($serverid, $optionname, $value) = mysql_fetch_row($result2)) {
        $encryptedValue = $this->encryptData($value);

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

?>
