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