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, $toRelRev2, $toValsRev ) = [ $fromRev, $fromRelRev, $fromValsRev ];
78 $fromRev = $this->revisionStore
->getPreviousRevision( $fromRelRev );
79 $fromRelRev = $fromRev;
80 $fromValsRev = $fromRev;
84 $toRev = $this->revisionStore
->getNextRevision( $fromRelRev );
90 $title = $fromRelRev->getPageAsLinkTarget();
91 $toRev = $this->revisionStore
->getRevisionByTitle( $title );
93 $title = Title
::newFromLinkTarget( $title );
95 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
103 list( $toRev, $toRelRev, $toValsRev ) = $this->getDiffRevision( 'to', $params );
106 // Handle missing from or to revisions
107 if ( !$fromRev ||
!$toRev ) {
108 $this->dieWithError( 'apierror-baddiff' );
112 if ( !$fromRev->audienceCan(
113 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
115 $this->dieWithError( [ 'apierror-missingcontent-revid', $fromRev->getId() ], 'missingcontent' );
117 if ( !$toRev->audienceCan(
118 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
120 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
124 $context = new DerivativeContext( $this->getContext() );
125 if ( $fromRelRev && $fromRelRev->getPageAsLinkTarget() ) {
126 $context->setTitle( Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() ) );
127 } elseif ( $toRelRev && $toRelRev->getPageAsLinkTarget() ) {
128 $context->setTitle( Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() ) );
130 $guessedTitle = $this->guessTitle();
131 if ( $guessedTitle ) {
132 $context->setTitle( $guessedTitle );
135 $de = new DifferenceEngine( $context );
136 $de->setRevisions( $fromRev, $toRev );
137 if ( $params['slots'] === null ) {
138 $difftext = $de->getDiffBody();
139 if ( $difftext === false ) {
140 $this->dieWithError( 'apierror-baddiff' );
144 foreach ( $params['slots'] as $role ) {
145 $difftext[$role] = $de->getDiffBodyForRole( $role );
149 // Fill in the response
151 $this->setVals( $vals, 'from', $fromValsRev );
152 $this->setVals( $vals, 'to', $toValsRev );
154 if ( isset( $this->props
['rel'] ) ) {
155 if ( !$fromRev instanceof MutableRevisionRecord
) {
156 $rev = $this->revisionStore
->getPreviousRevision( $fromRev );
158 $vals['prev'] = $rev->getId();
161 if ( !$toRev instanceof MutableRevisionRecord
) {
162 $rev = $this->revisionStore
->getNextRevision( $toRev );
164 $vals['next'] = $rev->getId();
169 if ( isset( $this->props
['diffsize'] ) ) {
170 $vals['diffsize'] = 0;
171 foreach ( (array)$difftext as $text ) {
172 $vals['diffsize'] +
= strlen( $text );
175 if ( isset( $this->props
['diff'] ) ) {
176 if ( is_array( $difftext ) ) {
177 ApiResult
::setArrayType( $difftext, 'kvp', 'diff' );
178 $vals['bodies'] = $difftext;
180 ApiResult
::setContentValue( $vals, 'body', $difftext );
184 // Diffs can be really big and there's little point in having
185 // ApiResult truncate it to an empty response since the diff is the
186 // whole reason this module exists. So pass NO_SIZE_CHECK here.
187 $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult
::NO_SIZE_CHECK
);
191 * Load a revision by ID
193 * Falls back to checking the archive table if appropriate.
196 * @return RevisionRecord|null
198 private function getRevisionById( $id ) {
199 $rev = $this->revisionStore
->getRevisionById( $id );
200 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
201 // Try the 'archive' table
202 $arQuery = $this->revisionStore
->getArchiveQueryInfo();
203 $row = $this->getDB()->selectRow(
207 [ 'ar_namespace', 'ar_title' ]
209 [ 'ar_rev_id' => $id ],
215 $rev = $this->revisionStore
->newRevisionFromArchiveRow( $row );
216 $rev->isArchive
= true;
223 * Guess an appropriate default Title for this request
227 private function guessTitle() {
228 if ( $this->guessedTitle
!== false ) {
229 return $this->guessedTitle
;
232 $this->guessedTitle
= null;
233 $params = $this->extractRequestParams();
235 foreach ( [ 'from', 'to' ] as $prefix ) {
236 if ( $params["{$prefix}rev"] !== null ) {
237 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
239 $this->guessedTitle
= Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
244 if ( $params["{$prefix}title"] !== null ) {
245 $title = Title
::newFromText( $params["{$prefix}title"] );
246 if ( $title && !$title->isExternal() ) {
247 $this->guessedTitle
= $title;
252 if ( $params["{$prefix}id"] !== null ) {
253 $title = Title
::newFromID( $params["{$prefix}id"] );
255 $this->guessedTitle
= $title;
261 return $this->guessedTitle
;
265 * Guess an appropriate default content model for this request
266 * @param string $role Slot for which to guess the model
267 * @return string|null Guessed content model
269 private function guessModel( $role ) {
270 $params = $this->extractRequestParams();
273 foreach ( [ 'from', 'to' ] as $prefix ) {
274 if ( $params["{$prefix}rev"] !== null ) {
275 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
277 if ( $rev->hasSlot( $role ) ) {
278 return $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
284 $guessedTitle = $this->guessTitle();
285 if ( $guessedTitle ) {
286 return $this->slotRoleRegistry
->getRoleHandler( $role )->getDefaultModel( $guessedTitle );
289 if ( isset( $params["fromcontentmodel-$role"] ) ) {
290 return $params["fromcontentmodel-$role"];
292 if ( isset( $params["tocontentmodel-$role"] ) ) {
293 return $params["tocontentmodel-$role"];
296 if ( $role === SlotRecord
::MAIN
) {
297 if ( isset( $params['fromcontentmodel'] ) ) {
298 return $params['fromcontentmodel'];
300 if ( isset( $params['tocontentmodel'] ) ) {
301 return $params['tocontentmodel'];
309 * Get the RevisionRecord for one side of the diff
311 * This uses the appropriate set of parameters to determine what content
314 * Returns three values:
315 * - A RevisionRecord holding the content
316 * - The revision specified, if any, even if content was supplied
317 * - The revision to pass to setVals(), if any
319 * @param string $prefix 'from' or 'to'
320 * @param array $params
321 * @return array [ RevisionRecord|null, RevisionRecord|null, RevisionRecord|null ]
323 private function getDiffRevision( $prefix, array $params ) {
324 // Back compat params
325 $this->requireMaxOneParameter( $params, "{$prefix}text", "{$prefix}slots" );
326 $this->requireMaxOneParameter( $params, "{$prefix}section", "{$prefix}slots" );
327 if ( $params["{$prefix}text"] !== null ) {
328 $params["{$prefix}slots"] = [ SlotRecord
::MAIN
];
329 $params["{$prefix}text-main"] = $params["{$prefix}text"];
330 $params["{$prefix}section-main"] = null;
331 $params["{$prefix}contentmodel-main"] = $params["{$prefix}contentmodel"];
332 $params["{$prefix}contentformat-main"] = $params["{$prefix}contentformat"];
337 $suppliedContent = $params["{$prefix}slots"] !== null;
339 // Get the revision and title, if applicable
341 if ( $params["{$prefix}rev"] !== null ) {
342 $revId = $params["{$prefix}rev"];
343 } elseif ( $params["{$prefix}title"] !== null ||
$params["{$prefix}id"] !== null ) {
344 if ( $params["{$prefix}title"] !== null ) {
345 $title = Title
::newFromText( $params["{$prefix}title"] );
346 if ( !$title ||
$title->isExternal() ) {
348 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
352 $title = Title
::newFromID( $params["{$prefix}id"] );
354 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
357 $revId = $title->getLatestRevID();
360 // Only die here if we're not using supplied text
361 if ( !$suppliedContent ) {
362 if ( $title->exists() ) {
364 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
368 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
375 if ( $revId !== null ) {
376 $rev = $this->getRevisionById( $revId );
378 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
380 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
382 // If we don't have supplied content, return here. Otherwise,
383 // continue on below with the supplied content.
384 if ( !$suppliedContent ) {
387 // Deprecated 'fromsection'/'tosection'
388 if ( isset( $params["{$prefix}section"] ) ) {
389 $section = $params["{$prefix}section"];
390 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
391 $content = $rev->getContent( SlotRecord
::MAIN
, RevisionRecord
::FOR_THIS_USER
,
395 [ 'apierror-missingcontent-revid-role', $rev->getId(), SlotRecord
::MAIN
], 'missingcontent'
398 $content = $content ?
$content->getSection( $section ) : null;
401 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
402 "nosuch{$prefix}section"
405 $newRev->setContent( SlotRecord
::MAIN
, $content );
408 return [ $newRev, $rev, $rev ];
412 // Override $content based on supplied text
414 $title = $this->guessTitle();
417 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
419 $newRev = $this->revisionStore
->newMutableRevisionFromArray( [
420 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
423 foreach ( $params["{$prefix}slots"] as $role ) {
424 $text = $params["{$prefix}text-{$role}"];
425 if ( $text === null ) {
426 // The SlotRecord::MAIN role can't be deleted
427 if ( $role === SlotRecord
::MAIN
) {
428 $this->dieWithError( [ 'apierror-compare-maintextrequired', $prefix ] );
431 // These parameters make no sense without text. Reject them to avoid
433 foreach ( [ 'section', 'contentmodel', 'contentformat' ] as $param ) {
434 if ( isset( $params["{$prefix}{$param}-{$role}"] ) ) {
435 $this->dieWithError( [
436 'apierror-compare-notext',
437 wfEscapeWikiText( "{$prefix}{$param}-{$role}" ),
438 wfEscapeWikiText( "{$prefix}text-{$role}" ),
443 $newRev->removeSlot( $role );
447 $model = $params["{$prefix}contentmodel-{$role}"];
448 $format = $params["{$prefix}contentformat-{$role}"];
450 if ( !$model && $rev && $rev->hasSlot( $role ) ) {
451 $model = $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
453 if ( !$model && $title && $role === SlotRecord
::MAIN
) {
454 // @todo: Use SlotRoleRegistry and do this for all slots
455 $model = $title->getContentModel();
458 $model = $this->guessModel( $role );
461 $model = CONTENT_MODEL_WIKITEXT
;
462 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
466 $content = ContentHandler
::makeContent( $text, $title, $model, $format );
467 } catch ( MWContentSerializationException
$ex ) {
468 $this->dieWithException( $ex, [
469 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
473 if ( $params["{$prefix}pst"] ) {
475 $this->dieWithError( 'apierror-compare-no-title' );
477 $popts = ParserOptions
::newFromContext( $this->getContext() );
478 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
481 $section = $params["{$prefix}section-{$role}"];
482 if ( $section !== null && $section !== '' ) {
484 $this->dieWithError( "apierror-compare-no{$prefix}revision" );
486 $oldContent = $rev->getContent( $role, RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
487 if ( !$oldContent ) {
489 [ 'apierror-missingcontent-revid-role', $rev->getId(), wfEscapeWikiText( $role ) ],
493 if ( !$oldContent->getContentHandler()->supportsSections() ) {
494 $this->dieWithError( [ 'apierror-sectionsnotsupported', $content->getModel() ] );
497 $content = $oldContent->replaceSection( $section, $content, '' );
498 } catch ( Exception
$ex ) {
499 // Probably a content model mismatch.
503 $this->dieWithError( [ 'apierror-sectionreplacefailed' ] );
507 // Deprecated 'fromsection'/'tosection'
508 if ( $role === SlotRecord
::MAIN
&& isset( $params["{$prefix}section"] ) ) {
509 $section = $params["{$prefix}section"];
510 $content = $content->getSection( $section );
513 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
514 "nosuch{$prefix}section"
519 $newRev->setContent( $role, $content );
521 return [ $newRev, $rev, null ];
525 * Set value fields from a RevisionRecord object
527 * @param array &$vals Result array to set data into
528 * @param string $prefix 'from' or 'to'
529 * @param RevisionRecord|null $rev
531 private function setVals( &$vals, $prefix, $rev ) {
533 $title = $rev->getPageAsLinkTarget();
534 if ( isset( $this->props
['ids'] ) ) {
535 $vals["{$prefix}id"] = $title->getArticleID();
536 $vals["{$prefix}revid"] = $rev->getId();
538 if ( isset( $this->props
['title'] ) ) {
539 ApiQueryBase
::addTitleInfo( $vals, $title, $prefix );
541 if ( isset( $this->props
['size'] ) ) {
542 $vals["{$prefix}size"] = $rev->getSize();
546 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
547 $vals["{$prefix}texthidden"] = true;
551 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
552 $vals["{$prefix}userhidden"] = true;
555 if ( isset( $this->props
['user'] ) ) {
556 $user = $rev->getUser( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
558 $vals["{$prefix}user"] = $user->getName();
559 $vals["{$prefix}userid"] = $user->getId();
563 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) ) {
564 $vals["{$prefix}commenthidden"] = true;
567 if ( isset( $this->props
['comment'] ) ||
isset( $this->props
['parsedcomment'] ) ) {
568 $comment = $rev->getComment( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
569 if ( $comment !== null ) {
570 if ( isset( $this->props
['comment'] ) ) {
571 $vals["{$prefix}comment"] = $comment->text
;
573 $vals["{$prefix}parsedcomment"] = Linker
::formatComment(
574 $comment->text
, Title
::newFromLinkTarget( $title )
580 $this->getMain()->setCacheMode( 'private' );
581 if ( $rev->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
582 $vals["{$prefix}suppressed"] = true;
586 if ( !empty( $rev->isArchive
) ) {
587 $this->getMain()->setCacheMode( 'private' );
588 $vals["{$prefix}archive"] = true;
593 public function getAllowedParams() {
594 $slotRoles = $this->slotRoleRegistry
->getKnownRoles();
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',