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