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