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