Completed
Push — trunk ( 48600c...80fb95 )
by SuperNova.WS
04:23
created

sn_options_vacation()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 42
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 26
nc 6
nop 1
dl 0
loc 42
rs 5.3846
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * options.php
5
 *
6
 * @copyright (c) 2010-2017 by Gorlum for http://supernova.ws
7
 */
8
9
function sn_options_model() {
10
  global $user, $template_result;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
11
12
  $language_new = sys_get_param_str('langer', $user['lang']);
13
  if ($language_new != $user['lang']) {
14
    SN::$lang->lng_switch($language_new);
15
  }
16
17
  lng_include('options');
18
  lng_include('messages');
19
20
  sys_user_options_unpack($user);
21
22
  $savedOk = false;
23
  if (sys_get_param_str('mode') == 'change') {
24
    if (!is_array($template_result['.']['result'])) {
25
      $template_result['.']['result'] = [];
26
    }
27
28
    $user = sn_options_admin_protection($user);
29
    $user = sn_options_vacation($user);
30
    $user = sn_options_gender($user);
31
    $user = sn_options_change_birthday($user);
32
    $user = sn_options_deprecated($user);
0 ignored issues
show
Deprecated Code introduced by
The function sn_options_deprecated() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

32
    $user = /** @scrutinizer ignore-deprecated */ sn_options_deprecated($user);
Loading history...
33
    sn_options_player_standard();
34
35
    $template_result['.']['result'][] = sn_options_change_password();
36
    list($user, $usernameResult) = sn_options_change_username($user);
37
    $template_result['.']['result'] = array_merge($template_result['.']['result'], $usernameResult);
38
39
    sn_options_timediff(
40
      sys_get_param_int('PLAYER_OPTION_TIME_DIFF'),
41
      sys_get_param_int('PLAYER_OPTION_TIME_DIFF_FORCED'),
42
      sys_get_param_int('opt_time_diff_clear')
43
    );
44
45
    require_once('includes/includes/sys_avatar.php');
46
    $avatar_upload_result = sys_avatar_upload($user['id'], $user['avatar']);
47
    $template_result['.']['result'][] = $avatar_upload_result;
48
49
    $user['email'] = sys_get_param_str('db_email');
50
    SN::$gc->theUser->setSkinName(sys_get_param_str('skin_name'));
51
    $user['lang'] = sys_get_param_str('langer', $user['lang']);
52
    $user['design'] = sys_get_param_int('design');
53
    $user['noipcheck'] = sys_get_param_int('noipcheck');
54
    $user['deltime'] = !sys_get_param_int('deltime') ? 0 : ($user['deltime'] ? $user['deltime'] : SN_TIME_NOW + SN::$config->player_delete_time);
55
56
    \DBAL\DbQuery::build(SN::$db)
57
      ->setTable('users')
58
      ->setValues([
59
        'email'                    => $user['email'],
60
        'lang'                     => $user['lang'],
61
        'avatar'                   => $user['avatar'],
62
        'design'                   => $user['design'],
63
        'noipcheck'                => $user['noipcheck'],
64
        'deltime'                  => $user['deltime'],
65
        'vacation'                 => $user['vacation'],
66
        'gender'                   => $user['gender'],
67
        'skin'                     => SN::$gc->theUser->getSkinName(),
68
        'user_birthday'            => $user['user_birthday'],
69
        'user_birthday_celebrated' => $user['user_birthday_celebrated'],
70
        'options'                  => $user['options'],
71
      ])
72
      ->setWhereArray(['id' => $user['id']])
73
      ->doUpdate();
74
75
    $savedOk = true;
76
  } elseif (sys_get_param_str('result') == 'ok') {
77
    $savedOk = true;
78
  }
79
80
  if ($savedOk) {
81
    $template_result['.']['result'][] = array(
82
      'STATUS'  => ERR_NONE,
83
      'MESSAGE' => SN::$lang['opt_msg_saved']
84
    );
85
  }
86
}
87
88
//-------------------------------
89
90
function sn_options_view($template = null) {
91
  global $lang, $template_result, $user, $planetrow, $user_option_list, $user_option_types, $sn_message_class_list, $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
92
93
  sys_user_vacation($user);
94
95
  $FMT_DATE = preg_replace(array('/d/', '/m/', '/Y/'), array('DD', 'MM', 'YYYY'), FMT_DATE);
96
97
  $template = gettemplate('options', $template);
98
99
  $dir = dir(SN_ROOT_PHYSICAL . 'skins');
100
  while (($entry = $dir->read()) !== false) {
101
    if (is_dir("skins/{$entry}") && $entry[0] != '.') {
102
      $template_result['.']['skin_list'][] = array(
103
        'VALUE'    => $entry,
104
        'NAME'     => $entry,
105
        'SELECTED' => SN::$gc->theUser->getSkinName() == $entry,
106
      );
107
    }
108
  }
109
  $dir->close();
110
111
  foreach ($lang['opt_planet_sort_options'] as $key => &$value) {
112
    $template_result['.']['planet_sort_options'][] = array(
113
      'VALUE'    => $key,
114
      'NAME'     => $value,
115
      'SELECTED' => SN::$user_options[PLAYER_OPTION_PLANET_SORT] == $key,
116
    );
117
  }
118
119
  foreach ($lang['sys_gender_list'] as $key => $value) {
120
    $template_result['.']['gender_list'][] = array(
121
      'VALUE'    => $key,
122
      'NAME'     => $value,
123
      'SELECTED' => $user['gender'] == $key,
124
    );
125
  }
126
127
  $lang_list = lng_get_list();
128
  foreach ($lang_list as $lang_id => $lang_data) {
129
    $template_result['.']['languages'][] = array(
130
      'VALUE'    => $lang_id,
131
      'NAME'     => $lang_data['LANG_NAME_NATIVE'],
132
      'SELECTED' => $lang_id == $user['lang'],
133
    );
134
  }
135
136
137
  if (isset($lang['menu_customize_show_hide_button_state'])) {
138
    foreach ($lang['menu_customize_show_hide_button_state'] as $key => $value) {
139
      $template->assign_block_vars('menu_customize_show_hide_button_state', array(
140
        'ID'   => $key,
141
        'NAME' => $value,
142
      ));
143
    }
144
  }
145
146
  $str_date_format = "%3$02d %2$0s %1$04d {$lang['top_of_year']} %4$02d:%5$02d:%6$02d";
147
  $time_now_parsed = getdate($user['deltime']);
148
149
  $user_time_diff = playerTimeDiff::user_time_diff_get();
150
151
152
  sn_options_add_standard($template);
153
154
  $template->assign_vars([
155
    'USER_ID' => $user['id'],
156
157
    'ACCOUNT_NAME' => sys_safe_output(SN::$auth->account->account_name),
158
159
    'USER_AUTHLEVEL' => $user['authlevel'],
160
161
    'menu_customize_show_hide_button'     => SN::$user_options[PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON],
162
    'PLAYER_OPTION_MENU_SHOW_ON_BUTTON'   => SN::$user_options[PLAYER_OPTION_MENU_SHOW_ON_BUTTON],
163
    'PLAYER_OPTION_MENU_HIDE_ON_BUTTON'   => SN::$user_options[PLAYER_OPTION_MENU_HIDE_ON_BUTTON],
164
    'PLAYER_OPTION_MENU_HIDE_ON_LEAVE'    => SN::$user_options[PLAYER_OPTION_MENU_HIDE_ON_LEAVE],
165
    'PLAYER_OPTION_MENU_UNPIN_ABSOLUTE'   => SN::$user_options[PLAYER_OPTION_MENU_UNPIN_ABSOLUTE],
166
    'PLAYER_OPTION_MENU_ITEMS_AS_BUTTONS' => SN::$user_options[PLAYER_OPTION_MENU_ITEMS_AS_BUTTONS],
167
    'PLAYER_OPTION_MENU_WHITE_TEXT'       => SN::$user_options[PLAYER_OPTION_MENU_WHITE_TEXT],
168
    'PLAYER_OPTION_MENU_OLD'              => SN::$user_options[PLAYER_OPTION_MENU_OLD],
169
170
    'PLAYER_OPTION_TUTORIAL_CURRENT_ID' => PLAYER_OPTION_TUTORIAL_CURRENT,
171
172
    'ADM_PROTECT_PLANETS' => $user['authlevel'] >= 3,
173
    'opt_usern_data'      => htmlspecialchars($user['username']),
174
    'opt_mail1_data'      => $user['email'],
175
    'opt_mail2_data'      => sys_safe_output(SN::$auth->account->account_email),
176
177
    'PLAYER_OPTION_PLANET_SORT_INVERSE'    => SN::$user_options[PLAYER_OPTION_PLANET_SORT_INVERSE],
178
    'PLAYER_OPTION_FLEET_SPY_DEFAULT'      => SN::$user_options[PLAYER_OPTION_FLEET_SPY_DEFAULT],
179
    'PLAYER_OPTION_TOOLTIP_DELAY'          => SN::$user_options[PLAYER_OPTION_TOOLTIP_DELAY],
180
    'PLAYER_OPTION_BUILD_AUTOCONVERT_HIDE' => SN::$user_options[PLAYER_OPTION_BUILD_AUTOCONVERT_HIDE],
181
182
    'opt_sskin_data' => ($user['design'] == 1) ? " checked='checked'" : '',
183
    'opt_noipc_data' => ($user['noipcheck'] == 1) ? " checked='checked'" : '',
184
    'deltime'        => $user['deltime'],
185
    'deltime_text'   => sprintf($str_date_format, $time_now_parsed['year'], $lang['months'][$time_now_parsed['mon']], $time_now_parsed['mday'],
186
      $time_now_parsed['hours'], $time_now_parsed['minutes'], $time_now_parsed['seconds']
187
    ),
188
189
    'opt_avatar' => $user['avatar'],
190
191
    'config_game_email_pm' => $config->game_email_pm,
192
193
    'user_settings_esp'        => SN::$user_options[PLAYER_OPTION_UNIVERSE_ICON_SPYING],
194
    'user_settings_mis'        => SN::$user_options[PLAYER_OPTION_UNIVERSE_ICON_MISSILE],
195
    'user_settings_wri'        => SN::$user_options[PLAYER_OPTION_UNIVERSE_ICON_PM],
196
    'user_settings_statistics' => SN::$user_options[PLAYER_OPTION_UNIVERSE_ICON_STATS],
197
    'user_settings_info'       => SN::$user_options[PLAYER_OPTION_UNIVERSE_ICON_PROFILE],
198
    'user_settings_bud'        => SN::$user_options[PLAYER_OPTION_UNIVERSE_ICON_BUDDY],
199
200
    'user_time_diff_forced' => $user_time_diff[PLAYER_OPTION_TIME_DIFF_FORCED],
201
202
    'adm_pl_prot' => $user['admin_protection'],
203
204
    'user_birthday' => $user['user_birthday'],
205
    'GENDER'        => $user['gender'],
206
    'GENDER_TEXT'   => $lang['sys_gender_list'][$user['gender']],
207
    'FMT_DATE'      => $FMT_DATE,
208
    'JS_FMT_DATE'   => js_safe_string($FMT_DATE),
209
210
    'USER_VACATION_DISABLE' => $config->user_vacation_disable,
211
    'VACATION_NEXT'         => $user['vacation_next'],
212
    'VACATION_NEXT_TEXT'    => date(FMT_DATE_TIME, $user['vacation_next']),
213
    'VACATION_TIMEOUT'      => $user['vacation_next'] - SN_TIME_NOW > 0 ? $user['vacation_next'] - SN_TIME_NOW : 0,
214
    'SN_TIME_NOW'           => SN_TIME_NOW,
215
216
    'SERVER_SEND_EMAIL' => $config->game_email_pm,
217
218
    'SERVER_NAME_CHANGE'         => $config->game_user_changename != SERVER_PLAYER_NAME_CHANGE_NONE,
219
    'SERVER_NAME_CHANGE_PAY'     => $config->game_user_changename == SERVER_PLAYER_NAME_CHANGE_PAY,
220
    'SERVER_NAME_CHANGE_ENABLED' => $config->game_user_changename == SERVER_PLAYER_NAME_CHANGE_FREE || ($config->game_user_changename == SERVER_PLAYER_NAME_CHANGE_PAY && mrc_get_level($user, $planetrow, RES_DARK_MATTER) >= $config->game_user_changename_cost),
221
222
    'DARK_MATTER' => prettyNumberStyledCompare($config->game_user_changename_cost, mrc_get_level($user, $planetrow, RES_DARK_MATTER)),
0 ignored issues
show
Bug introduced by
It seems like mrc_get_level($user, $planetrow, RES_DARK_MATTER) can also be of type boolean; however, parameter $compareTo of prettyNumberStyledCompare() does only seem to accept integer|double, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

222
    'DARK_MATTER' => prettyNumberStyledCompare($config->game_user_changename_cost, /** @scrutinizer ignore-type */ mrc_get_level($user, $planetrow, RES_DARK_MATTER)),
Loading history...
223
224
    'GROUP_DESIGN_BLOCK_TUTORIAL'      => GROUP_DESIGN_BLOCK_TUTORIAL,
225
    'GROUP_DESIGN_BLOCK_FLEET_COMPOSE' => GROUP_DESIGN_BLOCK_FLEET_COMPOSE,
226
    'GROUP_DESIGN_BLOCK_UNIVERSE'      => GROUP_DESIGN_BLOCK_UNIVERSE,
227
    'GROUP_DESIGN_BLOCK_NAVBAR'        => GROUP_DESIGN_BLOCK_NAVBAR,
228
    'GROUP_DESIGN_BLOCK_RESOURCEBAR'   => GROUP_DESIGN_BLOCK_RESOURCEBAR,
229
    'GROUP_DESIGN_BLOCK_PLANET_SORT'   => GROUP_DESIGN_BLOCK_PLANET_SORT,
230
    'GROUP_DESIGN_BLOCK_COMMON_ONE'    => GROUP_DESIGN_BLOCK_COMMON_ONE,
231
    'GROUP_DESIGN_BLOCK_COMMON_TWO'    => GROUP_DESIGN_BLOCK_COMMON_TWO,
232
233
    'PAGE_HEADER' => $lang['opt_header'],
234
  ]);
235
236
  foreach ($user_option_list as $option_group_id => $option_group) {
237
    if ($option_group_id == OPT_MESSAGE) {
238
      foreach ($sn_message_class_list as $message_class_id => $message_class_data) {
239
        if ($message_class_data['switchable'] || ($message_class_data['email'] && $config->game_email_pm)) {
240
          $option_name = $message_class_data['name'];
241
242
          $template->assign_block_vars("options_{$option_group_id}", array(
243
            'NAME'  => $message_class_data['name'],
244
            'TEXT'  => $lang['msg_class'][$message_class_id], // $lang['opt_custom'][$option_name],
0 ignored issues
show
Unused Code Comprehensibility introduced by
89% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
245
            'PM'    => $message_class_data['switchable'] ? $user["opt_{$option_name}"] : -1,
246
            'EMAIL' => $message_class_data['email'] && $config->game_email_pm ? $user["opt_email_{$option_name}"] : -1,
247
          ));
248
        }
249
      }
250
    } else {
251
      foreach ($option_group as $option_name => $option_value) {
252
        if (array_key_exists($option_name, $user_option_types)) {
253
          $option_type = $user_option_types[$option_name];
254
        } else {
255
          $option_type = 'switch';
256
        }
257
258
        $template->assign_block_vars("options_{$option_group_id}", array(
259
          'NAME'  => $option_name,
260
          'TYPE'  => $option_type,
261
          'TEXT'  => $lang['opt_custom'][$option_name],
262
          'HINT'  => $lang['opt_custom']["{$option_name}_hint"],
263
          'VALUE' => $user[$option_name],
264
        ));
265
      }
266
    }
267
  }
268
269
  return $template;
270
}
271
272
//-------------------------------
273
274
/**
275
 * @param $user
276
 *
277
 * @return array
278
 */
