Debian Codegraph @

includes/Rest/Handler/UpdateHandler.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Rest\Handler;
4
5 use MediaWiki\Api\IApiMessage;
6 use MediaWiki\Content\TextContent;
7 use MediaWiki\Json\FormatJson;
8 use MediaWiki\ParamValidator\TypeDef\ArrayDef;
9 use MediaWiki\Rest\LocalizedHttpException;
10 use MediaWiki\Revision\RevisionRecord;
11 use MediaWiki\Revision\SlotRecord;
12 use MediaWiki\Utils\MWTimestamp;
13 use Wikimedia\Message\MessageValue;
14 use Wikimedia\ParamValidator\ParamValidator;
15
16 /**
17 * Core REST API endpoint that handles page updates (main slot only)
18 */
19 class UpdateHandler extends EditHandler {
20
21 /**
22 * @var callable
23 */
24 private $jsonDiffFunction;
25
26 /**
27 * @inheritDoc
28 */
29 protected function getTitleParameter() {
30 return $this->getValidatedParams()['title'];
31 }
32
33 /**
34 * Sets the function to use for JSON diffs, for testing.
35 *
36 * @param callable $jsonDiffFunction
37 */
38 public function setJsonDiffFunction( callable $jsonDiffFunction ) {
39 $this->jsonDiffFunction = $jsonDiffFunction;
40 }
41
42 /**
43 * @inheritDoc
44 */
45 public function getParamSettings() {
46 return [
47 'title' => [
48 self::PARAM_SOURCE => 'path',
49 ParamValidator::PARAM_TYPE => 'string',
50 ParamValidator::PARAM_REQUIRED => true,
51 ],
52 ] + parent::getParamSettings();
53 }
54
55 /**
56 * @inheritDoc
57 */
58 public function getBodyParamSettings(): array {
59 return [
60 'source' => [
61 self::PARAM_SOURCE => 'body',
62 ParamValidator::PARAM_TYPE => 'string',
63 ParamValidator::PARAM_REQUIRED => true,
64 ],
65 'comment' => [
66 self::PARAM_SOURCE => 'body',
67 ParamValidator::PARAM_TYPE => 'string',
68 ParamValidator::PARAM_REQUIRED => true,
69 ],
70 'content_model' => [
71 self::PARAM_SOURCE => 'body',
72 ParamValidator::PARAM_TYPE => 'string',
73 ParamValidator::PARAM_REQUIRED => false,
74 ],
75 'latest' => [
76 self::PARAM_SOURCE => 'body',
77 ParamValidator::PARAM_TYPE => 'array',
78 ParamValidator::PARAM_REQUIRED => false,
79 ArrayDef::PARAM_SCHEMA => ArrayDef::makeObjectSchema(
80 [ 'id' => 'integer' ],
81 [ 'timestamp' => 'string' ], // from GET response, will be ignored
82 ),
83 ],
84 ] + $this->getTokenParamDefinition();
85 }
86
87 /**
88 * @inheritDoc
89 */
90 protected function getActionModuleParameters() {
91 $body = $this->getValidatedBody();
92 '@phan-var array $body';
93
94 $title = $this->getTitleParameter();
95 $baseRevId = $body['latest']['id'] ?? 0;
96
97 $contentmodel = $body['content_model'] ?: null;
98
99 if ( $contentmodel !== null && !$this->contentHandlerFactory->isDefinedModel( $contentmodel ) ) {
100 throw new LocalizedHttpException(
101 new MessageValue( 'rest-bad-content-model', [ $contentmodel ] ), 400
102 );
103 }
104
105 // Use a known good CSRF token if a token is not needed because we are
106 // using a method of authentication that protects against CSRF, like OAuth.
107 $token = $this->needsToken() ? $this->getToken() : $this->getUser()->getEditToken();
108
109 $params = [
110 'action' => 'edit',
111 'title' => $title,
112 'text' => $body['source'],
113 'summary' => $body['comment'],
114 'token' => $token
115 ];
116
117 if ( $contentmodel !== null ) {
118 $params['contentmodel'] = $contentmodel;
119 }
120
121 if ( $baseRevId > 0 ) {
122 $params['baserevid'] = $baseRevId;
123 $params['nocreate'] = true;
124 } else {
125 $params['createonly'] = true;
126 }
127
128 return $params;
129 }
130
131 /**
132 * @inheritDoc
133 */
134 protected function mapActionModuleResult( array $data ) {
135 if ( isset( $data['edit']['nochange'] ) ) {
136 // Null-edit, no new revision was created. The new revision is the same as the old.
137 // We may want to signal this more explicitly to the client in the future.
138
139 $title = $this->titleParser->parseTitle( $this->getValidatedParams()['title'] );
140 $currentRev = $this->revisionLookup->getRevisionByTitle( $title );
141
142 $data['edit']['newrevid'] = $currentRev->getId();
143 $data['edit']['newtimestamp']
144 = MWTimestamp::convert( TS_ISO_8601, $currentRev->getTimestamp() );
145 }
146
147 return parent::mapActionModuleResult( $data );
148 }
149
150 /**
151 * @inheritDoc
152 */
153 protected function throwHttpExceptionForActionModuleError( IApiMessage $msg, $statusCode = 400 ) {
154 $code = $msg->getApiCode();
155
156 // Provide a message instructing the client to provide the base revision ID for updates.
157 if ( $code === 'articleexists' ) {
158 $title = $this->getTitleParameter();
159 throw new LocalizedHttpException(
160 new MessageValue( 'rest-update-cannot-create-page', [ $title ] ),
161 409
162 );
163 }
164
165 if ( $code === 'editconflict' ) {
166 $data = $this->getConflictData();
167 throw new LocalizedHttpException( $this->makeMessageValue( $msg ), 409, $data );
168 }
169
170 parent::throwHttpExceptionForActionModuleError( $msg, $statusCode );
171 }
172
173 /**
174 * Returns an associative array to be used in the response in the event of edit conflicts.
175 *
176 * The resulting array contains the following keys:
177 * - base: revision ID of the base revision
178 * - current: revision ID of the current revision (new base after resolving the conflict)
179 * - local: the difference between the content submitted and the base revision
180 * - remote: the difference between the latest revision of the page and the base revision
181 *
182 * If the differences cannot be determined, an empty array is returned.
183 *
184 * @return array
185 */
186 private function getConflictData() {
187 $body = $this->getValidatedBody();
188 '@phan-var array $body';
189 $baseRevId = $body['latest']['id'] ?? 0;
190 $title = $this->titleParser->parseTitle( $this->getValidatedParams()['title'] );
191
192 $baseRev = $this->revisionLookup->getRevisionById( $baseRevId );
193 $currentRev = $this->revisionLookup->getRevisionByTitle( $title );
194
195 if ( !$baseRev || !$currentRev ) {
196 return [];
197 }
198
199 $baseContent = $baseRev->getContent(
200 SlotRecord::MAIN,
201 RevisionRecord::FOR_THIS_USER,
202 $this->getAuthority()
203 );
204 $currentContent = $currentRev->getContent(
205 SlotRecord::MAIN,
206 RevisionRecord::FOR_THIS_USER,
207 $this->getAuthority()
208 );
209
210 if ( !$baseContent || !$currentContent ) {
211 return [];
212 }
213
214 $model = $body['content_model'] ?: $baseContent->getModel();
215 $contentHandler = $this->contentHandlerFactory->getContentHandler( $model );
216 $newContent = $contentHandler->unserializeContent( $body['source'] );
217
218 if ( !$baseContent instanceof TextContent
219 || !$currentContent instanceof TextContent
220 || !$newContent instanceof TextContent
221 ) {
222 return [];
223 }
224
225 $localDiff = $this->getDiff( $baseContent, $newContent );
226 $remoteDiff = $this->getDiff( $baseContent, $currentContent );
227
228 if ( !$localDiff || !$remoteDiff ) {
229 return [];
230 }
231
232 return [
233 'base' => $baseRev->getId(),
234 'current' => $currentRev->getId(),
235 'local' => $localDiff,
236 'remote' => $remoteDiff,
237 ];
238 }
239
240 /**
241 * Returns a text diff encoded as an array, to be included in the response data.
242 *
243 * @param TextContent $from
244 * @param TextContent $to
245 *
246 * @return array|null
247 */
248 private function getDiff( TextContent $from, TextContent $to ) {
249 if ( !is_callable( $this->jsonDiffFunction ) ) {
250 return null;
251 }
252
253 $json = ( $this->jsonDiffFunction )( $from->getText(), $to->getText(), 2 );
254 return FormatJson::decode( $json, true );
255 }
256
257 public function getResponseBodySchemaFileName( string $method ): ?string {
258 return 'includes/Rest/Handler/Schema/ExistingPageSource.json';
259 }
260 }