Completed
Push — work-fleets ( 5fa106...33857b )
by SuperNova.WS
06:09
created

debug.php ➔ backtrace_no_arg()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 9.4285
1
<?php
2
/**
3
 * Some helpers to sweeten dev's life
4
 */
5
6
/*
7
 * debug.php ::  Clase Debug, maneja reporte de eventos
8
 *
9
 * V4.0 copyright 2010-2011 by Gorlum for http://supernova.ws
10
 *  [!] Merged `errors` to `logs`
11
 *  [+] Now debugger can work with database detached. All messages would be dumped to page
12
 *  [+] Now `logs` has both human-readable and machine-readable fields
13
 *
14
 * V3.0 copyright 2010 by Gorlum for http://supernova.ws
15
 *  [+] Full rewrtie & optimize
16
 *  [*] Now there is fallback procedure if no link to db detected
17
 *
18
 * V2.0 copyright 2010 by Gorlum for http://supernova.ws
19
 *  [*] Now error also contains backtrace - to see exact way problem comes
20
 *  [*] New method 'warning' sends message to dedicated SQL-table for non-errors
21
 *
22
 * V1.0 Created by Perberos. All rights reversed (C) 2006
23
 *
24
 *  Experiment code!!!
25
 *
26
 * vamos a experimentar >:)
27
 * le veo futuro a las classes, ayudaria mucho a tener un codigo mas ordenado...
28
 * que esperabas!!! soy newbie!!! D':<
29
*/
30
31
defined('INSIDE') || die();
32
33
if(php_sapi_name() == "cli") {
34
  // In cli-mode
35
  define('__DEBUG_CRLF', "\r\n");
36
  define('__DEBUG_LINE', '-------------------------------------------------' . __DEBUG_CRLF);
37
} else {
38
  // Not in cli-mode
39
  define('__DEBUG_CRLF', '<br />');
40
  define('__DEBUG_LINE', '<hr />');
41
}
42
43
44
class debug {
45
  var $log, $numqueries;
46
  var $log_array;
47
48
  private $log_file_handler = null;
49
50
  function log_file($message, $ident_change = 0) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
51
    static $ident = 0;
52
53
    if(!defined('SN_DEBUG_LOG')) {
54
      return;
55
    }
56
57
    if($this->log_file_handler === null) {
58
      $this->log_file_handler = @fopen(SN_ROOT_PHYSICAL . '/.logs/supernova.log', 'a+');
59
      @fwrite($this->log_file_handler, "\r\n\r\n");
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
60
    }
61
    $ident_change < 0 ? $ident += $ident_change * 2 : false;
62
    if($this->log_file_handler) {
63
      @fwrite($this->log_file_handler, date(FMT_DATE_TIME_SQL, time()) . str_repeat(' ', $ident + 1) . $message . "\r\n");
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
64
    }
65
    $ident_change > 0 ? $ident += $ident_change * 2 : false;
66
  }
67
68
  function debug() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
69
    $this->vars = $this->log = '';
0 ignored issues
show
Bug introduced by
The property vars does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
70
    $this->numqueries = 0;
71
  }
72
73
  function add($mes) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
74
    $this->log .= $mes;
75
    $this->numqueries++;
76
  }
77
78
  function add_to_array($mes) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
79
    $this->log_array[] = $mes;
80
  }
81
82
  function echo_log() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
83
    echo '<br><table><tr><td class=k colspan=4><a href="' . SN_ROOT_PHYSICAL . "admin/settings.php\">Debug Log</a>:</td></tr>{$this->log}</table>";
84
    die();
85
  }
86
87
  function compact_backtrace($backtrace, $long_comment = false) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
88
    static $exclude_functions = array('doquery', 'db_query', 'db_get_record_list', 'db_user_by_id', 'db_get_user_by_id');
89
90
    $result = array();
91
    $transaction_id = classSupernova::db_transaction_check(false) ? classSupernova::$transaction_id : classSupernova::$transaction_id++;
92
    $result[] = "tID {$transaction_id}";
93
    foreach($backtrace as $a_trace) {
94
      if(in_array($a_trace['function'], $exclude_functions)) {
95
        continue;
96
      }
97
      $function =
98
        ($a_trace['type']
99
          ? ($a_trace['type'] == '->'
100
            ? "({$a_trace['class']})" . get_class($a_trace['object'])
101
            : $a_trace['class']
102
          ) . $a_trace['type']
103
          : ''
104
        ) . $a_trace['function'] . '()';
105
106
      $file = str_replace(SN_ROOT_PHYSICAL, '', str_replace('\\', '/', $a_trace['file']));
107
108
      // $result[] = "{$function} ({$a_trace['line']})'{$file}'";
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
109
      $result[] = "{$function} - '{$file}' Line {$a_trace['line']}";
110
111
      if(!$long_comment) {
112
        break;
113
      }
114
    }
