Completed
Push — work-fleets ( 2bd11a...17dd3b )
by SuperNova.WS
06:36
created

debug::compact_backtrace()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 21
c 1
b 0
f 0
nc 10
nop 2
dl 0
loc 34
rs 8.439
ccs 0
cts 24
cp 0
crap 42
1
<?php
2
/**
3
 * Some helpers to sweeten dev's life
4
 */
5
6
use \DBAL\DbTransaction;
7
8
/*
9
 * debug.php ::  Clase Debug, maneja reporte de eventos
10
 *
11
 * V4.0 copyright 2010-2011 by Gorlum for http://supernova.ws
12
 *  [!] Merged `errors` to `logs`
13
 *  [+] Now debugger can work with database detached. All messages would be dumped to page
14
 *  [+] Now `logs` has both human-readable and machine-readable fields
15
 *
16
 * V3.0 copyright 2010 by Gorlum for http://supernova.ws
17
 *  [+] Full rewrtie & optimize
18
 *  [*] Now there is fallback procedure if no link to db detected
19
 *
20
 * V2.0 copyright 2010 by Gorlum for http://supernova.ws
21
 *  [*] Now error also contains backtrace - to see exact way problem comes
22
 *  [*] New method 'warning' sends message to dedicated SQL-table for non-errors
23
 *
24
 * V1.0 Created by Perberos. All rights reversed (C) 2006
25
 *
26
 *  Experiment code!!!
27
 *
28
 * vamos a experimentar >:)
29
 * le veo futuro a las classes, ayudaria mucho a tener un codigo mas ordenado...
30
 * que esperabas!!! soy newbie!!! D':<
31
*/
32
33
defined('INSIDE') || die();
34
35
if(php_sapi_name() == "cli") {
36
  // In cli-mode
37
  define('__DEBUG_CRLF', "\r\n");
38
  define('__DEBUG_LINE', '-------------------------------------------------' . __DEBUG_CRLF);
39
} else {
40
  // Not in cli-mode
41
  define('__DEBUG_CRLF', '<br />');
42
  define('__DEBUG_LINE', '<hr />');
43
}
44
45
46
class debug {
47
  var $log, $numqueries;
48
  var $log_array;
49
50
  private $log_file_handler = null;
51
52
  public function log_file($message, $ident_change = 0) {
53
    static $ident = 0;
54
55
    if(!defined('SN_DEBUG_LOG')) {
56
      return;
57
    }
58
59
    if($this->log_file_handler === null) {
60
      $this->log_file_handler = @fopen(SN_ROOT_PHYSICAL . '/.logs/supernova.log', 'a+');
61
      @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...
62
    }
63
    $ident_change < 0 ? $ident += $ident_change * 2 : false;
64
    if($this->log_file_handler) {
65
      @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...
66
    }
67
    $ident_change > 0 ? $ident += $ident_change * 2 : false;
68
  }
69
70
  public function debug() {
71
    $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...
72
    $this->numqueries = 0;
73
  }
74
75
  public function add($mes) {
76
    $this->log .= $mes;
77
    $this->numqueries++;
78
  }
79
80
  public function add_to_array($mes) {
81
    $this->log_array[] = $mes;
82
  }
83
84
  public function echo_log() {
85
    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>";
86
    die();
87
  }
88
89
  public function compact_backtrace($backtrace, $long_comment = false) {
90
    static $exclude_functions = array('doquery', 'db_query', 'db_get_record_list', 'db_user_by_id', 'db_get_user_by_id');
91
92
    $result = array();
93
    $transaction_id = classSupernova::$db->getTransaction()->getNextQueryTransactionId();
94
    $result[] = "tID {$transaction_id}";
95
    foreach($backtrace as $a_trace) {
96
      if(in_array($a_trace['function'], $exclude_functions)) {
97
        continue;
98
      }
99
      $function =
100
        ($a_trace['type']
101
          ? ($a_trace['type'] == '->'
102
            ? "({$a_trace['class']})" . get_class($a_trace['object'])
103
            : $a_trace['class']
104
          ) . $a_trace['type']
105
          : ''
106
        ) . $a_trace['function'] . '()';
107
108
      $file = str_replace(SN_ROOT_PHYSICAL, '', str_replace('\\', '/', $a_trace['file']));
109
110
      // $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...
111
      $result[] = "{$function} - '{$file}' Line {$a_trace['line']}";
112
113
      if(!$long_comment) {
114
        break;
115
      }
116
    }
117
118
119
    // $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...
120
121
    return $result;
122
  }
123
124
  public function dump($dump = false, $force_base = false, $deadlock = false) {
125
    global $user, $planetrow;
126
127
    if($dump === false) {
128
      return;
129
    }
130
131
    $error_backtrace = array();
132
    $base_dump = false;
133
134
    if($force_base === true) {
135
      $base_dump = true;
136
    }
137
138
    if($dump === true) {
139
      $base_dump = true;
140
    } else {
141
      if(!is_array($dump)) {
142
        $dump = array('var' => $dump);
143
      }
144
145
      foreach($dump as $dump_var_name => $dump_var) {
146
        if($dump_var_name == 'base_dump') {
147
          $base_dump = $dump_var;
148
        } else {
149
          $error_backtrace[$dump_var_name] = $dump_var;
150
        }
151
      }
152
    }
153
154
    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...
155
      $error_backtrace['deadlock'] = explode("\n", $q['Status']);
156
      $error_backtrace['locks'] = SnCache::getLocks();
157
      $error_backtrace['cSN_data'] = SnCache::getData();
158
      foreach($error_backtrace['cSN_data'] as &$location) {
159
        foreach($location as $location_id => &$location_data) {
160
          $location_data = isset($location_data['username']) ? $location_data['username'] :
161
            (isset($location_data['name']) ? $location_data['name'] : $location_id);
162
        }
163
      }
164
      $error_backtrace['cSN_queries'] = SnCache::getQueries();
165
    }
166
167
    if($base_dump) {
168
      if(is_array($this->log_array) && count($this->log_array) > 0) {
169
        foreach($this->log_array as $log) {
170
          $error_backtrace['queries'][] = $log;
171
        }
172
      }
173
174
      $error_backtrace['backtrace'] = debug_backtrace();
175
      unset($error_backtrace['backtrace'][1]);
176
      unset($error_backtrace['backtrace'][0]);
177
      $error_backtrace['$_GET'] = $_GET;
178
      $error_backtrace['$_POST'] = $_POST;
179
      $error_backtrace['$_REQUEST'] = $_REQUEST;
180
      $error_backtrace['$_COOKIE'] = $_COOKIE;
181
      $error_backtrace['$_SESSION'] = $_SESSION;
182
      $error_backtrace['$_SERVER'] = $_SERVER;
183
      $error_backtrace['user'] = $user;
184
      $error_backtrace['planetrow'] = $planetrow;
185
    }
186
187
    return $error_backtrace;
188
  }
