Test Setup Failed
Push — trunk ( cd2d21...adae1b )
by SuperNova.WS
09:23
created

general.php ➔ getUniqueFleetId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
require_once('general/math.php');
12
require_once('general/compatibility.php');
13
require_once('general_pname.php');
14
15
function sn_function_call($func_name, $func_arg = array())
16
{
17
  global $functions; // All data in $functions should be normalized to valid 'callable' state: '<function_name>'|array('<object_name>', '<method_name>')
18
19
  if(is_array($functions[$func_name]) && !is_callable($functions[$func_name]))
20
  {
21
    // Chain-callable functions should be made as following:
22
    // 1. Never use incomplete calls with parameters "by default"
23
    // 2. Reserve last parameter for cumulative result
24
    // 3. Use same format for original value and cumulative result (if there is original value)
25
    // 4. Honor cumulative result
26
    // 5. Return cumulative result
27
    foreach($functions[$func_name] as $func_chain_name)
28
    {
29
      // По идее - это уже тут не нужно, потому что оно все должно быть callable к этому моменту
30
      // Но для старых модулей...
31
      if(is_callable($func_chain_name))
32
      {
33
        $result = call_user_func_array($func_chain_name, $func_arg);
34
      }
35
    }
36
  }
37
  else
38
  {
39
    // TODO: This is left for backward compatibility. Appropriate code should be rewrote!
40
    $func_name = isset($functions[$func_name]) && is_callable($functions[$func_name]) ? $functions[$func_name] : ('sn_' . $func_name);
41
    if(is_callable($func_name))
42
    {
43
      $result = call_user_func_array($func_name, $func_arg);
44
    }
45
  }
46
47
  return $result;
0 ignored issues
show
Bug introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
48
}
49
50
/**
51
 * @param        $hook_list
52
 * @param        $template
53
 * @param string $hook_type - тип хука 'model' или 'view'
0 ignored issues
show
Documentation introduced by
Should the type for parameter $hook_type not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
54
 * @param string $page_name - имя страницы, для которого должен был быть выполнен хук
0 ignored issues
show
Documentation introduced by
Should the type for parameter $page_name not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
55
 */
56
function execute_hooks(&$hook_list, &$template, $hook_type = null, $page_name = null) {
57
  if(!empty($hook_list)) {
58
    foreach($hook_list as $hook) {
59
      if(is_callable($hook_call = (is_string($hook) ? $hook : (is_array($hook) ? $hook['callable'] : $hook->callable)))) {
60
        $template = call_user_func($hook_call, $template, $hook_type, $page_name);
61
      }
62
    }
63
  }
64
}
65
66
// ----------------------------------------------------------------------------------------------------------------
67
// Fonction de lecture / ecriture / exploitation de templates
68
function sys_file_read($filename)
69
{
70
  return @file_get_contents($filename);
71
}
72
73
function sys_file_write($filename, $content)
74
{
75
  return @file_put_contents($filename, $content, FILE_APPEND);
76
}
77
78
function get_game_speed($plain = false){return sn_function_call('get_game_speed', array($plain, &$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
79
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...
80
  return $result = classSupernova::$config->game_speed ? classSupernova::$config->game_speed : 1;
0 ignored issues
show
Documentation introduced by
The property game_speed does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
81
}
82
83
function flt_server_flight_speed_multiplier($plain = false){return sn_function_call('flt_server_flight_speed_multiplier', array($plain, &$result));}
84
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...
85
  global $config;
86
87
  return $result = classSupernova::$config->fleet_speed;
0 ignored issues
show
Documentation introduced by
The property fleet_speed does not exist on object<classConfig>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
88
}
89
90
function game_resource_multiplier($plain = false){return sn_function_call('game_resource_multiplier', array($plain,&$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
91
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...
92
  global $config;
93
94
  return $result = classSupernova::$config->resource_multiplier;
0 ignored issues
show
Documentation introduced by
The property resource_multiplier does not exist on object<classConfig>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
95
}
96
97
/**
98
 * Получение стоимости ММ в валюте сервера
99
 *
100
 * @param bool|false $plain
101
 *
102
 * @return mixed
103
 */
104
function get_mm_cost($plain = false){return sn_function_call('get_mm_cost', array($plain, &$result));}
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
  global $config;
107
108
  return $result = classSupernova::$config->payment_currency_exchange_mm_ ? classSupernova::$config->payment_currency_exchange_mm_ : 20000;
0 ignored issues
show
Documentation introduced by
The property payment_currency_exchange_mm_ does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

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

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...
240
}
241
242
// ----------------------------------------------------------------------------------------------------------------
243
function GetSpyLevel(&$user) {
244
  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...
245
}
246
247
// ----------------------------------------------------------------------------------------------------------------
248
function GetMaxFleets(&$user) {
249
  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...
250
}
251
252
// ----------------------------------------------------------------------------------------------------------------
253
/*
254
function GetMaxExpeditions(&$user)
255
{
256
  return floor(sqrt(mrc_get_level($user, false, TECH_EXPEDITION)));
257
}
258
*/
259
260
// ----------------------------------------------------------------------------------------------------------------
261
// Check input string for forbidden words
262
//
263
function CheckInputStrings($String)
264
{
265
  global $ListCensure;
266
267
  return preg_replace($ListCensure, '*', $String);
268
}
269
270
function is_email($email) {
271
  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));
272
}
273
274
function is_id($value)
275
{
276
  return preg_match('/^\d+$/', $value) && ($value >= 0);
277
}
278
279
/**
280
 * @param        $param_name
281
 * @param string $default
282
 *
283
 * @return string|array
284
 */
285
function sys_get_param($param_name, $default = '')
286
{
287
  return $_POST[$param_name] !== NULL ? $_POST[$param_name] : ($_GET[$param_name] !== NULL ? $_GET[$param_name] : $default);
288
}
289
290
function sys_get_param_id($param_name, $default = 0)
291
{
292
  return is_id($value = sys_get_param($param_name, $default)) ? $value : $default;
293
}
294
295
function sys_get_param_int($param_name, $default = 0)
296
{
297
  $value = sys_get_param($param_name, $default);
298
  return $value === 'on' ? 1 : ($value === 'off' ? $default : intval($value));
299
}
300
301
function sys_get_param_float($param_name, $default = 0)
302
{
303
  return floatval(sys_get_param($param_name, $default));
304
}
305
306
function sys_get_param_escaped($param_name, $default = '')
307
{
308
  return db_escape(sys_get_param($param_name, $default));
309
}
310
/*
311
function sys_get_param_safe($param_name, $default = '')
312
{
313
  return db_escape(strip_tags(sys_get_param($param_name, $default)));
314
}
315
*/
316
function sys_get_param_date_sql($param_name, $default = '2000-01-01')
317
{
318
  $val = sys_get_param($param_name, $default);
319
  return preg_match(PREG_DATE_SQL_RELAXED, $val) ? $val : $default;
320
}
321
322
function sys_get_param_str_unsafe($param_name, $default = '')
323
{
324
  return str_raw2unsafe(sys_get_param($param_name, $default));
325
}
326
327
function sys_get_param_str($param_name, $default = '')
328
{
329
  return db_escape(sys_get_param_str_unsafe($param_name, $default));
330
}
331
332
function sys_get_param_str_both($param_name, $default = '')
333
{
334
  $param = sys_get_param($param_name, $default);
335
  $param_unsafe = str_raw2unsafe($param);
336
  return array(
337
    'raw' => $param,
338
    'unsafe' => $param_unsafe,
339
    'safe' => db_escape($param_unsafe),
340
  );
341
}
342
343
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...
344
{
345
  $phone_raw = sys_get_param_str_unsafe($param_name, $default = '');
346
  if($phone_raw)
347
  {
348
    $phone = $phone_raw[0] == '+' ? '+' : '';
349
    for($i = 0; $i < strlen($phone_raw); $i++)
350
    {
351
      $ord = ord($phone_raw[$i]);
352
      if($ord >= 48 && $ord <= 57)
353
      {
354
        $phone .= $phone_raw[$i];
355
      }
356
    }
357
    $phone = strlen($phone) < 11 ? '' : $phone;
358
  }
359
  else
360
  {
361
    $phone = '';
362
  }
363
364
  return array('raw' => $phone_raw, 'phone' => $phone);
365
}
366
367
function GetPhalanxRange($phalanx_level)
368
{
369
  return $phalanx_level > 1 ? pow($phalanx_level, 2) - 1 : 0;
370
}
371
372
/**
373
 * @param array $planet
374
 *
375
 * @return bool
376
 */
