Source

joomla-platform / libraries / joomla / error / error.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
<?php
/**
 * @package     Joomla.Platform
 * @subpackage  Error
 *
 * @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

defined('JPATH_PLATFORM') or die;

// Error Definition: Illegal Options
define('JERROR_ILLEGAL_OPTIONS', 1);
// Error Definition: Callback does not exist
define('JERROR_CALLBACK_NOT_CALLABLE', 2);
// Error Definition: Illegal Handler
define('JERROR_ILLEGAL_MODE', 3);


/**
 * Error Handling Class
 *
 * This class is inspired in design and concept by patErrorManager <http://www.php-tools.net>
 *
 * patErrorManager contributors include:
 *	- gERD Schaufelberger	<gerd@php-tools.net>
 *	- Sebastian Mordziol	<argh@php-tools.net>
 *	- Stephan Schmidt		<scst@php-tools.net>
 *
 * @package	Joomla.Platform
 * @subpackage	Error
 * @since		11.1
 * @deprecated
 */
abstract class JError
{
	/**
	 * @var    bool  True to enable legacy error handling using JError, false to use exception handling.  This flag
	 *               is present to allow an easy transition into exception handling for code written against the
	 *               existing JError API in Joomla.
	 * @since  11.1
	 */
	public static $legacy = false;

	protected static $levels = array(
		E_NOTICE => 'Notice',
		E_WARNING => 'Warning',
		E_ERROR => 'Error'
	);

	protected static $handlers = array(
		E_NOTICE	=> array('mode' => 'message'),
		E_WARNING	=> array('mode' => 'message'),
		E_ERROR	=> array('mode' => 'callback', 'options' => array('JError','customErrorPage'))
	);

	protected static $stack = array();

	/**
	 * Method to determine if a value is an exception object.  This check supports
	 * both JException and PHP5 Exception objects
	 *
	 * @param	mixed	&$object	Object to check
	 * @return	boolean	True if argument is an exception, false otherwise.
	 * @since	11.1
	 */
	public static function isError(& $object)
	{
		// Supports PHP 5 exception handling
		return $object instanceof Exception;
	}

	/**
	 * Method for retrieving the last exception object in the error stack
	 *
	 * @return	mixed	Last exception object in the error stack or boolean false if none exist
	 * @since	11.1
	 */
	public static function getError($unset = false)
	{
		if (!isset(JError::$stack[0])) {
			return false;
		}

		if ($unset) {
			$error = array_shift(JError::$stack);
		}
		else {
			$error = &JError::$stack[0];
		}
		return $error;
	}

	/**
	 * Method for retrieving the exception stack
	 *
	 * @return	array	Chronological array of errors that have been stored during script execution
	 * @since	11.1
	 */
	public static function getErrors()
	{
		return JError::$stack;
	}

	/**
	 * Method to add non-JError thrown JExceptions to the JError stack for debugging purposes
	 *
	 * @param	object JException
	 *
	 * @return	void
	 * @since	11.1
	 */
	public static function addToStack(JException &$e) {
		JError::$stack[] = &$e;
	}

	/**
	 * Create a new JException object given the passed arguments
	 *
	 * @param	int		$level	The error level - use any of PHP's own error levels for this: E_ERROR, E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE.
	 * @param	string	$code	The application-internal error code for this error
	 * @param	string	$msg	The error message, which may also be shown the user if need be.
	 * @param	mixed	$info	Optional: Additional error information (usually only developer-relevant information that the user should never see, like a database DSN).
	 *
	 * @return	mixed	The JException object
	 * @since	11.1
	 *
	 * @see		JException
	 */
	public static function raise($level, $code, $msg, $info = null, $backtrace = false)
	{
		jimport('joomla.error.exception');

		// Build error object
		$exception = new JException($msg, $code, $level, $info, $backtrace);
		return JError::throwError($exception);
	}

	public static function throwError(&$exception)
	{
		static $thrown = false;

		// If thrown is hit again, we've come back to JError in the middle of throwing another JError, so die!
		if ($thrown) {
			// echo debug_print_backtrace();
			jexit(JText::_('JLIB_ERROR_INFINITE_LOOP'));
		}

		$thrown = true;
		$level = $exception->get('level');

		// See what to do with this kind of error
		$handler = JError::getErrorHandling($level);

		$function = 'handle'.ucfirst($handler['mode']);
		if (is_callable(array('JError', $function))) {
			$reference = call_user_func_array(array('JError',$function), array(&$exception, (isset($handler['options'])) ? $handler['options'] : array()));
		}
		else {
			// This is required to prevent a very unhelpful white-screen-of-death
			jexit(
				'JError::raise -> Static method JError::' . $function . ' does not exist.' .
				' Contact a developer to debug' .
				'<br /><strong>Error was</strong> ' .
				'<br />' . $exception->getMessage()
			);
		}
		// We don't need to store the error, since JException already does that for us!
		// Remove loop check
		$thrown = false;

		return $reference;
	}

