Action.class.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. * @author valentin carruesco
  6. * @category Core
  7. * @license cc by nc sa
  8. */
  9. class Action{
  10. /**
  11. * Execute an action
  12. * #### Example
  13. * ```php
  14. * Action::write(function($_,&$response){
  15. * $response['custom'] = 'hello world!';
  16. * },array('user'=>'u','plugin'=>'d')); //User must have user update right and delete plugin right to perform this action
  17. * ```
  18. * @param function action/code to execute
  19. * @param array Array wich contain right to execute action
  20. * @return print json response
  21. */
  22. public static function write($f,$p=array()){
  23. global $myUser,$_,$conf;
  24. header('content-type:application/json');
  25. $response = array('errors' => array());
  26. set_error_handler(function($level,$error,$file,$line){ throw new Exception($error." \r\n\r\n ".$file." - L ".$line."");});
  27. try{
  28. foreach ($p as $section => $right) {
  29. if(!$myUser->can($section,$right)) throw new Exception('Vous ne disposez pas des droits suffisants pour effectuer cette action');
  30. }
  31. $f($_,$response);
  32. if(!isset($response['errors'])) $response['errors'] = array();
  33. }catch(Exception $e){
  34. $response['errors'][] = $e->getMessage();
  35. }
  36. echo json_encode($response);
  37. restore_error_handler();
  38. }
  39. }
  40. ?>