MediaWiki  master
ApiFormatJson.php
Go to the documentation of this file.
1 <?php
24 
30 
31  private $isRaw;
32 
33  public function __construct( ApiMain $main, $format ) {
34  parent::__construct( $main, $format );
35  $this->isRaw = ( $format === 'rawfm' );
36 
37  if ( $this->getMain()->getCheck( 'callback' ) ) {
38  # T94015: jQuery appends a useless '_' parameter in jsonp mode.
39  # Mark the parameter as used in that case to avoid a warning that's
40  # outside the control of the end user.
41  # (and do it here because ApiMain::reportUnusedParams() gets called
42  # before our ::execute())
43  $this->getMain()->markParamsUsed( '_' );
44  }
45  }
46 
47  public function getMimeType() {
48  $params = $this->extractRequestParams();
49  // callback:
50  if ( isset( $params['callback'] ) ) {
51  return 'text/javascript';
52  }
53 
54  return 'application/json';
55  }
56 
57  public function execute() {
58  $params = $this->extractRequestParams();
59 
60  $opt = 0;
61  if ( $this->isRaw ) {
62  $opt |= FormatJson::ALL_OK;
63  $transform = [];
64  } else {
65  switch ( $params['formatversion'] ) {
66  case 1:
67  $opt |= $params['utf8'] ? FormatJson::ALL_OK : FormatJson::XMLMETA_OK;
68  $transform = [
69  'BC' => [],
70  'Types' => [ 'AssocAsObject' => true ],
71  'Strip' => 'all',
72  ];
73  break;
74 
75  case 2:
76  case 'latest':
77  $opt |= $params['ascii'] ? FormatJson::XMLMETA_OK : FormatJson::ALL_OK;
78  $transform = [
79  'Types' => [ 'AssocAsObject' => true ],
80  'Strip' => 'all',
81  ];
82  break;
83 
84  default:
85  // Should have been caught during parameter validation
86  // @codeCoverageIgnoreStart
87  self::dieDebug( __METHOD__, 'Unknown value for \'formatversion\'' );
88  // @codeCoverageIgnoreEnd
89  }
90  }
91  $data = $this->getResult()->getResultData( null, $transform );
92  $json = FormatJson::encode( $data, $this->getIsHtml(), $opt );
93  if ( $json === false ) {
94  // This should never happen, but it's a bug which could crop up
95  // if you use ApiResult::NO_VALIDATE for instance.
96  // @codeCoverageIgnoreStart
97  self::dieDebug( __METHOD__, 'Unable to encode API result as JSON' );
98  // @codeCoverageIgnoreEnd
99  }
100 
101  if ( isset( $params['callback'] ) ) {
102  $callback = preg_replace( "/[^][.\\'\\\"_A-Za-z0-9]/", '', $params['callback'] );
103  # Prepend a comment to try to avoid attacks against content
104  # sniffers, such as T70187.
105  $this->printText( "/**/$callback($json)" );
106  } else {
107  $this->printText( $json );
108  }
109  }
110 
111  public function getAllowedParams() {
112  if ( $this->isRaw ) {
113  return parent::getAllowedParams();
114  }
115 
116  return parent::getAllowedParams() + [
117  'callback' => [
118  ApiBase::PARAM_HELP_MSG => 'apihelp-json-param-callback',
119  ],
120  'utf8' => [
121  ParamValidator::PARAM_DEFAULT => false,
122  ApiBase::PARAM_HELP_MSG => 'apihelp-json-param-utf8',
123  ],
124  'ascii' => [
125  ParamValidator::PARAM_DEFAULT => false,
126  ApiBase::PARAM_HELP_MSG => 'apihelp-json-param-ascii',
127  ],
128  'formatversion' => [
129  ParamValidator::PARAM_TYPE => [ '1', '2', 'latest' ],
130  ParamValidator::PARAM_DEFAULT => '1',
131  ApiBase::PARAM_HELP_MSG => 'apihelp-json-param-formatversion',
133  '1' => 'apihelp-json-paramvalue-formatversion-1',
134  '2' => 'apihelp-json-paramvalue-formatversion-2',
135  'latest' => 'apihelp-json-paramvalue-formatversion-latest',
136  ],
137  ],
138  ];
139  }
140 }
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1771
getMain()
Get the main module.
Definition: ApiBase.php:547
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition: ApiBase.php:210
getResult()
Get the result object.
Definition: ApiBase.php:668
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:808
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:170
This is the abstract base class for API formatters.
printText( $text)
Append text to the output buffer.
getIsHtml()
Returns true when the HTML pretty-printer should be used.
API JSON output formatter.
getMimeType()
Overriding class returns the MIME type that should be sent to the client.
__construct(ApiMain $main, $format)
If $format ends with 'fm', pretty-print the output in HTML.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:64
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:98
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:57
const XMLMETA_OK
Skip escaping the characters '<', '>', and '&', which have special meanings in HTML and XML.
Definition: FormatJson.php:48
Service for formatting and validating API parameters.
return true
Definition: router.php:90