errors.php 21.7 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
184
185
186
187
188
189
190
191
        $message = implode("\n", $loglines);
        if ($escape) {
            $message = htmlspecialchars($message, ENT_COMPAT, 'UTF-8');
            $message = str_replace('  ', '&nbsp; ', $message);
        }
        $message = nl2br($message);
        $message = '<div style="font-family: monospace;">' . $prefix . $message . "</div>\n";
        if (is_a($SESSION, 'Session')) {
            $SESSION->$method($message, false);
192
        }
193
194
195
196
197
198
        else if (!function_exists('get_config') || get_config('installed')) {
            // Don't output when we are not installed, since this will cause the
            // redirect to the install page to fail.
            echo $message;
        }

199
        if ($backtrace && $htmlbacktrace) {
200
201
202
            if (is_a($SESSION, 'Session')) {
                $SESSION->add_info_msg($htmlbacktrace, false);
            }
203
            else if (!function_exists('get_config') || get_config('installed')) {
204
205
                echo $htmlbacktrace;
            }
206
207
208
209
210
211
212
        }
    }

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

222
223
224
225
226
227
228
229
230
231
/**
 * 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
 */
232
233
234
function log_build_backtrace($backtrace) {
    $calls = array();

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

238
239
240
241
242
243
244
245
    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 = '';
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
277
        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';
                }
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
            }
        }

        $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;">'
297
            . htmlspecialchars($call['type'], ENT_COMPAT, 'UTF-8') . '</span><span style="color:#339;">' . htmlspecialchars($call['func'], ENT_COMPAT, 'UTF-8')
298
299
300
301
302
303
            . '</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);
}
304
305
306
307
308

/**
 * Ends the script with an informational message
 *
 * @param string $message The message to display
309
 * @todo this function should go away
310
311
312
313
314
315
316
317
318
319
 */
function die_info($message) {
    $smarty = smarty();
    $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) {
Martyn Smith's avatar
Martyn Smith committed
380
        if (!($e instanceof MaharaException) || get_class($e) == 'MaharaException') {
381
            log_warn("An exception was thrown of class " . get_class($e) . ". \nTHIS IS BAD "
382
383
                     . "and should be changed to something extending MaharaException,\n" 
                     . "unless the exception is from a third party library.\n"
384
385
386
387
388
                     . "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();
        }
389
    }
390
    $e->handle_exception();
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
}


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();
414
        if (function_exists('get_string')) {
415
416
417
418
419
            $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;
420
421
            }
        }
422
423
424
425
426

        $tag = func_get_arg(0);
        $strings = $this->strings();
        if (array_key_exists($tag, $strings)) {
            return $strings[$tag];
427
        }
428
429
430
431
432
433
434
        
        return 'An error occured';
    }

    public function get_sitename() {
        if (!function_exists('get_config') || !$sitename = @get_config('sitename')) {
            $sitename = 'Mahara';
435
        }
436
437
438
439
440
441
        return $sitename;
    }

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

443
444
445
446
447
448
449
450
451
452
453
454
455
456
    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() {

457
        if (!empty($this->log)) {
458
            log_message($this->getMessage(), LOG_LEVEL_WARN, true, true, $this->getFile(), $this->getLine(), $this->getTrace());
459
460
461
462
463
464
465
466
        }

        if (defined('JSON')) { // behave differently
            @header('Content-type: text/plain');
            @header('Pragma: no-cache');
            echo json_encode(array('error' => true, 'message' => $this->render_exception()));
            exit;
        }
467
468
469
470
471
        
        if (defined('CRON')) {
            echo $this->render_exception();
            exit;
        }
472

473
474
475
476
        $outputtitle = $this->get_string('title');
        $outputmessage = $this->render_exception();
        $message = strip_tags($outputmessage);
        $message = htmlspecialchars_decode($message);
477

478
479
480
481
482
483
        if (function_exists('smarty')) {
            $smarty = smarty();
            $smarty->assign('title', $outputtitle);
            $smarty->assign('message', $outputmessage);
            $smarty->display('error.tpl');
        }
484
        else {
485
486
487
    echo <<<EOF
<html>
<head>
488
    <title>$outputtitle</title>
489
    <style type="text/css">
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
        html {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
        }
        body {
            width: 600px;
            margin: 100px auto;
            font-size: 12px;
        }
        h1 {
            color: #547c22;
            font-size: 20px;
            font-weight: normal;	
            margin: 0 0 5px 0;
            padding: 0;
            text-transform: capitalize;
            border-bottom: 1px solid #819f18;
            text-align: center;
        }
        #message {
            width: 90%;
            margin: 0 auto;
            text-align: justify;
        }
515
516
517
518
519
520
        #reason {
            margin: 0 3em;
        }
    </style>
