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