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