279
function sn_options_gender($user) {
280
  $gender = sys_get_param_int('gender', $user['gender']);
281
  !isset(SN::$lang['sys_gender_list'][$gender]) ? $gender = $user['gender'] : false;
282
  $user['gender'] = $user['gender'] == GENDER_UNKNOWN ? $gender : $user['gender'];
283
284
  return $user;
285
}
286
287
function sn_options_timediff($timeDiff, $force, $clear) {
288
//  $timeDiff = sys_get_param_int('PLAYER_OPTION_TIME_DIFF');
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
289
//  $force = sys_get_param_int('PLAYER_OPTION_TIME_DIFF_FORCED');
290
//  $clear = sys_get_param_int('opt_time_diff_clear');
291
  $user_time_diff = playerTimeDiff::user_time_diff_get();
292
  if ($force) {
293
    playerTimeDiff::user_time_diff_set(array(
294
      PLAYER_OPTION_TIME_DIFF              => $timeDiff,
295
      PLAYER_OPTION_TIME_DIFF_UTC_OFFSET   => 0,
296
      PLAYER_OPTION_TIME_DIFF_FORCED       => 1,
297
      PLAYER_OPTION_TIME_DIFF_MEASURE_TIME => SN_TIME_SQL,
298
    ));
299
  } elseif ($clear || $user_time_diff[PLAYER_OPTION_TIME_DIFF_FORCED]) {
300
    playerTimeDiff::user_time_diff_set(array(
301
      PLAYER_OPTION_TIME_DIFF              => '',
302
      PLAYER_OPTION_TIME_DIFF_UTC_OFFSET   => 0,
303
      PLAYER_OPTION_TIME_DIFF_FORCED       => 0,
304
      PLAYER_OPTION_TIME_DIFF_MEASURE_TIME => SN_TIME_SQL,
305
    ));
306
  }
307
}
308
309
/**
310
 * @param $user
311
 * @param $FMT_DATE
312
 * @param $pos
313
 * @param $match
314
 *
315
 * @return array
316
 */
