json.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 = OC_L10N::get('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 = OC_L10N::get('core');
  36. self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
  37. exit();
  38. }
  39. }
  40. /**
  41. * @brief Check an ajax get/post call if the request token is valid.
  42. * @return json Error msg if not valid.
  43. */
  44. public static function callCheck(){
  45. if( !OC_Util::isCallRegistered()){
  46. $l = OC_L10N::get('core');
  47. self::error(array( 'data' => array( 'message' => $l->t('Token expired. Please reload page.') )));
  48. exit();
  49. }
  50. }
  51. /**
  52. * Check if the user is a admin, send json error msg if not
  53. */
  54. public static function checkAdminUser(){
  55. self::checkLoggedIn();
  56. if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){
  57. $l = OC_L10N::get('core');
  58. self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
  59. exit();
  60. }
  61. }
  62. /**
  63. * Send json error msg
  64. */
  65. public static function error($data = array()){
  66. $data['status'] = 'error';
  67. self::encodedPrint($data);
  68. }
  69. /**
  70. * Send json success msg
  71. */
  72. public static function success($data = array()){
  73. $data['status'] = 'success';
  74. self::encodedPrint($data);
  75. }
  76. /**
  77. * Encode and print $data in json format
  78. */
  79. public static function encodedPrint($data,$setContentType=true){
  80. if(!isset($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '') {
  81. if($setContentType){
  82. self::setContentTypeHeader();
  83. }
  84. echo json_encode($data);
  85. }
  86. }
  87. }