377
function CheckAbandonPlanetState(&$planet)
378
{
379
  if($planet['destruyed'] && $planet['destruyed'] <= SN_TIME_NOW)
380
  {
381
    DBStaticPlanet::db_planet_delete_by_id($planet['id']);
382
    return true;
383
  }
384
  return false;
385
}
386
387
function eco_get_total_cost($unit_id, $unit_level)
388
{
389
  global $config;
390
391
  static $rate, $sn_group_resources_all, $sn_group_resources_loot;
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $sn_group_resources_all exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
Comprehensibility Naming introduced by
The variable name $sn_group_resources_loot exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
392
  if(!$rate)
393
  {
394
    $sn_group_resources_all = sn_get_groups('resources_all');
395
    $sn_group_resources_loot = sn_get_groups('resources_loot');
396
397
    $rate[RES_METAL] = classSupernova::$config->rpg_exchange_metal;
0 ignored issues
show
Documentation introduced by
The property rpg_exchange_metal does not exist on object<classConfig>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
398
    $rate[RES_CRYSTAL] = classSupernova::$config->rpg_exchange_crystal / classSupernova::$config->rpg_exchange_metal;
0 ignored issues
show
Documentation introduced by
The property rpg_exchange_crystal does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
The property rpg_exchange_metal does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
399
    $rate[RES_DEUTERIUM] = classSupernova::$config->rpg_exchange_deuterium / classSupernova::$config->rpg_exchange_metal;
0 ignored issues
show
Documentation introduced by
The property rpg_exchange_deuterium does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
The property rpg_exchange_metal does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
400
  }
401
402
  $unit_cost_data = get_unit_param($unit_id, 'cost');
403
  if(!is_array($unit_cost_data))
404
  {
405
    return array('total' => 0);
406
  }
407
  $factor = isset($unit_cost_data['factor']) ? $unit_cost_data['factor'] : 1;
408
  $cost_array = array(BUILD_CREATE => array(), 'total' => 0);
409
  $unit_level = $unit_level > 0 ? $unit_level : 0;
410
  foreach($unit_cost_data as $resource_id => $resource_amount)
411
  {
412
    if(!in_array($resource_id, $sn_group_resources_all))
413
    {
414
      continue;
415
    }
416
//    $cost_array[BUILD_CREATE][$resource_id] = $resource_amount * ($factor == 1 ? $unit_level : ((pow($factor, $unit_level) - $factor) / ($factor - 1)));
417
    $cost_array[BUILD_CREATE][$resource_id] = round($resource_amount * ($factor == 1 ? $unit_level : ((1 - pow($factor, $unit_level)) / (1 - $factor))));
418
    if(in_array($resource_id, $sn_group_resources_loot))
419
    {
420
      $cost_array['total'] += $cost_array[BUILD_CREATE][$resource_id] * $rate[$resource_id];
421
    }
422
  }
423
424
  return $cost_array;
425
}
426
427
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...
428
429
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...
430
431
/*
432
  ЭТО ПРОСТОЙ ВРАППЕР ДЛЯ БД! Здесь НЕТ никаких проверок! ВСЕ проверки должны быть сделаны заранее!
433
  Враппер возвращает уровень для указанного UNIT_ID и заполняет поле в соответствующей записи
434
  TODO: Он может быть перекрыт для возвращения дополнительной информации о юните - например, о Капитане (пока не реализовано)
435
436
  $context
437
    'location' - где искать данный тип юнита: LOC_USER
438
    'user' - &$user
439
440
  $options
441
    'for_update' - блокировать запись до конца транзакции
442
*/
443
/*
444
function unit_get_level($unit_id, &$context = null, $options = null){return sn_function_call('unit_get_level', array($unit_id, &$context, $options, &$result));}
445
function sn_unit_get_level($unit_id, &$context = null, $options = null, &$result)
446
{
447
  $unit_db_name = pname_resource_name($unit_id);
448
  $for_update = $options['for_update'];
449
450
  $unit_level = 0;
451
  if($context['location'] == LOC_USER)
452
  {
453
    $user = &$context['user'];
454
    if(!$user['id'])
455
    {
456
      $user[$unit_id]['unit_level'] = $user[$unit_db_name];
457
    }
458
    elseif($for_update || !isset($user[$unit_id]))
459
    {
460
      $unit_level = db_unit_by_location($user['id'], $context['location'], $user['id'], $unit_id, $for_update);
461
      $unit_level['unit_time_start'] = strtotime($unit_level['unit_time_start']);
462
      $unit_level['unit_time_finish'] = strtotime($unit_level['unit_time_finish']);
463
      $user[$unit_id] = $unit_level;
464
    }
465
    $unit_level = intval($user[$unit_id]['unit_level']);
466
  }
467
  elseif($context['location'] == LOC_PLANET)
468
  {
469
    $planet = &$context['planet'];
470
    if(!$planet['id'])
471
    {
472
      $planet[$unit_id]['unit_level'] = $planet[$unit_db_name];
473
    }
474
    elseif($for_update || !isset($planet[$unit_id]))
475
    {
476
      $unit_level = db_unit_by_location(0, $context['location'], $planet['id'], $unit_id, $for_update);
477
      $unit_level['unit_time_start'] = strtotime($unit_level['unit_time_start']);
478
      $unit_level['unit_time_finish'] = strtotime($unit_level['unit_time_finish']);
479
      $planet[$unit_id] = $unit_level;
480
    }
481
    $unit_level = intval($planet[$unit_id]['unit_level']);
482
  }
483
484
  return $result = $unit_level;
485
}
486
*/
487
488
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));}
489
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...
490
  $mercenary_level = 0;
491
  $unit_db_name = pname_resource_name($unit_id);
492
493
  if(in_array($unit_id, sn_get_groups(array('plans', 'mercenaries', 'tech', 'artifacts')))) {
494
    $unit = classSupernova::db_get_unit_by_location($user['id'], LOC_USER, $user['id'], $unit_id);
495
    $mercenary_level = is_array($unit) && $unit['unit_level'] ? $unit['unit_level'] : 0;
496
  } elseif(in_array($unit_id, sn_get_groups(array('structures', 'fleet', 'defense')))) {
497
    $unit = classSupernova::db_get_unit_by_location(is_array($user) ? $user['id'] : $planet['id_owner'], LOC_PLANET, $planet['id'], $unit_id);
498
    $mercenary_level = is_array($unit) && $unit['unit_level'] ? $unit['unit_level'] : 0;
499
  } elseif(in_array($unit_id, sn_get_groups('governors'))) {
500
    $mercenary_level = $unit_id == $planet['PLANET_GOVERNOR_ID'] ? $planet['PLANET_GOVERNOR_LEVEL'] : 0;
501
  } elseif($unit_id == RES_DARK_MATTER) {
502
    $mercenary_level = $user[$unit_db_name] + ($plain || $user['user_as_ally'] ? 0 : classSupernova::$auth->account->account_metamatter);
503
  } elseif($unit_id == RES_METAMATTER) {
504
    $mercenary_level = classSupernova::$auth->account->account_metamatter; //$user[$unit_db_name];
505
  } elseif(in_array($unit_id, sn_get_groups(array('resources_loot'))) || $unit_id == UNIT_SECTOR) {
506
    $mercenary_level = !empty($planet) ? $planet[$unit_db_name] : $user[$unit_db_name];
507
  }
508
509
  return $result = $mercenary_level;
