Test Failed
Branch trunk (d809b8)
by SuperNova.WS
05:48
created

template.php ➔ tpl_render_unit_bonus_data()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 4
nop 1
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
use \Pages\PageTutorial;
4
5
// Wrappers for functions
6
7
/**
8
 * Get template name from path to skin
9
 *
10
 * @param $userSkinPath
11
 *
12
 * @return mixed
13
 */
14
function getSkinPathTemplate($userSkinPath) {
15
  static $template_names = array();
16
17
  if(!isset($template_names[$userSkinPath])) {
18
    $template_names[$userSkinPath] = file_exists(SN_ROOT_PHYSICAL . $userSkinPath . '_template.ini') ? sys_file_read(SN_ROOT_PHYSICAL . $userSkinPath . '_template.ini') : TEMPLATE_NAME;
19
  }
20
21
  return $template_names[$userSkinPath];
22
}
23
24
/**
25
 * @param string    $message
26
 * @param string    $title
27
 * @param string    $redirectTo
28
 * @param int       $timeout
29
 * @param bool|true $showHeader
30
 */
31
function messageBox($message, $title = '', $redirectTo = '', $timeout = 5, $showHeader = true) {
32
  global $lang, $template_result;
33
34
  if (empty($title)) {
35
    $title = $lang['sys_error'];
36
  }
37
38
  $template = gettemplate('message_body', true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a object<template>|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
39
40
  $template_result['GLOBAL_DISPLAY_NAVBAR'] = $showHeader;
41
42
  $template->assign_vars(array(
43
//    'GLOBAL_DISPLAY_NAVBAR' => $showHeader,
44
45
    'TITLE'       => $title,
46
    'MESSAGE'     => $message,
47
    'REDIRECT_TO' => $redirectTo,
48
    'TIMEOUT'     => $timeout,
49
  ));
50
51
  display($template, $title);
52
}
53
54
/**
55
 * Admin message box
56
 *
57
 * @see messageBox()
58
 */
59
function messageBoxAdmin($message, $title = '', $redirectTo = '', $timeout = 5) {
60
  messageBox($message, $title, $redirectTo, $timeout, false);
61
}
62
63
function messageBoxAdminAccessDenied($level = AUTH_LEVEL_ADMINISTRATOR) {
64
  global $user, $lang;
65
66
  if($user['authlevel'] < $level) {
67
    messageBoxAdmin($lang['adm_err_denied'], $lang['admin_title_access_denied'], SN_ROOT_VIRTUAL . 'overview.php');
68
  }
69
}
70
71
/**
72
 * @param $menu
73
 * @param $extra
74
 */
75
function tpl_menu_merge_extra(&$menu, &$extra) {
76
  if(empty($menu) || empty($extra)) {
77
    return;
78
  }
79
80
  foreach($extra as $menu_item_id => $menu_item) {
81
    if(empty($menu_item['LOCATION'])) {
82
      $menu[$menu_item_id] = $menu_item;
83
      continue;
84
    }
85
86
    $item_location = $menu_item['LOCATION'];
87
    unset($menu_item['LOCATION']);
88
89
    $is_positioned = $item_location[0];
90
    if($is_positioned == '+' || $is_positioned == '-') {
91
      $item_location = substr($item_location, 1);
92
    } else {
93
      $is_positioned = '';
94
    }
95
96
    if($item_location) {
97
      $menu_keys = array_keys($menu);
98
      $insert_position = array_search($item_location, $menu_keys);
99
      if($insert_position === false) {
100
        $insert_position = count($menu) - 1;
101
        $is_positioned = '+';
102
        $item_location = '';
103
      }
104
    } else {
105
      $insert_position = $is_positioned == '-' ? 0 : count($menu);
106
    }
107
108
    $insert_position += $is_positioned == '+' ? 1 : 0;
109
    $spliced = array_splice($menu, $insert_position, count($menu) - $insert_position);
110
    $menu[$menu_item_id] = $menu_item;
111
112
    if(!$is_positioned && $item_location) {
113
      unset($spliced[$item_location]);
114
    }
115
    $menu = array_merge($menu, $spliced);
116
  }
117
118
  $extra = array();
119
}
120
121
/**
122
 * @param array    $sn_menu
123
 * @param template $template
124
 */
125
function tpl_menu_assign_to_template(&$sn_menu, &$template) {
126
  global $lang;
127
128
  if(empty($sn_menu) || !is_array($sn_menu)) {
129
    return;
130
  }
131
132
  foreach($sn_menu as $menu_item_id => $menu_item) {
133
    if(!$menu_item) {
134
      continue;
135
    }
136
137
    if(is_string($menu_item_id)) {
138
      $menu_item['ID'] = $menu_item_id;
139
    }
140
141
    if($menu_item['TYPE'] == 'lang') {
142
      $lang_string = &$lang;
143
      if(preg_match('#(\w+)(?:\[(\w+)\])?(?:\[(\w+)\])?(?:\[(\w+)\])?(?:\[(\w+)\])?#', $menu_item['ITEM'], $matches) && count($matches) > 1) {
144
        for($i = 1; $i < count($matches); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
145
          if(defined($matches[$i])) {
146
            $matches[$i] = constant($matches[$i]);
147
          }
148
          $lang_string = &$lang_string[$matches[$i]];
149
        }
150
      }
151
      $menu_item['ITEM'] = $lang_string && is_string($lang_string) ? $lang_string : "{L_{$menu_item['ITEM']}}";
152
    }
153
154
    $menu_item['ALT'] = htmlentities($menu_item['ALT']);
155
    $menu_item['TITLE'] = htmlentities($menu_item['TITLE']);
156
157
    if(!empty($menu_item['ICON'])) {
158
      if(is_string($menu_item['ICON'])) {
159
        $menu_item['ICON_PATH'] = $menu_item['ICON'];
160
      } else {
161
        $menu_item['ICON'] = $menu_item_id;
162
      }
163
    }
164
165
    $template->assign_block_vars('menu', $menu_item);
166
  }
167
}
168
169
/**
170
 * @param template $template
171
 *
172
 * @return template
173
 */
174
function tpl_render_menu($template) {
175
  global $user, $lang, $template_result, $sn_menu_admin_extra, $sn_menu_admin, $sn_menu, $sn_menu_extra;
176
177
  lng_include('admin');
178
179
//  $template = gettemplate('menu', true);
180
//  $template->assign_recursive($template_result);
181
182
  $template->assign_vars(array(
183
    'USER_AUTHLEVEL'      => $user['authlevel'],
184
    'USER_AUTHLEVEL_NAME' => $lang['user_level'][$user['authlevel']],
185
//    'USER_IMPERSONATOR'   => $template_result[F_IMPERSONATE_STATUS] != LOGIN_UNDEFINED,
186
    'PAYMENT'             => sn_module_get_active_count('payment'),
187
    'MENU_START_HIDE'     => !empty($_COOKIE[SN_COOKIE . '_menu_hidden']) || defined('SN_GOOGLE'),
188
  ));
189
190
  if(isset($template_result['MENU_CUSTOMIZE'])) {
191
    $template->assign_vars(array(
192
      'PLAYER_OPTION_MENU_SHOW_ON_BUTTON'   => classSupernova::$user_options[PLAYER_OPTION_MENU_SHOW_ON_BUTTON],
193
      'PLAYER_OPTION_MENU_HIDE_ON_BUTTON'   => classSupernova::$user_options[PLAYER_OPTION_MENU_HIDE_ON_BUTTON],
194
      'PLAYER_OPTION_MENU_HIDE_ON_LEAVE'    => classSupernova::$user_options[PLAYER_OPTION_MENU_HIDE_ON_LEAVE],
195
      'PLAYER_OPTION_MENU_UNPIN_ABSOLUTE'   => classSupernova::$user_options[PLAYER_OPTION_MENU_UNPIN_ABSOLUTE],
196
      'PLAYER_OPTION_MENU_ITEMS_AS_BUTTONS' => classSupernova::$user_options[PLAYER_OPTION_MENU_ITEMS_AS_BUTTONS],
197
      'PLAYER_OPTION_MENU_WHITE_TEXT'       => classSupernova::$user_options[PLAYER_OPTION_MENU_WHITE_TEXT],
198
      'PLAYER_OPTION_MENU_OLD'              => classSupernova::$user_options[PLAYER_OPTION_MENU_OLD],
199
      'PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON' => empty($_COOKIE[SN_COOKIE . '_menu_hidden']) && !defined('SN_GOOGLE')
200
        ? classSupernova::$user_options[PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON] : 1,
201
    ));
202
  }
203
204
  if(defined('IN_ADMIN') && IN_ADMIN === true && !empty($user['authlevel']) && $user['authlevel'] > 0) {
205
    tpl_menu_merge_extra($sn_menu_admin, $sn_menu_admin_extra);
206
    tpl_menu_assign_to_template($sn_menu_admin, $template);
207
  } else {
208
    tpl_menu_merge_extra($sn_menu, $sn_menu_extra);
209
    tpl_menu_assign_to_template($sn_menu, $template);
210
  }
211
212
  return $template;
213
}
214
215
/**
216
 * @param template|string $page
217
 * @param string          $title
218
 * @param bool|true       $isDisplayTopNav
0 ignored issues
show
Bug introduced by
There is no parameter named $isDisplayTopNav. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
219
 * @param string          $metatags
0 ignored issues
show
Bug introduced by
There is no parameter named $metatags. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
220
 * @param bool|false      $AdminPage
0 ignored issues
show
Bug introduced by
There is no parameter named $AdminPage. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
221
 * @param bool|true       $isDisplayMenu
0 ignored issues
show
Bug introduced by
There is no parameter named $isDisplayMenu. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
222
 *
223
 * @return mixed
224
 */
225
function display($page, $title = '') {
226
  if(!defined('SN_TIME_RENDER_START')) {
227
    define('SN_TIME_RENDER_START', microtime(true));
228
  }
229
230
  return sn_function_call('display', array($page, $title));
231
}
232
233
/**
234
 * @param template|string $page
235
 * @param string          $title
236
 * @param bool|true       $isDisplayTopNav
0 ignored issues
show
Bug introduced by
There is no parameter named $isDisplayTopNav. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
237
 * @param string          $metatags
0 ignored issues
show
Bug introduced by
There is no parameter named $metatags. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
238
 * @param bool|false      $AdminPage
0 ignored issues
show
Bug introduced by
There is no parameter named $AdminPage. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
239
 * @param bool|true       $isDisplayMenu
0 ignored issues
show
Bug introduced by
There is no parameter named $isDisplayMenu. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
240
 * @param bool|int|string $exitStatus - Код или сообщение выхода
0 ignored issues
show
Bug introduced by
There is no parameter named $exitStatus. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
241
 */
242
function sn_display($page, $title = '') {
243
  global $debug, $user, $planetrow, $config, $lang, $template_result, $sn_mvc, $sn_page_name;
244
245
  !empty($sn_mvc['view']['']) and execute_hooks($sn_mvc['view'][''], $page, 'view', '');
246
247
  $exitStatus = true;
248
  $template_result['LOGIN_LOGOUT'] = $inLoginLogout = defined('LOGIN_LOGOUT') && LOGIN_LOGOUT === true;
249
250
  if(is_object($page)) {
251
    isset($page->_rootref['PAGE_TITLE']) && empty($title) ? $title = $page->_rootref['PAGE_TITLE'] : false;
252
    !$title && !empty($page->_rootref['PAGE_HEADER']) ? $title = $page->_rootref['PAGE_HEADER'] : false;
253
    !isset($page->_rootref['PAGE_HEADER']) && $title ? $page->assign_var('PAGE_HEADER', $title) : false;
254
  }
255
256
  $isRenderGlobal = is_object($page) && isset($template_result['GLOBAL_DISPLAY_HEADER']) ? $template_result['GLOBAL_DISPLAY_HEADER'] : true;
257
258
  // Global header
259
  if($isRenderGlobal) {
260
    renderHeader($page, $title, $template_result, $inLoginLogout, $user, $config, $lang, $planetrow);
261
  }
262
263
  // Page content
264
  !is_array($page) ? $page = array($page) : false;
265
  $result_added = false;
266
  foreach($page as $page_item) {
267
    /**
268
     * @var template $page_item
269
     */
270
    if(!$result_added && is_object($page_item) && isset($page_item->_tpldata['result'])) {
271
      $resultTemplate = gettemplate('_result_message');
272
      $resultTemplate->_tpldata = $page_item->_tpldata;
273
      displayP($resultTemplate);
274
//      $page_item = gettemplate('_result_message', $page_item);
275
//      $temp = $page_item->files['_result_message'];
276
//      unset($page_item->files['_result_message']);
277
//      $page_item->files = array_reverse($page_item->files);
278
//      $page_item->files['_result_message'] = $temp;
279
//      $page_item->files = array_reverse($page_item->files);
280
      $result_added = true;
281
    }
282
//    $page_item->assign_recursive($template_result);
283
    displayP($page_item);
284
  }
285
286
  // Global footer
287
  if($isRenderGlobal) {
288
    renderFooter();
289
  }
290
291
  $user['authlevel'] >= 3 && $config->debug ? $debug->echo_log() : false;;
292
293
  sn_db_disconnect();
294
295
  $exitStatus and die($exitStatus === true ? 0 : $exitStatus);
296
}
297
298
/**
299
 * @param $page
300
 * @param $title
301
 * @param $template_result
302
 * @param $inLoginLogout
303
 * @param $user
304
 * @param $config
305
 * @param $lang
306
 * @param $planetrow
307
 */
308
function renderHeader($page, $title, &$template_result, $inLoginLogout, &$user, $config, $lang, $planetrow) {
309
  if(classSupernova::$headerRendered) {
310
    return;
311
  }
312
313
  ob_end_flush();
314
315
  ob_start();
316
//  pdump(microtime(true) - SN_TIME_MICRO, 'Header render started');
317
  $isDisplayTopNav = true;
318
  $isDisplayMenu = true;
319
320
  isset($template_result['GLOBAL_DISPLAY_MENU']) ? $isDisplayMenu = $template_result['GLOBAL_DISPLAY_MENU'] : false;
321
  isset($template_result['GLOBAL_DISPLAY_NAVBAR']) ? $isDisplayTopNav = $template_result['GLOBAL_DISPLAY_NAVBAR'] : false;
322
323
  // TODO: DEPRECATED! Use $template_result to turn menu and navbar or ond off!
324
  if (is_object($page)) {
325
    isset($page->_rootref['MENU']) ? $isDisplayMenu = $page->_rootref['MENU'] : false;
326
    isset($page->_rootref['NAVBAR']) ? $isDisplayTopNav = $page->_rootref['NAVBAR'] : false;
327
  }
328
329
  $inAdmin = defined('IN_ADMIN') && IN_ADMIN === true;
330
  $isDisplayMenu = ($isDisplayMenu || $inAdmin) && !isset($_COOKIE['menu_disable']);
331
  $isDisplayTopNav = $isDisplayTopNav && !$inAdmin;
332
333
  if ($inLoginLogout || empty($user['id']) || !is_numeric($user['id'])) {
334
    $isDisplayMenu = false;
335
    $isDisplayTopNav = false;
336
  }
337
338
  $user_time_diff = playerTimeDiff::user_time_diff_get();
339
  $user_time_measured_unix = intval(isset($user_time_diff[PLAYER_OPTION_TIME_DIFF_MEASURE_TIME]) ? strtotime($user_time_diff[PLAYER_OPTION_TIME_DIFF_MEASURE_TIME]) : 0);
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $user_time_measured_unix 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...
340
  $measureTimeDiff = intval(
341
    empty($user_time_diff[PLAYER_OPTION_TIME_DIFF_FORCED])
342
    &&
343
    (SN_TIME_NOW - $user_time_measured_unix > PERIOD_HOUR || $user_time_diff[PLAYER_OPTION_TIME_DIFF] == '')
344
  );
345
346
  $template = gettemplate('_page_20_header', true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a object<template>|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
347
348
  renderJavaScript();
349
350
  renderCss($inLoginLogout);
351
352
  $template->assign_vars(array(
353
    'LANG_LANGUAGE'  => $lang['LANG_INFO']['LANG_NAME_ISO2'],
354
    'LANG_ENCODING'  => 'utf-8',
355
    'LANG_DIRECTION' => $lang['LANG_INFO']['LANG_DIRECTION'],
356
357
    'SN_ROOT_VIRTUAL' => SN_ROOT_VIRTUAL,
358
359
    'ADV_SEO_META_DESCRIPTION' => $config->adv_seo_meta_description,
360
    'ADV_SEO_META_KEYWORDS'    => $config->adv_seo_meta_keywords,
361
362
    // WARNING! This can be set by page!
363
    // CHANGE CODE TO MAKE IT IMPOSSIBLE!
364
    'GLOBAL_META_TAGS'         => isset($page->_rootref['GLOBAL_META_TAGS']) ? $page->_rootref['GLOBAL_META_TAGS'] : '',
365
  ));
366
367
  $template->assign_vars(array(
368
    'GLOBAL_DISPLAY_MENU'   => $isDisplayMenu,
369
    'GLOBAL_DISPLAY_NAVBAR' => $isDisplayTopNav,
370
371
    'USER_AUTHLEVEL' => intval($user['authlevel']),
372
373
    'FONT_SIZE'                        => playerFontSize(),
374
    'FONT_SIZE_PERCENT_DEFAULT_STRING' => FONT_SIZE_PERCENT_DEFAULT_STRING,
375
376
    'SN_TIME_NOW'          => SN_TIME_NOW,
377
    'LOGIN_LOGOUT'         => $template_result['LOGIN_LOGOUT'],
378
    'GAME_MODE_CSS_PREFIX' => $config->game_mode == GAME_BLITZ ? 'blitz_' : '',
379
    'TIME_DIFF_MEASURE'    => $measureTimeDiff, // Проводить замер только если не выставлен флаг форсированного замера И (иссяк интервал замера ИЛИ замера еще не было)
380
381
    'title'                    => ($title ? "{$title} - " : '') . "{$lang['sys_server']} {$config->game_name} - {$lang['sys_supernova']}",
382
    'ADV_SEO_JAVASCRIPT'       => $config->adv_seo_javascript,
383
384
    'SOUND_ENABLED'                        => classSupernova::$user_options[PLAYER_OPTION_SOUND_ENABLED],
385
    'PLAYER_OPTION_ANIMATION_DISABLED'     => classSupernova::$user_options[PLAYER_OPTION_ANIMATION_DISABLED],
386
    'PLAYER_OPTION_PROGRESS_BARS_DISABLED' => classSupernova::$user_options[PLAYER_OPTION_PROGRESS_BARS_DISABLED],
387
388
    'IMPERSONATING'                        => !empty($template_result[F_IMPERSONATE_STATUS]) ? sprintf($lang['sys_impersonated_as'], $user['username'], $template_result[F_IMPERSONATE_OPERATOR]) : '',
389
    'PLAYER_OPTION_DESIGN_DISABLE_BORDERS' => classSupernova::$user_options[PLAYER_OPTION_DESIGN_DISABLE_BORDERS],
390
  ));
391
  $template->assign_recursive($template_result);
392
393
  if ($isDisplayMenu) {
394
    tpl_render_menu($template);
395
  }
396
397
  if ($isDisplayTopNav) {
398
    tpl_render_topnav($user, $planetrow, $template);
399
  }
400
401
  displayP($template);
402
  ob_end_flush();
403
404
  classSupernova::$headerRendered = true;
405
406
  ob_start();
407
}
408
409
/**
410
 * @internal param $config
411
 */
412
function renderFooter() {
413
  $templateFooter = gettemplate('_page_90_footer', true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a object<template>|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
414
415
  $templateFooter->assign_vars(array(
416
    'SN_TIME_NOW'  => SN_TIME_NOW,
417
    'SN_VERSION'   => SN_VERSION,
418
    'ADMIN_EMAIL'  => 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...
419
    'CURRENT_YEAR' => date('Y', SN_TIME_NOW),
420
  ));
421
422
  displayP($templateFooter);
423
}
424
425
/**
426
 * @return mixed|string
427
 */
428
function playerFontSize() {
429
  $font_size = !empty($_COOKIE[SN_COOKIE_F]) ? $_COOKIE[SN_COOKIE_F] : classSupernova::$user_options[PLAYER_OPTION_BASE_FONT_SIZE];
430
  if (strpos($font_size, '%') !== false) {
431
    // Размер шрифта в процентах
432
    $font_size = min(max(floatval($font_size), FONT_SIZE_PERCENT_MIN), FONT_SIZE_PERCENT_MAX) . '%';
433
434
    return $font_size;
435 View Code Duplication
  } elseif (strpos($font_size, 'px') !== false) {
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...
436
    // Размер шрифта в пикселях
437
    $font_size = min(max(floatval($font_size), FONT_SIZE_PIXELS_MIN), FONT_SIZE_PIXELS_MAX) . 'px';
438
439
    return $font_size;
440
  } else {
441
    // Не мышонка, не лягушка...
442
    $font_size = FONT_SIZE_PERCENT_DEFAULT_STRING;
443
444
    return $font_size;
445
  }
446
}
447
448
/**
449
 * @param $template_result
450
 * @param $is_login
451
 */
452
function tpl_global_header(&$template_result, $is_login) {
0 ignored issues
show
Unused Code introduced by
The parameter $template_result 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...
453
  renderJavaScript();
454
455
  renderCss($is_login);
456
}
457
458
/**
459
 * Checks if minified/full-size CSS file exists - and adds it if any
460
 *
461
 * @param $cssFileName
462
 * @param &$cssArray
463
 *
464
 * @return bool
465
 */
466
function cssAddFileName($cssFileName, &$cssArray) {
467
  $result = false;
468
  if(file_exists(SN_ROOT_PHYSICAL . $cssFileName . '.min.css')) {
469
    $cssArray[$cssFileName . '.min.css'] = '';
470
    $result = true;
471
  } elseif(file_exists(SN_ROOT_PHYSICAL . $cssFileName . '.css')) {
472
    $cssArray[$cssFileName . '.css'] = '';
473
    $result = true;
474
  }
475
476
  return $result;
477
}
478
479
/**
480
 * @param $is_login
481
 */
482
function renderCss($is_login) {
483
  global $sn_mvc, $sn_page_name, $template_result;
484
485
  empty($sn_mvc['css']) ? $sn_mvc['css'] = array('' => array()) : false;
486
487
  $standard_css = array();
488
  cssAddFileName('design/css/jquery-ui', $standard_css);
489
  cssAddFileName('design/css/global', $standard_css);
490
  $is_login ? cssAddFileName('design/css/login', $standard_css) : false;
491
  cssAddFileName(TEMPLATE_PATH . '/_template', $standard_css);
492
  cssAddFileName(classSupernova::$gc->theUser->getSkinPath() . 'skin', $standard_css);
0 ignored issues
show
Documentation introduced by
The property theUser 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...
493
  cssAddFileName('design/css/global_override', $standard_css);
494
495
  // Prepending standard CSS files
496
  $sn_mvc['css'][''] = array_merge($standard_css, $sn_mvc['css']['']);
497
498
  renderFileListInclude($template_result, $sn_mvc, $sn_page_name, 'css');
499
}
500
501
/**
502
 */
503
function renderJavaScript() {
504
  global $sn_mvc, $sn_page_name, $template_result;
505
506
  renderFileListInclude($template_result, $sn_mvc, $sn_page_name, 'javascript');
507
}
508
509
/**
510
 * @param array   $template_result
511
 * @param array[] $sn_mvc
512
 * @param string  $sn_page_name
513
 * @param string  $fileType - 'css' or 'javascript'
514
 */
515
function renderFileListInclude(&$template_result, &$sn_mvc, $sn_page_name, $fileType) {
516
  if (empty($sn_mvc[$fileType])) {
517
    return;
518
  }
519
520
  foreach ($sn_mvc[$fileType] as $page_name => $script_list) {
521
    if (empty($page_name) || $page_name == $sn_page_name) {
522
      foreach ($script_list as $filename => $content) {
523
        $template_result['.'][$fileType][] = array(
524
          'FILE'    => $filename,
525
          'CONTENT' => $content,
526
        );
527
      }
528
    }
529
  }
530
}
531
532
/**
533
 * @param $time
534
 * @param $event
535
 * @param $msg
536
 * @param $prefix
537
 * @param $is_decrease
538
 * @param $fleet_flying_row
539
 * @param $fleet_flying_sorter
540
 * @param $fleet_flying_events
541
 * @param $fleet_event_count
542
 */
543
function tpl_topnav_event_build_helper($time, $event, $msg, $prefix, $is_decrease, $fleet_flying_row, &$fleet_flying_sorter, &$fleet_flying_events, &$fleet_event_count) {
544
  $fleet_flying_sorter[$fleet_event_count] = $time;
545
  $fleet_flying_events[$fleet_event_count] = array(
546
    'ROW'              => $fleet_flying_row,
547
    'FLEET_ID'         => $fleet_flying_row['fleet_id'],
548
    'EVENT'            => $event,
549
    'COORDINATES'      => uni_render_coordinates($fleet_flying_row, $prefix),
550
    'COORDINATES_TYPE' => $fleet_flying_row["{$prefix}type"],
551
    'TEXT'             => "{$msg}",
552
    'DECREASE'         => $is_decrease,
553
  );
554
  $fleet_event_count++;
555
}
556
557
/**
558
 * @param template $template
559
 * @param array    $fleet_flying_list
560
 * @param string   $type
561
 */
562
function tpl_topnav_event_build(&$template, $fleet_flying_list, $type = 'fleet') {
563
  if(empty($fleet_flying_list)) {
564
    return;
565
  }
566
567
  global $lang;
568
569
  $fleet_event_count = 0;
570
  $fleet_flying_sorter = array();
571
  $fleet_flying_events = array();
572
  foreach($fleet_flying_list as &$fleet_flying_row) {
573
    $will_return = true;
574
    if($fleet_flying_row['fleet_mess'] == 0) {
575
      // cut fleets on Hold and Expedition
576
      if($fleet_flying_row['fleet_start_time'] >= SN_TIME_NOW) {
577
        $fleet_flying_row['fleet_mission'] == MT_RELOCATE ? $will_return = false : false;
578
        tpl_topnav_event_build_helper($fleet_flying_row['fleet_start_time'], EVENT_FLEET_ARRIVE, $lang['sys_event_arrive'], 'fleet_end_', !$will_return, $fleet_flying_row, $fleet_flying_sorter, $fleet_flying_events, $fleet_event_count);
579
      }
580
      if($fleet_flying_row['fleet_end_stay']) {
581
        tpl_topnav_event_build_helper($fleet_flying_row['fleet_end_stay'], EVENT_FLEET_STAY, $lang['sys_event_stay'], 'fleet_end_', false, $fleet_flying_row, $fleet_flying_sorter, $fleet_flying_events, $fleet_event_count);
582
      }
583
    }
584
    if($will_return) {
585
      tpl_topnav_event_build_helper($fleet_flying_row['fleet_end_time'], EVENT_FLEET_RETURN, $lang['sys_event_return'], 'fleet_start_', true, $fleet_flying_row, $fleet_flying_sorter, $fleet_flying_events, $fleet_event_count);
586
    }
587
  }
588
589
  asort($fleet_flying_sorter);
590
591
  $fleet_flying_count = count($fleet_flying_list);
592
  foreach($fleet_flying_sorter as $fleet_event_id => $fleet_time) {
593
    $fleet_event = &$fleet_flying_events[$fleet_event_id];
594
    $template->assign_block_vars("flying_{$type}s", array(
595
      'TIME' => max(0, $fleet_time - SN_TIME_NOW),
596
      'TEXT' => $fleet_flying_count,
597
      'HINT' => date(FMT_DATE_TIME, $fleet_time + SN_CLIENT_TIME_DIFF) . " - {$lang['sys_fleet']} {$fleet_event['TEXT']} {$fleet_event['COORDINATES']} {$lang['sys_planet_type_sh'][$fleet_event['COORDINATES_TYPE']]} {$lang['type_mission'][$fleet_event['ROW']['fleet_mission']]}",
598
    ));
599
    $fleet_event['DECREASE'] ? $fleet_flying_count-- : false;
600
  }
601
}
602
603
/**
604
 * @param array $user
605
 * @param array $planetrow
606
 * @param template $template
607
 *
608
 * @return string|template
609
 */
610
function tpl_render_topnav(&$user, $planetrow, $template) { return sn_function_call('tpl_render_topnav', array(&$user, $planetrow, $template)); }
611
612
/**
613
 * @param array $user
614
 * @param array $planetrow
615
 * @param template $template
616
 *
617
 * @return string|template
618
 */
619
function sn_tpl_render_topnav(&$user, $planetrow, $template) {
620
  global $lang, $config, $sn_module_list, $template_result, $sn_mvc;
621
622
  if(!is_array($user)) {
623
    return '';
624
  }
625
626
  $GET_mode = sys_get_param_str('mode');
627
628
  $ThisUsersPlanets = DBStaticPlanet::db_planet_list_sorted($user);
629
  foreach($ThisUsersPlanets as $CurPlanet) {
630
    if($CurPlanet['destruyed']) {
631
      continue;
632
    }
633
634
    $fleet_listx = flt_get_fleets_to_planet($CurPlanet);
635
636
    $template->assign_block_vars('topnav_planets', array(
637
      'ID'          => $CurPlanet['id'],
638
      'NAME'        => $CurPlanet['name'],
639
      'TYPE'        => $CurPlanet['planet_type'],
640
      'TYPE_TEXT'   => $lang['sys_planet_type_sh'][$CurPlanet['planet_type']],
641
      'PLIMAGE'     => $CurPlanet['image'],
642
      'FLEET_ENEMY' => $fleet_listx['enemy']['count'],
643
      'COORDS'      => uni_render_coordinates($CurPlanet),
644
      'SELECTED'    => $CurPlanet['id'] == $user['current_planet'] ? ' selected' : '',
645
    ));
646
  }
647
648
  $fleet_flying_list = tpl_get_fleets_flying($user);
649
  tpl_topnav_event_build($template, $fleet_flying_list[0]);
650
  tpl_topnav_event_build($template, $fleet_flying_list[MT_EXPLORE], 'expedition');
651
652
  que_tpl_parse($template, QUE_STRUCTURES, $user, $planetrow, null, true);
653
  que_tpl_parse($template, QUE_RESEARCH, $user, array(), null, !classSupernova::$user_options[PLAYER_OPTION_NAVBAR_RESEARCH_WIDE]);
654
  que_tpl_parse($template, SUBQUE_FLEET, $user, $planetrow, null, true);
655
656
  tpl_navbar_extra_buttons($sn_mvc, $template);
657
  tpl_navbar_render_news($template, $user, $config);
658
  tpl_navbar_render_notes($template, $user);
659
  $tutorial_enabled = PageTutorial::renderNavBar($template);
660
661
662
  $premium_lvl = mrc_get_level($user, false, UNIT_PREMIUM, true, true);
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...
663
664
  $str_date_format = "%3$02d %2$0s %1$04d {$lang['top_of_year']} %4$02d:%5$02d:%6$02d";
665
  $time_now_parsed = getdate(SN_TIME_NOW);
666
  $time_local_parsed = getdate(defined('SN_CLIENT_TIME_LOCAL') ? SN_CLIENT_TIME_LOCAL : SN_TIME_NOW);
667
668
  $template->assign_vars(array(
669
    'HALLOWEEN' => !empty($sn_module_list['event']['event_halloween_2015']) && $sn_module_list['event']['event_halloween_2015']->manifest['active'],
670
671
    'QUE_ID'   => QUE_RESEARCH,
672
    'QUE_HTML' => 'topnav',
673
674
    'RESEARCH_ONGOING' => (boolean)$user['que'],
675
676
    'TIME_TEXT'       => sprintf($str_date_format, $time_now_parsed['year'], $lang['months'][$time_now_parsed['mon']], $time_now_parsed['mday'],
677
      $time_now_parsed['hours'], $time_now_parsed['minutes'], $time_now_parsed['seconds']
678
    ),
679
    'TIME_TEXT_LOCAL' => sprintf($str_date_format, $time_local_parsed['year'], $lang['months'][$time_local_parsed['mon']], $time_local_parsed['mday'],
680
      $time_local_parsed['hours'], $time_local_parsed['minutes'], $time_local_parsed['seconds']
681
    ),
682
683
    'GAME_BLITZ_REGISTER'             => $config->game_blitz_register,
684
    'GAME_BLITZ_REGISTER_TEXT'        => $lang['sys_blitz_registration_mode_list'][$config->game_blitz_register],
685
    'BLITZ_REGISTER_OPEN'             => $config->game_blitz_register == BLITZ_REGISTER_OPEN,
686
    'BLITZ_REGISTER_CLOSED'           => $config->game_blitz_register == BLITZ_REGISTER_CLOSED,
687
    'BLITZ_REGISTER_SHOW_LOGIN'       => $config->game_blitz_register == BLITZ_REGISTER_SHOW_LOGIN,
688
    'BLITZ_REGISTER_DISCLOSURE_NAMES' => $config->game_blitz_register == BLITZ_REGISTER_DISCLOSURE_NAMES,
689
    'GAME_BLITZ'                      => $config->game_mode == GAME_BLITZ,
690
691
    'USERS_ONLINE'  => $config->var_online_user_count,
692
    'USERS_TOTAL'   => $config->users_amount,
693
    'USER_RANK'     => $user['total_rank'],
694
    'USER_NICK'     => $user['username'],
695
    'USER_AVATAR'   => $user['avatar'],
696
    'USER_AVATARID' => $user['id'],
697
    'USER_PREMIUM'  => $premium_lvl,
698
    'USER_RACE'     => $user['player_race'],
699
700
    'TOPNAV_CURRENT_PLANET'       => $user['current_planet'],
701
    'TOPNAV_CURRENT_PLANET_NAME'  => uni_render_planet_full($planetrow), // htmlspecialchars($planetrow['name']),
702
    'TOPNAV_CURRENT_PLANET_IMAGE' => $planetrow['image'],
703
    'TOPNAV_COLONIES_CURRENT'     => get_player_current_colonies($user),
704
    'TOPNAV_COLONIES_MAX'         => get_player_max_colonies($user),
705
    'NAVBAR_MODE'                 => $GET_mode,
706
707
    'TOPNAV_DARK_MATTER'            => mrc_get_level($user, '', RES_DARK_MATTER),
0 ignored issues
show
Documentation introduced by
'' is of type string, 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...
708
    'TOPNAV_DARK_MATTER_TEXT'       => pretty_number(mrc_get_level($user, '', RES_DARK_MATTER)),
0 ignored issues
show
Documentation introduced by
'' is of type string, 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...
709
    'TOPNAV_DARK_MATTER_PLAIN'      => mrc_get_level($user, '', RES_DARK_MATTER, false, true),
0 ignored issues
show
Documentation introduced by
'' is of type string, 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...
710
    'TOPNAV_DARK_MATTER_PLAIN_TEXT' => pretty_number(mrc_get_level($user, '', RES_DARK_MATTER, false, true)),
0 ignored issues
show
Documentation introduced by
'' is of type string, 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...
711
    'TOPNAV_METAMATTER'             => mrc_get_level($user, '', RES_METAMATTER),
0 ignored issues
show
Documentation introduced by
'' is of type string, 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...
712
    'TOPNAV_METAMATTER_TEXT'        => pretty_number(mrc_get_level($user, '', RES_METAMATTER)),
0 ignored issues
show
Documentation introduced by
'' is of type string, 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...
713
714
    // TODO ГРЯЗНЫЙ ХАК!!!
715
    'TOPNAV_PAYMENT'                => sn_module_get_active_count('payment') && !defined('SN_GOOGLE'),
716
717
    'TOPNAV_MESSAGES_ADMIN'    => $user['msg_admin'],
718
    'TOPNAV_MESSAGES_PLAYER'   => $user['mnl_joueur'],
719
    'TOPNAV_MESSAGES_ALLIANCE' => $user['mnl_alliance'],
720
    'TOPNAV_MESSAGES_ATTACK'   => $user['mnl_attaque'],
721
    'TOPNAV_MESSAGES_ALL'      => $user['new_message'],
722
723
    'TOPNAV_FLEETS_FLYING'      => count($fleet_flying_list[0]),
724
    'TOPNAV_FLEETS_TOTAL'       => GetMaxFleets($user),
725
    'TOPNAV_EXPEDITIONS_FLYING' => count($fleet_flying_list[MT_EXPLORE]),
726
    'TOPNAV_EXPEDITIONS_TOTAL'  => get_player_max_expeditons($user),
727
728
    'TOPNAV_QUEST_COMPLETE' => get_quest_amount_complete($user['id']),
729
    'TOPNAV_QUEST_IN_PROGRESS' => get_quest_amount_in_progress($user['id']),
730
731
    'GAME_NEWS_OVERVIEW'       => $config->game_news_overview,
732
    'GAME_RESEARCH_DISABLED'   => defined('GAME_RESEARCH_DISABLED') && GAME_RESEARCH_DISABLED,
733
    'GAME_DEFENSE_DISABLED'    => defined('GAME_DEFENSE_DISABLED') && GAME_DEFENSE_DISABLED,
734
    'GAME_STRUCTURES_DISABLED' => defined('GAME_STRUCTURES_DISABLED') && GAME_STRUCTURES_DISABLED,
735
    'GAME_HANGAR_DISABLED'     => defined('GAME_HANGAR_DISABLED') && GAME_HANGAR_DISABLED,
736
737
    'PLAYER_OPTION_NAVBAR_PLANET_VERTICAL'        => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_PLANET_VERTICAL],
738
    'PLAYER_OPTION_NAVBAR_PLANET_OLD'             => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_PLANET_OLD],
739
    'PLAYER_OPTION_NAVBAR_PLANET_DISABLE_STORAGE' => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_PLANET_DISABLE_STORAGE],
740
    'PLAYER_OPTION_NAVBAR_DISABLE_RESEARCH'       => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_RESEARCH],
741
    'PLAYER_OPTION_NAVBAR_DISABLE_PLANET'         => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_PLANET],
742
    'PLAYER_OPTION_NAVBAR_DISABLE_HANGAR'         => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_HANGAR],
