errors.php 34.9 KB
Newer Older
1 2
<?php
/**
3 4
 *
 * @package    mahara
Penny Leach's avatar
Penny Leach committed
5
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7 8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9 10 11
 *
 */

12 13
defined('INTERNAL') || die();

14 15 16
/**#@+
 * @access private
 */
17
// These are bitmaps - the next one should be 4
18
/** Display the errors on the screen */
19
define('LOG_TARGET_SCREEN', 1);
20
/** Write the errors to the error log, as specified in your php configuration */
21
define('LOG_TARGET_ERRORLOG', 2);
22 23
/** Write the error to stdout (using echo) */
define('LOG_TARGET_STDOUT', 4);
24 25 26
/** Display the errors on the screen in the admin area only (short term hack
    until we create an admin notifications page) */
define('LOG_TARGET_ADMIN', 8);
27 28
/** Log to a specific file */
define('LOG_TARGET_FILE', 16);
29 30

// Logging levels
31
/** Environment type errors, such as register_globals being on */
32
define('LOG_LEVEL_ENVIRON', 1);
33
/** Debug messages */
34
define('LOG_LEVEL_DBG', 2);
35
/** Informational messages */
36
define('LOG_LEVEL_INFO', 4);
37
/** Warnings */
38
define('LOG_LEVEL_WARN', 8);
39 40 41

// developermodes,  also bitmaps
/** include debug.css */
42
define('DEVMODE_DEBUGCSS', 1);
43
/** include unpacked mochikit */
44
define('DEVMODE_UNPACKEDJS', 2);
45
// more here.. start at 16 :)
46

47
/**#@-*/
48

49

Aaron Wells's avatar
Aaron Wells committed
50 51 52 53
// Default error reporting settings. Some of these may be changed
// later in init.php after we've loaded config.php
$errorlevel = E_ALL & ~E_STRICT;
error_reporting($errorlevel);
Yuliya Bozhko's avatar
Yuliya Bozhko committed
54 55 56 57
if (!defined('TESTSRUNNING')) {
    set_error_handler('error', $errorlevel);
    set_exception_handler('exception');
}
58 59 60 61


// Logging functions

62 63 64 65 66 67 68 69 70 71
/**
 * 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);
72 73
}

74 75 76 77 78 79 80 81 82 83
/**
 * 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);
84 85
}

86 87 88 89 90 91 92 93 94 95
/**
 * 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);
96 97
}

98 99 100 101 102 103 104 105 106 107
/**
 * 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);
108 109
}

110 111 112 113 114 115 116 117 118
/**
 * 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.
119 120
 * @param string $file      The file the error occurred in
 * @param int    $line      The line number the error occurred on
121 122 123 124
 * @param array  $trace     The backtrace for the error
 * @access private
 */
