errors.php 20.1 KB
Newer Older
1
2
<?php
/**
3
 * This program is part of Mahara
4
 *
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 * @package    mahara
Penny Leach's avatar
Penny Leach committed
20
 * @subpackage core
21
22
23
 * @author     Nigel McNie <nigel@catalyst.net.nz>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006,2007 Catalyst IT Ltd http://catalyst.net.nz
24
25
26
 *
 */

27
28
defined('INTERNAL') || die();

29
30
31
/**#@+
 * @access private
 */
32
// These are bitmaps - the next one should be 4
33
/** Display the errors on the screen */
34
define('LOG_TARGET_SCREEN', 1);
35
/** Write the errors to the error log, as specified in your php configuration */
36
37
38
define('LOG_TARGET_ERRORLOG', 2);

// Logging levels
39
/** Environment type errors, such as register_globals being on */
40
define('LOG_LEVEL_ENVIRON', 1);
41
/** Debug messages */
42
define('LOG_LEVEL_DBG', 2);
43
/** Informational messages */
44
define('LOG_LEVEL_INFO', 4);
45
/** Warnings */
46
define('LOG_LEVEL_WARN', 8);
47
/**#@-*/
48

49
// Tell PHP about our error settings
50
error_reporting(E_ALL);
51
52
set_error_handler('error');
set_exception_handler('exception');
53
54
55
56


// Logging functions

57
58
59
60
61
62
63
64
65
66
/**
 * Logs a message at the debug level
 *
 * @param string $message   The message to display
 * @param bool   $escape    Whether to HTML escape the message
 * @param bool   $backtrace Whether to provide a backtrace if the system is
 *                          configured to give backtraces at this level.
 */
function log_debug ($message, $escape=true, $backtrace=true) {
    log_message($message, LOG_LEVEL_DBG, $escape, $backtrace);
67
68
}

69
70
71
72
73
74
75
76
77
78
/**
 * Logs a message at the info level
 *
 * @param string $message   The message to display
 * @param bool   $escape    Whether to HTML escape the message
 * @param bool   $backtrace Whether to provide a backtrace if the system is
 *                          configured to give backtraces at this level.
 */
function log_info ($message, $escape=true, $backtrace=true) {
    log_message($message, LOG_LEVEL_INFO, $escape, $backtrace);
79
80
}

81
82
83
84
85
86
87
88
89
90
/**
 * Logs a message at the warning level
 *
 * @param string $message   The message to display
 * @param bool   $escape    Whether to HTML escape the message
 * @param bool   $backtrace Whether to provide a backtrace if the system is
 *                          configured to give backtraces at this level.
 */
function log_warn ($message, $escape=true, $backtrace=true) {
    log_message($message, LOG_LEVEL_WARN, $escape, $backtrace);
91
92
}

93
94
95
96
97
98
99
100
101
102
/**
 * Logs a message at the environment level
 *
 * @param string $message   The message to display
 * @param bool   $escape    Whether to HTML escape the message
 * @param bool   $backtrace Whether to provide a backtrace if the system is
 *                          configured to give backtraces at this level.
 */
function log_environ ($message, $escape=true, $backtrace=true) {
    log_message($message, LOG_LEVEL_ENVIRON, $escape, $backtrace);
103
104
}

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
 * Logs a message at the given log level. This function should not be called by
 * any code outside of this module.
 *
 * @param string $message   The message to display
 * @param int    $loglevel  The level to log the message at
 * @param bool   $escape    Whether to HTML escape the message
 * @param bool   $backtrace Whether to provide a backtrace if the system is
 *                          configured to give backtraces at this level.
 * @param string $file      The file the error occured in
 * @param int    $line      The line number the error occured on
 * @param array  $trace     The backtrace for the error
 * @access private
 */
