Completed
Push — trunk ( d06df9...f48ee3 )
by SuperNova.WS
11:23
created

SnTemplate::display()   F

Complexity

Conditions 32
Paths > 20000

Size

Total Lines 101
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 32
eloc 49
c 1
b 0
f 0
nc 10782720
nop 2
dl 0
loc 101
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
use Common\Traits\TSingleton;
4
use Core\GlobalContainer;
5
use Fleet\DbFleetStatic;
6
use Note\Note;
7
use \Pages\PageTutorial;
8
use Planet\DBStaticPlanet;
9
use Player\playerTimeDiff;
10
use Template\TemplateMeta;
11
12
/**
13
 * Template manager
14
 */
15
class SnTemplate {
16
17
  use TSingleton;
18
19
  const TPL_HTML = '.tpl.html';
20
  /**
21
   * Partial path to templates root
22
   */
23
  const SN_TEMPLATES_PARTIAL_PATH = 'design/templates/';
24
  const SN_TEMPLATE_NAME_DEFAULT = 'OpenGame';
25
  const P_CONTENT = '__RENDERED_CONTENT';
26
27
  /**
28
   * @param template|string $template
29
   */
30
  public static function displayP($template) {
31
    if (is_object($template)) {
32
      if (empty($template->parsed)) {
33
        self::parsetemplate($template);
34
      }
35
36
      foreach ($template->files as $section => $filename) {
37
        $template->display($section);
38
      }
39
    } else {
40
      print($template);
41
    }
42
  }
43
44
  /**
45
   * @param template|string $template
46
   * @param array|bool      $array
47
   *
48
   * @return mixed
49
   */
50
  public static function parsetemplate($template, $array = false) {
51
    if (is_object($template)) {
52
      return self::templateObjectParse($template, $array);
53
    } else {
54
      $search[]  = '#\{L_([a-z0-9\-_]*?)\[([a-z0-9\-_]*?)\]\}#Ssie';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$search was never initialized. Although not strictly required by PHP, it is generally a good practice to add $search = array(); before regardless.
Loading history...
55
      $replace[] = '((isset($lang[\'\1\'][\'\2\'])) ? $lang[\'\1\'][\'\2\'] : \'{L_\1[\2]}\');';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$replace was never initialized. Although not strictly required by PHP, it is generally a good practice to add $replace = array(); before regardless.
Loading history...
56
57
      $search[]  = '#\{L_([a-z0-9\-_]*?)\}#Ssie';
58
      $replace[] = '((isset($lang[\'\1\'])) ? $lang[\'\1\'] : \'{L_\1}\');';
59
60
      $search[]  = '#\{([a-z0-9\-_]*?)\}#Ssie';
61
      $replace[] = '((isset($array[\'\1\'])) ? $array[\'\1\'] : \'{\1}\');';
62
63
      return preg_replace($search, $replace, $template);
64
    }
65
  }
66
67
  /**
68
   * @param template   $template
69
   * @param array|bool $array
70
   *
71
   * @return mixed
72
   */
73
  public static function templateObjectParse($template, $array = false) {
74
    global $user;
75
76
    if (!empty($array) && is_array($array)) {
77
      foreach ($array as $key => $data) {
78
        $template->assign_var($key, $data);
79
      }
80
    }
81
82
    $template->assign_vars(array(
83
      'SN_TIME_NOW'      => SN_TIME_NOW,
84
      'SN_TEMPLATE_NAME' => SnTemplate::getPlayerTemplateName(),
85
      'USER_AUTHLEVEL'   => isset($user['authlevel']) ? $user['authlevel'] : -1,
86
      'SN_GOOGLE'        => defined('SN_GOOGLE'),
87
    ));
88
89
    $template->parsed = true;
90
91
    return $template;
92
  }
93
94
  /**
95
   * @param array $menu
96
   * @param array $extra
97
   */
98
  public static function tpl_menu_merge_extra(&$menu, &$extra) {
99
    if (!is_array($extra) || !is_array($menu) || empty($menu)) {
0 ignored issues
show
introduced by
The condition is_array($menu) is always true.
Loading history...
introduced by
The condition is_array($extra) is always true.
Loading history...
100
      return;
101
    }
102
103
    foreach ($extra as $menu_item_id => $menu_item) {
104
      if (empty($menu_item['LOCATION'])) {
105
        $menu[$menu_item_id] = $menu_item;
106
        continue;
107
      }
108
109
      $item_location = $menu_item['LOCATION'];
110
      unset($menu_item['LOCATION']);
111
112
      $is_positioned = $item_location[0];
113
      if ($is_positioned == '+' || $is_positioned == '-') {
114
        $item_location = substr($item_location, 1);
115
      } else {
116
        $is_positioned = '';
117
      }
118
119
      if ($item_location) {
120
        $menu_keys       = array_keys($menu);
121
        $insert_position = array_search($item_location, $menu_keys);
122
        if ($insert_position === false) {
123
          $insert_position = count($menu) - 1;
124
          $is_positioned   = '+';
125
          $item_location   = '';
126
        }
127
      } else {
128
        $insert_position = $is_positioned == '-' ? 0 : count($menu);
129
      }
130
131
      $insert_position     += $is_positioned == '+' ? 1 : 0;
132
      $spliced             = array_splice($menu, $insert_position, count($menu) - $insert_position);
133
      $menu[$menu_item_id] = $menu_item;
134
135
      if (!$is_positioned && $item_location) {
136
        unset($spliced[$item_location]);
137
      }
138
      $menu = array_merge($menu, $spliced);
139
    }
140
141
    $extra = array();
142
  }
143
144
  /**
145
   * @param array $menu
146
   *
147
   * @return array
148
   */
149
  public static function tpl_menu_adminize($menu) {
150
    !is_array($menu) ? $menu = [] : false;
0 ignored issues
show
introduced by
The condition is_array($menu) is always true.
Loading history...
151
152
    foreach ($menu as &$menuItem) {
153
      if (!isset($menuItem[MENU_FIELD_AUTH_LEVEL])) {
154
        $menuItem[MENU_FIELD_AUTH_LEVEL] = AUTH_LEVEL_ADMINISTRATOR;
155
      }
156
    }
157
158
    return $menu;
159
  }
160
161
  /**
162
   * @param array    $sn_menu
163
   * @param template $template
164
   */
165
  public static function tpl_menu_assign_to_template(&$sn_menu, &$template) {
166
    global $lang;
167
168
    if (empty($sn_menu) || !is_array($sn_menu)) {
169
      return;
170
    }
171
172
    foreach ($sn_menu as $menu_item_id => $menu_item) {
173
      if (!$menu_item) {
174
        continue;
175
      }
176
177
      if (is_string($menu_item_id)) {
178
        $menu_item['ID'] = $menu_item_id;
179
      }
180
181
      if ($menu_item['TYPE'] == 'lang') {
182
        $lang_string = &$lang;
183
        if (preg_match('#(\w+)(?:\[(\w+)\])?(?:\[(\w+)\])?(?:\[(\w+)\])?(?:\[(\w+)\])?#', $menu_item['ITEM'], $matches) && count($matches) > 1) {
184
          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...
185
            if (defined($matches[$i])) {
186
              $matches[$i] = constant($matches[$i]);
187
            }
188
            $lang_string = &$lang_string[$matches[$i]];
189
          }
190
        }
191
        $menu_item['ITEM'] = $lang_string && is_string($lang_string) ? $lang_string : "{L_{$menu_item['ITEM']}}";
192
      }
193
194
      $menu_item['ALT']   = htmlentities($menu_item['ALT']);
195
      $menu_item['TITLE'] = htmlentities($menu_item['TITLE']);
196
197
      if (!empty($menu_item['ICON'])) {
198
        if (is_string($menu_item['ICON'])) {
199
          $menu_item['ICON_PATH'] = $menu_item['ICON'];
200
        } else {
201
          $menu_item['ICON'] = $menu_item_id;
202
        }
203
      }
204
205
      $template->assign_block_vars('menu', $menu_item);
206
    }
207
  }
