AjaxHandler.php 2.7 KB

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