Merge "[MCR] fix RevisionStore::checkDatabaseWikiId for DB names with dashes."
[lhc/web/wiklou.git] / includes / api / ApiComparePages.php
1 <?php
2 /**
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
18 *
19 * @file
20 */
21
22 class ApiComparePages extends ApiBase {
23
24 private $guessed = false, $guessedTitle, $guessedModel, $props;
25
26 public function execute() {
27 $params = $this->extractRequestParams();
28
29 // Parameter validation
30 $this->requireAtLeastOneParameter( $params, 'fromtitle', 'fromid', 'fromrev', 'fromtext' );
31 $this->requireAtLeastOneParameter( $params, 'totitle', 'toid', 'torev', 'totext', 'torelative' );
32
33 $this->props = array_flip( $params['prop'] );
34
35 // Cache responses publicly by default. This may be overridden later.
36 $this->getMain()->setCacheMode( 'public' );
37
38 // Get the 'from' Revision and Content
39 list( $fromRev, $fromContent, $relRev ) = $this->getDiffContent( 'from', $params );
40
41 // Get the 'to' Revision and Content
42 if ( $params['torelative'] !== null ) {
43 if ( !$relRev ) {
44 $this->dieWithError( 'apierror-compare-relative-to-nothing' );
45 }
46 switch ( $params['torelative'] ) {
47 case 'prev':
48 // Swap 'from' and 'to'
49 $toRev = $fromRev;
50 $toContent = $fromContent;
51 $fromRev = $relRev->getPrevious();
52 $fromContent = $fromRev
53 ? $fromRev->getContent( Revision::FOR_THIS_USER, $this->getUser() )
54 : $toContent->getContentHandler()->makeEmptyContent();
55 if ( !$fromContent ) {
56 $this->dieWithError(
57 [ 'apierror-missingcontent-revid', $fromRev->getId() ], 'missingcontent'
58 );
59 }
60 break;
61
62 case 'next':
63 $toRev = $relRev->getNext();
64 $toContent = $toRev
65 ? $toRev->getContent( Revision::FOR_THIS_USER, $this->getUser() )
66 : $fromContent;
67 if ( !$toContent ) {
68 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
69 }
70 break;
71
72 case 'cur':
73 $title = $relRev->getTitle();
74 $id = $title->getLatestRevID();
75 $toRev = $id ? Revision::newFromId( $id ) : null;
76 if ( !$toRev ) {
77 $this->dieWithError(
78 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
79 );
80 }
81 $toContent = $toRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
82 if ( !$toContent ) {
83 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
84 }
85 break;
86 }
87 $relRev2 = null;
88 } else {
89 list( $toRev, $toContent, $relRev2 ) = $this->getDiffContent( 'to', $params );
90 }
91
92 // Should never happen, but just in case...
93 if ( !$fromContent || !$toContent ) {
94 $this->dieWithError( 'apierror-baddiff' );
95 }
96
97 // Extract sections, if told to
98 if ( isset( $params['fromsection'] ) ) {
99 $fromContent = $fromContent->getSection( $params['fromsection'] );
100 if ( !$fromContent ) {
101 $this->dieWithError(
102 [ 'apierror-compare-nosuchfromsection', wfEscapeWikiText( $params['fromsection'] ) ],
103 'nosuchfromsection'
104 );
105 }
106 }
107 if ( isset( $params['tosection'] ) ) {
108 $toContent = $toContent->getSection( $params['tosection'] );
109 if ( !$toContent ) {
110 $this->dieWithError(
111 [ 'apierror-compare-nosuchtosection', wfEscapeWikiText( $params['tosection'] ) ],
112 'nosuchtosection'
113 );
114 }
115 }
116
117 // Get the diff
118 $context = new DerivativeContext( $this->getContext() );
119 if ( $relRev && $relRev->getTitle() ) {
120 $context->setTitle( $relRev->getTitle() );
121 } elseif ( $relRev2 && $relRev2->getTitle() ) {
122 $context->setTitle( $relRev2->getTitle() );
123 } else {
124 $this->guessTitleAndModel();
125 if ( $this->guessedTitle ) {
126 $context->setTitle( $this->guessedTitle );
127 }
128 }
129 $de = $fromContent->getContentHandler()->createDifferenceEngine(
130 $context,
131 $fromRev ? $fromRev->getId() : 0,
132 $toRev ? $toRev->getId() : 0,
133 /* $rcid = */ null,
134 /* $refreshCache = */ false,
135 /* $unhide = */ true
136 );
137 $de->setContent( $fromContent, $toContent );
138 $difftext = $de->getDiffBody();
139 if ( $difftext === false ) {
140 $this->dieWithError( 'apierror-baddiff' );
141 }
142
143 // Fill in the response
144 $vals = [];
145 $this->setVals( $vals, 'from', $fromRev );
146 $this->setVals( $vals, 'to', $toRev );
147
148 if ( isset( $this->props['rel'] ) ) {
149 if ( $fromRev ) {
150 $rev = $fromRev->getPrevious();
151 if ( $rev ) {
152 $vals['prev'] = $rev->getId();
153 }
154 }
155 if ( $toRev ) {
156 $rev = $toRev->getNext();
157 if ( $rev ) {
158 $vals['next'] = $rev->getId();
159 }
160 }
161 }
162
163 if ( isset( $this->props['diffsize'] ) ) {
164 $vals['diffsize'] = strlen( $difftext );
165 }
166 if ( isset( $this->props['diff'] ) ) {
167 ApiResult::setContentValue( $vals, 'body', $difftext );
168 }
169
170 $this->getResult()->addValue( null, $this->getModuleName(), $vals );
171 }
172
173 /**
174 * Guess an appropriate default Title and content model for this request
175 *
176 * Fills in $this->guessedTitle based on the first of 'fromrev',
177 * 'fromtitle', 'fromid', 'torev', 'totitle', and 'toid' that's present and
178 * valid.
179 *
180 * Fills in $this->guessedModel based on the Revision or Title used to
181 * determine $this->guessedTitle, or the 'fromcontentmodel' or
182 * 'tocontentmodel' parameters if no title was guessed.
183 */
184 private function guessTitleAndModel() {
185 if ( $this->guessed ) {
186 return;
187 }
188
189 $this->guessed = true;
190 $params = $this->extractRequestParams();
191
192 foreach ( [ 'from', 'to' ] as $prefix ) {
193 if ( $params["{$prefix}rev"] !== null ) {
194 $revId = $params["{$prefix}rev"];
195 $rev = Revision::newFromId( $revId );
196 if ( !$rev ) {
197 // Titles of deleted revisions aren't secret, per T51088
198 $arQuery = Revision::getArchiveQueryInfo();
199 $row = $this->getDB()->selectRow(
200 $arQuery['tables'],
201 array_merge(
202 $arQuery['fields'],
203 [ 'ar_namespace', 'ar_title' ]
204 ),
205 [ 'ar_rev_id' => $revId ],
206 __METHOD__,
207 [],
208 $arQuery['joins']
209 );
210 if ( $row ) {
211 $rev = Revision::newFromArchiveRow( $row );
212 }
213 }
214 if ( $rev ) {
215 $this->guessedTitle = $rev->getTitle();
216 $this->guessedModel = $rev->getContentModel();
217 break;
218 }
219 }
220
221 if ( $params["{$prefix}title"] !== null ) {
222 $title = Title::newFromText( $params["{$prefix}title"] );
223 if ( $title && !$title->isExternal() ) {
224 $this->guessedTitle = $title;
225 break;
226 }
227 }
228
229 if ( $params["{$prefix}id"] !== null ) {
230 $title = Title::newFromID( $params["{$prefix}id"] );
231 if ( $title ) {
232 $this->guessedTitle = $title;
233 break;
234 }
235 }
236 }
237
238 if ( !$this->guessedModel ) {
239 if ( $this->guessedTitle ) {
240 $this->guessedModel = $this->guessedTitle->getContentModel();
241 } elseif ( $params['fromcontentmodel'] !== null ) {
242 $this->guessedModel = $params['fromcontentmodel'];
243 } elseif ( $params['tocontentmodel'] !== null ) {
244 $this->guessedModel = $params['tocontentmodel'];
245 }
246 }
247 }
248
249 /**
250 * Get the Revision and Content for one side of the diff
251 *
252 * This uses the appropriate set of 'rev', 'id', 'title', 'text', 'pst',
253 * 'contentmodel', and 'contentformat' parameters to determine what content
254 * should be diffed.
255 *
256 * Returns three values:
257 * - The revision used to retrieve the content, if any
258 * - The content to be diffed
259 * - The revision specified, if any, even if not used to retrieve the
260 * Content
261 *
262 * @param string $prefix 'from' or 'to'
263 * @param array $params
264 * @return array [ Revision|null, Content, Revision|null ]
265 */
266 private function getDiffContent( $prefix, array $params ) {
267 $title = null;
268 $rev = null;
269 $suppliedContent = $params["{$prefix}text"] !== null;
270
271 // Get the revision and title, if applicable
272 $revId = null;
273 if ( $params["{$prefix}rev"] !== null ) {
274 $revId = $params["{$prefix}rev"];
275 } elseif ( $params["{$prefix}title"] !== null || $params["{$prefix}id"] !== null ) {
276 if ( $params["{$prefix}title"] !== null ) {
277 $title = Title::newFromText( $params["{$prefix}title"] );
278 if ( !$title || $title->isExternal() ) {
279 $this->dieWithError(
280 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
281 );
282 }
283 } else {
284 $title = Title::newFromID( $params["{$prefix}id"] );
285 if ( !$title ) {
286 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
287 }
288 }
289 $revId = $title->getLatestRevID();
290 if ( !$revId ) {
291 $revId = null;
292 // Only die here if we're not using supplied text
293 if ( !$suppliedContent ) {
294 if ( $title->exists() ) {
295 $this->dieWithError(
296 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
297 );
298 } else {
299 $this->dieWithError(
300 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
301 'missingtitle'
302 );
303 }
304 }
305 }
306 }
307 if ( $revId !== null ) {
308 $rev = Revision::newFromId( $revId );
309 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
310 // Try the 'archive' table
311 $arQuery = Revision::getArchiveQueryInfo();
312 $row = $this->getDB()->selectRow(
313 $arQuery['tables'],
314 array_merge(
315 $arQuery['fields'],
316 [ 'ar_namespace', 'ar_title' ]
317 ),
318 [ 'ar_rev_id' => $revId ],
319 __METHOD__,
320 [],
321 $arQuery['joins']
322 );
323 if ( $row ) {
324 $rev = Revision::newFromArchiveRow( $row );
325 $rev->isArchive = true;
326 }
327 }
328 if ( !$rev ) {
329 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
330 }
331 $title = $rev->getTitle();
332
333 // If we don't have supplied content, return here. Otherwise,
334 // continue on below with the supplied content.
335 if ( !$suppliedContent ) {
336 $content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
337 if ( !$content ) {
338 $this->dieWithError( [ 'apierror-missingcontent-revid', $revId ], 'missingcontent' );
339 }
340 return [ $rev, $content, $rev ];
341 }
342 }
343
344 // Override $content based on supplied text
345 $model = $params["{$prefix}contentmodel"];
346 $format = $params["{$prefix}contentformat"];
347
348 if ( !$model && $rev ) {
349 $model = $rev->getContentModel();
350 }
351 if ( !$model && $title ) {
352 $model = $title->getContentModel();
353 }
354 if ( !$model ) {
355 $this->guessTitleAndModel();
356 $model = $this->guessedModel;
357 }
358 if ( !$model ) {
359 $model = CONTENT_MODEL_WIKITEXT;
360 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
361 }
362
363 if ( !$title ) {
364 $this->guessTitleAndModel();
365 $title = $this->guessedTitle;
366 }
367
368 try {
369 $content = ContentHandler::makeContent( $params["{$prefix}text"], $title, $model, $format );
370 } catch ( MWContentSerializationException $ex ) {
371 $this->dieWithException( $ex, [
372 'wrap' => ApiMessage::create( 'apierror-contentserializationexception', 'parseerror' )
373 ] );
374 }
375
376 if ( $params["{$prefix}pst"] ) {
377 if ( !$title ) {
378 $this->dieWithError( 'apierror-compare-no-title' );
379 }
380 $popts = ParserOptions::newFromContext( $this->getContext() );
381 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
382 }
383
384 return [ null, $content, $rev ];
385 }
386
387 /**
388 * Set value fields from a Revision object
389 * @param array &$vals Result array to set data into
390 * @param string $prefix 'from' or 'to'
391 * @param Revision|null $rev
392 */
393 private function setVals( &$vals, $prefix, $rev ) {
394 if ( $rev ) {
395 $title = $rev->getTitle();
396 if ( isset( $this->props['ids'] ) ) {
397 $vals["{$prefix}id"] = $title->getArticleId();
398 $vals["{$prefix}revid"] = $rev->getId();
399 }
400 if ( isset( $this->props['title'] ) ) {
401 ApiQueryBase::addTitleInfo( $vals, $title, $prefix );
402 }
403 if ( isset( $this->props['size'] ) ) {
404 $vals["{$prefix}size"] = $rev->getSize();
405 }
406
407 $anyHidden = false;
408 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
409 $vals["{$prefix}texthidden"] = true;
410 $anyHidden = true;
411 }
412
413 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
414 $vals["{$prefix}userhidden"] = true;
415 $anyHidden = true;
416 }
417 if ( isset( $this->props['user'] ) &&
418 $rev->userCan( Revision::DELETED_USER, $this->getUser() )
419 ) {
420 $vals["{$prefix}user"] = $rev->getUserText( Revision::RAW );
421 $vals["{$prefix}userid"] = $rev->getUser( Revision::RAW );
422 }
423
424 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
425 $vals["{$prefix}commenthidden"] = true;
426 $anyHidden = true;
427 }
428 if ( $rev->userCan( Revision::DELETED_COMMENT, $this->getUser() ) ) {
429 if ( isset( $this->props['comment'] ) ) {
430 $vals["{$prefix}comment"] = $rev->getComment( Revision::RAW );
431 }
432 if ( isset( $this->props['parsedcomment'] ) ) {
433 $vals["{$prefix}parsedcomment"] = Linker::formatComment(
434 $rev->getComment( Revision::RAW ),
435 $rev->getTitle()
436 );
437 }
438 }
439
440 if ( $anyHidden ) {
441 $this->getMain()->setCacheMode( 'private' );
442 if ( $rev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
443 $vals["{$prefix}suppressed"] = true;
444 }
445 }
446
447 if ( !empty( $rev->isArchive ) ) {
448 $this->getMain()->setCacheMode( 'private' );
449 $vals["{$prefix}archive"] = true;
450 }
451 }
452 }
453
454 public function getAllowedParams() {
455 // Parameters for the 'from' and 'to' content
456 $fromToParams = [
457 'title' => null,
458 'id' => [
459 ApiBase::PARAM_TYPE => 'integer'
460 ],
461 'rev' => [
462 ApiBase::PARAM_TYPE => 'integer'
463 ],
464 'text' => [
465 ApiBase::PARAM_TYPE => 'text'
466 ],
467 'section' => null,
468 'pst' => false,
469 'contentformat' => [
470 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
471 ],
472 'contentmodel' => [
473 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
474 ]
475 ];
476
477 $ret = [];
478 foreach ( $fromToParams as $k => $v ) {
479 $ret["from$k"] = $v;
480 }
481 foreach ( $fromToParams as $k => $v ) {
482 $ret["to$k"] = $v;
483 }
484
485 $ret = wfArrayInsertAfter(
486 $ret,
487 [ 'torelative' => [ ApiBase::PARAM_TYPE => [ 'prev', 'next', 'cur' ], ] ],
488 'torev'
489 );
490
491 $ret['prop'] = [
492 ApiBase::PARAM_DFLT => 'diff|ids|title',
493 ApiBase::PARAM_TYPE => [
494 'diff',
495 'diffsize',
496 'rel',
497 'ids',
498 'title',
499 'user',
500 'comment',
501 'parsedcomment',
502 'size',
503 ],
504 ApiBase::PARAM_ISMULTI => true,
505 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
506 ];
507
508 return $ret;
509 }
510
511 protected function getExamplesMessages() {
512 return [
513 'action=compare&fromrev=1&torev=2'
514 => 'apihelp-compare-example-1',
515 ];
516 }
517 }