Remove unused parameter
[mediawiki.git] / includes / Article.php
blob1b4bcce954455842949f3ddf1b536847ae2cd9b9
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
7 /**
8 * Class representing a MediaWiki article and history.
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.
15 class Article {
16 /**@{{
17 * @private
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 /**@}}*/
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
50 public function __construct( Title $title, $oldId = null ) {
51 $this->mTitle =& $title;
52 $this->mOldId = $oldId;
55 /**
56 * Constructor from an article article
57 * @param $id The article ID to load
59 public static function newFromID( $id ) {
60 $t = Title::newFromID( $id );
61 return $t == null ? null : new Article( $t );
64 /**
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
69 public function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom = $from;
73 /**
74 * If this page is a redirect, get its target
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
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__
92 if( $row = $dbr->fetchObject($res) ) {
93 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
95 # This page doesn't have an entry in the redirect table
96 return $this->mRedirectTarget = $this->insertRedirect();
99 /**
100 * Insert an entry for this page into the redirect table.
102 * Don't call this function directly unless you know what you're doing.
103 * @return Title object
105 public function insertRedirect() {
106 $retval = Title::newFromRedirect( $this->getContent() );
107 if( !$retval ) {
108 return null;
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()
117 __METHOD__
119 return $retval;
123 * Get the Title object this page redirects to
125 * @return mixed false, Title of in-wiki target, or string with URL
127 public function followRedirect() {
128 $text = $this->getContent();
129 return $this->followRedirectText( $text );
133 * Get the Title object this text redirects to
135 * @return mixed false, Title of in-wiki target, or string with URL
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.
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 ) );
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.
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();
163 return $rt;
166 // No or invalid redirect
167 return false;
171 * get the title object of the article
173 public function getTitle() {
174 return $this->mTitle;
178 * Clear the object
179 * @private
181 public function clear() {
182 $this->mDataLoaded = false;
183 $this->mContentLoaded = false;
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;
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()
205 * @return Return the text of this revision
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' );
223 wfProfileOut( __METHOD__ );
224 return $text;
225 } else {
226 $this->loadContent();
227 wfProfileOut( __METHOD__ );
228 return $this->mContent;
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).
237 * If a section contains subsections, these are also returned.
239 * @param $text String: text to look in
240 * @param $section Integer: section number
241 * @return string text of the requested section
242 * @deprecated
244 public function getSection( $text, $section ) {
245 global $wgParser;
246 return $wgParser->getSection( $text, $section );
250 * @return int The oldid of the article that is to be shown, 0 for the
251 * current revision
253 public function getOldID() {
254 if( is_null( $this->mOldId ) ) {
255 $this->mOldId = $this->getOldIDFromRequest();
257 return $this->mOldId;
261 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
263 * @return int The old id for the request
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' );
278 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
279 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
280 if( $previd ) {
281 $oldid = $previd;
285 if( !$oldid ) {
286 $oldid = 0;
288 return $oldid;
292 * Load the revision (including text) into this object
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__ );
308 * Fetch a page record with the given conditions
309 * @param $dbr Database object
310 * @param $conditions Array
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',
326 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
327 $row = $dbr->selectRow(
328 'page',
329 $fields,
330 $conditions,
331 __METHOD__
333 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
334 return $row ;
338 * @param $dbr Database object
339 * @param $title Title object
341 public function pageDataFromTitle( $dbr, $title ) {
342 return $this->pageData( $dbr, array(
343 'page_namespace' => $title->getNamespace(),
344 'page_title' => $title->getDBkey() ) );
348 * @param $dbr Database
349 * @param $id Integer
351 protected function pageDataFromId( $dbr, $id ) {
352 return $this->pageData( $dbr, array( 'page_id' => $id ) );
356 * Set the general counter, title etc data loaded from
357 * some source.
359 * @param $data Database row object or "fromdb"
361 public function loadPageData( $data = 'fromdb' ) {
362 if( $data === 'fromdb' ) {
363 $dbr = wfGetDB( DB_MASTER );
364 $data = $this->pageDataFromId( $dbr, $this->getId() );
367 $lc = LinkCache::singleton();
368 if( $data ) {
369 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
371 $this->mTitle->mArticleID = $data->page_id;
373 # Old-fashioned restrictions
374 $this->mTitle->loadRestrictions( $data->page_restrictions );
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 );
384 $this->mTitle->mArticleID = 0;
387 $this->mDataLoaded = true;
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
396 function fetchContent( $oldid = 0 ) {
397 if( $this->mContentLoaded ) {
398 return $this->mContent;
401 $dbr = wfGetDB( DB_MASTER );
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 ) ;
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;
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;
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;
429 $this->loadPageData( $data );
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;
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
442 $this->mUser = $revision->getUser();
443 $this->mUserText = $revision->getUserText();
444 $this->mComment = $revision->getComment();
445 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
447 $this->mRevIdFetched = $revision->getId();
448 $this->mContentLoaded = true;
449 $this->mRevision =& $revision;
451 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
453 return $this->mContent;
457 * Read/write accessor to select FOR UPDATE
459 * @param $x Mixed: FIXME
461 public function forUpdate( $x = NULL ) {
462 return wfSetVar( $this->mForUpdate, $x );
466 * Get the database which should be used for reads
468 * @return Database
469 * @deprecated - just call wfGetDB( DB_MASTER ) instead
471 function getDB() {
472 wfDeprecated( __METHOD__ );
473 return wfGetDB( DB_MASTER );
477 * Get options for all SELECT statements
479 * @param $options Array: an optional options array which'll be appended to
480 * the default
481 * @return Array: options
483 protected function getSelectOptions( $options = '' ) {
484 if( $this->mForUpdate ) {
485 if( is_array( $options ) ) {
486 $options[] = 'FOR UPDATE';
487 } else {
488 $options = 'FOR UPDATE';
491 return $options;
495 * @return int Page ID
497 public function getID() {
498 if( $this->mTitle ) {
499 return $this->mTitle->getArticleID();
500 } else {
501 return 0;
506 * @return bool Whether or not the page exists in the database
508 public function exists() {
509 return $this->getId() > 0;
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.
518 * @return bool
520 public function hasViewableContent() {
521 return $this->exists() || $this->mTitle->isAlwaysKnown();
525 * @return int The view count for the page
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()
542 return $this->mCounter;
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
549 * @param $text String: text to analyze
550 * @return bool
552 public function isCountable( $text ) {
553 global $wgUseCommaCount;
555 $token = $wgUseCommaCount ? ',' : '[[';
556 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
560 * Tests if the article text represents a redirect
562 * @param $text String: FIXME
563 * @return bool
565 public function isRedirect( $text = false ) {
566 if( $text === false ) {
567 if( $this->mDataLoaded ) {
568 return $this->mIsRedirect;
570 // Apparently loadPageData was never called
571 $this->loadContent();
572 $titleObj = Title::newFromRedirect( $this->fetchContent() );
573 } else {
574 $titleObj = Title::newFromRedirect( $text );
576 return $titleObj !== NULL;
580 * Returns true if the currently-referenced revision is the current edit
581 * to this page (and it exists).
582 * @return bool
584 public function isCurrent() {
585 # If no oldid, this is the current version.
586 if( $this->getOldID() == 0 ) {
587 return true;
589 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
593 * Loads everything except the text
594 * This isn't necessary for all uses, so it's only done if needed.
596 protected function loadLastEdit() {
597 if( -1 != $this->mUser )
598 return;
600 # New or non-existent articles have no user information
601 $id = $this->getID();
602 if( 0 == $id ) return;
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();
615 public function getTimestamp() {
616 // Check if the field has been filled by ParserCache::get()
617 if( !$this->mTimestamp ) {
618 $this->loadLastEdit();
620 return wfTimestamp(TS_MW, $this->mTimestamp);
623 public function getUser() {
624 $this->loadLastEdit();
625 return $this->mUser;
628 public function getUserText() {
629 $this->loadLastEdit();
630 return $this->mUserText;
633 public function getComment() {
634 $this->loadLastEdit();
635 return $this->mComment;
638 public function getMinorEdit() {
639 $this->loadLastEdit();
640 return $this->mMinorEdit;
643 /* Use this to fetch the rev ID used on page views */
644 public function getRevIdFetched() {
645 $this->loadLastEdit();
646 return $this->mRevIdFetched;
650 * @param $limit Integer: default 0.
651 * @param $offset Integer: default 0.
653 public function getContributors($limit = 0, $offset = 0) {
654 # XXX: this is expensive; cache this info somewhere.
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();
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";
670 if($limit > 0) { $sql .= ' LIMIT '.$limit; }
671 if($offset > 0) { $sql .= ' OFFSET '.$offset; }
673 $sql .= ' '. $this->getSelectOptions();
675 $res = $dbr->query($sql, __METHOD__ );
677 return new UserArrayFromResult( $res );
681 * This is the default action of the script: just view the page of
682 * the given title.
684 public function view() {
685 global $wgUser, $wgOut, $wgRequest, $wgContLang;
686 global $wgEnableParserCache, $wgStylePath, $wgParser;
687 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
688 global $wgDefaultRobotPolicy;
690 wfProfileIn( __METHOD__ );
692 # Get variables from query string
693 $oldid = $this->getOldID();
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) );
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;
714 $ns = $this->mTitle->getNamespace(); # shortcut
715 $sk = $wgUser->getSkin();
717 # getOldID may want us to redirect somewhere else
718 if( $this->mRedirectUrl ) {
719 $wgOut->redirect( $this->mRedirectUrl );
720 wfProfileOut( __METHOD__ );
721 return;
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;
731 $wgOut->setArticleFlag( true );
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;
744 $wgOut->setRobotPolicy( $policy );
746 # If we got diff and oldid in the query, we want to see a
747 # diff page instead of the article.
749 if( !is_null( $diff ) ) {
750 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
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 );
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();
765 wfProfileOut( __METHOD__ );
766 return;
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' );
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 );
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\");" );
790 $wasRedirected = true;
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;
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;
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();
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' );
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;
841 if( $return404 ) {
842 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
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;
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...
874 $wgOut->setRevisionId( $this->getRevIdFetched() );
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" );
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 );
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();
908 # Timing hack
909 if( $time > 3 ) {
910 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
911 $this->mTitle->getPrefixedDBkey()));
914 if( !$this->isCurrent() ) {
915 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
919 /* title may have been set from the cache */
920 $t = $wgOut->getPageTitle();
921 if( empty( $t ) ) {
922 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
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' ) );
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');
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" )
947 '</div>'
951 # Trackbacks
952 if( $wgUseTrackbacks ) {
953 $this->addTrackbacks();
956 $this->viewUpdates();
957 wfProfileOut( __METHOD__ );
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()
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 ) );
981 $wgOut->addHTML( '</div>' );
986 * Should the parser cache be used?
988 protected function useParserCache( $oldid ) {
989 global $wgUser, $wgEnableParserCache;
991 return $wgEnableParserCache
992 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
993 && $this->exists()
994 && empty( $oldid )
995 && !$this->mTitle->isCssOrJsPage()
996 && !$this->mTitle->isCssJsSubpage();
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?
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';
1011 if( $appendSubtitle ) {
1012 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
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() ) );
1020 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1021 '<span class="redirectText">'.$link.'</span>';
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() )
1032 if( !$dbr->numRows($tbs) ) return;
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 ) );
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);
1050 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
1051 $this->mTitle->invalidateCache();
1054 public function deletetrackback() {
1055 global $wgUser, $wgRequest, $wgOut, $wgTitle;
1056 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1057 $wgOut->addWikiMsg( 'sessionfailure' );
1058 return;
1061 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1062 if( count($permission_errors) ) {
1063 $wgOut->showPermissionsErrorPage( $permission_errors );
1064 return;
1067 $db = wfGetDB( DB_MASTER );
1068 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1070 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1071 $this->mTitle->invalidateCache();
1074 public function render() {
1075 global $wgOut;
1076 $wgOut->setArticleBodyOnly(true);
1077 $this->view();
1081 * Handle action=purge
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();
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 );
1105 * Perform the actions of a page purging
1107 public function doPurge() {
1108 global $wgUseSquid;
1109 // Invalidate the cache
1110 $this->mTitle->invalidateCache();
1112 if( $wgUseSquid ) {
1113 // Commit the transaction before the purge is sent
1114 $dbw = wfGetDB( DB_MASTER );
1115 $dbw->immediateCommit();
1117 // Send purge
1118 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1119 $update->doUpdate();
1121 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1122 global $wgMessageCache;
1123 if( $this->getID() == 0 ) {
1124 $text = false;
1125 } else {
1126 $text = $this->getContent();
1128 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
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.
1139 * @param $dbw Database
1140 * @return int The newly created page_id key, or false if the title already existed
1141 * @private
1143 public function insertOn( $dbw ) {
1144 wfProfileIn( __METHOD__ );
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' );
1161 $affected = $dbw->affectedRows();
1162 if( $affected ) {
1163 $newid = $dbw->insertId();
1164 $this->mTitle->resetArticleId( $newid );
1166 wfProfileOut( __METHOD__ );
1167 return $affected ? $newid : false;
1171 * Update the page record to point to a newly saved revision.
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
1185 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1186 wfProfileIn( __METHOD__ );
1188 $text = $revision->getText();
1189 $rt = Title::newFromRedirect( $text );
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;
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 ),
1205 $conditions,
1206 __METHOD__ );
1208 $result = $dbw->affectedRows() != 0;
1209 if( $result ) {
1210 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1213 wfProfileOut( __METHOD__ );
1214 return $result;
1218 * Add row to the redirect table if this is a redirect, remove otherwise.
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
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(),
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__);
1248 if( $this->getTitle()->getNamespace() == NS_FILE ) {
1249 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1251 wfProfileOut( __METHOD__ );
1252 return ( $dbw->affectedRows() != 0 );
1254 return true;
1258 * If the given revision is newer than the currently set page_latest,
1259 * update the page record. Otherwise, do nothing.
1261 * @param $dbw Database object
1262 * @param $revision Revision object
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;
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;
1285 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1286 wfProfileOut( __METHOD__ );
1287 return $ret;
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
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 );
1305 if( !$rev ) {
1306 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1307 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1308 return null;
1310 $oldtext = $rev->getText();
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 );
1324 wfProfileOut( __METHOD__ );
1325 return $text;
1329 * @deprecated use Article::doEdit()
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 );
1338 # If this is a comment, add the summary as headline
1339 if( $comment && $summary != "" ) {
1340 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1343 $this->doEdit( $text, $summary, $flags );
1345 $dbw = wfGetDB( DB_MASTER );
1346 if($watchthis) {
1347 if(!$this->mTitle->userIsWatching()) {
1348 $dbw->begin();
1349 $this->doWatch();
1350 $dbw->commit();
1352 } else {
1353 if( $this->mTitle->userIsWatching() ) {
1354 $dbw->begin();
1355 $this->doUnwatch();
1356 $dbw->commit();
1359 $this->doRedirect( $this->isRedirect( $text ) );
1363 * @deprecated use Article::doEdit()
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 );
1371 $status = $this->doEdit( $text, $summary, $flags );
1372 if( !$status->isOK() ) {
1373 return false;
1376 $dbw = wfGetDB( DB_MASTER );
1377 if( $watchthis ) {
1378 if(!$this->mTitle->userIsWatching()) {
1379 $dbw->begin();
1380 $this->doWatch();
1381 $dbw->commit();
1383 } else {
1384 if( $this->mTitle->userIsWatching() ) {
1385 $dbw->begin();
1386 $this->doUnwatch();
1387 $dbw->commit();
1391 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1392 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1394 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1395 return true;
1399 * Article::doEdit()
1401 * Change an existing article or create a new article. Updates RC and all necessary caches,
1402 * optionally via the deferred update array.
1404 * $wgUser must be set before calling this function.
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
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.
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
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
1440 * Extensions may define additional errors.
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
1446 * Compatibility note: this function previously returned a boolean value indicating success/failure
1448 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1449 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
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' );
1456 wfProfileIn( __METHOD__ );
1458 $user = is_null($user) ? $wgUser : $user;
1459 $status = Status::newGood( array() );
1461 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1462 $this->loadPageData();
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;
1473 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1474 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1476 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1477 wfProfileOut( __METHOD__ );
1478 if( $status->isOK() ) {
1479 $status->fatal( 'edit-hook-aborted');
1481 return $status;
1484 # Silently ignore EDIT_MINOR if not allowed
1485 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1486 $bot = $flags & EDIT_FORCE_BOT;
1488 $oldtext = $this->getContent();
1489 $oldsize = strlen( $oldtext );
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 );
1496 $editInfo = $this->prepareTextForEdit( $text );
1497 $text = $editInfo->pst;
1498 $newsize = strlen( $text );
1500 $dbw = wfGetDB( DB_MASTER );
1501 $now = wfTimestampNow();
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 );
1511 $revisionId = 0;
1513 $changed = ( strcmp( $text, $oldtext ) != 0 );
1515 if( $changed ) {
1516 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1517 - (int)$this->isCountable( $oldtext );
1518 $this->mTotalAdjustment = 0;
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;
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 ) );
1538 $dbw->begin();
1539 $revisionId = $revision->insertOn( $dbw );
1541 # Update page
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 );
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__ );
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
1571 # Log auto-patrolled edits
1572 if( $patrolled ) {
1573 PatrolLog::record( $rc, true );
1576 $user->incEditCount();
1577 $dbw->commit();
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();
1589 if( !$wgDBtransactions ) {
1590 ignore_user_abort( $userAbort );
1592 // Now that ignore_user_abort is restored, we can respond to fatal errors
1593 if( !$status->isOK() ) {
1594 wfProfileOut( __METHOD__ );
1595 return $status;
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;
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;
1613 $dbw->begin();
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 );
1619 if( $newid === false ) {
1620 $dbw->rollback();
1621 $status->fatal( 'edit-already-exists' );
1622 wfProfileOut( __METHOD__ );
1623 return $status;
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 );
1637 $this->mTitle->resetArticleID( $newid );
1639 # Update the page record with revision data
1640 $this->updateRevisionOn( $dbw, $revision, 0 );
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 );
1656 $user->incEditCount();
1657 $dbw->commit();
1659 # Update links, etc.
1660 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1662 # Clear caches
1663 Article::onArticleCreate( $this->mTitle );
1665 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1666 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1669 # Do updates right now unless deferral was requested
1670 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
1671 wfDoUpdates();
1674 // Return the new revision (or null) to the caller
1675 $status->value['revision'] = $revision;
1677 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1678 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status ) );
1680 wfProfileOut( __METHOD__ );
1681 return $status;
1685 * @deprecated wrapper for doRedirect
1687 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1688 wfDeprecated( __METHOD__ );
1689 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1693 * Output a redirect back to the article.
1694 * This is typically used after an edit.
1696 * @param $noRedir Boolean: add redirect=no
1697 * @param $sectionAnchor String: section to redirect to, including "#"
1698 * @param $extraQuery String: extra query params
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;
1709 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1713 * Mark this particular edit/page as patrolled
1715 public function markpatrolled() {
1716 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1717 $wgOut->setRobotPolicy( 'noindex,nofollow' );
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;
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 );
1731 $dbw = wfGetDB( DB_MASTER );
1732 $errors = $rc->doMarkPatrolled();
1734 if( in_array(array('rcpatroldisabled'), $errors) ) {
1735 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1736 return;
1739 if( in_array(array('hookaborted'), $errors) ) {
1740 // The hook itself has handled any output
1741 return;
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;
1751 if( !empty($errors) ) {
1752 $wgOut->showPermissionsErrorPage( $errors );
1753 return;
1756 # Inform the user
1757 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1758 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1759 $wgOut->returnToMain( false, $return );
1763 * User-interface handler for the "watch" action
1766 public function watch() {
1767 global $wgUser, $wgOut;
1768 if( $wgUser->isAnon() ) {
1769 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1770 return;
1772 if( wfReadOnly() ) {
1773 $wgOut->readOnlyPage();
1774 return;
1776 if( $this->doWatch() ) {
1777 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1778 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1779 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1781 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1785 * Add this page to $wgUser's watchlist
1786 * @return bool true on successful watch operation
1788 public function doWatch() {
1789 global $wgUser;
1790 if( $wgUser->isAnon() ) {
1791 return false;
1793 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
1794 $wgUser->addWatch( $this->mTitle );
1795 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1797 return false;
1801 * User interface handler for the "unwatch" action.
1803 public function unwatch() {
1804 global $wgUser, $wgOut;
1805 if( $wgUser->isAnon() ) {
1806 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1807 return;
1809 if( wfReadOnly() ) {
1810 $wgOut->readOnlyPage();
1811 return;
1813 if( $this->doUnwatch() ) {
1814 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1815 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1816 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1818 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1822 * Stop watching a page
1823 * @return bool true on successful unwatch
1825 public function doUnwatch() {
1826 global $wgUser;
1827 if( $wgUser->isAnon() ) {
1828 return false;
1830 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
1831 $wgUser->removeWatch( $this->mTitle );
1832 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1834 return false;
1838 * action=protect handler
1840 public function protect() {
1841 $form = new ProtectionForm( $this );
1842 $form->execute();
1846 * action=unprotect handler (alias)
1848 public function unprotect() {
1849 $this->protect();
1853 * Update the article's restriction field, and leave a log entry.
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
1861 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1862 global $wgUser, $wgRestrictionTypes, $wgContLang;
1864 $id = $this->mTitle->getArticleID();
1865 if( $id <= 0 || wfReadOnly() || !$this->mTitle->userCan('protect') ) {
1866 return false;
1869 if( !$cascade ) {
1870 $cascade = false;
1873 // Take this opportunity to purge out expired restrictions
1874 Title::purgeExpiredRestrictions();
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;
1897 $current = Article::flattenRestrictions( $current );
1899 $changed = ($changed || $current != $updated );
1900 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
1901 $protect = ( $updated != '' );
1903 # If nothing's changed, do nothing
1904 if( $changed ) {
1905 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1907 $dbw = wfGetDB( DB_MASTER );
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';
1916 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
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').']';
1929 if( $reason )
1930 $comment .= ": $reason";
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' );
1945 $protect_description .= ') ';
1948 $protect_description = trim($protect_description);
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__ );
1969 # Insert a null revision
1970 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1971 $nullRevId = $nullRevision->insertOn( $dbw );
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'
1985 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
1986 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
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 );
1997 } # End hook
1998 } # End "changed" check
2000 return true;
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
2009 protected static function flattenRestrictions( $limit ) {
2010 if( !is_array( $limit ) ) {
2011 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2013 $bits = array();
2014 ksort( $limit );
2015 foreach( $limit as $action => $restrictions ) {
2016 if( $restrictions != '' ) {
2017 $bits[] = "$action=$restrictions";
2020 return implode( ':', $bits );
2024 * Auto-generates a deletion reason
2025 * @param &$hasHistory Boolean: whether the page has a history
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;
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;
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 )
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;
2071 $dbw->freeResult( $res );
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' );
2085 if( $reason == '-' ) {
2086 // Allow these UI messages to be blanked out cleanly
2087 return '';
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;
2105 * UI entry point for page deletion
2107 public function delete() {
2108 global $wgUser, $wgOut, $wgRequest;
2110 $confirm = $wgRequest->wasPosted() &&
2111 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2113 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2114 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2116 $reason = $this->DeleteReasonList;
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;
2124 # Flag to hide all contents of the archived revisions
2125 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2127 # This code desperately needs to be totally rewritten
2129 # Read-only check...
2130 if( wfReadOnly() ) {
2131 $wgOut->readOnlyPage();
2132 return;
2135 # Check permissions
2136 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2138 if( count( $permission_errors ) > 0 ) {
2139 $wgOut->showPermissionsErrorPage( $permission_errors );
2140 return;
2143 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
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;
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;
2163 if( $confirm ) {
2164 $this->doDelete( $reason, $suppress );
2165 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2166 $this->doWatch();
2167 } elseif( $this->mTitle->userIsWatching() ) {
2168 $this->doUnwatch();
2170 return;
2173 // Generate deletion reason
2174 $hasHistory = false;
2175 if( !$reason ) $reason = $this->generateReason($hasHistory);
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 ) ) );
2188 return $this->confirmDelete( $reason );
2192 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2194 public function isBigDeletion() {
2195 global $wgDeleteRevisionsLimit;
2196 if( $wgDeleteRevisionsLimit ) {
2197 $revCount = $this->estimateRevisionCount();
2198 return $revCount > $wgDeleteRevisionsLimit;
2200 return false;
2204 * @return int approximate revision count
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__ );
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
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
2239 if( !$res ) {
2240 wfProfileOut( __METHOD__ );
2241 return array();
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;
2250 } while ( $continue );
2252 $authors = array( $row->rev_user_text );
2253 while ( $row = $db->fetchObject( $res ) ) {
2254 $authors[] = $row->rev_user_text;
2256 wfProfileOut( __METHOD__ );
2257 return $authors;
2261 * Output deletion confirmation dialog
2262 * @param $reason String: prefilled reason
2264 public function confirmDelete( $reason ) {
2265 global $wgOut, $wgUser;
2267 wfDebug( "Article::confirmDelete\n" );
2269 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2270 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2271 $wgOut->addWikiMsg( 'confirmdeletetext' );
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 = '';
2284 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
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' );
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>';
2336 $wgOut->addHTML( $form );
2337 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2341 * Perform a deletion and output success or failure messages
2343 public function doDelete( $reason, $suppress = false ) {
2344 global $wgOut, $wgUser;
2345 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2347 $error = '';
2348 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2349 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2350 $deleted = $this->mTitle->getPrefixedText();
2352 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2353 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2355 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
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 );
2370 * Back-end article deletion
2371 * Deletes the article with database consistency, writes logs, purges caches
2372 * Returns success
2374 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2375 global $wgUseSquid, $wgDeferredUpdateList;
2376 global $wgUseTrackbacks;
2378 wfDebug( __METHOD__."\n" );
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 );
2385 if( $t == '' || $id == 0 ) {
2386 return false;
2389 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2390 array_push( $wgDeferredUpdateList, $u );
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';
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.
2410 // For backwards compatibility, note that some older archive
2411 // table entries will have ar_text and ar_flags fields still.
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__
2437 # Delete restrictions for it
2438 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
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;
2448 # If using cascading deletes, we can skip some explicit deletes
2449 if( !$dbw->cascadingDeletes() ) {
2450 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2452 if($wgUseTrackbacks)
2453 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
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 ) );
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__ );
2478 # Clear caches
2479 Article::onArticleDelete( $this->mTitle );
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;
2487 $this->updateCategoryCounts( array(), $cats );
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;
2493 # Log the deletion, if the page was suppressed, log it at Oversight instead
2494 $logtype = $suppress ? 'suppress' : 'delete';
2495 $log = new LogPage( $logtype );
2497 # Make sure logging got through
2498 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2500 $dbw->commit();
2502 return true;
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
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.
2517 * @param $resultDetails Array: contains result-specific array of additional values
2518 * 'alreadyrolled' : 'current' (rev)
2519 * success : 'summary' (str), 'current' (rev), 'target' (rev)
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().
2526 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2527 global $wgUser;
2528 $resultDetails = null;
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 ) );
2535 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2536 $errors[] = array( 'sessionfailure' );
2538 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2539 $errors[] = array( 'actionthrottledtext' );
2541 # If there were errors, bail out now
2542 if( !empty( $errors ) )
2543 return $errors;
2545 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2549 * Backend implementation of doRollback(), please refer there for parameter
2550 * and return value documentation
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.
2557 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2558 global $wgUseRCPatrol, $wgUser, $wgLang;
2559 $dbw = wfGetDB( DB_MASTER );
2561 if( wfReadOnly() ) {
2562 return array( array( 'readonlytext' ) );
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'));
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())
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' )
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'));
2601 $set = array();
2602 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2603 # Mark all reverted edits as bot
2604 $set['rc_bot'] = 1;
2606 if( $wgUseRCPatrol ) {
2607 # Mark all reverted edits as patrolled
2608 $set['rc_patrolled'] = 1;
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__
2621 # Generate the edit summary if necessary
2622 $target = Revision::newFromId( $s->rev_id );
2623 if( empty( $summary ) ){
2624 $summary = wfMsgForContent( 'revertpage' );
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())
2633 $summary = wfMsgReplaceArgs( $summary, $args );
2635 # Save
2636 $flags = EDIT_UPDATE;
2638 if( $wgUser->isAllowed('minoredit') )
2639 $flags |= EDIT_MINOR;
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;
2651 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2653 $resultDetails = array(
2654 'summary' => $summary,
2655 'current' => $current,
2656 'target' => $target,
2657 'newid' => $revId
2659 return array();
2663 * User interface for rollback operations
2665 public function rollback() {
2666 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2667 $details = null;
2669 $result = $this->doRollback(
2670 $wgRequest->getVal( 'from' ),
2671 $wgRequest->getText( 'summary' ),
2672 $wgRequest->getVal( 'token' ),
2673 $wgRequest->getBool( 'bot' ),
2674 $details
2677 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2678 $wgOut->rateLimited();
2679 return;
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' ) );
2693 return;
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;
2707 $wgOut->showPermissionsErrorPage( $out );
2708 return;
2710 if( $result == array( array( 'readonlytext' ) ) ) {
2711 $wgOut->readOnlyPage();
2712 return;
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 );
2727 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
2728 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
2729 $de->showDiff( '', '' );
2735 * Do standard deferred updates after page view
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 );
2745 # Update newtalk / watchlist notification status
2746 $wgUser->clearNotification( $this->mTitle );
2750 * Prepare text which is about to be saved.
2751 * Returns a stdclass with source, pst and output members
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;
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;
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.
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
2786 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2787 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2789 wfProfileIn( __METHOD__ );
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;
2801 # Save it to the parser cache
2802 if( $wgEnableParserCache ) {
2803 $parserCache = ParserCache::singleton();
2804 $parserCache->save( $editInfo->output, $this, $wgUser );
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();
2812 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
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 );
2827 $id = $this->getID();
2828 $title = $this->mTitle->getPrefixedDBkey();
2829 $shortTitle = $this->mTitle->getDBkey();
2831 if( 0 == $id ) {
2832 wfProfileOut( __METHOD__ );
2833 return;
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 );
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" );
2862 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2863 $wgMessageCache->replace( $shortTitle, $text );
2866 wfProfileOut( __METHOD__ );
2870 * Perform article updates on a special page creation.
2872 * @param $rev Revision object
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.
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 );
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 -\>
2891 * @param $oldid String: revision ID of this article revision
2893 public function setOldSubtitle( $oldid = 0 ) {
2894 global $wgLang, $wgOut, $wgUser;
2896 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
2897 return;
2900 $revision = Revision::newFromId( $oldid );
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 );
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>";
2943 $cdel = "(<small>$cdel</small>) ";
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 );
2949 $m = wfMsg( 'revision-info-current' );
2950 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2951 ? 'revision-info-current'
2952 : 'revision-info';
2954 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), $td, $userlinks, $revision->getID() ) . "</div>\n" .
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 );
2962 * This function is called right before saving the wikitext,
2963 * so we can do things like signatures and links-in-context.
2965 * @param $text String
2967 public function preSaveTransform( $text ) {
2968 global $wgParser, $wgUser;
2969 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2972 /* Caching functions */
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)
2979 protected function tryFileCache() {
2980 static $called = false;
2981 if( $called ) {
2982 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2983 return false;
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' ) );
2996 } else {
2997 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2999 return false;
3003 * Check if the page can be cached
3004 * @return bool
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 ) );
3015 return $cacheable;
3019 * Loads page_touched and returns a value indicating if it should be used
3022 public function checkTouched() {
3023 if( !$this->mDataLoaded ) {
3024 $this->loadPageData();
3026 return !$this->mIsRedirect;
3030 * Get the page_touched field
3032 public function getTouched() {
3033 # Ensure that page data has been loaded
3034 if( !$this->mDataLoaded ) {
3035 $this->loadPageData();
3037 return $this->mTouched;
3041 * Get the page_latest field
3043 public function getLatest() {
3044 if( !$this->mDataLoaded ) {
3045 $this->loadPageData();
3047 return $this->mLatest;
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.
3055 * @param $text String: text submitted
3056 * @param $comment String: comment submitted
3057 * @param $minor Boolean: whereas it's a minor modification
3059 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3060 wfProfileIn( __METHOD__ );
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 );
3072 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3074 wfProfileOut( __METHOD__ );
3078 * Used to increment the view counter
3080 * @param $id Integer: article id
3082 public static function incViewCount( $id ) {
3083 $id = intval( $id );
3084 global $wgHitcounterUpdateFreq, $wgDBtype;
3086 $dbw = wfGetDB( DB_MASTER );
3087 $pageTable = $dbw->tableName( 'page' );
3088 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3089 $acchitsTable = $dbw->tableName( 'acchits' );
3091 if( $wgHitcounterUpdateFreq <= 1 ) {
3092 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3093 return;
3096 # Not important enough to warrant an error page in case of failure
3097 $oldignore = $dbw->ignoreErrors( true );
3099 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
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;
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 );
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');
3127 else {
3128 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3129 "FROM $acchitsTable WHERE page_id = hc_id");
3131 $dbw->query("DROP TABLE $acchitsTable");
3133 ignore_user_abort( $old_user_abort );
3134 wfProfileOut( 'Article::incViewCount-collect' );
3136 $dbw->ignoreErrors( $oldignore );
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.
3144 * This is a good place to put code to clear caches, for instance.
3146 * This is called on page move and undelete, as well as edit
3148 * @param $title a title object
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();
3158 $other->invalidateCache();
3159 $other->purgeSquid();
3161 $title->touchLinks();
3162 $title->purgeSquid();
3163 $title->deleteTitleProtection();
3166 public static function onArticleDelete( $title ) {
3167 global $wgUseFileCache, $wgMessageCache;
3168 # Update existence markers on article/talk tabs...
3169 if( $title->isTalkPage() ) {
3170 $other = $title->getSubjectPage();
3171 } else {
3172 $other = $title->getTalkPage();
3174 $other->invalidateCache();
3175 $other->purgeSquid();
3177 $title->touchLinks();
3178 $title->purgeSquid();
3180 # File cache
3181 if( $wgUseFileCache ) {
3182 $cm = new HTMLFileCache( $title );
3183 @unlink( $cm->fileCacheName() );
3186 # Messages
3187 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3188 $wgMessageCache->replace( $title->getDBkey(), false );
3190 # Images
3191 if( $title->getNamespace() == NS_FILE ) {
3192 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3193 $update->doUpdate();
3195 # User talk pages
3196 if( $title->getNamespace() == NS_USER_TALK ) {
3197 $user = User::newFromName( $title->getText(), false );
3198 $user->setNewtalk( false );
3203 * Purge caches on page update etc
3205 public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
3206 global $wgDeferredUpdateList, $wgUseFileCache;
3208 // Invalidate caches of articles which include this page
3209 if( $transclusions !== 'skiptransclusions' )
3210 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3212 // Invalidate the caches of all pages which redirect here
3213 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3215 # Purge squid for this page only
3216 $title->purgeSquid();
3218 # Clear file cache for this page only
3219 if( $wgUseFileCache ) {
3220 $cm = new HTMLFileCache( $title );
3221 @unlink( $cm->fileCacheName() );
3225 /**#@-*/
3228 * Overriden by ImagePage class, only present here to avoid a fatal error
3229 * Called for ?action=revert
3231 public function revert() {
3232 global $wgOut;
3233 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3237 * Info about this page
3238 * Called for ?action=info when $wgAllowPageInfo is on.
3240 public function info() {
3241 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3243 if( !$wgAllowPageInfo ) {
3244 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3245 return;
3248 $page = $this->mTitle->getSubjectPage();
3250 $wgOut->setPagetitle( $page->getPrefixedText() );
3251 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3252 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3254 if( !$this->mTitle->exists() ) {
3255 $wgOut->addHTML( '<div class="noarticletext">' );
3256 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3257 // This doesn't quite make sense; the user is asking for
3258 // information about the _page_, not the message... -- RC
3259 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3260 } else {
3261 $msg = $wgUser->isLoggedIn()
3262 ? 'noarticletext'
3263 : 'noarticletextanon';
3264 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3266 $wgOut->addHTML( '</div>' );
3267 } else {
3268 $dbr = wfGetDB( DB_SLAVE );
3269 $wl_clause = array(
3270 'wl_title' => $page->getDBkey(),
3271 'wl_namespace' => $page->getNamespace() );
3272 $numwatchers = $dbr->selectField(
3273 'watchlist',
3274 'COUNT(*)',
3275 $wl_clause,
3276 __METHOD__,
3277 $this->getSelectOptions() );
3279 $pageInfo = $this->pageCountInfo( $page );
3280 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3282 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3283 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3284 if( $talkInfo ) {
3285 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3287 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3288 if( $talkInfo ) {
3289 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3291 $wgOut->addHTML( '</ul>' );
3296 * Return the total number of edits and number of unique editors
3297 * on a given page. If page does not exist, returns false.
3299 * @param $title Title object
3300 * @return array
3302 protected function pageCountInfo( $title ) {
3303 $id = $title->getArticleId();
3304 if( $id == 0 ) {
3305 return false;
3307 $dbr = wfGetDB( DB_SLAVE );
3308 $rev_clause = array( 'rev_page' => $id );
3309 $edits = $dbr->selectField(
3310 'revision',
3311 'COUNT(rev_page)',
3312 $rev_clause,
3313 __METHOD__,
3314 $this->getSelectOptions()
3316 $authors = $dbr->selectField(
3317 'revision',
3318 'COUNT(DISTINCT rev_user_text)',
3319 $rev_clause,
3320 __METHOD__,
3321 $this->getSelectOptions()
3323 return array( 'edits' => $edits, 'authors' => $authors );
3327 * Return a list of templates used by this article.
3328 * Uses the templatelinks table
3330 * @return Array of Title objects
3332 public function getUsedTemplates() {
3333 $result = array();
3334 $id = $this->mTitle->getArticleID();
3335 if( $id == 0 ) {
3336 return array();
3338 $dbr = wfGetDB( DB_SLAVE );
3339 $res = $dbr->select( array( 'templatelinks' ),
3340 array( 'tl_namespace', 'tl_title' ),
3341 array( 'tl_from' => $id ),
3342 __METHOD__ );
3343 if( $res !== false ) {
3344 foreach( $res as $row ) {
3345 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3348 $dbr->freeResult( $res );
3349 return $result;
3353 * Returns a list of hidden categories this page is a member of.
3354 * Uses the page_props and categorylinks tables.
3356 * @return Array of Title objects
3358 public function getHiddenCategories() {
3359 $result = array();
3360 $id = $this->mTitle->getArticleID();
3361 if( $id == 0 ) {
3362 return array();
3364 $dbr = wfGetDB( DB_SLAVE );
3365 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3366 array( 'cl_to' ),
3367 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3368 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3369 __METHOD__ );
3370 if( $res !== false ) {
3371 foreach( $res as $row ) {
3372 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3375 $dbr->freeResult( $res );
3376 return $result;
3380 * Return an applicable autosummary if one exists for the given edit.
3381 * @param $oldtext String: the previous text of the page.
3382 * @param $newtext String: The submitted text of the page.
3383 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3384 * @return string An appropriate autosummary, or an empty string.
3386 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3387 # Decide what kind of autosummary is needed.
3389 # Redirect autosummaries
3390 $ot = Title::newFromRedirect( $oldtext );
3391 $rt = Title::newFromRedirect( $newtext );
3392 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3393 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3396 # New page autosummaries
3397 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3398 # If they're making a new article, give its text, truncated, in the summary.
3399 global $wgContLang;
3400 $truncatedtext = $wgContLang->truncate(
3401 str_replace("\n", ' ', $newtext),
3402 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
3403 '...' );
3404 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3407 # Blanking autosummaries
3408 if( $oldtext != '' && $newtext == '' ) {
3409 return wfMsgForContent( 'autosumm-blank' );
3410 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3411 # Removing more than 90% of the article
3412 global $wgContLang;
3413 $truncatedtext = $wgContLang->truncate(
3414 $newtext,
3415 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
3416 '...'
3418 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3421 # If we reach this point, there's no applicable autosummary for our case, so our
3422 # autosummary is empty.
3423 return '';
3427 * Add the primary page-view wikitext to the output buffer
3428 * Saves the text into the parser cache if possible.
3429 * Updates templatelinks if it is out of date.
3431 * @param $text String
3432 * @param $cache Boolean
3434 public function outputWikiText( $text, $cache = true ) {
3435 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3437 $popts = $wgOut->parserOptions();
3438 $popts->setTidy(true);
3439 $popts->enableLimitReport();
3440 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3441 $popts, true, true, $this->getRevIdFetched() );
3442 $popts->setTidy(false);
3443 $popts->enableLimitReport( false );
3444 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3445 $parserCache = ParserCache::singleton();
3446 $parserCache->save( $parserOutput, $this, $wgUser );
3448 // Make sure file cache is not used on uncacheable content.
3449 // Output that has magic words in it can still use the parser cache
3450 // (if enabled), though it will generally expire sooner.
3451 if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
3452 $wgUseFileCache = false;
3455 if( $this->isCurrent() && !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3456 // templatelinks table may have become out of sync,
3457 // especially if using variable-based transclusions.
3458 // For paranoia, check if things have changed and if
3459 // so apply updates to the database. This will ensure
3460 // that cascaded protections apply as soon as the changes
3461 // are visible.
3463 # Get templates from templatelinks
3464 $id = $this->mTitle->getArticleID();
3466 $tlTemplates = array();
3468 $dbr = wfGetDB( DB_SLAVE );
3469 $res = $dbr->select( array( 'templatelinks' ),
3470 array( 'tl_namespace', 'tl_title' ),
3471 array( 'tl_from' => $id ),
3472 __METHOD__ );
3474 global $wgContLang;
3476 if( $res !== false ) {
3477 foreach( $res as $row ) {
3478 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3482 # Get templates from parser output.
3483 $poTemplates_allns = $parserOutput->getTemplates();
3485 $poTemplates = array ();
3486 foreach ( $poTemplates_allns as $ns_templates ) {
3487 $poTemplates = array_merge( $poTemplates, $ns_templates );
3490 # Get the diff
3491 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3493 if( count( $templates_diff ) > 0 ) {
3494 # Whee, link updates time.
3495 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3496 $u->doUpdate();
3500 $wgOut->addParserOutput( $parserOutput );
3504 * Update all the appropriate counts in the category table, given that
3505 * we've added the categories $added and deleted the categories $deleted.
3507 * @param $added array The names of categories that were added
3508 * @param $deleted array The names of categories that were deleted
3509 * @return null
3511 public function updateCategoryCounts( $added, $deleted ) {
3512 $ns = $this->mTitle->getNamespace();
3513 $dbw = wfGetDB( DB_MASTER );
3515 # First make sure the rows exist. If one of the "deleted" ones didn't
3516 # exist, we might legitimately not create it, but it's simpler to just
3517 # create it and then give it a negative value, since the value is bogus
3518 # anyway.
3520 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3521 $insertCats = array_merge( $added, $deleted );
3522 if( !$insertCats ) {
3523 # Okay, nothing to do
3524 return;
3526 $insertRows = array();
3527 foreach( $insertCats as $cat ) {
3528 $insertRows[] = array( 'cat_title' => $cat );
3530 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3532 $addFields = array( 'cat_pages = cat_pages + 1' );
3533 $removeFields = array( 'cat_pages = cat_pages - 1' );
3534 if( $ns == NS_CATEGORY ) {
3535 $addFields[] = 'cat_subcats = cat_subcats + 1';
3536 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3537 } elseif( $ns == NS_FILE ) {
3538 $addFields[] = 'cat_files = cat_files + 1';
3539 $removeFields[] = 'cat_files = cat_files - 1';
3542 if( $added ) {
3543 $dbw->update(
3544 'category',
3545 $addFields,
3546 array( 'cat_title' => $added ),
3547 __METHOD__
3550 if( $deleted ) {
3551 $dbw->update(
3552 'category',
3553 $removeFields,
3554 array( 'cat_title' => $deleted ),
3555 __METHOD__