Test Failed
Push — trunk ( 132e87...b3f953 )
by SuperNova.WS
11:54
created

SnBootstrap   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 100
dl 0
loc 159
rs 9.6
c 1
b 0
f 0
ccs 0
cts 107
cp 0
wmc 35

3 Methods

Rating   Name   Duplication   Size   Complexity  
B performUpdate() 0 37 8
B init_debug_state() 0 30 10
C install_benchmark() 0 78 17
1
<?php
2
/**
3
 * Created by Gorlum 11.06.2017 9:58
4
 */
5
6
namespace Core;
7
8
9
use core_auth;
10
use DBAL\db_mysql;
11
use \SN;
0 ignored issues
show
Bug introduced by
The type \SN was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
13
class SnBootstrap {
14
15
  public static function install_benchmark() {
16
    register_shutdown_function(function () {
17
      if (defined('IN_AJAX')) {
18
        return;
19
      }
20
21
      global $user, $locale_cache_statistic;
22
23
      $now       = microtime(true);
24
      $totalTime = round($now - SN_TIME_MICRO, 6);
25
      !defined('SN_TIME_RENDER_START') ? define('SN_TIME_RENDER_START', microtime(true)) : false;
26
      $executionTime = round(SN_TIME_RENDER_START - SN_TIME_MICRO, 6);
27
      $displayTime   = round($now - SN_TIME_RENDER_START, 6);
28
29
      $benchmarkResults =
30
        '[' . SN_TIME_SQL . '] '
31
        . 'Benchmark ' . $totalTime . 's'
32
        . (defined('SN_TIME_RENDER_START')
33
          ?
34
          " (exec: {$executionTime}s" .
35
          ", display: {$displayTime}s"
36
          . (class_exists('SN') && is_object(SN::$db) ? ', DB: ' . round(SN::$db->time_mysql_total, 6) . 's' : '')
37
          . ")"
38
          : ''
39
        )
40
        . ', memory: ' . number_format(memory_get_usage() - SN_MEM_START)
41
        . (!empty($locale_cache_statistic['misses']) ? ', LOCALE MISSED' : '')
42
        . '';
43
44
      $benchPrefix = '<div id="benchmark" class="benchmark" style="flex-grow: 1;flex-shrink: 1;"><hr>';
45
      $benchSuffix = '</div>';
46
      if (class_exists(SN::class, false) && SN::$gSomethingWasRendered) {
47
//        print "<script type='text/javascript'>document.body.innerHTML += '{$benchPrefix}" . htmlentities($benchmarkResults, ENT_QUOTES, 'UTF-8') . "{$benchSuffix}';</script>";
48
//        print "<script type='text/javascript'>document.addEventListener('DOMContentLoaded', function() {document.body.innerHTML += '{$benchPrefix}" . htmlentities($benchmarkResults, ENT_QUOTES, 'UTF-8') . "{$benchSuffix}';});</script>";
49
        print
50
"<script type='text/javascript'>
51
(function (document) {
52
    var prefix = '{$benchPrefix}';
53
    var suffix = '{$benchSuffix}';
54
    var result = '" . htmlentities($benchmarkResults, ENT_QUOTES, 'UTF-8') . "';
55
    var element = document.getElementById('debug');
56
57
    if(element) {
58
      element.innerHTML += prefix + result + suffix;
59
    } else {
60
      document.write(prefix + result + suffix);
61
    }
62
}(document));
63
</script>";
64
      } else {
65
        print($benchPrefix . $benchmarkResults . $benchSuffix);
66
      }
67
68
69
      if (isset($user['authlevel']) && $user['authlevel'] >= 2 && file_exists(SN_ROOT_PHYSICAL . 'badqrys.txt') && @filesize(SN_ROOT_PHYSICAL . 'badqrys.txt') > 0) {
70
        echo '<a href="badqrys.txt" target="_blank" style="color:red">', 'HACK ALERT!', '</a>';
71
      }
72
73
      if (!empty($locale_cache_statistic['misses'])) {
74
        print('<!--');
75
        pdump($locale_cache_statistic);
76
        print('-->');
77
      }
78
79
      $error = error_get_last();
80
      if ($error['type'] === E_ERROR) {
81
        $fName  = SN_ROOT_PHYSICAL . '_error.txt';
82
        $output = [
83
          "\n\n",
84
          SN_TIME_SQL . " - ERROR",
85
          var_export($error, true),
86
//          var_export(debug_backtrace(), true),
87
          var_export(core_auth::$device, true),
88
        ];
89
        file_put_contents($fName, implode("\n", $output), FILE_APPEND | LOCK_EX);
90
91
        if (!empty($error['file']) && strpos($error['file'], 'classCache.php') !== false) {
92
          print('<span style="color: red">Looks like cache clearing takes too long... Try to restart your web-server and/or cache engine</span>');
93
        }
94
      }
95
    });
96
  }
97
98
  public static function init_debug_state() {
99
    if ($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
100
      define('BE_DEBUG', true);
101
    }
102
103
    // Declaring PHP-constants from server config
104
    /** @see \classConfig::$DEBUG_SQL_FILE_LOG */
105
    foreach ([
106
      'DEBUG_SQL_FILE_LOG'     => ['DEBUG_SQL_ERROR' => true, 'DEBUG_SQL_COMMENT_LONG' => true,],
107
      'DEBUG_SQL_ERROR'        => ['DEBUG_SQL_COMMENT' => true,],
108
      'DEBUG_SQL_COMMENT_LONG' => ['DEBUG_SQL_COMMENT' => true,],
109
      'DEBUG_SQL_COMMENT'      => []
110
    ] as $constantName => $implications) {
111
      if (!empty(SN::$config->$constantName) && !defined($constantName)) {
112
        define($constantName, true);
113
      }
114
      foreach ($implications as $impliedConstantName => $impliedValue) {
115
        if (!defined($impliedConstantName)) {
116
          define($impliedConstantName, $impliedValue);
117
        }
118
      }
119
    }
120
121
    if (defined('BE_DEBUG') || SN::$config->debug) {
122
      @define('BE_DEBUG', true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for define(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

122
      /** @scrutinizer ignore-unhandled */ @define('BE_DEBUG', true);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
123
      @ini_set('display_errors', 1);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for ini_set(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

123
      /** @scrutinizer ignore-unhandled */ @ini_set('display_errors', 1);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
124
      @error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for error_reporting(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

124
      /** @scrutinizer ignore-unhandled */ @error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
125
    } else {
126
      @define('BE_DEBUG', false);
127
      @ini_set('display_errors', 0);
128
    }
129
130
  }
131
132
  /**
133
   * @param \classConfig $config
134
   */
135
  public static function performUpdate($config) {
136
    if (
137
      !file_exists($update_file = SN_ROOT_PHYSICAL . "includes/update.php")
138
      ||
139
      (
140
        filemtime($update_file) <= $config->pass()->var_db_update
141
        &&
142
        $config->pass()->db_version >= DB_VERSION
143
      )
144
    ) {
145
      return;
146
    }
147
148
    if (defined('IN_ADMIN') || !$config->pass()->game_installed) {
149
      db_mysql::db_transaction_start(); // Для защиты от двойного запуска апдейта - начинаем транзакцию. Так запись в базе будет блокирована
150
      if (SN_TIME_NOW >= $config->pass()->var_db_update_end) {
151
        $config->pass()->var_db_update_end = SN_TIME_NOW + $config->upd_lock_time;
152
        db_mysql::db_transaction_commit();
153
154
        require_once($update_file);
155
156
        $current_time                      = time();
157
        $config->pass()->var_db_update     = $current_time;
158
        $config->pass()->var_db_update_end = $current_time;
159
        $config->pass()->game_installed    = 1;
160
      } elseif (filemtime($update_file) > $config->var_db_update) {
161
        $timeout = $config->var_db_update_end - SN_TIME_NOW;
162
        die(
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
163
        "Обновляется база данных. Рассчетное время окончания - {$timeout} секунд (время обновления может увеличиваться). Пожалуйста, подождите...<br />
164
        Obnovljaetsja baza dannyh. Rasschetnoe vremya okonchanija - {$timeout} secund. Pozhalujsta, podozhdute...<br />
165
        Database update in progress. Estimated update time {$timeout} seconds (can increase depending on update process). Please wait..."
166
        );
167
      }
168
      db_mysql::db_transaction_rollback();
169
    } else {
170
      die(
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
171
      'Происходит обновление сервера - пожалуйста, подождите...<br />
172
      Proishodit obnovlenie servera - pozhalujsta, podozhdute...<br />
173
      Server upgrading now - please wait...<br />
174
      <a href="admin/overview.php">Admin link</a>'
175
      );
176
    }
177
  }
178
179
}
180