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