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\RevisionStore
;
26 use MediaWiki\Revision\SlotRecord
;
28 class ApiComparePages
extends ApiBase
{
30 /** @var RevisionStore */
31 private $revisionStore;
33 private $guessedTitle = false, $props;
35 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
36 parent
::__construct( $mainModule, $moduleName, $modulePrefix );
37 $this->revisionStore
= MediaWikiServices
::getInstance()->getRevisionStore();
40 public function execute() {
41 $params = $this->extractRequestParams();
43 // Parameter validation
44 $this->requireAtLeastOneParameter(
45 $params, 'fromtitle', 'fromid', 'fromrev', 'fromtext', 'fromslots'
47 $this->requireAtLeastOneParameter(
48 $params, 'totitle', 'toid', 'torev', 'totext', 'torelative', 'toslots'
51 $this->props
= array_flip( $params['prop'] );
53 // Cache responses publicly by default. This may be overridden later.
54 $this->getMain()->setCacheMode( 'public' );
56 // Get the 'from' RevisionRecord
57 list( $fromRev, $fromRelRev, $fromValsRev ) = $this->getDiffRevision( 'from', $params );
59 // Get the 'to' RevisionRecord
60 if ( $params['torelative'] !== null ) {
62 $this->dieWithError( 'apierror-compare-relative-to-nothing' );
64 switch ( $params['torelative'] ) {
66 // Swap 'from' and 'to'
67 list( $toRev, $toRelRev, $toValsRev ) = [ $fromRev, $fromRelRev, $fromValsRev ];
68 $fromRev = $this->revisionStore
->getPreviousRevision( $toRelRev );
69 $fromRelRev = $fromRev;
70 $fromValsRev = $fromRev;
72 $title = Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() );
74 'apiwarn-compare-no-prev',
75 wfEscapeWikiText( $title->getPrefixedText() ),
79 // (T203433) Create an empty dummy revision as the "previous".
80 // The main slot has to exist, the rest will be handled by DifferenceEngine.
81 $fromRev = $this->revisionStore
->newMutableRevisionFromArray( [
82 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
86 $toRelRev->getContent( SlotRecord
::MAIN
, RevisionRecord
::RAW
)
94 $toRev = $this->revisionStore
->getNextRevision( $fromRelRev );
98 $title = Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() );
100 'apiwarn-compare-no-next',
101 wfEscapeWikiText( $title->getPrefixedText() ),
105 // (T203433) The web UI treats "next" as "cur" in this case.
106 // Avoid repeating metadata by making a MutableRevisionRecord with no changes.
107 $toRev = MutableRevisionRecord
::newFromParentRevision( $fromRelRev );
112 $title = $fromRelRev->getPageAsLinkTarget();
113 $toRev = $this->revisionStore
->getRevisionByTitle( $title );
115 $title = Title
::newFromLinkTarget( $title );
117 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
125 list( $toRev, $toRelRev, $toValsRev ) = $this->getDiffRevision( 'to', $params );
128 // Handle missing from or to revisions (should never happen)
129 // @codeCoverageIgnoreStart
130 if ( !$fromRev ||
!$toRev ) {
131 $this->dieWithError( 'apierror-baddiff' );
133 // @codeCoverageIgnoreEnd
136 if ( !$fromRev->audienceCan(
137 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
139 $this->dieWithError( [ 'apierror-missingcontent-revid', $fromRev->getId() ], 'missingcontent' );
141 if ( !$toRev->audienceCan(
142 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
144 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
148 $context = new DerivativeContext( $this->getContext() );
149 if ( $fromRelRev && $fromRelRev->getPageAsLinkTarget() ) {
150 $context->setTitle( Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() ) );
151 } elseif ( $toRelRev && $toRelRev->getPageAsLinkTarget() ) {
152 $context->setTitle( Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() ) );
154 $guessedTitle = $this->guessTitle();
155 if ( $guessedTitle ) {
156 $context->setTitle( $guessedTitle );
159 $de = new DifferenceEngine( $context );
160 $de->setRevisions( $fromRev, $toRev );
161 if ( $params['slots'] === null ) {
162 $difftext = $de->getDiffBody();
163 if ( $difftext === false ) {
164 $this->dieWithError( 'apierror-baddiff' );
168 foreach ( $params['slots'] as $role ) {
169 $difftext[$role] = $de->getDiffBodyForRole( $role );
173 // Fill in the response
175 $this->setVals( $vals, 'from', $fromValsRev );
176 $this->setVals( $vals, 'to', $toValsRev );
178 if ( isset( $this->props
['rel'] ) ) {
179 if ( !$fromRev instanceof MutableRevisionRecord
) {
180 $rev = $this->revisionStore
->getPreviousRevision( $fromRev );
182 $vals['prev'] = $rev->getId();
185 if ( !$toRev instanceof MutableRevisionRecord
) {
186 $rev = $this->revisionStore
->getNextRevision( $toRev );
188 $vals['next'] = $rev->getId();
193 if ( isset( $this->props
['diffsize'] ) ) {
194 $vals['diffsize'] = 0;
195 foreach ( (array)$difftext as $text ) {
196 $vals['diffsize'] +
= strlen( $text );
199 if ( isset( $this->props
['diff'] ) ) {
200 if ( is_array( $difftext ) ) {
201 ApiResult
::setArrayType( $difftext, 'kvp', 'diff' );
202 $vals['bodies'] = $difftext;
204 ApiResult
::setContentValue( $vals, 'body', $difftext );
208 // Diffs can be really big and there's little point in having
209 // ApiResult truncate it to an empty response since the diff is the
210 // whole reason this module exists. So pass NO_SIZE_CHECK here.
211 $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult
::NO_SIZE_CHECK
);
215 * Load a revision by ID
217 * Falls back to checking the archive table if appropriate.
220 * @return RevisionRecord|null
222 private function getRevisionById( $id ) {
223 $rev = $this->revisionStore
->getRevisionById( $id );
224 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
225 // Try the 'archive' table
226 $arQuery = $this->revisionStore
->getArchiveQueryInfo();
227 $row = $this->getDB()->selectRow(
231 [ 'ar_namespace', 'ar_title' ]
233 [ 'ar_rev_id' => $id ],
239 $rev = $this->revisionStore
->newRevisionFromArchiveRow( $row );
240 $rev->isArchive
= true;
247 * Guess an appropriate default Title for this request
251 private function guessTitle() {
252 if ( $this->guessedTitle
!== false ) {
253 return $this->guessedTitle
;
256 $this->guessedTitle
= null;
257 $params = $this->extractRequestParams();
259 foreach ( [ 'from', 'to' ] as $prefix ) {
260 if ( $params["{$prefix}rev"] !== null ) {
261 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
263 $this->guessedTitle
= Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
268 if ( $params["{$prefix}title"] !== null ) {
269 $title = Title
::newFromText( $params["{$prefix}title"] );
270 if ( $title && !$title->isExternal() ) {
271 $this->guessedTitle
= $title;
276 if ( $params["{$prefix}id"] !== null ) {
277 $title = Title
::newFromID( $params["{$prefix}id"] );
279 $this->guessedTitle
= $title;
285 return $this->guessedTitle
;
289 * Guess an appropriate default content model for this request
290 * @param string $role Slot for which to guess the model
291 * @return string|null Guessed content model
293 private function guessModel( $role ) {
294 $params = $this->extractRequestParams();
297 foreach ( [ 'from', 'to' ] as $prefix ) {
298 if ( $params["{$prefix}rev"] !== null ) {
299 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
301 if ( $rev->hasSlot( $role ) ) {
302 return $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
308 $guessedTitle = $this->guessTitle();
309 if ( $guessedTitle && $role === SlotRecord
::MAIN
) {
310 // @todo: Use SlotRoleRegistry and do this for all slots
311 return $guessedTitle->getContentModel();
314 if ( isset( $params["fromcontentmodel-$role"] ) ) {
315 return $params["fromcontentmodel-$role"];
317 if ( isset( $params["tocontentmodel-$role"] ) ) {
318 return $params["tocontentmodel-$role"];
321 if ( $role === SlotRecord
::MAIN
) {
322 if ( isset( $params['fromcontentmodel'] ) ) {
323 return $params['fromcontentmodel'];
325 if ( isset( $params['tocontentmodel'] ) ) {
326 return $params['tocontentmodel'];
334 * Get the RevisionRecord for one side of the diff
336 * This uses the appropriate set of parameters to determine what content
339 * Returns three values:
340 * - A RevisionRecord holding the content
341 * - The revision specified, if any, even if content was supplied
342 * - The revision to pass to setVals(), if any
344 * @param string $prefix 'from' or 'to'
345 * @param array $params
346 * @return array [ RevisionRecord|null, RevisionRecord|null, RevisionRecord|null ]
348 private function getDiffRevision( $prefix, array $params ) {
349 // Back compat params
350 $this->requireMaxOneParameter( $params, "{$prefix}text", "{$prefix}slots" );
351 $this->requireMaxOneParameter( $params, "{$prefix}section", "{$prefix}slots" );
352 if ( $params["{$prefix}text"] !== null ) {
353 $params["{$prefix}slots"] = [ SlotRecord
::MAIN
];
354 $params["{$prefix}text-main"] = $params["{$prefix}text"];
355 $params["{$prefix}section-main"] = null;
356 $params["{$prefix}contentmodel-main"] = $params["{$prefix}contentmodel"];
357 $params["{$prefix}contentformat-main"] = $params["{$prefix}contentformat"];
362 $suppliedContent = $params["{$prefix}slots"] !== null;
364 // Get the revision and title, if applicable
366 if ( $params["{$prefix}rev"] !== null ) {
367 $revId = $params["{$prefix}rev"];
368 } elseif ( $params["{$prefix}title"] !== null ||
$params["{$prefix}id"] !== null ) {
369 if ( $params["{$prefix}title"] !== null ) {
370 $title = Title
::newFromText( $params["{$prefix}title"] );
371 if ( !$title ||
$title->isExternal() ) {
373 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
377 $title = Title
::newFromID( $params["{$prefix}id"] );
379 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
382 $revId = $title->getLatestRevID();
385 // Only die here if we're not using supplied text
386 if ( !$suppliedContent ) {
387 if ( $title->exists() ) {
389 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
393 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
400 if ( $revId !== null ) {
401 $rev = $this->getRevisionById( $revId );
403 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
405 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
407 // If we don't have supplied content, return here. Otherwise,
408 // continue on below with the supplied content.
409 if ( !$suppliedContent ) {
412 // Deprecated 'fromsection'/'tosection'
413 if ( isset( $params["{$prefix}section"] ) ) {
414 $section = $params["{$prefix}section"];
415 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
416 $content = $rev->getContent( SlotRecord
::MAIN
, RevisionRecord
::FOR_THIS_USER
,
420 [ 'apierror-missingcontent-revid-role', $rev->getId(), SlotRecord
::MAIN
], 'missingcontent'
423 $content = $content ?
$content->getSection( $section ) : null;
426 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
427 "nosuch{$prefix}section"
430 $newRev->setContent( SlotRecord
::MAIN
, $content );
433 return [ $newRev, $rev, $rev ];
437 // Override $content based on supplied text
439 $title = $this->guessTitle();
442 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
444 $newRev = $this->revisionStore
->newMutableRevisionFromArray( [
445 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
448 foreach ( $params["{$prefix}slots"] as $role ) {
449 $text = $params["{$prefix}text-{$role}"];
450 if ( $text === null ) {
451 // The SlotRecord::MAIN role can't be deleted
452 if ( $role === SlotRecord
::MAIN
) {
453 $this->dieWithError( [ 'apierror-compare-maintextrequired', $prefix ] );
456 // These parameters make no sense without text. Reject them to avoid
458 foreach ( [ 'section', 'contentmodel', 'contentformat' ] as $param ) {
459 if ( isset( $params["{$prefix}{$param}-{$role}"] ) ) {
460 $this->dieWithError( [
461 'apierror-compare-notext',
462 wfEscapeWikiText( "{$prefix}{$param}-{$role}" ),
463 wfEscapeWikiText( "{$prefix}text-{$role}" ),
468 $newRev->removeSlot( $role );
472 $model = $params["{$prefix}contentmodel-{$role}"];
473 $format = $params["{$prefix}contentformat-{$role}"];
475 if ( !$model && $rev && $rev->hasSlot( $role ) ) {
476 $model = $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
478 if ( !$model && $title && $role === SlotRecord
::MAIN
) {
479 // @todo: Use SlotRoleRegistry and do this for all slots
480 $model = $title->getContentModel();
483 $model = $this->guessModel( $role );
486 $model = CONTENT_MODEL_WIKITEXT
;
487 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
491 $content = ContentHandler
::makeContent( $text, $title, $model, $format );
492 } catch ( MWContentSerializationException
$ex ) {
493 $this->dieWithException( $ex, [
494 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
498 if ( $params["{$prefix}pst"] ) {
500 $this->dieWithError( 'apierror-compare-no-title' );
502 $popts = ParserOptions
::newFromContext( $this->getContext() );
503 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
506 $section = $params["{$prefix}section-{$role}"];
507 if ( $section !== null && $section !== '' ) {
509 $this->dieWithError( "apierror-compare-no{$prefix}revision" );
511 $oldContent = $rev->getContent( $role, RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
512 if ( !$oldContent ) {
514 [ 'apierror-missingcontent-revid-role', $rev->getId(), wfEscapeWikiText( $role ) ],
518 if ( !$oldContent->getContentHandler()->supportsSections() ) {
519 $this->dieWithError( [ 'apierror-sectionsnotsupported', $content->getModel() ] );
522 $content = $oldContent->replaceSection( $section, $content, '' );
523 } catch ( Exception
$ex ) {
524 // Probably a content model mismatch.
528 $this->dieWithError( [ 'apierror-sectionreplacefailed' ] );
532 // Deprecated 'fromsection'/'tosection'
533 if ( $role === SlotRecord
::MAIN
&& isset( $params["{$prefix}section"] ) ) {
534 $section = $params["{$prefix}section"];
535 $content = $content->getSection( $section );
538 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
539 "nosuch{$prefix}section"
544 $newRev->setContent( $role, $content );
546 return [ $newRev, $rev, null ];
550 * Set value fields from a RevisionRecord object
552 * @param array &$vals Result array to set data into
553 * @param string $prefix 'from' or 'to'
554 * @param RevisionRecord|null $rev
556 private function setVals( &$vals, $prefix, $rev ) {
558 $title = $rev->getPageAsLinkTarget();
559 if ( isset( $this->props
['ids'] ) ) {
560 $vals["{$prefix}id"] = $title->getArticleID();
561 $vals["{$prefix}revid"] = $rev->getId();
563 if ( isset( $this->props
['title'] ) ) {
564 ApiQueryBase
::addTitleInfo( $vals, $title, $prefix );
566 if ( isset( $this->props
['size'] ) ) {
567 $vals["{$prefix}size"] = $rev->getSize();
571 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
572 $vals["{$prefix}texthidden"] = true;
576 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
577 $vals["{$prefix}userhidden"] = true;
580 if ( isset( $this->props
['user'] ) ) {
581 $user = $rev->getUser( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
583 $vals["{$prefix}user"] = $user->getName();
584 $vals["{$prefix}userid"] = $user->getId();
588 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) ) {
589 $vals["{$prefix}commenthidden"] = true;
592 if ( isset( $this->props
['comment'] ) ||
isset( $this->props
['parsedcomment'] ) ) {
593 $comment = $rev->getComment( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
594 if ( $comment !== null ) {
595 if ( isset( $this->props
['comment'] ) ) {
596 $vals["{$prefix}comment"] = $comment->text
;
598 $vals["{$prefix}parsedcomment"] = Linker
::formatComment(
599 $comment->text
, Title
::newFromLinkTarget( $title )
605 $this->getMain()->setCacheMode( 'private' );
606 if ( $rev->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
607 $vals["{$prefix}suppressed"] = true;
611 if ( !empty( $rev->isArchive
) ) {
612 $this->getMain()->setCacheMode( 'private' );
613 $vals["{$prefix}archive"] = true;
618 public function getAllowedParams() {
619 $slotRoles = MediaWikiServices
::getInstance()->getSlotRoleStore()->getMap();
620 if ( !in_array( SlotRecord
::MAIN
, $slotRoles, true ) ) {
621 $slotRoles[] = SlotRecord
::MAIN
;
623 sort( $slotRoles, SORT_STRING
);
625 // Parameters for the 'from' and 'to' content
629 ApiBase
::PARAM_TYPE
=> 'integer'
632 ApiBase
::PARAM_TYPE
=> 'integer'
636 ApiBase
::PARAM_TYPE
=> $slotRoles,
637 ApiBase
::PARAM_ISMULTI
=> true,
640 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
641 ApiBase
::PARAM_TYPE
=> 'text',
643 'section-{slot}' => [
644 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
645 ApiBase
::PARAM_TYPE
=> 'string',
647 'contentformat-{slot}' => [
648 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
649 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
651 'contentmodel-{slot}' => [
652 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
653 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
658 ApiBase
::PARAM_TYPE
=> 'text',
659 ApiBase
::PARAM_DEPRECATED
=> true,
662 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
663 ApiBase
::PARAM_DEPRECATED
=> true,
666 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
667 ApiBase
::PARAM_DEPRECATED
=> true,
670 ApiBase
::PARAM_DFLT
=> null,
671 ApiBase
::PARAM_DEPRECATED
=> true,
676 foreach ( $fromToParams as $k => $v ) {
677 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
678 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'fromslots';
682 foreach ( $fromToParams as $k => $v ) {
683 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
684 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'toslots';
689 $ret = wfArrayInsertAfter(
691 [ 'torelative' => [ ApiBase
::PARAM_TYPE
=> [ 'prev', 'next', 'cur' ], ] ],
696 ApiBase
::PARAM_DFLT
=> 'diff|ids|title',
697 ApiBase
::PARAM_TYPE
=> [
708 ApiBase
::PARAM_ISMULTI
=> true,
709 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
713 ApiBase
::PARAM_TYPE
=> $slotRoles,
714 ApiBase
::PARAM_ISMULTI
=> true,
715 ApiBase
::PARAM_ALL
=> true,
721 protected function getExamplesMessages() {
723 'action=compare&fromrev=1&torev=2'
724 => 'apihelp-compare-example-1',