208
209
  /**
210
   * @param template $template
211
   *
212
   * @return template
213
   */
214
  public static function tpl_render_menu($template) {
215
    global $user, $lang, $template_result, $sn_menu_admin_extra, $sn_menu_admin, $sn_menu, $sn_menu_extra;
216
217
    lng_include('admin');
218
219
    $template->assign_vars(array(
220
      'USER_AUTHLEVEL'      => $user['authlevel'],
221
      'USER_AUTHLEVEL_NAME' => $lang['user_level'][$user['authlevel']],
222
      'PAYMENT'             => SN::$gc->modules->countModulesInGroup('payment'),
223
      'MENU_START_HIDE'     => !empty($_COOKIE[SN_COOKIE . '_menu_hidden']) || defined('SN_GOOGLE'),
224
    ));
225
226
    if (isset($template_result['MENU_CUSTOMIZE'])) {
227
      $template->assign_vars(array(
228
        'PLAYER_OPTION_MENU_SHOW_ON_BUTTON'   => SN::$user_options[PLAYER_OPTION_MENU_SHOW_ON_BUTTON],
229
        'PLAYER_OPTION_MENU_HIDE_ON_BUTTON'   => SN::$user_options[PLAYER_OPTION_MENU_HIDE_ON_BUTTON],
230
        'PLAYER_OPTION_MENU_HIDE_ON_LEAVE'    => SN::$user_options[PLAYER_OPTION_MENU_HIDE_ON_LEAVE],
231
        'PLAYER_OPTION_MENU_UNPIN_ABSOLUTE'   => SN::$user_options[PLAYER_OPTION_MENU_UNPIN_ABSOLUTE],
232
        'PLAYER_OPTION_MENU_ITEMS_AS_BUTTONS' => SN::$user_options[PLAYER_OPTION_MENU_ITEMS_AS_BUTTONS],
233
        'PLAYER_OPTION_MENU_WHITE_TEXT'       => SN::$user_options[PLAYER_OPTION_MENU_WHITE_TEXT],
234
        'PLAYER_OPTION_MENU_OLD'              => SN::$user_options[PLAYER_OPTION_MENU_OLD],
235
        'PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON' => empty($_COOKIE[SN_COOKIE . '_menu_hidden']) && !defined('SN_GOOGLE')
236
          ? SN::$user_options[PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON] : 1,
237
      ));
238
    }
239
240
    if (defined('IN_ADMIN') && IN_ADMIN === true && !empty($user['authlevel']) && $user['authlevel'] > 0) {
241
      SnTemplate::tpl_menu_merge_extra($sn_menu_admin, $sn_menu_admin_extra);
242
      $sn_menu_admin = SnTemplate::tpl_menu_adminize($sn_menu_admin);
243
      SnTemplate::tpl_menu_assign_to_template($sn_menu_admin, $template);
244
    } else {
245
      SnTemplate::tpl_menu_merge_extra($sn_menu, $sn_menu_extra);
246
      SnTemplate::tpl_menu_assign_to_template($sn_menu, $template);
247
    }
248
249
    return $template;
250
  }
251
252
  /**
253
   * @param template[] $page
254
   * @param array      $template_result
255
   */
