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