115
116
117
    // $result = implode(',', $result);
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
118
119
    return $result;
120
  }
121
122
  function dump($dump = false, $force_base = false, $deadlock = false) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
123
    global $user, $planetrow;
124
125
    if($dump === false) {
126
      return;
127
    }
128
129
    $error_backtrace = array();
130
    $base_dump = false;
131
132
    if($force_base === true) {
133
      $base_dump = true;
134
    }
135
136
    if($dump === true) {
137
      $base_dump = true;
138
    } else {
139
      if(!is_array($dump)) {
140
        $dump = array('var' => $dump);
141
      }
142
143
      foreach($dump as $dump_var_name => $dump_var) {
144
        if($dump_var_name == 'base_dump') {
145
          $base_dump = $dump_var;
146
        } else {
147
          $error_backtrace[$dump_var_name] = $dump_var;
148
        }
149
      }
150
    }
151
152
    if($deadlock && ($q = db_fetch(classSupernova::$db->mysql_get_innodb_status()))) {
0 ignored issues
show
Bug introduced by
\classSupernova::$db->mysql_get_innodb_status() cannot be passed to db_fetch() as the parameter $query expects a reference.
Loading history...
153
      $error_backtrace['deadlock'] = explode("\n", $q['Status']);
154
      $error_backtrace['locks'] = SnCache::getLocks();
155
      $error_backtrace['cSN_data'] = SnCache::getData();
156
      foreach($error_backtrace['cSN_data'] as &$location) {
157
        foreach($location as $location_id => &$location_data) {
158
          $location_data = isset($location_data['username']) ? $location_data['username'] :
159
            (isset($location_data['name']) ? $location_data['name'] : $location_id);
160
        }
161
      }
162
      $error_backtrace['cSN_queries'] = SnCache::getQueries();
163
    }
164
165
    if($base_dump) {
166
      if(is_array($this->log_array) && count($this->log_array) > 0) {
167
        foreach($this->log_array as $log) {
168
          $error_backtrace['queries'][] = $log;
169
        }
170
      }
171
172
      $error_backtrace['backtrace'] = debug_backtrace();
173
      unset($error_backtrace['backtrace'][1]);
174
      unset($error_backtrace['backtrace'][0]);
175
      $error_backtrace['$_GET'] = $_GET;
176
      $error_backtrace['$_POST'] = $_POST;
177
      $error_backtrace['$_REQUEST'] = $_REQUEST;
178
      $error_backtrace['$_COOKIE'] = $_COOKIE;
179
      $error_backtrace['$_SESSION'] = $_SESSION;
180
      $error_backtrace['$_SERVER'] = $_SERVER;
181
      $error_backtrace['user'] = $user;
182
      $error_backtrace['planetrow'] = $planetrow;
183
    }
184
185
    return $error_backtrace;
186
  }
187
188
  function error_fatal($die_message, $details = 'There is a fatal error on page') {
0 ignored issues
show
Unused Code introduced by
The parameter $details is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
189
    // TODO - Записывать детали ошибки в лог-файл
190
    die($die_message);
191
  }
192
193
  function error($message = 'There is a error on page', $title = 'Internal Error', $error_code = 500, $dump = true) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
194
    global $sys_stop_log_hit, $sys_log_disabled, $user;
195
196
    if(empty(classSupernova::$db->connected)) {
197
      // TODO - писать ошибку в файл
198
      die('SQL server currently unavailable. Please contact Administration...');
199
    }
200
201
    sn_db_transaction_rollback();
202
203
    if(classSupernova::$config->debug == 1) {
204
      echo "<h2>{$title}</h2><br><font color=red>{$message}</font><br><hr>";
205
      echo "<table>{$this->log}</table>";
206
    }
207
208
    $fatal_error = 'Fatal error: cannot write to `logs` table. Please contact Administration...';
209
210
    $error_text = db_escape($message);
211
    $error_backtrace = $this->dump($dump, true, strpos($message, 'Deadlock') !== false);
212
213
    $userId = empty($user['id']) ? 0 : $user['id'];
