Completed
Push — work-fleets ( 8591a1...0fb536 )
by SuperNova.WS
07:12
created

general.php ➔ getMinifiedName()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 19
rs 9.2
1
<?php
2
3
/*
4
Function wrapping
5
6
Due glitch in PHP 5.3.1 SuperNova is incompatible with this version
7
Reference: https://bugs.php.net/bug.php?id=50394
8
9
*/
10
11
use DBStatic\DBStaticAlly;
12
use DBStatic\DBStaticPlanet;
13
use DBStatic\DBStaticUnit;
14
use DBStatic\DBStaticUser;
15
16
require_once('general_pname.php');
17
18
/**
19
 * @param       $func_name
20
 * @param array $func_arg
21
 *
22
 * @return mixed
23
 */
24
function sn_function_call($func_name, $func_arg = array()) {
25
  // All data in classSupernova::$functions should be normalized to valid 'callable' state: '<function_name>'|array('<object_name>', '<method_name>')
26
  $result = null;
27
28
  if (!empty(classSupernova::$functions[$func_name]) && is_array(classSupernova::$functions[$func_name]) && !is_callable(classSupernova::$functions[$func_name])) {
29
    // Chain-callable functions should be made as following:
30
    // 1. Never use incomplete calls with parameters "by default"
31
    // 2. Reserve last parameter for cumulative result
32
    // 3. Use same format for original value and cumulative result (if there is original value)
33
    // 4. Honor cumulative result
34
    // 5. Return cumulative result
35
    foreach (classSupernova::$functions[$func_name] as $func_chain_name) {
36
      // По идее - это уже тут не нужно, потому что оно все должно быть callable к этому моменту
37
      // Но для старых модулей...
38
      if (is_callable($func_chain_name)) {
39
        $result = call_user_func_array($func_chain_name, $func_arg);
40
      }
41
    }
42
  } else {
43
    // TODO: This is left for backward compatibility. Appropriate code should be rewrote!
44
    $func_name = isset(classSupernova::$functions[$func_name]) && is_callable(classSupernova::$functions[$func_name]) ? classSupernova::$functions[$func_name] : ('sn_' . $func_name);
45
    if (is_callable($func_name)) {
46
      $result = call_user_func_array($func_name, $func_arg);
47
    }
48
  }
49
50
  return $result;
51
}
52
53
/**
54
 * @param        $hook_list
55
 * @param        $template
56
 * @param string $hook_type - тип хука 'model' или 'view'
57
 * @param string $page_name - имя страницы, для которого должен был быть выполнен хук
58
 */
59
function execute_hooks(&$hook_list, &$template, $hook_type = null, $page_name = null) {
60
  if (!empty($hook_list)) {
61
    foreach ($hook_list as $hook) {
62
      if (is_callable($hook_call = (is_string($hook) ? $hook : (is_array($hook) ? $hook['callable'] : $hook->callable)))) {
63
        $template = call_user_func($hook_call, $template, $hook_type, $page_name);
64
      }
65
    }
66
  }
67
}
68
69
// ----------------------------------------------------------------------------------------------------------------
70
function sys_file_read($filename) {
71
  return @file_get_contents($filename);
72
}
73
74
function sys_file_write($filename, $content) {
75
  return @file_put_contents($filename, $content, FILE_APPEND);
76
}
77
78
function get_game_speed($plain = false) { return sn_function_call(__FUNCTION__, array($plain, &$result)); }
79
80
function sn_get_game_speed($plain = false, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $plain is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
81
  return $result = classSupernova::$config->game_speed ? classSupernova::$config->game_speed : 1;
82
}
83
84
function flt_server_flight_speed_multiplier($plain = false) { return sn_function_call(__FUNCTION__, array($plain, &$result)); }
85
86
function sn_flt_server_flight_speed_multiplier($plain = false, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $plain is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
87
  return $result = classSupernova::$config->fleet_speed;
88
}
89
90
function game_resource_multiplier($plain = false) { return sn_function_call(__FUNCTION__, array($plain, &$result)); }
91
92
function sn_game_resource_multiplier($plain = false, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $plain is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
93
  return $result = classSupernova::$config->resource_multiplier;
94
}
95
96
/**
97
 * Получение стоимости ММ в валюте сервера
98
 *
99
 * @param bool|false $plain
100
 *
101
 * @return mixed
102
 */
103
function get_mm_cost($plain = false) { return sn_function_call(__FUNCTION__, array($plain, &$result)); }
104
105
function sn_get_mm_cost($plain = false, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $plain is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
106
  return $result = classSupernova::$config->payment_currency_exchange_mm_ ? classSupernova::$config->payment_currency_exchange_mm_ : METAMATTER_DEFAULT_LOT_SIZE;
107
}
108
109
/**
110
 * Получение курса обмены валюты в серверную валюту
111
 *
112
 * @param $currency_symbol
113
 *
114
 * @return float
115
 */
116
function get_exchange_rate($currency_symbol) {
117
  $currency_symbol = strtolower($currency_symbol);
118
  $config_field = 'payment_currency_exchange_' . $currency_symbol;
119
120
  // Заворачиваем получение стоимости ММ через перекрываемую процедуру
121
  $exchange_rate = floatval($currency_symbol == 'mm_' ? get_mm_cost() : classSupernova::$config->$config_field);
122
123
  return $exchange_rate;
124
}
125
126
/**
127
 * pretty_number implementation for SuperNova
128
 *
129
 * @param float     $n - number to format
130
 * @param int|bool  $floor - (ignored if $limit set)
131
 *    - integer   - floors to $floor numbers after decimal points
132
 *    - true      - floors number before format
133
 *    - otherwise - floors to 2 numbers after decimal points
134
 * @param int|bool  $color
135
 *    - true    - colors number to green if positive or zero; red if negative
136
 *    - 0
137
 *    - numeric - colors number to green if less then $color; red if greater
138
 * @param int|bool  $limit - generally converts "15000" to "15k", "2000000" to "2kk" etc
139
 *    - 0/false - proceed with $floor
140
 *    - numeric - divides number to segments by power of $limit and adds 'k' for each segment
141
 *        - makes sense for 1000, but works with any number
142
 * @param bool|null $style
143
 *    - null  - standard result
144
 *    - true  - return only style class for current params
145
 *    - false - return array('text' => $ret, 'class' => $class), where $ret - unstyled
146
 *
147
 * @return array|float|string
148
 */
