Passed
Branch trunk (7dc288)
by SuperNova.WS
06:07
created

tpl_planet_density_info()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 3
dl 0
loc 14
rs 9.4285
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;
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...
33
34
  if (empty($title)) {
35
    $title = $lang['sys_error'];
36
  }
37
38
  $template = gettemplate('message_body', true);
39
40
  $template_result['GLOBAL_DISPLAY_NAVBAR'] = $showHeader;
41
42
  $template->assign_vars(array(
43
//    'GLOBAL_DISPLAY_NAVBAR' => $showHeader,
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
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;
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...
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;
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...
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;
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...
176
177
  lng_include('admin');
178
179
//  $template = gettemplate('menu', true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
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,
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...
186
    'PAYMENT'             => sn_module::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
219
 * @param string          $metatags
220
 * @param bool|false      $AdminPage
221
 * @param bool|true       $isDisplayMenu
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
237
 * @param string          $metatags
238
 * @param bool|false      $AdminPage
239
 * @param bool|true       $isDisplayMenu
240
 * @param bool|int|string $exitStatus - Код или сообщение выхода
241
 */
242
function sn_display($page, $title = '') {
243
  global $debug, $user, $planetrow, $config, $lang, $template_result, $sn_mvc, $sn_page_name;
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...
244
245
  !empty($sn_mvc['view']['']) and execute_hooks($sn_mvc['view'][''], $page, 'view', '');
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
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;
0 ignored issues
show
introduced by
The condition ! is_array($page) can never be false.
Loading history...
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);
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
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);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
283
    displayP($page_item);
284
  }
285
286
  if(is_array($template_result[TEMPLATE_EXTRA_ARRAY]) && !empty($template_result[TEMPLATE_EXTRA_ARRAY])) {
287
    foreach($template_result[TEMPLATE_EXTRA_ARRAY] as $extraName => $extraTemplate) {
288
      /**
289
       * @var template $extraTemplate
290
       */
291
      displayP($extraTemplate);
292
    }
293
  }
294
295
  // Global footer
296
  if ($isRenderGlobal) {
297
    renderFooter();
298
  }
299
300
  $user['authlevel'] >= 3 && $config->debug ? $debug->echo_log() : false;;
301
302
  sn_db_disconnect();
303
304
  $exitStatus and die($exitStatus === true ? 0 : $exitStatus);
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...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
introduced by
The condition $exitStatus === true can never be false.
Loading history...
305
}
306
307
/**
308
 * @param $page
309
 * @param $title
310
 * @param $template_result
311
 * @param $inLoginLogout
312
 * @param $user
313
 * @param $config
314
 * @param $lang
315
 * @param $planetrow
316
 */
317
function renderHeader($page, $title, &$template_result, $inLoginLogout, &$user, $config, $lang, $planetrow) {
318
  if (classSupernova::$headerRendered) {
319
    return;
320
  }
321
322
  ob_end_flush();
323
324
  ob_start();
325
//  pdump(microtime(true) - SN_TIME_MICRO, 'Header render started');
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
326
  $isDisplayTopNav = true;
327
  $isDisplayMenu = true;
328
329
  isset($template_result['GLOBAL_DISPLAY_MENU']) ? $isDisplayMenu = $template_result['GLOBAL_DISPLAY_MENU'] : false;
330
  isset($template_result['GLOBAL_DISPLAY_NAVBAR']) ? $isDisplayTopNav = $template_result['GLOBAL_DISPLAY_NAVBAR'] : false;
331
332
  // TODO: DEPRECATED! Use $template_result to turn menu and navbar or ond off!
333
  if (is_object($page)) {
334
    isset($page->_rootref['MENU']) ? $isDisplayMenu = $page->_rootref['MENU'] : false;
335
    isset($page->_rootref['NAVBAR']) ? $isDisplayTopNav = $page->_rootref['NAVBAR'] : false;
336
  }
337
338
  $inAdmin = defined('IN_ADMIN') && IN_ADMIN === true;
339
  $isDisplayMenu = ($isDisplayMenu || $inAdmin) && !isset($_COOKIE['menu_disable']);
340
  $isDisplayTopNav = $isDisplayTopNav && !$inAdmin;
341
342
  if ($inLoginLogout || empty($user['id']) || !is_numeric($user['id'])) {
343
    $isDisplayMenu = false;
344
    $isDisplayTopNav = false;
345
  }
346
347
  $user_time_diff = playerTimeDiff::user_time_diff_get();
348
  $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);
349
  $measureTimeDiff = intval(
350
    empty($user_time_diff[PLAYER_OPTION_TIME_DIFF_FORCED])
351
    &&
352
    (SN_TIME_NOW - $user_time_measured_unix > PERIOD_HOUR || $user_time_diff[PLAYER_OPTION_TIME_DIFF] == '')
353
  );
354
355
  $template = gettemplate('_page_20_header', true);