317
function sn_options_change_birthday($user) {
318
  $user_birthday = sys_get_param_str_unsafe('user_birthday');
319
  $FMT_DATE = preg_replace(array('/d/', '/m/', '/Y/'), array('DD', 'MM', 'YYYY'), FMT_DATE);
320
321
  if ($user['birthday'] || empty($user_birthday) || $user_birthday == $FMT_DATE) {
322
    return $user;
323
  }
324
325
  try {
326
    // Some black magic to parse any valid date format - those that contains all three "d", "m" and "Y" and any of the delimeters "\", "/", ".", "-"
327
    $pos['d'] = strpos(FMT_DATE, 'd');
0 ignored issues
show
Comprehensibility Best Practice introduced by
$pos was never initialized. Although not strictly required by PHP, it is generally a good practice to add $pos = array(); before regardless.
Loading history...
328
    $pos['m'] = strpos(FMT_DATE, 'm');
329
    $pos['Y'] = strpos(FMT_DATE, 'Y');
330
    asort($pos);
331
    $i = 0;
332
    foreach ($pos as &$position) {
333
      $position = ++$i;
334
    }
335
336
    $regexp = "/" . preg_replace(array('/\\\\/', '/\//', '/\./', '/\-/', '/d/', '/m/', '/Y/'), array('\\\\\\', '\/', '\.', '\-', '(\d?\d)', '(\d?\d)', '(\d{4})'), FMT_DATE) . "/";
337
    if (!preg_match($regexp, $user_birthday, $match)) {
338
      throw new Exception();
339
    }
340
341
    if (!checkdate($match[$pos['m']], $match[$pos['d']], $match[$pos['Y']])) {
342
      throw new Exception();
343
    }
344
345
    $user_birthday_new_unescaped = "{$match[$pos['Y']]}-{$match[$pos['m']]}-{$match[$pos['d']]}";
346
    $user['user_birthday'] = $user_birthday_new_unescaped;
347
    // EOF black magic! Now we have valid SQL date in $user['user_birthday'] - independent of date format
348
349
    $year = date('Y', SN_TIME_NOW);
350
    if (mktime(0, 0, 0, $match[$pos['m']], $match[$pos['d']], $year) > SN_TIME_NOW) {
0 ignored issues
show
Bug introduced by
$year of type string is incompatible with the type integer expected by parameter $year of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

350
    if (mktime(0, 0, 0, $match[$pos['m']], $match[$pos['d']], /** @scrutinizer ignore-type */ $year) > SN_TIME_NOW) {
Loading history...
351
      $year--;
352
    }
353
    $user['user_birthday_celebrated'] = "{$year}-{$match[$pos['m']]}-{$match[$pos['d']]}";
354
  } catch (exception $e) {
355
    $user['user_birthday'] = null;
356
    $user['user_birthday_celebrated'] = null;
357
  }
358
359
  return $user;
360
}
361
362
/**
363
 * @return array
364
 */
365
function sn_options_change_password() {
366
  $result = [];
367
  if (!($new_password = sys_get_param('newpass1'))) {
368
    return $result;
369
  }
370
371
  try {
372
    if ($new_password != sys_get_param('newpass2')) {
373
      throw new Exception('opt_err_pass_unmatched', ERR_WARNING);
374
    }
375
376
    if (!SN::$auth->password_change(sys_get_param('db_password'), $new_password)) {
377
      throw new Exception('opt_err_pass_wrong', ERR_WARNING);
378
    }
379
380
    throw new Exception('opt_msg_pass_changed', ERR_NONE);
381
  } catch (Exception $e) {
382
    $result = [
383
      'STATUS'  => in_array($e->getCode(), [ERR_NONE, ERR_WARNING, ERR_ERROR]) ? $e->getCode() : ERR_ERROR,
384
      'MESSAGE' => SN::$lang[$e->getMessage()],
385
    ];
386
  }
387
388
  return $result;
389
}
390
391
function sn_options_player_standard() {
392
  $player_options = sys_get_param('options');
393
  if (empty($player_options)) {
394
    return;
395
  }
396
397
  if ($player_options[PLAYER_OPTION_TUTORIAL_CURRENT]) {
398
    $player_options[PLAYER_OPTION_TUTORIAL_CURRENT] = SN::$config->tutorial_first_item;
399
    $player_options[PLAYER_OPTION_TUTORIAL_FINISHED] = 0;
400
  } else {
401
    unset($player_options[PLAYER_OPTION_TUTORIAL_CURRENT]);
402
  }
403
404
  array_walk($player_options, function (&$value) {
0 ignored issues
show
Bug introduced by
$player_options of type string is incompatible with the type array expected by parameter $array of array_walk(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

404
  array_walk(/** @scrutinizer ignore-type */ $player_options, function (&$value) {
Loading history...
405
    // TODO - Когда будет больше параметров - сделать больше проверок
406
    $value = intval($value);
407
  });
408
  SN::$user_options->offsetSet($player_options);
409
}
410
411
/**
412
 * @param array $user
413
 *
414
 * @return array
415
 */
416
function sn_options_change_username($user) {
417
  $config = SN::$config;
418
  $lang = SN::$lang;
419
420
  $result = [];
421
422
  $username = substr(sys_get_param_str_unsafe('username'), 0, 32);
423
  if (
424
    empty($username)
425
    || $user['username'] == $username
426
    || $config->game_user_changename == SERVER_PLAYER_NAME_CHANGE_NONE
427
    || !sys_get_param_int('username_confirm')
428
    || strpbrk($username, LOGIN_REGISTER_CHARACTERS_PROHIBITED)
429
  ) {
430
    return [$user, $result];
431
  }
432
433
  // проверка на корректность
434
  sn_db_transaction_start();
435
  $username_safe = db_escape($username);
436
  $name_check = doquery("SELECT * FROM `{{player_name_history}}` WHERE `player_name` LIKE \"{$username_safe}\" LIMIT 1 FOR UPDATE;", true);
437
  if (empty($name_check['player_id']) || $name_check['player_id'] == $user['id']) {
438
    $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. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

438
    $user = /** @scrutinizer ignore-deprecated */ db_user_by_id($user['id'], true);
Loading history...
439
    switch ($config->game_user_changename) {
440
      /** @noinspection PhpMissingBreakStatementInspection */
441
      case SERVER_PLAYER_NAME_CHANGE_PAY:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
442
        if (mrc_get_level($user, [], RES_DARK_MATTER) < $config->game_user_changename_cost) {
443
          $result[] = [
444
            'STATUS'  => ERR_ERROR,
445
            'MESSAGE' => $lang['opt_msg_name_change_err_no_dm'],
446
          ];
447
          break;
448
        }
449
        rpg_points_change(
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
450
          $user['id'],
451
          RPG_NAME_CHANGE,
452
          -$config->game_user_changename_cost,
453
          vsprintf('Пользователь ID %1$d сменил имя с "%2$s" на "%3$s"', [$user['id'], $user['username'], $username,])
454
        );
455
456
      case SERVER_PLAYER_NAME_CHANGE_FREE:
457
        db_user_set_by_id($user['id'], "`username` = '{$username_safe}'");
0 ignored issues
show
Deprecated Code introduced by
The function db_user_set_by_id() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

457
        /** @scrutinizer ignore-deprecated */ db_user_set_by_id($user['id'], "`username` = '{$username_safe}'");
Loading history...
458
        doquery("REPLACE INTO {{player_name_history}} SET `player_id` = {$user['id']}, `player_name` = '{$username_safe}'");
459
        // TODO: Change cookie to not force user relogin
460
        // sn_setcookie(SN_COOKIE, '', time() - PERIOD_WEEK, SN_ROOT_RELATIVE);
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
461
        $result[] = [
462
          'STATUS'  => ERR_NONE,
463
          'MESSAGE' => $lang['opt_msg_name_changed']
464
        ];
465
        $user['username'] = $username;
466
      break;
467
    }
468
  } else {
469
    $result[] = [
470
      'STATUS'  => ERR_ERROR,
471
      'MESSAGE' => $lang['opt_msg_name_change_err_used_name'],
472
    ];
473
  }
474
  sn_db_transaction_commit();
475
476
  return [$user, $result];
477
}
478
479
/**
480
 * Set old options
481
 *
482
 * @param array $user
483
 *
484
 * @return array
485
 * @deprecated
486
 */
487
function sn_options_deprecated($user) {
488
  global $user_option_list;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
489
490
  foreach ($user_option_list as $option_group_id => $option_group) {
491
    foreach ($option_group as $option_name => $option_value) {
492
      if ($user[$option_name] !== null) {
493
        $user[$option_name] = sys_get_param_str($option_name);
494
      } else {
495
        $user[$option_name] = $option_value;
496
      }
497
    }
498
  }
499
500
  sys_user_options_pack($user);
501
502
  return $user;
503
}
504
505
/**
506
 * @param array $user
507
 *
508
 * @return array
509
 */
510
function sn_options_admin_protection($user) {
511
  if ($user['authlevel'] <= AUTH_LEVEL_REGISTERED) {
512
    return $user;
513
  }
514
515
  $planet_protection = sys_get_param_int('adm_pl_prot') ? $user['authlevel'] : 0;
516
  DBStaticPlanet::db_planet_set_by_owner($user['id'], "`id_level` = '{$planet_protection}'");
517
  db_user_set_by_id($user['id'], "`admin_protection` = '{$planet_protection}'");
0 ignored issues
show
Deprecated Code introduced by
The function db_user_set_by_id() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

517
  /** @scrutinizer ignore-deprecated */ db_user_set_by_id($user['id'], "`admin_protection` = '{$planet_protection}'");
Loading history...
518
  $user['admin_protection'] = $planet_protection;
519
520
  return $user;
521
}
522
523
/**
524
 * @param array $user
525
 *
526
 * @return array
527
 */
528
function sn_options_vacation($user) {
529
  $config = SN::$config;
530
  $lang = SN::$lang;
531
532
  if (!sys_get_param_int('vacation') || $config->user_vacation_disable) {
533
    return $user;
534
  }
535
536
  sn_db_transaction_start();
537
  if ($user['authlevel'] < AUTH_LEVEL_ADMINISTRATOR) {
538
    if ($user['vacation_next'] > SN_TIME_NOW) {
539
      messageBox($lang['opt_vacation_err_timeout'], $lang['Error'], 'index.php?page=options', 5);
540
      die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
541
    }
542
543
    if (fleet_count_flying($user['id'])) {
544
      messageBox($lang['opt_vacation_err_your_fleet'], $lang['Error'], 'index.php?page=options', 5);
545
      die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
546
    }
547
548
    $que = que_get($user['id'], false);
549
    if (!empty($que)) {
550
      messageBox($lang['opt_vacation_err_que'], $lang['Error'], 'index.php?page=options', 5);
551
      die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
552
    }
553
554
    $query = SN::db_get_record_list(LOC_PLANET, "`id_owner` = {$user['id']}");
555
    foreach ($query as $planet) {
556
      DBStaticPlanet::db_planet_set_by_id($planet['id'],
557
        "last_update = " . SN_TIME_NOW . ", energy_used = '0', energy_max = '0',
558
        metal_perhour = '{$config->metal_basic_income}', crystal_perhour = '{$config->crystal_basic_income}', deuterium_perhour = '{$config->deuterium_basic_income}',
559
        metal_mine_porcent = '0', crystal_mine_porcent = '0', deuterium_sintetizer_porcent = '0', solar_plant_porcent = '0',
560
        fusion_plant_porcent = '0', solar_satelit_porcent = '0', ship_sattelite_sloth_porcent = 0"
561
      );
562
    }
563
    $user['vacation'] = SN_TIME_NOW + $config->player_vacation_time;
564
  } else {
565
    $user['vacation'] = SN_TIME_NOW;
566
  }
567
  sn_db_transaction_commit();
568
569
  return $user;
570
}
571
572
573
/**
574
 * @param template $template
575
 * @param string   $blockName
576
 * @param int      $blockId
577
 * @param int[]    $optionsNavBar
578
 * @param array    $options
579
 */
580
function sn_options_render_block($template, $blockName, $blockId, $optionsNavBar, $options = []) {
581
  $template->assign_block_vars('player_options', [
582
    'ID'   => $blockId,
583
    'NAME' => $blockName,
584
  ]);
585
586
  foreach ($optionsNavBar as $optionId) {
587
    $template->assign_block_vars('player_options.option', [
588
      'ID'         => $optionId,
589
      'VALUE'      => SN::$user_options[$optionId],
590
      'NAME'       => SN::$lang['opt_player_options'][$optionId],
591
      'ALWAYS_OFF' => !empty($options[$optionId]['always_off']),
592
      'CLASS'      => !empty($options[$optionId]['class']) ? $options[$optionId]['class'] : 'cell',
593
    ]);
594
  }
595
}
596
597
/**
598
 * @param $template
599
 */
600
function sn_options_add_standard($template) {
601
  sn_options_render_block($template, '', 5, [
602
  ]);
603
604
605
  // 8
606
  sn_options_render_block($template, '', GROUP_DESIGN_BLOCK_COMMON_TWO,
607
    [
608
      PLAYER_OPTION_SOUND_ENABLED,
609
      PLAYER_OPTION_ANIMATION_DISABLED,
610
      PLAYER_OPTION_PROGRESS_BARS_DISABLED,
611
    ],
612
    [
613
      PLAYER_OPTION_SOUND_ENABLED          => ['class' => 'header'],
614
      PLAYER_OPTION_ANIMATION_DISABLED     => ['class' => 'header'],
615
      PLAYER_OPTION_PROGRESS_BARS_DISABLED => ['class' => 'header'],
616
    ]
617
  );
618
  // 7
619
  sn_options_render_block($template, '', GROUP_DESIGN_BLOCK_COMMON_ONE, [
620
    PLAYER_OPTION_BUILD_AUTOCONVERT_HIDE,
621
    PLAYER_OPTION_DESIGN_DISABLE_BORDERS,
622
    PLAYER_OPTION_TECH_TREE_TABLE,
623
  ]);
624
  // 6
625
  sn_options_render_block($template, '', GROUP_DESIGN_BLOCK_PLANET_SORT, [
626
    PLAYER_OPTION_PLANET_SORT_INVERSE,
627
  ]);
628
  // 4
629
  sn_options_render_block($template, SN::$lang['opt_navbar_resourcebar_description'], GROUP_DESIGN_BLOCK_RESOURCEBAR, [
630
    PLAYER_OPTION_NAVBAR_PLANET_VERTICAL,
631
    PLAYER_OPTION_NAVBAR_PLANET_DISABLE_STORAGE,
632
    PLAYER_OPTION_NAVBAR_PLANET_OLD,
633
  ]);
634
  // 3
635
  sn_options_render_block($template, SN::$lang['opt_navbar_buttons_title'], GROUP_DESIGN_BLOCK_NAVBAR, [
636
    PLAYER_OPTION_NAVBAR_RESEARCH_WIDE,
637
    PLAYER_OPTION_NAVBAR_DISABLE_RESEARCH,
638
    PLAYER_OPTION_NAVBAR_DISABLE_PLANET,
639
    PLAYER_OPTION_NAVBAR_DISABLE_HANGAR,
640
    PLAYER_OPTION_NAVBAR_DISABLE_EXPEDITIONS,
641
    PLAYER_OPTION_NAVBAR_DISABLE_FLYING_FLEETS,
642
    PLAYER_OPTION_NAVBAR_DISABLE_QUESTS,
643
    PLAYER_OPTION_NAVBAR_DISABLE_META_MATTER,
644
  ]);
645
  // 2
646
  sn_options_render_block($template, SN::$lang['galaxyvision_options'], GROUP_DESIGN_BLOCK_UNIVERSE, [
647
    PLAYER_OPTION_UNIVERSE_OLD,
648
    PLAYER_OPTION_UNIVERSE_DISABLE_COLONIZE,
649
  ]);
650
  // 1
651
  sn_options_render_block($template, SN::$lang['option_fleet_send'], GROUP_DESIGN_BLOCK_FLEET_COMPOSE, [
652
    PLAYER_OPTION_FLEET_SHIP_SELECT_OLD,
653
    PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION,
654
    PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED,
655
    PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY,
656
  ]);
657
  // 0
658
  sn_options_render_block($template, SN::$lang['opt_tutorial'], GROUP_DESIGN_BLOCK_TUTORIAL, [
659
    PLAYER_OPTION_TUTORIAL_DISABLED,
660
    // PLAYER_OPTION_TUTORIAL_WINDOWED,
661
    PLAYER_OPTION_TUTORIAL_CURRENT,
662
  ], [PLAYER_OPTION_TUTORIAL_CURRENT => ['always_off' => true]]);
663
}
664