214
215
    if(!$sys_log_disabled) {
216
      $query = "INSERT INTO `{{logs}}` SET
217
        `log_time` = '" . time() . "', `log_code` = '" . db_escape($error_code) . "', `log_sender` = '" . db_escape($userId) . "',
218
        `log_username` = '" . db_escape($user['user_name']) . "', `log_title` = '" . db_escape($title) . "',  `log_text` = '" . db_escape($message) . "',
219
        `log_page` = '" . db_escape(strpos($_SERVER['SCRIPT_NAME'], SN_ROOT_RELATIVE) === false ? $_SERVER['SCRIPT_NAME'] : substr($_SERVER['SCRIPT_NAME'], strlen(SN_ROOT_RELATIVE))) . "'" .
220
//        ($error_backtrace ? ", `log_dump` = '" . db_escape(serialize($error_backtrace)) . "'" : '') . ";";
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% 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...
221
      ", `log_dump` = '" . ($error_backtrace ? db_escape(serialize($error_backtrace)) : '') . "'" . ";";
222
      doquery($query, '', false, true) or die($fatal_error . db_error());
223
224
      $message = "Пожалуйста, свяжитесь с админом, если ошибка повторится. Ошибка №: <b>" . db_insert_id() . "</b>";
225
226
      $sys_stop_log_hit = true;
227
      $sys_log_disabled = true;
228
      !function_exists('message') ? die($message) : message($message, 'Ошибка', '', 0, false);
229
    } else {
230
//        // TODO Здесь надо писать в файло
231
      ob_start();
232
      print("<hr>User ID {$user['id']} raised error code {$error_code} titled '{$title}' with text '{$error_text}' on page {$_SERVER['SCRIPT_NAME']}");
233
234
      foreach($error_backtrace as $name => $value) {
0 ignored issues
show
Bug introduced by
The expression $error_backtrace of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
235
        print(__DEBUG_LINE);
236
        pdump($value, $name);
237
      }
238
      ob_end_flush();
239
      die();
240
    }
241
  }
242
243
  function warning($message, $title = 'System Message', $log_code = 300, $dump = false) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
244
    global $user, $sys_log_disabled;
245
246
    if(empty(classSupernova::$db->connected)) {
247
      // TODO - писать ошибку в файл
248
      die('SQL server currently unavailable. Please contact Administration...');
249
    }
250
251
    $error_backtrace = $this->dump($dump, false);
252
253
    $userId = empty($user['id']) ? 0 : $user['id'];
254
255
    if(!$sys_log_disabled) {
256
      $query = "INSERT INTO `{{logs}}` SET
257
        `log_time` = '" . time() . "', `log_code` = '" . db_escape($log_code) . "', `log_sender` = '" . db_escape($userId) . "',
258
        `log_username` = '" . db_escape($user['user_name']) . "', `log_title` = '" . db_escape($title) . "',  `log_text` = '" . db_escape($message) . "',
259
        `log_page` = '" . db_escape(strpos($_SERVER['SCRIPT_NAME'], SN_ROOT_RELATIVE) === false ? $_SERVER['SCRIPT_NAME'] : substr($_SERVER['SCRIPT_NAME'], strlen(SN_ROOT_RELATIVE))) . "'" .
260
        ", `log_dump` = '" . ($error_backtrace ? db_escape(serialize($error_backtrace)) : '') . "'" . ";";
261
      doquery($query, '', false, true);
262
    } else {
263
//        // TODO Здесь надо писать в файло
264
      print("<hr>User ID {$user['id']} made log entry with code {$log_code} titled '{$title}' with text '{$message}' on page {$_SERVER['SCRIPT_NAME']}");
265
    }
266
  }
