AjaxHandler.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * Ajax Handler
  4. *
  5. * @author vesta, http://vestacp.com/
  6. * @author Dmitry Malishev <dima.malishev@gmail.com>
  7. * @author Dmitry Naumov-Socolov <naumov.socolov@gmail.com>
  8. * @copyright vesta 2010-2011
  9. */
  10. class AjaxHandler {
  11. static public $instance = null;
  12. public $errors = array();
  13. public $status = TRUE;
  14. /**
  15. * Grab current instance or create it
  16. *
  17. * @return AjaxHandler
  18. */
  19. static function getInstance($request=null)
  20. {
  21. return null == self::$instance ? self::$instance = new self() : self::$instance;
  22. }
  23. /**
  24. * Called functions should reply in the following way
  25. * return $this->reply($result, $data, $msg, $extra);
  26. *
  27. * @param Request $request
  28. * @return string
  29. */
  30. function dispatch($request) {
  31. $method = Request::parseAjaxMethod($request);
  32. $inc_file = V_ROOT_DIR . 'api' . DIRECTORY_SEPARATOR . $method['namespace'] . '.class.php';
  33. if (!is_readable($inc_file)) {
  34. throw new SystemException(Message::INVALID_METHOD);
  35. }
  36. require $inc_file;
  37. $space = new $method['namespace'];
  38. $method = $method['function'] . 'Execute';
  39. if (!method_exists($space, $method)) {
  40. throw new SystemException(Message::INVALID_METHOD);
  41. }
  42. return $space->$method($request);
  43. }
  44. /**
  45. * Prepare response for ajax
  46. */
  47. function reply($result, $data, $message = '', $extra = array()) {
  48. return json_encode(array('result' => $result,
  49. 'data' => $data,
  50. 'message' => $message,
  51. 'extra' => $extra,
  52. 'errors' => $this->errors
  53. ));
  54. }
  55. static function makeReply($reply) {
  56. print $reply;
  57. }
  58. //
  59. // Error handlers
  60. //
  61. static function generalError($error) {
  62. self::renderGlobalError(Message::ERROR, Message::GENERAL_ERROR, $error);
  63. }
  64. static function protectionError($error) {
  65. self::renderGlobalError(Message::ERROR, Message::PROTECTION_ERROR, $error);
  66. }
  67. static function systemError($error) {
  68. self::renderGlobalError(Message::ERROR, Message::SYSTEM_ERROR, $error);
  69. }
  70. static function renderGlobalError($type, $message, $error) {
  71. /*$trace = $error->getTrace();
  72. AjaxHandler::makeReply(
  73. AjaxHandler::getInstance()->reply(false, $type, $message . ': ' . $error->getMessage(), $trace[0]['file'] . ' / ' . $trace[0]['line'])
  74. );*/
  75. print $message;
  76. }
  77. }