189
190
  public 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...
191
    // TODO - Записывать детали ошибки в лог-файл
192
    die($die_message);
193
  }
194
195
  public function error($message = 'There is a error on page', $title = 'Internal Error', $error_code = 500, $dump = true) {
196
    global $sys_stop_log_hit, $sys_log_disabled, $user;
197
198
    if(empty(classSupernova::$db->connected)) {
199
      // TODO - писать ошибку в файл
200
      die('SQL server currently unavailable. Please contact Administration...');
201
    }
202
203
    sn_db_transaction_rollback();
204
205
    if(classSupernova::$config->debug == 1) {
206
      echo "<h2>{$title}</h2><br><font color=red>{$message}</font><br><hr>";
207
      echo "<table>{$this->log}</table>";
208
    }
209
210
    $fatal_error = 'Fatal error: cannot write to `logs` table. Please contact Administration...';
211
212
    $error_text = db_escape($message);
213
    $error_backtrace = $this->dump($dump, true, strpos($message, 'Deadlock') !== false);
214
215
    $userId = empty($user['id']) ? 0 : $user['id'];
216
217
    if(!$sys_log_disabled) {
218
      $query = "INSERT INTO `{{logs}}` SET
219
        `log_time` = '" . time() . "', `log_code` = '" . db_escape($error_code) . "', `log_sender` = '" . db_escape($userId) . "',
220
        `log_username` = '" . db_escape($user['user_name']) . "', `log_title` = '" . db_escape($title) . "',  `log_text` = '" . db_escape($message) . "',
221
        `log_page` = '" . db_escape(strpos($_SERVER['SCRIPT_NAME'], SN_ROOT_RELATIVE) === false ? $_SERVER['SCRIPT_NAME'] : substr($_SERVER['SCRIPT_NAME'], strlen(SN_ROOT_RELATIVE))) . "'" .
222
//        ($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...
223
      ", `log_dump` = '" . ($error_backtrace ? db_escape(serialize($error_backtrace)) : '') . "'" . ";";
224
      classSupernova::$db->doExecute($query, true) or die($fatal_error . classSupernova::$db->db_error());
225
226
      $message = "Пожалуйста, свяжитесь с админом, если ошибка повторится. Ошибка №: <b>" . classSupernova::$db->db_insert_id() . "</b>";
227
228
      $sys_stop_log_hit = true;
229
      $sys_log_disabled = true;
230
      !function_exists('message') ? die($message) : message($message, 'Ошибка', '', 0, false);
231
    } else {
232
//        // TODO Здесь надо писать в файло
233
      ob_start();
234
      print("<hr>User ID {$user['id']} raised error code {$error_code} titled '{$title}' with text '{$error_text}' on page {$_SERVER['SCRIPT_NAME']}");
235
236
      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...
237
        print(__DEBUG_LINE);
238
        pdump($value, $name);
239
      }
240
      ob_end_flush();
241
      die();
242
    }
