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