256
  public static function renderFooter($page, $template_result) {
257
    $templateFooter = self::gettemplate('_page_90_footer', true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type null|template expected by parameter $template of SnTemplate::gettemplate(). ( Ignorable by Annotation )

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

257
    $templateFooter = self::gettemplate('_page_90_footer', /** @scrutinizer ignore-type */ true);
Loading history...
258
259
    $templateFooter->assign_vars([
260
      'SN_TIME_NOW'      => SN_TIME_NOW,
261
      'SN_VERSION'       => SN_VERSION,
262
      'ADMIN_EMAIL'      => SN::$config->game_adminEmail,
263
      'CURRENT_YEAR'     => date('Y', SN_TIME_NOW),
264
      'DB_PATCH_VERSION' => dbPatchGetCurrent(),
265
    ]);
266
267
    /**
268
     * @var template $page_item
269
     */
270
    if (
271
      is_object($page[0])
272
      &&
273
      (
274
        isset($page[0]->_tpldata['page_hint'])
275
        ||
276
        isset($page[0]->_rootref['PAGE_HINT'])
277
        ||
278
        !empty($template_result['.']['page_hint'])
279
        ||
280
        !empty($template_result['PAGE_HINT'])
281
      )
282
    ) {
283
      $resultTemplate = self::gettemplate('page_hint');
284
285
      $resultTemplate->_tpldata = &$page[0]->_tpldata;
286
      $resultTemplate->_rootref = &$page[0]->_rootref;
287
      $resultTemplate->assign_recursive($template_result);
288
289
      SnTemplate::displayP($resultTemplate);
290
    }
291
292
    SnTemplate::displayP($templateFooter);
293
  }
294
295
  /**
296
   * @param $page
297
   * @param $title
298
   * @param $template_result
299
   * @param $inLoginLogout
300
   * @param $user
301
   * @param $config
302
   * @param $lang
303
   * @param $planetrow
304
   */
305
  public static function renderHeader($page, $title, &$template_result, $inLoginLogout, &$user, $config, $lang, $planetrow, $renderedContent) {
306
    if (SN::$headerRendered) {
307
      return;
308
    }
309
310
    ob_end_flush();
311
312
    ob_start();
313
//  pdump(microtime(true) - SN_TIME_MICRO, 'Header render started');
314
    $isDisplayTopNav = true;
315
    $isDisplayMenu   = true;
316
317
    isset($template_result['GLOBAL_DISPLAY_MENU']) ? $isDisplayMenu = $template_result['GLOBAL_DISPLAY_MENU'] : false;
318
    isset($template_result['GLOBAL_DISPLAY_NAVBAR']) ? $isDisplayTopNav = $template_result['GLOBAL_DISPLAY_NAVBAR'] : false;
319
320
    // TODO: DEPRECATED! Use $template_result to turn menu and navbar or ond off!
321
    if (is_object($page)) {
322
      isset($page->_rootref['MENU']) ? $isDisplayMenu = $page->_rootref['MENU'] : false;
323
      isset($page->_rootref['NAVBAR']) ? $isDisplayTopNav = $page->_rootref['NAVBAR'] : false;
324
    }
325
326
    $inAdmin         = defined('IN_ADMIN') && IN_ADMIN === true;
327
    $isDisplayMenu   = ($isDisplayMenu || $inAdmin) && !isset($_COOKIE['menu_disable']);
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: $isDisplayMenu = ($isDis...inAdmin && ! IssetNode), Probably Intended Meaning: $isDisplayMenu = $isDisp...inAdmin && ! IssetNode)
Loading history...
328
    $isDisplayTopNav = $isDisplayTopNav && !$inAdmin;
329
330
    if ($inLoginLogout || empty($user['id']) || !is_numeric($user['id'])) {
331
      $isDisplayMenu   = false;
332
      $isDisplayTopNav = false;
333
    }
334
335
    $template = self::gettemplate('_page_20_header', true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type null|template expected by parameter $template of SnTemplate::gettemplate(). ( Ignorable by Annotation )

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

335
    $template = self::gettemplate('_page_20_header', /** @scrutinizer ignore-type */ true);
Loading history...
336
337
    self::renderJavaScript();
338
339
    self::renderCss($inLoginLogout);
340
341
    $template->assign_vars(array(
342
      self::P_CONTENT => $renderedContent,
343
344
      'LANG_LANGUAGE'  => $lang['LANG_INFO']['LANG_NAME_ISO2'],
345
      'LANG_ENCODING'  => 'utf-8',
346
      'LANG_DIRECTION' => $lang['LANG_INFO']['LANG_DIRECTION'],
347
348
      'SN_ROOT_VIRTUAL' => SN_ROOT_VIRTUAL,
349
350
      'ADV_SEO_META_DESCRIPTION' => $config->adv_seo_meta_description,
351
      'ADV_SEO_META_KEYWORDS'    => $config->adv_seo_meta_keywords,
352
353
      // WARNING! This can be set by page!
354
      // CHANGE CODE TO MAKE IT IMPOSSIBLE!
355
      'GLOBAL_META_TAGS'         => isset($page->_rootref['GLOBAL_META_TAGS']) ? $page->_rootref['GLOBAL_META_TAGS'] : '',
356
    ));
357
358
    $template->assign_vars(array(
359
      'GLOBAL_DISPLAY_MENU'   => $isDisplayMenu,
360
      'GLOBAL_DISPLAY_NAVBAR' => $isDisplayTopNav,
361
362
      'USER_AUTHLEVEL' => intval($user['authlevel']),
363
364
      'FONT_SIZE'                        => self::playerFontSize(),
365
      'FONT_SIZE_PERCENT_DEFAULT_STRING' => FONT_SIZE_PERCENT_DEFAULT_STRING,
366
367
      'SN_TIME_NOW'          => SN_TIME_NOW,
368
      'LOGIN_LOGOUT'         => $template_result['LOGIN_LOGOUT'],
369
      'GAME_MODE_CSS_PREFIX' => $config->game_mode == GAME_BLITZ ? 'blitz_' : '',
370
      'TIME_DIFF_MEASURE'    => playerTimeDiff::timeDiffTemplate(), // Проводить замер только если не выставлен флаг форсированного замера И (иссяк интервал замера ИЛИ замера еще не было)
371
372
      'title'              => ($title ? "{$title} - " : '') . "{$lang['sys_server']} {$config->game_name} - {$lang['sys_supernova']}",
373
      'ADV_SEO_JAVASCRIPT' => $config->adv_seo_javascript,
374
375
      'SOUND_ENABLED'                        => SN::$user_options[PLAYER_OPTION_SOUND_ENABLED],
376
      'PLAYER_OPTION_ANIMATION_DISABLED'     => SN::$user_options[PLAYER_OPTION_ANIMATION_DISABLED],
377
      'PLAYER_OPTION_PROGRESS_BARS_DISABLED' => SN::$user_options[PLAYER_OPTION_PROGRESS_BARS_DISABLED],
378
379
      'IMPERSONATING'                        => !empty($template_result[F_IMPERSONATE_STATUS]) ? sprintf($lang['sys_impersonated_as'], $user['username'], $template_result[F_IMPERSONATE_OPERATOR]) : '',
380
      'PLAYER_OPTION_DESIGN_DISABLE_BORDERS' => SN::$user_options[PLAYER_OPTION_DESIGN_DISABLE_BORDERS],
381
    ));
382
    $template->assign_recursive($template_result);
383
384
    if ($isDisplayMenu) {
385
      SnTemplate::tpl_render_menu($template);
386
    }
387
388
    if ($isDisplayTopNav) {
389
      SN::$gc->pimp->tpl_render_topnav($user, $planetrow, $template);
390
    }
391
392
    SnTemplate::displayP($template);
393
    ob_end_flush();
394
395
    SN::$headerRendered = true;
396
397
    ob_start();
398
  }
399
400
  /**
401
   * @param $is_login
402
   */
403
  public static function renderCss($is_login) {
404
    global $sn_mvc, $sn_page_name, $template_result;
405
406
    empty($sn_mvc['css']) ? $sn_mvc['css'] = ['' => []] : false;
407
408
    $standard_css = [];
409
    $standard_css = self::cssAddFileName('design/css/jquery-ui', $standard_css);
410
    $standard_css = self::cssAddFileName('design/css/global', $standard_css);
411
    $is_login ? $standard_css = self::cssAddFileName('design/css/login', $standard_css) : false;
412
413
    $standard_css = self::getCurrentTemplate()->cssAddFileName('_template', $standard_css);
414
415
    $standard_css = self::cssAddFileName(SN::$gc->theUser->getSkinPath() . 'skin', $standard_css);
416
    $standard_css = self::cssAddFileName('design/css/global_override', $standard_css);
417
418
    // Prepending standard CSS files
419
    $sn_mvc['css'][''] = array_merge($standard_css, $sn_mvc['css']['']);
420
421
    self::renderFileListInclude($template_result, $sn_mvc, $sn_page_name, 'css');
422
  }
423
424
  /**
425
   */
426
  public static function renderJavaScript() {
427
    global $sn_mvc, $sn_page_name, $template_result;
428
429
    self::renderFileListInclude($template_result, $sn_mvc, $sn_page_name, 'javascript');
430
  }
431
432
  /**
433
   * @param $time
434
   * @param $event
435
   * @param $msg
436
   * @param $prefix
437
   * @param $is_decrease
438
   * @param $fleet_flying_row
439
   * @param $fleet_flying_sorter
440
   * @param $fleet_flying_events
441
   * @param $fleet_event_count
442
   */
443
  public static function tpl_topnav_event_build_helper($time, $event, $msg, $prefix, $is_decrease, $fleet_flying_row, &$fleet_flying_sorter, &$fleet_flying_events, &$fleet_event_count) {
444
    $fleet_flying_sorter[$fleet_event_count] = $time;
445
    $fleet_flying_events[$fleet_event_count] = array(
446
      'ROW'              => $fleet_flying_row,
447
      'FLEET_ID'         => $fleet_flying_row['fleet_id'],
448
      'EVENT'            => $event,
449
      'COORDINATES'      => uni_render_coordinates($fleet_flying_row, $prefix),
450
      'COORDINATES_TYPE' => $fleet_flying_row["{$prefix}type"],
451
      'TEXT'             => "{$msg}",
452
      'DECREASE'         => $is_decrease,
453
    );
454
    $fleet_event_count++;
455
  }
456
457
  /**
458
   * @param template $template
459
   * @param array    $fleet_flying_list
460
   * @param string   $type
461
   */
462
  public static function tpl_topnav_event_build(&$template, $fleet_flying_list, $type = 'fleet') {
463
    if (empty($fleet_flying_list)) {
464
      return;
465
    }
466
467
    global $lang;
468
469
    $fleet_event_count   = 0;
470
    $fleet_flying_sorter = array();
471
    $fleet_flying_events = array();
472
    foreach ($fleet_flying_list as &$fleet_flying_row) {
473
      $will_return = true;
474
      if ($fleet_flying_row['fleet_mess'] == 0) {
475
        // cut fleets on Hold and Expedition
476
        if ($fleet_flying_row['fleet_start_time'] >= SN_TIME_NOW) {
477
          $fleet_flying_row['fleet_mission'] == MT_RELOCATE ? $will_return = false : false;
478
          SnTemplate::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);
479
        }
480
        if ($fleet_flying_row['fleet_end_stay']) {
481
          SnTemplate::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);
482
        }
483
      }
484
      if ($will_return) {
485
        SnTemplate::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);
486
      }
