Action.class.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. /**
  3. * Execute an action (request which no need html view response: ajax,json etc...) and manage automatically
  4. * access rights, exceptions and json response.
  5. *
  6. * @author valentin carruesco
  7. *
  8. * @category Core
  9. *
  10. * @license cc by nc sa
  11. */
  12. class Action
  13. {
  14. /**
  15. * Execute an action
  16. * #### Example
  17. * ```php
  18. * Action::write(function(&$response){
  19. * $response['custom'] = 'hello world!';
  20. * },array('user'=>'u','plugin'=>'d')); //User must have user update right and delete plugin right to perform this action
  21. * ```.
  22. *
  23. * @param function action/code to execute
  24. * @param array Array wich contain right to execute action
  25. *
  26. * @return print json response
  27. */
  28. public static function write($f, $p = array())
  29. {
  30. global $myUser;
  31. header('content-type:application/json');
  32. $response = array();
  33. set_error_handler(function ($level, $error, $file, $line) { throw new Exception($error." \r\n\r\n ".$file.' - L '.$line.'');});
  34. try {
  35. foreach ($p as $section => $right) {
  36. if (!$myUser->can($section, $right))
  37. throw new Exception('Vous ne disposez pas des droits suffisants pour effectuer cette action');
  38. }
  39. $f($response);
  40. } catch (Exception $e) {
  41. $response['error'] = $e->getMessage();
  42. $response['errorCode'] = $e->getCode();
  43. if($myUser->superadmin) $response['trace'] = $e->getTraceAsString();
  44. }
  45. echo json_encode($response);
  46. restore_error_handler();
  47. }
  48. }