743
    'PLAYER_OPTION_NAVBAR_DISABLE_FLYING_FLEETS'  => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_FLYING_FLEETS],
744
    'PLAYER_OPTION_NAVBAR_DISABLE_EXPEDITIONS'    => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_EXPEDITIONS],
745
    'PLAYER_OPTION_NAVBAR_DISABLE_QUESTS'         => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_QUESTS],
746
    'PLAYER_OPTION_NAVBAR_DISABLE_META_MATTER'    => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_META_MATTER],
747
    'PLAYER_OPTION_NAVBAR_RESEARCH_WIDE'          => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_RESEARCH_WIDE],
748
749
    'TUTORIAL_ENABLED' => $tutorial_enabled,
750
751
    'SUBQUE_FLEET' => SUBQUE_FLEET,
752
    'QUE_RESEARCH' => QUE_RESEARCH,
753
    'QUE_STRUCTURES' => QUE_STRUCTURES,
754
  ));
755
756
  if((defined('SN_RENDER_NAVBAR_PLANET') && SN_RENDER_NAVBAR_PLANET === true) || ($user['option_list'][OPT_INTERFACE]['opt_int_navbar_resource_force'] && SN_RENDER_NAVBAR_PLANET !== false)) {
757
    tpl_set_resource_info($template, $planetrow);
758
    $template->assign_vars(array(
759
      'SN_RENDER_NAVBAR_PLANET' => true,
760
      'SN_NAVBAR_HIDE_FLEETS'   => true,
761
    ));
762
  }