487
    }
488
489
    asort($fleet_flying_sorter);
490
491
    $fleet_flying_count = count($fleet_flying_list);
492
    foreach ($fleet_flying_sorter as $fleet_event_id => $fleet_time) {
493
      $fleet_event = &$fleet_flying_events[$fleet_event_id];
494
      $template->assign_block_vars("flying_{$type}s", array(
495
        'TIME' => max(0, $fleet_time - SN_TIME_NOW),
496
        'TEXT' => $fleet_flying_count,
497
        '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']]}",
498
      ));
499
      $fleet_event['DECREASE'] ? $fleet_flying_count-- : false;
500
    }
501
  }
502
503
  /**
504
   * @return mixed|string
505
   */
506
  public static function playerFontSize() {
507
    $font_size = !empty($_COOKIE[SN_COOKIE_F]) ? $_COOKIE[SN_COOKIE_F] : SN::$user_options[PLAYER_OPTION_BASE_FONT_SIZE];
508
    if (strpos($font_size, '%') !== false) {
509
      // Размер шрифта в процентах
510
      $font_size = min(max(floatval($font_size), FONT_SIZE_PERCENT_MIN), FONT_SIZE_PERCENT_MAX) . '%';
511
512
      return $font_size;
513
    } elseif (strpos($font_size, 'px') !== false) {
514
      // Размер шрифта в пикселях
515
      $font_size = min(max(floatval($font_size), FONT_SIZE_PIXELS_MIN), FONT_SIZE_PIXELS_MAX) . 'px';
516
517
      return $font_size;
518
    } else {
519
      // Не мышонка, не лягушка...
520
      $font_size = FONT_SIZE_PERCENT_DEFAULT_STRING;
521
522
      return $font_size;
523
    }
524
  }
525
526
  /**
527
   * Checks if minified/full-size CSS file exists - and adds it if any
528
   *
529
   * @param string $cssFileName
530
   * @param array  $cssArray
531
   *
532
   * @return array
533
   */
534
  public static function cssAddFileName($cssFileName, $cssArray) {
535
    if (file_exists(SN_ROOT_PHYSICAL . $cssFileName . '.min.css')) {
536
      $cssArray[$cssFileName . '.min.css'] = '';
537
    } elseif (file_exists(SN_ROOT_PHYSICAL . $cssFileName . '.css')) {
538
      $cssArray[$cssFileName . '.css'] = '';
539
    }
540
541
    return $cssArray;
542
  }
543
544
  /**
545
   * @param array   $template_result
546
   * @param array[] $sn_mvc
547
   * @param string  $sn_page_name
548
   * @param string  $fileType - 'css' or 'javascript'
549
   */
550
  public static function renderFileListInclude(&$template_result, &$sn_mvc, $sn_page_name, $fileType) {
551
    if (empty($sn_mvc[$fileType])) {
552
      return;
553
    }
554
555
    foreach ($sn_mvc[$fileType] as $page_name => $script_list) {
556
      if (empty($page_name) || $page_name == $sn_page_name) {
557
        foreach ($script_list as $filename => $content) {
558
          $template_result['.'][$fileType][] = array(
559
            'FILE'    => $filename,
560
            'CONTENT' => $content,
561
          );
562
        }
563
      }
564
    }
565
  }
566
567
  /**
568
   * @param $template
569
   * @param $user
570
   */
571
  public static function tpl_navbar_render_notes(&$template, &$user) {
572
    $notes_query = doquery("SELECT * FROM {{notes}} WHERE `owner` = {$user['id']} AND `sticky` = 1 ORDER BY priority DESC, time DESC");
0 ignored issues
show
Deprecated Code introduced by
The function doquery() has been deprecated. ( Ignorable by Annotation )

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

572
    $notes_query = /** @scrutinizer ignore-deprecated */ doquery("SELECT * FROM {{notes}} WHERE `owner` = {$user['id']} AND `sticky` = 1 ORDER BY priority DESC, time DESC");
Loading history...
573
    while ($note_row = db_fetch($notes_query)) {
574
      Note::note_assign($template, $note_row);
0 ignored issues
show
Deprecated Code introduced by
The function Note\Note::note_assign() has been deprecated. ( Ignorable by Annotation )

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

574
      /** @scrutinizer ignore-deprecated */ Note::note_assign($template, $note_row);
Loading history...
575
    }
576
  }
577
578
  /**
579
   * @param $template
580
   * @param $user
581
   * @param $config
582
   */
583
  public static function tpl_navbar_render_news(&$template, &$user, $config) {
584
    if ($config->game_news_overview) {
585
      $user_last_read_safe     = intval($user['news_lastread']);
586
      $newsSql                 = "AND UNIX_TIMESTAMP(`tsTimeStamp`) >= {$user_last_read_safe} ";
587
      $newsOverviewShowSeconds = intval($config->game_news_overview_show);
588
      if ($newsOverviewShowSeconds) {
589
        $newsSql .= "AND `tsTimeStamp` >= DATE_SUB(NOW(), INTERVAL {$newsOverviewShowSeconds} SECOND) ";
590
      }
591
      nws_render($user, $template, $newsSql, $config->game_news_overview);
592
    }
593
  }
594
595
  /**
596
   * @param array  $sn_mvc
597
   * @param string $blockName
598
   *
599
   * @return array|false
600
   */
601
  public static function render_button_block(&$sn_mvc, $blockName) {
602
    $result = false;
603
604
    if (!empty($sn_mvc[$blockName]) && is_array($sn_mvc[$blockName])) {
605
      foreach ($sn_mvc[$blockName] as $navbar_button_image => $navbar_button_url) {
606
        $result[] = array(
607
          'IMAGE'        => $navbar_button_image,
608
          'URL_RELATIVE' => $navbar_button_url,
609
        );
610
      }
611
612
      $result = array(
613
        '.' => array(
614
          $blockName =>
615
            $result
616
        ),
617
      );
618
    }
619
620
    return $result;
621
  }
622
623
  /**
624
   * @param array    $sn_mvc
625
   * @param template $template
626
   */
