json.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * Copyright (c) 2011 Bart Visscher <bartv@thisnet.nl>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. class OC_JSON{
  9. static protected $send_content_type_header = false;
  10. /**
  11. * set Content-Type header to jsonrequest
  12. */
  13. public static function setContentTypeHeader($type='application/json'){
  14. if (!self::$send_content_type_header){
  15. // We send json data
  16. header( 'Content-Type: '.$type );
  17. self::$send_content_type_header = true;
  18. }
  19. }
  20. /**
  21. * Check if the app is enabled, send json error msg if not
  22. */
  23. public static function checkAppEnabled($app){
  24. if( !OC_App::isEnabled($app)){
  25. $l = new OC_L10N('core');
  26. self::error(array( 'data' => array( 'message' => $l->t('Application is not enabled') )));
  27. exit();
  28. }
  29. }
  30. /**
  31. * Check if the user is logged in, send json error msg if not
  32. */
  33. public static function checkLoggedIn(){
  34. if( !OC_User::isLoggedIn()){
  35. $l = new OC_L10N('core');
  36. self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
  37. exit();
  38. }
  39. }
  40. /**
  41. * Check if the user is a admin, send json error msg if not
  42. */
  43. public static function checkAdminUser(){
  44. self::checkLoggedIn();
  45. if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){
  46. $l = new OC_L10N('core');
  47. self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
  48. exit();
  49. }
  50. }
  51. /**
  52. * Send json error msg
  53. */
  54. public static function error($data = array()){
  55. $data['status'] = 'error';
  56. self::encodedPrint($data);
  57. }
  58. /**
  59. * Send json success msg
  60. */
  61. public static function success($data = array()){
  62. $data['status'] = 'success';
  63. self::encodedPrint($data);
  64. }
  65. /**
  66. * Encode and print $data in json format
  67. */
  68. public static function encodedPrint($data,$setContentType=true){
  69. if($setContentType){
  70. self::setContentTypeHeader();
  71. }
  72. echo json_encode($data);
  73. }
  74. }