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,$_,$conf;
  31. header('content-type:application/json');
  32. $response = array('errors' => 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. }
  40. $f($_, $response);
  41. if (!isset($response['errors'])) {
  42. $response['errors'] = array();
  43. }
  44. } catch (Exception $e) {
  45. $response['errors'][] = $e->getMessage();
  46. }
  47. echo json_encode($response);
  48. restore_error_handler();
  49. }
  50. }