function log_message ($message, $loglevel, $escape, $backtrace, $file=null, $line=null, $trace=null) {
120
    global $SESSION;
121
122
123
124
125
126
127
128
129
130
131
132
    static $loglevelnames = array(
        LOG_LEVEL_ENVIRON => 'environ',
        LOG_LEVEL_DBG     => 'dbg',
        LOG_LEVEL_INFO    => 'info',
        LOG_LEVEL_WARN    => 'warn'
    );

    if (!function_exists('get_config') || null === ($targets = get_config('log_' . $loglevelnames[$loglevel] . '_targets'))) {
        $targets = LOG_TARGET_SCREEN | LOG_TARGET_ERRORLOG;
    }

    // Get nice backtrace information if required
133
    $trace = ($trace) ? $trace : debug_backtrace();
134
135
136
137
138
139
    // If the last caller was the 'error' function then it came from a PHP warning
    if (!is_null($file)) {
        $filename = $file;
        $linenum  = $line;
    }
    else {
140
141
        $filename  = $trace[1]['file'];
        $linenum   = $trace[1]['line'];
142
    }
143

144
    if (!function_exists('get_config') || get_config('log_backtrace_levels') & $loglevel) {
145
        list($textbacktrace, $htmlbacktrace) = log_build_backtrace($trace);
146
147
148
149
150
    }
    else {
        $textbacktrace = $htmlbacktrace = '';
    }

151
152
153
    if (is_bool($message)) {
        $loglines = array(($message ? 'bool(true)' : 'bool(false)'));
    }
154
155
156
    else if (is_null($message)) {
        $loglines = array('NULL');
    }
157
158
159
    else {
        $loglines = explode("\n", print_r($message, true));
    }
160
161
162

    // Make a prefix for each line, if we are logging a normal debug/info/warn message
    if ($loglevel != LOG_LEVEL_ENVIRON && function_exists('get_config')) {
163
164
165
166
167
        $docroot = get_config('docroot');
        $prefixfilename = (substr($filename, 0, strlen($docroot)) == $docroot)
            ? substr($filename, strlen($docroot))
            : $filename;
        $prefix = '(' . $prefixfilename . ':' . $linenum . ') ';
168
169
170
171
    }
    else {
        $prefix = '';
    }
172
    $prefix = '[' . str_pad(substr(strtoupper($loglevelnames[$loglevel]), 0, 3), 3) . '] ' . $prefix;
173
174

    if ($targets & LOG_TARGET_SCREEN) {
175
176
177
178
179
        // Work out which method to call for displaying the message
        if ($loglevel == LOG_LEVEL_DBG || $loglevel == LOG_LEVEL_INFO) {
            $method = 'add_info_msg';
        }
        else {
180
            $method = 'add_error_msg';
181
182
        }

183
        foreach ($loglines as $line) {
184
            if ($escape) {
185
                $line = htmlspecialchars($line, ENT_COMPAT, 'UTF-8');
186
187
                $line = str_replace('  ', '&nbsp; ', $line);
            }
188
189
190
191
            $line = '<div style="font-family: monospace;">' . $prefix . $line . "</div>\n";
            if (is_a($SESSION, 'Session')) {
                $SESSION->$method($line, false);
            }
Nigel McNie's avatar
Nigel McNie committed
192
            else if (!function_exists('get_config') || get_config('installed')) {
193
194
                // Don't output when we are not installed, since this will cause the
                // redirect to the install page to fail.
195
196
                echo $line;
            }
197
        }
198
        if ($backtrace && $htmlbacktrace) {
199
200
201
            if (is_a($SESSION, 'Session')) {
                $SESSION->add_info_msg($htmlbacktrace, false);
            }
202
            else if (!function_exists('get_config') || get_config('installed')) {
203
204
                echo $htmlbacktrace;
            }
205
206
207
208
209
210
211
        }
    }

    if ($targets & LOG_TARGET_ERRORLOG) {
        foreach ($loglines as $line) {
            error_log($prefix . $line);
        }
212
        if ($backtrace && $textbacktrace) {
213
214
215
216
217
218
219
220
            $lines = explode("\n", $textbacktrace);
            foreach ($lines as $line) {
                error_log($line);
            }
        }
    }
}

221
222
223
224
225
226
227
228
229
230
/**
 * Given an array that contains a backtrace, builds two versions of it - one in
 * HTML form and one in text form - for logging.
 *
 * @param array $backtrace The backtrace to build
 * @return array           An array containing the backtraces, index 0
 *                         containing the text version and index 1 containing
 *                         the HTML version.
 * @access private
 */
