errors.php 34.4 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
    global $USER;
    if ($USER) {
Martyn Smith's avatar
Martyn Smith committed
528
        if (!($e instanceof MaharaException) || get_class($e) == 'MaharaException') {
529
            log_warn("An exception was thrown of class " . get_class($e) . ". \nTHIS IS BAD "
530
                     . "and should be changed to something extending MaharaException,\n"
531
                     . "unless the exception is from a third party library.\n"
532 533 534 535 536
                     . "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();
        }
537
    }
538 539

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


interface MaharaThrowable {
545

546
    public function render_exception();
547

548 549
}

550
// Standard exceptions  - top level exception class.
551 552 553 554
// all exceptions should extend one of these three.

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

    protected $log = true;

562
    public function __construct($message='', $code=0) {
563 564 565 566 567 568
        parent::__construct($message, $code);
        if (!defined('MAHARA_CRASHING')) {
            define('MAHARA_CRASHING', true);
        }
    }

569 570
    public function get_string() {
        $args = func_get_args();
571
        if (function_exists('get_string')) {
572 573 574 575 576
            $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;
577 578
            }
        }
579 580 581 582 583

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

586
        return 'An error occurred';
587 588 589 590 591
    }

    public function get_sitename() {
        if (!function_exists('get_config') || !$sitename = @get_config('sitename')) {
            $sitename = 'Mahara';
592
        }
593 594 595 596 597 598
        return $sitename;
    }

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

600 601 602 603 604 605 606 607 608 609 610 611
    public function set_log() {
        $this->log = true;
    }

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

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

612
    public final function handle_exception() {
613

614
        if (!empty($this->log)) {
615
            log_message($this->getMessage(), LOG_LEVEL_WARN, true, true, $this->getFile(), $this->getLine(), $this->getTrace());
616 617 618 619 620 621 622 623
        }

        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;
        }
624 625 626 627 628

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

629
        if (defined('CRON') || defined('CLI')) {
630 631 632
            echo $this->render_exception();
            exit;
        }
633

Donal McMullan's avatar
Donal McMullan committed
634 635 636 637 638
        if (defined('XMLRPC')) { // it's preferable to throw an XmlrpcServerException
            echo xmlrpc_error($this->render_exception(), $this->getCode());
            exit;
        }

639 640 641 642 643
        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();
        }

644
        $outputtitle = $this->get_string('title');
645
        $outputmessage = trim($this->render_exception());
646

647
        if (function_exists('smarty') && !$this instanceof ConfigSanityException) {
648 649 650 651 652 653 654 655 656 657 658 659
            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
                log_warn("Exception thrown by smarty call while handling exception");
            }
660
        }
661 662 663 664

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






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

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

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

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

737 738
}

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

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

    public function strings() {
750 751
        return array_merge(parent::strings(),
                           array('message' => 'The environment where ' . $this->get_sitename()
752 753 754
                           . ' 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:'));
755 756 757 758 759 760
    }
}

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

    protected $log = false;
764

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

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

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

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

794

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

804 805 806
class FeatureNotEnabledException extends ConfigException {
}

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

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

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

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

837 838 839 840 841 842 843 844 845 846 847
/**
 * 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
848 849 850
/**
 * Xmlrpc Server exception - must output well formed XMLRPC error to the client
 */
Donal McMullan's avatar
Donal McMullan committed
851 852 853
class XmlrpcServerException extends SystemException {}

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

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

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

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

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

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

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

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

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

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

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

916 917 918 919 920 921 922 923 924 925 926
/**
 * 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')));
    }
}

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

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

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

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

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

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

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

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

980 981 982 983 984 985 986 987 988 989 990 991
/**
 * 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'
992
                    || get_record('group_member_invite', 'group', GROUP, 'member', $USER->get('id'))) {
993 994 995 996 997 998
                    $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);
999
                    $next = substr($_SERVER['REQUEST_URI'], strlen(get_mahara_install_subdirectory()) - 1);
1000 1001 1002
                    $goto = group_homepage_url($group);
                    $goto .= (strpos($goto, '?') ? '&' : '?') . 'next=' . urlencode($next);
                    redirect($goto);
1003
                }
1004
                if ($group->request && !get_record('group_member_request', 'group', GROUP, 'member', $USER->get('id'))) {
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
                    $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();
    }
}

1015
/**
1016
 * Exception - Access totally denied, the user won't be able to access it even if they log in
1017 1018 1019 1020
 * as the administrator
 */
class AccessTotallyDeniedException extends UserException {
    public function strings() {
1021
        return array_merge(parent::strings(),
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
                           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();
    }
}

1032 1033 1034 1035 1036 1037 1038
/**
* 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)
*/
1039
class ImportException extends SystemException {
1040 1041 1042

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

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

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

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

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