267
}
268
269
// Copyright (c) 2009-2010 Gorlum for http://supernova.ws
270
// Dump variables nicer then var_dump()
271
272
function dump($value, $varname = null, $level = 0, $dumper = '') {
0 ignored issues
show
Best Practice introduced by
The function dump() has been defined more than once; this definition is ignored, only the first definition in docs/txt2html.php (L3-51) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
273
  if(isset($varname)) {
274
    $varname .= " = ";
275
  }
276
277 View Code Duplication
  if($level == -1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
278
    $trans[' '] = '&there4;';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$trans was never initialized. Although not strictly required by PHP, it is generally a good practice to add $trans = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
279
    $trans["\t"] = '&rArr;';
280
    $trans["\n"] = '&para;;';
281
    $trans["\r"] = '&lArr;';
282
    $trans["\0"] = '&oplus;';
283
284
    return strtr(htmlspecialchars($value), $trans);
285
  }
286
  if($level == 0) {
287
//    $dumper = '<pre>' . mt_rand(10, 99) . '|' . $varname;
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% 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...
288
    $dumper = mt_rand(10, 99) . '|' . $varname;
289
  }
290
291
  $type = gettype($value);
292
  $dumper .= $type;
293
294 View Code Duplication
  if($type == 'string') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
295
    $dumper .= '(' . strlen($value) . ')';
296
    $value = dump($value, '', -1);
297
  } elseif($type == 'boolean') {
298
    $value = ($value ? 'true' : 'false');
299
  } elseif($type == 'object') {
300
    $props = get_class_vars(get_class($value));
301
    $dumper .= '(' . count($props) . ') <u>' . get_class($value) . '</u>';
302
    foreach($props as $key => $val) {
303
      $dumper .= "\n" . str_repeat("\t", $level + 1) . $key . ' => ';
304
      $dumper .= dump($value->$key, '', $level + 1);
305
    }
306
    $value = '';
307
  } elseif($type == 'array') {
308
    $dumper .= '(' . count($value) . ')';
309
    foreach($value as $key => $val) {
310
      $dumper .= "\n" . str_repeat("\t", $level + 1) . dump($key, '', -1) . ' => ';
311
      $dumper .= dump($val, '', $level + 1);
312
    }
313
    $value = '';
314
  }
315
  $dumper .= " <b>$value</b>";
316
//  if($level == 0) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% 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...
317
//    $dumper .= '</pre>';
318
//  }
319
320
  return $dumper;
