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