</head>
<body>
521
EOF;
Nigel McNie's avatar
Nigel McNie committed
522
    if (function_exists('insert_messages')) {
523
524
525
        echo insert_messages();
    }
    echo <<<EOF
526
<h1>$outputtitle</h1>
527
<div id="message">$outputmessage</div>
528
529
530
</body>
</html>
EOF;
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
        }
        // end of printing stuff to the screen...
        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'));
    }
    
557
558
}

559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
/**
 * 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.  '
Penny Leach's avatar
Penny Leach committed
574
                           . ' Details, if any, follow:'));
575
576
577
578
579
580
    }
}

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

    protected $log = false;
584

585
    public function render_exception() {
586
587
588
589
590
591
592
        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()
Penny Leach's avatar
Penny Leach committed
593
                                 .' is causing an error.<br>Details if any, follow:'));
594
595
596
597
    }
}

    
598
599
600

/** 
 * The configuration that Mahara is trying to be run in is insane
601
 */
602
603
604
605
606
class ConfigSanityException extends ConfigException {
    public function strings() {
        return array_merge(parent::strings(), array('message' => ''));
    }
}
607
608

/**
609
 * An SQL related error occured
610
 */
611
612
613
614
615
616
617
618
619
class SQLException extends SystemException {
    public function handle_exception() {
        if (!empty($GLOBALS['_TRANSACTION_STARTED'])) {
            db_rollback();
        }
        log_warn($this->getMessage());
        parent::handle_exception();
    }
}
620

621
622
623
/**
 * An exception generated by invalid GET or POST parameters
 */
624
class ParameterException extends UserException {
625
    public function strings() {
626
627
628
        return array_merge(parent::strings(), array('message' => 'A required parameter was missing'));
    }
}
629

630
631
632
/**
 * An exception generated when e-mail can't be sent
 */
633
class EmailException extends SystemException {}
634

635
636
637
/** 
 * Exception - artefact not found 
 */
638
class ArtefactNotFoundException extends UserException {}
639
640
641
642

/**
 * Exception - view not found
 */
643
644
class ViewNotFoundException extends UserException {}

Penny Leach's avatar
Penny Leach committed
645
646
647
648
/**
 * Exception - user not found
 */
class UserNotFoundException extends UserException {}
649

650
651
652
653
654
/**
 * Exception - community not found
 */
class CommunityNotFoundException extends UserException {}

Martyn Smith's avatar
Martyn Smith committed
655
656
657
658
659
/**
 * Exception - fired when something happens that would make the user exceed their quota
 */
class QuotaExceededException extends UserException {}

660
661
662
/**
 * Exception - anything to do with template parsing
 */
663
class TemplateParserException extends ConfigException {}
Penny Leach's avatar
Penny Leach committed
664
665
666
667

/**
 * Exception - Access denied. Throw this if a user is trying to view something they can't
 */
668
669
670
671
672
673
674
675
676
677
678
679
680
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();
    }
}

681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/**
 * Exception - Not found. Throw this if a user is trying to view something
 * that doesn't exist
 */
class NotFoundException extends UserException {
    public function strings() {
        return array_merge(parent::strings(), 
                           array('message' => 'The page you are looking for could not be found',
                                 'title' => 'Not found'));
    }

    public function render_exception() {
        header('HTTP/1.0 404 Not Found', true);
        return parent::render_exception();
    }
}

698

699
?>