763
764
  return $template;
765
}
766
767
/**
768
 * @param $template
769
 * @param $user
770
 */
771
function tpl_navbar_render_notes(&$template, &$user) {
772
  $notes_query = doquery("SELECT * FROM {{notes}} WHERE `owner` = {$user['id']} AND `sticky` = 1 ORDER BY priority DESC, time DESC");
773
  while ($note_row = db_fetch($notes_query)) {
774
    note_assign($template, $note_row);
775
  }
776
}
777
778
/**
779
 * @param $template
780
 * @param $user
781
 * @param $config
782
 */
783
function tpl_navbar_render_news(&$template, &$user, $config) {
784
  if ($config->game_news_overview) {
785
    $user_last_read_safe = intval($user['news_lastread']);
786
    $newsSql = "WHERE UNIX_TIMESTAMP(`tsTimeStamp`) >= {$user_last_read_safe}";
787
    $newsOverviewShowSeconds = intval($config->game_news_overview_show);
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $newsOverviewShowSeconds 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...
788
    if ($newsOverviewShowSeconds) {
789
      $newsSql .= " AND `tsTimeStamp` >= DATE_SUB(NOW(), INTERVAL {$newsOverviewShowSeconds} SECOND)";
790
    }
791
    nws_render($template, $newsSql, $config->game_news_overview);
792
  }
793
}
794
795
/**
796
 * @param array $sn_mvc
797
 * @param string $blockName
798
 *
799
 * @return array|false
800
 */
