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