231
232
233
function log_build_backtrace($backtrace) {
    $calls = array();

234
    // Remove the call to log_message
235
    //array_shift($backtrace);
236

237
238
239
240
241
242
243
244
    foreach ($backtrace as $bt) {
        $bt['file']  = (isset($bt['file'])) ? $bt['file'] : 'Unknown';
        $bt['line']  = (isset($bt['line'])) ? $bt['line'] : 0;
        $bt['class'] = (isset($bt['class'])) ? $bt['class'] : '';
        $bt['type']  = (isset($bt['type'])) ? $bt['type'] : '';
        $bt['args']  = (isset($bt['args'])) ? $bt['args'] : '';

        $args = '';
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        if ($bt['args']) {
            foreach ($bt['args'] as $arg) {
                if (!empty($args)) {
                    $args .= ', ';
                }
                switch (gettype($arg)) {
                    case 'integer':
                    case 'double':
                        $args .= $arg;
                        break;
                    case 'string':
                        $arg = substr($arg, 0, 50) . ((strlen($arg) > 50) ? '...' : '');
                        $args .= '"' . $arg . '"';
                        break;
                    case 'array':
                        $args .= 'array(size ' . count($arg) . ')';
                        break;
                    case 'object':
                        $args .= 'object(' . get_class($arg) . ')';
                        break;
                    case 'resource':
                        $args .= 'resource(' . strstr($arg, '#') . ')';
                        break;
                    case 'boolean':
                        $args .= $arg ? 'true' : 'false';
                        break;
                    case 'NULL':
                        $args .= 'null';
                        break;
                    default:
                        $args .= 'unknown';
                }
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
            }
        }

        $calls[] = array(
            'file'  => $bt['file'],
            'line'  => $bt['line'],
            'class' => $bt['class'],
            'type'  => $bt['type'],
            'func'  => $bt['function'],
            'args'  => $args
        );
    }

    $textmessage = "Call stack (most recent first):\n";
    $htmlmessage = "<pre><strong>Call stack (most recent first):</strong>\n<ul>";

    foreach ($calls as $call) {
        $textmessage .= "  * {$call['class']}{$call['type']}{$call['func']}({$call['args']}) at {$call['file']}:{$call['line']}\n";
        $htmlmessage .= '<li><span style="color:#933;">' . htmlspecialchars($call['class'], ENT_COMPAT, 'UTF-8') . '</span><span style="color:#060;">'
296
            . htmlspecialchars($call['type'], ENT_COMPAT, 'UTF-8') . '</span><span style="color:#339;">' . htmlspecialchars($call['func'], ENT_COMPAT, 'UTF-8')
297
298
299
300
301
302
            . '</span><span style="color:#060;">(</span><span style="color:#f00;">' . htmlspecialchars($call['args'], ENT_COMPAT, 'UTF-8') . '</span><span style="color:#060;">)</span> at <strong>' . htmlspecialchars($call['file'], ENT_COMPAT, 'UTF-8') . ':' . $call['line'] . '</strong></li>';
    }
    $htmlmessage .= "</pre>\n";

    return array($textmessage, $htmlmessage);
}
303
304
305
306
307

/**
 * Ends the script with an informational message
 *
 * @param string $message The message to display
308
 * @todo this function should go away
309
310
311
312
313
314
315
316
317
318
319
 */
function die_info($message) {
    $smarty = smarty();
    $message .= '<p><a href="#" onclick="history.go(-1)">back</a></p>';
    $smarty->assign('message', $message);
    $smarty->assign('type', 'info');
    $smarty->display('message.tpl');
    exit;
}


320
321
// Error/Exception handling

322
323
324
325
326
327
328
329
330
/**
 * Called when any error occurs, due to a PHP error or through a call to
 * {@link trigger_error}.
 *
 * @param int    $code    The code of the error message
 * @param string $message The message reported
 * @param string $file    The file the error was detected in
 * @param string $line    The line number the error was detected on
 * @param array  $vars    The contents of $GLOBALS at the time the error was detected
331
 * @access private
332
 */