149
function pretty_number($n, $floor = true, $color = false, $limit = false, $style = null) {
150
  $n = floatval($n);
151
  if (is_int($floor)) {
152
    $n = round($n, $floor); // , PHP_ROUND_HALF_DOWN
153
  } elseif ($floor === true) {
154
    $n = floor($n);
155
    $floor = 0;
156
  } else {
157
    $floor = 2;
158
  }
159
160
  $ret = $n;
161
162
  $suffix = '';
163
  if ($limit) {
164
    if ($ret > 0) {
165
      while($ret > $limit) {
166
        $suffix .= 'k';
167
        $ret = round($ret / 1000);
168
      }
169
    } else {
170
      while($ret < -$limit) {
171
        $suffix .= 'k';
172
        $ret = round($ret / 1000);
173
      }
174
    }
175
  }
176
177
  $ret = number_format($ret, $floor, ',', '.');
178
  $ret .= $suffix;
179
180
  if ($color !== false) {
181
    if ($color === true) {
182
      $class = $n == 0 ? 'zero' : ($n > 0 ? 'positive' : 'negative');
183
    } elseif ($color >= 0) {
184
      $class = $n == $color ? 'zero' : ($n < $color ? 'positive' : 'negative');
185
    } else {
186
      $class = ($n == -$color) ? 'zero' : ($n < -$color ? 'negative' : 'positive');
187
    }
188
189
    if (!isset($style)) {
190
      $ret = "<span class='{$class}'>{$ret}</span>";
191
    } else {
192
      $ret = $style ? $ret = $class : $ret = array('text' => $ret, 'class' => $class);
193
    }
194
  }
195
196
  return $ret;
197
}
198
199
// ----------------------------------------------------------------------------------------------------------------
200
function pretty_time($seconds) {
201
  $day = floor($seconds / (24 * 3600));
202
203
  $sys_day_short = classLocale::$lang['sys_day_short'];
204
205
  return sprintf("%s%02d:%02d:%02d", $day ? "{$day}{$sys_day_short} " : '', floor($seconds / 3600 % 24), floor($seconds / 60 % 60), floor($seconds / 1 % 60));
206
}
207
208
// ----------------------------------------------------------------------------------------------------------------
209
function eco_planet_fields_max($planet) {
210
  return $planet['field_max'] + ($planet['planet_type'] == PT_PLANET ? mrc_get_level($user, $planet, STRUC_TERRAFORMER) * 5 : (mrc_get_level($user, $planet, STRUC_MOON_STATION) * 3));
211
}
212
213
// ----------------------------------------------------------------------------------------------------------------
214
function flt_get_missile_range($user) {
215
  return max(0, mrc_get_level($user, false, TECH_ENGINE_ION) * 5 - 1);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a array|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
216
}
217
218
// ----------------------------------------------------------------------------------------------------------------
219
function GetSpyLevel(&$user) {
220
  return mrc_modify_value($user, false, array(MRC_SPY, TECH_SPY), 0);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
221
}
222
223
// ----------------------------------------------------------------------------------------------------------------
224
function GetMaxFleets(&$user) {
225
  return mrc_modify_value($user, false, array(MRC_COORDINATOR, TECH_COMPUTER), 1);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
226
}
227
228
// ----------------------------------------------------------------------------------------------------------------
229
// Check input string for forbidden words
230
//
231
function CheckInputStrings($String) {
232
  global $ListCensure;
233
234
  return preg_replace($ListCensure, '*', $String);
235
}
236
237
function is_email($email) {
238
  return (preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
239
}
240
241
function is_id($value) {
242
//  return preg_match('/^\d+$/', $value) && ($value >= 0);
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
243
  return is_numeric($value) && ($value + 0 >= 0);
244
}
245
246
/**
247
 * @param        $param_name
248
 * @param string $default
249
 *
250
 * @return string|array
251
 */
252
function sys_get_param($param_name, $default = '') {
253
  return $_POST[$param_name] !== null ? $_POST[$param_name] : ($_GET[$param_name] !== null ? $_GET[$param_name] : $default);
254
}
255
256
function sys_get_param_array($param_name, $default = array()) {
257
  return is_array($result = sys_get_param($param_name, $default)) ? $result : array();
0 ignored issues
show
Documentation introduced by
$default is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
258
}
259
260
function sys_get_param_id($param_name, $default = 0) {
261
  return is_id($value = sys_get_param($param_name, $default)) ? $value : $default;
262
}
263
264
function sys_get_param_int($param_name, $default = 0) {
265
  $value = sys_get_param($param_name, $default);
266
267
  return $value === 'on' ? 1 : ($value === 'off' ? $default : intval($value));
268
}
269
270
function sys_get_param_float($param_name, $default = 0) {
271
  return floatval(sys_get_param($param_name, $default));
272
}
273
274
function sys_get_param_escaped($param_name, $default = '') {
275
  return db_escape(sys_get_param($param_name, $default));
276
}
277
278
function sys_get_param_date_sql($param_name, $default = '2000-01-01') {
279
  $val = sys_get_param($param_name, $default);
280
281
  return preg_match(PREG_DATE_SQL_RELAXED, $val) ? $val : $default;
282
}
283
284
function sys_get_param_str_unsafe($param_name, $default = '') {
285
  return str_raw2unsafe(sys_get_param($param_name, $default));
286
}
287
288
function sys_get_param_str($param_name, $default = '') {
289
  return db_escape(sys_get_param_str_unsafe($param_name, $default));
290
}
291
292
function sys_get_param_str_both($param_name, $default = '') {
293
  $param = sys_get_param($param_name, $default);
294
  $param_unsafe = str_raw2unsafe($param);
295
296
  return array(
297
    'raw'    => $param,
298
    'unsafe' => $param_unsafe,
299
    'safe'   => db_escape($param_unsafe),
300
  );
301
}
302
303
function sys_get_param_phone($param_name, $default = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $default is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
304
  $phone_raw = sys_get_param_str_unsafe($param_name, $default = '');
305
  if ($phone_raw) {
306
    $phone = $phone_raw[0] == '+' ? '+' : '';
307
    for ($i = 0; $i < strlen($phone_raw); $i++) {
308
      $ord = ord($phone_raw[$i]);
309
      if ($ord >= 48 && $ord <= 57) {
310
        $phone .= $phone_raw[$i];
311
      }
312
    }
313
    $phone = strlen($phone) < 11 ? '' : $phone;
314
  } else {
315
    $phone = '';
316
  }
317
318
  return array('raw' => $phone_raw, 'phone' => $phone);
319
}
320
321
function GetPhalanxRange($phalanx_level) {
322
  return $phalanx_level > 1 ? pow($phalanx_level, 2) - 1 : 0;
323
}
324
325
function CheckAbandonPlanetState(&$planet) {
326
  if ($planet['destruyed'] && $planet['destruyed'] <= SN_TIME_NOW) {
327
    DBStaticPlanet::db_planet_delete_by_id($planet['id']);
328
  }
329
}
330
331
function eco_get_total_cost($unit_id, $unit_level) {
332
  static $rate, $sn_group_resources_all, $sn_group_resources_loot;
333
  if (!$rate) {
334
    $sn_group_resources_all = sn_get_groups('resources_all');
335
    $sn_group_resources_loot = sn_get_groups('resources_loot');
336
337
    $rate[RES_METAL] = classSupernova::$config->rpg_exchange_metal;
338
    $rate[RES_CRYSTAL] = classSupernova::$config->rpg_exchange_crystal / classSupernova::$config->rpg_exchange_metal;
339
    $rate[RES_DEUTERIUM] = classSupernova::$config->rpg_exchange_deuterium / classSupernova::$config->rpg_exchange_metal;
340
  }
341
342
  $unit_cost_data = get_unit_param($unit_id, 'cost');
343
  if (!is_array($unit_cost_data)) {
344
    return array('total' => 0);
345
  }
346
  $factor = isset($unit_cost_data['factor']) ? $unit_cost_data['factor'] : 1;
347
  $cost_array = array(BUILD_CREATE => array(), 'total' => 0);
348
  $unit_level = $unit_level > 0 ? $unit_level : 0;
349
  foreach ($unit_cost_data as $resource_id => $resource_amount) {
350
    if (!in_array($resource_id, $sn_group_resources_all)) {
351
      continue;
352
    }
353
    $cost_array[BUILD_CREATE][$resource_id] = round($resource_amount * ($factor == 1 ? $unit_level : ((1 - pow($factor, $unit_level)) / (1 - $factor))));
354
    if (in_array($resource_id, $sn_group_resources_loot)) {
355
      $cost_array['total'] += $cost_array[BUILD_CREATE][$resource_id] * $rate[$resource_id];
356
    }
357
  }
358
359
  return $cost_array;
360
}
361
362
function sn_unit_purchase($unit_id) { }
0 ignored issues
show
Unused Code introduced by
The parameter $unit_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
363
364
function sn_unit_relocate($unit_id, $from, $to) { }
0 ignored issues
show
Unused Code introduced by
The parameter $unit_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $from is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $to is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
365
366
/**
367
 * @param array|bool|null $user
368
 * @param array|null      $planet
369
 * @param int             $unit_id
370
 * @param bool            $for_update
371
 * @param bool            $plain
372
 *
373
 * @return mixed
374
 */
375
function mrc_get_level(&$user, $planet = array(), $unit_id, $for_update = false, $plain = false) { return sn_function_call(__FUNCTION__, array(&$user, $planet, $unit_id, $for_update, $plain, &$result)); }
376
377
function sn_mrc_get_level(&$user, $planet = array(), $unit_id, $for_update = false, $plain = false, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $for_update is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
378
  $mercenary_level = 0;
379
  $unit_db_name = pname_resource_name($unit_id);
380
381
  if (in_array($unit_id, sn_get_groups(array('plans', 'mercenaries', 'tech', 'artifacts')))) {
382
    $unit = DBStaticUnit::db_get_unit_by_location($user['id'], LOC_USER, $user['id'], $unit_id);
383
    $mercenary_level = is_array($unit) && $unit['unit_level'] ? $unit['unit_level'] : 0;
384
  } elseif (in_array($unit_id, sn_get_groups(array('structures', 'fleet', 'defense')))) {
385
    $unit = DBStaticUnit::db_get_unit_by_location(isset($user['id']) ? $user['id'] : $planet['id_owner'], LOC_PLANET, $planet['id'], $unit_id);
386
    $mercenary_level = is_array($unit) && $unit['unit_level'] ? $unit['unit_level'] : 0;
387
  } elseif (in_array($unit_id, sn_get_groups('governors'))) {
388
    $mercenary_level = $unit_id == $planet['PLANET_GOVERNOR_ID'] ? $planet['PLANET_GOVERNOR_LEVEL'] : 0;
389
  } elseif ($unit_id == RES_DARK_MATTER) {
390
    $mercenary_level = $user[$unit_db_name] + ($plain || $user['user_as_ally'] ? 0 : classSupernova::$auth->account->account_metamatter);
391
  } elseif ($unit_id == RES_METAMATTER) {
392
    $mercenary_level = classSupernova::$auth->account->account_metamatter; //$user[$unit_db_name];
393
  } elseif (in_array($unit_id, sn_get_groups(array('resources_loot'))) || $unit_id == UNIT_SECTOR) {
394
    $mercenary_level = !empty($planet) ? $planet[$unit_db_name] : $user[$unit_db_name];
395
  }
396
397
  return $result = $mercenary_level;
398
}
399
400
function mrc_modify_value(&$user, $planet = array(), $mercenaries, $value) { return sn_function_call(__FUNCTION__, array(&$user, $planet, $mercenaries, $value)); }
401
402
function sn_mrc_modify_value(&$user, $planet = array(), $mercenaries, $value, $base_value = null) {
403
  if (!is_array($mercenaries)) {
404
    $mercenaries = array($mercenaries);
405
  }
406
407
  $base_value = isset($base_value) ? $base_value : $value;
408
409
  foreach ($mercenaries as $mercenary_id) {
410
    $mercenary_level = mrc_get_level($user, $planet, $mercenary_id);
411
412
    $mercenary = get_unit_param($mercenary_id);
413
    $mercenary_bonus = $mercenary['bonus'];
414
415
    switch($mercenary['bonus_type']) {
416
      case BONUS_PERCENT_CUMULATIVE:
417
        $value *= 1 + $mercenary_level * $mercenary_bonus / 100;
418
      break;
419
420
      case BONUS_PERCENT:
421
        $mercenary_level = $mercenary_bonus < 0 && $mercenary_level * $mercenary_bonus < -90 ? -90 / $mercenary_bonus : $mercenary_level;
422
        $value += $base_value * $mercenary_level * $mercenary_bonus / 100;
423
      break;
424
425
      case BONUS_ADD:
426
        $value += $mercenary_level * $mercenary_bonus;
427
      break;
428
429
      case BONUS_ABILITY:
430
        $value = $mercenary_level ? $mercenary_level : 0;
431
      break;
432
433
      default:
434
      break;
435
    }
436
  }
437
438
  return $value;
439
}
440
441
// Generates random string of $length symbols from $allowed_chars charset
442
function sys_random_string($length = 16, $allowed_chars = SN_SYS_SEC_CHARS_ALLOWED) {
443
  $allowed_length = strlen($allowed_chars);
444
445
  $random_string = '';
446
  for ($i = 0; $i < $length; $i++) {
447
    $random_string .= $allowed_chars[mt_rand(0, $allowed_length - 1)];
448
  }
449
450
  return $random_string;
451
}
452
453
function js_safe_string($string) {
454
  return str_replace(array("\r", "\n"), array('\r', '\n'), addslashes($string));
455
}
456
457
function sys_safe_output($string) {
458
  return str_replace(array("&", "\"", "<", ">", "'"), array("&amp;", "&quot;", "&lt;", "&gt;", "&apos;"), $string);
459
}
460
461
function sys_user_options_pack(&$user) {
462
  global $user_option_list;
463
464
  $options = '';
465
  $option_list = array();
466
  foreach ($user_option_list as $option_group_id => $option_group) {
467
    $option_list[$option_group_id] = array();
468
    foreach ($option_group as $option_name => $option_value) {
469
      if (!isset($user[$option_name])) {
470
        $user[$option_name] = $option_value;
471
      } elseif ($user[$option_name] == '') {
472
        $user[$option_name] = 0;
473
      }
474
      $options .= "{$option_name}^{$user[$option_name]}|";
475
      $option_list[$option_group_id][$option_name] = $user[$option_name];
476
    }
477
  }
478
479
  $user['options'] = $options;
480
  $user['option_list'] = $option_list;
481
482
  return $options;
483
}
484
485
function sys_user_options_unpack(&$user) {
486
  global $user_option_list;
487
488
  $option_list = array();
489
  $option_string_list = explode('|', $user['options']);
490
491
  foreach ($option_string_list as $option_string) {
492
    list($option_name, $option_value) = explode('^', $option_string);
493
    $option_list[$option_name] = $option_value;
494
  }
495
496
  $final_list = array();
497
  foreach ($user_option_list as $option_group_id => $option_group) {
498
    $final_list[$option_group_id] = array();
499
    foreach ($option_group as $option_name => $option_value) {
500
      if (!isset($option_list[$option_name])) {
501
        $option_list[$option_name] = $option_value;
502
      }
503
      $user[$option_name] = $final_list[$option_group_id][$option_name] = $option_list[$option_name];
504
    }
505
  }
506
507
  $user['option_list'] = $final_list;
508
509
  return $final_list;
510
}
511
512
function sys_unit_str2arr($fleet_string) {
513
  $fleet_array = array();
514
  if (!empty($fleet_string)) {
515
    $arrTemp = explode(';', $fleet_string);
516
    foreach ($arrTemp as $temp) {
517
      if ($temp) {
518
        $temp = explode(',', $temp);
519
        if (!empty($temp[0]) && !empty($temp[1])) {
520
          $fleet_array[$temp[0]] += $temp[1];
521
        }
522
      }
523
    }
524
  }
525
526
  return $fleet_array;
527
}
528
529
function sys_unit_arr2str($unit_list) {
530
  $fleet_string = array();
531
  if (isset($unit_list)) {
532
    if (!is_array($unit_list)) {
533
      $unit_list = array($unit_list => 1);
534
    }
535
536
    foreach ($unit_list as $unit_id => $unit_count) {
537
      if ($unit_id && $unit_count) {
538
        $fleet_string[] = "{$unit_id},{$unit_count}";
539
      }
540
    }
541
  }
542
543
  return implode(';', $fleet_string);
544
}
545
546
function mymail($email_unsafe, $title, $body, $from = '', $html = false) {
547
  $from = trim($from ? $from : classSupernova::$config->game_adminEmail);
548
549
  $head = '';
550
  $head .= "Content-Type: text/" . ($html ? 'html' : 'plain') . "; charset=utf-8 \r\n";
551
  $head .= "Date: " . date('r') . " \r\n";
552
  $classConfig = classSupernova::$config;
553
  $head .= "Return-Path: {$classConfig->game_adminEmail} \r\n";
554
  $head .= "From: {$from} \r\n";
555
  $head .= "Sender: {$from} \r\n";
556
  $head .= "Reply-To: {$from} \r\n";
557
  // $head .= "Organization: {$org} \r\n";
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
558
  $head .= "X-Sender: {$from} \r\n";
559
  $head .= "X-Priority: 3 \r\n";
560
  $body = str_replace("\r\n", "\n", $body);
561
  $body = str_replace("\n", "\r\n", $body);
562
563
  if ($html) {
564
    $body = '<html><head><base href="' . SN_ROOT_VIRTUAL . '"></head><body>' . nl2br($body) . '</body></html>';
565
  }
566
567
  $title = '=?UTF-8?B?' . base64_encode($title) . '?=';
568
569
  return @mail($email_unsafe, $title, $body, $head);
0 ignored issues
show
Security Header Injection introduced by
$email_unsafe can contain request data and is used in request header context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_POST
    in includes/general.php on line 253
  2. sys_get_param() returns tainted data
    in includes/general.php on line 285
  3. Data is passed through strip_tags(), and Data is passed through trim()
    in vendor/includes/general.php on line 1297
  4. sys_get_param_str_unsafe() returns tainted data, and auth_local::$input_email_unsafe is assigned
    in classes/auth_local.php on line 364
  5. Tainted property auth_local::$input_email_unsafe is read, and $email_unsafe is assigned
    in classes/auth_local.php on line 207
  6. $email_unsafe is passed to mymail()
    in classes/auth_local.php on line 240

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
570
}
571
572
function sys_time_human($time, $full = false) {
573
  $seconds = $time % 60;
574
  $time = floor($time / 60);
575
  $minutes = $time % 60;
576
  $time = floor($time / 60);
577
  $hours = $time % 24;
578
  $time = floor($time / 24);
579
580
  $classLocale = classLocale::$lang;
581
582
  return
583
    ($full || $time ? "{$time} {$classLocale['sys_day']}&nbsp;" : '') .
584
    ($full || $hours ? "{$hours} {$classLocale['sys_hrs']}&nbsp;" : '') .
585
    ($full || $minutes ? "{$minutes} {$classLocale['sys_min']}&nbsp;" : '') .
586
    ($full || !$time || $seconds ? "{$seconds} {$classLocale['sys_sec']}" : '');
587
}
588
589
function sys_time_human_system($time) {
590
  return $time ? date(FMT_DATE_TIME_SQL, $time) . " ({$time}), " . sys_time_human(SN_TIME_NOW - $time) : '{NEVER}';
591
}
592
593
function sys_redirect($url) {
594
  header("Location: {$url}");
595
  ob_end_flush();
596
  die();
597
}
598
599
// TODO Для полноценного функионирования апдейтера пакет функций, включая эту должен быть вынесен раньше - или грузить general.php до апдейтера
600
function sys_get_unit_location($user, $planet, $unit_id) { return sn_function_call(__FUNCTION__, array($user, $planet, $unit_id)); }
601
602
function sn_sys_get_unit_location($user, $planet, $unit_id) {
0 ignored issues
show
Unused Code introduced by
The parameter $user is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $planet is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
603
  return get_unit_param($unit_id, 'location');
604
}
605
606
function sn_ali_fill_user_ally(&$user) {
607
  if (!$user['ally_id']) {
608
    return;
609
  }
610
611
  if (!isset($user['ally'])) {
612
    $user['ally'] = DBStaticAlly::db_ally_get_by_id($user['ally_id']);
613
  }
614
615
  if (!isset($user['ally']['player'])) {
616
    $user['ally']['player'] = DBStaticUser::db_user_by_id($user['ally']['ally_user_id'], true, '*', false);
617
  }
618
}
619
620
function sn_get_url_contents($url) {
621
  if (function_exists('curl_init')) {
622
    $crl = curl_init();
623
    $timeout = 5;
624
    curl_setopt($crl, CURLOPT_URL, $url);
625
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
626
    curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
627
    $return = curl_exec($crl);
628
    curl_close($crl);
629
  } else {
630
    $return = @file_get_contents($url);
631
  }
632
633
  return $return;
634
}
635
636
function get_engine_data($user, $engine_info) {
637
  $sn_data_tech_bonus = get_unit_param($engine_info['tech'], 'bonus');
638
639
  $user_tech_level = intval(mrc_get_level($user, null, $engine_info['tech']));
640
641
  $engine_info['speed_base'] = $engine_info['speed'];
642
  $tech_bonus = ($user_tech_level - $engine_info['min_level']) * $sn_data_tech_bonus / 100;
643
  $tech_bonus = $tech_bonus < -0.9 ? -0.95 : $tech_bonus;
644
  $engine_info['speed'] = floor(mrc_modify_value($user, false, array(MRC_NAVIGATOR), $engine_info['speed']) * (1 + $tech_bonus));
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
645
646
  $engine_info['consumption_base'] = $engine_info['consumption'];
647
  $tech_bonus = ($user_tech_level - $engine_info['min_level']) * $sn_data_tech_bonus / 1000;
648
  $tech_bonus = $tech_bonus > 0.5 ? 0.5 : ($tech_bonus < 0 ? $tech_bonus * 2 : $tech_bonus);
649
  $engine_info['consumption'] = ceil($engine_info['consumption'] * (1 - $tech_bonus));
650
651
  return $engine_info;
652
}
653
654
function get_ship_data($ship_id, $user) {
655
  $ship_data = array();
656
  if (in_array($ship_id, classSupernova::$gc->groupFleetAndMissiles)) {
657
    $engines = get_unit_param($ship_id, 'engine');
658
    empty($engines) ? $engines = array() : false;
659
    foreach ($engines as $engine_info) {
660
      $tech_level = intval(mrc_get_level($user, null, $engine_info['tech']));
661
      if (empty($ship_data) || $tech_level >= $engine_info['min_level']) {
662
        $ship_data = $engine_info;
663
        $ship_data['tech_level'] = $tech_level;
664
      }
665
    }
666
    $ship_data = get_engine_data($user, $ship_data);
667
    $ship_data['capacity'] = get_unit_param($ship_id, 'capacity');
668
  }
669
670
  return $ship_data;
671
}
672
673
if (!function_exists('strptime')) {
674
  function strptime($date, $format) {
675
    $masks = array(
676
      '%d' => '(?P<d>[0-9]{2})',
677
      '%m' => '(?P<m>[0-9]{2})',
678
      '%Y' => '(?P<Y>[0-9]{4})',
679
      '%H' => '(?P<H>[0-9]{2})',
680
      '%M' => '(?P<M>[0-9]{2})',
681
      '%S' => '(?P<S>[0-9]{2})',
682
      // usw..
683
    );
684
685
    $rexep = "#" . strtr(preg_quote($format), $masks) . "#";
686
    if (preg_match($rexep, $date, $out)) {
687
      $ret = array(
688
        "tm_sec"  => (int)$out['S'],
689
        "tm_min"  => (int)$out['M'],
690
        "tm_hour" => (int)$out['H'],
691
        "tm_mday" => (int)$out['d'],
692
        "tm_mon"  => $out['m'] ? $out['m'] - 1 : 0,
693
        "tm_year" => $out['Y'] > 1900 ? $out['Y'] - 1900 : 0,
694
      );
695
    } else {
696
      $ret = false;
697
    }
698
699
    return $ret;
700
  }
701
}
702
703
function sn_sys_sector_buy($redirect = 'overview.php') {
704
  global $user, $planetrow;
705
706
  if (!sys_get_param_str('sector_buy') || $planetrow['planet_type'] != PT_PLANET) {
707
    return;
708
  }
709
710
  sn_db_transaction_start();
711
  $user = DBStaticUser::db_user_by_id($user['id'], true, '*');
712
  $planetrow = DBStaticPlanet::db_planet_by_id($planetrow['id'], true, '*');
713
  // Тут не надо делать обсчет - ресурсы мы уже посчитали, очередь (и количество зданий) - тоже
714
  $sector_cost = eco_get_build_data($user, $planetrow, UNIT_SECTOR, mrc_get_level($user, $planetrow, UNIT_SECTOR), true);
715
  $sector_cost = $sector_cost[BUILD_CREATE][RES_DARK_MATTER];
716
  if ($sector_cost <= mrc_get_level($user, null, RES_DARK_MATTER)) {
717
    $planet_name_text = uni_render_planet($planetrow);
718
    if (rpg_points_change($user['id'], RPG_SECTOR, -$sector_cost, sprintf(classLocale::$lang['sys_sector_purchase_log'],
719
        $user['username'], $user['id'], $planet_name_text, classLocale::$lang['sys_planet_type'][$planetrow['planet_type']], $planetrow['id'], $sector_cost)
720
    )) {
721
      $sector_db_name = pname_resource_name(UNIT_SECTOR);
722
      DBStaticPlanet::db_planet_update_adjust_by_id(
723
        $planetrow['id'],
724
        array(
725
          $sector_db_name => +1,
726
        )
727
      );
728
    } else {
729
      sn_db_transaction_rollback();
730
    }
731
  }
732
  sn_db_transaction_commit();
733
734
  sys_redirect($redirect);
735
}
736
737
/**
738
 * @param           $functions
739
 * @param           $handler_list
740
 * @param sn_module $class_module_name
741
 * @param string    $sub_type
742
 */
743
function sn_sys_handler_add(&$functions, $handler_list, $class_module_name = '', $sub_type = '') {
744
  if (isset($handler_list) && is_array($handler_list) && !empty($handler_list)) {
745
    foreach ($handler_list as $function_name => $function_data) {
746
      $override_with = '';
747
      if (is_string($function_data)) {
748
        $override_with = &$function_data;
749
      } elseif (isset($function_data['callable'])) {
750
        $override_with = &$function_data['callable'];
751
      }
752
753
      $overwrite = $override_with[0] == '*';
754
      if ($overwrite) {
755
        $override_with = substr($override_with, 1);
756
      }
757
758
      if (($point_position = strpos($override_with, '.')) === false && $class_module_name) {
759
        $override_with = array($class_module_name, $override_with);
760
      } elseif ($point_position == 0) {
761
        $override_with = substr($override_with, 1);
762
      } elseif ($point_position > 0) {
763
        $override_with = array(substr($override_with, 0, $point_position), substr($override_with, $point_position + 1));
764
      }
765
766
      if ($overwrite) {
767
        $functions[$function_name] = array();
768
        $function_data = array('callable' => $override_with);
769
      } elseif (!isset($functions[$function_name])) {
770
        $functions[$function_name] = array();
771
        $sn_function_name = 'sn_' . $function_name . ($sub_type ? '_' . $sub_type : '');
772
        $functions[$function_name][] = $sn_function_name;
773
      }
774
775
      $functions[$function_name][] = $function_data;
776
    }
777
  }
778
}
779
780
// TODO - поменять название
781
// Может принимать: (array)$user, $nick_render_array, $nick_render_array_html, $nick_render_string_compact
782
function player_nick_render_to_html($result, $options = false) {
783
  // TODO - обрабатывать разные случаи: $user, $render_nick_array, $string
784
785
  if (is_string($result) && strpos($result, ':{i:')) {
786
    $result = player_nick_uncompact($result);
787
  }
788
789
  if (is_array($result)) {
790
    if (isset($result['id'])) {
791
      $result = player_nick_render_current_to_array($result, $options);
792
    }
793
    if (!isset($result[NICK_HTML])) {
794
      $result = player_nick_render_array_to_html($result);
795
    }
796
    unset($result[NICK_HTML]);
797
    ksort($result);
798
    $result = implode('', $result);
799
  }
800
801
  return $result;
802
}
803
804
805
function player_nick_compact($nick_array) {
806
  ksort($nick_array);
807
808
  return serialize($nick_array);
809
}
810
811
function player_nick_uncompact($nick_string) {
812
  try {
813
    $result = unserialize($nick_string);
814
  } catch (Exception $e) {
815
    $result = strpos($nick_string, ':{i:') ? null : $nick_string; // fallback if it is already string - for old chat strings, for example
816
  }
817
818
  return $result;
819
}
820
821
function player_nick_render_array_to_html($nick_array) { return sn_function_call(__FUNCTION__, array($nick_array, &$result)); }
822
823
function sn_player_nick_render_array_to_html($nick_array, &$result) {
824
  global $user;
825
826
  // ALL STRING ARE UNSAFE!!!
827
  if (isset($nick_array[NICK_BIRTHSDAY])) {
828
    $result[NICK_BIRTHSDAY] = '<img src="design/images/birthday.png" />';
829
  }
830
831
  if (isset($nick_array[NICK_VACATION])) {
832
    $result[NICK_VACATION] = '<img src="design/images/icon_vacation.png" />';
833
  }
834
835
  if (isset($nick_array[NICK_GENDER])) {
836
    $result[NICK_GENDER] = '<img src="' . ($user['dpath'] ? $user['dpath'] : DEFAULT_SKINPATH) . 'images/gender_' . $nick_array[NICK_GENDER] . '.png" />';
837
  }
838
839
  if (isset($nick_array[NICK_AUTH_LEVEL]) || isset($nick_array[NICK_PREMIUM])) {
840
    switch($nick_array[NICK_AUTH_LEVEL]) {
841
      case 4:
842
        $highlight = classSupernova::$config->chat_highlight_developer;
843
      break;
844
845
      case 3:
846
        $highlight = classSupernova::$config->chat_highlight_admin;
847
      break;
848
849
      case 2:
850
        $highlight = classSupernova::$config->chat_highlight_operator;
851
      break;
852
853
      case 1:
854
        $highlight = classSupernova::$config->chat_highlight_moderator;
855
      break;
856
857
      default:
858
        $highlight = isset($nick_array[NICK_PREMIUM]) ? classSupernova::$config->chat_highlight_premium : '';
859
    }
860
861
    if ($highlight) {
862
      list($result[NICK_HIGHLIGHT], $result[NICK_HIGHLIGHT_END]) = explode('$1', $highlight);
863
    }
864
  }
865
866 View Code Duplication
  if (isset($nick_array[NICK_CLASS])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
867
    $result[NICK_CLASS] = '<span ' . $nick_array[NICK_CLASS] . '>';
868
    $result[NICK_CLASS_END] = '</span>';
869
  }
870
871
  $result[NICK_NICK] = sys_safe_output($nick_array[NICK_NICK]);
872
873 View Code Duplication
  if (isset($nick_array[NICK_ALLY])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
874
    $result[NICK_ALLY] = '[' . sys_safe_output($nick_array[NICK_ALLY]) . ']';
875
  }
876
877
  $result[NICK_HTML] = true;
878
879
  return $result;
880
}
881
882
function player_nick_render_current_to_array($render_user, $options = false) { return sn_function_call(__FUNCTION__, array($render_user, $options, &$result)); }
883
884
function sn_player_nick_render_current_to_array($render_user, $options = false, &$result) {
885
  if ($render_user['user_birthday'] && ($options === true || isset($options['icons']) || isset($options['birthday'])) && (date('Y', SN_TIME_NOW) . date('-m-d', strtotime($render_user['user_birthday'])) == date('Y-m-d', SN_TIME_NOW))) {
886
    $result[NICK_BIRTHSDAY] = '';
887
  }
888
889
  if ($options === true || (isset($options['icons']) && $options['icons']) || (isset($options['gender']) && $options['gender'])) {
890
    $result[NICK_GENDER] = $render_user['gender'] == GENDER_UNKNOWN ? 'unknown' : ($render_user['gender'] == GENDER_FEMALE ? 'female' : 'male');
891
  }
892
893
  if (($options === true || (isset($options['icons']) && $options['icons']) || (isset($options['vacancy']) && $options['vacancy'])) && $render_user['vacation']) {
894
    $result[NICK_VACATION] = $render_user['vacation'];
895
  }
896
897
  if ($options === true || (isset($options['color']) && $options['color'])) {
898
    if ($user_auth_level = $render_user['authlevel']) {
899
      $result[NICK_AUTH_LEVEL] = $user_auth_level;
900
    }
901
    if ($user_premium = mrc_get_level($render_user, null, UNIT_PREMIUM)) {
902
      $result[NICK_PREMIUM] = $user_premium;
903
    }
904
  }
905
906
  if ((isset($options['class']) && $options['class'])) {
907
    $result[NICK_CLASS] = (isset($result_options[NICK_CLASS]) ? ' ' . $result_options[NICK_CLASS] : '') . $options['class'];
0 ignored issues
show
Bug introduced by
The variable $result_options does not exist. Did you mean $options?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
908
  }
909
910
  if ($render_user['ally_tag'] && ($options === true || (isset($options['ally']) && $options['ally']))) {
911
    $result[NICK_ALLY] = $render_user['ally_tag'];
912
  }
913
914
  $result[NICK_NICK] = $render_user['username'];
915
916
  return $result;
917
}
918
919
920
// TODO sys_stat_get_user_skip_list() ПЕРЕДЕЛАТЬ!
921
function sys_stat_get_user_skip_list() {
922
  $result = array();
923
924
  $user_skip_list = array();
925
926
  if (classSupernova::$config->stats_hide_admins) {
927
    $user_skip_list[] = '`authlevel` > 0';
928
  }
929
930
  if (classSupernova::$config->stats_hide_player_list) {
931
    $temp = explode(',', classSupernova::$config->stats_hide_player_list);
932
    foreach ($temp as $user_id) {
933
      $user_id = floatval($user_id);
934
      if ($user_id) {
935
        $user_skip_list[] = '`id` = ' . $user_id;
936
      }
937
    }
938
  }
939
940
  if (!empty($user_skip_list)) {
941
    $user_skip_list = implode(' OR ', $user_skip_list);
942
    $user_skip_query = DBStaticUser::db_user_list($user_skip_list);
943
    if (!empty($user_skip_query)) {
944
      foreach ($user_skip_query as $user_skip_row) {
945
        $result[$user_skip_row['id']] = $user_skip_row['id'];
946
      }
947
    }
948
  }
949
950
  return $result;
951
}
952
953
/**
954
 * @param int|float|string $unit_id
955
 * @param null|string|int  $param_name
956
 * @param null|array       $user
957
 * @param null|array       $planet
958
 *
959
 * @return mixed
960
 */
961
function get_unit_param($unit_id, $param_name = null, $user = null, $planet = null) { return sn_function_call(__FUNCTION__, array($unit_id, $param_name, $user, $planet, &$result)); }
962
963
function sn_get_unit_param($unit_id, $param_name = null, $user = null, $planet = null, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $user is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $planet is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
964
  global $sn_data;
965
966
  $result = isset($sn_data[$unit_id])
967
    ? ($param_name === null
968
      ? $sn_data[$unit_id]
969
      : (isset($sn_data[$unit_id][$param_name]) ? $sn_data[$unit_id][$param_name] : $result)
970
    )
971
    : $result;
972
973
  return $result;
974
}
975
976
/**
977
 * @param $groups
978
 *
979
 * @return array
980
 */
981
function sn_get_groups($groups) { return sn_function_call(__FUNCTION__, array($groups, &$result)); }
982
983
/**
984
 * @param $groups
985
 * @param $result
986
 *
987
 * @return array
988
 */
989
function sn_sn_get_groups($groups, &$result) {
990
  $result = is_array($result) ? $result : array();
991
  foreach ($groups = is_array($groups) ? $groups : array($groups) as $group_name) {
992
    $result += is_array($a_group = get_unit_param(UNIT_GROUP, $group_name)) ? $a_group : array();
993
  }
994
995
  return $result;
996
}
997
998
function isInGroup($groups, $unitId) {
999
  $group = sn_get_groups($groups);
1000
1001
  return !empty($group[$unitId]);
1002
}
1003
1004
// Format $value to ID
1005
/**
1006
 * @param     $value
1007
 * @param int $default
1008
 *
1009
 * @return float|int
1010
 */
1011
function idval($value, $default = 0) {
1012
  $value = floatval($value);
1013
1014
  return preg_match('#^(\d*)#', $value, $matches) && $matches[1] ? floatval($matches[1]) : $default;
1015
}
1016
1017
function unit_requirements_render($user, $planetrow, $unit_id, $field = 'require') { return sn_function_call(__FUNCTION__, array($user, $planetrow, $unit_id, $field, &$result)); }
1018
1019
function sn_unit_requirements_render($user, $planetrow, $unit_id, $field = 'require', &$result) {
1020
  $sn_data_unit = get_unit_param($unit_id);
1021
1022
  $result = is_array($result) ? $result : array();
1023
  if ($sn_data_unit[$field] && !($sn_data_unit[P_UNIT_TYPE] == UNIT_MERCENARIES && classSupernova::$config->empire_mercenary_temporary)) {
1024
    foreach ($sn_data_unit[$field] as $require_id => $require_level) {
1025
      $level_got = mrc_get_level($user, $planetrow, $require_id);
1026
      $level_basic = mrc_get_level($user, $planetrow, $require_id, false, true);
1027
      $result[] = array(
1028
        'NAME'             => classLocale::$lang['tech'][$require_id],
1029
        //'CLASS' => $require_level > $level_got ? 'negative' : ($require_level == $level_got ? 'zero' : 'positive'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1030
        'REQUEREMENTS_MET' => intval($require_level <= $level_got ? REQUIRE_MET : REQUIRE_MET_NOT),
1031
        'LEVEL_REQUIRE'    => $require_level,
1032
        'LEVEL'            => $level_got,
1033
        'LEVEL_BASIC'      => $level_basic,
1034
        'LEVEL_BONUS'      => max(0, $level_got - $level_basic),
1035
        'ID'               => $require_id,
1036
      );
1037
    }
1038
  }
1039
1040
  return $result;
1041
}
1042
1043
function ally_get_ranks(&$ally) {
1044
  global $ally_rights;
1045
1046
  $ranks = array();
1047
1048
  if ($ally['ranklist']) {
1049
    $str_ranks = explode(';', $ally['ranklist']);
1050
    foreach ($str_ranks as $str_rank) {
1051
      if (!$str_rank) {
1052
        continue;
1053
      }
1054
1055
      $tmp = explode(',', $str_rank);
1056
      $rank_id = count($ranks);
1057
      foreach ($ally_rights as $key => $value) {
1058
        $ranks[$rank_id][$value] = $tmp[$key];
1059
      }
1060
    }
1061
  }
1062
1063
  return $ranks;
1064
}
1065
1066
function sys_player_new_adjust($user_id, $planet_id) { return sn_function_call(__FUNCTION__, array($user_id, $planet_id, &$result)); }
1067
1068
function sn_sys_player_new_adjust($user_id, $planet_id, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $user_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $planet_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1069
  return $result;
1070
}
1071
1072
function array_merge_recursive_numeric($array1, $array2) {
1073
  if (!empty($array2) && is_array($array2)) {
1074
    foreach ($array2 as $key => $value) {
1075
      $array1[$key] = !isset($array1[$key]) || !is_array($array1[$key]) ? $value : array_merge_recursive_numeric($array1[$key], $value);
1076
    }
1077
  }
1078
1079
  return $array1;
1080
}
1081
1082
function sn_sys_array_cumulative_sum(&$array) {
1083
  $accum = 0;
1084
  foreach ($array as &$value) {
1085
    $accum += $value;
1086
    $value = $accum;
1087
  }
1088
}
1089
1090
function planet_density_price_chart($planet_row) {
1091
  $sn_data_density = sn_get_groups('planet_density');
1092
  $density_price_chart = array();
1093
1094
  foreach ($sn_data_density as $density_id => $density_data) {
1095
    // Отсекаем записи с RARITY = 0 - служебные записи и супер-ядра
1096
    $density_data[UNIT_PLANET_DENSITY_RARITY] ? $density_price_chart[$density_id] = $density_data[UNIT_PLANET_DENSITY_RARITY] : false;
1097
  }
1098
  unset($density_price_chart[PLANET_DENSITY_NONE]);
1099
1100
  $total_rarity = array_sum($density_price_chart);
1101
1102
  foreach ($density_price_chart as &$density_data) {
1103
    $density_data = ceil($total_rarity / $density_data * $planet_row['field_max'] * PLANET_DENSITY_TO_DARK_MATTER_RATE);
1104
  }
1105
1106
  return $density_price_chart;
1107
}
1108
1109
function sn_sys_planet_core_transmute(&$user, &$planetrow) {
1110
  if (!sys_get_param_str('transmute')) {
1111
    return array();
1112
  }
1113
1114
  try {
1115 View Code Duplication
    if ($planetrow['planet_type'] != PT_PLANET) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1116
      throw new Exception(classLocale::$lang['ov_core_err_not_a_planet'], ERR_ERROR);
1117
    }
1118
1119
    if ($planetrow['density_index'] == ($new_density_index = sys_get_param_id('density_type'))) {
1120
      throw new Exception(classLocale::$lang['ov_core_err_same_density'], ERR_WARNING);
1121
    }
1122
1123
    sn_db_transaction_start();
1124
    $user = DBStaticUser::db_user_by_id($user['id'], true, '*');
1125
    $planetrow = DBStaticPlanet::db_planet_by_id($planetrow['id'], true, '*');
1126
1127
    $planet_density_index = $planetrow['density_index'];
1128
1129
    $density_price_chart = planet_density_price_chart($planetrow);
1130
    if (!isset($density_price_chart[$new_density_index])) {
1131
      // Hack attempt
1132
      throw new Exception(classLocale::$lang['ov_core_err_denisty_type_wrong'], ERR_ERROR);
1133
    }
1134
1135
    $user_dark_matter = mrc_get_level($user, null, RES_DARK_MATTER);
1136
    $transmute_cost = $density_price_chart[$new_density_index];
1137
    if ($user_dark_matter < $transmute_cost) {
1138
      throw new Exception(classLocale::$lang['ov_core_err_no_dark_matter'], ERR_ERROR);
1139
    }
1140
1141
    $sn_data_planet_density = sn_get_groups('planet_density');
1142
    $prev_density_index = PLANET_DENSITY_NONE;
1143
    foreach ($sn_data_planet_density as $key => $value) {
1144
      if ($key == $new_density_index) {
1145
        break;
1146
      }
1147
      $prev_density_index = $key;
1148
    }
1149
1150
    $new_density = round(($sn_data_planet_density[$new_density_index][UNIT_PLANET_DENSITY] + $sn_data_planet_density[$prev_density_index][UNIT_PLANET_DENSITY]) / 2);
1151
1152
    rpg_points_change($user['id'], RPG_PLANET_DENSITY_CHANGE, -$transmute_cost,
1153
      array(
0 ignored issues
show
Documentation introduced by
array('Planet %1$s ID %2...y_index], $new_density) is of type array<integer,?,{"0":"st...,"7":"?","8":"double"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1154
        'Planet %1$s ID %2$d at coordinates %3$s changed density type from %4$d "%5$s" to %6$d "%7$s". New density is %8$d kg/m3',
1155
        $planetrow['name'],
1156
        $planetrow['id'],
1157
        uni_render_coordinates($planetrow),
1158
        $planet_density_index,
1159
        classLocale::$lang['uni_planet_density_types'][$planet_density_index],
1160
        $new_density_index,
1161
        classLocale::$lang['uni_planet_density_types'][$new_density_index],
1162
        $new_density
1163
      )
1164
    );
1165
1166
    DBStaticPlanet::db_planet_update_set_by_id(
1167
      $planetrow['id'],
1168
      array(
1169
        'density'       => $new_density,
1170
        'density_index' => $new_density_index,
1171
      )
1172
    );
1173
1174
1175
    sn_db_transaction_commit();
1176
1177
    $planetrow['density'] = $new_density;
1178
    $planetrow['density_index'] = $new_density_index;
1179
    $result = array(
1180
      'STATUS'  => ERR_NONE,
1181
      'MESSAGE' => sprintf(classLocale::$lang['ov_core_err_none'], classLocale::$lang['uni_planet_density_types'][$planet_density_index], classLocale::$lang['uni_planet_density_types'][$new_density_index], $new_density),
1182
    );
1183
  } catch (Exception $e) {
1184
    sn_db_transaction_rollback();
1185
    $result = array(
1186
      'STATUS'  => $e->getCode(),
1187
      'MESSAGE' => $e->getMessage(),
1188
    );
1189
  }
1190
1191
  return $result;
1192
}
1193
1194
function sn_module_get_active_count($group = '*') {
1195
  $active_modules = 0;
1196
  if (isset(sn_module::$sn_module_list[$group]) && is_array(sn_module::$sn_module_list[$group])) {
1197
    foreach (sn_module::$sn_module_list[$group] as $payment_module) {
1198
      $active_modules += $payment_module->manifest['active'];
1199
    }
1200
  }
1201
1202
  return $active_modules;
1203
}
1204
1205
function get_resource_exchange() {
1206
  static $rates;
1207
1208
  if (!$rates) {
1209
    $rates = array(
1210
      RES_METAL       => 'rpg_exchange_metal',
1211
      RES_CRYSTAL     => 'rpg_exchange_crystal',
1212
      RES_DEUTERIUM   => 'rpg_exchange_deuterium',
1213
      RES_DARK_MATTER => 'rpg_exchange_darkMatter',
1214
    );
1215
1216
    foreach ($rates as &$rate) {
1217
      $rate = classSupernova::$config->$rate;
1218
    }
1219
  }
1220
1221
  return $rates;
1222
}
1223
1224
function get_unit_cost_in(&$cost, $in_resource = RES_METAL) {
0 ignored issues
show
Unused Code introduced by
The parameter $in_resource is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1225
  static $rates;
1226
1227
  if (!$rates) {
1228
    $rates = get_resource_exchange();
1229
  }
1230
1231
  $metal_cost = 0;
1232
  foreach ($cost as $resource_id => $resource_value) {
1233
    $metal_cost += $rates[$resource_id] * $resource_value;
1234
  }
1235
1236
  return $metal_cost;
1237
}
1238
1239
/**
1240
 * @param array $user
1241
 * @param int   $astrotech
1242
 *
1243
 * @return int
1244
 */
1245
function get_player_max_expeditons(&$user, $astrotech = -1) { return sn_function_call(__FUNCTION__, array(&$user, $astrotech, &$result)); }
1246
1247
/**
1248
 * @param     $user
1249
 * @param int $astrotech
1250
 * @param int $result
1251
 *
1252
 * @return float|int
1253
 */
1254
function sn_get_player_max_expeditons(&$user, $astrotech = -1, &$result = 0) {
1255
  if ($astrotech == -1) {
1256
    if (!isset($user[UNIT_PLAYER_EXPEDITIONS_MAX])) {
1257
      $astrotech = mrc_get_level($user, null, TECH_ASTROTECH);
1258
      $user[UNIT_PLAYER_EXPEDITIONS_MAX] = $astrotech >= 1 ? floor(sqrt($astrotech - 1)) : 0;
1259
    }
1260
1261
    return $result += $user[UNIT_PLAYER_EXPEDITIONS_MAX];
1262
  } else {
1263
    return $result += $astrotech >= 1 ? floor(sqrt($astrotech - 1)) : 0;
1264
  }
1265
}
1266
1267
function get_player_max_expedition_duration(&$user, $astrotech = -1) {
1268
  return $astrotech == -1 ? mrc_get_level($user, null, TECH_ASTROTECH) : $astrotech;
1269
}
1270
1271
function get_player_max_colonies(&$user, $astrotech = -1) {
1272
  if ($astrotech == -1) {
1273
    if (!isset($user[UNIT_PLAYER_COLONIES_MAX])) {
1274
1275
      $expeditions = get_player_max_expeditons($user);
1276
      $astrotech = mrc_get_level($user, null, TECH_ASTROTECH);
1277
      $colonies = $astrotech - $expeditions;
1278
1279
      $user[UNIT_PLAYER_COLONIES_MAX] = classSupernova::$config->player_max_colonies < 0 ? $colonies : min(classSupernova::$config->player_max_colonies, $colonies);
1280
    }
1281
1282
    return $user[UNIT_PLAYER_COLONIES_MAX];
1283 View Code Duplication
  } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1284
    $expeditions = get_player_max_expeditons($user, $astrotech);
1285
    // $astrotech = mrc_get_level($user, false, TECH_ASTROTECH);
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1286
    $colonies = $astrotech - $expeditions;
1287
1288
    return classSupernova::$config->player_max_colonies < 0 ? $colonies : min(classSupernova::$config->player_max_colonies, $colonies);
1289
  }
1290
}
1291
1292
function get_player_current_colonies(&$user) {
1293
  return $user[UNIT_PLAYER_COLONIES_CURRENT] = isset($user[UNIT_PLAYER_COLONIES_CURRENT]) ? $user[UNIT_PLAYER_COLONIES_CURRENT] : max(0, DBStaticPlanet::db_planet_count_by_type($user['id']) - 1);
1294
}
1295
1296
function str_raw2unsafe($raw) {
1297
  return trim(strip_tags($raw));
1298
}
1299
1300
function ip2longu($ip) {
1301
  return sprintf('%u', floatval(ip2long($ip)));
1302
}
1303
1304
1305
function sn_powerup_get_price_matrix($powerup_id, $powerup_unit = false, $level_max = null, $plain = false) { return sn_function_call(__FUNCTION__, array($powerup_id, $powerup_unit, $level_max, $plain, &$result)); }
1306
1307
function sn_sn_powerup_get_price_matrix($powerup_id, $powerup_unit = false, $level_max = null, $plain = false, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $plain is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1308
  global $sn_powerup_buy_discounts;
1309
1310
  $result = array();
1311
1312
  $powerup_data = get_unit_param($powerup_id);
1313
  $is_upgrade = !empty($powerup_unit) && $powerup_unit;
1314
1315
  $level_current = $term_original = $time_left = 0;
1316
  if ($is_upgrade) {
1317
    $time_finish = strtotime($powerup_unit['unit_time_finish']);
1318
    $time_left = max(0, $time_finish - SN_TIME_NOW);
1319
    if ($time_left > 0) {
1320
      $term_original = $time_finish - strtotime($powerup_unit['unit_time_start']);
1321
      $level_current = $powerup_unit['unit_level'];
1322
    }
1323
  }
1324
1325
  $level_max = $level_max > $powerup_data[P_MAX_STACK] ? $level_max : $powerup_data[P_MAX_STACK];
1326
  $original_cost = 0;
1327
  for ($i = 1; $i <= $level_max; $i++) {
1328
    $base_cost = eco_get_total_cost($powerup_id, $i);
1329
    $base_cost = $base_cost[BUILD_CREATE][RES_DARK_MATTER];
1330
    foreach ($sn_powerup_buy_discounts as $period => $discount) {
1331
      $upgrade_price = floor($base_cost * $discount * $period / PERIOD_MONTH);
1332
      $result[$i][$period] = $upgrade_price;
1333
      $original_cost = $is_upgrade && $i == $level_current && $period <= $term_original ? $upgrade_price : $original_cost;
1334
    }
1335
  }
1336
1337
  if ($is_upgrade && $time_left) {
1338
    $term_original = round($term_original / PERIOD_DAY);
1339
    $time_left = min(floor($time_left / PERIOD_DAY), $term_original);
1340
    $cost_left = $term_original > 0 ? ceil($time_left / $term_original * $original_cost) : 0;
1341
1342
    array_walk_recursive($result, function (&$value) use ($cost_left) {
1343
      $value -= $cost_left;
1344
    });
1345
  }
1346
1347
  return $result;
1348
}
1349
1350
/**
1351
 * @param template $template
1352
 * @param array    $note_row
1353
 */