356
357
  renderJavaScript();
358
359
  renderCss($inLoginLogout);
360
361
  $template->assign_vars(array(
362
    'LANG_LANGUAGE'  => $lang['LANG_INFO']['LANG_NAME_ISO2'],
363
    'LANG_ENCODING'  => 'utf-8',
364
    'LANG_DIRECTION' => $lang['LANG_INFO']['LANG_DIRECTION'],
365
366
    'SN_ROOT_VIRTUAL' => SN_ROOT_VIRTUAL,
367
368
    'ADV_SEO_META_DESCRIPTION' => $config->adv_seo_meta_description,
369
    'ADV_SEO_META_KEYWORDS'    => $config->adv_seo_meta_keywords,
370
371
    // WARNING! This can be set by page!
372
    // CHANGE CODE TO MAKE IT IMPOSSIBLE!
373
    'GLOBAL_META_TAGS'         => isset($page->_rootref['GLOBAL_META_TAGS']) ? $page->_rootref['GLOBAL_META_TAGS'] : '',
374
  ));
375
376
  $template->assign_vars(array(
377
    'GLOBAL_DISPLAY_MENU'   => $isDisplayMenu,
378
    'GLOBAL_DISPLAY_NAVBAR' => $isDisplayTopNav,
379
380
    'USER_AUTHLEVEL' => intval($user['authlevel']),
381
382
    'FONT_SIZE'                        => playerFontSize(),
383
    'FONT_SIZE_PERCENT_DEFAULT_STRING' => FONT_SIZE_PERCENT_DEFAULT_STRING,
384
385
    'SN_TIME_NOW'          => SN_TIME_NOW,
386
    'LOGIN_LOGOUT'         => $template_result['LOGIN_LOGOUT'],
387
    'GAME_MODE_CSS_PREFIX' => $config->game_mode == GAME_BLITZ ? 'blitz_' : '',
388
    'TIME_DIFF_MEASURE'    => $measureTimeDiff, // Проводить замер только если не выставлен флаг форсированного замера И (иссяк интервал замера ИЛИ замера еще не было)
389
390
    'title'              => ($title ? "{$title} - " : '') . "{$lang['sys_server']} {$config->game_name} - {$lang['sys_supernova']}",
391
    'ADV_SEO_JAVASCRIPT' => $config->adv_seo_javascript,
392
393
    'SOUND_ENABLED'                        => classSupernova::$user_options[PLAYER_OPTION_SOUND_ENABLED],
394
    'PLAYER_OPTION_ANIMATION_DISABLED'     => classSupernova::$user_options[PLAYER_OPTION_ANIMATION_DISABLED],
395
    'PLAYER_OPTION_PROGRESS_BARS_DISABLED' => classSupernova::$user_options[PLAYER_OPTION_PROGRESS_BARS_DISABLED],
396
397
    'IMPERSONATING'                        => !empty($template_result[F_IMPERSONATE_STATUS]) ? sprintf($lang['sys_impersonated_as'], $user['username'], $template_result[F_IMPERSONATE_OPERATOR]) : '',
398
    'PLAYER_OPTION_DESIGN_DISABLE_BORDERS' => classSupernova::$user_options[PLAYER_OPTION_DESIGN_DISABLE_BORDERS],
399
  ));
400
  $template->assign_recursive($template_result);
401
402
  if ($isDisplayMenu) {
403
    tpl_render_menu($template);
404
  }
405
406
  if ($isDisplayTopNav) {
407
    tpl_render_topnav($user, $planetrow, $template);
408
  }
409
410
  displayP($template);
411
  ob_end_flush();
412
413
  classSupernova::$headerRendered = true;
414
415
  ob_start();
416
}
417
418
/**
419
 */
420
function renderFooter() {
421
  $templateFooter = gettemplate('_page_90_footer', true);
422
423
  $templateFooter->assign_vars(array(
424
    'SN_TIME_NOW'  => SN_TIME_NOW,
425
    'SN_VERSION'   => SN_VERSION,
426
    'ADMIN_EMAIL'  => classSupernova::$config->game_adminEmail,
427
    'CURRENT_YEAR' => date('Y', SN_TIME_NOW),
428
  ));
429
430
  displayP($templateFooter);
431
}
432
433
/**
434
 * @return mixed|string
435
 */
