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 /** @var \MediaWiki\Revision\SlotRoleRegistry */
34 private $slotRoleRegistry;
36 private $guessedTitle = false, $props;
38 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
39 parent
::__construct( $mainModule, $moduleName, $modulePrefix );
40 $this->revisionStore
= MediaWikiServices
::getInstance()->getRevisionStore();
41 $this->slotRoleRegistry
= MediaWikiServices
::getInstance()->getSlotRoleRegistry();
44 public function execute() {
45 $params = $this->extractRequestParams();
47 // Parameter validation
48 $this->requireAtLeastOneParameter(
49 $params, 'fromtitle', 'fromid', 'fromrev', 'fromtext', 'fromslots'
51 $this->requireAtLeastOneParameter(
52 $params, 'totitle', 'toid', 'torev', 'totext', 'torelative', 'toslots'
55 $this->props
= array_flip( $params['prop'] );
57 // Cache responses publicly by default. This may be overridden later.
58 $this->getMain()->setCacheMode( 'public' );
60 // Get the 'from' RevisionRecord
61 list( $fromRev, $fromRelRev, $fromValsRev ) = $this->getDiffRevision( 'from', $params );
63 // Get the 'to' RevisionRecord
64 if ( $params['torelative'] !== null ) {
66 $this->dieWithError( 'apierror-compare-relative-to-nothing' );
68 switch ( $params['torelative'] ) {
70 // Swap 'from' and 'to'
71 list( $toRev, $toRelRev2, $toValsRev ) = [ $fromRev, $fromRelRev, $fromValsRev ];
72 $fromRev = $this->revisionStore
->getPreviousRevision( $fromRelRev );
73 $fromRelRev = $fromRev;
74 $fromValsRev = $fromRev;
78 $toRev = $this->revisionStore
->getNextRevision( $fromRelRev );
84 $title = $fromRelRev->getPageAsLinkTarget();
85 $toRev = $this->revisionStore
->getRevisionByTitle( $title );
87 $title = Title
::newFromLinkTarget( $title );
89 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
97 list( $toRev, $toRelRev, $toValsRev ) = $this->getDiffRevision( 'to', $params );
100 // Handle missing from or to revisions
101 if ( !$fromRev ||
!$toRev ) {
102 $this->dieWithError( 'apierror-baddiff' );
106 if ( !$fromRev->audienceCan(
107 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
109 $this->dieWithError( [ 'apierror-missingcontent-revid', $fromRev->getId() ], 'missingcontent' );
111 if ( !$toRev->audienceCan(
112 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
114 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
118 $context = new DerivativeContext( $this->getContext() );
119 if ( $fromRelRev && $fromRelRev->getPageAsLinkTarget() ) {
120 $context->setTitle( Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() ) );
121 } elseif ( $toRelRev && $toRelRev->getPageAsLinkTarget() ) {
122 $context->setTitle( Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() ) );
124 $guessedTitle = $this->guessTitle();
125 if ( $guessedTitle ) {
126 $context->setTitle( $guessedTitle );
129 $de = new DifferenceEngine( $context );
130 $de->setRevisions( $fromRev, $toRev );
131 if ( $params['slots'] === null ) {
132 $difftext = $de->getDiffBody();
133 if ( $difftext === false ) {
134 $this->dieWithError( 'apierror-baddiff' );
138 foreach ( $params['slots'] as $role ) {
139 $difftext[$role] = $de->getDiffBodyForRole( $role );
143 // Fill in the response
145 $this->setVals( $vals, 'from', $fromValsRev );
146 $this->setVals( $vals, 'to', $toValsRev );
148 if ( isset( $this->props
['rel'] ) ) {
149 if ( !$fromRev instanceof MutableRevisionRecord
) {
150 $rev = $this->revisionStore
->getPreviousRevision( $fromRev );
152 $vals['prev'] = $rev->getId();
155 if ( !$toRev instanceof MutableRevisionRecord
) {
156 $rev = $this->revisionStore
->getNextRevision( $toRev );
158 $vals['next'] = $rev->getId();
163 if ( isset( $this->props
['diffsize'] ) ) {
164 $vals['diffsize'] = 0;
165 foreach ( (array)$difftext as $text ) {
166 $vals['diffsize'] +
= strlen( $text );
169 if ( isset( $this->props
['diff'] ) ) {
170 if ( is_array( $difftext ) ) {
171 ApiResult
::setArrayType( $difftext, 'kvp', 'diff' );
172 $vals['bodies'] = $difftext;
174 ApiResult
::setContentValue( $vals, 'body', $difftext );
178 // Diffs can be really big and there's little point in having
179 // ApiResult truncate it to an empty response since the diff is the
180 // whole reason this module exists. So pass NO_SIZE_CHECK here.
181 $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult
::NO_SIZE_CHECK
);
185 * Load a revision by ID
187 * Falls back to checking the archive table if appropriate.
190 * @return RevisionRecord|null
192 private function getRevisionById( $id ) {
193 $rev = $this->revisionStore
->getRevisionById( $id );
194 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
195 // Try the 'archive' table
196 $arQuery = $this->revisionStore
->getArchiveQueryInfo();
197 $row = $this->getDB()->selectRow(
201 [ 'ar_namespace', 'ar_title' ]
203 [ 'ar_rev_id' => $id ],
209 $rev = $this->revisionStore
->newRevisionFromArchiveRow( $row );
210 $rev->isArchive
= true;
217 * Guess an appropriate default Title for this request
221 private function guessTitle() {
222 if ( $this->guessedTitle
!== false ) {
223 return $this->guessedTitle
;
226 $this->guessedTitle
= null;
227 $params = $this->extractRequestParams();
229 foreach ( [ 'from', 'to' ] as $prefix ) {
230 if ( $params["{$prefix}rev"] !== null ) {
231 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
233 $this->guessedTitle
= Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
238 if ( $params["{$prefix}title"] !== null ) {
239 $title = Title
::newFromText( $params["{$prefix}title"] );
240 if ( $title && !$title->isExternal() ) {
241 $this->guessedTitle
= $title;
246 if ( $params["{$prefix}id"] !== null ) {
247 $title = Title
::newFromID( $params["{$prefix}id"] );
249 $this->guessedTitle
= $title;
255 return $this->guessedTitle
;
259 * Guess an appropriate default content model for this request
260 * @param string $role Slot for which to guess the model
261 * @return string|null Guessed content model
263 private function guessModel( $role ) {
264 $params = $this->extractRequestParams();
267 foreach ( [ 'from', 'to' ] as $prefix ) {
268 if ( $params["{$prefix}rev"] !== null ) {
269 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
271 if ( $rev->hasSlot( $role ) ) {
272 return $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
278 $guessedTitle = $this->guessTitle();
279 if ( $guessedTitle ) {
280 return $this->slotRoleRegistry
->getRoleHandler( $role )->getDefaultModel( $guessedTitle );
283 if ( isset( $params["fromcontentmodel-$role"] ) ) {
284 return $params["fromcontentmodel-$role"];
286 if ( isset( $params["tocontentmodel-$role"] ) ) {
287 return $params["tocontentmodel-$role"];
290 if ( $role === SlotRecord
::MAIN
) {
291 if ( isset( $params['fromcontentmodel'] ) ) {
292 return $params['fromcontentmodel'];
294 if ( isset( $params['tocontentmodel'] ) ) {
295 return $params['tocontentmodel'];
303 * Get the RevisionRecord for one side of the diff
305 * This uses the appropriate set of parameters to determine what content
308 * Returns three values:
309 * - A RevisionRecord holding the content
310 * - The revision specified, if any, even if content was supplied
311 * - The revision to pass to setVals(), if any
313 * @param string $prefix 'from' or 'to'
314 * @param array $params
315 * @return array [ RevisionRecord|null, RevisionRecord|null, RevisionRecord|null ]
317 private function getDiffRevision( $prefix, array $params ) {
318 // Back compat params
319 $this->requireMaxOneParameter( $params, "{$prefix}text", "{$prefix}slots" );
320 $this->requireMaxOneParameter( $params, "{$prefix}section", "{$prefix}slots" );
321 if ( $params["{$prefix}text"] !== null ) {
322 $params["{$prefix}slots"] = [ SlotRecord
::MAIN
];
323 $params["{$prefix}text-main"] = $params["{$prefix}text"];
324 $params["{$prefix}section-main"] = null;
325 $params["{$prefix}contentmodel-main"] = $params["{$prefix}contentmodel"];
326 $params["{$prefix}contentformat-main"] = $params["{$prefix}contentformat"];
331 $suppliedContent = $params["{$prefix}slots"] !== null;
333 // Get the revision and title, if applicable
335 if ( $params["{$prefix}rev"] !== null ) {
336 $revId = $params["{$prefix}rev"];
337 } elseif ( $params["{$prefix}title"] !== null ||
$params["{$prefix}id"] !== null ) {
338 if ( $params["{$prefix}title"] !== null ) {
339 $title = Title
::newFromText( $params["{$prefix}title"] );
340 if ( !$title ||
$title->isExternal() ) {
342 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
346 $title = Title
::newFromID( $params["{$prefix}id"] );
348 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
351 $revId = $title->getLatestRevID();
354 // Only die here if we're not using supplied text
355 if ( !$suppliedContent ) {
356 if ( $title->exists() ) {
358 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
362 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
369 if ( $revId !== null ) {
370 $rev = $this->getRevisionById( $revId );
372 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
374 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
376 // If we don't have supplied content, return here. Otherwise,
377 // continue on below with the supplied content.
378 if ( !$suppliedContent ) {
381 // Deprecated 'fromsection'/'tosection'
382 if ( isset( $params["{$prefix}section"] ) ) {
383 $section = $params["{$prefix}section"];
384 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
385 $content = $rev->getContent( SlotRecord
::MAIN
, RevisionRecord
::FOR_THIS_USER
,
389 [ 'apierror-missingcontent-revid-role', $rev->getId(), SlotRecord
::MAIN
], 'missingcontent'
392 $content = $content ?
$content->getSection( $section ) : null;
395 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
396 "nosuch{$prefix}section"
399 $newRev->setContent( SlotRecord
::MAIN
, $content );
402 return [ $newRev, $rev, $rev ];
406 // Override $content based on supplied text
408 $title = $this->guessTitle();
411 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
413 $newRev = $this->revisionStore
->newMutableRevisionFromArray( [
414 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
417 foreach ( $params["{$prefix}slots"] as $role ) {
418 $text = $params["{$prefix}text-{$role}"];
419 if ( $text === null ) {
420 // The SlotRecord::MAIN role can't be deleted
421 if ( $role === SlotRecord
::MAIN
) {
422 $this->dieWithError( [ 'apierror-compare-maintextrequired', $prefix ] );
425 // These parameters make no sense without text. Reject them to avoid
427 foreach ( [ 'section', 'contentmodel', 'contentformat' ] as $param ) {
428 if ( isset( $params["{$prefix}{$param}-{$role}"] ) ) {
429 $this->dieWithError( [
430 'apierror-compare-notext',
431 wfEscapeWikiText( "{$prefix}{$param}-{$role}" ),
432 wfEscapeWikiText( "{$prefix}text-{$role}" ),
437 $newRev->removeSlot( $role );
441 $model = $params["{$prefix}contentmodel-{$role}"];
442 $format = $params["{$prefix}contentformat-{$role}"];
444 if ( !$model && $rev && $rev->hasSlot( $role ) ) {
445 $model = $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
447 if ( !$model && $title && $role === SlotRecord
::MAIN
) {
448 // @todo: Use SlotRoleRegistry and do this for all slots
449 $model = $title->getContentModel();
452 $model = $this->guessModel( $role );
455 $model = CONTENT_MODEL_WIKITEXT
;
456 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
460 $content = ContentHandler
::makeContent( $text, $title, $model, $format );
461 } catch ( MWContentSerializationException
$ex ) {
462 $this->dieWithException( $ex, [
463 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
467 if ( $params["{$prefix}pst"] ) {
469 $this->dieWithError( 'apierror-compare-no-title' );
471 $popts = ParserOptions
::newFromContext( $this->getContext() );
472 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
475 $section = $params["{$prefix}section-{$role}"];
476 if ( $section !== null && $section !== '' ) {
478 $this->dieWithError( "apierror-compare-no{$prefix}revision" );
480 $oldContent = $rev->getContent( $role, RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
481 if ( !$oldContent ) {
483 [ 'apierror-missingcontent-revid-role', $rev->getId(), wfEscapeWikiText( $role ) ],
487 if ( !$oldContent->getContentHandler()->supportsSections() ) {
488 $this->dieWithError( [ 'apierror-sectionsnotsupported', $content->getModel() ] );
491 $content = $oldContent->replaceSection( $section, $content, '' );
492 } catch ( Exception
$ex ) {
493 // Probably a content model mismatch.
497 $this->dieWithError( [ 'apierror-sectionreplacefailed' ] );
501 // Deprecated 'fromsection'/'tosection'
502 if ( $role === SlotRecord
::MAIN
&& isset( $params["{$prefix}section"] ) ) {
503 $section = $params["{$prefix}section"];
504 $content = $content->getSection( $section );
507 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
508 "nosuch{$prefix}section"
513 $newRev->setContent( $role, $content );
515 return [ $newRev, $rev, null ];
519 * Set value fields from a RevisionRecord object
521 * @param array &$vals Result array to set data into
522 * @param string $prefix 'from' or 'to'
523 * @param RevisionRecord|null $rev
525 private function setVals( &$vals, $prefix, $rev ) {
527 $title = $rev->getPageAsLinkTarget();
528 if ( isset( $this->props
['ids'] ) ) {
529 $vals["{$prefix}id"] = $title->getArticleID();
530 $vals["{$prefix}revid"] = $rev->getId();
532 if ( isset( $this->props
['title'] ) ) {
533 ApiQueryBase
::addTitleInfo( $vals, $title, $prefix );
535 if ( isset( $this->props
['size'] ) ) {
536 $vals["{$prefix}size"] = $rev->getSize();
540 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
541 $vals["{$prefix}texthidden"] = true;
545 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
546 $vals["{$prefix}userhidden"] = true;
549 if ( isset( $this->props
['user'] ) ) {
550 $user = $rev->getUser( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
552 $vals["{$prefix}user"] = $user->getName();
553 $vals["{$prefix}userid"] = $user->getId();
557 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) ) {
558 $vals["{$prefix}commenthidden"] = true;
561 if ( isset( $this->props
['comment'] ) ||
isset( $this->props
['parsedcomment'] ) ) {
562 $comment = $rev->getComment( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
563 if ( $comment !== null ) {
564 if ( isset( $this->props
['comment'] ) ) {
565 $vals["{$prefix}comment"] = $comment->text
;
567 $vals["{$prefix}parsedcomment"] = Linker
::formatComment(
568 $comment->text
, Title
::newFromLinkTarget( $title )
574 $this->getMain()->setCacheMode( 'private' );
575 if ( $rev->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
576 $vals["{$prefix}suppressed"] = true;
580 if ( !empty( $rev->isArchive
) ) {
581 $this->getMain()->setCacheMode( 'private' );
582 $vals["{$prefix}archive"] = true;
587 public function getAllowedParams() {
588 $slotRoles = $this->slotRoleRegistry
->getKnownRoles();
589 sort( $slotRoles, SORT_STRING
);
591 // Parameters for the 'from' and 'to' content
595 ApiBase
::PARAM_TYPE
=> 'integer'
598 ApiBase
::PARAM_TYPE
=> 'integer'
602 ApiBase
::PARAM_TYPE
=> $slotRoles,
603 ApiBase
::PARAM_ISMULTI
=> true,
606 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
607 ApiBase
::PARAM_TYPE
=> 'text',
609 'section-{slot}' => [
610 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
611 ApiBase
::PARAM_TYPE
=> 'string',
613 'contentformat-{slot}' => [
614 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
615 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
617 'contentmodel-{slot}' => [
618 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
619 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
624 ApiBase
::PARAM_TYPE
=> 'text',
625 ApiBase
::PARAM_DEPRECATED
=> true,
628 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
629 ApiBase
::PARAM_DEPRECATED
=> true,
632 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
633 ApiBase
::PARAM_DEPRECATED
=> true,
636 ApiBase
::PARAM_DFLT
=> null,
637 ApiBase
::PARAM_DEPRECATED
=> true,
642 foreach ( $fromToParams as $k => $v ) {
643 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
644 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'fromslots';
648 foreach ( $fromToParams as $k => $v ) {
649 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
650 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'toslots';
655 $ret = wfArrayInsertAfter(
657 [ 'torelative' => [ ApiBase
::PARAM_TYPE
=> [ 'prev', 'next', 'cur' ], ] ],
662 ApiBase
::PARAM_DFLT
=> 'diff|ids|title',
663 ApiBase
::PARAM_TYPE
=> [
674 ApiBase
::PARAM_ISMULTI
=> true,
675 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
679 ApiBase
::PARAM_TYPE
=> $slotRoles,
680 ApiBase
::PARAM_ISMULTI
=> true,
681 ApiBase
::PARAM_ALL
=> true,
687 protected function getExamplesMessages() {
689 'action=compare&fromrev=1&torev=2'
690 => 'apihelp-compare-example-1',