clean up handling of JS/CSS pages
[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 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
609 $this->showCssOrJsPage();
610 $outputDone = true;
611 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->fetchContentObject(), $this->getTitle(), $wgOut ) ) ) { #FIXME: document new hook!
612 # Allow extensions do their own custom view for certain pages
613 $outputDone = true;
614 } elseif( Hooks::isRegistered( 'ArticleViewCustom' ) && !wfRunHooks( 'ArticleViewCustom', array( $this->fetchContent(), $this->getTitle(), $wgOut ) ) ) { #FIXME: fetchContent() is deprecated! #FIXME: deprecate hook!
615 # Allow extensions do their own custom view for certain pages
616 $outputDone = true;
617 } else {
618 $content = $this->getContentObject();
619 $rt = $content->getRedirectChain();
620 if ( $rt ) {
621 wfDebug( __METHOD__ . ": showing redirect=no page\n" );
622 # Viewing a redirect page (e.g. with parameter redirect=no)
623 $wgOut->addHTML( $this->viewRedirect( $rt ) );
624 # Parse just to get categories, displaytitle, etc.
625 $this->mParserOutput = $content->getParserOutput( $this->getTitle(), $oldid, $parserOptions );
626 $wgOut->addParserOutputNoText( $this->mParserOutput );
627 $outputDone = true;
628 }
629 }
630 break;
631 case 4:
632 # Run the parse, protected by a pool counter
633 wfDebug( __METHOD__ . ": doing uncached parse\n" );
634
635 $poolArticleView = new PoolWorkArticleView( $this, $parserOptions,
636 $this->getRevIdFetched(), $useParserCache, $this->getContentObject() );
637
638 if ( !$poolArticleView->execute() ) {
639 $error = $poolArticleView->getError();
640 if ( $error ) {
641 $wgOut->clearHTML(); // for release() errors
642 $wgOut->enableClientCache( false );
643 $wgOut->setRobotPolicy( 'noindex,nofollow' );
644
645 $errortext = $error->getWikiText( false, 'view-pool-error' );
646 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
647 }
648 # Connection or timeout error
649 wfProfileOut( __METHOD__ );
650 return;
651 }
652
653 $this->mParserOutput = $poolArticleView->getParserOutput();
654 $wgOut->addParserOutput( $this->mParserOutput );
655
656 # Don't cache a dirty ParserOutput object
657 if ( $poolArticleView->getIsDirty() ) {
658 $wgOut->setSquidMaxage( 0 );
659 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
660 }
661
662 $outputDone = true;
663 break;
664 # Should be unreachable, but just in case...
665 default:
666 break 2;
667 }
668 }
669
670 # Get the ParserOutput actually *displayed* here.
671 # Note that $this->mParserOutput is the *current* version output.
672 $pOutput = ( $outputDone instanceof ParserOutput )
673 ? $outputDone // object fetched by hook
674 : $this->mParserOutput;
675
676 # Adjust title for main page & pages with displaytitle
677 if ( $pOutput ) {
678 $this->adjustDisplayTitle( $pOutput );
679 }
680
681 # For the main page, overwrite the <title> element with the con-
682 # tents of 'pagetitle-view-mainpage' instead of the default (if
683 # that's not empty).
684 # This message always exists because it is in the i18n files
685 if ( $this->getTitle()->isMainPage() ) {
686 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
687 if ( !$msg->isDisabled() ) {
688 $wgOut->setHTMLTitle( $msg->title( $this->getTitle() )->text() );
689 }
690 }
691
692 # Check for any __NOINDEX__ tags on the page using $pOutput
693 $policy = $this->getRobotPolicy( 'view', $pOutput );
694 $wgOut->setIndexPolicy( $policy['index'] );
695 $wgOut->setFollowPolicy( $policy['follow'] );
696
697 $this->showViewFooter();
698 $this->mPage->doViewUpdates( $wgUser );
699
700 wfProfileOut( __METHOD__ );
701 }
702
703 /**
704 * Adjust title for pages with displaytitle, -{T|}- or language conversion
705 * @param $pOutput ParserOutput
706 */
707 public function adjustDisplayTitle( ParserOutput $pOutput ) {
708 global $wgOut;
709 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
710 $titleText = $pOutput->getTitleText();
711 if ( strval( $titleText ) !== '' ) {
712 $wgOut->setPageTitle( $titleText );
713 }
714 }
715
716 /**
717 * Show a diff page according to current request variables. For use within
718 * Article::view() only, other callers should use the DifferenceEngine class.
719 */
720 public function showDiffPage() {
721 global $wgRequest, $wgUser;
722
723 $diff = $wgRequest->getVal( 'diff' );
724 $rcid = $wgRequest->getVal( 'rcid' );
725 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
726 $purge = $wgRequest->getVal( 'action' ) == 'purge';
727 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
728 $oldid = $this->getOldID();
729
730 $contentHandler = ContentHandler::getForTitle( $this->getTitle() );
731 $de = $contentHandler->getDifferenceEngine( $this->getContext(), $oldid, $diff, $rcid, $purge, $unhide );
732
733 // DifferenceEngine directly fetched the revision:
734 $this->mRevIdFetched = $de->mNewid;
735 $de->showDiffPage( $diffOnly );
736
737 if ( $diff == 0 || $diff == $this->mPage->getLatest() ) {
738 # Run view updates for current revision only
739 $this->mPage->doViewUpdates( $wgUser );
740 }
741 }
742
743 /**
744 * Show a page view for a page formatted as CSS or JavaScript. To be called by
745 * Article::view() only.
746 *
747 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
748 * page views.
749 */
750 protected function showCssOrJsPage( $showCacheHint = true ) {
751 global $wgOut;
752
753 if ( $showCacheHint ) {
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
761 // Give hooks a chance to customise the output
762 if ( !Hooks::isRegistered('ShowRawCssJs') || wfRunHooks( 'ShowRawCssJs', array( $this->fetchContent(), $this->getTitle(), $wgOut ) ) ) { #FIXME: fetchContent() is deprecated #FIXME: hook is deprecated
763 $po = $this->mContentObject->getParserOutput();
764 $wgOut->addHTML( $po->getText() );
765 }
766 }
767
768 /**
769 * Get the robot policy to be used for the current view
770 * @param $action String the action= GET parameter
771 * @param $pOutput ParserOutput
772 * @return Array the policy that should be set
773 * TODO: actions other than 'view'
774 */
775 public function getRobotPolicy( $action, $pOutput ) {
776 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
777 global $wgDefaultRobotPolicy, $wgRequest;
778
779 $ns = $this->getTitle()->getNamespace();
780
781 if ( $ns == NS_USER || $ns == NS_USER_TALK ) {
782 # Don't index user and user talk pages for blocked users (bug 11443)
783 if ( !$this->getTitle()->isSubpage() ) {
784 if ( Block::newFromTarget( null, $this->getTitle()->getText() ) instanceof Block ) {
785 return array(
786 'index' => 'noindex',
787 'follow' => 'nofollow'
788 );
789 }
790 }
791 }
792
793 if ( $this->mPage->getID() === 0 || $this->getOldID() ) {
794 # Non-articles (special pages etc), and old revisions
795 return array(
796 'index' => 'noindex',
797 'follow' => 'nofollow'
798 );
799 } elseif ( $wgOut->isPrintable() ) {
800 # Discourage indexing of printable versions, but encourage following
801 return array(
802 'index' => 'noindex',
803 'follow' => 'follow'
804 );
805 } elseif ( $wgRequest->getInt( 'curid' ) ) {
806 # For ?curid=x urls, disallow indexing
807 return array(
808 'index' => 'noindex',
809 'follow' => 'follow'
810 );
811 }
812
813 # Otherwise, construct the policy based on the various config variables.
814 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
815
816 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
817 # Honour customised robot policies for this namespace
818 $policy = array_merge(
819 $policy,
820 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
821 );
822 }
823 if ( $this->getTitle()->canUseNoindex() && is_object( $pOutput ) && $pOutput->getIndexPolicy() ) {
824 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
825 # a final sanity check that we have really got the parser output.
826 $policy = array_merge(
827 $policy,
828 array( 'index' => $pOutput->getIndexPolicy() )
829 );
830 }
831
832 if ( isset( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] ) ) {
833 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
834 $policy = array_merge(
835 $policy,
836 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] )
837 );
838 }
839
840 return $policy;
841 }
842
843 /**
844 * Converts a String robot policy into an associative array, to allow
845 * merging of several policies using array_merge().
846 * @param $policy Mixed, returns empty array on null/false/'', transparent
847 * to already-converted arrays, converts String.
848 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
849 */
850 public static function formatRobotPolicy( $policy ) {
851 if ( is_array( $policy ) ) {
852 return $policy;
853 } elseif ( !$policy ) {
854 return array();
855 }
856
857 $policy = explode( ',', $policy );
858 $policy = array_map( 'trim', $policy );
859
860 $arr = array();
861 foreach ( $policy as $var ) {
862 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
863 $arr['index'] = $var;
864 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
865 $arr['follow'] = $var;
866 }
867 }
868
869 return $arr;
870 }
871
872 /**
873 * If this request is a redirect view, send "redirected from" subtitle to
874 * $wgOut. Returns true if the header was needed, false if this is not a
875 * redirect view. Handles both local and remote redirects.
876 *
877 * @return boolean
878 */
879 public function showRedirectedFromHeader() {
880 global $wgOut, $wgRequest, $wgRedirectSources;
881
882 $rdfrom = $wgRequest->getVal( 'rdfrom' );
883
884 if ( isset( $this->mRedirectedFrom ) ) {
885 // This is an internally redirected page view.
886 // We'll need a backlink to the source page for navigation.
887 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
888 $redir = Linker::linkKnown(
889 $this->mRedirectedFrom,
890 null,
891 array(),
892 array( 'redirect' => 'no' )
893 );
894
895 $wgOut->addSubtitle( wfMessage( 'redirectedfrom' )->rawParams( $redir ) );
896
897 // Set the fragment if one was specified in the redirect
898 if ( strval( $this->getTitle()->getFragment() ) != '' ) {
899 $fragment = Xml::escapeJsString( $this->getTitle()->getFragmentForURL() );
900 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
901 }
902
903 // Add a <link rel="canonical"> tag
904 $wgOut->addLink( array( 'rel' => 'canonical',
905 'href' => $this->getTitle()->getLocalURL() )
906 );
907
908 // Tell $wgOut the user arrived at this article through a redirect
909 $wgOut->setRedirectedFrom( $this->mRedirectedFrom );
910
911 return true;
912 }
913 } elseif ( $rdfrom ) {
914 // This is an externally redirected view, from some other wiki.
915 // If it was reported from a trusted site, supply a backlink.
916 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
917 $redir = Linker::makeExternalLink( $rdfrom, $rdfrom );
918 $wgOut->addSubtitle( wfMessage( 'redirectedfrom' )->rawParams( $redir ) );
919
920 return true;
921 }
922 }
923
924 return false;
925 }
926
927 /**
928 * Show a header specific to the namespace currently being viewed, like
929 * [[MediaWiki:Talkpagetext]]. For Article::view().
930 */
931 public function showNamespaceHeader() {
932 global $wgOut;
933
934 if ( $this->getTitle()->isTalkPage() ) {
935 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
936 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
937 }
938 }
939 }
940
941 /**
942 * Show the footer section of an ordinary page view
943 */
944 public function showViewFooter() {
945 global $wgOut;
946
947 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
948 if ( $this->getTitle()->getNamespace() == NS_USER_TALK && IP::isValid( $this->getTitle()->getText() ) ) {
949 $wgOut->addWikiMsg( 'anontalkpagetext' );
950 }
951
952 # If we have been passed an &rcid= parameter, we want to give the user a
953 # chance to mark this new article as patrolled.
954 $this->showPatrolFooter();
955
956 wfRunHooks( 'ArticleViewFooter', array( $this ) );
957
958 }
959
960 /**
961 * If patrol is possible, output a patrol UI box. This is called from the
962 * footer section of ordinary page views. If patrol is not possible or not
963 * desired, does nothing.
964 */
965 public function showPatrolFooter() {
966 global $wgOut, $wgRequest, $wgUser;
967
968 $rcid = $wgRequest->getVal( 'rcid' );
969
970 if ( !$rcid || !$this->getTitle()->quickUserCan( 'patrol' ) ) {
971 return;
972 }
973
974 $token = $wgUser->getEditToken( $rcid );
975 $wgOut->preventClickjacking();
976
977 $wgOut->addHTML(
978 "<div class='patrollink'>" .
979 wfMsgHtml(
980 'markaspatrolledlink',
981 Linker::link(
982 $this->getTitle(),
983 wfMsgHtml( 'markaspatrolledtext' ),
984 array(),
985 array(
986 'action' => 'markpatrolled',
987 'rcid' => $rcid,
988 'token' => $token,
989 ),
990 array( 'known', 'noclasses' )
991 )
992 ) .
993 '</div>'
994 );
995 }
996
997 /**
998 * Show the error text for a missing article. For articles in the MediaWiki
999 * namespace, show the default message text. To be called from Article::view().
1000 */
1001 public function showMissingArticle() {
1002 global $wgOut, $wgRequest, $wgUser, $wgSend404Code;
1003
1004 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1005 if ( $this->getTitle()->getNamespace() == NS_USER || $this->getTitle()->getNamespace() == NS_USER_TALK ) {
1006 $parts = explode( '/', $this->getTitle()->getText() );
1007 $rootPart = $parts[0];
1008 $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1009 $ip = User::isIP( $rootPart );
1010
1011 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1012 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1013 array( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ) );
1014 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1015 LogEventsList::showLogExtract(
1016 $wgOut,
1017 'block',
1018 $user->getUserPage()->getPrefixedText(),
1019 '',
1020 array(
1021 'lim' => 1,
1022 'showIfEmpty' => false,
1023 'msgKey' => array(
1024 'blocked-notice-logextract',
1025 $user->getName() # Support GENDER in notice
1026 )
1027 )
1028 );
1029 }
1030 }
1031
1032 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1033
1034 # Show delete and move logs
1035 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->getTitle()->getPrefixedText(), '',
1036 array( 'lim' => 10,
1037 'conds' => array( "log_action != 'revision'" ),
1038 'showIfEmpty' => false,
1039 'msgKey' => array( 'moveddeleted-notice' ) )
1040 );
1041
1042 # Show error message
1043 $oldid = $this->getOldID();
1044 if ( $oldid ) {
1045 $text = wfMsgNoTrans( 'missing-article',
1046 $this->getTitle()->getPrefixedText(),
1047 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1048 } elseif ( $this->getTitle()->getNamespace() === NS_MEDIAWIKI ) {
1049 // Use the default message text
1050 $text = $this->getTitle()->getDefaultMessageText();
1051 } else {
1052 $createErrors = $this->getTitle()->getUserPermissionsErrors( 'create', $wgUser );
1053 $editErrors = $this->getTitle()->getUserPermissionsErrors( 'edit', $wgUser );
1054 $errors = array_merge( $createErrors, $editErrors );
1055
1056 if ( !count( $errors ) ) {
1057 $text = wfMsgNoTrans( 'noarticletext' );
1058 } else {
1059 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1060 }
1061 }
1062 $text = "<div class='noarticletext'>\n$text\n</div>";
1063
1064 if ( !$this->mPage->hasViewableContent() && $wgSend404Code ) {
1065 // If there's no backing content, send a 404 Not Found
1066 // for better machine handling of broken links.
1067 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1068 }
1069
1070 $wgOut->addWikiText( $text );
1071 }
1072
1073 /**
1074 * If the revision requested for view is deleted, check permissions.
1075 * Send either an error message or a warning header to $wgOut.
1076 *
1077 * @return boolean true if the view is allowed, false if not.
1078 */
1079 public function showDeletedRevisionHeader() {
1080 global $wgOut, $wgRequest;
1081
1082 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1083 // Not deleted
1084 return true;
1085 }
1086
1087 // If the user is not allowed to see it...
1088 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1089 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1090 'rev-deleted-text-permission' );
1091
1092 return false;
1093 // If the user needs to confirm that they want to see it...
1094 } elseif ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1095 # Give explanation and add a link to view the revision...
1096 $oldid = intval( $this->getOldID() );
1097 $link = $this->getTitle()->getFullUrl( "oldid={$oldid}&unhide=1" );
1098 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1099 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1100 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1101 array( $msg, $link ) );
1102
1103 return false;
1104 // We are allowed to see...
1105 } else {
1106 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1107 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1108 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1109
1110 return true;
1111 }
1112 }
1113
1114 /**
1115 * Generate the navigation links when browsing through an article revisions
1116 * It shows the information as:
1117 * Revision as of \<date\>; view current revision
1118 * \<- Previous version | Next Version -\>
1119 *
1120 * @param $oldid String: revision ID of this article revision
1121 */
1122 public function setOldSubtitle( $oldid = 0 ) {
1123 global $wgLang, $wgOut, $wgUser, $wgRequest;
1124
1125 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
1126 return;
1127 }
1128
1129 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1130
1131 # Cascade unhide param in links for easy deletion browsing
1132 $extraParams = array();
1133 if ( $wgRequest->getVal( 'unhide' ) ) {
1134 $extraParams['unhide'] = 1;
1135 }
1136
1137 $revision = Revision::newFromId( $oldid );
1138 $timestamp = $revision->getTimestamp();
1139
1140 $current = ( $oldid == $this->mPage->getLatest() );
1141 $td = $wgLang->timeanddate( $timestamp, true );
1142 $tddate = $wgLang->date( $timestamp, true );
1143 $tdtime = $wgLang->time( $timestamp, true );
1144
1145 # Show user links if allowed to see them. If hidden, then show them only if requested...
1146 $userlinks = Linker::revUserTools( $revision, !$unhide );
1147
1148 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
1149 ? 'revision-info-current'
1150 : 'revision-info';
1151
1152 $wgOut->addSubtitle( "<div id=\"mw-{$infomsg}\">" . wfMessage( $infomsg,
1153 $td )->rawParams( $userlinks )->params( $revision->getID(), $tddate,
1154 $tdtime, $revision->getUser() )->parse() . "</div>" );
1155
1156 $lnk = $current
1157 ? wfMsgHtml( 'currentrevisionlink' )
1158 : Linker::link(
1159 $this->getTitle(),
1160 wfMsgHtml( 'currentrevisionlink' ),
1161 array(),
1162 $extraParams,
1163 array( 'known', 'noclasses' )
1164 );
1165 $curdiff = $current
1166 ? wfMsgHtml( 'diff' )
1167 : Linker::link(
1168 $this->getTitle(),
1169 wfMsgHtml( 'diff' ),
1170 array(),
1171 array(
1172 'diff' => 'cur',
1173 'oldid' => $oldid
1174 ) + $extraParams,
1175 array( 'known', 'noclasses' )
1176 );
1177 $prev = $this->getTitle()->getPreviousRevisionID( $oldid ) ;
1178 $prevlink = $prev
1179 ? Linker::link(
1180 $this->getTitle(),
1181 wfMsgHtml( 'previousrevision' ),
1182 array(),
1183 array(
1184 'direction' => 'prev',
1185 'oldid' => $oldid
1186 ) + $extraParams,
1187 array( 'known', 'noclasses' )
1188 )
1189 : wfMsgHtml( 'previousrevision' );
1190 $prevdiff = $prev
1191 ? Linker::link(
1192 $this->getTitle(),
1193 wfMsgHtml( 'diff' ),
1194 array(),
1195 array(
1196 'diff' => 'prev',
1197 'oldid' => $oldid
1198 ) + $extraParams,
1199 array( 'known', 'noclasses' )
1200 )
1201 : wfMsgHtml( 'diff' );
1202 $nextlink = $current
1203 ? wfMsgHtml( 'nextrevision' )
1204 : Linker::link(
1205 $this->getTitle(),
1206 wfMsgHtml( 'nextrevision' ),
1207 array(),
1208 array(
1209 'direction' => 'next',
1210 'oldid' => $oldid
1211 ) + $extraParams,
1212 array( 'known', 'noclasses' )
1213 );
1214 $nextdiff = $current
1215 ? wfMsgHtml( 'diff' )
1216 : Linker::link(
1217 $this->getTitle(),
1218 wfMsgHtml( 'diff' ),
1219 array(),
1220 array(
1221 'diff' => 'next',
1222 'oldid' => $oldid
1223 ) + $extraParams,
1224 array( 'known', 'noclasses' )
1225 );
1226
1227 $cdel = Linker::getRevDeleteLink( $wgUser, $revision, $this->getTitle() );
1228 if ( $cdel !== '' ) {
1229 $cdel .= ' ';
1230 }
1231
1232 $wgOut->addSubtitle( "<div id=\"mw-revision-nav\">" . $cdel .
1233 wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
1234 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>" );
1235 }
1236
1237 /**
1238 * View redirect
1239 *
1240 * @param $target Title|Array of destination(s) to redirect
1241 * @param $appendSubtitle Boolean [optional]
1242 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1243 * @return string containing HMTL with redirect link
1244 */
1245 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1246 global $wgOut, $wgStylePath;
1247
1248 if ( !is_array( $target ) ) {
1249 $target = array( $target );
1250 }
1251
1252 $lang = $this->getTitle()->getPageLanguage();
1253 $imageDir = $lang->getDir();
1254
1255 if ( $appendSubtitle ) {
1256 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1257 }
1258
1259 // the loop prepends the arrow image before the link, so the first case needs to be outside
1260
1261 /**
1262 * @var $title Title
1263 */
1264 $title = array_shift( $target );
1265
1266 if ( $forceKnown ) {
1267 $link = Linker::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1268 } else {
1269 $link = Linker::link( $title, htmlspecialchars( $title->getFullText() ) );
1270 }
1271
1272 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1273 $alt = $lang->isRTL() ? '←' : '→';
1274 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1275 foreach ( $target as $rt ) {
1276 $link .= Html::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1277 if ( $forceKnown ) {
1278 $link .= Linker::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1279 } else {
1280 $link .= Linker::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1281 }
1282 }
1283
1284 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1285 return '<div class="redirectMsg">' .
1286 Html::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1287 '<span class="redirectText">' . $link . '</span></div>';
1288 }
1289
1290 /**
1291 * Handle action=render
1292 */
1293 public function render() {
1294 global $wgOut;
1295
1296 $wgOut->setArticleBodyOnly( true );
1297 $this->view();
1298 }
1299
1300 /**
1301 * action=protect handler
1302 */
1303 public function protect() {
1304 $form = new ProtectionForm( $this );
1305 $form->execute();
1306 }
1307
1308 /**
1309 * action=unprotect handler (alias)
1310 */
1311 public function unprotect() {
1312 $this->protect();
1313 }
1314
1315 /**
1316 * UI entry point for page deletion
1317 */
1318 public function delete() {
1319 global $wgOut, $wgRequest, $wgLang;
1320
1321 # This code desperately needs to be totally rewritten
1322
1323 $title = $this->getTitle();
1324 $user = $this->getContext()->getUser();
1325
1326 # Check permissions
1327 $permission_errors = $title->getUserPermissionsErrors( 'delete', $user );
1328 if ( count( $permission_errors ) ) {
1329 throw new PermissionsError( 'delete', $permission_errors );
1330 }
1331
1332 # Read-only check...
1333 if ( wfReadOnly() ) {
1334 throw new ReadOnlyError;
1335 }
1336
1337 # Better double-check that it hasn't been deleted yet!
1338 $dbw = wfGetDB( DB_MASTER );
1339 $conds = $title->pageCond();
1340 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1341 if ( $latest === false ) {
1342 $wgOut->setPageTitle( wfMessage( 'cannotdelete-title', $title->getPrefixedText() ) );
1343 $wgOut->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1344 array( 'cannotdelete', wfEscapeWikiText( $title->getPrefixedText() ) )
1345 );
1346 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1347 LogEventsList::showLogExtract(
1348 $wgOut,
1349 'delete',
1350 $title->getPrefixedText()
1351 );
1352
1353 return;
1354 }
1355
1356 $deleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1357 $deleteReason = $wgRequest->getText( 'wpReason' );
1358
1359 if ( $deleteReasonList == 'other' ) {
1360 $reason = $deleteReason;
1361 } elseif ( $deleteReason != '' ) {
1362 // Entry from drop down menu + additional comment
1363 $reason = $deleteReasonList . wfMsgForContent( 'colon-separator' ) . $deleteReason;
1364 } else {
1365 $reason = $deleteReasonList;
1366 }
1367
1368 if ( $wgRequest->wasPosted() && $user->matchEditToken( $wgRequest->getVal( 'wpEditToken' ),
1369 array( 'delete', $this->getTitle()->getPrefixedText() ) ) )
1370 {
1371 # Flag to hide all contents of the archived revisions
1372 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $user->isAllowed( 'suppressrevision' );
1373
1374 $this->doDelete( $reason, $suppress );
1375
1376 if ( $wgRequest->getCheck( 'wpWatch' ) && $user->isLoggedIn() ) {
1377 $this->doWatch();
1378 } elseif ( $title->userIsWatching() ) {
1379 $this->doUnwatch();
1380 }
1381
1382 return;
1383 }
1384
1385 // Generate deletion reason
1386 $hasHistory = false;
1387 if ( !$reason ) {
1388 try {
1389 $reason = $this->generateReason( $hasHistory );
1390 } catch (MWException $e) {
1391 # if a page is horribly broken, we still want to be able to delete it. so be lenient about errors here.
1392 wfDebug("Error while building auto delete summary: $e");
1393 $reason = '';
1394 }
1395 }
1396
1397 // If the page has a history, insert a warning
1398 if ( $hasHistory ) {
1399 $revisions = $this->mTitle->estimateRevisionCount();
1400 // @todo FIXME: i18n issue/patchwork message
1401 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
1402 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
1403 wfMsgHtml( 'word-separator' ) . Linker::link( $title,
1404 wfMsgHtml( 'history' ),
1405 array( 'rel' => 'archives' ),
1406 array( 'action' => 'history' ) ) .
1407 '</strong>'
1408 );
1409
1410 if ( $this->mTitle->isBigDeletion() ) {
1411 global $wgDeleteRevisionsLimit;
1412 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
1413 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
1414 }
1415 }
1416
1417 return $this->confirmDelete( $reason );
1418 }
1419
1420 /**
1421 * Output deletion confirmation dialog
1422 * @todo FIXME: Move to another file?
1423 * @param $reason String: prefilled reason
1424 */
1425 public function confirmDelete( $reason ) {
1426 global $wgOut;
1427
1428 wfDebug( "Article::confirmDelete\n" );
1429
1430 $wgOut->setPageTitle( wfMessage( 'delete-confirm', $this->getTitle()->getPrefixedText() ) );
1431 $wgOut->addBacklinkSubtitle( $this->getTitle() );
1432 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1433 $wgOut->addWikiMsg( 'confirmdeletetext' );
1434
1435 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
1436
1437 $user = $this->getContext()->getUser();
1438
1439 if ( $user->isAllowed( 'suppressrevision' ) ) {
1440 $suppress = "<tr id=\"wpDeleteSuppressRow\">
1441 <td></td>
1442 <td class='mw-input'><strong>" .
1443 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
1444 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
1445 "</strong></td>
1446 </tr>";
1447 } else {
1448 $suppress = '';
1449 }
1450 $checkWatch = $user->getBoolOption( 'watchdeletion' ) || $this->getTitle()->userIsWatching();
1451
1452 $form = Xml::openElement( 'form', array( 'method' => 'post',
1453 'action' => $this->getTitle()->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
1454 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
1455 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
1456 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
1457 "<tr id=\"wpDeleteReasonListRow\">
1458 <td class='mw-label'>" .
1459 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
1460 "</td>
1461 <td class='mw-input'>" .
1462 Xml::listDropDown( 'wpDeleteReasonList',
1463 wfMsgForContent( 'deletereason-dropdown' ),
1464 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
1465 "</td>
1466 </tr>
1467 <tr id=\"wpDeleteReasonRow\">
1468 <td class='mw-label'>" .
1469 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
1470 "</td>
1471 <td class='mw-input'>" .
1472 Html::input( 'wpReason', $reason, 'text', array(
1473 'size' => '60',
1474 'maxlength' => '255',
1475 'tabindex' => '2',
1476 'id' => 'wpReason',
1477 'autofocus'
1478 ) ) .
1479 "</td>
1480 </tr>";
1481
1482 # Disallow watching if user is not logged in
1483 if ( $user->isLoggedIn() ) {
1484 $form .= "
1485 <tr>
1486 <td></td>
1487 <td class='mw-input'>" .
1488 Xml::checkLabel( wfMsg( 'watchthis' ),
1489 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
1490 "</td>
1491 </tr>";
1492 }
1493
1494 $form .= "
1495 $suppress
1496 <tr>
1497 <td></td>
1498 <td class='mw-submit'>" .
1499 Xml::submitButton( wfMsg( 'deletepage' ),
1500 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
1501 "</td>
1502 </tr>" .
1503 Xml::closeElement( 'table' ) .
1504 Xml::closeElement( 'fieldset' ) .
1505 Html::hidden( 'wpEditToken', $user->getEditToken( array( 'delete', $this->getTitle()->getPrefixedText() ) ) ) .
1506 Xml::closeElement( 'form' );
1507
1508 if ( $user->isAllowed( 'editinterface' ) ) {
1509 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
1510 $link = Linker::link(
1511 $title,
1512 wfMsgHtml( 'delete-edit-reasonlist' ),
1513 array(),
1514 array( 'action' => 'edit' )
1515 );
1516 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
1517 }
1518
1519 $wgOut->addHTML( $form );
1520 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1521 LogEventsList::showLogExtract( $wgOut, 'delete',
1522 $this->getTitle()->getPrefixedText()
1523 );
1524 }
1525
1526 /**
1527 * Perform a deletion and output success or failure messages
1528 * @param $reason
1529 * @param $suppress bool
1530 */
1531 public function doDelete( $reason, $suppress = false ) {
1532 global $wgOut;
1533
1534 $error = '';
1535 if ( $this->mPage->doDeleteArticle( $reason, $suppress, 0, true, $error ) ) {
1536 $deleted = $this->getTitle()->getPrefixedText();
1537
1538 $wgOut->setPageTitle( wfMessage( 'actioncomplete' ) );
1539 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1540
1541 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
1542
1543 $wgOut->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
1544 $wgOut->returnToMain( false );
1545 } else {
1546 $wgOut->setPageTitle( wfMessage( 'cannotdelete-title', $this->getTitle()->getPrefixedText() ) );
1547 if ( $error == '' ) {
1548 $wgOut->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1549 array( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) )
1550 );
1551 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1552
1553 LogEventsList::showLogExtract(
1554 $wgOut,
1555 'delete',
1556 $this->getTitle()->getPrefixedText()
1557 );
1558 } else {
1559 $wgOut->addHTML( $error );
1560 }
1561 }
1562 }
1563
1564 /* Caching functions */
1565
1566 /**
1567 * checkLastModified returns true if it has taken care of all
1568 * output to the client that is necessary for this request.
1569 * (that is, it has sent a cached version of the page)
1570 *
1571 * @return boolean true if cached version send, false otherwise
1572 */
1573 protected function tryFileCache() {
1574 static $called = false;
1575
1576 if ( $called ) {
1577 wfDebug( "Article::tryFileCache(): called twice!?\n" );
1578 return false;
1579 }
1580
1581 $called = true;
1582 if ( $this->isFileCacheable() ) {
1583 $cache = HTMLFileCache::newFromTitle( $this->getTitle(), 'view' );
1584 if ( $cache->isCacheGood( $this->mPage->getTouched() ) ) {
1585 wfDebug( "Article::tryFileCache(): about to load file\n" );
1586 $cache->loadFromFileCache( $this->getContext() );
1587 return true;
1588 } else {
1589 wfDebug( "Article::tryFileCache(): starting buffer\n" );
1590 ob_start( array( &$cache, 'saveToFileCache' ) );
1591 }
1592 } else {
1593 wfDebug( "Article::tryFileCache(): not cacheable\n" );
1594 }
1595
1596 return false;
1597 }
1598
1599 /**
1600 * Check if the page can be cached
1601 * @return bool
1602 */
1603 public function isFileCacheable() {
1604 $cacheable = false;
1605
1606 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
1607 $cacheable = $this->mPage->getID()
1608 && !$this->mRedirectedFrom && !$this->getTitle()->isRedirect();
1609 // Extension may have reason to disable file caching on some pages.
1610 if ( $cacheable ) {
1611 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
1612 }
1613 }
1614
1615 return $cacheable;
1616 }
1617
1618 /**#@-*/
1619
1620 /**
1621 * Lightweight method to get the parser output for a page, checking the parser cache
1622 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
1623 * consider, so it's not appropriate to use there.
1624 *
1625 * @since 1.16 (r52326) for LiquidThreads
1626 *
1627 * @param $oldid mixed integer Revision ID or null
1628 * @param $user User The relevant user
1629 * @return ParserOutput or false if the given revsion ID is not found
1630 */
1631 public function getParserOutput( $oldid = null, User $user = null ) {
1632 global $wgUser;
1633
1634 $user = is_null( $user ) ? $wgUser : $user;
1635 $parserOptions = $this->mPage->makeParserOptions( $user );
1636
1637 return $this->mPage->getParserOutput( $parserOptions, $oldid );
1638 }
1639
1640 /**
1641 * Get parser options suitable for rendering the primary article wikitext
1642 * @return ParserOptions|false
1643 */
1644 public function getParserOptions() {
1645 global $wgUser;
1646 if ( !$this->mParserOptions ) {
1647 $this->mParserOptions = $this->mPage->makeParserOptions( $wgUser );
1648 }
1649 // Clone to allow modifications of the return value without affecting cache
1650 return clone $this->mParserOptions;
1651 }
1652
1653 /**
1654 * Sets the context this Article is executed in
1655 *
1656 * @param $context IContextSource
1657 * @since 1.18
1658 */
1659 public function setContext( $context ) {
1660 $this->mContext = $context;
1661 }
1662
1663 /**
1664 * Gets the context this Article is executed in
1665 *
1666 * @return IContextSource
1667 * @since 1.18
1668 */
1669 public function getContext() {
1670 if ( $this->mContext instanceof IContextSource ) {
1671 return $this->mContext;
1672 } else {
1673 wfDebug( __METHOD__ . " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
1674 return RequestContext::getMain();
1675 }
1676 }
1677
1678 /**
1679 * Info about this page
1680 * @deprecated since 1.19
1681 */
1682 public function info() {
1683 wfDeprecated( __METHOD__, '1.19' );
1684 Action::factory( 'info', $this )->show();
1685 }
1686
1687 /**
1688 * Mark this particular edit/page as patrolled
1689 * @deprecated since 1.18
1690 */
1691 public function markpatrolled() {
1692 wfDeprecated( __METHOD__, '1.18' );
1693 Action::factory( 'markpatrolled', $this )->show();
1694 }
1695
1696 /**
1697 * Handle action=purge
1698 * @deprecated since 1.19
1699 */
1700 public function purge() {
1701 return Action::factory( 'purge', $this )->show();
1702 }
1703
1704 /**
1705 * Handle action=revert
1706 * @deprecated since 1.19
1707 */
1708 public function revert() {
1709 wfDeprecated( __METHOD__, '1.19' );
1710 Action::factory( 'revert', $this )->show();
1711 }
1712
1713 /**
1714 * Handle action=rollback
1715 * @deprecated since 1.19
1716 */
1717 public function rollback() {
1718 wfDeprecated( __METHOD__, '1.19' );
1719 Action::factory( 'rollback', $this )->show();
1720 }
1721
1722 /**
1723 * User-interface handler for the "watch" action.
1724 * Requires Request to pass a token as of 1.18.
1725 * @deprecated since 1.18
1726 */
1727 public function watch() {
1728 wfDeprecated( __METHOD__, '1.18' );
1729 Action::factory( 'watch', $this )->show();
1730 }
1731
1732 /**
1733 * Add this page to $wgUser's watchlist
1734 *
1735 * This is safe to be called multiple times
1736 *
1737 * @return bool true on successful watch operation
1738 * @deprecated since 1.18
1739 */
1740 public function doWatch() {
1741 global $wgUser;
1742 wfDeprecated( __METHOD__, '1.18' );
1743 return WatchAction::doWatch( $this->getTitle(), $wgUser );
1744 }
1745
1746 /**
1747 * User interface handler for the "unwatch" action.
1748 * Requires Request to pass a token as of 1.18.
1749 * @deprecated since 1.18
1750 */
1751 public function unwatch() {
1752 wfDeprecated( __METHOD__, '1.18' );
1753 Action::factory( 'unwatch', $this )->show();
1754 }
1755
1756 /**
1757 * Stop watching a page
1758 * @return bool true on successful unwatch
1759 * @deprecated since 1.18
1760 */
1761 public function doUnwatch() {
1762 global $wgUser;
1763 wfDeprecated( __METHOD__, '1.18' );
1764 return WatchAction::doUnwatch( $this->getTitle(), $wgUser );
1765 }
1766
1767 /**
1768 * Output a redirect back to the article.
1769 * This is typically used after an edit.
1770 *
1771 * @deprecated in 1.18; call $wgOut->redirect() directly
1772 * @param $noRedir Boolean: add redirect=no
1773 * @param $sectionAnchor String: section to redirect to, including "#"
1774 * @param $extraQuery String: extra query params
1775 */
1776 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1777 wfDeprecated( __METHOD__, '1.18' );
1778 global $wgOut;
1779
1780 if ( $noRedir ) {
1781 $query = 'redirect=no';
1782 if ( $extraQuery )
1783 $query .= "&$extraQuery";
1784 } else {
1785 $query = $extraQuery;
1786 }
1787
1788 $wgOut->redirect( $this->getTitle()->getFullURL( $query ) . $sectionAnchor );
1789 }
1790
1791 /**
1792 * Use PHP's magic __get handler to handle accessing of
1793 * raw WikiPage fields for backwards compatibility.
1794 *
1795 * @param $fname String Field name
1796 */
1797 public function __get( $fname ) {
1798 if ( property_exists( $this->mPage, $fname ) ) {
1799 #wfWarn( "Access to raw $fname field " . __CLASS__ );
1800 return $this->mPage->$fname;
1801 }
1802 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE );
1803 }
1804
1805 /**
1806 * Use PHP's magic __set handler to handle setting of
1807 * raw WikiPage fields for backwards compatibility.
1808 *
1809 * @param $fname String Field name
1810 * @param $fvalue mixed New value
1811 */
1812 public function __set( $fname, $fvalue ) {
1813 if ( property_exists( $this->mPage, $fname ) ) {
1814 #wfWarn( "Access to raw $fname field of " . __CLASS__ );
1815 $this->mPage->$fname = $fvalue;
1816 // Note: extensions may want to toss on new fields
1817 } elseif ( !in_array( $fname, array( 'mContext', 'mPage' ) ) ) {
1818 $this->mPage->$fname = $fvalue;
1819 } else {
1820 trigger_error( 'Inaccessible property via __set(): ' . $fname, E_USER_NOTICE );
1821 }
1822 }
1823
1824 /**
1825 * Use PHP's magic __call handler to transform instance calls to
1826 * WikiPage functions for backwards compatibility.
1827 *
1828 * @param $fname String Name of called method
1829 * @param $args Array Arguments to the method
1830 */
1831 public function __call( $fname, $args ) {
1832 if ( is_callable( array( $this->mPage, $fname ) ) ) {
1833 #wfWarn( "Call to " . __CLASS__ . "::$fname; please use WikiPage instead" );
1834 return call_user_func_array( array( $this->mPage, $fname ), $args );
1835 }
1836 trigger_error( 'Inaccessible function via __call(): ' . $fname, E_USER_ERROR );
1837 }
1838
1839 // ****** B/C functions to work-around PHP silliness with __call and references ****** //
1840
1841 /**
1842 * @param $limit array
1843 * @param $expiry array
1844 * @param $cascade bool
1845 * @param $reason string
1846 * @param $user User
1847 * @return Status
1848 */
1849 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
1850 return $this->mPage->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user );
1851 }
1852
1853 /**
1854 * @param $limit array
1855 * @param $reason string
1856 * @param $cascade int
1857 * @param $expiry array
1858 * @return bool
1859 */
1860 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1861 return $this->mPage->updateRestrictions( $limit, $reason, $cascade, $expiry );
1862 }
1863
1864 /**
1865 * @param $reason string
1866 * @param $suppress bool
1867 * @param $id int
1868 * @param $commit bool
1869 * @param $error string
1870 * @return bool
1871 */
1872 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
1873 return $this->mPage->doDeleteArticle( $reason, $suppress, $id, $commit, $error );
1874 }
1875
1876 /**
1877 * @param $fromP
1878 * @param $summary
1879 * @param $token
1880 * @param $bot
1881 * @param $resultDetails
1882 * @param $user User
1883 * @return array
1884 */
1885 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails, User $user = null ) {
1886 global $wgUser;
1887 $user = is_null( $user ) ? $wgUser : $user;
1888 return $this->mPage->doRollback( $fromP, $summary, $token, $bot, $resultDetails, $user );
1889 }
1890
1891 /**
1892 * @param $fromP
1893 * @param $summary
1894 * @param $bot
1895 * @param $resultDetails
1896 * @param $guser User
1897 * @return array
1898 */
1899 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
1900 global $wgUser;
1901 $guser = is_null( $guser ) ? $wgUser : $guser;
1902 return $this->mPage->commitRollback( $fromP, $summary, $bot, $resultDetails, $guser );
1903 }
1904
1905 /**
1906 * @param $hasHistory bool
1907 * @return mixed
1908 */
1909 public function generateReason( &$hasHistory ) {
1910 $title = $this->mPage->getTitle();
1911 $handler = ContentHandler::getForTitle( $title );
1912 return $handler->getAutoDeleteReason( $title, $hasHistory );
1913 }
1914
1915 // ****** B/C functions for static methods ( __callStatic is PHP>=5.3 ) ****** //
1916
1917 /**
1918 * @return array
1919 */
1920 public static function selectFields() {
1921 return WikiPage::selectFields();
1922 }
1923
1924 /**
1925 * @param $title Title
1926 */
1927 public static function onArticleCreate( $title ) {
1928 WikiPage::onArticleCreate( $title );
1929 }
1930
1931 /**
1932 * @param $title Title
1933 */
1934 public static function onArticleDelete( $title ) {
1935 WikiPage::onArticleDelete( $title );
1936 }
1937
1938 /**
1939 * @param $title Title
1940 */
1941 public static function onArticleEdit( $title ) {
1942 WikiPage::onArticleEdit( $title );
1943 }
1944
1945 /**
1946 * @param $oldtext
1947 * @param $newtext
1948 * @param $flags
1949 * @return string
1950 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
1951 */
1952 public static function getAutosummary( $oldtext, $newtext, $flags ) {
1953 return WikiPage::getAutosummary( $oldtext, $newtext, $flags );
1954 }
1955 // ******
1956 }