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