function log_message ($message, $loglevel, $escape, $backtrace, $file=null, $line=null, $trace=null) {
125 126
    global $SESSION, $CFG;
    if (!$SESSION && function_exists('get_config') && $CFG) {
127
        require_once(get_config('docroot') . 'auth/session.php');
128 129
        $SESSION = Session::singleton();
    }
130 131 132 133 134 135

    static $requestprefix = '';
    if (!$requestprefix) {
        $requestprefix = substr(md5(microtime()), 0, 2) . ' ';
    }

136 137 138 139 140 141 142 143 144 145 146 147
    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
148
    $trace = ($trace) ? $trace : debug_backtrace();
149 150 151 152 153 154
    // If the last caller was the 'error' function then it came from a PHP warning
    if (!is_null($file)) {
        $filename = $file;
        $linenum  = $line;
    }
    else {
155 156
        $filename  = $trace[1]['file'];
        $linenum   = $trace[1]['line'];
157
    }
158

159
    if (!function_exists('get_config') || get_config('log_backtrace_levels') & $loglevel) {
160
        list($textbacktrace, $htmlbacktrace) = log_build_backtrace($trace);
161 162 163 164 165
    }
    else {
        $textbacktrace = $htmlbacktrace = '';
    }

166 167 168
    if (is_bool($message)) {
        $loglines = array(($message ? 'bool(true)' : 'bool(false)'));
    }
169 170 171
    else if (is_null($message)) {
        $loglines = array('NULL');
    }
172 173 174
    else {
        $loglines = explode("\n", print_r($message, true));
    }
175 176

    // Make a prefix for each line, if we are logging a normal debug/info/warn message
177
    $prefix = $requestprefix;
178
    if ($loglevel != LOG_LEVEL_ENVIRON && function_exists('get_config')) {
179 180 181 182
        $docroot = get_config('docroot');
        $prefixfilename = (substr($filename, 0, strlen($docroot)) == $docroot)
            ? substr($filename, strlen($docroot))
            : $filename;
183
        $prefix .= '(' . $prefixfilename . ':' . $linenum . ') ';
184
    }
185
    $prefix = '[' . str_pad(substr(strtoupper($loglevelnames[$loglevel]), 0, 3), 3) . '] ' . $prefix;
186

187
    if ($targets & LOG_TARGET_SCREEN || (defined('ADMIN') && $targets & LOG_TARGET_ADMIN)) {
188 189 190 191 192
        // Work out which method to call for displaying the message
        if ($loglevel == LOG_LEVEL_DBG || $loglevel == LOG_LEVEL_INFO) {
            $method = 'add_info_msg';
        }
        else {
193
            $method = 'add_error_msg';
194 195
        }

196 197 198 199 200 201
        $message = implode("\n", $loglines);
        if ($escape) {
            $message = htmlspecialchars($message, ENT_COMPAT, 'UTF-8');
            $message = str_replace('  ', '&nbsp; ', $message);
        }
        $message = nl2br($message);
202
        $message = '<div class="backtrace">' . $prefix . $message . "</div>\n";
203 204
        if (is_a($SESSION, 'Session')) {
            $SESSION->$method($message, false);
205
        }
206 207 208 209 210 211
        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;
        }

212
        if ($backtrace && $htmlbacktrace) {
213 214 215
            if (is_a($SESSION, 'Session')) {
                $SESSION->add_info_msg($htmlbacktrace, false);
            }
216
            else if (!function_exists('get_config') || get_config('installed')) {
217 218
                echo $htmlbacktrace;
            }
219 220 221 222 223 224 225
        }
    }

    if ($targets & LOG_TARGET_ERRORLOG) {
        foreach ($loglines as $line) {
            error_log($prefix . $line);
        }
226
        if ($backtrace && $textbacktrace) {
227 228 229 230 231 232
            $lines = explode("\n", $textbacktrace);
            foreach ($lines as $line) {
                error_log($line);
            }
        }
    }
233 234 235 236 237 238 239 240 241

    if ($targets & LOG_TARGET_STDOUT) {
        foreach ($loglines as $line) {
            echo($prefix . $line . "\n");
        }
        if ($backtrace && $textbacktrace) {
            echo $textbacktrace;
        }
    }
242 243

    if (function_exists('get_config')) {
244 245 246
        if (!$logfilename = get_config('log_file')) {
            $logfilename = get_config('dataroot') . 'error.log';
        }
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 (($targets & LOG_TARGET_FILE) && $logfilename) {
            global $LOGFILE_FH;
            static $logfile_open_attempted = null;
            if (!$logfile_open_attempted) {
                $logfile_open_attempted = true;
                $LOGFILE_FH = fopen($logfilename, 'wb');
                if ($LOGFILE_FH !== false) {
                    function _close_logfile() {
                        global $LOGFILE_FH;
                        fclose($LOGFILE_FH);
                    }
                    register_shutdown_function('_close_logfile');
                }
                else {
                    error_log("Could not open your custom log file ($logfilename)");
                }
            }

            if (is_resource($LOGFILE_FH)) {
                foreach ($loglines as $line) {
                    fwrite($LOGFILE_FH, $prefix . $line . "\n");
                }
                if ($backtrace && $textbacktrace) {
                    $lines = explode("\n", $textbacktrace);
                    foreach ($lines as $line) {
                        fwrite($LOGFILE_FH, $line . "\n");
                    }
                }
            }
        }
    }
