ErrorStack.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. <?php
  2. /**
  3. * Error Stack Implementation
  4. *
  5. * This is an incredibly simple implementation of a very complex error handling
  6. * facility. It contains the ability
  7. * to track multiple errors from multiple packages simultaneously. In addition,
  8. * it can track errors of many levels, save data along with the error, context
  9. * information such as the exact file, line number, class and function that
  10. * generated the error, and if necessary, it can raise a traditional PEAR_Error.
  11. * It has built-in support for PEAR::Log, to log errors as they occur
  12. *
  13. * Since version 0.2alpha, it is also possible to selectively ignore errors,
  14. * through the use of an error callback, see {@link pushCallback()}
  15. *
  16. * Since version 0.3alpha, it is possible to specify the exception class
  17. * returned from {@link push()}
  18. *
  19. * Since version PEAR1.3.2, ErrorStack no longer instantiates an exception class. This can
  20. * still be done quite handily in an error callback or by manipulating the returned array
  21. * @category Debugging
  22. * @package PEAR_ErrorStack
  23. * @author Greg Beaver <cellog@php.net>
  24. * @copyright 2004-2008 Greg Beaver
  25. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  26. * @link http://pear.php.net/package/PEAR_ErrorStack
  27. */
  28. /**
  29. * Singleton storage
  30. *
  31. * Format:
  32. * <pre>
  33. * array(
  34. * 'package1' => PEAR_ErrorStack object,
  35. * 'package2' => PEAR_ErrorStack object,
  36. * ...
  37. * )
  38. * </pre>
  39. * @access private
  40. * @global array $GLOBALS['_PEAR_ERRORSTACK_SINGLETON']
  41. */
  42. $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] = array();
  43. /**
  44. * Global error callback (default)
  45. *
  46. * This is only used if set to non-false. * is the default callback for
  47. * all packages, whereas specific packages may set a default callback
  48. * for all instances, regardless of whether they are a singleton or not.
  49. *
  50. * To exclude non-singletons, only set the local callback for the singleton
  51. * @see PEAR_ErrorStack::setDefaultCallback()
  52. * @access private
  53. * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK']
  54. */
  55. $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'] = array(
  56. '*' => false,
  57. );
  58. /**
  59. * Global Log object (default)
  60. *
  61. * This is only used if set to non-false. Use to set a default log object for
  62. * all stacks, regardless of instantiation order or location
  63. * @see PEAR_ErrorStack::setDefaultLogger()
  64. * @access private
  65. * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']
  66. */
  67. $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = false;
  68. /**
  69. * Global Overriding Callback
  70. *
  71. * This callback will override any error callbacks that specific loggers have set.
  72. * Use with EXTREME caution
  73. * @see PEAR_ErrorStack::staticPushCallback()
  74. * @access private
  75. * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']
  76. */
  77. $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
  78. /**#@+
  79. * One of four possible return values from the error Callback
  80. * @see PEAR_ErrorStack::_errorCallback()
  81. */
  82. /**
  83. * If this is returned, then the error will be both pushed onto the stack
  84. * and logged.
  85. */
  86. define('PEAR_ERRORSTACK_PUSHANDLOG', 1);
  87. /**
  88. * If this is returned, then the error will only be pushed onto the stack,
  89. * and not logged.
  90. */
  91. define('PEAR_ERRORSTACK_PUSH', 2);
  92. /**
  93. * If this is returned, then the error will only be logged, but not pushed
  94. * onto the error stack.
  95. */
  96. define('PEAR_ERRORSTACK_LOG', 3);
  97. /**
  98. * If this is returned, then the error is completely ignored.
  99. */
  100. define('PEAR_ERRORSTACK_IGNORE', 4);
  101. /**
  102. * If this is returned, then the error is logged and die() is called.
  103. */
  104. define('PEAR_ERRORSTACK_DIE', 5);
  105. /**#@-*/
  106. /**
  107. * Error code for an attempt to instantiate a non-class as a PEAR_ErrorStack in
  108. * the singleton method.
  109. */
  110. define('PEAR_ERRORSTACK_ERR_NONCLASS', 1);
  111. /**
  112. * Error code for an attempt to pass an object into {@link PEAR_ErrorStack::getMessage()}
  113. * that has no __toString() method
  114. */
  115. define('PEAR_ERRORSTACK_ERR_OBJTOSTRING', 2);
  116. /**
  117. * Error Stack Implementation
  118. *
  119. * Usage:
  120. * <code>
  121. * // global error stack
  122. * $global_stack = &PEAR_ErrorStack::singleton('MyPackage');
  123. * // local error stack
  124. * $local_stack = new PEAR_ErrorStack('MyPackage');
  125. * </code>
  126. * @author Greg Beaver <cellog@php.net>
  127. * @version @package_version@
  128. * @package PEAR_ErrorStack
  129. * @category Debugging
  130. * @copyright 2004-2008 Greg Beaver
  131. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  132. * @link http://pear.php.net/package/PEAR_ErrorStack
  133. */
  134. class PEAR_ErrorStack {
  135. /**
  136. * Errors are stored in the order that they are pushed on the stack.
  137. * @since 0.4alpha Errors are no longer organized by error level.
  138. * This renders pop() nearly unusable, and levels could be more easily
  139. * handled in a callback anyway
  140. * @var array
  141. * @access private
  142. */
  143. var $_errors = array();
  144. /**
  145. * Storage of errors by level.
  146. *
  147. * Allows easy retrieval and deletion of only errors from a particular level
  148. * @since PEAR 1.4.0dev
  149. * @var array
  150. * @access private
  151. */
  152. var $_errorsByLevel = array();
  153. /**
  154. * Package name this error stack represents
  155. * @var string
  156. * @access protected
  157. */
  158. var $_package;
  159. /**
  160. * Determines whether a PEAR_Error is thrown upon every error addition
  161. * @var boolean
  162. * @access private
  163. */
  164. var $_compat = false;
  165. /**
  166. * If set to a valid callback, this will be used to generate the error
  167. * message from the error code, otherwise the message passed in will be
  168. * used
  169. * @var false|string|array
  170. * @access private
  171. */
  172. var $_msgCallback = false;
  173. /**
  174. * If set to a valid callback, this will be used to generate the error
  175. * context for an error. For PHP-related errors, this will be a file
  176. * and line number as retrieved from debug_backtrace(), but can be
  177. * customized for other purposes. The error might actually be in a separate
  178. * configuration file, or in a database query.
  179. * @var false|string|array
  180. * @access protected
  181. */
  182. var $_contextCallback = false;
  183. /**
  184. * If set to a valid callback, this will be called every time an error
  185. * is pushed onto the stack. The return value will be used to determine
  186. * whether to allow an error to be pushed or logged.
  187. *
  188. * The return value must be one an PEAR_ERRORSTACK_* constant
  189. * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG
  190. * @var false|string|array
  191. * @access protected
  192. */
  193. var $_errorCallback = array();
  194. /**
  195. * PEAR::Log object for logging errors
  196. * @var false|Log
  197. * @access protected
  198. */
  199. var $_logger = false;
  200. /**
  201. * Error messages - designed to be overridden
  202. * @var array
  203. * @abstract
  204. */
  205. var $_errorMsgs = array();
  206. /**
  207. * Set up a new error stack
  208. *
  209. * @param string $package name of the package this error stack represents
  210. * @param callback $msgCallback callback used for error message generation
  211. * @param callback $contextCallback callback used for context generation,
  212. * defaults to {@link getFileLine()}
  213. * @param boolean $throwPEAR_Error
  214. */
  215. function __construct($package, $msgCallback = false, $contextCallback = false,
  216. $throwPEAR_Error = false)
  217. {
  218. $this->_package = $package;
  219. $this->setMessageCallback($msgCallback);
  220. $this->setContextCallback($contextCallback);
  221. $this->_compat = $throwPEAR_Error;
  222. }
  223. /**
  224. * Return a single error stack for this package.
  225. *
  226. * Note that all parameters are ignored if the stack for package $package
  227. * has already been instantiated
  228. * @param string $package name of the package this error stack represents
  229. * @param callback $msgCallback callback used for error message generation
  230. * @param callback $contextCallback callback used for context generation,
  231. * defaults to {@link getFileLine()}
  232. * @param boolean $throwPEAR_Error
  233. * @param string $stackClass class to instantiate
  234. *
  235. * @return PEAR_ErrorStack
  236. */
  237. public static function &singleton(
  238. $package, $msgCallback = false, $contextCallback = false,
  239. $throwPEAR_Error = false, $stackClass = 'PEAR_ErrorStack'
  240. ) {
  241. if (isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) {
  242. return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package];
  243. }
  244. if (!class_exists($stackClass)) {
  245. if (function_exists('debug_backtrace')) {
  246. $trace = debug_backtrace();
  247. }
  248. PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_NONCLASS,
  249. 'exception', array('stackclass' => $stackClass),
  250. 'stack class "%stackclass%" is not a valid class name (should be like PEAR_ErrorStack)',
  251. false, $trace);
  252. }
  253. $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package] =
  254. new $stackClass($package, $msgCallback, $contextCallback, $throwPEAR_Error);
  255. return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package];
  256. }
  257. /**
  258. * Internal error handler for PEAR_ErrorStack class
  259. *
  260. * Dies if the error is an exception (and would have died anyway)
  261. * @access private
  262. */
  263. function _handleError($err)
  264. {
  265. if ($err['level'] == 'exception') {
  266. $message = $err['message'];
  267. if (isset($_SERVER['REQUEST_URI'])) {
  268. echo '<br />';
  269. } else {
  270. echo "\n";
  271. }
  272. var_dump($err['context']);
  273. die($message);
  274. }
  275. }
  276. /**
  277. * Set up a PEAR::Log object for all error stacks that don't have one
  278. * @param Log $log
  279. */
  280. public static function setDefaultLogger(&$log)
  281. {
  282. if (is_object($log) && method_exists($log, 'log') ) {
  283. $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = &$log;
  284. } elseif (is_callable($log)) {
  285. $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = &$log;
  286. }
  287. }
  288. /**
  289. * Set up a PEAR::Log object for this error stack
  290. * @param Log $log
  291. */
  292. function setLogger(&$log)
  293. {
  294. if (is_object($log) && method_exists($log, 'log') ) {
  295. $this->_logger = &$log;
  296. } elseif (is_callable($log)) {
  297. $this->_logger = &$log;
  298. }
  299. }
  300. /**
  301. * Set an error code => error message mapping callback
  302. *
  303. * This method sets the callback that can be used to generate error
  304. * messages for any instance
  305. * @param array|string Callback function/method
  306. */
  307. function setMessageCallback($msgCallback)
  308. {
  309. if (!$msgCallback) {
  310. $this->_msgCallback = array(&$this, 'getErrorMessage');
  311. } else {
  312. if (is_callable($msgCallback)) {
  313. $this->_msgCallback = $msgCallback;
  314. }
  315. }
  316. }
  317. /**
  318. * Get an error code => error message mapping callback
  319. *
  320. * This method returns the current callback that can be used to generate error
  321. * messages
  322. * @return array|string|false Callback function/method or false if none
  323. */
  324. function getMessageCallback()
  325. {
  326. return $this->_msgCallback;
  327. }
  328. /**
  329. * Sets a default callback to be used by all error stacks
  330. *
  331. * This method sets the callback that can be used to generate error
  332. * messages for a singleton
  333. * @param array|string Callback function/method
  334. * @param string Package name, or false for all packages
  335. */
  336. public static function setDefaultCallback($callback = false, $package = false)
  337. {
  338. if (!is_callable($callback)) {
  339. $callback = false;
  340. }
  341. $package = $package ? $package : '*';
  342. $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$package] = $callback;
  343. }
  344. /**
  345. * Set a callback that generates context information (location of error) for an error stack
  346. *
  347. * This method sets the callback that can be used to generate context
  348. * information for an error. Passing in NULL will disable context generation
  349. * and remove the expensive call to debug_backtrace()
  350. * @param array|string|null Callback function/method
  351. * @return bool
  352. * @return array|bool|callable|false|string
  353. */
  354. function setContextCallback($contextCallback)
  355. {
  356. if ($contextCallback === null) {
  357. return $this->_contextCallback = false;
  358. }
  359. if (!$contextCallback) {
  360. $this->_contextCallback = [&$this, 'getFileLine'];
  361. } else {
  362. if (is_callable($contextCallback)) {
  363. $this->_contextCallback = $contextCallback;
  364. }
  365. }
  366. return $this->_contextCallback;
  367. }
  368. /**
  369. * Set an error Callback
  370. * If set to a valid callback, this will be called every time an error
  371. * is pushed onto the stack. The return value will be used to determine
  372. * whether to allow an error to be pushed or logged.
  373. *
  374. * The return value must be one of the ERRORSTACK_* constants.
  375. *
  376. * This functionality can be used to emulate PEAR's pushErrorHandling, and
  377. * the PEAR_ERROR_CALLBACK mode, without affecting the integrity of
  378. * the error stack or logging
  379. * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG
  380. * @see popCallback()
  381. * @param string|array $cb
  382. */
  383. function pushCallback($cb)
  384. {
  385. array_push($this->_errorCallback, $cb);
  386. }
  387. /**
  388. * Remove a callback from the error callback stack
  389. * @see pushCallback()
  390. * @return array|string|false
  391. */
  392. function popCallback()
  393. {
  394. if (!count($this->_errorCallback)) {
  395. return false;
  396. }
  397. return array_pop($this->_errorCallback);
  398. }
  399. /**
  400. * Set a temporary overriding error callback for every package error stack
  401. *
  402. * Use this to temporarily disable all existing callbacks (can be used
  403. * to emulate the @ operator, for instance)
  404. * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG
  405. * @see staticPopCallback(), pushCallback()
  406. * @param string|array $cb
  407. */
  408. public static function staticPushCallback($cb)
  409. {
  410. array_push($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'], $cb);
  411. }
  412. /**
  413. * Remove a temporary overriding error callback
  414. * @see staticPushCallback()
  415. * @return array|string|false
  416. */
  417. public static function staticPopCallback()
  418. {
  419. $ret = array_pop($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK']);
  420. if (!is_array($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'])) {
  421. $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
  422. }
  423. return $ret;
  424. }
  425. /**
  426. * Add an error to the stack
  427. *
  428. * If the message generator exists, it is called with 2 parameters.
  429. * - the current Error Stack object
  430. * - an array that is in the same format as an error. Available indices
  431. * are 'code', 'package', 'time', 'params', 'level', and 'context'
  432. *
  433. * Next, if the error should contain context information, this is
  434. * handled by the context grabbing method.
  435. * Finally, the error is pushed onto the proper error stack
  436. * @param int $code Package-specific error code
  437. * @param string $level Error level. This is NOT spell-checked
  438. * @param array $params associative array of error parameters
  439. * @param string $msg Error message, or a portion of it if the message
  440. * is to be generated
  441. * @param array $repackage If this error re-packages an error pushed by
  442. * another package, place the array returned from
  443. * {@link pop()} in this parameter
  444. * @param array $backtrace Protected parameter: use this to pass in the
  445. * {@link debug_backtrace()} that should be used
  446. * to find error context
  447. * @return PEAR_Error|array if compatibility mode is on, a PEAR_Error is also
  448. * thrown. If a PEAR_Error is returned, the userinfo
  449. * property is set to the following array:
  450. *
  451. * <code>
  452. * array(
  453. * 'code' => $code,
  454. * 'params' => $params,
  455. * 'package' => $this->_package,
  456. * 'level' => $level,
  457. * 'time' => time(),
  458. * 'context' => $context,
  459. * 'message' => $msg,
  460. * //['repackage' => $err] repackaged error array/Exception class
  461. * );
  462. * </code>
  463. *
  464. * Normally, the previous array is returned.
  465. */
  466. function push($code, $level = 'error', $params = array(), $msg = false,
  467. $repackage = false, $backtrace = false)
  468. {
  469. $context = false;
  470. // grab error context
  471. if ($this->_contextCallback) {
  472. if (!$backtrace) {
  473. $backtrace = debug_backtrace();
  474. }
  475. $context = call_user_func($this->_contextCallback, $code, $params, $backtrace);
  476. }
  477. // save error
  478. $time = explode(' ', microtime());
  479. $time = $time[1] + $time[0];
  480. $err = array(
  481. 'code' => $code,
  482. 'params' => $params,
  483. 'package' => $this->_package,
  484. 'level' => $level,
  485. 'time' => $time,
  486. 'context' => $context,
  487. 'message' => $msg,
  488. );
  489. if ($repackage) {
  490. $err['repackage'] = $repackage;
  491. }
  492. // set up the error message, if necessary
  493. if ($this->_msgCallback) {
  494. $msg = call_user_func_array($this->_msgCallback,
  495. array(&$this, $err));
  496. $err['message'] = $msg;
  497. }
  498. $push = $log = true;
  499. $die = false;
  500. // try the overriding callback first
  501. $callback = $this->staticPopCallback();
  502. if ($callback) {
  503. $this->staticPushCallback($callback);
  504. }
  505. if (!is_callable($callback)) {
  506. // try the local callback next
  507. $callback = $this->popCallback();
  508. if (is_callable($callback)) {
  509. $this->pushCallback($callback);
  510. } else {
  511. // try the default callback
  512. $callback = isset($GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$this->_package]) ?
  513. $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$this->_package] :
  514. $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK']['*'];
  515. }
  516. }
  517. if (is_callable($callback)) {
  518. switch(call_user_func($callback, $err)){
  519. case PEAR_ERRORSTACK_IGNORE:
  520. return $err;
  521. break;
  522. case PEAR_ERRORSTACK_PUSH:
  523. $log = false;
  524. break;
  525. case PEAR_ERRORSTACK_LOG:
  526. $push = false;
  527. break;
  528. case PEAR_ERRORSTACK_DIE:
  529. $die = true;
  530. break;
  531. // anything else returned has the same effect as pushandlog
  532. }
  533. }
  534. if ($push) {
  535. array_unshift($this->_errors, $err);
  536. if (!isset($this->_errorsByLevel[$err['level']])) {
  537. $this->_errorsByLevel[$err['level']] = array();
  538. }
  539. $this->_errorsByLevel[$err['level']][] = &$this->_errors[0];
  540. }
  541. if ($log) {
  542. if ($this->_logger || $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']) {
  543. $this->_log($err);
  544. }
  545. }
  546. if ($die) {
  547. die();
  548. }
  549. if ($this->_compat && $push) {
  550. return $this->raiseError($msg, $code, null, null, $err);
  551. }
  552. return $err;
  553. }
  554. /**
  555. * Static version of {@link push()}
  556. *
  557. * @param string $package Package name this error belongs to
  558. * @param int $code Package-specific error code
  559. * @param string $level Error level. This is NOT spell-checked
  560. * @param array $params associative array of error parameters
  561. * @param string $msg Error message, or a portion of it if the message
  562. * is to be generated
  563. * @param array $repackage If this error re-packages an error pushed by
  564. * another package, place the array returned from
  565. * {@link pop()} in this parameter
  566. * @param array $backtrace Protected parameter: use this to pass in the
  567. * {@link debug_backtrace()} that should be used
  568. * to find error context
  569. * @return PEAR_Error|array if compatibility mode is on, a PEAR_Error is also
  570. * thrown. see docs for {@link push()}
  571. */
  572. public static function staticPush(
  573. $package, $code, $level = 'error', $params = array(),
  574. $msg = false, $repackage = false, $backtrace = false
  575. ) {
  576. $s = &PEAR_ErrorStack::singleton($package);
  577. if ($s->_contextCallback) {
  578. if (!$backtrace) {
  579. if (function_exists('debug_backtrace')) {
  580. $backtrace = debug_backtrace();
  581. }
  582. }
  583. }
  584. return $s->push($code, $level, $params, $msg, $repackage, $backtrace);
  585. }
  586. /**
  587. * Log an error using PEAR::Log
  588. * @param array $err Error array
  589. * @param array $levels Error level => Log constant map
  590. * @access protected
  591. */
  592. function _log($err)
  593. {
  594. if ($this->_logger) {
  595. $logger = &$this->_logger;
  596. } else {
  597. $logger = &$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'];
  598. }
  599. if (is_a($logger, 'Log')) {
  600. $levels = array(
  601. 'exception' => PEAR_LOG_CRIT,
  602. 'alert' => PEAR_LOG_ALERT,
  603. 'critical' => PEAR_LOG_CRIT,
  604. 'error' => PEAR_LOG_ERR,
  605. 'warning' => PEAR_LOG_WARNING,
  606. 'notice' => PEAR_LOG_NOTICE,
  607. 'info' => PEAR_LOG_INFO,
  608. 'debug' => PEAR_LOG_DEBUG);
  609. if (isset($levels[$err['level']])) {
  610. $level = $levels[$err['level']];
  611. } else {
  612. $level = PEAR_LOG_INFO;
  613. }
  614. $logger->log($err['message'], $level, $err);
  615. } else { // support non-standard logs
  616. call_user_func($logger, $err);
  617. }
  618. }
  619. /**
  620. * Pop an error off of the error stack
  621. *
  622. * @return false|array
  623. * @since 0.4alpha it is no longer possible to specify a specific error
  624. * level to return - the last error pushed will be returned, instead
  625. */
  626. function pop()
  627. {
  628. $err = @array_shift($this->_errors);
  629. if (!is_null($err)) {
  630. @array_pop($this->_errorsByLevel[$err['level']]);
  631. if (!count($this->_errorsByLevel[$err['level']])) {
  632. unset($this->_errorsByLevel[$err['level']]);
  633. }
  634. }
  635. return $err;
  636. }
  637. /**
  638. * Pop an error off of the error stack, static method
  639. *
  640. * @param string package name
  641. * @return boolean
  642. * @since PEAR1.5.0a1
  643. */
  644. static function staticPop($package)
  645. {
  646. if ($package) {
  647. if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) {
  648. return false;
  649. }
  650. return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->pop();
  651. }
  652. return false;
  653. }
  654. /**
  655. * Determine whether there are any errors on the stack
  656. * @param string|array|bool $level name. Use to determine if any errors
  657. * of level (string), or levels (array) have been pushed
  658. * @return boolean
  659. */
  660. function hasErrors($level = false)
  661. {
  662. if ($level) {
  663. return isset($this->_errorsByLevel[$level]);
  664. }
  665. return count($this->_errors);
  666. }
  667. /**
  668. * Retrieve all errors since last purge
  669. *
  670. * @param boolean set in order to empty the error stack
  671. * @param string level name, to return only errors of a particular severity
  672. * @return array
  673. */
  674. function getErrors($purge = false, $level = false)
  675. {
  676. if (!$purge) {
  677. if ($level) {
  678. if (!isset($this->_errorsByLevel[$level])) {
  679. return array();
  680. } else {
  681. return $this->_errorsByLevel[$level];
  682. }
  683. } else {
  684. return $this->_errors;
  685. }
  686. }
  687. if ($level) {
  688. $ret = $this->_errorsByLevel[$level];
  689. foreach ($this->_errorsByLevel[$level] as $i => $unused) {
  690. // entries are references to the $_errors array
  691. $this->_errorsByLevel[$level][$i] = false;
  692. }
  693. // array_filter removes all entries === false
  694. $this->_errors = array_filter($this->_errors);
  695. unset($this->_errorsByLevel[$level]);
  696. return $ret;
  697. }
  698. $ret = $this->_errors;
  699. $this->_errors = array();
  700. $this->_errorsByLevel = array();
  701. return $ret;
  702. }
  703. /**
  704. * Determine whether there are any errors on a single error stack, or on any error stack
  705. *
  706. * The optional parameter can be used to test the existence of any errors without the need of
  707. * singleton instantiation
  708. * @param string|false Package name to check for errors
  709. * @param string Level name to check for a particular severity
  710. * @return boolean
  711. */
  712. public static function staticHasErrors($package = false, $level = false)
  713. {
  714. if ($package) {
  715. if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) {
  716. return false;
  717. }
  718. return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->hasErrors($level);
  719. }
  720. foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) {
  721. if ($obj->hasErrors($level)) {
  722. return true;
  723. }
  724. }
  725. return false;
  726. }
  727. /**
  728. * Get a list of all errors since last purge, organized by package
  729. * @since PEAR 1.4.0dev BC break! $level is now in the place $merge used to be
  730. * @param boolean $purge Set to purge the error stack of existing errors
  731. * @param string $level Set to a level name in order to retrieve only errors of a particular level
  732. * @param boolean $merge Set to return a flat array, not organized by package
  733. * @param array $sortfunc Function used to sort a merged array - default
  734. * sorts by time, and should be good for most cases
  735. *
  736. * @return array
  737. */
  738. public static function staticGetErrors(
  739. $purge = false, $level = false, $merge = false,
  740. $sortfunc = array('PEAR_ErrorStack', '_sortErrors')
  741. ) {
  742. $ret = array();
  743. if (!is_callable($sortfunc)) {
  744. $sortfunc = array('PEAR_ErrorStack', '_sortErrors');
  745. }
  746. foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) {
  747. $test = $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->getErrors($purge, $level);
  748. if ($test) {
  749. if ($merge) {
  750. $ret = array_merge($ret, $test);
  751. } else {
  752. $ret[$package] = $test;
  753. }
  754. }
  755. }
  756. if ($merge) {
  757. usort($ret, $sortfunc);
  758. }
  759. return $ret;
  760. }
  761. /**
  762. * Error sorting function, sorts by time
  763. * @access private
  764. */
  765. public static function _sortErrors($a, $b)
  766. {
  767. if ($a['time'] == $b['time']) {
  768. return 0;
  769. }
  770. if ($a['time'] < $b['time']) {
  771. return 1;
  772. }
  773. return -1;
  774. }
  775. /**
  776. * Standard file/line number/function/class context callback
  777. *
  778. * This function uses a backtrace generated from {@link debug_backtrace()}
  779. * and so will not work at all in PHP < 4.3.0. The frame should
  780. * reference the frame that contains the source of the error.
  781. * @return array|false either array('file' => file, 'line' => line,
  782. * 'function' => function name, 'class' => class name) or
  783. * if this doesn't work, then false
  784. * @param unused
  785. * @param integer backtrace frame.
  786. * @param array Results of debug_backtrace()
  787. */
  788. public static function getFileLine($code, $params, $backtrace = null)
  789. {
  790. if ($backtrace === null) {
  791. return false;
  792. }
  793. $frame = 0;
  794. $functionframe = 1;
  795. if (!isset($backtrace[1])) {
  796. $functionframe = 0;
  797. } else {
  798. while (isset($backtrace[$functionframe]['function']) &&
  799. $backtrace[$functionframe]['function'] == 'eval' &&
  800. isset($backtrace[$functionframe + 1])) {
  801. $functionframe++;
  802. }
  803. }
  804. if (isset($backtrace[$frame])) {
  805. if (!isset($backtrace[$frame]['file'])) {
  806. $frame++;
  807. }
  808. $funcbacktrace = $backtrace[$functionframe];
  809. $filebacktrace = $backtrace[$frame];
  810. $ret = array('file' => $filebacktrace['file'],
  811. 'line' => $filebacktrace['line']);
  812. // rearrange for eval'd code or create function errors
  813. if (strpos($filebacktrace['file'], '(') &&
  814. preg_match(';^(.*?)\((\d+)\) : (.*?)\\z;', $filebacktrace['file'],
  815. $matches)) {
  816. $ret['file'] = $matches[1];
  817. $ret['line'] = $matches[2] + 0;
  818. }
  819. if (isset($funcbacktrace['function']) && isset($backtrace[1])) {
  820. if ($funcbacktrace['function'] != 'eval') {
  821. if ($funcbacktrace['function'] == '__lambda_func') {
  822. $ret['function'] = 'create_function() code';
  823. } else {
  824. $ret['function'] = $funcbacktrace['function'];
  825. }
  826. }
  827. }
  828. if (isset($funcbacktrace['class']) && isset($backtrace[1])) {
  829. $ret['class'] = $funcbacktrace['class'];
  830. }
  831. return $ret;
  832. }
  833. return false;
  834. }
  835. /**
  836. * Standard error message generation callback
  837. *
  838. * This method may also be called by a custom error message generator
  839. * to fill in template values from the params array, simply
  840. * set the third parameter to the error message template string to use
  841. *
  842. * The special variable %__msg% is reserved: use it only to specify
  843. * where a message passed in by the user should be placed in the template,
  844. * like so:
  845. *
  846. * Error message: %msg% - internal error
  847. *
  848. * If the message passed like so:
  849. *
  850. * <code>
  851. * $stack->push(ERROR_CODE, 'error', array(), 'server error 500');
  852. * </code>
  853. *
  854. * The returned error message will be "Error message: server error 500 -
  855. * internal error"
  856. * @param PEAR_ErrorStack
  857. * @param array
  858. * @param string|false Pre-generated error message template
  859. *
  860. * @return string
  861. */
  862. public static function getErrorMessage(&$stack, $err, $template = false)
  863. {
  864. if ($template) {
  865. $mainmsg = $template;
  866. } else {
  867. $mainmsg = $stack->getErrorMessageTemplate($err['code']);
  868. }
  869. $mainmsg = str_replace('%__msg%', $err['message'], $mainmsg);
  870. if (is_array($err['params']) && count($err['params'])) {
  871. foreach ($err['params'] as $name => $val) {
  872. if (is_array($val)) {
  873. // @ is needed in case $val is a multi-dimensional array
  874. $val = @implode(', ', $val);
  875. }
  876. if (is_object($val)) {
  877. if (method_exists($val, '__toString')) {
  878. $val = $val->__toString();
  879. } else {
  880. PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_OBJTOSTRING,
  881. 'warning', array('obj' => get_class($val)),
  882. 'object %obj% passed into getErrorMessage, but has no __toString() method');
  883. $val = 'Object';
  884. }
  885. }
  886. $mainmsg = str_replace('%' . $name . '%', $val, $mainmsg);
  887. }
  888. }
  889. return $mainmsg;
  890. }
  891. /**
  892. * Standard Error Message Template generator from code
  893. * @return string
  894. */
  895. function getErrorMessageTemplate($code)
  896. {
  897. if (!isset($this->_errorMsgs[$code])) {
  898. return '%__msg%';
  899. }
  900. return $this->_errorMsgs[$code];
  901. }
  902. /**
  903. * Set the Error Message Template array
  904. *
  905. * The array format must be:
  906. * <pre>
  907. * array(error code => 'message template',...)
  908. * </pre>
  909. *
  910. * Error message parameters passed into {@link push()} will be used as input
  911. * for the error message. If the template is 'message %foo% was %bar%', and the
  912. * parameters are array('foo' => 'one', 'bar' => 'six'), the error message returned will
  913. * be 'message one was six'
  914. *
  915. * Returns string via property
  916. * @param $template
  917. * @return null
  918. */
  919. function setErrorMessageTemplate($template)
  920. {
  921. $this->_errorMsgs = $template;
  922. return null;
  923. }
  924. /**
  925. * emulate PEAR::raiseError()
  926. *
  927. * @return PEAR_Error
  928. */
  929. function raiseError()
  930. {
  931. require_once '../PEAR.php';
  932. $args = func_get_args();
  933. return call_user_func_array(array('PEAR', 'raiseError'), $args);
  934. }
  935. }
  936. $stack = &PEAR_ErrorStack::singleton('PEAR_ErrorStack');
  937. $stack->pushCallback(array('PEAR_ErrorStack', '_handleError'));