	/**
	 * Wrapper method for the {@link raise()} method with predefined error level of E_ERROR and backtrace set to true.
	 *
	 * @param	string	$code	The application-internal error code for this error
	 * @param	string	$msg	The error message, which may also be shown the user if need be.
	 * @param	mixed	$info	Optional: Additional error information (usually only developer-relevant information that
	 * 							the user should never see, like a database DSN).
	 *
	 * @return	object	$error	The configured JError object
	 * @since	11.1
	 */
	public static function raiseError($code, $msg, $info = null)
	{
		return JError::raise(E_ERROR, $code, $msg, $info, true);
	}

	/**
	 * Wrapper method for the {@link raise()} method with predefined error level of E_WARNING and backtrace set to false.
	 *
	 * @param	string	$code	The application-internal error code for this error
	 * @param	string	$msg	The error message, which may also be shown the user if need be.
	 * @param	mixed	$info	Optional: Additional error information (usually only developer-relevant information that
	 * 							the user should never see, like a database DSN).
	 *
	 * @return	object	$error	The configured JError object
	 * @since	11.1
	 */
	public static function raiseWarning($code, $msg, $info = null)
	{
		return JError::raise(E_WARNING, $code, $msg, $info);
	}

	/**
	 * Wrapper method for the {@link raise()} method with predefined error level of E_NOTICE and backtrace set to false.
	 *
	 * @param	string	$code	The application-internal error code for this error
	 * @param	string	$msg	The error message, which may also be shown the user if need be.
	 * @param	mixed	$info	Optional: Additional error information (usually only developer-relevant information
	 * 							that the user should never see, like a database DSN).
	 *
	 * @return	object	$error	The configured JError object
	 * @since	11.1
	 */
	public static function raiseNotice($code, $msg, $info = null)
	{
		return JError::raise(E_NOTICE, $code, $msg, $info);
	}

	/**
	* Method to get the current error handler settings for a specified error level.
	*
	* @param	int		$level	The error level to retrieve. This can be any of PHP's own error levels, e.g. E_ALL, E_NOTICE...
	*
	* @return	array	All error handling details
	* @since	11.1
	*/
	public static function getErrorHandling($level)
	{
		return JError::$handlers[$level];
	}

	/**
	 * Method to set the way the JError will handle different error levels. Use this if you want to override the default settings.
	 *
	 * Error handling modes:
	 * - ignore
	 * - echo
	 * - verbose
	 * - die
	 * - message
	 * - log
	 * - callback
	 *
	 * You may also set the error handling for several modes at once using PHP's bit operations.
	 * Examples:
	 * - E_ALL = Set the handling for all levels
	 * - E_ERROR | E_WARNING = Set the handling for errors and warnings
	 * - E_ALL ^ E_ERROR = Set the handling for all levels except errors
	 *
	 * @param	int		$level		The error level for which to set the error handling
	 * @param	string	$mode		The mode to use for the error handling.
	 * @param	mixed	$options	Optional: Any options needed for the given mode.
	 *
	 * @return	mixed	True on success, or a JException object if failed.
	 * @since	11.1
	 */
	public static function setErrorHandling($level, $mode, $options = null)
	{
		$levels = JError::$levels;

		$function = 'handle'.ucfirst($mode);

		if (!is_callable(array ('JError',$function))) {
			return JError::raiseError(E_ERROR, 'JError:'.JERROR_ILLEGAL_MODE, 'Error Handling mode is not known', 'Mode: '.$mode.' is not implemented.');
		}

		foreach ($levels as $eLevel => $eTitle)
		{
			if (($level & $eLevel) != $eLevel) {
				continue;
			}

			// Set callback options
			if ($mode == 'callback') {
				if (!is_array($options)) {
					return JError::raiseError(E_ERROR, 'JError:'.JERROR_ILLEGAL_OPTIONS, 'Options for callback not valid');
				}

				if (!is_callable($options)) {
					$tmp = array ('GLOBAL');
					if (is_array($options)) {
						$tmp[0] = $options[0];
						$tmp[1] = $options[1];
					}
					else {
						$tmp[1] = $options;
					}

					return JError::raiseError(E_ERROR, 'JError:'.JERROR_CALLBACK_NOT_CALLABLE, 'Function is not callable', 'Function:'.$tmp[1].' scope '.$tmp[0].'.');
				}
			}

			// Save settings
			JError::$handlers[$eLevel] = array ('mode' => $mode);
			if ($options != null) {
				JError::$handlers[$eLevel]['options'] = $options;
			}
		}

		return true;
	}