278 279
}

280 281 282 283 284 285 286 287 288 289
/**
 * 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
 */
290
function log_build_backtrace($backtrace) {
291
    global $CFG;
292 293
    $calls = array();

294
    // Remove the call to log_message
295
    //array_shift($backtrace);
296

297
    foreach ($backtrace as $bt) {
298 299 300 301

        // Blank out any passwords from the logs
        censor_password_parameters($bt);

302 303 304 305 306 307 308
        $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 = '';
309
        if ($bt['args']) {
310 311 312 313 314 315 316 317 318 319 320 321 322
            // Determine whether or not to print the values of the function's
            // arguments (which may contain sensitive data).
            // Still always print the values of the "include" pseudofunctions,
            // though, so the stacktrace will make sense.
            $showvalues = ($CFG->log_backtrace_print_args === true || in_array(
                    $bt['function'],
                    array(
                        'require',
                        'include',
                        'require_once',
                        'include_once'
                    )
            ));
323 324 325 326 327 328 329
            foreach ($bt['args'] as $arg) {
                if (!empty($args)) {
                    $args .= ', ';
                }
                switch (gettype($arg)) {
                    case 'integer':
                    case 'double':
330 331 332 333 334 335
                        if ($showvalues) {
                            $args .= $arg;
                        }
                        else {
                            $args .= (gettype($arg));
                        }
336 337
                        break;
                    case 'string':
338 339 340 341 342 343 344
                        if ($showvalues) {
                            $arg = substr($arg, 0, 50) . ((strlen($arg) > 50) ? '...' : '');
                            $args .= '"' . $arg . '"';
                        }
                        else {
                            $args .= 'string(size ' . strlen($arg) . ')';
                        }
345 346 347 348 349 350 351 352
                        break;
                    case 'array':
                        $args .= 'array(size ' . count($arg) . ')';
                        break;
                    case 'object':
                        $args .= 'object(' . get_class($arg) . ')';
                        break;
                    case 'resource':
353
                        $args .= 'resource(' . strstr((string)$arg, '#') . ')';
354 355 356 357 358 359 360 361 362 363
                        break;
                    case 'boolean':
                        $args .= $arg ? 'true' : 'false';
                        break;
                    case 'NULL':
                        $args .= 'null';
                        break;
                    default:
                        $args .= 'unknown';
                }
364 365 366 367 368 369 370 371 372 373 374 375 376 377
            }
        }

        $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";
378
    $htmlmessage = "<div class=\"backtrace\"><strong>Call stack (most recent first):</strong>\n<ul>";
379 380 381 382

    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;">'
383
            . htmlspecialchars($call['type'], ENT_COMPAT, 'UTF-8') . '</span><span style="color:#339;">' . htmlspecialchars($call['func'], ENT_COMPAT, 'UTF-8')
384 385
            . '</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>';
    }
386
    $htmlmessage .= "</div>\n";
387 388 389

    return array($textmessage, $htmlmessage);
}
390

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

/**
 * Detects whether a backtrace line contains a function call with password parameters in it.
 * Replaces the value of any password params with "********" so that passwords won't be
 * printed in the logs or error messages.
 *
 * This function assumes any parameter with a name that contains "password" or "pw"
 * is a password.
 *
 * @param array &$backtraceline An entry in the array returned by debug_backtrace()
 * @return void
 */