801
function render_button_block(&$sn_mvc, $blockName) {
802
  $result = false;
803
804
  if (!empty($sn_mvc[$blockName]) && is_array($sn_mvc[$blockName])) {
805
    foreach ($sn_mvc[$blockName] as $navbar_button_image => $navbar_button_url) {
806
      $result[] = array(
807
        'IMAGE'        => $navbar_button_image,
808
        'URL_RELATIVE' => $navbar_button_url,
809
      );
810
    }
811
812
    $result = array(
813
      '.' => array(
814
        $blockName =>
815
          $result
816
      ),
817
    );
818
  }
819
820
  return $result;
821
}
822
823
/**
824
 * @param array $sn_mvc
825
 * @param template $template
826
 */
827
function tpl_navbar_extra_buttons(&$sn_mvc, $template) {
828
  ($block = render_button_block($sn_mvc, 'navbar_prefix_button')) ? $template->assign_recursive($block) : false;
829
  ($block = render_button_block($sn_mvc, 'navbar_main_button')) ? $template->assign_recursive($block) : false;
830
}
831
832
/**
833
 * @param template|string $template
834
 */
835
function templateRenderToHtml($template) {
836
  $output = null;
0 ignored issues
show
Unused Code introduced by
$output is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
837
838
  ob_start();
839
  displayP($template);
840
  $output = ob_get_contents();
841
  ob_end_clean();
842
843
  return $output;
844
}
845
846
847
/**
848
 * @param template|string $template
849
 */
