Add part to update ctd_user_defined in populateChangeTagDef
[lhc/web/wiklou.git] / includes / page / Article.php
1 <?php
2 /**
3 * User interface for page actions.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22 use MediaWiki\MediaWikiServices;
23
24 /**
25 * Class for viewing MediaWiki article and history.
26 *
27 * This maintains WikiPage functions for backwards compatibility.
28 *
29 * @todo Move and rewrite code to an Action class
30 *
31 * See design.txt for an overview.
32 * Note: edit user interface and cache support functions have been
33 * moved to separate EditPage and HTMLFileCache classes.
34 */
35 class Article implements Page {
36 /**
37 * @var IContextSource|null The context this Article is executed in.
38 * If null, REquestContext::getMain() is used.
39 */
40 protected $mContext;
41
42 /** @var WikiPage The WikiPage object of this instance */
43 protected $mPage;
44
45 /**
46 * @var ParserOptions|null ParserOptions object for $wgUser articles.
47 * Initialized by getParserOptions by calling $this->mPage->makeParserOptions().
48 */
49 public $mParserOptions;
50
51 /**
52 * @var string|null Text of the revision we are working on
53 * @todo BC cruft
54 */
55 public $mContent;
56
57 /**
58 * @var Content|null Content of the revision we are working on.
59 * Initialized by fetchContentObject().
60 * @since 1.21
61 */
62 public $mContentObject;
63
64 /** @var bool Is the content ($mContent) already loaded? */
65 public $mContentLoaded = false;
66
67 /** @var int|null The oldid of the article that is to be shown, 0 for the current revision */
68 public $mOldId;
69
70 /** @var Title|null Title from which we were redirected here, if any. */
71 public $mRedirectedFrom = null;
72
73 /** @var string|bool URL to redirect to or false if none */
74 public $mRedirectUrl = false;
75
76 /** @var int Revision ID of revision we are working on */
77 public $mRevIdFetched = 0;
78
79 /**
80 * @var Revision|null Revision we are working on. Initialized by getOldIDFromRequest()
81 * or fetchContentObject().
82 */
83 public $mRevision = null;
84
85 /**
86 * @var ParserOutput|null|false The ParserOutput generated for viewing the page,
87 * initialized by view(). If no ParserOutput could be generated, this is set to false.
88 */
89 public $mParserOutput;
90
91 /**
92 * @var bool Whether render() was called. With the way subclasses work
93 * here, there doesn't seem to be any other way to stop calling
94 * OutputPage::enableSectionEditLinks() and still have it work as it did before.
95 */
96 private $disableSectionEditForRender = false;
97
98 /**
99 * Constructor and clear the article
100 * @param Title $title Reference to a Title object.
101 * @param int|null $oldId Revision ID, null to fetch from request, zero for current
102 */
103 public function __construct( Title $title, $oldId = null ) {
104 $this->mOldId = $oldId;
105 $this->mPage = $this->newPage( $title );
106 }
107
108 /**
109 * @param Title $title
110 * @return WikiPage
111 */
112 protected function newPage( Title $title ) {
113 return new WikiPage( $title );
114 }
115
116 /**
117 * Constructor from a page id
118 * @param int $id Article ID to load
119 * @return Article|null
120 */
121 public static function newFromID( $id ) {
122 $t = Title::newFromID( $id );
123 return $t == null ? null : new static( $t );
124 }
125
126 /**
127 * Create an Article object of the appropriate class for the given page.
128 *
129 * @param Title $title
130 * @param IContextSource $context
131 * @return Article
132 */
133 public static function newFromTitle( $title, IContextSource $context ) {
134 if ( NS_MEDIA == $title->getNamespace() ) {
135 // FIXME: where should this go?
136 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
137 }
138
139 $page = null;
140 Hooks::run( 'ArticleFromTitle', [ &$title, &$page, $context ] );
141 if ( !$page ) {
142 switch ( $title->getNamespace() ) {
143 case NS_FILE:
144 $page = new ImagePage( $title );
145 break;
146 case NS_CATEGORY:
147 $page = new CategoryPage( $title );
148 break;
149 default:
150 $page = new Article( $title );
151 }
152 }
153 $page->setContext( $context );
154
155 return $page;
156 }
157
158 /**
159 * Create an Article object of the appropriate class for the given page.
160 *
161 * @param WikiPage $page
162 * @param IContextSource $context
163 * @return Article
164 */
165 public static function newFromWikiPage( WikiPage $page, IContextSource $context ) {
166 $article = self::newFromTitle( $page->getTitle(), $context );
167 $article->mPage = $page; // override to keep process cached vars
168 return $article;
169 }
170
171 /**
172 * Get the page this view was redirected from
173 * @return Title|null
174 * @since 1.28
175 */
176 public function getRedirectedFrom() {
177 return $this->mRedirectedFrom;
178 }
179
180 /**
181 * Tell the page view functions that this view was redirected
182 * from another page on the wiki.
183 * @param Title $from
184 */
185 public function setRedirectedFrom( Title $from ) {
186 $this->mRedirectedFrom = $from;
187 }
188
189 /**
190 * Get the title object of the article
191 *
192 * @return Title Title object of this page
193 */
194 public function getTitle() {
195 return $this->mPage->getTitle();
196 }
197
198 /**
199 * Get the WikiPage object of this instance
200 *
201 * @since 1.19
202 * @return WikiPage
203 */
204 public function getPage() {
205 return $this->mPage;
206 }
207
208 /**
209 * Clear the object
210 */
211 public function clear() {
212 $this->mContentLoaded = false;
213
214 $this->mRedirectedFrom = null; # Title object if set
215 $this->mRevIdFetched = 0;
216 $this->mRedirectUrl = false;
217
218 $this->mPage->clear();
219 }
220
221 /**
222 * Returns a Content object representing the pages effective display content,
223 * not necessarily the revision's content!
224 *
225 * Note that getContent does not follow redirects anymore.
226 * If you need to fetch redirectable content easily, try
227 * the shortcut in WikiPage::getRedirectTarget()
228 *
229 * This function has side effects! Do not use this function if you
230 * only want the real revision text if any.
231 *
232 * @return Content Return the content of this revision
233 *
234 * @since 1.21
235 */
236 protected function getContentObject() {
237 if ( $this->mPage->getId() === 0 ) {
238 # If this is a MediaWiki:x message, then load the messages
239 # and return the message value for x.
240 if ( $this->getTitle()->getNamespace() == NS_MEDIAWIKI ) {
241 $text = $this->getTitle()->getDefaultMessageText();
242 if ( $text === false ) {
243 $text = '';
244 }
245
246 $content = ContentHandler::makeContent( $text, $this->getTitle() );
247 } else {
248 $message = $this->getContext()->getUser()->isLoggedIn() ? 'noarticletext' : 'noarticletextanon';
249 $content = new MessageContent( $message, null, 'parsemag' );
250 }
251 } else {
252 $this->fetchContentObject();
253 $content = $this->mContentObject;
254 }
255
256 return $content;
257 }
258
259 /**
260 * @return int The oldid of the article that is to be shown, 0 for the current revision
261 */
262 public function getOldID() {
263 if ( is_null( $this->mOldId ) ) {
264 $this->mOldId = $this->getOldIDFromRequest();
265 }
266
267 return $this->mOldId;
268 }
269
270 /**
271 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
272 *
273 * @return int The old id for the request
274 */
275 public function getOldIDFromRequest() {
276 $this->mRedirectUrl = false;
277
278 $request = $this->getContext()->getRequest();
279 $oldid = $request->getIntOrNull( 'oldid' );
280
281 if ( $oldid === null ) {
282 return 0;
283 }
284
285 if ( $oldid !== 0 ) {
286 # Load the given revision and check whether the page is another one.
287 # In that case, update this instance to reflect the change.
288 if ( $oldid === $this->mPage->getLatest() ) {
289 $this->mRevision = $this->mPage->getRevision();
290 } else {
291 $this->mRevision = Revision::newFromId( $oldid );
292 if ( $this->mRevision !== null ) {
293 // Revision title doesn't match the page title given?
294 if ( $this->mPage->getId() != $this->mRevision->getPage() ) {
295 $function = get_class( $this->mPage ). '::newFromID';
296 $this->mPage = $function( $this->mRevision->getPage() );
297 }
298 }
299 }
300 }
301
302 if ( $request->getVal( 'direction' ) == 'next' ) {
303 $nextid = $this->getTitle()->getNextRevisionID( $oldid );
304 if ( $nextid ) {
305 $oldid = $nextid;
306 $this->mRevision = null;
307 } else {
308 $this->mRedirectUrl = $this->getTitle()->getFullURL( 'redirect=no' );
309 }
310 } elseif ( $request->getVal( 'direction' ) == 'prev' ) {
311 $previd = $this->getTitle()->getPreviousRevisionID( $oldid );
312 if ( $previd ) {
313 $oldid = $previd;
314 $this->mRevision = null;
315 }
316 }
317
318 return $oldid;
319 }
320
321 /**
322 * Get text content object
323 * Does *NOT* follow redirects.
324 * @todo When is this null?
325 *
326 * @note Code that wants to retrieve page content from the database should
327 * use WikiPage::getContent().
328 *
329 * @return Content|null|bool
330 *
331 * @since 1.21
332 */
333 protected function fetchContentObject() {
334 if ( $this->mContentLoaded ) {
335 return $this->mContentObject;
336 }
337
338 $this->mContentLoaded = true;
339 $this->mContent = null;
340
341 $oldid = $this->getOldID();
342
343 # Pre-fill content with error message so that if something
344 # fails we'll have something telling us what we intended.
345 // XXX: this isn't page content but a UI message. horrible.
346 $this->mContentObject = new MessageContent( 'missing-revision', [ $oldid ] );
347
348 if ( $oldid ) {
349 # $this->mRevision might already be fetched by getOldIDFromRequest()
350 if ( !$this->mRevision ) {
351 $this->mRevision = Revision::newFromId( $oldid );
352 if ( !$this->mRevision ) {
353 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
354 return false;
355 }
356 }
357 } else {
358 $oldid = $this->mPage->getLatest();
359 if ( !$oldid ) {
360 wfDebug( __METHOD__ . " failed to find page data for title " .
361 $this->getTitle()->getPrefixedText() . "\n" );
362 return false;
363 }
364
365 # Update error message with correct oldid
366 $this->mContentObject = new MessageContent( 'missing-revision', [ $oldid ] );
367
368 $this->mRevision = $this->mPage->getRevision();
369
370 if ( !$this->mRevision ) {
371 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id $oldid\n" );
372 return false;
373 }
374 }
375
376 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
377 // We should instead work with the Revision object when we need it...
378 // Loads if user is allowed
379 $content = $this->mRevision->getContent(
380 Revision::FOR_THIS_USER,
381 $this->getContext()->getUser()
382 );
383
384 if ( !$content ) {
385 wfDebug( __METHOD__ . " failed to retrieve content of revision " .
386 $this->mRevision->getId() . "\n" );
387 return false;
388 }
389
390 $this->mContentObject = $content;
391 $this->mRevIdFetched = $this->mRevision->getId();
392
393 // Avoid PHP 7.1 warning of passing $this by reference
394 $articlePage = $this;
395
396 Hooks::run(
397 'ArticleAfterFetchContentObject',
398 [ &$articlePage, &$this->mContentObject ]
399 );
400
401 return $this->mContentObject;
402 }
403
404 /**
405 * Returns true if the currently-referenced revision is the current edit
406 * to this page (and it exists).
407 * @return bool
408 */
409 public function isCurrent() {
410 # If no oldid, this is the current version.
411 if ( $this->getOldID() == 0 ) {
412 return true;
413 }
414
415 return $this->mPage->exists() && $this->mRevision && $this->mRevision->isCurrent();
416 }
417
418 /**
419 * Get the fetched Revision object depending on request parameters or null
420 * on failure.
421 *
422 * @since 1.19
423 * @return Revision|null
424 */
425 public function getRevisionFetched() {
426 $this->fetchContentObject();
427
428 return $this->mRevision;
429 }
430
431 /**
432 * Use this to fetch the rev ID used on page views
433 *
434 * @return int Revision ID of last article revision
435 */
436 public function getRevIdFetched() {
437 if ( $this->mRevIdFetched ) {
438 return $this->mRevIdFetched;
439 } else {
440 return $this->mPage->getLatest();
441 }
442 }
443
444 /**
445 * This is the default action of the index.php entry point: just view the
446 * page of the given title.
447 */
448 public function view() {
449 global $wgUseFileCache, $wgDebugToolbar;
450
451 # Get variables from query string
452 # As side effect this will load the revision and update the title
453 # in a revision ID is passed in the request, so this should remain
454 # the first call of this method even if $oldid is used way below.
455 $oldid = $this->getOldID();
456
457 $user = $this->getContext()->getUser();
458 # Another whitelist check in case getOldID() is altering the title
459 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'read', $user );
460 if ( count( $permErrors ) ) {
461 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
462 throw new PermissionsError( 'read', $permErrors );
463 }
464
465 $outputPage = $this->getContext()->getOutput();
466 # getOldID() may as well want us to redirect somewhere else
467 if ( $this->mRedirectUrl ) {
468 $outputPage->redirect( $this->mRedirectUrl );
469 wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
470
471 return;
472 }
473
474 # If we got diff in the query, we want to see a diff page instead of the article.
475 if ( $this->getContext()->getRequest()->getCheck( 'diff' ) ) {
476 wfDebug( __METHOD__ . ": showing diff page\n" );
477 $this->showDiffPage();
478
479 return;
480 }
481
482 # Set page title (may be overridden by DISPLAYTITLE)
483 $outputPage->setPageTitle( $this->getTitle()->getPrefixedText() );
484
485 $outputPage->setArticleFlag( true );
486 # Allow frames by default
487 $outputPage->allowClickjacking();
488
489 $parserCache = MediaWikiServices::getInstance()->getParserCache();
490
491 $parserOptions = $this->getParserOptions();
492 $poOptions = [];
493 # Render printable version, use printable version cache
494 if ( $outputPage->isPrintable() ) {
495 $parserOptions->setIsPrintable( true );
496 $poOptions['enableSectionEditLinks'] = false;
497 } elseif ( $this->disableSectionEditForRender
498 || !$this->isCurrent() || !$this->getTitle()->quickUserCan( 'edit', $user )
499 ) {
500 $poOptions['enableSectionEditLinks'] = false;
501 }
502
503 # Try client and file cache
504 if ( !$wgDebugToolbar && $oldid === 0 && $this->mPage->checkTouched() ) {
505 # Try to stream the output from file cache
506 if ( $wgUseFileCache && $this->tryFileCache() ) {
507 wfDebug( __METHOD__ . ": done file cache\n" );
508 # tell wgOut that output is taken care of
509 $outputPage->disable();
510 $this->mPage->doViewUpdates( $user, $oldid );
511
512 return;
513 }
514 }
515
516 # Should the parser cache be used?
517 $useParserCache = $this->mPage->shouldCheckParserCache( $parserOptions, $oldid );
518 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
519 if ( $user->getStubThreshold() ) {
520 MediaWikiServices::getInstance()->getStatsdDataFactory()->increment( 'pcache_miss_stub' );
521 }
522
523 $this->showRedirectedFromHeader();
524 $this->showNamespaceHeader();
525
526 # Iterate through the possible ways of constructing the output text.
527 # Keep going until $outputDone is set, or we run out of things to do.
528 $pass = 0;
529 $outputDone = false;
530 $this->mParserOutput = false;
531
532 while ( !$outputDone && ++$pass ) {
533 switch ( $pass ) {
534 case 1:
535 // Avoid PHP 7.1 warning of passing $this by reference
536 $articlePage = $this;
537 Hooks::run( 'ArticleViewHeader', [ &$articlePage, &$outputDone, &$useParserCache ] );
538 break;
539 case 2:
540 # Early abort if the page doesn't exist
541 if ( !$this->mPage->exists() ) {
542 wfDebug( __METHOD__ . ": showing missing article\n" );
543 $this->showMissingArticle();
544 $this->mPage->doViewUpdates( $user );
545 return;
546 }
547
548 # Try the parser cache
549 if ( $useParserCache ) {
550 $this->mParserOutput = $parserCache->get( $this->mPage, $parserOptions );
551
552 if ( $this->mParserOutput !== false ) {
553 if ( $oldid ) {
554 wfDebug( __METHOD__ . ": showing parser cache contents for current rev permalink\n" );
555 $this->setOldSubtitle( $oldid );
556 } else {
557 wfDebug( __METHOD__ . ": showing parser cache contents\n" );
558 }
559 $outputPage->addParserOutput( $this->mParserOutput, $poOptions );
560 # Ensure that UI elements requiring revision ID have
561 # the correct version information.
562 $outputPage->setRevisionId( $this->mPage->getLatest() );
563 # Preload timestamp to avoid a DB hit
564 $cachedTimestamp = $this->mParserOutput->getTimestamp();
565 if ( $cachedTimestamp !== null ) {
566 $outputPage->setRevisionTimestamp( $cachedTimestamp );
567 $this->mPage->setTimestamp( $cachedTimestamp );
568 }
569 $outputDone = true;
570 }
571 }
572 break;
573 case 3:
574 # This will set $this->mRevision if needed
575 $this->fetchContentObject();
576
577 # Are we looking at an old revision
578 if ( $oldid && $this->mRevision ) {
579 $this->setOldSubtitle( $oldid );
580
581 if ( !$this->showDeletedRevisionHeader() ) {
582 wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
583 return;
584 }
585 }
586
587 # Ensure that UI elements requiring revision ID have
588 # the correct version information.
589 $outputPage->setRevisionId( $this->getRevIdFetched() );
590 # Preload timestamp to avoid a DB hit
591 $outputPage->setRevisionTimestamp( $this->mPage->getTimestamp() );
592
593 # Pages containing custom CSS or JavaScript get special treatment
594 if ( $this->getTitle()->isSiteConfigPage() || $this->getTitle()->isUserConfigPage() ) {
595 $dir = $this->getContext()->getLanguage()->getDir();
596 $lang = $this->getContext()->getLanguage()->getHtmlCode();
597
598 $outputPage->wrapWikiMsg(
599 "<div id='mw-clearyourcache' lang='$lang' dir='$dir' class='mw-content-$dir'>\n$1\n</div>",
600 'clearyourcache'
601 );
602 } elseif ( !Hooks::run( 'ArticleContentViewCustom',
603 [ $this->fetchContentObject(), $this->getTitle(), $outputPage ] )
604 ) {
605 # Allow extensions do their own custom view for certain pages
606 $outputDone = true;
607 }
608 break;
609 case 4:
610 # Run the parse, protected by a pool counter
611 wfDebug( __METHOD__ . ": doing uncached parse\n" );
612
613 $content = $this->getContentObject();
614 $poolArticleView = new PoolWorkArticleView( $this->getPage(), $parserOptions,
615 $this->getRevIdFetched(), $useParserCache, $content );
616
617 if ( !$poolArticleView->execute() ) {
618 $error = $poolArticleView->getError();
619 if ( $error ) {
620 $outputPage->clearHTML(); // for release() errors
621 $outputPage->enableClientCache( false );
622 $outputPage->setRobotPolicy( 'noindex,nofollow' );
623
624 $errortext = $error->getWikiText( false, 'view-pool-error' );
625 $outputPage->addWikiText( Html::errorBox( $errortext ) );
626 }
627 # Connection or timeout error
628 return;
629 }
630
631 $this->mParserOutput = $poolArticleView->getParserOutput();
632 $outputPage->addParserOutput( $this->mParserOutput, $poOptions );
633 if ( $content->getRedirectTarget() ) {
634 $outputPage->addSubtitle( "<span id=\"redirectsub\">" .
635 $this->getContext()->msg( 'redirectpagesub' )->parse() . "</span>" );
636 }
637
638 # Don't cache a dirty ParserOutput object
639 if ( $poolArticleView->getIsDirty() ) {
640 $outputPage->setCdnMaxage( 0 );
641 $outputPage->addHTML( "<!-- parser cache is expired, " .
642 "sending anyway due to pool overload-->\n" );
643 }
644
645 $outputDone = true;
646 break;
647 # Should be unreachable, but just in case...
648 default:
649 break 2;
650 }
651 }
652
653 # Get the ParserOutput actually *displayed* here.
654 # Note that $this->mParserOutput is the *current*/oldid version output.
655 $pOutput = ( $outputDone instanceof ParserOutput )
656 ? $outputDone // object fetched by hook
657 : $this->mParserOutput ?: null; // ParserOutput or null, avoid false
658
659 # Adjust title for main page & pages with displaytitle
660 if ( $pOutput ) {
661 $this->adjustDisplayTitle( $pOutput );
662 }
663
664 # For the main page, overwrite the <title> element with the con-
665 # tents of 'pagetitle-view-mainpage' instead of the default (if
666 # that's not empty).
667 # This message always exists because it is in the i18n files
668 if ( $this->getTitle()->isMainPage() ) {
669 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
670 if ( !$msg->isDisabled() ) {
671 $outputPage->setHTMLTitle( $msg->title( $this->getTitle() )->text() );
672 }
673 }
674
675 # Use adaptive TTLs for CDN so delayed/failed purges are noticed less often.
676 # This could use getTouched(), but that could be scary for major template edits.
677 $outputPage->adaptCdnTTL( $this->mPage->getTimestamp(), IExpiringStore::TTL_DAY );
678
679 # Check for any __NOINDEX__ tags on the page using $pOutput
680 $policy = $this->getRobotPolicy( 'view', $pOutput );
681 $outputPage->setIndexPolicy( $policy['index'] );
682 $outputPage->setFollowPolicy( $policy['follow'] );
683
684 $this->showViewFooter();
685 $this->mPage->doViewUpdates( $user, $oldid );
686
687 # Load the postEdit module if the user just saved this revision
688 # See also EditPage::setPostEditCookie
689 $request = $this->getContext()->getRequest();
690 $cookieKey = EditPage::POST_EDIT_COOKIE_KEY_PREFIX . $this->getRevIdFetched();
691 $postEdit = $request->getCookie( $cookieKey );
692 if ( $postEdit ) {
693 # Clear the cookie. This also prevents caching of the response.
694 $request->response()->clearCookie( $cookieKey );
695 $outputPage->addJsConfigVars( 'wgPostEdit', $postEdit );
696 $outputPage->addModules( 'mediawiki.action.view.postEdit' );
697 }
698 }
699
700 /**
701 * Adjust title for pages with displaytitle, -{T|}- or language conversion
702 * @param ParserOutput $pOutput
703 */
704 public function adjustDisplayTitle( ParserOutput $pOutput ) {
705 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
706 $titleText = $pOutput->getTitleText();
707 if ( strval( $titleText ) !== '' ) {
708 $this->getContext()->getOutput()->setPageTitle( $titleText );
709 }
710 }
711
712 /**
713 * Show a diff page according to current request variables. For use within
714 * Article::view() only, other callers should use the DifferenceEngine class.
715 */
716 protected function showDiffPage() {
717 $request = $this->getContext()->getRequest();
718 $user = $this->getContext()->getUser();
719 $diff = $request->getVal( 'diff' );
720 $rcid = $request->getVal( 'rcid' );
721 $diffOnly = $request->getBool( 'diffonly', $user->getOption( 'diffonly' ) );
722 $purge = $request->getVal( 'action' ) == 'purge';
723 $unhide = $request->getInt( 'unhide' ) == 1;
724 $oldid = $this->getOldID();
725
726 $rev = $this->getRevisionFetched();
727
728 if ( !$rev ) {
729 $this->getContext()->getOutput()->setPageTitle( wfMessage( 'errorpagetitle' ) );
730 $msg = $this->getContext()->msg( 'difference-missing-revision' )
731 ->params( $oldid )
732 ->numParams( 1 )
733 ->parseAsBlock();
734 $this->getContext()->getOutput()->addHTML( $msg );
735 return;
736 }
737
738 $contentHandler = $rev->getContentHandler();
739 $de = $contentHandler->createDifferenceEngine(
740 $this->getContext(),
741 $oldid,
742 $diff,
743 $rcid,
744 $purge,
745 $unhide
746 );
747
748 // DifferenceEngine directly fetched the revision:
749 $this->mRevIdFetched = $de->getNewid();
750 $de->showDiffPage( $diffOnly );
751
752 // Run view updates for the newer revision being diffed (and shown
753 // below the diff if not $diffOnly).
754 list( $old, $new ) = $de->mapDiffPrevNext( $oldid, $diff );
755 // New can be false, convert it to 0 - this conveniently means the latest revision
756 $this->mPage->doViewUpdates( $user, (int)$new );
757 }
758
759 /**
760 * Get the robot policy to be used for the current view
761 * @param string $action The action= GET parameter
762 * @param ParserOutput|null $pOutput
763 * @return array The policy that should be set
764 * @todo actions other than 'view'
765 */
766 public function getRobotPolicy( $action, ParserOutput $pOutput = null ) {
767 global $wgArticleRobotPolicies, $wgNamespaceRobotPolicies, $wgDefaultRobotPolicy;
768
769 $ns = $this->getTitle()->getNamespace();
770
771 # Don't index user and user talk pages for blocked users (T13443)
772 if ( ( $ns == NS_USER || $ns == NS_USER_TALK ) && !$this->getTitle()->isSubpage() ) {
773 $specificTarget = null;
774 $vagueTarget = null;
775 $titleText = $this->getTitle()->getText();
776 if ( IP::isValid( $titleText ) ) {
777 $vagueTarget = $titleText;
778 } else {
779 $specificTarget = $titleText;
780 }
781 if ( Block::newFromTarget( $specificTarget, $vagueTarget ) instanceof Block ) {
782 return [
783 'index' => 'noindex',
784 'follow' => 'nofollow'
785 ];
786 }
787 }
788
789 if ( $this->mPage->getId() === 0 || $this->getOldID() ) {
790 # Non-articles (special pages etc), and old revisions
791 return [
792 'index' => 'noindex',
793 'follow' => 'nofollow'
794 ];
795 } elseif ( $this->getContext()->getOutput()->isPrintable() ) {
796 # Discourage indexing of printable versions, but encourage following
797 return [
798 'index' => 'noindex',
799 'follow' => 'follow'
800 ];
801 } elseif ( $this->getContext()->getRequest()->getInt( 'curid' ) ) {
802 # For ?curid=x urls, disallow indexing
803 return [
804 'index' => 'noindex',
805 'follow' => 'follow'
806 ];
807 }
808
809 # Otherwise, construct the policy based on the various config variables.
810 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
811
812 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
813 # Honour customised robot policies for this namespace
814 $policy = array_merge(
815 $policy,
816 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
817 );
818 }
819 if ( $this->getTitle()->canUseNoindex() && is_object( $pOutput ) && $pOutput->getIndexPolicy() ) {
820 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
821 # a final sanity check that we have really got the parser output.
822 $policy = array_merge(
823 $policy,
824 [ 'index' => $pOutput->getIndexPolicy() ]
825 );
826 }
827
828 if ( isset( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] ) ) {
829 # (T16900) site config can override user-defined __INDEX__ or __NOINDEX__
830 $policy = array_merge(
831 $policy,
832 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] )
833 );
834 }
835
836 return $policy;
837 }
838
839 /**
840 * Converts a String robot policy into an associative array, to allow
841 * merging of several policies using array_merge().
842 * @param array|string $policy Returns empty array on null/false/'', transparent
843 * to already-converted arrays, converts string.
844 * @return array 'index' => \<indexpolicy\>, 'follow' => \<followpolicy\>
845 */
846 public static function formatRobotPolicy( $policy ) {
847 if ( is_array( $policy ) ) {
848 return $policy;
849 } elseif ( !$policy ) {
850 return [];
851 }
852
853 $policy = explode( ',', $policy );
854 $policy = array_map( 'trim', $policy );
855
856 $arr = [];
857 foreach ( $policy as $var ) {
858 if ( in_array( $var, [ 'index', 'noindex' ] ) ) {
859 $arr['index'] = $var;
860 } elseif ( in_array( $var, [ 'follow', 'nofollow' ] ) ) {
861 $arr['follow'] = $var;
862 }
863 }
864
865 return $arr;
866 }
867
868 /**
869 * If this request is a redirect view, send "redirected from" subtitle to
870 * the output. Returns true if the header was needed, false if this is not
871 * a redirect view. Handles both local and remote redirects.
872 *
873 * @return bool
874 */
875 public function showRedirectedFromHeader() {
876 global $wgRedirectSources;
877
878 $context = $this->getContext();
879 $outputPage = $context->getOutput();
880 $request = $context->getRequest();
881 $rdfrom = $request->getVal( 'rdfrom' );
882
883 // Construct a URL for the current page view, but with the target title
884 $query = $request->getValues();
885 unset( $query['rdfrom'] );
886 unset( $query['title'] );
887 if ( $this->getTitle()->isRedirect() ) {
888 // Prevent double redirects
889 $query['redirect'] = 'no';
890 }
891 $redirectTargetUrl = $this->getTitle()->getLinkURL( $query );
892
893 if ( isset( $this->mRedirectedFrom ) ) {
894 // Avoid PHP 7.1 warning of passing $this by reference
895 $articlePage = $this;
896
897 // This is an internally redirected page view.
898 // We'll need a backlink to the source page for navigation.
899 if ( Hooks::run( 'ArticleViewRedirect', [ &$articlePage ] ) ) {
900 $redir = Linker::linkKnown(
901 $this->mRedirectedFrom,
902 null,
903 [],
904 [ 'redirect' => 'no' ]
905 );
906
907 $outputPage->addSubtitle( "<span class=\"mw-redirectedfrom\">" .
908 $context->msg( 'redirectedfrom' )->rawParams( $redir )->parse()
909 . "</span>" );
910
911 // Add the script to update the displayed URL and
912 // set the fragment if one was specified in the redirect
913 $outputPage->addJsConfigVars( [
914 'wgInternalRedirectTargetUrl' => $redirectTargetUrl,
915 ] );
916 $outputPage->addModules( 'mediawiki.action.view.redirect' );
917
918 // Add a <link rel="canonical"> tag
919 $outputPage->setCanonicalUrl( $this->getTitle()->getCanonicalURL() );
920
921 // Tell the output object that the user arrived at this article through a redirect
922 $outputPage->setRedirectedFrom( $this->mRedirectedFrom );
923
924 return true;
925 }
926 } elseif ( $rdfrom ) {
927 // This is an externally redirected view, from some other wiki.
928 // If it was reported from a trusted site, supply a backlink.
929 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
930 $redir = Linker::makeExternalLink( $rdfrom, $rdfrom );
931 $outputPage->addSubtitle( "<span class=\"mw-redirectedfrom\">" .
932 $context->msg( 'redirectedfrom' )->rawParams( $redir )->parse()
933 . "</span>" );
934
935 // Add the script to update the displayed URL
936 $outputPage->addJsConfigVars( [
937 'wgInternalRedirectTargetUrl' => $redirectTargetUrl,
938 ] );
939 $outputPage->addModules( 'mediawiki.action.view.redirect' );
940
941 return true;
942 }
943 }
944
945 return false;
946 }
947
948 /**
949 * Show a header specific to the namespace currently being viewed, like
950 * [[MediaWiki:Talkpagetext]]. For Article::view().
951 */
952 public function showNamespaceHeader() {
953 if ( $this->getTitle()->isTalkPage() ) {
954 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
955 $this->getContext()->getOutput()->wrapWikiMsg(
956 "<div class=\"mw-talkpageheader\">\n$1\n</div>",
957 [ 'talkpageheader' ]
958 );
959 }
960 }
961 }
962
963 /**
964 * Show the footer section of an ordinary page view
965 */
966 public function showViewFooter() {
967 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
968 if ( $this->getTitle()->getNamespace() == NS_USER_TALK
969 && IP::isValid( $this->getTitle()->getText() )
970 ) {
971 $this->getContext()->getOutput()->addWikiMsg( 'anontalkpagetext' );
972 }
973
974 // Show a footer allowing the user to patrol the shown revision or page if possible
975 $patrolFooterShown = $this->showPatrolFooter();
976
977 Hooks::run( 'ArticleViewFooter', [ $this, $patrolFooterShown ] );
978 }
979
980 /**
981 * If patrol is possible, output a patrol UI box. This is called from the
982 * footer section of ordinary page views. If patrol is not possible or not
983 * desired, does nothing.
984 * Side effect: When the patrol link is build, this method will call
985 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
986 *
987 * @return bool
988 */
989 public function showPatrolFooter() {
990 global $wgUseNPPatrol, $wgUseRCPatrol, $wgUseFilePatrol;
991
992 // Allow hooks to decide whether to not output this at all
993 if ( !Hooks::run( 'ArticleShowPatrolFooter', [ $this ] ) ) {
994 return false;
995 }
996
997 $outputPage = $this->getContext()->getOutput();
998 $user = $this->getContext()->getUser();
999 $title = $this->getTitle();
1000 $rc = false;
1001
1002 if ( !$title->quickUserCan( 'patrol', $user )
1003 || !( $wgUseRCPatrol || $wgUseNPPatrol
1004 || ( $wgUseFilePatrol && $title->inNamespace( NS_FILE ) ) )
1005 ) {
1006 // Patrolling is disabled or the user isn't allowed to
1007 return false;
1008 }
1009
1010 if ( $this->mRevision
1011 && !RecentChange::isInRCLifespan( $this->mRevision->getTimestamp(), 21600 )
1012 ) {
1013 // The current revision is already older than what could be in the RC table
1014 // 6h tolerance because the RC might not be cleaned out regularly
1015 return false;
1016 }
1017
1018 // Check for cached results
1019 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1020 $key = $cache->makeKey( 'unpatrollable-page', $title->getArticleID() );
1021 if ( $cache->get( $key ) ) {
1022 return false;
1023 }
1024
1025 $dbr = wfGetDB( DB_REPLICA );
1026 $oldestRevisionTimestamp = $dbr->selectField(
1027 'revision',
1028 'MIN( rev_timestamp )',
1029 [ 'rev_page' => $title->getArticleID() ],
1030 __METHOD__
1031 );
1032
1033 // New page patrol: Get the timestamp of the oldest revison which
1034 // the revision table holds for the given page. Then we look
1035 // whether it's within the RC lifespan and if it is, we try
1036 // to get the recentchanges row belonging to that entry
1037 // (with rc_new = 1).
1038 $recentPageCreation = false;
1039 if ( $oldestRevisionTimestamp
1040 && RecentChange::isInRCLifespan( $oldestRevisionTimestamp, 21600 )
1041 ) {
1042 // 6h tolerance because the RC might not be cleaned out regularly
1043 $recentPageCreation = true;
1044 $rc = RecentChange::newFromConds(
1045 [
1046 'rc_new' => 1,
1047 'rc_timestamp' => $oldestRevisionTimestamp,
1048 'rc_namespace' => $title->getNamespace(),
1049 'rc_cur_id' => $title->getArticleID()
1050 ],
1051 __METHOD__
1052 );
1053 if ( $rc ) {
1054 // Use generic patrol message for new pages
1055 $markPatrolledMsg = wfMessage( 'markaspatrolledtext' );
1056 }
1057 }
1058
1059 // File patrol: Get the timestamp of the latest upload for this page,
1060 // check whether it is within the RC lifespan and if it is, we try
1061 // to get the recentchanges row belonging to that entry
1062 // (with rc_type = RC_LOG, rc_log_type = upload).
1063 $recentFileUpload = false;
1064 if ( ( !$rc || $rc->getAttribute( 'rc_patrolled' ) ) && $wgUseFilePatrol
1065 && $title->getNamespace() === NS_FILE ) {
1066 // Retrieve timestamp of most recent upload
1067 $newestUploadTimestamp = $dbr->selectField(
1068 'image',
1069 'MAX( img_timestamp )',
1070 [ 'img_name' => $title->getDBkey() ],
1071 __METHOD__
1072 );
1073 if ( $newestUploadTimestamp
1074 && RecentChange::isInRCLifespan( $newestUploadTimestamp, 21600 )
1075 ) {
1076 // 6h tolerance because the RC might not be cleaned out regularly
1077 $recentFileUpload = true;
1078 $rc = RecentChange::newFromConds(
1079 [
1080 'rc_type' => RC_LOG,
1081 'rc_log_type' => 'upload',
1082 'rc_timestamp' => $newestUploadTimestamp,
1083 'rc_namespace' => NS_FILE,
1084 'rc_cur_id' => $title->getArticleID()
1085 ],
1086 __METHOD__
1087 );
1088 if ( $rc ) {
1089 // Use patrol message specific to files
1090 $markPatrolledMsg = wfMessage( 'markaspatrolledtext-file' );
1091 }
1092 }
1093 }
1094
1095 if ( !$recentPageCreation && !$recentFileUpload ) {
1096 // Page creation and latest upload (for files) is too old to be in RC
1097
1098 // We definitely can't patrol so cache the information
1099 // When a new file version is uploaded, the cache is cleared
1100 $cache->set( $key, '1' );
1101
1102 return false;
1103 }
1104
1105 if ( !$rc ) {
1106 // Don't cache: This can be hit if the page gets accessed very fast after
1107 // its creation / latest upload or in case we have high replica DB lag. In case
1108 // the revision is too old, we will already return above.
1109 return false;
1110 }
1111
1112 if ( $rc->getAttribute( 'rc_patrolled' ) ) {
1113 // Patrolled RC entry around
1114
1115 // Cache the information we gathered above in case we can't patrol
1116 // Don't cache in case we can patrol as this could change
1117 $cache->set( $key, '1' );
1118
1119 return false;
1120 }
1121
1122 if ( $rc->getPerformer()->equals( $user ) ) {
1123 // Don't show a patrol link for own creations/uploads. If the user could
1124 // patrol them, they already would be patrolled
1125 return false;
1126 }
1127
1128 $outputPage->preventClickjacking();
1129 if ( $user->isAllowed( 'writeapi' ) ) {
1130 $outputPage->addModules( 'mediawiki.page.patrol.ajax' );
1131 }
1132
1133 $link = Linker::linkKnown(
1134 $title,
1135 $markPatrolledMsg->escaped(),
1136 [],
1137 [
1138 'action' => 'markpatrolled',
1139 'rcid' => $rc->getAttribute( 'rc_id' ),
1140 ]
1141 );
1142
1143 $outputPage->addHTML(
1144 "<div class='patrollink' data-mw='interface'>" .
1145 wfMessage( 'markaspatrolledlink' )->rawParams( $link )->escaped() .
1146 '</div>'
1147 );
1148
1149 return true;
1150 }
1151
1152 /**
1153 * Purge the cache used to check if it is worth showing the patrol footer
1154 * For example, it is done during re-uploads when file patrol is used.
1155 * @param int $articleID ID of the article to purge
1156 * @since 1.27
1157 */
1158 public static function purgePatrolFooterCache( $articleID ) {
1159 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1160 $cache->delete( $cache->makeKey( 'unpatrollable-page', $articleID ) );
1161 }
1162
1163 /**
1164 * Show the error text for a missing article. For articles in the MediaWiki
1165 * namespace, show the default message text. To be called from Article::view().
1166 */
1167 public function showMissingArticle() {
1168 global $wgSend404Code;
1169
1170 $outputPage = $this->getContext()->getOutput();
1171 // Whether the page is a root user page of an existing user (but not a subpage)
1172 $validUserPage = false;
1173
1174 $title = $this->getTitle();
1175
1176 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1177 if ( $title->getNamespace() == NS_USER
1178 || $title->getNamespace() == NS_USER_TALK
1179 ) {
1180 $rootPart = explode( '/', $title->getText() )[0];
1181 $user = User::newFromName( $rootPart, false /* allow IP users */ );
1182 $ip = User::isIP( $rootPart );
1183 $block = Block::newFromTarget( $user, $user );
1184
1185 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1186 $outputPage->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1187 [ 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ] );
1188 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
1189 # Show log extract if the user is currently blocked
1190 LogEventsList::showLogExtract(
1191 $outputPage,
1192 'block',
1193 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
1194 '',
1195 [
1196 'lim' => 1,
1197 'showIfEmpty' => false,
1198 'msgKey' => [
1199 'blocked-notice-logextract',
1200 $user->getName() # Support GENDER in notice
1201 ]
1202 ]
1203 );
1204 $validUserPage = !$title->isSubpage();
1205 } else {
1206 $validUserPage = !$title->isSubpage();
1207 }
1208 }
1209
1210 Hooks::run( 'ShowMissingArticle', [ $this ] );
1211
1212 # Show delete and move logs if there were any such events.
1213 # The logging query can DOS the site when bots/crawlers cause 404 floods,
1214 # so be careful showing this. 404 pages must be cheap as they are hard to cache.
1215 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
1216 $key = $cache->makeKey( 'page-recent-delete', md5( $title->getPrefixedText() ) );
1217 $loggedIn = $this->getContext()->getUser()->isLoggedIn();
1218 $sessionExists = $this->getContext()->getRequest()->getSession()->isPersistent();
1219 if ( $loggedIn || $cache->get( $key ) || $sessionExists ) {
1220 $logTypes = [ 'delete', 'move', 'protect' ];
1221
1222 $dbr = wfGetDB( DB_REPLICA );
1223
1224 $conds = [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ];
1225 // Give extensions a chance to hide their (unrelated) log entries
1226 Hooks::run( 'Article::MissingArticleConditions', [ &$conds, $logTypes ] );
1227 LogEventsList::showLogExtract(
1228 $outputPage,
1229 $logTypes,
1230 $title,
1231 '',
1232 [
1233 'lim' => 10,
1234 'conds' => $conds,
1235 'showIfEmpty' => false,
1236 'msgKey' => [ $loggedIn || $sessionExists
1237 ? 'moveddeleted-notice'
1238 : 'moveddeleted-notice-recent'
1239 ]
1240 ]
1241 );
1242 }
1243
1244 if ( !$this->mPage->hasViewableContent() && $wgSend404Code && !$validUserPage ) {
1245 // If there's no backing content, send a 404 Not Found
1246 // for better machine handling of broken links.
1247 $this->getContext()->getRequest()->response()->statusHeader( 404 );
1248 }
1249
1250 // Also apply the robot policy for nonexisting pages (even if a 404 was used for sanity)
1251 $policy = $this->getRobotPolicy( 'view' );
1252 $outputPage->setIndexPolicy( $policy['index'] );
1253 $outputPage->setFollowPolicy( $policy['follow'] );
1254
1255 $hookResult = Hooks::run( 'BeforeDisplayNoArticleText', [ $this ] );
1256
1257 if ( !$hookResult ) {
1258 return;
1259 }
1260
1261 # Show error message
1262 $oldid = $this->getOldID();
1263 if ( !$oldid && $title->getNamespace() === NS_MEDIAWIKI && $title->hasSourceText() ) {
1264 $outputPage->addParserOutput( $this->getContentObject()->getParserOutput( $title ) );
1265 } else {
1266 if ( $oldid ) {
1267 $text = wfMessage( 'missing-revision', $oldid )->plain();
1268 } elseif ( $title->quickUserCan( 'create', $this->getContext()->getUser() )
1269 && $title->quickUserCan( 'edit', $this->getContext()->getUser() )
1270 ) {
1271 $message = $this->getContext()->getUser()->isLoggedIn() ? 'noarticletext' : 'noarticletextanon';
1272 $text = wfMessage( $message )->plain();
1273 } else {
1274 $text = wfMessage( 'noarticletext-nopermission' )->plain();
1275 }
1276
1277 $dir = $this->getContext()->getLanguage()->getDir();
1278 $lang = $this->getContext()->getLanguage()->getHtmlCode();
1279 $outputPage->addWikiText( Xml::openElement( 'div', [
1280 'class' => "noarticletext mw-content-$dir",
1281 'dir' => $dir,
1282 'lang' => $lang,
1283 ] ) . "\n$text\n</div>" );
1284 }
1285 }
1286
1287 /**
1288 * If the revision requested for view is deleted, check permissions.
1289 * Send either an error message or a warning header to the output.
1290 *
1291 * @return bool True if the view is allowed, false if not.
1292 */
1293 public function showDeletedRevisionHeader() {
1294 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1295 // Not deleted
1296 return true;
1297 }
1298
1299 $outputPage = $this->getContext()->getOutput();
1300 $user = $this->getContext()->getUser();
1301 // If the user is not allowed to see it...
1302 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT, $user ) ) {
1303 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1304 'rev-deleted-text-permission' );
1305
1306 return false;
1307 // If the user needs to confirm that they want to see it...
1308 } elseif ( $this->getContext()->getRequest()->getInt( 'unhide' ) != 1 ) {
1309 # Give explanation and add a link to view the revision...
1310 $oldid = intval( $this->getOldID() );
1311 $link = $this->getTitle()->getFullURL( "oldid={$oldid}&unhide=1" );
1312 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1313 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1314 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1315 [ $msg, $link ] );
1316
1317 return false;
1318 // We are allowed to see...
1319 } else {
1320 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1321 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1322 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1323
1324 return true;
1325 }
1326 }
1327
1328 /**
1329 * Generate the navigation links when browsing through an article revisions
1330 * It shows the information as:
1331 * Revision as of \<date\>; view current revision
1332 * \<- Previous version | Next Version -\>
1333 *
1334 * @param int $oldid Revision ID of this article revision
1335 */
1336 public function setOldSubtitle( $oldid = 0 ) {
1337 // Avoid PHP 7.1 warning of passing $this by reference
1338 $articlePage = $this;
1339
1340 if ( !Hooks::run( 'DisplayOldSubtitle', [ &$articlePage, &$oldid ] ) ) {
1341 return;
1342 }
1343
1344 $context = $this->getContext();
1345 $unhide = $context->getRequest()->getInt( 'unhide' ) == 1;
1346
1347 # Cascade unhide param in links for easy deletion browsing
1348 $extraParams = [];
1349 if ( $unhide ) {
1350 $extraParams['unhide'] = 1;
1351 }
1352
1353 if ( $this->mRevision && $this->mRevision->getId() === $oldid ) {
1354 $revision = $this->mRevision;
1355 } else {
1356 $revision = Revision::newFromId( $oldid );
1357 }
1358
1359 $timestamp = $revision->getTimestamp();
1360
1361 $current = ( $oldid == $this->mPage->getLatest() );
1362 $language = $context->getLanguage();
1363 $user = $context->getUser();
1364
1365 $td = $language->userTimeAndDate( $timestamp, $user );
1366 $tddate = $language->userDate( $timestamp, $user );
1367 $tdtime = $language->userTime( $timestamp, $user );
1368
1369 # Show user links if allowed to see them. If hidden, then show them only if requested...
1370 $userlinks = Linker::revUserTools( $revision, !$unhide );
1371
1372 $infomsg = $current && !$context->msg( 'revision-info-current' )->isDisabled()
1373 ? 'revision-info-current'
1374 : 'revision-info';
1375
1376 $outputPage = $context->getOutput();
1377 $revisionInfo = "<div id=\"mw-{$infomsg}\">" .
1378 $context->msg( $infomsg, $td )
1379 ->rawParams( $userlinks )
1380 ->params( $revision->getId(), $tddate, $tdtime, $revision->getUserText() )
1381 ->rawParams( Linker::revComment( $revision, true, true ) )
1382 ->parse() .
1383 "</div>";
1384
1385 $lnk = $current
1386 ? $context->msg( 'currentrevisionlink' )->escaped()
1387 : Linker::linkKnown(
1388 $this->getTitle(),
1389 $context->msg( 'currentrevisionlink' )->escaped(),
1390 [],
1391 $extraParams
1392 );
1393 $curdiff = $current
1394 ? $context->msg( 'diff' )->escaped()
1395 : Linker::linkKnown(
1396 $this->getTitle(),
1397 $context->msg( 'diff' )->escaped(),
1398 [],
1399 [
1400 'diff' => 'cur',
1401 'oldid' => $oldid
1402 ] + $extraParams
1403 );
1404 $prev = $this->getTitle()->getPreviousRevisionID( $oldid );
1405 $prevlink = $prev
1406 ? Linker::linkKnown(
1407 $this->getTitle(),
1408 $context->msg( 'previousrevision' )->escaped(),
1409 [],
1410 [
1411 'direction' => 'prev',
1412 'oldid' => $oldid
1413 ] + $extraParams
1414 )
1415 : $context->msg( 'previousrevision' )->escaped();
1416 $prevdiff = $prev
1417 ? Linker::linkKnown(
1418 $this->getTitle(),
1419 $context->msg( 'diff' )->escaped(),
1420 [],
1421 [
1422 'diff' => 'prev',
1423 'oldid' => $oldid
1424 ] + $extraParams
1425 )
1426 : $context->msg( 'diff' )->escaped();
1427 $nextlink = $current
1428 ? $context->msg( 'nextrevision' )->escaped()
1429 : Linker::linkKnown(
1430 $this->getTitle(),
1431 $context->msg( 'nextrevision' )->escaped(),
1432 [],
1433 [
1434 'direction' => 'next',
1435 'oldid' => $oldid
1436 ] + $extraParams
1437 );
1438 $nextdiff = $current
1439 ? $context->msg( 'diff' )->escaped()
1440 : Linker::linkKnown(
1441 $this->getTitle(),
1442 $context->msg( 'diff' )->escaped(),
1443 [],
1444 [
1445 'diff' => 'next',
1446 'oldid' => $oldid
1447 ] + $extraParams
1448 );
1449
1450 $cdel = Linker::getRevDeleteLink( $user, $revision, $this->getTitle() );
1451 if ( $cdel !== '' ) {
1452 $cdel .= ' ';
1453 }
1454
1455 // the outer div is need for styling the revision info and nav in MobileFrontend
1456 $outputPage->addSubtitle( "<div class=\"mw-revision\">" . $revisionInfo .
1457 "<div id=\"mw-revision-nav\">" . $cdel .
1458 $context->msg( 'revision-nav' )->rawParams(
1459 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff
1460 )->escaped() . "</div></div>" );
1461 }
1462
1463 /**
1464 * Return the HTML for the top of a redirect page
1465 *
1466 * Chances are you should just be using the ParserOutput from
1467 * WikitextContent::getParserOutput instead of calling this for redirects.
1468 *
1469 * @param Title|array $target Destination(s) to redirect
1470 * @param bool $appendSubtitle [optional]
1471 * @param bool $forceKnown Should the image be shown as a bluelink regardless of existence?
1472 * @return string Containing HTML with redirect link
1473 *
1474 * @deprecated since 1.30
1475 */
1476 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1477 $lang = $this->getTitle()->getPageLanguage();
1478 $out = $this->getContext()->getOutput();
1479 if ( $appendSubtitle ) {
1480 $out->addSubtitle( wfMessage( 'redirectpagesub' ) );
1481 }
1482 $out->addModuleStyles( 'mediawiki.action.view.redirectPage' );
1483 return static::getRedirectHeaderHtml( $lang, $target, $forceKnown );
1484 }
1485
1486 /**
1487 * Return the HTML for the top of a redirect page
1488 *
1489 * Chances are you should just be using the ParserOutput from
1490 * WikitextContent::getParserOutput instead of calling this for redirects.
1491 *
1492 * @since 1.23
1493 * @param Language $lang
1494 * @param Title|array $target Destination(s) to redirect
1495 * @param bool $forceKnown Should the image be shown as a bluelink regardless of existence?
1496 * @return string Containing HTML with redirect link
1497 */
1498 public static function getRedirectHeaderHtml( Language $lang, $target, $forceKnown = false ) {
1499 if ( !is_array( $target ) ) {
1500 $target = [ $target ];
1501 }
1502
1503 $html = '<ul class="redirectText">';
1504 /** @var Title $title */
1505 foreach ( $target as $title ) {
1506 $html .= '<li>' . Linker::link(
1507 $title,
1508 htmlspecialchars( $title->getFullText() ),
1509 [],
1510 // Make sure wiki page redirects are not followed
1511 $title->isRedirect() ? [ 'redirect' => 'no' ] : [],
1512 ( $forceKnown ? [ 'known', 'noclasses' ] : [] )
1513 ) . '</li>';
1514 }
1515 $html .= '</ul>';
1516
1517 $redirectToText = wfMessage( 'redirectto' )->inLanguage( $lang )->escaped();
1518
1519 return '<div class="redirectMsg">' .
1520 '<p>' . $redirectToText . '</p>' .
1521 $html .
1522 '</div>';
1523 }
1524
1525 /**
1526 * Adds help link with an icon via page indicators.
1527 * Link target can be overridden by a local message containing a wikilink:
1528 * the message key is: 'namespace-' + namespace number + '-helppage'.
1529 * @param string $to Target MediaWiki.org page title or encoded URL.
1530 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1531 * @since 1.25
1532 */
1533 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1534 $msg = wfMessage(
1535 'namespace-' . $this->getTitle()->getNamespace() . '-helppage'
1536 );
1537
1538 $out = $this->getContext()->getOutput();
1539 if ( !$msg->isDisabled() ) {
1540 $helpUrl = Skin::makeUrl( $msg->plain() );
1541 $out->addHelpLink( $helpUrl, true );
1542 } else {
1543 $out->addHelpLink( $to, $overrideBaseUrl );
1544 }
1545 }
1546
1547 /**
1548 * Handle action=render
1549 */
1550 public function render() {
1551 $this->getContext()->getRequest()->response()->header( 'X-Robots-Tag: noindex' );
1552 $this->getContext()->getOutput()->setArticleBodyOnly( true );
1553 $this->disableSectionEditForRender = true;
1554 $this->view();
1555 }
1556
1557 /**
1558 * action=protect handler
1559 */
1560 public function protect() {
1561 $form = new ProtectionForm( $this );
1562 $form->execute();
1563 }
1564
1565 /**
1566 * action=unprotect handler (alias)
1567 */
1568 public function unprotect() {
1569 $this->protect();
1570 }
1571
1572 /**
1573 * UI entry point for page deletion
1574 */
1575 public function delete() {
1576 # This code desperately needs to be totally rewritten
1577
1578 $title = $this->getTitle();
1579 $context = $this->getContext();
1580 $user = $context->getUser();
1581 $request = $context->getRequest();
1582
1583 # Check permissions
1584 $permissionErrors = $title->getUserPermissionsErrors( 'delete', $user );
1585 if ( count( $permissionErrors ) ) {
1586 throw new PermissionsError( 'delete', $permissionErrors );
1587 }
1588
1589 # Read-only check...
1590 if ( wfReadOnly() ) {
1591 throw new ReadOnlyError;
1592 }
1593
1594 # Better double-check that it hasn't been deleted yet!
1595 $this->mPage->loadPageData(
1596 $request->wasPosted() ? WikiPage::READ_LATEST : WikiPage::READ_NORMAL
1597 );
1598 if ( !$this->mPage->exists() ) {
1599 $deleteLogPage = new LogPage( 'delete' );
1600 $outputPage = $context->getOutput();
1601 $outputPage->setPageTitle( $context->msg( 'cannotdelete-title', $title->getPrefixedText() ) );
1602 $outputPage->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1603 [ 'cannotdelete', wfEscapeWikiText( $title->getPrefixedText() ) ]
1604 );
1605 $outputPage->addHTML(
1606 Xml::element( 'h2', null, $deleteLogPage->getName()->text() )
1607 );
1608 LogEventsList::showLogExtract(
1609 $outputPage,
1610 'delete',
1611 $title
1612 );
1613
1614 return;
1615 }
1616
1617 $deleteReasonList = $request->getText( 'wpDeleteReasonList', 'other' );
1618 $deleteReason = $request->getText( 'wpReason' );
1619
1620 if ( $deleteReasonList == 'other' ) {
1621 $reason = $deleteReason;
1622 } elseif ( $deleteReason != '' ) {
1623 // Entry from drop down menu + additional comment
1624 $colonseparator = wfMessage( 'colon-separator' )->inContentLanguage()->text();
1625 $reason = $deleteReasonList . $colonseparator . $deleteReason;
1626 } else {
1627 $reason = $deleteReasonList;
1628 }
1629
1630 if ( $request->wasPosted() && $user->matchEditToken( $request->getVal( 'wpEditToken' ),
1631 [ 'delete', $this->getTitle()->getPrefixedText() ] )
1632 ) {
1633 # Flag to hide all contents of the archived revisions
1634 $suppress = $request->getCheck( 'wpSuppress' ) && $user->isAllowed( 'suppressrevision' );
1635
1636 $this->doDelete( $reason, $suppress );
1637
1638 WatchAction::doWatchOrUnwatch( $request->getCheck( 'wpWatch' ), $title, $user );
1639
1640 return;
1641 }
1642
1643 // Generate deletion reason
1644 $hasHistory = false;
1645 if ( !$reason ) {
1646 try {
1647 $reason = $this->generateReason( $hasHistory );
1648 } catch ( Exception $e ) {
1649 # if a page is horribly broken, we still want to be able to
1650 # delete it. So be lenient about errors here.
1651 wfDebug( "Error while building auto delete summary: $e" );
1652 $reason = '';
1653 }
1654 }
1655
1656 // If the page has a history, insert a warning
1657 if ( $hasHistory ) {
1658 $title = $this->getTitle();
1659
1660 // The following can use the real revision count as this is only being shown for users
1661 // that can delete this page.
1662 // This, as a side-effect, also makes sure that the following query isn't being run for
1663 // pages with a larger history, unless the user has the 'bigdelete' right
1664 // (and is about to delete this page).
1665 $dbr = wfGetDB( DB_REPLICA );
1666 $revisions = $edits = (int)$dbr->selectField(
1667 'revision',
1668 'COUNT(rev_page)',
1669 [ 'rev_page' => $title->getArticleID() ],
1670 __METHOD__
1671 );
1672
1673 // @todo FIXME: i18n issue/patchwork message
1674 $context->getOutput()->addHTML(
1675 '<strong class="mw-delete-warning-revisions">' .
1676 $context->msg( 'historywarning' )->numParams( $revisions )->parse() .
1677 $context->msg( 'word-separator' )->escaped() . Linker::linkKnown( $title,
1678 $context->msg( 'history' )->escaped(),
1679 [],
1680 [ 'action' => 'history' ] ) .
1681 '</strong>'
1682 );
1683
1684 if ( $title->isBigDeletion() ) {
1685 global $wgDeleteRevisionsLimit;
1686 $context->getOutput()->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
1687 [
1688 'delete-warning-toobig',
1689 $context->getLanguage()->formatNum( $wgDeleteRevisionsLimit )
1690 ]
1691 );
1692 }
1693 }
1694
1695 $this->confirmDelete( $reason );
1696 }
1697
1698 /**
1699 * Output deletion confirmation dialog
1700 * @todo FIXME: Move to another file?
1701 * @param string $reason Prefilled reason
1702 */
1703 public function confirmDelete( $reason ) {
1704 wfDebug( "Article::confirmDelete\n" );
1705
1706 $title = $this->getTitle();
1707 $ctx = $this->getContext();
1708 $outputPage = $ctx->getOutput();
1709 $outputPage->setPageTitle( wfMessage( 'delete-confirm', $title->getPrefixedText() ) );
1710 $outputPage->addBacklinkSubtitle( $title );
1711 $outputPage->setRobotPolicy( 'noindex,nofollow' );
1712 $outputPage->addModules( 'mediawiki.action.delete' );
1713
1714 $backlinkCache = $title->getBacklinkCache();
1715 if ( $backlinkCache->hasLinks( 'pagelinks' ) || $backlinkCache->hasLinks( 'templatelinks' ) ) {
1716 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1717 'deleting-backlinks-warning' );
1718 }
1719
1720 $subpageQueryLimit = 51;
1721 $subpages = $title->getSubpages( $subpageQueryLimit );
1722 $subpageCount = count( $subpages );
1723 if ( $subpageCount > 0 ) {
1724 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1725 [ 'deleting-subpages-warning', Message::numParam( $subpageCount ) ] );
1726 }
1727 $outputPage->addWikiMsg( 'confirmdeletetext' );
1728
1729 Hooks::run( 'ArticleConfirmDelete', [ $this, $outputPage, &$reason ] );
1730
1731 $user = $this->getContext()->getUser();
1732 $checkWatch = $user->getBoolOption( 'watchdeletion' ) || $user->isWatched( $title );
1733
1734 $outputPage->enableOOUI();
1735
1736 $options = Xml::listDropDownOptions(
1737 $ctx->msg( 'deletereason-dropdown' )->inContentLanguage()->text(),
1738 [ 'other' => $ctx->msg( 'deletereasonotherlist' )->inContentLanguage()->text() ]
1739 );
1740 $options = Xml::listDropDownOptionsOoui( $options );
1741
1742 $fields[] = new OOUI\FieldLayout(
1743 new OOUI\DropdownInputWidget( [
1744 'name' => 'wpDeleteReasonList',
1745 'inputId' => 'wpDeleteReasonList',
1746 'tabIndex' => 1,
1747 'infusable' => true,
1748 'value' => '',
1749 'options' => $options
1750 ] ),
1751 [
1752 'label' => $ctx->msg( 'deletecomment' )->text(),
1753 'align' => 'top',
1754 ]
1755 );
1756
1757 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
1758 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
1759 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
1760 $conf = $this->getContext()->getConfig();
1761 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD;
1762 $fields[] = new OOUI\FieldLayout(
1763 new OOUI\TextInputWidget( [
1764 'name' => 'wpReason',
1765 'inputId' => 'wpReason',
1766 'tabIndex' => 2,
1767 'maxLength' => $oldCommentSchema ? 255 : CommentStore::COMMENT_CHARACTER_LIMIT,
1768 'infusable' => true,
1769 'value' => $reason,
1770 'autofocus' => true,
1771 ] ),
1772 [
1773 'label' => $ctx->msg( 'deleteotherreason' )->text(),
1774 'align' => 'top',
1775 ]
1776 );
1777
1778 if ( $user->isLoggedIn() ) {
1779 $fields[] = new OOUI\FieldLayout(
1780 new OOUI\CheckboxInputWidget( [
1781 'name' => 'wpWatch',
1782 'inputId' => 'wpWatch',
1783 'tabIndex' => 3,
1784 'selected' => $checkWatch,
1785 ] ),
1786 [
1787 'label' => $ctx->msg( 'watchthis' )->text(),
1788 'align' => 'inline',
1789 'infusable' => true,
1790 ]
1791 );
1792 }
1793
1794 if ( $user->isAllowed( 'suppressrevision' ) ) {
1795 $fields[] = new OOUI\FieldLayout(
1796 new OOUI\CheckboxInputWidget( [
1797 'name' => 'wpSuppress',
1798 'inputId' => 'wpSuppress',
1799 'tabIndex' => 4,
1800 ] ),
1801 [
1802 'label' => $ctx->msg( 'revdelete-suppress' )->text(),
1803 'align' => 'inline',
1804 'infusable' => true,
1805 ]
1806 );
1807 }
1808
1809 $fields[] = new OOUI\FieldLayout(
1810 new OOUI\ButtonInputWidget( [
1811 'name' => 'wpConfirmB',
1812 'inputId' => 'wpConfirmB',
1813 'tabIndex' => 5,
1814 'value' => $ctx->msg( 'deletepage' )->text(),
1815 'label' => $ctx->msg( 'deletepage' )->text(),
1816 'flags' => [ 'primary', 'destructive' ],
1817 'type' => 'submit',
1818 ] ),
1819 [
1820 'align' => 'top',
1821 ]
1822 );
1823
1824 $fieldset = new OOUI\FieldsetLayout( [
1825 'label' => $ctx->msg( 'delete-legend' )->text(),
1826 'id' => 'mw-delete-table',
1827 'items' => $fields,
1828 ] );
1829
1830 $form = new OOUI\FormLayout( [
1831 'method' => 'post',
1832 'action' => $title->getLocalURL( 'action=delete' ),
1833 'id' => 'deleteconfirm',
1834 ] );
1835 $form->appendContent(
1836 $fieldset,
1837 new OOUI\HtmlSnippet(
1838 Html::hidden( 'wpEditToken', $user->getEditToken( [ 'delete', $title->getPrefixedText() ] ) )
1839 )
1840 );
1841
1842 $outputPage->addHTML(
1843 new OOUI\PanelLayout( [
1844 'classes' => [ 'deletepage-wrapper' ],
1845 'expanded' => false,
1846 'padded' => true,
1847 'framed' => true,
1848 'content' => $form,
1849 ] )
1850 );
1851
1852 if ( $user->isAllowed( 'editinterface' ) ) {
1853 $link = Linker::linkKnown(
1854 $ctx->msg( 'deletereason-dropdown' )->inContentLanguage()->getTitle(),
1855 wfMessage( 'delete-edit-reasonlist' )->escaped(),
1856 [],
1857 [ 'action' => 'edit' ]
1858 );
1859 $outputPage->addHTML( '<p class="mw-delete-editreasons">' . $link . '</p>' );
1860 }
1861
1862 $deleteLogPage = new LogPage( 'delete' );
1863 $outputPage->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) );
1864 LogEventsList::showLogExtract( $outputPage, 'delete', $title );
1865 }
1866
1867 /**
1868 * Perform a deletion and output success or failure messages
1869 * @param string $reason
1870 * @param bool $suppress
1871 */
1872 public function doDelete( $reason, $suppress = false ) {
1873 $error = '';
1874 $context = $this->getContext();
1875 $outputPage = $context->getOutput();
1876 $user = $context->getUser();
1877 $status = $this->mPage->doDeleteArticleReal( $reason, $suppress, 0, true, $error, $user );
1878
1879 if ( $status->isGood() ) {
1880 $deleted = $this->getTitle()->getPrefixedText();
1881
1882 $outputPage->setPageTitle( wfMessage( 'actioncomplete' ) );
1883 $outputPage->setRobotPolicy( 'noindex,nofollow' );
1884
1885 $loglink = '[[Special:Log/delete|' . wfMessage( 'deletionlog' )->text() . ']]';
1886
1887 $outputPage->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
1888
1889 Hooks::run( 'ArticleDeleteAfterSuccess', [ $this->getTitle(), $outputPage ] );
1890
1891 $outputPage->returnToMain( false );
1892 } else {
1893 $outputPage->setPageTitle(
1894 wfMessage( 'cannotdelete-title',
1895 $this->getTitle()->getPrefixedText() )
1896 );
1897
1898 if ( $error == '' ) {
1899 $outputPage->addWikiText(
1900 "<div class=\"error mw-error-cannotdelete\">\n" . $status->getWikiText() . "\n</div>"
1901 );
1902 $deleteLogPage = new LogPage( 'delete' );
1903 $outputPage->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) );
1904
1905 LogEventsList::showLogExtract(
1906 $outputPage,
1907 'delete',
1908 $this->getTitle()
1909 );
1910 } else {
1911 $outputPage->addHTML( $error );
1912 }
1913 }
1914 }
1915
1916 /* Caching functions */
1917
1918 /**
1919 * checkLastModified returns true if it has taken care of all
1920 * output to the client that is necessary for this request.
1921 * (that is, it has sent a cached version of the page)
1922 *
1923 * @return bool True if cached version send, false otherwise
1924 */
1925 protected function tryFileCache() {
1926 static $called = false;
1927
1928 if ( $called ) {
1929 wfDebug( "Article::tryFileCache(): called twice!?\n" );
1930 return false;
1931 }
1932
1933 $called = true;
1934 if ( $this->isFileCacheable() ) {
1935 $cache = new HTMLFileCache( $this->getTitle(), 'view' );
1936 if ( $cache->isCacheGood( $this->mPage->getTouched() ) ) {
1937 wfDebug( "Article::tryFileCache(): about to load file\n" );
1938 $cache->loadFromFileCache( $this->getContext() );
1939 return true;
1940 } else {
1941 wfDebug( "Article::tryFileCache(): starting buffer\n" );
1942 ob_start( [ &$cache, 'saveToFileCache' ] );
1943 }
1944 } else {
1945 wfDebug( "Article::tryFileCache(): not cacheable\n" );
1946 }
1947
1948 return false;
1949 }
1950
1951 /**
1952 * Check if the page can be cached
1953 * @param int $mode One of the HTMLFileCache::MODE_* constants (since 1.28)
1954 * @return bool
1955 */
1956 public function isFileCacheable( $mode = HTMLFileCache::MODE_NORMAL ) {
1957 $cacheable = false;
1958
1959 if ( HTMLFileCache::useFileCache( $this->getContext(), $mode ) ) {
1960 $cacheable = $this->mPage->getId()
1961 && !$this->mRedirectedFrom && !$this->getTitle()->isRedirect();
1962 // Extension may have reason to disable file caching on some pages.
1963 if ( $cacheable ) {
1964 // Avoid PHP 7.1 warning of passing $this by reference
1965 $articlePage = $this;
1966 $cacheable = Hooks::run( 'IsFileCacheable', [ &$articlePage ] );
1967 }
1968 }
1969
1970 return $cacheable;
1971 }
1972
1973 /**#@-*/
1974
1975 /**
1976 * Lightweight method to get the parser output for a page, checking the parser cache
1977 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
1978 * consider, so it's not appropriate to use there.
1979 *
1980 * @since 1.16 (r52326) for LiquidThreads
1981 *
1982 * @param int|null $oldid Revision ID or null
1983 * @param User|null $user The relevant user
1984 * @return ParserOutput|bool ParserOutput or false if the given revision ID is not found
1985 */
1986 public function getParserOutput( $oldid = null, User $user = null ) {
1987 // XXX: bypasses mParserOptions and thus setParserOptions()
1988
1989 if ( $user === null ) {
1990 $parserOptions = $this->getParserOptions();
1991 } else {
1992 $parserOptions = $this->mPage->makeParserOptions( $user );
1993 }
1994
1995 return $this->mPage->getParserOutput( $parserOptions, $oldid );
1996 }
1997
1998 /**
1999 * Override the ParserOptions used to render the primary article wikitext.
2000 *
2001 * @param ParserOptions $options
2002 * @throws MWException If the parser options where already initialized.
2003 */
2004 public function setParserOptions( ParserOptions $options ) {
2005 if ( $this->mParserOptions ) {
2006 throw new MWException( "can't change parser options after they have already been set" );
2007 }
2008
2009 // clone, so if $options is modified later, it doesn't confuse the parser cache.
2010 $this->mParserOptions = clone $options;
2011 }
2012
2013 /**
2014 * Get parser options suitable for rendering the primary article wikitext
2015 * @return ParserOptions
2016 */
2017 public function getParserOptions() {
2018 if ( !$this->mParserOptions ) {
2019 $this->mParserOptions = $this->mPage->makeParserOptions( $this->getContext() );
2020 }
2021 // Clone to allow modifications of the return value without affecting cache
2022 return clone $this->mParserOptions;
2023 }
2024
2025 /**
2026 * Sets the context this Article is executed in
2027 *
2028 * @param IContextSource $context
2029 * @since 1.18
2030 */
2031 public function setContext( $context ) {
2032 $this->mContext = $context;
2033 }
2034
2035 /**
2036 * Gets the context this Article is executed in
2037 *
2038 * @return IContextSource
2039 * @since 1.18
2040 */
2041 public function getContext() {
2042 if ( $this->mContext instanceof IContextSource ) {
2043 return $this->mContext;
2044 } else {
2045 wfDebug( __METHOD__ . " called and \$mContext is null. " .
2046 "Return RequestContext::getMain(); for sanity\n" );
2047 return RequestContext::getMain();
2048 }
2049 }
2050
2051 /**
2052 * Use PHP's magic __get handler to handle accessing of
2053 * raw WikiPage fields for backwards compatibility.
2054 *
2055 * @param string $fname Field name
2056 * @return mixed
2057 */
2058 public function __get( $fname ) {
2059 if ( property_exists( $this->mPage, $fname ) ) {
2060 # wfWarn( "Access to raw $fname field " . __CLASS__ );
2061 return $this->mPage->$fname;
2062 }
2063 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE );
2064 }
2065
2066 /**
2067 * Use PHP's magic __set handler to handle setting of
2068 * raw WikiPage fields for backwards compatibility.
2069 *
2070 * @param string $fname Field name
2071 * @param mixed $fvalue New value
2072 */
2073 public function __set( $fname, $fvalue ) {
2074 if ( property_exists( $this->mPage, $fname ) ) {
2075 # wfWarn( "Access to raw $fname field of " . __CLASS__ );
2076 $this->mPage->$fname = $fvalue;
2077 // Note: extensions may want to toss on new fields
2078 } elseif ( !in_array( $fname, [ 'mContext', 'mPage' ] ) ) {
2079 $this->mPage->$fname = $fvalue;
2080 } else {
2081 trigger_error( 'Inaccessible property via __set(): ' . $fname, E_USER_NOTICE );
2082 }
2083 }
2084
2085 /**
2086 * Call to WikiPage function for backwards compatibility.
2087 * @see WikiPage::checkFlags
2088 */
2089 public function checkFlags( $flags ) {
2090 return $this->mPage->checkFlags( $flags );
2091 }
2092
2093 /**
2094 * Call to WikiPage function for backwards compatibility.
2095 * @see WikiPage::checkTouched
2096 */
2097 public function checkTouched() {
2098 return $this->mPage->checkTouched();
2099 }
2100
2101 /**
2102 * Call to WikiPage function for backwards compatibility.
2103 * @see WikiPage::clearPreparedEdit
2104 */
2105 public function clearPreparedEdit() {
2106 $this->mPage->clearPreparedEdit();
2107 }
2108
2109 /**
2110 * Call to WikiPage function for backwards compatibility.
2111 * @see WikiPage::doDeleteArticleReal
2112 */
2113 public function doDeleteArticleReal(
2114 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null,
2115 $tags = []
2116 ) {
2117 return $this->mPage->doDeleteArticleReal(
2118 $reason, $suppress, $u1, $u2, $error, $user, $tags
2119 );
2120 }
2121
2122 /**
2123 * Call to WikiPage function for backwards compatibility.
2124 * @see WikiPage::doDeleteUpdates
2125 */
2126 public function doDeleteUpdates( $id, Content $content = null ) {
2127 return $this->mPage->doDeleteUpdates( $id, $content );
2128 }
2129
2130 /**
2131 * Call to WikiPage function for backwards compatibility.
2132 * @deprecated since 1.29. Use WikiPage::doEditContent() directly instead
2133 * @see WikiPage::doEditContent
2134 */
2135 public function doEditContent( Content $content, $summary, $flags = 0, $originalRevId = false,
2136 User $user = null, $serialFormat = null
2137 ) {
2138 wfDeprecated( __METHOD__, '1.29' );
2139 return $this->mPage->doEditContent( $content, $summary, $flags, $originalRevId,
2140 $user, $serialFormat
2141 );
2142 }
2143
2144 /**
2145 * Call to WikiPage function for backwards compatibility.
2146 * @see WikiPage::doEditUpdates
2147 */
2148 public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2149 return $this->mPage->doEditUpdates( $revision, $user, $options );
2150 }
2151
2152 /**
2153 * Call to WikiPage function for backwards compatibility.
2154 * @see WikiPage::doPurge
2155 * @note In 1.28 (and only 1.28), this took a $flags parameter that
2156 * controlled how much purging was done.
2157 */
2158 public function doPurge() {
2159 return $this->mPage->doPurge();
2160 }
2161
2162 /**
2163 * Call to WikiPage function for backwards compatibility.
2164 * @see WikiPage::doViewUpdates
2165 */
2166 public function doViewUpdates( User $user, $oldid = 0 ) {
2167 $this->mPage->doViewUpdates( $user, $oldid );
2168 }
2169
2170 /**
2171 * Call to WikiPage function for backwards compatibility.
2172 * @see WikiPage::exists
2173 */
2174 public function exists() {
2175 return $this->mPage->exists();
2176 }
2177
2178 /**
2179 * Call to WikiPage function for backwards compatibility.
2180 * @see WikiPage::followRedirect
2181 */
2182 public function followRedirect() {
2183 return $this->mPage->followRedirect();
2184 }
2185
2186 /**
2187 * Call to WikiPage function for backwards compatibility.
2188 * @see ContentHandler::getActionOverrides
2189 */
2190 public function getActionOverrides() {
2191 return $this->mPage->getActionOverrides();
2192 }
2193
2194 /**
2195 * Call to WikiPage function for backwards compatibility.
2196 * @see WikiPage::getAutoDeleteReason
2197 */
2198 public function getAutoDeleteReason( &$hasHistory ) {
2199 return $this->mPage->getAutoDeleteReason( $hasHistory );
2200 }
2201
2202 /**
2203 * Call to WikiPage function for backwards compatibility.
2204 * @see WikiPage::getCategories
2205 */
2206 public function getCategories() {
2207 return $this->mPage->getCategories();
2208 }
2209
2210 /**
2211 * Call to WikiPage function for backwards compatibility.
2212 * @see WikiPage::getComment
2213 */
2214 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
2215 return $this->mPage->getComment( $audience, $user );
2216 }
2217
2218 /**
2219 * Call to WikiPage function for backwards compatibility.
2220 * @see WikiPage::getContentHandler
2221 */
2222 public function getContentHandler() {
2223 return $this->mPage->getContentHandler();
2224 }
2225
2226 /**
2227 * Call to WikiPage function for backwards compatibility.
2228 * @see WikiPage::getContentModel
2229 */
2230 public function getContentModel() {
2231 return $this->mPage->getContentModel();
2232 }
2233
2234 /**
2235 * Call to WikiPage function for backwards compatibility.
2236 * @see WikiPage::getContributors
2237 */
2238 public function getContributors() {
2239 return $this->mPage->getContributors();
2240 }
2241
2242 /**
2243 * Call to WikiPage function for backwards compatibility.
2244 * @see WikiPage::getCreator
2245 */
2246 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
2247 return $this->mPage->getCreator( $audience, $user );
2248 }
2249
2250 /**
2251 * Call to WikiPage function for backwards compatibility.
2252 * @see WikiPage::getDeletionUpdates
2253 */
2254 public function getDeletionUpdates( Content $content = null ) {
2255 return $this->mPage->getDeletionUpdates( $content );
2256 }
2257
2258 /**
2259 * Call to WikiPage function for backwards compatibility.
2260 * @see WikiPage::getHiddenCategories
2261 */
2262 public function getHiddenCategories() {
2263 return $this->mPage->getHiddenCategories();
2264 }
2265
2266 /**
2267 * Call to WikiPage function for backwards compatibility.
2268 * @see WikiPage::getId
2269 */
2270 public function getId() {
2271 return $this->mPage->getId();
2272 }
2273
2274 /**
2275 * Call to WikiPage function for backwards compatibility.
2276 * @see WikiPage::getLatest
2277 */
2278 public function getLatest() {
2279 return $this->mPage->getLatest();
2280 }
2281
2282 /**
2283 * Call to WikiPage function for backwards compatibility.
2284 * @see WikiPage::getLinksTimestamp
2285 */
2286 public function getLinksTimestamp() {
2287 return $this->mPage->getLinksTimestamp();
2288 }
2289
2290 /**
2291 * Call to WikiPage function for backwards compatibility.
2292 * @see WikiPage::getMinorEdit
2293 */
2294 public function getMinorEdit() {
2295 return $this->mPage->getMinorEdit();
2296 }
2297
2298 /**
2299 * Call to WikiPage function for backwards compatibility.
2300 * @see WikiPage::getOldestRevision
2301 */
2302 public function getOldestRevision() {
2303 return $this->mPage->getOldestRevision();
2304 }
2305
2306 /**
2307 * Call to WikiPage function for backwards compatibility.
2308 * @see WikiPage::getRedirectTarget
2309 */
2310 public function getRedirectTarget() {
2311 return $this->mPage->getRedirectTarget();
2312 }
2313
2314 /**
2315 * Call to WikiPage function for backwards compatibility.
2316 * @see WikiPage::getRedirectURL
2317 */
2318 public function getRedirectURL( $rt ) {
2319 return $this->mPage->getRedirectURL( $rt );
2320 }
2321
2322 /**
2323 * Call to WikiPage function for backwards compatibility.
2324 * @see WikiPage::getRevision
2325 */
2326 public function getRevision() {
2327 return $this->mPage->getRevision();
2328 }
2329
2330 /**
2331 * Call to WikiPage function for backwards compatibility.
2332 * @see WikiPage::getTimestamp
2333 */
2334 public function getTimestamp() {
2335 return $this->mPage->getTimestamp();
2336 }
2337
2338 /**
2339 * Call to WikiPage function for backwards compatibility.
2340 * @see WikiPage::getTouched
2341 */
2342 public function getTouched() {
2343 return $this->mPage->getTouched();
2344 }
2345
2346 /**
2347 * Call to WikiPage function for backwards compatibility.
2348 * @see WikiPage::getUndoContent
2349 */
2350 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
2351 return $this->mPage->getUndoContent( $undo, $undoafter );
2352 }
2353
2354 /**
2355 * Call to WikiPage function for backwards compatibility.
2356 * @see WikiPage::getUser
2357 */
2358 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
2359 return $this->mPage->getUser( $audience, $user );
2360 }
2361
2362 /**
2363 * Call to WikiPage function for backwards compatibility.
2364 * @see WikiPage::getUserText
2365 */
2366 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
2367 return $this->mPage->getUserText( $audience, $user );
2368 }
2369
2370 /**
2371 * Call to WikiPage function for backwards compatibility.
2372 * @see WikiPage::hasViewableContent
2373 */
2374 public function hasViewableContent() {
2375 return $this->mPage->hasViewableContent();
2376 }
2377
2378 /**
2379 * Call to WikiPage function for backwards compatibility.
2380 * @see WikiPage::insertOn
2381 */
2382 public function insertOn( $dbw, $pageId = null ) {
2383 return $this->mPage->insertOn( $dbw, $pageId );
2384 }
2385
2386 /**
2387 * Call to WikiPage function for backwards compatibility.
2388 * @see WikiPage::insertProtectNullRevision
2389 */
2390 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2391 array $expiry, $cascade, $reason, $user = null
2392 ) {
2393 return $this->mPage->insertProtectNullRevision( $revCommentMsg, $limit,
2394 $expiry, $cascade, $reason, $user
2395 );
2396 }
2397
2398 /**
2399 * Call to WikiPage function for backwards compatibility.
2400 * @see WikiPage::insertRedirect
2401 */
2402 public function insertRedirect() {
2403 return $this->mPage->insertRedirect();
2404 }
2405
2406 /**
2407 * Call to WikiPage function for backwards compatibility.
2408 * @see WikiPage::insertRedirectEntry
2409 */
2410 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
2411 return $this->mPage->insertRedirectEntry( $rt, $oldLatest );
2412 }
2413
2414 /**
2415 * Call to WikiPage function for backwards compatibility.
2416 * @see WikiPage::isCountable
2417 */
2418 public function isCountable( $editInfo = false ) {
2419 return $this->mPage->isCountable( $editInfo );
2420 }
2421
2422 /**
2423 * Call to WikiPage function for backwards compatibility.
2424 * @see WikiPage::isRedirect
2425 */
2426 public function isRedirect() {
2427 return $this->mPage->isRedirect();
2428 }
2429
2430 /**
2431 * Call to WikiPage function for backwards compatibility.
2432 * @see WikiPage::loadFromRow
2433 */
2434 public function loadFromRow( $data, $from ) {
2435 return $this->mPage->loadFromRow( $data, $from );
2436 }
2437
2438 /**
2439 * Call to WikiPage function for backwards compatibility.
2440 * @see WikiPage::loadPageData
2441 */
2442 public function loadPageData( $from = 'fromdb' ) {
2443 $this->mPage->loadPageData( $from );
2444 }
2445
2446 /**
2447 * Call to WikiPage function for backwards compatibility.
2448 * @see WikiPage::lockAndGetLatest
2449 */
2450 public function lockAndGetLatest() {
2451 return $this->mPage->lockAndGetLatest();
2452 }
2453
2454 /**
2455 * Call to WikiPage function for backwards compatibility.
2456 * @see WikiPage::makeParserOptions
2457 */
2458 public function makeParserOptions( $context ) {
2459 return $this->mPage->makeParserOptions( $context );
2460 }
2461
2462 /**
2463 * Call to WikiPage function for backwards compatibility.
2464 * @see WikiPage::pageDataFromId
2465 */
2466 public function pageDataFromId( $dbr, $id, $options = [] ) {
2467 return $this->mPage->pageDataFromId( $dbr, $id, $options );
2468 }
2469
2470 /**
2471 * Call to WikiPage function for backwards compatibility.
2472 * @see WikiPage::pageDataFromTitle
2473 */
2474 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
2475 return $this->mPage->pageDataFromTitle( $dbr, $title, $options );
2476 }
2477
2478 /**
2479 * Call to WikiPage function for backwards compatibility.
2480 * @see WikiPage::prepareContentForEdit
2481 */
2482 public function prepareContentForEdit(
2483 Content $content, $revision = null, User $user = null,
2484 $serialFormat = null, $useCache = true
2485 ) {
2486 return $this->mPage->prepareContentForEdit(
2487 $content, $revision, $user,
2488 $serialFormat, $useCache
2489 );
2490 }
2491
2492 /**
2493 * Call to WikiPage function for backwards compatibility.
2494 * @see WikiPage::protectDescription
2495 */
2496 public function protectDescription( array $limit, array $expiry ) {
2497 return $this->mPage->protectDescription( $limit, $expiry );
2498 }
2499
2500 /**
2501 * Call to WikiPage function for backwards compatibility.
2502 * @see WikiPage::protectDescriptionLog
2503 */
2504 public function protectDescriptionLog( array $limit, array $expiry ) {
2505 return $this->mPage->protectDescriptionLog( $limit, $expiry );
2506 }
2507
2508 /**
2509 * Call to WikiPage function for backwards compatibility.
2510 * @see WikiPage::replaceSectionAtRev
2511 */
2512 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
2513 $sectionTitle = '', $baseRevId = null
2514 ) {
2515 return $this->mPage->replaceSectionAtRev( $sectionId, $sectionContent,
2516 $sectionTitle, $baseRevId
2517 );
2518 }
2519
2520 /**
2521 * Call to WikiPage function for backwards compatibility.
2522 * @see WikiPage::replaceSectionContent
2523 */
2524 public function replaceSectionContent(
2525 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
2526 ) {
2527 return $this->mPage->replaceSectionContent(
2528 $sectionId, $sectionContent, $sectionTitle, $edittime
2529 );
2530 }
2531
2532 /**
2533 * Call to WikiPage function for backwards compatibility.
2534 * @see WikiPage::setTimestamp
2535 */
2536 public function setTimestamp( $ts ) {
2537 return $this->mPage->setTimestamp( $ts );
2538 }
2539
2540 /**
2541 * Call to WikiPage function for backwards compatibility.
2542 * @see WikiPage::shouldCheckParserCache
2543 */
2544 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
2545 return $this->mPage->shouldCheckParserCache( $parserOptions, $oldId );
2546 }
2547
2548 /**
2549 * Call to WikiPage function for backwards compatibility.
2550 * @see WikiPage::supportsSections
2551 */
2552 public function supportsSections() {
2553 return $this->mPage->supportsSections();
2554 }
2555
2556 /**
2557 * Call to WikiPage function for backwards compatibility.
2558 * @see WikiPage::triggerOpportunisticLinksUpdate
2559 */
2560 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
2561 return $this->mPage->triggerOpportunisticLinksUpdate( $parserOutput );
2562 }
2563
2564 /**
2565 * Call to WikiPage function for backwards compatibility.
2566 * @see WikiPage::updateCategoryCounts
2567 */
2568 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
2569 return $this->mPage->updateCategoryCounts( $added, $deleted, $id );
2570 }
2571
2572 /**
2573 * Call to WikiPage function for backwards compatibility.
2574 * @see WikiPage::updateIfNewerOn
2575 */
2576 public function updateIfNewerOn( $dbw, $revision ) {
2577 return $this->mPage->updateIfNewerOn( $dbw, $revision );
2578 }
2579
2580 /**
2581 * Call to WikiPage function for backwards compatibility.
2582 * @see WikiPage::updateRedirectOn
2583 */
2584 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
2585 return $this->mPage->updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect );
2586 }
2587
2588 /**
2589 * Call to WikiPage function for backwards compatibility.
2590 * @see WikiPage::updateRevisionOn
2591 */
2592 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
2593 $lastRevIsRedirect = null
2594 ) {
2595 return $this->mPage->updateRevisionOn( $dbw, $revision, $lastRevision,
2596 $lastRevIsRedirect
2597 );
2598 }
2599
2600 /**
2601 * @param array $limit
2602 * @param array $expiry
2603 * @param bool &$cascade
2604 * @param string $reason
2605 * @param User $user
2606 * @return Status
2607 */
2608 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade,
2609 $reason, User $user
2610 ) {
2611 return $this->mPage->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user );
2612 }
2613
2614 /**
2615 * @param array $limit
2616 * @param string $reason
2617 * @param int &$cascade
2618 * @param array $expiry
2619 * @return bool
2620 */
2621 public function updateRestrictions( $limit = [], $reason = '',
2622 &$cascade = 0, $expiry = []
2623 ) {
2624 return $this->mPage->doUpdateRestrictions(
2625 $limit,
2626 $expiry,
2627 $cascade,
2628 $reason,
2629 $this->getContext()->getUser()
2630 );
2631 }
2632
2633 /**
2634 * @param string $reason
2635 * @param bool $suppress
2636 * @param int|null $u1 Unused
2637 * @param bool|null $u2 Unused
2638 * @param string &$error
2639 * @return bool
2640 */
2641 public function doDeleteArticle(
2642 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = ''
2643 ) {
2644 return $this->mPage->doDeleteArticle( $reason, $suppress, $u1, $u2, $error );
2645 }
2646
2647 /**
2648 * @param string $fromP
2649 * @param string $summary
2650 * @param string $token
2651 * @param bool $bot
2652 * @param array &$resultDetails
2653 * @param User|null $user
2654 * @return array
2655 */
2656 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails, User $user = null ) {
2657 $user = is_null( $user ) ? $this->getContext()->getUser() : $user;
2658 return $this->mPage->doRollback( $fromP, $summary, $token, $bot, $resultDetails, $user );
2659 }
2660
2661 /**
2662 * @param string $fromP
2663 * @param string $summary
2664 * @param bool $bot
2665 * @param array &$resultDetails
2666 * @param User|null $guser
2667 * @return array
2668 */
2669 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
2670 $guser = is_null( $guser ) ? $this->getContext()->getUser() : $guser;
2671 return $this->mPage->commitRollback( $fromP, $summary, $bot, $resultDetails, $guser );
2672 }
2673
2674 /**
2675 * @param bool &$hasHistory
2676 * @return mixed
2677 */
2678 public function generateReason( &$hasHistory ) {
2679 $title = $this->mPage->getTitle();
2680 $handler = ContentHandler::getForTitle( $title );
2681 return $handler->getAutoDeleteReason( $title, $hasHistory );
2682 }
2683
2684 // ******
2685 }