321
}
322
323
function pdump($value, $varname = null) {
0 ignored issues
show
Best Practice introduced by
The function pdump() has been defined more than once; this definition is ignored, only the first definition in docs/txt2html.php (L53-56) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
324
  $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
325
//  print_rr($backtrace);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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
//  $backtrace = $backtrace[1];
327
328
  $caller = '';
329
  if(defined('SN_DEBUG_PDUMP_CALLER') && SN_DEBUG_PDUMP_CALLER) {
330
    $caller = (!empty($backtrace[1]['class']) ? $backtrace[1]['class'] : '') .
331
      (!empty($backtrace[1]['type']) ? $backtrace[1]['type'] : '') .
332
      $backtrace[1]['function'] .
333
      (!empty($backtrace[0]['file'])
334
        ? (
335
          ' (' . substr($backtrace[0]['file'], SN_ROOT_PHYSICAL_STR_LEN) .
336
          (!empty($backtrace[0]['line']) ? ':' . $backtrace[0]['line'] : '') .
337
          ')'
338
        )
339
        : ''
340
      );
341
    $caller = "\r\n" . $caller;
342
  }
343
344
  print('<pre style="text-align: left; background-color: #111111; color: #0A0; font-family: Courier, monospace !important; padding: 1em 0; font-weight: 800; font-size: 14px;">' .
0 ignored issues
show
Security Cross-Site Scripting introduced by
'<pre style="text-align:...e) . $caller . '</pre>' can contain request data and is used in output context(s) leading to a potential security vulnerability.

5 paths for user data to reach this point

  1. Path: Read from $_GET, and $error_backtrace is assigned in includes/classes/debug.php on line 175
  1. Read from $_GET, and $error_backtrace is assigned
    in includes/classes/debug.php on line 175
  2. $error_backtrace is assigned
    in includes/classes/debug.php on line 176
  3. $error_backtrace is assigned
    in includes/classes/debug.php on line 177
  4. $error_backtrace is assigned
    in includes/classes/debug.php on line 178
  5. $error_backtrace is assigned
    in includes/classes/debug.php on line 179
  6. $error_backtrace is assigned
    in includes/classes/debug.php on line 180
  7. $error_backtrace is assigned
    in includes/classes/debug.php on line 181
  8. $error_backtrace is assigned
    in includes/classes/debug.php on line 182
  9. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 211
  10. $name is assigned
    in includes/classes/debug.php on line 234
  11. $name is passed to pdump()
    in includes/classes/debug.php on line 236
  2. Path: Read from $_POST, and $error_backtrace is assigned in includes/classes/debug.php on line 176
  1. Read from $_POST, and $error_backtrace is assigned
    in includes/classes/debug.php on line 176
  2. $error_backtrace is assigned
    in includes/classes/debug.php on line 177
  3. $error_backtrace is assigned
    in includes/classes/debug.php on line 178
  4. $error_backtrace is assigned
    in includes/classes/debug.php on line 179
  5. $error_backtrace is assigned
    in includes/classes/debug.php on line 180
  6. $error_backtrace is assigned
    in includes/classes/debug.php on line 181
  7. $error_backtrace is assigned
    in includes/classes/debug.php on line 182
  8. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 211
  9. $name is assigned
    in includes/classes/debug.php on line 234
  10. $name is passed to pdump()
    in includes/classes/debug.php on line 236
  3. Path: Read from $_REQUEST, and $error_backtrace is assigned in includes/classes/debug.php on line 177
  1. Read from $_REQUEST, and $error_backtrace is assigned
    in includes/classes/debug.php on line 177
  2. $error_backtrace is assigned
    in includes/classes/debug.php on line 178
  3. $error_backtrace is assigned
    in includes/classes/debug.php on line 179
  4. $error_backtrace is assigned
    in includes/classes/debug.php on line 180
  5. $error_backtrace is assigned
    in includes/classes/debug.php on line 181
  6. $error_backtrace is assigned
    in includes/classes/debug.php on line 182
  7. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 211
  8. $name is assigned
    in includes/classes/debug.php on line 234
  9. $name is passed to pdump()
    in includes/classes/debug.php on line 236
  4. Path: Read from $_COOKIE, and $error_backtrace is assigned in includes/classes/debug.php on line 178
  1. Read from $_COOKIE, and $error_backtrace is assigned
    in includes/classes/debug.php on line 178
  2. $error_backtrace is assigned
    in includes/classes/debug.php on line 179
  3. $error_backtrace is assigned
    in includes/classes/debug.php on line 180
  4. $error_backtrace is assigned
    in includes/classes/debug.php on line 181
  5. $error_backtrace is assigned
    in includes/classes/debug.php on line 182
  6. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 211
  7. $name is assigned
    in includes/classes/debug.php on line 234
  8. $name is passed to pdump()
    in includes/classes/debug.php on line 236
  5. Path: Read from $_SERVER, and $error_backtrace is assigned in includes/classes/debug.php on line 180
  1. Read from $_SERVER, and $error_backtrace is assigned
    in includes/classes/debug.php on line 180
  2. $error_backtrace is assigned
    in includes/classes/debug.php on line 181
  3. $error_backtrace is assigned
    in includes/classes/debug.php on line 182
  4. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 211
  5. $name is assigned
    in includes/classes/debug.php on line 234
  6. $name is passed to pdump()
    in includes/classes/debug.php on line 236

Preventing Cross-Site-Scripting Attacks

Cross-Site-Scripting allows an attacker to inject malicious code into your website - in particular Javascript code, and have that code executed with the privileges of a visiting user. This can be used to obtain data, or perform actions on behalf of that visiting user.

In order to prevent this, make sure to escape all user-provided data:

// for HTML
$sanitized = htmlentities($tainted, ENT_QUOTES);

// for URLs
$sanitized = urlencode($tainted);

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
345
    dump($value, $varname) .
346
    $caller .
347
    '</pre>'
348
  );
349
}
350
351
function debug($value, $varname = null) {
0 ignored issues
show
Best Practice introduced by
The function debug() has been defined more than once; this definition is ignored, only the first definition in docs/txt2html.php (L58-61) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
352
  pdump($value, $varname);
353
}
354
355
function pr($prePrint = false) {
356
  if($prePrint) {
357
    print(__DEBUG_CRLF);
358
  }
359
  print(mt_rand() . __DEBUG_CRLF);
360
}
361
362
function pc($prePrint = false) {
363
  global $_PRINT_COUNT_VALUE;
364
  $_PRINT_COUNT_VALUE++;
365
366
  if($prePrint) {
367
    print(__DEBUG_CRLF);
368
  }
369
  print($_PRINT_COUNT_VALUE . __DEBUG_CRLF);
370
}
371
372
function prep($message) {
373
  print('<pre>' . $message . '</pre>');
374
}
375
376
function backtrace_no_arg() {
377
  $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
378
  array_shift($trace);
379
380
  return $trace;
381
}
382
383
function pvar_dump($expression) {
384
  print('<pre style="text-align: left; background-color: #111111; color: #0A0; font-family: Courier, monospace !important; padding: 1em 0; font-weight: 800; font-size: 14px;">');
385
  var_dump($expression);
386
  print('</pre>');
387
}
388
389
/**
390
 * Smart die() implementation that knew where it's grave
391
 *
392
 * @param string $message
393
 */
394
function pdie($message = '') {
395
  $backtrace = debug_backtrace();
396
  die(__DEBUG_LINE . ($message ? $message . ' @ ' : '') . $backtrace[0]['file'] . ':' . $backtrace[0]['line']);
397
}
398