function censor_password_parameters(&$backtraceline) {
    if (isset($backtraceline['function'])) {
        try {
            if (isset($backtraceline['class'])) {
                $refClass = new ReflectionClass($backtraceline['class']);
                $refFunc = $refClass->getMethod($backtraceline['function']);
            }
            else {
                // Function-like "language constructs" such as "require" and "echo"
                // are listed as a function by debug_backtrace(), but can't be
                // reflected.
                if (!function_exists($backtraceline['function'])) {
                    return;
                }
                $refFunc = new ReflectionFunction($backtraceline['function']);
            }

            foreach ($refFunc->getParameters() as $param) {
                $name = strtolower($param->getName());
                if (
                    strpos($name, 'password') !== false
                    || strpos($name, 'pw') !== false
                ) {
                    $i = $param->getPosition();
                    if (isset($backtraceline['args'][$i])) {
                        $backtraceline['args'][$i] = '********';
                    }
                }
            }
            return;
        }
        catch (ReflectionException $re) {
            // Don't want a failure here to totally prevent logging.
            return;
        }
    }

    return;
}

443 444 445 446
/**
 * Ends the script with an informational message
 *
 * @param string $message The message to display
447
 * @todo this function should go away
448 449
 */
function die_info($message) {
450
    $smarty = smarty(array(), array(), array(), array('sidebars' => false));
451 452 453 454 455 456 457
    $smarty->assign('message', $message);
    $smarty->assign('type', 'info');
    $smarty->display('message.tpl');
    exit;
}


458 459
// Error/Exception handling

460 461 462 463 464 465 466 467 468
/**
 * 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
469
 * @access private
470
 */
471 472 473
function error ($code, $message, $file, $line, $vars) {
    static $error_lookup = array(
        E_NOTICE => 'Notice',
474
        E_WARNING => 'Warning',
Aaron Wells's avatar
Aaron Wells committed
475 476
        E_STRICT => 'Strict',
        // These won't get handled here unless PHP's behavior changes
477 478 479 480 481
        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'
482 483
    );

484 485 486 487
    if (defined('E_RECOVERABLE_ERROR')) {
        $error_lookup[E_RECOVERABLE_ERROR] = 'Warning';
    }

488 489 490 491 492 493 494 495
    if (!error_reporting()) {
        return;
    }

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

496
    // Ignore errors from smarty templates, which happen all too often
497
    if (function_exists('get_config')) {
498
        $compiledir = realpath(get_config('dataroot') . 'dwoo/compile');
499 500 501 502

        if (E_NOTICE == $code && substr($file, 0, strlen($compiledir)) == $compiledir) {
            return;
        }
503 504 505 506

        if (E_NOTICE == $code && preg_match('#^' . quotemeta(get_config('docroot') . 'theme/') . '[a-z0-9-]+/pieforms#', $file)) {
            return;
        }
507 508
    }

509 510 511 512
    // Fix up the message, which is in HTML form
    $message = strip_tags($message);
    $message = htmlspecialchars_decode($message);

513
    log_message($message, LOG_LEVEL_WARN, true, true, $file, $line);
514 515
}

516
/**
517 518 519 520
 * 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.
 *
521 522
 * @param Throwable $e The exception that was thrown. (For PHP 5 & 7 cross-compatibility,
 * this parameter must have no type declaration.)
523
 * @access private
524
 */
525
function exception ($e) {
526 527 528 529 530 531 532 533 534 535
    $classname = get_class($e);
    if (!($e instanceof MaharaException)) {
        $e = new SystemException("[{$classname}]: " . $e->getMessage(), $e->getCode());
    }
    else if ($classname == 'MaharaException') {
        // Mahara coding practice says not to use MaharaException directly, but for more
        // graceful error handling we have chosen not to make it abstract. Instead, make
        // it print like a SystemException.
        /* @var MaharaException $e */
        $e = new SystemException($e->getMessage(), $e->getCode());
536
    }
537 538

    // Display the message and die
539
    $e->handle_exception();
540 541 542 543 544
}