243
  }
244
245
  public function warning($message, $title = 'System Message', $log_code = 300, $dump = false) {
246
    global $user, $sys_log_disabled;
247
248
    if(empty(classSupernova::$db->connected)) {
249
      // TODO - писать ошибку в файл
250
      die('SQL server currently unavailable. Please contact Administration...');
251
    }
252
253
    $error_backtrace = $this->dump($dump, false);
254
255
    $userId = empty($user['id']) ? 0 : $user['id'];
256
257
    if(!$sys_log_disabled) {
258
      $query = "INSERT INTO `{{logs}}` SET
259
        `log_time` = '" . time() . "', `log_code` = '" . db_escape($log_code) . "', `log_sender` = '" . db_escape($userId) . "',
260
        `log_username` = '" . db_escape($user['user_name']) . "', `log_title` = '" . db_escape($title) . "',  `log_text` = '" . db_escape($message) . "',
261
        `log_page` = '" . db_escape(strpos($_SERVER['SCRIPT_NAME'], SN_ROOT_RELATIVE) === false ? $_SERVER['SCRIPT_NAME'] : substr($_SERVER['SCRIPT_NAME'], strlen(SN_ROOT_RELATIVE))) . "'" .
262
        ", `log_dump` = '" . ($error_backtrace ? db_escape(serialize($error_backtrace)) : '') . "'" . ";";
263
      classSupernova::$db->doExecute($query, true);
264
    } else {
265
//        // TODO Здесь надо писать в файло
266
      print("<hr>User ID {$user['id']} made log entry with code {$log_code} titled '{$title}' with text '{$message}' on page {$_SERVER['SCRIPT_NAME']}");
267
    }
268
  }
269
}
270
271
// Copyright (c) 2009-2010 Gorlum for http://supernova.ws
272
// Dump variables nicer then var_dump()
273
274
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...
275
  if(isset($varname)) {
276
    $varname .= " = ";
277
  }
278
279
  if($level == -1) {
280
    $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...
281
    $trans["\t"] = '&rArr;';
282
    $trans["\n"] = '&para;;';
283
    $trans["\r"] = '&lArr;';
284
    $trans["\0"] = '&oplus;';
285
286
    return strtr(htmlspecialchars($value), $trans);
287
  }
288
  if($level == 0) {
289
//    $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...
290
    $dumper = mt_rand(10, 99) . '|' . $varname;
291
  }
292
293
  $type = gettype($value);
294
  $dumper .= $type;
295
296
  if($type == TYPE_STRING) {
297
    $dumper .= '(' . strlen($value) . ')';
298
    $value = dump($value, '', -1);
299
  } elseif($type == TYPE_BOOLEAN) {
300
    $value = ($value ? 'true' : 'false');
301
  } elseif($type == 'object') {
302
    $props = get_class_vars(get_class($value));
303
    $dumper .= '(' . count($props) . ') <u>' . get_class($value) . '</u>';
304
    foreach($props as $key => $val) {
305
      $dumper .= "\n" . str_repeat("\t", $level + 1) . $key . ' => ';
306
      $dumper .= dump($value->$key, '', $level + 1);
307
    }
308
    $value = '';
309 View Code Duplication
  } elseif($type == TYPE_ARRAY) {
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...
310
    $dumper .= '(' . count($value) . ')';
311
    foreach($value as $key => $val) {
312
      $dumper .= "\n" . str_repeat("\t", $level + 1) . dump($key, '', -1) . ' => ';
313
      $dumper .= dump($val, '', $level + 1);
314
    }
315
    $value = '';
316
  }
317
  $dumper .= " <b>$value</b>";
318
//  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...
319
//    $dumper .= '</pre>';
320
//  }
321
322
  return $dumper;
323
}
324
325
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...
326
  $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
327
//  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...
328
//  $backtrace = $backtrace[1];
329
330
  $caller = '';
331
  if(defined('SN_DEBUG_PDUMP_CALLER') && SN_DEBUG_PDUMP_CALLER) {
332
    $caller = (!empty($backtrace[1]['class']) ? $backtrace[1]['class'] : '') .
333
      (!empty($backtrace[1]['type']) ? $backtrace[1]['type'] : '') .
334
      $backtrace[1]['function'] .
335
      (!empty($backtrace[0]['file'])
336
        ? (
337
          ' (' . substr($backtrace[0]['file'], SN_ROOT_PHYSICAL_STR_LEN) .
338
          (!empty($backtrace[0]['line']) ? ':' . $backtrace[0]['line'] : '') .
339
          ')'
340
        )
341
        : ''
342
      );
343
    $caller = "\r\n" . $caller;
344
  }