436
function playerFontSize() {
437
  $font_size = !empty($_COOKIE[SN_COOKIE_F]) ? $_COOKIE[SN_COOKIE_F] : classSupernova::$user_options[PLAYER_OPTION_BASE_FONT_SIZE];
438
  if (strpos($font_size, '%') !== false) {
439
    // Размер шрифта в процентах
440
    $font_size = min(max(floatval($font_size), FONT_SIZE_PERCENT_MIN), FONT_SIZE_PERCENT_MAX) . '%';
441
442
    return $font_size;
443
  } elseif (strpos($font_size, 'px') !== false) {
444
    // Размер шрифта в пикселях
445
    $font_size = min(max(floatval($font_size), FONT_SIZE_PIXELS_MIN), FONT_SIZE_PIXELS_MAX) . 'px';
446
447
    return $font_size;
448
  } else {
449
    // Не мышонка, не лягушка...
450
    $font_size = FONT_SIZE_PERCENT_DEFAULT_STRING;
451
452
    return $font_size;
453
  }
454
}
455
456
/**
457
 * @param $template_result
458
 * @param $is_login
459
 */
460
function tpl_global_header(&$template_result, $is_login) {
461
  renderJavaScript();
462
463
  renderCss($is_login);
464
}
465
466
/**
467
 * Checks if minified/full-size CSS file exists - and adds it if any
468
 *
469
 * @param $cssFileName
470
 * @param &$cssArray
471
 *
472
 * @return bool
473
 */
474
function cssAddFileName($cssFileName, &$cssArray) {
475
  $result = false;
476
  if (file_exists(SN_ROOT_PHYSICAL . $cssFileName . '.min.css')) {
477
    $cssArray[$cssFileName . '.min.css'] = '';
478
    $result = true;
479
  } elseif (file_exists(SN_ROOT_PHYSICAL . $cssFileName . '.css')) {
480
    $cssArray[$cssFileName . '.css'] = '';
481
    $result = true;
482
  }
483
484
  return $result;
485
}
486
487
/**
488
 * @param $is_login
489
 */
490
function renderCss($is_login) {
491
  global $sn_mvc, $sn_page_name, $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...
492
493
  empty($sn_mvc['css']) ? $sn_mvc['css'] = array('' => array()) : false;
494
495
  $standard_css = array();
496
  cssAddFileName('design/css/jquery-ui', $standard_css);
497
  cssAddFileName('design/css/global', $standard_css);
498
  $is_login ? cssAddFileName('design/css/login', $standard_css) : false;
499
  cssAddFileName(TEMPLATE_PATH . '/_template', $standard_css);
500
  cssAddFileName(classSupernova::$gc->theUser->getSkinPath() . 'skin', $standard_css);
501
  cssAddFileName('design/css/global_override', $standard_css);
502
503
  // Prepending standard CSS files
504
  $sn_mvc['css'][''] = array_merge($standard_css, $sn_mvc['css']['']);
505
506
  renderFileListInclude($template_result, $sn_mvc, $sn_page_name, 'css');
507
}
508
509
/**
510
 */
511
function renderJavaScript() {
512
  global $sn_mvc, $sn_page_name, $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...
513
514
  renderFileListInclude($template_result, $sn_mvc, $sn_page_name, 'javascript');
515
}
516
517
/**
518
 * @param array   $template_result
519
 * @param array[] $sn_mvc
520
 * @param string  $sn_page_name
521
 * @param string  $fileType - 'css' or 'javascript'
522
 */
523
function renderFileListInclude(&$template_result, &$sn_mvc, $sn_page_name, $fileType) {
524
  if (empty($sn_mvc[$fileType])) {
525
    return;
526
  }
527
528
  foreach ($sn_mvc[$fileType] as $page_name => $script_list) {
529
    if (empty($page_name) || $page_name == $sn_page_name) {
530
      foreach ($script_list as $filename => $content) {
531
        $template_result['.'][$fileType][] = array(
532
          'FILE'    => $filename,
533
          'CONTENT' => $content,
534
        );
535
      }
536
    }
537
  }
538
}
539
540
/**
541
 * @param $time
542
 * @param $event
543
 * @param $msg
544
 * @param $prefix
545
 * @param $is_decrease
546
 * @param $fleet_flying_row
547
 * @param $fleet_flying_sorter
548
 * @param $fleet_flying_events
549
 * @param $fleet_event_count
550
 */
551
function tpl_topnav_event_build_helper($time, $event, $msg, $prefix, $is_decrease, $fleet_flying_row, &$fleet_flying_sorter, &$fleet_flying_events, &$fleet_event_count) {
552
  $fleet_flying_sorter[$fleet_event_count] = $time;
553
  $fleet_flying_events[$fleet_event_count] = array(
554
    'ROW'              => $fleet_flying_row,
555
    'FLEET_ID'         => $fleet_flying_row['fleet_id'],
556
    'EVENT'            => $event,
557
    'COORDINATES'      => uni_render_coordinates($fleet_flying_row, $prefix),
558
    'COORDINATES_TYPE' => $fleet_flying_row["{$prefix}type"],
559
    'TEXT'             => "{$msg}",
560
    'DECREASE'         => $is_decrease,
561
  );
562
  $fleet_event_count++;
563
}
564
565
/**
566
 * @param template $template
567
 * @param array    $fleet_flying_list
568
 * @param string   $type
569
 */