	/**
	 * Method that attaches the error handler to JError
	 *
	 * @see set_error_handler
	 */
	public static function attachHandler()
	{
		set_error_handler(array('JError', 'customErrorHandler'));
	}

	/**
	 * Method that detaches the error handler from JError
	 *
	 * @see restore_error_handler
	 */
	public static function detachHandler()
	{
		restore_error_handler();
	}

	/**
	* Method to register a new error level for handling errors
	*
	* This allows you to add custom error levels to the built-in
	* - E_NOTICE
	* - E_WARNING
	* - E_NOTICE
	*
	* @param	int		$level		Error level to register
	* @param	string	$name		Human readable name for the error level
	* @param	string	$handler	Error handler to set for the new error level [optional]
	*
	* @return	boolean	True on success; false if the level already has been registered
	* @since	11.1
	*/
	public static function registerErrorLevel($level, $name, $handler = 'ignore')
	{
		if (isset(JError::$levels[$level])) {
			return false;
		}

		JError::$levels[$level] = $name;
		JError::setErrorHandling($level, $handler);

		return true;
	}

	/**
	* Translate an error level integer to a human readable string
	* e.g. E_ERROR will be translated to 'Error'
	*
	* @param	int		$level	Error level to translate
	*
	* @return	mixed	Human readable error level name or boolean false if it doesn't exist
	* @since	11.1
	*/
	public static function translateErrorLevel($level)
	{
		if (isset(JError::$levels[$level])) {
			return JError::$levels[$level];
		}

		return false;
	}

	/**
	 * Ignore error handler
	 *	- Ignores the error
	 *
	 * @param	object	$error		Exception object to handle
	 * @param	array	$options	Handler options
	 *
	 * @return	object	The exception object
	 * @since	11.1
	 *
	 * @see	raise()
	 */
	public static function handleIgnore(&$error, $options)
	{
		return $error;
	}

	/**
	 * Echo error handler
	 *	- Echos the error message to output
	 *
	 * @param	object	$error		Exception object to handle
	 * @param	array	$options	Handler options
	 *
	 * @return	object	The exception object
	 * @since	11.1
	 *
	 * @see	raise()
	 */
	public static function handleEcho(&$error, $options)
	{
		$level_human = JError::translateErrorLevel($error->get('level'));

		if (isset ($_SERVER['HTTP_HOST'])) {
			// output as html
			echo "<br /><b>jos-$level_human</b>: ".$error->get('message')."<br />\n";
		}
		else {
			// Output as simple text
			if (defined('STDERR')) {
				fwrite(STDERR, "J$level_human: ".$error->get('message')."\n");
			}
			else {
				echo "J$level_human: ".$error->get('message')."\n";
			}
		}

		return $error;
	}

	/**
	 * Verbose error handler
	 *	- Echos the error message to output as well as related info
	 *
	 * @param	object	$error		Exception object to handle
	 * @param	array	$options	Handler options
	 *
	 * @return	object	The exception object
	 * @since	11.1
	 *
	 * @see	raise()
	 */
	public static function handleVerbose(& $error, $options)
	{
		$level_human = JError::translateErrorLevel($error->get('level'));
		$info = $error->get('info');

		if (isset ($_SERVER['HTTP_HOST'])) {
			// Output as html
			echo "<br /><b>J$level_human</b>: ".$error->get('message')."<br />\n";

			if ($info != null) {
				echo "&#160;&#160;&#160;".$info."<br />\n";
			}

			echo $error->getBacktrace(true);
		}
		else {
			// Output as simple text
			echo "J$level_human: ".$error->get('message')."\n";
			if ($info != null) {
				echo "\t".$info."\n";
			}

		}

		return $error;
	}

	/**
	 * Die error handler
	 *	- Echos the error message to output and then dies
	 *
	 * @param	object	$error		Exception object to handle
	 * @param	array	$options	Handler options
	 *
	 * @return	object	The exception object
	 * @since	11.1
	 *
	 * @see	raise()
	 */
	public static function handleDie(& $error, $options)
	{
		$level_human = JError::translateErrorLevel($error->get('level'));

		if (isset ($_SERVER['HTTP_HOST'])) {
			// Output as html
			jexit("<br /><b>J$level_human</b>: ".$error->get('message')."<br />\n");
		}
		else {
			// Output as simple text
			if (defined('STDERR')) {
				fwrite(STDERR, "J$level_human: ".$error->get('message')."\n");
				jexit();
			}
			else {
				jexit("J$level_human: ".$error->get('message')."\n");
			}
		}

		return $error;
	}

