]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/Article.php
MediaWiki 1.17.0
[autoinstalls/mediawiki.git] / includes / Article.php
1 <?php
2 /**
3  * File for articles
4  * @file
5  */
6
7 /**
8  * Class representing a MediaWiki article and history.
9  *
10  * See design.txt for an overview.
11  * Note: edit user interface and cache support functions have been
12  * moved to separate EditPage and HTMLFileCache classes.
13  *
14  * @internal documentation reviewed 15 Mar 2010
15  */
16 class Article {
17         /**@{{
18          * @private
19          */
20         var $mComment = '';               // !<
21         var $mContent;                    // !<
22         var $mContentLoaded = false;      // !<
23         var $mCounter = -1;               // !< Not loaded
24         var $mCurID = -1;                 // !< Not loaded
25         var $mDataLoaded = false;         // !<
26         var $mForUpdate = false;          // !<
27         var $mGoodAdjustment = 0;         // !<
28         var $mIsRedirect = false;         // !<
29         var $mLatest = false;             // !<
30         var $mMinorEdit;                  // !<
31         var $mOldId;                      // !<
32         var $mPreparedEdit = false;       // !< Title object if set
33         var $mRedirectedFrom = null;      // !< Title object if set
34         var $mRedirectTarget = null;      // !< Title object if set
35         var $mRedirectUrl = false;        // !<
36         var $mRevIdFetched = 0;           // !<
37         var $mRevision;                   // !< Revision object if set
38         var $mTimestamp = '';             // !<
39         var $mTitle;                      // !< Title object
40         var $mTotalAdjustment = 0;        // !<
41         var $mTouched = '19700101000000'; // !<
42         var $mUser = -1;                  // !< Not loaded
43         var $mUserText = '';              // !< username from Revision if set
44         var $mParserOptions;              // !< ParserOptions object
45         var $mParserOutput;               // !< ParserCache object if set
46         /**@}}*/
47
48         /**
49          * Constructor and clear the article
50          * @param $title Reference to a Title object.
51          * @param $oldId Integer revision ID, null to fetch from request, zero for current
52          */
53         public function __construct( Title $title, $oldId = null ) {
54                 // FIXME: does the reference play any role here?
55                 $this->mTitle =& $title;
56                 $this->mOldId = $oldId;
57         }
58
59         /**
60          * Constructor from an page id
61          * @param $id The article ID to load
62          */
63         public static function newFromID( $id ) {
64                 $t = Title::newFromID( $id );
65                 # FIXME: doesn't inherit right
66                 return $t == null ? null : new self( $t );
67                 # return $t == null ? null : new static( $t ); // PHP 5.3
68         }
69
70         /**
71          * Tell the page view functions that this view was redirected
72          * from another page on the wiki.
73          * @param $from Title object.
74          */
75         public function setRedirectedFrom( Title $from ) {
76                 $this->mRedirectedFrom = $from;
77         }
78
79         /**
80          * If this page is a redirect, get its target
81          *
82          * The target will be fetched from the redirect table if possible.
83          * If this page doesn't have an entry there, call insertRedirect()
84          * @return mixed Title object, or null if this page is not a redirect
85          */
86         public function getRedirectTarget() {
87                 if ( !$this->mTitle->isRedirect() ) {
88                         return null;
89                 }
90
91                 if ( $this->mRedirectTarget !== null ) {
92                         return $this->mRedirectTarget;
93                 }
94
95                 # Query the redirect table
96                 $dbr = wfGetDB( DB_SLAVE );
97                 $row = $dbr->selectRow( 'redirect',
98                         array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
99                         array( 'rd_from' => $this->getID() ),
100                         __METHOD__
101                 );
102
103                 // rd_fragment and rd_interwiki were added later, populate them if empty
104                 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
105                         return $this->mRedirectTarget = Title::makeTitle(
106                                 $row->rd_namespace, $row->rd_title,
107                                 $row->rd_fragment, $row->rd_interwiki );
108                 }
109
110                 # This page doesn't have an entry in the redirect table
111                 return $this->mRedirectTarget = $this->insertRedirect();
112         }
113
114         /**
115          * Insert an entry for this page into the redirect table.
116          *
117          * Don't call this function directly unless you know what you're doing.
118          * @return Title object or null if not a redirect
119          */
120         public function insertRedirect() {
121                 // recurse through to only get the final target
122                 $retval = Title::newFromRedirectRecurse( $this->getContent() );
123                 if ( !$retval ) {
124                         return null;
125                 }
126                 $this->insertRedirectEntry( $retval );
127                 return $retval;
128         }
129         
130         /**
131          * Insert or update the redirect table entry for this page to indicate
132          * it redirects to $rt .
133          * @param $rt Title redirect target
134          */
135         public function insertRedirectEntry( $rt ) {
136                 $dbw = wfGetDB( DB_MASTER );
137                 $dbw->replace( 'redirect', array( 'rd_from' ),
138                         array(
139                                 'rd_from' => $this->getID(),
140                                 'rd_namespace' => $rt->getNamespace(),
141                                 'rd_title' => $rt->getDBkey(),
142                                 'rd_fragment' => $rt->getFragment(),
143                                 'rd_interwiki' => $rt->getInterwiki(),
144                         ),
145                         __METHOD__
146                 );
147         }
148
149         /**
150          * Get the Title object or URL this page redirects to
151          *
152          * @return mixed false, Title of in-wiki target, or string with URL
153          */
154         public function followRedirect() {
155                 return $this->getRedirectURL( $this->getRedirectTarget() );
156         }
157
158         /**
159          * Get the Title object this text redirects to
160          *
161          * @param $text string article content containing redirect info
162          * @return mixed false, Title of in-wiki target, or string with URL
163          * @deprecated
164          */
165         public function followRedirectText( $text ) {
166                 // recurse through to only get the final target
167                 return $this->getRedirectURL( Title::newFromRedirectRecurse( $text ) );
168         }
169         
170         /**
171          * Get the Title object or URL to use for a redirect. We use Title
172          * objects for same-wiki, non-special redirects and URLs for everything
173          * else.
174          * @param $rt Title Redirect target
175          * @return mixed false, Title object of local target, or string with URL
176          */
177         public function getRedirectURL( $rt ) {
178                 if ( $rt ) {
179                         if ( $rt->getInterwiki() != '' ) {
180                                 if ( $rt->isLocal() ) {
181                                         // Offsite wikis need an HTTP redirect.
182                                         //
183                                         // This can be hard to reverse and may produce loops,
184                                         // so they may be disabled in the site configuration.
185                                         $source = $this->mTitle->getFullURL( 'redirect=no' );
186                                         return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
187                                 }
188                         } else {
189                                 if ( $rt->getNamespace() == NS_SPECIAL ) {
190                                         // Gotta handle redirects to special pages differently:
191                                         // Fill the HTTP response "Location" header and ignore
192                                         // the rest of the page we're on.
193                                         //
194                                         // This can be hard to reverse, so they may be disabled.
195                                         if ( $rt->isSpecial( 'Userlogout' ) ) {
196                                                 // rolleyes
197                                         } else {
198                                                 return $rt->getFullURL();
199                                         }
200                                 }
201
202                                 return $rt;
203                         }
204                 }
205
206                 // No or invalid redirect
207                 return false;
208         }
209
210         /**
211          * Get the title object of the article
212          * @return Title object of this page
213          */
214         public function getTitle() {
215                 return $this->mTitle;
216         }
217
218         /**
219          * Clear the object
220          * FIXME: shouldn't this be public?
221          * @private
222          */
223         public function clear() {
224                 $this->mDataLoaded    = false;
225                 $this->mContentLoaded = false;
226
227                 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
228                 $this->mRedirectedFrom = null; # Title object if set
229                 $this->mRedirectTarget = null; # Title object if set
230                 $this->mUserText =
231                 $this->mTimestamp = $this->mComment = '';
232                 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
233                 $this->mTouched = '19700101000000';
234                 $this->mForUpdate = false;
235                 $this->mIsRedirect = false;
236                 $this->mRevIdFetched = 0;
237                 $this->mRedirectUrl = false;
238                 $this->mLatest = false;
239                 $this->mPreparedEdit = false;
240         }
241
242         /**
243          * Note that getContent/loadContent do not follow redirects anymore.
244          * If you need to fetch redirectable content easily, try
245          * the shortcut in Article::followRedirect()
246          *
247          * This function has side effects! Do not use this function if you
248          * only want the real revision text if any.
249          *
250          * @return Return the text of this revision
251          */
252         public function getContent() {
253                 global $wgUser, $wgContLang, $wgMessageCache;
254
255                 wfProfileIn( __METHOD__ );
256
257                 if ( $this->getID() === 0 ) {
258                         # If this is a MediaWiki:x message, then load the messages
259                         # and return the message value for x.
260                         if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
261                                 # If this is a system message, get the default text.
262                                 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
263                                 $text = wfMsgGetKey( $message, false, $lang, false );
264
265                                 if ( wfEmptyMsg( $message, $text ) )
266                                         $text = '';
267                         } else {
268                                 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
269                         }
270                         wfProfileOut( __METHOD__ );
271
272                         return $text;
273                 } else {
274                         $this->loadContent();
275                         wfProfileOut( __METHOD__ );
276
277                         return $this->mContent;
278                 }
279         }
280
281         /**
282          * Get the text of the current revision. No side-effects...
283          *
284          * @return Return the text of the current revision
285          */
286         public function getRawText() {
287                 // Check process cache for current revision
288                 if ( $this->mContentLoaded && $this->mOldId == 0 ) {
289                         return $this->mContent;
290                 }
291
292                 $rev = Revision::newFromTitle( $this->mTitle );
293                 $text = $rev ? $rev->getRawText() : false;
294
295                 return $text;
296         }
297
298         /**
299          * This function returns the text of a section, specified by a number ($section).
300          * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
301          * the first section before any such heading (section 0).
302          *
303          * If a section contains subsections, these are also returned.
304          *
305          * @param $text String: text to look in
306          * @param $section Integer: section number
307          * @return string text of the requested section
308          * @deprecated
309          */
310         public function getSection( $text, $section ) {
311                 global $wgParser;
312                 return $wgParser->getSection( $text, $section );
313         }
314
315         /**
316          * Get the text that needs to be saved in order to undo all revisions
317          * between $undo and $undoafter. Revisions must belong to the same page,
318          * must exist and must not be deleted
319          * @param $undo Revision
320          * @param $undoafter Revision Must be an earlier revision than $undo
321          * @return mixed string on success, false on failure
322          */
323         public function getUndoText( Revision $undo, Revision $undoafter = null ) {
324                 $currentRev = Revision::newFromTitle( $this->mTitle );
325                 if ( !$currentRev ) {
326                         return false; // no page
327                 }
328                 $undo_text = $undo->getText();
329                 $undoafter_text = $undoafter->getText();
330                 $cur_text = $currentRev->getText();
331
332                 if ( $cur_text == $undo_text ) {
333                         # No use doing a merge if it's just a straight revert.
334                         return $undoafter_text;
335                 }
336
337                 $undone_text = '';
338
339                 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
340                         return false;
341                 }
342
343                 return $undone_text;
344         }
345
346         /**
347          * @return int The oldid of the article that is to be shown, 0 for the
348          *             current revision
349          */
350         public function getOldID() {
351                 if ( is_null( $this->mOldId ) ) {
352                         $this->mOldId = $this->getOldIDFromRequest();
353                 }
354
355                 return $this->mOldId;
356         }
357
358         /**
359          * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
360          *
361          * @return int The old id for the request
362          */
363         public function getOldIDFromRequest() {
364                 global $wgRequest;
365
366                 $this->mRedirectUrl = false;
367
368                 $oldid = $wgRequest->getVal( 'oldid' );
369
370                 if ( isset( $oldid ) ) {
371                         $oldid = intval( $oldid );
372                         if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
373                                 $nextid = $this->mTitle->getNextRevisionID( $oldid );
374                                 if ( $nextid ) {
375                                         $oldid = $nextid;
376                                 } else {
377                                         $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
378                                 }
379                         } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
380                                 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
381                                 if ( $previd ) {
382                                         $oldid = $previd;
383                                 }
384                         }
385                 }
386
387                 if ( !$oldid ) {
388                         $oldid = 0;
389                 }
390
391                 return $oldid;
392         }
393
394         /**
395          * Load the revision (including text) into this object
396          */
397         function loadContent() {
398                 if ( $this->mContentLoaded ) {
399                         return;
400                 }
401
402                 wfProfileIn( __METHOD__ );
403
404                 $oldid = $this->getOldID();
405                 $this->mOldId = $oldid;
406                 $this->fetchContent( $oldid );
407
408                 wfProfileOut( __METHOD__ );
409         }
410
411         /**
412          * Fetch a page record with the given conditions
413          * @param $dbr Database object
414          * @param $conditions Array
415          * @return mixed Database result resource, or false on failure
416          */
417         protected function pageData( $dbr, $conditions ) {
418                 $fields = array(
419                                 'page_id',
420                                 'page_namespace',
421                                 'page_title',
422                                 'page_restrictions',
423                                 'page_counter',
424                                 'page_is_redirect',
425                                 'page_is_new',
426                                 'page_random',
427                                 'page_touched',
428                                 'page_latest',
429                                 'page_len',
430                 );
431
432                 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
433
434                 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__ );
435
436                 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
437
438                 return $row;
439         }
440
441         /**
442          * Fetch a page record matching the Title object's namespace and title
443          * using a sanitized title string
444          *
445          * @param $dbr Database object
446          * @param $title Title object
447          * @return mixed Database result resource, or false on failure
448          */
449         public function pageDataFromTitle( $dbr, $title ) {
450                 return $this->pageData( $dbr, array(
451                         'page_namespace' => $title->getNamespace(),
452                         'page_title'     => $title->getDBkey() ) );
453         }
454
455         /**
456          * Fetch a page record matching the requested ID
457          *
458          * @param $dbr Database
459          * @param $id Integer
460          */
461         protected function pageDataFromId( $dbr, $id ) {
462                 return $this->pageData( $dbr, array( 'page_id' => $id ) );
463         }
464
465         /**
466          * Set the general counter, title etc data loaded from
467          * some source.
468          *
469          * @param $data Database row object or "fromdb"
470          */
471         public function loadPageData( $data = 'fromdb' ) {
472                 if ( $data === 'fromdb' ) {
473                         $dbr = wfGetDB( DB_MASTER );
474                         $data = $this->pageDataFromId( $dbr, $this->getId() );
475                 }
476
477                 $lc = LinkCache::singleton();
478
479                 if ( $data ) {
480                         $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect, $data->page_latest );
481
482                         $this->mTitle->mArticleID = intval( $data->page_id );
483
484                         # Old-fashioned restrictions
485                         $this->mTitle->loadRestrictions( $data->page_restrictions );
486
487                         $this->mCounter     = intval( $data->page_counter );
488                         $this->mTouched     = wfTimestamp( TS_MW, $data->page_touched );
489                         $this->mIsRedirect  = intval( $data->page_is_redirect );
490                         $this->mLatest      = intval( $data->page_latest );
491                 } else {
492                         $lc->addBadLinkObj( $this->mTitle );
493                         $this->mTitle->mArticleID = 0;
494                 }
495
496                 $this->mDataLoaded = true;
497         }
498
499         /**
500          * Get text of an article from database
501          * Does *NOT* follow redirects.
502          *
503          * @param $oldid Int: 0 for whatever the latest revision is
504          * @return mixed string containing article contents, or false if null
505          */
506         function fetchContent( $oldid = 0 ) {
507                 if ( $this->mContentLoaded ) {
508                         return $this->mContent;
509                 }
510
511                 $dbr = wfGetDB( DB_MASTER );
512
513                 # Pre-fill content with error message so that if something
514                 # fails we'll have something telling us what we intended.
515                 $t = $this->mTitle->getPrefixedText();
516                 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
517                 $this->mContent = wfMsgNoTrans( 'missing-article', $t, $d ) ;
518
519                 if ( $oldid ) {
520                         $revision = Revision::newFromId( $oldid );
521                         if ( $revision === null ) {
522                                 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
523                                 return false;
524                         }
525
526                         $data = $this->pageDataFromId( $dbr, $revision->getPage() );
527
528                         if ( !$data ) {
529                                 wfDebug( __METHOD__ . " failed to get page data linked to revision id $oldid\n" );
530                                 return false;
531                         }
532
533                         $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
534                         $this->loadPageData( $data );
535                 } else {
536                         if ( !$this->mDataLoaded ) {
537                                 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
538
539                                 if ( !$data ) {
540                                         wfDebug( __METHOD__ . " failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
541                                         return false;
542                                 }
543
544                                 $this->loadPageData( $data );
545                         }
546                         $revision = Revision::newFromId( $this->mLatest );
547                         if (  $revision === null ) {
548                                 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id {$this->mLatest}\n" );
549                                 return false;
550                         }
551                 }
552
553                 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
554                 // We should instead work with the Revision object when we need it...
555                 $this->mContent   = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
556
557                 $this->mUser      = $revision->getUser();
558                 $this->mUserText  = $revision->getUserText();
559                 $this->mComment   = $revision->getComment();
560                 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
561
562                 $this->mRevIdFetched = $revision->getId();
563                 $this->mContentLoaded = true;
564                 $this->mRevision =& $revision;
565
566                 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) );
567
568                 return $this->mContent;
569         }
570
571         /**
572          * Read/write accessor to select FOR UPDATE
573          *
574          * @param $x Mixed: FIXME
575          * @return mixed value of $x, or value stored in Article::mForUpdate
576          */
577         public function forUpdate( $x = null ) {
578                 return wfSetVar( $this->mForUpdate, $x );
579         }
580
581         /**
582          * Get options for all SELECT statements
583          *
584          * @param $options Array: an optional options array which'll be appended to
585          *                       the default
586          * @return Array: options
587          */
588         protected function getSelectOptions( $options = '' ) {
589                 if ( $this->mForUpdate ) {
590                         if ( is_array( $options ) ) {
591                                 $options[] = 'FOR UPDATE';
592                         } else {
593                                 $options = 'FOR UPDATE';
594                         }
595                 }
596
597                 return $options;
598         }
599
600         /**
601          * @return int Page ID
602          */
603         public function getID() {
604                 return $this->mTitle->getArticleID();
605         }
606
607         /**
608          * @return bool Whether or not the page exists in the database
609          */
610         public function exists() {
611                 return $this->getId() > 0;
612         }
613
614         /**
615          * Check if this page is something we're going to be showing
616          * some sort of sensible content for. If we return false, page
617          * views (plain action=view) will return an HTTP 404 response,
618          * so spiders and robots can know they're following a bad link.
619          *
620          * @return bool
621          */
622         public function hasViewableContent() {
623                 return $this->exists() || $this->mTitle->isAlwaysKnown();
624         }
625
626         /**
627          * @return int The view count for the page
628          */
629         public function getCount() {
630                 if ( -1 == $this->mCounter ) {
631                         $id = $this->getID();
632
633                         if ( $id == 0 ) {
634                                 $this->mCounter = 0;
635                         } else {
636                                 $dbr = wfGetDB( DB_SLAVE );
637                                 $this->mCounter = $dbr->selectField( 'page',
638                                         'page_counter',
639                                         array( 'page_id' => $id ),
640                                         __METHOD__,
641                                         $this->getSelectOptions()
642                                 );
643                         }
644                 }
645
646                 return $this->mCounter;
647         }
648
649         /**
650          * Determine whether a page would be suitable for being counted as an
651          * article in the site_stats table based on the title & its content
652          *
653          * @param $text String: text to analyze
654          * @return bool
655          */
656         public function isCountable( $text ) {
657                 global $wgUseCommaCount;
658
659                 $token = $wgUseCommaCount ? ',' : '[[';
660
661                 return $this->mTitle->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
662         }
663
664         /**
665          * Tests if the article text represents a redirect
666          *
667          * @param $text mixed string containing article contents, or boolean
668          * @return bool
669          */
670         public function isRedirect( $text = false ) {
671                 if ( $text === false ) {
672                         if ( $this->mDataLoaded ) {
673                                 return $this->mIsRedirect;
674                         }
675
676                         // Apparently loadPageData was never called
677                         $this->loadContent();
678                         $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
679                 } else {
680                         $titleObj = Title::newFromRedirect( $text );
681                 }
682
683                 return $titleObj !== null;
684         }
685
686         /**
687          * Returns true if the currently-referenced revision is the current edit
688          * to this page (and it exists).
689          * @return bool
690          */
691         public function isCurrent() {
692                 # If no oldid, this is the current version.
693                 if ( $this->getOldID() == 0 ) {
694                         return true;
695                 }
696
697                 return $this->exists() && isset( $this->mRevision ) && $this->mRevision->isCurrent();
698         }
699
700         /**
701          * Loads everything except the text
702          * This isn't necessary for all uses, so it's only done if needed.
703          */
704         protected function loadLastEdit() {
705                 if ( -1 != $this->mUser ) {
706                         return;
707                 }
708
709                 # New or non-existent articles have no user information
710                 $id = $this->getID();
711                 if ( 0 == $id ) {
712                         return;
713                 }
714
715                 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
716                 if ( !is_null( $this->mLastRevision ) ) {
717                         $this->mUser      = $this->mLastRevision->getUser();
718                         $this->mUserText  = $this->mLastRevision->getUserText();
719                         $this->mTimestamp = $this->mLastRevision->getTimestamp();
720                         $this->mComment   = $this->mLastRevision->getComment();
721                         $this->mMinorEdit = $this->mLastRevision->isMinor();
722                         $this->mRevIdFetched = $this->mLastRevision->getId();
723                 }
724         }
725
726         /**
727          * @return string GMT timestamp of last article revision
728          **/
729
730         public function getTimestamp() {
731                 // Check if the field has been filled by ParserCache::get()
732                 if ( !$this->mTimestamp ) {
733                         $this->loadLastEdit();
734                 }
735
736                 return wfTimestamp( TS_MW, $this->mTimestamp );
737         }
738
739         /**
740          * @return int user ID for the user that made the last article revision
741          */
742         public function getUser() {
743                 $this->loadLastEdit();
744                 return $this->mUser;
745         }
746
747         /**
748          * @return string username of the user that made the last article revision
749          */
750         public function getUserText() {
751                 $this->loadLastEdit();
752                 return $this->mUserText;
753         }
754
755         /**
756          * @return string Comment stored for the last article revision
757          */
758         public function getComment() {
759                 $this->loadLastEdit();
760                 return $this->mComment;
761         }
762
763         /**
764          * Returns true if last revision was marked as "minor edit"
765          *
766          * @return boolean Minor edit indicator for the last article revision.
767          */
768         public function getMinorEdit() {
769                 $this->loadLastEdit();
770                 return $this->mMinorEdit;
771         }
772
773         /**
774          * Use this to fetch the rev ID used on page views
775          *
776          * @return int revision ID of last article revision
777          */
778         public function getRevIdFetched() {
779                 $this->loadLastEdit();
780                 return $this->mRevIdFetched;
781         }
782
783         /**
784          * FIXME: this does what?
785          * @param $limit Integer: default 0.
786          * @param $offset Integer: default 0.
787          * @return UserArrayFromResult object with User objects of article contributors for requested range
788          */
789         public function getContributors( $limit = 0, $offset = 0 ) {
790                 # FIXME: this is expensive; cache this info somewhere.
791
792                 $dbr = wfGetDB( DB_SLAVE );
793                 $revTable = $dbr->tableName( 'revision' );
794                 $userTable = $dbr->tableName( 'user' );
795
796                 $pageId = $this->getId();
797
798                 $user = $this->getUser();
799
800                 if ( $user ) {
801                         $excludeCond = "AND rev_user != $user";
802                 } else {
803                         $userText = $dbr->addQuotes( $this->getUserText() );
804                         $excludeCond = "AND rev_user_text != $userText";
805                 }
806
807                 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ); // username hidden?
808
809                 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
810                         FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
811                         WHERE rev_page = $pageId
812                         $excludeCond
813                         AND $deletedBit = 0
814                         GROUP BY rev_user, rev_user_text
815                         ORDER BY timestamp DESC";
816
817                 if ( $limit > 0 ) {
818                         $sql = $dbr->limitResult( $sql, $limit, $offset );
819                 }
820
821                 $sql .= ' ' . $this->getSelectOptions();
822                 $res = $dbr->query( $sql, __METHOD__ );
823
824                 return new UserArrayFromResult( $res );
825         }
826
827         /**
828          * This is the default action of the index.php entry point: just view the
829          * page of the given title.
830          */
831         public function view() {
832                 global $wgUser, $wgOut, $wgRequest, $wgParser;
833                 global $wgUseFileCache, $wgUseETag;
834
835                 wfProfileIn( __METHOD__ );
836
837                 # Get variables from query string
838                 $oldid = $this->getOldID();
839                 $parserCache = ParserCache::singleton();
840
841                 $parserOptions = $this->getParserOptions();
842                 # Render printable version, use printable version cache
843                 if ( $wgOut->isPrintable() ) {
844                         $parserOptions->setIsPrintable( true );
845                         $parserOptions->setEditSection( false );
846                 } else if ( $wgUseETag && !$this->mTitle->quickUserCan( 'edit' ) ) {
847                         $parserOptions->setEditSection( false );
848                 }
849
850                 # Try client and file cache
851                 if ( $oldid === 0 && $this->checkTouched() ) {
852                         if ( $wgUseETag ) {
853                                 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
854                         }
855
856                         # Is it client cached?
857                         if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
858                                 wfDebug( __METHOD__ . ": done 304\n" );
859                                 wfProfileOut( __METHOD__ );
860
861                                 return;
862                         # Try file cache
863                         } else if ( $wgUseFileCache && $this->tryFileCache() ) {
864                                 wfDebug( __METHOD__ . ": done file cache\n" );
865                                 # tell wgOut that output is taken care of
866                                 $wgOut->disable();
867                                 $this->viewUpdates();
868                                 wfProfileOut( __METHOD__ );
869
870                                 return;
871                         }
872                 }
873
874                 # getOldID may want us to redirect somewhere else
875                 if ( $this->mRedirectUrl ) {
876                         $wgOut->redirect( $this->mRedirectUrl );
877                         wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
878                         wfProfileOut( __METHOD__ );
879
880                         return;
881                 }
882
883                 $wgOut->setArticleFlag( true );
884                 # Set page title (may be overridden by DISPLAYTITLE)
885                 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
886
887                 # If we got diff in the query, we want to see a diff page instead of the article.
888                 if ( $wgRequest->getCheck( 'diff' ) ) {
889                         wfDebug( __METHOD__ . ": showing diff page\n" );
890                         $this->showDiffPage();
891                         wfProfileOut( __METHOD__ );
892
893                         return;
894                 }
895
896                 # Allow frames by default
897                 $wgOut->allowClickjacking();
898
899                 if ( !$wgUseETag && !$this->mTitle->quickUserCan( 'edit' ) ) {
900                         $parserOptions->setEditSection( false );
901                 }
902
903                 # Should the parser cache be used?
904                 $useParserCache = $this->useParserCache( $oldid );
905                 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
906                 if ( $wgUser->getStubThreshold() ) {
907                         wfIncrStats( 'pcache_miss_stub' );
908                 }
909
910                 $wasRedirected = $this->showRedirectedFromHeader();
911                 $this->showNamespaceHeader();
912
913                 # Iterate through the possible ways of constructing the output text.
914                 # Keep going until $outputDone is set, or we run out of things to do.
915                 $pass = 0;
916                 $outputDone = false;
917                 $this->mParserOutput = false;
918
919                 while ( !$outputDone && ++$pass ) {
920                         switch( $pass ) {
921                                 case 1:
922                                         wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
923                                         break;
924                                 case 2:
925                                         # Try the parser cache
926                                         if ( $useParserCache ) {
927                                                 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
928
929                                                 if ( $this->mParserOutput !== false ) {
930                                                         wfDebug( __METHOD__ . ": showing parser cache contents\n" );
931                                                         $wgOut->addParserOutput( $this->mParserOutput );
932                                                         # Ensure that UI elements requiring revision ID have
933                                                         # the correct version information.
934                                                         $wgOut->setRevisionId( $this->mLatest );
935                                                         $outputDone = true;
936                                                 }
937                                         }
938                                         break;
939                                 case 3:
940                                         $text = $this->getContent();
941                                         if ( $text === false || $this->getID() == 0 ) {
942                                                 wfDebug( __METHOD__ . ": showing missing article\n" );
943                                                 $this->showMissingArticle();
944                                                 wfProfileOut( __METHOD__ );
945                                                 return;
946                                         }
947
948                                         # Another whitelist check in case oldid is altering the title
949                                         if ( !$this->mTitle->userCanRead() ) {
950                                                 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
951                                                 $wgOut->loginToUse();
952                                                 $wgOut->output();
953                                                 $wgOut->disable();
954                                                 wfProfileOut( __METHOD__ );
955                                                 return;
956                                         }
957
958                                         # Are we looking at an old revision
959                                         if ( $oldid && !is_null( $this->mRevision ) ) {
960                                                 $this->setOldSubtitle( $oldid );
961
962                                                 if ( !$this->showDeletedRevisionHeader() ) {
963                                                         wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
964                                                         wfProfileOut( __METHOD__ );
965                                                         return;
966                                                 }
967
968                                                 # If this "old" version is the current, then try the parser cache...
969                                                 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
970                                                         $this->mParserOutput = $parserCache->get( $this, $parserOptions );
971                                                         if ( $this->mParserOutput ) {
972                                                                 wfDebug( __METHOD__ . ": showing parser cache for current rev permalink\n" );                                                           
973                                                                 $wgOut->addParserOutput( $this->mParserOutput );
974                                                                 $wgOut->setRevisionId( $this->mLatest );
975                                                                 $outputDone = true;
976                                                                 break;                                                          
977                                                         }
978                                                 }
979                                         }
980
981                                         # Ensure that UI elements requiring revision ID have
982                                         # the correct version information.
983                                         $wgOut->setRevisionId( $this->getRevIdFetched() );
984
985                                         # Pages containing custom CSS or JavaScript get special treatment
986                                         if ( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
987                                                 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
988                                                 $this->showCssOrJsPage();
989                                                 $outputDone = true;
990                                         } else {
991                                                 $rt = Title::newFromRedirectArray( $text );
992                                                 if ( $rt ) {
993                                                         wfDebug( __METHOD__ . ": showing redirect=no page\n" );
994                                                         # Viewing a redirect page (e.g. with parameter redirect=no)
995                                                         # Don't append the subtitle if this was an old revision
996                                                         $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
997                                                         # Parse just to get categories, displaytitle, etc.
998                                                         $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
999                                                         $wgOut->addParserOutputNoText( $this->mParserOutput );
1000                                                         $outputDone = true;
1001                                                 }
1002                                         }
1003                                         break;
1004                                 case 4:
1005                                         # Run the parse, protected by a pool counter
1006                                         wfDebug( __METHOD__ . ": doing uncached parse\n" );
1007
1008                                         $key = $parserCache->getKey( $this, $parserOptions );
1009                                         $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
1010                                         
1011                                         if ( !$poolArticleView->execute() ) {
1012                                                 # Connection or timeout error
1013                                                 wfProfileOut( __METHOD__ );
1014                                                 return;
1015                                         } else {
1016                                                 $outputDone = true;
1017                                         }
1018                                         break;
1019                                 # Should be unreachable, but just in case...
1020                                 default:
1021                                         break 2;
1022                         }
1023                 }
1024
1025                 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1026                 if ( $this->mParserOutput ) {
1027                         $titleText = $this->mParserOutput->getTitleText();
1028
1029                         if ( strval( $titleText ) !== '' ) {
1030                                 $wgOut->setPageTitle( $titleText );
1031                         }
1032                 }
1033
1034                 # For the main page, overwrite the <title> element with the con-
1035                 # tents of 'pagetitle-view-mainpage' instead of the default (if
1036                 # that's not empty).
1037                 # This message always exists because it is in the i18n files
1038                 if ( $this->mTitle->equals( Title::newMainPage() )
1039                         && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
1040                 {
1041                         $wgOut->setHTMLTitle( $m );
1042                 }
1043
1044                 # Now that we've filled $this->mParserOutput, we know whether
1045                 # there are any __NOINDEX__ tags on the page
1046                 $policy = $this->getRobotPolicy( 'view' );
1047                 $wgOut->setIndexPolicy( $policy['index'] );
1048                 $wgOut->setFollowPolicy( $policy['follow'] );
1049
1050                 $this->showViewFooter();
1051                 $this->viewUpdates();
1052                 wfProfileOut( __METHOD__ );
1053         }
1054
1055         /**
1056          * Show a diff page according to current request variables. For use within
1057          * Article::view() only, other callers should use the DifferenceEngine class.
1058          */
1059         public function showDiffPage() {
1060                 global $wgRequest, $wgUser;
1061
1062                 $diff = $wgRequest->getVal( 'diff' );
1063                 $rcid = $wgRequest->getVal( 'rcid' );
1064                 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1065                 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1066                 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1067                 $oldid = $this->getOldID();
1068
1069                 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $unhide );
1070                 // DifferenceEngine directly fetched the revision:
1071                 $this->mRevIdFetched = $de->mNewid;
1072                 $de->showDiffPage( $diffOnly );
1073
1074                 // Needed to get the page's current revision
1075                 $this->loadPageData();
1076                 if ( $diff == 0 || $diff == $this->mLatest ) {
1077                         # Run view updates for current revision only
1078                         $this->viewUpdates();
1079                 }
1080         }
1081
1082         /**
1083          * Show a page view for a page formatted as CSS or JavaScript. To be called by
1084          * Article::view() only.
1085          *
1086          * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1087          * page views.
1088          */
1089         protected function showCssOrJsPage() {
1090                 global $wgOut;
1091
1092                 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1093
1094                 // Give hooks a chance to customise the output
1095                 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
1096                         // Wrap the whole lot in a <pre> and don't parse
1097                         $m = array();
1098                         preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
1099                         $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1100                         $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
1101                         $wgOut->addHTML( "\n</pre>\n" );
1102                 }
1103         }
1104
1105         /**
1106          * Get the robot policy to be used for the current view
1107          * @param $action String the action= GET parameter
1108          * @return Array the policy that should be set
1109          * TODO: actions other than 'view'
1110          */
1111         public function getRobotPolicy( $action ) {
1112                 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1113                 global $wgDefaultRobotPolicy, $wgRequest;
1114
1115                 $ns = $this->mTitle->getNamespace();
1116
1117                 if ( $ns == NS_USER || $ns == NS_USER_TALK ) {
1118                         # Don't index user and user talk pages for blocked users (bug 11443)
1119                         if ( !$this->mTitle->isSubpage() ) {
1120                                 $block = new Block();
1121                                 if ( $block->load( $this->mTitle->getText() ) ) {
1122                                         return array(
1123                                                 'index'  => 'noindex',
1124                                                 'follow' => 'nofollow'
1125                                         );
1126                                 }
1127                         }
1128                 }
1129
1130                 if ( $this->getID() === 0 || $this->getOldID() ) {
1131                         # Non-articles (special pages etc), and old revisions
1132                         return array(
1133                                 'index'  => 'noindex',
1134                                 'follow' => 'nofollow'
1135                         );
1136                 } elseif ( $wgOut->isPrintable() ) {
1137                         # Discourage indexing of printable versions, but encourage following
1138                         return array(
1139                                 'index'  => 'noindex',
1140                                 'follow' => 'follow'
1141                         );
1142                 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1143                         # For ?curid=x urls, disallow indexing
1144                         return array(
1145                                 'index'  => 'noindex',
1146                                 'follow' => 'follow'
1147                         );
1148                 }
1149
1150                 # Otherwise, construct the policy based on the various config variables.
1151                 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
1152
1153                 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1154                         # Honour customised robot policies for this namespace
1155                         $policy = array_merge(
1156                                 $policy,
1157                                 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1158                         );
1159                 }
1160                 if ( $this->mTitle->canUseNoindex() && is_object( $this->mParserOutput ) && $this->mParserOutput->getIndexPolicy() ) {
1161                         # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1162                         # a final sanity check that we have really got the parser output.
1163                         $policy = array_merge(
1164                                 $policy,
1165                                 array( 'index' => $this->mParserOutput->getIndexPolicy() )
1166                         );
1167                 }
1168
1169                 if ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
1170                         # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1171                         $policy = array_merge(
1172                                 $policy,
1173                                 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] )
1174                         );
1175                 }
1176
1177                 return $policy;
1178         }
1179
1180         /**
1181          * Converts a String robot policy into an associative array, to allow
1182          * merging of several policies using array_merge().
1183          * @param $policy Mixed, returns empty array on null/false/'', transparent
1184          *            to already-converted arrays, converts String.
1185          * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1186          */
1187         public static function formatRobotPolicy( $policy ) {
1188                 if ( is_array( $policy ) ) {
1189                         return $policy;
1190                 } elseif ( !$policy ) {
1191                         return array();
1192                 }
1193
1194                 $policy = explode( ',', $policy );
1195                 $policy = array_map( 'trim', $policy );
1196
1197                 $arr = array();
1198                 foreach ( $policy as $var ) {
1199                         if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1200                                 $arr['index'] = $var;
1201                         } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1202                                 $arr['follow'] = $var;
1203                         }
1204                 }
1205
1206                 return $arr;
1207         }
1208
1209         /**
1210          * If this request is a redirect view, send "redirected from" subtitle to
1211          * $wgOut. Returns true if the header was needed, false if this is not a
1212          * redirect view. Handles both local and remote redirects.
1213          *
1214          * @return boolean
1215          */
1216         public function showRedirectedFromHeader() {
1217                 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1218
1219                 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1220                 $sk = $wgUser->getSkin();
1221
1222                 if ( isset( $this->mRedirectedFrom ) ) {
1223                         // This is an internally redirected page view.
1224                         // We'll need a backlink to the source page for navigation.
1225                         if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1226                                 $redir = $sk->link(
1227                                         $this->mRedirectedFrom,
1228                                         null,
1229                                         array(),
1230                                         array( 'redirect' => 'no' ),
1231                                         array( 'known', 'noclasses' )
1232                                 );
1233
1234                                 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1235                                 $wgOut->setSubtitle( $s );
1236
1237                                 // Set the fragment if one was specified in the redirect
1238                                 if ( strval( $this->mTitle->getFragment() ) != '' ) {
1239                                         $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1240                                         $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1241                                 }
1242
1243                                 // Add a <link rel="canonical"> tag
1244                                 $wgOut->addLink( array( 'rel' => 'canonical',
1245                                         'href' => $this->mTitle->getLocalURL() )
1246                                 );
1247
1248                                 return true;
1249                         }
1250                 } elseif ( $rdfrom ) {
1251                         // This is an externally redirected view, from some other wiki.
1252                         // If it was reported from a trusted site, supply a backlink.
1253                         if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1254                                 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1255                                 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1256                                 $wgOut->setSubtitle( $s );
1257
1258                                 return true;
1259                         }
1260                 }
1261
1262                 return false;
1263         }
1264
1265         /**
1266          * Show a header specific to the namespace currently being viewed, like
1267          * [[MediaWiki:Talkpagetext]]. For Article::view().
1268          */
1269         public function showNamespaceHeader() {
1270                 global $wgOut;
1271
1272                 if ( $this->mTitle->isTalkPage() ) {
1273                         $msg = wfMsgNoTrans( 'talkpageheader' );
1274                         if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1275                                 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1276                         }
1277                 }
1278         }
1279
1280         /**
1281          * Show the footer section of an ordinary page view
1282          */
1283         public function showViewFooter() {
1284                 global $wgOut, $wgUseTrackbacks;
1285
1286                 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1287                 if ( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1288                         $wgOut->addWikiMsg( 'anontalkpagetext' );
1289                 }
1290
1291                 # If we have been passed an &rcid= parameter, we want to give the user a
1292                 # chance to mark this new article as patrolled.
1293                 $this->showPatrolFooter();
1294
1295                 # Trackbacks
1296                 if ( $wgUseTrackbacks ) {
1297                         $this->addTrackbacks();
1298                 }
1299         }
1300
1301         /**
1302          * If patrol is possible, output a patrol UI box. This is called from the
1303          * footer section of ordinary page views. If patrol is not possible or not
1304          * desired, does nothing.
1305          */
1306         public function showPatrolFooter() {
1307                 global $wgOut, $wgRequest, $wgUser;
1308
1309                 $rcid = $wgRequest->getVal( 'rcid' );
1310
1311                 if ( !$rcid || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1312                         return;
1313                 }
1314
1315                 $sk = $wgUser->getSkin();
1316                 $token = $wgUser->editToken( $rcid );
1317                 $wgOut->preventClickjacking();
1318
1319                 $wgOut->addHTML(
1320                         "<div class='patrollink'>" .
1321                                 wfMsgHtml(
1322                                         'markaspatrolledlink',
1323                                         $sk->link(
1324                                                 $this->mTitle,
1325                                                 wfMsgHtml( 'markaspatrolledtext' ),
1326                                                 array(),
1327                                                 array(
1328                                                         'action' => 'markpatrolled',
1329                                                         'rcid' => $rcid,
1330                                                         'token' => $token,
1331                                                 ),
1332                                                 array( 'known', 'noclasses' )
1333                                         )
1334                                 ) .
1335                         '</div>'
1336                 );
1337         }
1338
1339         /**
1340          * Show the error text for a missing article. For articles in the MediaWiki
1341          * namespace, show the default message text. To be called from Article::view().
1342          */
1343         public function showMissingArticle() {
1344                 global $wgOut, $wgRequest, $wgUser;
1345
1346                 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1347                 if ( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
1348                         $parts = explode( '/', $this->mTitle->getText() );
1349                         $rootPart = $parts[0];
1350                         $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1351                         $ip = User::isIP( $rootPart );
1352
1353                         if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1354                                 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1355                                         array( 'userpage-userdoesnotexist-view', $rootPart ) );
1356                         } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1357                                 LogEventsList::showLogExtract(
1358                                         $wgOut,
1359                                         'block',
1360                                         $user->getUserPage()->getPrefixedText(),
1361                                         '',
1362                                         array(
1363                                                 'lim' => 1,
1364                                                 'showIfEmpty' => false,
1365                                                 'msgKey' => array(
1366                                                         'blocked-notice-logextract',
1367                                                         $user->getName() # Support GENDER in notice
1368                                                 )
1369                                         )
1370                                 );
1371                         }
1372                 }
1373
1374                 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1375
1376                 # Show delete and move logs
1377                 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle->getPrefixedText(), '',
1378                         array(  'lim' => 10,
1379                                 'conds' => array( "log_action != 'revision'" ),
1380                                 'showIfEmpty' => false,
1381                                 'msgKey' => array( 'moveddeleted-notice' ) )
1382                 );
1383
1384                 # Show error message
1385                 $oldid = $this->getOldID();
1386                 if ( $oldid ) {
1387                         $text = wfMsgNoTrans( 'missing-article',
1388                                 $this->mTitle->getPrefixedText(),
1389                                 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1390                 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1391                         // Use the default message text
1392                         $text = $this->getContent();
1393                 } else {
1394                         $createErrors = $this->mTitle->getUserPermissionsErrors( 'create', $wgUser );
1395                         $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
1396                         $errors = array_merge( $createErrors, $editErrors );
1397
1398                         if ( !count( $errors ) ) {
1399                                 $text = wfMsgNoTrans( 'noarticletext' );
1400                         } else {
1401                                 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1402                         }
1403                 }
1404                 $text = "<div class='noarticletext'>\n$text\n</div>";
1405
1406                 if ( !$this->hasViewableContent() ) {
1407                         // If there's no backing content, send a 404 Not Found
1408                         // for better machine handling of broken links.
1409                         $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1410                 }
1411
1412                 $wgOut->addWikiText( $text );
1413         }
1414
1415         /**
1416          * If the revision requested for view is deleted, check permissions.
1417          * Send either an error message or a warning header to $wgOut.
1418          *
1419          * @return boolean true if the view is allowed, false if not.
1420          */
1421         public function showDeletedRevisionHeader() {
1422                 global $wgOut, $wgRequest;
1423
1424                 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1425                         // Not deleted
1426                         return true;
1427                 }
1428
1429                 // If the user is not allowed to see it...
1430                 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1431                         $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1432                                 'rev-deleted-text-permission' );
1433
1434                         return false;
1435                 // If the user needs to confirm that they want to see it...
1436                 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1437                         # Give explanation and add a link to view the revision...
1438                         $oldid = intval( $this->getOldID() );
1439                         $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1440                         $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1441                                 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1442                         $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1443                                 array( $msg, $link ) );
1444
1445                         return false;
1446                 // We are allowed to see...
1447                 } else {
1448                         $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1449                                 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1450                         $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1451
1452                         return true;
1453                 }
1454         }
1455
1456         /**
1457          * Should the parser cache be used?
1458          *
1459          * @return boolean
1460          */
1461         public function useParserCache( $oldid ) {
1462                 global $wgUser, $wgEnableParserCache;
1463
1464                 return $wgEnableParserCache
1465                         && $wgUser->getStubThreshold() == 0
1466                         && $this->exists()
1467                         && empty( $oldid )
1468                         && !$this->mTitle->isCssOrJsPage()
1469                         && !$this->mTitle->isCssJsSubpage();
1470         }
1471
1472         /**
1473          * Execute the uncached parse for action=view
1474          */
1475         public function doViewParse() {
1476                 global $wgOut;
1477
1478                 $oldid = $this->getOldID();
1479                 $parserOptions = $this->getParserOptions();
1480
1481                 # Render printable version, use printable version cache
1482                 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1483
1484                 # Don't show section-edit links on old revisions... this way lies madness.
1485                 if ( !$this->isCurrent() || $wgOut->isPrintable() || !$this->mTitle->quickUserCan( 'edit' ) ) {
1486                         $parserOptions->setEditSection( false );
1487                 }
1488                 
1489                 $useParserCache = $this->useParserCache( $oldid );
1490                 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1491                 
1492                 return true;
1493         }
1494
1495         /**
1496          * Try to fetch an expired entry from the parser cache. If it is present,
1497          * output it and return true. If it is not present, output nothing and
1498          * return false. This is used as a callback function for
1499          * PoolCounter::executeProtected().
1500          *
1501          * @return boolean
1502          */
1503         public function tryDirtyCache() {
1504                 global $wgOut;
1505                 $parserCache = ParserCache::singleton();
1506                 $options = $this->getParserOptions();
1507                 
1508                 if ( $wgOut->isPrintable() ) {
1509                         $options->setIsPrintable( true );
1510                         $options->setEditSection( false );
1511                 }
1512                 
1513                 $output = $parserCache->getDirty( $this, $options );
1514
1515                 if ( $output ) {
1516                         wfDebug( __METHOD__ . ": sending dirty output\n" );
1517                         wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1518                         $wgOut->setSquidMaxage( 0 );
1519                         $this->mParserOutput = $output;
1520                         $wgOut->addParserOutput( $output );
1521                         $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1522
1523                         return true;
1524                 } else {
1525                         wfDebugLog( 'dirty', "dirty missing\n" );
1526                         wfDebug( __METHOD__ . ": no dirty cache\n" );
1527
1528                         return false;
1529                 }
1530         }
1531
1532         /**
1533          * View redirect
1534          *
1535          * @param $target Title object or Array of destination(s) to redirect
1536          * @param $appendSubtitle Boolean [optional]
1537          * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1538          * @return string containing HMTL with redirect link
1539          */
1540         public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1541                 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1542
1543                 if ( !is_array( $target ) ) {
1544                         $target = array( $target );
1545                 }
1546
1547                 $imageDir = $wgContLang->getDir();
1548
1549                 if ( $appendSubtitle ) {
1550                         $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1551                 }
1552
1553                 $sk = $wgUser->getSkin();
1554                 // the loop prepends the arrow image before the link, so the first case needs to be outside
1555                 $title = array_shift( $target );
1556
1557                 if ( $forceKnown ) {
1558                         $link = $sk->linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1559                 } else {
1560                         $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1561                 }
1562
1563                 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1564                 $alt = $wgContLang->isRTL() ? '←' : '→';
1565                 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1566                 // FIXME: where this happens?
1567                 foreach ( $target as $rt ) {
1568                         $link .= Html::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1569                         if ( $forceKnown ) {
1570                                 $link .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText() ) );
1571                         } else {
1572                                 $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1573                         }
1574                 }
1575
1576                 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';              
1577                 return '<div class="redirectMsg">' .
1578                         Html::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1579                         '<span class="redirectText">' . $link . '</span></div>';
1580         }
1581
1582         /**
1583          * Builds trackback links for article display if $wgUseTrackbacks is set to true
1584          */
1585         public function addTrackbacks() {
1586                 global $wgOut, $wgUser;
1587
1588                 $dbr = wfGetDB( DB_SLAVE );
1589                 $tbs = $dbr->select( 'trackbacks',
1590                         array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1591                         array( 'tb_page' => $this->getID() )
1592                 );
1593
1594                 if ( !$dbr->numRows( $tbs ) ) {
1595                         return;
1596                 }
1597
1598                 $wgOut->preventClickjacking();
1599
1600                 $tbtext = "";
1601                 foreach ( $tbs as $o ) {
1602                         $rmvtxt = "";
1603
1604                         if ( $wgUser->isAllowed( 'trackback' ) ) {
1605                                 $delurl = $this->mTitle->getFullURL( "action=deletetrackback&tbid=" .
1606                                         $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1607                                 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1608                         }
1609
1610                         $tbtext .= "\n";
1611                         $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex ) ? 'trackbackexcerpt' : 'trackback',
1612                                         $o->tb_title,
1613                                         $o->tb_url,
1614                                         $o->tb_ex,
1615                                         $o->tb_name,
1616                                         $rmvtxt );
1617                 }
1618
1619                 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1620         }
1621
1622         /**
1623          * Removes trackback record for current article from trackbacks table
1624          */
1625         public function deletetrackback() {
1626                 global $wgUser, $wgRequest, $wgOut;
1627
1628                 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1629                         $wgOut->addWikiMsg( 'sessionfailure' );
1630
1631                         return;
1632                 }
1633
1634                 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1635
1636                 if ( count( $permission_errors ) ) {
1637                         $wgOut->showPermissionsErrorPage( $permission_errors );
1638
1639                         return;
1640                 }
1641
1642                 $db = wfGetDB( DB_MASTER );
1643                 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1644
1645                 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1646                 $this->mTitle->invalidateCache();
1647         }
1648
1649         /**
1650          * Handle action=render
1651          */
1652
1653         public function render() {
1654                 global $wgOut;
1655
1656                 $wgOut->setArticleBodyOnly( true );
1657                 $this->view();
1658         }
1659
1660         /**
1661          * Handle action=purge
1662          */
1663         public function purge() {
1664                 global $wgUser, $wgRequest, $wgOut;
1665
1666                 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1667                         //FIXME: shouldn't this be in doPurge()?
1668                         if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1669                                 $this->doPurge();
1670                                 $this->view();
1671                         }
1672                 } else {
1673                         $formParams = array(
1674                                 'method' => 'post',
1675                                 'action' =>  $wgRequest->getRequestURL(),
1676                         );
1677
1678                         $wgOut->addWikiMsg( 'confirm-purge-top' );
1679
1680                         $form  = Html::openElement( 'form', $formParams );
1681                         $form .= Xml::submitButton( wfMsg( 'confirm_purge_button' ) );
1682                         $form .= Html::closeElement( 'form' );
1683                         
1684                         $wgOut->addHTML( $form );
1685                         $wgOut->addWikiMsg( 'confirm-purge-bottom' );
1686
1687                         $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1688                         $wgOut->setRobotPolicy( 'noindex,nofollow' );
1689                 }
1690         }
1691
1692         /**
1693          * Perform the actions of a page purging
1694          */
1695         public function doPurge() {
1696                 global $wgUseSquid;
1697
1698                 // Invalidate the cache
1699                 $this->mTitle->invalidateCache();
1700
1701                 if ( $wgUseSquid ) {
1702                         // Commit the transaction before the purge is sent
1703                         $dbw = wfGetDB( DB_MASTER );
1704                         $dbw->commit();
1705
1706                         // Send purge
1707                         $update = SquidUpdate::newSimplePurge( $this->mTitle );
1708                         $update->doUpdate();
1709                 }
1710
1711                 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1712                         global $wgMessageCache;
1713
1714                         if ( $this->getID() == 0 ) {
1715                                 $text = false;
1716                         } else {
1717                                 $text = $this->getRawText();
1718                         }
1719
1720                         $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1721                 }
1722         }
1723
1724         /**
1725          * Insert a new empty page record for this article.
1726          * This *must* be followed up by creating a revision
1727          * and running $this->updateRevisionOn( ... );
1728          * or else the record will be left in a funky state.
1729          * Best if all done inside a transaction.
1730          *
1731          * @param $dbw Database
1732          * @return int The newly created page_id key, or false if the title already existed
1733          * @private
1734          */
1735         public function insertOn( $dbw ) {
1736                 wfProfileIn( __METHOD__ );
1737
1738                 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1739                 $dbw->insert( 'page', array(
1740                         'page_id'           => $page_id,
1741                         'page_namespace'    => $this->mTitle->getNamespace(),
1742                         'page_title'        => $this->mTitle->getDBkey(),
1743                         'page_counter'      => 0,
1744                         'page_restrictions' => '',
1745                         'page_is_redirect'  => 0, # Will set this shortly...
1746                         'page_is_new'       => 1,
1747                         'page_random'       => wfRandom(),
1748                         'page_touched'      => $dbw->timestamp(),
1749                         'page_latest'       => 0, # Fill this in shortly...
1750                         'page_len'          => 0, # Fill this in shortly...
1751                 ), __METHOD__, 'IGNORE' );
1752
1753                 $affected = $dbw->affectedRows();
1754
1755                 if ( $affected ) {
1756                         $newid = $dbw->insertId();
1757                         $this->mTitle->resetArticleId( $newid );
1758                 }
1759                 wfProfileOut( __METHOD__ );
1760
1761                 return $affected ? $newid : false;
1762         }
1763
1764         /**
1765          * Update the page record to point to a newly saved revision.
1766          *
1767          * @param $dbw DatabaseBase: object
1768          * @param $revision Revision: For ID number, and text used to set
1769                             length and redirect status fields
1770          * @param $lastRevision Integer: if given, will not overwrite the page field
1771          *                      when different from the currently set value.
1772          *                      Giving 0 indicates the new page flag should be set
1773          *                      on.
1774          * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1775          *                           removing rows in redirect table.
1776          * @return bool true on success, false on failure
1777          * @private
1778          */
1779         public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1780                 wfProfileIn( __METHOD__ );
1781
1782                 $text = $revision->getText();
1783                 $rt = Title::newFromRedirectRecurse( $text );
1784
1785                 $conditions = array( 'page_id' => $this->getId() );
1786
1787                 if ( !is_null( $lastRevision ) ) {
1788                         # An extra check against threads stepping on each other
1789                         $conditions['page_latest'] = $lastRevision;
1790                 }
1791
1792                 $dbw->update( 'page',
1793                         array( /* SET */
1794                                 'page_latest'      => $revision->getId(),
1795                                 'page_touched'     => $dbw->timestamp(),
1796                                 'page_is_new'      => ( $lastRevision === 0 ) ? 1 : 0,
1797                                 'page_is_redirect' => $rt !== null ? 1 : 0,
1798                                 'page_len'         => strlen( $text ),
1799                         ),
1800                         $conditions,
1801                         __METHOD__ );
1802
1803                 $result = $dbw->affectedRows() != 0;
1804                 if ( $result ) {
1805                         $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1806                 }
1807
1808                 wfProfileOut( __METHOD__ );
1809                 return $result;
1810         }
1811
1812         /**
1813          * Add row to the redirect table if this is a redirect, remove otherwise.
1814          *
1815          * @param $dbw Database
1816          * @param $redirectTitle a title object pointing to the redirect target,
1817          *                       or NULL if this is not a redirect
1818          * @param $lastRevIsRedirect If given, will optimize adding and
1819          *                           removing rows in redirect table.
1820          * @return bool true on success, false on failure
1821          * @private
1822          */
1823         public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1824                 // Always update redirects (target link might have changed)
1825                 // Update/Insert if we don't know if the last revision was a redirect or not
1826                 // Delete if changing from redirect to non-redirect
1827                 $isRedirect = !is_null( $redirectTitle );
1828
1829                 if ( $isRedirect || is_null( $lastRevIsRedirect ) || $lastRevIsRedirect !== $isRedirect ) {
1830                         wfProfileIn( __METHOD__ );
1831                         if ( $isRedirect ) {
1832                                 $this->insertRedirectEntry( $redirectTitle );
1833                         } else {
1834                                 // This is not a redirect, remove row from redirect table
1835                                 $where = array( 'rd_from' => $this->getId() );
1836                                 $dbw->delete( 'redirect', $where, __METHOD__ );
1837                         }
1838
1839                         if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1840                                 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1841                         }
1842                         wfProfileOut( __METHOD__ );
1843
1844                         return ( $dbw->affectedRows() != 0 );
1845                 }
1846
1847                 return true;
1848         }
1849
1850         /**
1851          * If the given revision is newer than the currently set page_latest,
1852          * update the page record. Otherwise, do nothing.
1853          *
1854          * @param $dbw Database object
1855          * @param $revision Revision object
1856          * @return mixed
1857          */
1858         public function updateIfNewerOn( &$dbw, $revision ) {
1859                 wfProfileIn( __METHOD__ );
1860
1861                 $row = $dbw->selectRow(
1862                         array( 'revision', 'page' ),
1863                         array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1864                         array(
1865                                 'page_id' => $this->getId(),
1866                                 'page_latest=rev_id' ),
1867                         __METHOD__ );
1868
1869                 if ( $row ) {
1870                         if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1871                                 wfProfileOut( __METHOD__ );
1872                                 return false;
1873                         }
1874                         $prev = $row->rev_id;
1875                         $lastRevIsRedirect = (bool)$row->page_is_redirect;
1876                 } else {
1877                         # No or missing previous revision; mark the page as new
1878                         $prev = 0;
1879                         $lastRevIsRedirect = null;
1880                 }
1881
1882                 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1883
1884                 wfProfileOut( __METHOD__ );
1885                 return $ret;
1886         }
1887
1888         /**
1889          * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1890          * @param $text String: new text of the section
1891          * @param $summary String: new section's subject, only if $section is 'new'
1892          * @param $edittime String: revision timestamp or null to use the current revision
1893          * @return string Complete article text, or null if error
1894          */
1895         public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1896                 wfProfileIn( __METHOD__ );
1897
1898                 if ( strval( $section ) == '' ) {
1899                         // Whole-page edit; let the whole text through
1900                 } else {
1901                         if ( is_null( $edittime ) ) {
1902                                 $rev = Revision::newFromTitle( $this->mTitle );
1903                         } else {
1904                                 $dbw = wfGetDB( DB_MASTER );
1905                                 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1906                         }
1907
1908                         if ( !$rev ) {
1909                                 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1910                                         $this->getId() . "; section: $section; edittime: $edittime)\n" );
1911                                 wfProfileOut( __METHOD__ );
1912                                 return null;
1913                         }
1914
1915                         $oldtext = $rev->getText();
1916
1917                         if ( $section == 'new' ) {
1918                                 # Inserting a new section
1919                                 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1920                                 $text = strlen( trim( $oldtext ) ) > 0
1921                                                 ? "{$oldtext}\n\n{$subject}{$text}"
1922                                                 : "{$subject}{$text}";
1923                         } else {
1924                                 # Replacing an existing section; roll out the big guns
1925                                 global $wgParser;
1926
1927                                 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1928                         }
1929                 }
1930
1931                 wfProfileOut( __METHOD__ );
1932                 return $text;
1933         }
1934
1935         /**
1936          * This function is not deprecated until somebody fixes the core not to use
1937          * it. Nevertheless, use Article::doEdit() instead.
1938          */
1939         function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1940                 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1941                         ( $isminor ? EDIT_MINOR : 0 ) |
1942                         ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1943                         ( $bot ? EDIT_FORCE_BOT : 0 );
1944
1945                 # If this is a comment, add the summary as headline
1946                 if ( $comment && $summary != "" ) {
1947                         $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
1948                 }
1949                 $this->doEdit( $text, $summary, $flags );
1950
1951                 $dbw = wfGetDB( DB_MASTER );
1952                 if ( $watchthis ) {
1953                         if ( !$this->mTitle->userIsWatching() ) {
1954                                 $dbw->begin();
1955                                 $this->doWatch();
1956                                 $dbw->commit();
1957                         }
1958                 } else {
1959                         if ( $this->mTitle->userIsWatching() ) {
1960                                 $dbw->begin();
1961                                 $this->doUnwatch();
1962                                 $dbw->commit();
1963                         }
1964                 }
1965                 $this->doRedirect( $this->isRedirect( $text ) );
1966         }
1967
1968         /**
1969          * @deprecated use Article::doEdit()
1970          */
1971         function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1972                 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1973                         ( $minor ? EDIT_MINOR : 0 ) |
1974                         ( $forceBot ? EDIT_FORCE_BOT : 0 );
1975
1976                 $status = $this->doEdit( $text, $summary, $flags );
1977
1978                 if ( !$status->isOK() ) {
1979                         return false;
1980                 }
1981
1982                 $dbw = wfGetDB( DB_MASTER );
1983                 if ( $watchthis ) {
1984                         if ( !$this->mTitle->userIsWatching() ) {
1985                                 $dbw->begin();
1986                                 $this->doWatch();
1987                                 $dbw->commit();
1988                         }
1989                 } else {
1990                         if ( $this->mTitle->userIsWatching() ) {
1991                                 $dbw->begin();
1992                                 $this->doUnwatch();
1993                                 $dbw->commit();
1994                         }
1995                 }
1996
1997                 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1998                 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1999
2000                 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
2001                 return true;
2002         }
2003
2004         /**
2005          * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
2006          * @param $flags Int
2007          * @return Int updated $flags
2008          */
2009         function checkFlags( $flags ) {
2010                 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
2011                         if ( $this->mTitle->getArticleID() ) {
2012                                 $flags |= EDIT_UPDATE;
2013                         } else {
2014                                 $flags |= EDIT_NEW;
2015                         }
2016                 }
2017
2018                 return $flags;
2019         }
2020
2021         /**
2022          * Article::doEdit()
2023          *
2024          * Change an existing article or create a new article. Updates RC and all necessary caches,
2025          * optionally via the deferred update array.
2026          *
2027          * $wgUser must be set before calling this function.
2028          *
2029          * @param $text String: new text
2030          * @param $summary String: edit summary
2031          * @param $flags Integer bitfield:
2032          *      EDIT_NEW
2033          *          Article is known or assumed to be non-existent, create a new one
2034          *      EDIT_UPDATE
2035          *          Article is known or assumed to be pre-existing, update it
2036          *      EDIT_MINOR
2037          *          Mark this edit minor, if the user is allowed to do so
2038          *      EDIT_SUPPRESS_RC
2039          *          Do not log the change in recentchanges
2040          *      EDIT_FORCE_BOT
2041          *          Mark the edit a "bot" edit regardless of user rights
2042          *      EDIT_DEFER_UPDATES
2043          *          Defer some of the updates until the end of index.php
2044          *      EDIT_AUTOSUMMARY
2045          *          Fill in blank summaries with generated text where possible
2046          *
2047          * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2048          * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2049          * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2050          * edit-already-exists error will be returned. These two conditions are also possible with
2051          * auto-detection due to MediaWiki's performance-optimised locking strategy.
2052          *
2053          * @param $baseRevId the revision ID this edit was based off, if any
2054          * @param $user Optional user object, $wgUser will be used if not passed
2055          *
2056          * @return Status object. Possible errors:
2057          *     edit-hook-aborted:       The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2058          *     edit-gone-missing:       In update mode, but the article didn't exist
2059          *     edit-conflict:           In update mode, the article changed unexpectedly
2060          *     edit-no-change:          Warning that the text was the same as before
2061          *     edit-already-exists:     In creation mode, but the article already exists
2062          *
2063          *  Extensions may define additional errors.
2064          *
2065          *  $return->value will contain an associative array with members as follows:
2066          *     new:                     Boolean indicating if the function attempted to create a new article
2067          *     revision:                The revision object for the inserted revision, or null
2068          *
2069          *  Compatibility note: this function previously returned a boolean value indicating success/failure
2070          */
2071         public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
2072                 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2073
2074                 # Low-level sanity check
2075                 if ( $this->mTitle->getText() === '' ) {
2076                         throw new MWException( 'Something is trying to edit an article with an empty title' );
2077                 }
2078
2079                 wfProfileIn( __METHOD__ );
2080
2081                 $user = is_null( $user ) ? $wgUser : $user;
2082                 $status = Status::newGood( array() );
2083
2084                 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2085                 $this->loadPageData();
2086
2087                 $flags = $this->checkFlags( $flags );
2088
2089                 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2090                         $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
2091                 {
2092                         wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
2093
2094                         if ( $status->isOK() ) {
2095                                 $status->fatal( 'edit-hook-aborted' );
2096                         }
2097
2098                         wfProfileOut( __METHOD__ );
2099                         return $status;
2100                 }
2101
2102                 # Silently ignore EDIT_MINOR if not allowed
2103                 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
2104                 $bot = $flags & EDIT_FORCE_BOT;
2105
2106                 $oldtext = $this->getRawText(); // current revision
2107                 $oldsize = strlen( $oldtext );
2108
2109                 # Provide autosummaries if one is not provided and autosummaries are enabled.
2110                 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
2111                         $summary = $this->getAutosummary( $oldtext, $text, $flags );
2112                 }
2113
2114                 $editInfo = $this->prepareTextForEdit( $text );
2115                 $text = $editInfo->pst;
2116                 $newsize = strlen( $text );
2117
2118                 $dbw = wfGetDB( DB_MASTER );
2119                 $now = wfTimestampNow();
2120                 $this->mTimestamp = $now;
2121
2122                 if ( $flags & EDIT_UPDATE ) {
2123                         # Update article, but only if changed.
2124                         $status->value['new'] = false;
2125
2126                         # Make sure the revision is either completely inserted or not inserted at all
2127                         if ( !$wgDBtransactions ) {
2128                                 $userAbort = ignore_user_abort( true );
2129                         }
2130
2131                         $changed = ( strcmp( $text, $oldtext ) != 0 );
2132
2133                         if ( $changed ) {
2134                                 $this->mGoodAdjustment = (int)$this->isCountable( $text )
2135                                   - (int)$this->isCountable( $oldtext );
2136                                 $this->mTotalAdjustment = 0;
2137
2138                                 if ( !$this->mLatest ) {
2139                                         # Article gone missing
2140                                         wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
2141                                         $status->fatal( 'edit-gone-missing' );
2142
2143                                         wfProfileOut( __METHOD__ );
2144                                         return $status;
2145                                 }
2146
2147                                 $revision = new Revision( array(
2148                                         'page'       => $this->getId(),
2149                                         'comment'    => $summary,
2150                                         'minor_edit' => $isminor,
2151                                         'text'       => $text,
2152                                         'parent_id'  => $this->mLatest,
2153                                         'user'       => $user->getId(),
2154                                         'user_text'  => $user->getName(),
2155                                 ) );
2156
2157                                 $dbw->begin();
2158                                 $revisionId = $revision->insertOn( $dbw );
2159
2160                                 # Update page
2161                                 #
2162                                 # Note that we use $this->mLatest instead of fetching a value from the master DB
2163                                 # during the course of this function. This makes sure that EditPage can detect
2164                                 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2165                                 # before this function is called. A previous function used a separate query, this
2166                                 # creates a window where concurrent edits can cause an ignored edit conflict.
2167                                 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
2168
2169                                 if ( !$ok ) {
2170                                         /* Belated edit conflict! Run away!! */
2171                                         $status->fatal( 'edit-conflict' );
2172
2173                                         # Delete the invalid revision if the DB is not transactional
2174                                         if ( !$wgDBtransactions ) {
2175                                                 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
2176                                         }
2177
2178                                         $revisionId = 0;
2179                                         $dbw->rollback();
2180                                 } else {
2181                                         global $wgUseRCPatrol;
2182                                         wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2183                                         # Update recentchanges
2184                                         if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2185                                                 # Mark as patrolled if the user can do so
2186                                                 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan( 'autopatrol' );
2187                                                 # Add RC row to the DB
2188                                                 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
2189                                                         $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2190                                                         $revisionId, $patrolled
2191                                                 );
2192
2193                                                 # Log auto-patrolled edits
2194                                                 if ( $patrolled ) {
2195                                                         PatrolLog::record( $rc, true );
2196                                                 }
2197                                         }
2198                                         $user->incEditCount();
2199                                         $dbw->commit();
2200                                 }
2201                         } else {
2202                                 $status->warning( 'edit-no-change' );
2203                                 $revision = null;
2204                                 // Keep the same revision ID, but do some updates on it
2205                                 $revisionId = $this->getRevIdFetched();
2206                                 // Update page_touched, this is usually implicit in the page update
2207                                 // Other cache updates are done in onArticleEdit()
2208                                 $this->mTitle->invalidateCache();
2209                         }
2210
2211                         if ( !$wgDBtransactions ) {
2212                                 ignore_user_abort( $userAbort );
2213                         }
2214
2215                         // Now that ignore_user_abort is restored, we can respond to fatal errors
2216                         if ( !$status->isOK() ) {
2217                                 wfProfileOut( __METHOD__ );
2218                                 return $status;
2219                         }
2220
2221                         # Invalidate cache of this article and all pages using this article
2222                         # as a template. Partly deferred.
2223                         Article::onArticleEdit( $this->mTitle );
2224                         # Update links tables, site stats, etc.
2225                         $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2226                 } else {
2227                         # Create new article
2228                         $status->value['new'] = true;
2229
2230                         # Set statistics members
2231                         # We work out if it's countable after PST to avoid counter drift
2232                         # when articles are created with {{subst:}}
2233                         $this->mGoodAdjustment = (int)$this->isCountable( $text );
2234                         $this->mTotalAdjustment = 1;
2235
2236                         $dbw->begin();
2237
2238                         # Add the page record; stake our claim on this title!
2239                         # This will return false if the article already exists
2240                         $newid = $this->insertOn( $dbw );
2241
2242                         if ( $newid === false ) {
2243                                 $dbw->rollback();
2244                                 $status->fatal( 'edit-already-exists' );
2245
2246                                 wfProfileOut( __METHOD__ );
2247                                 return $status;
2248                         }
2249
2250                         # Save the revision text...
2251                         $revision = new Revision( array(
2252                                 'page'       => $newid,
2253                                 'comment'    => $summary,
2254                                 'minor_edit' => $isminor,
2255                                 'text'       => $text,
2256                                 'user'       => $user->getId(),
2257                                 'user_text'  => $user->getName(),
2258                                 ) );
2259                         $revisionId = $revision->insertOn( $dbw );
2260
2261                         $this->mTitle->resetArticleID( $newid );
2262
2263                         # Update the page record with revision data
2264                         $this->updateRevisionOn( $dbw, $revision, 0 );
2265
2266                         wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2267
2268                         # Update recentchanges
2269                         if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2270                                 global $wgUseRCPatrol, $wgUseNPPatrol;
2271
2272                                 # Mark as patrolled if the user can do so
2273                                 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && $this->mTitle->userCan( 'autopatrol' );
2274                                 # Add RC row to the DB
2275                                 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2276                                         '', strlen( $text ), $revisionId, $patrolled );
2277
2278                                 # Log auto-patrolled edits
2279                                 if ( $patrolled ) {
2280                                         PatrolLog::record( $rc, true );
2281                                 }
2282                         }
2283                         $user->incEditCount();
2284                         $dbw->commit();
2285
2286                         # Update links, etc.
2287                         $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2288
2289                         # Clear caches
2290                         Article::onArticleCreate( $this->mTitle );
2291
2292                         wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2293                                 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
2294                 }
2295
2296                 # Do updates right now unless deferral was requested
2297                 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2298                         wfDoUpdates();
2299                 }
2300
2301                 // Return the new revision (or null) to the caller
2302                 $status->value['revision'] = $revision;
2303
2304                 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2305                         $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
2306
2307                 wfProfileOut( __METHOD__ );
2308                 return $status;
2309         }
2310
2311         /**
2312          * @deprecated wrapper for doRedirect
2313          */
2314         public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2315                 wfDeprecated( __METHOD__ );
2316                 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2317         }
2318
2319         /**
2320          * Output a redirect back to the article.
2321          * This is typically used after an edit.
2322          *
2323          * @param $noRedir Boolean: add redirect=no
2324          * @param $sectionAnchor String: section to redirect to, including "#"
2325          * @param $extraQuery String: extra query params
2326          */
2327         public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2328                 global $wgOut;
2329
2330                 if ( $noRedir ) {
2331                         $query = 'redirect=no';
2332                         if ( $extraQuery )
2333                                 $query .= "&$extraQuery";
2334                 } else {
2335                         $query = $extraQuery;
2336                 }
2337
2338                 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2339         }
2340
2341         /**
2342          * Mark this particular edit/page as patrolled
2343          */
2344         public function markpatrolled() {
2345                 global $wgOut, $wgUser, $wgRequest;
2346
2347                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2348
2349                 # If we haven't been given an rc_id value, we can't do anything
2350                 $rcid = (int) $wgRequest->getVal( 'rcid' );
2351
2352                 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
2353                         $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
2354                         return;
2355                 }
2356
2357                 $rc = RecentChange::newFromId( $rcid );
2358
2359                 if ( is_null( $rc ) ) {
2360                         $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2361                         return;
2362                 }
2363
2364                 # It would be nice to see where the user had actually come from, but for now just guess
2365                 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2366                 $return = SpecialPage::getTitleFor( $returnto );
2367
2368                 $errors = $rc->doMarkPatrolled();
2369
2370                 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2371                         $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2372
2373                         return;
2374                 }
2375
2376                 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2377                         // The hook itself has handled any output
2378                         return;
2379                 }
2380
2381                 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2382                         $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2383                         $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2384                         $wgOut->returnToMain( false, $return );
2385
2386                         return;
2387                 }
2388
2389                 if ( !empty( $errors ) ) {
2390                         $wgOut->showPermissionsErrorPage( $errors );
2391
2392                         return;
2393                 }
2394
2395                 # Inform the user
2396                 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2397                 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2398                 $wgOut->returnToMain( false, $return );
2399         }
2400
2401         /**
2402          * User-interface handler for the "watch" action
2403          */
2404         public function watch() {
2405                 global $wgUser, $wgOut;
2406
2407                 if ( $wgUser->isAnon() ) {
2408                         $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2409                         return;
2410                 }
2411
2412                 if ( wfReadOnly() ) {
2413                         $wgOut->readOnlyPage();
2414                         return;
2415                 }
2416
2417                 if ( $this->doWatch() ) {
2418                         $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2419                         $wgOut->setRobotPolicy( 'noindex,nofollow' );
2420                         $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2421                 }
2422
2423                 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2424         }
2425
2426         /**
2427          * Add this page to $wgUser's watchlist
2428          *
2429          * This is safe to be called multiple times
2430          *
2431          * @return bool true on successful watch operation
2432          */
2433         public function doWatch() {
2434                 global $wgUser;
2435
2436                 if ( $wgUser->isAnon() ) {
2437                         return false;
2438                 }
2439
2440                 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2441                         $wgUser->addWatch( $this->mTitle );
2442                         return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2443                 }
2444
2445                 return false;
2446         }
2447
2448         /**
2449          * User interface handler for the "unwatch" action.
2450          */
2451         public function unwatch() {
2452                 global $wgUser, $wgOut;
2453
2454                 if ( $wgUser->isAnon() ) {
2455                         $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2456                         return;
2457                 }
2458
2459                 if ( wfReadOnly() ) {
2460                         $wgOut->readOnlyPage();
2461                         return;
2462                 }
2463
2464                 if ( $this->doUnwatch() ) {
2465                         $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2466                         $wgOut->setRobotPolicy( 'noindex,nofollow' );
2467                         $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2468                 }
2469
2470                 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2471         }
2472
2473         /**
2474          * Stop watching a page
2475          * @return bool true on successful unwatch
2476          */
2477         public function doUnwatch() {
2478                 global $wgUser;
2479
2480                 if ( $wgUser->isAnon() ) {
2481                         return false;
2482                 }
2483
2484                 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2485                         $wgUser->removeWatch( $this->mTitle );
2486                         return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2487                 }
2488
2489                 return false;
2490         }
2491
2492         /**
2493          * action=protect handler
2494          */
2495         public function protect() {
2496                 $form = new ProtectionForm( $this );
2497                 $form->execute();
2498         }
2499
2500         /**
2501          * action=unprotect handler (alias)
2502          */
2503         public function unprotect() {
2504                 $this->protect();
2505         }
2506
2507         /**
2508          * Update the article's restriction field, and leave a log entry.
2509          *
2510          * @param $limit Array: set of restriction keys
2511          * @param $reason String
2512          * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2513          * @param $expiry Array: per restriction type expiration
2514          * @return bool true on success
2515          */
2516         public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2517                 global $wgUser, $wgContLang;
2518
2519                 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2520
2521                 $id = $this->mTitle->getArticleID();
2522
2523                 if ( $id <= 0 ) {
2524                         wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
2525                         return false;
2526                 }
2527
2528                 if ( wfReadOnly() ) {
2529                         wfDebug( "updateRestrictions failed: read-only\n" );
2530                         return false;
2531                 }
2532
2533                 if ( !$this->mTitle->userCan( 'protect' ) ) {
2534                         wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2535                         return false;
2536                 }
2537
2538                 if ( !$cascade ) {
2539                         $cascade = false;
2540                 }
2541
2542                 // Take this opportunity to purge out expired restrictions
2543                 Title::purgeExpiredRestrictions();
2544
2545                 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2546                 # we expect a single selection, but the schema allows otherwise.
2547                 $current = array();
2548                 $updated = Article::flattenRestrictions( $limit );
2549                 $changed = false;
2550
2551                 foreach ( $restrictionTypes as $action ) {
2552                         if ( isset( $expiry[$action] ) ) {
2553                                 # Get current restrictions on $action
2554                                 $aLimits = $this->mTitle->getRestrictions( $action );
2555                                 $current[$action] = implode( '', $aLimits );
2556                                 # Are any actual restrictions being dealt with here?
2557                                 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
2558
2559                                 # If something changed, we need to log it. Checking $aRChanged
2560                                 # assures that "unprotecting" a page that is not protected does
2561                                 # not log just because the expiry was "changed".
2562                                 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2563                                         $changed = true;
2564                                 }
2565                         }
2566                 }
2567
2568                 $current = Article::flattenRestrictions( $current );
2569
2570                 $changed = ( $changed || $current != $updated );
2571                 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
2572                 $protect = ( $updated != '' );
2573
2574                 # If nothing's changed, do nothing
2575                 if ( $changed ) {
2576                         if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2577                                 $dbw = wfGetDB( DB_MASTER );
2578
2579                                 # Prepare a null revision to be added to the history
2580                                 $modified = $current != '' && $protect;
2581
2582                                 if ( $protect ) {
2583                                         $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2584                                 } else {
2585                                         $comment_type = 'unprotectedarticle';
2586                                 }
2587
2588                                 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2589
2590                                 # Only restrictions with the 'protect' right can cascade...
2591                                 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2592                                 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2593
2594                                 # The schema allows multiple restrictions
2595                                 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2596                                         $cascade = false;
2597                                 }
2598
2599                                 $cascade_description = '';
2600
2601                                 if ( $cascade ) {
2602                                         $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2603                                 }
2604
2605                                 if ( $reason ) {
2606                                         $comment .= ": $reason";
2607                                 }
2608
2609                                 $editComment = $comment;
2610                                 $encodedExpiry = array();
2611                                 $protect_description = '';
2612                                 foreach ( $limit as $action => $restrictions ) {
2613                                         if ( !isset( $expiry[$action] ) )
2614                                                 $expiry[$action] = Block::infinity();
2615
2616                                         $encodedExpiry[$action] = Block::encodeExpiry( $expiry[$action], $dbw );
2617                                         if ( $restrictions != '' ) {
2618                                                 $protect_description .= "[$action=$restrictions] (";
2619                                                 if ( $encodedExpiry[$action] != 'infinity' ) {
2620                                                         $protect_description .= wfMsgForContent( 'protect-expiring',
2621                                                                 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2622                                                                 $wgContLang->date( $expiry[$action], false, false ) ,
2623                                                                 $wgContLang->time( $expiry[$action], false, false ) );
2624                                                 } else {
2625                                                         $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2626                                                 }
2627
2628                                                 $protect_description .= ') ';
2629                                         }
2630                                 }
2631                                 $protect_description = trim( $protect_description );
2632
2633                                 if ( $protect_description && $protect ) {
2634                                         $editComment .= " ($protect_description)";
2635                                 }
2636
2637                                 if ( $cascade ) {
2638                                         $editComment .= "$cascade_description";
2639                                 }
2640
2641                                 # Update restrictions table
2642                                 foreach ( $limit as $action => $restrictions ) {
2643                                         if ( $restrictions != '' ) {
2644                                                 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2645                                                         array( 'pr_page' => $id,
2646                                                                 'pr_type' => $action,
2647                                                                 'pr_level' => $restrictions,
2648                                                                 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2649                                                                 'pr_expiry' => $encodedExpiry[$action]
2650                                                         ),
2651                                                         __METHOD__
2652                                                 );
2653                                         } else {
2654                                                 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2655                                                         'pr_type' => $action ), __METHOD__ );
2656                                         }
2657                                 }
2658
2659                                 # Insert a null revision
2660                                 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2661                                 $nullRevId = $nullRevision->insertOn( $dbw );
2662
2663                                 $latest = $this->getLatest();
2664                                 # Update page record
2665                                 $dbw->update( 'page',
2666                                         array( /* SET */
2667                                                 'page_touched' => $dbw->timestamp(),
2668                                                 'page_restrictions' => '',
2669                                                 'page_latest' => $nullRevId
2670                                         ), array( /* WHERE */
2671                                                 'page_id' => $id
2672                                         ), 'Article::protect'
2673                                 );
2674
2675                                 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2676                                 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2677
2678                                 # Update the protection log
2679                                 $log = new LogPage( 'protect' );
2680                                 if ( $protect ) {
2681                                         $params = array( $protect_description, $cascade ? 'cascade' : '' );
2682                                         $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
2683                                 } else {
2684                                         $log->addEntry( 'unprotect', $this->mTitle, $reason );
2685                                 }
2686                         } # End hook
2687                 } # End "changed" check
2688
2689                 return true;
2690         }
2691
2692         /**
2693          * Take an array of page restrictions and flatten it to a string
2694          * suitable for insertion into the page_restrictions field.
2695          * @param $limit Array
2696          * @return String
2697          */
2698         protected static function flattenRestrictions( $limit ) {
2699                 if ( !is_array( $limit ) ) {
2700                         throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2701                 }
2702
2703                 $bits = array();
2704                 ksort( $limit );
2705
2706                 foreach ( $limit as $action => $restrictions ) {
2707                         if ( $restrictions != '' ) {
2708                                 $bits[] = "$action=$restrictions";
2709                         }
2710                 }
2711
2712                 return implode( ':', $bits );
2713         }
2714
2715         /**
2716          * Auto-generates a deletion reason
2717          *
2718          * @param &$hasHistory Boolean: whether the page has a history
2719          * @return mixed String containing deletion reason or empty string, or boolean false
2720          *    if no revision occurred
2721          */
2722         public function generateReason( &$hasHistory ) {
2723                 global $wgContLang;
2724
2725                 $dbw = wfGetDB( DB_MASTER );
2726                 // Get the last revision
2727                 $rev = Revision::newFromTitle( $this->mTitle );
2728
2729                 if ( is_null( $rev ) ) {
2730                         return false;
2731                 }
2732
2733                 // Get the article's contents
2734                 $contents = $rev->getText();
2735                 $blank = false;
2736
2737                 // If the page is blank, use the text from the previous revision,
2738                 // which can only be blank if there's a move/import/protect dummy revision involved
2739                 if ( $contents == '' ) {
2740                         $prev = $rev->getPrevious();
2741
2742                         if ( $prev )    {
2743                                 $contents = $prev->getText();
2744                                 $blank = true;
2745                         }
2746                 }
2747
2748                 // Find out if there was only one contributor
2749                 // Only scan the last 20 revisions
2750                 $res = $dbw->select( 'revision', 'rev_user_text',
2751                         array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2752                         __METHOD__,
2753                         array( 'LIMIT' => 20 )
2754                 );
2755
2756                 if ( $res === false ) {
2757                         // This page has no revisions, which is very weird
2758                         return false;
2759                 }
2760
2761                 $hasHistory = ( $res->numRows() > 1 );
2762                 $row = $dbw->fetchObject( $res );
2763
2764                 if ( $row ) { // $row is false if the only contributor is hidden
2765                         $onlyAuthor = $row->rev_user_text;
2766                         // Try to find a second contributor
2767                         foreach ( $res as $row ) {
2768                                 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2769                                         $onlyAuthor = false;
2770                                         break;
2771                                 }
2772                         }
2773                 } else {
2774                         $onlyAuthor = false;
2775                 }
2776
2777                 // Generate the summary with a '$1' placeholder
2778                 if ( $blank ) {
2779                         // The current revision is blank and the one before is also
2780                         // blank. It's just not our lucky day
2781                         $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2782                 } else {
2783                         if ( $onlyAuthor ) {
2784                                 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2785                         } else {
2786                                 $reason = wfMsgForContent( 'excontent', '$1' );
2787                         }
2788                 }
2789
2790                 if ( $reason == '-' ) {
2791                         // Allow these UI messages to be blanked out cleanly
2792                         return '';
2793                 }
2794
2795                 // Replace newlines with spaces to prevent uglyness
2796                 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2797                 // Calculate the maximum amount of chars to get
2798                 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2799                 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2800                 $contents = $wgContLang->truncate( $contents, $maxLength );
2801                 // Remove possible unfinished links
2802                 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2803                 // Now replace the '$1' placeholder
2804                 $reason = str_replace( '$1', $contents, $reason );
2805
2806                 return $reason;
2807         }
2808
2809
2810         /*
2811          * UI entry point for page deletion
2812          */
2813         public function delete() {
2814                 global $wgUser, $wgOut, $wgRequest;
2815
2816                 $confirm = $wgRequest->wasPosted() &&
2817                                 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2818
2819                 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2820                 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2821
2822                 $reason = $this->DeleteReasonList;
2823
2824                 if ( $reason != 'other' && $this->DeleteReason != '' ) {
2825                         // Entry from drop down menu + additional comment
2826                         $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2827                 } elseif ( $reason == 'other' ) {
2828                         $reason = $this->DeleteReason;
2829                 }
2830
2831                 # Flag to hide all contents of the archived revisions
2832                 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2833
2834                 # This code desperately needs to be totally rewritten
2835
2836                 # Read-only check...
2837                 if ( wfReadOnly() ) {
2838                         $wgOut->readOnlyPage();
2839
2840                         return;
2841                 }
2842
2843                 # Check permissions
2844                 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2845
2846                 if ( count( $permission_errors ) > 0 ) {
2847                         $wgOut->showPermissionsErrorPage( $permission_errors );
2848
2849                         return;
2850                 }
2851
2852                 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2853
2854                 # Better double-check that it hasn't been deleted yet!
2855                 $dbw = wfGetDB( DB_MASTER );
2856                 $conds = $this->mTitle->pageCond();
2857                 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2858                 if ( $latest === false ) {
2859                         $wgOut->showFatalError(
2860                                 Html::rawElement(
2861                                         'div',
2862                                         array( 'class' => 'error mw-error-cannotdelete' ),
2863                                         wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2864                                 )
2865                         );
2866                         $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2867                         LogEventsList::showLogExtract(
2868                                 $wgOut,
2869                                 'delete',
2870                                 $this->mTitle->getPrefixedText()
2871                         );
2872
2873                         return;
2874                 }
2875
2876                 # Hack for big sites
2877                 $bigHistory = $this->isBigDeletion();
2878                 if ( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2879                         global $wgLang, $wgDeleteRevisionsLimit;
2880
2881                         $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2882                                 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2883
2884                         return;
2885                 }
2886
2887                 if ( $confirm ) {
2888                         $this->doDelete( $reason, $suppress );
2889
2890                         if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2891                                 $this->doWatch();
2892                         } elseif ( $this->mTitle->userIsWatching() ) {
2893                                 $this->doUnwatch();
2894                         }
2895
2896                         return;
2897                 }
2898
2899                 // Generate deletion reason
2900                 $hasHistory = false;
2901                 if ( !$reason ) {
2902                         $reason = $this->generateReason( $hasHistory );
2903                 }
2904
2905                 // If the page has a history, insert a warning
2906                 if ( $hasHistory && !$confirm ) {
2907                         global $wgLang;
2908
2909                         $skin = $wgUser->getSkin();
2910                         $revisions = $this->estimateRevisionCount();
2911                         //FIXME: lego
2912                         $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2913                                 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2914                                 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2915                                 '</strong>'
2916                         );
2917
2918                         if ( $bigHistory ) {
2919                                 global $wgDeleteRevisionsLimit;
2920                                 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2921                                         array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2922                         }
2923                 }
2924
2925                 return $this->confirmDelete( $reason );
2926         }
2927
2928         /**
2929          * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2930          */
2931         public function isBigDeletion() {
2932                 global $wgDeleteRevisionsLimit;
2933
2934                 if ( $wgDeleteRevisionsLimit ) {
2935                         $revCount = $this->estimateRevisionCount();
2936
2937                         return $revCount > $wgDeleteRevisionsLimit;
2938                 }
2939
2940                 return false;
2941         }
2942
2943         /**
2944          * @return int approximate revision count
2945          */
2946         public function estimateRevisionCount() {
2947                 $dbr = wfGetDB( DB_SLAVE );
2948
2949                 // For an exact count...
2950                 // return $dbr->selectField( 'revision', 'COUNT(*)',
2951                 //      array( 'rev_page' => $this->getId() ), __METHOD__ );
2952                 return $dbr->estimateRowCount( 'revision', '*',
2953                         array( 'rev_page' => $this->getId() ), __METHOD__ );
2954         }
2955
2956         /**
2957          * Get the last N authors
2958          * @param $num Integer: number of revisions to get
2959          * @param $revLatest String: the latest rev_id, selected from the master (optional)
2960          * @return array Array of authors, duplicates not removed
2961          */
2962         public function getLastNAuthors( $num, $revLatest = 0 ) {
2963                 wfProfileIn( __METHOD__ );
2964                 // First try the slave
2965                 // If that doesn't have the latest revision, try the master
2966                 $continue = 2;
2967                 $db = wfGetDB( DB_SLAVE );
2968
2969                 do {
2970                         $res = $db->select( array( 'page', 'revision' ),
2971                                 array( 'rev_id', 'rev_user_text' ),
2972                                 array(
2973                                         'page_namespace' => $this->mTitle->getNamespace(),
2974                                         'page_title' => $this->mTitle->getDBkey(),
2975                                         'rev_page = page_id'
2976                                 ), __METHOD__, $this->getSelectOptions( array(
2977                                         'ORDER BY' => 'rev_timestamp DESC',
2978                                         'LIMIT' => $num
2979                                 ) )
2980                         );
2981
2982                         if ( !$res ) {
2983                                 wfProfileOut( __METHOD__ );
2984                                 return array();
2985                         }
2986
2987                         $row = $db->fetchObject( $res );
2988
2989                         if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2990                                 $db = wfGetDB( DB_MASTER );
2991                                 $continue--;
2992                         } else {
2993                                 $continue = 0;
2994                         }
2995                 } while ( $continue );
2996
2997                 $authors = array( $row->rev_user_text );
2998
2999                 foreach ( $res as $row ) {
3000                         $authors[] = $row->rev_user_text;
3001                 }
3002
3003                 wfProfileOut( __METHOD__ );
3004                 return $authors;
3005         }
3006
3007         /**
3008          * Output deletion confirmation dialog
3009          * FIXME: Move to another file?
3010          * @param $reason String: prefilled reason
3011          */
3012         public function confirmDelete( $reason ) {
3013                 global $wgOut, $wgUser;
3014
3015                 wfDebug( "Article::confirmDelete\n" );
3016
3017                 $deleteBackLink = $wgUser->getSkin()->linkKnown( $this->mTitle );
3018                 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
3019                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3020                 $wgOut->addWikiMsg( 'confirmdeletetext' );
3021
3022                 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
3023
3024                 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
3025                         $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
3026                                         <td></td>
3027                                         <td class='mw-input'><strong>" .
3028                                                 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
3029                                                         'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
3030                                         "</strong></td>
3031                                 </tr>";
3032                 } else {
3033                         $suppress = '';
3034                 }
3035                 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
3036
3037                 $form = Xml::openElement( 'form', array( 'method' => 'post',
3038                         'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
3039                         Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
3040                         Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
3041                         Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
3042                         "<tr id=\"wpDeleteReasonListRow\">
3043                                 <td class='mw-label'>" .
3044                                         Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
3045                                 "</td>
3046                                 <td class='mw-input'>" .
3047                                         Xml::listDropDown( 'wpDeleteReasonList',
3048                                                 wfMsgForContent( 'deletereason-dropdown' ),
3049                                                 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
3050                                 "</td>
3051                         </tr>
3052                         <tr id=\"wpDeleteReasonRow\">
3053                                 <td class='mw-label'>" .
3054                                         Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
3055                                 "</td>
3056                                 <td class='mw-input'>" .
3057                                 Html::input( 'wpReason', $reason, 'text', array(
3058                                         'size' => '60',
3059                                         'maxlength' => '255',
3060                                         'tabindex' => '2',
3061                                         'id' => 'wpReason',
3062                                         'autofocus'
3063                                 ) ) .
3064                                 "</td>
3065                         </tr>";
3066
3067                 # Disallow watching if user is not logged in
3068                 if ( $wgUser->isLoggedIn() ) {
3069                         $form .= "
3070                         <tr>
3071                                 <td></td>
3072                                 <td class='mw-input'>" .
3073                                         Xml::checkLabel( wfMsg( 'watchthis' ),
3074                                                 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
3075                                 "</td>
3076                         </tr>";
3077                 }
3078
3079                 $form .= "
3080                         $suppress
3081                         <tr>
3082                                 <td></td>
3083                                 <td class='mw-submit'>" .
3084                                         Xml::submitButton( wfMsg( 'deletepage' ),
3085                                                 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
3086                                 "</td>
3087                         </tr>" .
3088                         Xml::closeElement( 'table' ) .
3089                         Xml::closeElement( 'fieldset' ) .
3090                         Html::hidden( 'wpEditToken', $wgUser->editToken() ) .
3091                         Xml::closeElement( 'form' );
3092
3093                         if ( $wgUser->isAllowed( 'editinterface' ) ) {
3094                                 $skin = $wgUser->getSkin();
3095                                 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
3096                                 $link = $skin->link(
3097                                         $title,
3098                                         wfMsgHtml( 'delete-edit-reasonlist' ),
3099                                         array(),
3100                                         array( 'action' => 'edit' )
3101                                 );
3102                                 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3103                         }
3104
3105                 $wgOut->addHTML( $form );
3106                 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3107                 LogEventsList::showLogExtract( $wgOut, 'delete',
3108                         $this->mTitle->getPrefixedText()
3109                 );
3110         }
3111
3112         /**
3113          * Perform a deletion and output success or failure messages
3114          */
3115         public function doDelete( $reason, $suppress = false ) {
3116                 global $wgOut, $wgUser;
3117
3118                 $id = $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
3119
3120                 $error = '';
3121                 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3122                         if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
3123                                 $deleted = $this->mTitle->getPrefixedText();
3124
3125                                 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3126                                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3127
3128                                 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3129
3130                                 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3131                                 $wgOut->returnToMain( false );
3132                                 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3133                         }
3134                 } else {
3135                         if ( $error == '' ) {
3136                                 $wgOut->showFatalError(
3137                                         Html::rawElement(
3138                                                 'div',
3139                                                 array( 'class' => 'error mw-error-cannotdelete' ),
3140                                                 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
3141                                         )
3142                                 );
3143
3144                                 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3145
3146                                 LogEventsList::showLogExtract(
3147                                         $wgOut,
3148                                         'delete',
3149                                         $this->mTitle->getPrefixedText()
3150                                 );
3151                         } else {
3152                                 $wgOut->showFatalError( $error );
3153                         }
3154                 }
3155         }
3156
3157         /**
3158          * Back-end article deletion
3159          * Deletes the article with database consistency, writes logs, purges caches
3160          *
3161          * @param $reason string delete reason for deletion log
3162          * @param suppress bitfield
3163          *      Revision::DELETED_TEXT
3164          *      Revision::DELETED_COMMENT
3165          *      Revision::DELETED_USER
3166          *      Revision::DELETED_RESTRICTED
3167          * @param $id int article ID
3168          * @param $commit boolean defaults to true, triggers transaction end
3169          * @return boolean true if successful
3170          */
3171         public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
3172                 global $wgDeferredUpdateList, $wgUseTrackbacks;
3173
3174                 wfDebug( __METHOD__ . "\n" );
3175
3176                 $dbw = wfGetDB( DB_MASTER );
3177                 $t = $this->mTitle->getDBkey();
3178                 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
3179
3180                 if ( $t === '' || $id == 0 ) {
3181                         return false;
3182                 }
3183
3184                 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3185                 array_push( $wgDeferredUpdateList, $u );
3186
3187                 // Bitfields to further suppress the content
3188                 if ( $suppress ) {
3189                         $bitfield = 0;
3190                         // This should be 15...
3191                         $bitfield |= Revision::DELETED_TEXT;
3192                         $bitfield |= Revision::DELETED_COMMENT;
3193                         $bitfield |= Revision::DELETED_USER;
3194                         $bitfield |= Revision::DELETED_RESTRICTED;
3195                 } else {
3196                         $bitfield = 'rev_deleted';
3197                 }
3198
3199                 $dbw->begin();
3200                 // For now, shunt the revision data into the archive table.
3201                 // Text is *not* removed from the text table; bulk storage
3202                 // is left intact to avoid breaking block-compression or
3203                 // immutable storage schemes.
3204                 //
3205                 // For backwards compatibility, note that some older archive
3206                 // table entries will have ar_text and ar_flags fields still.
3207                 //
3208                 // In the future, we may keep revisions and mark them with
3209                 // the rev_deleted field, which is reserved for this purpose.
3210                 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3211                         array(
3212                                 'ar_namespace'  => 'page_namespace',
3213                                 'ar_title'      => 'page_title',
3214                                 'ar_comment'    => 'rev_comment',
3215                                 'ar_user'       => 'rev_user',
3216                                 'ar_user_text'  => 'rev_user_text',
3217                                 'ar_timestamp'  => 'rev_timestamp',
3218                                 'ar_minor_edit' => 'rev_minor_edit',
3219                                 'ar_rev_id'     => 'rev_id',
3220                                 'ar_text_id'    => 'rev_text_id',
3221                                 'ar_text'       => '\'\'', // Be explicit to appease
3222                                 'ar_flags'      => '\'\'', // MySQL's "strict mode"...
3223                                 'ar_len'        => 'rev_len',
3224                                 'ar_page_id'    => 'page_id',
3225                                 'ar_deleted'    => $bitfield
3226                         ), array(
3227                                 'page_id' => $id,
3228                                 'page_id = rev_page'
3229                         ), __METHOD__
3230                 );
3231
3232                 # Delete restrictions for it
3233                 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
3234
3235                 # Now that it's safely backed up, delete it
3236                 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
3237                 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3238
3239                 if ( !$ok ) {
3240                         $dbw->rollback();
3241                         return false;
3242                 }
3243
3244                 # Fix category table counts
3245                 $cats = array();
3246                 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
3247
3248                 foreach ( $res as $row ) {
3249                         $cats [] = $row->cl_to;
3250                 }
3251
3252                 $this->updateCategoryCounts( array(), $cats );
3253
3254                 # If using cascading deletes, we can skip some explicit deletes
3255                 if ( !$dbw->cascadingDeletes() ) {
3256                         $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
3257
3258                         if ( $wgUseTrackbacks )
3259                                 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
3260
3261                         # Delete outgoing links
3262                         $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3263                         $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3264                         $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3265                         $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3266                         $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3267                         $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3268                         $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
3269                         $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3270                 }
3271
3272                 # If using cleanup triggers, we can skip some manual deletes
3273                 if ( !$dbw->cleanupTriggers() ) {
3274                         # Clean up recentchanges entries...
3275                         $dbw->delete( 'recentchanges',
3276                                 array( 'rc_type != ' . RC_LOG,
3277                                         'rc_namespace' => $this->mTitle->getNamespace(),
3278                                         'rc_title' => $this->mTitle->getDBkey() ),
3279                                 __METHOD__ );
3280                         $dbw->delete( 'recentchanges',
3281                                 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
3282                                 __METHOD__ );
3283                 }
3284
3285                 # Clear caches
3286                 Article::onArticleDelete( $this->mTitle );
3287
3288                 # Clear the cached article id so the interface doesn't act like we exist
3289                 $this->mTitle->resetArticleID( 0 );
3290
3291                 # Log the deletion, if the page was suppressed, log it at Oversight instead
3292                 $logtype = $suppress ? 'suppress' : 'delete';
3293                 $log = new LogPage( $logtype );
3294
3295                 # Make sure logging got through
3296                 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
3297
3298                 if ( $commit ) {
3299                         $dbw->commit();
3300                 }
3301
3302                 return true;
3303         }
3304
3305         /**
3306          * Roll back the most recent consecutive set of edits to a page
3307          * from the same user; fails if there are no eligible edits to
3308          * roll back to, e.g. user is the sole contributor. This function
3309          * performs permissions checks on $wgUser, then calls commitRollback()
3310          * to do the dirty work
3311          *
3312          * @param $fromP String: Name of the user whose edits to rollback.
3313          * @param $summary String: Custom summary. Set to default summary if empty.
3314          * @param $token String: Rollback token.
3315          * @param $bot Boolean: If true, mark all reverted edits as bot.
3316          *
3317          * @param $resultDetails Array: contains result-specific array of additional values
3318          *    'alreadyrolled' : 'current' (rev)
3319          *    success        : 'summary' (str), 'current' (rev), 'target' (rev)
3320          *
3321          * @return array of errors, each error formatted as
3322          *   array(messagekey, param1, param2, ...).
3323          * On success, the array is empty.  This array can also be passed to
3324          * OutputPage::showPermissionsErrorPage().
3325          */
3326         public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3327                 global $wgUser;
3328
3329                 $resultDetails = null;
3330
3331                 # Check permissions
3332                 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
3333                 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
3334                 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3335
3336                 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3337                         $errors[] = array( 'sessionfailure' );
3338                 }
3339
3340                 if ( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
3341                         $errors[] = array( 'actionthrottledtext' );
3342                 }
3343
3344                 # If there were errors, bail out now
3345                 if ( !empty( $errors ) ) {
3346                         return $errors;
3347                 }
3348
3349                 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3350         }
3351
3352         /**
3353          * Backend implementation of doRollback(), please refer there for parameter
3354          * and return value documentation
3355          *
3356          * NOTE: This function does NOT check ANY permissions, it just commits the
3357          * rollback to the DB Therefore, you should only call this function direct-
3358          * ly if you want to use custom permissions checks. If you don't, use
3359          * doRollback() instead.
3360          */
3361         public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3362                 global $wgUseRCPatrol, $wgUser, $wgLang;
3363
3364                 $dbw = wfGetDB( DB_MASTER );
3365
3366                 if ( wfReadOnly() ) {
3367                         return array( array( 'readonlytext' ) );
3368                 }
3369
3370                 # Get the last editor
3371                 $current = Revision::newFromTitle( $this->mTitle );
3372                 if ( is_null( $current ) ) {
3373                         # Something wrong... no page?
3374                         return array( array( 'notanarticle' ) );
3375                 }
3376
3377                 $from = str_replace( '_', ' ', $fromP );
3378                 # User name given should match up with the top revision.
3379                 # If the user was deleted then $from should be empty.
3380                 if ( $from != $current->getUserText() ) {
3381                         $resultDetails = array( 'current' => $current );
3382                         return array( array( 'alreadyrolled',
3383                                 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3384                                 htmlspecialchars( $fromP ),
3385                                 htmlspecialchars( $current->getUserText() )
3386                         ) );
3387                 }
3388
3389                 # Get the last edit not by this guy...
3390                 # Note: these may not be public values
3391                 $user = intval( $current->getRawUser() );
3392                 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3393                 $s = $dbw->selectRow( 'revision',
3394                         array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3395                         array( 'rev_page' => $current->getPage(),
3396                                 "rev_user != {$user} OR rev_user_text != {$user_text}"
3397                         ), __METHOD__,
3398                         array( 'USE INDEX' => 'page_timestamp',
3399                                 'ORDER BY' => 'rev_timestamp DESC' )
3400                         );
3401                 if ( $s === false ) {
3402                         # No one else ever edited this page
3403                         return array( array( 'cantrollback' ) );
3404                 } else if ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
3405                         # Only admins can see this text
3406                         return array( array( 'notvisiblerev' ) );
3407                 }
3408
3409                 $set = array();
3410                 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3411                         # Mark all reverted edits as bot
3412                         $set['rc_bot'] = 1;
3413                 }
3414
3415                 if ( $wgUseRCPatrol ) {
3416                         # Mark all reverted edits as patrolled
3417                         $set['rc_patrolled'] = 1;
3418                 }
3419
3420                 if ( count( $set ) ) {
3421                         $dbw->update( 'recentchanges', $set,
3422                                 array( /* WHERE */
3423                                         'rc_cur_id' => $current->getPage(),
3424                                         'rc_user_text' => $current->getUserText(),
3425                                         "rc_timestamp > '{$s->rev_timestamp}'",
3426                                 ), __METHOD__
3427                         );
3428                 }
3429
3430                 # Generate the edit summary if necessary
3431                 $target = Revision::newFromId( $s->rev_id );
3432                 if ( empty( $summary ) ) {
3433                         if ( $from == '' ) { // no public user name
3434                                 $summary = wfMsgForContent( 'revertpage-nouser' );
3435                         } else {
3436                                 $summary = wfMsgForContent( 'revertpage' );
3437                         }
3438                 }
3439
3440                 # Allow the custom summary to use the same args as the default message
3441                 $args = array(
3442                         $target->getUserText(), $from, $s->rev_id,
3443                         $wgLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ), true ),
3444                         $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3445                 );
3446                 $summary = wfMsgReplaceArgs( $summary, $args );
3447
3448                 # Save
3449                 $flags = EDIT_UPDATE;
3450
3451                 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3452                         $flags |= EDIT_MINOR;
3453                 }
3454
3455                 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) || $wgUser->isAllowed( 'bot' ) ) ) {
3456                         $flags |= EDIT_FORCE_BOT;
3457                 }
3458
3459                 # Actually store the edit
3460                 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3461                 if ( !empty( $status->value['revision'] ) ) {
3462                         $revId = $status->value['revision']->getId();
3463                 } else {
3464                         $revId = false;
3465                 }
3466
3467                 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3468
3469                 $resultDetails = array(
3470                         'summary' => $summary,
3471                         'current' => $current,
3472                         'target'  => $target,
3473                         'newid'   => $revId
3474                 );
3475
3476                 return array();
3477         }
3478
3479         /**
3480          * User interface for rollback operations
3481          */
3482         public function rollback() {
3483                 global $wgUser, $wgOut, $wgRequest;
3484
3485                 $details = null;
3486
3487                 $result = $this->doRollback(
3488                         $wgRequest->getVal( 'from' ),
3489                         $wgRequest->getText( 'summary' ),
3490                         $wgRequest->getVal( 'token' ),
3491                         $wgRequest->getBool( 'bot' ),
3492                         $details
3493                 );
3494
3495                 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3496                         $wgOut->rateLimited();
3497                         return;
3498                 }
3499
3500                 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3501                         $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3502                         $errArray = $result[0];
3503                         $errMsg = array_shift( $errArray );
3504                         $wgOut->addWikiMsgArray( $errMsg, $errArray );
3505
3506                         if ( isset( $details['current'] ) ) {
3507                                 $current = $details['current'];
3508
3509                                 if ( $current->getComment() != '' ) {
3510                                         $wgOut->addWikiMsgArray( 'editcomment', array(
3511                                                 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3512                                 }
3513                         }
3514
3515                         return;
3516                 }
3517
3518                 # Display permissions errors before read-only message -- there's no
3519                 # point in misleading the user into thinking the inability to rollback
3520                 # is only temporary.
3521                 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3522                         # array_diff is completely broken for arrays of arrays, sigh.
3523                         # Remove any 'readonlytext' error manually.
3524                         $out = array();
3525                         foreach ( $result as $error ) {
3526                                 if ( $error != array( 'readonlytext' ) ) {
3527                                         $out [] = $error;
3528                                 }
3529                         }
3530                         $wgOut->showPermissionsErrorPage( $out );
3531
3532                         return;
3533                 }
3534
3535                 if ( $result == array( array( 'readonlytext' ) ) ) {
3536                         $wgOut->readOnlyPage();
3537
3538                         return;
3539                 }
3540
3541                 $current = $details['current'];
3542                 $target = $details['target'];
3543                 $newId = $details['newid'];
3544                 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3545                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3546
3547                 if ( $current->getUserText() === '' ) {
3548                         $old = wfMsg( 'rev-deleted-user' );
3549                 } else {
3550                         $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3551                                 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3552                 }
3553
3554                 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3555                         . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3556                 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3557                 $wgOut->returnToMain( false, $this->mTitle );
3558
3559                 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3560                         $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3561                         $de->showDiff( '', '' );
3562                 }
3563         }
3564
3565         /**
3566          * Do standard deferred updates after page view
3567          */
3568         public function viewUpdates() {
3569                 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3570                 if ( wfReadOnly() ) {
3571                         return;
3572                 }
3573
3574                 # Don't update page view counters on views from bot users (bug 14044)
3575                 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3576                         Article::incViewCount( $this->getID() );
3577                         $u = new SiteStatsUpdate( 1, 0, 0 );
3578                         array_push( $wgDeferredUpdateList, $u );
3579                 }
3580
3581                 # Update newtalk / watchlist notification status
3582                 $wgUser->clearNotification( $this->mTitle );
3583         }
3584
3585         /**
3586          * Prepare text which is about to be saved.
3587          * Returns a stdclass with source, pst and output members
3588          */
3589         public function prepareTextForEdit( $text, $revid = null ) {
3590                 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
3591                         // Already prepared
3592                         return $this->mPreparedEdit;
3593                 }
3594
3595                 global $wgParser;
3596
3597                 $edit = (object)array();
3598                 $edit->revid = $revid;
3599                 $edit->newText = $text;
3600                 $edit->pst = $this->preSaveTransform( $text );
3601                 $edit->popts = $this->getParserOptions();
3602                 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
3603                 $edit->oldText = $this->getContent();
3604
3605                 $this->mPreparedEdit = $edit;
3606
3607                 return $edit;
3608         }
3609
3610         /**
3611          * Do standard deferred updates after page edit.
3612          * Update links tables, site stats, search index and message cache.
3613          * Purges pages that include this page if the text was changed here.
3614          * Every 100th edit, prune the recent changes table.
3615          *
3616          * @private
3617          * @param $text String: New text of the article
3618          * @param $summary String: Edit summary
3619          * @param $minoredit Boolean: Minor edit
3620          * @param $timestamp_of_pagechange Timestamp associated with the page change
3621          * @param $newid Integer: rev_id value of the new revision
3622          * @param $changed Boolean: Whether or not the content actually changed
3623          */
3624         public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3625                 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3626
3627                 wfProfileIn( __METHOD__ );
3628
3629                 # Parse the text
3630                 # Be careful not to double-PST: $text is usually already PST-ed once
3631                 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3632                         wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3633                         $editInfo = $this->prepareTextForEdit( $text, $newid );
3634                 } else {
3635                         wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3636                         $editInfo = $this->mPreparedEdit;
3637                 }
3638
3639                 # Save it to the parser cache
3640                 if ( $wgEnableParserCache ) {
3641                         $parserCache = ParserCache::singleton();
3642                         $parserCache->save( $editInfo->output, $this, $editInfo->popts );
3643                 }
3644
3645                 # Update the links tables
3646                 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3647                 $u->doUpdate();
3648
3649                 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3650
3651                 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3652                         if ( 0 == mt_rand( 0, 99 ) ) {
3653                                 // Flush old entries from the `recentchanges` table; we do this on
3654                                 // random requests so as to avoid an increase in writes for no good reason
3655                                 global $wgRCMaxAge;
3656
3657                                 $dbw = wfGetDB( DB_MASTER );
3658                                 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3659                                 $recentchanges = $dbw->tableName( 'recentchanges' );
3660                                 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3661
3662                                 $dbw->query( $sql );
3663                         }
3664                 }
3665
3666                 $id = $this->getID();
3667                 $title = $this->mTitle->getPrefixedDBkey();
3668                 $shortTitle = $this->mTitle->getDBkey();
3669
3670                 if ( 0 == $id ) {
3671                         wfProfileOut( __METHOD__ );
3672                         return;
3673                 }
3674
3675                 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3676                 array_push( $wgDeferredUpdateList, $u );
3677                 $u = new SearchUpdate( $id, $title, $text );
3678                 array_push( $wgDeferredUpdateList, $u );
3679
3680                 # If this is another user's talk page, update newtalk
3681                 # Don't do this if $changed = false otherwise some idiot can null-edit a
3682                 # load of user talk pages and piss people off, nor if it's a minor edit
3683                 # by a properly-flagged bot.
3684                 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3685                         && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3686                 ) {
3687                         if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3688                                 $other = User::newFromName( $shortTitle, false );
3689                                 if ( !$other ) {
3690                                         wfDebug( __METHOD__ . ": invalid username\n" );
3691                                 } elseif ( User::isIP( $shortTitle ) ) {
3692                                         // An anonymous user
3693                                         $other->setNewtalk( true );
3694                                 } elseif ( $other->isLoggedIn() ) {
3695                                         $other->setNewtalk( true );
3696                                 } else {
3697                                         wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
3698                                 }
3699                         }
3700                 }
3701
3702                 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3703                         $wgMessageCache->replace( $shortTitle, $text );
3704                 }
3705
3706                 wfProfileOut( __METHOD__ );
3707         }
3708
3709         /**
3710          * Perform article updates on a special page creation.
3711          *
3712          * @param $rev Revision object
3713          *
3714          * @todo This is a shitty interface function. Kill it and replace the
3715          * other shitty functions like editUpdates and such so it's not needed
3716          * anymore.
3717          */
3718         public function createUpdates( $rev ) {
3719                 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3720                 $this->mTotalAdjustment = 1;
3721                 $this->editUpdates( $rev->getText(), $rev->getComment(),
3722                         $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3723         }
3724
3725         /**
3726          * Generate the navigation links when browsing through an article revisions
3727          * It shows the information as:
3728          *   Revision as of \<date\>; view current revision
3729          *   \<- Previous version | Next Version -\>
3730          *
3731          * @param $oldid String: revision ID of this article revision
3732          */
3733         public function setOldSubtitle( $oldid = 0 ) {
3734                 global $wgLang, $wgOut, $wgUser, $wgRequest;
3735
3736                 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3737                         return;
3738                 }
3739
3740                 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3741
3742                 # Cascade unhide param in links for easy deletion browsing
3743                 $extraParams = array();
3744                 if ( $wgRequest->getVal( 'unhide' ) ) {
3745                         $extraParams['unhide'] = 1;
3746                 }
3747
3748                 $revision = Revision::newFromId( $oldid );
3749
3750                 $current = ( $oldid == $this->mLatest );
3751                 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3752                 $tddate = $wgLang->date( $this->mTimestamp, true );
3753                 $tdtime = $wgLang->time( $this->mTimestamp, true );
3754                 $sk = $wgUser->getSkin();
3755                 $lnk = $current
3756                         ? wfMsgHtml( 'currentrevisionlink' )
3757                         : $sk->link(
3758                                 $this->mTitle,
3759                                 wfMsgHtml( 'currentrevisionlink' ),
3760                                 array(),
3761                                 $extraParams,
3762                                 array( 'known', 'noclasses' )
3763                         );
3764                 $curdiff = $current
3765                         ? wfMsgHtml( 'diff' )
3766                         : $sk->link(
3767                                 $this->mTitle,
3768                                 wfMsgHtml( 'diff' ),
3769                                 array(),
3770                                 array(
3771                                         'diff' => 'cur',
3772                                         'oldid' => $oldid
3773                                 ) + $extraParams,
3774                                 array( 'known', 'noclasses' )
3775                         );
3776                 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3777                 $prevlink = $prev
3778                         ? $sk->link(
3779                                 $this->mTitle,
3780                                 wfMsgHtml( 'previousrevision' ),
3781                                 array(),
3782                                 array(
3783                                         'direction' => 'prev',
3784                                         'oldid' => $oldid
3785                                 ) + $extraParams,
3786                                 array( 'known', 'noclasses' )
3787                         )
3788                         : wfMsgHtml( 'previousrevision' );
3789                 $prevdiff = $prev
3790                         ? $sk->link(
3791                                 $this->mTitle,
3792                                 wfMsgHtml( 'diff' ),
3793                                 array(),
3794                                 array(
3795                                         'diff' => 'prev',
3796                                         'oldid' => $oldid
3797                                 ) + $extraParams,
3798                                 array( 'known', 'noclasses' )
3799                         )
3800                         : wfMsgHtml( 'diff' );
3801                 $nextlink = $current
3802                         ? wfMsgHtml( 'nextrevision' )
3803                         : $sk->link(
3804                                 $this->mTitle,
3805                                 wfMsgHtml( 'nextrevision' ),
3806                                 array(),
3807                                 array(
3808                                         'direction' => 'next',
3809                                         'oldid' => $oldid
3810                                 ) + $extraParams,
3811                                 array( 'known', 'noclasses' )
3812                         );
3813                 $nextdiff = $current
3814                         ? wfMsgHtml( 'diff' )
3815                         : $sk->link(
3816                                 $this->mTitle,
3817                                 wfMsgHtml( 'diff' ),
3818                                 array(),
3819                                 array(
3820                                         'diff' => 'next',
3821                                         'oldid' => $oldid
3822                                 ) + $extraParams,
3823                                 array( 'known', 'noclasses' )
3824                         );
3825
3826                 $cdel = '';
3827
3828                 // User can delete revisions or view deleted revisions...
3829                 $canHide = $wgUser->isAllowed( 'deleterevision' );
3830                 if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3831                         if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3832                                 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3833                         } else {
3834                                 $query = array(
3835                                         'type'   => 'revision',
3836                                         'target' => $this->mTitle->getPrefixedDbkey(),
3837                                         'ids'    => $oldid
3838                                 );
3839                                 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
3840                         }
3841                         $cdel .= ' ';
3842                 }
3843
3844                 # Show user links if allowed to see them. If hidden, then show them only if requested...
3845                 $userlinks = $sk->revUserTools( $revision, !$unhide );
3846
3847                 $m = wfMsg( 'revision-info-current' );
3848                 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3849                         ? 'revision-info-current'
3850                         : 'revision-info';
3851
3852                 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3853                         wfMsgExt(
3854                                 $infomsg,
3855                                 array( 'parseinline', 'replaceafter' ),
3856                                 $td,
3857                                 $userlinks,
3858                                 $revision->getID(),
3859                                 $tddate,
3860                                 $tdtime,
3861                                 $revision->getUser()
3862                         ) .
3863                         "</div>\n" .
3864                         "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3865                         $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3866
3867                 $wgOut->setSubtitle( $r );
3868         }
3869
3870         /**
3871          * This function is called right before saving the wikitext,
3872          * so we can do things like signatures and links-in-context.
3873          *
3874          * @param $text String article contents
3875          * @return string article contents with altered wikitext markup (signatures
3876          *      converted, {{subst:}}, templates, etc.)
3877          */
3878         public function preSaveTransform( $text ) {
3879                 global $wgParser, $wgUser;
3880
3881                 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3882         }
3883
3884         /* Caching functions */
3885
3886         /**
3887          * checkLastModified returns true if it has taken care of all
3888          * output to the client that is necessary for this request.
3889          * (that is, it has sent a cached version of the page)
3890          *
3891          * @return boolean true if cached version send, false otherwise
3892          */
3893         protected function tryFileCache() {
3894                 static $called = false;
3895
3896                 if ( $called ) {
3897                         wfDebug( "Article::tryFileCache(): called twice!?\n" );
3898                         return false;
3899                 }
3900
3901                 $called = true;
3902                 if ( $this->isFileCacheable() ) {
3903                         $cache = new HTMLFileCache( $this->mTitle );
3904                         if ( $cache->isFileCacheGood( $this->mTouched ) ) {
3905                                 wfDebug( "Article::tryFileCache(): about to load file\n" );
3906                                 $cache->loadFromFileCache();
3907                                 return true;
3908                         } else {
3909                                 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3910                                 ob_start( array( &$cache, 'saveToFileCache' ) );
3911                         }
3912                 } else {
3913                         wfDebug( "Article::tryFileCache(): not cacheable\n" );
3914                 }
3915
3916                 return false;
3917         }
3918
3919         /**
3920          * Check if the page can be cached
3921          * @return bool
3922          */
3923         public function isFileCacheable() {
3924                 $cacheable = false;
3925
3926                 if ( HTMLFileCache::useFileCache() ) {
3927                         $cacheable = $this->getID() && !$this->mRedirectedFrom && !$this->mTitle->isRedirect();
3928                         // Extension may have reason to disable file caching on some pages.
3929                         if ( $cacheable ) {
3930                                 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3931                         }
3932                 }
3933
3934                 return $cacheable;
3935         }
3936
3937         /**
3938          * Loads page_touched and returns a value indicating if it should be used
3939          * @return boolean true if not a redirect
3940          */
3941         public function checkTouched() {
3942                 if ( !$this->mDataLoaded ) {
3943                         $this->loadPageData();
3944                 }
3945
3946                 return !$this->mIsRedirect;
3947         }
3948
3949         /**
3950          * Get the page_touched field
3951          * @return string containing GMT timestamp
3952          */
3953         public function getTouched() {
3954                 if ( !$this->mDataLoaded ) {
3955                         $this->loadPageData();
3956                 }
3957
3958                 return $this->mTouched;
3959         }
3960
3961         /**
3962          * Get the page_latest field
3963          * @return integer rev_id of current revision
3964          */
3965         public function getLatest() {
3966                 if ( !$this->mDataLoaded ) {
3967                         $this->loadPageData();
3968                 }
3969
3970                 return (int)$this->mLatest;
3971         }
3972
3973         /**
3974          * Edit an article without doing all that other stuff
3975          * The article must already exist; link tables etc
3976          * are not updated, caches are not flushed.
3977          *
3978          * @param $text String: text submitted
3979          * @param $comment String: comment submitted
3980          * @param $minor Boolean: whereas it's a minor modification
3981          */
3982         public function quickEdit( $text, $comment = '', $minor = 0 ) {
3983                 wfProfileIn( __METHOD__ );
3984
3985                 $dbw = wfGetDB( DB_MASTER );
3986                 $revision = new Revision( array(
3987                         'page'       => $this->getId(),
3988                         'text'       => $text,
3989                         'comment'    => $comment,
3990                         'minor_edit' => $minor ? 1 : 0,
3991                         ) );
3992                 $revision->insertOn( $dbw );
3993                 $this->updateRevisionOn( $dbw, $revision );
3994
3995                 global $wgUser;
3996                 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3997
3998                 wfProfileOut( __METHOD__ );
3999         }
4000
4001         /**
4002          * Used to increment the view counter
4003          *
4004          * @param $id Integer: article id
4005          */
4006         public static function incViewCount( $id ) {
4007                 $id = intval( $id );
4008
4009                 global $wgHitcounterUpdateFreq;
4010
4011                 $dbw = wfGetDB( DB_MASTER );
4012                 $pageTable = $dbw->tableName( 'page' );
4013                 $hitcounterTable = $dbw->tableName( 'hitcounter' );
4014                 $acchitsTable = $dbw->tableName( 'acchits' );
4015                 $dbType = $dbw->getType();
4016
4017                 if ( $wgHitcounterUpdateFreq <= 1 || $dbType == 'sqlite' ) {
4018                         $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
4019
4020                         return;
4021                 }
4022
4023                 # Not important enough to warrant an error page in case of failure
4024                 $oldignore = $dbw->ignoreErrors( true );
4025
4026                 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
4027
4028                 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 + 1 );
4029                 if ( ( rand() % $checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
4030                         # Most of the time (or on SQL errors), skip row count check
4031                         $dbw->ignoreErrors( $oldignore );
4032
4033                         return;
4034                 }
4035
4036                 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
4037                 $row = $dbw->fetchObject( $res );
4038                 $rown = intval( $row->n );
4039
4040                 if ( $rown >= $wgHitcounterUpdateFreq ) {
4041                         wfProfileIn( 'Article::incViewCount-collect' );
4042                         $old_user_abort = ignore_user_abort( true );
4043
4044                         $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__, false );
4045                         $tabletype = $dbType == 'mysql' ? "ENGINE=HEAP " : '';
4046                         $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
4047                                 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
4048                                 'GROUP BY hc_id', __METHOD__ );
4049                         $dbw->delete( 'hitcounter', '*', __METHOD__ );
4050                         $dbw->unlockTables( __METHOD__ );
4051
4052                         if ( $dbType == 'mysql' ) {
4053                                 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
4054                                         'WHERE page_id = hc_id', __METHOD__ );
4055                         } else {
4056                                 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
4057                                         "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__ );
4058                         }
4059                         $dbw->query( "DROP TABLE $acchitsTable", __METHOD__ );
4060
4061                         ignore_user_abort( $old_user_abort );
4062                         wfProfileOut( 'Article::incViewCount-collect' );
4063                 }
4064
4065                 $dbw->ignoreErrors( $oldignore );
4066         }
4067
4068         /**#@+
4069          * The onArticle*() functions are supposed to be a kind of hooks
4070          * which should be called whenever any of the specified actions
4071          * are done.
4072          *
4073          * This is a good place to put code to clear caches, for instance.
4074          *
4075          * This is called on page move and undelete, as well as edit
4076          *
4077          * @param $title a title object
4078          */
4079         public static function onArticleCreate( $title ) {
4080                 # Update existence markers on article/talk tabs...
4081                 if ( $title->isTalkPage() ) {
4082                         $other = $title->getSubjectPage();
4083                 } else {
4084                         $other = $title->getTalkPage();
4085                 }
4086
4087                 $other->invalidateCache();
4088                 $other->purgeSquid();
4089
4090                 $title->touchLinks();
4091                 $title->purgeSquid();
4092                 $title->deleteTitleProtection();
4093         }
4094
4095         /**
4096          * Clears caches when article is deleted
4097          */
4098         public static function onArticleDelete( $title ) {
4099                 global $wgMessageCache;
4100
4101                 # Update existence markers on article/talk tabs...
4102                 if ( $title->isTalkPage() ) {
4103                         $other = $title->getSubjectPage();
4104                 } else {
4105                         $other = $title->getTalkPage();
4106                 }
4107
4108                 $other->invalidateCache();
4109                 $other->purgeSquid();
4110
4111                 $title->touchLinks();
4112                 $title->purgeSquid();
4113
4114                 # File cache
4115                 HTMLFileCache::clearFileCache( $title );
4116
4117                 # Messages
4118                 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
4119                         $wgMessageCache->replace( $title->getDBkey(), false );
4120                 }
4121
4122                 # Images
4123                 if ( $title->getNamespace() == NS_FILE ) {
4124                         $update = new HTMLCacheUpdate( $title, 'imagelinks' );
4125                         $update->doUpdate();
4126                 }
4127
4128                 # User talk pages
4129                 if ( $title->getNamespace() == NS_USER_TALK ) {
4130                         $user = User::newFromName( $title->getText(), false );
4131                         $user->setNewtalk( false );
4132                 }
4133
4134                 # Image redirects
4135                 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4136         }
4137
4138         /**
4139          * Purge caches on page update etc
4140          *
4141          * @param $title Title object
4142          * @todo:  verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4143          */
4144         public static function onArticleEdit( $title ) {
4145                 global $wgDeferredUpdateList;
4146
4147                 // Invalidate caches of articles which include this page
4148                 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4149
4150                 // Invalidate the caches of all pages which redirect here
4151                 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4152
4153                 # Purge squid for this page only
4154                 $title->purgeSquid();
4155
4156                 # Clear file cache for this page only
4157                 HTMLFileCache::clearFileCache( $title );
4158         }
4159
4160         /**#@-*/
4161
4162         /**
4163          * Overriden by ImagePage class, only present here to avoid a fatal error
4164          * Called for ?action=revert
4165          */
4166         public function revert() {
4167                 global $wgOut;
4168                 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4169         }
4170
4171         /**
4172          * Info about this page
4173          * Called for ?action=info when $wgAllowPageInfo is on.
4174          */
4175         public function info() {
4176                 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4177
4178                 if ( !$wgAllowPageInfo ) {
4179                         $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4180                         return;
4181                 }
4182
4183                 $page = $this->mTitle->getSubjectPage();
4184
4185                 $wgOut->setPagetitle( $page->getPrefixedText() );
4186                 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4187                 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4188
4189                 if ( !$this->mTitle->exists() ) {
4190                         $wgOut->addHTML( '<div class="noarticletext">' );
4191                         if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
4192                                 // This doesn't quite make sense; the user is asking for
4193                                 // information about the _page_, not the message... -- RC
4194                                 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
4195                         } else {
4196                                 $msg = $wgUser->isLoggedIn()
4197                                         ? 'noarticletext'
4198                                         : 'noarticletextanon';
4199                                 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
4200                         }
4201
4202                         $wgOut->addHTML( '</div>' );
4203                 } else {
4204                         $dbr = wfGetDB( DB_SLAVE );
4205                         $wl_clause = array(
4206                                 'wl_title'     => $page->getDBkey(),
4207                                 'wl_namespace' => $page->getNamespace() );
4208                         $numwatchers = $dbr->selectField(
4209                                 'watchlist',
4210                                 'COUNT(*)',
4211                                 $wl_clause,
4212                                 __METHOD__,
4213                                 $this->getSelectOptions() );
4214
4215                         $pageInfo = $this->pageCountInfo( $page );
4216                         $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4217
4218
4219                         //FIXME: unescaped messages
4220                         $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4221                         $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4222
4223                         if ( $talkInfo ) {
4224                                 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4225                         }
4226
4227                         $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4228
4229                         if ( $talkInfo ) {
4230                                 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4231                         }
4232
4233                         $wgOut->addHTML( '</ul>' );
4234                 }
4235         }
4236
4237         /**
4238          * Return the total number of edits and number of unique editors
4239          * on a given page. If page does not exist, returns false.
4240          *
4241          * @param $title Title object
4242          * @return mixed array or boolean false
4243          */
4244         public function pageCountInfo( $title ) {
4245                 $id = $title->getArticleId();
4246
4247                 if ( $id == 0 ) {
4248                         return false;
4249                 }
4250
4251                 $dbr = wfGetDB( DB_SLAVE );
4252                 $rev_clause = array( 'rev_page' => $id );
4253                 $edits = $dbr->selectField(
4254                         'revision',
4255                         'COUNT(rev_page)',
4256                         $rev_clause,
4257                         __METHOD__,
4258                         $this->getSelectOptions()
4259                 );
4260                 $authors = $dbr->selectField(
4261                         'revision',
4262                         'COUNT(DISTINCT rev_user_text)',
4263                         $rev_clause,
4264                         __METHOD__,
4265                         $this->getSelectOptions()
4266                 );
4267
4268                 return array( 'edits' => $edits, 'authors' => $authors );
4269         }
4270
4271         /**
4272          * Return a list of templates used by this article.
4273          * Uses the templatelinks table
4274          *
4275          * @return Array of Title objects
4276          */
4277         public function getUsedTemplates() {
4278                 $result = array();
4279                 $id = $this->mTitle->getArticleID();
4280
4281                 if ( $id == 0 ) {
4282                         return array();
4283                 }
4284
4285                 $dbr = wfGetDB( DB_SLAVE );
4286                 $res = $dbr->select( array( 'templatelinks' ),
4287                         array( 'tl_namespace', 'tl_title' ),
4288                         array( 'tl_from' => $id ),
4289                         __METHOD__ );
4290
4291                 if ( $res !== false ) {
4292                         foreach ( $res as $row ) {
4293                                 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
4294                         }
4295                 }
4296
4297                 return $result;
4298         }
4299
4300         /**
4301          * Returns a list of hidden categories this page is a member of.
4302          * Uses the page_props and categorylinks tables.
4303          *
4304          * @return Array of Title objects
4305          */
4306         public function getHiddenCategories() {
4307                 $result = array();
4308                 $id = $this->mTitle->getArticleID();
4309
4310                 if ( $id == 0 ) {
4311                         return array();
4312                 }
4313
4314                 $dbr = wfGetDB( DB_SLAVE );
4315                 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4316                         array( 'cl_to' ),
4317                         array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4318                                 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
4319                         __METHOD__ );
4320
4321                 if ( $res !== false ) {
4322                         foreach ( $res as $row ) {
4323                                 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
4324                         }
4325                 }
4326
4327                 return $result;
4328         }
4329
4330         /**
4331         * Return an applicable autosummary if one exists for the given edit.
4332         * @param $oldtext String: the previous text of the page.
4333         * @param $newtext String: The submitted text of the page.
4334         * @param $flags Bitmask: a bitmask of flags submitted for the edit.
4335         * @return string An appropriate autosummary, or an empty string.
4336         */
4337         public static function getAutosummary( $oldtext, $newtext, $flags ) {
4338                 global $wgContLang;
4339                 
4340                 # Decide what kind of autosummary is needed.
4341
4342                 # Redirect autosummaries
4343                 $ot = Title::newFromRedirect( $oldtext );
4344                 $rt = Title::newFromRedirect( $newtext );
4345
4346                 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
4347                         return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4348                 }
4349
4350                 # New page autosummaries
4351                 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
4352                         # If they're making a new article, give its text, truncated, in the summary.
4353
4354                         $truncatedtext = $wgContLang->truncate(
4355                                 str_replace( "\n", ' ', $newtext ),
4356                                 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4357
4358                         return wfMsgForContent( 'autosumm-new', $truncatedtext );
4359                 }
4360
4361                 # Blanking autosummaries
4362                 if ( $oldtext != '' && $newtext == '' ) {
4363                         return wfMsgForContent( 'autosumm-blank' );
4364                 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4365                         # Removing more than 90% of the article
4366
4367                         $truncatedtext = $wgContLang->truncate(
4368                                 $newtext,
4369                                 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4370
4371                         return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4372                 }
4373
4374                 # If we reach this point, there's no applicable autosummary for our case, so our
4375                 # autosummary is empty.
4376                 return '';
4377         }
4378
4379         /**
4380          * Add the primary page-view wikitext to the output buffer
4381          * Saves the text into the parser cache if possible.
4382          * Updates templatelinks if it is out of date.
4383          *
4384          * @param $text String
4385          * @param $cache Boolean
4386          * @param $parserOptions mixed ParserOptions object, or boolean false
4387          */
4388         public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4389                 global $wgOut;
4390
4391                 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4392                 $wgOut->addParserOutput( $this->mParserOutput );
4393         }
4394
4395         /**
4396          * This does all the heavy lifting for outputWikitext, except it returns the parser
4397          * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4398          * say, embedding thread pages within a discussion system (LiquidThreads)
4399          *
4400          * @param $text string
4401          * @param $cache boolean
4402          * @param $parserOptions parsing options, defaults to false
4403          * @return string containing parsed output
4404          */
4405         public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4406                 global $wgParser, $wgEnableParserCache, $wgUseFileCache;
4407
4408                 if ( !$parserOptions ) {
4409                         $parserOptions = $this->getParserOptions();
4410                 }
4411
4412                 $time = - wfTime();
4413                 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
4414                         $parserOptions, true, true, $this->getRevIdFetched() );
4415                 $time += wfTime();
4416
4417                 # Timing hack
4418                 if ( $time > 3 ) {
4419                         wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4420                                 $this->mTitle->getPrefixedDBkey() ) );
4421                 }
4422
4423                 if ( $wgEnableParserCache && $cache && $this->mParserOutput->isCacheable() ) {
4424                         $parserCache = ParserCache::singleton();
4425                         $parserCache->save( $this->mParserOutput, $this, $parserOptions );
4426                 }
4427
4428                 // Make sure file cache is not used on uncacheable content.
4429                 // Output that has magic words in it can still use the parser cache
4430                 // (if enabled), though it will generally expire sooner.
4431                 if ( !$this->mParserOutput->isCacheable() || $this->mParserOutput->containsOldMagic() ) {
4432                         $wgUseFileCache = false;
4433                 }
4434
4435                 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4436
4437                 return $this->mParserOutput;
4438         }
4439
4440         /**
4441          * Get parser options suitable for rendering the primary article wikitext
4442          * @return mixed ParserOptions object or boolean false
4443          */
4444         public function getParserOptions() {
4445                 global $wgUser;
4446
4447                 if ( !$this->mParserOptions ) {
4448                         $this->mParserOptions = new ParserOptions( $wgUser );
4449                         $this->mParserOptions->setTidy( true );
4450                         $this->mParserOptions->enableLimitReport();
4451                 }
4452
4453                 // Clone to allow modifications of the return value without affecting 
4454                 // the cache
4455                 return clone $this->mParserOptions;
4456         }
4457
4458         /**
4459          * Updates cascading protections
4460          *
4461          * @param $parserOutput mixed ParserOptions object, or boolean false
4462          **/
4463         protected function doCascadeProtectionUpdates( $parserOutput ) {
4464                 if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4465                         return;
4466                 }
4467
4468                 // templatelinks table may have become out of sync,
4469                 // especially if using variable-based transclusions.
4470                 // For paranoia, check if things have changed and if
4471                 // so apply updates to the database. This will ensure
4472                 // that cascaded protections apply as soon as the changes
4473                 // are visible.
4474
4475                 # Get templates from templatelinks
4476                 $id = $this->mTitle->getArticleID();
4477
4478                 $tlTemplates = array();
4479
4480                 $dbr = wfGetDB( DB_SLAVE );
4481                 $res = $dbr->select( array( 'templatelinks' ),
4482                         array( 'tl_namespace', 'tl_title' ),
4483                         array( 'tl_from' => $id ),
4484                         __METHOD__
4485                 );
4486
4487                 foreach ( $res as $row ) {
4488                         $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4489                 }
4490
4491                 # Get templates from parser output.
4492                 $poTemplates = array();
4493                 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4494                         foreach ( $templates as $dbk => $id ) {
4495                                 $poTemplates["$ns:$dbk"] = true;
4496                         }
4497                 }
4498
4499                 # Get the diff
4500                 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4501
4502                 if ( count( $templates_diff ) > 0 ) {
4503                         # Whee, link updates time.
4504                         $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4505                         $u->doUpdate();
4506                 }
4507         }
4508
4509         /**
4510          * Update all the appropriate counts in the category table, given that
4511          * we've added the categories $added and deleted the categories $deleted.
4512          *
4513          * @param $added array   The names of categories that were added
4514          * @param $deleted array The names of categories that were deleted
4515          */
4516         public function updateCategoryCounts( $added, $deleted ) {
4517                 $ns = $this->mTitle->getNamespace();
4518                 $dbw = wfGetDB( DB_MASTER );
4519
4520                 # First make sure the rows exist.  If one of the "deleted" ones didn't
4521                 # exist, we might legitimately not create it, but it's simpler to just
4522                 # create it and then give it a negative value, since the value is bogus
4523                 # anyway.
4524                 #
4525                 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4526                 $insertCats = array_merge( $added, $deleted );
4527                 if ( !$insertCats ) {
4528                         # Okay, nothing to do
4529                         return;
4530                 }
4531
4532                 $insertRows = array();
4533
4534                 foreach ( $insertCats as $cat ) {
4535                         $insertRows[] = array(
4536                                 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4537                                 'cat_title' => $cat
4538                         );
4539                 }
4540                 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4541
4542                 $addFields    = array( 'cat_pages = cat_pages + 1' );
4543                 $removeFields = array( 'cat_pages = cat_pages - 1' );
4544
4545                 if ( $ns == NS_CATEGORY ) {
4546                         $addFields[]    = 'cat_subcats = cat_subcats + 1';
4547                         $removeFields[] = 'cat_subcats = cat_subcats - 1';
4548                 } elseif ( $ns == NS_FILE ) {
4549                         $addFields[]    = 'cat_files = cat_files + 1';
4550                         $removeFields[] = 'cat_files = cat_files - 1';
4551                 }
4552
4553                 if ( $added ) {
4554                         $dbw->update(
4555                                 'category',
4556                                 $addFields,
4557                                 array( 'cat_title' => $added ),
4558                                 __METHOD__
4559                         );
4560                 }
4561
4562                 if ( $deleted ) {
4563                         $dbw->update(
4564                                 'category',
4565                                 $removeFields,
4566                                 array( 'cat_title' => $deleted ),
4567                                 __METHOD__
4568                         );
4569                 }
4570         }
4571
4572         /**
4573          * Lightweight method to get the parser output for a page, checking the parser cache
4574          * and so on. Doesn't consider most of the stuff that Article::view is forced to
4575          * consider, so it's not appropriate to use there.
4576          *
4577          * @since 1.16 (r52326) for LiquidThreads
4578          * 
4579          * @param $oldid mixed integer Revision ID or null
4580          */
4581         public function getParserOutput( $oldid = null ) {
4582                 global $wgEnableParserCache, $wgUser;
4583
4584                 // Should the parser cache be used?
4585                 $useParserCache = $wgEnableParserCache &&
4586                         $wgUser->getStubThreshold() == 0 &&
4587                         $this->exists() &&
4588                         $oldid === null;
4589
4590                 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4591
4592                 if ( $wgUser->getStubThreshold() ) {
4593                         wfIncrStats( 'pcache_miss_stub' );
4594                 }
4595
4596                 $parserOutput = false;
4597                 if ( $useParserCache ) {
4598                         $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4599                 }
4600
4601                 if ( $parserOutput === false ) {
4602                         // Cache miss; parse and output it.
4603                         $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4604
4605                         return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4606                 } else {
4607                         return $parserOutput;
4608                 }
4609         }
4610
4611         // Deprecated methods
4612         /**
4613          * Get the database which should be used for reads
4614          *
4615          * @return Database
4616          * @deprecated - just call wfGetDB( DB_MASTER ) instead
4617          */
4618         function getDB() {
4619                 wfDeprecated( __METHOD__ );
4620                 return wfGetDB( DB_MASTER );
4621         }
4622
4623 }
4624
4625 class PoolWorkArticleView extends PoolCounterWork {
4626         private $mArticle;
4627         
4628         function __construct( $article, $key, $useParserCache, $parserOptions ) {
4629                 parent::__construct( 'ArticleView', $key );
4630                 $this->mArticle = $article;
4631                 $this->cacheable = $useParserCache;
4632                 $this->parserOptions = $parserOptions;
4633         }
4634         
4635         function doWork() {
4636                 return $this->mArticle->doViewParse();
4637         }
4638         
4639         function getCachedWork() {
4640                 global $wgOut;
4641                 
4642                 $parserCache = ParserCache::singleton();
4643                 $this->mArticle->mParserOutput = $parserCache->get( $this->mArticle, $this->parserOptions );
4644
4645                 if ( $this->mArticle->mParserOutput !== false ) {
4646                         wfDebug( __METHOD__ . ": showing contents parsed by someone else\n" );
4647                         $wgOut->addParserOutput( $this->mArticle->mParserOutput );
4648                         # Ensure that UI elements requiring revision ID have
4649                         # the correct version information.
4650                         $wgOut->setRevisionId( $this->mArticle->getLatest() );
4651                         return true;
4652                 }
4653                 return false;
4654         }
4655         
4656         function fallback() {
4657                 return $this->mArticle->tryDirtyCache();
4658         }
4659         
4660         function error( $status ) {
4661                 global $wgOut;
4662
4663                 $wgOut->clearHTML(); // for release() errors
4664                 $wgOut->enableClientCache( false );
4665                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
4666                 
4667                 $errortext = $status->getWikiText( false, 'view-pool-error' );
4668                 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
4669                 
4670                 return false;
4671         }
4672 }