570
function tpl_topnav_event_build(&$template, $fleet_flying_list, $type = 'fleet') {
571
  if (empty($fleet_flying_list)) {
572
    return;
573
  }
574
575
  global $lang;
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...
576
577
  $fleet_event_count = 0;
578
  $fleet_flying_sorter = array();
579
  $fleet_flying_events = array();
580
  foreach ($fleet_flying_list as &$fleet_flying_row) {
581
    $will_return = true;
582
    if ($fleet_flying_row['fleet_mess'] == 0) {
583
      // cut fleets on Hold and Expedition
584
      if ($fleet_flying_row['fleet_start_time'] >= SN_TIME_NOW) {
585
        $fleet_flying_row['fleet_mission'] == MT_RELOCATE ? $will_return = false : false;
586
        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);
587
      }
588
      if ($fleet_flying_row['fleet_end_stay']) {
589
        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);
590
      }
591
    }
592
    if ($will_return) {
593
      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);
594
    }
595
  }
596
597
  asort($fleet_flying_sorter);
598
599
  $fleet_flying_count = count($fleet_flying_list);
600
  foreach ($fleet_flying_sorter as $fleet_event_id => $fleet_time) {
601
    $fleet_event = &$fleet_flying_events[$fleet_event_id];
602
    $template->assign_block_vars("flying_{$type}s", array(
603
      'TIME' => max(0, $fleet_time - SN_TIME_NOW),
604
      'TEXT' => $fleet_flying_count,
605
      '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']]}",
606
    ));
607
    $fleet_event['DECREASE'] ? $fleet_flying_count-- : false;
608
  }
609
}
610
611
/**
612
 * @param array    $user
613
 * @param array    $planetrow
614
 * @param template $template
615
 *
616
 * @return string|template
617
 */
618
function tpl_render_topnav(&$user, $planetrow, $template) { return sn_function_call('tpl_render_topnav', array(&$user, $planetrow, $template)); }
619
620
/**
621
 * @param array    $user
622
 * @param array    $planetrow
623
 * @param template $template
624
 *
625
 * @return string|template
626
 */
