MediaWiki  master
ApiComparePages.php
Go to the documentation of this file.
1 <?php
22 class ApiComparePages extends ApiBase {
23 
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  // Diffs can be really big and there's little point in having
171  // ApiResult truncate it to an empty response since the diff is the
172  // whole reason this module exists. So pass NO_SIZE_CHECK here.
173  $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult::NO_SIZE_CHECK );
174  }
175 
187  private function guessTitleAndModel() {
188  if ( $this->guessed ) {
189  return;
190  }
191 
192  $this->guessed = true;
193  $params = $this->extractRequestParams();
194 
195  foreach ( [ 'from', 'to' ] as $prefix ) {
196  if ( $params["{$prefix}rev"] !== null ) {
197  $revId = $params["{$prefix}rev"];
198  $rev = Revision::newFromId( $revId );
199  if ( !$rev ) {
200  // Titles of deleted revisions aren't secret, per T51088
201  $arQuery = Revision::getArchiveQueryInfo();
202  $row = $this->getDB()->selectRow(
203  $arQuery['tables'],
204  array_merge(
205  $arQuery['fields'],
206  [ 'ar_namespace', 'ar_title' ]
207  ),
208  [ 'ar_rev_id' => $revId ],
209  __METHOD__,
210  [],
211  $arQuery['joins']
212  );
213  if ( $row ) {
215  }
216  }
217  if ( $rev ) {
218  $this->guessedTitle = $rev->getTitle();
219  $this->guessedModel = $rev->getContentModel();
220  break;
221  }
222  }
223 
224  if ( $params["{$prefix}title"] !== null ) {
225  $title = Title::newFromText( $params["{$prefix}title"] );
226  if ( $title && !$title->isExternal() ) {
227  $this->guessedTitle = $title;
228  break;
229  }
230  }
231 
232  if ( $params["{$prefix}id"] !== null ) {
233  $title = Title::newFromID( $params["{$prefix}id"] );
234  if ( $title ) {
235  $this->guessedTitle = $title;
236  break;
237  }
238  }
239  }
240 
241  if ( !$this->guessedModel ) {
242  if ( $this->guessedTitle ) {
243  $this->guessedModel = $this->guessedTitle->getContentModel();
244  } elseif ( $params['fromcontentmodel'] !== null ) {
245  $this->guessedModel = $params['fromcontentmodel'];
246  } elseif ( $params['tocontentmodel'] !== null ) {
247  $this->guessedModel = $params['tocontentmodel'];
248  }
249  }
250  }
251 
269  private function getDiffContent( $prefix, array $params ) {
270  $title = null;
271  $rev = null;
272  $suppliedContent = $params["{$prefix}text"] !== null;
273 
274  // Get the revision and title, if applicable
275  $revId = null;
276  if ( $params["{$prefix}rev"] !== null ) {
277  $revId = $params["{$prefix}rev"];
278  } elseif ( $params["{$prefix}title"] !== null || $params["{$prefix}id"] !== null ) {
279  if ( $params["{$prefix}title"] !== null ) {
280  $title = Title::newFromText( $params["{$prefix}title"] );
281  if ( !$title || $title->isExternal() ) {
282  $this->dieWithError(
283  [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
284  );
285  }
286  } else {
287  $title = Title::newFromID( $params["{$prefix}id"] );
288  if ( !$title ) {
289  $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
290  }
291  }
292  $revId = $title->getLatestRevID();
293  if ( !$revId ) {
294  $revId = null;
295  // Only die here if we're not using supplied text
296  if ( !$suppliedContent ) {
297  if ( $title->exists() ) {
298  $this->dieWithError(
299  [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
300  );
301  } else {
302  $this->dieWithError(
303  [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
304  'missingtitle'
305  );
306  }
307  }
308  }
309  }
310  if ( $revId !== null ) {
311  $rev = Revision::newFromId( $revId );
312  if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
313  // Try the 'archive' table
314  $arQuery = Revision::getArchiveQueryInfo();
315  $row = $this->getDB()->selectRow(
316  $arQuery['tables'],
317  array_merge(
318  $arQuery['fields'],
319  [ 'ar_namespace', 'ar_title' ]
320  ),
321  [ 'ar_rev_id' => $revId ],
322  __METHOD__,
323  [],
324  $arQuery['joins']
325  );
326  if ( $row ) {
328  $rev->isArchive = true;
329  }
330  }
331  if ( !$rev ) {
332  $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
333  }
334  $title = $rev->getTitle();
335 
336  // If we don't have supplied content, return here. Otherwise,
337  // continue on below with the supplied content.
338  if ( !$suppliedContent ) {
339  $content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
340  if ( !$content ) {
341  $this->dieWithError( [ 'apierror-missingcontent-revid', $revId ], 'missingcontent' );
342  }
343  return [ $rev, $content, $rev ];
344  }
345  }
346 
347  // Override $content based on supplied text
348  $model = $params["{$prefix}contentmodel"];
349  $format = $params["{$prefix}contentformat"];
350 
351  if ( !$model && $rev ) {
352  $model = $rev->getContentModel();
353  }
354  if ( !$model && $title ) {
355  $model = $title->getContentModel();
356  }
357  if ( !$model ) {
358  $this->guessTitleAndModel();
359  $model = $this->guessedModel;
360  }
361  if ( !$model ) {
362  $model = CONTENT_MODEL_WIKITEXT;
363  $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
364  }
365 
366  if ( !$title ) {
367  $this->guessTitleAndModel();
369  }
370 
371  try {
372  $content = ContentHandler::makeContent( $params["{$prefix}text"], $title, $model, $format );
373  } catch ( MWContentSerializationException $ex ) {
374  $this->dieWithException( $ex, [
375  'wrap' => ApiMessage::create( 'apierror-contentserializationexception', 'parseerror' )
376  ] );
377  }
378 
379  if ( $params["{$prefix}pst"] ) {
380  if ( !$title ) {
381  $this->dieWithError( 'apierror-compare-no-title' );
382  }
383  $popts = ParserOptions::newFromContext( $this->getContext() );
384  $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
385  }
386 
387  return [ null, $content, $rev ];
388  }
389 
396  private function setVals( &$vals, $prefix, $rev ) {
397  if ( $rev ) {
398  $title = $rev->getTitle();
399  if ( isset( $this->props['ids'] ) ) {
400  $vals["{$prefix}id"] = $title->getArticleID();
401  $vals["{$prefix}revid"] = $rev->getId();
402  }
403  if ( isset( $this->props['title'] ) ) {
404  ApiQueryBase::addTitleInfo( $vals, $title, $prefix );
405  }
406  if ( isset( $this->props['size'] ) ) {
407  $vals["{$prefix}size"] = $rev->getSize();
408  }
409 
410  $anyHidden = false;
411  if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
412  $vals["{$prefix}texthidden"] = true;
413  $anyHidden = true;
414  }
415 
416  if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
417  $vals["{$prefix}userhidden"] = true;
418  $anyHidden = true;
419  }
420  if ( isset( $this->props['user'] ) &&
421  $rev->userCan( Revision::DELETED_USER, $this->getUser() )
422  ) {
423  $vals["{$prefix}user"] = $rev->getUserText( Revision::RAW );
424  $vals["{$prefix}userid"] = $rev->getUser( Revision::RAW );
425  }
426 
427  if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
428  $vals["{$prefix}commenthidden"] = true;
429  $anyHidden = true;
430  }
431  if ( $rev->userCan( Revision::DELETED_COMMENT, $this->getUser() ) ) {
432  if ( isset( $this->props['comment'] ) ) {
433  $vals["{$prefix}comment"] = $rev->getComment( Revision::RAW );
434  }
435  if ( isset( $this->props['parsedcomment'] ) ) {
436  $vals["{$prefix}parsedcomment"] = Linker::formatComment(
437  $rev->getComment( Revision::RAW ),
438  $rev->getTitle()
439  );
440  }
441  }
442 
443  if ( $anyHidden ) {
444  $this->getMain()->setCacheMode( 'private' );
445  if ( $rev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
446  $vals["{$prefix}suppressed"] = true;
447  }
448  }
449 
450  if ( !empty( $rev->isArchive ) ) {
451  $this->getMain()->setCacheMode( 'private' );
452  $vals["{$prefix}archive"] = true;
453  }
454  }
455  }
456 
457  public function getAllowedParams() {
458  // Parameters for the 'from' and 'to' content
459  $fromToParams = [
460  'title' => null,
461  'id' => [
462  ApiBase::PARAM_TYPE => 'integer'
463  ],
464  'rev' => [
465  ApiBase::PARAM_TYPE => 'integer'
466  ],
467  'text' => [
468  ApiBase::PARAM_TYPE => 'text'
469  ],
470  'section' => null,
471  'pst' => false,
472  'contentformat' => [
474  ],
475  'contentmodel' => [
477  ]
478  ];
479 
480  $ret = [];
481  foreach ( $fromToParams as $k => $v ) {
482  $ret["from$k"] = $v;
483  }
484  foreach ( $fromToParams as $k => $v ) {
485  $ret["to$k"] = $v;
486  }
487 
489  $ret,
490  [ 'torelative' => [ ApiBase::PARAM_TYPE => [ 'prev', 'next', 'cur' ], ] ],
491  'torev'
492  );
493 
494  $ret['prop'] = [
495  ApiBase::PARAM_DFLT => 'diff|ids|title',
497  'diff',
498  'diffsize',
499  'rel',
500  'ids',
501  'title',
502  'user',
503  'comment',
504  'parsedcomment',
505  'size',
506  ],
507  ApiBase::PARAM_ISMULTI => true,
509  ];
510 
511  return $ret;
512  }
513 
514  protected function getExamplesMessages() {
515  return [
516  'action=compare&fromrev=1&torev=2'
517  => 'apihelp-compare-example-1',
518  ];
519  }
520 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
const FOR_THIS_USER
Definition: Revision.php:56
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:87
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource 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
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
static newFromArchiveRow( $row, $overrides=[])
Make a fake revision object from an archive table row.
Definition: Revision.php:167
getResult()
Get the result object.
Definition: ApiBase.php:659
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:235
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:420
static getAllContentFormats()
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:2041
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:48
getMain()
Get the main module.
Definition: ApiBase.php:555
static getContentModels()
getDB()
Gets a default replica DB connection object.
Definition: ApiBase.php:687
An IContextSource implementation which will inherit context from another source but allow individual ...
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1972
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:770
dieWithException( $exception, array $options=[])
Abort execution with an error derived from an exception.
Definition: ApiBase.php:1984
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
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
Definition: ApiResult.php:478
IContextSource $context
setVals(&$vals, $prefix, $rev)
Set value fields from a Revision object.
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:2041
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:1088
requireAtLeastOneParameter( $params, $required)
Die if none of a certain set of parameters is set and not false.
Definition: ApiBase.php:967
getContext()
Get the base IContextSource object.
$params
const DELETED_RESTRICTED
Definition: Revision.php:50
static getArchiveQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new archived revision objec...
Definition: Revision.php:506
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don&#39;t use this unless yo...
Definition: ApiResult.php:58
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:949
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:539
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:1813
const RAW
Definition: Revision.php:57
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
const DELETED_TEXT
Definition: Revision.php:47
wfArrayInsertAfter(array $array, array $insert, $after)
Insert array into another array after the specified KEY
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
const DELETED_USER
Definition: Revision.php:49
getDiffContent( $prefix, array $params)
Get the Revision and Content for one side of the diff.
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1896
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:51
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:37
const DELETED_COMMENT
Definition: Revision.php:48
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:114
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
$content
Definition: pageupdater.txt:72
guessTitleAndModel()
Guess an appropriate default Title and content model for this request.
Exception representing a failure to serialize or unserialize a content object.
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:273