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