public function JoinNewWorld($world_id)
 {
     /*
     POST /hc//index.php/json_gateway?svc=BatchController.call HTTP/1.1
     Accept: application/json
     Content-type: application/json; charset=UTF-8;
     X-Signature: 004d3e4c635fd823773950f50a999aad
     X-Timestamp: 1410114993
     User-Agent: Dalvik/1.4.0 (Linux; U; Android 2.3.4; DROID3 Build/5.5.1_84_D3G-66_M2-10)
     Host: gcand.gree-apps.net
     Connection: Keep-Alive
     Content-Length: 541
     Accept-Encoding: gzip
     
     [{"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 "Joining World {$world_id}...\r\n";
     $params = array();
     $params['game_world_id'] = WorldDAO::getGameIdFromLocalId($this->db, $world_id);
     $response = $this->de->MakeRequest('JOIN_NEW_WORLD', $params);
     if (!$response) {
         return false;
     }
     $this->world_id = $world_id;
     $this->player_id = $response['metadata']['player']['player_id'];
     $local_user_id = PgrmUserDAO::getLocalIdFromGameId($this->db, $this->user_id);
     $new_local_player_id = PgrmPlayerDAO::joinNewWorld($this->db, $this->player_id, $local_user_id, $this->world_id);
     if ($this->db->hasError()) {
         echo 'Error joining world: ';
         print_r($this->db->getError());
         echo "\r\n";
         $log_msg = print_r($response, true) . "\r\n\r\n" . print_r($this->db->getError(), true);
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Error saving player into World {$this->world_id} as player {$this->player_id}", $log_msg, 1);
     }
     echo "Joined!\r\n";
     DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Joined World {$this->world_id} as player {$this->player_id}");
     // Authenticate into our new world
     return $this->Authenticate();
 }
 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;
     }
 }
 public function MakeRequest($endpoint, $data_string, $method, $retry_count = 0)
 {
     $log_msg = "Attempt #" . ($retry_count + 1) . "\r\n\r\n" . $data_string;
     $log_seq = 0;
     $func_args = func_get_args();
     $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args);
     if ($retry_count > 0) {
         echo "Retry Attempt #{$retry_count}\r\n";
     }
     if ($retry_count >= self::$min_retry_delay && self::$min_retry_delay > 0) {
         $waittime = ($retry_count - self::$min_retry_delay + 1) * 5;
         echo "Waiting {$waittime} seconds before retry.\r\n";
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Retry Attempt #{$retry_count}: Waiting {$waittime} seconds before retry.");
         usleep($waittime * 1000000);
     }
     // Assemble our URL
     $url = $this->url_base . $endpoint;
     // Initialize our Curl request
     $headers = $this->get_headers($endpoint, $data_string);
     $proxy = false;
     if ($this->proxies != false) {
         $proxy = $this->proxies[array_rand($this->proxies)];
     }
     $ch = $this->init_request($url, $proxy);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
     $log_msg = "Proxy: {$proxy['ip_address']}:{$proxy['port']}\r\n\r\n" . print_r($headers, true);
     $request_id = DataLoadLogDAO::logWebserviceRequest($this->db, $func_log_id, $url, $method, $proxy, $headers, $data_string);
     // Execute our request
     $start = microtime(true);
     $response_string = curl_exec($ch);
     $end = microtime(true);
     if (!$response_string) {
         $curl_error = curl_error($ch);
     }
     // cleans up the curl request
     curl_close($ch);
     $request_time = $end - $start;
     //echo "Request completed in ".$request_time." seconds\r\n";
     // If our call failed
     if (!$response_string) {
         $log_msg = "Error Description: {$curl_error}\r\n\r\nProxy: {$proxy['ip_address']}:{$proxy['port']}<br/>\r\nURL: {$url}<br/>\r\nData: {$data_string}<br/>\r\n";
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Error occurred during curl request", $log_msg, 1);
         echo "Error occurred while getting Curl response.\r\n";
         //echo "Proxy: {$proxy['ip_address']}:{$proxy['port']}<br/>\r\n";
         //echo "URL: $url<br/>\r\n";
         //echo "Data: $data_string<br/>\r\n\r\n";
         ProxyDAO::countFailure($this->db, $proxy['id'], $request_time);
         // Retry if we haven't reached our max
         if (!$this->max_attempts_reached($retry_count)) {
             return $this->MakeRequest($endpoint, $data_string, $method, $retry_count + 1);
         } else {
             return false;
         }
     }
     // We send a header requesting a gzip encoded response, so try to decode it
     $decoded = gzdecode($response_string);
     // If we encountered an error in decoding, see what we can do with it
     if (!$decoded) {
         // Some of our proxies decode the gzip for us, so check to see if we've been decoded
         // If we have UTF-8 encoding already, then we might be OK after all
         if (mb_check_encoding($response_string, 'UTF-8')) {
             DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'WARNING', "Gzip decoding failed, but response is utf8 encoded.  We'll try to use it.", $response_string);
             echo "Error occurred while decoding CURL response, but let's assume this is OK!\r\n";
             // If we think we got a proxy error, then log it, and disable the proxy server.  Otherwise return the response
             if (stripos($response_string, 'The maximum web proxy user limit has been reached') > 0) {
                 DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Proxy Limit Reached", null, 1);
                 ProxyDAO::disableProxy($this->db, $proxy['id'], 'The maximum web proxy user limit has been reached');
             } else {
                 if (stripos($response_string, '<title>Access Den') > 0) {
                     DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Access Denied", null, 1);
                     ProxyDAO::disableProxy($this->db, $proxy['id'], 'Access Denied Received');
                 } else {
                     ProxyDAO::countSuccess($this->db, $proxy['id'], $request_time);
                     // Since we have a valid string, try to decode the JSON response
                     $json_array = json_decode($response_string, true);
                     if (!$json_array) {
                         DataLoadLogDAO::logWebserviceResponse($this->db, $request_id, $decoded, $request_time);
                         DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Failed to Decode JSON Response');
                         return false;
                     }
                     DataLoadLogDAO::logWebserviceResponse($this->db, $request_id, $response_string, $request_time, $json_array);
                     // Validate that the request completed successfully
                     $this->ValidateResponse($json_array, $func_log_id, $request_id);
                     return $json_array;
                 }
             }
         } else {
             DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Gzip decoding failed, and we don't know what to do with it.  Retry this request.", $response_string, 1);
             echo "Error occurred while decoding CURL response, and we think this is a problem!\r\n";
             ProxyDAO::countFailure($this->db, $proxy['id'], $request_time);
         }
         // If we made it this far then we need to retry
         if (!$this->max_attempts_reached($retry_count)) {
             DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Failed to Decode Response. Retrying.', 1);
             return $this->MakeRequest($endpoint, $data_string, $method, $retry_count + 1);
         } else {
             DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Request Failed. Retry limit hit [{$retry_count}]. Quitting.", 1);
             return false;
         }
     }
     // If we made it this far, then we were successful, to let's log it as a success to our proxy
     ProxyDAO::countSuccess($this->db, $proxy['id'], $request_time);
     // Since we have a valid string, try to decode the JSON response
     $json_array = json_decode($decoded, true);
     if ($json_array === null) {
         DataLoadLogDAO::logWebserviceResponse($this->db, $request_id, $decoded, $request_time);
         DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Failed to Decode JSON Response', 1);
         return false;
     }
     DataLoadLogDAO::logWebserviceResponse($this->db, $request_id, $decoded, $request_time, $json_array);
     // Validate that the request completed successfully
     $status = $this->ValidateResponse($json_array, $func_log_id, $request_id);
     if ($status === 'retry') {
         DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Validation returned [{$status}].  Retrying request...", $response_string, 1);
         echo "Validation returned [{$status}].  Retrying request...\n";
         return $this->MakeRequest($endpoint, $data_string, $method, $retry_count + 1);
     }
     // Return the decoded string
     return $json_array;
 }
 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;
 }
            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);
                 echo "Quitting.\r\n";
             }
         }
         break;
     }
     // Make sure we have enough commanders left to jeep with, otherwise recall our cap and stop.
     if (count($jeeping_commanders) < $num_jeeps + $jeep_increment) {
         $won->sendWarningText('Out of commanders to jeep.  Qutting.', false);
         echo date_format(new DateTime(), 'H:i:s') . " | Out of commanders to jeep.  Quitting.\r\n";
         // Now wait a little while longer before we recall just to seem human
         usleep($seconds_pause_before_recall * rand(900000, 1100000));
         $recall_army = $game->RecallArmy($cap_army['id']);
         // If we failed to recall the cap, send an alert and quit the program
         if (!is_array($recall_army)) {
             echo date_format(new DateTime(), 'H:i:s') . " | Cap Hold Army Recall Failed! Reason: {$recall_army}.\r\n";
             DataLoadLogDAO::logEvent2($won->db, $func_log_id, $log_seq++, 'ERROR', "Cap Hold Army Recall Failed! Reason: {$recall_army}", null, 1);
             // If the reason we failed was because the army was no longer in the base, attempt to continue
             if ($recall_army == "CAN'T_FIND_ARMY_TO_SEND_BACK_HOME") {
                 // Ignore this error, the army is not in the base but we're quitting anyway so we don't care
             } else {
                 // We failed to recall and we don't know why.  Sound the alarm!
                 $won->sendWarningText("Cap Hold Army Recall Failed! Reason: {$recall_army}. Quitting.", true);
                 echo "Quitting.\r\n";
             }
         }
         break;
     }
     // 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
 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');
 }