minimize use of textual page content, clean up hooks for custom page rendering
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class for viewing MediaWiki article and history.
9 *
10 * This maintains WikiPage functions for backwards compatibility.
11 *
12 * @TODO: move and rewrite code to an Action class
13 *
14 * See design.txt for an overview.
15 * Note: edit user interface and cache support functions have been
16 * moved to separate EditPage and HTMLFileCache classes.
17 *
18 * @internal documentation reviewed 15 Mar 2010
19 */
20 class Article extends Page {
21 /**@{{
22 * @private
23 */
24
25 /**
26 * @var IContextSource
27 */
28 protected $mContext;
29
30 /**
31 * @var WikiPage
32 */
33 protected $mPage;
34
35 /**
36 * @var ParserOptions: ParserOptions object for $wgUser articles
37 */
38 public $mParserOptions;
39
40 var $mContent; // !< #BC cruft
41 var $mContentObject; // !<
42 var $mContentLoaded = false; // !<
43 var $mOldId; // !<
44
45 /**
46 * @var Title
47 */
48 var $mRedirectedFrom = null;
49
50 /**
51 * @var mixed: boolean false or URL string
52 */
53 var $mRedirectUrl = false; // !<
54 var $mRevIdFetched = 0; // !<
55
56 /**
57 * @var Revision
58 */
59 var $mRevision = null;
60
61 /**
62 * @var ParserOutput
63 */
64 var $mParserOutput;
65
66 /**@}}*/
67
68 /**
69 * Constructor and clear the article
70 * @param $title Title Reference to a Title object.
71 * @param $oldId Integer revision ID, null to fetch from request, zero for current
72 */
73 public function __construct( Title $title, $oldId = null ) {
74 $this->mOldId = $oldId;
75 $this->mPage = $this->newPage( $title );
76 }
77
78 /**
79 * @param $title Title
80 * @return WikiPage
81 */
82 protected function newPage( Title $title ) {
83 return new WikiPage( $title );
84 }
85
86 /**
87 * Constructor from a page id
88 * @param $id Int article ID to load
89 * @return Article|null
90 */
91 public static function newFromID( $id ) {
92 $t = Title::newFromID( $id );
93 # @todo FIXME: Doesn't inherit right
94 return $t == null ? null : new self( $t );
95 # return $t == null ? null : new static( $t ); // PHP 5.3
96 }
97
98 /**
99 * Create an Article object of the appropriate class for the given page.
100 *
101 * @param $title Title
102 * @param $context IContextSource
103 * @return Article object
104 */
105 public static function newFromTitle( $title, IContextSource $context ) {
106 if ( NS_MEDIA == $title->getNamespace() ) {
107 // FIXME: where should this go?
108 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
109 }
110
111 $page = null;
112 wfRunHooks( 'ArticleFromTitle', array( &$title, &$page ) );
113 if ( !$page ) {
114 switch( $title->getNamespace() ) {
115 case NS_FILE:
116 $page = new ImagePage( $title ); #FIXME: teach ImagePage to use ContentHandler
117 break;
118 case NS_CATEGORY:
119 $page = new CategoryPage( $title ); #FIXME: teach ImagePage to use ContentHandler
120 break;
121 default:
122 $handler = ContentHandler::getForTitle( $title );
123 $page = $handler->createArticle( $title );
124 }
125 }
126 $page->setContext( $context );
127
128 return $page;
129 }
130
131 /**
132 * Create an Article object of the appropriate class for the given page.
133 *
134 * @param $page WikiPage
135 * @param $context IContextSource
136 * @return Article object
137 */
138 public static function newFromWikiPage( WikiPage $page, IContextSource $context ) {
139 $article = self::newFromTitle( $page->getTitle(), $context );
140 $article->mPage = $page; // override to keep process cached vars
141 return $article;
142 }
143
144 /**
145 * Tell the page view functions that this view was redirected
146 * from another page on the wiki.
147 * @param $from Title object.
148 */
149 public function setRedirectedFrom( Title $from ) {
150 $this->mRedirectedFrom = $from;
151 }
152
153 /**
154 * Get the title object of the article
155 *
156 * @return Title object of this page
157 */
158 public function getTitle() {
159 return $this->mPage->getTitle();
160 }
161
162 /**
163 * Get the WikiPage object of this instance
164 *
165 * @since 1.19
166 * @return WikiPage
167 */
168 public function getPage() {
169 return $this->mPage;
170 }
171
172 /**
173 * Clear the object
174 */
175 public function clear() {
176 $this->mContentLoaded = false;
177
178 $this->mRedirectedFrom = null; # Title object if set
179 $this->mRevIdFetched = 0;
180 $this->mRedirectUrl = false;
181
182 $this->mPage->clear();
183 }
184
185 /**
186 * Note that getContent/loadContent do not follow redirects anymore.
187 * If you need to fetch redirectable content easily, try
188 * the shortcut in WikiPage::getRedirectTarget()
189 *
190 * This function has side effects! Do not use this function if you
191 * only want the real revision text if any.
192 *
193 * @return Return the text of this revision
194 * @deprecated in 1.20; use getContentObject() instead
195 */
196 public function getContent() {
197 wfDeprecated( __METHOD__, '1.20' );
198 $content = $this->getContentObject();
199 return ContentHandler::getContentText( $content );
200 }
201
202 /**
203 * Note that getContent/loadContent do not follow redirects anymore.
204 * If you need to fetch redirectable content easily, try
205 * the shortcut in WikiPage::getRedirectTarget()
206 *
207 * This function has side effects! Do not use this function if you
208 * only want the real revision text if any.
209 *
210 * @return Return the content of this revision
211 */
212 public function getContentObject() {
213 global $wgUser;
214
215 wfProfileIn( __METHOD__ );
216
217 if ( $this->mPage->getID() === 0 ) {
218 # If this is a MediaWiki:x message, then load the messages
219 # and return the message value for x.
220 if ( $this->getTitle()->getNamespace() == NS_MEDIAWIKI ) {
221 $text = $this->getTitle()->getDefaultMessageText();
222 if ( $text === false ) {
223 $text = '';
224 }
225 } else {
226 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
227 }
228 wfProfileOut( __METHOD__ );
229
230 return ContentHandler::makeContent( $text, $this->getTitle() );
231 } else {
232 $this->fetchContentObject();
233 wfProfileOut( __METHOD__ );
234
235 return $this->mContentObject;
236 }
237 }
238
239 /**
240 * @return int The oldid of the article that is to be shown, 0 for the
241 * current revision
242 */
243 public function getOldID() {
244 if ( is_null( $this->mOldId ) ) {
245 $this->mOldId = $this->getOldIDFromRequest();
246 }
247
248 return $this->mOldId;
249 }
250
251 /**
252 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
253 *
254 * @return int The old id for the request
255 */
256 public function getOldIDFromRequest() {
257 global $wgRequest;
258
259 $this->mRedirectUrl = false;
260
261 $oldid = $wgRequest->getIntOrNull( 'oldid' );
262
263 if ( $oldid === null ) {
264 return 0;
265 }
266
267 if ( $oldid !== 0 ) {
268 # Load the given revision and check whether the page is another one.
269 # In that case, update this instance to reflect the change.
270 $this->mRevision = Revision::newFromId( $oldid );
271 if ( $this->mRevision !== null ) {
272 // Revision title doesn't match the page title given?
273 if ( $this->mPage->getID() != $this->mRevision->getPage() ) {
274 $function = array( get_class( $this->mPage ), 'newFromID' );
275 $this->mPage = call_user_func( $function, $this->mRevision->getPage() );
276 }
277 }
278 }
279
280 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
281 $nextid = $this->getTitle()->getNextRevisionID( $oldid );
282 if ( $nextid ) {
283 $oldid = $nextid;
284 $this->mRevision = null;
285 } else {
286 $this->mRedirectUrl = $this->getTitle()->getFullURL( 'redirect=no' );
287 }
288 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
289 $previd = $this->getTitle()->getPreviousRevisionID( $oldid );
290 if ( $previd ) {
291 $oldid = $previd;
292 $this->mRevision = null;
293 }
294 }
295
296 return $oldid;
297 }
298
299 /**
300 * Load the revision (including text) into this object
301 *
302 * @deprecated in 1.19; use fetchContent()
303 */
304 function loadContent() {
305 wfDeprecated( __METHOD__, '1.19' );
306 $this->fetchContent();
307 }
308
309 /**
310 * Get text of an article from database
311 * Does *NOT* follow redirects.
312 *
313 * @return mixed string containing article contents, or false if null
314 * @deprecated in 1.20, use getContentObject() instead
315 */
316 protected function fetchContent() { #BC cruft!
317 wfDeprecated( __METHOD__, '1.20' );
318
319 if ( $this->mContentLoaded && $this->mContent ) {
320 return $this->mContent;
321 }
322
323 wfProfileIn( __METHOD__ );
324
325 $content = $this->fetchContentObject();
326
327 $this->mContent = ContentHandler::getContentText( $content ); #FIXME: get rid of mContent everywhere!
328 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ); #BC cruft!
329
330 wfProfileOut( __METHOD__ );
331
332 return $this->mContent;
333 }
334
335
336 /**
337 * Get text content object
338 * Does *NOT* follow redirects.
339 *
340 * @return Content object containing article contents, or null
341 */
342 protected function fetchContentObject() {
343 if ( $this->mContentLoaded ) {
344 return $this->mContentObject;
345 }
346
347 wfProfileIn( __METHOD__ );
348
349 $this->mContentLoaded = true;
350 $this->mContent = null;
351
352 $oldid = $this->getOldID();
353
354 # Pre-fill content with error message so that if something
355 # fails we'll have something telling us what we intended.
356 $t = $this->getTitle()->getPrefixedText();
357 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
358 $this->mContentObject = new MessageContent( 'missing-article', array($t, $d), array() ) ;
359
360 if ( $oldid ) {
361 # $this->mRevision might already be fetched by getOldIDFromRequest()
362 if ( !$this->mRevision ) {
363 $this->mRevision = Revision::newFromId( $oldid );
364 if ( !$this->mRevision ) {
365 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
366 wfProfileOut( __METHOD__ );
367 return false;
368 }
369 }
370 } else {
371 if ( !$this->mPage->getLatest() ) {
372 wfDebug( __METHOD__ . " failed to find page data for title " . $this->getTitle()->getPrefixedText() . "\n" );
373 wfProfileOut( __METHOD__ );
374 return false;
375 }
376
377 $this->mRevision = $this->mPage->getRevision();
378
379 if ( !$this->mRevision ) {
380 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id " . $this->mPage->getLatest() . "\n" );
381 wfProfileOut( __METHOD__ );
382 return false;
383 }
384 }
385
386 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
387 // We should instead work with the Revision object when we need it...
388 $this->mContentObject = $this->mRevision->getContent( Revision::FOR_THIS_USER ); // Loads if user is allowed
389 $this->mRevIdFetched = $this->mRevision->getId();
390
391 wfRunHooks( 'ArticleAfterFetchContentObject', array( &$this, &$this->mContentObject ) ); #FIXME: register new hook
392
393 wfProfileOut( __METHOD__ );
394
395 return $this->mContentObject;
396 }
397
398 /**
399 * No-op
400 * @deprecated since 1.18
401 */
402 public function forUpdate() {
403 wfDeprecated( __METHOD__, '1.18' );
404 }
405
406 /**
407 * Returns true if the currently-referenced revision is the current edit
408 * to this page (and it exists).
409 * @return bool
410 */
411 public function isCurrent() {
412 # If no oldid, this is the current version.
413 if ( $this->getOldID() == 0 ) {
414 return true;
415 }
416
417 return $this->mPage->exists() && $this->mRevision && $this->mRevision->isCurrent();
418 }
419
420 /**
421 * Get the fetched Revision object depending on request parameters or null
422 * on failure.
423 *
424 * @since 1.19
425 * @return Revision|null
426 */
427 public function getRevisionFetched() {
428 $this->fetchContentObject();
429
430 return $this->mRevision;
431 }
432
433 /**
434 * Use this to fetch the rev ID used on page views
435 *
436 * @return int revision ID of last article revision
437 */
438 public function getRevIdFetched() {
439 if ( $this->mRevIdFetched ) {
440 return $this->mRevIdFetched;
441 } else {
442 return $this->mPage->getLatest();
443 }
444 }
445
446 /**
447 * This is the default action of the index.php entry point: just view the
448 * page of the given title.
449 */
450 public function view() {
451 global $wgUser, $wgOut, $wgRequest, $wgParser;
452 global $wgUseFileCache, $wgUseETag, $wgDebugToolbar;
453
454 wfProfileIn( __METHOD__ );
455
456 # Get variables from query string
457 # As side effect this will load the revision and update the title
458 # in a revision ID is passed in the request, so this should remain
459 # the first call of this method even if $oldid is used way below.
460 $oldid = $this->getOldID();
461
462 # Another whitelist check in case getOldID() is altering the title
463 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'read', $wgUser );
464 if ( count( $permErrors ) ) {
465 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
466 wfProfileOut( __METHOD__ );
467 throw new PermissionsError( 'read', $permErrors );
468 }
469
470 # getOldID() may as well want us to redirect somewhere else
471 if ( $this->mRedirectUrl ) {
472 $wgOut->redirect( $this->mRedirectUrl );
473 wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
474 wfProfileOut( __METHOD__ );
475
476 return;
477 }
478
479 # If we got diff in the query, we want to see a diff page instead of the article.
480 if ( $wgRequest->getCheck( 'diff' ) ) {
481 wfDebug( __METHOD__ . ": showing diff page\n" );
482 $this->showDiffPage();
483 wfProfileOut( __METHOD__ );
484
485 return;
486 }
487
488 # Set page title (may be overridden by DISPLAYTITLE)
489 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
490
491 $wgOut->setArticleFlag( true );
492 # Allow frames by default
493 $wgOut->allowClickjacking();
494
495 $parserCache = ParserCache::singleton();
496
497 $parserOptions = $this->getParserOptions();
498 # Render printable version, use printable version cache
499 if ( $wgOut->isPrintable() ) {
500 $parserOptions->setIsPrintable( true );
501 $parserOptions->setEditSection( false );
502 } elseif ( !$this->getTitle()->quickUserCan( 'edit' ) ) {
503 $parserOptions->setEditSection( false );
504 }
505
506 # Try client and file cache
507 if ( !$wgDebugToolbar && $oldid === 0 && $this->mPage->checkTouched() ) {
508 if ( $wgUseETag ) {
509 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
510 }
511
512 # Is it client cached?
513 if ( $wgOut->checkLastModified( $this->mPage->getTouched() ) ) {
514 wfDebug( __METHOD__ . ": done 304\n" );
515 wfProfileOut( __METHOD__ );
516
517 return;
518 # Try file cache
519 } elseif ( $wgUseFileCache && $this->tryFileCache() ) {
520 wfDebug( __METHOD__ . ": done file cache\n" );
521 # tell wgOut that output is taken care of
522 $wgOut->disable();
523 $this->mPage->doViewUpdates( $wgUser );
524 wfProfileOut( __METHOD__ );
525
526 return;
527 }
528 }
529
530 # Should the parser cache be used?
531 $useParserCache = $this->mPage->isParserCacheUsed( $parserOptions, $oldid );
532 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
533 if ( $wgUser->getStubThreshold() ) {
534 wfIncrStats( 'pcache_miss_stub' );
535 }
536
537 $this->showRedirectedFromHeader();
538 $this->showNamespaceHeader();
539
540 # Iterate through the possible ways of constructing the output text.
541 # Keep going until $outputDone is set, or we run out of things to do.
542 $pass = 0;
543 $outputDone = false;
544 $this->mParserOutput = false;
545
546 while ( !$outputDone && ++$pass ) {
547 switch( $pass ) {
548 case 1:
549 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
550 break;
551 case 2:
552 # Early abort if the page doesn't exist
553 if ( !$this->mPage->exists() ) {
554 wfDebug( __METHOD__ . ": showing missing article\n" );
555 $this->showMissingArticle();
556 wfProfileOut( __METHOD__ );
557 return;
558 }
559
560 # Try the parser cache
561 if ( $useParserCache ) {
562 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
563
564 if ( $this->mParserOutput !== false ) {
565 if ( $oldid ) {
566 wfDebug( __METHOD__ . ": showing parser cache contents for current rev permalink\n" );
567 $this->setOldSubtitle( $oldid );
568 } else {
569 wfDebug( __METHOD__ . ": showing parser cache contents\n" );
570 }
571 $wgOut->addParserOutput( $this->mParserOutput );
572 # Ensure that UI elements requiring revision ID have
573 # the correct version information.
574 $wgOut->setRevisionId( $this->mPage->getLatest() );
575 # Preload timestamp to avoid a DB hit
576 $cachedTimestamp = $this->mParserOutput->getTimestamp();
577 if ( $cachedTimestamp !== null ) {
578 $wgOut->setRevisionTimestamp( $cachedTimestamp );
579 $this->mPage->setTimestamp( $cachedTimestamp );
580 }
581 $outputDone = true;
582 }
583 }
584 break;
585 case 3:
586 # This will set $this->mRevision if needed
587 $this->fetchContentObject();
588
589 # Are we looking at an old revision
590 if ( $oldid && $this->mRevision ) {
591 $this->setOldSubtitle( $oldid );
592
593 if ( !$this->showDeletedRevisionHeader() ) {
594 wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
595 wfProfileOut( __METHOD__ );
596 return;
597 }
598 }
599
600 # Ensure that UI elements requiring revision ID have
601 # the correct version information.
602 $wgOut->setRevisionId( $this->getRevIdFetched() );
603 # Preload timestamp to avoid a DB hit
604 $wgOut->setRevisionTimestamp( $this->getTimestamp() );
605
606 # Pages containing custom CSS or JavaScript get special treatment
607 if ( $this->getTitle()->isCssOrJsPage() || $this->getTitle()->isCssJsSubpage() ) {
608 #FIXME: use ContentHandler for specialized actions insetad.
609 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
610 $this->showCssOrJsPage();
611 $outputDone = true;
612 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->fetchContentObject(), $this->getTitle(), $wgOut ) ) ) { #FIXME: document new hook!
613 # Allow extensions do their own custom view for certain pages
614 $outputDone = true;
615 } elseif( Hooks::isRegistered( 'ArticleViewCustom' ) && !wfRunHooks( 'ArticleViewCustom', array( $this->fetchContent(), $this->getTitle(), $wgOut ) ) ) { #FIXME: fetchContent() is deprecated! #FIXME: deprecate hook!
616 # Allow extensions do their own custom view for certain pages
617 $outputDone = true;
618 } else {
619 $content = $this->getContentObject();
620 $rt = $content->getRedirectChain();
621 if ( $rt ) {
622 wfDebug( __METHOD__ . ": showing redirect=no page\n" );
623 # Viewing a redirect page (e.g. with parameter redirect=no)
624 $wgOut->addHTML( $this->viewRedirect( $rt ) );
625 # Parse just to get categories, displaytitle, etc.
626 $this->mParserOutput = $content->getParserOutput( $this->getTitle(), $oldid, $parserOptions );
627 $wgOut->addParserOutputNoText( $this->mParserOutput );
628 $outputDone = true;
629 }
630 }
631 break;
632 case 4:
633 # Run the parse, protected by a pool counter
634 wfDebug( __METHOD__ . ": doing uncached parse\n" );
635
636 $poolArticleView = new PoolWorkArticleView( $this, $parserOptions,
637 $this->getRevIdFetched(), $useParserCache, $this->getContentObject() );
638
639 if ( !$poolArticleView->execute() ) {
640 $error = $poolArticleView->getError();
641 if ( $error ) {
642 $wgOut->clearHTML(); // for release() errors
643 $wgOut->enableClientCache( false );
644 $wgOut->setRobotPolicy( 'noindex,nofollow' );
645
646 $errortext = $error->getWikiText( false, 'view-pool-error' );
647 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
648 }
649 # Connection or timeout error
650 wfProfileOut( __METHOD__ );
651 return;
652 }
653
654 $this->mParserOutput = $poolArticleView->getParserOutput();
655 $wgOut->addParserOutput( $this->mParserOutput );
656
657 # Don't cache a dirty ParserOutput object
658 if ( $poolArticleView->getIsDirty() ) {
659 $wgOut->setSquidMaxage( 0 );
660 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
661 }
662
663 $outputDone = true;
664 break;
665 # Should be unreachable, but just in case...
666 default:
667 break 2;
668 }
669 }
670
671 # Get the ParserOutput actually *displayed* here.
672 # Note that $this->mParserOutput is the *current* version output.
673 $pOutput = ( $outputDone instanceof ParserOutput )
674 ? $outputDone // object fetched by hook
675 : $this->mParserOutput;
676
677 # Adjust title for main page & pages with displaytitle
678 if ( $pOutput ) {
679 $this->adjustDisplayTitle( $pOutput );
680 }
681
682 # For the main page, overwrite the <title> element with the con-
683 # tents of 'pagetitle-view-mainpage' instead of the default (if
684 # that's not empty).
685 # This message always exists because it is in the i18n files
686 if ( $this->getTitle()->isMainPage() ) {
687 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
688 if ( !$msg->isDisabled() ) {
689 $wgOut->setHTMLTitle( $msg->title( $this->getTitle() )->text() );
690 }
691 }
692
693 # Check for any __NOINDEX__ tags on the page using $pOutput
694 $policy = $this->getRobotPolicy( 'view', $pOutput );
695 $wgOut->setIndexPolicy( $policy['index'] );
696 $wgOut->setFollowPolicy( $policy['follow'] );
697
698 $this->showViewFooter();
699 $this->mPage->doViewUpdates( $wgUser );
700
701 wfProfileOut( __METHOD__ );
702 }
703
704 /**
705 * Adjust title for pages with displaytitle, -{T|}- or language conversion
706 * @param $pOutput ParserOutput
707 */
708 public function adjustDisplayTitle( ParserOutput $pOutput ) {
709 global $wgOut;
710 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
711 $titleText = $pOutput->getTitleText();
712 if ( strval( $titleText ) !== '' ) {
713 $wgOut->setPageTitle( $titleText );
714 }
715 }
716
717 /**
718 * Show a diff page according to current request variables. For use within
719 * Article::view() only, other callers should use the DifferenceEngine class.
720 */
721 public function showDiffPage() {
722 global $wgRequest, $wgUser;
723
724 $diff = $wgRequest->getVal( 'diff' );
725 $rcid = $wgRequest->getVal( 'rcid' );
726 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
727 $purge = $wgRequest->getVal( 'action' ) == 'purge';
728 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
729 $oldid = $this->getOldID();
730
731 $contentHandler = ContentHandler::getForTitle( $this->getTitle() );
732 $de = $contentHandler->getDifferenceEngine( $this->getContext(), $oldid, $diff, $rcid, $purge, $unhide );
733
734 // DifferenceEngine directly fetched the revision:
735 $this->mRevIdFetched = $de->mNewid;
736 $de->showDiffPage( $diffOnly );
737
738 if ( $diff == 0 || $diff == $this->mPage->getLatest() ) {
739 # Run view updates for current revision only
740 $this->mPage->doViewUpdates( $wgUser );
741 }
742 }
743
744 /**
745 * Show a page view for a page formatted as CSS or JavaScript. To be called by
746 * Article::view() only.
747 *
748 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
749 * page views.
750 */
751 protected function showCssOrJsPage() {
752 global $wgOut;
753
754 $dir = $this->getContext()->getLanguage()->getDir();
755 $lang = $this->getContext()->getLanguage()->getCode();
756
757 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache' lang='$lang' dir='$dir' class='mw-content-$dir'>\n$1\n</div>",
758 'clearyourcache' );
759
760 // Give hooks a chance to customise the output
761 if ( !Hooks::isRegistered('ShowRawCssJs') || wfRunHooks( 'ShowRawCssJs', array( $this->fetchContent(), $this->getTitle(), $wgOut ) ) ) { #FIXME: fetchContent() is deprecated #FIXME: hook is deprecated
762 $po = $this->mContentObject->getParserOutput();
763 $wgOut->addHTML( $po->getText() );
764 }
765 }
766
767 /**
768 * Get the robot policy to be used for the current view
769 * @param $action String the action= GET parameter
770 * @param $pOutput ParserOutput
771 * @return Array the policy that should be set
772 * TODO: actions other than 'view'
773 */
774 public function getRobotPolicy( $action, $pOutput ) {
775 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
776 global $wgDefaultRobotPolicy, $wgRequest;
777
778 $ns = $this->getTitle()->getNamespace();
779
780 if ( $ns == NS_USER || $ns == NS_USER_TALK ) {
781 # Don't index user and user talk pages for blocked users (bug 11443)
782 if ( !$this->getTitle()->isSubpage() ) {
783 if ( Block::newFromTarget( null, $this->getTitle()->getText() ) instanceof Block ) {
784 return array(
785 'index' => 'noindex',
786 'follow' => 'nofollow'
787 );
788 }
789 }
790 }
791
792 if ( $this->mPage->getID() === 0 || $this->getOldID() ) {
793 # Non-articles (special pages etc), and old revisions
794 return array(
795 'index' => 'noindex',
796 'follow' => 'nofollow'
797 );
798 } elseif ( $wgOut->isPrintable() ) {
799 # Discourage indexing of printable versions, but encourage following
800 return array(
801 'index' => 'noindex',
802 'follow' => 'follow'
803 );
804 } elseif ( $wgRequest->getInt( 'curid' ) ) {
805 # For ?curid=x urls, disallow indexing
806 return array(
807 'index' => 'noindex',
808 'follow' => 'follow'
809 );
810 }
811
812 # Otherwise, construct the policy based on the various config variables.
813 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
814
815 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
816 # Honour customised robot policies for this namespace
817 $policy = array_merge(
818 $policy,
819 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
820 );
821 }
822 if ( $this->getTitle()->canUseNoindex() && is_object( $pOutput ) && $pOutput->getIndexPolicy() ) {
823 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
824 # a final sanity check that we have really got the parser output.
825 $policy = array_merge(
826 $policy,
827 array( 'index' => $pOutput->getIndexPolicy() )
828 );
829 }
830
831 if ( isset( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] ) ) {
832 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
833 $policy = array_merge(
834 $policy,
835 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] )
836 );
837 }
838
839 return $policy;
840 }
841
842 /**
843 * Converts a String robot policy into an associative array, to allow
844 * merging of several policies using array_merge().
845 * @param $policy Mixed, returns empty array on null/false/'', transparent
846 * to already-converted arrays, converts String.
847 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
848 */
849 public static function formatRobotPolicy( $policy ) {
850 if ( is_array( $policy ) ) {
851 return $policy;
852 } elseif ( !$policy ) {
853 return array();
854 }
855
856 $policy = explode( ',', $policy );
857 $policy = array_map( 'trim', $policy );
858
859 $arr = array();
860 foreach ( $policy as $var ) {
861 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
862 $arr['index'] = $var;
863 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
864 $arr['follow'] = $var;
865 }
866 }
867
868 return $arr;
869 }
870
871 /**
872 * If this request is a redirect view, send "redirected from" subtitle to
873 * $wgOut. Returns true if the header was needed, false if this is not a
874 * redirect view. Handles both local and remote redirects.
875 *
876 * @return boolean
877 */
878 public function showRedirectedFromHeader() {
879 global $wgOut, $wgRequest, $wgRedirectSources;
880
881 $rdfrom = $wgRequest->getVal( 'rdfrom' );
882
883 if ( isset( $this->mRedirectedFrom ) ) {
884 // This is an internally redirected page view.
885 // We'll need a backlink to the source page for navigation.
886 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
887 $redir = Linker::linkKnown(
888 $this->mRedirectedFrom,
889 null,
890 array(),
891 array( 'redirect' => 'no' )
892 );
893
894 $wgOut->addSubtitle( wfMessage( 'redirectedfrom' )->rawParams( $redir ) );
895
896 // Set the fragment if one was specified in the redirect
897 if ( strval( $this->getTitle()->getFragment() ) != '' ) {
898 $fragment = Xml::escapeJsString( $this->getTitle()->getFragmentForURL() );
899 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
900 }
901
902 // Add a <link rel="canonical"> tag
903 $wgOut->addLink( array( 'rel' => 'canonical',
904 'href' => $this->getTitle()->getLocalURL() )
905 );
906
907 // Tell $wgOut the user arrived at this article through a redirect
908 $wgOut->setRedirectedFrom( $this->mRedirectedFrom );
909
910 return true;
911 }
912 } elseif ( $rdfrom ) {
913 // This is an externally redirected view, from some other wiki.
914 // If it was reported from a trusted site, supply a backlink.
915 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
916 $redir = Linker::makeExternalLink( $rdfrom, $rdfrom );
917 $wgOut->addSubtitle( wfMessage( 'redirectedfrom' )->rawParams( $redir ) );
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 global $wgOut;
932
933 if ( $this->getTitle()->isTalkPage() ) {
934 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
935 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
936 }
937 }
938 }
939
940 /**
941 * Show the footer section of an ordinary page view
942 */
943 public function showViewFooter() {
944 global $wgOut;
945
946 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
947 if ( $this->getTitle()->getNamespace() == NS_USER_TALK && IP::isValid( $this->getTitle()->getText() ) ) {
948 $wgOut->addWikiMsg( 'anontalkpagetext' );
949 }
950
951 # If we have been passed an &rcid= parameter, we want to give the user a
952 # chance to mark this new article as patrolled.
953 $this->showPatrolFooter();
954
955 wfRunHooks( 'ArticleViewFooter', array( $this ) );
956
957 }
958
959 /**
960 * If patrol is possible, output a patrol UI box. This is called from the
961 * footer section of ordinary page views. If patrol is not possible or not
962 * desired, does nothing.
963 */
964 public function showPatrolFooter() {
965 global $wgOut, $wgRequest, $wgUser;
966
967 $rcid = $wgRequest->getVal( 'rcid' );
968
969 if ( !$rcid || !$this->getTitle()->quickUserCan( 'patrol' ) ) {
970 return;
971 }
972
973 $token = $wgUser->getEditToken( $rcid );
974 $wgOut->preventClickjacking();
975
976 $wgOut->addHTML(
977 "<div class='patrollink'>" .
978 wfMsgHtml(
979 'markaspatrolledlink',
980 Linker::link(
981 $this->getTitle(),
982 wfMsgHtml( 'markaspatrolledtext' ),
983 array(),
984 array(
985 'action' => 'markpatrolled',
986 'rcid' => $rcid,
987 'token' => $token,
988 ),
989 array( 'known', 'noclasses' )
990 )
991 ) .
992 '</div>'
993 );
994 }
995
996 /**
997 * Show the error text for a missing article. For articles in the MediaWiki
998 * namespace, show the default message text. To be called from Article::view().
999 */
1000 public function showMissingArticle() {
1001 global $wgOut, $wgRequest, $wgUser, $wgSend404Code;
1002
1003 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1004 if ( $this->getTitle()->getNamespace() == NS_USER || $this->getTitle()->getNamespace() == NS_USER_TALK ) {
1005 $parts = explode( '/', $this->getTitle()->getText() );
1006 $rootPart = $parts[0];
1007 $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1008 $ip = User::isIP( $rootPart );
1009
1010 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1011 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1012 array( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ) );
1013 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1014 LogEventsList::showLogExtract(
1015 $wgOut,
1016 'block',
1017 $user->getUserPage()->getPrefixedText(),
1018 '',
1019 array(
1020 'lim' => 1,
1021 'showIfEmpty' => false,
1022 'msgKey' => array(
1023 'blocked-notice-logextract',
1024 $user->getName() # Support GENDER in notice
1025 )
1026 )
1027 );
1028 }
1029 }
1030
1031 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1032
1033 # Show delete and move logs
1034 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->getTitle()->getPrefixedText(), '',
1035 array( 'lim' => 10,
1036 'conds' => array( "log_action != 'revision'" ),
1037 'showIfEmpty' => false,
1038 'msgKey' => array( 'moveddeleted-notice' ) )
1039 );
1040
1041 # Show error message
1042 $oldid = $this->getOldID();
1043 if ( $oldid ) {
1044 $text = wfMsgNoTrans( 'missing-article',
1045 $this->getTitle()->getPrefixedText(),
1046 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1047 } elseif ( $this->getTitle()->getNamespace() === NS_MEDIAWIKI ) {
1048 // Use the default message text
1049 $text = $this->getTitle()->getDefaultMessageText();
1050 } else {
1051 $createErrors = $this->getTitle()->getUserPermissionsErrors( 'create', $wgUser );
1052 $editErrors = $this->getTitle()->getUserPermissionsErrors( 'edit', $wgUser );
1053 $errors = array_merge( $createErrors, $editErrors );
1054
1055 if ( !count( $errors ) ) {
1056 $text = wfMsgNoTrans( 'noarticletext' );
1057 } else {
1058 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1059 }
1060 }
1061 $text = "<div class='noarticletext'>\n$text\n</div>";
1062
1063 if ( !$this->mPage->hasViewableContent() && $wgSend404Code ) {
1064 // If there's no backing content, send a 404 Not Found
1065 // for better machine handling of broken links.
1066 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1067 }
1068
1069 $wgOut->addWikiText( $text );
1070 }
1071
1072 /**
1073 * If the revision requested for view is deleted, check permissions.
1074 * Send either an error message or a warning header to $wgOut.
1075 *
1076 * @return boolean true if the view is allowed, false if not.
1077 */
1078 public function showDeletedRevisionHeader() {
1079 global $wgOut, $wgRequest;
1080
1081 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1082 // Not deleted
1083 return true;
1084 }
1085
1086 // If the user is not allowed to see it...
1087 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1088 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1089 'rev-deleted-text-permission' );
1090
1091 return false;
1092 // If the user needs to confirm that they want to see it...
1093 } elseif ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1094 # Give explanation and add a link to view the revision...
1095 $oldid = intval( $this->getOldID() );
1096 $link = $this->getTitle()->getFullUrl( "oldid={$oldid}&unhide=1" );
1097 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1098 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1099 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1100 array( $msg, $link ) );
1101
1102 return false;
1103 // We are allowed to see...
1104 } else {
1105 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1106 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1107 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1108
1109 return true;
1110 }
1111 }
1112
1113 /**
1114 * Generate the navigation links when browsing through an article revisions
1115 * It shows the information as:
1116 * Revision as of \<date\>; view current revision
1117 * \<- Previous version | Next Version -\>
1118 *
1119 * @param $oldid String: revision ID of this article revision
1120 */
1121 public function setOldSubtitle( $oldid = 0 ) {
1122 global $wgLang, $wgOut, $wgUser, $wgRequest;
1123
1124 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
1125 return;
1126 }
1127
1128 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1129
1130 # Cascade unhide param in links for easy deletion browsing
1131 $extraParams = array();
1132 if ( $wgRequest->getVal( 'unhide' ) ) {
1133 $extraParams['unhide'] = 1;
1134 }
1135
1136 $revision = Revision::newFromId( $oldid );
1137 $timestamp = $revision->getTimestamp();
1138
1139 $current = ( $oldid == $this->mPage->getLatest() );
1140 $td = $wgLang->timeanddate( $timestamp, true );
1141 $tddate = $wgLang->date( $timestamp, true );
1142 $tdtime = $wgLang->time( $timestamp, true );
1143
1144 # Show user links if allowed to see them. If hidden, then show them only if requested...
1145 $userlinks = Linker::revUserTools( $revision, !$unhide );
1146
1147 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
1148 ? 'revision-info-current'
1149 : 'revision-info';
1150
1151 $wgOut->addSubtitle( "<div id=\"mw-{$infomsg}\">" . wfMessage( $infomsg,
1152 $td )->rawParams( $userlinks )->params( $revision->getID(), $tddate,
1153 $tdtime, $revision->getUser() )->parse() . "</div>" );
1154
1155 $lnk = $current
1156 ? wfMsgHtml( 'currentrevisionlink' )
1157 : Linker::link(
1158 $this->getTitle(),
1159 wfMsgHtml( 'currentrevisionlink' ),
1160 array(),
1161 $extraParams,
1162 array( 'known', 'noclasses' )
1163 );
1164 $curdiff = $current
1165 ? wfMsgHtml( 'diff' )
1166 : Linker::link(
1167 $this->getTitle(),
1168 wfMsgHtml( 'diff' ),
1169 array(),
1170 array(
1171 'diff' => 'cur',
1172 'oldid' => $oldid
1173 ) + $extraParams,
1174 array( 'known', 'noclasses' )
1175 );
1176 $prev = $this->getTitle()->getPreviousRevisionID( $oldid ) ;
1177 $prevlink = $prev
1178 ? Linker::link(
1179 $this->getTitle(),
1180 wfMsgHtml( 'previousrevision' ),
1181 array(),
1182 array(
1183 'direction' => 'prev',
1184 'oldid' => $oldid
1185 ) + $extraParams,
1186 array( 'known', 'noclasses' )
1187 )
1188 : wfMsgHtml( 'previousrevision' );
1189 $prevdiff = $prev
1190 ? Linker::link(
1191 $this->getTitle(),
1192 wfMsgHtml( 'diff' ),
1193 array(),
1194 array(
1195 'diff' => 'prev',
1196 'oldid' => $oldid
1197 ) + $extraParams,
1198 array( 'known', 'noclasses' )
1199 )
1200 : wfMsgHtml( 'diff' );
1201 $nextlink = $current
1202 ? wfMsgHtml( 'nextrevision' )
1203 : Linker::link(
1204 $this->getTitle(),
1205 wfMsgHtml( 'nextrevision' ),
1206 array(),
1207 array(
1208 'direction' => 'next',
1209 'oldid' => $oldid
1210 ) + $extraParams,
1211 array( 'known', 'noclasses' )
1212 );
1213 $nextdiff = $current
1214 ? wfMsgHtml( 'diff' )
1215 : Linker::link(
1216 $this->getTitle(),
1217 wfMsgHtml( 'diff' ),
1218 array(),
1219 array(
1220 'diff' => 'next',
1221 'oldid' => $oldid
1222 ) + $extraParams,
1223 array( 'known', 'noclasses' )
1224 );
1225
1226 $cdel = Linker::getRevDeleteLink( $wgUser, $revision, $this->getTitle() );
1227 if ( $cdel !== '' ) {
1228 $cdel .= ' ';
1229 }
1230
1231 $wgOut->addSubtitle( "<div id=\"mw-revision-nav\">" . $cdel .
1232 wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
1233 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>" );
1234 }
1235
1236 /**
1237 * View redirect
1238 *
1239 * @param $target Title|Array of destination(s) to redirect
1240 * @param $appendSubtitle Boolean [optional]
1241 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1242 * @return string containing HMTL with redirect link
1243 */
1244 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1245 global $wgOut, $wgStylePath;
1246
1247 if ( !is_array( $target ) ) {
1248 $target = array( $target );
1249 }
1250
1251 $lang = $this->getTitle()->getPageLanguage();
1252 $imageDir = $lang->getDir();
1253
1254 if ( $appendSubtitle ) {
1255 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1256 }
1257
1258 // the loop prepends the arrow image before the link, so the first case needs to be outside
1259
1260 /**
1261 * @var $title Title
1262 */
1263 $title = array_shift( $target );
1264
1265 if ( $forceKnown ) {
1266 $link = Linker::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1267 } else {
1268 $link = Linker::link( $title, htmlspecialchars( $title->getFullText() ) );
1269 }
1270
1271 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1272 $alt = $lang->isRTL() ? '←' : '→';
1273 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1274 foreach ( $target as $rt ) {
1275 $link .= Html::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1276 if ( $forceKnown ) {
1277 $link .= Linker::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1278 } else {
1279 $link .= Linker::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1280 }
1281 }
1282
1283 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1284 return '<div class="redirectMsg">' .
1285 Html::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1286 '<span class="redirectText">' . $link . '</span></div>';
1287 }
1288
1289 /**
1290 * Handle action=render
1291 */
1292 public function render() {
1293 global $wgOut;
1294
1295 $wgOut->setArticleBodyOnly( true );
1296 $this->view();
1297 }
1298
1299 /**
1300 * action=protect handler
1301 */
1302 public function protect() {
1303 $form = new ProtectionForm( $this );
1304 $form->execute();
1305 }
1306
1307 /**
1308 * action=unprotect handler (alias)
1309 */
1310 public function unprotect() {
1311 $this->protect();
1312 }
1313
1314 /**
1315 * UI entry point for page deletion
1316 */
1317 public function delete() {
1318 global $wgOut, $wgRequest, $wgLang;
1319
1320 # This code desperately needs to be totally rewritten
1321
1322 $title = $this->getTitle();
1323 $user = $this->getContext()->getUser();
1324
1325 # Check permissions
1326 $permission_errors = $title->getUserPermissionsErrors( 'delete', $user );
1327 if ( count( $permission_errors ) ) {
1328 throw new PermissionsError( 'delete', $permission_errors );
1329 }
1330
1331 # Read-only check...
1332 if ( wfReadOnly() ) {
1333 throw new ReadOnlyError;
1334 }
1335
1336 # Better double-check that it hasn't been deleted yet!
1337 $dbw = wfGetDB( DB_MASTER );
1338 $conds = $title->pageCond();
1339 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1340 if ( $latest === false ) {
1341 $wgOut->setPageTitle( wfMessage( 'cannotdelete-title', $title->getPrefixedText() ) );
1342 $wgOut->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1343 array( 'cannotdelete', wfEscapeWikiText( $title->getPrefixedText() ) )
1344 );
1345 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1346 LogEventsList::showLogExtract(
1347 $wgOut,
1348 'delete',
1349 $title->getPrefixedText()
1350 );
1351
1352 return;
1353 }
1354
1355 $deleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1356 $deleteReason = $wgRequest->getText( 'wpReason' );
1357
1358 if ( $deleteReasonList == 'other' ) {
1359 $reason = $deleteReason;
1360 } elseif ( $deleteReason != '' ) {
1361 // Entry from drop down menu + additional comment
1362 $reason = $deleteReasonList . wfMsgForContent( 'colon-separator' ) . $deleteReason;
1363 } else {
1364 $reason = $deleteReasonList;
1365 }
1366
1367 if ( $wgRequest->wasPosted() && $user->matchEditToken( $wgRequest->getVal( 'wpEditToken' ),
1368 array( 'delete', $this->getTitle()->getPrefixedText() ) ) )
1369 {
1370 # Flag to hide all contents of the archived revisions
1371 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $user->isAllowed( 'suppressrevision' );
1372
1373 $this->doDelete( $reason, $suppress );
1374
1375 if ( $wgRequest->getCheck( 'wpWatch' ) && $user->isLoggedIn() ) {
1376 $this->doWatch();
1377 } elseif ( $title->userIsWatching() ) {
1378 $this->doUnwatch();
1379 }
1380
1381 return;
1382 }
1383
1384 // Generate deletion reason
1385 $hasHistory = false;
1386 if ( !$reason ) {
1387 $reason = $this->generateReason( $hasHistory );
1388 }
1389
1390 // If the page has a history, insert a warning
1391 if ( $hasHistory ) {
1392 $revisions = $this->mTitle->estimateRevisionCount();
1393 // @todo FIXME: i18n issue/patchwork message
1394 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
1395 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
1396 wfMsgHtml( 'word-separator' ) . Linker::link( $title,
1397 wfMsgHtml( 'history' ),
1398 array( 'rel' => 'archives' ),
1399 array( 'action' => 'history' ) ) .
1400 '</strong>'
1401 );
1402
1403 if ( $this->mTitle->isBigDeletion() ) {
1404 global $wgDeleteRevisionsLimit;
1405 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
1406 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
1407 }
1408 }
1409
1410 return $this->confirmDelete( $reason );
1411 }
1412
1413 /**
1414 * Output deletion confirmation dialog
1415 * @todo FIXME: Move to another file?
1416 * @param $reason String: prefilled reason
1417 */
1418 public function confirmDelete( $reason ) {
1419 global $wgOut;
1420
1421 wfDebug( "Article::confirmDelete\n" );
1422
1423 $wgOut->setPageTitle( wfMessage( 'delete-confirm', $this->getTitle()->getPrefixedText() ) );
1424 $wgOut->addBacklinkSubtitle( $this->getTitle() );
1425 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1426 $wgOut->addWikiMsg( 'confirmdeletetext' );
1427
1428 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
1429
1430 $user = $this->getContext()->getUser();
1431
1432 if ( $user->isAllowed( 'suppressrevision' ) ) {
1433 $suppress = "<tr id=\"wpDeleteSuppressRow\">
1434 <td></td>
1435 <td class='mw-input'><strong>" .
1436 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
1437 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
1438 "</strong></td>
1439 </tr>";
1440 } else {
1441 $suppress = '';
1442 }
1443 $checkWatch = $user->getBoolOption( 'watchdeletion' ) || $this->getTitle()->userIsWatching();
1444
1445 $form = Xml::openElement( 'form', array( 'method' => 'post',
1446 'action' => $this->getTitle()->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
1447 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
1448 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
1449 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
1450 "<tr id=\"wpDeleteReasonListRow\">
1451 <td class='mw-label'>" .
1452 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
1453 "</td>
1454 <td class='mw-input'>" .
1455 Xml::listDropDown( 'wpDeleteReasonList',
1456 wfMsgForContent( 'deletereason-dropdown' ),
1457 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
1458 "</td>
1459 </tr>
1460 <tr id=\"wpDeleteReasonRow\">
1461 <td class='mw-label'>" .
1462 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
1463 "</td>
1464 <td class='mw-input'>" .
1465 Html::input( 'wpReason', $reason, 'text', array(
1466 'size' => '60',
1467 'maxlength' => '255',
1468 'tabindex' => '2',
1469 'id' => 'wpReason',
1470 'autofocus'
1471 ) ) .
1472 "</td>
1473 </tr>";
1474
1475 # Disallow watching if user is not logged in
1476 if ( $user->isLoggedIn() ) {
1477 $form .= "
1478 <tr>
1479 <td></td>
1480 <td class='mw-input'>" .
1481 Xml::checkLabel( wfMsg( 'watchthis' ),
1482 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
1483 "</td>
1484 </tr>";
1485 }
1486
1487 $form .= "
1488 $suppress
1489 <tr>
1490 <td></td>
1491 <td class='mw-submit'>" .
1492 Xml::submitButton( wfMsg( 'deletepage' ),
1493 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
1494 "</td>
1495 </tr>" .
1496 Xml::closeElement( 'table' ) .
1497 Xml::closeElement( 'fieldset' ) .
1498 Html::hidden( 'wpEditToken', $user->getEditToken( array( 'delete', $this->getTitle()->getPrefixedText() ) ) ) .
1499 Xml::closeElement( 'form' );
1500
1501 if ( $user->isAllowed( 'editinterface' ) ) {
1502 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
1503 $link = Linker::link(
1504 $title,
1505 wfMsgHtml( 'delete-edit-reasonlist' ),
1506 array(),
1507 array( 'action' => 'edit' )
1508 );
1509 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
1510 }
1511
1512 $wgOut->addHTML( $form );
1513 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1514 LogEventsList::showLogExtract( $wgOut, 'delete',
1515 $this->getTitle()->getPrefixedText()
1516 );
1517 }
1518
1519 /**
1520 * Perform a deletion and output success or failure messages
1521 * @param $reason
1522 * @param $suppress bool
1523 */
1524 public function doDelete( $reason, $suppress = false ) {
1525 global $wgOut;
1526
1527 $error = '';
1528 if ( $this->mPage->doDeleteArticle( $reason, $suppress, 0, true, $error ) ) {
1529 $deleted = $this->getTitle()->getPrefixedText();
1530
1531 $wgOut->setPageTitle( wfMessage( 'actioncomplete' ) );
1532 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1533
1534 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
1535
1536 $wgOut->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
1537 $wgOut->returnToMain( false );
1538 } else {
1539 $wgOut->setPageTitle( wfMessage( 'cannotdelete-title', $this->getTitle()->getPrefixedText() ) );
1540 if ( $error == '' ) {
1541 $wgOut->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1542 array( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) )
1543 );
1544 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1545
1546 LogEventsList::showLogExtract(
1547 $wgOut,
1548 'delete',
1549 $this->getTitle()->getPrefixedText()
1550 );
1551 } else {
1552 $wgOut->addHTML( $error );
1553 }
1554 }
1555 }
1556
1557 /* Caching functions */
1558
1559 /**
1560 * checkLastModified returns true if it has taken care of all
1561 * output to the client that is necessary for this request.
1562 * (that is, it has sent a cached version of the page)
1563 *
1564 * @return boolean true if cached version send, false otherwise
1565 */
1566 protected function tryFileCache() {
1567 static $called = false;
1568
1569 if ( $called ) {
1570 wfDebug( "Article::tryFileCache(): called twice!?\n" );
1571 return false;
1572 }
1573
1574 $called = true;
1575 if ( $this->isFileCacheable() ) {
1576 $cache = HTMLFileCache::newFromTitle( $this->getTitle(), 'view' );
1577 if ( $cache->isCacheGood( $this->mPage->getTouched() ) ) {
1578 wfDebug( "Article::tryFileCache(): about to load file\n" );
1579 $cache->loadFromFileCache( $this->getContext() );
1580 return true;
1581 } else {
1582 wfDebug( "Article::tryFileCache(): starting buffer\n" );
1583 ob_start( array( &$cache, 'saveToFileCache' ) );
1584 }
1585 } else {
1586 wfDebug( "Article::tryFileCache(): not cacheable\n" );
1587 }
1588
1589 return false;
1590 }
1591
1592 /**
1593 * Check if the page can be cached
1594 * @return bool
1595 */
1596 public function isFileCacheable() {
1597 $cacheable = false;
1598
1599 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
1600 $cacheable = $this->mPage->getID()
1601 && !$this->mRedirectedFrom && !$this->getTitle()->isRedirect();
1602 // Extension may have reason to disable file caching on some pages.
1603 if ( $cacheable ) {
1604 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
1605 }
1606 }
1607
1608 return $cacheable;
1609 }
1610
1611 /**#@-*/
1612
1613 /**
1614 * Lightweight method to get the parser output for a page, checking the parser cache
1615 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
1616 * consider, so it's not appropriate to use there.
1617 *
1618 * @since 1.16 (r52326) for LiquidThreads
1619 *
1620 * @param $oldid mixed integer Revision ID or null
1621 * @param $user User The relevant user
1622 * @return ParserOutput or false if the given revsion ID is not found
1623 */
1624 public function getParserOutput( $oldid = null, User $user = null ) {
1625 global $wgUser;
1626
1627 $user = is_null( $user ) ? $wgUser : $user;
1628 $parserOptions = $this->mPage->makeParserOptions( $user );
1629
1630 return $this->mPage->getParserOutput( $parserOptions, $oldid );
1631 }
1632
1633 /**
1634 * Get parser options suitable for rendering the primary article wikitext
1635 * @return ParserOptions|false
1636 */
1637 public function getParserOptions() {
1638 global $wgUser;
1639 if ( !$this->mParserOptions ) {
1640 $this->mParserOptions = $this->mPage->makeParserOptions( $wgUser );
1641 }
1642 // Clone to allow modifications of the return value without affecting cache
1643 return clone $this->mParserOptions;
1644 }
1645
1646 /**
1647 * Sets the context this Article is executed in
1648 *
1649 * @param $context IContextSource
1650 * @since 1.18
1651 */
1652 public function setContext( $context ) {
1653 $this->mContext = $context;
1654 }
1655
1656 /**
1657 * Gets the context this Article is executed in
1658 *
1659 * @return IContextSource
1660 * @since 1.18
1661 */
1662 public function getContext() {
1663 if ( $this->mContext instanceof IContextSource ) {
1664 return $this->mContext;
1665 } else {
1666 wfDebug( __METHOD__ . " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
1667 return RequestContext::getMain();
1668 }
1669 }
1670
1671 /**
1672 * Info about this page
1673 * @deprecated since 1.19
1674 */
1675 public function info() {
1676 wfDeprecated( __METHOD__, '1.19' );
1677 Action::factory( 'info', $this )->show();
1678 }
1679
1680 /**
1681 * Mark this particular edit/page as patrolled
1682 * @deprecated since 1.18
1683 */
1684 public function markpatrolled() {
1685 wfDeprecated( __METHOD__, '1.18' );
1686 Action::factory( 'markpatrolled', $this )->show();
1687 }
1688
1689 /**
1690 * Handle action=purge
1691 * @deprecated since 1.19
1692 */
1693 public function purge() {
1694 return Action::factory( 'purge', $this )->show();
1695 }
1696
1697 /**
1698 * Handle action=revert
1699 * @deprecated since 1.19
1700 */
1701 public function revert() {
1702 wfDeprecated( __METHOD__, '1.19' );
1703 Action::factory( 'revert', $this )->show();
1704 }
1705
1706 /**
1707 * Handle action=rollback
1708 * @deprecated since 1.19
1709 */
1710 public function rollback() {
1711 wfDeprecated( __METHOD__, '1.19' );
1712 Action::factory( 'rollback', $this )->show();
1713 }
1714
1715 /**
1716 * User-interface handler for the "watch" action.
1717 * Requires Request to pass a token as of 1.18.
1718 * @deprecated since 1.18
1719 */
1720 public function watch() {
1721 wfDeprecated( __METHOD__, '1.18' );
1722 Action::factory( 'watch', $this )->show();
1723 }
1724
1725 /**
1726 * Add this page to $wgUser's watchlist
1727 *
1728 * This is safe to be called multiple times
1729 *
1730 * @return bool true on successful watch operation
1731 * @deprecated since 1.18
1732 */
1733 public function doWatch() {
1734 global $wgUser;
1735 wfDeprecated( __METHOD__, '1.18' );
1736 return WatchAction::doWatch( $this->getTitle(), $wgUser );
1737 }
1738
1739 /**
1740 * User interface handler for the "unwatch" action.
1741 * Requires Request to pass a token as of 1.18.
1742 * @deprecated since 1.18
1743 */
1744 public function unwatch() {
1745 wfDeprecated( __METHOD__, '1.18' );
1746 Action::factory( 'unwatch', $this )->show();
1747 }
1748
1749 /**
1750 * Stop watching a page
1751 * @return bool true on successful unwatch
1752 * @deprecated since 1.18
1753 */
1754 public function doUnwatch() {
1755 global $wgUser;
1756 wfDeprecated( __METHOD__, '1.18' );
1757 return WatchAction::doUnwatch( $this->getTitle(), $wgUser );
1758 }
1759
1760 /**
1761 * Output a redirect back to the article.
1762 * This is typically used after an edit.
1763 *
1764 * @deprecated in 1.18; call $wgOut->redirect() directly
1765 * @param $noRedir Boolean: add redirect=no
1766 * @param $sectionAnchor String: section to redirect to, including "#"
1767 * @param $extraQuery String: extra query params
1768 */
1769 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1770 wfDeprecated( __METHOD__, '1.18' );
1771 global $wgOut;
1772
1773 if ( $noRedir ) {
1774 $query = 'redirect=no';
1775 if ( $extraQuery )
1776 $query .= "&$extraQuery";
1777 } else {
1778 $query = $extraQuery;
1779 }
1780
1781 $wgOut->redirect( $this->getTitle()->getFullURL( $query ) . $sectionAnchor );
1782 }
1783
1784 /**
1785 * Use PHP's magic __get handler to handle accessing of
1786 * raw WikiPage fields for backwards compatibility.
1787 *
1788 * @param $fname String Field name
1789 */
1790 public function __get( $fname ) {
1791 if ( property_exists( $this->mPage, $fname ) ) {
1792 #wfWarn( "Access to raw $fname field " . __CLASS__ );
1793 return $this->mPage->$fname;
1794 }
1795 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE );
1796 }
1797
1798 /**
1799 * Use PHP's magic __set handler to handle setting of
1800 * raw WikiPage fields for backwards compatibility.
1801 *
1802 * @param $fname String Field name
1803 * @param $fvalue mixed New value
1804 */
1805 public function __set( $fname, $fvalue ) {
1806 if ( property_exists( $this->mPage, $fname ) ) {
1807 #wfWarn( "Access to raw $fname field of " . __CLASS__ );
1808 $this->mPage->$fname = $fvalue;
1809 // Note: extensions may want to toss on new fields
1810 } elseif ( !in_array( $fname, array( 'mContext', 'mPage' ) ) ) {
1811 $this->mPage->$fname = $fvalue;
1812 } else {
1813 trigger_error( 'Inaccessible property via __set(): ' . $fname, E_USER_NOTICE );
1814 }
1815 }
1816
1817 /**
1818 * Use PHP's magic __call handler to transform instance calls to
1819 * WikiPage functions for backwards compatibility.
1820 *
1821 * @param $fname String Name of called method
1822 * @param $args Array Arguments to the method
1823 */
1824 public function __call( $fname, $args ) {
1825 if ( is_callable( array( $this->mPage, $fname ) ) ) {
1826 #wfWarn( "Call to " . __CLASS__ . "::$fname; please use WikiPage instead" );
1827 return call_user_func_array( array( $this->mPage, $fname ), $args );
1828 }
1829 trigger_error( 'Inaccessible function via __call(): ' . $fname, E_USER_ERROR );
1830 }
1831
1832 // ****** B/C functions to work-around PHP silliness with __call and references ****** //
1833
1834 /**
1835 * @param $limit array
1836 * @param $expiry array
1837 * @param $cascade bool
1838 * @param $reason string
1839 * @param $user User
1840 * @return Status
1841 */
1842 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
1843 return $this->mPage->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user );
1844 }
1845
1846 /**
1847 * @param $limit array
1848 * @param $reason string
1849 * @param $cascade int
1850 * @param $expiry array
1851 * @return bool
1852 */
1853 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1854 return $this->mPage->updateRestrictions( $limit, $reason, $cascade, $expiry );
1855 }
1856
1857 /**
1858 * @param $reason string
1859 * @param $suppress bool
1860 * @param $id int
1861 * @param $commit bool
1862 * @param $error string
1863 * @return bool
1864 */
1865 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
1866 return $this->mPage->doDeleteArticle( $reason, $suppress, $id, $commit, $error );
1867 }
1868
1869 /**
1870 * @param $fromP
1871 * @param $summary
1872 * @param $token
1873 * @param $bot
1874 * @param $resultDetails
1875 * @param $user User
1876 * @return array
1877 */
1878 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails, User $user = null ) {
1879 global $wgUser;
1880 $user = is_null( $user ) ? $wgUser : $user;
1881 return $this->mPage->doRollback( $fromP, $summary, $token, $bot, $resultDetails, $user );
1882 }
1883
1884 /**
1885 * @param $fromP
1886 * @param $summary
1887 * @param $bot
1888 * @param $resultDetails
1889 * @param $guser User
1890 * @return array
1891 */
1892 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
1893 global $wgUser;
1894 $guser = is_null( $guser ) ? $wgUser : $guser;
1895 return $this->mPage->commitRollback( $fromP, $summary, $bot, $resultDetails, $guser );
1896 }
1897
1898 /**
1899 * @param $hasHistory bool
1900 * @return mixed
1901 */
1902 public function generateReason( &$hasHistory ) {
1903 $title = $this->mPage->getTitle();
1904 $handler = ContentHandler::getForTitle( $title );
1905 return $handler->getAutoDeleteReason( $title, $hasHistory );
1906 }
1907
1908 // ****** B/C functions for static methods ( __callStatic is PHP>=5.3 ) ****** //
1909
1910 /**
1911 * @return array
1912 */
1913 public static function selectFields() {
1914 return WikiPage::selectFields();
1915 }
1916
1917 /**
1918 * @param $title Title
1919 */
1920 public static function onArticleCreate( $title ) {
1921 WikiPage::onArticleCreate( $title );
1922 }
1923
1924 /**
1925 * @param $title Title
1926 */
1927 public static function onArticleDelete( $title ) {
1928 WikiPage::onArticleDelete( $title );
1929 }
1930
1931 /**
1932 * @param $title Title
1933 */
1934 public static function onArticleEdit( $title ) {
1935 WikiPage::onArticleEdit( $title );
1936 }
1937
1938 /**
1939 * @param $oldtext
1940 * @param $newtext
1941 * @param $flags
1942 * @return string
1943 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
1944 */
1945 public static function getAutosummary( $oldtext, $newtext, $flags ) {
1946 return WikiPage::getAutosummary( $oldtext, $newtext, $flags );
1947 }
1948 // ******
1949 }