private function ValidateResponse($json_array, $func_log_id, $request_id)
 {
     // These statuses will trigger an error state but not kill the program
     $response_whitelist = array('EVENT_QUEUE_EXECUTE_NOW_FAILED');
     // Validate that the request completed successfully
     if ($json_array['status'] == 'OK' && array_key_exists(0, $json_array['responses']) && array_key_exists('status', $json_array['responses'][0])) {
         if ($json_array['responses'][0]['status'] == 'OK') {
             DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Request Successful');
         } elseif (in_array($json_array['responses'][0]['status'], $response_whitelist)) {
             $status_str = "Statuses: [{$json_array['status']}], [{$json_array['responses'][0]['status']}]";
             echo "Request Failed.  {$status_str}\nContinuing...\n";
             DataLoadLogDAO::webServiceStatusFailure($this->db, $request_id);
             DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Request Failed.  {$status_str}", 1);
             return 'retry';
         } else {
             $status_str = "Statuses: [{$json_array['status']}], [{$json_array['responses'][0]['status']}]";
             DataLoadLogDAO::webServiceStatusFailure($this->db, $request_id);
             DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Request Failed.  {$status_str}", 1);
             DataLoadDAO::loadFailed($this->db, $this->data_load_id);
             die("Data Load Failed. {$status_str}\n");
         }
     } elseif (array_key_exists(0, $json_array['responses']) && substr($json_array['responses'][0], 0, 9) === 'EXCEPTION') {
         $status_str = "Statuses: [{$json_array['status']}], [{$json_array['responses'][0]}]";
         echo "Request Failed.  {$status_str}\nContinuing...\n";
         DataLoadLogDAO::webServiceStatusFailure($this->db, $request_id);
         DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Request Failed.  {$status_str}", 1);
         return 'retry';
     } else {
         $status_str = "Statuses: [{$json_array['status']}], [{$json_array['responses'][0]}]";
         DataLoadLogDAO::webServiceStatusFailure($this->db, $request_id);
         DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Request Failed.  {$status_str}", 1);
         DataLoadDAO::loadFailed($this->db, $this->data_load_id);
         die("Data Load Failed. {$status_str}\n");
     }
     return true;
 }
 public function SwitchWorld($world_id)
 {
     /*
     		POST /hc//index.php/json_gateway?svc=BatchController.call HTTP/1.1
     		x-newrelic-id: UgMDWFFADQYCUFFUBw==
     		Accept: application/json
     		Content-type: application/json; charset=UTF-8;
     		X-Signature: 51931c0ffc90f6ac0e64e5f6bb1a7bbd
     		X-Timestamp: 1424498999
     		User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.2.2; Droid4X-MAC Build/JDQ39E)
     		Host: gcand.gree-apps.net
     		Connection: Keep-Alive
     		Accept-Encoding: gzip
     		Content-Length: 545
     [{"transaction_time":"1424498999746","platform":"android","session_id":"6283633","start_sequence_num":1,"iphone_udid":"92639d40a61db79e7d8c01479b7638fc","wd_player_id":0,"locale":"en-US","_explicitType":"Session","client_build":"360","game_name":"HCGame","api_version":"1","mac_address":"14:10:9F:D6:7B:33","end_sequence_num":1,"req_id":1,"player_id":101019808535303,"language":"en","game_data_version":"hc_20150218_47131","client_version":"1.9.8"},[{"service":"world.world","method":"switch_world","_explicitType":"Command","params":[101013]}]]
     		[{"transaction_time":"1410114994026","platform":"android","session_id":"51507  ","start_sequence_num":1,"iphone_udid":"8763af18eb4deace1840060a3bd9086b","wd_player_id":0,"locale":"en-US","_explicitType":"Session","client_build":"251","game_name":"HCGame","api_version":"1","mac_address":"c8:aa:21:40:0a:2a","end_sequence_num":1,"req_id":1,"player_id":101013596288193,"language":"en","game_data_version":"hc_20140903_38604","client_version":"1.8.4"},[{"service":"world.world","method":"join_world","_explicitType":"Command","params":[101001]}]]
     */
     $log_seq = 0;
     $func_args = func_get_args();
     $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args);
     echo "Switching to World {$world_id}...\r\n";
     $params = array();
     $params['game_world_id'] = WorldDAO::getGameIdFromLocalId($this->db, $world_id);
     $response = $this->de->MakeRequest('SWITCH_WORLD', $params);
     if (!$response) {
         return false;
     }
     $success = $response['responses'][0]['return_value']['success'];
     if ($success != 1) {
         return false;
     }
     $this->world_id = $world_id;
     $this->player_id = $response['metadata']['player']['player_id'];
     DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Switched to World {$this->world_id} as player {$this->player_id}");
     // Authenticate into our new world
     return $this->Authenticate();
 }
 public function CompleteWorldMapExtraction()
 {
     $log_seq = 0;
     $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__);
     DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'DEBUG', 'Before Setting Resource Patch Counts');
     $updates = WorldMapDAO::setResourcePatches($this->db, $this->auth->world_id);
     if ($this->db->hasError()) {
         echo "Error updating resource patches for world {$this->auth->world_id}: \r\n";
         print_r($this->db->getError());
         echo "\r\n";
         $log_msg = print_r($this->db->getError(), true);
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Error updating resource patches in World {$this->auth->world_id}", $log_msg, 1);
     } else {
         echo "Updated {$updates} bases resource patch counts\r\n";
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Updated {$updates} bases resource patch counts");
     }
     DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'DEBUG', 'Before Archiving Old Bases');
     $archives = WorldMapDAO::archiveOldBases($this->db, $this->auth->world_id, $this->data_load_id);
     if ($archives !== false) {
         echo "Archived {$archives} bases from world {$this->auth->world_id} older than data load {$this->data_load_id}\r\n";
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Archived {$archives} bases from world {$this->auth->world_id} older than data load {$this->data_load_id}");
     } else {
         if ($this->db->hasError()) {
             echo "Error archiving bases from world {$this->auth->world_id} older than data load {$this->data_load_id}: \r\n";
             print_r($this->db->getError());
             echo "\r\n";
             $log_msg = print_r($this->db->getError(), true);
             DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Database Error while archiving bases from world {$this->auth->world_id} older than data load {$this->data_load_id}", $log_msg, 1);
         } else {
             echo "Error archiving bases from world {$this->auth->world_id}";
             DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Unknown error while archiving bases from world {$this->auth->world_id} older than data load {$this->data_load_id}", 1);
         }
     }
     DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Updated {$updates} resource patches and archived {$archives} bases from world {$this->auth->world_id}");
     return true;
 }
 function SendWarningText($message, $ringer = false, $debug = 0)
 {
     // If we need to get the alert immediately, turn on the ringer
     if ($ringer) {
         $message = PgrmConfigDAO::getConfigProperty($this->db, 'SMTP', 'SERVER', 'value1') . ' | ' . $message;
     }
     $log_seq = 0;
     $func_args = func_get_args();
     $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args);
     //Create a new PHPMailer instance
     $mail = new PHPMailer();
     //Tell PHPMailer to use SMTP
     $mail->isSMTP();
     //Enable SMTP debugging
     // 0 = off (for production use)
     // 1 = client messages
     // 2 = client and server messages
     $mail->SMTPDebug = $debug;
     //Ask for HTML-friendly debug output
     $mail->Debugoutput = 'html';
     //Set the hostname of the mail server
     $server = PgrmConfigDAO::getConfigProperties($this->db, 'SMTP', 'SERVER');
     $mail->Host = $server['value1'];
     //Set the SMTP port number - likely to be 25, 465 or 587
     $mail->Port = $server['value2'];
     //Whether to use SMTP authentication
     $mail->SMTPAuth = true;
     //Username to use for SMTP authentication
     $credentials = PgrmConfigDAO::getConfigProperties($this->db, 'SMTP', 'CREDENTIALS');
     $mail->Username = $credentials['value1'];
     //Password to use for SMTP authentication
     $mail->Password = $credentials['value2'];
     //Set who the message is to be sent from
     $from_email = PgrmConfigDAO::getConfigProperties($this->db, 'SMTP', 'FROM_EMAIL');
     $mail->setFrom($from_email['value1'], $from_email['value2']);
     //Set who the message is to be sent to
     $text_to = PgrmConfigDAO::getConfigProperties($this->db, 'SMTP', 'WARNING_TEXT_TO');
     $mail->addAddress($text_to['value1'], $text_to['value2']);
     //Set the subject line
     $mail->Subject = '';
     //Set the body of the message
     $mail->isHTML(false);
     $mail->Body = $message;
     //send the message, check for errors
     if (!$mail->send()) {
         echo "Mailer Error: " . $mail->ErrorInfo . "\r\n";
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', 'Error Sending Message', $mail->ErrorInfo, 1);
         DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Error Sending Message', 1);
         return false;
     } else {
         //echo "Message sent!";
         DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Message Sent');
         return true;
     }
 }
            if (!array_key_exists($target_base_id, $flights) || $flights[$target_base_id] < $arrival_time) {
                $flights[$target_base_id] = $arrival_time;
            }
            // Wait for a little bit
            sleep($seconds_between_waves);
        }
        // Log an operation complete after each base flown
        DataLoadDAO::operationComplete($won->db, $won->data_load_id);
        // Pause shortly
        sleep($seconds_between_bases);
    }
    // Sort list of flight times so that we can easily find the shortest
    asort($flights);
    // Turn the flights list back into actual time deltas
    // We do this here instead of storing them above to account for delays in sending flights
    $current_ts = time();
    foreach ($flights as $index => $arrival_ts) {
        $flights[$index] = $arrival_ts - $current_ts;
    }
    print_r($flights);
    DataLoadLogDAO::logEvent2($won->db, $func_log_id, $log_seq++, 'INFO', 'Flights After Sending: [' . count($flights) . ']', print_r($flights, true));
    $seconds_to_sleep = array_shift($flights) + 10;
    echo "Waiting {$seconds_to_sleep} seconds for next wave to land\n\n";
    DataLoadLogDAO::logEvent2($won->db, $func_log_id, $log_seq++, 'INFO', "Waiting {$seconds_to_sleep} seconds for next wave to land");
    // Wait for the next wave to land before we wake back up
    sleep($seconds_to_sleep);
    // Not our first run anymore!
    $first_run = false;
}
DataLoadLogDAO::completeFunction($won->db, $func_log_id, 'Stop Signal Detected.  Stopping.');
DataLoadDAO::loadComplete($won->db, $won->data_load_id);
        }
        // Kill some time before we start jeeping since this makes us need less jeeps to fully refill the base
        usleep($minutes_before_jeep * 60 * rand(950000, 1050000));
    }
    // Send the necessary jeeps to refill the base
    echo date_format(new DateTime(), 'H:i:s') . " | Starting Jeeps...\r\n";
    for ($i = 1; $i <= $num_jeeps; $i++) {
        // Pause so it's not obvious that we're not really playing
        usleep($seconds_pause_between_jeeps * rand(900000, 1100000));
        // Select the next commander to jeep with. If we used one earlier to hold the base, skip the first one now
        $current_jeeping_comm = $jeeping_commanders[$i - (1 - $jeep_increment)];
        echo date_format(new DateTime(), 'H:i:s') . " | Jeeping comm #{$i}: {$current_jeeping_comm['id']}\r\n";
        $jeep_army = $game->SendAttack($npc_id, 1, 1, $current_jeeping_comm['id'], $jeep_units_to_send);
        // This should never happen but isn't a huge deal anyway
        if (!$jeep_army) {
            echo "Jeep Failed!\r\n";
        }
    }
    // Wait until our last jeep has landed
    // usleep($jeep_army['delta_time_to_destination'] * rand(1000000, 1200000));
    // Just kidding, we don't need to do that.  It's a waste of time.
    // Now wait a little while longer before we recall just to seem human
    usleep($seconds_pause_between_rounds * rand(900000, 1100000));
    // Need to save this information so that we can recall it next time around
    $last_cap_army = $cap_army;
    // Re-Sync our player data so that we can use this to decide which commanders to use next round
    $auth_result = $game->SyncPlayer();
    $first = false;
}
DataLoadLogDAO::completeFunction($won->db, $func_log_id, 'Done Training');
DataLoadDAO::loadComplete($won->db, $won->data_load_id);
 function SaveGuildLeaderboard($leader_data)
 {
     $log_seq = 0;
     $func_args = func_get_args();
     $func_args[0] = 'Removed Hex Array. See WS Request Log.';
     $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args);
     $count = 0;
     foreach ($leader_data as $key => $leader) {
         $guild = new Guild();
         $guild->world_id = $this->auth->world_id;
         $guild->data_load_id = $this->data_load_id;
         $guild->game_guild_id = $leader['guild_id'];
         if (array_key_exists('owner_id', $leader) && ($leader_id = PlayerDAO::getLocalIdFromGameId($this->db, $leader['owner_id']))) {
             $guild->leader_id = $leader_id;
         }
         $guild->guild_name = $leader['guild_name'];
         $guild->battle_points = $leader['score'];
         $guild->glory_points = $leader['glory_points'];
         $guild->members = $leader['member_count'];
         $id = GuildDAO::getLocalIdFromGameId($this->db, $guild->game_guild_id);
         if ($id) {
             $guild->id = $id;
             GuildDAO::updateGuild($this->db, $guild);
         } else {
             GuildDAO::insertGuild($this->db, $guild);
         }
         if ($this->db->hasError()) {
             echo 'Error saving guild: ';
             print_r($this->db->getError());
             echo "\r\n";
             $log_msg = var_dump($player) . "\r\n\r\n" . print_r($this->db->getError(), true);
             DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Error Saving Guild: World [{$guild->world_id}], Guild: [{$guild->guild_name}]", $log_msg, 1);
         } else {
             $count++;
         }
     }
     DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Saved {$count} Guilds");
 }
 public function Run()
 {
     $heartbeat_msg = '{"payload":{},"type":"heartbeat"}';
     $log_seq = 0;
     $func_args = func_get_args();
     $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args);
     $seconds_between_heartbeat = 30;
     $closed = false;
     while (1) {
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Send heartbeat message");
         echo "Sending: {$heartbeat_msg}\n----------\n";
         $this->client->send($heartbeat_msg);
         $last_heartbeat = microtime(true);
         DataLoadDAO::operationComplete($this->db, $this->data_load_id);
         // This loop controls how many times we will try go receive in between heartbeats
         //for($i = 0; $i < 1; $i++) {
         // Continue reading until we run out of content to read, disconnect, or reach our heartbeat time
         while (1) {
             try {
                 $message_handled = false;
                 $opcode = '';
                 DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Listening...");
                 $seconds_since_heartbeat = microtime(true) - $last_heartbeat;
                 echo "Seconds Since Heartbeat: {$seconds_since_heartbeat}\n";
                 $new_timeout = round($seconds_between_heartbeat - $seconds_since_heartbeat, 0);
                 if ($new_timeout <= 0) {
                     break;
                 }
                 echo "New Heartbeat Timeout: {$new_timeout} seconds\n";
                 echo "Receiving: ";
                 $this->client->setTimeout($new_timeout);
                 $data = $this->client->receive();
                 $opcode = $this->client->getLastOpcode();
                 echo "{$opcode}\n";
                 DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'MESSAGE', "Receive Complete [{$opcode}]");
                 //, $data);
                 // Handle special cases here
                 switch ($opcode) {
                     case 'ping':
                         // Respond with pong
                         echo "Sending Pong\n----------\n";
                         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Sending pong message");
                         $this->client->send('', 'pong');
                         $message_handled = true;
                         break;
                     case 'close':
                         echo "Received Close.  Disconnecting...\n";
                         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Sending pong message");
                         $message_handled = true;
                         $closed = true;
                         break;
                 }
                 // If we already handled this message, go receive a new one
                 if ($message_handled) {
                     break;
                 }
                 try {
                     echo "Trying to decode string\n";
                     $decoded_data = @gzdecode($data);
                     if ($decoded_data == false) {
                         echo "String not compressed\n{$data}\n==========\n";
                         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'MESSAGE', "[{$opcode}] Message Not Compressed", $data);
                     } else {
                         $data = $decoded_data;
                         echo "DECODED:\n{$data}\n==========\n";
                         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'MESSAGE', "Decoded [{$opcode}] message", $data);
                     }
                 } catch (Exception $ex) {
                     echo "Error\n";
                 }
             } catch (Exception $ex) {
                 echo "No Data Found\n";
                 DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "No Data Found [{$opcode}]", $ex->getMessage(), 1);
                 //usleep(5000000);
                 //break;
             }
         }
         //}
         if ($closed) {
             break;
         }
     }
     DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Finished with Listener, this should never happen');
 }
 public function SendChatMessage($chat_stream, $message)
 {
     // [{"transaction_time":"1448671061854","platform":"android","session_id":"7968688","start_sequence_num":0,"iphone_udid":"8c9c72c38515837f4957843075bcac39","wd_player_id":0,"locale":"en-US","_explicitType":"Session","client_build":"489","game_name":"HCGame","api_version":"1","mac_address":"14:10:9F:D6:7B:33","end_sequence_num":0,"req_id":1,"player_id":101013624609676,"language":"en","game_data_version":"hc_NA_20151126_60629","client_version":"2.5.3.1"},[{"service":"chatservice.chatservice","method":"channels","_explicitType":"Command","params":["\/guild_101013232844480","2 concrete donated"]}]]
     $log_seq = 0;
     $func_args = func_get_args();
     $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args);
     echo "Sending '{$message}' to [{$chat_stream}]...\r\n";
     $params = array();
     $params['chat_stream'] = $chat_stream;
     $params['message'] = $message;
     $result = $this->de->MakeRequest('SEND_CHAT_MESSAGE', $params);
     if (!$result) {
         return false;
     }
     echo "Sent!\r\n\r\n";
     DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Successfully sent [{$message}] to [{$chat_stream}]");
     return $result;
 }