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