errors.php 9.61 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
20
21
22
23
 *  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
 * @subpackage core or plugintype/pluginname
 * @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
32
33
34
35
36
37
38
39
40
41
42
43
44
// These are bitmaps - the next one should be 4
define('LOG_TARGET_SCREEN', 1);
define('LOG_TARGET_ERRORLOG', 2);

// Logging levels
define('LOG_LEVEL_ENVIRON', 1);
define('LOG_LEVEL_DBG', 2);
define('LOG_LEVEL_INFO', 4);
define('LOG_LEVEL_WARN', 8);

// Turn error reporting all the way up
error_reporting(E_ALL);


// Logging functions

45
46
function log_dbg ($message, $escape=true) {
    log_message($message, LOG_LEVEL_DBG, $escape);
47
48
}

49
50
function log_info ($message, $escape=true) {
    log_message($message, LOG_LEVEL_INFO, $escape);
51
52
}

53
54
function log_warn ($message, $escape=true) {
    log_message($message, LOG_LEVEL_WARN, $escape);
55
56
}

57
58
function log_environ ($message, $escape=true) {
    log_message($message, LOG_LEVEL_ENVIRON, $escape);
59
60
}

61
62
function log_message ($message, $loglevel, $escape, $file=null, $line=null) {
    global $SESSION;
63
64
65
66
67
68
69
70
71
72
73
74
75
    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
    $backtrace = debug_backtrace();
76
77
78
79
80
81
82
83
84
85
    // If the last caller was the 'error' function then it came from a PHP warning
    //print_r($backtrace);
    if (!is_null($file)) {
        $filename = $file;
        $linenum  = $line;
    }
    else {
        $filename  = $backtrace[1]['file'];
        $linenum   = $backtrace[1]['line'];
    }
86

87
    if (!function_exists('get_config') || get_config('log_backtrace_levels') & $loglevel) {
88
89
90
91
92
93
94
95
96
97
        list($textbacktrace, $htmlbacktrace) = log_build_backtrace(debug_backtrace());
    }
    else {
        $textbacktrace = $htmlbacktrace = '';
    }

    $loglines = explode("\n", print_r($message, true));

    // 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')) {
98
99
100
101
102
        $docroot = get_config('docroot');
        $prefixfilename = (substr($filename, 0, strlen($docroot)) == $docroot)
            ? substr($filename, strlen($docroot))
            : $filename;
        $prefix = '(' . $prefixfilename . ':' . $linenum . ') ';
103
104
105
106
107
108
    }
    else {
        $prefix = '';
    }

    if ($targets & LOG_TARGET_SCREEN) {
109
110
111
112
113
114
115
116
        // Work out which method to call for displaying the message
        if ($loglevel == LOG_LEVEL_DBG || $loglevel == LOG_LEVEL_INFO) {
            $method = 'add_info_msg';
        }
        else {
            $method = 'add_err_msg';
        }

117
        foreach ($loglines as $line) {
118
119
120
121
            if ($escape) {
                $line =htmlspecialchars($line, ENT_COMPAT, 'UTF-8');
                $line = str_replace('  ', '&nbsp; ', $line);
            }
122
123
124
125
126
127
128
            $line = '<div style="font-family: monospace;">' . $prefix . $line . "</div>\n";
            if (is_a($SESSION, 'Session')) {
                $SESSION->$method($line, false);
            }
            else {
                echo $line;
            }
129
130
        }
        if ($htmlbacktrace) {
131
132
133
134
135
136
            if (is_a($SESSION, 'Session')) {
                $SESSION->add_info_msg($htmlbacktrace, false);
            }
            else {
                echo $htmlbacktrace;
            }
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
        }
    }

    if ($targets & LOG_TARGET_ERRORLOG) {
        foreach ($loglines as $line) {
            error_log($prefix . $line);
        }
        if ($textbacktrace) {
            $lines = explode("\n", $textbacktrace);
            foreach ($lines as $line) {
                error_log($line);
            }
        }
    }
}


function log_build_backtrace($backtrace) {
    $calls = array();

157
158
159
    // Remove the call to log_message
    array_shift($backtrace);

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
    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 = '';
        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';
            }
        }

        $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;">'
            . htmlspecialchars($call['type'], ENT_COMPAT, 'UTF-8') . '</span><span style="color:#933;">' . htmlspecialchars($call['func'], ENT_COMPAT, 'UTF-8')
            . '</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);
}
// Error/Exception handling

set_error_handler('error');
function error ($code, $message, $file, $line, $vars) {
    static $error_lookup = array(
        E_NOTICE => 'Notice',
230
231
232
233
234
235
236
        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'
237
238
239
240
241
242
243
244
245
246
    );

    if (!error_reporting()) {
        return;
    }

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

247
248
249
250
251
252
    // Ignore errors from smarty templates, which happen all too often
    $compiledir = get_config('dataroot') . 'smarty/compile';
    if (E_NOTICE == $code && substr($file, 0, strlen($compiledir)) == $compiledir) {
        return;
    }

253
254
255
256
    // Fix up the message, which is in HTML form
    $message = strip_tags($message);
    $message = htmlspecialchars_decode($message);

257
    log_message($message, LOG_LEVEL_WARN, true, $file, $line);
258
259
}

260
261
262

// Standard exceptions
class ConfigSanityException extends Exception {}
263
class DatalibException extends Exception {}
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

// Catch exceptions that fall through to main()
set_exception_handler('exception');

function exception ($e) {
    // @todo<nigel>: maybe later, rewrite as:
    // if $e not Exception
    //     get language string based on class name
    // rather than by switch on class name
    switch (get_class($e)) {
        case 'ConfigSanityException':
            $message = get_string('configsanityexception', 'error', $e->getMessage());
            break;
        default:
            $message = $e->getMessage();
    }

281
282
    log_warn($message);

283
284
285
286
287
288
289
290
291
292
293
    echo <<<EOF
<html>
<head>
    <title>\$projectname - Site Unavailable</title>
    <style type="text/css">
        #reason {
            margin: 0 3em;
        }
    </style>
</head>
<body>
294
EOF;
Nigel McNie's avatar
Nigel McNie committed
295
    if (function_exists('insert_messages')) {
296
297
298
299
        echo insert_messages();
    }
    echo <<<EOF
<h1>OMGWTF</h1>
300
301
302
303
304
305
306
307
308
<p>$message</p>
<hr>
<p>@todo&lt;nigel&gt;: make this page more shiny :)</p>
</body>
</html>
EOF;
    die();
}

309

310
?>