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.
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.
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
22 use MediaWiki\MediaWikiServices
;
23 use MediaWiki\Revision\MutableRevisionRecord
;
24 use MediaWiki\Revision\RevisionRecord
;
25 use MediaWiki\Revision\RevisionArchiveRecord
;
26 use MediaWiki\Revision\RevisionStore
;
27 use MediaWiki\Revision\SlotRecord
;
29 class ApiComparePages
extends ApiBase
{
31 /** @var RevisionStore */
32 private $revisionStore;
34 private $guessedTitle = false, $props;
36 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
37 parent
::__construct( $mainModule, $moduleName, $modulePrefix );
38 $this->revisionStore
= MediaWikiServices
::getInstance()->getRevisionStore();
41 public function execute() {
42 $params = $this->extractRequestParams();
44 // Parameter validation
45 $this->requireAtLeastOneParameter(
46 $params, 'fromtitle', 'fromid', 'fromrev', 'fromtext', 'fromslots'
48 $this->requireAtLeastOneParameter(
49 $params, 'totitle', 'toid', 'torev', 'totext', 'torelative', 'toslots'
52 $this->props
= array_flip( $params['prop'] );
54 // Cache responses publicly by default. This may be overridden later.
55 $this->getMain()->setCacheMode( 'public' );
57 // Get the 'from' RevisionRecord
58 list( $fromRev, $fromRelRev, $fromValsRev ) = $this->getDiffRevision( 'from', $params );
60 // Get the 'to' RevisionRecord
61 if ( $params['torelative'] !== null ) {
63 $this->dieWithError( 'apierror-compare-relative-to-nothing' );
65 if ( $params['torelative'] !== 'cur' && $fromRelRev instanceof RevisionArchiveRecord
) {
66 // RevisionStore's getPreviousRevision/getNextRevision blow up
67 // when passed an RevisionArchiveRecord for a deleted page
68 $this->dieWithError( [ 'apierror-compare-relative-to-deleted', $params['torelative'] ] );
70 switch ( $params['torelative'] ) {
72 // Swap 'from' and 'to'
73 list( $toRev, $toRelRev2, $toValsRev ) = [ $fromRev, $fromRelRev, $fromValsRev ];
74 $fromRev = $this->revisionStore
->getPreviousRevision( $fromRelRev );
75 $fromRelRev = $fromRev;
76 $fromValsRev = $fromRev;
80 $toRev = $this->revisionStore
->getNextRevision( $fromRelRev );
86 $title = $fromRelRev->getPageAsLinkTarget();
87 $toRev = $this->revisionStore
->getRevisionByTitle( $title );
89 $title = Title
::newFromLinkTarget( $title );
91 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
99 list( $toRev, $toRelRev, $toValsRev ) = $this->getDiffRevision( 'to', $params );
102 // Handle missing from or to revisions
103 if ( !$fromRev ||
!$toRev ) {
104 $this->dieWithError( 'apierror-baddiff' );
108 if ( !$fromRev->audienceCan(
109 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
111 $this->dieWithError( [ 'apierror-missingcontent-revid', $fromRev->getId() ], 'missingcontent' );
113 if ( !$toRev->audienceCan(
114 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
116 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
120 $context = new DerivativeContext( $this->getContext() );
121 if ( $fromRelRev && $fromRelRev->getPageAsLinkTarget() ) {
122 $context->setTitle( Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() ) );
123 } elseif ( $toRelRev && $toRelRev->getPageAsLinkTarget() ) {
124 $context->setTitle( Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() ) );
126 $guessedTitle = $this->guessTitle();
127 if ( $guessedTitle ) {
128 $context->setTitle( $guessedTitle );
131 $de = new DifferenceEngine( $context );
132 $de->setRevisions( $fromRev, $toRev );
133 if ( $params['slots'] === null ) {
134 $difftext = $de->getDiffBody();
135 if ( $difftext === false ) {
136 $this->dieWithError( 'apierror-baddiff' );
140 foreach ( $params['slots'] as $role ) {
141 $difftext[$role] = $de->getDiffBodyForRole( $role );
145 // Fill in the response
147 $this->setVals( $vals, 'from', $fromValsRev );
148 $this->setVals( $vals, 'to', $toValsRev );
150 if ( isset( $this->props
['rel'] ) ) {
151 if ( !$fromRev instanceof MutableRevisionRecord
) {
152 $rev = $this->revisionStore
->getPreviousRevision( $fromRev );
154 $vals['prev'] = $rev->getId();
157 if ( !$toRev instanceof MutableRevisionRecord
) {
158 $rev = $this->revisionStore
->getNextRevision( $toRev );
160 $vals['next'] = $rev->getId();
165 if ( isset( $this->props
['diffsize'] ) ) {
166 $vals['diffsize'] = 0;
167 foreach ( (array)$difftext as $text ) {
168 $vals['diffsize'] +
= strlen( $text );
171 if ( isset( $this->props
['diff'] ) ) {
172 if ( is_array( $difftext ) ) {
173 ApiResult
::setArrayType( $difftext, 'kvp', 'diff' );
174 $vals['bodies'] = $difftext;
176 ApiResult
::setContentValue( $vals, 'body', $difftext );
180 // Diffs can be really big and there's little point in having
181 // ApiResult truncate it to an empty response since the diff is the
182 // whole reason this module exists. So pass NO_SIZE_CHECK here.
183 $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult
::NO_SIZE_CHECK
);
187 * Load a revision by ID
189 * Falls back to checking the archive table if appropriate.
192 * @return RevisionRecord|null
194 private function getRevisionById( $id ) {
195 $rev = $this->revisionStore
->getRevisionById( $id );
196 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
197 // Try the 'archive' table
198 $arQuery = $this->revisionStore
->getArchiveQueryInfo();
199 $row = $this->getDB()->selectRow(
203 [ 'ar_namespace', 'ar_title' ]
205 [ 'ar_rev_id' => $id ],
211 $rev = $this->revisionStore
->newRevisionFromArchiveRow( $row );
212 $rev->isArchive
= true;
219 * Guess an appropriate default Title for this request
223 private function guessTitle() {
224 if ( $this->guessedTitle
!== false ) {
225 return $this->guessedTitle
;
228 $this->guessedTitle
= null;
229 $params = $this->extractRequestParams();
231 foreach ( [ 'from', 'to' ] as $prefix ) {
232 if ( $params["{$prefix}rev"] !== null ) {
233 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
235 $this->guessedTitle
= Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
240 if ( $params["{$prefix}title"] !== null ) {
241 $title = Title
::newFromText( $params["{$prefix}title"] );
242 if ( $title && !$title->isExternal() ) {
243 $this->guessedTitle
= $title;
248 if ( $params["{$prefix}id"] !== null ) {
249 $title = Title
::newFromID( $params["{$prefix}id"] );
251 $this->guessedTitle
= $title;
257 return $this->guessedTitle
;
261 * Guess an appropriate default content model for this request
262 * @param string $role Slot for which to guess the model
263 * @return string|null Guessed content model
265 private function guessModel( $role ) {
266 $params = $this->extractRequestParams();
269 foreach ( [ 'from', 'to' ] as $prefix ) {
270 if ( $params["{$prefix}rev"] !== null ) {
271 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
273 if ( $rev->hasSlot( $role ) ) {
274 return $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
280 $guessedTitle = $this->guessTitle();
281 if ( $guessedTitle && $role === SlotRecord
::MAIN
) {
282 // @todo: Use SlotRoleRegistry and do this for all slots
283 return $guessedTitle->getContentModel();
286 if ( isset( $params["fromcontentmodel-$role"] ) ) {
287 return $params["fromcontentmodel-$role"];
289 if ( isset( $params["tocontentmodel-$role"] ) ) {
290 return $params["tocontentmodel-$role"];
293 if ( $role === SlotRecord
::MAIN
) {
294 if ( isset( $params['fromcontentmodel'] ) ) {
295 return $params['fromcontentmodel'];
297 if ( isset( $params['tocontentmodel'] ) ) {
298 return $params['tocontentmodel'];
306 * Get the RevisionRecord for one side of the diff
308 * This uses the appropriate set of parameters to determine what content
311 * Returns three values:
312 * - A RevisionRecord holding the content
313 * - The revision specified, if any, even if content was supplied
314 * - The revision to pass to setVals(), if any
316 * @param string $prefix 'from' or 'to'
317 * @param array $params
318 * @return array [ RevisionRecord|null, RevisionRecord|null, RevisionRecord|null ]
320 private function getDiffRevision( $prefix, array $params ) {
321 // Back compat params
322 $this->requireMaxOneParameter( $params, "{$prefix}text", "{$prefix}slots" );
323 $this->requireMaxOneParameter( $params, "{$prefix}section", "{$prefix}slots" );
324 if ( $params["{$prefix}text"] !== null ) {
325 $params["{$prefix}slots"] = [ SlotRecord
::MAIN
];
326 $params["{$prefix}text-main"] = $params["{$prefix}text"];
327 $params["{$prefix}section-main"] = null;
328 $params["{$prefix}contentmodel-main"] = $params["{$prefix}contentmodel"];
329 $params["{$prefix}contentformat-main"] = $params["{$prefix}contentformat"];
334 $suppliedContent = $params["{$prefix}slots"] !== null;
336 // Get the revision and title, if applicable
338 if ( $params["{$prefix}rev"] !== null ) {
339 $revId = $params["{$prefix}rev"];
340 } elseif ( $params["{$prefix}title"] !== null ||
$params["{$prefix}id"] !== null ) {
341 if ( $params["{$prefix}title"] !== null ) {
342 $title = Title
::newFromText( $params["{$prefix}title"] );
343 if ( !$title ||
$title->isExternal() ) {
345 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
349 $title = Title
::newFromID( $params["{$prefix}id"] );
351 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
354 $revId = $title->getLatestRevID();
357 // Only die here if we're not using supplied text
358 if ( !$suppliedContent ) {
359 if ( $title->exists() ) {
361 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
365 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
372 if ( $revId !== null ) {
373 $rev = $this->getRevisionById( $revId );
375 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
377 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
379 // If we don't have supplied content, return here. Otherwise,
380 // continue on below with the supplied content.
381 if ( !$suppliedContent ) {
384 // Deprecated 'fromsection'/'tosection'
385 if ( isset( $params["{$prefix}section"] ) ) {
386 $section = $params["{$prefix}section"];
387 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
388 $content = $rev->getContent( SlotRecord
::MAIN
, RevisionRecord
::FOR_THIS_USER
,
392 [ 'apierror-missingcontent-revid-role', $rev->getId(), SlotRecord
::MAIN
], 'missingcontent'
395 $content = $content ?
$content->getSection( $section ) : null;
398 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
399 "nosuch{$prefix}section"
402 $newRev->setContent( SlotRecord
::MAIN
, $content );
405 return [ $newRev, $rev, $rev ];
409 // Override $content based on supplied text
411 $title = $this->guessTitle();
414 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
416 $newRev = $this->revisionStore
->newMutableRevisionFromArray( [
417 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
420 foreach ( $params["{$prefix}slots"] as $role ) {
421 $text = $params["{$prefix}text-{$role}"];
422 if ( $text === null ) {
423 // The SlotRecord::MAIN role can't be deleted
424 if ( $role === SlotRecord
::MAIN
) {
425 $this->dieWithError( [ 'apierror-compare-maintextrequired', $prefix ] );
428 // These parameters make no sense without text. Reject them to avoid
430 foreach ( [ 'section', 'contentmodel', 'contentformat' ] as $param ) {
431 if ( isset( $params["{$prefix}{$param}-{$role}"] ) ) {
432 $this->dieWithError( [
433 'apierror-compare-notext',
434 wfEscapeWikiText( "{$prefix}{$param}-{$role}" ),
435 wfEscapeWikiText( "{$prefix}text-{$role}" ),
440 $newRev->removeSlot( $role );
444 $model = $params["{$prefix}contentmodel-{$role}"];
445 $format = $params["{$prefix}contentformat-{$role}"];
447 if ( !$model && $rev && $rev->hasSlot( $role ) ) {
448 $model = $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
450 if ( !$model && $title && $role === SlotRecord
::MAIN
) {
451 // @todo: Use SlotRoleRegistry and do this for all slots
452 $model = $title->getContentModel();
455 $model = $this->guessModel( $role );
458 $model = CONTENT_MODEL_WIKITEXT
;
459 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
463 $content = ContentHandler
::makeContent( $text, $title, $model, $format );
464 } catch ( MWContentSerializationException
$ex ) {
465 $this->dieWithException( $ex, [
466 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
470 if ( $params["{$prefix}pst"] ) {
472 $this->dieWithError( 'apierror-compare-no-title' );
474 $popts = ParserOptions
::newFromContext( $this->getContext() );
475 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
478 $section = $params["{$prefix}section-{$role}"];
479 if ( $section !== null && $section !== '' ) {
481 $this->dieWithError( "apierror-compare-no{$prefix}revision" );
483 $oldContent = $rev->getContent( $role, RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
484 if ( !$oldContent ) {
486 [ 'apierror-missingcontent-revid-role', $rev->getId(), wfEscapeWikiText( $role ) ],
490 if ( !$oldContent->getContentHandler()->supportsSections() ) {
491 $this->dieWithError( [ 'apierror-sectionsnotsupported', $content->getModel() ] );
494 $content = $oldContent->replaceSection( $section, $content, '' );
495 } catch ( Exception
$ex ) {
496 // Probably a content model mismatch.
500 $this->dieWithError( [ 'apierror-sectionreplacefailed' ] );
504 // Deprecated 'fromsection'/'tosection'
505 if ( $role === SlotRecord
::MAIN
&& isset( $params["{$prefix}section"] ) ) {
506 $section = $params["{$prefix}section"];
507 $content = $content->getSection( $section );
510 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
511 "nosuch{$prefix}section"
516 $newRev->setContent( $role, $content );
518 return [ $newRev, $rev, null ];
522 * Set value fields from a RevisionRecord object
524 * @param array &$vals Result array to set data into
525 * @param string $prefix 'from' or 'to'
526 * @param RevisionRecord|null $rev
528 private function setVals( &$vals, $prefix, $rev ) {
530 $title = $rev->getPageAsLinkTarget();
531 if ( isset( $this->props
['ids'] ) ) {
532 $vals["{$prefix}id"] = $title->getArticleID();
533 $vals["{$prefix}revid"] = $rev->getId();
535 if ( isset( $this->props
['title'] ) ) {
536 ApiQueryBase
::addTitleInfo( $vals, $title, $prefix );
538 if ( isset( $this->props
['size'] ) ) {
539 $vals["{$prefix}size"] = $rev->getSize();
543 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
544 $vals["{$prefix}texthidden"] = true;
548 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
549 $vals["{$prefix}userhidden"] = true;
552 if ( isset( $this->props
['user'] ) ) {
553 $user = $rev->getUser( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
555 $vals["{$prefix}user"] = $user->getName();
556 $vals["{$prefix}userid"] = $user->getId();
560 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) ) {
561 $vals["{$prefix}commenthidden"] = true;
564 if ( isset( $this->props
['comment'] ) ||
isset( $this->props
['parsedcomment'] ) ) {
565 $comment = $rev->getComment( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
566 if ( $comment !== null ) {
567 if ( isset( $this->props
['comment'] ) ) {
568 $vals["{$prefix}comment"] = $comment->text
;
570 $vals["{$prefix}parsedcomment"] = Linker
::formatComment(
571 $comment->text
, Title
::newFromLinkTarget( $title )
577 $this->getMain()->setCacheMode( 'private' );
578 if ( $rev->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
579 $vals["{$prefix}suppressed"] = true;
583 if ( !empty( $rev->isArchive
) ) {
584 $this->getMain()->setCacheMode( 'private' );
585 $vals["{$prefix}archive"] = true;
590 public function getAllowedParams() {
591 $slotRoles = MediaWikiServices
::getInstance()->getSlotRoleStore()->getMap();
592 if ( !in_array( SlotRecord
::MAIN
, $slotRoles, true ) ) {
593 $slotRoles[] = SlotRecord
::MAIN
;
595 sort( $slotRoles, SORT_STRING
);
597 // Parameters for the 'from' and 'to' content
601 ApiBase
::PARAM_TYPE
=> 'integer'
604 ApiBase
::PARAM_TYPE
=> 'integer'
608 ApiBase
::PARAM_TYPE
=> $slotRoles,
609 ApiBase
::PARAM_ISMULTI
=> true,
612 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
613 ApiBase
::PARAM_TYPE
=> 'text',
615 'section-{slot}' => [
616 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
617 ApiBase
::PARAM_TYPE
=> 'string',
619 'contentformat-{slot}' => [
620 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
621 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
623 'contentmodel-{slot}' => [
624 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
625 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
630 ApiBase
::PARAM_TYPE
=> 'text',
631 ApiBase
::PARAM_DEPRECATED
=> true,
634 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
635 ApiBase
::PARAM_DEPRECATED
=> true,
638 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
639 ApiBase
::PARAM_DEPRECATED
=> true,
642 ApiBase
::PARAM_DFLT
=> null,
643 ApiBase
::PARAM_DEPRECATED
=> true,
648 foreach ( $fromToParams as $k => $v ) {
649 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
650 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'fromslots';
654 foreach ( $fromToParams as $k => $v ) {
655 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
656 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'toslots';
661 $ret = wfArrayInsertAfter(
663 [ 'torelative' => [ ApiBase
::PARAM_TYPE
=> [ 'prev', 'next', 'cur' ], ] ],
668 ApiBase
::PARAM_DFLT
=> 'diff|ids|title',
669 ApiBase
::PARAM_TYPE
=> [
680 ApiBase
::PARAM_ISMULTI
=> true,
681 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
685 ApiBase
::PARAM_TYPE
=> $slotRoles,
686 ApiBase
::PARAM_ISMULTI
=> true,
687 ApiBase
::PARAM_ALL
=> true,
693 protected function getExamplesMessages() {
695 'action=compare&fromrev=1&torev=2'
696 => 'apihelp-compare-example-1',