/**
545 546 547 548 549 550 551
 * Generic Mahara exception. Use a more specific exception class where possible, because
 * this one doesn't print its message very gracefully. "SystemException" is a good
 * generic one.
 *
 * I'd make this an abstract class... except that inexperienced devs are likely to
 * attempt to instantiate it anyway, and if they do so, PHP will throw a fatal error
 * that won't become apparent until the rare occasion when an exception actually happens.
552 553 554 555 556
 */
class MaharaException extends Exception {

    protected $log = true;

557
    public function __construct($message='', $code=0) {
558 559 560 561 562 563
        parent::__construct($message, $code);
        if (!defined('MAHARA_CRASHING')) {
            define('MAHARA_CRASHING', true);
        }
    }

564 565
    public function get_string() {
        $args = func_get_args();
566
        if (function_exists('get_string')) {
567 568 569 570 571
            $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;
572 573
            }
        }
574 575 576 577 578

        $tag = func_get_arg(0);
        $strings = $this->strings();
        if (array_key_exists($tag, $strings)) {
            return $strings[$tag];
579
        }
580

581
        return 'An error occurred';
582 583 584 585 586
    }

    public function get_sitename() {
        if (!function_exists('get_config') || !$sitename = @get_config('sitename')) {
            $sitename = 'Mahara';
587
        }
588 589 590 591 592 593
        return $sitename;
    }

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

595 596 597 598 599 600 601 602 603 604 605 606
    public function set_log() {
        $this->log = true;
    }

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

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

607
    public final function handle_exception() {
608

609
        if (!empty($this->log)) {
610
            log_message($this->getMessage(), LOG_LEVEL_WARN, true, true, $this->getFile(), $this->getLine(), $this->getTrace());
611 612 613 614 615 616 617 618
        }

        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;
        }
619 620 621 622 623

        if (defined('TESTSRUNNING')) {
            exit; // let it be caught by phpunit
        }

624
        if (defined('CRON') || defined('CLI')) {
625 626 627
            echo $this->render_exception();
            exit;
        }
628

Donal McMullan's avatar
Donal McMullan committed
629 630 631 632 633
        if (defined('XMLRPC')) { // it's preferable to throw an XmlrpcServerException
            echo xmlrpc_error($this->render_exception(), $this->getCode());
            exit;
        }

634 635 636 637 638
        if (headers_sent()) {
            echo '<span style="color: red;">ERROR - something bad happened after headers have been sent. Check the error log for more information.</span>';
            die();
        }

639
        $outputtitle = $this->get_string('title');
640
        $outputmessage = trim($this->render_exception());
641

642
        if (function_exists('smarty') && !$this instanceof ConfigSanityException) {
643 644 645 646 647 648 649 650 651 652
            try {
                $smarty = smarty(array(), array(), array(), array('sidebars' => false));
                $smarty->assign('title', $outputtitle);
                $smarty->assign('message', $outputmessage);
                $smarty->display('error.tpl');
                die();
            }
            catch (Exception $e) {
                // If an exception is thrown in smarty(), ignore it
                // and print the message out the ugly way
653 654 655
                log_debug("Exception thrown by smarty call while handling exception:\n".
                        '[' . get_class($e) . ']: ' . $e->getMessage(), true, false
                );
656
            }
657
        }
658 659 660 661

        $outputtitle   = htmlspecialchars($outputtitle, ENT_COMPAT, 'UTF-8');
        $outputmessage = nl2br(htmlspecialchars($outputmessage, ENT_COMPAT, 'UTF-8'));
        echo <<<EOF
662 663
<html>
<head>
664
    <title>$outputtitle</title>
665
    <style type="text/css">
666 667 668 669 670 671 672 673 674 675 676 677 678
        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;
679
            font-weight: normal;
680 681 682 683 684 685 686 687 688 689 690
            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;
        }
691 692 693 694 695 696
        #reason {
            margin: 0 3em;
        }
    </style>
</head>
<body>
697
EOF;
698
        echo <<<EOF
699
<h1>$outputtitle</h1>
700
<div id="message">$outputmessage</div>
701 702 703
</body>
</html>
EOF;
704 705 706 707 708 709 710 711 712
        // end of printing stuff to the screen...
        die();
    }
}





