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