345
346
  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 177
  1. Read from $_GET, 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. $error_backtrace is assigned
    in includes/classes/debug.php on line 183
  8. $error_backtrace is assigned
    in includes/classes/debug.php on line 184
  9. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 213
  10. $name is assigned
    in includes/classes/debug.php on line 236
  11. $name is passed to pdump()
    in includes/classes/debug.php on line 238
  2. Path: Read from $_POST, and $error_backtrace is assigned in includes/classes/debug.php on line 178
  1. Read from $_POST, 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. $error_backtrace is assigned
    in includes/classes/debug.php on line 183
  7. $error_backtrace is assigned
    in includes/classes/debug.php on line 184
  8. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 213
  9. $name is assigned
    in includes/classes/debug.php on line 236
  10. $name is passed to pdump()
    in includes/classes/debug.php on line 238
  3. Path: Read from $_REQUEST, and $error_backtrace is assigned in includes/classes/debug.php on line 179
  1. Read from $_REQUEST, and $error_backtrace is assigned
    in includes/classes/debug.php on line 179
  2. $error_backtrace is assigned
    in includes/classes/debug.php on line 180
  3. $error_backtrace is assigned
    in includes/classes/debug.php on line 181
  4. $error_backtrace is assigned
    in includes/classes/debug.php on line 182
  5. $error_backtrace is assigned
    in includes/classes/debug.php on line 183
  6. $error_backtrace is assigned
    in includes/classes/debug.php on line 184
  7. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 213
  8. $name is assigned
    in includes/classes/debug.php on line 236
  9. $name is passed to pdump()
    in includes/classes/debug.php on line 238
  4. Path: Read from $_COOKIE, and $error_backtrace is assigned in includes/classes/debug.php on line 180
  1. Read from $_COOKIE, 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. $error_backtrace is assigned
    in includes/classes/debug.php on line 183
  5. $error_backtrace is assigned
    in includes/classes/debug.php on line 184
  6. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 213
  7. $name is assigned
    in includes/classes/debug.php on line 236
  8. $name is passed to pdump()
    in includes/classes/debug.php on line 238
  5. Path: Read from $_SERVER, and $error_backtrace is assigned in includes/classes/debug.php on line 182
  1. Read from $_SERVER, and $error_backtrace is assigned
    in includes/classes/debug.php on line 182
  2. $error_backtrace is assigned
    in includes/classes/debug.php on line 183
  3. $error_backtrace is assigned
    in includes/classes/debug.php on line 184
  4. debug::dump() returns tainted data, and $error_backtrace is assigned
    in includes/classes/debug.php on line 213
  5. $name is assigned
    in includes/classes/debug.php on line 236
  6. $name is passed to pdump()
    in includes/classes/debug.php on line 238

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...
347
    dump($value, $varname) .
348
    $caller .
349
    '</pre>'
350
  );
351
}
352
353
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...
354
  pdump($value, $varname);
355
}
356
357
function pr($prePrint = false) {
358
  if($prePrint) {
359
    print(__DEBUG_CRLF);
360
  }
361
  print(mt_rand() . __DEBUG_CRLF);
362
}
363
364
function pc($prePrint = false) {
365
  global $_PRINT_COUNT_VALUE;
366
  $_PRINT_COUNT_VALUE++;
367
368
  if($prePrint) {
369
    print(__DEBUG_CRLF);
370
  }
371
  print($_PRINT_COUNT_VALUE . __DEBUG_CRLF);
372
}
373
374
function prep($message) {
375
  print('<pre>' . $message . '</pre>');
376
}
377
378
function backtrace_no_arg() {
379
  $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
380
  array_shift($trace);
381
382
  return $trace;
383
}
384
385
function pvar_dump($expression) {
386
  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;">');
387
  var_dump($expression);
388
  print('</pre>');
389
}
390
391
/**
392
 * Smart die() implementation that knew where it's grave
393
 *
394
 * @param string $message
395
 * @param int $level - shift backtrace to X levels back
396
 */
397
function pdie($message = '', $level = 0) {
398
  $backtrace = debug_backtrace();
399
  for($i = 0; $i < $level; $i++) {
400
    array_pop($backtrace);
401
  }
402
403
  die(__DEBUG_LINE . ($message ? $message . ' @ ' : '') . $backtrace[0]['file'] . ':' . $backtrace[0]['line']);
404
}
405