333
334
335
function error ($code, $message, $file, $line, $vars) {
    static $error_lookup = array(
        E_NOTICE => 'Notice',
336
337
338
339
340
341
342
        E_WARNING => 'Warning',
        // Not sure if these ever get handled here
        E_ERROR => 'Error',
        // These three are not used by this application but may be used by third parties
        E_USER_NOTICE => 'User Notice',
        E_USER_WARNING => 'User Warning',
        E_USER_ERROR => 'User Error'
343
344
345
346
347
348
349
350
351
352
    );

    if (!error_reporting()) {
        return;
    }

    if (!isset($error_lookup[$code])) {
        return;
    }

353
    // Ignore errors from smarty templates, which happen all too often
354
355
356
357
358
359
    if (function_exists('get_config')) {
        $compiledir = get_config('dataroot') . 'smarty/compile';

        if (E_NOTICE == $code && substr($file, 0, strlen($compiledir)) == $compiledir) {
            return;
        }
360
361
    }

362
363
364
365
    // Fix up the message, which is in HTML form
    $message = strip_tags($message);
    $message = htmlspecialchars_decode($message);

366
    log_message($message, LOG_LEVEL_WARN, true, true, $file, $line);
367
368
}

369
/**
370
371
372
373
374
 * Catches all otherwise uncaught exceptions. Will be deliberately used in some
 * situations. After this is called the script will end, so make sure to catch
 * any exceptions that you can deal with.
 *
 * @param Exception $e The exception that was thrown.
375
 * @access private
376
 */
377
function exception (Exception $e) {
378
379
    global $USER;
    if ($USER) {
380
        $logged = false;
Martyn Smith's avatar
Martyn Smith committed
381
        if (!($e instanceof MaharaException) || get_class($e) == 'MaharaException') {
382
            log_warn("An exception was thrown of class " . get_class($e) . ". \nTHIS IS BAD "
383
384
                     . "and should be changed to something extending MaharaException,\n" 
                     . "unless the exception is from a third party library.\n"
385
386
387
388
389
390
391
392
                     . "Original trace follows", true, false);
            log_message($e->getMessage(), LOG_LEVEL_WARN, true, true, $e->getFile(), $e->getLine(), $e->getTrace());
            $e = new SystemException($e->getMessage());
            $e->set_log_off();
        }
        
        $e->handle_exception($logged);
    }
393
394
395
    else {
        log_message($e->getMessage(), LOG_LEVEL_WARN, true, true, $e->getFile(), $e->getLine(), $e->getTrace());
    }
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
}


interface MaharaThrowable {
    
    public function render_exception();
    
}

// Standard exceptions  - top level exception class. 
// all exceptions should extend one of these three.

/**
 * Very top of the tree for exceptions in Mahara.
 * Nothing should extend this directly. 
 * Contains a few helper functions for all exceptions.
 */
class MaharaException extends Exception {

    protected $log = true;

    public function get_string() {
        $args = func_get_args();
419
        if (function_exists('get_string')) {
420
421
422
423
424
            $args[0] = strtolower(get_class($this)) . $args[0];
            $args[1] = 'error';
            $str = call_user_func_array('get_string', $args);
            if (strpos($str, '[[') !== 0) {
                return $str;
425
426
            }
        }
427
428
429
430
431

        $tag = func_get_arg(0);
        $strings = $this->strings();
        if (array_key_exists($tag, $strings)) {
            return $strings[$tag];
432
        }
433
434
435
436
437
438
439
        
        return 'An error occured';
    }

    public function get_sitename() {
        if (!function_exists('get_config') || !$sitename = @get_config('sitename')) {
            $sitename = 'Mahara';
440
        }
441
442
443
444
445
446
        return $sitename;
    }

    public function strings() {
        return array('title' => $this->get_sitename() . ': Site unavailable');
    }
447

448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
    public function set_log() {
        $this->log = true;
    }

    public function set_log_off() {
        $this->log = false;
    }

    public function render_exception() {
        return $this->getMessage();
    }