1354
function note_assign(&$template, $note_row) {
1355
  global $note_priority_classes;
1356
1357
  $template->assign_block_vars('note', array(
1358
    'ID'                     => $note_row['id'],
1359
    'TIME'                   => $note_row['time'],
1360
    'TIME_TEXT'              => date(FMT_DATE_TIME, $note_row['time']),
1361
    'PRIORITY'               => $note_row['priority'],
1362
    'PRIORITY_CLASS'         => $note_priority_classes[$note_row['priority']],
1363
    'PRIORITY_TEXT'          => classLocale::$lang['sys_notes_priorities'][$note_row['priority']],
1364
    'TITLE'                  => htmlentities($note_row['title'], ENT_COMPAT, 'UTF-8'),
1365
    'GALAXY'                 => intval($note_row['galaxy']),
1366
    'SYSTEM'                 => intval($note_row['system']),
1367
    'PLANET'                 => intval($note_row['planet']),
1368
    'PLANET_TYPE'            => intval($note_row['planet_type']),
1369
    'PLANET_TYPE_TEXT'       => classLocale::$lang['sys_planet_type'][$note_row['planet_type']],
1370
    'PLANET_TYPE_TEXT_SHORT' => classLocale::$lang['sys_planet_type_sh'][$note_row['planet_type']],
1371
    'TEXT'                   => sys_bbcodeParse(htmlentities($note_row['text'], ENT_COMPAT, 'UTF-8')),
1372
    'TEXT_EDIT'              => htmlentities($note_row['text'], ENT_COMPAT, 'UTF-8'),
1373
    'STICKY'                 => intval($note_row['sticky']),
1374
  ));
1375
}
1376
1377
function sn_version_compare_extra($version) {
1378
  static $version_regexp = '#(\d+)([a-f])(\d+)(?:\.(\d+))*#';
1379
  preg_match($version_regexp, $version, $version);
1380
  unset($version[0]);
1381
  $version[2] = ord($version[2]) - ord('a');
1382
1383
  return implode('.', $version);
1384
}
1385
1386
function sn_version_compare($ver1, $ver2) {
1387
  return version_compare(sn_version_compare_extra($ver1), sn_version_compare_extra($ver2));
1388
}
1389
1390
function sn_setcookie($name, $value = null, $expire = null, $path = SN_ROOT_RELATIVE, $domain = null, $secure = null, $httponly = null) {
1391
  $_COOKIE[$name] = $value;
1392
1393
  return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
1394
}
1395
1396
function market_get_autoconvert_cost() {
1397
  return classSupernova::$config->rpg_cost_exchange ? classSupernova::$config->rpg_cost_exchange * 3 : 3000;
1398
}
1399
1400
function print_rr($var, $capture = false) {
1401
  $print = '<pre>' . htmlspecialchars(print_r($var, true)) . '</pre>';
1402
  if ($capture) {
1403
    return $print;
1404
  } else {
1405
    print($print);
1406
  }
1407
}
1408
1409
function can_capture_planet() { return sn_function_call(__FUNCTION__, array(&$result)); }
1410
1411
function sn_can_capture_planet(&$result) {
1412
  return $result = false;
1413
}
1414
1415
/**
1416
 * Возвращает информацию об IPv4 адресах пользователя
1417
 *
1418
 * НЕ ПОДДЕРЖИВАЕТ IPv6!
1419
 *
1420
 * @return array
1421
 */