627
  public static function tpl_navbar_extra_buttons(&$sn_mvc, $template) {
628
    ($block = SnTemplate::render_button_block($sn_mvc, 'navbar_prefix_button')) ? $template->assign_recursive($block) : false;
629
    ($block = SnTemplate::render_button_block($sn_mvc, 'navbar_main_button')) ? $template->assign_recursive($block) : false;
630
  }
631
632
  /**
633
   * @param template|string $template
634
   *
635
   * @return false|string|null
636
   */
637
  public static function templateRenderToHtml($template) {
638
    $output = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $output is dead and can be removed.
Loading history...
639
640
    ob_start();
641
    SnTemplate::displayP($template);
642
    $output = ob_get_contents();
643
    ob_end_clean();
644
645
    return $output;
646
  }
647
648
  /**
649
   * @param template $template
650
   */
651
  public static function tpl_login_lang(&$template) {
652
    global $language;
653
654
    $url_params = array();
655
656
    $language ? $url_params[] = "lang={$language}" : false;
657
658
    ($id_ref = sys_get_param_id('id_ref')) ? $url_params[] = "id_ref={$id_ref}" : false;
659
660
    $template->assign_vars($q = array(
661
      'LANG'     => $language ? $language : '',
662
      'referral' => $id_ref ? '&id_ref=' . $id_ref : '',
663
664
      'REQUEST_PARAMS' => !empty($url_params) ? '?' . implode('&', $url_params) : '',// "?lang={$language}" . ($id_ref ? "&id_ref={$id_ref}" : ''),
665
      'FILENAME'       => basename($_SERVER['PHP_SELF']),
666
    ));
667
668
    foreach (lng_get_list() as $lng_id => $lng_data) {
669
      if (isset($lng_data['LANG_VARIANTS']) && is_array($lng_data['LANG_VARIANTS'])) {
670
        foreach ($lng_data['LANG_VARIANTS'] as $lang_variant) {
671
          $lng_data1 = $lng_data;
672
          $lng_data1 = array_merge($lng_data1, $lang_variant);
673
          $template->assign_block_vars('language', $lng_data1);
674
        }
675
      } else {
676
        $template->assign_block_vars('language', $lng_data);
677
      }
678
    }
679
  }
680
681
  /**
682
   * @param template $template
683
   * @param string   $blockName
684
   * @param mixed    $values
685
   * @param string   $keyName   - Name for key name
686
   * @param string   $valueName - Name for value name
687
   */
688
  public static function tpl_assign_select(&$template, $blockName, $values, $keyName = 'KEY', $valueName = 'VALUE') {
689
    !is_array($values) ? $values = array($values => $values) : false;
690
691
    foreach ($values as $key => $value) {
692
      $template->assign_block_vars($blockName, array(
693
        $keyName   => HelperString::htmlSafe($key),
694
        $valueName => HelperString::htmlSafe($value),
695
      ));
696
    }
697
  }
698
699
  /**
700
   * Renders unit bonus from unit data
701
   *
702
   * @param array $unitInfo
703
   *
704
   * @return string
705
   */
706
  public static function tpl_render_unit_bonus_data($unitInfo) {
707
    $strBonus = self::tplAddPlus($unitInfo[P_BONUS_VALUE]);
708
    switch ($unitInfo[P_BONUS_TYPE]) {
709
      case BONUS_PERCENT:
710
        $strBonus = "{$strBonus}% ";
711
      break;
712
713
      case BONUS_ABILITY:
714
        $strBonus = '';
715
      break;
716
717
      case BONUS_ADD:
718
      default:
719
      break;
720
    }
721
722
    return $strBonus;
723
  }
724
725
  /**
726
   * Converts number to string then adds "+" sign for positive AND ZERO numbers
727
   *
728
   * @param float $value
729
   *
730
   * @return string
731
   */
732
  public static function tplAddPlus($value) {
733
    return ($value >= 0 ? '+' : '') . $value;
734
  }
735
736
  /**
737
   * Convert number to prettified string then adds "+" sign for positive AND ZERO numbers
738
   *
739
   * @param float $value
740
   *
741
   * @return string
742
   */
743
  public static function tplPrettyPlus($value) {
744
    return ($value >= 0 ? '+' : '') . HelperString::numberFloorAndFormat($value);
745
  }
746
747
  /**
748
   * Add message to result box
749
   *
750
   * If $template specified - message would be added to template supplied. Otherwise - to $template_result
751
   *
752
   * @param string $message
753
   * @param int    $status
754
   * @param null   $template
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $template is correct as it would always require null to be passed?
Loading history...
755
   */
756
  public static function tplAddResult($message, $status = ERR_NONE, $template = null) {
757
    global $template_result;
758
759
    $block = [
760
      'STATUS'  => $status,
761
      'MESSAGE' => $message,
762
    ];
763
764
    if ($template instanceof template) {
765
      $template->assign_block_vars('result', $block);
766
    } else {
767
      $template_result['.']['result'][] = $block;
768
    }
769
  }
770
771
  /**
772
   * @param string    $message
773
   * @param string    $title
774
   * @param string    $redirectTo
775
   * @param int       $timeout
776
   * @param bool|true $showHeader
777
   */