713 714
// Standard exceptions  - top level exception class.
// all exceptions should extend one of these three.
715 716 717 718

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

721 722 723 724 725
    public function __construct($message, $code=0) {
        parent::__construct($message, $code);
        $this->set_log();
    }

726 727 728 729 730
    public function render_exception () {
        return $this->get_string('message');
    }

    public function strings() {
731
        return array_merge(parent::strings(),
732
                           array('message' => 'A nonrecoverable error occurred. '
733 734
                                 . 'This probably means you have encountered a bug in the system'));
    }
735

736 737
}

738 739 740 741
/**
 * ConfigException - something is misconfigured that's causing a problem.
 * Generally these will be the fault of admins
 */
742
class ConfigException extends MaharaException {
743

744
    public function render_exception () {
745
        return $this->get_string('message') . "\n\n" . $this->getMessage();
746 747 748
    }

    public function strings() {
749 750
        return array_merge(parent::strings(),
                           array('message' => 'The environment where ' . $this->get_sitename()
751 752 753
                           . ' is running is misconfigured and this is causing problems. '
                           . 'You probably need to contact a server administrator to get this fixed. '
                           . 'Details, if any, follow:'));
754 755 756 757 758 759
    }
}

/**
 * UserException - the user has done something they shouldn't (or tried to)
 */
760
class UserException extends MaharaException {
761 762

    protected $log = false;
763

764
    public function render_exception() {
765
        return $this->get_string('message') . "\n\n" . $this->getMessage();
766 767 768
    }

    public function strings() {
769 770
        return array_merge(parent::strings(),
                           array('message' => 'Something in the way you\'re interacting with '
771
                                 . $this->get_sitename()
772
                                 . " is causing an error.\nDetails if any, follow:"));
773 774 775
    }
}

776 777 778 779 780 781
/**
 * Exception - Not found. Throw this if a user is trying to view something
 * that doesn't exist
 */