850
function displayP($template) {
851
  if(is_object($template)) {
852
    if(empty($template->parsed)) {
853
      parsetemplate($template);
854
    }
855
856
    foreach($template->files as $section => $filename) {
857
      $template->display($section);
858
    }
859
  } else {
860
    print($template);
861
  }
862
}
863
864
/**
865
 * @param template $template
866
 * @param array|bool      $array
867
 *
868
 * @return mixed
869
 */
870
function templateObjectParse($template, $array = false) {
871
  global $user;
872
873
  if(!empty($array) && is_array($array)) {
874
    foreach($array as $key => $data) {
875
      $template->assign_var($key, $data);
876
    }
877
  }
878
879
  $template->assign_vars(array(
880
    'SN_TIME_NOW'    => SN_TIME_NOW,
881
    'USER_AUTHLEVEL' => isset($user['authlevel']) ? $user['authlevel'] : -1,
882
    'SN_GOOGLE'      => defined('SN_GOOGLE'),
883
  ));
884
885
  $template->parsed = true;
886
887
  return $template;
888
}
889
890
/**
891
 * @param template|string $template
892
 * @param array|bool      $array
893
 *
894
 * @return mixed
895
 */
896
function parsetemplate($template, $array = false) {
897
  if(is_object($template)) {
898
    return templateObjectParse($template, $array);
899
  } else {
900
    $search[] = '#\{L_([a-z0-9\-_]*?)\[([a-z0-9\-_]*?)\]\}#Ssie';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$search was never initialized. Although not strictly required by PHP, it is generally a good practice to add $search = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
901
    $replace[] = '((isset($lang[\'\1\'][\'\2\'])) ? $lang[\'\1\'][\'\2\'] : \'{L_\1[\2]}\');';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$replace was never initialized. Although not strictly required by PHP, it is generally a good practice to add $replace = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
902
903
    $search[] = '#\{L_([a-z0-9\-_]*?)\}#Ssie';
904
    $replace[] = '((isset($lang[\'\1\'])) ? $lang[\'\1\'] : \'{L_\1}\');';
905
906
    $search[] = '#\{([a-z0-9\-_]*?)\}#Ssie';
907
    $replace[] = '((isset($array[\'\1\'])) ? $array[\'\1\'] : \'{\1}\');';
908
909
    return preg_replace($search, $replace, $template);
910
  }
911
}
912
913
/**
914
 * @param array|string  $files
915
 * @param template|null $template
916
 * @param string|null   $template_path - path to template
917
 *
918
 * @return template
919
 */
