Merge "Follow-up I0bb4ed7f7: Use correct 'this'"
[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
1687 $backlinkCache = $title->getBacklinkCache();
1688 if ( $backlinkCache->hasLinks( 'pagelinks' ) || $backlinkCache->hasLinks( 'templatelinks' ) ) {
1689 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1690 'deleting-backlinks-warning' );
1691 }
1692
1693 $subpageQueryLimit = 51;
1694 $subpages = $title->getSubpages( $subpageQueryLimit );
1695 $subpageCount = count( $subpages );
1696 if ( $subpageCount > 0 ) {
1697 $outputPage->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1698 [ 'deleting-subpages-warning', Message::numParam( $subpageCount ) ] );
1699 }
1700 $outputPage->addWikiMsg( 'confirmdeletetext' );
1701
1702 Hooks::run( 'ArticleConfirmDelete', [ $this, $outputPage, &$reason ] );
1703
1704 $user = $this->getContext()->getUser();
1705 $checkWatch = $user->getBoolOption( 'watchdeletion' ) || $user->isWatched( $title );
1706
1707 $outputPage->enableOOUI();
1708
1709 $options = Xml::listDropDownOptions(
1710 $ctx->msg( 'deletereason-dropdown' )->inContentLanguage()->text(),
1711 [ 'other' => $ctx->msg( 'deletereasonotherlist' )->inContentLanguage()->text() ]
1712 );
1713 $options = Xml::listDropDownOptionsOoui( $options );
1714
1715 $fields[] = new OOUI\FieldLayout(
1716 new OOUI\DropdownInputWidget( [
1717 'name' => 'wpDeleteReasonList',
1718 'inputId' => 'wpDeleteReasonList',
1719 'tabIndex' => 1,
1720 'infusable' => true,
1721 'value' => '',
1722 'options' => $options
1723 ] ),
1724 [
1725 'label' => $ctx->msg( 'deletecomment' )->text(),
1726 'align' => 'top',
1727 ]
1728 );
1729
1730 $fields[] = new OOUI\FieldLayout(
1731 new OOUI\TextInputWidget( [
1732 'name' => 'wpReason',
1733 'inputId' => 'wpReason',
1734 'tabIndex' => 2,
1735 'maxLength' => 255,
1736 'infusable' => true,
1737 'value' => $reason,
1738 'autofocus' => true,
1739 ] ),
1740 [
1741 'label' => $ctx->msg( 'deleteotherreason' )->text(),
1742 'align' => 'top',
1743 ]
1744 );
1745
1746 if ( $user->isLoggedIn() ) {
1747 $fields[] = new OOUI\FieldLayout(
1748 new OOUI\CheckboxInputWidget( [
1749 'name' => 'wpWatch',
1750 'inputId' => 'wpWatch',
1751 'tabIndex' => 3,
1752 'selected' => $checkWatch,
1753 ] ),
1754 [
1755 'label' => $ctx->msg( 'watchthis' )->text(),
1756 'align' => 'inline',
1757 'infusable' => true,
1758 ]
1759 );
1760 }
1761
1762 if ( $user->isAllowed( 'suppressrevision' ) ) {
1763 $fields[] = new OOUI\FieldLayout(
1764 new OOUI\CheckboxInputWidget( [
1765 'name' => 'wpSuppress',
1766 'inputId' => 'wpSuppress',
1767 'tabIndex' => 4,
1768 ] ),
1769 [
1770 'label' => $ctx->msg( 'revdelete-suppress' )->text(),
1771 'align' => 'inline',
1772 'infusable' => true,
1773 ]
1774 );
1775 }
1776
1777 $fields[] = new OOUI\FieldLayout(
1778 new OOUI\ButtonInputWidget( [
1779 'name' => 'wpConfirmB',
1780 'inputId' => 'wpConfirmB',
1781 'tabIndex' => 5,
1782 'value' => $ctx->msg( 'deletepage' )->text(),
1783 'label' => $ctx->msg( 'deletepage' )->text(),
1784 'flags' => [ 'primary', 'destructive' ],
1785 'type' => 'submit',
1786 ] ),
1787 [
1788 'align' => 'top',
1789 ]
1790 );
1791
1792 $fieldset = new OOUI\FieldsetLayout( [
1793 'label' => $ctx->msg( 'delete-legend' )->text(),
1794 'id' => 'mw-delete-table',
1795 'items' => $fields,
1796 ] );
1797
1798 $form = new OOUI\FormLayout( [
1799 'method' => 'post',
1800 'action' => $title->getLocalURL( 'action=delete' ),
1801 'id' => 'deleteconfirm',
1802 ] );
1803 $form->appendContent(
1804 $fieldset,
1805 new OOUI\HtmlSnippet(
1806 Html::hidden( 'wpEditToken', $user->getEditToken( [ 'delete', $title->getPrefixedText() ] ) )
1807 )
1808 );
1809
1810 $outputPage->addHTML(
1811 new OOUI\PanelLayout( [
1812 'classes' => [ 'deletepage-wrapper' ],
1813 'expanded' => false,
1814 'padded' => true,
1815 'framed' => true,
1816 'content' => $form,
1817 ] )
1818 );
1819
1820 if ( $user->isAllowed( 'editinterface' ) ) {
1821 $link = Linker::linkKnown(
1822 $ctx->msg( 'deletereason-dropdown' )->inContentLanguage()->getTitle(),
1823 wfMessage( 'delete-edit-reasonlist' )->escaped(),
1824 [],
1825 [ 'action' => 'edit' ]
1826 );
1827 $outputPage->addHTML( '<p class="mw-delete-editreasons">' . $link . '</p>' );
1828 }
1829
1830 $deleteLogPage = new LogPage( 'delete' );
1831 $outputPage->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) );
1832 LogEventsList::showLogExtract( $outputPage, 'delete', $title );
1833 }
1834
1835 /**
1836 * Perform a deletion and output success or failure messages
1837 * @param string $reason
1838 * @param bool $suppress
1839 */
1840 public function doDelete( $reason, $suppress = false ) {
1841 $error = '';
1842 $context = $this->getContext();
1843 $outputPage = $context->getOutput();
1844 $user = $context->getUser();
1845 $status = $this->mPage->doDeleteArticleReal( $reason, $suppress, 0, true, $error, $user );
1846
1847 if ( $status->isGood() ) {
1848 $deleted = $this->getTitle()->getPrefixedText();
1849
1850 $outputPage->setPageTitle( wfMessage( 'actioncomplete' ) );
1851 $outputPage->setRobotPolicy( 'noindex,nofollow' );
1852
1853 $loglink = '[[Special:Log/delete|' . wfMessage( 'deletionlog' )->text() . ']]';
1854
1855 $outputPage->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
1856
1857 Hooks::run( 'ArticleDeleteAfterSuccess', [ $this->getTitle(), $outputPage ] );
1858
1859 $outputPage->returnToMain( false );
1860 } else {
1861 $outputPage->setPageTitle(
1862 wfMessage( 'cannotdelete-title',
1863 $this->getTitle()->getPrefixedText() )
1864 );
1865
1866 if ( $error == '' ) {
1867 $outputPage->addWikiText(
1868 "<div class=\"error mw-error-cannotdelete\">\n" . $status->getWikiText() . "\n</div>"
1869 );
1870 $deleteLogPage = new LogPage( 'delete' );
1871 $outputPage->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) );
1872
1873 LogEventsList::showLogExtract(
1874 $outputPage,
1875 'delete',
1876 $this->getTitle()
1877 );
1878 } else {
1879 $outputPage->addHTML( $error );
1880 }
1881 }
1882 }
1883
1884 /* Caching functions */
1885
1886 /**
1887 * checkLastModified returns true if it has taken care of all
1888 * output to the client that is necessary for this request.
1889 * (that is, it has sent a cached version of the page)
1890 *
1891 * @return bool True if cached version send, false otherwise
1892 */
1893 protected function tryFileCache() {
1894 static $called = false;
1895
1896 if ( $called ) {
1897 wfDebug( "Article::tryFileCache(): called twice!?\n" );
1898 return false;
1899 }
1900
1901 $called = true;
1902 if ( $this->isFileCacheable() ) {
1903 $cache = new HTMLFileCache( $this->getTitle(), 'view' );
1904 if ( $cache->isCacheGood( $this->mPage->getTouched() ) ) {
1905 wfDebug( "Article::tryFileCache(): about to load file\n" );
1906 $cache->loadFromFileCache( $this->getContext() );
1907 return true;
1908 } else {
1909 wfDebug( "Article::tryFileCache(): starting buffer\n" );
1910 ob_start( [ &$cache, 'saveToFileCache' ] );
1911 }
1912 } else {
1913 wfDebug( "Article::tryFileCache(): not cacheable\n" );
1914 }
1915
1916 return false;
1917 }
1918
1919 /**
1920 * Check if the page can be cached
1921 * @param int $mode One of the HTMLFileCache::MODE_* constants (since 1.28)
1922 * @return bool
1923 */
1924 public function isFileCacheable( $mode = HTMLFileCache::MODE_NORMAL ) {
1925 $cacheable = false;
1926
1927 if ( HTMLFileCache::useFileCache( $this->getContext(), $mode ) ) {
1928 $cacheable = $this->mPage->getId()
1929 && !$this->mRedirectedFrom && !$this->getTitle()->isRedirect();
1930 // Extension may have reason to disable file caching on some pages.
1931 if ( $cacheable ) {
1932 // Avoid PHP 7.1 warning of passing $this by reference
1933 $articlePage = $this;
1934 $cacheable = Hooks::run( 'IsFileCacheable', [ &$articlePage ] );
1935 }
1936 }
1937
1938 return $cacheable;
1939 }
1940
1941 /**#@-*/
1942
1943 /**
1944 * Lightweight method to get the parser output for a page, checking the parser cache
1945 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
1946 * consider, so it's not appropriate to use there.
1947 *
1948 * @since 1.16 (r52326) for LiquidThreads
1949 *
1950 * @param int|null $oldid Revision ID or null
1951 * @param User $user The relevant user
1952 * @return ParserOutput|bool ParserOutput or false if the given revision ID is not found
1953 */
1954 public function getParserOutput( $oldid = null, User $user = null ) {
1955 // XXX: bypasses mParserOptions and thus setParserOptions()
1956
1957 if ( $user === null ) {
1958 $parserOptions = $this->getParserOptions();
1959 } else {
1960 $parserOptions = $this->mPage->makeParserOptions( $user );
1961 }
1962
1963 return $this->mPage->getParserOutput( $parserOptions, $oldid );
1964 }
1965
1966 /**
1967 * Override the ParserOptions used to render the primary article wikitext.
1968 *
1969 * @param ParserOptions $options
1970 * @throws MWException If the parser options where already initialized.
1971 */
1972 public function setParserOptions( ParserOptions $options ) {
1973 if ( $this->mParserOptions ) {
1974 throw new MWException( "can't change parser options after they have already been set" );
1975 }
1976
1977 // clone, so if $options is modified later, it doesn't confuse the parser cache.
1978 $this->mParserOptions = clone $options;
1979 }
1980
1981 /**
1982 * Get parser options suitable for rendering the primary article wikitext
1983 * @return ParserOptions
1984 */
1985 public function getParserOptions() {
1986 if ( !$this->mParserOptions ) {
1987 $this->mParserOptions = $this->mPage->makeParserOptions( $this->getContext() );
1988 }
1989 // Clone to allow modifications of the return value without affecting cache
1990 return clone $this->mParserOptions;
1991 }
1992
1993 /**
1994 * Sets the context this Article is executed in
1995 *
1996 * @param IContextSource $context
1997 * @since 1.18
1998 */
1999 public function setContext( $context ) {
2000 $this->mContext = $context;
2001 }
2002
2003 /**
2004 * Gets the context this Article is executed in
2005 *
2006 * @return IContextSource
2007 * @since 1.18
2008 */
2009 public function getContext() {
2010 if ( $this->mContext instanceof IContextSource ) {
2011 return $this->mContext;
2012 } else {
2013 wfDebug( __METHOD__ . " called and \$mContext is null. " .
2014 "Return RequestContext::getMain(); for sanity\n" );
2015 return RequestContext::getMain();
2016 }
2017 }
2018
2019 /**
2020 * Use PHP's magic __get handler to handle accessing of
2021 * raw WikiPage fields for backwards compatibility.
2022 *
2023 * @param string $fname Field name
2024 * @return mixed
2025 */
2026 public function __get( $fname ) {
2027 if ( property_exists( $this->mPage, $fname ) ) {
2028 # wfWarn( "Access to raw $fname field " . __CLASS__ );
2029 return $this->mPage->$fname;
2030 }
2031 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE );
2032 }
2033
2034 /**
2035 * Use PHP's magic __set handler to handle setting of
2036 * raw WikiPage fields for backwards compatibility.
2037 *
2038 * @param string $fname Field name
2039 * @param mixed $fvalue New value
2040 */
2041 public function __set( $fname, $fvalue ) {
2042 if ( property_exists( $this->mPage, $fname ) ) {
2043 # wfWarn( "Access to raw $fname field of " . __CLASS__ );
2044 $this->mPage->$fname = $fvalue;
2045 // Note: extensions may want to toss on new fields
2046 } elseif ( !in_array( $fname, [ 'mContext', 'mPage' ] ) ) {
2047 $this->mPage->$fname = $fvalue;
2048 } else {
2049 trigger_error( 'Inaccessible property via __set(): ' . $fname, E_USER_NOTICE );
2050 }
2051 }
2052
2053 /**
2054 * Call to WikiPage function for backwards compatibility.
2055 * @see WikiPage::checkFlags
2056 */
2057 public function checkFlags( $flags ) {
2058 return $this->mPage->checkFlags( $flags );
2059 }
2060
2061 /**
2062 * Call to WikiPage function for backwards compatibility.
2063 * @see WikiPage::checkTouched
2064 */
2065 public function checkTouched() {
2066 return $this->mPage->checkTouched();
2067 }
2068
2069 /**
2070 * Call to WikiPage function for backwards compatibility.
2071 * @see WikiPage::clearPreparedEdit
2072 */
2073 public function clearPreparedEdit() {
2074 $this->mPage->clearPreparedEdit();
2075 }
2076
2077 /**
2078 * Call to WikiPage function for backwards compatibility.
2079 * @see WikiPage::doDeleteArticleReal
2080 */
2081 public function doDeleteArticleReal(
2082 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null,
2083 $tags = []
2084 ) {
2085 return $this->mPage->doDeleteArticleReal(
2086 $reason, $suppress, $u1, $u2, $error, $user, $tags
2087 );
2088 }
2089
2090 /**
2091 * Call to WikiPage function for backwards compatibility.
2092 * @see WikiPage::doDeleteUpdates
2093 */
2094 public function doDeleteUpdates( $id, Content $content = null ) {
2095 return $this->mPage->doDeleteUpdates( $id, $content );
2096 }
2097
2098 /**
2099 * Call to WikiPage function for backwards compatibility.
2100 * @deprecated since 1.29. Use WikiPage::doEditContent() directly instead
2101 * @see WikiPage::doEditContent
2102 */
2103 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
2104 User $user = null, $serialFormat = null
2105 ) {
2106 wfDeprecated( __METHOD__, '1.29' );
2107 return $this->mPage->doEditContent( $content, $summary, $flags, $baseRevId,
2108 $user, $serialFormat
2109 );
2110 }
2111
2112 /**
2113 * Call to WikiPage function for backwards compatibility.
2114 * @see WikiPage::doEditUpdates
2115 */
2116 public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2117 return $this->mPage->doEditUpdates( $revision, $user, $options );
2118 }
2119
2120 /**
2121 * Call to WikiPage function for backwards compatibility.
2122 * @see WikiPage::doPurge
2123 * @note In 1.28 (and only 1.28), this took a $flags parameter that
2124 * controlled how much purging was done.
2125 */
2126 public function doPurge() {
2127 return $this->mPage->doPurge();
2128 }
2129
2130 /**
2131 * Call to WikiPage function for backwards compatibility.
2132 * @see WikiPage::doViewUpdates
2133 */
2134 public function doViewUpdates( User $user, $oldid = 0 ) {
2135 $this->mPage->doViewUpdates( $user, $oldid );
2136 }
2137
2138 /**
2139 * Call to WikiPage function for backwards compatibility.
2140 * @see WikiPage::exists
2141 */
2142 public function exists() {
2143 return $this->mPage->exists();
2144 }
2145
2146 /**
2147 * Call to WikiPage function for backwards compatibility.
2148 * @see WikiPage::followRedirect
2149 */
2150 public function followRedirect() {
2151 return $this->mPage->followRedirect();
2152 }
2153
2154 /**
2155 * Call to WikiPage function for backwards compatibility.
2156 * @see ContentHandler::getActionOverrides
2157 */
2158 public function getActionOverrides() {
2159 return $this->mPage->getActionOverrides();
2160 }
2161
2162 /**
2163 * Call to WikiPage function for backwards compatibility.
2164 * @see WikiPage::getAutoDeleteReason
2165 */
2166 public function getAutoDeleteReason( &$hasHistory ) {
2167 return $this->mPage->getAutoDeleteReason( $hasHistory );
2168 }
2169
2170 /**
2171 * Call to WikiPage function for backwards compatibility.
2172 * @see WikiPage::getCategories
2173 */
2174 public function getCategories() {
2175 return $this->mPage->getCategories();
2176 }
2177
2178 /**
2179 * Call to WikiPage function for backwards compatibility.
2180 * @see WikiPage::getComment
2181 */
2182 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
2183 return $this->mPage->getComment( $audience, $user );
2184 }
2185
2186 /**
2187 * Call to WikiPage function for backwards compatibility.
2188 * @see WikiPage::getContentHandler
2189 */
2190 public function getContentHandler() {
2191 return $this->mPage->getContentHandler();
2192 }
2193
2194 /**
2195 * Call to WikiPage function for backwards compatibility.
2196 * @see WikiPage::getContentModel
2197 */
2198 public function getContentModel() {
2199 return $this->mPage->getContentModel();
2200 }
2201
2202 /**
2203 * Call to WikiPage function for backwards compatibility.
2204 * @see WikiPage::getContributors
2205 */
2206 public function getContributors() {
2207 return $this->mPage->getContributors();
2208 }
2209
2210 /**
2211 * Call to WikiPage function for backwards compatibility.
2212 * @see WikiPage::getCreator
2213 */
2214 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
2215 return $this->mPage->getCreator( $audience, $user );
2216 }
2217
2218 /**
2219 * Call to WikiPage function for backwards compatibility.
2220 * @see WikiPage::getDeletionUpdates
2221 */
2222 public function getDeletionUpdates( Content $content = null ) {
2223 return $this->mPage->getDeletionUpdates( $content );
2224 }
2225
2226 /**
2227 * Call to WikiPage function for backwards compatibility.
2228 * @see WikiPage::getHiddenCategories
2229 */
2230 public function getHiddenCategories() {
2231 return $this->mPage->getHiddenCategories();
2232 }
2233
2234 /**
2235 * Call to WikiPage function for backwards compatibility.
2236 * @see WikiPage::getId
2237 */
2238 public function getId() {
2239 return $this->mPage->getId();
2240 }
2241
2242 /**
2243 * Call to WikiPage function for backwards compatibility.
2244 * @see WikiPage::getLatest
2245 */
2246 public function getLatest() {
2247 return $this->mPage->getLatest();
2248 }
2249
2250 /**
2251 * Call to WikiPage function for backwards compatibility.
2252 * @see WikiPage::getLinksTimestamp
2253 */
2254 public function getLinksTimestamp() {
2255 return $this->mPage->getLinksTimestamp();
2256 }
2257
2258 /**
2259 * Call to WikiPage function for backwards compatibility.
2260 * @see WikiPage::getMinorEdit
2261 */
2262 public function getMinorEdit() {
2263 return $this->mPage->getMinorEdit();
2264 }
2265
2266 /**
2267 * Call to WikiPage function for backwards compatibility.
2268 * @see WikiPage::getOldestRevision
2269 */
2270 public function getOldestRevision() {
2271 return $this->mPage->getOldestRevision();
2272 }
2273
2274 /**
2275 * Call to WikiPage function for backwards compatibility.
2276 * @see WikiPage::getRedirectTarget
2277 */
2278 public function getRedirectTarget() {
2279 return $this->mPage->getRedirectTarget();
2280 }
2281
2282 /**
2283 * Call to WikiPage function for backwards compatibility.
2284 * @see WikiPage::getRedirectURL
2285 */
2286 public function getRedirectURL( $rt ) {
2287 return $this->mPage->getRedirectURL( $rt );
2288 }
2289
2290 /**
2291 * Call to WikiPage function for backwards compatibility.
2292 * @see WikiPage::getRevision
2293 */
2294 public function getRevision() {
2295 return $this->mPage->getRevision();
2296 }
2297
2298 /**
2299 * Call to WikiPage function for backwards compatibility.
2300 * @see WikiPage::getTimestamp
2301 */
2302 public function getTimestamp() {
2303 return $this->mPage->getTimestamp();
2304 }
2305
2306 /**
2307 * Call to WikiPage function for backwards compatibility.
2308 * @see WikiPage::getTouched
2309 */
2310 public function getTouched() {
2311 return $this->mPage->getTouched();
2312 }
2313
2314 /**
2315 * Call to WikiPage function for backwards compatibility.
2316 * @see WikiPage::getUndoContent
2317 */
2318 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
2319 return $this->mPage->getUndoContent( $undo, $undoafter );
2320 }
2321
2322 /**
2323 * Call to WikiPage function for backwards compatibility.
2324 * @see WikiPage::getUser
2325 */
2326 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
2327 return $this->mPage->getUser( $audience, $user );
2328 }
2329
2330 /**
2331 * Call to WikiPage function for backwards compatibility.
2332 * @see WikiPage::getUserText
2333 */
2334 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
2335 return $this->mPage->getUserText( $audience, $user );
2336 }
2337
2338 /**
2339 * Call to WikiPage function for backwards compatibility.
2340 * @see WikiPage::hasViewableContent
2341 */
2342 public function hasViewableContent() {
2343 return $this->mPage->hasViewableContent();
2344 }
2345
2346 /**
2347 * Call to WikiPage function for backwards compatibility.
2348 * @see WikiPage::insertOn
2349 */
2350 public function insertOn( $dbw, $pageId = null ) {
2351 return $this->mPage->insertOn( $dbw, $pageId );
2352 }
2353
2354 /**
2355 * Call to WikiPage function for backwards compatibility.
2356 * @see WikiPage::insertProtectNullRevision
2357 */
2358 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2359 array $expiry, $cascade, $reason, $user = null
2360 ) {
2361 return $this->mPage->insertProtectNullRevision( $revCommentMsg, $limit,
2362 $expiry, $cascade, $reason, $user
2363 );
2364 }
2365
2366 /**
2367 * Call to WikiPage function for backwards compatibility.
2368 * @see WikiPage::insertRedirect
2369 */
2370 public function insertRedirect() {
2371 return $this->mPage->insertRedirect();
2372 }
2373
2374 /**
2375 * Call to WikiPage function for backwards compatibility.
2376 * @see WikiPage::insertRedirectEntry
2377 */
2378 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
2379 return $this->mPage->insertRedirectEntry( $rt, $oldLatest );
2380 }
2381
2382 /**
2383 * Call to WikiPage function for backwards compatibility.
2384 * @see WikiPage::isCountable
2385 */
2386 public function isCountable( $editInfo = false ) {
2387 return $this->mPage->isCountable( $editInfo );
2388 }
2389
2390 /**
2391 * Call to WikiPage function for backwards compatibility.
2392 * @see WikiPage::isRedirect
2393 */
2394 public function isRedirect() {
2395 return $this->mPage->isRedirect();
2396 }
2397
2398 /**
2399 * Call to WikiPage function for backwards compatibility.
2400 * @see WikiPage::loadFromRow
2401 */
2402 public function loadFromRow( $data, $from ) {
2403 return $this->mPage->loadFromRow( $data, $from );
2404 }
2405
2406 /**
2407 * Call to WikiPage function for backwards compatibility.
2408 * @see WikiPage::loadPageData
2409 */
2410 public function loadPageData( $from = 'fromdb' ) {
2411 $this->mPage->loadPageData( $from );
2412 }
2413
2414 /**
2415 * Call to WikiPage function for backwards compatibility.
2416 * @see WikiPage::lockAndGetLatest
2417 */
2418 public function lockAndGetLatest() {
2419 return $this->mPage->lockAndGetLatest();
2420 }
2421
2422 /**
2423 * Call to WikiPage function for backwards compatibility.
2424 * @see WikiPage::makeParserOptions
2425 */
2426 public function makeParserOptions( $context ) {
2427 return $this->mPage->makeParserOptions( $context );
2428 }
2429
2430 /**
2431 * Call to WikiPage function for backwards compatibility.
2432 * @see WikiPage::pageDataFromId
2433 */
2434 public function pageDataFromId( $dbr, $id, $options = [] ) {
2435 return $this->mPage->pageDataFromId( $dbr, $id, $options );
2436 }
2437
2438 /**
2439 * Call to WikiPage function for backwards compatibility.
2440 * @see WikiPage::pageDataFromTitle
2441 */
2442 public function pageDataFromTitle( $dbr, $title, $options = [] ) {
2443 return $this->mPage->pageDataFromTitle( $dbr, $title, $options );
2444 }
2445
2446 /**
2447 * Call to WikiPage function for backwards compatibility.
2448 * @see WikiPage::prepareContentForEdit
2449 */
2450 public function prepareContentForEdit(
2451 Content $content, $revision = null, User $user = null,
2452 $serialFormat = null, $useCache = true
2453 ) {
2454 return $this->mPage->prepareContentForEdit(
2455 $content, $revision, $user,
2456 $serialFormat, $useCache
2457 );
2458 }
2459
2460 /**
2461 * Call to WikiPage function for backwards compatibility.
2462 * @see WikiPage::protectDescription
2463 */
2464 public function protectDescription( array $limit, array $expiry ) {
2465 return $this->mPage->protectDescription( $limit, $expiry );
2466 }
2467
2468 /**
2469 * Call to WikiPage function for backwards compatibility.
2470 * @see WikiPage::protectDescriptionLog
2471 */
2472 public function protectDescriptionLog( array $limit, array $expiry ) {
2473 return $this->mPage->protectDescriptionLog( $limit, $expiry );
2474 }
2475
2476 /**
2477 * Call to WikiPage function for backwards compatibility.
2478 * @see WikiPage::replaceSectionAtRev
2479 */
2480 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
2481 $sectionTitle = '', $baseRevId = null
2482 ) {
2483 return $this->mPage->replaceSectionAtRev( $sectionId, $sectionContent,
2484 $sectionTitle, $baseRevId
2485 );
2486 }
2487
2488 /**
2489 * Call to WikiPage function for backwards compatibility.
2490 * @see WikiPage::replaceSectionContent
2491 */
2492 public function replaceSectionContent(
2493 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
2494 ) {
2495 return $this->mPage->replaceSectionContent(
2496 $sectionId, $sectionContent, $sectionTitle, $edittime
2497 );
2498 }
2499
2500 /**
2501 * Call to WikiPage function for backwards compatibility.
2502 * @see WikiPage::setTimestamp
2503 */
2504 public function setTimestamp( $ts ) {
2505 return $this->mPage->setTimestamp( $ts );
2506 }
2507
2508 /**
2509 * Call to WikiPage function for backwards compatibility.
2510 * @see WikiPage::shouldCheckParserCache
2511 */
2512 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
2513 return $this->mPage->shouldCheckParserCache( $parserOptions, $oldId );
2514 }
2515
2516 /**
2517 * Call to WikiPage function for backwards compatibility.
2518 * @see WikiPage::supportsSections
2519 */
2520 public function supportsSections() {
2521 return $this->mPage->supportsSections();
2522 }
2523
2524 /**
2525 * Call to WikiPage function for backwards compatibility.
2526 * @see WikiPage::triggerOpportunisticLinksUpdate
2527 */
2528 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
2529 return $this->mPage->triggerOpportunisticLinksUpdate( $parserOutput );
2530 }
2531
2532 /**
2533 * Call to WikiPage function for backwards compatibility.
2534 * @see WikiPage::updateCategoryCounts
2535 */
2536 public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
2537 return $this->mPage->updateCategoryCounts( $added, $deleted, $id );
2538 }
2539
2540 /**
2541 * Call to WikiPage function for backwards compatibility.
2542 * @see WikiPage::updateIfNewerOn
2543 */
2544 public function updateIfNewerOn( $dbw, $revision ) {
2545 return $this->mPage->updateIfNewerOn( $dbw, $revision );
2546 }
2547
2548 /**
2549 * Call to WikiPage function for backwards compatibility.
2550 * @see WikiPage::updateRedirectOn
2551 */
2552 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
2553 return $this->mPage->updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect );
2554 }
2555
2556 /**
2557 * Call to WikiPage function for backwards compatibility.
2558 * @see WikiPage::updateRevisionOn
2559 */
2560 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
2561 $lastRevIsRedirect = null
2562 ) {
2563 return $this->mPage->updateRevisionOn( $dbw, $revision, $lastRevision,
2564 $lastRevIsRedirect
2565 );
2566 }
2567
2568 /**
2569 * @param array $limit
2570 * @param array $expiry
2571 * @param bool &$cascade
2572 * @param string $reason
2573 * @param User $user
2574 * @return Status
2575 */
2576 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade,
2577 $reason, User $user
2578 ) {
2579 return $this->mPage->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user );
2580 }
2581
2582 /**
2583 * @param array $limit
2584 * @param string $reason
2585 * @param int &$cascade
2586 * @param array $expiry
2587 * @return bool
2588 */
2589 public function updateRestrictions( $limit = [], $reason = '',
2590 &$cascade = 0, $expiry = []
2591 ) {
2592 return $this->mPage->doUpdateRestrictions(
2593 $limit,
2594 $expiry,
2595 $cascade,
2596 $reason,
2597 $this->getContext()->getUser()
2598 );
2599 }
2600
2601 /**
2602 * @param string $reason
2603 * @param bool $suppress
2604 * @param int $u1 Unused
2605 * @param bool $u2 Unused
2606 * @param string &$error
2607 * @return bool
2608 */
2609 public function doDeleteArticle(
2610 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = ''
2611 ) {
2612 return $this->mPage->doDeleteArticle( $reason, $suppress, $u1, $u2, $error );
2613 }
2614
2615 /**
2616 * @param string $fromP
2617 * @param string $summary
2618 * @param string $token
2619 * @param bool $bot
2620 * @param array &$resultDetails
2621 * @param User|null $user
2622 * @return array
2623 */
2624 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails, User $user = null ) {
2625 $user = is_null( $user ) ? $this->getContext()->getUser() : $user;
2626 return $this->mPage->doRollback( $fromP, $summary, $token, $bot, $resultDetails, $user );
2627 }
2628
2629 /**
2630 * @param string $fromP
2631 * @param string $summary
2632 * @param bool $bot
2633 * @param array &$resultDetails
2634 * @param User|null $guser
2635 * @return array
2636 */
2637 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
2638 $guser = is_null( $guser ) ? $this->getContext()->getUser() : $guser;
2639 return $this->mPage->commitRollback( $fromP, $summary, $bot, $resultDetails, $guser );
2640 }
2641
2642 /**
2643 * @param bool &$hasHistory
2644 * @return mixed
2645 */
2646 public function generateReason( &$hasHistory ) {
2647 $title = $this->mPage->getTitle();
2648 $handler = ContentHandler::getForTitle( $title );
2649 return $handler->getAutoDeleteReason( $title, $hasHistory );
2650 }
2651
2652 // ******
2653 }