	/**
	 * Message error handler
	 *	- Enqueues the error message into the system queue
	 *
	 * @param	object	$error		Exception object to handle
	 * @param	array	$options	Handler options
	 *
	 * @return	object	The exception object
	 * @since	11.1
	 *
	 * @see	raise()
	 */
	public static function handleMessage(& $error, $options)
	{
		$appl = JFactory::getApplication();
		$type = ($error->get('level') == E_NOTICE) ? 'notice' : 'error';
		$appl->enqueueMessage($error->get('message'), $type);

		return $error;
	}

	/**
	 * Log error handler
	 *	- Logs the error message to a system log file
	 *
	 * @param	object	$error		Exception object to handle
	 * @param	array	$options	Handler options
	 *
	 * @return	object	The exception object
	 * @since	11.1
	 *
	 * @see	raise()
	 */
	public static function handleLog(& $error, $options)
	{
		static $log;

		if ($log == null) {
			jimport('joomla.error.log');
			$fileName = date('Y-m-d').'.error.log';
			$options['format'] = "{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}";
			$log = JLog::getInstance($fileName, $options);
		}

		$entry['level'] = $error->get('level');
		$entry['code'] = $error->get('code');
		$entry['message'] = str_replace(array ("\r","\n"), array ('','\\n'), $error->get('message'));
		$log->addEntry($entry);

		return $error;
	}

	/**
	 * Callback error handler
	 *	- Send the error object to a callback method for error handling
	 *
	 * @param	object	$error		Exception object to handle
	 * @param	array	$options	Handler options
	 *
	 * @return	object	The exception object
	 * @since	11.1
	 *
	 * @see	raise()
	 */
	public static function handleCallback(&$error, $options)
	{
		return call_user_func($options, $error);
	}

	/**
	 * Display a custom error page and exit gracefully
	 *
	 * @param	object	$error Exception object
	 * @return	void
	 * @since	11.1
	 */
	public static function customErrorPage(& $error)
	{
		// Initialise variables.
		jimport('joomla.document.document');
		$app		= JFactory::getApplication();
		$document	= JDocument::getInstance('error');
		$config		= JFactory::getConfig();

		// Get the current template from the application
		$template = $app->getTemplate();

		// Push the error object into the document
		$document->setError($error);

		@ob_end_clean();
		$document->setTitle(JText::_('Error').': '.$error->get('code'));
		$data = $document->render(false, array (
			'template' => $template,
			'directory' => JPATH_THEMES,
			'debug' => $config->get('debug')
		));

		// Do not allow cache
		JResponse::allowCache(false);

		JResponse::setBody($data);
		echo JResponse::toString();
		$app->close(0);
	}

	public static function customErrorHandler($level, $msg)
	{
		JError::raise($level, '', $msg);
	}

	public static function renderBacktrace($error)
	{
		$contents	= null;
		$backtrace	= $error->getTrace();

		if (is_array($backtrace)) {
			ob_start();
			$j = 1;
			echo '<table border="0" cellpadding="0" cellspacing="0" class="Table">';
			echo '		<tr>';
			echo '				<td colspan="3" class="TD"><strong>Call stack</strong></td>';
			echo '		</tr>';
			echo '		<tr>';
			echo '				<td class="TD"><strong>#</strong></td>';
			echo '				<td class="TD"><strong>Function</strong></td>';
			echo '				<td class="TD"><strong>Location</strong></td>';
			echo '		</tr>';

			for ($i = count($backtrace)-1; $i >= 0 ; $i--)
			{
				echo	'		<tr>';
				echo	'				<td class="TD">'.$j.'</td>';

				if (isset($backtrace[$i]['class'])) {
						echo	'		<td class="TD">'.$backtrace[$i]['class'].$backtrace[$i]['type'].$backtrace[$i]['function'].'()</td>';
				}
				else {
						echo	'		<td class="TD">'.$backtrace[$i]['function'].'()</td>';
				}

				if (isset($backtrace[$i]['file'])) {
						echo	'				<td class="TD">'.$backtrace[$i]['file'].':'.$backtrace[$i]['line'].'</td>';
				}
				else {
						echo	'				<td class="TD">&#160;</td>';
				}

				echo	'		</tr>';
				$j++;
			}

			echo '</table>';
			$contents = ob_get_contents();
			ob_end_clean();
		}

		return $contents;
	}
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.