778
  public static function messageBox($message, $title = '', $redirectTo = '', $timeout = 5, $showHeader = true) {
779
    global $lang, $template_result;
780
781
    if (empty($title)) {
782
      $title = $lang['sys_error'];
783
    }
784
785
    $template = self::gettemplate('message_body', true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type null|template expected by parameter $template of SnTemplate::gettemplate(). ( Ignorable by Annotation )

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

785
    $template = self::gettemplate('message_body', /** @scrutinizer ignore-type */ true);
Loading history...
786
787
    $template_result['GLOBAL_DISPLAY_NAVBAR'] = $showHeader;
788
789
    $template->assign_vars(array(
790
//    'GLOBAL_DISPLAY_NAVBAR' => $showHeader,
791
792
      'TITLE'       => $title,
793
      'MESSAGE'     => $message,
794
      'REDIRECT_TO' => $redirectTo,
795
      'TIMEOUT'     => $timeout,
796
    ));
797
798
    self::display($template, $title);
799
  }
800
801
  /**
802
   * Admin message box
803
   *
804
   * @param        $message
805
   * @param string $title
806
   * @param string $redirectTo
807
   * @param int    $timeout
808
   *
809
   * @see SnTemplate::messageBox()
810
   */
811
  public static function messageBoxAdmin($message, $title = '', $redirectTo = '', $timeout = 5) {
812
    SnTemplate::messageBox($message, $title, $redirectTo, $timeout, false);
813
  }
814
815
  public static function messageBoxAdminAccessDenied($level = AUTH_LEVEL_ADMINISTRATOR) {
816
    global $user, $lang;
817
818
    if ($user['authlevel'] < $level) {
819
      SnTemplate::messageBoxAdmin($lang['adm_err_denied'], $lang['admin_title_access_denied'], SN_ROOT_VIRTUAL . 'overview.php');
820
    }
821
  }
822
823
  /**
824
   * @param          $prevUser
825
   * @param array    $user
826
   * @param array    $planetrow
827
   * @param template $template
828
   *
829
   * @return array
830
   */
831
  public static function sn_tpl_render_topnav(&$prevUser, $user, $planetrow, $template) {
832
    global $lang, $config, $sn_mvc;
833
834
    // This call was not first one... Using results from previous call
835
    if (!empty($prevUser['username'])) {
836
      $user = $prevUser;
837
    }
838
839
    if (!is_array($user)) {
840
      return $user;
841
    }
842
843
    $GET_mode = sys_get_param_str('mode');
844
845
    $ThisUsersPlanets = DBStaticPlanet::db_planet_list_sorted($user);
846
    foreach ($ThisUsersPlanets as $CurPlanet) {
0 ignored issues
show
Bug introduced by
The expression $ThisUsersPlanets of type false is not traversable.
Loading history...
847
      if ($CurPlanet['destruyed']) {
848
        continue;
849
      }
850
851
      $fleet_listx = flt_get_fleets_to_planet($CurPlanet);
852
853
      $template->assign_block_vars('topnav_planets', [
854
        'ID'          => $CurPlanet['id'],
855
        'NAME'        => $CurPlanet['name'],
856
        'TYPE'        => $CurPlanet['planet_type'],
857
        'TYPE_TEXT'   => $lang['sys_planet_type_sh'][$CurPlanet['planet_type']],
858
        'IS_CAPITAL'  => $CurPlanet['planet_type'] == PT_PLANET && $CurPlanet['id'] == $user['id_planet'],
859
        'IS_MOON'     => $CurPlanet['planet_type'] == PT_MOON,
860
        'PLIMAGE'     => $CurPlanet['image'],
861
        'FLEET_ENEMY' => $fleet_listx['enemy']['count'],
862
        'COORDS'      => uni_render_coordinates($CurPlanet),
863
        'SELECTED'    => $CurPlanet['id'] == $user['current_planet'] ? ' selected' : '',
864
      ]);
865
    }
866
867
    $fleet_flying_list = DbFleetStatic::tpl_get_fleets_flying($user);
868
    SnTemplate::tpl_topnav_event_build($template, $fleet_flying_list[0]);
869
    SnTemplate::tpl_topnav_event_build($template, $fleet_flying_list[MT_EXPLORE], 'expedition');
870
871
    que_tpl_parse($template, QUE_STRUCTURES, $user, $planetrow, null, true);
872
    que_tpl_parse($template, QUE_RESEARCH, $user, array(), null, !SN::$user_options[PLAYER_OPTION_NAVBAR_RESEARCH_WIDE]);
873
    que_tpl_parse($template, SUBQUE_FLEET, $user, $planetrow, null, true);
874
875
    SnTemplate::tpl_navbar_extra_buttons($sn_mvc, $template);
876
    SnTemplate::tpl_navbar_render_news($template, $user, $config);
877
    SnTemplate::tpl_navbar_render_notes($template, $user);
878
    $tutorial_enabled = PageTutorial::renderNavBar($template);
879
880
881
    $premium_lvl = mrc_get_level($user, false, UNIT_PREMIUM, true, true);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array expected by parameter $planet of mrc_get_level(). ( Ignorable by Annotation )

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

881
    $premium_lvl = mrc_get_level($user, /** @scrutinizer ignore-type */ false, UNIT_PREMIUM, true, true);
Loading history...
882
883
    $str_date_format   = "%3$02d %2$0s %1$04d {$lang['top_of_year']} %4$02d:%5$02d:%6$02d";
884
    $time_now_parsed   = getdate(SN_TIME_NOW);
885
    $time_local_parsed = getdate(defined('SN_CLIENT_TIME_LOCAL') ? SN_CLIENT_TIME_LOCAL : SN_TIME_NOW);
886
887
    $template->assign_vars(array(
888
      'QUE_ID'   => QUE_RESEARCH,
889
      'QUE_HTML' => 'topnav',
890
891
      'RESEARCH_ONGOING' => (boolean)$user['que'],
892
893
      'TIME_TEXT'       => sprintf($str_date_format, $time_now_parsed['year'], $lang['months'][$time_now_parsed['mon']], $time_now_parsed['mday'],
894
        $time_now_parsed['hours'], $time_now_parsed['minutes'], $time_now_parsed['seconds']
895
      ),
896
      'TIME_TEXT_LOCAL' => sprintf($str_date_format, $time_local_parsed['year'], $lang['months'][$time_local_parsed['mon']], $time_local_parsed['mday'],
897
        $time_local_parsed['hours'], $time_local_parsed['minutes'], $time_local_parsed['seconds']
898
      ),
899
900
      'GAME_BLITZ_REGISTER'             => $config->game_blitz_register,
901
      'GAME_BLITZ_REGISTER_TEXT'        => $lang['sys_blitz_registration_mode_list'][$config->game_blitz_register],
902
      'BLITZ_REGISTER_OPEN'             => $config->game_blitz_register == BLITZ_REGISTER_OPEN,
903
      'BLITZ_REGISTER_CLOSED'           => $config->game_blitz_register == BLITZ_REGISTER_CLOSED,
904
      'BLITZ_REGISTER_SHOW_LOGIN'       => $config->game_blitz_register == BLITZ_REGISTER_SHOW_LOGIN,
905
      'BLITZ_REGISTER_DISCLOSURE_NAMES' => $config->game_blitz_register == BLITZ_REGISTER_DISCLOSURE_NAMES,
906
      'GAME_BLITZ'                      => $config->game_mode == GAME_BLITZ,
907
908
      'USERS_ONLINE'  => $config->var_online_user_count,
909
      'USERS_TOTAL'   => $config->users_amount,
910
      'USER_RANK'     => $user['total_rank'],
911
      'USER_NICK'     => $user['username'],
912
      'USER_AVATAR'   => $user['avatar'],
913
      'USER_AVATARID' => $user['id'],
914
      'USER_PREMIUM'  => $premium_lvl,
915
      'USER_RACE'     => $user['player_race'],
916
917
      'TOPNAV_CURRENT_PLANET'       => $user['current_planet'],
918
      'TOPNAV_CURRENT_PLANET_NAME'  => uni_render_planet_full($planetrow), // htmlspecialchars($planetrow['name']),
919
      'TOPNAV_CURRENT_PLANET_IMAGE' => $planetrow['image'],
920
      'TOPNAV_COLONIES_CURRENT'     => get_player_current_colonies($user),
921
      'TOPNAV_COLONIES_MAX'         => get_player_max_colonies($user),
922
      'NAVBAR_MODE'                 => $GET_mode,
923
924
      'TOPNAV_DARK_MATTER'            => mrc_get_level($user, '', RES_DARK_MATTER),
0 ignored issues
show
Bug introduced by
'' of type string is incompatible with the type array expected by parameter $planet of mrc_get_level(). ( Ignorable by Annotation )

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

924
      'TOPNAV_DARK_MATTER'            => mrc_get_level($user, /** @scrutinizer ignore-type */ '', RES_DARK_MATTER),
Loading history...
925
      'TOPNAV_DARK_MATTER_TEXT'       => HelperString::numberFloorAndFormat(mrc_get_level($user, '', RES_DARK_MATTER)),
0 ignored issues
show
Bug introduced by
It seems like mrc_get_level($user, '', RES_DARK_MATTER) can also be of type boolean; however, parameter $number of HelperString::numberFloorAndFormat() does only seem to accept double|integer, maybe add an additional type check? ( Ignorable by Annotation )

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

925
      'TOPNAV_DARK_MATTER_TEXT'       => HelperString::numberFloorAndFormat(/** @scrutinizer ignore-type */ mrc_get_level($user, '', RES_DARK_MATTER)),
Loading history...
926
      'TOPNAV_DARK_MATTER_PLAIN'      => mrc_get_level($user, '', RES_DARK_MATTER, false, true),
927
      'TOPNAV_DARK_MATTER_PLAIN_TEXT' => HelperString::numberFloorAndFormat(mrc_get_level($user, '', RES_DARK_MATTER, false, true)),
928
      'TOPNAV_METAMATTER'             => mrc_get_level($user, '', RES_METAMATTER),
929
      'TOPNAV_METAMATTER_TEXT'        => HelperString::numberFloorAndFormat(mrc_get_level($user, '', RES_METAMATTER)),
930
931
      // TODO ГРЯЗНЫЙ ХАК!!!
932
      'TOPNAV_PAYMENT'                => SN::$gc->modules->countModulesInGroup('payment') && !defined('SN_GOOGLE'),
933
934
      'TOPNAV_MESSAGES_ADMIN'    => $user['msg_admin'],
935
      'TOPNAV_MESSAGES_PLAYER'   => $user['mnl_joueur'],
936
      'TOPNAV_MESSAGES_ALLIANCE' => $user['mnl_alliance'],
937
      'TOPNAV_MESSAGES_ATTACK'   => $user['mnl_attaque'],
938
      'TOPNAV_MESSAGES_ALL'      => $user['new_message'],
939
940
      'TOPNAV_FLEETS_FLYING'      => count($fleet_flying_list[0]),
941
      'TOPNAV_FLEETS_TOTAL'       => GetMaxFleets($user),
942
      'TOPNAV_EXPEDITIONS_FLYING' => count($fleet_flying_list[MT_EXPLORE]),
943
      'TOPNAV_EXPEDITIONS_TOTAL'  => get_player_max_expeditons($user),
944
945
      'TOPNAV_QUEST_COMPLETE'    => get_quest_amount_complete($user['id']),
946
      'TOPNAV_QUEST_IN_PROGRESS' => get_quest_amount_in_progress($user['id']),
947
948
      'GAME_NEWS_OVERVIEW'       => $config->game_news_overview,
949
      'GAME_RESEARCH_DISABLED'   => defined('GAME_RESEARCH_DISABLED') && GAME_RESEARCH_DISABLED,
0 ignored issues
show
Bug introduced by
The constant GAME_RESEARCH_DISABLED was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
950
      'GAME_DEFENSE_DISABLED'    => defined('GAME_DEFENSE_DISABLED') && GAME_DEFENSE_DISABLED,
0 ignored issues
show
Bug introduced by
The constant GAME_DEFENSE_DISABLED was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
951
      'GAME_STRUCTURES_DISABLED' => defined('GAME_STRUCTURES_DISABLED') && GAME_STRUCTURES_DISABLED,
0 ignored issues
show
Bug introduced by
The constant GAME_STRUCTURES_DISABLED was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
952
      'GAME_HANGAR_DISABLED'     => defined('GAME_HANGAR_DISABLED') && GAME_HANGAR_DISABLED,
0 ignored issues
show
Bug introduced by
The constant GAME_HANGAR_DISABLED was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
953
954
      'PLAYER_OPTION_NAVBAR_PLANET_VERTICAL'        => SN::$user_options[PLAYER_OPTION_NAVBAR_PLANET_VERTICAL],
955
      'PLAYER_OPTION_NAVBAR_PLANET_OLD'             => SN::$user_options[PLAYER_OPTION_NAVBAR_PLANET_OLD],
956
      'PLAYER_OPTION_NAVBAR_PLANET_DISABLE_STORAGE' => SN::$user_options[PLAYER_OPTION_NAVBAR_PLANET_DISABLE_STORAGE],
957
      'PLAYER_OPTION_NAVBAR_DISABLE_RESEARCH'       => SN::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_RESEARCH],
958
      'PLAYER_OPTION_NAVBAR_DISABLE_PLANET'         => SN::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_PLANET],
959
      'PLAYER_OPTION_NAVBAR_DISABLE_HANGAR'         => SN::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_HANGAR],
960
      'PLAYER_OPTION_NAVBAR_DISABLE_FLYING_FLEETS'  => SN::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_FLYING_FLEETS],
