protected function process_data(&$user, &$msg)
 {
     $decoded_msg = $this->decode_data($user, $msg);
     //echo 'DECODED MSG: ' . $decoded_msg . PHP_EOL;
     foreach (explode(' ;; ', $decoded_msg) as $single_msg) {
         //echo strstr($single_msg . ' ', ' ', true) . PHP_EOL;
         $args = trim(strstr($single_msg, ' '));
         switch (strstr($single_msg . ' ', ' ', true)) {
             case 'search':
                 $this->search_pts($user, $args);
             case 'result_file':
                 foreach (explode(',', $args) as $result) {
                     if ($result == null) {
                         continue;
                     }
                     $result_file = new pts_result_file($result);
                     $json['pts']['msg']['name'] = 'result_file';
                     $json['pts']['msg']['result'] = $result;
                     $json['pts']['msg']['result_file'] = base64_encode($result_file->to_json());
                     $this->send_json_data($user->socket, $json);
                 }
                 break;
             case 'results_by_date':
                 $results = pts_tests::test_results_by_date();
                 $json['pts']['msg']['name'] = 'results_by_date';
                 $json['pts']['msg']['result_count'] = count($results);
                 $json['pts']['msg']['results'] = base64_encode(json_encode($results));
                 $this->send_json_data($user->socket, $json);
                 break;
             case 'results_grouped_by_date':
                 $results = pts_tests::test_results_by_date();
                 $json['pts']['msg']['name'] = 'results_grouped_by_date';
                 $json['pts']['msg']['result_count'] = count($results);
                 $sections = array(mktime(date('H'), date('i') - 10, 0, date('n'), date('j')) => 'Just Now', mktime(0, 0, 0, date('n'), date('j')) => 'Today', mktime(0, 0, 0, date('n'), date('j') - date('N') + 1) => 'This Week', mktime(0, 0, 0, date('n'), 1) => 'This Month', mktime(0, 0, 0, date('n') - 1, 1) => 'Last Month', mktime(0, 0, 0, 1, 1) => 'This Year', mktime(0, 0, 0, 1, 1, date('Y') - 1) => 'Last Year');
                 $section = current($sections);
                 foreach ($results as $result_time => &$result) {
                     if ($result_time < key($sections)) {
                         while ($result_time < key($sections) && $section !== false) {
                             $section = next($sections);
                         }
                         if ($section === false) {
                             break;
                         }
                     }
                     if (!isset($json['pts']['msg']['results'][current($sections)])) {
                         $json['pts']['msg']['results'][current($sections)] = array();
                     }
                     if ($result != null) {
                         $json['pts']['msg']['results'][current($sections)][] = $result;
                     }
                 }
                 $this->send_json_data($user->socket, $json);
                 break;
             case 'user-svg-system-graphs':
                 //	pts_client::timed_function(array($this, 'generate_system_svg_graphs'), array($user), 1, array($this, 'sensor_logging_continue'), array($user));
                 $this->generate_system_svg_graphs($user, $args);
                 break;
             case 'user-large-svg-system-graphs':
                 //	pts_client::timed_function(array($this, 'generate_system_svg_graphs'), array($user), 1, array($this, 'sensor_logging_continue'), array($user));
                 $this->generate_large_system_svg_graphs($user, $args);
                 break;
             case 'tests-by-popularity':
                 $args = explode(' ', $args);
                 $limit = isset($args[0]) && is_numeric($args[0]) ? $args[0] : 10;
                 $test_type = isset($args[1]) && $args[1] != null ? $args[1] : null;
                 $tests = pts_openbenchmarking_client::popular_tests($limit, $test_type);
                 $json['pts']['msg']['name'] = 'tests_by_popularity';
                 $json['pts']['msg']['test_count'] = count($tests);
                 $json['pts']['msg']['test_type'] = $test_type;
                 $json['pts']['msg']['tests'] = array();
                 $json['pts']['msg']['test_profiles'] = array();
                 foreach ($tests as $test) {
                     $json['pts']['msg']['tests'][] = $test;
                     $tp = new pts_test_profile($test);
                     $json['pts']['msg']['test_profiles'][] = base64_encode($tp->to_json());
                 }
                 $this->send_json_data($user->socket, $json);
                 break;
             case 'available-system-logs':
                 if ($this->phodevi_vfs instanceof phodevi_vfs) {
                     $json['pts']['msg']['name'] = 'available_system_logs';
                     $json['pts']['msg']['logs'] = $this->phodevi_vfs->list_cache_nodes($args);
                     $this->send_json_data($user->socket, $json);
                 }
                 break;
             case 'fetch-system-log':
                 if ($this->phodevi_vfs instanceof phodevi_vfs && $args != null && $this->phodevi_vfs->cache_isset_names($args)) {
                     $json['pts']['msg']['name'] = 'fetch_system_log';
                     $json['pts']['msg']['log_name'] = $args;
                     $json['pts']['msg']['log'] = base64_encode($this->phodevi_vfs->__get($args));
                     $this->send_json_data($user->socket, $json);
                 }
                 break;
             case 'pts-version':
                 $json['pts']['msg']['name'] = 'pts_version';
                 $json['pts']['msg']['version'] = pts_core::program_title(true);
                 $this->send_json_data($user->socket, $json);
                 break;
             case 'core-version':
                 $version = PTS_CORE_VERSION;
                 $this->send_data($user->socket, $version);
                 break;
             case 'run-benchmark-queue':
                 // BENCHMARK
                 //$this->run_benchmark($user, $args);
                 pts_client::fork(array($this, 'run_benchmark'), array($user, $args));
                 break;
         }
     }
 }
 public function __construct()
 {
     $systems_already_reported = array();
     pts_client::fork(array('pts_phoromatic_event_server', 'ob_cache_run'), null);
     $is_first_run = true;
     while (true) {
         $hour = date('G');
         $minute = date('i');
         phoromatic_server::prepare_database();
         if ($is_first_run || $minute == 0) {
             if ($is_first_run || $hour == 8) {
                 pts_client::fork(array('pts_phoromatic_event_server', 'ob_cache_run'), null);
             }
             // Check for basic hung systems
             $stmt = phoromatic_server::$db->prepare('SELECT LastCommunication, CurrentTask, EstimatedTimeForTask, SystemID, AccountID, LastIP FROM phoromatic_systems WHERE State > 0 ORDER BY LastCommunication DESC');
             $result = $stmt ? $stmt->execute() : false;
             while ($result && ($row = $result->fetchArray())) {
                 $last_comm = strtotime($row['LastCommunication']);
                 if ($last_comm > time() - 3600) {
                     continue;
                 }
                 // if last comm time is less than an hour, still might be busy testing
                 if ($last_comm < time() - 3600 * 3 && !$is_first_run) {
                     continue;
                 }
                 // it's already been reported enough for now...
                 if (stripos($row['CurrentTask'], 'shutdown') !== false || stripos($row['CurrentTask'], 'shutting down') !== false) {
                     continue;
                 }
                 // if the system shutdown, no reason to report it
                 if (phoromatic_server::estimated_time_remaining_diff($row['EstimatedTimeForTask'], $row['LastCommunication']) > 0) {
                     continue;
                 }
                 // system task time didn't run out yet
                 // UPDATE SYSTEM STATUS TO "UNKNOWN"
                 $stmt_unknown = phoromatic_server::$db->prepare('UPDATE phoromatic_systems SET CurrentTask = :unknown_state WHERE AccountID = :account_id AND SystemID = :system_id');
                 $stmt_unknown->bindValue(':account_id', $row['AccountID']);
                 $stmt_unknown->bindValue(':system_id', $row['SystemID']);
                 $stmt_unknown->bindValue(':unknown_state', 'Unknown');
                 $stmt_unknown->execute();
                 $stmt_email = phoromatic_server::$db->prepare('SELECT UserName, Email FROM phoromatic_users WHERE UserID IN (SELECT UserID FROM phoromatic_user_settings WHERE AccountID = :account_id AND NotifyOnHungSystems = 1) AND AccountID = :account_id');
                 $stmt_email->bindValue(':account_id', $row['AccountID']);
                 $result_email = $stmt_email->execute();
                 while ($row_email = $result_email->fetchArray()) {
                     if (empty($row_email['Email'])) {
                         continue;
                     }
                     phoromatic_server::send_email($row_email['Email'], 'Phoromatic System Potential Hang: ' . phoromatic_server::system_id_to_name($row['SystemID'], $row['AccountID']), phoromatic_server::account_id_to_group_admin_email($row['AccountID']), '<p><strong>' . $row_email['UserName'] . ':</strong></p><p>One of the systems associated with your Phoromatic account has not been communicating with the Phoromatic Server in more than sixty minutes. Below is the system information details:</p><p><strong>System:</strong> ' . phoromatic_server::system_id_to_name($row['SystemID'], $row['AccountID']) . '<br /><strong>Last Communication:</strong> ' . phoromatic_server::user_friendly_timedate($row['LastCommunication']) . '<br /><strong>Last Task:</strong> ' . $row['CurrentTask'] . '<br /><strong>Local IP:</strong> ' . $row['LastIP'] . '</p>');
                 }
             }
         }
         if ($is_first_run || $minute % 2 == 0) {
             // Check for systems to wake
             $stmt = phoromatic_server::$db->prepare('SELECT LastCommunication, CurrentTask, SystemID, AccountID, NetworkMAC, LastIP, MaintenanceMode FROM phoromatic_systems WHERE State > 0 AND NetworkMAC NOT LIKE \'\' AND NetworkWakeOnLAN LIKE \'%g%\' ORDER BY LastCommunication DESC');
             $result = $stmt ? $stmt->execute() : false;
             while ($result && ($row = $result->fetchArray())) {
                 if (!isset($phoromatic_account_settings[$row['AccountID']])) {
                     $stmt1 = phoromatic_server::$db->prepare('SELECT NetworkPowerUpWhenNeeded, PowerOnSystemDaily FROM phoromatic_account_settings WHERE AccountID = :account_id');
                     $stmt1->bindValue(':account_id', $row['AccountID']);
                     $result1 = $stmt1->execute();
                     $phoromatic_account_settings[$row['AccountID']] = $result1->fetchArray(SQLITE3_ASSOC);
                 }
                 $last_comm = strtotime($row['LastCommunication']);
                 if ($last_comm < time() - 360 && $row['MaintenanceMode'] == 1) {
                     self::send_wol_wakeup($row['NetworkMAC'], $row['LastIP']);
                     continue;
                 }
                 if ($minute % 20 == 0 && $last_comm < time() - 3600 * 18 && $phoromatic_account_settings[$row['AccountID']]['PowerOnSystemDaily'] == 1) {
                     // Daily power on test if system hasn't communicated / powered on in a day
                     // XXX right now the "daily" power on test is 18 hours. change or make user value in future?
                     // Just doing this check every 20 minutes as not too vital
                     self::send_wol_wakeup($row['NetworkMAC'], $row['LastIP']);
                     continue;
                 }
                 if ($last_comm < time() - 600 || stripos($row['CurrentTask'], 'Shutdown') !== false) {
                     // System hasn't communicated in a number of minutes so it might be powered off
                     if (phoromatic_server::system_has_outstanding_jobs($row['AccountID'], $row['SystemID']) !== false) {
                         // Make sure account has network WoL enabled
                         if ($phoromatic_account_settings[$row['AccountID']]['NetworkPowerUpWhenNeeded'] == 1) {
                             self::send_wol_wakeup($row['NetworkMAC'], $row['LastIP']);
                         }
                     }
                 }
             }
         }
         if ($minute % 8 == 0 && $hour > 1) {
             // See if system appears down
             $stmt = phoromatic_server::$db->prepare('SELECT LastCommunication, CurrentTask, SystemID, AccountID, LastIP FROM phoromatic_systems WHERE State > 0 ORDER BY LastCommunication DESC');
             $result = $stmt ? $stmt->execute() : false;
             while ($result && ($row = $result->fetchArray())) {
                 $sys_hash = sha1($row['AccountID'] . $row['SystemID']);
                 // Avoid sending duplicate messages over time
                 if (isset($systems_already_reported[$sys_hash]) && $systems_already_reported[$sys_hash] > time() - 3600 * 24) {
                     continue;
                 }
                 if (phoromatic_server::system_check_if_down($row['AccountID'], $row['SystemID'], $row['LastCommunication'], $row['CurrentTask'])) {
                     if (strtotime($row['LastCommunication']) < time() - 86400 * 7) {
                         // If system hasn't been online in a week, likely has bigger worries...
                         continue;
                     }
                     $stmt_email = phoromatic_server::$db->prepare('SELECT UserName, Email FROM phoromatic_users WHERE UserID IN (SELECT UserID FROM phoromatic_user_settings WHERE AccountID = :account_id AND NotifyOnHungSystems = 1) AND AccountID = :account_id');
                     $stmt_email->bindValue(':account_id', $row['AccountID']);
                     $result_email = $stmt_email->execute();
                     while ($row_email = $result_email->fetchArray()) {
                         if (empty($row_email['Email'])) {
                             continue;
                         }
                         phoromatic_server::send_email($row_email['Email'], 'Phoromatic System Potential Problem: ' . phoromatic_server::system_id_to_name($row['SystemID'], $row['AccountID']), phoromatic_server::account_id_to_group_admin_email($row['AccountID']), '<p><strong>' . $row_email['UserName'] . ':</strong></p><p>One of the systems associated with your Phoromatic account has not been communicating with the Phoromatic Server and is part of a current active test schedule. Below is the system information details:</p><p><strong>System:</strong> ' . phoromatic_server::system_id_to_name($row['SystemID'], $row['AccountID']) . '<br /><strong>Last Communication:</strong> ' . phoromatic_server::user_friendly_timedate($row['LastCommunication']) . '<br /><strong>Last Task:</strong> ' . $row['CurrentTask'] . '<br /><strong>Local IP:</strong> ' . $row['LastIP'] . '</p>');
                     }
                     $systems_already_reported[$sys_hash] = time();
                 }
             }
         }
         phoromatic_server::close_database();
         sleep(60 - date('s') + 1);
         $is_first_run = false;
     }
 }