920
function gettemplate($files, $template = null, $template_path = null) {
921
  global $sn_mvc, $sn_page_name;
922
923
  $template_ex = '.tpl.html';
924
925
  is_string($files) ? $files = array(basename($files) => $files) : false;
926
927
  !is_object($template) ? $template = new template(SN_ROOT_PHYSICAL) : false;
928
  //$template->set_custom_template($template_path ? $template_path : TEMPLATE_DIR, TEMPLATE_NAME, TEMPLATE_DIR);
929
930
  $templateName = getSkinPathTemplate(classSupernova::$gc->theUser->getSkinPath());
0 ignored issues
show
Documentation introduced by
The property theUser 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...
931
  !$template_path || !is_string($template_path) ? $template_path = SN_ROOT_PHYSICAL . 'design/templates/' : false;
0 ignored issues
show
Bug Best Practice introduced by
The expression $template_path of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
932
  $template->set_custom_template($template_path . $templateName . '/', $templateName, TEMPLATE_DIR);
0 ignored issues
show
Documentation introduced by
TEMPLATE_DIR 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...
933
934
  // TODO ГРЯЗНЫЙ ХАК! Это нужно, что бы по возможности перезаписать инфу из языковых пакетов модулей там, где она была перезаписана раньше инфой из основного пакета. Почему?
935
  //  - сначала грузятся модули и их языковые пакеты
936
  //  - затем по ходу дела ОСНОВНОЙ языковой пакет может перезаписать данные из МОДУЛЬНОГО языкового пакета
937
  // Поэтому и нужен этот грязный хак
938
  // В норме же - страницы заявляют сами, какие им пакеты нужны. Так что сначала всегда должны грузится основные языковые пакеты, а уже ПОВЕРХ них - пакеты модулей
939
  !empty($sn_mvc['i18n']['']) ? lng_load_i18n($sn_mvc['i18n']['']) : false;
940
  $sn_page_name ? lng_load_i18n($sn_mvc['i18n'][$sn_page_name]) : false;
941
942
  foreach($files as &$filename) {
943
    $filename = $filename . $template_ex;
944
  }
945
946
  $template->set_filenames($files);
947
948
  return $template;
949
}
950
951
/**
952
 * @param template $template
953
 */