627
function sn_tpl_render_topnav(&$user, $planetrow, $template) {
628
  global $lang, $config, $sn_module_list, $template_result, $sn_mvc;
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...
629
630
  if (!is_array($user)) {
631
    return '';
632
  }
633
634
  $GET_mode = sys_get_param_str('mode');
635
636
  $ThisUsersPlanets = DBStaticPlanet::db_planet_list_sorted($user);
637
  foreach ($ThisUsersPlanets as $CurPlanet) {
638
    if ($CurPlanet['destruyed']) {
639
      continue;
640
    }
641
642
    $fleet_listx = flt_get_fleets_to_planet($CurPlanet);
643
644
    $template->assign_block_vars('topnav_planets', array(
645
      'ID'          => $CurPlanet['id'],
646
      'NAME'        => $CurPlanet['name'],
647
      'TYPE'        => $CurPlanet['planet_type'],
648
      'TYPE_TEXT'   => $lang['sys_planet_type_sh'][$CurPlanet['planet_type']],
649
      'PLIMAGE'     => $CurPlanet['image'],
650
      'FLEET_ENEMY' => $fleet_listx['enemy']['count'],
651
      'COORDS'      => uni_render_coordinates($CurPlanet),
652
      'SELECTED'    => $CurPlanet['id'] == $user['current_planet'] ? ' selected' : '',
653
    ));
654
  }
655
656
  $fleet_flying_list = tpl_get_fleets_flying($user);
657
  tpl_topnav_event_build($template, $fleet_flying_list[0]);
658
  tpl_topnav_event_build($template, $fleet_flying_list[MT_EXPLORE], 'expedition');
659
660
  que_tpl_parse($template, QUE_STRUCTURES, $user, $planetrow, null, true);
661
  que_tpl_parse($template, QUE_RESEARCH, $user, array(), null, !classSupernova::$user_options[PLAYER_OPTION_NAVBAR_RESEARCH_WIDE]);
662
  que_tpl_parse($template, SUBQUE_FLEET, $user, $planetrow, null, true);
663
664
  tpl_navbar_extra_buttons($sn_mvc, $template);
665
  tpl_navbar_render_news($template, $user, $config);
666
  tpl_navbar_render_notes($template, $user);
667
  $tutorial_enabled = PageTutorial::renderNavBar($template);
668
669
670
  $premium_lvl = mrc_get_level($user, false, UNIT_PREMIUM, true, true);
671
672
  $str_date_format = "%3$02d %2$0s %1$04d {$lang['top_of_year']} %4$02d:%5$02d:%6$02d";
673
  $time_now_parsed = getdate(SN_TIME_NOW);
674
  $time_local_parsed = getdate(defined('SN_CLIENT_TIME_LOCAL') ? SN_CLIENT_TIME_LOCAL : SN_TIME_NOW);
675
676
  $template->assign_vars(array(
677
    'HALLOWEEN' => !empty($sn_module_list['event']['event_halloween_2015']) && $sn_module_list['event']['event_halloween_2015']->manifest['active'],
678
679
    'QUE_ID'   => QUE_RESEARCH,
680
    'QUE_HTML' => 'topnav',
681
682
    'RESEARCH_ONGOING' => (boolean)$user['que'],
683
684
    'TIME_TEXT'       => sprintf($str_date_format, $time_now_parsed['year'], $lang['months'][$time_now_parsed['mon']], $time_now_parsed['mday'],
685
      $time_now_parsed['hours'], $time_now_parsed['minutes'], $time_now_parsed['seconds']
686
    ),
687
    'TIME_TEXT_LOCAL' => sprintf($str_date_format, $time_local_parsed['year'], $lang['months'][$time_local_parsed['mon']], $time_local_parsed['mday'],
688
      $time_local_parsed['hours'], $time_local_parsed['minutes'], $time_local_parsed['seconds']
689
    ),
690
691
    'GAME_BLITZ_REGISTER'             => $config->game_blitz_register,
692
    'GAME_BLITZ_REGISTER_TEXT'        => $lang['sys_blitz_registration_mode_list'][$config->game_blitz_register],
693
    'BLITZ_REGISTER_OPEN'             => $config->game_blitz_register == BLITZ_REGISTER_OPEN,
694
    'BLITZ_REGISTER_CLOSED'           => $config->game_blitz_register == BLITZ_REGISTER_CLOSED,
695
    'BLITZ_REGISTER_SHOW_LOGIN'       => $config->game_blitz_register == BLITZ_REGISTER_SHOW_LOGIN,
696
    'BLITZ_REGISTER_DISCLOSURE_NAMES' => $config->game_blitz_register == BLITZ_REGISTER_DISCLOSURE_NAMES,
697
    'GAME_BLITZ'                      => $config->game_mode == GAME_BLITZ,
698
699
    'USERS_ONLINE'  => $config->var_online_user_count,
700
    'USERS_TOTAL'   => $config->users_amount,
701
    'USER_RANK'     => $user['total_rank'],
702
    'USER_NICK'     => $user['username'],
703
    'USER_AVATAR'   => $user['avatar'],
704
    'USER_AVATARID' => $user['id'],
705
    'USER_PREMIUM'  => $premium_lvl,
706
    'USER_RACE'     => $user['player_race'],
707
708
    'TOPNAV_CURRENT_PLANET'       => $user['current_planet'],
709
    'TOPNAV_CURRENT_PLANET_NAME'  => uni_render_planet_full($planetrow), // htmlspecialchars($planetrow['name']),
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% 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...
710
    'TOPNAV_CURRENT_PLANET_IMAGE' => $planetrow['image'],
711
    'TOPNAV_COLONIES_CURRENT'     => get_player_current_colonies($user),
712
    'TOPNAV_COLONIES_MAX'         => get_player_max_colonies($user),
713
    'NAVBAR_MODE'                 => $GET_mode,
714
715
    'TOPNAV_DARK_MATTER'            => mrc_get_level($user, '', RES_DARK_MATTER),
716
    'TOPNAV_DARK_MATTER_TEXT'       => HelperString::numberFloorAndFormat(mrc_get_level($user, '', RES_DARK_MATTER)),
717
    'TOPNAV_DARK_MATTER_PLAIN'      => mrc_get_level($user, '', RES_DARK_MATTER, false, true),
718
    'TOPNAV_DARK_MATTER_PLAIN_TEXT' => HelperString::numberFloorAndFormat(mrc_get_level($user, '', RES_DARK_MATTER, false, true)),
719
    'TOPNAV_METAMATTER'             => mrc_get_level($user, '', RES_METAMATTER),
720
    'TOPNAV_METAMATTER_TEXT'        => HelperString::numberFloorAndFormat(mrc_get_level($user, '', RES_METAMATTER)),
721
722
    // TODO ГРЯЗНЫЙ ХАК!!!
723
    'TOPNAV_PAYMENT'                => sn_module::sn_module_get_active_count('payment') && !defined('SN_GOOGLE'),
724
725
    'TOPNAV_MESSAGES_ADMIN'    => $user['msg_admin'],
726
    'TOPNAV_MESSAGES_PLAYER'   => $user['mnl_joueur'],
727
    'TOPNAV_MESSAGES_ALLIANCE' => $user['mnl_alliance'],
728
    'TOPNAV_MESSAGES_ATTACK'   => $user['mnl_attaque'],
729
    'TOPNAV_MESSAGES_ALL'      => $user['new_message'],
730
731
    'TOPNAV_FLEETS_FLYING'      => count($fleet_flying_list[0]),
732
    'TOPNAV_FLEETS_TOTAL'       => GetMaxFleets($user),
733
    'TOPNAV_EXPEDITIONS_FLYING' => count($fleet_flying_list[MT_EXPLORE]),
734
    'TOPNAV_EXPEDITIONS_TOTAL'  => get_player_max_expeditons($user),
735
736
    'TOPNAV_QUEST_COMPLETE'    => get_quest_amount_complete($user['id']),
737
    'TOPNAV_QUEST_IN_PROGRESS' => get_quest_amount_in_progress($user['id']),
738
739
    'GAME_NEWS_OVERVIEW'       => $config->game_news_overview,
740
    'GAME_RESEARCH_DISABLED'   => defined('GAME_RESEARCH_DISABLED') && GAME_RESEARCH_DISABLED,
741
    'GAME_DEFENSE_DISABLED'    => defined('GAME_DEFENSE_DISABLED') && GAME_DEFENSE_DISABLED,
742
    'GAME_STRUCTURES_DISABLED' => defined('GAME_STRUCTURES_DISABLED') && GAME_STRUCTURES_DISABLED,
743
    'GAME_HANGAR_DISABLED'     => defined('GAME_HANGAR_DISABLED') && GAME_HANGAR_DISABLED,
744
745
    'PLAYER_OPTION_NAVBAR_PLANET_VERTICAL'        => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_PLANET_VERTICAL],
746
    'PLAYER_OPTION_NAVBAR_PLANET_OLD'             => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_PLANET_OLD],
747
    'PLAYER_OPTION_NAVBAR_PLANET_DISABLE_STORAGE' => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_PLANET_DISABLE_STORAGE],