1422
// OK v4
1423
function sec_player_ip() {
1424
  // TODO - IPv6 support
1425
  $ip = array(
1426
    'ip'          => $_SERVER["REMOTE_ADDR"],
1427
    'proxy_chain' => $_SERVER["HTTP_X_FORWARDED_FOR"]
1428
      ? $_SERVER["HTTP_X_FORWARDED_FOR"]
1429
      : ($_SERVER["HTTP_CLIENT_IP"]
1430
        ? $_SERVER["HTTP_CLIENT_IP"]
1431
        : '' // $_SERVER["REMOTE_ADDR"]
1432
      ),
1433
  );
1434
1435
  return array_map('db_escape', $ip);
1436
}
1437
1438
/**
1439
 * Converts unix timestamp to SQL DateTime
1440
 *
1441
 * @param int $value
1442
 *
1443
 * @return string|null
1444
 */
1445
function unixTimeStampToSqlString($value) {
1446
  $result = !empty($value) ? date(FMT_DATE_TIME_SQL, $value) : null;
1447
1448
  return $result ? $result : null;
1449
}
1450
1451
/**
1452
 * Converts SQL DateTime to unix timestamp
1453
 *
1454
 * @param $value
1455
 *
1456
 * @return int
1457
 */
1458
function sqlStringToUnixTimeStamp($value) {
1459
  $result = !empty($value) ? strtotime($value) : 0;
1460
1461
  return $result ? $result : 0;
1462
}
1463
1464
/**
1465
 * @param mixed $value
1466
 *
1467
 * @return mixed|null
1468
 */