class NotFoundException extends UserException {
    public function strings() {
782
        return array_merge(parent::strings(),
783 784
                           array('message' => get_string('notfoundexception', 'error'),
                                 'title'   => get_string('notfound', 'error')));
785 786 787 788 789 790 791 792
    }

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

793

794
/**
795
 * The configuration that Mahara is trying to be run in is insane
796
 */
797 798 799 800 801
class ConfigSanityException extends ConfigException {
    public function strings() {
        return array_merge(parent::strings(), array('message' => ''));
    }
}
802

803 804 805
class FeatureNotEnabledException extends ConfigException {
}

806
/**
807
 * An SQL related error occurred
808
 */
809
class SQLException extends SystemException {
810
    public function __construct($message=null, $code=0) {
811 812
        global $DB_IGNORE_SQL_EXCEPTIONS;

813
        if ($GLOBALS['_TRANSACTION_LEVEL'] > 0) {
814 815
            db_rollback();
        }
816
        parent::__construct($message, $code);
817

818
        if (empty($DB_IGNORE_SQL_EXCEPTIONS) && !defined('TESTSRUNNING')) {
819 820
            log_warn($this->getMessage());
        }
821 822
    }
}
823

824 825 826
/**
 * An exception generated by invalid GET or POST parameters
 */
827
class ParameterException extends UserException {
828
    public function strings() {
829 830 831 832
        return array_merge(parent::strings(), array(
            'title'   => 'Mahara: Invalid Parameter',
            'message' => 'A required parameter is missing or malformed')
        );
833 834
    }
}
835

836 837 838 839 840 841 842 843 844 845 846
/**
 * A function or method has been passed the wrong kind of argument
 * Unfortunately, broken type-hints cause fatal errors - not exceptions
 */
class ParamOutOfRangeException extends SystemException {}

/**
 * Remote Server exception - something has gone wrong at the remote machine
 */
class RemoteServerException extends SystemException {}

Donal McMullan's avatar
Donal McMullan committed
847 848 849
/**
 * Xmlrpc Server exception - must output well formed XMLRPC error to the client
 */
Donal McMullan's avatar
Donal McMullan committed
850 851 852
class XmlrpcServerException extends SystemException {}

/**
853
 * Xmlrpc Client exception - Something has gone wrong in the networking
Donal McMullan's avatar
Donal McMullan committed
854
 */
855 856 857
class XmlrpcClientException extends SystemException {
    public function strings() {
        return array_merge(parent::strings(), array(
858
            'title'   => get_string('xmlrpccouldnotlogyouin', 'auth'),
859
            'message' => get_string('xmlrpccouldnotlogyouindetail1', 'auth', get_config('sitename')))
860 861 862
        );
    }
}
Donal McMullan's avatar
Donal McMullan committed
863 864 865 866 867

/**
 * Error with SSL and encryption
 */
class CryptException extends SystemException {}
Donal McMullan's avatar
Donal McMullan committed
868

869 870 871
/**
 * An exception generated when e-mail can't be sent
 */
872
class EmailException extends SystemException {}
873

874 875 876 877 878
/**
 * Exception - Invalid address
 */
class InvalidEmailException extends EmailException {}

879 880 881 882 883
/**
 * Exception - Email is disabled for this user
 */
class EmailDisabledException extends EmailException {}

884 885
/**
 * Exception - artefact not found
886
 */
887
class ArtefactNotFoundException extends NotFoundException {}
888

889 890 891 892
/**
 * Exception - block instance not found
 */
class BlockInstanceNotFoundException extends NotFoundException {}
893

894
/**
895 896 897
 * Exception - interaction instance not found
 */
class InteractionInstanceNotFoundException extends NotFoundException {}
898

899 900 901
/**
 * Exception - view not found
 */
902
class ViewNotFoundException extends NotFoundException {}
903

904 905 906 907 908 909
/**
 * Exception - view limit exceeded
 * for example, multiple profile views
 */
class ViewLimitExceededException extends UserException {}

Penny Leach's avatar
Penny Leach committed
910 911 912
/**
 * Exception - user not found
 */
913
class UserNotFoundException extends NotFoundException {}
914

915 916 917 918 919 920 921 922 923 924 925
/**
 * Exception - user not found while doing XMLRPC authentication
 */
class XmlrpcUserNotFoundException extends UserNotFoundException {
    public function strings() {
        return array_merge(parent::strings(),
            array('message' => ''),
            array('title'   => get_string('unabletosigninviasso', 'auth')));
    }
}

926
/**
927
 * Exception - group not found
928
 */
929
class GroupNotFoundException extends NotFoundException {}
930

Martyn Smith's avatar
Martyn Smith committed
931 932 933 934 935
/**
 * Exception - fired when something happens that would make the user exceed their quota
 */
class QuotaExceededException extends UserException {}

936 937 938 939 940
/**
 * Exception - fired when uploading a file fails
 */
class UploadException extends UserException {}

941 942 943 944 945
/**
 * Exception - collection not found
 */
class CollectionNotFoundException extends NotFoundException {}

946 947 948 949 950
/**
 * Exception - file not found in dataroot
 */
class FileNotFoundException extends NotFoundException {}

951 952 953 954 955
/**
 * Exception - For when a skin is not found
 */
class SkinNotFoundException extends NotFoundException {}

Penny Leach's avatar
Penny Leach committed
956 957 958
/**
 * Exception - Access denied. Throw this if a user is trying to view something they can't
 */
959 960
class AccessDeniedException extends UserException {
    public function strings() {
961
        return array_merge(parent::strings(),
962 963
                           array('message' => get_string('accessdeniedexception', 'error'),
                                 'title'   => get_string('accessdenied', 'error')));
964 965 966
    }