748
    'PLAYER_OPTION_NAVBAR_DISABLE_RESEARCH'       => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_RESEARCH],
749
    'PLAYER_OPTION_NAVBAR_DISABLE_PLANET'         => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_PLANET],
750
    'PLAYER_OPTION_NAVBAR_DISABLE_HANGAR'         => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_HANGAR],
751
    'PLAYER_OPTION_NAVBAR_DISABLE_FLYING_FLEETS'  => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_FLYING_FLEETS],
752
    'PLAYER_OPTION_NAVBAR_DISABLE_EXPEDITIONS'    => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_EXPEDITIONS],
753
    'PLAYER_OPTION_NAVBAR_DISABLE_QUESTS'         => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_QUESTS],
754
    'PLAYER_OPTION_NAVBAR_DISABLE_META_MATTER'    => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_META_MATTER],
755
    'PLAYER_OPTION_NAVBAR_RESEARCH_WIDE'          => classSupernova::$user_options[PLAYER_OPTION_NAVBAR_RESEARCH_WIDE],
756
757
    'TUTORIAL_ENABLED' => $tutorial_enabled,
758
759
    'SUBQUE_FLEET'   => SUBQUE_FLEET,
760
    'QUE_RESEARCH'   => QUE_RESEARCH,
761
    'QUE_STRUCTURES' => QUE_STRUCTURES,
762
  ));
763
764
  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)) {
765
    tpl_set_resource_info($template, $planetrow);
766
    $template->assign_vars(array(
767
      'SN_RENDER_NAVBAR_PLANET' => true,
768
      'SN_NAVBAR_HIDE_FLEETS'   => true,
769
    ));
770
  }
771
772
  return $template;
773
}
774
775
/**
776
 * @param $template
777
 * @param $user
778
 */
779
function tpl_navbar_render_notes(&$template, &$user) {
780
  $notes_query = doquery("SELECT * FROM {{notes}} WHERE `owner` = {$user['id']} AND `sticky` = 1 ORDER BY priority DESC, time DESC");
781
  while ($note_row = db_fetch($notes_query)) {
782
    \Note\Note::note_assign($template, $note_row);
783
  }
784
}
785
786
/**
787
 * @param $template
788
 * @param $user
789
 * @param $config
790
 */
791
function tpl_navbar_render_news(&$template, &$user, $config) {
792
  if ($config->game_news_overview) {
793
    $user_last_read_safe = intval($user['news_lastread']);
794
    $newsSql = "WHERE UNIX_TIMESTAMP(`tsTimeStamp`) >= {$user_last_read_safe}";
795
    $newsOverviewShowSeconds = intval($config->game_news_overview_show);
796
    if ($newsOverviewShowSeconds) {
797
      $newsSql .= " AND `tsTimeStamp` >= DATE_SUB(NOW(), INTERVAL {$newsOverviewShowSeconds} SECOND)";
798
    }
799
    nws_render($template, $newsSql, $config->game_news_overview);
800
  }
801
}
802
803
/**
804
 * @param array  $sn_mvc
805
 * @param string $blockName
806
 *
807
 * @return array|false
808
 */
