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