AjaxHandler.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. public function getLoggedUser()
  24. {
  25. return VestaSession::getInstance()->getUser();
  26. }
  27. /**
  28. * Called functions should reply in the following way
  29. * return $this->reply($result, $data, $msg, $extra);
  30. *
  31. * @param Request $request
  32. * @return string
  33. */
  34. function dispatch($request) {
  35. $method = Request::parseAjaxMethod($request);
  36. $inc_file = V_ROOT_DIR . 'api' . DIRECTORY_SEPARATOR . $method['namespace'] . '.class.php';
  37. if (!is_readable($inc_file)) {
  38. throw new SystemException(Message::INVALID_METHOD);
  39. }
  40. require $inc_file;
  41. $space = new $method['namespace'];
  42. $method = $method['function'] . 'Execute';
  43. if (!method_exists($space, $method)) {
  44. throw new SystemException(Message::INVALID_METHOD);
  45. }
  46. return $space->$method($request);
  47. }
  48. /**
  49. * Prepare response for ajax
  50. */
  51. function reply($result, $data, $message = '', $extra = array()) {
  52. return json_encode(array('result' => $result,
  53. 'data' => $data,
  54. 'message' => $message,
  55. 'extra' => $extra,
  56. 'errors' => $this->errors
  57. ));
  58. }
  59. static function makeReply($reply) {
  60. print $reply;
  61. }
  62. //
  63. // Error handlers
  64. //
  65. static function generalError($error) {
  66. self::renderGlobalError(Message::ERROR, Message::GENERAL_ERROR, $error);
  67. }
  68. static function protectionError($error) {
  69. self::renderGlobalError(Message::ERROR, Message::PROTECTION_ERROR, $error);
  70. }
  71. static function systemError($error) {
  72. self::renderGlobalError(Message::ERROR, Message::SYSTEM_ERROR, $error);
  73. }
  74. static function renderGlobalError($type, $message, $error) {
  75. /*$trace = $error->getTrace();
  76. AjaxHandler::makeReply(
  77. AjaxHandler::getInstance()->reply(false, $type, $message . ': ' . $error->getMessage(), $trace[0]['file'] . ' / ' . $trace[0]['line'])
  78. );*/
  79. print $message;
  80. }
  81. }