809
function render_button_block(&$sn_mvc, $blockName) {
810
  $result = false;
811
812
  if (!empty($sn_mvc[$blockName]) && is_array($sn_mvc[$blockName])) {
813
    foreach ($sn_mvc[$blockName] as $navbar_button_image => $navbar_button_url) {
814
      $result[] = array(
815
        'IMAGE'        => $navbar_button_image,
816
        'URL_RELATIVE' => $navbar_button_url,
817
      );
818
    }
819
820
    $result = array(
821
      '.' => array(
822
        $blockName =>
823
          $result
824
      ),
825
    );
826
  }
827
828
  return $result;
829
}
830
831
/**
832
 * @param array    $sn_mvc
833
 * @param template $template
834
 */
835
function tpl_navbar_extra_buttons(&$sn_mvc, $template) {
836
  ($block = render_button_block($sn_mvc, 'navbar_prefix_button')) ? $template->assign_recursive($block) : false;
837
  ($block = render_button_block($sn_mvc, 'navbar_main_button')) ? $template->assign_recursive($block) : false;
838
}
839
840
/**
841
 * @param template|string $template
842
 */
843
function templateRenderToHtml($template) {
844
  $output = null;
845
846
  ob_start();
847
  displayP($template);
848
  $output = ob_get_contents();
849
  ob_end_clean();
850
851
  return $output;
852
}
853
854
855
/**
856
 * @param template|string $template
857
 */
858
function displayP($template) {
859
  if (is_object($template)) {
860
    if (empty($template->parsed)) {
861
      parsetemplate($template);
862
    }
863
864
    foreach ($template->files as $section => $filename) {
865
      $template->display($section);
866
    }
867
  } else {
868
    print($template);
869
  }
870
}
871
872
/**
873
 * @param template   $template
874
 * @param array|bool $array
875
 *
876
 * @return mixed
877
 */
878
function templateObjectParse($template, $array = false) {
879
  global $user;
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...
880
881
  if (!empty($array) && is_array($array)) {
882
    foreach ($array as $key => $data) {
883
      $template->assign_var($key, $data);
884
    }
885
  }
886
887
  $template->assign_vars(array(
888
    'SN_TIME_NOW'    => SN_TIME_NOW,
889
    'USER_AUTHLEVEL' => isset($user['authlevel']) ? $user['authlevel'] : -1,
890
    'SN_GOOGLE'      => defined('SN_GOOGLE'),
891
  ));
892
893
  $template->parsed = true;
894
895
  return $template;
896
}
897
898
/**
899
 * @param template|string $template
900
 * @param array|bool      $array
901
 *
902
 * @return mixed
903
 */
904
function parsetemplate($template, $array = false) {
905
  if (is_object($template)) {
906
    return templateObjectParse($template, $array);
907
  } else {
908
    $search[] = '#\{L_([a-z0-9\-_]*?)\[([a-z0-9\-_]*?)\]\}#Ssie';
909
    $replace[] = '((isset($lang[\'\1\'][\'\2\'])) ? $lang[\'\1\'][\'\2\'] : \'{L_\1[\2]}\');';
910
911
    $search[] = '#\{L_([a-z0-9\-_]*?)\}#Ssie';
912
    $replace[] = '((isset($lang[\'\1\'])) ? $lang[\'\1\'] : \'{L_\1}\');';
913
914
    $search[] = '#\{([a-z0-9\-_]*?)\}#Ssie';
915
    $replace[] = '((isset($array[\'\1\'])) ? $array[\'\1\'] : \'{\1}\');';
916
917
    return preg_replace($search, $replace, $template);
918
  }
919
}
920
921
/**
922
 * @param array|string  $files
923
 * @param template|null $template
924
 * @param string|null   $template_path - path to template
925
 *
926
 * @return template
927
 */
928
function gettemplate($files, $template = null, $template_path = null) {
929
  global $sn_mvc, $sn_page_name;
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...
930
931
  $template_ex = '.tpl.html';
932
933
  is_string($files) ? $files = array(basename($files) => $files) : false;
934
935
  !is_object($template) ? $template = new template(SN_ROOT_PHYSICAL) : false;
936
  //$template->set_custom_template($template_path ? $template_path : TEMPLATE_DIR, TEMPLATE_NAME, TEMPLATE_DIR);
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
937
938
  $templateName = getSkinPathTemplate(classSupernova::$gc->theUser->getSkinPath());
939
  !$template_path || !is_string($template_path) ? $template_path = SN_ROOT_PHYSICAL . 'design/templates/' : false;
940
  $template->set_custom_template($template_path . $templateName . '/', $templateName, TEMPLATE_DIR);
941
942
  // TODO ГРЯЗНЫЙ ХАК! Это нужно, что бы по возможности перезаписать инфу из языковых пакетов модулей там, где она была перезаписана раньше инфой из основного пакета. Почему?
943
  //  - сначала грузятся модули и их языковые пакеты
944
  //  - затем по ходу дела ОСНОВНОЙ языковой пакет может перезаписать данные из МОДУЛЬНОГО языкового пакета
945
  // Поэтому и нужен этот грязный хак
946
  // В норме же - страницы заявляют сами, какие им пакеты нужны. Так что сначала всегда должны грузится основные языковые пакеты, а уже ПОВЕРХ них - пакеты модулей
947
  !empty($sn_mvc['i18n']['']) ? lng_load_i18n($sn_mvc['i18n']['']) : false;
948
  $sn_page_name ? lng_load_i18n($sn_mvc['i18n'][$sn_page_name]) : false;
949
950
  foreach ($files as &$filename) {
951
    $filename = $filename . $template_ex;
952
  }
953
954
  $template->set_filenames($files);
955
956
  return $template;
957
}
958
959
/**
960
 * @param template $template
961
 */
