]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/Article.php
MediaWiki 1.14.0
[autoinstallsdev/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  */
15 class Article {
16         /**@{{
17          * @private
18          */
19         var $mComment = '';               //!<
20         var $mContent;                    //!<
21         var $mContentLoaded = false;      //!<
22         var $mCounter = -1;               //!< Not loaded
23         var $mCurID = -1;                 //!< Not loaded
24         var $mDataLoaded = false;         //!<
25         var $mForUpdate = false;          //!<
26         var $mGoodAdjustment = 0;         //!<
27         var $mIsRedirect = false;         //!<
28         var $mLatest = false;             //!<
29         var $mMinorEdit;                  //!<
30         var $mOldId;                      //!<
31         var $mPreparedEdit = false;       //!< Title object if set
32         var $mRedirectedFrom = null;      //!< Title object if set
33         var $mRedirectTarget = null;      //!< Title object if set
34         var $mRedirectUrl = false;        //!<
35         var $mRevIdFetched = 0;           //!<
36         var $mRevision;                   //!<
37         var $mTimestamp = '';             //!<
38         var $mTitle;                      //!<
39         var $mTotalAdjustment = 0;        //!<
40         var $mTouched = '19700101000000'; //!<
41         var $mUser = -1;                  //!< Not loaded
42         var $mUserText = '';              //!<
43         /**@}}*/
44
45         /**
46          * Constructor and clear the article
47          * @param $title Reference to a Title object.
48          * @param $oldId Integer revision ID, null to fetch from request, zero for current
49          */
50         public function __construct( Title $title, $oldId = null ) {
51                 $this->mTitle =& $title;
52                 $this->mOldId = $oldId;
53         }
54
55         /**
56          * Constructor from an article article
57          * @param $id The article ID to load
58          */
59         public static function newFromID( $id ) {
60                 $t = Title::newFromID( $id );
61                 return $t == null ? null : new Article( $t );
62         }
63
64         /**
65          * Tell the page view functions that this view was redirected
66          * from another page on the wiki.
67          * @param $from Title object.
68          */
69         public function setRedirectedFrom( $from ) {
70                 $this->mRedirectedFrom = $from;
71         }
72
73         /**
74          * If this page is a redirect, get its target
75          *
76          * The target will be fetched from the redirect table if possible.
77          * If this page doesn't have an entry there, call insertRedirect()
78          * @return mixed Title object, or null if this page is not a redirect
79          */
80         public function getRedirectTarget() {
81                 if( !$this->mTitle || !$this->mTitle->isRedirect() )
82                         return null;
83                 if( !is_null($this->mRedirectTarget) )
84                         return $this->mRedirectTarget;
85                 # Query the redirect table
86                 $dbr = wfGetDB( DB_SLAVE );
87                 $res = $dbr->select( 'redirect',
88                         array('rd_namespace', 'rd_title'),
89                         array('rd_from' => $this->getID()),
90                         __METHOD__
91                 );
92                 if( $row = $dbr->fetchObject($res) ) {
93                         return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
94                 }
95                 # This page doesn't have an entry in the redirect table
96                 return $this->mRedirectTarget = $this->insertRedirect();
97         }
98
99         /**
100          * Insert an entry for this page into the redirect table.
101          *
102          * Don't call this function directly unless you know what you're doing.
103          * @return Title object
104          */
105         public function insertRedirect() {
106                 $retval = Title::newFromRedirect( $this->getContent() );
107                 if( !$retval ) {
108                         return null;
109                 }
110                 $dbw = wfGetDB( DB_MASTER );
111                 $dbw->replace( 'redirect', array('rd_from'), 
112                         array(
113                                 'rd_from' => $this->getID(),
114                                 'rd_namespace' => $retval->getNamespace(),
115                                 'rd_title' => $retval->getDBKey()
116                         ),
117                         __METHOD__
118                 );
119                 return $retval;
120         }
121
122         /**
123          * Get the Title object this page redirects to
124          *
125          * @return mixed false, Title of in-wiki target, or string with URL
126          */
127         public function followRedirect() {
128                 $text = $this->getContent();
129                 return $this->followRedirectText( $text );
130         }
131
132         /**
133          * Get the Title object this text redirects to
134          *
135          * @return mixed false, Title of in-wiki target, or string with URL
136          */
137         public function followRedirectText( $text ) {
138                 $rt = Title::newFromRedirect( $text );
139                 # process if title object is valid and not special:userlogout
140                 if( $rt ) {
141                         if( $rt->getInterwiki() != '' ) {
142                                 if( $rt->isLocal() ) {
143                                         // Offsite wikis need an HTTP redirect.
144                                         //
145                                         // This can be hard to reverse and may produce loops,
146                                         // so they may be disabled in the site configuration.
147                                         $source = $this->mTitle->getFullURL( 'redirect=no' );
148                                         return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
149                                 }
150                         } else {
151                                 if( $rt->getNamespace() == NS_SPECIAL ) {
152                                         // Gotta handle redirects to special pages differently:
153                                         // Fill the HTTP response "Location" header and ignore
154                                         // the rest of the page we're on.
155                                         //
156                                         // This can be hard to reverse, so they may be disabled.
157                                         if( $rt->isSpecial( 'Userlogout' ) ) {
158                                                 // rolleyes
159                                         } else {
160                                                 return $rt->getFullURL();
161                                         }
162                                 }
163                                 return $rt;
164                         }
165                 }
166                 // No or invalid redirect
167                 return false;
168         }
169
170         /**
171          * get the title object of the article
172          */
173         public function getTitle() {
174                 return $this->mTitle;
175         }
176
177         /**
178          * Clear the object
179          * @private
180          */
181         public function clear() {
182                 $this->mDataLoaded    = false;
183                 $this->mContentLoaded = false;
184
185                 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
186                 $this->mRedirectedFrom = null; # Title object if set
187                 $this->mRedirectTarget = null; # Title object if set
188                 $this->mUserText =
189                 $this->mTimestamp = $this->mComment = '';
190                 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
191                 $this->mTouched = '19700101000000';
192                 $this->mForUpdate = false;
193                 $this->mIsRedirect = false;
194                 $this->mRevIdFetched = 0;
195                 $this->mRedirectUrl = false;
196                 $this->mLatest = false;
197                 $this->mPreparedEdit = false;
198         }
199
200         /**
201          * Note that getContent/loadContent do not follow redirects anymore.
202          * If you need to fetch redirectable content easily, try
203          * the shortcut in Article::followContent()
204          *
205          * @return Return the text of this revision
206         */
207         public function getContent() {
208                 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
209                 wfProfileIn( __METHOD__ );
210                 if( $this->getID() === 0 ) {
211                         # If this is a MediaWiki:x message, then load the messages
212                         # and return the message value for x.
213                         if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
214                                 # If this is a system message, get the default text.
215                                 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
216                                 $wgMessageCache->loadAllMessages( $lang );
217                                 $text = wfMsgGetKey( $message, false, $lang, false );
218                                 if( wfEmptyMsg( $message, $text ) )
219                                         $text = '';
220                         } else {
221                                 $text = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
222                         }
223                         wfProfileOut( __METHOD__ );
224                         return $text;
225                 } else {
226                         $this->loadContent();
227                         wfProfileOut( __METHOD__ );
228                         return $this->mContent;
229                 }
230         }
231
232         /**
233          * This function returns the text of a section, specified by a number ($section).
234          * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
235          * the first section before any such heading (section 0).
236          *
237          * If a section contains subsections, these are also returned.
238          *
239          * @param $text String: text to look in
240          * @param $section Integer: section number
241          * @return string text of the requested section
242          * @deprecated
243          */
244         public function getSection( $text, $section ) {
245                 global $wgParser;
246                 return $wgParser->getSection( $text, $section );
247         }
248
249         /**
250          * @return int The oldid of the article that is to be shown, 0 for the
251          *             current revision
252          */
253         public function getOldID() {
254                 if( is_null( $this->mOldId ) ) {
255                         $this->mOldId = $this->getOldIDFromRequest();
256                 }
257                 return $this->mOldId;
258         }
259
260         /**
261          * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
262          *
263          * @return int The old id for the request
264          */
265         public function getOldIDFromRequest() {
266                 global $wgRequest;
267                 $this->mRedirectUrl = false;
268                 $oldid = $wgRequest->getVal( 'oldid' );
269                 if( isset( $oldid ) ) {
270                         $oldid = intval( $oldid );
271                         if( $wgRequest->getVal( 'direction' ) == 'next' ) {
272                                 $nextid = $this->mTitle->getNextRevisionID( $oldid );
273                                 if( $nextid  ) {
274                                         $oldid = $nextid;
275                                 } else {
276                                         $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
277                                 }
278                         } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
279                                 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
280                                 if( $previd ) {
281                                         $oldid = $previd;
282                                 }
283                         }
284                 }
285                 if( !$oldid ) {
286                         $oldid = 0;
287                 }
288                 return $oldid;
289         }
290
291         /**
292          * Load the revision (including text) into this object
293          */
294         function loadContent() {
295                 if( $this->mContentLoaded ) return;
296                 wfProfileIn( __METHOD__ );
297                 # Query variables :P
298                 $oldid = $this->getOldID();
299                 # Pre-fill content with error message so that if something
300                 # fails we'll have something telling us what we intended.
301                 $this->mOldId = $oldid;
302                 $this->fetchContent( $oldid );
303                 wfProfileOut( __METHOD__ );
304         }
305
306
307         /**
308          * Fetch a page record with the given conditions
309          * @param $dbr Database object
310          * @param $conditions Array
311          */
312         protected function pageData( $dbr, $conditions ) {
313                 $fields = array(
314                                 'page_id',
315                                 'page_namespace',
316                                 'page_title',
317                                 'page_restrictions',
318                                 'page_counter',
319                                 'page_is_redirect',
320                                 'page_is_new',
321                                 'page_random',
322                                 'page_touched',
323                                 'page_latest',
324                                 'page_len',
325                 );
326                 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
327                 $row = $dbr->selectRow(
328                         'page',
329                         $fields,
330                         $conditions,
331                         __METHOD__
332                 );
333                 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
334                 return $row ;
335         }
336
337         /**
338          * @param $dbr Database object
339          * @param $title Title object
340          */
341         public function pageDataFromTitle( $dbr, $title ) {
342                 return $this->pageData( $dbr, array(
343                         'page_namespace' => $title->getNamespace(),
344                         'page_title'     => $title->getDBkey() ) );
345         }
346
347         /**
348          * @param $dbr Database
349          * @param $id Integer
350          */
351         protected function pageDataFromId( $dbr, $id ) {
352                 return $this->pageData( $dbr, array( 'page_id' => $id ) );
353         }
354
355         /**
356          * Set the general counter, title etc data loaded from
357          * some source.
358          *
359          * @param $data Database row object or "fromdb"
360          */
361         public function loadPageData( $data = 'fromdb' ) {
362                 if( $data === 'fromdb' ) {
363                         $dbr = wfGetDB( DB_MASTER );
364                         $data = $this->pageDataFromId( $dbr, $this->getId() );
365                 }
366
367                 $lc = LinkCache::singleton();
368                 if( $data ) {
369                         $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
370
371                         $this->mTitle->mArticleID = $data->page_id;
372
373                         # Old-fashioned restrictions
374                         $this->mTitle->loadRestrictions( $data->page_restrictions );
375
376                         $this->mCounter     = $data->page_counter;
377                         $this->mTouched     = wfTimestamp( TS_MW, $data->page_touched );
378                         $this->mIsRedirect  = $data->page_is_redirect;
379                         $this->mLatest      = $data->page_latest;
380                 } else {
381                         if( is_object( $this->mTitle ) ) {
382                                 $lc->addBadLinkObj( $this->mTitle );
383                         }
384                         $this->mTitle->mArticleID = 0;
385                 }
386
387                 $this->mDataLoaded  = true;
388         }
389
390         /**
391          * Get text of an article from database
392          * Does *NOT* follow redirects.
393          * @param $oldid Int: 0 for whatever the latest revision is
394          * @return string
395          */
396         function fetchContent( $oldid = 0 ) {
397                 if( $this->mContentLoaded ) {
398                         return $this->mContent;
399                 }
400
401                 $dbr = wfGetDB( DB_MASTER );
402
403                 # Pre-fill content with error message so that if something
404                 # fails we'll have something telling us what we intended.
405                 $t = $this->mTitle->getPrefixedText();
406                 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
407                 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
408
409                 if( $oldid ) {
410                         $revision = Revision::newFromId( $oldid );
411                         if( is_null( $revision ) ) {
412                                 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
413                                 return false;
414                         }
415                         $data = $this->pageDataFromId( $dbr, $revision->getPage() );
416                         if( !$data ) {
417                                 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
418                                 return false;
419                         }
420                         $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
421                         $this->loadPageData( $data );
422                 } else {
423                         if( !$this->mDataLoaded ) {
424                                 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
425                                 if( !$data ) {
426                                         wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
427                                         return false;
428                                 }
429                                 $this->loadPageData( $data );
430                         }
431                         $revision = Revision::newFromId( $this->mLatest );
432                         if( is_null( $revision ) ) {
433                                 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
434                                 return false;
435                         }
436                 }
437
438                 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
439                 // We should instead work with the Revision object when we need it...
440                 $this->mContent   = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
441
442                 $this->mUser      = $revision->getUser();
443                 $this->mUserText  = $revision->getUserText();
444                 $this->mComment   = $revision->getComment();
445                 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
446
447                 $this->mRevIdFetched = $revision->getId();
448                 $this->mContentLoaded = true;
449                 $this->mRevision =& $revision;
450
451                 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
452
453                 return $this->mContent;
454         }
455
456         /**
457          * Read/write accessor to select FOR UPDATE
458          *
459          * @param $x Mixed: FIXME
460          */
461         public function forUpdate( $x = NULL ) {
462                 return wfSetVar( $this->mForUpdate, $x );
463         }
464
465         /**
466          * Get the database which should be used for reads
467          *
468          * @return Database
469          * @deprecated - just call wfGetDB( DB_MASTER ) instead
470          */
471         function getDB() {
472                 wfDeprecated( __METHOD__ );
473                 return wfGetDB( DB_MASTER );
474         }
475
476         /**
477          * Get options for all SELECT statements
478          *
479          * @param $options Array: an optional options array which'll be appended to
480          *                       the default
481          * @return Array: options
482          */
483         protected function getSelectOptions( $options = '' ) {
484                 if( $this->mForUpdate ) {
485                         if( is_array( $options ) ) {
486                                 $options[] = 'FOR UPDATE';
487                         } else {
488                                 $options = 'FOR UPDATE';
489                         }
490                 }
491                 return $options;
492         }
493
494         /**
495          * @return int Page ID
496          */
497         public function getID() {
498                 if( $this->mTitle ) {
499                         return $this->mTitle->getArticleID();
500                 } else {
501                         return 0;
502                 }
503         }
504
505         /**
506          * @return bool Whether or not the page exists in the database
507          */
508         public function exists() {
509                 return $this->getId() > 0;
510         }
511         
512         /**
513          * Check if this page is something we're going to be showing
514          * some sort of sensible content for. If we return false, page
515          * views (plain action=view) will return an HTTP 404 response,
516          * so spiders and robots can know they're following a bad link.
517          *
518          * @return bool
519          */
520         public function hasViewableContent() {
521                 return $this->exists() || $this->mTitle->isAlwaysKnown();
522         }
523
524         /**
525          * @return int The view count for the page
526          */
527         public function getCount() {
528                 if( -1 == $this->mCounter ) {
529                         $id = $this->getID();
530                         if( $id == 0 ) {
531                                 $this->mCounter = 0;
532                         } else {
533                                 $dbr = wfGetDB( DB_SLAVE );
534                                 $this->mCounter = $dbr->selectField( 'page', 
535                                         'page_counter', 
536                                         array( 'page_id' => $id ), 
537                                         __METHOD__, 
538                                         $this->getSelectOptions()
539                                 );
540                         }
541                 }
542                 return $this->mCounter;
543         }
544
545         /**
546          * Determine whether a page  would be suitable for being counted as an
547          * article in the site_stats table based on the title & its content
548          *
549          * @param $text String: text to analyze
550          * @return bool
551          */
552         public function isCountable( $text ) {
553                 global $wgUseCommaCount;
554
555                 $token = $wgUseCommaCount ? ',' : '[[';
556                 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
557         }
558
559         /**
560          * Tests if the article text represents a redirect
561          *
562          * @param $text String: FIXME
563          * @return bool
564          */
565         public function isRedirect( $text = false ) {
566                 if( $text === false ) {
567                         if( $this->mDataLoaded ) {
568                                 return $this->mIsRedirect;
569                         }
570                         // Apparently loadPageData was never called
571                         $this->loadContent();
572                         $titleObj = Title::newFromRedirect( $this->fetchContent() );
573                 } else {
574                         $titleObj = Title::newFromRedirect( $text );
575                 }
576                 return $titleObj !== NULL;
577         }
578
579         /**
580          * Returns true if the currently-referenced revision is the current edit
581          * to this page (and it exists).
582          * @return bool
583          */
584         public function isCurrent() {
585                 # If no oldid, this is the current version.
586                 if( $this->getOldID() == 0 ) {
587                         return true;
588                 }
589                 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
590         }
591
592         /**
593          * Loads everything except the text
594          * This isn't necessary for all uses, so it's only done if needed.
595          */
596         protected function loadLastEdit() {
597                 if( -1 != $this->mUser )
598                         return;
599
600                 # New or non-existent articles have no user information
601                 $id = $this->getID();
602                 if( 0 == $id ) return;
603
604                 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
605                 if( !is_null( $this->mLastRevision ) ) {
606                         $this->mUser      = $this->mLastRevision->getUser();
607                         $this->mUserText  = $this->mLastRevision->getUserText();
608                         $this->mTimestamp = $this->mLastRevision->getTimestamp();
609                         $this->mComment   = $this->mLastRevision->getComment();
610                         $this->mMinorEdit = $this->mLastRevision->isMinor();
611                         $this->mRevIdFetched = $this->mLastRevision->getId();
612                 }
613         }
614
615         public function getTimestamp() {
616                 // Check if the field has been filled by ParserCache::get()
617                 if( !$this->mTimestamp ) {
618                         $this->loadLastEdit();
619                 }
620                 return wfTimestamp(TS_MW, $this->mTimestamp);
621         }
622
623         public function getUser() {
624                 $this->loadLastEdit();
625                 return $this->mUser;
626         }
627
628         public function getUserText() {
629                 $this->loadLastEdit();
630                 return $this->mUserText;
631         }
632
633         public function getComment() {
634                 $this->loadLastEdit();
635                 return $this->mComment;
636         }
637
638         public function getMinorEdit() {
639                 $this->loadLastEdit();
640                 return $this->mMinorEdit;
641         }
642
643         /* Use this to fetch the rev ID used on page views */
644         public function getRevIdFetched() {
645                 $this->loadLastEdit();
646                 return $this->mRevIdFetched;
647         }
648
649         /**
650          * @param $limit Integer: default 0.
651          * @param $offset Integer: default 0.
652          */
653         public function getContributors($limit = 0, $offset = 0) {
654                 # XXX: this is expensive; cache this info somewhere.
655
656                 $contribs = array();
657                 $dbr = wfGetDB( DB_SLAVE );
658                 $revTable = $dbr->tableName( 'revision' );
659                 $userTable = $dbr->tableName( 'user' );
660                 $user = $this->getUser();
661                 $pageId = $this->getId();
662
663                 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
664                         FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
665                         WHERE rev_page = $pageId
666                         AND rev_user != $user
667                         GROUP BY rev_user, rev_user_text, user_real_name
668                         ORDER BY timestamp DESC";
669
670                 if($limit > 0) { $sql .= ' LIMIT '.$limit; }
671                 if($offset > 0) { $sql .= ' OFFSET '.$offset; }
672
673                 $sql .= ' '. $this->getSelectOptions();
674
675                 $res = $dbr->query($sql, __METHOD__ );
676
677                 return new UserArrayFromResult( $res );
678         }
679
680         /**
681          * This is the default action of the script: just view the page of
682          * the given title.
683         */
684         public function view() {
685                 global $wgUser, $wgOut, $wgRequest, $wgContLang;
686                 global $wgEnableParserCache, $wgStylePath, $wgParser;
687                 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
688                 global $wgDefaultRobotPolicy;
689
690                 wfProfileIn( __METHOD__ );
691
692                 # Get variables from query string
693                 $oldid = $this->getOldID();
694
695                 # Try file cache
696                 if( $oldid === 0 && $this->checkTouched() ) {
697                         global $wgUseETag;
698                         if( $wgUseETag ) {
699                                 $parserCache = ParserCache::singleton();
700                                 $wgOut->setETag( $parserCache->getETag($this,$wgUser) );
701                         }
702                         if( $wgOut->checkLastModified( $this->getTouched() ) ) {
703                                 wfProfileOut( __METHOD__ );
704                                 return;
705                         } else if( $this->tryFileCache() ) {
706                                 # tell wgOut that output is taken care of
707                                 $wgOut->disable();
708                                 $this->viewUpdates();
709                                 wfProfileOut( __METHOD__ );
710                                 return;
711                         }
712                 }
713
714                 $ns = $this->mTitle->getNamespace(); # shortcut
715                 $sk = $wgUser->getSkin();
716
717                 # getOldID may want us to redirect somewhere else
718                 if( $this->mRedirectUrl ) {
719                         $wgOut->redirect( $this->mRedirectUrl );
720                         wfProfileOut( __METHOD__ );
721                         return;
722                 }
723
724                 $diff = $wgRequest->getVal( 'diff' );
725                 $rcid = $wgRequest->getVal( 'rcid' );
726                 $rdfrom = $wgRequest->getVal( 'rdfrom' );
727                 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
728                 $purge = $wgRequest->getVal( 'action' ) == 'purge';
729                 $return404 = false;
730
731                 $wgOut->setArticleFlag( true );
732
733                 # Discourage indexing of printable versions, but encourage following
734                 if( $wgOut->isPrintable() ) {
735                         $policy = 'noindex,follow';
736                 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
737                         $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
738                 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
739                         # Honour customised robot policies for this namespace
740                         $policy = $wgNamespaceRobotPolicies[$ns];
741                 } else {
742                         $policy = $wgDefaultRobotPolicy;
743                 }
744                 $wgOut->setRobotPolicy( $policy );
745
746                 # If we got diff and oldid in the query, we want to see a
747                 # diff page instead of the article.
748
749                 if( !is_null( $diff ) ) {
750                         $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
751
752                         $diff = $wgRequest->getVal( 'diff' );
753                         $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
754                         $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff);
755                         // DifferenceEngine directly fetched the revision:
756                         $this->mRevIdFetched = $de->mNewid;
757                         $de->showDiffPage( $diffOnly );
758
759                         // Needed to get the page's current revision
760                         $this->loadPageData();
761                         if( $diff == 0 || $diff == $this->mLatest ) {
762                                 # Run view updates for current revision only
763                                 $this->viewUpdates();
764                         }
765                         wfProfileOut( __METHOD__ );
766                         return;
767                 }
768
769                 # Should the parser cache be used?
770                 $pcache = $this->useParserCache( $oldid );
771                 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
772                 if( $wgUser->getOption( 'stubthreshold' ) ) {
773                         wfIncrStats( 'pcache_miss_stub' );
774                 }
775
776                 $wasRedirected = false;
777                 if( isset( $this->mRedirectedFrom ) ) {
778                         // This is an internally redirected page view.
779                         // We'll need a backlink to the source page for navigation.
780                         if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
781                                 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
782                                 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
783                                 $wgOut->setSubtitle( $s );
784
785                                 // Set the fragment if one was specified in the redirect
786                                 if( strval( $this->mTitle->getFragment() ) != '' ) {
787                                         $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
788                                         $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
789                                 }
790                                 $wasRedirected = true;
791                         }
792                 } elseif( !empty( $rdfrom ) ) {
793                         // This is an externally redirected view, from some other wiki.
794                         // If it was reported from a trusted site, supply a backlink.
795                         global $wgRedirectSources;
796                         if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
797                                 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
798                                 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
799                                 $wgOut->setSubtitle( $s );
800                                 $wasRedirected = true;
801                         }
802                 }
803
804                 $outputDone = false;
805                 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
806                 if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
807                         // Ensure that UI elements requiring revision ID have
808                         // the correct version information.
809                         $wgOut->setRevisionId( $this->mLatest );
810                         $outputDone = true;
811                 }
812                 # Fetch content and check for errors
813                 if( !$outputDone ) {
814                         # If the article does not exist and was deleted, show the log
815                         if( $this->getID() == 0 ) {
816                                 $this->showDeletionLog();
817                         }
818                         $text = $this->getContent();
819                         if( $text === false ) {
820                                 # Failed to load, replace text with error message
821                                 $t = $this->mTitle->getPrefixedText();
822                                 if( $oldid ) {
823                                         $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
824                                         $text = wfMsg( 'missing-article', $t, $d );
825                                 } else {
826                                         $text = wfMsg( 'noarticletext' );
827                                 }
828                         }
829                         
830                         # Non-existent pages
831                         if( $this->getID() === 0 ) {
832                                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
833                                 $text = "<div class='noarticletext'>\n$text\n</div>";
834                                 if( !$this->hasViewableContent() ) {
835                                         // If there's no backing content, send a 404 Not Found
836                                         // for better machine handling of broken links.
837                                         $return404 = true;
838                                 }
839                         } 
840
841                         if( $return404 ) {
842                                 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
843                         }
844
845                         # Another whitelist check in case oldid is altering the title
846                         if( !$this->mTitle->userCanRead() ) {
847                                 $wgOut->loginToUse();
848                                 $wgOut->output();
849                                 $wgOut->disable();
850                                 wfProfileOut( __METHOD__ );
851                                 return;
852                         }
853                         
854                         # For ?curid=x urls, disallow indexing
855                         if( $wgRequest->getInt('curid') )
856                                 $wgOut->setRobotPolicy( 'noindex,follow' );
857
858                         # We're looking at an old revision
859                         if( !empty( $oldid ) ) {
860                                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
861                                 if( is_null( $this->mRevision ) ) {
862                                         // FIXME: This would be a nice place to load the 'no such page' text.
863                                 } else {
864                                         $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
865                                         if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
866                                                 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
867                                                         $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
868                                                         $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
869                                                         wfProfileOut( __METHOD__ );
870                                                         return;
871                                                 } else {
872                                                         $wgOut->addWikiMsg( 'rev-deleted-text-view' );
873                                                         // and we are allowed to see...
874                                                 }
875                                         }
876                                 }
877                         }
878
879                         $wgOut->setRevisionId( $this->getRevIdFetched() );
880
881                          // Pages containing custom CSS or JavaScript get special treatment
882                         if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
883                                 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
884                                 // Give hooks a chance to customise the output
885                                 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
886                                         // Wrap the whole lot in a <pre> and don't parse
887                                         $m = array();
888                                         preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
889                                         $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
890                                         $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
891                                         $wgOut->addHTML( "\n</pre>\n" );
892                                 }
893                         } else if( $rt = Title::newFromRedirect( $text ) ) {
894                                 # Don't append the subtitle if this was an old revision
895                                 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
896                                 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
897                                 $wgOut->addParserOutputNoText( $parseout );
898                         } else if( $pcache ) {
899                                 # Display content and save to parser cache
900                                 $this->outputWikiText( $text );
901                         } else {
902                                 # Display content, don't attempt to save to parser cache
903                                 # Don't show section-edit links on old revisions... this way lies madness.
904                                 if( !$this->isCurrent() ) {
905                                         $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
906                                 }
907                                 # Display content and don't save to parser cache
908                                 # With timing hack -- TS 2006-07-26
909                                 $time = -wfTime();
910                                 $this->outputWikiText( $text, false );
911                                 $time += wfTime();
912
913                                 # Timing hack
914                                 if( $time > 3 ) {
915                                         wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
916                                                 $this->mTitle->getPrefixedDBkey()));
917                                 }
918
919                                 if( !$this->isCurrent() ) {
920                                         $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
921                                 }
922                         }
923                 }
924                 /* title may have been set from the cache */
925                 $t = $wgOut->getPageTitle();
926                 if( empty( $t ) ) {
927                         $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
928
929                         # For the main page, overwrite the <title> element with the con-
930                         # tents of 'pagetitle-view-mainpage' instead of the default (if
931                         # that's not empty).
932                         if( $this->mTitle->equals( Title::newMainPage() ) &&
933                         wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
934                                 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
935                         }
936                 }
937
938                 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
939                 if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
940                         $wgOut->addWikiMsg('anontalkpagetext');
941                 }
942
943                 # If we have been passed an &rcid= parameter, we want to give the user a
944                 # chance to mark this new article as patrolled.
945                 if( !empty($rcid) && $this->mTitle->exists() && $this->mTitle->userCan('patrol') ) {
946                         $wgOut->addHTML(
947                                 "<div class='patrollink'>" .
948                                         wfMsgHtml( 'markaspatrolledlink',
949                                         $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
950                                                 "action=markpatrolled&rcid=$rcid" )
951                                         ) .
952                                 '</div>'
953                          );
954                 }
955
956                 # Trackbacks
957                 if( $wgUseTrackbacks ) {
958                         $this->addTrackbacks();
959                 }
960
961                 $this->viewUpdates();
962                 wfProfileOut( __METHOD__ );
963         }
964         
965         protected function showDeletionLog() {
966                 global $wgUser, $wgOut;
967                 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
968                 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
969                 if( $pager->getNumRows() > 0 ) {
970                         $pager->mLimit = 10;
971                         $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
972                         $wgOut->addWikiMsg( 'deleted-notice' );
973                         $wgOut->addHTML(
974                                 $loglist->beginLogEventsList() .
975                                 $pager->getBody() .
976                                 $loglist->endLogEventsList()
977                         );
978                         if( $pager->getNumRows() > 10 ) {
979                                 $wgOut->addHTML( $wgUser->getSkin()->link(
980                                         SpecialPage::getTitleFor( 'Log' ),
981                                         wfMsgHtml( 'deletelog-fulllog' ),
982                                         array(),
983                                         array( 'type' => 'delete', 'page' => $this->mTitle->getPrefixedText() ) 
984                                 ) );
985                         }
986                         $wgOut->addHTML( '</div>' );
987                 }
988         }
989
990         /*
991         * Should the parser cache be used?
992         */
993         protected function useParserCache( $oldid ) {
994                 global $wgUser, $wgEnableParserCache;
995
996                 return $wgEnableParserCache
997                         && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
998                         && $this->exists()
999                         && empty( $oldid )
1000                         && !$this->mTitle->isCssOrJsPage()
1001                         && !$this->mTitle->isCssJsSubpage();
1002         }
1003
1004         /**
1005          * View redirect
1006          * @param $target Title object of destination to redirect
1007          * @param $appendSubtitle Boolean [optional]
1008          * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1009          */
1010         public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1011                 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1012                 # Display redirect
1013                 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1014                 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
1015
1016                 if( $appendSubtitle ) {
1017                         $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1018                 }
1019                 $sk = $wgUser->getSkin();
1020                 if( $forceKnown ) {
1021                         $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1022                 } else {
1023                         $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
1024                 }
1025                 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1026                         '<span class="redirectText">'.$link.'</span>';
1027
1028         }
1029
1030         public function addTrackbacks() {
1031                 global $wgOut, $wgUser;
1032                 $dbr = wfGetDB( DB_SLAVE );
1033                 $tbs = $dbr->select( 'trackbacks',
1034                         array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1035                         array('tb_page' => $this->getID() )
1036                 );
1037                 if( !$dbr->numRows($tbs) ) return;
1038
1039                 $tbtext = "";
1040                 while( $o = $dbr->fetchObject($tbs) ) {
1041                         $rmvtxt = "";
1042                         if( $wgUser->isAllowed( 'trackback' ) ) {
1043                                 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
1044                                         $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1045                                 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1046                         }
1047                         $tbtext .= "\n";
1048                         $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1049                                         $o->tb_title,
1050                                         $o->tb_url,
1051                                         $o->tb_ex,
1052                                         $o->tb_name,
1053                                         $rmvtxt);
1054                 }
1055                 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1056                 $this->mTitle->invalidateCache();
1057         }
1058
1059         public function deletetrackback() {
1060                 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1061                 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1062                         $wgOut->addWikiMsg( 'sessionfailure' );
1063                         return;
1064                 }
1065
1066                 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1067                 if( count($permission_errors) ) {
1068                         $wgOut->showPermissionsErrorPage( $permission_errors );
1069                         return;
1070                 }
1071
1072                 $db = wfGetDB( DB_MASTER );
1073                 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1074
1075                 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1076                 $this->mTitle->invalidateCache();
1077         }
1078
1079         public function render() {
1080                 global $wgOut;
1081                 $wgOut->setArticleBodyOnly(true);
1082                 $this->view();
1083         }
1084
1085         /**
1086          * Handle action=purge
1087          */
1088         public function purge() {
1089                 global $wgUser, $wgRequest, $wgOut;
1090                 if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1091                         if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1092                                 $this->doPurge();
1093                                 $this->view();
1094                         }
1095                 } else {
1096                         $action = htmlspecialchars( $wgRequest->getRequestURL() );
1097                         $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1098                         $form = "<form method=\"post\" action=\"$action\">\n" .
1099                                         "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1100                                         "</form>\n";
1101                         $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1102                         $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1103                         $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1104                         $wgOut->setRobotPolicy( 'noindex,nofollow' );
1105                         $wgOut->addHTML( $top . $form . $bottom );
1106                 }
1107         }
1108
1109         /**
1110          * Perform the actions of a page purging
1111          */
1112         public function doPurge() {
1113                 global $wgUseSquid;
1114                 // Invalidate the cache
1115                 $this->mTitle->invalidateCache();
1116
1117                 if( $wgUseSquid ) {
1118                         // Commit the transaction before the purge is sent
1119                         $dbw = wfGetDB( DB_MASTER );
1120                         $dbw->immediateCommit();
1121
1122                         // Send purge
1123                         $update = SquidUpdate::newSimplePurge( $this->mTitle );
1124                         $update->doUpdate();
1125                 }
1126                 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1127                         global $wgMessageCache;
1128                         if( $this->getID() == 0 ) {
1129                                 $text = false;
1130                         } else {
1131                                 $text = $this->getContent();
1132                         }
1133                         $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1134                 }
1135         }
1136
1137         /**
1138          * Insert a new empty page record for this article.
1139          * This *must* be followed up by creating a revision
1140          * and running $this->updateToLatest( $rev_id );
1141          * or else the record will be left in a funky state.
1142          * Best if all done inside a transaction.
1143          *
1144          * @param $dbw Database
1145          * @return int The newly created page_id key, or false if the title already existed
1146          * @private
1147          */
1148         public function insertOn( $dbw ) {
1149                 wfProfileIn( __METHOD__ );
1150
1151                 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1152                 $dbw->insert( 'page', array(
1153                         'page_id'           => $page_id,
1154                         'page_namespace'    => $this->mTitle->getNamespace(),
1155                         'page_title'        => $this->mTitle->getDBkey(),
1156                         'page_counter'      => 0,
1157                         'page_restrictions' => '',
1158                         'page_is_redirect'  => 0, # Will set this shortly...
1159                         'page_is_new'       => 1,
1160                         'page_random'       => wfRandom(),
1161                         'page_touched'      => $dbw->timestamp(),
1162                         'page_latest'       => 0, # Fill this in shortly...
1163                         'page_len'          => 0, # Fill this in shortly...
1164                 ), __METHOD__, 'IGNORE' );
1165
1166                 $affected = $dbw->affectedRows();
1167                 if( $affected ) {
1168                         $newid = $dbw->insertId();
1169                         $this->mTitle->resetArticleId( $newid );
1170                 }
1171                 wfProfileOut( __METHOD__ );
1172                 return $affected ? $newid : false;
1173         }
1174
1175         /**
1176          * Update the page record to point to a newly saved revision.
1177          *
1178          * @param $dbw Database object
1179          * @param $revision Revision: For ID number, and text used to set
1180                             length and redirect status fields
1181          * @param $lastRevision Integer: if given, will not overwrite the page field
1182          *                      when different from the currently set value.
1183          *                      Giving 0 indicates the new page flag should be set
1184          *                      on.
1185          * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1186          *                                                       removing rows in redirect table.
1187          * @return bool true on success, false on failure
1188          * @private
1189          */
1190         public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1191                 wfProfileIn( __METHOD__ );
1192
1193                 $text = $revision->getText();
1194                 $rt = Title::newFromRedirect( $text );
1195
1196                 $conditions = array( 'page_id' => $this->getId() );
1197                 if( !is_null( $lastRevision ) ) {
1198                         # An extra check against threads stepping on each other
1199                         $conditions['page_latest'] = $lastRevision;
1200                 }
1201
1202                 $dbw->update( 'page',
1203                         array( /* SET */
1204                                 'page_latest'      => $revision->getId(),
1205                                 'page_touched'     => $dbw->timestamp(),
1206                                 'page_is_new'      => ($lastRevision === 0) ? 1 : 0,
1207                                 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1208                                 'page_len'         => strlen( $text ),
1209                         ),
1210                         $conditions,
1211                         __METHOD__ );
1212
1213                 $result = $dbw->affectedRows() != 0;
1214                 if( $result ) {
1215                         $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1216                 }
1217
1218                 wfProfileOut( __METHOD__ );
1219                 return $result;
1220         }
1221
1222         /**
1223          * Add row to the redirect table if this is a redirect, remove otherwise.
1224          *
1225          * @param $dbw Database
1226          * @param $redirectTitle a title object pointing to the redirect target,
1227          *                                               or NULL if this is not a redirect
1228          * @param $lastRevIsRedirect If given, will optimize adding and
1229          *                                                       removing rows in redirect table.
1230          * @return bool true on success, false on failure
1231          * @private
1232          */
1233         public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1234                 // Always update redirects (target link might have changed)
1235                 // Update/Insert if we don't know if the last revision was a redirect or not
1236                 // Delete if changing from redirect to non-redirect
1237                 $isRedirect = !is_null($redirectTitle);
1238                 if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1239                         wfProfileIn( __METHOD__ );
1240                         if( $isRedirect ) {
1241                                 // This title is a redirect, Add/Update row in the redirect table
1242                                 $set = array( /* SET */
1243                                         'rd_namespace' => $redirectTitle->getNamespace(),
1244                                         'rd_title'     => $redirectTitle->getDBkey(),
1245                                         'rd_from'      => $this->getId(),
1246                                 );
1247                                 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1248                         } else {
1249                                 // This is not a redirect, remove row from redirect table
1250                                 $where = array( 'rd_from' => $this->getId() );
1251                                 $dbw->delete( 'redirect', $where, __METHOD__);
1252                         }
1253                         if( $this->getTitle()->getNamespace() == NS_FILE ) {
1254                                 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1255                         }
1256                         wfProfileOut( __METHOD__ );
1257                         return ( $dbw->affectedRows() != 0 );
1258                 }
1259                 return true;
1260         }
1261
1262         /**
1263          * If the given revision is newer than the currently set page_latest,
1264          * update the page record. Otherwise, do nothing.
1265          *
1266          * @param $dbw Database object
1267          * @param $revision Revision object
1268          */
1269         public function updateIfNewerOn( &$dbw, $revision ) {
1270                 wfProfileIn( __METHOD__ );
1271                 $row = $dbw->selectRow(
1272                         array( 'revision', 'page' ),
1273                         array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1274                         array(
1275                                 'page_id' => $this->getId(),
1276                                 'page_latest=rev_id' ),
1277                         __METHOD__ );
1278                 if( $row ) {
1279                         if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1280                                 wfProfileOut( __METHOD__ );
1281                                 return false;
1282                         }
1283                         $prev = $row->rev_id;
1284                         $lastRevIsRedirect = (bool)$row->page_is_redirect;
1285                 } else {
1286                         # No or missing previous revision; mark the page as new
1287                         $prev = 0;
1288                         $lastRevIsRedirect = null;
1289                 }
1290                 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1291                 wfProfileOut( __METHOD__ );
1292                 return $ret;
1293         }
1294
1295         /**
1296          * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1297          * @return string Complete article text, or null if error
1298          */
1299         public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1300                 wfProfileIn( __METHOD__ );
1301                 if( strval( $section ) == '' ) {
1302                         // Whole-page edit; let the whole text through
1303                 } else {
1304                         if( is_null($edittime) ) {
1305                                 $rev = Revision::newFromTitle( $this->mTitle );
1306                         } else {
1307                                 $dbw = wfGetDB( DB_MASTER );
1308                                 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1309                         }
1310                         if( !$rev ) {
1311                                 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1312                                         $this->getId() . "; section: $section; edittime: $edittime)\n" );
1313                                 return null;
1314                         }
1315                         $oldtext = $rev->getText();
1316
1317                         if( $section == 'new' ) {
1318                                 # Inserting a new section
1319                                 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1320                                 $text = strlen( trim( $oldtext ) ) > 0
1321                                                 ? "{$oldtext}\n\n{$subject}{$text}"
1322                                                 : "{$subject}{$text}";
1323                         } else {
1324                                 # Replacing an existing section; roll out the big guns
1325                                 global $wgParser;
1326                                 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1327                         }
1328                 }
1329                 wfProfileOut( __METHOD__ );
1330                 return $text;
1331         }
1332
1333         /**
1334          * @deprecated use Article::doEdit()
1335          */
1336         function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1337                 wfDeprecated( __METHOD__ );
1338                 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1339                         ( $isminor ? EDIT_MINOR : 0 ) |
1340                         ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1341                         ( $bot ? EDIT_FORCE_BOT : 0 );
1342
1343                 # If this is a comment, add the summary as headline
1344                 if( $comment && $summary != "" ) {
1345                         $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1346                 }
1347
1348                 $this->doEdit( $text, $summary, $flags );
1349
1350                 $dbw = wfGetDB( DB_MASTER );
1351                 if($watchthis) {
1352                         if(!$this->mTitle->userIsWatching()) {
1353                                 $dbw->begin();
1354                                 $this->doWatch();
1355                                 $dbw->commit();
1356                         }
1357                 } else {
1358                         if( $this->mTitle->userIsWatching() ) {
1359                                 $dbw->begin();
1360                                 $this->doUnwatch();
1361                                 $dbw->commit();
1362                         }
1363                 }
1364                 $this->doRedirect( $this->isRedirect( $text ) );
1365         }
1366
1367         /**
1368          * @deprecated use Article::doEdit()
1369          */
1370         function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1371                 wfDeprecated( __METHOD__ );
1372                 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1373                         ( $minor ? EDIT_MINOR : 0 ) |
1374                         ( $forceBot ? EDIT_FORCE_BOT : 0 );
1375
1376                 $status = $this->doEdit( $text, $summary, $flags );
1377                 if( !$status->isOK() ) {
1378                         return false;
1379                 }
1380
1381                 $dbw = wfGetDB( DB_MASTER );
1382                 if( $watchthis ) {
1383                         if(!$this->mTitle->userIsWatching()) {
1384                                 $dbw->begin();
1385                                 $this->doWatch();
1386                                 $dbw->commit();
1387                         }
1388                 } else {
1389                         if( $this->mTitle->userIsWatching() ) {
1390                                 $dbw->begin();
1391                                 $this->doUnwatch();
1392                                 $dbw->commit();
1393                         }
1394                 }
1395
1396                 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1397                 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1398
1399                 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1400                 return true;
1401         }
1402
1403         /**
1404          * Article::doEdit()
1405          *
1406          * Change an existing article or create a new article. Updates RC and all necessary caches,
1407          * optionally via the deferred update array.
1408          *
1409          * $wgUser must be set before calling this function.
1410          *
1411          * @param $text String: new text
1412          * @param $summary String: edit summary
1413          * @param $flags Integer bitfield:
1414          *      EDIT_NEW
1415          *          Article is known or assumed to be non-existent, create a new one
1416          *      EDIT_UPDATE
1417          *          Article is known or assumed to be pre-existing, update it
1418          *      EDIT_MINOR
1419          *          Mark this edit minor, if the user is allowed to do so
1420          *      EDIT_SUPPRESS_RC
1421          *          Do not log the change in recentchanges
1422          *      EDIT_FORCE_BOT
1423          *          Mark the edit a "bot" edit regardless of user rights
1424          *      EDIT_DEFER_UPDATES
1425          *          Defer some of the updates until the end of index.php
1426          *      EDIT_AUTOSUMMARY
1427          *          Fill in blank summaries with generated text where possible
1428          *
1429          * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1430          * If EDIT_UPDATE is specified and the article doesn't exist, the function will an 
1431          * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an 
1432          * edit-already-exists error will be returned. These two conditions are also possible with 
1433          * auto-detection due to MediaWiki's performance-optimised locking strategy.
1434          *
1435          * @param $baseRevId the revision ID this edit was based off, if any
1436          * @param $user Optional user object, $wgUser will be used if not passed
1437          *
1438          * @return Status object. Possible errors:
1439          *     edit-hook-aborted:       The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1440          *     edit-gone-missing:       In update mode, but the article didn't exist
1441          *     edit-conflict:           In update mode, the article changed unexpectedly
1442          *     edit-no-change:          Warning that the text was the same as before
1443          *     edit-already-exists:     In creation mode, but the article already exists
1444          *
1445          *  Extensions may define additional errors.
1446          *
1447          *  $return->value will contain an associative array with members as follows:
1448          *     new:                     Boolean indicating if the function attempted to create a new article
1449          *     revision:                The revision object for the inserted revision, or null
1450          *
1451          *  Compatibility note: this function previously returned a boolean value indicating success/failure
1452          */
1453         public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1454                 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1455
1456                 # Low-level sanity check
1457                 if( $this->mTitle->getText() == '' ) {
1458                         throw new MWException( 'Something is trying to edit an article with an empty title' );
1459                 }
1460
1461                 wfProfileIn( __METHOD__ );
1462
1463                 $user = is_null($user) ? $wgUser : $user;
1464                 $status = Status::newGood( array() );
1465
1466                 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1467                 $this->loadPageData(); 
1468
1469                 if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1470                         $aid = $this->mTitle->getArticleID();
1471                         if( $aid ) {
1472                                 $flags |= EDIT_UPDATE;
1473                         } else {
1474                                 $flags |= EDIT_NEW;
1475                         }
1476                 }
1477
1478                 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1479                         $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1480                 {
1481                         wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1482                         wfProfileOut( __METHOD__ );
1483                         if( $status->isOK() ) {
1484                                 $status->fatal( 'edit-hook-aborted');
1485                         }
1486                         return $status;
1487                 }
1488
1489                 # Silently ignore EDIT_MINOR if not allowed
1490                 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1491                 $bot = $flags & EDIT_FORCE_BOT;
1492
1493                 $oldtext = $this->getContent();
1494                 $oldsize = strlen( $oldtext );
1495
1496                 # Provide autosummaries if one is not provided and autosummaries are enabled.
1497                 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1498                         $summary = $this->getAutosummary( $oldtext, $text, $flags );
1499                 }
1500
1501                 $editInfo = $this->prepareTextForEdit( $text );
1502                 $text = $editInfo->pst;
1503                 $newsize = strlen( $text );
1504
1505                 $dbw = wfGetDB( DB_MASTER );
1506                 $now = wfTimestampNow();
1507
1508                 if( $flags & EDIT_UPDATE ) {
1509                         # Update article, but only if changed.
1510                         $status->value['new'] = false;
1511                         # Make sure the revision is either completely inserted or not inserted at all
1512                         if( !$wgDBtransactions ) {
1513                                 $userAbort = ignore_user_abort( true );
1514                         }
1515
1516                         $revisionId = 0;
1517
1518                         $changed = ( strcmp( $text, $oldtext ) != 0 );
1519
1520                         if( $changed ) {
1521                                 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1522                                   - (int)$this->isCountable( $oldtext );
1523                                 $this->mTotalAdjustment = 0;
1524
1525                                 if( !$this->mLatest ) {
1526                                         # Article gone missing
1527                                         wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1528                                         $status->fatal( 'edit-gone-missing' );
1529                                         wfProfileOut( __METHOD__ );
1530                                         return $status;
1531                                 }
1532
1533                                 $revision = new Revision( array(
1534                                         'page'       => $this->getId(),
1535                                         'comment'    => $summary,
1536                                         'minor_edit' => $isminor,
1537                                         'text'       => $text,
1538                                         'parent_id'  => $this->mLatest,
1539                                         'user'       => $user->getId(),
1540                                         'user_text'  => $user->getName(),
1541                                         ) );
1542
1543                                 $dbw->begin();
1544                                 $revisionId = $revision->insertOn( $dbw );
1545
1546                                 # Update page
1547                                 #
1548                                 # Note that we use $this->mLatest instead of fetching a value from the master DB 
1549                                 # during the course of this function. This makes sure that EditPage can detect 
1550                                 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp() 
1551                                 # before this function is called. A previous function used a separate query, this
1552                                 # creates a window where concurrent edits can cause an ignored edit conflict.
1553                                 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1554
1555                                 if( !$ok ) {
1556                                         /* Belated edit conflict! Run away!! */
1557                                         $status->fatal( 'edit-conflict' );
1558                                         # Delete the invalid revision if the DB is not transactional
1559                                         if( !$wgDBtransactions ) {
1560                                                 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1561                                         }
1562                                         $revisionId = 0;
1563                                         $dbw->rollback();
1564                                 } else {
1565                                         global $wgUseRCPatrol;
1566                                         wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1567                                         # Update recentchanges
1568                                         if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1569                                                 # Mark as patrolled if the user can do so
1570                                                 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
1571                                                 # Add RC row to the DB
1572                                                 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1573                                                         $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1574                                                         $revisionId, $patrolled
1575                                                 );
1576                                                 # Log auto-patrolled edits
1577                                                 if( $patrolled ) {
1578                                                         PatrolLog::record( $rc, true );
1579                                                 }
1580                                         }
1581                                         $user->incEditCount();
1582                                         $dbw->commit();
1583                                 }
1584                         } else {
1585                                 $status->warning( 'edit-no-change' );
1586                                 $revision = null;
1587                                 // Keep the same revision ID, but do some updates on it
1588                                 $revisionId = $this->getRevIdFetched();
1589                                 // Update page_touched, this is usually implicit in the page update
1590                                 // Other cache updates are done in onArticleEdit()
1591                                 $this->mTitle->invalidateCache();
1592                         }
1593
1594                         if( !$wgDBtransactions ) {
1595                                 ignore_user_abort( $userAbort );
1596                         }
1597                         // Now that ignore_user_abort is restored, we can respond to fatal errors
1598                         if( !$status->isOK() ) {
1599                                 wfProfileOut( __METHOD__ );
1600                                 return $status;
1601                         }
1602
1603                         # Invalidate cache of this article and all pages using this article
1604                         # as a template. Partly deferred. Leave templatelinks for editUpdates().
1605                         Article::onArticleEdit( $this->mTitle, 'skiptransclusions' );
1606                         # Update links tables, site stats, etc.
1607                         $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1608                 } else {
1609                         # Create new article
1610                         $status->value['new'] = true;
1611
1612                         # Set statistics members
1613                         # We work out if it's countable after PST to avoid counter drift
1614                         # when articles are created with {{subst:}}
1615                         $this->mGoodAdjustment = (int)$this->isCountable( $text );
1616                         $this->mTotalAdjustment = 1;
1617
1618                         $dbw->begin();
1619
1620                         # Add the page record; stake our claim on this title!
1621                         # This will return false if the article already exists
1622                         $newid = $this->insertOn( $dbw );
1623
1624                         if( $newid === false ) {
1625                                 $dbw->rollback();
1626                                 $status->fatal( 'edit-already-exists' );
1627                                 wfProfileOut( __METHOD__ );
1628                                 return $status;
1629                         }
1630
1631                         # Save the revision text...
1632                         $revision = new Revision( array(
1633                                 'page'       => $newid,
1634                                 'comment'    => $summary,
1635                                 'minor_edit' => $isminor,
1636                                 'text'       => $text,
1637                                 'user'       => $user->getId(),
1638                                 'user_text'  => $user->getName(),
1639                                 ) );
1640                         $revisionId = $revision->insertOn( $dbw );
1641
1642                         $this->mTitle->resetArticleID( $newid );
1643
1644                         # Update the page record with revision data
1645                         $this->updateRevisionOn( $dbw, $revision, 0 );
1646
1647                         wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1648                         # Update recentchanges
1649                         if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1650                                 global $wgUseRCPatrol, $wgUseNPPatrol;
1651                                 # Mark as patrolled if the user can do so
1652                                 $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
1653                                 # Add RC row to the DB
1654                                 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1655                                         '', strlen($text), $revisionId, $patrolled );
1656                                 # Log auto-patrolled edits
1657                                 if( $patrolled ) {
1658                                         PatrolLog::record( $rc, true );
1659                                 }
1660                         }
1661                         $user->incEditCount();
1662                         $dbw->commit();
1663
1664                         # Update links, etc.
1665                         $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1666
1667                         # Clear caches
1668                         Article::onArticleCreate( $this->mTitle );
1669
1670                         wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1671                                 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1672                 }
1673
1674                 # Do updates right now unless deferral was requested
1675                 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
1676                         wfDoUpdates();
1677                 }
1678
1679                 // Return the new revision (or null) to the caller
1680                 $status->value['revision'] = $revision;
1681
1682                 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1683                         $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status ) );
1684
1685                 wfProfileOut( __METHOD__ );
1686                 return $status;
1687         }
1688
1689         /**
1690          * @deprecated wrapper for doRedirect
1691          */
1692         public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1693                 wfDeprecated( __METHOD__ );
1694                 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1695         }
1696
1697         /**
1698          * Output a redirect back to the article.
1699          * This is typically used after an edit.
1700          *
1701          * @param $noRedir Boolean: add redirect=no
1702          * @param $sectionAnchor String: section to redirect to, including "#"
1703          * @param $extraQuery String: extra query params
1704          */
1705         public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1706                 global $wgOut;
1707                 if( $noRedir ) {
1708                         $query = 'redirect=no';
1709                         if( $extraQuery )
1710                                 $query .= "&$query";
1711                 } else {
1712                         $query = $extraQuery;
1713                 }
1714                 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1715         }
1716
1717         /**
1718          * Mark this particular edit/page as patrolled
1719          */
1720         public function markpatrolled() {
1721                 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1722                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1723
1724                 # If we haven't been given an rc_id value, we can't do anything
1725                 $rcid = (int) $wgRequest->getVal('rcid');
1726                 $rc = RecentChange::newFromId($rcid);
1727                 if( is_null($rc) ) {
1728                         $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1729                         return;
1730                 }
1731
1732                 #It would be nice to see where the user had actually come from, but for now just guess
1733                 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1734                 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1735
1736                 $dbw = wfGetDB( DB_MASTER );
1737                 $errors = $rc->doMarkPatrolled();
1738
1739                 if( in_array(array('rcpatroldisabled'), $errors) ) {
1740                         $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1741                         return;
1742                 }
1743                 
1744                 if( in_array(array('hookaborted'), $errors) ) {
1745                         // The hook itself has handled any output
1746                         return;
1747                 }
1748                 
1749                 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
1750                         $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1751                         $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1752                         $wgOut->returnToMain( false, $return );
1753                         return;
1754                 }
1755
1756                 if( !empty($errors) ) {
1757                         $wgOut->showPermissionsErrorPage( $errors );
1758                         return;
1759                 }
1760
1761                 # Inform the user
1762                 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1763                 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1764                 $wgOut->returnToMain( false, $return );
1765         }
1766
1767         /**
1768          * User-interface handler for the "watch" action
1769          */
1770
1771         public function watch() {
1772                 global $wgUser, $wgOut;
1773                 if( $wgUser->isAnon() ) {
1774                         $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1775                         return;
1776                 }
1777                 if( wfReadOnly() ) {
1778                         $wgOut->readOnlyPage();
1779                         return;
1780                 }
1781                 if( $this->doWatch() ) {
1782                         $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1783                         $wgOut->setRobotPolicy( 'noindex,nofollow' );
1784                         $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1785                 }
1786                 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1787         }
1788
1789         /**
1790          * Add this page to $wgUser's watchlist
1791          * @return bool true on successful watch operation
1792          */
1793         public function doWatch() {
1794                 global $wgUser;
1795                 if( $wgUser->isAnon() ) {
1796                         return false;
1797                 }
1798                 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1799                         $wgUser->addWatch( $this->mTitle );
1800                         return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1801                 }
1802                 return false;
1803         }
1804
1805         /**
1806          * User interface handler for the "unwatch" action.
1807          */
1808         public function unwatch() {
1809                 global $wgUser, $wgOut;
1810                 if( $wgUser->isAnon() ) {
1811                         $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1812                         return;
1813                 }
1814                 if( wfReadOnly() ) {
1815                         $wgOut->readOnlyPage();
1816                         return;
1817                 }
1818                 if( $this->doUnwatch() ) {
1819                         $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1820                         $wgOut->setRobotPolicy( 'noindex,nofollow' );
1821                         $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1822                 }
1823                 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1824         }
1825
1826         /**
1827          * Stop watching a page
1828          * @return bool true on successful unwatch
1829          */
1830         public function doUnwatch() {
1831                 global $wgUser;
1832                 if( $wgUser->isAnon() ) {
1833                         return false;
1834                 }
1835                 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1836                         $wgUser->removeWatch( $this->mTitle );
1837                         return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1838                 }
1839                 return false;
1840         }
1841
1842         /**
1843          * action=protect handler
1844          */
1845         public function protect() {
1846                 $form = new ProtectionForm( $this );
1847                 $form->execute();
1848         }
1849
1850         /**
1851          * action=unprotect handler (alias)
1852          */
1853         public function unprotect() {
1854                 $this->protect();
1855         }
1856
1857         /**
1858          * Update the article's restriction field, and leave a log entry.
1859          *
1860          * @param $limit Array: set of restriction keys
1861          * @param $reason String
1862          * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1863          * @param $expiry Array: per restriction type expiration
1864          * @return bool true on success
1865          */
1866         public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1867                 global $wgUser, $wgRestrictionTypes, $wgContLang;
1868
1869                 $id = $this->mTitle->getArticleID();
1870                 if( $id <= 0 || wfReadOnly() || !$this->mTitle->userCan('protect') ) {
1871                         return false;
1872                 }
1873
1874                 if( !$cascade ) {
1875                         $cascade = false;
1876                 }
1877
1878                 // Take this opportunity to purge out expired restrictions
1879                 Title::purgeExpiredRestrictions();
1880
1881                 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1882                 # we expect a single selection, but the schema allows otherwise.
1883                 $current = array();
1884                 $updated = Article::flattenRestrictions( $limit );
1885                 $changed = false;
1886                 foreach( $wgRestrictionTypes as $action ) {
1887                         if( isset( $expiry[$action] ) ) {
1888                                 # Get current restrictions on $action
1889                                 $aLimits = $this->mTitle->getRestrictions( $action );
1890                                 $current[$action] = implode( '', $aLimits );
1891                                 # Are any actual restrictions being dealt with here?
1892                                 $aRChanged = count($aLimits) || !empty($limit[$action]);
1893                                 # If something changed, we need to log it. Checking $aRChanged
1894                                 # assures that "unprotecting" a page that is not protected does
1895                                 # not log just because the expiry was "changed".
1896                                 if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
1897                                         $changed = true;
1898                                 }
1899                         }
1900                 }
1901
1902                 $current = Article::flattenRestrictions( $current );
1903
1904                 $changed = ($changed || $current != $updated );
1905                 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1906                 $protect = ( $updated != '' );
1907
1908                 # If nothing's changed, do nothing
1909                 if( $changed ) {
1910                         if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1911
1912                                 $dbw = wfGetDB( DB_MASTER );
1913                                 
1914                                 # Prepare a null revision to be added to the history
1915                                 $modified = $current != '' && $protect;
1916                                 if( $protect ) {
1917                                         $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1918                                 } else {
1919                                         $comment_type = 'unprotectedarticle';
1920                                 }
1921                                 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1922
1923                                 # Only restrictions with the 'protect' right can cascade...
1924                                 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1925                                 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1926                                 # The schema allows multiple restrictions
1927                                 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
1928                                         $cascade = false;
1929                                 $cascade_description = '';       
1930                                 if( $cascade ) {
1931                                         $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';      
1932                                 }
1933
1934                                 if( $reason )
1935                                         $comment .= ": $reason";
1936
1937                                 $editComment = $comment;
1938                                 $encodedExpiry = array();
1939                                 $protect_description = '';
1940                                 foreach( $limit as $action => $restrictions  ) {
1941                                         $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
1942                                         if( $restrictions != '' ) {
1943                                                 $protect_description .= "[$action=$restrictions] (";
1944                                                 if( $encodedExpiry[$action] != 'infinity' ) {
1945                                                         $protect_description .= wfMsgForContent( 'protect-expiring', 
1946                                                                 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1947                                                                 $wgContLang->date( $expiry[$action], false, false ) ,
1948                                                                 $wgContLang->time( $expiry[$action], false, false ) );   
1949                                                 } else {
1950                                                         $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1951                                                 }
1952                                                 $protect_description .= ') ';
1953                                         }
1954                                 }
1955                                 $protect_description = trim($protect_description);
1956                                         
1957                                 if( $protect_description && $protect )
1958                                         $editComment .= " ($protect_description)";
1959                                 if( $cascade )
1960                                         $editComment .= "$cascade_description";
1961                                 # Update restrictions table
1962                                 foreach( $limit as $action => $restrictions ) {
1963                                         if($restrictions != '' ) {
1964                                                 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1965                                                         array( 'pr_page' => $id, 
1966                                                                 'pr_type' => $action, 
1967                                                                 'pr_level' => $restrictions, 
1968                                                                 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
1969                                                                 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__  );
1970                                         } else {
1971                                                 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1972                                                         'pr_type' => $action ), __METHOD__ );
1973                                         }
1974                                 }
1975
1976                                 # Insert a null revision
1977                                 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1978                                 $nullRevId = $nullRevision->insertOn( $dbw );
1979
1980                                 $latest = $this->getLatest();
1981                                 # Update page record
1982                                 $dbw->update( 'page',
1983                                         array( /* SET */
1984                                                 'page_touched' => $dbw->timestamp(),
1985                                                 'page_restrictions' => '',
1986                                                 'page_latest' => $nullRevId
1987                                         ), array( /* WHERE */
1988                                                 'page_id' => $id
1989                                         ), 'Article::protect'
1990                                 );
1991
1992                                 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
1993                                 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1994
1995                                 # Update the protection log
1996                                 $log = new LogPage( 'protect' );
1997                                 if( $protect ) {
1998                                         $params = array($protect_description,$cascade ? 'cascade' : '');
1999                                         $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2000                                 } else {
2001                                         $log->addEntry( 'unprotect', $this->mTitle, $reason );
2002                                 }
2003
2004                         } # End hook
2005                 } # End "changed" check
2006
2007                 return true;
2008         }
2009
2010         /**
2011          * Take an array of page restrictions and flatten it to a string
2012          * suitable for insertion into the page_restrictions field.
2013          * @param $limit Array
2014          * @return String
2015          */
2016         protected static function flattenRestrictions( $limit ) {
2017                 if( !is_array( $limit ) ) {
2018                         throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2019                 }
2020                 $bits = array();
2021                 ksort( $limit );
2022                 foreach( $limit as $action => $restrictions ) {
2023                         if( $restrictions != '' ) {
2024                                 $bits[] = "$action=$restrictions";
2025                         }
2026                 }
2027                 return implode( ':', $bits );
2028         }
2029
2030         /**
2031          * Auto-generates a deletion reason
2032          * @param &$hasHistory Boolean: whether the page has a history
2033          */
2034         public function generateReason( &$hasHistory ) {
2035                 global $wgContLang;
2036                 $dbw = wfGetDB( DB_MASTER );
2037                 // Get the last revision
2038                 $rev = Revision::newFromTitle( $this->mTitle );
2039                 if( is_null( $rev ) )
2040                         return false;
2041
2042                 // Get the article's contents
2043                 $contents = $rev->getText();
2044                 $blank = false;
2045                 // If the page is blank, use the text from the previous revision,
2046                 // which can only be blank if there's a move/import/protect dummy revision involved
2047                 if( $contents == '' ) {
2048                         $prev = $rev->getPrevious();
2049                         if( $prev )     {
2050                                 $contents = $prev->getText();
2051                                 $blank = true;
2052                         }
2053                 }
2054
2055                 // Find out if there was only one contributor
2056                 // Only scan the last 20 revisions
2057                 $limit = 20;
2058                 $res = $dbw->select( 'revision', 'rev_user_text',
2059                         array( 'rev_page' => $this->getID() ), __METHOD__,
2060                         array( 'LIMIT' => $limit )
2061                 );
2062                 if( $res === false )
2063                         // This page has no revisions, which is very weird
2064                         return false;
2065                 if( $res->numRows() > 1 )
2066                                 $hasHistory = true;
2067                 else
2068                                 $hasHistory = false;
2069                 $row = $dbw->fetchObject( $res );
2070                 $onlyAuthor = $row->rev_user_text;
2071                 // Try to find a second contributor
2072                 foreach( $res as $row ) {
2073                         if( $row->rev_user_text != $onlyAuthor ) {
2074                                 $onlyAuthor = false;
2075                                 break;
2076                         }
2077                 }
2078                 $dbw->freeResult( $res );
2079
2080                 // Generate the summary with a '$1' placeholder
2081                 if( $blank ) {
2082                         // The current revision is blank and the one before is also
2083                         // blank. It's just not our lucky day
2084                         $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2085                 } else {
2086                         if( $onlyAuthor )
2087                                 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2088                         else
2089                                 $reason = wfMsgForContent( 'excontent', '$1' );
2090                 }
2091                 
2092                 if( $reason == '-' ) {
2093                         // Allow these UI messages to be blanked out cleanly
2094                         return '';
2095                 }
2096
2097                 // Replace newlines with spaces to prevent uglyness
2098                 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2099                 // Calculate the maximum amount of chars to get
2100                 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2101                 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2102                 $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
2103                 // Remove possible unfinished links
2104                 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2105                 // Now replace the '$1' placeholder
2106                 $reason = str_replace( '$1', $contents, $reason );
2107                 return $reason;
2108         }
2109
2110
2111         /*
2112          * UI entry point for page deletion
2113          */
2114         public function delete() {
2115                 global $wgUser, $wgOut, $wgRequest;
2116
2117                 $confirm = $wgRequest->wasPosted() &&
2118                                 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2119
2120                 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2121                 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2122
2123                 $reason = $this->DeleteReasonList;
2124
2125                 if( $reason != 'other' && $this->DeleteReason != '' ) {
2126                         // Entry from drop down menu + additional comment
2127                         $reason .= ': ' . $this->DeleteReason;
2128                 } elseif( $reason == 'other' ) {
2129                         $reason = $this->DeleteReason;
2130                 }
2131                 # Flag to hide all contents of the archived revisions
2132                 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2133
2134                 # This code desperately needs to be totally rewritten
2135
2136                 # Read-only check...
2137                 if( wfReadOnly() ) {
2138                         $wgOut->readOnlyPage();
2139                         return;
2140                 }
2141
2142                 # Check permissions
2143                 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2144
2145                 if( count( $permission_errors ) > 0 ) {
2146                         $wgOut->showPermissionsErrorPage( $permission_errors );
2147                         return;
2148                 }
2149
2150                 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2151
2152                 # Better double-check that it hasn't been deleted yet!
2153                 $dbw = wfGetDB( DB_MASTER );
2154                 $conds = $this->mTitle->pageCond();
2155                 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2156                 if( $latest === false ) {
2157                         $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2158                         $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2159                         LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2160                         return;
2161                 }
2162
2163                 # Hack for big sites
2164                 $bigHistory = $this->isBigDeletion();
2165                 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2166                         global $wgLang, $wgDeleteRevisionsLimit;
2167                         $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2168                                 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2169                         return;
2170                 }
2171
2172                 if( $confirm ) {
2173                         $this->doDelete( $reason, $suppress );
2174                         if( $wgRequest->getCheck( 'wpWatch' ) ) {
2175                                 $this->doWatch();
2176                         } elseif( $this->mTitle->userIsWatching() ) {
2177                                 $this->doUnwatch();
2178                         }
2179                         return;
2180                 }
2181
2182                 // Generate deletion reason
2183                 $hasHistory = false;
2184                 if( !$reason ) $reason = $this->generateReason($hasHistory);
2185
2186                 // If the page has a history, insert a warning
2187                 if( $hasHistory && !$confirm ) {
2188                         $skin = $wgUser->getSkin();
2189                         $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2190                         if( $bigHistory ) {
2191                                 global $wgLang, $wgDeleteRevisionsLimit;
2192                                 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2193                                         array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2194                         }
2195                 }
2196
2197                 return $this->confirmDelete( $reason );
2198         }
2199
2200         /**
2201          * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2202          */
2203         public function isBigDeletion() {
2204                 global $wgDeleteRevisionsLimit;
2205                 if( $wgDeleteRevisionsLimit ) {
2206                         $revCount = $this->estimateRevisionCount();
2207                         return $revCount > $wgDeleteRevisionsLimit;
2208                 }
2209                 return false;
2210         }
2211
2212         /**
2213          * @return int approximate revision count
2214          */
2215         public function estimateRevisionCount() {
2216                 $dbr = wfGetDB( DB_SLAVE );
2217                 // For an exact count...
2218                 //return $dbr->selectField( 'revision', 'COUNT(*)',
2219                 //      array( 'rev_page' => $this->getId() ), __METHOD__ );
2220                 return $dbr->estimateRowCount( 'revision', '*',
2221                         array( 'rev_page' => $this->getId() ), __METHOD__ );
2222         }
2223
2224         /**
2225          * Get the last N authors
2226          * @param $num Integer: number of revisions to get
2227          * @param $revLatest String: the latest rev_id, selected from the master (optional)
2228          * @return array Array of authors, duplicates not removed
2229          */
2230         public function getLastNAuthors( $num, $revLatest = 0 ) {
2231                 wfProfileIn( __METHOD__ );
2232                 // First try the slave
2233                 // If that doesn't have the latest revision, try the master
2234                 $continue = 2;
2235                 $db = wfGetDB( DB_SLAVE );
2236                 do {
2237                         $res = $db->select( array( 'page', 'revision' ),
2238                                 array( 'rev_id', 'rev_user_text' ),
2239                                 array(
2240                                         'page_namespace' => $this->mTitle->getNamespace(),
2241                                         'page_title' => $this->mTitle->getDBkey(),
2242                                         'rev_page = page_id'
2243                                 ), __METHOD__, $this->getSelectOptions( array(
2244                                         'ORDER BY' => 'rev_timestamp DESC',
2245                                         'LIMIT' => $num
2246                                 ) )
2247                         );
2248                         if( !$res ) {
2249                                 wfProfileOut( __METHOD__ );
2250                                 return array();
2251                         }
2252                         $row = $db->fetchObject( $res );
2253                         if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2254                                 $db = wfGetDB( DB_MASTER );
2255                                 $continue--;
2256                         } else {
2257                                 $continue = 0;
2258                         }
2259                 } while ( $continue );
2260
2261                 $authors = array( $row->rev_user_text );
2262                 while ( $row = $db->fetchObject( $res ) ) {
2263                         $authors[] = $row->rev_user_text;
2264                 }
2265                 wfProfileOut( __METHOD__ );
2266                 return $authors;
2267         }
2268
2269         /**
2270          * Output deletion confirmation dialog
2271          * @param $reason String: prefilled reason
2272          */
2273         public function confirmDelete( $reason ) {
2274                 global $wgOut, $wgUser;
2275
2276                 wfDebug( "Article::confirmDelete\n" );
2277
2278                 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2279                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2280                 $wgOut->addWikiMsg( 'confirmdeletetext' );
2281
2282                 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2283                         $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2284                                         <td></td>
2285                                         <td class='mw-input'>" .
2286                                                 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2287                                                         'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2288                                         "</td>
2289                                 </tr>";
2290                 } else {
2291                         $suppress = '';
2292                 }
2293                 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2294
2295                 $form = Xml::openElement( 'form', array( 'method' => 'post', 
2296                         'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2297                         Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2298                         Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2299                         Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2300                         "<tr id=\"wpDeleteReasonListRow\">
2301                                 <td class='mw-label'>" .
2302                                         Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2303                                 "</td>
2304                                 <td class='mw-input'>" .
2305                                         Xml::listDropDown( 'wpDeleteReasonList',
2306                                                 wfMsgForContent( 'deletereason-dropdown' ),
2307                                                 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2308                                 "</td>
2309                         </tr>
2310                         <tr id=\"wpDeleteReasonRow\">
2311                                 <td class='mw-label'>" .
2312                                         Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2313                                 "</td>
2314                                 <td class='mw-input'>" .
2315                                         Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 
2316                                                 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2317                                 "</td>
2318                         </tr>
2319                         <tr>
2320                                 <td></td>
2321                                 <td class='mw-input'>" .
2322                                         Xml::checkLabel( wfMsg( 'watchthis' ),
2323                                                 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2324                                 "</td>
2325                         </tr>
2326                         $suppress
2327                         <tr>
2328                                 <td></td>
2329                                 <td class='mw-submit'>" .
2330                                         Xml::submitButton( wfMsg( 'deletepage' ),
2331                                                 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2332                                 "</td>
2333                         </tr>" .
2334                         Xml::closeElement( 'table' ) .
2335                         Xml::closeElement( 'fieldset' ) .
2336                         Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2337                         Xml::closeElement( 'form' );
2338
2339                         if( $wgUser->isAllowed( 'editinterface' ) ) {
2340                                 $skin = $wgUser->getSkin();
2341                                 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2342                                 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2343                         }
2344
2345                 $wgOut->addHTML( $form );
2346                 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2347         }
2348
2349         /**
2350          * Perform a deletion and output success or failure messages
2351          */
2352         public function doDelete( $reason, $suppress = false ) {
2353                 global $wgOut, $wgUser;
2354                 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2355
2356                 $error = '';
2357                 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2358                         if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2359                                 $deleted = $this->mTitle->getPrefixedText();
2360
2361                                 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2362                                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2363
2364                                 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2365
2366                                 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2367                                 $wgOut->returnToMain( false );
2368                                 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2369                         } else {
2370                                 if( $error == '' ) {
2371                                         $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2372                                         $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2373                                         LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2374                                 } else {
2375                                         $wgOut->showFatalError( $error );
2376                                 }
2377                         }
2378                 }
2379         }
2380
2381         /**
2382          * Back-end article deletion
2383          * Deletes the article with database consistency, writes logs, purges caches
2384          * Returns success
2385          */
2386         public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2387                 global $wgUseSquid, $wgDeferredUpdateList;
2388                 global $wgUseTrackbacks;
2389
2390                 wfDebug( __METHOD__."\n" );
2391
2392                 $dbw = wfGetDB( DB_MASTER );
2393                 $ns = $this->mTitle->getNamespace();
2394                 $t = $this->mTitle->getDBkey();
2395                 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2396
2397                 if( $t == '' || $id == 0 ) {
2398                         return false;
2399                 }
2400
2401                 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2402                 array_push( $wgDeferredUpdateList, $u );
2403
2404                 // Bitfields to further suppress the content
2405                 if( $suppress ) {
2406                         $bitfield = 0;
2407                         // This should be 15...
2408                         $bitfield |= Revision::DELETED_TEXT;
2409                         $bitfield |= Revision::DELETED_COMMENT;
2410                         $bitfield |= Revision::DELETED_USER;
2411                         $bitfield |= Revision::DELETED_RESTRICTED;
2412                 } else {
2413                         $bitfield = 'rev_deleted';
2414                 }
2415
2416                 $dbw->begin();
2417                 // For now, shunt the revision data into the archive table.
2418                 // Text is *not* removed from the text table; bulk storage
2419                 // is left intact to avoid breaking block-compression or
2420                 // immutable storage schemes.
2421                 //
2422                 // For backwards compatibility, note that some older archive
2423                 // table entries will have ar_text and ar_flags fields still.
2424                 //
2425                 // In the future, we may keep revisions and mark them with
2426                 // the rev_deleted field, which is reserved for this purpose.
2427                 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2428                         array(
2429                                 'ar_namespace'  => 'page_namespace',
2430                                 'ar_title'      => 'page_title',
2431                                 'ar_comment'    => 'rev_comment',
2432                                 'ar_user'       => 'rev_user',
2433                                 'ar_user_text'  => 'rev_user_text',
2434                                 'ar_timestamp'  => 'rev_timestamp',
2435                                 'ar_minor_edit' => 'rev_minor_edit',
2436                                 'ar_rev_id'     => 'rev_id',
2437                                 'ar_text_id'    => 'rev_text_id',
2438                                 'ar_text'       => '\'\'', // Be explicit to appease
2439                                 'ar_flags'      => '\'\'', // MySQL's "strict mode"...
2440                                 'ar_len'        => 'rev_len',
2441                                 'ar_page_id'    => 'page_id',
2442                                 'ar_deleted'    => $bitfield
2443                         ), array(
2444                                 'page_id' => $id,
2445                                 'page_id = rev_page'
2446                         ), __METHOD__
2447                 );
2448
2449                 # Delete restrictions for it
2450                 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2451
2452                 # Now that it's safely backed up, delete it
2453                 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2454                 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2455                 if( !$ok ) {
2456                         $dbw->rollback();
2457                         return false;
2458                 }
2459                 
2460                 # Fix category table counts
2461                 $cats = array();
2462                 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2463                 foreach( $res as $row ) {
2464                         $cats []= $row->cl_to;
2465                 }
2466                 $this->updateCategoryCounts( array(), $cats );
2467
2468                 # If using cascading deletes, we can skip some explicit deletes
2469                 if( !$dbw->cascadingDeletes() ) {
2470                         $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2471
2472                         if($wgUseTrackbacks)
2473                                 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2474
2475                         # Delete outgoing links
2476                         $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2477                         $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2478                         $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2479                         $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2480                         $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2481                         $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2482                         $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2483                 }
2484
2485                 # If using cleanup triggers, we can skip some manual deletes
2486                 if( !$dbw->cleanupTriggers() ) {
2487                         # Clean up recentchanges entries...
2488                         $dbw->delete( 'recentchanges',
2489                                 array( 'rc_type != '.RC_LOG, 
2490                                         'rc_namespace' => $this->mTitle->getNamespace(),
2491                                         'rc_title' => $this->mTitle->getDBKey() ),
2492                                 __METHOD__ );
2493                         $dbw->delete( 'recentchanges',
2494                                 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2495                                 __METHOD__ );
2496                 }
2497
2498                 # Clear caches
2499                 Article::onArticleDelete( $this->mTitle );
2500
2501                 # Clear the cached article id so the interface doesn't act like we exist
2502                 $this->mTitle->resetArticleID( 0 );
2503                 $this->mTitle->mArticleID = 0;
2504
2505                 # Log the deletion, if the page was suppressed, log it at Oversight instead
2506                 $logtype = $suppress ? 'suppress' : 'delete';
2507                 $log = new LogPage( $logtype );
2508
2509                 # Make sure logging got through
2510                 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2511
2512                 $dbw->commit();
2513
2514                 return true;
2515         }
2516
2517         /**
2518          * Roll back the most recent consecutive set of edits to a page
2519          * from the same user; fails if there are no eligible edits to
2520          * roll back to, e.g. user is the sole contributor. This function
2521          * performs permissions checks on $wgUser, then calls commitRollback()
2522          * to do the dirty work
2523          *
2524          * @param $fromP String: Name of the user whose edits to rollback.
2525          * @param $summary String: Custom summary. Set to default summary if empty.
2526          * @param $token String: Rollback token.
2527          * @param $bot Boolean: If true, mark all reverted edits as bot.
2528          *
2529          * @param $resultDetails Array: contains result-specific array of additional values
2530          *    'alreadyrolled' : 'current' (rev)
2531          *    success        : 'summary' (str), 'current' (rev), 'target' (rev)
2532          *
2533          * @return array of errors, each error formatted as
2534          *   array(messagekey, param1, param2, ...).
2535          * On success, the array is empty.  This array can also be passed to
2536          * OutputPage::showPermissionsErrorPage().
2537          */
2538         public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2539                 global $wgUser;
2540                 $resultDetails = null;
2541
2542                 # Check permissions
2543                 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2544                 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2545                 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2546
2547                 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2548                         $errors[] = array( 'sessionfailure' );
2549
2550                 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2551                         $errors[] = array( 'actionthrottledtext' );
2552                 }
2553                 # If there were errors, bail out now
2554                 if( !empty( $errors ) )
2555                         return $errors;
2556
2557                 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2558         }
2559
2560         /**
2561          * Backend implementation of doRollback(), please refer there for parameter
2562          * and return value documentation
2563          *
2564          * NOTE: This function does NOT check ANY permissions, it just commits the
2565          * rollback to the DB Therefore, you should only call this function direct-
2566          * ly if you want to use custom permissions checks. If you don't, use
2567          * doRollback() instead.
2568          */
2569         public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2570                 global $wgUseRCPatrol, $wgUser, $wgLang;
2571                 $dbw = wfGetDB( DB_MASTER );
2572
2573                 if( wfReadOnly() ) {
2574                         return array( array( 'readonlytext' ) );
2575                 }
2576
2577                 # Get the last editor
2578                 $current = Revision::newFromTitle( $this->mTitle );
2579                 if( is_null( $current ) ) {
2580                         # Something wrong... no page?
2581                         return array(array('notanarticle'));
2582                 }
2583
2584                 $from = str_replace( '_', ' ', $fromP );
2585                 if( $from != $current->getUserText() ) {
2586                         $resultDetails = array( 'current' => $current );
2587                         return array(array('alreadyrolled',
2588                                 htmlspecialchars($this->mTitle->getPrefixedText()),
2589                                 htmlspecialchars($fromP),
2590                                 htmlspecialchars($current->getUserText())
2591                         ));
2592                 }
2593
2594                 # Get the last edit not by this guy
2595                 $user = intval( $current->getUser() );
2596                 $user_text = $dbw->addQuotes( $current->getUserText() );
2597                 $s = $dbw->selectRow( 'revision',
2598                         array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2599                         array(  'rev_page' => $current->getPage(),
2600                                 "rev_user != {$user} OR rev_user_text != {$user_text}"
2601                         ), __METHOD__,
2602                         array(  'USE INDEX' => 'page_timestamp',
2603                                 'ORDER BY'  => 'rev_timestamp DESC' )
2604                         );
2605                 if( $s === false ) {
2606                         # No one else ever edited this page
2607                         return array(array('cantrollback'));
2608                 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2609                         # Only admins can see this text
2610                         return array(array('notvisiblerev'));
2611                 }
2612
2613                 $set = array();
2614                 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2615                         # Mark all reverted edits as bot
2616                         $set['rc_bot'] = 1;
2617                 }
2618                 if( $wgUseRCPatrol ) {
2619                         # Mark all reverted edits as patrolled
2620                         $set['rc_patrolled'] = 1;
2621                 }
2622
2623                 if( $set ) {
2624                         $dbw->update( 'recentchanges', $set,
2625                                         array( /* WHERE */
2626                                                 'rc_cur_id' => $current->getPage(),
2627                                                 'rc_user_text' => $current->getUserText(),
2628                                                 "rc_timestamp > '{$s->rev_timestamp}'",
2629                                         ), __METHOD__
2630                                 );
2631                 }
2632
2633                 # Generate the edit summary if necessary
2634                 $target = Revision::newFromId( $s->rev_id );
2635                 if( empty( $summary ) ){
2636                         $summary = wfMsgForContent( 'revertpage' );
2637                 }
2638
2639                 # Allow the custom summary to use the same args as the default message
2640                 $args = array(
2641                         $target->getUserText(), $from, $s->rev_id,
2642                         $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2643                         $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2644                 );
2645                 $summary = wfMsgReplaceArgs( $summary, $args );
2646
2647                 # Save
2648                 $flags = EDIT_UPDATE;
2649
2650                 if( $wgUser->isAllowed('minoredit') )
2651                         $flags |= EDIT_MINOR;
2652
2653                 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2654                         $flags |= EDIT_FORCE_BOT;
2655                 # Actually store the edit
2656                 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2657                 if( !empty( $status->value['revision'] ) ) {
2658                         $revId = $status->value['revision']->getId();
2659                 } else {
2660                         $revId = false;
2661                 }
2662
2663                 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2664
2665                 $resultDetails = array(
2666                         'summary' => $summary,
2667                         'current' => $current,
2668                         'target' => $target,
2669                         'newid' => $revId
2670                 );
2671                 return array();
2672         }
2673
2674         /**
2675          * User interface for rollback operations
2676          */
2677         public function rollback() {
2678                 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2679                 $details = null;
2680
2681                 $result = $this->doRollback(
2682                         $wgRequest->getVal( 'from' ),
2683                         $wgRequest->getText( 'summary' ),
2684                         $wgRequest->getVal( 'token' ),
2685                         $wgRequest->getBool( 'bot' ),
2686                         $details
2687                 );
2688
2689                 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2690                         $wgOut->rateLimited();
2691                         return;
2692                 }
2693                 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
2694                         $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2695                         $errArray = $result[0];
2696                         $errMsg = array_shift( $errArray );
2697                         $wgOut->addWikiMsgArray( $errMsg, $errArray );
2698                         if( isset( $details['current'] ) ){
2699                                 $current = $details['current'];
2700                                 if( $current->getComment() != '' ) {
2701                                         $wgOut->addWikiMsgArray( 'editcomment', array( 
2702                                                 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2703                                 }
2704                         }
2705                         return;
2706                 }
2707                 # Display permissions errors before read-only message -- there's no
2708                 # point in misleading the user into thinking the inability to rollback
2709                 # is only temporary.
2710                 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
2711                         # array_diff is completely broken for arrays of arrays, sigh.  Re-
2712                         # move any 'readonlytext' error manually.
2713                         $out = array();
2714                         foreach( $result as $error ) {
2715                                 if( $error != array( 'readonlytext' ) ) {
2716                                         $out []= $error;
2717                                 }
2718                         }
2719                         $wgOut->showPermissionsErrorPage( $out );
2720                         return;
2721                 }
2722                 if( $result == array( array( 'readonlytext' ) ) ) {
2723                         $wgOut->readOnlyPage();
2724                         return;
2725                 }
2726
2727                 $current = $details['current'];
2728                 $target = $details['target'];
2729                 $newId = $details['newid'];
2730                 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2731                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2732                 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2733                         . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2734                 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2735                         . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2736                 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2737                 $wgOut->returnToMain( false, $this->mTitle );
2738
2739                 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2740                         $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
2741                         $de->showDiff( '', '' );
2742                 }
2743         }
2744
2745
2746         /**
2747          * Do standard deferred updates after page view
2748          */
2749         public function viewUpdates() {
2750                 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
2751                 # Don't update page view counters on views from bot users (bug 14044)
2752                 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
2753                         Article::incViewCount( $this->getID() );
2754                         $u = new SiteStatsUpdate( 1, 0, 0 );
2755                         array_push( $wgDeferredUpdateList, $u );
2756                 }
2757                 # Update newtalk / watchlist notification status
2758                 $wgUser->clearNotification( $this->mTitle );
2759         }
2760
2761         /**
2762          * Prepare text which is about to be saved.
2763          * Returns a stdclass with source, pst and output members
2764          */
2765         public function prepareTextForEdit( $text, $revid=null ) {
2766                 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2767                         // Already prepared
2768                         return $this->mPreparedEdit;
2769                 }
2770                 global $wgParser;
2771                 $edit = (object)array();
2772                 $edit->revid = $revid;
2773                 $edit->newText = $text;
2774                 $edit->pst = $this->preSaveTransform( $text );
2775                 $options = new ParserOptions;
2776                 $options->setTidy( true );
2777                 $options->enableLimitReport();
2778                 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2779                 $edit->oldText = $this->getContent();
2780                 $this->mPreparedEdit = $edit;
2781                 return $edit;
2782         }
2783
2784         /**
2785          * Do standard deferred updates after page edit.
2786          * Update links tables, site stats, search index and message cache.
2787          * Purges pages that include this page if the text was changed here.
2788          * Every 100th edit, prune the recent changes table.
2789          *
2790          * @private
2791          * @param $text New text of the article
2792          * @param $summary Edit summary
2793          * @param $minoredit Minor edit
2794          * @param $timestamp_of_pagechange Timestamp associated with the page change
2795          * @param $newid rev_id value of the new revision
2796          * @param $changed Whether or not the content actually changed
2797          */
2798         public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2799                 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2800
2801                 wfProfileIn( __METHOD__ );
2802
2803                 # Parse the text
2804                 # Be careful not to double-PST: $text is usually already PST-ed once
2805                 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2806                         wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2807                         $editInfo = $this->prepareTextForEdit( $text, $newid );
2808                 } else {
2809                         wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2810                         $editInfo = $this->mPreparedEdit;
2811                 }
2812
2813                 # Save it to the parser cache
2814                 if( $wgEnableParserCache ) {
2815                         $parserCache = ParserCache::singleton();
2816                         $parserCache->save( $editInfo->output, $this, $wgUser );
2817                 }
2818
2819                 # Update the links tables
2820                 $u = new LinksUpdate( $this->mTitle, $editInfo->output, false );
2821                 $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
2822                 $u->doUpdate();
2823                 
2824                 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
2825
2826                 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2827                         if( 0 == mt_rand( 0, 99 ) ) {
2828                                 // Flush old entries from the `recentchanges` table; we do this on
2829                                 // random requests so as to avoid an increase in writes for no good reason
2830                                 global $wgRCMaxAge;
2831                                 $dbw = wfGetDB( DB_MASTER );
2832                                 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2833                                 $recentchanges = $dbw->tableName( 'recentchanges' );
2834                                 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2835                                 $dbw->query( $sql );
2836                         }
2837                 }
2838
2839                 $id = $this->getID();
2840                 $title = $this->mTitle->getPrefixedDBkey();
2841                 $shortTitle = $this->mTitle->getDBkey();
2842
2843                 if( 0 == $id ) {
2844                         wfProfileOut( __METHOD__ );
2845                         return;
2846                 }
2847
2848                 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2849                 array_push( $wgDeferredUpdateList, $u );
2850                 $u = new SearchUpdate( $id, $title, $text );
2851                 array_push( $wgDeferredUpdateList, $u );
2852
2853                 # If this is another user's talk page, update newtalk
2854                 # Don't do this if $changed = false otherwise some idiot can null-edit a
2855                 # load of user talk pages and piss people off, nor if it's a minor edit
2856                 # by a properly-flagged bot.
2857                 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2858                         && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
2859                         if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2860                                 $other = User::newFromName( $shortTitle, false );
2861                                 if( !$other ) {
2862                                         wfDebug( __METHOD__.": invalid username\n" );
2863                                 } elseif( User::isIP( $shortTitle ) ) {
2864                                         // An anonymous user
2865                                         $other->setNewtalk( true );
2866                                 } elseif( $other->isLoggedIn() ) {
2867                                         $other->setNewtalk( true );
2868                                 } else {
2869                                         wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
2870                                 }
2871                         }
2872                 }
2873
2874                 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2875                         $wgMessageCache->replace( $shortTitle, $text );
2876                 }
2877
2878                 wfProfileOut( __METHOD__ );
2879         }
2880
2881         /**
2882          * Perform article updates on a special page creation.
2883          *
2884          * @param $rev Revision object
2885          *
2886          * @todo This is a shitty interface function. Kill it and replace the
2887          * other shitty functions like editUpdates and such so it's not needed
2888          * anymore.
2889          */
2890         public function createUpdates( $rev ) {
2891                 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2892                 $this->mTotalAdjustment = 1;
2893                 $this->editUpdates( $rev->getText(), $rev->getComment(),
2894                         $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2895         }
2896
2897         /**
2898          * Generate the navigation links when browsing through an article revisions
2899          * It shows the information as:
2900          *   Revision as of \<date\>; view current revision
2901          *   \<- Previous version | Next Version -\>
2902          *
2903          * @param $oldid String: revision ID of this article revision
2904          */
2905         public function setOldSubtitle( $oldid = 0 ) {
2906                 global $wgLang, $wgOut, $wgUser;
2907
2908                 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
2909                         return;
2910                 }
2911
2912                 $revision = Revision::newFromId( $oldid );
2913
2914                 $current = ( $oldid == $this->mLatest );
2915                 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2916                 $sk = $wgUser->getSkin();
2917                 $lnk = $current
2918                         ? wfMsgHtml( 'currentrevisionlink' )
2919                         : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'currentrevisionlink' ) );
2920                 $curdiff = $current
2921                         ? wfMsgHtml( 'diff' )
2922                         : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
2923                 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2924                 $prevlink = $prev
2925                         ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2926                         : wfMsgHtml( 'previousrevision' );
2927                 $prevdiff = $prev
2928                         ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
2929                         : wfMsgHtml( 'diff' );
2930                 $nextlink = $current
2931                         ? wfMsgHtml( 'nextrevision' )
2932                         : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2933                 $nextdiff = $current
2934                         ? wfMsgHtml( 'diff' )
2935                         : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
2936
2937                 $cdel='';
2938                 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2939                         $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2940                         if( $revision->isCurrent() ) {
2941                         // We don't handle top deleted edits too well
2942                                 $cdel = wfMsgHtml( 'rev-delundel' );
2943                         } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2944                         // If revision was hidden from sysops
2945                                 $cdel = wfMsgHtml( 'rev-delundel' );
2946                         } else {
2947                                 $cdel = $sk->makeKnownLinkObj( $revdel,
2948                                         wfMsgHtml('rev-delundel'),
2949                                         'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2950                                         '&oldid=' . urlencode( $oldid ) );
2951                                 // Bolden oversighted content
2952                                 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2953                                         $cdel = "<strong>$cdel</strong>";
2954                         }
2955                         $cdel = "(<small>$cdel</small>) ";
2956                 }
2957                 # Show user links if allowed to see them. Normally they
2958                 # are hidden regardless, but since we can already see the text here...
2959                 $userlinks = $sk->revUserTools( $revision, false );
2960
2961                 $m = wfMsg( 'revision-info-current' );
2962                 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2963                         ? 'revision-info-current'
2964                         : 'revision-info';
2965
2966                 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), $td, $userlinks, $revision->getID() ) . "</div>\n" .
2967
2968                      "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
2969                         $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2970                 $wgOut->setSubtitle( $r );
2971         }
2972
2973         /**
2974          * This function is called right before saving the wikitext,
2975          * so we can do things like signatures and links-in-context.
2976          *
2977          * @param $text String
2978          */
2979         public function preSaveTransform( $text ) {
2980                 global $wgParser, $wgUser;
2981                 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2982         }
2983
2984         /* Caching functions */
2985
2986         /**
2987          * checkLastModified returns true if it has taken care of all
2988          * output to the client that is necessary for this request.
2989          * (that is, it has sent a cached version of the page)
2990          */
2991         protected function tryFileCache() {
2992                 static $called = false;
2993                 if( $called ) {
2994                         wfDebug( "Article::tryFileCache(): called twice!?\n" );
2995                         return false;
2996                 }
2997                 $called = true;
2998                 if( $this->isFileCacheable() ) {
2999                         $cache = new HTMLFileCache( $this->mTitle );
3000                         if( $cache->isFileCacheGood( $this->mTouched ) ) {
3001                                 wfDebug( "Article::tryFileCache(): about to load file\n" );
3002                                 $cache->loadFromFileCache();
3003                                 return true;
3004                         } else {
3005                                 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3006                                 ob_start( array(&$cache, 'saveToFileCache' ) );
3007                         }
3008                 } else {
3009                         wfDebug( "Article::tryFileCache(): not cacheable\n" );
3010                 }
3011                 return false;
3012         }
3013
3014         /**
3015          * Check if the page can be cached
3016          * @return bool
3017          */
3018         public function isFileCacheable() {
3019                 $cacheable = false;
3020                 if( HTMLFileCache::useFileCache() ) {
3021                         $cacheable = $this->getID() && !$this->mRedirectedFrom;
3022                         // Extension may have reason to disable file caching on some pages.
3023                         if( $cacheable ) {
3024                                 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3025                         }
3026                 }
3027                 return $cacheable;
3028         }
3029
3030         /**
3031          * Loads page_touched and returns a value indicating if it should be used
3032          *
3033          */
3034         public function checkTouched() {
3035                 if( !$this->mDataLoaded ) {
3036                         $this->loadPageData();
3037                 }
3038                 return !$this->mIsRedirect;
3039         }
3040
3041         /**
3042          * Get the page_touched field
3043          */
3044         public function getTouched() {
3045                 # Ensure that page data has been loaded
3046                 if( !$this->mDataLoaded ) {
3047                         $this->loadPageData();
3048                 }
3049                 return $this->mTouched;
3050         }
3051
3052         /**
3053          * Get the page_latest field
3054          */
3055         public function getLatest() {
3056                 if( !$this->mDataLoaded ) {
3057                         $this->loadPageData();
3058                 }
3059                 return $this->mLatest;
3060         }
3061
3062         /**
3063          * Edit an article without doing all that other stuff
3064          * The article must already exist; link tables etc
3065          * are not updated, caches are not flushed.
3066          *
3067          * @param $text String: text submitted
3068          * @param $comment String: comment submitted
3069          * @param $minor Boolean: whereas it's a minor modification
3070          */
3071         public function quickEdit( $text, $comment = '', $minor = 0 ) {
3072                 wfProfileIn( __METHOD__ );
3073
3074                 $dbw = wfGetDB( DB_MASTER );
3075                 $revision = new Revision( array(
3076                         'page'       => $this->getId(),
3077                         'text'       => $text,
3078                         'comment'    => $comment,
3079                         'minor_edit' => $minor ? 1 : 0,
3080                         ) );
3081                 $revision->insertOn( $dbw );
3082                 $this->updateRevisionOn( $dbw, $revision );
3083
3084                 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3085
3086                 wfProfileOut( __METHOD__ );
3087         }
3088
3089         /**
3090          * Used to increment the view counter
3091          *
3092          * @param $id Integer: article id
3093          */
3094         public static function incViewCount( $id ) {
3095                 $id = intval( $id );
3096                 global $wgHitcounterUpdateFreq, $wgDBtype;
3097
3098                 $dbw = wfGetDB( DB_MASTER );
3099                 $pageTable = $dbw->tableName( 'page' );
3100                 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3101                 $acchitsTable = $dbw->tableName( 'acchits' );
3102
3103                 if( $wgHitcounterUpdateFreq <= 1 ) {
3104                         $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3105                         return;
3106                 }
3107
3108                 # Not important enough to warrant an error page in case of failure
3109                 $oldignore = $dbw->ignoreErrors( true );
3110
3111                 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3112
3113                 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3114                 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3115                         # Most of the time (or on SQL errors), skip row count check
3116                         $dbw->ignoreErrors( $oldignore );
3117                         return;
3118                 }
3119
3120                 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3121                 $row = $dbw->fetchObject( $res );
3122                 $rown = intval( $row->n );
3123                 if( $rown >= $wgHitcounterUpdateFreq ){
3124                         wfProfileIn( 'Article::incViewCount-collect' );
3125                         $old_user_abort = ignore_user_abort( true );
3126
3127                         if($wgDBtype == 'mysql')
3128                                 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3129                         $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3130                         $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3131                                 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3132                                 'GROUP BY hc_id');
3133                         $dbw->query("DELETE FROM $hitcounterTable");
3134                         if($wgDBtype == 'mysql') {
3135                                 $dbw->query('UNLOCK TABLES');
3136                                 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3137                                         'WHERE page_id = hc_id');
3138                         }
3139                         else {
3140                                 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3141                                         "FROM $acchitsTable WHERE page_id = hc_id");
3142                         }
3143                         $dbw->query("DROP TABLE $acchitsTable");
3144
3145                         ignore_user_abort( $old_user_abort );
3146                         wfProfileOut( 'Article::incViewCount-collect' );
3147                 }
3148                 $dbw->ignoreErrors( $oldignore );
3149         }
3150
3151         /**#@+
3152          * The onArticle*() functions are supposed to be a kind of hooks
3153          * which should be called whenever any of the specified actions
3154          * are done.
3155          *
3156          * This is a good place to put code to clear caches, for instance.
3157          *
3158          * This is called on page move and undelete, as well as edit
3159          *
3160          * @param $title a title object
3161          */
3162
3163         public static function onArticleCreate( $title ) {
3164                 # Update existence markers on article/talk tabs...
3165                 if( $title->isTalkPage() ) {
3166                         $other = $title->getSubjectPage();
3167                 } else {
3168                         $other = $title->getTalkPage();
3169                 }
3170                 $other->invalidateCache();
3171                 $other->purgeSquid();
3172
3173                 $title->touchLinks();
3174                 $title->purgeSquid();
3175                 $title->deleteTitleProtection();
3176         }
3177
3178         public static function onArticleDelete( $title ) {
3179                 global $wgMessageCache;
3180                 # Update existence markers on article/talk tabs...
3181                 if( $title->isTalkPage() ) {
3182                         $other = $title->getSubjectPage();
3183                 } else {
3184                         $other = $title->getTalkPage();
3185                 }
3186                 $other->invalidateCache();
3187                 $other->purgeSquid();
3188
3189                 $title->touchLinks();
3190                 $title->purgeSquid();
3191
3192                 # File cache
3193                 HTMLFileCache::clearFileCache( $title );
3194
3195                 # Messages
3196                 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3197                         $wgMessageCache->replace( $title->getDBkey(), false );
3198                 }
3199                 # Images
3200                 if( $title->getNamespace() == NS_FILE ) {
3201                         $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3202                         $update->doUpdate();
3203                 }
3204                 # User talk pages
3205                 if( $title->getNamespace() == NS_USER_TALK ) {
3206                         $user = User::newFromName( $title->getText(), false );
3207                         $user->setNewtalk( false );
3208                 }
3209         }
3210
3211         /**
3212          * Purge caches on page update etc
3213          */
3214         public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3215                 global $wgDeferredUpdateList;
3216
3217                 // Invalidate caches of articles which include this page
3218                 if( $transclusions !== 'skiptransclusions' )
3219                         $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3220
3221                 // Invalidate the caches of all pages which redirect here
3222                 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3223
3224                 # Purge squid for this page only
3225                 $title->purgeSquid();
3226
3227                 # Clear file cache for this page only
3228                 HTMLFileCache::clearFileCache( $title );
3229         }
3230
3231         /**#@-*/
3232
3233         /**
3234          * Overriden by ImagePage class, only present here to avoid a fatal error
3235          * Called for ?action=revert
3236          */
3237         public function revert() {
3238                 global $wgOut;
3239                 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3240         }
3241
3242         /**
3243          * Info about this page
3244          * Called for ?action=info when $wgAllowPageInfo is on.
3245          */
3246         public function info() {
3247                 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3248
3249                 if( !$wgAllowPageInfo ) {
3250                         $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3251                         return;
3252                 }
3253
3254                 $page = $this->mTitle->getSubjectPage();
3255
3256                 $wgOut->setPagetitle( $page->getPrefixedText() );
3257                 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3258                 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3259
3260                 if( !$this->mTitle->exists() ) {
3261                         $wgOut->addHTML( '<div class="noarticletext">' );
3262                         if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3263                                 // This doesn't quite make sense; the user is asking for
3264                                 // information about the _page_, not the message... -- RC
3265                                 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3266                         } else {
3267                                 $msg = $wgUser->isLoggedIn()
3268                                         ? 'noarticletext'
3269                                         : 'noarticletextanon';
3270                                 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3271                         }
3272                         $wgOut->addHTML( '</div>' );
3273                 } else {
3274                         $dbr = wfGetDB( DB_SLAVE );
3275                         $wl_clause = array(
3276                                 'wl_title'     => $page->getDBkey(),
3277                                 'wl_namespace' => $page->getNamespace() );
3278                         $numwatchers = $dbr->selectField(
3279                                 'watchlist',
3280                                 'COUNT(*)',
3281                                 $wl_clause,
3282                                 __METHOD__,
3283                                 $this->getSelectOptions() );
3284
3285                         $pageInfo = $this->pageCountInfo( $page );
3286                         $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3287
3288                         $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3289                         $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3290                         if( $talkInfo ) {
3291                                 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3292                         }
3293                         $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3294                         if( $talkInfo ) {
3295                                 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3296                         }
3297                         $wgOut->addHTML( '</ul>' );
3298                 }
3299         }
3300
3301         /**
3302          * Return the total number of edits and number of unique editors
3303          * on a given page. If page does not exist, returns false.
3304          *
3305          * @param $title Title object
3306          * @return array
3307          */
3308         protected function pageCountInfo( $title ) {
3309                 $id = $title->getArticleId();
3310                 if( $id == 0 ) {
3311                         return false;
3312                 }
3313                 $dbr = wfGetDB( DB_SLAVE );
3314                 $rev_clause = array( 'rev_page' => $id );
3315                 $edits = $dbr->selectField(
3316                         'revision',
3317                         'COUNT(rev_page)',
3318                         $rev_clause,
3319                         __METHOD__,
3320                         $this->getSelectOptions()
3321                 );
3322                 $authors = $dbr->selectField(
3323                         'revision',
3324                         'COUNT(DISTINCT rev_user_text)',
3325                         $rev_clause,
3326                         __METHOD__,
3327                         $this->getSelectOptions()
3328                 );
3329                 return array( 'edits' => $edits, 'authors' => $authors );
3330         }
3331
3332         /**
3333          * Return a list of templates used by this article.
3334          * Uses the templatelinks table
3335          *
3336          * @return Array of Title objects
3337          */
3338         public function getUsedTemplates() {
3339                 $result = array();
3340                 $id = $this->mTitle->getArticleID();
3341                 if( $id == 0 ) {
3342                         return array();
3343                 }
3344                 $dbr = wfGetDB( DB_SLAVE );
3345                 $res = $dbr->select( array( 'templatelinks' ),
3346                         array( 'tl_namespace', 'tl_title' ),
3347                         array( 'tl_from' => $id ),
3348                         __METHOD__ );
3349                 if( $res !== false ) {
3350                         foreach( $res as $row ) {
3351                                 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3352                         }
3353                 }
3354                 $dbr->freeResult( $res );
3355                 return $result;
3356         }
3357
3358         /**
3359          * Returns a list of hidden categories this page is a member of.
3360          * Uses the page_props and categorylinks tables.
3361          *
3362          * @return Array of Title objects
3363          */
3364         public function getHiddenCategories() {
3365                 $result = array();
3366                 $id = $this->mTitle->getArticleID();
3367                 if( $id == 0 ) {
3368                         return array();
3369                 }
3370                 $dbr = wfGetDB( DB_SLAVE );
3371                 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3372                         array( 'cl_to' ),
3373                         array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3374                                 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3375                         __METHOD__ );
3376                 if( $res !== false ) {
3377                         foreach( $res as $row ) {
3378                                 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3379                         }
3380                 }
3381                 $dbr->freeResult( $res );
3382                 return $result;
3383         }
3384
3385         /**
3386         * Return an applicable autosummary if one exists for the given edit.
3387         * @param $oldtext String: the previous text of the page.
3388         * @param $newtext String: The submitted text of the page.
3389         * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3390         * @return string An appropriate autosummary, or an empty string.
3391         */
3392         public static function getAutosummary( $oldtext, $newtext, $flags ) {
3393                 # Decide what kind of autosummary is needed.
3394
3395                 # Redirect autosummaries
3396                 $ot = Title::newFromRedirect( $oldtext );
3397                 $rt = Title::newFromRedirect( $newtext );
3398                 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3399                         return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3400                 }
3401
3402                 # New page autosummaries
3403                 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3404                         # If they're making a new article, give its text, truncated, in the summary.
3405                         global $wgContLang;
3406                         $truncatedtext = $wgContLang->truncate(
3407                                 str_replace("\n", ' ', $newtext),
3408                                 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3409                                 '...' );
3410                         return wfMsgForContent( 'autosumm-new', $truncatedtext );
3411                 }
3412
3413                 # Blanking autosummaries
3414                 if( $oldtext != '' && $newtext == '' ) {
3415                         return wfMsgForContent( 'autosumm-blank' );
3416                 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3417                         # Removing more than 90% of the article
3418                         global $wgContLang;
3419                         $truncatedtext = $wgContLang->truncate(
3420                                 $newtext,
3421                                 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3422                                 '...'
3423                         );
3424                         return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3425                 }
3426
3427                 # If we reach this point, there's no applicable autosummary for our case, so our
3428                 # autosummary is empty.
3429                 return '';
3430         }
3431
3432         /**
3433          * Add the primary page-view wikitext to the output buffer
3434          * Saves the text into the parser cache if possible.
3435          * Updates templatelinks if it is out of date.
3436          *
3437          * @param $text String
3438          * @param $cache Boolean
3439          */
3440         public function outputWikiText( $text, $cache = true ) {
3441                 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3442
3443                 $popts = $wgOut->parserOptions();
3444                 $popts->setTidy(true);
3445                 $popts->enableLimitReport();
3446                 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3447                         $popts, true, true, $this->getRevIdFetched() );
3448                 $popts->setTidy(false);
3449                 $popts->enableLimitReport( false );
3450                 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3451                         $parserCache = ParserCache::singleton();
3452                         $parserCache->save( $parserOutput, $this, $wgUser );
3453                 }
3454                 // Make sure file cache is not used on uncacheable content.
3455                 // Output that has magic words in it can still use the parser cache
3456                 // (if enabled), though it will generally expire sooner.
3457                 if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
3458                         $wgUseFileCache = false;
3459                 }
3460
3461                 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3462                         // templatelinks table may have become out of sync,
3463                         // especially if using variable-based transclusions.
3464                         // For paranoia, check if things have changed and if
3465                         // so apply updates to the database. This will ensure
3466                         // that cascaded protections apply as soon as the changes
3467                         // are visible.
3468
3469                         # Get templates from templatelinks
3470                         $id = $this->mTitle->getArticleID();
3471
3472                         $tlTemplates = array();
3473
3474                         $dbr = wfGetDB( DB_SLAVE );
3475                         $res = $dbr->select( array( 'templatelinks' ),
3476                                 array( 'tl_namespace', 'tl_title' ),
3477                                 array( 'tl_from' => $id ),
3478                                 __METHOD__ );
3479
3480                         global $wgContLang;
3481
3482                         if( $res !== false ) {
3483                                 foreach( $res as $row ) {
3484                                         $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3485                                 }
3486                         }
3487
3488                         # Get templates from parser output.
3489                         $poTemplates_allns = $parserOutput->getTemplates();
3490
3491                         $poTemplates = array ();
3492                         foreach ( $poTemplates_allns as $ns_templates ) {
3493                                 $poTemplates = array_merge( $poTemplates, $ns_templates );
3494                         }
3495
3496                         # Get the diff
3497                         $templates_diff = array_diff( $poTemplates, $tlTemplates );
3498
3499                         if( count( $templates_diff ) > 0 ) {
3500                                 # Whee, link updates time.
3501                                 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3502                                 $u->doUpdate();
3503                         }
3504                 }
3505
3506                 $wgOut->addParserOutput( $parserOutput );
3507         }
3508
3509         /**
3510          * Update all the appropriate counts in the category table, given that
3511          * we've added the categories $added and deleted the categories $deleted.
3512          *
3513          * @param $added array   The names of categories that were added
3514          * @param $deleted array The names of categories that were deleted
3515          * @return null
3516          */
3517         public function updateCategoryCounts( $added, $deleted ) {
3518                 $ns = $this->mTitle->getNamespace();
3519                 $dbw = wfGetDB( DB_MASTER );
3520
3521                 # First make sure the rows exist.  If one of the "deleted" ones didn't
3522                 # exist, we might legitimately not create it, but it's simpler to just
3523                 # create it and then give it a negative value, since the value is bogus
3524                 # anyway.
3525                 #
3526                 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3527                 $insertCats = array_merge( $added, $deleted );
3528                 if( !$insertCats ) {
3529                         # Okay, nothing to do
3530                         return;
3531                 }
3532                 $insertRows = array();
3533                 foreach( $insertCats as $cat ) {
3534                         $insertRows[] = array( 'cat_title' => $cat );
3535                 }
3536                 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3537
3538                 $addFields    = array( 'cat_pages = cat_pages + 1' );
3539                 $removeFields = array( 'cat_pages = cat_pages - 1' );
3540                 if( $ns == NS_CATEGORY ) {
3541                         $addFields[]    = 'cat_subcats = cat_subcats + 1';
3542                         $removeFields[] = 'cat_subcats = cat_subcats - 1';
3543                 } elseif( $ns == NS_FILE ) {
3544                         $addFields[]    = 'cat_files = cat_files + 1';
3545                         $removeFields[] = 'cat_files = cat_files - 1';
3546                 }
3547
3548                 if( $added ) {
3549                         $dbw->update(
3550                                 'category',
3551                                 $addFields,
3552                                 array( 'cat_title' => $added ),
3553                                 __METHOD__
3554                         );
3555                 }
3556                 if( $deleted ) {
3557                         $dbw->update(
3558                                 'category',
3559                                 $removeFields,
3560                                 array( 'cat_title' => $deleted ),
3561                                 __METHOD__
3562                         );
3563                 }
3564         }
3565 }