1469
function nullIfEmpty($value) {
1470
  return !empty($value) ? $value : null;
1471
}
1472
1473
1474
/**
1475
 * @param $sort_option
1476
 * @param $sort_option_inverse
1477
 *
1478
 * @return mixed
1479
 */
1480
function sortUnitRenderedList(&$ListToSort, $sort_option, $sort_option_inverse) {
1481
  if ($sort_option || $sort_option_inverse != PLAYER_OPTION_SORT_ORDER_PLAIN) {
1482
    switch($sort_option) {
1483
      case PLAYER_OPTION_SORT_NAME:
1484
        $sort_option_field = 'NAME';
1485
      break;
1486
      case PLAYER_OPTION_SORT_SPEED:
1487
        $sort_option_field = 'SPEED';
1488
      break;
1489
      case PLAYER_OPTION_SORT_COUNT:
1490
        $sort_option_field = 'AMOUNT';
1491
      break;
1492
      case PLAYER_OPTION_SORT_ID:
1493
        $sort_option_field = 'ID';
1494
      break;
1495
      case PLAYER_OPTION_SORT_CREATE_TIME_LENGTH:
1496
        $sort_option_field = 'TIME_SECONDS';
1497
      break;
1498
      default:
1499
        $sort_option_field = '__INDEX';
1500
      break;
1501
    }
1502
    $sort_option_inverse_closure = $sort_option_inverse ? -1 : 1;
1503
    usort($ListToSort, function ($a, $b) use ($sort_option_field, $sort_option_inverse_closure) {
1504
      return $a[$sort_option_field] < $b[$sort_option_field] ? -1 * $sort_option_inverse_closure : (
1505
      $a[$sort_option_field] > $b[$sort_option_field] ? 1 * $sort_option_inverse_closure : 0
1506
      );
1507
    });
1508
  }
1509
1510
}
1511
1512
function checkReturnRef(&$ref1, &$ref2) {
1513
  if (isset($ref1['id'])) {
1514
    $ref1['id']++;
1515
    pdump($ref1['id']);
1516
    pdump($ref2['id']);
1517
    if ($ref2['id'] == $ref1['id']) {
1518
      pdump('ok');
1519
    } else {
1520
      pdie('failed');
1521
    }
1522
    $ref2['id']--;
1523
    if ($ref2['id'] == $ref1['id']) {
1524
      pdump('ok');
1525
    } else {
1526
      pdie('failed');
1527
    }
1528
  }
1529
1530
}
1531
1532
function setNull(&$item) {
1533
  $item = null;
1534
}
1535
1536
/**
1537
 * @param string $filename
1538
 * @param string $extension
1539
 *
1540
 * @return string
1541
 */
1542
function getMinifiedName($filename, $extension) {
1543
  // TODO - TURN ON!!!!
1544
//  // Checking for dedicated minified version in specialized folder
1545
//  if (file_exists(SN_ROOT_PHYSICAL . ($result = 'minified/' . $extension . '/' . $filename . '.min' . $extension))) {
1546
//  } // Fallback to shared minimized version in specialized folder
1547
//  elseif (file_exists(SN_ROOT_PHYSICAL . ($result = 'minified/' . $extension . '/' . basename($filename) . '.min' . $extension))) {
1548
//  } // Fallback to minified version in same folder
1549
//  else
1550
  if (file_exists(SN_ROOT_PHYSICAL . ($result = $filename . '.min' . $extension))) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
1551
  } // Fallback to full version in same folder
1552
  elseif (file_exists(SN_ROOT_PHYSICAL . ($result = $filename . $extension))) {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
1553
  } // Final stand - looks like it's deprecated full-name-with-extension thing?
1554
  elseif (!file_exists(SN_ROOT_PHYSICAL . ($result = $filename))) {
1555
    // Still not exists? Then no use!
1556
    $result = '';
1557
  }
1558
1559
  return $result;
1560
}
1561