    public function handle_exception() {

        $outputtitle = $this->get_string('title');
        $outputmessage = $this->render_exception();
        $message = strip_tags($outputmessage);
        $message = htmlspecialchars_decode($message);
466

467
468
469
470
471
472
        if (function_exists('smarty')) {
            $smarty = smarty();
            $smarty->assign('title', $outputtitle);
            $smarty->assign('message', $outputmessage);
            $smarty->display('error.tpl');
        }
473
        else {
474
475
476
    echo <<<EOF
<html>
<head>
477
    <title>$outputtitle</title>
478
479
480
481
482
483
484
    <style type="text/css">
        #reason {
            margin: 0 3em;
        }
    </style>
</head>
<body>
485
EOF;
Nigel McNie's avatar
Nigel McNie committed
486
    if (function_exists('insert_messages')) {
487
488
489
        echo insert_messages();
    }
    echo <<<EOF
490
<h1>$outputtitle</h1>
491
$outputmessage
492
493
494
495
<hr>
</body>
</html>
EOF;
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
        }
        // end of printing stuff to the screen...
        if (!empty($this->log)) {
            log_message($message, LOG_LEVEL_WARN, true, true, $this->getFile(), $this->getLine(), $this->getTrace());
        }
        die();
    }
}






/**
 * SystemException - this is basically a bug in the system.
 */
class SystemException extends MaharaException implements MaharaThrowable {

    public function render_exception () {
        return $this->get_string('message');
    }

    public function strings() {
        return array_merge(parent::strings(), 
                           array('message' => 'A nonrecoverable error occured. '
                                 . 'This probably means you have encountered a bug in the system'));
    }
    
525
526
}

527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/**
 * ConfigException - something is misconfigured that's causing a problem.
 * Generally these will be the fault of admins
 */
class ConfigException extends MaharaException  implements MaharaThrowable {
     
    public function render_exception () {
        return $this->getMessage();
    }

    public function strings() {
        return array_merge(parent::strings(), 
                           array('message' => $this->get_sitename() 
                           . ' is misconfigured and this is causing problems. '
                           . 'You probably need to contact an administrator to get this fixed.  '
                           . ' Details, if any, follow'));
    }
}

/**
 * UserException - the user has done something they shouldn't (or tried to)
 */
Martyn Smith's avatar
Martyn Smith committed
549
class UserException extends MaharaException implements MaharaThrowable {
550
551

    protected $log = false;
552

553
    public function render_exception() {
554
555
556
557
558
559
560
561
562
563
564
565
        return $this->get_string('message') . '<br><br>' . $this->getMessage();
    }

    public function strings() {
        return array_merge(parent::strings(),  
                           array('message' => 'Something in the way you\'re interacting with ' 
                                 . $this->get_sitename()
                                 .' is causing an error.<br>Details if any, follow'));
    }
}

    
566
567
568

/** 
 * The configuration that Mahara is trying to be run in is insane
569
 */
570
571
572
573
574
class ConfigSanityException extends ConfigException {
    public function strings() {
        return array_merge(parent::strings(), array('message' => ''));
    }
}
575
576

/**
577
 * An SQL related error occured
578
 */
579
580
581
582
583
584
585
586
587
class SQLException extends SystemException {
    public function handle_exception() {
        if (!empty($GLOBALS['_TRANSACTION_STARTED'])) {
            db_rollback();
        }
        log_warn($this->getMessage());
        parent::handle_exception();
    }
}
588

589
590
591
/**
 * An exception generated by invalid GET or POST parameters
 */
592
class ParameterException extends UserException {
593
    public function strings() {
594
595
596
        return array_merge(parent::strings(), array('message' => 'A required parameter was missing'));
    }
}
597

598
599
600
/**
 * An exception generated when e-mail can't be sent
 */
601
class EmailException extends SystemException {}
602

603
604
605
/** 
 * Exception - artefact not found 
 */
606
class ArtefactNotFoundException extends UserException {}
607
608
609
610

/**
 * Exception - view not found
 */
611
612
class ViewNotFoundException extends UserException {}

613
614
615
616

/**
 * Exception - anything to do with template parsing
 */
617
class TemplateParserException extends ConfigException {}
Penny Leach's avatar
Penny Leach committed
618
619
620
621

/**
 * Exception - Access denied. Throw this if a user is trying to view something they can't
 */
622
623
624
625
626
627
628
629
630
631
632
633
634
635
class AccessDeniedException extends UserException {
    public function strings() {
        return array_merge(parent::strings(), 
                           array('message' => 'You do not have access to view this page',
                                 'title' => 'Access denied'));
    }

    public function render_exception() {
        header("HTTP/1.0 403 Forbidden", true);
        return parent::render_exception();
    }
}


636
?>