MediaWiki REL1_31
ApiComparePages.php
Go to the documentation of this file.
1<?php
22class ApiComparePages extends ApiBase {
23
25
26 public function execute() {
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() ) ],
79 'nosuchrevid'
80 );
81 }
82 $toContent = $toRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
83 if ( !$toContent ) {
84 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
85 }
86 break;
87 }
88 $relRev2 = null;
89 } else {
90 list( $toRev, $toContent, $relRev2 ) = $this->getDiffContent( 'to', $params );
91 }
92
93 // Should never happen, but just in case...
94 if ( !$fromContent || !$toContent ) {
95 $this->dieWithError( 'apierror-baddiff' );
96 }
97
98 // Extract sections, if told to
99 if ( isset( $params['fromsection'] ) ) {
100 $fromContent = $fromContent->getSection( $params['fromsection'] );
101 if ( !$fromContent ) {
102 $this->dieWithError(
103 [ 'apierror-compare-nosuchfromsection', wfEscapeWikiText( $params['fromsection'] ) ],
104 'nosuchfromsection'
105 );
106 }
107 }
108 if ( isset( $params['tosection'] ) ) {
109 $toContent = $toContent->getSection( $params['tosection'] );
110 if ( !$toContent ) {
111 $this->dieWithError(
112 [ 'apierror-compare-nosuchtosection', wfEscapeWikiText( $params['tosection'] ) ],
113 'nosuchtosection'
114 );
115 }
116 }
117
118 // Get the diff
119 $context = new DerivativeContext( $this->getContext() );
120 if ( $relRev && $relRev->getTitle() ) {
121 $context->setTitle( $relRev->getTitle() );
122 } elseif ( $relRev2 && $relRev2->getTitle() ) {
123 $context->setTitle( $relRev2->getTitle() );
124 } else {
125 $this->guessTitleAndModel();
126 if ( $this->guessedTitle ) {
127 $context->setTitle( $this->guessedTitle );
128 }
129 }
130 $de = $fromContent->getContentHandler()->createDifferenceEngine(
131 $context,
132 $fromRev ? $fromRev->getId() : 0,
133 $toRev ? $toRev->getId() : 0,
134 /* $rcid = */ null,
135 /* $refreshCache = */ false,
136 /* $unhide = */ true
137 );
138 $de->setContent( $fromContent, $toContent );
139 $difftext = $de->getDiffBody();
140 if ( $difftext === false ) {
141 $this->dieWithError( 'apierror-baddiff' );
142 }
143
144 // Fill in the response
145 $vals = [];
146 $this->setVals( $vals, 'from', $fromRev );
147 $this->setVals( $vals, 'to', $toRev );
148
149 if ( isset( $this->props['rel'] ) ) {
150 if ( $fromRev ) {
151 $rev = $fromRev->getPrevious();
152 if ( $rev ) {
153 $vals['prev'] = $rev->getId();
154 }
155 }
156 if ( $toRev ) {
157 $rev = $toRev->getNext();
158 if ( $rev ) {
159 $vals['next'] = $rev->getId();
160 }
161 }
162 }
163
164 if ( isset( $this->props['diffsize'] ) ) {
165 $vals['diffsize'] = strlen( $difftext );
166 }
167 if ( isset( $this->props['diff'] ) ) {
168 ApiResult::setContentValue( $vals, 'body', $difftext );
169 }
170
171 // Diffs can be really big and there's little point in having
172 // ApiResult truncate it to an empty response since the diff is the
173 // whole reason this module exists. So pass NO_SIZE_CHECK here.
174 $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult::NO_SIZE_CHECK );
175 }
176
188 private function guessTitleAndModel() {
189 if ( $this->guessed ) {
190 return;
191 }
192
193 $this->guessed = true;
194 $params = $this->extractRequestParams();
195
196 foreach ( [ 'from', 'to' ] as $prefix ) {
197 if ( $params["{$prefix}rev"] !== null ) {
198 $revId = $params["{$prefix}rev"];
199 $rev = Revision::newFromId( $revId );
200 if ( !$rev ) {
201 // Titles of deleted revisions aren't secret, per T51088
202 $arQuery = Revision::getArchiveQueryInfo();
203 $row = $this->getDB()->selectRow(
204 $arQuery['tables'],
205 array_merge(
206 $arQuery['fields'],
207 [ 'ar_namespace', 'ar_title' ]
208 ),
209 [ 'ar_rev_id' => $revId ],
210 __METHOD__,
211 [],
212 $arQuery['joins']
213 );
214 if ( $row ) {
215 $rev = Revision::newFromArchiveRow( $row );
216 }
217 }
218 if ( $rev ) {
219 $this->guessedTitle = $rev->getTitle();
220 $this->guessedModel = $rev->getContentModel();
221 break;
222 }
223 }
224
225 if ( $params["{$prefix}title"] !== null ) {
226 $title = Title::newFromText( $params["{$prefix}title"] );
227 if ( $title && !$title->isExternal() ) {
228 $this->guessedTitle = $title;
229 break;
230 }
231 }
232
233 if ( $params["{$prefix}id"] !== null ) {
234 $title = Title::newFromID( $params["{$prefix}id"] );
235 if ( $title ) {
236 $this->guessedTitle = $title;
237 break;
238 }
239 }
240 }
241
242 if ( !$this->guessedModel ) {
243 if ( $this->guessedTitle ) {
244 $this->guessedModel = $this->guessedTitle->getContentModel();
245 } elseif ( $params['fromcontentmodel'] !== null ) {
246 $this->guessedModel = $params['fromcontentmodel'];
247 } elseif ( $params['tocontentmodel'] !== null ) {
248 $this->guessedModel = $params['tocontentmodel'];
249 }
250 }
251 }
252
270 private function getDiffContent( $prefix, array $params ) {
271 $title = null;
272 $rev = null;
273 $suppliedContent = $params["{$prefix}text"] !== null;
274
275 // Get the revision and title, if applicable
276 $revId = null;
277 if ( $params["{$prefix}rev"] !== null ) {
278 $revId = $params["{$prefix}rev"];
279 } elseif ( $params["{$prefix}title"] !== null || $params["{$prefix}id"] !== null ) {
280 if ( $params["{$prefix}title"] !== null ) {
281 $title = Title::newFromText( $params["{$prefix}title"] );
282 if ( !$title || $title->isExternal() ) {
283 $this->dieWithError(
284 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
285 );
286 }
287 } else {
288 $title = Title::newFromID( $params["{$prefix}id"] );
289 if ( !$title ) {
290 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
291 }
292 }
293 $revId = $title->getLatestRevID();
294 if ( !$revId ) {
295 $revId = null;
296 // Only die here if we're not using supplied text
297 if ( !$suppliedContent ) {
298 if ( $title->exists() ) {
299 $this->dieWithError(
300 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ],
301 'nosuchrevid'
302 );
303 } else {
304 $this->dieWithError(
305 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
306 'missingtitle'
307 );
308 }
309 }
310 }
311 }
312 if ( $revId !== null ) {
313 $rev = Revision::newFromId( $revId );
314 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
315 // Try the 'archive' table
316 $arQuery = Revision::getArchiveQueryInfo();
317 $row = $this->getDB()->selectRow(
318 $arQuery['tables'],
319 array_merge(
320 $arQuery['fields'],
321 [ 'ar_namespace', 'ar_title' ]
322 ),
323 [ 'ar_rev_id' => $revId ],
324 __METHOD__,
325 [],
326 $arQuery['joins']
327 );
328 if ( $row ) {
329 $rev = Revision::newFromArchiveRow( $row );
330 $rev->isArchive = true;
331 }
332 }
333 if ( !$rev ) {
334 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
335 }
336 $title = $rev->getTitle();
337
338 // If we don't have supplied content, return here. Otherwise,
339 // continue on below with the supplied content.
340 if ( !$suppliedContent ) {
341 $content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
342 if ( !$content ) {
343 $this->dieWithError( [ 'apierror-missingcontent-revid', $revId ], 'missingcontent' );
344 }
345 return [ $rev, $content, $rev ];
346 }
347 }
348
349 // Override $content based on supplied text
350 $model = $params["{$prefix}contentmodel"];
351 $format = $params["{$prefix}contentformat"];
352
353 if ( !$model && $rev ) {
354 $model = $rev->getContentModel();
355 }
356 if ( !$model && $title ) {
357 $model = $title->getContentModel();
358 }
359 if ( !$model ) {
360 $this->guessTitleAndModel();
361 $model = $this->guessedModel;
362 }
363 if ( !$model ) {
364 $model = CONTENT_MODEL_WIKITEXT;
365 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
366 }
367
368 if ( !$title ) {
369 $this->guessTitleAndModel();
370 $title = $this->guessedTitle;
371 }
372
373 try {
374 $content = ContentHandler::makeContent( $params["{$prefix}text"], $title, $model, $format );
375 } catch ( MWContentSerializationException $ex ) {
376 $this->dieWithException( $ex, [
377 'wrap' => ApiMessage::create( 'apierror-contentserializationexception', 'parseerror' )
378 ] );
379 }
380
381 if ( $params["{$prefix}pst"] ) {
382 if ( !$title ) {
383 $this->dieWithError( 'apierror-compare-no-title' );
384 }
385 $popts = ParserOptions::newFromContext( $this->getContext() );
386 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
387 }
388
389 return [ null, $content, $rev ];
390 }
391
398 private function setVals( &$vals, $prefix, $rev ) {
399 if ( $rev ) {
400 $title = $rev->getTitle();
401 if ( isset( $this->props['ids'] ) ) {
402 $vals["{$prefix}id"] = $title->getArticleID();
403 $vals["{$prefix}revid"] = $rev->getId();
404 }
405 if ( isset( $this->props['title'] ) ) {
406 ApiQueryBase::addTitleInfo( $vals, $title, $prefix );
407 }
408 if ( isset( $this->props['size'] ) ) {
409 $vals["{$prefix}size"] = $rev->getSize();
410 }
411
412 $anyHidden = false;
413 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
414 $vals["{$prefix}texthidden"] = true;
415 $anyHidden = true;
416 }
417
418 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
419 $vals["{$prefix}userhidden"] = true;
420 $anyHidden = true;
421 }
422 if ( isset( $this->props['user'] ) &&
423 $rev->userCan( Revision::DELETED_USER, $this->getUser() )
424 ) {
425 $vals["{$prefix}user"] = $rev->getUserText( Revision::RAW );
426 $vals["{$prefix}userid"] = $rev->getUser( Revision::RAW );
427 }
428
429 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
430 $vals["{$prefix}commenthidden"] = true;
431 $anyHidden = true;
432 }
433 if ( $rev->userCan( Revision::DELETED_COMMENT, $this->getUser() ) ) {
434 if ( isset( $this->props['comment'] ) ) {
435 $vals["{$prefix}comment"] = $rev->getComment( Revision::RAW );
436 }
437 if ( isset( $this->props['parsedcomment'] ) ) {
438 $vals["{$prefix}parsedcomment"] = Linker::formatComment(
439 $rev->getComment( Revision::RAW ),
440 $rev->getTitle()
441 );
442 }
443 }
444
445 if ( $anyHidden ) {
446 $this->getMain()->setCacheMode( 'private' );
447 if ( $rev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
448 $vals["{$prefix}suppressed"] = true;
449 }
450 }
451
452 if ( !empty( $rev->isArchive ) ) {
453 $this->getMain()->setCacheMode( 'private' );
454 $vals["{$prefix}archive"] = true;
455 }
456 }
457 }
458
459 public function getAllowedParams() {
460 // Parameters for the 'from' and 'to' content
461 $fromToParams = [
462 'title' => null,
463 'id' => [
464 ApiBase::PARAM_TYPE => 'integer'
465 ],
466 'rev' => [
467 ApiBase::PARAM_TYPE => 'integer'
468 ],
469 'text' => [
470 ApiBase::PARAM_TYPE => 'text'
471 ],
472 'section' => null,
473 'pst' => false,
474 'contentformat' => [
475 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
476 ],
477 'contentmodel' => [
478 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
479 ]
480 ];
481
482 $ret = [];
483 foreach ( $fromToParams as $k => $v ) {
484 $ret["from$k"] = $v;
485 }
486 foreach ( $fromToParams as $k => $v ) {
487 $ret["to$k"] = $v;
488 }
489
491 $ret,
492 [ 'torelative' => [ ApiBase::PARAM_TYPE => [ 'prev', 'next', 'cur' ], ] ],
493 'torev'
494 );
495
496 $ret['prop'] = [
497 ApiBase::PARAM_DFLT => 'diff|ids|title',
499 'diff',
500 'diffsize',
501 'rel',
502 'ids',
503 'title',
504 'user',
505 'comment',
506 'parsedcomment',
507 'size',
508 ],
511 ];
512
513 return $ret;
514 }
515
516 protected function getExamplesMessages() {
517 return [
518 'action=compare&fromrev=1&torev=2'
519 => 'apihelp-compare-example-1',
520 ];
521 }
522}
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfArrayInsertAfter(array $array, array $insert, $after)
Insert array into another array after the specified KEY
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:37
getDB()
Gets a default replica DB connection object.
Definition ApiBase.php:669
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition ApiBase.php:1895
getMain()
Get the main module.
Definition ApiBase.php:537
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:87
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:48
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:749
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition ApiBase.php:157
getResult()
Get the result object.
Definition ApiBase.php:641
dieWithException( $exception, array $options=[])
Abort execution with an error derived from an exception.
Definition ApiBase.php:1907
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1819
requireAtLeastOneParameter( $params, $required)
Die if none of a certain set of parameters is set and not false.
Definition ApiBase.php:851
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:521
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:51
guessTitleAndModel()
Guess an appropriate default Title and content model for this request.
getExamplesMessages()
Returns usage examples for this module.
setVals(&$vals, $prefix, $rev)
Set value fields from a Revision object.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getDiffContent( $prefix, array $params)
Get the Revision and Content for one side of the diff.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Definition ApiResult.php:56
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
IContextSource $context
getContext()
Get the base IContextSource object.
An IContextSource implementation which will inherit context from another source but allow individual ...
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition Linker.php:1109
Exception representing a failure to serialize or unserialize a content object.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:964
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2006
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:2005
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition hooks.txt:1777
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:245
$params