510
}
511
512
function mrc_modify_value(&$user, $planet = array(), $mercenaries, $value) {return sn_function_call('mrc_modify_value', array(&$user, $planet, $mercenaries, $value));}
513
function sn_mrc_modify_value(&$user, $planet = array(), $mercenaries, $value, $base_value = null)
514
{
515
  if(!is_array($mercenaries))
516
  {
517
    $mercenaries = array($mercenaries);
518
  }
519
520
  $base_value = isset($base_value) ? $base_value : $value;
521
522
  foreach($mercenaries as $mercenary_id)
523
  {
524
    $mercenary_level = mrc_get_level($user, $planet, $mercenary_id);
525
526
    $mercenary = get_unit_param($mercenary_id);
527
    $mercenary_bonus = $mercenary['bonus'];
528
529
    switch($mercenary['bonus_type'])
530
    {
531
      case BONUS_PERCENT_CUMULATIVE:
532
        $value *= 1 + $mercenary_level * $mercenary_bonus / 100;
533
      break;
534
535
      case BONUS_PERCENT:
536
        $mercenary_level = $mercenary_bonus < 0 && $mercenary_level * $mercenary_bonus < -90 ? -90 / $mercenary_bonus : $mercenary_level;
537
        $value += $base_value * $mercenary_level * $mercenary_bonus / 100;
538
      break;
539
540
      case BONUS_ADD:
541
        $value += $mercenary_level * $mercenary_bonus;
542
      break;
543
544
      case BONUS_ABILITY:
545
        $value = $mercenary_level ? $mercenary_level : 0;
546
      break;
547
548
      default:
549
      break;
550
    }
551
  }
552
553
  return $value;
554
}
555
556
// Generates random string of $length symbols from $allowed_chars charset
557
function sys_random_string($length = 16, $allowed_chars = SN_SYS_SEC_CHARS_ALLOWED) {
558
  $allowed_length = strlen($allowed_chars);
559
560
  $random_string = '';
561
  for($i = 0; $i < $length; $i++) {
562
    $random_string .= $allowed_chars[mt_rand(0, $allowed_length - 1)];
563
  }
564
565
  return $random_string;
566
}
567
568
function js_safe_string($string)
569
{
570
  return str_replace(array("\r", "\n"), array('\r', '\n'), addslashes($string));
571
}
572
573
function sys_safe_output($string)
574
{
575
  return str_replace(array("&", "\"", "<", ">", "'"), array("&amp;", "&quot;", "&lt;", "&gt;", "&apos;"), $string);
576
}
577
578
function sys_user_options_pack(&$user)
579
{
580
  global $user_option_list;
581
582
  $options = '';
583
  $option_list = array();
584
  foreach($user_option_list as $option_group_id => $option_group)
585
  {
586
    $option_list[$option_group_id] = array();
587
    foreach($option_group as $option_name => $option_value)
588
    {
589
      if (!isset($user[$option_name]))
590
      {
591
        $user[$option_name] = $option_value;
592
      } elseif ($user[$option_name] == '') {
593
        $user[$option_name] = 0;
594
      }
595
      $options .= "{$option_name}^{$user[$option_name]}|";
596
      $option_list[$option_group_id][$option_name] = $user[$option_name];
597
    }
598
  }
599
600
  $user['options'] = $options;
601
  $user['option_list'] = $option_list;
602
603
  return $options;
604
}
605
606
function sys_user_options_unpack(&$user)
607
{
608
  global $user_option_list;
609
610
  $option_list = array();
611
  $option_string_list = explode('|', $user['options']);
612
613
  foreach($option_string_list as $option_string)
614
  {
615
    list($option_name, $option_value) = explode('^', $option_string);
616
    $option_list[$option_name] = $option_value;
617
  }
618
619
  $final_list = array();
620
  foreach($user_option_list as $option_group_id => $option_group)
621
  {
622
    $final_list[$option_group_id] = array();
623
    foreach($option_group as $option_name => $option_value)
624
    {
625
      if(!isset($option_list[$option_name]))
626
      {
627
        $option_list[$option_name] = $option_value;
628
      }
629
      $user[$option_name] = $final_list[$option_group_id][$option_name] = $option_list[$option_name];
630
    }
631
  }
632
633
  $user['option_list'] = $final_list;
634
635
  return $final_list;
636
}
637
638
function sys_unit_str2arr($fleet_string)
639
{
640
  $fleet_array = array();
641
  if(!empty($fleet_string))
642
  {
643
    $arrTemp = explode(';', $fleet_string);
644
    foreach($arrTemp as $temp)
645
    {
646
      if($temp)
647
      {
648
        $temp = explode(',', $temp);
649
        if(!empty($temp[0]) && !empty($temp[1]))
650
        {
651
          $fleet_array[$temp[0]] += $temp[1];
652
        }
653
      }
654
    }
655
  }
656
657
  return $fleet_array;
658
}
659
660
function sys_unit_arr2str($unit_list)
661
{
662
  $fleet_string = array();
663
  if(isset($unit_list))
664
  {
665
    if(!is_array($unit_list))
666
    {
667
      $unit_list = array($unit_list => 1);
668
    }
669
670
    foreach($unit_list as $unit_id => $unit_count)
671
    {
672
      if($unit_id && $unit_count)
673
      {
674
        $fleet_string[] = "{$unit_id},{$unit_count}";
675
      }
676
    }
677
  }
678
679
  return implode(';', $fleet_string);
680
}
681
682
function mymail($email_unsafe, $title, $body, $from = '', $html = false) {
683
  global $config, $lang;
684
685
  $from = trim($from ? $from : classSupernova::$config->game_adminEmail);
0 ignored issues
show
Documentation introduced by
The property game_adminEmail does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
686
687
  $head  = '';
688
  $head .= "Content-Type: text/" . ($html ? 'html' : 'plain'). "; charset=utf-8 \r\n";
689
  $head .= "Date: " . date('r') . " \r\n";
690
  $head .= "Return-Path: {classSupernova::$config->game_adminEmail} \r\n";
691
  $head .= "From: {$from} \r\n";
692
  $head .= "Sender: {$from} \r\n";
693
  $head .= "Reply-To: {$from} \r\n";
694
  $head .= "Organization: {$org} \r\n";
0 ignored issues
show
Bug introduced by
The variable $org does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
695
  $head .= "X-Sender: {$from} \r\n";
696
  $head .= "X-Priority: 3 \r\n";
697
  $body = str_replace("\r\n", "\n", $body);
698
  $body = str_replace("\n", "\r\n", $body);
699
700
  if($html) {
701
    $body = '<html><head><base href="' . SN_ROOT_VIRTUAL . '"></head><body>' . nl2br($body) . '</body></html>';
702
  }
703
704
  $title = '=?UTF-8?B?' . base64_encode($title) . '?=';
705
706
  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 287
  2. sys_get_param() returns tainted data
    in includes/general.php on line 324
  3. Data is passed through strip_tags(), and Data is passed through trim()
    in vendor/includes/general.php on line 1539
  4. sys_get_param_str_unsafe() returns tainted data, and auth_local::$input_email_unsafe is assigned
    in classes/auth_local.php on line 374
  5. Tainted property auth_local::$input_email_unsafe is read, and $email_unsafe is assigned
    in classes/auth_local.php on line 211
  6. $email_unsafe is passed to mymail()
    in classes/auth_local.php on line 248

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...
707
}
708
709
function sys_time_human($time, $full = false)
710
{
711
  global $lang;
712
713
  $seconds = $time % 60;
714
  $time = floor($time/60);
715
  $minutes = $time % 60;
716
  $time = floor($time/60);
717
  $hours = $time % 24;
718
  $time = floor($time/24);
719
720
  return
721
    ($full || $time    ? "{$time} {$lang['sys_day']}&nbsp;" : '') .
722
    ($full || $hours   ? "{$hours} {$lang['sys_hrs']}&nbsp;" : '') .
723
    ($full || $minutes ? "{$minutes} {$lang['sys_min']}&nbsp;" : '') .
724
    ($full || !$time || $seconds ? "{$seconds} {$lang['sys_sec']}" : '');
725
}
726
727
function sys_time_human_system($time) {
728
  return $time ? date(FMT_DATE_TIME_SQL, $time) . " ({$time}), " . sys_time_human(SN_TIME_NOW - $time) : '{NEVER}';
729
}
730
731
function sys_redirect($url)
732
{
733
  header("Location: {$url}");
734
  ob_end_flush();
735
  die();
736
}
737
738
/**
739
 * Redirects via JS-script
740
 *
741
 * @param string $url
742
 */
743
function sys_redirect_js($url)
744
{
745
  ob_end_flush();
746
747
  $redirectTemplate = gettemplate('_redirect');
748
  $redirectTemplate->assign_vars(array(
749
    'URL' => js_safe_string($url),
750
  ));
751
752
  display($redirectTemplate);
753
  die();
754
}
755
756
/**
757
 * Wrapper for header() function
758
 *
759
 * @param string $header
760
 */
