]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/PEAR/Exception.php
Update PEAR to v1.10.9 and patch it so it works quietly
[quix0rs-gnu-social.git] / extlib / PEAR / Exception.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 /**
4  * PEAR_Exception
5  *
6  * PHP versions 4 and 5
7  *
8  * @category   pear
9  * @package    PEAR
10  * @author     Tomas V. V. Cox <cox@idecnet.com>
11  * @author     Hans Lellelid <hans@velum.net>
12  * @author     Bertrand Mansion <bmansion@mamasam.com>
13  * @author     Greg Beaver <cellog@php.net>
14  * @copyright  1997-2009 The Authors
15  * @license    http://opensource.org/licenses/bsd-license.php New BSD License
16  * @version    CVS: $Id: Exception.php 313023 2011-07-06 19:17:11Z dufuz $
17  * @link       http://pear.php.net/package/PEAR
18  * @since      File available since Release 1.3.3
19  */
20
21
22 /**
23  * Base PEAR_Exception Class
24  *
25  * 1) Features:
26  *
27  * - Nestable exceptions (throw new PEAR_Exception($msg, $prev_exception))
28  * - Definable triggers, shot when exceptions occur
29  * - Pretty and informative error messages
30  * - Added more context info available (like class, method or cause)
31  * - cause can be a PEAR_Exception or an array of mixed
32  *   PEAR_Exceptions/PEAR_ErrorStack warnings
33  * - callbacks for specific exception classes and their children
34  *
35  * 2) Ideas:
36  *
37  * - Maybe a way to define a 'template' for the output
38  *
39  * 3) Inherited properties from PHP Exception Class:
40  *
41  * protected $message
42  * protected $code
43  * protected $line
44  * protected $file
45  * private   $trace
46  *
47  * 4) Inherited methods from PHP Exception Class:
48  *
49  * __clone
50  * __construct
51  * getMessage
52  * getCode
53  * getFile
54  * getLine
55  * getTraceSafe
56  * getTraceSafeAsString
57  * __toString
58  *
59  * 5) Usage example
60  *
61  * <code>
62  *  require_once 'PEAR/Exception.php';
63  *
64  *  class Test {
65  *     function foo() {
66  *         throw new PEAR_Exception('Error Message', ERROR_CODE);
67  *     }
68  *  }
69  *
70  *  function myLogger($pear_exception) {
71  *     echo $pear_exception->getMessage();
72  *  }
73  *  // each time a exception is thrown the 'myLogger' will be called
74  *  // (its use is completely optional)
75  *  PEAR_Exception::addObserver('myLogger');
76  *  $test = new Test;
77  *  try {
78  *     $test->foo();
79  *  } catch (PEAR_Exception $e) {
80  *     print $e;
81  *  }
82  * </code>
83  *
84  * @category   pear
85  * @package    PEAR
86  * @author     Tomas V.V.Cox <cox@idecnet.com>
87  * @author     Hans Lellelid <hans@velum.net>
88  * @author     Bertrand Mansion <bmansion@mamasam.com>
89  * @author     Greg Beaver <cellog@php.net>
90  * @copyright  1997-2009 The Authors
91  * @license    http://opensource.org/licenses/bsd-license.php New BSD License
92  * @version    Release: 1.9.4
93  * @link       http://pear.php.net/package/PEAR
94  * @since      Class available since Release 1.3.3
95  *
96  */
97 class PEAR_Exception extends Exception
98 {
99     const OBSERVER_PRINT = -2;
100     const OBSERVER_TRIGGER = -4;
101     const OBSERVER_DIE = -8;
102     private static $_observers = array();
103     private static $_uniqueid = 0;
104     protected $cause;
105     private $_trace;
106
107     /**
108      * Supported signatures:
109      *  - PEAR_Exception(string $message);
110      *  - PEAR_Exception(string $message, int $code);
111      *  - PEAR_Exception(string $message, Exception $cause);
112      *  - PEAR_Exception(string $message, Exception $cause, int $code);
113      *  - PEAR_Exception(string $message, PEAR_Error $cause);
114      *  - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
115      *  - PEAR_Exception(string $message, array $causes);
116      *  - PEAR_Exception(string $message, array $causes, int $code);
117      * @param string exception message
118      * @param int|Exception|PEAR_Error|array|null exception cause
119      * @param int|null exception code or null
120      * @throws PEAR_Exception
121      */
122     public function __construct($message, $p2 = null, $p3 = null)
123     {
124         if (is_int($p2)) {
125             $code = $p2;
126             $this->cause = null;
127         } elseif (is_object($p2) || is_array($p2)) {
128             // using is_object allows both Exception and PEAR_Error
129             if (is_object($p2) && !($p2 instanceof Exception)) {
130                 if (!class_exists('PEAR_Error') || !($p2 instanceof PEAR_Error)) {
131                     throw new PEAR_Exception('exception cause must be Exception, ' .
132                         'array, or PEAR_Error');
133                 }
134             }
135             $code = $p3;
136             if (is_array($p2) && isset($p2['message'])) {
137                 // fix potential problem of passing in a single warning
138                 $p2 = array($p2);
139             }
140             $this->cause = $p2;
141         } else {
142             $code = null;
143             $this->cause = null;
144         }
145         parent::__construct($message, $code);
146         $this->signal();
147     }
148
149     private function signal()
150     {
151         foreach (self::$_observers as $func) {
152             if (is_callable($func)) {
153                 call_user_func($func, $this);
154                 continue;
155             }
156             settype($func, 'array');
157             switch ($func[0]) {
158                 case self::OBSERVER_PRINT :
159                     $f = (isset($func[1])) ? $func[1] : '%s';
160                     printf($f, $this->getMessage());
161                     break;
162                 case self::OBSERVER_TRIGGER :
163                     $f = (isset($func[1])) ? $func[1] : E_USER_NOTICE;
164                     trigger_error($this->getMessage(), $f);
165                     break;
166                 case self::OBSERVER_DIE :
167                     $f = (isset($func[1])) ? $func[1] : '%s';
168                     die(printf($f, $this->getMessage()));
169                     break;
170                 default:
171                     trigger_error('invalid observer type', E_USER_WARNING);
172             }
173         }
174     }
175
176     /**
177      * @param mixed $callback - A valid php callback, see php func is_callable()
178      *                         - A PEAR_Exception::OBSERVER_* constant
179      *                         - An array(const PEAR_Exception::OBSERVER_*,
180      *                           mixed $options)
181      * @param string $label The name of the observer. Use this if you want
182      *                         to remove it later with removeObserver()
183      */
184     public static function addObserver($callback, $label = 'default')
185     {
186         self::$_observers[$label] = $callback;
187     }
188
189     public static function removeObserver($label = 'default')
190     {
191         unset(self::$_observers[$label]);
192     }
193
194     /**
195      * @return int unique identifier for an observer
196      */
197     public static function getUniqueId()
198     {
199         return self::$_uniqueid++;
200     }
201
202     /**
203      * Return specific error information that can be used for more detailed
204      * error messages or translation.
205      *
206      * This method may be overridden in child exception classes in order
207      * to add functionality not present in PEAR_Exception and is a placeholder
208      * to define API
209      *
210      * The returned array must be an associative array of parameter => value like so:
211      * <pre>
212      * array('name' => $name, 'context' => array(...))
213      * </pre>
214      * @return array
215      */
216     public function getErrorData()
217     {
218         return array();
219     }
220
221     /**
222      * Returns the exception that caused this exception to be thrown
223      * @access public
224      * @return Exception|array The context of the exception
225      */
226     public function getCause()
227     {
228         return $this->cause;
229     }
230
231     public function getErrorClass()
232     {
233         $trace = $this->getTraceSafe();
234         return $trace[0]['class'];
235     }
236
237     public function getErrorMethod()
238     {
239         $trace = $this->getTraceSafe();
240         return $trace[0]['function'];
241     }
242
243     public function __toString()
244     {
245         if (isset($_SERVER['REQUEST_URI'])) {
246             return $this->toHtml();
247         }
248         return $this->toText();
249     }
250
251     public function toHtml()
252     {
253         $trace = $this->getTraceSafe();
254         $causes = array();
255         $this->getCauseMessage($causes);
256         $html = '<table style="border: 1px" cellspacing="0">' . "\n";
257         foreach ($causes as $i => $cause) {
258             $html .= '<tr><td colspan="3" style="background: #ff9999">'
259                 . str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
260                 . htmlspecialchars($cause['message']) . ' in <b>' . $cause['file'] . '</b> '
261                 . 'on line <b>' . $cause['line'] . '</b>'
262                 . "</td></tr>\n";
263         }
264         $html .= '<tr><td colspan="3" style="background-color: #aaaaaa; text-align: center; font-weight: bold;">Exception trace</td></tr>' . "\n"
265             . '<tr><td style="text-align: center; background: #cccccc; width:20px; font-weight: bold;">#</td>'
266             . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Function</td>'
267             . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Location</td></tr>' . "\n";
268
269         foreach ($trace as $k => $v) {
270             $html .= '<tr><td style="text-align: center;">' . $k . '</td>'
271                 . '<td>';
272             if (!empty($v['class'])) {
273                 $html .= $v['class'] . $v['type'];
274             }
275             $html .= $v['function'];
276             $args = array();
277             if (!empty($v['args'])) {
278                 foreach ($v['args'] as $arg) {
279                     if (is_null($arg)) $args[] = 'null';
280                     elseif (is_array($arg)) $args[] = 'Array';
281                     elseif (is_object($arg)) $args[] = 'Object(' . get_class($arg) . ')';
282                     elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
283                     elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
284                     else {
285                         $arg = (string)$arg;
286                         $str = htmlspecialchars(substr($arg, 0, 16));
287                         if (strlen($arg) > 16) $str .= '&hellip;';
288                         $args[] = "'" . $str . "'";
289                     }
290                 }
291             }
292             $html .= '(' . implode(', ', $args) . ')'
293                 . '</td>'
294                 . '<td>' . (isset($v['file']) ? $v['file'] : 'unknown')
295                 . ':' . (isset($v['line']) ? $v['line'] : 'unknown')
296                 . '</td></tr>' . "\n";
297         }
298         $html .= '<tr><td style="text-align: center;">' . ($k + 1) . '</td>'
299             . '<td>{main}</td>'
300             . '<td>&nbsp;</td></tr>' . "\n"
301             . '</table>';
302         return $html;
303     }
304
305     /**
306      * Function must be public to call on caused exceptions
307      * @param array
308      */
309     public function getCauseMessage(&$causes)
310     {
311         $trace = $this->getTraceSafe();
312         $cause = array('class' => get_class($this),
313             'message' => $this->message,
314             'file' => 'unknown',
315             'line' => 'unknown');
316         if (isset($trace[0])) {
317             if (isset($trace[0]['file'])) {
318                 $cause['file'] = $trace[0]['file'];
319                 $cause['line'] = $trace[0]['line'];
320             }
321         }
322         $causes[] = $cause;
323         if ($this->cause instanceof PEAR_Exception) {
324             $this->cause->getCauseMessage($causes);
325         } elseif ($this->cause instanceof Exception) {
326             $causes[] = array('class' => get_class($this->cause),
327                 'message' => $this->cause->getMessage(),
328                 'file' => $this->cause->getFile(),
329                 'line' => $this->cause->getLine());
330         } elseif (class_exists('PEAR_Error') && $this->cause instanceof PEAR_Error) {
331             $causes[] = array('class' => get_class($this->cause),
332                 'message' => $this->cause->getMessage(),
333                 'file' => 'unknown',
334                 'line' => 'unknown');
335         } elseif (is_array($this->cause)) {
336             foreach ($this->cause as $cause) {
337                 if ($cause instanceof PEAR_Exception) {
338                     $cause->getCauseMessage($causes);
339                 } elseif ($cause instanceof Exception) {
340                     $causes[] = array('class' => get_class($cause),
341                         'message' => $cause->getMessage(),
342                         'file' => $cause->getFile(),
343                         'line' => $cause->getLine());
344                 } elseif (class_exists('PEAR_Error') && $cause instanceof PEAR_Error) {
345                     $causes[] = array('class' => get_class($cause),
346                         'message' => $cause->getMessage(),
347                         'file' => 'unknown',
348                         'line' => 'unknown');
349                 } elseif (is_array($cause) && isset($cause['message'])) {
350                     // PEAR_ErrorStack warning
351                     $causes[] = array(
352                         'class' => $cause['package'],
353                         'message' => $cause['message'],
354                         'file' => isset($cause['context']['file']) ?
355                             $cause['context']['file'] :
356                             'unknown',
357                         'line' => isset($cause['context']['line']) ?
358                             $cause['context']['line'] :
359                             'unknown',
360                     );
361                 }
362             }
363         }
364     }
365
366     public function getTraceSafe()
367     {
368         if (!isset($this->_trace)) {
369             $this->_trace = $this->getTrace();
370             if (empty($this->_trace)) {
371                 $backtrace = debug_backtrace();
372                 $this->_trace = array($backtrace[count($backtrace) - 1]);
373             }
374         }
375         return $this->_trace;
376     }
377
378     public function toText()
379     {
380         $causes = array();
381         $this->getCauseMessage($causes);
382         $causeMsg = '';
383         foreach ($causes as $i => $cause) {
384             $causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': '
385                 . $cause['message'] . ' in ' . $cause['file']
386                 . ' on line ' . $cause['line'] . "\n";
387         }
388         return $causeMsg . $this->getTraceAsString();
389     }
390 }