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