Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Completed
Branch master (287493)
by Dan
06:08
created
tools/discord/commands/money.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@
 block discarded – undo
2 2
 
3 3
 require_once(TOOLS . 'chat_helpers/channel_msg_money.php');
4 4
 
5
-$fn_money = function ($message) {
5
+$fn_money = function($message) {
6 6
 	$link = new GameLink($message->channel, $message->author);
7 7
 	if (!$link->valid) return;
8 8
 
Please login to merge, or discard this patch.
tools/discord/bot.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-require_once(__DIR__.'/../../htdocs/config.inc');
3
+require_once(__DIR__ . '/../../htdocs/config.inc');
4 4
 require_once(LIB . 'Default/smr.inc');
5 5
 require_once(TOOLS . 'discord/GameLink.inc');
6 6
 require_once(TOOLS . 'discord/mysql_cleanup.php');
Please login to merge, or discard this patch.
tools/discord/GameLink.inc 1 patch
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -3,11 +3,11 @@  discard block
 block discarded – undo
3 3
 // Holds information linking the received message and the game data
4 4
 class GameLink
5 5
 {
6
-	public $valid = false;  // identifies if the message is linked to game data
7
-	public $user;           // Discord user associated with the message
8
-	public $account;        // SmrAccount instance
9
-	public $alliance;       // SmrAlliance instance
10
-	public $player;         // SmrPlayer instance
6
+	public $valid = false; // identifies if the message is linked to game data
7
+	public $user; // Discord user associated with the message
8
+	public $account; // SmrAccount instance
9
+	public $alliance; // SmrAlliance instance
10
+	public $player; // SmrPlayer instance
11 11
 
12 12
 	// Takes the following arguments:
13 13
 	//	channel = Discord\Parts\Channel\Channel instance
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 
61 61
 			$this->player = SmrPlayer::getPlayer($this->account->getAccountID(), $this->alliance->getGameID(), true);
62 62
 			if ($this->player->getAllianceID() != $this->alliance->getAllianceID()) {
63
-				$channel->sendMessage("Player `".$this->player->getPlayerName()."` is not a member of alliance `".$this->alliance->getAllianceName()."`");
63
+				$channel->sendMessage("Player `" . $this->player->getPlayerName() . "` is not a member of alliance `" . $this->alliance->getAllianceName() . "`");
64 64
 				return;
65 65
 			}
66 66
 		}
Please login to merge, or discard this patch.
tools/discord/mysql_cleanup.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -5,12 +5,12 @@
 block discarded – undo
5 5
 function mysql_cleanup(callable $func) {
6 6
 
7 7
 	// Create a new closure that wraps the original closure
8
-	$func_wrapper = function ($message, $params) use ($func) {
8
+	$func_wrapper = function($message, $params) use ($func) {
9 9
 		// First, call the original closure
10 10
 		try {
11 11
 			$func($message, $params);
12 12
 		} catch (Throwable $e) {
13
-			print('Error in '.$e->getFile().' line '.$e->getLine().':'.EOL);
13
+			print('Error in ' . $e->getFile() . ' line ' . $e->getLine() . ':' . EOL);
14 14
 			print($e->getMessage() . EOL);
15 15
 			$message->reply('I encountered an error. Please report this to an admin!');
16 16
 		}
Please login to merge, or discard this patch.
tools/cache_player.php 1 patch
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 
4
-require_once ( realpath(dirname(__FILE__)) . '/../htdocs/config.inc');
4
+require_once (realpath(dirname(__FILE__)) . '/../htdocs/config.inc');
5 5
 require_once ($INCLUDE . '/dbconnect.inc');
6 6
 
7 7
 $sql = query('SELECT * FROM news WHERE irc_sent = \'FALSE\'');
@@ -54,20 +54,20 @@  discard block
 block discarded – undo
54 54
 */
55 55
 function send_irc_message($message) {
56 56
 	$fsockopen = @fsockopen('Chat.VJTD3.com', 80, $errorint, $errorstr, 15);
57
-	@fwrite($fsockopen, 'GET /smrnews.php?'.rawurlencode($message).' HTTP/1.0'.EOL);
57
+	@fwrite($fsockopen, 'GET /smrnews.php?' . rawurlencode($message) . ' HTTP/1.0' . EOL);
58 58
 	unset($message);
59
-	@fwrite($fsockopen, 'Host: Chat.VJTD3.com'.EOL);
59
+	@fwrite($fsockopen, 'Host: Chat.VJTD3.com' . EOL);
60 60
 	@fwrite($fsockopen, EOL);
61 61
 	if ($fsockopen)
62 62
 	{
63 63
 		while (!feof($fsockopen))
64 64
 		{
65
-			@$data .=fread($fsockopen, 1024);
65
+			@$data .= fread($fsockopen, 1024);
66 66
 		}
67 67
 	}
68 68
 	fclose($fsockopen);
69 69
 	unset($fsockopen);
70
-	$data = explode(EOL.EOL, $data, 2);
70
+	$data = explode(EOL . EOL, $data, 2);
71 71
 	$data = @$data['1'];
72 72
 	return (@$data['0'] === '1' ? 1 : 0);
73 73
 }
Please login to merge, or discard this patch.
tools/apc_cache.php 1 patch
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -12,28 +12,28 @@
 block discarded – undo
12 12
  * @param string $dir start directory
13 13
  * @return void
14 14
  */
15
-function compile_files($dir,$exts=array('*.php'))
15
+function compile_files($dir, $exts = array('*.php'))
16 16
 {
17 17
     $dirs = glob($dir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
18 18
     if (is_array($dirs) && count($dirs) > 0) {
19
-        while(list(,$v) = each($dirs)) {
20
-            compile_files($v,$exts);
19
+        while (list(,$v) = each($dirs)) {
20
+            compile_files($v, $exts);
21 21
         }
22 22
     }
23 23
 	
24
-	foreach($exts as $ext)
24
+	foreach ($exts as $ext)
25 25
 	{
26
-		echo "\n\n".'Compiling '.$ext."\n";
26
+		echo "\n\n" . 'Compiling ' . $ext . "\n";
27 27
 		$files = glob($dir . DIRECTORY_SEPARATOR . $ext);
28 28
 		if (is_array($files) && count($files) > 0)
29 29
 		{
30
-			while(list(,$v) = each($files))
30
+			while (list(,$v) = each($files))
31 31
 			{
32
-				echo 'Compiling '.$v."\n";
32
+				echo 'Compiling ' . $v . "\n";
33 33
 				apc_compile_file($v);
34 34
 			}
35 35
 		}
36 36
 	}
37 37
 }
38 38
  
39
-compile_files('/home/page/SMR',array('*.inc','*.php'));
39
+compile_files('/home/page/SMR', array('*.inc', '*.php'));
Please login to merge, or discard this patch.
tools/updatePortCache.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -4,6 +4,6 @@
 block discarded – undo
4 4
 $db = new SmrMySqlDatabase();
5 5
 $db->query('SELECT account_id,sector_id,game_id FROM player_visited_port');
6 6
 while ($db->nextRecord()) {
7
-	SmrPort::getCachedPort($db->getInt('game_id'),$db->getInt('sector_id'),$db->getInt('account_id'))->addCachePort($db->getInt('account_id'));
7
+	SmrPort::getCachedPort($db->getInt('game_id'), $db->getInt('sector_id'), $db->getInt('account_id'))->addCachePort($db->getInt('account_id'));
8 8
 	SmrPort::clearCache();
9 9
 }
Please login to merge, or discard this patch.
tools/npc/npc.php 1 patch
Spacing   +194 added lines, -194 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@  discard block
 block discarded – undo
6 6
 function overrideForward($container) {
7 7
 	global $forwardedContainer;
8 8
 	$forwardedContainer = $container;
9
-	if($container['body']=='error.php') {
9
+	if ($container['body'] == 'error.php') {
10 10
 		// We hit a create_error - this shouldn't happen for an NPC often,
11 11
 		// for now we want to throw an exception for it for testing.
12 12
 		debug('Hit an error');
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 	debug('Script started');
86 86
 
87 87
 	define('SCRIPT_ID', $db->getInsertID());
88
-	$db->query('UPDATE npc_logs SET script_id='.SCRIPT_ID.' WHERE log_id='.SCRIPT_ID);
88
+	$db->query('UPDATE npc_logs SET script_id=' . SCRIPT_ID . ' WHERE log_id=' . SCRIPT_ID);
89 89
 
90 90
 	$NPC_LOGINS_USED = array('');
91 91
 
@@ -102,11 +102,11 @@  discard block
 block discarded – undo
102 102
 	try {
103 103
 		changeNPCLogin();
104 104
 	}
105
-	catch(ForwardException $e) {}
105
+	catch (ForwardException $e) {}
106 106
 
107 107
 	NPCStuff();
108 108
 }
109
-catch(Throwable $e) {
109
+catch (Throwable $e) {
110 110
 	logException($e);
111 111
 	// Try to shut down cleanly
112 112
 	exitNPC();
@@ -114,72 +114,72 @@  discard block
 block discarded – undo
114 114
 
115 115
 
116 116
 function NPCStuff() {
117
-	global $actions,$var,$previousContainer,$underAttack,$NPC_LOGIN,$db;
117
+	global $actions, $var, $previousContainer, $underAttack, $NPC_LOGIN, $db;
118 118
 
119 119
 	$underAttack = false;
120
-	$actions=-1;
120
+	$actions = -1;
121 121
 
122
-	while(true) {
122
+	while (true) {
123 123
 		$actions++;
124 124
 		try {
125
-			$TRADE_ROUTE =& $GLOBALS['TRADE_ROUTE'];
126
-			debug('Action #'.$actions);
125
+			$TRADE_ROUTE = & $GLOBALS['TRADE_ROUTE'];
126
+			debug('Action #' . $actions);
127 127
 
128 128
 			SmrSession::updateGame(NPC_GAME_ID);
129 129
 
130
-			debug('Getting player for account id: '.SmrSession::$account_id);
130
+			debug('Getting player for account id: ' . SmrSession::$account_id);
131 131
 			//We have to reload player on each loop
132 132
 			$player = SmrPlayer::getPlayer(SmrSession::$account_id, SmrSession::getGameID(), true);
133 133
 			$player->updateTurns();
134 134
 
135
-			if($actions==0) {
136
-				if($player->getAllianceName() != $NPC_LOGIN['AllianceName']) {
135
+			if ($actions == 0) {
136
+				if ($player->getAllianceName() != $NPC_LOGIN['AllianceName']) {
137 137
 					// dirty hack so we can revisit the init block here on next iteration
138 138
 					$actions--;
139 139
 
140
-					if($player->hasAlliance())
140
+					if ($player->hasAlliance())
141 141
 						processContainer(leaveAlliance());
142 142
 
143 143
 					// figure out if the selected alliance already exist
144
-					$db->query('SELECT alliance_id FROM alliance WHERE alliance_name='.$db->escapeString($NPC_LOGIN['AllianceName']).' AND game_id='.$db->escapeNumber(SmrSession::getGameID()));
144
+					$db->query('SELECT alliance_id FROM alliance WHERE alliance_name=' . $db->escapeString($NPC_LOGIN['AllianceName']) . ' AND game_id=' . $db->escapeNumber(SmrSession::getGameID()));
145 145
 					if ($db->nextRecord()) {
146
-						processContainer(joinAlliance($db->getField('alliance_id'),'*--NPCS--*'));
146
+						processContainer(joinAlliance($db->getField('alliance_id'), '*--NPCS--*'));
147 147
 					}
148 148
 					else {
149
-						processContainer(createAlliance($NPC_LOGIN['AllianceName'],'*--NPCS--*'));
149
+						processContainer(createAlliance($NPC_LOGIN['AllianceName'], '*--NPCS--*'));
150 150
 					}
151 151
 				}
152
-				if($player->getTurns() <= mt_rand($player->getMaxTurns() / 2, $player->getMaxTurns()) && ($player->hasNewbieTurns() || $player->hasFederalProtection())) {
153
-					debug('We don\'t have enough turns to bother starting trading, and we are protected: '.$player->getTurns());
152
+				if ($player->getTurns() <= mt_rand($player->getMaxTurns() / 2, $player->getMaxTurns()) && ($player->hasNewbieTurns() || $player->hasFederalProtection())) {
153
+					debug('We don\'t have enough turns to bother starting trading, and we are protected: ' . $player->getTurns());
154 154
 					changeNPCLogin();
155 155
 				}
156 156
 			}
157 157
 
158
-			if(!isset($TRADE_ROUTE)) { //We only want to change trade route if there isn't already one set.
159
-				$TRADE_ROUTES =& findRoutes($player);
160
-				$TRADE_ROUTE =& changeRoute($TRADE_ROUTES);
158
+			if (!isset($TRADE_ROUTE)) { //We only want to change trade route if there isn't already one set.
159
+				$TRADE_ROUTES = & findRoutes($player);
160
+				$TRADE_ROUTE = & changeRoute($TRADE_ROUTES);
161 161
 			}
162 162
 
163
-			if($player->isDead()) {
163
+			if ($player->isDead()) {
164 164
 				debug('Some evil person killed us, let\'s move on now.');
165 165
 				$previousContainer = null; //We died, we don't care what we were doing beforehand.
166
-				$TRADE_ROUTE =& changeRoute($TRADE_ROUTES); //Change route
166
+				$TRADE_ROUTE = & changeRoute($TRADE_ROUTES); //Change route
167 167
 				processContainer(create_container('death_processing.php'));
168 168
 			}
169
-			if($player->getNewbieTurns() <= NEWBIE_TURNS_WARNING_LIMIT && $player->getNewbieWarning()) {
169
+			if ($player->getNewbieTurns() <= NEWBIE_TURNS_WARNING_LIMIT && $player->getNewbieWarning()) {
170 170
 				processContainer(create_container('newbie_warning_processing.php'));
171 171
 			}
172 172
 
173 173
 			$fedContainer = null;
174
-			if($var['url']=='shop_ship_processing.php'&&($fedContainer = plotToFed($player,true))!==true) { //We just bought a ship, we should head back to our trade gal/uno - we use HQ for now as it's both in our gal and a UNO, plus it's safe which is always a bonus
174
+			if ($var['url'] == 'shop_ship_processing.php' && ($fedContainer = plotToFed($player, true)) !== true) { //We just bought a ship, we should head back to our trade gal/uno - we use HQ for now as it's both in our gal and a UNO, plus it's safe which is always a bonus
175 175
 				processContainer($fedContainer);
176 176
 			}
177
-			else if($player->getShip()->isUnderAttack()===true
178
-				&&($player->hasPlottedCourse()===false||$player->getPlottedCourse()->getEndSector()->offersFederalProtection()===false)
179
-				&&($fedContainer==null?$fedContainer = plotToFed($player,true):$fedContainer)!==true) { //We're under attack and need to plot course to fed.
177
+			else if ($player->getShip()->isUnderAttack() === true
178
+				&&($player->hasPlottedCourse() === false || $player->getPlottedCourse()->getEndSector()->offersFederalProtection() === false)
179
+				&&($fedContainer == null ? $fedContainer = plotToFed($player, true) : $fedContainer) !== true) { //We're under attack and need to plot course to fed.
180 180
 				// Get the lock, remove under attack and update.
181 181
 				acquire_lock($player->getSectorID());
182
-				$ship =& $player->getShip(true);
182
+				$ship = & $player->getShip(true);
183 183
 				$ship->removeUnderAttack();
184 184
 				$ship->updateHardware();
185 185
 				release_lock();
@@ -188,74 +188,74 @@  discard block
 block discarded – undo
188 188
 				$underAttack = true;
189 189
 				processContainer($fedContainer);
190 190
 			}
191
-			else if($player->hasPlottedCourse()===true&&$player->getPlottedCourse()->getEndSector()->offersFederalProtection()) { //We have a route to fed to follow, figure it's probably a damned sensible thing to follow.
192
-				debug('Follow Course: '.$player->getPlottedCourse()->getNextOnPath());
193
-				processContainer(moveToSector($player,$player->getPlottedCourse()->getNextOnPath()));
191
+			else if ($player->hasPlottedCourse() === true && $player->getPlottedCourse()->getEndSector()->offersFederalProtection()) { //We have a route to fed to follow, figure it's probably a damned sensible thing to follow.
192
+				debug('Follow Course: ' . $player->getPlottedCourse()->getNextOnPath());
193
+				processContainer(moveToSector($player, $player->getPlottedCourse()->getNextOnPath()));
194 194
 			}
195
-			else if(($container = canWeUNO($player,true))!==false) { //We have money and are at a uno, let's uno!
195
+			else if (($container = canWeUNO($player, true)) !== false) { //We have money and are at a uno, let's uno!
196 196
 				debug('We\'re UNOing');
197 197
 				processContainer($container);
198 198
 			}
199
-			else if($player->hasPlottedCourse()===true) { //We have a route to follow, figure it's probably a sensible thing to follow.
200
-				debug('Follow Course: '.$player->getPlottedCourse()->getNextOnPath());
201
-				processContainer(moveToSector($player,$player->getPlottedCourse()->getNextOnPath()));
199
+			else if ($player->hasPlottedCourse() === true) { //We have a route to follow, figure it's probably a sensible thing to follow.
200
+				debug('Follow Course: ' . $player->getPlottedCourse()->getNextOnPath());
201
+				processContainer(moveToSector($player, $player->getPlottedCourse()->getNextOnPath()));
202 202
 			}
203
-			else if($player->getTurns()<NPC_LOW_TURNS || ($player->getTurns() < $player->getMaxTurns() / 2 && $player->getNewbieTurns()<NPC_LOW_NEWBIE_TURNS) || $underAttack) { //We're low on turns or have been under attack and need to plot course to fed
204
-				if($player->getTurns()<NPC_LOW_TURNS) {
205
-					debug('Low Turns:'.$player->getTurns());
203
+			else if ($player->getTurns() < NPC_LOW_TURNS || ($player->getTurns() < $player->getMaxTurns() / 2 && $player->getNewbieTurns() < NPC_LOW_NEWBIE_TURNS) || $underAttack) { //We're low on turns or have been under attack and need to plot course to fed
204
+				if ($player->getTurns() < NPC_LOW_TURNS) {
205
+					debug('Low Turns:' . $player->getTurns());
206 206
 				}
207
-				if($underAttack) {
207
+				if ($underAttack) {
208 208
 					debug('Fedding after attack.');
209 209
 				}
210
-				if($player->hasNewbieTurns()) { //We have newbie turns, we can just wait here.
210
+				if ($player->hasNewbieTurns()) { //We have newbie turns, we can just wait here.
211 211
 					debug('We have newbie turns, let\'s just switch to another NPC.');
212 212
 					changeNPCLogin();
213 213
 				}
214
-				if($player->hasFederalProtection()) {
214
+				if ($player->hasFederalProtection()) {
215 215
 					debug('We are in fed, time to switch to another NPC.');
216 216
 					changeNPCLogin();
217 217
 				}
218
-				$ship =& $player->getShip();
219
-				processContainer(plotToFed($player,!$ship->hasMaxShields()||!$ship->hasMaxArmour()||!$ship->hasMaxCargoHolds()));
218
+				$ship = & $player->getShip();
219
+				processContainer(plotToFed($player, !$ship->hasMaxShields() || !$ship->hasMaxArmour() || !$ship->hasMaxCargoHolds()));
220 220
 			}
221
-			else if(($container = checkForShipUpgrade($player))!==false) { //We have money and are at a uno, let's uno!
221
+			else if (($container = checkForShipUpgrade($player)) !== false) { //We have money and are at a uno, let's uno!
222 222
 				debug('We\'re reshipping!');
223 223
 				processContainer($container);
224 224
 			}
225
-			else if(($container = canWeUNO($player,false))!==false) { //We need to UNO and have enough money to do it properly so let's do it sooner rather than later.
225
+			else if (($container = canWeUNO($player, false)) !== false) { //We need to UNO and have enough money to do it properly so let's do it sooner rather than later.
226 226
 				debug('We need to UNO, so off we go!');
227 227
 				processContainer($container);
228 228
 			}
229
-			else if($TRADE_ROUTE instanceof Route) {
229
+			else if ($TRADE_ROUTE instanceof Route) {
230 230
 				debug('Trade Route');
231
-				$forwardRoute =& $TRADE_ROUTE->getForwardRoute();
232
-				$returnRoute =& $TRADE_ROUTE->getReturnRoute();
233
-				if($forwardRoute->getBuySectorId()==$player->getSectorID()||$returnRoute->getBuySectorId()==$player->getSectorID()) {
234
-					if($forwardRoute->getBuySectorId()==$player->getSectorID()) {
235
-						$buyRoute =& $forwardRoute;
236
-						$sellRoute =& $returnRoute;
231
+				$forwardRoute = & $TRADE_ROUTE->getForwardRoute();
232
+				$returnRoute = & $TRADE_ROUTE->getReturnRoute();
233
+				if ($forwardRoute->getBuySectorId() == $player->getSectorID() || $returnRoute->getBuySectorId() == $player->getSectorID()) {
234
+					if ($forwardRoute->getBuySectorId() == $player->getSectorID()) {
235
+						$buyRoute = & $forwardRoute;
236
+						$sellRoute = & $returnRoute;
237 237
 					}
238
-					else if($returnRoute->getBuySectorId()==$player->getSectorID()) {
239
-						$buyRoute =& $returnRoute;
240
-						$sellRoute =& $forwardRoute;
238
+					else if ($returnRoute->getBuySectorId() == $player->getSectorID()) {
239
+						$buyRoute = & $returnRoute;
240
+						$sellRoute = & $forwardRoute;
241 241
 					}
242 242
 
243
-					$ship =& $player->getShip();
244
-					if($ship->getUsedHolds()>0) {
245
-						if($ship->hasCargo($sellRoute->getGoodID())) { //Sell goods
243
+					$ship = & $player->getShip();
244
+					if ($ship->getUsedHolds() > 0) {
245
+						if ($ship->hasCargo($sellRoute->getGoodID())) { //Sell goods
246 246
 							$goodID = $sellRoute->getGoodID();
247 247
 
248
-							$port =& $player->getSector()->getPort();
249
-							$tradeable = checkPortTradeable($port,$player);
248
+							$port = & $player->getSector()->getPort();
249
+							$tradeable = checkPortTradeable($port, $player);
250 250
 
251
-							if($tradeable===true && $port->getGoodAmount($goodID)>=$ship->getCargo($sellRoute->getGoodID())) { //TODO: Sell what we can rather than forcing sell all at once?
251
+							if ($tradeable === true && $port->getGoodAmount($goodID) >= $ship->getCargo($sellRoute->getGoodID())) { //TODO: Sell what we can rather than forcing sell all at once?
252 252
 								//Sell goods
253 253
 								debug('Sell Goods');
254
-								processContainer(tradeGoods($goodID,$player,$port));
254
+								processContainer(tradeGoods($goodID, $player, $port));
255 255
 							}
256 256
 							else {
257 257
 								//Move to next route or fed.
258
-								if(($TRADE_ROUTE =& changeRoute($TRADE_ROUTES))===false) {
258
+								if (($TRADE_ROUTE = & changeRoute($TRADE_ROUTES)) === false) {
259 259
 									debug('Changing Route Failed');
260 260
 									processContainer(plotToFed($player));
261 261
 								}
@@ -265,9 +265,9 @@  discard block
 block discarded – undo
265 265
 								}
266 266
 							}
267 267
 						}
268
-						else if($ship->hasCargo($buyRoute->getGoodID())===true) { //We've bought goods, plot to sell
269
-							debug('Plot To Sell: '.$buyRoute->getSellSectorId());
270
-							processContainer(plotToSector($player,$buyRoute->getSellSectorId()));
268
+						else if ($ship->hasCargo($buyRoute->getGoodID()) === true) { //We've bought goods, plot to sell
269
+							debug('Plot To Sell: ' . $buyRoute->getSellSectorId());
270
+							processContainer(plotToSector($player, $buyRoute->getSellSectorId()));
271 271
 						}
272 272
 						else {
273 273
 							//Dump goods
@@ -278,16 +278,16 @@  discard block
 block discarded – undo
278 278
 					else { //Buy goods
279 279
 						$goodID = $buyRoute->getGoodID();
280 280
 
281
-						$port =& $player->getSector()->getPort();
282
-						$tradeable = checkPortTradeable($port,$player);
281
+						$port = & $player->getSector()->getPort();
282
+						$tradeable = checkPortTradeable($port, $player);
283 283
 
284
-						if($tradeable===true && $port->getGoodAmount($goodID)>=$ship->getEmptyHolds()) { //Buy goods
284
+						if ($tradeable === true && $port->getGoodAmount($goodID) >= $ship->getEmptyHolds()) { //Buy goods
285 285
 							debug('Buy Goods');
286
-							processContainer(tradeGoods($goodID,$player,$port));
286
+							processContainer(tradeGoods($goodID, $player, $port));
287 287
 						}
288 288
 						else {
289 289
 							//Move to next route or fed.
290
-							if(($TRADE_ROUTE =& changeRoute($TRADE_ROUTES))===false) {
290
+							if (($TRADE_ROUTE = & changeRoute($TRADE_ROUTES)) === false) {
291 291
 								debug('Changing Route Failed');
292 292
 								processContainer(plotToFed($player));
293 293
 							}
@@ -299,8 +299,8 @@  discard block
 block discarded – undo
299 299
 					}
300 300
 				}
301 301
 				else {
302
-					debug('Plot To Buy: '.$forwardRoute->getBuySectorId());
303
-					processContainer(plotToSector($player,$forwardRoute->getBuySectorId()));
302
+					debug('Plot To Buy: ' . $forwardRoute->getBuySectorId());
303
+					processContainer(plotToSector($player, $forwardRoute->getBuySectorId()));
304 304
 				}
305 305
 			}
306 306
 			else { //Something weird is going on.. Let's fed and wait.
@@ -316,15 +316,15 @@  discard block
 block discarded – undo
316 316
 			}
317 317
 			*/
318 318
 		}
319
-		catch(ForwardException $e) {
319
+		catch (ForwardException $e) {
320 320
 			global $lock;
321
-			if($lock) { //only save if we have the lock.
321
+			if ($lock) { //only save if we have the lock.
322 322
 				SmrSector::saveSectors();
323 323
 				SmrShip::saveShips();
324 324
 				SmrPlayer::savePlayers();
325 325
 				SmrForce::saveForces();
326
-				SmrPort::savePorts();;
327
-				if(class_exists('WeightedRandom', false))
326
+				SmrPort::savePorts(); ;
327
+				if (class_exists('WeightedRandom', false))
328 328
 					WeightedRandom::saveWeightedRandoms();
329 329
 				release_lock();
330 330
 			}
@@ -351,23 +351,23 @@  discard block
 block discarded – undo
351 351
 }
352 352
 
353 353
 function debug($message, $debugObject = null) {
354
-	global $account,$var,$db;
355
-	echo date('Y-m-d H:i:s - ').$message.($debugObject!==null?EOL.var_export($debugObject,true):'').EOL;
356
-	$db->query('INSERT INTO npc_logs (script_id, npc_id, time, message, debug_info, var) VALUES ('.(defined('SCRIPT_ID')?SCRIPT_ID:0).', '.(is_object($account)?$account->getAccountID():0).',NOW(),'.$db->escapeString($message).','.$db->escapeString(var_export($debugObject,true)).','.$db->escapeString(var_export($var,true)).')');
354
+	global $account, $var, $db;
355
+	echo date('Y-m-d H:i:s - ') . $message . ($debugObject !== null ?EOL.var_export($debugObject, true) : '') . EOL;
356
+	$db->query('INSERT INTO npc_logs (script_id, npc_id, time, message, debug_info, var) VALUES (' . (defined('SCRIPT_ID') ?SCRIPT_ID:0) . ', ' . (is_object($account) ? $account->getAccountID() : 0) . ',NOW(),' . $db->escapeString($message) . ',' . $db->escapeString(var_export($debugObject, true)) . ',' . $db->escapeString(var_export($var, true)) . ')');
357 357
 }
358 358
 
359 359
 function processContainer($container) {
360 360
 	global $forwardedContainer, $previousContainer, $player;
361
-	if($container == $previousContainer && $forwardedContainer['body'] != 'forces_attack.php') {
361
+	if ($container == $previousContainer && $forwardedContainer['body'] != 'forces_attack.php') {
362 362
 		debug('We are executing the same container twice?', array('ForwardedContainer' => $forwardedContainer, 'Container' => $container));
363
-		if($player->hasNewbieTurns() || $player->hasFederalProtection()) {
363
+		if ($player->hasNewbieTurns() || $player->hasFederalProtection()) {
364 364
 			// Only throw the exception if we have protection, otherwise let's hope that the NPC will be able to find its way to safety rather than dying in the open.
365 365
 			throw new Exception('We are executing the same container twice?');
366 366
 		}
367 367
 	}
368 368
 	clearCaches(); //Clear caches of anything we have used for decision making before processing container and getting lock.
369 369
 	$previousContainer = $container;
370
-	debug('Executing container',$container);
370
+	debug('Executing container', $container);
371 371
  	//Redefine MICRO_TIME and TIME, the rest of the game expects them to be the single point in time that the script is executing, with it being redefined for each page load - unfortunately NPCs are one consistent script so we have to do a hack and redefine it (or change every instance of the TIME constant.
372 372
 	uopz_redefine('MICRO_TIME', microtime(true));
373 373
 	uopz_redefine('TIME', intval(MICRO_TIME));
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 }
377 377
 
378 378
 function sleepNPC() {
379
-	usleep(mt_rand(MIN_SLEEP_TIME,MAX_SLEEP_TIME)); //Sleep for a random time
379
+	usleep(mt_rand(MIN_SLEEP_TIME, MAX_SLEEP_TIME)); //Sleep for a random time
380 380
 }
381 381
 
382 382
 // Releases an NPC when it is done working
@@ -385,11 +385,11 @@  discard block
 block discarded – undo
385 385
 		debug('releaseNPC: no login specified to release');
386 386
 	} else {
387 387
 		$db = new SmrMySqlDatabase();
388
-		$db->query('UPDATE npc_logins SET working='.$db->escapeBoolean(false).' WHERE login='.$db->escapeString($login));
389
-		if ($db->getChangedRows()>0) {
390
-			debug('Released NPC: '.$login);
388
+		$db->query('UPDATE npc_logins SET working=' . $db->escapeBoolean(false) . ' WHERE login=' . $db->escapeString($login));
389
+		if ($db->getChangedRows() > 0) {
390
+			debug('Released NPC: ' . $login);
391 391
 		} else {
392
-			debug('Failed to release NPC: '.$login);
392
+			debug('Failed to release NPC: ' . $login);
393 393
 		}
394 394
 	}
395 395
 }
@@ -403,13 +403,13 @@  discard block
 block discarded – undo
403 403
 }
404 404
 
405 405
 function changeNPCLogin() {
406
-	global $NPC_LOGIN,$actions,$NPC_LOGINS_USED,$underAttack,$previousContainer;
407
-	if($actions > 0) {
408
-		debug('We have taken actions and now want to change NPC, let\'s exit and let next script choose a new NPC to reset execution time', getrusage ());
406
+	global $NPC_LOGIN, $actions, $NPC_LOGINS_USED, $underAttack, $previousContainer;
407
+	if ($actions > 0) {
408
+		debug('We have taken actions and now want to change NPC, let\'s exit and let next script choose a new NPC to reset execution time', getrusage());
409 409
 		exitNPC();
410 410
 	}
411 411
 
412
-	$actions=-1;
412
+	$actions = -1;
413 413
 	$GLOBALS['TRADE_ROUTE'] = null;
414 414
 
415 415
 	// Release previous NPC, if any
@@ -428,9 +428,9 @@  discard block
 block discarded – undo
428 428
 				LEFT JOIN player p ON a.account_id = p.account_id AND p.game_id = ' . $db->escapeNumber(NPC_GAME_ID) . '
429 429
 				WHERE active=' . $db->escapeBoolean(true) . ' AND working=' . $db->escapeBoolean(false) . ' AND login NOT IN (' . $db->escapeArray($NPC_LOGINS_USED) . ')
430 430
 				ORDER BY (turns IS NOT NULL), turns DESC');
431
-	while($db->nextRecord()) {
432
-		$db2->query('UPDATE npc_logins SET working='.$db2->escapeBoolean(true).' WHERE login='.$db2->escapeString($db->getField('login')).' AND working='.$db2->escapeBoolean(false));
433
-		if($db2->getChangedRows()>0) {
431
+	while ($db->nextRecord()) {
432
+		$db2->query('UPDATE npc_logins SET working=' . $db2->escapeBoolean(true) . ' WHERE login=' . $db2->escapeString($db->getField('login')) . ' AND working=' . $db2->escapeBoolean(false));
433
+		if ($db2->getChangedRows() > 0) {
434 434
 			$NPC_LOGIN = array(
435 435
 					'Login' => $db->getField('login'),
436 436
 					'PlayerName' => $db->getField('player_name'),
@@ -441,30 +441,30 @@  discard block
 block discarded – undo
441 441
 	}
442 442
 	$NPC_LOGINS_USED[] = $NPC_LOGIN['Login'];
443 443
 
444
-	if($NPC_LOGIN===null) {
444
+	if ($NPC_LOGIN === null) {
445 445
 		debug('No free NPCs');
446 446
 		exitNPC();
447 447
 	}
448
-	debug('Chosen NPC: '.$NPC_LOGIN['Login']);
448
+	debug('Chosen NPC: ' . $NPC_LOGIN['Login']);
449 449
 
450
-	if(SmrAccount::getAccountByName($NPC_LOGIN['Login'])==null) {
451
-		debug('Creating account for: '.$NPC_LOGIN['Login']);
452
-		$account = SmrAccount::createAccount($NPC_LOGIN['Login'],'','[email protected]','NPC','NPC',0,0);
450
+	if (SmrAccount::getAccountByName($NPC_LOGIN['Login']) == null) {
451
+		debug('Creating account for: ' . $NPC_LOGIN['Login']);
452
+		$account = SmrAccount::createAccount($NPC_LOGIN['Login'], '', '[email protected]', 'NPC', 'NPC', 0, 0);
453 453
 		$account->setValidated(true);
454 454
 	}
455 455
 	else {
456 456
 		$account = SmrAccount::getAccountByName($NPC_LOGIN['Login']);
457 457
 	}
458 458
 
459
-	$GLOBALS['account'] =& $account;
459
+	$GLOBALS['account'] = & $account;
460 460
 	SmrSession::$account_id = $account->getAccountID();
461 461
 	$underAttack = false;
462 462
 
463 463
 	//Auto-create player if need be.
464
-	$db->query('SELECT 1 FROM player WHERE account_id = '.$account->getAccountID().' AND game_id = '.NPC_GAME_ID.' LIMIT 1');
465
-	if(!$db->nextRecord()) {
464
+	$db->query('SELECT 1 FROM player WHERE account_id = ' . $account->getAccountID() . ' AND game_id = ' . NPC_GAME_ID . ' LIMIT 1');
465
+	if (!$db->nextRecord()) {
466 466
 		SmrSession::updateGame(0); //Have to be out of game to join game.
467
-		debug('Auto-creating player: '.$account->getLogin());
467
+		debug('Auto-creating player: ' . $account->getLogin());
468 468
 		processContainer(joinGame(SmrSession::getGameID(), $NPC_LOGIN['PlayerName']));
469 469
 	}
470 470
 
@@ -472,63 +472,63 @@  discard block
 block discarded – undo
472 472
 }
473 473
 
474 474
 function canWeUNO(AbstractSmrPlayer &$player, $oppurtunisticOnly) {
475
-	if($player->getCredits()<MINUMUM_RESERVE_CREDITS)
475
+	if ($player->getCredits() < MINUMUM_RESERVE_CREDITS)
476 476
 		return false;
477
-	$ship =& $player->getShip();
478
-	if($ship->hasMaxShields()&&$ship->hasMaxArmour()&&$ship->hasMaxCargoHolds())
477
+	$ship = & $player->getShip();
478
+	if ($ship->hasMaxShields() && $ship->hasMaxArmour() && $ship->hasMaxCargoHolds())
479 479
 		return false;
480
-	$sector =& $player->getSector();
480
+	$sector = & $player->getSector();
481 481
 
482 482
 	// We buy armour in preference to shields as it's cheaper.
483 483
 	// We buy cargo holds last if we have no newbie turns because we'd rather not die
484
-	$hardwareArray = array(HARDWARE_ARMOUR,HARDWARE_SHIELDS,HARDWARE_CARGO);
484
+	$hardwareArray = array(HARDWARE_ARMOUR, HARDWARE_SHIELDS, HARDWARE_CARGO);
485 485
 
486 486
 	$amount = 0;
487 487
 
488
-	$locations =& $sector->getLocations();
489
-	foreach($locations as &$location) {
490
-		if($location->isHardwareSold()) {
491
-			$hardwareSold =& $location->getHardwareSold();
492
-			if($player->getNewbieTurns() > MIN_NEWBIE_TURNS_TO_BUY_CARGO && !$ship->hasMaxCargoHolds() && isset($hardwareSold[HARDWARE_CARGO]) && ($amount = floor(($player->getCredits()-MINUMUM_RESERVE_CREDITS)/Globals::getHardwareCost(HARDWARE_CARGO))) > 0) { // Buy cargo holds first if we have plenty of newbie turns left.
488
+	$locations = & $sector->getLocations();
489
+	foreach ($locations as &$location) {
490
+		if ($location->isHardwareSold()) {
491
+			$hardwareSold = & $location->getHardwareSold();
492
+			if ($player->getNewbieTurns() > MIN_NEWBIE_TURNS_TO_BUY_CARGO && !$ship->hasMaxCargoHolds() && isset($hardwareSold[HARDWARE_CARGO]) && ($amount = floor(($player->getCredits() - MINUMUM_RESERVE_CREDITS) / Globals::getHardwareCost(HARDWARE_CARGO))) > 0) { // Buy cargo holds first if we have plenty of newbie turns left.
493 493
 				$hardwareID = HARDWARE_CARGO;
494 494
 			}
495 495
 			else {
496
-				foreach($hardwareArray as $hardwareArrayID) {
497
-					if(!$ship->hasMaxHardware($hardwareArrayID) && isset($hardwareSold[$hardwareArrayID]) && ($amount = floor(($player->getCredits()-MINUMUM_RESERVE_CREDITS)/Globals::getHardwareCost($hardwareArrayID))) > 0) {
496
+				foreach ($hardwareArray as $hardwareArrayID) {
497
+					if (!$ship->hasMaxHardware($hardwareArrayID) && isset($hardwareSold[$hardwareArrayID]) && ($amount = floor(($player->getCredits() - MINUMUM_RESERVE_CREDITS) / Globals::getHardwareCost($hardwareArrayID))) > 0) {
498 498
 						$hardwareID = $hardwareArrayID;
499 499
 						break;
500 500
 					}
501 501
 				}
502 502
 			}
503
-			if(isset($hardwareID)) {
504
-				return doUNO($hardwareID,min($ship->getMaxHardware($hardwareID)-$ship->getHardware($hardwareID),$amount));
503
+			if (isset($hardwareID)) {
504
+				return doUNO($hardwareID, min($ship->getMaxHardware($hardwareID) - $ship->getHardware($hardwareID), $amount));
505 505
 			}
506 506
 		}
507 507
 	}
508 508
 
509
-	if($oppurtunisticOnly===true)
509
+	if ($oppurtunisticOnly === true)
510 510
 		return false;
511 511
 
512
-	if($player->getCredits()-$ship->getCostToUNO()<MINUMUM_RESERVE_CREDITS)
512
+	if ($player->getCredits() - $ship->getCostToUNO() < MINUMUM_RESERVE_CREDITS)
513 513
 		return false; //Only do non-oppurtunistic UNO if we have the money to do it properly!
514 514
 
515
-	foreach($hardwareArray as $hardwareArrayID) {
516
-		if(!$ship->hasMaxHardware($hardwareArrayID)) {
515
+	foreach ($hardwareArray as $hardwareArrayID) {
516
+		if (!$ship->hasMaxHardware($hardwareArrayID)) {
517 517
 			$hardwareNeededID = $hardwareArrayID;
518 518
 			return plotToNearest($player, Globals::getHardwareTypes($hardwareArrayID));
519 519
 		}
520 520
 	}
521 521
 }
522 522
 
523
-function doUNO($hardwareID,$amount) {
524
-	debug('Buying '.$amount.' units of "'.Globals::getHardwareName($hardwareID).'"');
523
+function doUNO($hardwareID, $amount) {
524
+	debug('Buying ' . $amount . ' units of "' . Globals::getHardwareName($hardwareID) . '"');
525 525
 	$_REQUEST['amount'] = $amount;
526
-	return create_container('shop_hardware_processing.php','',array('hardware_id'=>$hardwareID));
526
+	return create_container('shop_hardware_processing.php', '', array('hardware_id'=>$hardwareID));
527 527
 }
528 528
 
529
-function tradeGoods($goodID,AbstractSmrPlayer &$player,SmrPort &$port) {
529
+function tradeGoods($goodID, AbstractSmrPlayer &$player, SmrPort &$port) {
530 530
 	sleepNPC(); //We have an extra sleep at port to make the NPC more vulnerable.
531
-	$ship =& $player->getShip();
531
+	$ship = & $player->getShip();
532 532
 	$relations = $player->getRelation($port->getRaceID());
533 533
 
534 534
 	$transaction = $port->getGoodTransaction($goodID);
@@ -542,29 +542,29 @@  discard block
 block discarded – undo
542 542
 	$idealPrice = $port->getIdealPrice($goodID, $transaction, $amount, $relations);
543 543
 	$offeredPrice = $port->getOfferPrice($idealPrice, $relations, $transaction);
544 544
 
545
-	return create_container('shop_goods_processing.php','',array('offered_price'=>$offeredPrice,'ideal_price'=>$idealPrice,'amount'=>$amount,'good_id'=>$goodID,'bargain_price'=>$offeredPrice));
545
+	return create_container('shop_goods_processing.php', '', array('offered_price'=>$offeredPrice, 'ideal_price'=>$idealPrice, 'amount'=>$amount, 'good_id'=>$goodID, 'bargain_price'=>$offeredPrice));
546 546
 }
547 547
 
548 548
 function dumpCargo(&$player) {
549
-	$ship =& $player->getShip();
550
-	$cargo =& $ship->getCargo();
551
-	debug('Ship Cargo',$cargo);
552
-	foreach($cargo as $goodID => $amount) {
553
-		if($amount > 0) {
554
-			return create_container('cargo_dump_processing.php','',array('good_id'=>$goodID,'amount'=>$amount));
549
+	$ship = & $player->getShip();
550
+	$cargo = & $ship->getCargo();
551
+	debug('Ship Cargo', $cargo);
552
+	foreach ($cargo as $goodID => $amount) {
553
+		if ($amount > 0) {
554
+			return create_container('cargo_dump_processing.php', '', array('good_id'=>$goodID, 'amount'=>$amount));
555 555
 		}
556 556
 	}
557 557
 }
558 558
 
559
-function plotToSector(&$player,$sectorID) {
560
-	return create_container('course_plot_processing.php','',array('from'=>$player->getSectorID(),'to'=>$sectorID));
559
+function plotToSector(&$player, $sectorID) {
560
+	return create_container('course_plot_processing.php', '', array('from'=>$player->getSectorID(), 'to'=>$sectorID));
561 561
 }
562 562
 
563
-function plotToFed(&$player,$plotToHQ=false) {
564
-	debug('Plotting To Fed',$plotToHQ);
563
+function plotToFed(&$player, $plotToHQ = false) {
564
+	debug('Plotting To Fed', $plotToHQ);
565 565
 
566
-	if($plotToHQ === false && $player->getSector()->offersFederalProtection()) {
567
-		if(!$player->hasNewbieTurns() && !$player->hasFederalProtection() && $player->getShip()->hasIllegalGoods()) { //We have illegals and no newbie turns, dump the illegals to get fed protection.
566
+	if ($plotToHQ === false && $player->getSector()->offersFederalProtection()) {
567
+		if (!$player->hasNewbieTurns() && !$player->hasFederalProtection() && $player->getShip()->hasIllegalGoods()) { //We have illegals and no newbie turns, dump the illegals to get fed protection.
568 568
 			debug('Dumping illegals');
569 569
 			processContainer(dumpCargo($player));
570 570
 		}
@@ -572,36 +572,36 @@  discard block
 block discarded – undo
572 572
 		changeNPCLogin();
573 573
 		return true;
574 574
 	}
575
-	if($plotToHQ===true) {
576
-		return plotToNearest($player,SmrLocation::getLocation($player->getRaceID()+LOCATION_GROUP_RACIAL_HQS));
575
+	if ($plotToHQ === true) {
576
+		return plotToNearest($player, SmrLocation::getLocation($player->getRaceID() + LOCATION_GROUP_RACIAL_HQS));
577 577
 	}
578
-	return plotToNearest($player,SmrLocation::getLocation($player->getRaceID()+LOCATION_GROUP_RACIAL_BEACONS));
578
+	return plotToNearest($player, SmrLocation::getLocation($player->getRaceID() + LOCATION_GROUP_RACIAL_BEACONS));
579 579
 //	return plotToNearest($player,$plotToHQ===true?'HQ':'Fed');
580 580
 }
581 581
 
582 582
 function plotToNearest(AbstractSmrPlayer &$player, &$realX) {
583
-	debug('Plotting To: ',$realX); //TODO: Can we make the debug output a bit nicer?
583
+	debug('Plotting To: ', $realX); //TODO: Can we make the debug output a bit nicer?
584 584
 
585
-	if($player->getSector()->hasX($realX)) { //Check if current sector has what we're looking for before we attempt to plot and get error.
585
+	if ($player->getSector()->hasX($realX)) { //Check if current sector has what we're looking for before we attempt to plot and get error.
586 586
 		debug('Already available in sector');
587 587
 		return true;
588 588
 	}
589 589
 
590
-	return create_container('course_plot_nearest_processing.php','',array('RealX'=>$realX));
590
+	return create_container('course_plot_nearest_processing.php', '', array('RealX'=>$realX));
591 591
 }
592
-function moveToSector(&$player,$targetSector) {
593
-	debug('Moving from #'.$player->getSectorID().' to #'.$targetSector);
594
-	return create_container('sector_move_processing.php','',array('target_sector'=>$targetSector,'target_page'=>''));
592
+function moveToSector(&$player, $targetSector) {
593
+	debug('Moving from #' . $player->getSectorID() . ' to #' . $targetSector);
594
+	return create_container('sector_move_processing.php', '', array('target_sector'=>$targetSector, 'target_page'=>''));
595 595
 }
596 596
 
597 597
 function checkForShipUpgrade(AbstractSmrPlayer &$player) {
598
-	foreach(SHIP_UPGRADE_PATH[$player->getRaceID()] as $upgradeShipID) {
599
-		if($player->getShipTypeID()==$upgradeShipID) //We can't upgrade, only downgrade.
598
+	foreach (SHIP_UPGRADE_PATH[$player->getRaceID()] as $upgradeShipID) {
599
+		if ($player->getShipTypeID() == $upgradeShipID) //We can't upgrade, only downgrade.
600 600
 			return false;
601
-		if($upgradeShipID == SHIP_TYPE_NEWBIE_MERCHANT_VESSEL) //We can't actually buy the NMV, we just don't want to downgrade from it if we have it.
601
+		if ($upgradeShipID == SHIP_TYPE_NEWBIE_MERCHANT_VESSEL) //We can't actually buy the NMV, we just don't want to downgrade from it if we have it.
602 602
 			continue;
603 603
 		$cost = $player->getShip()->getCostToUpgrade($upgradeShipID);
604
-		if($cost <= 0 || $player->getCredits()-$cost > MINUMUM_RESERVE_CREDITS) {
604
+		if ($cost <= 0 || $player->getCredits() - $cost > MINUMUM_RESERVE_CREDITS) {
605 605
 			return doShipUpgrade($player, $upgradeShipID);
606 606
 		}
607 607
 	}
@@ -609,50 +609,50 @@  discard block
 block discarded – undo
609 609
 	return false;
610 610
 }
611 611
 
612
-function doShipUpgrade(AbstractSmrPlayer &$player,$upgradeShipID) {
613
-	$plotNearest = plotToNearest($player,AbstractSmrShip::getBaseShip(Globals::getGameType($player->getGameID()),$upgradeShipID));
612
+function doShipUpgrade(AbstractSmrPlayer &$player, $upgradeShipID) {
613
+	$plotNearest = plotToNearest($player, AbstractSmrShip::getBaseShip(Globals::getGameType($player->getGameID()), $upgradeShipID));
614 614
 
615
-	if($plotNearest == true) { //We're already there!
615
+	if ($plotNearest == true) { //We're already there!
616 616
 		//TODO: We're going to want to UNO after upgrading
617
-		return create_container('shop_ship_processing.php','',array('ship_id'=>$upgradeShipID));
617
+		return create_container('shop_ship_processing.php', '', array('ship_id'=>$upgradeShipID));
618 618
 	} //Otherwise return the plot
619 619
 	return $plotNearest;
620 620
 }
621 621
 
622 622
 function &changeRoute(array &$tradeRoutes) {
623 623
 	$false = false;
624
-	if(count($tradeRoutes)==0)
624
+	if (count($tradeRoutes) == 0)
625 625
 		return $false;
626 626
 	$routeKey = array_rand($tradeRoutes);
627
-	$tradeRoute =& $tradeRoutes[$routeKey];
627
+	$tradeRoute = & $tradeRoutes[$routeKey];
628 628
 	unset($tradeRoutes[$routeKey]);
629
-	$GLOBALS['TRADE_ROUTE'] =& $tradeRoute;
630
-	debug('Switched route',$tradeRoute);
629
+	$GLOBALS['TRADE_ROUTE'] = & $tradeRoute;
630
+	debug('Switched route', $tradeRoute);
631 631
 	return $tradeRoute;
632 632
 }
633 633
 
634
-function joinGame($gameID,$playerName) {
634
+function joinGame($gameID, $playerName) {
635 635
 	global $NPC_LOGIN;
636
-	debug('Creating player for: '.$NPC_LOGIN['Login']);
636
+	debug('Creating player for: ' . $NPC_LOGIN['Login']);
637 637
 	$races = Globals::getRaces();
638
-	while(($raceID = array_rand($races))===1); //Random race that's not neutral.
638
+	while (($raceID = array_rand($races)) === 1); //Random race that's not neutral.
639 639
 
640
-	debug('Chosen race "'.$races[$raceID]['Race Name'].'": '.$raceID);
640
+	debug('Chosen race "' . $races[$raceID]['Race Name'] . '": ' . $raceID);
641 641
 
642 642
 	$_REQUEST['player_name'] = $playerName;
643 643
 	$_REQUEST['race_id'] = $raceID;
644 644
 
645
-	return create_container('game_join_processing.php','',array('game_id'=>NPC_GAME_ID));
645
+	return create_container('game_join_processing.php', '', array('game_id'=>NPC_GAME_ID));
646 646
 }
647 647
 
648
-function joinAlliance($allianceID,$password) {
649
-	debug('Joining alliance: '.$allianceID);
648
+function joinAlliance($allianceID, $password) {
649
+	debug('Joining alliance: ' . $allianceID);
650 650
 	$_REQUEST['password'] = $password;
651
-	return create_container('alliance_join_processing.php','',array('alliance_id'=>$allianceID));
651
+	return create_container('alliance_join_processing.php', '', array('alliance_id'=>$allianceID));
652 652
 }
653 653
 
654
-function createAlliance($allianceName,$password) {
655
-	debug('Creating alliance: '.$allianceName);
654
+function createAlliance($allianceName, $password) {
655
+	debug('Creating alliance: ' . $allianceName);
656 656
 	$_REQUEST['name'] = $allianceName;
657 657
 	$_REQUEST['password'] = $password;
658 658
 	$_REQUEST['perms'] = 'full';
@@ -661,54 +661,54 @@  discard block
 block discarded – undo
661 661
 
662 662
 function leaveAlliance() {
663 663
 	debug('Leaving alliance');
664
-	return create_container('alliance_leave_processing.php','',array('action'=>'YES'));
664
+	return create_container('alliance_leave_processing.php', '', array('action'=>'YES'));
665 665
 }
666 666
 
667 667
 function &findRoutes(&$player) {
668 668
 	debug('Finding Routes');
669 669
 
670
-	$galaxies =& SmrGalaxy::getGameGalaxies($player->getGameID());
670
+	$galaxies = & SmrGalaxy::getGameGalaxies($player->getGameID());
671 671
 
672 672
 	$tradeGoods = array(GOOD_NOTHING => false);
673
-	$goods =& Globals::getGoods();
674
-	foreach($goods as $goodID => &$good) {
675
-		if($player->meetsAlignmentRestriction($good['AlignRestriction']))
673
+	$goods = & Globals::getGoods();
674
+	foreach ($goods as $goodID => &$good) {
675
+		if ($player->meetsAlignmentRestriction($good['AlignRestriction']))
676 676
 			$tradeGoods[$goodID] = true;
677 677
 		else
678 678
 			$tradeGoods[$goodID] = false;
679 679
 	} unset($good);
680 680
 	$tradeRaces = array();
681
-	$races =& Globals::getRaces();
682
-	foreach($races as $raceID => &$race) {
681
+	$races = & Globals::getRaces();
682
+	foreach ($races as $raceID => &$race) {
683 683
 		$tradeRaces[$raceID] = false;
684 684
 	} unset($race);
685 685
 	$tradeRaces[$player->getRaceID()] = true;
686 686
 
687
-	$galaxy =& $player->getSector()->getGalaxy();
687
+	$galaxy = & $player->getSector()->getGalaxy();
688 688
 
689 689
 	$maxNumberOfPorts = 2;
690
-	$routesForPort=-1;
691
-	$numberOfRoutes=1000;
692
-	$maxDistance=15;
690
+	$routesForPort = -1;
691
+	$numberOfRoutes = 1000;
692
+	$maxDistance = 15;
693 693
 
694
-	$startSectorID=$galaxy->getStartSector();
695
-	$endSectorID=$galaxy->getEndSector();
694
+	$startSectorID = $galaxy->getStartSector();
695
+	$endSectorID = $galaxy->getEndSector();
696 696
 
697 697
 	$db = new SmrMySqlDatabase();
698
-	$db->query('SELECT routes FROM route_cache WHERE game_id='.$db->escapeNumber($player->getGameID()).' AND max_ports='.$db->escapeNumber($maxNumberOfPorts).' AND goods_allowed='.$db->escapeObject($tradeGoods).' AND races_allowed='.$db->escapeObject($tradeRaces).' AND start_sector_id='.$db->escapeNumber($startSectorID).' AND end_sector_id='.$db->escapeNumber($endSectorID).' AND routes_for_port='.$db->escapeNumber($routesForPort).' AND max_distance='.$db->escapeNumber($maxDistance));
699
-	if($db->nextRecord()) {
698
+	$db->query('SELECT routes FROM route_cache WHERE game_id=' . $db->escapeNumber($player->getGameID()) . ' AND max_ports=' . $db->escapeNumber($maxNumberOfPorts) . ' AND goods_allowed=' . $db->escapeObject($tradeGoods) . ' AND races_allowed=' . $db->escapeObject($tradeRaces) . ' AND start_sector_id=' . $db->escapeNumber($startSectorID) . ' AND end_sector_id=' . $db->escapeNumber($endSectorID) . ' AND routes_for_port=' . $db->escapeNumber($routesForPort) . ' AND max_distance=' . $db->escapeNumber($maxDistance));
699
+	if ($db->nextRecord()) {
700 700
 		$routes = unserialize(gzuncompress($db->getField('routes')));
701
-		debug('Using Cached Routes: #'.count($routes));
701
+		debug('Using Cached Routes: #' . count($routes));
702 702
 		return $routes;
703 703
 	}
704 704
 	else {
705 705
 		debug('Generating Routes');
706 706
 		$allSectors = array();
707
-		foreach($galaxies as &$galaxy) {
707
+		foreach ($galaxies as &$galaxy) {
708 708
 			$allSectors += $galaxy->getSectors(); //Merge arrays
709 709
 		} unset($galaxy);
710 710
 
711
-		$distances =& Plotter::calculatePortToPortDistances($allSectors,$maxDistance,$startSectorID,$endSectorID);
711
+		$distances = & Plotter::calculatePortToPortDistances($allSectors, $maxDistance, $startSectorID, $endSectorID);
712 712
 
713 713
 
714 714
 		if ($maxNumberOfPorts == 1)
@@ -718,9 +718,9 @@  discard block
 block discarded – undo
718 718
 
719 719
 		unset($distances);
720 720
 
721
-		$allRoutes =& $allRoutes[RouteGenerator::EXP_ROUTE];
721
+		$allRoutes = & $allRoutes[RouteGenerator::EXP_ROUTE];
722 722
 		$routesMerged = array();
723
-		foreach($allRoutes as $multi => &$routesByMulti) {
723
+		foreach ($allRoutes as $multi => &$routesByMulti) {
724 724
 			$routesMerged += $routesByMulti; //Merge arrays
725 725
 		} unset($routesByMulti);
726 726
 
@@ -735,8 +735,8 @@  discard block
 block discarded – undo
735 735
 
736 736
 		$db->query('INSERT INTO route_cache ' .
737 737
 				'(game_id, max_ports, goods_allowed, races_allowed, start_sector_id, end_sector_id, routes_for_port, max_distance, routes)' .
738
-				' VALUES ('.$db->escapeNumber($player->getGameID()).', '.$db->escapeNumber($maxNumberOfPorts).', '.$db->escapeObject($tradeGoods).', '.$db->escapeObject($tradeRaces).', '.$db->escapeNumber($startSectorID).', '.$db->escapeNumber($endSectorID).', '.$db->escapeNumber($routesForPort).', '.$db->escapeNumber($maxDistance).', '.$db->escapeObject($routesMerged,true).')');
739
-		debug('Found Routes: #'.count($routesMerged));
738
+				' VALUES (' . $db->escapeNumber($player->getGameID()) . ', ' . $db->escapeNumber($maxNumberOfPorts) . ', ' . $db->escapeObject($tradeGoods) . ', ' . $db->escapeObject($tradeRaces) . ', ' . $db->escapeNumber($startSectorID) . ', ' . $db->escapeNumber($endSectorID) . ', ' . $db->escapeNumber($routesForPort) . ', ' . $db->escapeNumber($maxDistance) . ', ' . $db->escapeObject($routesMerged, true) . ')');
739
+		debug('Found Routes: #' . count($routesMerged));
740 740
 		return $routesMerged;
741 741
 	}
742 742
 }
Please login to merge, or discard this patch.
tools/npc/chess.php 1 patch
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -10,22 +10,22 @@  discard block
 block discarded – undo
10 10
 
11 11
 	debug('Script started');
12 12
 	define('SCRIPT_ID', $db->getInsertID());
13
-	$db->query('UPDATE npc_logs SET script_id='.SCRIPT_ID.' WHERE log_id='.SCRIPT_ID);
13
+	$db->query('UPDATE npc_logs SET script_id=' . SCRIPT_ID . ' WHERE log_id=' . SCRIPT_ID);
14 14
 
15 15
 	define('NPC_SCRIPT', true);
16 16
 
17 17
 	$descriptorSpec = array(
18
-		0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
18
+		0 => array("pipe", "r"), // stdin is a pipe that the child will read from
19 19
 		1 => array("pipe", "w")  // stdout is a pipe that the child will write to
20 20
 	);
21 21
 	$engine = proc_open(UCI_CHESS_ENGINE, $descriptorSpec, $pipes);
22
-	$toEngine =& $pipes[0];
23
-	$fromEngine =& $pipes[1];
22
+	$toEngine = & $pipes[0];
23
+	$fromEngine = & $pipes[1];
24 24
 
25 25
 	function readFromEngine($block = true) {
26 26
 		global $fromEngine;
27 27
 		stream_set_blocking($fromEngine, $block == true ? 1 : 0);
28
-		while(($s = fgets($fromEngine)) !== false) {
28
+		while (($s = fgets($fromEngine)) !== false) {
29 29
 			debug('<-- ' . trim($s));
30 30
 			stream_set_blocking($fromEngine, 0);
31 31
 		}
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 		global $toEngine;
35 35
 		debug('--> ' . $s);
36 36
 		fputs($toEngine, $s . EOL);
37
-		if($read === true) {
37
+		if ($read === true) {
38 38
 			readFromEngine($block);
39 39
 		}
40 40
 	}
@@ -46,20 +46,20 @@  discard block
 block discarded – undo
46 46
 	writeToEngine('ucinewgame', false);
47 47
 	SmrSession::updateGame(NPC_GAME_ID);
48 48
 
49
-	while(true) {
49
+	while (true) {
50 50
 		//Redefine MICRO_TIME and TIME, the rest of the game expects them to be the single point in time that the script is executing, with it being redefined for each page load - unfortunately NPCs are one consistent script so we have to do a hack and redefine it (or change every instance of the TIME constant).
51 51
 		runkit_constant_redefine('MICRO_TIME', microtime(true));
52 52
 		runkit_constant_redefine('TIME', intval(MICRO_TIME));
53 53
 
54
-		$chessGames =& ChessGame::getNPCMoveGames(true);
55
-		foreach($chessGames as &$chessGame) {
54
+		$chessGames = & ChessGame::getNPCMoveGames(true);
55
+		foreach ($chessGames as &$chessGame) {
56 56
 			debug('Looking at game: ' . $chessGame->getChessGameID());
57 57
 			writeToEngine('position fen ' . $chessGame->getFENString(), false);
58 58
 			writeToEngine('go ' . ($chessGame->getCurrentTurnColour() == ChessGame::PLAYER_WHITE ? 'w' : 'b') . 'time ' . UCI_TIME_PER_MOVE_MS, true, false);
59 59
 			stream_set_blocking($fromEngine, 1);
60
-			while(stripos($move = trim(fgets($fromEngine)), 'bestmove') !== 0) {
60
+			while (stripos($move = trim(fgets($fromEngine)), 'bestmove') !== 0) {
61 61
 				debug('<-- ' . $move);
62
-				if(stripos($move, 'Seg') === 0) {
62
+				if (stripos($move, 'Seg') === 0) {
63 63
 					// Segfault
64 64
 					debug('UCI engine segfaulted?');
65 65
 					exit;
@@ -80,12 +80,12 @@  discard block
 block discarded – undo
80 80
 	fclose($fromEngine);
81 81
 	proc_close($engine);
82 82
 }
83
-catch(Throwable $e) {
83
+catch (Throwable $e) {
84 84
 	logException($e);
85 85
 	exit;
86 86
 }
87 87
 function debug($message, $debugObject = null) {
88
-	global $account,$var,$db;
89
-	echo date('Y-m-d H:i:s - ').$message.($debugObject!==null?EOL.var_export($debugObject,true):'').EOL;
90
-	$db->query('INSERT INTO npc_logs (script_id, npc_id, time, message, debug_info, var) VALUES ('.(defined('SCRIPT_ID')?SCRIPT_ID:0).', '.(is_object($account)?$account->getAccountID():0).',NOW(),'.$db->escapeString($message).','.$db->escapeString(var_export($debugObject,true)).','.$db->escapeString(var_export($var,true)).')');
88
+	global $account, $var, $db;
89
+	echo date('Y-m-d H:i:s - ') . $message . ($debugObject !== null ?EOL.var_export($debugObject, true) : '') . EOL;
90
+	$db->query('INSERT INTO npc_logs (script_id, npc_id, time, message, debug_info, var) VALUES (' . (defined('SCRIPT_ID') ?SCRIPT_ID:0) . ', ' . (is_object($account) ? $account->getAccountID() : 0) . ',NOW(),' . $db->escapeString($message) . ',' . $db->escapeString(var_export($debugObject, true)) . ',' . $db->escapeString(var_export($var, true)) . ')');
91 91
 }
Please login to merge, or discard this patch.