954
function tpl_login_lang(&$template) {
955
  global $language;
956
957
  $url_params = array();
958
959
  $language ? $url_params[] = "lang={$language}" : false;
960
961
  ($id_ref = sys_get_param_id('id_ref')) ? $url_params[] = "id_ref={$id_ref}" : false;
962
963
  $template->assign_vars($q = array(
964
    'LANG'     => $language ? $language : '',
965
    'referral' => $id_ref ? '&id_ref=' . $id_ref : '',
966
967
    'REQUEST_PARAMS' => !empty($url_params) ? '?' . implode('&', $url_params) : '',// "?lang={$language}" . ($id_ref ? "&id_ref={$id_ref}" : ''),
968
    'FILENAME'       => basename($_SERVER['PHP_SELF']),
969
  ));
970
971
  foreach(lng_get_list() as $lng_id => $lng_data) {
972
    if(isset($lng_data['LANG_VARIANTS']) && is_array($lng_data['LANG_VARIANTS'])) {
973
      foreach($lng_data['LANG_VARIANTS'] as $lang_variant) {
974
        $lng_data1 = $lng_data;
975
        $lng_data1 = array_merge($lng_data1, $lang_variant);
976
        $template->assign_block_vars('language', $lng_data1);
977
      }
978
    } else {
979
      $template->assign_block_vars('language', $lng_data);
980
    }
981
  }
982
}
983
984
/**
985
 * @param array $user
986
 *
987
 * @return array
988
 */