    public function render_exception() {
967 968
        global $USER;
        if (defined('PUBLIC') && !$USER->is_logged_in()) {
969
            $loginurl = get_full_script_path();
970 971 972 973
            $loginurl .= (false === strpos($loginurl, '?')) ? '?' : '&';
            $loginurl .= 'login';
            redirect($loginurl);
        }
974 975 976 977 978
        header("HTTP/1.0 403 Forbidden", true);
        return parent::render_exception();
    }
}

979 980 981 982 983 984 985 986 987 988 989 990
/**
 * Exception - Access denied to a group page because the user isn't a member
 * Give the user a chance to join then continue
 */
class GroupAccessDeniedException extends AccessDeniedException {
    public function render_exception() {
        global $USER, $SESSION;
        if (defined('GROUP') && $USER->is_logged_in()) {
            $roles = $USER->get('grouproles');
            if (!isset($roles[GROUP])) {
                $group = group_current_group();
                if ($group->jointype == 'open'
991
                    || get_record('group_member_invite', 'group', GROUP, 'member', $USER->get('id'))) {
992 993 994 995 996 997
                    $message = get_string('notmembermayjoin', 'group', $group->name);
                    // Error code equals 1 if we have objection=1 in url
                    if ($this->getCode() == '1') {
                        $message .= ' ' . get_string('accessdeniedobjection', 'error');
                    }
                    $SESSION->add_error_msg($message);
998
                    $next = substr($_SERVER['REQUEST_URI'], strlen(get_mahara_install_subdirectory()) - 1);
999 1000 1001
                    $goto = group_homepage_url($group);
                    $goto .= (strpos($goto, '?') ? '&' : '?') . 'next=' . urlencode($next);
                    redirect($goto);
1002
                }
1003
                if ($group->request && !get_record('group_member_request', 'group', GROUP, 'member', $USER->get('id'))) {
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
                    $SESSION->add_error_msg(get_string('notamember', 'group'));
                    redirect(get_config('wwwroot') . 'group/requestjoin.php?id=' . GROUP . '&returnto=view');
                }
            }
        }
        header("HTTP/1.0 403 Forbidden", true);
        return parent::render_exception();
    }
}

1014
/**
1015
 * Exception - Access totally denied, the user won't be able to access it even if they log in
1016 1017 1018 1019
 * as the administrator
 */
class AccessTotallyDeniedException extends UserException {
    public function strings() {
1020
        return array_merge(parent::strings(),
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
                           array('message' => get_string('accessdeniedexception', 'error'),
                                 'title'   => get_string('accessdenied', 'error')));
    }

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

1031 1032 1033 1034 1035 1036 1037
/**
* something has happened during import.
* either: the user is there, in which case they get the bug screen,
*         it's a spawned request during an xmlrpc server ping (content_ready) in which case XMLRPC will be defined
*         or it's a queued fetch, in which case CRON will be defined.
* @todo maybe refactor at the point that we have something other than importing over mnet (eg userland)
*/
1038
class ImportException extends SystemException {
1039 1040 1041

    public function __construct($importer, $message=null, $code=0) {
        parent::__construct($message, $code);
1042 1043 1044
        if ($importer instanceof PluginImport) {
            $importer->cleanup();
        }
1045 1046
    }

1047 1048 1049
    public function render_exception() {
        return $this->getMessage();
    }
1050 1051
}

1052 1053 1054
/**
* something has happened during export.
*/
1055
class ExportException extends SystemException {
1056

1057 1058 1059
    public function __construct($exporter, $message=null, $code=0) {
        parent::__construct($message, $code);
    }
1060 1061 1062 1063

    public function render_exception() {
        return $this->getMessage();
    }
1064
}
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078

/**
 * An exception related to read/write/extract archive artefact
 */
class ArchiveException extends SystemException {
    public function strings() {
        return array_merge(parent::strings(),
                array('message' => get_string('invalidarchive1', 'artefact.file'),
                    'title'   => get_string('invalidarchive1', 'artefact.file')));
    }
    public function render_exception() {
        return $this->getMessage();
    }
}