Completed
Push — trunk ( c0c172...91a948 )
by SuperNova.WS
11:04
created

SnBootstrap   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 106
ccs 0
cts 87
cp 0
rs 10
wmc 30

3 Methods

Rating   Name   Duplication   Size   Complexity  
C performUpdate() 0 37 8
C init_debug_state() 0 20 11
C install_benchmark() 0 36 11
1
<?php
2
/**
3
 * Created by Gorlum 11.06.2017 9:58
4
 */
5
6
namespace Core;
7
8
9
use \SN;
10
11
class SnBootstrap {
12
13
  public static function install_benchmark() {
14
    register_shutdown_function(function () {
15
      if (defined('IN_AJAX')) {
16
        return;
17
      }
18
19
      global $user, $locale_cache_statistic;
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...
20
21
      $now = microtime(true);
22
      $totalTime = round($now - SN_TIME_MICRO, 6);
23
      !defined('SN_TIME_RENDER_START') ? define('SN_TIME_RENDER_START', microtime(true)) : false;
24
      $executionTime = round(SN_TIME_RENDER_START - SN_TIME_MICRO, 6);
25
      $displayTime = round($now - SN_TIME_RENDER_START, 6);
26
27
      print(
28
        '<div id="benchmark" class="benchmark"><hr>[' . SN_TIME_SQL . '] '
29
        . 'Benchmark ' . $totalTime . 's'
30
        . (defined('SN_TIME_RENDER_START')
31
          ?
32
          " (exec: {$executionTime}s" .
33
          ", display: {$displayTime}s"
34
          . (class_exists('SN') && is_object(SN::$db) ? ', DB: ' . round(SN::$db->time_mysql_total, 6) . 's' : '')
35
          . ")"
36
          : ''
37
        )
38
        . ', memory: ' . number_format(memory_get_usage() - SN_MEM_START)
39
        . (!empty($locale_cache_statistic['misses']) ? ', LOCALE MISSED' : '')
40
        . '</div>');
41
      if ($user['authlevel'] >= 2 && file_exists(SN_ROOT_PHYSICAL . 'badqrys.txt') && @filesize(SN_ROOT_PHYSICAL . 'badqrys.txt') > 0) {
42
        echo '<a href="badqrys.txt" target="_blank" style="color:red">', 'HACK ALERT!', '</a>';
43
      }
44
45
      if (!empty($locale_cache_statistic['misses'])) {
46
        print('<!--');
47
        pdump($locale_cache_statistic);
48
        print('-->');
49
      }
50
    });
51
  }
52
53
  public static function init_debug_state() {
54
    if ($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
55
      define('BE_DEBUG', true);
56
    }
57
    // define('DEBUG_SQL_ONLINE', 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...
58
    define('DEBUG_SQL_ERROR', true); // Выводить в сообщении об ошибке так же полный дамп запросов за сессию. Подойдет любое значение
59
    define('DEBUG_SQL_COMMENT_LONG', true); // Добавлять SQL запрос длинные комментарии. Не зависим от всех остальных параметров. Подойдет любое значение
60
    define('DEBUG_SQL_COMMENT', true); // Добавлять комментарии прямо в SQL запрос. Подойдет любое значение
61
    // Включаем нужные настройки
62
    defined('DEBUG_SQL_ONLINE') && !defined('DEBUG_SQL_ERROR') ? define('DEBUG_SQL_ERROR', true) : false;
63
    defined('DEBUG_SQL_ERROR') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
64
    defined('DEBUG_SQL_COMMENT_LONG') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
65
66
    if (defined('BE_DEBUG') || SN::$config->debug) {
0 ignored issues
show
Bug Best Practice introduced by
The property debug does not exist on classConfig. Since you implemented __get, consider adding a @property annotation.
Loading history...
67
      @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

67
      /** @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...
68
      @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

68
      /** @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...
69
      @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

69
      /** @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...
70
    } else {
71
      @define('BE_DEBUG', false);
72
      @ini_set('display_errors', 0);
73
    }
74
75
  }
76
77
  /**
78
   * @param \classConfig $config
79
   */
80
  public static function performUpdate(&$config) {
81
    $update_file = SN_ROOT_PHYSICAL . "includes/update.php";
82
    if (
83
      !file_exists($update_file)
84
      ||
85
      (
86
        filemtime($update_file) <= $config->db_loadItem('var_db_update')
87
        &&
88
        $config->db_loadItem('db_version') >= DB_VERSION
89
      )
90
    ) {
91
      return;
92
    }
93
94
    if (defined('IN_ADMIN')) {
95
      sn_db_transaction_start(); // Для защиты от двойного запуска апдейта - начинаем транзакцию. Так запись в базе будет блокирована
96
      if (SN_TIME_NOW >= $config->db_loadItem('var_db_update_end')) {
97
        $config->db_saveItem('var_db_update_end', SN_TIME_NOW + ($config->upd_lock_time ? $config->upd_lock_time : 300));
98
        sn_db_transaction_commit();
99
100
        require_once($update_file);
101
102
        $current_time = time();
103
        $config->db_saveItem('var_db_update', $current_time);
104
        $config->db_saveItem('var_db_update_end', $current_time);
105
      } elseif (filemtime($update_file) > $config->var_db_update) {
106
        $timeout = $config->var_db_update_end - SN_TIME_NOW;
107
        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...
108
        "Обновляется база данных. Рассчетное время окончания - {$timeout} секунд (время обновления может увеличиваться). Пожалуйста, подождите...<br />
109
        Obnovljaetsja baza dannyh. Rasschetnoe vremya okonchanija - {$timeout} secund. Pozhalujsta, podozhdute...<br />
110
        Database update in progress. Estimated update time {$timeout} seconds (can increase depending on update process). Please wait..."
111
        );
112
      }
113
      sn_db_transaction_rollback();
114
    } else {
115
      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...
116
      'Происходит обновление сервера - пожалуйста, подождите...<br />
117
      Proishodit obnovlenie servera - pozhalujsta, podozhdute...<br />
118
      Server upgrading now - please wait...<br />
119
      <a href="admin/overview.php">Admin link</a>'
120
      );
121
    }
122
  }
123
124
}
125