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 /** @var \MediaWiki\Revision\SlotRoleRegistry */
35 private $slotRoleRegistry;
37 private $guessedTitle = false, $props;
39 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
40 parent
::__construct( $mainModule, $moduleName, $modulePrefix );
41 $this->revisionStore
= MediaWikiServices
::getInstance()->getRevisionStore();
42 $this->slotRoleRegistry
= MediaWikiServices
::getInstance()->getSlotRoleRegistry();
45 public function execute() {
46 $params = $this->extractRequestParams();
48 // Parameter validation
49 $this->requireAtLeastOneParameter(
50 $params, 'fromtitle', 'fromid', 'fromrev', 'fromtext', 'fromslots'
52 $this->requireAtLeastOneParameter(
53 $params, 'totitle', 'toid', 'torev', 'totext', 'torelative', 'toslots'
56 $this->props
= array_flip( $params['prop'] );
58 // Cache responses publicly by default. This may be overridden later.
59 $this->getMain()->setCacheMode( 'public' );
61 // Get the 'from' RevisionRecord
62 list( $fromRev, $fromRelRev, $fromValsRev ) = $this->getDiffRevision( 'from', $params );
64 // Get the 'to' RevisionRecord
65 if ( $params['torelative'] !== null ) {
67 $this->dieWithError( 'apierror-compare-relative-to-nothing' );
69 if ( $params['torelative'] !== 'cur' && $fromRelRev instanceof RevisionArchiveRecord
) {
70 // RevisionStore's getPreviousRevision/getNextRevision blow up
71 // when passed an RevisionArchiveRecord for a deleted page
72 $this->dieWithError( [ 'apierror-compare-relative-to-deleted', $params['torelative'] ] );
74 switch ( $params['torelative'] ) {
76 // Swap 'from' and 'to'
77 list( $toRev, $toRelRev, $toValsRev ) = [ $fromRev, $fromRelRev, $fromValsRev ];
78 $fromRev = $this->revisionStore
->getPreviousRevision( $toRelRev );
79 $fromRelRev = $fromRev;
80 $fromValsRev = $fromRev;
82 $title = Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() );
84 'apiwarn-compare-no-prev',
85 wfEscapeWikiText( $title->getPrefixedText() ),
89 // (T203433) Create an empty dummy revision as the "previous".
90 // The main slot has to exist, the rest will be handled by DifferenceEngine.
91 $fromRev = $this->revisionStore
->newMutableRevisionFromArray( [
92 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
96 $toRelRev->getContent( SlotRecord
::MAIN
, RevisionRecord
::RAW
)
104 $toRev = $this->revisionStore
->getNextRevision( $fromRelRev );
108 $title = Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() );
110 'apiwarn-compare-no-next',
111 wfEscapeWikiText( $title->getPrefixedText() ),
115 // (T203433) The web UI treats "next" as "cur" in this case.
116 // Avoid repeating metadata by making a MutableRevisionRecord with no changes.
117 $toRev = MutableRevisionRecord
::newFromParentRevision( $fromRelRev );
122 $title = $fromRelRev->getPageAsLinkTarget();
123 $toRev = $this->revisionStore
->getRevisionByTitle( $title );
125 $title = Title
::newFromLinkTarget( $title );
127 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
135 list( $toRev, $toRelRev, $toValsRev ) = $this->getDiffRevision( 'to', $params );
138 // Handle missing from or to revisions (should never happen)
139 // @codeCoverageIgnoreStart
140 if ( !$fromRev ||
!$toRev ) {
141 $this->dieWithError( 'apierror-baddiff' );
143 // @codeCoverageIgnoreEnd
146 if ( !$fromRev->audienceCan(
147 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
149 $this->dieWithError( [ 'apierror-missingcontent-revid', $fromRev->getId() ], 'missingcontent' );
151 if ( !$toRev->audienceCan(
152 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
154 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
158 $context = new DerivativeContext( $this->getContext() );
159 if ( $fromRelRev && $fromRelRev->getPageAsLinkTarget() ) {
160 $context->setTitle( Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() ) );
161 } elseif ( $toRelRev && $toRelRev->getPageAsLinkTarget() ) {
162 $context->setTitle( Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() ) );
164 $guessedTitle = $this->guessTitle();
165 if ( $guessedTitle ) {
166 $context->setTitle( $guessedTitle );
169 $de = new DifferenceEngine( $context );
170 $de->setRevisions( $fromRev, $toRev );
171 if ( $params['slots'] === null ) {
172 $difftext = $de->getDiffBody();
173 if ( $difftext === false ) {
174 $this->dieWithError( 'apierror-baddiff' );
178 foreach ( $params['slots'] as $role ) {
179 $difftext[$role] = $de->getDiffBodyForRole( $role );
183 // Fill in the response
185 $this->setVals( $vals, 'from', $fromValsRev );
186 $this->setVals( $vals, 'to', $toValsRev );
188 if ( isset( $this->props
['rel'] ) ) {
189 if ( !$fromRev instanceof MutableRevisionRecord
) {
190 $rev = $this->revisionStore
->getPreviousRevision( $fromRev );
192 $vals['prev'] = $rev->getId();
195 if ( !$toRev instanceof MutableRevisionRecord
) {
196 $rev = $this->revisionStore
->getNextRevision( $toRev );
198 $vals['next'] = $rev->getId();
203 if ( isset( $this->props
['diffsize'] ) ) {
204 $vals['diffsize'] = 0;
205 foreach ( (array)$difftext as $text ) {
206 $vals['diffsize'] +
= strlen( $text );
209 if ( isset( $this->props
['diff'] ) ) {
210 if ( is_array( $difftext ) ) {
211 ApiResult
::setArrayType( $difftext, 'kvp', 'diff' );
212 $vals['bodies'] = $difftext;
214 ApiResult
::setContentValue( $vals, 'body', $difftext );
218 // Diffs can be really big and there's little point in having
219 // ApiResult truncate it to an empty response since the diff is the
220 // whole reason this module exists. So pass NO_SIZE_CHECK here.
221 $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult
::NO_SIZE_CHECK
);
225 * Load a revision by ID
227 * Falls back to checking the archive table if appropriate.
230 * @return RevisionRecord|null
232 private function getRevisionById( $id ) {
233 $rev = $this->revisionStore
->getRevisionById( $id );
234 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
235 // Try the 'archive' table
236 $arQuery = $this->revisionStore
->getArchiveQueryInfo();
237 $row = $this->getDB()->selectRow(
241 [ 'ar_namespace', 'ar_title' ]
243 [ 'ar_rev_id' => $id ],
249 $rev = $this->revisionStore
->newRevisionFromArchiveRow( $row );
250 $rev->isArchive
= true;
257 * Guess an appropriate default Title for this request
261 private function guessTitle() {
262 if ( $this->guessedTitle
!== false ) {
263 return $this->guessedTitle
;
266 $this->guessedTitle
= null;
267 $params = $this->extractRequestParams();
269 foreach ( [ 'from', 'to' ] as $prefix ) {
270 if ( $params["{$prefix}rev"] !== null ) {
271 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
273 $this->guessedTitle
= Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
278 if ( $params["{$prefix}title"] !== null ) {
279 $title = Title
::newFromText( $params["{$prefix}title"] );
280 if ( $title && !$title->isExternal() ) {
281 $this->guessedTitle
= $title;
286 if ( $params["{$prefix}id"] !== null ) {
287 $title = Title
::newFromID( $params["{$prefix}id"] );
289 $this->guessedTitle
= $title;
295 return $this->guessedTitle
;
299 * Guess an appropriate default content model for this request
300 * @param string $role Slot for which to guess the model
301 * @return string|null Guessed content model
303 private function guessModel( $role ) {
304 $params = $this->extractRequestParams();
307 foreach ( [ 'from', 'to' ] as $prefix ) {
308 if ( $params["{$prefix}rev"] !== null ) {
309 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
310 if ( $rev && $rev->hasSlot( $role ) ) {
311 return $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
316 $guessedTitle = $this->guessTitle();
317 if ( $guessedTitle ) {
318 return $this->slotRoleRegistry
->getRoleHandler( $role )->getDefaultModel( $guessedTitle );
321 if ( isset( $params["fromcontentmodel-$role"] ) ) {
322 return $params["fromcontentmodel-$role"];
324 if ( isset( $params["tocontentmodel-$role"] ) ) {
325 return $params["tocontentmodel-$role"];
328 if ( $role === SlotRecord
::MAIN
) {
329 if ( isset( $params['fromcontentmodel'] ) ) {
330 return $params['fromcontentmodel'];
332 if ( isset( $params['tocontentmodel'] ) ) {
333 return $params['tocontentmodel'];
341 * Get the RevisionRecord for one side of the diff
343 * This uses the appropriate set of parameters to determine what content
346 * Returns three values:
347 * - A RevisionRecord holding the content
348 * - The revision specified, if any, even if content was supplied
349 * - The revision to pass to setVals(), if any
351 * @param string $prefix 'from' or 'to'
352 * @param array $params
353 * @return array [ RevisionRecord|null, RevisionRecord|null, RevisionRecord|null ]
355 private function getDiffRevision( $prefix, array $params ) {
356 // Back compat params
357 $this->requireMaxOneParameter( $params, "{$prefix}text", "{$prefix}slots" );
358 $this->requireMaxOneParameter( $params, "{$prefix}section", "{$prefix}slots" );
359 if ( $params["{$prefix}text"] !== null ) {
360 $params["{$prefix}slots"] = [ SlotRecord
::MAIN
];
361 $params["{$prefix}text-main"] = $params["{$prefix}text"];
362 $params["{$prefix}section-main"] = null;
363 $params["{$prefix}contentmodel-main"] = $params["{$prefix}contentmodel"];
364 $params["{$prefix}contentformat-main"] = $params["{$prefix}contentformat"];
369 $suppliedContent = $params["{$prefix}slots"] !== null;
371 // Get the revision and title, if applicable
373 if ( $params["{$prefix}rev"] !== null ) {
374 $revId = $params["{$prefix}rev"];
375 } elseif ( $params["{$prefix}title"] !== null ||
$params["{$prefix}id"] !== null ) {
376 if ( $params["{$prefix}title"] !== null ) {
377 $title = Title
::newFromText( $params["{$prefix}title"] );
378 if ( !$title ||
$title->isExternal() ) {
380 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
384 $title = Title
::newFromID( $params["{$prefix}id"] );
386 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
389 $revId = $title->getLatestRevID();
392 // Only die here if we're not using supplied text
393 if ( !$suppliedContent ) {
394 if ( $title->exists() ) {
396 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
400 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
407 if ( $revId !== null ) {
408 $rev = $this->getRevisionById( $revId );
410 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
412 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
414 // If we don't have supplied content, return here. Otherwise,
415 // continue on below with the supplied content.
416 if ( !$suppliedContent ) {
419 // Deprecated 'fromsection'/'tosection'
420 if ( isset( $params["{$prefix}section"] ) ) {
421 $section = $params["{$prefix}section"];
422 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
423 $content = $rev->getContent( SlotRecord
::MAIN
, RevisionRecord
::FOR_THIS_USER
,
427 [ 'apierror-missingcontent-revid-role', $rev->getId(), SlotRecord
::MAIN
], 'missingcontent'
430 $content = $content ?
$content->getSection( $section ) : null;
433 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
434 "nosuch{$prefix}section"
437 $newRev->setContent( SlotRecord
::MAIN
, $content );
440 return [ $newRev, $rev, $rev ];
444 // Override $content based on supplied text
446 $title = $this->guessTitle();
449 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
451 $newRev = $this->revisionStore
->newMutableRevisionFromArray( [
452 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
455 foreach ( $params["{$prefix}slots"] as $role ) {
456 $text = $params["{$prefix}text-{$role}"];
457 if ( $text === null ) {
458 // The SlotRecord::MAIN role can't be deleted
459 if ( $role === SlotRecord
::MAIN
) {
460 $this->dieWithError( [ 'apierror-compare-maintextrequired', $prefix ] );
463 // These parameters make no sense without text. Reject them to avoid
465 foreach ( [ 'section', 'contentmodel', 'contentformat' ] as $param ) {
466 if ( isset( $params["{$prefix}{$param}-{$role}"] ) ) {
467 $this->dieWithError( [
468 'apierror-compare-notext',
469 wfEscapeWikiText( "{$prefix}{$param}-{$role}" ),
470 wfEscapeWikiText( "{$prefix}text-{$role}" ),
475 $newRev->removeSlot( $role );
479 $model = $params["{$prefix}contentmodel-{$role}"];
480 $format = $params["{$prefix}contentformat-{$role}"];
482 if ( !$model && $rev && $rev->hasSlot( $role ) ) {
483 $model = $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
485 if ( !$model && $title && $role === SlotRecord
::MAIN
) {
486 // @todo: Use SlotRoleRegistry and do this for all slots
487 $model = $title->getContentModel();
490 $model = $this->guessModel( $role );
493 $model = CONTENT_MODEL_WIKITEXT
;
494 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
498 $content = ContentHandler
::makeContent( $text, $title, $model, $format );
499 } catch ( MWContentSerializationException
$ex ) {
500 $this->dieWithException( $ex, [
501 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
505 if ( $params["{$prefix}pst"] ) {
507 $this->dieWithError( 'apierror-compare-no-title' );
509 $popts = ParserOptions
::newFromContext( $this->getContext() );
510 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
513 $section = $params["{$prefix}section-{$role}"];
514 if ( $section !== null && $section !== '' ) {
516 $this->dieWithError( "apierror-compare-no{$prefix}revision" );
518 $oldContent = $rev->getContent( $role, RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
519 if ( !$oldContent ) {
521 [ 'apierror-missingcontent-revid-role', $rev->getId(), wfEscapeWikiText( $role ) ],
525 if ( !$oldContent->getContentHandler()->supportsSections() ) {
526 $this->dieWithError( [ 'apierror-sectionsnotsupported', $content->getModel() ] );
529 $content = $oldContent->replaceSection( $section, $content, '' );
530 } catch ( Exception
$ex ) {
531 // Probably a content model mismatch.
535 $this->dieWithError( [ 'apierror-sectionreplacefailed' ] );
539 // Deprecated 'fromsection'/'tosection'
540 if ( $role === SlotRecord
::MAIN
&& isset( $params["{$prefix}section"] ) ) {
541 $section = $params["{$prefix}section"];
542 $content = $content->getSection( $section );
545 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
546 "nosuch{$prefix}section"
551 $newRev->setContent( $role, $content );
553 return [ $newRev, $rev, null ];
557 * Set value fields from a RevisionRecord object
559 * @param array &$vals Result array to set data into
560 * @param string $prefix 'from' or 'to'
561 * @param RevisionRecord|null $rev
563 private function setVals( &$vals, $prefix, $rev ) {
565 $title = $rev->getPageAsLinkTarget();
566 if ( isset( $this->props
['ids'] ) ) {
567 $vals["{$prefix}id"] = $title->getArticleID();
568 $vals["{$prefix}revid"] = $rev->getId();
570 if ( isset( $this->props
['title'] ) ) {
571 ApiQueryBase
::addTitleInfo( $vals, $title, $prefix );
573 if ( isset( $this->props
['size'] ) ) {
574 $vals["{$prefix}size"] = $rev->getSize();
578 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
579 $vals["{$prefix}texthidden"] = true;
583 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
584 $vals["{$prefix}userhidden"] = true;
587 if ( isset( $this->props
['user'] ) ) {
588 $user = $rev->getUser( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
590 $vals["{$prefix}user"] = $user->getName();
591 $vals["{$prefix}userid"] = $user->getId();
595 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) ) {
596 $vals["{$prefix}commenthidden"] = true;
599 if ( isset( $this->props
['comment'] ) ||
isset( $this->props
['parsedcomment'] ) ) {
600 $comment = $rev->getComment( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
601 if ( $comment !== null ) {
602 if ( isset( $this->props
['comment'] ) ) {
603 $vals["{$prefix}comment"] = $comment->text
;
605 $vals["{$prefix}parsedcomment"] = Linker
::formatComment(
606 $comment->text
, Title
::newFromLinkTarget( $title )
612 $this->getMain()->setCacheMode( 'private' );
613 if ( $rev->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
614 $vals["{$prefix}suppressed"] = true;
618 if ( !empty( $rev->isArchive
) ) {
619 $this->getMain()->setCacheMode( 'private' );
620 $vals["{$prefix}archive"] = true;
625 public function getAllowedParams() {
626 $slotRoles = $this->slotRoleRegistry
->getKnownRoles();
627 sort( $slotRoles, SORT_STRING
);
629 // Parameters for the 'from' and 'to' content
633 ApiBase
::PARAM_TYPE
=> 'integer'
636 ApiBase
::PARAM_TYPE
=> 'integer'
640 ApiBase
::PARAM_TYPE
=> $slotRoles,
641 ApiBase
::PARAM_ISMULTI
=> true,
644 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
645 ApiBase
::PARAM_TYPE
=> 'text',
647 'section-{slot}' => [
648 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
649 ApiBase
::PARAM_TYPE
=> 'string',
651 'contentformat-{slot}' => [
652 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
653 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
655 'contentmodel-{slot}' => [
656 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
657 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
662 ApiBase
::PARAM_TYPE
=> 'text',
663 ApiBase
::PARAM_DEPRECATED
=> true,
666 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
667 ApiBase
::PARAM_DEPRECATED
=> true,
670 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
671 ApiBase
::PARAM_DEPRECATED
=> true,
674 ApiBase
::PARAM_DFLT
=> null,
675 ApiBase
::PARAM_DEPRECATED
=> true,
680 foreach ( $fromToParams as $k => $v ) {
681 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
682 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'fromslots';
686 foreach ( $fromToParams as $k => $v ) {
687 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
688 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'toslots';
693 $ret = wfArrayInsertAfter(
695 [ 'torelative' => [ ApiBase
::PARAM_TYPE
=> [ 'prev', 'next', 'cur' ], ] ],
700 ApiBase
::PARAM_DFLT
=> 'diff|ids|title',
701 ApiBase
::PARAM_TYPE
=> [
712 ApiBase
::PARAM_ISMULTI
=> true,
713 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
717 ApiBase
::PARAM_TYPE
=> $slotRoles,
718 ApiBase
::PARAM_ISMULTI
=> true,
719 ApiBase
::PARAM_ALL
=> true,
725 protected function getExamplesMessages() {
727 'action=compare&fromrev=1&torev=2'
728 => 'apihelp-compare-example-1',