962
function tpl_login_lang(&$template) {
963
  global $language;
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...
964
965
  $url_params = array();
966
967
  $language ? $url_params[] = "lang={$language}" : false;
968
969
  ($id_ref = sys_get_param_id('id_ref')) ? $url_params[] = "id_ref={$id_ref}" : false;
970
971
  $template->assign_vars($q = array(
972
    'LANG'     => $language ? $language : '',
973
    'referral' => $id_ref ? '&id_ref=' . $id_ref : '',
974
975
    'REQUEST_PARAMS' => !empty($url_params) ? '?' . implode('&', $url_params) : '',// "?lang={$language}" . ($id_ref ? "&id_ref={$id_ref}" : ''),
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
976
    'FILENAME'       => basename($_SERVER['PHP_SELF']),
977
  ));
978
979
  foreach (lng_get_list() as $lng_id => $lng_data) {
980
    if (isset($lng_data['LANG_VARIANTS']) && is_array($lng_data['LANG_VARIANTS'])) {
981
      foreach ($lng_data['LANG_VARIANTS'] as $lang_variant) {
982
        $lng_data1 = $lng_data;
983
        $lng_data1 = array_merge($lng_data1, $lang_variant);
984
        $template->assign_block_vars('language', $lng_data1);
985
      }
986
    } else {
987
      $template->assign_block_vars('language', $lng_data);
988
    }
989
  }
990
}
991
992
/**
993
 * @param array $user
994
 *
995
 * @return array
996
 */
997
function tpl_get_fleets_flying(&$user) {
998
  $fleet_flying_list = array();
999
1000
  $fleet_flying_list[0] = fleet_list_by_owner_id($user['id']);
1001
  foreach ($fleet_flying_list[0] as $fleet_id => $fleet_flying_row) {
1002
    $fleet_flying_list[$fleet_flying_row['fleet_mission']][$fleet_id] = &$fleet_flying_list[0][$fleet_id];
1003
  }
1004
1005
  return $fleet_flying_list;
1006
}
1007
1008
/**
1009
 * @param template $template
1010
 * @param string   $name
1011
 * @param mixed    $values
1012
 */
1013
function tpl_assign_select(&$template, $name, $values) {
1014
  !is_array($values) ? $values = array($values => $values) : false;
1015
1016
  foreach ($values as $key => $value) {
1017
    $template->assign_block_vars($name, array(
1018
      'KEY'   => htmlentities($key, ENT_COMPAT, 'UTF-8'),
1019
      'VALUE' => htmlentities($value, ENT_COMPAT, 'UTF-8'),
1020
    ));
1021
  }
1022
}
1023
1024
/**
1025
 * Renders unit bonus from unit data
1026
 *
1027
 * @param array $unitInfo
1028
 *
1029
 * @return string
1030
 */
1031
function tpl_render_unit_bonus_data($unitInfo) {
1032
  $strBonus = tplAddPlus($unitInfo[P_BONUS_VALUE]);
1033
  switch ($unitInfo[P_BONUS_TYPE]) {
1034
    case BONUS_PERCENT:
1035
      $strBonus = "{$strBonus}% ";
1036
    break;
1037
1038
    case BONUS_ABILITY:
1039
      $strBonus = '';
1040
    break;
1041
1042
    case BONUS_ADD:
1043
    default:
1044
    break;
1045
  }
1046
1047
  return $strBonus;
1048
}
1049
1050
/**
1051
 * Converts number to string then adds "+" sign for positive AND ZERO numbers
1052
 *
1053
 * @param float $value
1054
 *
1055
 * @return string
1056
 */
1057
function tplAddPlus($value) {
1058
  return ($value >= 0 ? '+' : '') . $value;
1059
}
1060
1061
1062
/**
1063
 * Convert number to prettified string then adds "+" sign for positive AND ZERO numbers
1064
 *
1065
 * @param float $value
1066
 *
1067
 * @return string
1068
 */
1069
function tplPrettyPlus($value) {
1070
  return ($value >= 0 ? '+' : '') . HelperString::numberFloorAndFormat($value);
1071
}
1072