961
      'PLAYER_OPTION_NAVBAR_DISABLE_EXPEDITIONS'    => SN::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_EXPEDITIONS],
962
      'PLAYER_OPTION_NAVBAR_DISABLE_QUESTS'         => SN::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_QUESTS],
963
      'PLAYER_OPTION_NAVBAR_DISABLE_META_MATTER'    => SN::$user_options[PLAYER_OPTION_NAVBAR_DISABLE_META_MATTER],
964
      'PLAYER_OPTION_NAVBAR_RESEARCH_WIDE'          => SN::$user_options[PLAYER_OPTION_NAVBAR_RESEARCH_WIDE],
965
966
      'TUTORIAL_ENABLED' => $tutorial_enabled,
967
968
      'PT_MOON'        => PT_MOON,
969
      'SUBQUE_FLEET'   => SUBQUE_FLEET,
970
      'QUE_RESEARCH'   => QUE_RESEARCH,
971
      'QUE_STRUCTURES' => QUE_STRUCTURES,
972
    ));
973
974
    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)) {
975
      tpl_set_resource_info($template, $planetrow);
976
      $template->assign_vars(array(
977
        'SN_RENDER_NAVBAR_PLANET' => true,
978
        'SN_NAVBAR_HIDE_FLEETS'   => true,
979
      ));
980
    }
981
982
    return $user;
983
  }
984
985
  /**
986
   * @param array|string  $files
987
   * @param template|null $template
988
   * @param string|null   $template_path - path to templates root
989
   *
990
   * @return template
991
   */
992
  public static function gettemplate($files, $template = null, $template_path = null) {
993
    global $sn_mvc, $sn_page_name;
994
995
    $template = self::getCurrentTemplate()->getTemplate($template, $template_path);
996
997
    // TODO ГРЯЗНЫЙ ХАК! Это нужно, что бы по возможности перезаписать инфу из языковых пакетов модулей там, где она была перезаписана раньше инфой из основного пакета. Почему?
998
    //  - сначала грузятся модули и их языковые пакеты
999
    //  - затем по ходу дела ОСНОВНОЙ языковой пакет может перезаписать данные из МОДУЛЬНОГО языкового пакета
1000
    // Поэтому и нужен этот грязный хак
1001
    // В норме же - страницы заявляют сами, какие им пакеты нужны. Так что сначала всегда должны грузится основные языковые пакеты, а уже ПОВЕРХ них - пакеты модулей
1002
    !empty($sn_mvc['i18n']['']) ? lng_load_i18n($sn_mvc['i18n']['']) : false;
1003
    $sn_page_name ? lng_load_i18n($sn_mvc['i18n'][$sn_page_name]) : false;
1004
1005
    if (empty($files)) {
1006
      // Make sure that all empty files will translate to empty array
1007
      $files = [];
1008
    } elseif (is_string($files)) {
1009
      // If we have single filename - making array from it
1010
      $files = [basename($files) => $files];
1011
    } elseif (!is_array($files)) {
0 ignored issues
show
introduced by
The condition is_array($files) is always true.
Loading history...
1012
      // And final touch - all other non-string and non-array inputs converted to empty array
1013
      $files = [];
1014
    }
1015
1016
    foreach ($files as &$filename) {
1017
      $filename = $filename . self::TPL_HTML;
1018
    }
1019
1020
    $template->set_filenames($files);
1021
1022
    return $template;
1023
  }
