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\Storage\MutableRevisionRecord
;
24 use MediaWiki\Storage\RevisionRecord
;
25 use MediaWiki\Storage\RevisionStore
;
26 use MediaWiki\Storage\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, $toRelRev2, $toValsRev ) = [ $fromRev, $fromRelRev, $fromValsRev ];
68 $fromRev = $this->revisionStore
->getPreviousRevision( $fromRelRev );
69 $fromRelRev = $fromRev;
70 $fromValsRev = $fromRev;
74 $toRev = $this->revisionStore
->getNextRevision( $fromRelRev );
80 $title = $fromRelRev->getPageAsLinkTarget();
81 $toRev = $this->revisionStore
->getRevisionByTitle( $title );
83 $title = Title
::newFromLinkTarget( $title );
85 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
93 list( $toRev, $toRelRev, $toValsRev ) = $this->getDiffRevision( 'to', $params );
96 // Handle missing from or to revisions
97 if ( !$fromRev ||
!$toRev ) {
98 $this->dieWithError( 'apierror-baddiff' );
102 if ( !$fromRev->audienceCan(
103 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
105 $this->dieWithError( [ 'apierror-missingcontent-revid', $fromRev->getId() ], 'missingcontent' );
107 if ( !$toRev->audienceCan(
108 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
110 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
114 $context = new DerivativeContext( $this->getContext() );
115 if ( $fromRelRev && $fromRelRev->getPageAsLinkTarget() ) {
116 $context->setTitle( Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() ) );
117 } elseif ( $toRelRev && $toRelRev->getPageAsLinkTarget() ) {
118 $context->setTitle( Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() ) );
120 $guessedTitle = $this->guessTitle();
121 if ( $guessedTitle ) {
122 $context->setTitle( $guessedTitle );
125 $de = new DifferenceEngine( $context );
126 $de->setRevisions( $fromRev, $toRev );
127 if ( $params['slots'] === null ) {
128 $difftext = $de->getDiffBody();
129 if ( $difftext === false ) {
130 $this->dieWithError( 'apierror-baddiff' );
134 foreach ( $params['slots'] as $role ) {
135 $difftext[$role] = $de->getDiffBodyForRole( $role );
139 // Fill in the response
141 $this->setVals( $vals, 'from', $fromValsRev );
142 $this->setVals( $vals, 'to', $toValsRev );
144 if ( isset( $this->props
['rel'] ) ) {
145 if ( !$fromRev instanceof MutableRevisionRecord
) {
146 $rev = $this->revisionStore
->getPreviousRevision( $fromRev );
148 $vals['prev'] = $rev->getId();
151 if ( !$toRev instanceof MutableRevisionRecord
) {
152 $rev = $this->revisionStore
->getNextRevision( $toRev );
154 $vals['next'] = $rev->getId();
159 if ( isset( $this->props
['diffsize'] ) ) {
160 $vals['diffsize'] = 0;
161 foreach ( (array)$difftext as $text ) {
162 $vals['diffsize'] +
= strlen( $text );
165 if ( isset( $this->props
['diff'] ) ) {
166 if ( is_array( $difftext ) ) {
167 ApiResult
::setArrayType( $difftext, 'kvp', 'diff' );
168 $vals['bodies'] = $difftext;
170 ApiResult
::setContentValue( $vals, 'body', $difftext );
174 // Diffs can be really big and there's little point in having
175 // ApiResult truncate it to an empty response since the diff is the
176 // whole reason this module exists. So pass NO_SIZE_CHECK here.
177 $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult
::NO_SIZE_CHECK
);
181 * Load a revision by ID
183 * Falls back to checking the archive table if appropriate.
186 * @return RevisionRecord|null
188 private function getRevisionById( $id ) {
189 $rev = $this->revisionStore
->getRevisionById( $id );
190 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
191 // Try the 'archive' table
192 $arQuery = $this->revisionStore
->getArchiveQueryInfo();
193 $row = $this->getDB()->selectRow(
197 [ 'ar_namespace', 'ar_title' ]
199 [ 'ar_rev_id' => $id ],
205 $rev = $this->revisionStore
->newRevisionFromArchiveRow( $row );
206 $rev->isArchive
= true;
213 * Guess an appropriate default Title for this request
217 private function guessTitle() {
218 if ( $this->guessedTitle
!== false ) {
219 return $this->guessedTitle
;
222 $this->guessedTitle
= null;
223 $params = $this->extractRequestParams();
225 foreach ( [ 'from', 'to' ] as $prefix ) {
226 if ( $params["{$prefix}rev"] !== null ) {
227 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
229 $this->guessedTitle
= Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
234 if ( $params["{$prefix}title"] !== null ) {
235 $title = Title
::newFromText( $params["{$prefix}title"] );
236 if ( $title && !$title->isExternal() ) {
237 $this->guessedTitle
= $title;
242 if ( $params["{$prefix}id"] !== null ) {
243 $title = Title
::newFromID( $params["{$prefix}id"] );
245 $this->guessedTitle
= $title;
251 return $this->guessedTitle
;
255 * Guess an appropriate default content model for this request
256 * @param string $role Slot for which to guess the model
257 * @return string|null Guessed content model
259 private function guessModel( $role ) {
260 $params = $this->extractRequestParams();
263 foreach ( [ 'from', 'to' ] as $prefix ) {
264 if ( $params["{$prefix}rev"] !== null ) {
265 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
267 if ( $rev->hasSlot( $role ) ) {
268 return $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
274 $guessedTitle = $this->guessTitle();
275 if ( $guessedTitle && $role === SlotRecord
::MAIN
) {
276 // @todo: Use SlotRoleRegistry and do this for all slots
277 return $guessedTitle->getContentModel();
280 if ( isset( $params["fromcontentmodel-$role"] ) ) {
281 return $params["fromcontentmodel-$role"];
283 if ( isset( $params["tocontentmodel-$role"] ) ) {
284 return $params["tocontentmodel-$role"];
287 if ( $role === SlotRecord
::MAIN
) {
288 if ( isset( $params['fromcontentmodel'] ) ) {
289 return $params['fromcontentmodel'];
291 if ( isset( $params['tocontentmodel'] ) ) {
292 return $params['tocontentmodel'];
300 * Get the RevisionRecord for one side of the diff
302 * This uses the appropriate set of parameters to determine what content
305 * Returns three values:
306 * - A RevisionRecord holding the content
307 * - The revision specified, if any, even if content was supplied
308 * - The revision to pass to setVals(), if any
310 * @param string $prefix 'from' or 'to'
311 * @param array $params
312 * @return array [ RevisionRecord|null, RevisionRecord|null, RevisionRecord|null ]
314 private function getDiffRevision( $prefix, array $params ) {
315 // Back compat params
316 $this->requireMaxOneParameter( $params, "{$prefix}text", "{$prefix}slots" );
317 $this->requireMaxOneParameter( $params, "{$prefix}section", "{$prefix}slots" );
318 if ( $params["{$prefix}text"] !== null ) {
319 $params["{$prefix}slots"] = [ SlotRecord
::MAIN
];
320 $params["{$prefix}text-main"] = $params["{$prefix}text"];
321 $params["{$prefix}section-main"] = null;
322 $params["{$prefix}contentmodel-main"] = $params["{$prefix}contentmodel"];
323 $params["{$prefix}contentformat-main"] = $params["{$prefix}contentformat"];
328 $suppliedContent = $params["{$prefix}slots"] !== null;
330 // Get the revision and title, if applicable
332 if ( $params["{$prefix}rev"] !== null ) {
333 $revId = $params["{$prefix}rev"];
334 } elseif ( $params["{$prefix}title"] !== null ||
$params["{$prefix}id"] !== null ) {
335 if ( $params["{$prefix}title"] !== null ) {
336 $title = Title
::newFromText( $params["{$prefix}title"] );
337 if ( !$title ||
$title->isExternal() ) {
339 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
343 $title = Title
::newFromID( $params["{$prefix}id"] );
345 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
348 $revId = $title->getLatestRevID();
351 // Only die here if we're not using supplied text
352 if ( !$suppliedContent ) {
353 if ( $title->exists() ) {
355 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
359 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
366 if ( $revId !== null ) {
367 $rev = $this->getRevisionById( $revId );
369 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
371 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
373 // If we don't have supplied content, return here. Otherwise,
374 // continue on below with the supplied content.
375 if ( !$suppliedContent ) {
378 // Deprecated 'fromsection'/'tosection'
379 if ( isset( $params["{$prefix}section"] ) ) {
380 $section = $params["{$prefix}section"];
381 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
382 $content = $rev->getContent( SlotRecord
::MAIN
, RevisionRecord
::FOR_THIS_USER
,
386 [ 'apierror-missingcontent-revid-role', $rev->getId(), SlotRecord
::MAIN
], 'missingcontent'
389 $content = $content ?
$content->getSection( $section ) : null;
392 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
393 "nosuch{$prefix}section"
396 $newRev->setContent( SlotRecord
::MAIN
, $content );
399 return [ $newRev, $rev, $rev ];
403 // Override $content based on supplied text
405 $title = $this->guessTitle();
408 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
410 $newRev = $this->revisionStore
->newMutableRevisionFromArray( [
411 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
414 foreach ( $params["{$prefix}slots"] as $role ) {
415 $text = $params["{$prefix}text-{$role}"];
416 if ( $text === null ) {
417 // The SlotRecord::MAIN role can't be deleted
418 if ( $role === SlotRecord
::MAIN
) {
419 $this->dieWithError( [ 'apierror-compare-maintextrequired', $prefix ] );
422 // These parameters make no sense without text. Reject them to avoid
424 foreach ( [ 'section', 'contentmodel', 'contentformat' ] as $param ) {
425 if ( isset( $params["{$prefix}{$param}-{$role}"] ) ) {
426 $this->dieWithError( [
427 'apierror-compare-notext',
428 wfEscapeWikiText( "{$prefix}{$param}-{$role}" ),
429 wfEscapeWikiText( "{$prefix}text-{$role}" ),
434 $newRev->removeSlot( $role );
438 $model = $params["{$prefix}contentmodel-{$role}"];
439 $format = $params["{$prefix}contentformat-{$role}"];
441 if ( !$model && $rev && $rev->hasSlot( $role ) ) {
442 $model = $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
444 if ( !$model && $title && $role === SlotRecord
::MAIN
) {
445 // @todo: Use SlotRoleRegistry and do this for all slots
446 $model = $title->getContentModel();
449 $model = $this->guessModel( $role );
452 $model = CONTENT_MODEL_WIKITEXT
;
453 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
457 $content = ContentHandler
::makeContent( $text, $title, $model, $format );
458 } catch ( MWContentSerializationException
$ex ) {
459 $this->dieWithException( $ex, [
460 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
464 if ( $params["{$prefix}pst"] ) {
466 $this->dieWithError( 'apierror-compare-no-title' );
468 $popts = ParserOptions
::newFromContext( $this->getContext() );
469 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
472 $section = $params["{$prefix}section-{$role}"];
473 if ( $section !== null && $section !== '' ) {
475 $this->dieWithError( "apierror-compare-no{$prefix}revision" );
477 $oldContent = $rev->getContent( $role, RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
478 if ( !$oldContent ) {
480 [ 'apierror-missingcontent-revid-role', $rev->getId(), wfEscapeWikiText( $role ) ],
484 if ( !$oldContent->getContentHandler()->supportsSections() ) {
485 $this->dieWithError( [ 'apierror-sectionsnotsupported', $content->getModel() ] );
488 $content = $oldContent->replaceSection( $section, $content, '' );
489 } catch ( Exception
$ex ) {
490 // Probably a content model mismatch.
494 $this->dieWithError( [ 'apierror-sectionreplacefailed' ] );
498 // Deprecated 'fromsection'/'tosection'
499 if ( $role === SlotRecord
::MAIN
&& isset( $params["{$prefix}section"] ) ) {
500 $section = $params["{$prefix}section"];
501 $content = $content->getSection( $section );
504 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
505 "nosuch{$prefix}section"
510 $newRev->setContent( $role, $content );
512 return [ $newRev, $rev, null ];
516 * Set value fields from a RevisionRecord object
518 * @param array &$vals Result array to set data into
519 * @param string $prefix 'from' or 'to'
520 * @param RevisionRecord|null $rev
522 private function setVals( &$vals, $prefix, $rev ) {
524 $title = $rev->getPageAsLinkTarget();
525 if ( isset( $this->props
['ids'] ) ) {
526 $vals["{$prefix}id"] = $title->getArticleID();
527 $vals["{$prefix}revid"] = $rev->getId();
529 if ( isset( $this->props
['title'] ) ) {
530 ApiQueryBase
::addTitleInfo( $vals, $title, $prefix );
532 if ( isset( $this->props
['size'] ) ) {
533 $vals["{$prefix}size"] = $rev->getSize();
537 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
538 $vals["{$prefix}texthidden"] = true;
542 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
543 $vals["{$prefix}userhidden"] = true;
546 if ( isset( $this->props
['user'] ) ) {
547 $user = $rev->getUser( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
549 $vals["{$prefix}user"] = $user->getName();
550 $vals["{$prefix}userid"] = $user->getId();
554 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) ) {
555 $vals["{$prefix}commenthidden"] = true;
558 if ( isset( $this->props
['comment'] ) ||
isset( $this->props
['parsedcomment'] ) ) {
559 $comment = $rev->getComment( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
560 if ( $comment !== null ) {
561 if ( isset( $this->props
['comment'] ) ) {
562 $vals["{$prefix}comment"] = $comment->text
;
564 $vals["{$prefix}parsedcomment"] = Linker
::formatComment(
565 $comment->text
, Title
::newFromLinkTarget( $title )
571 $this->getMain()->setCacheMode( 'private' );
572 if ( $rev->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
573 $vals["{$prefix}suppressed"] = true;
577 if ( !empty( $rev->isArchive
) ) {
578 $this->getMain()->setCacheMode( 'private' );
579 $vals["{$prefix}archive"] = true;
584 public function getAllowedParams() {
585 $slotRoles = MediaWikiServices
::getInstance()->getSlotRoleStore()->getMap();
586 if ( !in_array( SlotRecord
::MAIN
, $slotRoles, true ) ) {
587 $slotRoles[] = SlotRecord
::MAIN
;
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',