989
function tpl_get_fleets_flying(&$user) {
990
  $fleet_flying_list = array();
991
992
  $fleet_flying_list[0] = fleet_list_by_owner_id($user['id']);
993
  foreach($fleet_flying_list[0] as $fleet_id => $fleet_flying_row) {
994
    $fleet_flying_list[$fleet_flying_row['fleet_mission']][$fleet_id] = &$fleet_flying_list[0][$fleet_id];
995
  }
996
997
  return $fleet_flying_list;
998
}
999
1000
/**
1001
 * @param template $template
1002
 * @param array    $planet
1003
 * @param int      $que_type
1004
 *
1005
 * @return int
1006
 */
1007
function tpl_assign_hangar(&$template, $planet, $que_type) {
1008
  $que = que_get($planet['id_owner'], $planet['id'], $que_type);
0 ignored issues
show
Documentation introduced by
$que_type is of type integer, 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...
1009
  $que = $que['ques'][$que_type][$planet['id_owner']][$planet['id']];
1010
1011
  $que_length = 0;
1012
  if(!empty($que)) {
1013
    foreach($que as $que_item) {
1014
      $template->assign_block_vars('que', que_tpl_parse_element($que_item));
1015
    }
1016
    $que_length = count($que);
1017
  }
1018
1019
  return $que_length;
1020
}
1021
1022
/**
1023
 * @param template $template
1024
 * @param array    $density_price_chart
1025
 * @param int      $user_dark_matter
1026
 */
1027
function tpl_planet_density_info(&$template, &$density_price_chart, $user_dark_matter) {
1028
  global $lang;
1029
1030
  foreach($density_price_chart as $density_price_index => &$density_price_data) {
1031
    $density_cost = $density_price_data;
1032
    $density_number_style = pretty_number($density_cost, true, $user_dark_matter, false, false);
0 ignored issues
show
Documentation introduced by
$user_dark_matter is of type integer|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...
1033
1034
    $density_price_data = array(
1035
      'COST'            => $density_cost,
1036
      'COST_TEXT'       => $density_number_style['text'],
1037
      'COST_TEXT_CLASS' => $density_number_style['class'],
1038
      'REST'            => $user_dark_matter - $density_cost,
1039
      'ID'              => $density_price_index,
1040
      'TEXT'            => $lang['uni_planet_density_types'][$density_price_index],
1041
    );
1042
    $template->assign_block_vars('densities', $density_price_data);
1043
  }
1044
}
1045
1046
/**
1047
 * @param template $template
1048
 * @param string   $name
1049
 * @param mixed    $values
1050
 */
1051
function tpl_assign_select(&$template, $name, $values) {
1052
  !is_array($values) ? $values = array($values => $values) : false;
1053
1054
  foreach($values as $key => $value) {
1055
    $template->assign_block_vars($name, array(
1056
      'KEY'   => htmlentities($key, ENT_COMPAT, 'UTF-8'),
1057
      'VALUE' => htmlentities($value, ENT_COMPAT, 'UTF-8'),
1058
    ));
1059
  }
1060
}
1061
1062
/**
1063
 * Renders unit bonus from unit data
1064
 *
1065
 * @param array $unitInfo
1066
 *
1067
 * @return string
1068
 */
1069
function tpl_render_unit_bonus_data($unitInfo) {
1070
  $strBonus = tplAddPlus($unitInfo['bonus']);
1071
  switch ($unitInfo['bonus_type']) {
1072
    case BONUS_PERCENT:
1073
      $strBonus = "{$strBonus}% ";
1074
    break;
1075
1076
    case BONUS_ABILITY:
1077
      $strBonus = '';
1078
    break;
1079
1080
    case BONUS_ADD:
1081
    default:
1082
    break;
1083
  }
1084
1085
  return $strBonus;
1086
}
1087
1088
/**
1089
 * Converts number to string then adds "+" sign for positive AND ZERO numbers
1090
 *
1091
 * @param float $value
1092
 *
1093
 * @return string
1094
 */
1095
function tplAddPlus($value) {
1096
  return ($value >= 0 ? '+' : '') . $value;
1097
}
1098
1099
1100
/**
1101
 * Convert number to prettified string then adds "+" sign for positive AND ZERO numbers
1102
 *
1103
 * @param float $value
1104
 *
1105
 * @return string
1106
 */
1107
function tplPrettyPlus($value) {
1108
  return ($value >= 0 ? '+' : '') . pretty_number($value);
1109
}
1110