1024
1025
  /**
1026
   * @param template|string $page
1027
   * @param string          $title
1028
   *
1029
   * @return mixed
1030
   */
1031
  public static function display($page, $title = '') {
1032
    SN::$gSomethingWasRendered = true;
1033
1034
    if (!defined('SN_TIME_RENDER_START')) {
1035
      define('SN_TIME_RENDER_START', microtime(true));
1036
    }
1037
1038
//  return sn_function_call('display', array($page, $title));
1039
//}
1040
//
1041
///**
1042
// * @param template|string $page
1043
// * @param string          $title
1044
// */
1045
//function sn_display($page, $title = '') {
1046
    global $debug, $user, $planetrow, $config, $lang, $template_result, $sn_mvc;
1047
1048
    !empty($sn_mvc['view']['']) and execute_hooks($sn_mvc['view'][''], $page, 'view', '');
1049
1050
    $exitStatus                      = true;
1051
    $template_result['LOGIN_LOGOUT'] = $inLoginLogout = defined('LOGIN_LOGOUT') && LOGIN_LOGOUT === true;
1052
1053
    if (is_object($page)) {
1054
      isset($page->_rootref['PAGE_TITLE']) && empty($title) ? $title = $page->_rootref['PAGE_TITLE'] : false;
1055
      !$title && !empty($page->_rootref['PAGE_HEADER']) ? $title = $page->_rootref['PAGE_HEADER'] : false;
1056
      !isset($page->_rootref['PAGE_HEADER']) && $title ? $page->assign_var('PAGE_HEADER', $title) : false;
1057
    }
1058
1059
    $isRenderGlobal = is_object($page) && isset($template_result['GLOBAL_DISPLAY_HEADER']) ? $template_result['GLOBAL_DISPLAY_HEADER'] : true;
1060
1061
    if(self::getCurrentTemplate()->isRenderWhole()) {
1062
      ob_start();
1063
    } else {
1064
      // Global header
1065
      if ($isRenderGlobal) {
1066
        SnTemplate::renderHeader($page, $title, $template_result, $inLoginLogout, $user, $config, $lang, $planetrow, null);
1067
      }
1068
    }
1069
1070
    // Page content
1071
    !is_array($page) ? $page = array($page) : false;
1072
    $result_added = false;
1073
    foreach ($page as $page_item) {
1074
      /**
1075
       * @var template $page_item
1076
       */
1077
      if (
1078
        !$result_added
1079
        && is_object($page_item)
1080
        && (
1081
          isset($page_item->_tpldata['result'])
1082
          ||
1083
          !empty($template_result['.']['result'])
1084
        )
1085
      ) {
1086
        $resultTemplate = SnTemplate::gettemplate('_result_message');
1087
1088
        $resultTemplate->_tpldata = $page_item->_tpldata;
1089
        $resultTemplate->assign_recursive($template_result);
1090
        SnTemplate::displayP($resultTemplate);
1091
        $result_added = true;
1092
      }
1093
1094
      SnTemplate::displayP($page_item);
1095
    }
1096
1097
    if (is_array($template_result[TEMPLATE_EXTRA_ARRAY]) && !empty($template_result[TEMPLATE_EXTRA_ARRAY])) {
1098
      foreach ($template_result[TEMPLATE_EXTRA_ARRAY] as $extraName => $extraTemplate) {
1099
        /**
1100
         * @var template $extraTemplate
1101
         */
1102
        SnTemplate::displayP($extraTemplate);
1103
      }
1104
    }
1105
1106
    if(self::getCurrentTemplate()->isRenderWhole()) {
1107
      $renderedContent = ob_get_clean();
1108
      // Global header
1109
      if ($isRenderGlobal) {
1110
        SnTemplate::renderHeader($page, $title, $template_result, $inLoginLogout, $user, $config, $lang, $planetrow, $renderedContent);
1111
      } else {
1112
        echo $renderedContent;
1113
      }
1114
    }
1115
1116
    // Flushing all opened buffers
1117
    while (@ob_end_flush());
1118
1119
1120
    // Global footer
1121
    if ($isRenderGlobal) {
1122
      SnTemplate::renderFooter($page, $template_result);
1123
    }
1124
1125
    $user['authlevel'] >= 3 && $config->debug ? $debug->echo_log() : false;;
1126
1127
    sn_db_disconnect();
1128
1129
    $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...
introduced by
The condition $exitStatus === true is always true.
Loading history...
1130
1131
    return $exitStatus;
1132
  }
1133
1134
  /**
1135
   * @var GlobalContainer|null $gc
1136
   */
1137
  protected $gc = null;
1138
1139
  /**
1140
   * @var TemplateMeta[] $templates
1141
   */
1142
  protected $templates = [];
1143
1144
  public function __construct($gc = null) {
1145
    $this->gc = empty($gc) ? SN::$gc : $gc;
1146
  }
1147
1148
  public function registerTemplate($templateName) {
1149
    if (empty($this->templates[$templateName])) {
1150
      $this->templates[$templateName] = new TemplateMeta($this, $templateName);
1151
    }
1152
1153
    return $this->templates[$templateName];
1154
  }
1155
1156
1157
  /**
1158
   * Дефолтное имя темплейта на сервере
1159
   *
1160
   * @return string
1161
   */
1162
  public static function getServerDefaultTemplateName() {
1163
    return SN::$config->game_default_template ? SN::$config->game_default_template : self::SN_TEMPLATE_NAME_DEFAULT;
1164
  }
1165
1166
  /**
1167
   * Имя темплейта у игрока
1168
   *
1169
   * @return string
1170
   */
1171
  public static function getPlayerTemplateName() {
1172
    return SN::$gc->theUser->getTemplateName();
1173
  }
1174
1175
  /**
1176
   * Относительный путь к сконфигурированному темплейту
1177
   * 'design/templates/(имя_темплейта)
1178
   *
1179
   * @return string
1180
   * @deprecated
1181
   */
1182
  public static function pathRelativeToCurrentTemplate() {
1183
    return self::SN_TEMPLATES_PARTIAL_PATH . self::getPlayerTemplateName();
1184
  }
1185
1186
  /**
1187
   * @return TemplateMeta
1188
   */
1189
  protected static function getCurrentTemplate() {
1190
    $templateName = SnTemplate::getPlayerTemplateName();
1191
    $tMeta        = static::me()->registerTemplate($templateName);
0 ignored issues
show
Bug introduced by
It seems like registerTemplate() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

1191
    $tMeta        = static::me()->/** @scrutinizer ignore-call */ registerTemplate($templateName);
Loading history...
1192
1193
    return $tMeta;
1194
  }
1195
1196
}
1197