761
function setHeader($header) {
762
  header($header);
763
}
764
765
// TODO Для полноценного функионирования апдейтера пакет функций, включая эту должен быть вынесен раньше - или грузить general.php до апдейтера
766
function sys_get_unit_location($user, $planet, $unit_id){return sn_function_call('sys_get_unit_location', array($user, $planet, $unit_id));}
767
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...
768
{
769
  return get_unit_param($unit_id, 'location');
770
}
771
772
function sn_ali_fill_user_ally(&$user) {
773
  if(!$user['ally_id']) {
774
    return;
775
  }
776
777
  if(!isset($user['ally'])) {
778
    $user['ally'] = doquery("SELECT * FROM {{alliance}} WHERE `id` = {$user['ally_id']} LIMIT 1;", true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, 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...
779
  }
780
781
  if(!isset($user['ally']['player'])) {
782
    $user['ally']['player'] = db_user_by_id($user['ally']['ally_user_id'], true, '*', false);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated.

This function has been deprecated.

Loading history...
783
  }
784
}
785
786
function sn_get_url_contents($url)
787
{
788
  if(function_exists('curl_init'))
789
  {
790
    $crl = curl_init();
791
    $timeout = 5;
792
    curl_setopt ($crl, CURLOPT_URL,$url);
793
    curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
794
    curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
795
    $return = curl_exec($crl);
796
    curl_close($crl);
797
  }
798
  else
799
  {
800
    $return = @file_get_contents($url);
801
  }
802
803
  return $return;
804
}
805
806
function get_engine_data($user, $engine_info)
807
{
808
  $sn_data_tech_bonus = get_unit_param($engine_info['tech'], 'bonus');
809
810
  $user_tech_level = intval(mrc_get_level($user, false, $engine_info['tech']));
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...
811
812
  $engine_info['speed_base'] = $engine_info['speed'];
813
  $tech_bonus = ($user_tech_level - $engine_info['min_level']) * $sn_data_tech_bonus / 100;
814
  $tech_bonus = $tech_bonus < -0.9 ? -0.95 : $tech_bonus;
815
  $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...
816
817
  $engine_info['consumption_base'] = $engine_info['consumption'];
818
  $tech_bonus = ($user_tech_level - $engine_info['min_level']) * $sn_data_tech_bonus / 1000;
819
  $tech_bonus = $tech_bonus > 0.5 ? 0.5 : ($tech_bonus < 0 ? $tech_bonus * 2 : $tech_bonus);
820
  $engine_info['consumption'] = ceil($engine_info['consumption'] * (1 - $tech_bonus));
821
822
  return $engine_info;
823
}
824
825
function get_ship_data($ship_id, $user)
826
{
827
  $ship_data = array();
828
  if(in_array($ship_id, sn_get_groups(array('fleet', 'missile'))))
829
  {
830
    foreach(get_unit_param($ship_id, 'engine') as $engine_info)
831
    {
832
      $tech_level = intval(mrc_get_level($user, false, $engine_info['tech']));
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...
833
      if(empty($ship_data) || $tech_level >= $engine_info['min_level'])
834
      {
835
        $ship_data = $engine_info;
836
        $ship_data['tech_level'] = $tech_level;
837
      }
838
    }
839
    $ship_data = get_engine_data($user, $ship_data);
840
    $ship_data['capacity'] = get_unit_param($ship_id, 'capacity');
841
  }
842
843
  return $ship_data;
844
}
845
846
if(!function_exists('strptime'))
847
{
848
  function strptime($date, $format)
849
  {
850
    $masks = array(
851
      '%d' => '(?P<d>[0-9]{2})',
852
      '%m' => '(?P<m>[0-9]{2})',
853
      '%Y' => '(?P<Y>[0-9]{4})',
854
      '%H' => '(?P<H>[0-9]{2})',
855
      '%M' => '(?P<M>[0-9]{2})',
856
      '%S' => '(?P<S>[0-9]{2})',
857
     // usw..
858
    );
859
860
    $rexep = "#".strtr(preg_quote($format), $masks)."#";
861
    if(preg_match($rexep, $date, $out))
862
    {
863
      $ret = array(
864
        "tm_sec"  => (int) $out['S'],
865
        "tm_min"  => (int) $out['M'],
866
        "tm_hour" => (int) $out['H'],
867
        "tm_mday" => (int) $out['d'],
868
        "tm_mon"  => $out['m'] ? $out['m'] - 1 : 0,
869
        "tm_year" => $out['Y'] > 1900 ? $out['Y'] - 1900 : 0,
870
      );
871
    }
872
    else
873
    {
874
      $ret = false;
875
    }
876
    return $ret;
877
  }
878
}
879
880
function sn_sys_sector_buy($redirect = 'overview.php') {
881
  global $lang, $user, $planetrow;
882
883
  if(!sys_get_param_str('sector_buy') || $planetrow['planet_type'] != PT_PLANET) {
884
    return;
885
  }
886
887
  sn_db_transaction_start();
888
  $user = db_user_by_id($user['id'], true, '*');
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated.

This function has been deprecated.

Loading history...
889
  $planetrow = DBStaticPlanet::db_planet_by_id($planetrow['id'], true, '*');
890
  // Тут не надо делать обсчет - ресурсы мы уже посчитали, очередь (и количество зданий) - тоже
891
//  $planetrow = sys_o_get_updated($user, $planetrow, SN_TIME_NOW);
892
//  $user = $planetrow['user'];
893
//  $planetrow = $planetrow['planet'];
894
  $sector_cost = eco_get_build_data($user, $planetrow, UNIT_SECTOR, mrc_get_level($user, $planetrow, UNIT_SECTOR), true);
0 ignored issues
show
Bug introduced by
It seems like $planetrow defined by \DBStaticPlanet::db_plan...etrow['id'], true, '*') on line 889 can also be of type null; however, mrc_get_level() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
895
  $sector_cost = $sector_cost[BUILD_CREATE][RES_DARK_MATTER];
896
  if($sector_cost <= mrc_get_level($user, null, RES_DARK_MATTER)) {
0 ignored issues
show
Documentation introduced by
null is of type null, 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...
897
    $planet_name_text = uni_render_planet($planetrow);
898
    if(rpg_points_change($user['id'], RPG_SECTOR, -$sector_cost, sprintf($lang['sys_sector_purchase_log'],
0 ignored issues
show
Documentation introduced by
sprintf($lang['sys_secto...ow['id'], $sector_cost) is of type string, but the function expects a boolean.

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...
899
        $user['username'], $user['id'], $planet_name_text, $lang['sys_planet_type'][$planetrow['planet_type']], $planetrow['id'], $sector_cost)
900
    )) {
901
      $sector_db_name = pname_resource_name(UNIT_SECTOR);
902
      DBStaticPlanet::db_planet_set_by_id($planetrow['id'], "{$sector_db_name} = {$sector_db_name} + 1");
903
    } else {
904
      sn_db_transaction_rollback();
905
    }
906
  }
907
  sn_db_transaction_commit();
908
909
  sys_redirect($redirect);
910
}
911
912
function sn_sys_handler_add(&$functions, $handler_list, $class_module_name = '', $sub_type = '')
913
{
914
  if(isset($handler_list) && is_array($handler_list) && !empty($handler_list))
915
  {
916
    foreach($handler_list as $function_name => $function_data)
917
    {
918
      if(is_string($function_data))
919
      {
920
        $override_with = &$function_data;
921
      }
922
      elseif(isset($function_data['callable']))
923
      {
924
        $override_with = &$function_data['callable'];
925
      }
926
927
      $overwrite = $override_with[0] == '*';
0 ignored issues
show
Bug introduced by
The variable $override_with does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
928
      if($overwrite)
929
      {
930
        $override_with = substr($override_with, 1);
931
      }
932
933
      if(($point_position = strpos($override_with, '.')) === false && $class_module_name)
934
      {
935
        $override_with = array($class_module_name, $override_with);
936
      }
937
      elseif($point_position == 0)
938
      {
939
        $override_with = substr($override_with, 1);
940
      }
941
      elseif($point_position > 0)
942
      {
943
        $override_with = array(substr($override_with, 0, $point_position), substr($override_with, $point_position + 1));
944
      }
945
946
      if($overwrite)
947
      {
948
        $functions[$function_name] = array();
949
      }
950
      elseif(!isset($functions[$function_name]))
951
      {
952
        $functions[$function_name] = array();
953
        $sn_function_name = 'sn_' . $function_name . ($sub_type ? '_' . $sub_type : '');
954
        //if(is_callable($sn_function_name))
955
        {
956
          $functions[$function_name][] = $sn_function_name;
957
        }
958
      }
959
960
      $functions[$function_name][] = $function_data;
961
    }
962
  }
963
}
964
965
// TODO - поменять название
966
// Может принимать: (array)$user, $nick_render_array, $nick_render_array_html, $nick_render_string_compact
967
function player_nick_render_to_html($result, $options = false){
968
  // TODO - обрабатывать разные случаи: $user, $render_nick_array, $string
969
970
  if(is_string($result) && strpos($result, ':{i:')) {
971
    $result = player_nick_uncompact($result);
972
  }
973
974
  if(is_array($result)) {
975
    if(isset($result['id'])) {
976
      $result = player_nick_render_current_to_array($result, $options);
977
    }
978
    if(!isset($result[NICK_HTML])) {
979
      $result = player_nick_render_array_to_html($result);
980
    }
981
    unset($result[NICK_HTML]);
982
    // unset($result[NICK_ID]);
983
    ksort($result);
984
    $result = implode('', $result);
985
  }
986
987
  return $result;
988
}
989
990
991
function player_nick_compact($nick_array) {
992
  ksort($nick_array);
993
  return serialize($nick_array);
994
}
995
996
function player_nick_uncompact($nick_string) {
997
  try {
998
    $result = unserialize($nick_string);
999
    // ksort($result); // Всегда ksort-ый в player_nick_compact()
1000
  } catch(exception $e) {
1001
    $result = strpos($nick_string, ':{i:') ? null : $nick_string; // fallback if it is already string - for old chat strings, for example
1002
  }
1003
  return $result;
1004
}
1005
1006
function player_nick_render_array_to_html($nick_array){return sn_function_call('player_nick_render_array_to_html', array($nick_array, &$result));}
1007
function sn_player_nick_render_array_to_html($nick_array, &$result) {
1008
  global $config, $user;
1009
1010
  static $iconCache = array();
1011
1012
  if(empty($iconCache['gender_' . $nick_array[NICK_GENDER]])) {
1013
    $iconCache['gender_' . $nick_array[NICK_GENDER]] = classSupernova::$gc->skinModel->getImageCurrent("gender_{$nick_array[NICK_GENDER]}|html");
0 ignored issues
show
Documentation introduced by
The property skinModel does not exist on object<Common\GlobalContainer>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1014
    $iconCache['icon_vacation'] = classSupernova::$gc->skinModel->getImageCurrent('icon_vacation|html');
0 ignored issues
show
Documentation introduced by
The property skinModel does not exist on object<Common\GlobalContainer>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1015
    $iconCache['icon_birthday'] = classSupernova::$gc->skinModel->getImageCurrent('icon_birthday|html');
0 ignored issues
show
Documentation introduced by
The property skinModel does not exist on object<Common\GlobalContainer>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1016
  }
1017
  $iconGender = $iconCache['gender_' . $nick_array[NICK_GENDER]];
1018
1019
  // ALL STRING ARE UNSAFE!!!
1020
  if(isset($nick_array[NICK_BIRTHSDAY])) {
1021
//    $result[NICK_BIRTHSDAY] = '<img src="design/images/birthday.png" />';
1022
    $result[NICK_BIRTHSDAY] = $iconCache['icon_birthday'];
1023
  }
1024
1025
  if(isset($nick_array[NICK_VACATION])) {
1026
//    $result[NICK_VACATION] = '<img src="design/images/icon_vacation.png" />';
1027
//    $result[NICK_VACATION] = classSupernova::$gc->skinModel->getImageCurrent('icon_vacation|html');
1028
    $result[NICK_VACATION] = $iconCache['icon_vacation'];
1029
  }
1030
1031
  if(isset($nick_array[NICK_GENDER])) {
1032
//    $result[NICK_GENDER] = '<img src="' . classSupernova::$gc->theUser->getSkinPath() . 'images/gender_' . $nick_array[NICK_GENDER] . '.png" />';
1033
//    $result[NICK_GENDER] = classSupernova::$gc->skinModel->getImageCurrent("gender_{$nick_array[NICK_GENDER]}|html");
1034
    $result[NICK_GENDER] = $iconGender;
1035
  }
1036
1037
  if(isset($nick_array[NICK_AUTH_LEVEL]) || isset($nick_array[NICK_PREMIUM])) {
1038
    switch($nick_array[NICK_AUTH_LEVEL]) {
1039
      case 4:
1040
        $highlight = classSupernova::$config->chat_highlight_developer;
0 ignored issues
show
Documentation introduced by
The property chat_highlight_developer does not exist on object<classConfig>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1041
        break;
1042
1043
      case 3:
1044
        $highlight = classSupernova::$config->chat_highlight_admin;
0 ignored issues
show
Documentation introduced by
The property chat_highlight_admin does not exist on object<classConfig>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1045
        break;
1046
1047
      case 2:
1048
        $highlight = classSupernova::$config->chat_highlight_operator;
0 ignored issues
show
Documentation introduced by
The property chat_highlight_operator does not exist on object<classConfig>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1049
        break;
1050
1051
      case 1:
1052
        $highlight = classSupernova::$config->chat_highlight_moderator;
0 ignored issues
show
Documentation introduced by
The property chat_highlight_moderator does not exist on object<classConfig>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1053
        break;
1054
1055
      default:
1056
        $highlight = isset($nick_array[NICK_PREMIUM]) ? classSupernova::$config->chat_highlight_premium : '';
0 ignored issues
show
Documentation introduced by
The property chat_highlight_premium does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1057
    }
1058
1059
    if($highlight) {
1060
      list($result[NICK_HIGHLIGHT], $result[NICK_HIGHLIGHT_END]) = explode('$1', $highlight);
1061
    }
1062
    // $result = preg_replace("#(.+)#", $highlight, $result);
1063
  }
1064
1065 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...
1066
    $result[NICK_CLASS] = '<span ' . $nick_array[NICK_CLASS] .'>';
1067
    $result[NICK_CLASS_END] = '</span>';
1068
  }
1069
1070
  $result[NICK_NICK] = sys_safe_output($nick_array[NICK_NICK]);
1071
1072 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...
1073
    $result[NICK_ALLY] = '[' . sys_safe_output($nick_array[NICK_ALLY]) . ']';
1074
  }
1075
1076
  $result[NICK_HTML] = true;
1077
1078
  return $result;
1079
}
1080
1081
function player_nick_render_current_to_array($render_user, $options = false){return sn_function_call('player_nick_render_current_to_array', array($render_user, $options, &$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1082
function sn_player_nick_render_current_to_array($render_user, $options = false, &$result) {
1083
  /*
1084
  $options = $options !== true ? $options :
1085
    array(
1086
      'color' => true,
1087
      'icons' => true,
1088
      'gender' => true,
1089
      'birthday' => true,
1090
      'ally' => true,
1091
    );
1092
  */
1093
1094
1095
  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))) {
1096
    $result[NICK_BIRTHSDAY] = '';
1097
  }
1098
1099
  if($options === true || (isset($options['icons']) && $options['icons']) || (isset($options['gender']) && $options['gender'])) {
1100
    $result[NICK_GENDER] = $render_user['gender'] == GENDER_UNKNOWN ? 'unknown' : ($render_user['gender'] == GENDER_FEMALE ? 'female' : 'male');
1101
  }
1102
1103
  if(($options === true || (isset($options['icons']) && $options['icons']) || (isset($options['vacancy']) && $options['vacancy'])) && $render_user['vacation']) {
1104
    $result[NICK_VACATION] = $render_user['vacation'];
1105
  }
1106
1107
  if($options === true || (isset($options['color']) && $options['color'])) {
1108
    if($user_auth_level = $render_user['authlevel']) {
1109
      $result[NICK_AUTH_LEVEL] = $user_auth_level;
1110
    }
1111
    if($user_premium = mrc_get_level($render_user, false, UNIT_PREMIUM)) {
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...
1112
      $result[NICK_PREMIUM] = $user_premium;
1113
    }
1114
  }
1115
1116
  if((isset($options['class']) && $options['class'])) {
1117
    $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...
1118
  }
1119
1120
  if($render_user['ally_tag'] && ($options === true || (isset($options['ally']) && $options['ally']))) {
1121
    $result[NICK_ALLY] = $render_user['ally_tag'];
1122
  }
1123
1124
  $result[NICK_NICK] = $render_user['username'];
1125
1126
  return $result;
1127
}
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
// TODO sys_stat_get_user_skip_list() ПЕРЕДЕЛАТЬ!
1164
function sys_stat_get_user_skip_list() {
1165
  global $config;
1166
1167
  $result = array();
1168
1169
  $user_skip_list = array();
1170
1171
  if(classSupernova::$config->stats_hide_admins) {
0 ignored issues
show
Documentation introduced by
The property stats_hide_admins does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1172
    $user_skip_list[] = '`authlevel` > 0';
1173
  }
1174
1175
  if(classSupernova::$config->stats_hide_player_list) {
0 ignored issues
show
Documentation introduced by
The property stats_hide_player_list does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1176
    $temp = explode(',', classSupernova::$config->stats_hide_player_list);
0 ignored issues
show
Documentation introduced by
The property stats_hide_player_list does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1177
    foreach($temp as $user_id) {
1178
      $user_id = floatval($user_id);
1179
      if($user_id) {
1180
        $user_skip_list[] = '`id` = ' . $user_id;
1181
      }
1182
    }
1183
  }
1184
1185
  if(!empty($user_skip_list)) {
1186
    $user_skip_list = implode(' OR ', $user_skip_list);
1187
    $user_skip_query = db_user_list($user_skip_list);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_list() has been deprecated.

This function has been deprecated.

Loading history...
1188
    if(!empty($user_skip_query)) {
1189
      foreach($user_skip_query as $user_skip_row) {
1190
        $result[$user_skip_row['id']] = $user_skip_row['id'];
1191
      }
1192
    }
1193
  }
1194
1195
  return $result;
1196
}
1197
1198
// function player_nick_render_to_html($render_user, $options = false){return sn_function_call('player_nick_render_to_html', array($render_user, $options, &$result));}
1199
// function sn_render_player_nick($render_user, $options = false, &$result)
1200
1201
function get_unit_param($unit_id, $param_name = null, $user = null, $planet = null){return sn_function_call('get_unit_param', array($unit_id, $param_name, $user, $planet, &$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1202
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...
1203
{
1204
  global $sn_data;
1205
1206
  $result = isset($sn_data[$unit_id])
1207
    ? ($param_name === null
1208
      ? $sn_data[$unit_id]
1209
      : (isset($sn_data[$unit_id][$param_name]) ? $sn_data[$unit_id][$param_name] : $result)
1210
    )
1211
    : $result;
1212
1213
  return $result;
1214
}
1215
1216
function sn_get_groups($groups){return sn_function_call('sn_get_groups', array($groups, &$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1217
function sn_sn_get_groups($groups, &$result)
1218
{
1219
  $result = is_array($result) ? $result : array();
1220
  foreach($groups = is_array($groups) ? $groups : array($groups) as $group_name)
1221
  {
1222
    $result += is_array($a_group = get_unit_param(UNIT_GROUP, $group_name)) ? $a_group : array();
1223
  }
1224
1225
  return $result;
1226
}
1227
1228
// Format $value to ID
1229
/**
1230
 * @param     $value
1231
 * @param int $default
1232
 *
1233
 * @return float|int
1234
 */
1235
function idval($value, $default = 0)
1236
{
1237
  $value = floatval($value);
1238
  return preg_match('#^(\d*)#', $value, $matches) && $matches[1] ? floatval($matches[1]) : $default;
1239
}
1240
1241
function unit_requirements_render($user, $planetrow, $unit_id, $field = 'require'){return sn_function_call('unit_requirements_render', array($user, $planetrow, $unit_id, $field, &$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1242
function sn_unit_requirements_render($user, $planetrow, $unit_id, $field = 'require', &$result)
1243
{
1244
  global $lang, $config;
1245
1246
  $sn_data_unit = get_unit_param($unit_id);
1247
1248
  $result = is_array($result) ? $result : array();
1249
  if($sn_data_unit[$field] && !($sn_data_unit[P_UNIT_TYPE] == UNIT_MERCENARIES && classSupernova::$config->empire_mercenary_temporary))
0 ignored issues
show
Documentation introduced by
The property empire_mercenary_temporary does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1250
  {
1251
    foreach($sn_data_unit[$field] as $require_id => $require_level)
1252
    {
1253
      $level_got = mrc_get_level($user, $planetrow, $require_id);
1254
      $level_basic = mrc_get_level($user, $planetrow, $require_id, false, true);
1255
      $result[] = array(
1256
        'NAME' => $lang['tech'][$require_id],
1257
        //'CLASS' => $require_level > $level_got ? 'negative' : ($require_level == $level_got ? 'zero' : 'positive'),
1258
        'REQUEREMENTS_MET' => intval($require_level <= $level_got ? REQUIRE_MET : REQUIRE_MET_NOT),
1259
        'LEVEL_REQUIRE' => $require_level,
1260
        'LEVEL' => $level_got,
1261
        'LEVEL_BASIC' => $level_basic,
1262
        'LEVEL_BONUS' => max(0, $level_got - $level_basic),
1263
        'ID' => $require_id,
1264
      );
1265
    }
1266
  }
1267
1268
  return $result;
1269
}
1270
1271
function ally_get_ranks(&$ally)
1272
{
1273
  global $ally_rights;
1274
1275
  $ranks = array();
1276
1277
  if($ally['ranklist'])
1278
  {
1279
    $str_ranks = explode(';', $ally['ranklist']);
1280
    foreach($str_ranks as $str_rank)
1281
    {
1282
      if(!$str_rank)
1283
      {
1284
        continue;
1285
      }
1286
1287
      $tmp = explode(',', $str_rank);
1288
      $rank_id = count($ranks);
1289
      foreach($ally_rights as $key => $value)
1290
      {
1291
        $ranks[$rank_id][$value] = $tmp[$key];
1292
      }
1293
    }
1294
  }
1295
1296
  return $ranks;
1297
}
1298
1299
function sys_player_new_adjust($user_id, $planet_id){return sn_function_call('sys_player_new_adjust', array($user_id, $planet_id, &$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1300
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...
1301
  return $result;
1302
}
1303
1304
function array_merge_recursive_numeric($array1, $array2) {
1305
  if(!empty($array2) && is_array($array2)) {
1306
    foreach($array2 as $key => $value) {
1307
//    if(!isset($array1[$key]) || !is_array($array1[$key])) {
1308
//      $array1[$key] = $value;
1309
//    } else {
1310
//      $array1[$key] = array_merge_recursive_numeric($array1[$key], $value);
1311
//    }
1312
      $array1[$key] = !isset($array1[$key]) || !is_array($array1[$key]) ? $value : array_merge_recursive_numeric($array1[$key], $value);
1313
    }
1314
  }
1315
1316
  return $array1;
1317
}
1318
1319
function sn_sys_array_cumulative_sum(&$array)
1320
{
1321
  $accum = 0;
1322
  foreach($array as &$value)
1323
  {
1324
    $accum += $value;
1325
    $value = $accum;
1326
  }
1327
}
1328
1329
function planet_density_price_chart($planet_row) {
1330
  $sn_data_density = sn_get_groups('planet_density');
1331
  $density_price_chart = array();
1332
1333
  foreach($sn_data_density as $density_id => $density_data) {
1334
    // Отсекаем записи с RARITY = 0 - служебные записи и супер-ядра
1335
    $density_data[UNIT_PLANET_DENSITY_RARITY] ? $density_price_chart[$density_id] = $density_data[UNIT_PLANET_DENSITY_RARITY] : false;
1336
  }
1337
  unset($density_price_chart[PLANET_DENSITY_NONE]);
1338
1339
  $total_rarity = array_sum($density_price_chart);
1340
1341
  foreach($density_price_chart as &$density_data) {
1342
    $density_data = ceil($total_rarity / $density_data * $planet_row['field_max'] * PLANET_DENSITY_TO_DARK_MATTER_RATE);
1343
  }
1344
1345
  return $density_price_chart;
1346
}
1347
1348
function sn_sys_planet_core_transmute(&$user, &$planetrow) {
1349
  if(!sys_get_param_str('transmute')) {
1350
    return array();
1351
  }
1352
1353
  global $lang;
1354
1355
  try {
1356
    if($planetrow['planet_type'] != PT_PLANET) {
1357
      throw new exception($lang['ov_core_err_not_a_planet'], ERR_ERROR);
1358
    }
1359
1360
    if($planetrow['density_index'] == ($new_density_index = sys_get_param_id('density_type'))) {
1361
      throw new exception($lang['ov_core_err_same_density'], ERR_WARNING);
1362
    }
1363
1364
    sn_db_transaction_start();
1365
    $user = db_user_by_id($user['id'], true, '*');
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated.

This function has been deprecated.

Loading history...
1366
    $planetrow = DBStaticPlanet::db_planet_by_id($planetrow['id'], true, '*');
1367
//    $global_data = sys_o_get_updated($user, $planetrow['id'], SN_TIME_NOW);
1368
//    $user = $global_data['user'];
1369
//    $planetrow = $global_data['planet'];
1370
1371
    $planet_density_index = $planetrow['density_index'];
1372
1373
    $density_price_chart = planet_density_price_chart($planetrow);
1374
    if(!isset($density_price_chart[$new_density_index])) {
1375
      // Hack attempt
1376
      throw new exception($lang['ov_core_err_denisty_type_wrong'], ERR_ERROR);
1377
    }
1378
1379
    $user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
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...
1380
    // $transmute_cost = get_unit_param(UNIT_PLANET_DENSITY, 'cost');
1381
    // $transmute_cost = $transmute_cost[RES_DARK_MATTER] * $density_price_chart[$new_density_index];
1382
    $transmute_cost = $density_price_chart[$new_density_index];
1383
    if($user_dark_matter < $transmute_cost) {
1384
      throw new exception($lang['ov_core_err_no_dark_matter'], ERR_ERROR);
1385
    }
1386
1387
    $sn_data_planet_density = sn_get_groups('planet_density');
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $sn_data_planet_density exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
1388
    foreach($sn_data_planet_density as $key => $value) {
1389
      if($key == $new_density_index) {
1390
        break;
1391
      }
1392
      $prev_density_index = $key;
1393
    }
1394
1395
    $new_density = round(($sn_data_planet_density[$new_density_index][UNIT_PLANET_DENSITY] + $sn_data_planet_density[$prev_density_index][UNIT_PLANET_DENSITY]) / 2);
0 ignored issues
show
Bug introduced by
The variable $prev_density_index does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1396
1397
    rpg_points_change($user['id'], RPG_PLANET_DENSITY_CHANGE, -$transmute_cost,
1398
      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 boolean.

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...
1399
        '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',
1400
        $planetrow['name'],
1401
        $planetrow['id'],
1402
        uni_render_coordinates($planetrow),
1403
        $planet_density_index,
1404
        $lang['uni_planet_density_types'][$planet_density_index],
1405
        $new_density_index,
1406
        $lang['uni_planet_density_types'][$new_density_index],
1407
        $new_density
1408
      )
1409
    );
1410
1411
    DBStaticPlanet::db_planet_set_by_id($planetrow['id'], "`density` = {$new_density}, `density_index` = {$new_density_index}");
1412
    sn_db_transaction_commit();
1413
1414
    $planetrow['density'] = $new_density;
1415
    $planetrow['density_index'] = $new_density_index;
1416
    $result = array(
1417
      'STATUS'  => ERR_NONE,
1418
      'MESSAGE' => sprintf($lang['ov_core_err_none'], $lang['uni_planet_density_types'][$planet_density_index], $lang['uni_planet_density_types'][$new_density_index], $new_density),
1419
    );
1420
  } catch(exception $e) {
1421
    sn_db_transaction_rollback();
1422
    $result = array(
1423
      'STATUS'  => $e->getCode(),
1424
      'MESSAGE' => $e->getMessage(),
1425
    );
1426
  }
1427
1428
  return $result;
1429
}
1430
1431
function sn_module_get_active_count($group = '*')
1432
{
1433
  global $sn_module_list;
1434
1435
  $active_modules = 0;
1436
  if(isset($sn_module_list[$group]) && is_array($sn_module_list[$group]))
1437
  {
1438
    foreach($sn_module_list[$group] as $payment_module)
1439
    {
1440
      $active_modules += $payment_module->manifest['active'];
1441
    }
1442
  }
1443
1444
  return $active_modules;
1445
}
1446
1447
function get_resource_exchange()
1448
{
1449
  static $rates;
1450
1451
  if(!$rates)
1452
  {
1453
    global $config;
1454
1455
    $rates = array(
1456
      RES_METAL => 'rpg_exchange_metal',
1457
      RES_CRYSTAL => 'rpg_exchange_crystal',
1458
      RES_DEUTERIUM => 'rpg_exchange_deuterium',
1459
      RES_DARK_MATTER => 'rpg_exchange_darkMatter',
1460
    );
1461
1462
    foreach($rates as &$rate)
1463
    {
1464
      $rate = classSupernova::$config->$rate;
1465
    }
1466
  }
1467
1468
  return $rates;
1469
}
1470
1471
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...
1472
{
1473
  static $rates;
1474
1475
  if(!$rates)
1476
  {
1477
    $rates = get_resource_exchange();
1478
  }
1479
1480
  $metal_cost = 0;
1481
  foreach($cost as $resource_id => $resource_value)
1482
  {
1483
    $metal_cost += $rates[$resource_id] * $resource_value;
1484
  }
1485
1486
  return $metal_cost;
1487
}
1488
1489
function get_player_max_expeditons(&$user, $astrotech = -1){return sn_function_call('get_player_max_expeditons', array(&$user, $astrotech, &$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1490
function sn_get_player_max_expeditons(&$user, $astrotech = -1, &$result = 0)
1491
{
1492
  if($astrotech == -1) {
1493
    if(!isset($user[UNIT_PLAYER_EXPEDITIONS_MAX]))
1494
    {
1495
      $astrotech = mrc_get_level($user, false, TECH_ASTROTECH);
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...
1496
      $user[UNIT_PLAYER_EXPEDITIONS_MAX] = $astrotech >= 1 ? floor(sqrt($astrotech - 1)) : 0;
1497
    }
1498
1499
    return $result += $user[UNIT_PLAYER_EXPEDITIONS_MAX];
1500
  } else {
1501
    return $result += $astrotech >= 1 ? floor(sqrt($astrotech - 1)) : 0;
1502
  }
1503
}
1504
1505
function get_player_max_expedition_duration(&$user, $astrotech = -1)
1506
{
1507
  return $astrotech == -1 ? mrc_get_level($user, false, TECH_ASTROTECH) : $astrotech;
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...
1508
}
1509
1510
function get_player_max_colonies(&$user, $astrotech = -1) {
1511
  global $config;
1512
1513
  if($astrotech == -1) {
1514
    if(!isset($user[UNIT_PLAYER_COLONIES_MAX])) {
1515
1516
      $expeditions = get_player_max_expeditons($user);
1517
      $astrotech = mrc_get_level($user, false, TECH_ASTROTECH);
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...
1518
      $colonies = $astrotech - $expeditions;
1519
1520
      $user[UNIT_PLAYER_COLONIES_MAX] = classSupernova::$config->player_max_colonies < 0 ? $colonies : min(classSupernova::$config->player_max_colonies, $colonies);
0 ignored issues
show
Documentation introduced by
The property player_max_colonies does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1521
    }
1522
1523
    return $user[UNIT_PLAYER_COLONIES_MAX];
1524
  } else {
1525
    $expeditions = get_player_max_expeditons($user, $astrotech);
1526
    // $astrotech = mrc_get_level($user, false, TECH_ASTROTECH);
1527
    $colonies = $astrotech - $expeditions;
1528
1529
    return classSupernova::$config->player_max_colonies < 0 ? $colonies : min(classSupernova::$config->player_max_colonies, $colonies);
0 ignored issues
show
Documentation introduced by
The property player_max_colonies does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1530
  }
1531
}
1532
1533
function get_player_current_colonies(&$user)
1534
{
1535
  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);
1536
}
1537
1538
function str_raw2unsafe($raw) {
1539
  return trim(strip_tags($raw));
1540
}
1541
1542
function ip2longu($ip) {
1543
  return sprintf('%u', floatval(ip2long($ip)));
1544
}
1545
1546
1547
function sn_powerup_get_price_matrix($powerup_id, $powerup_unit = false, $level_max = null, $plain = false){return sn_function_call('sn_powerup_get_price_matrix', array($powerup_id, $powerup_unit, $level_max, $plain, &$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1548
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...
1549
  global $sn_powerup_buy_discounts;
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $sn_powerup_buy_discounts exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
1550
1551
  $result = array();
1552
1553
  $powerup_data = get_unit_param($powerup_id);
1554
  $is_upgrade = !empty($powerup_unit) && $powerup_unit;
1555
1556
  $level_current = $term_original = $time_left = 0;
1557
  if($is_upgrade) {
1558
    $time_finish = strtotime($powerup_unit['unit_time_finish']);
1559
    $time_left = max(0, $time_finish - SN_TIME_NOW);
1560
    if($time_left > 0) {
1561
      $term_original = $time_finish - strtotime($powerup_unit['unit_time_start']);
1562
      $level_current = $powerup_unit['unit_level'];
1563
    }
1564
  }
1565
1566
  $level_max = $level_max > $powerup_data[P_MAX_STACK] ? $level_max : $powerup_data[P_MAX_STACK];
1567
  $original_cost = 0;
1568
  for($i = 1; $i <= $level_max; $i++) {
1569
    $base_cost = eco_get_total_cost($powerup_id, $i);
1570
    $base_cost = $base_cost[BUILD_CREATE][RES_DARK_MATTER];
1571
    foreach($sn_powerup_buy_discounts as $period => $discount) {
1572
      $upgrade_price = floor($base_cost * $discount * $period / PERIOD_MONTH);
1573
      $result[$i][$period] = $upgrade_price;
1574
      $original_cost = $is_upgrade && $i == $level_current && $period <= $term_original ? $upgrade_price : $original_cost;
1575
    }
1576
  }
1577
1578
  if($is_upgrade && $time_left) {
1579
    $term_original = round($term_original / PERIOD_DAY);
1580
    $time_left = min(floor($time_left / PERIOD_DAY), $term_original);
1581
    $cost_left = $term_original > 0 ? ceil($time_left / $term_original * $original_cost) : 0;
1582
1583
    array_walk_recursive($result, function(&$value) use ($cost_left) {
1584
      $value -= $cost_left;
1585
    });
1586
  }
1587
1588
  return $result;
1589
}
1590
1591
function note_assign(&$template, $note_row) {
1592
  global $note_priority_classes, $lang;
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $note_priority_classes exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
1593
1594
  $template->assign_block_vars('note', array(
1595
    'ID' => $note_row['id'],
1596
    'TIME' => $note_row['time'],
1597
    'TIME_TEXT' => date(FMT_DATE_TIME, $note_row['time']),
1598
    'PRIORITY' => $note_row['priority'],
1599
    'PRIORITY_CLASS' => $note_priority_classes[$note_row['priority']],
1600
    'PRIORITY_TEXT' => $lang['sys_notes_priorities'][$note_row['priority']],
1601
    'TITLE' => htmlentities($note_row['title'], ENT_COMPAT, 'UTF-8'),
1602
    'GALAXY' => intval($note_row['galaxy']),
1603
    'SYSTEM' => intval($note_row['system']),
1604
    'PLANET' => intval($note_row['planet']),
1605
    'PLANET_TYPE' => intval($note_row['planet_type']),
1606
    'PLANET_TYPE_TEXT' => $lang['sys_planet_type'][$note_row['planet_type']],
1607
    'PLANET_TYPE_TEXT_SHORT' => $lang['sys_planet_type_sh'][$note_row['planet_type']],
1608
    'TEXT' => HelperString::htmlEncode($note_row['text'], HTML_ENCODE_MULTILINE),
1609
    'TEXT_EDIT' => htmlentities($note_row['text'], ENT_COMPAT, 'UTF-8'),
1610
    'STICKY' => intval($note_row['sticky']),
1611
  ));
1612
}
1613
1614
function sn_version_compare_extra($version) {
1615
  static $version_regexp = '#(\d+)([a-f])(\d+)(?:\.(\d+))*#';
1616
  preg_match($version_regexp, $version, $version);
1617
  unset($version[0]);
1618
  $version[2] = ord($version[2]) - ord('a');
1619
  return implode('.', $version);
1620
}
1621
1622
function sn_version_compare($ver1, $ver2) {
1623
  return version_compare(sn_version_compare_extra($ver1), sn_version_compare_extra($ver2));
1624
}
1625
1626
function sn_setcookie($name, $value = null, $expire = null, $path = SN_ROOT_RELATIVE, $domain = null, $secure = null, $httponly = null) {
1627
  $_COOKIE[$name] = $value;
1628
  return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
1629
}
1630
1631
function market_get_autoconvert_cost() {
1632
  global $config;
1633
1634
  return classSupernova::$config->rpg_cost_exchange ? classSupernova::$config->rpg_cost_exchange * 3 : 3000;
0 ignored issues
show
Documentation introduced by
The property rpg_cost_exchange does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1635
}
1636
1637
function print_rr($var, $capture = false) {
1638
  $print = '<pre>' . htmlspecialchars(print_r($var, true)) . '</pre>';
1639
  if($capture) {
1640
    return $print;
1641
  } else {
1642
    print($print);
1643
  }
1644
}
1645
1646
function can_capture_planet(){return sn_function_call('can_capture_planet', array(&$result));}
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1647
function sn_can_capture_planet(&$result) {
1648
  return $result = false;
1649
}
1650
1651
/**
1652
 * Возвращает информацию об IPv4 адресах пользователя
1653
 *
1654
 * НЕ ПОДДЕРЖИВАЕТ IPv6!
1655
 *
1656
 * @return array
1657
 */
1658
// OK v4
1659
function sec_player_ip() {
1660
  // TODO - IPv6 support
1661
  $ip = array(
1662
    'ip' => $_SERVER["REMOTE_ADDR"],
1663
    'proxy_chain' => $_SERVER["HTTP_X_FORWARDED_FOR"]
1664
      ? $_SERVER["HTTP_X_FORWARDED_FOR"]
1665
      : ($_SERVER["HTTP_CLIENT_IP"]
1666
        ? $_SERVER["HTTP_CLIENT_IP"]
1667
        : '' // $_SERVER["REMOTE_ADDR"]
1668
      ),
1669
  );
1670
1671
  return array_map('db_escape', $ip);
1672
}
1673
1674
1675
function price_matrix_templatize(&$price_matrix_plain, &$price_matrix_original, &$price_matrix_upgrade, $user_dark_matter) {
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $price_matrix_original exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
1676
  $prices = array();
1677
  foreach($price_matrix_original as $level_num => $level_data) {
1678
    $price_per_period = array();
1679
    foreach($level_data as $period => $price) {
1680
      $price_text = pretty_number($price, true, $user_dark_matter, false, false);
1681
      $price_per_period[$period] = array(
1682
        'PERIOD' => $period,
1683
        'PRICE_ORIGIN'  => $price,
1684
        'PRICE_ORIGIN_TEXT'  => $price_text['text'],
1685
        'PRICE_ORIGIN_CLASS'  => $price_text['class'],
1686
        'PRICE_UPGRADE' => $price_matrix_upgrade[$level_num][$period],
1687
        'PRICE_UPGRADE_TEXT' => pretty_number($price_matrix_upgrade[$level_num][$period], true),
1688
      );
1689
      if(isset($price_matrix_plain[$level_num][$period])) {
1690
        $price_per_period[$period] += array(
1691
          'PRICE_PLAIN_PERCENT'  => ceil(100 - ($price / $price_matrix_plain[$level_num][$period]) * 100),
1692
          'PRICE_PLAIN'  => $price_matrix_plain[$level_num][$period],
1693
          'PRICE_PLAIN_TEXT'  => pretty_number($price_matrix_plain[$level_num][$period], true),
1694
        );
1695
      }
1696
    }
1697
1698
    $prices[$level_num] = array(
1699
      '.' => array('period' => $price_per_period),
1700
      'LEVEL'   => $level_num,
1701
    );
1702
  }
1703
1704
  return $prices;
1705
}
1706
1707
// ------------------------------------------------------------------------------------------------------------------------------
1708
function sn_sys_load_php_files($dir_name, $load_extension = 'php', $modules = false) {
1709
  if(file_exists($dir_name)) {
1710
    $dir = opendir($dir_name);
1711
    while(($file = readdir($dir)) !== false) {
1712
      if($file == '..' || $file == '.') {
1713
        continue;
1714
      }
1715
1716
      $full_filename = $dir_name . $file;
1717
      if($modules && is_dir($full_filename)) {
1718
        if(file_exists($full_filename = "{$full_filename}/{$file}.{$load_extension}")) {
1719
          require_once($full_filename);
1720
          // Registering module
1721
          if(class_exists($file)) {
1722
            new $file($full_filename);
1723
          }
1724
        }
1725
      } else {
1726
        $extension = substr($full_filename, -strlen($load_extension));
1727
        if($extension == $load_extension) {
1728
          require_once($full_filename);
1729
        }
1730
      }
1731
    }
1732
  }
1733
}
1734
1735
/**
1736
 * Returns unique string ID for total fleets on planet
1737
 *
1738
 * @param array $planetTemplatized
1739
 *
1740
 * @return int|string
1741
 */
1742
function getUniqueFleetId($planetTemplatized) {
1743
  return empty($planetTemplatized['id']) ? 0 : sprintf(FLEET_ID_TEMPLATE, $planetTemplatized['id']);
1744
}