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