Fix typos identified by Nick Jenkins with his magic tool o' doom
[mediawiki.git] / includes / Article.php
blob1f83a2e2ca27f36f810ca0e657b8e9c10696a222
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
16 /**
17 * Class representing a MediaWiki article and history.
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
23 * @package MediaWiki
25 class Article {
26 /**#@+
27 * @access private
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 var $mRevision;
39 var $mRedirectUrl;
40 var $mLatest;
41 /**#@-*/
43 /**
44 * Constructor and clear the article
45 * @param Title &$title
46 * @param integer $oldId Revision ID, null to fetch from request, zero for current
48 function Article( &$title, $oldId = null ) {
49 $this->mTitle =& $title;
50 $this->mOldId = $oldId;
51 $this->clear();
54 /**
55 * Tell the page view functions that this view was redirected
56 * from another page on the wiki.
57 * @param Title $from
59 function setRedirectedFrom( $from ) {
60 $this->mRedirectedFrom = $from;
63 /**
64 * @return mixed false, Title of in-wiki target, or string with URL
66 function followRedirect() {
67 $text = $this->getContent();
68 $rt = Title::newFromRedirect( $text );
70 # process if title object is valid and not special:userlogout
71 if( $rt ) {
72 if( $rt->getInterwiki() != '' ) {
73 if( $rt->isLocal() ) {
74 // Offsite wikis need an HTTP redirect.
76 // This can be hard to reverse and may produce loops,
77 // so they may be disabled in the site configuration.
79 $source = $this->mTitle->getFullURL( 'redirect=no' );
80 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
82 } else {
83 if( $rt->getNamespace() == NS_SPECIAL ) {
84 // Gotta hand redirects to special pages differently:
85 // Fill the HTTP response "Location" header and ignore
86 // the rest of the page we're on.
88 // This can be hard to reverse, so they may be disabled.
90 if( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) {
91 // rolleyes
92 } else {
93 return $rt->getFullURL();
96 return $rt;
100 // No or invalid redirect
101 return false;
105 * get the title object of the article
107 function getTitle() {
108 return $this->mTitle;
112 * Clear the object
113 * @access private
115 function clear() {
116 $this->mDataLoaded = false;
117 $this->mContentLoaded = false;
119 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
120 $this->mRedirectedFrom = null; # Title object if set
121 $this->mUserText =
122 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
123 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
124 $this->mTouched = '19700101000000';
125 $this->mForUpdate = false;
126 $this->mIsRedirect = false;
127 $this->mRevIdFetched = 0;
128 $this->mRedirectUrl = false;
129 $this->mLatest = false;
133 * Note that getContent/loadContent do not follow redirects anymore.
134 * If you need to fetch redirectable content easily, try
135 * the shortcut in Article::followContent()
137 * @fixme There are still side-effects in this!
138 * In general, you should use the Revision class, not Article,
139 * to fetch text for purposes other than page views.
141 * @return Return the text of this revision
143 function getContent() {
144 global $wgRequest, $wgUser, $wgOut;
146 # Get variables from query string :P
147 $action = $wgRequest->getText( 'action', 'view' );
148 $section = $wgRequest->getText( 'section' );
149 $preload = $wgRequest->getText( 'preload' );
151 $fname = 'Article::getContent';
152 wfProfileIn( $fname );
154 if ( 0 == $this->getID() ) {
155 if ( 'edit' == $action ) {
156 wfProfileOut( $fname );
158 # If requested, preload some text.
159 $text=$this->getPreloadedText($preload);
161 # We used to put MediaWiki:Newarticletext here if
162 # $text was empty at this point.
163 # This is now shown above the edit box instead.
164 return $text;
166 wfProfileOut( $fname );
167 $wgOut->setRobotpolicy( 'noindex,nofollow' );
169 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
170 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
171 } else {
172 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
175 return "<div class='noarticletext'>$ret</div>";
176 } else {
177 $this->loadContent();
178 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
179 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
180 $wgUser->isIP($this->mTitle->getText()) &&
181 $action=='view'
183 wfProfileOut( $fname );
184 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
185 } else {
186 if($action=='edit') {
187 if($section!='') {
188 if($section=='new') {
189 wfProfileOut( $fname );
190 $text=$this->getPreloadedText($preload);
191 return $text;
194 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
195 # comments to be stripped as well)
196 $rv=$this->getSection($this->mContent,$section);
197 wfProfileOut( $fname );
198 return $rv;
201 wfProfileOut( $fname );
202 return $this->mContent;
208 * Get the contents of a page from its title and remove includeonly tags
210 * @param string The title of the page
211 * @return string The contents of the page
213 function getPreloadedText($preload) {
214 if ( $preload === '' )
215 return '';
216 else {
217 $preloadTitle = Title::newFromText( $preload );
218 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
219 $rev=Revision::newFromTitle($preloadTitle);
220 if ( is_object( $rev ) ) {
221 $text = $rev->getText();
222 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
223 // its own mini-parser! -ævar
224 $text = preg_replace( '~</?includeonly>~', '', $text );
225 return $text;
226 } else
227 return '';
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 string $text text to look in
240 * @param integer $section section number
241 * @return string text of the requested section
243 function getSection($text,$section) {
245 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
246 # comments to be stripped as well)
247 $striparray=array();
248 $parser=new Parser();
249 $parser->mOutputType=OT_WIKI;
250 $parser->mOptions = new ParserOptions();
251 $striptext=$parser->strip($text, $striparray, true);
253 # now that we can be sure that no pseudo-sections are in the source,
254 # split it up by section
255 $secs =
256 preg_split(
257 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
258 $striptext, -1,
259 PREG_SPLIT_DELIM_CAPTURE);
260 if($section==0) {
261 $rv=$secs[0];
262 } else {
263 $headline=$secs[$section*2-1];
264 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
265 $hlevel=$matches[1];
267 # translate wiki heading into level
268 if(strpos($hlevel,'=')!==false) {
269 $hlevel=strlen($hlevel);
272 $rv=$headline. $secs[$section*2];
273 $count=$section+1;
275 $break=false;
276 while(!empty($secs[$count*2-1]) && !$break) {
278 $subheadline=$secs[$count*2-1];
279 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
280 $subhlevel=$matches[1];
281 if(strpos($subhlevel,'=')!==false) {
282 $subhlevel=strlen($subhlevel);
284 if($subhlevel > $hlevel) {
285 $rv.=$subheadline.$secs[$count*2];
287 if($subhlevel <= $hlevel) {
288 $break=true;
290 $count++;
294 # reinsert stripped tags
295 $rv=$parser->unstrip($rv,$striparray);
296 $rv=$parser->unstripNoWiki($rv,$striparray);
297 $rv=trim($rv);
298 return $rv;
303 * @return int The oldid of the article that is to be shown, 0 for the
304 * current revision
306 function getOldID() {
307 if ( is_null( $this->mOldId ) ) {
308 $this->mOldId = $this->getOldIDFromRequest();
310 return $this->mOldId;
314 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
316 * @return int The old id for the request
318 function getOldIDFromRequest() {
319 global $wgRequest;
320 $this->mRedirectUrl = false;
321 $oldid = $wgRequest->getVal( 'oldid' );
322 if ( isset( $oldid ) ) {
323 $oldid = intval( $oldid );
324 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
325 $nextid = $this->mTitle->getNextRevisionID( $oldid );
326 if ( $nextid ) {
327 $oldid = $nextid;
328 } else {
329 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
331 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
332 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
333 if ( $previd ) {
334 $oldid = $previd;
335 } else {
336 # TODO
339 $lastid = $oldid;
341 if ( !$oldid ) {
342 $oldid = 0;
344 return $oldid;
348 * Load the revision (including text) into this object
350 function loadContent() {
351 if ( $this->mContentLoaded ) return;
353 # Query variables :P
354 $oldid = $this->getOldID();
356 $fname = 'Article::loadContent';
358 # Pre-fill content with error message so that if something
359 # fails we'll have something telling us what we intended.
361 $t = $this->mTitle->getPrefixedText();
363 $this->mOldId = $oldid;
364 $this->fetchContent( $oldid );
369 * Fetch a page record with the given conditions
370 * @param Database $dbr
371 * @param array $conditions
372 * @access private
374 function pageData( &$dbr, $conditions ) {
375 $fields = array(
376 'page_id',
377 'page_namespace',
378 'page_title',
379 'page_restrictions',
380 'page_counter',
381 'page_is_redirect',
382 'page_is_new',
383 'page_random',
384 'page_touched',
385 'page_latest',
386 'page_len' ) ;
387 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
388 $row = $dbr->selectRow( 'page',
389 $fields,
390 $conditions,
391 'Article::pageData' );
392 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
393 return $row ;
397 * @param Database $dbr
398 * @param Title $title
400 function pageDataFromTitle( &$dbr, $title ) {
401 return $this->pageData( $dbr, array(
402 'page_namespace' => $title->getNamespace(),
403 'page_title' => $title->getDBkey() ) );
407 * @param Database $dbr
408 * @param int $id
410 function pageDataFromId( &$dbr, $id ) {
411 return $this->pageData( $dbr, array( 'page_id' => $id ) );
415 * Set the general counter, title etc data loaded from
416 * some source.
418 * @param object $data
419 * @access private
421 function loadPageData( $data = 'fromdb' ) {
422 if ( $data === 'fromdb' ) {
423 $dbr =& $this->getDB();
424 $data = $this->pageDataFromId( $dbr, $this->getId() );
427 $lc =& LinkCache::singleton();
428 if ( $data ) {
429 $lc->addGoodLinkObj( $data->page_id, $this->mTitle );
431 $this->mTitle->mArticleID = $data->page_id;
432 $this->mTitle->loadRestrictions( $data->page_restrictions );
433 $this->mTitle->mRestrictionsLoaded = true;
435 $this->mCounter = $data->page_counter;
436 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
437 $this->mIsRedirect = $data->page_is_redirect;
438 $this->mLatest = $data->page_latest;
439 } else {
440 if ( is_object( $this->mTitle ) ) {
441 $lc->addBadLinkObj( $this->mTitle );
443 $this->mTitle->mArticleID = 0;
446 $this->mDataLoaded = true;
450 * Get text of an article from database
451 * Does *NOT* follow redirects.
452 * @param int $oldid 0 for whatever the latest revision is
453 * @return string
455 function fetchContent( $oldid = 0 ) {
456 if ( $this->mContentLoaded ) {
457 return $this->mContent;
460 $dbr =& $this->getDB();
461 $fname = 'Article::fetchContent';
463 # Pre-fill content with error message so that if something
464 # fails we'll have something telling us what we intended.
465 $t = $this->mTitle->getPrefixedText();
466 if( $oldid ) {
467 $t .= ',oldid='.$oldid;
469 $this->mContent = wfMsg( 'missingarticle', $t ) ;
471 if( $oldid ) {
472 $revision = Revision::newFromId( $oldid );
473 if( is_null( $revision ) ) {
474 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
475 return false;
477 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
478 if( !$data ) {
479 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
480 return false;
482 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
483 $this->loadPageData( $data );
484 } else {
485 if( !$this->mDataLoaded ) {
486 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
487 if( !$data ) {
488 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
489 return false;
491 $this->loadPageData( $data );
493 $revision = Revision::newFromId( $this->mLatest );
494 if( is_null( $revision ) ) {
495 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
496 return false;
500 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
501 // We should instead work with the Revision object when we need it...
502 $this->mContent = $revision->userCan( MW_REV_DELETED_TEXT ) ? $revision->getRawText() : "";
503 //$this->mContent = $revision->getText();
505 $this->mUser = $revision->getUser();
506 $this->mUserText = $revision->getUserText();
507 $this->mComment = $revision->getComment();
508 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
510 $this->mRevIdFetched = $revision->getID();
511 $this->mContentLoaded = true;
512 $this->mRevision =& $revision;
514 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
516 return $this->mContent;
520 * Read/write accessor to select FOR UPDATE
522 * @param mixed $x
524 function forUpdate( $x = NULL ) {
525 return wfSetVar( $this->mForUpdate, $x );
529 * Get the database which should be used for reads
531 * @return Database
533 function &getDB() {
534 $ret =& wfGetDB( DB_MASTER );
535 return $ret;
539 * Get options for all SELECT statements
541 * @param array $options an optional options array which'll be appended to
542 * the default
543 * @return array Options
545 function getSelectOptions( $options = '' ) {
546 if ( $this->mForUpdate ) {
547 if ( is_array( $options ) ) {
548 $options[] = 'FOR UPDATE';
549 } else {
550 $options = 'FOR UPDATE';
553 return $options;
557 * @return int Page ID
559 function getID() {
560 if( $this->mTitle ) {
561 return $this->mTitle->getArticleID();
562 } else {
563 return 0;
568 * @return bool Whether or not the page exists in the database
570 function exists() {
571 return $this->getId() != 0;
575 * @return int The view count for the page
577 function getCount() {
578 if ( -1 == $this->mCounter ) {
579 $id = $this->getID();
580 if ( $id == 0 ) {
581 $this->mCounter = 0;
582 } else {
583 $dbr =& wfGetDB( DB_SLAVE );
584 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
585 'Article::getCount', $this->getSelectOptions() );
588 return $this->mCounter;
592 * Determine whether a page would be suitable for being counted as an
593 * article in the site_stats table based on the title & its content
595 * @param string $text Text to analyze
596 * @return bool
598 function isCountable( $text ) {
599 global $wgUseCommaCount;
601 $token = $wgUseCommaCount ? ',' : '[[';
602 return
603 $this->mTitle->getNamespace() == NS_MAIN
604 && ! $this->isRedirect( $text )
605 && in_string( $token, $text );
609 * Tests if the article text represents a redirect
611 * @param string $text
612 * @return bool
614 function isRedirect( $text = false ) {
615 if ( $text === false ) {
616 $this->loadContent();
617 $titleObj = Title::newFromRedirect( $this->fetchContent() );
618 } else {
619 $titleObj = Title::newFromRedirect( $text );
621 return $titleObj !== NULL;
625 * Returns true if the currently-referenced revision is the current edit
626 * to this page (and it exists).
627 * @return bool
629 function isCurrent() {
630 return $this->exists() &&
631 isset( $this->mRevision ) &&
632 $this->mRevision->isCurrent();
636 * Loads everything except the text
637 * This isn't necessary for all uses, so it's only done if needed.
638 * @access private
640 function loadLastEdit() {
641 if ( -1 != $this->mUser )
642 return;
644 # New or non-existent articles have no user information
645 $id = $this->getID();
646 if ( 0 == $id ) return;
648 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
649 if( !is_null( $this->mLastRevision ) ) {
650 $this->mUser = $this->mLastRevision->getUser();
651 $this->mUserText = $this->mLastRevision->getUserText();
652 $this->mTimestamp = $this->mLastRevision->getTimestamp();
653 $this->mComment = $this->mLastRevision->getComment();
654 $this->mMinorEdit = $this->mLastRevision->isMinor();
655 $this->mRevIdFetched = $this->mLastRevision->getID();
659 function getTimestamp() {
660 // Check if the field has been filled by ParserCache::get()
661 if ( !$this->mTimestamp ) {
662 $this->loadLastEdit();
664 return wfTimestamp(TS_MW, $this->mTimestamp);
667 function getUser() {
668 $this->loadLastEdit();
669 return $this->mUser;
672 function getUserText() {
673 $this->loadLastEdit();
674 return $this->mUserText;
677 function getComment() {
678 $this->loadLastEdit();
679 return $this->mComment;
682 function getMinorEdit() {
683 $this->loadLastEdit();
684 return $this->mMinorEdit;
687 function getRevIdFetched() {
688 $this->loadLastEdit();
689 return $this->mRevIdFetched;
692 function getContributors($limit = 0, $offset = 0) {
693 $fname = 'Article::getContributors';
695 # XXX: this is expensive; cache this info somewhere.
697 $title = $this->mTitle;
698 $contribs = array();
699 $dbr =& wfGetDB( DB_SLAVE );
700 $revTable = $dbr->tableName( 'revision' );
701 $userTable = $dbr->tableName( 'user' );
702 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
703 $ns = $title->getNamespace();
704 $user = $this->getUser();
705 $pageId = $this->getId();
707 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
708 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
709 WHERE rev_page = $pageId
710 AND rev_user != $user
711 GROUP BY rev_user, rev_user_text, user_real_name
712 ORDER BY timestamp DESC";
714 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
715 $sql .= ' '. $this->getSelectOptions();
717 $res = $dbr->query($sql, $fname);
719 while ( $line = $dbr->fetchObject( $res ) ) {
720 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
723 $dbr->freeResult($res);
724 return $contribs;
728 * This is the default action of the script: just view the page of
729 * the given title.
731 function view() {
732 global $wgUser, $wgOut, $wgRequest, $wgContLang;
733 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
734 global $wgUseTrackbacks;
735 $sk = $wgUser->getSkin();
737 $fname = 'Article::view';
738 wfProfileIn( $fname );
739 $parserCache =& ParserCache::singleton();
740 # Get variables from query string
741 $oldid = $this->getOldID();
743 # getOldID may want us to redirect somewhere else
744 if ( $this->mRedirectUrl ) {
745 $wgOut->redirect( $this->mRedirectUrl );
746 wfProfileOut( $fname );
747 return;
750 $diff = $wgRequest->getVal( 'diff' );
751 $rcid = $wgRequest->getVal( 'rcid' );
752 $rdfrom = $wgRequest->getVal( 'rdfrom' );
754 $wgOut->setArticleFlag( true );
755 $wgOut->setRobotpolicy( 'index,follow' );
756 # If we got diff and oldid in the query, we want to see a
757 # diff page instead of the article.
759 if ( !is_null( $diff ) ) {
760 require_once( 'DifferenceEngine.php' );
761 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
763 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
764 // DifferenceEngine directly fetched the revision:
765 $this->mRevIdFetched = $de->mNewid;
766 $de->showDiffPage();
768 if( $diff == 0 ) {
769 # Run view updates for current revision only
770 $this->viewUpdates();
772 wfProfileOut( $fname );
773 return;
776 if ( empty( $oldid ) && $this->checkTouched() ) {
777 $wgOut->setETag($parserCache->getETag($this, $wgUser));
779 if( $wgOut->checkLastModified( $this->mTouched ) ){
780 wfProfileOut( $fname );
781 return;
782 } else if ( $this->tryFileCache() ) {
783 # tell wgOut that output is taken care of
784 $wgOut->disable();
785 $this->viewUpdates();
786 wfProfileOut( $fname );
787 return;
790 # Should the parser cache be used?
791 $pcache = $wgEnableParserCache &&
792 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
793 $this->exists() &&
794 empty( $oldid );
795 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
796 if ( $wgUser->getOption( 'stubthreshold' ) ) {
797 wfIncrStats( 'pcache_miss_stub' );
800 $wasRedirected = false;
801 if ( isset( $this->mRedirectedFrom ) ) {
802 // This is an internally redirected page view.
803 // We'll need a backlink to the source page for navigation.
804 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
805 $sk = $wgUser->getSkin();
806 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
807 $s = wfMsg( 'redirectedfrom', $redir );
808 $wgOut->setSubtitle( $s );
809 $wasRedirected = true;
811 } elseif ( !empty( $rdfrom ) ) {
812 // This is an externally redirected view, from some other wiki.
813 // If it was reported from a trusted site, supply a backlink.
814 global $wgRedirectSources;
815 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
816 $sk = $wgUser->getSkin();
817 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
818 $s = wfMsg( 'redirectedfrom', $redir );
819 $wgOut->setSubtitle( $s );
820 $wasRedirected = true;
824 $outputDone = false;
825 if ( $pcache ) {
826 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
827 $outputDone = true;
830 if ( !$outputDone ) {
831 $text = $this->getContent();
832 if ( $text === false ) {
833 # Failed to load, replace text with error message
834 $t = $this->mTitle->getPrefixedText();
835 if( $oldid ) {
836 $t .= ',oldid='.$oldid;
837 $text = wfMsg( 'missingarticle', $t );
838 } else {
839 $text = wfMsg( 'noarticletext', $t );
843 # Another whitelist check in case oldid is altering the title
844 if ( !$this->mTitle->userCanRead() ) {
845 $wgOut->loginToUse();
846 $wgOut->output();
847 exit;
850 # We're looking at an old revision
852 if ( !empty( $oldid ) ) {
853 $wgOut->setRobotpolicy( 'noindex,nofollow' );
854 if( is_null( $this->mRevision ) ) {
855 // FIXME: This would be a nice place to load the 'no such page' text.
856 } else {
857 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
858 if( $this->mRevision->isDeleted( MW_REV_DELETED_TEXT ) ) {
859 if( !$this->mRevision->userCan( MW_REV_DELETED_TEXT ) ) {
860 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
861 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
862 return;
863 } else {
864 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
865 // and we are allowed to see...
872 if( !$outputDone ) {
874 * @fixme: this hook doesn't work most of the time, as it doesn't
875 * trigger when the parser cache is used.
877 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
878 $wgOut->setRevisionId( $this->getRevIdFetched() );
879 # wrap user css and user js in pre and don't parse
880 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
881 if (
882 $this->mTitle->getNamespace() == NS_USER &&
883 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
885 $wgOut->addWikiText( wfMsg('clearyourcache'));
886 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
887 } else if ( $rt = Title::newFromRedirect( $text ) ) {
888 # Display redirect
889 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
890 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
891 if( !$wasRedirected ) {
892 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
894 $targetUrl = $rt->escapeLocalURL();
895 $titleText = htmlspecialchars( $rt->getPrefixedText() );
896 $link = $sk->makeLinkObj( $rt );
898 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
899 '<span class="redirectText">'.$link.'</span>' );
901 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
902 $wgOut->addParserOutputNoText( $parseout );
903 } else if ( $pcache ) {
904 # Display content and save to parser cache
905 $wgOut->addPrimaryWikiText( $text, $this );
906 } else {
907 # Display content, don't attempt to save to parser cache
909 # Don't show section-edit links on old revisions... this way lies madness.
910 if( !$this->isCurrent() ) {
911 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
913 # Display content and don't save to parser cache
914 $wgOut->addPrimaryWikiText( $text, $this, false );
916 if( !$this->isCurrent() ) {
917 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
921 /* title may have been set from the cache */
922 $t = $wgOut->getPageTitle();
923 if( empty( $t ) ) {
924 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
927 # If we have been passed an &rcid= parameter, we want to give the user a
928 # chance to mark this new article as patrolled.
929 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
930 $wgOut->addHTML(
931 "<div class='patrollink'>" .
932 wfMsg ( 'markaspatrolledlink',
933 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
935 '</div>'
939 # Trackbacks
940 if ($wgUseTrackbacks)
941 $this->addTrackbacks();
943 $this->viewUpdates();
944 wfProfileOut( $fname );
947 function addTrackbacks() {
948 global $wgOut, $wgUser;
950 $dbr =& wfGetDB(DB_SLAVE);
951 $tbs = $dbr->select(
952 /* FROM */ 'trackbacks',
953 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
954 /* WHERE */ array('tb_page' => $this->getID())
957 if (!$dbr->numrows($tbs))
958 return;
960 $tbtext = "";
961 while ($o = $dbr->fetchObject($tbs)) {
962 $rmvtxt = "";
963 if ($wgUser->isSysop()) {
964 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
965 . $o->tb_id . "&token=" . $wgUser->editToken());
966 $rmvtxt = wfMsg('trackbackremove', $delurl);
968 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
969 $o->tb_title,
970 $o->tb_url,
971 $o->tb_ex,
972 $o->tb_name,
973 $rmvtxt);
975 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
978 function deletetrackback() {
979 global $wgUser, $wgRequest, $wgOut, $wgTitle;
981 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
982 $wgOut->addWikitext(wfMsg('sessionfailure'));
983 return;
986 if ((!$wgUser->isAllowed('delete'))) {
987 $wgOut->sysopRequired();
988 return;
991 if (wfReadOnly()) {
992 $wgOut->readOnlyPage();
993 return;
996 $db =& wfGetDB(DB_MASTER);
997 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
998 $wgTitle->invalidateCache();
999 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1002 function render() {
1003 global $wgOut;
1005 $wgOut->setArticleBodyOnly(true);
1006 $this->view();
1010 * Handle action=purge
1012 function purge() {
1013 global $wgUser, $wgRequest, $wgOut;
1015 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
1016 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1017 $this->doPurge();
1019 } else {
1020 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1021 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
1022 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1023 $msg = str_replace( '$1',
1024 "<form method=\"post\" action=\"$action\">\n" .
1025 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1026 "</form>\n", $msg );
1028 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1029 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1030 $wgOut->addHTML( $msg );
1035 * Perform the actions of a page purging
1037 function doPurge() {
1038 global $wgUseSquid;
1039 // Invalidate the cache
1040 $this->mTitle->invalidateCache();
1042 if ( $wgUseSquid ) {
1043 // Commit the transaction before the purge is sent
1044 $dbw = wfGetDB( DB_MASTER );
1045 $dbw->immediateCommit();
1047 // Send purge
1048 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1049 $update->doUpdate();
1051 $this->view();
1055 * Insert a new empty page record for this article.
1056 * This *must* be followed up by creating a revision
1057 * and running $this->updateToLatest( $rev_id );
1058 * or else the record will be left in a funky state.
1059 * Best if all done inside a transaction.
1061 * @param Database $dbw
1062 * @param string $restrictions
1063 * @return int The newly created page_id key
1064 * @access private
1066 function insertOn( &$dbw, $restrictions = '' ) {
1067 $fname = 'Article::insertOn';
1068 wfProfileIn( $fname );
1070 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1071 $dbw->insert( 'page', array(
1072 'page_id' => $page_id,
1073 'page_namespace' => $this->mTitle->getNamespace(),
1074 'page_title' => $this->mTitle->getDBkey(),
1075 'page_counter' => 0,
1076 'page_restrictions' => $restrictions,
1077 'page_is_redirect' => 0, # Will set this shortly...
1078 'page_is_new' => 1,
1079 'page_random' => wfRandom(),
1080 'page_touched' => $dbw->timestamp(),
1081 'page_latest' => 0, # Fill this in shortly...
1082 'page_len' => 0, # Fill this in shortly...
1083 ), $fname );
1084 $newid = $dbw->insertId();
1086 $this->mTitle->resetArticleId( $newid );
1088 wfProfileOut( $fname );
1089 return $newid;
1093 * Update the page record to point to a newly saved revision.
1095 * @param Database $dbw
1096 * @param Revision $revision For ID number, and text used to set
1097 length and redirect status fields
1098 * @param int $lastRevision If given, will not overwrite the page field
1099 * when different from the currently set value.
1100 * Giving 0 indicates the new page flag should
1101 * be set on.
1102 * @return bool true on success, false on failure
1103 * @access private
1105 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1106 $fname = 'Article::updateToRevision';
1107 wfProfileIn( $fname );
1109 $conditions = array( 'page_id' => $this->getId() );
1110 if( !is_null( $lastRevision ) ) {
1111 # An extra check against threads stepping on each other
1112 $conditions['page_latest'] = $lastRevision;
1115 $text = $revision->getText();
1116 $dbw->update( 'page',
1117 array( /* SET */
1118 'page_latest' => $revision->getId(),
1119 'page_touched' => $dbw->timestamp(),
1120 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1121 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1122 'page_len' => strlen( $text ),
1124 $conditions,
1125 $fname );
1127 wfProfileOut( $fname );
1128 return ( $dbw->affectedRows() != 0 );
1132 * If the given revision is newer than the currently set page_latest,
1133 * update the page record. Otherwise, do nothing.
1135 * @param Database $dbw
1136 * @param Revision $revision
1138 function updateIfNewerOn( &$dbw, $revision ) {
1139 $fname = 'Article::updateIfNewerOn';
1140 wfProfileIn( $fname );
1142 $row = $dbw->selectRow(
1143 array( 'revision', 'page' ),
1144 array( 'rev_id', 'rev_timestamp' ),
1145 array(
1146 'page_id' => $this->getId(),
1147 'page_latest=rev_id' ),
1148 $fname );
1149 if( $row ) {
1150 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1151 wfProfileOut( $fname );
1152 return false;
1154 $prev = $row->rev_id;
1155 } else {
1156 # No or missing previous revision; mark the page as new
1157 $prev = 0;
1160 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1161 wfProfileOut( $fname );
1162 return $ret;
1166 * Insert a new article into the database
1167 * @access private
1169 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1170 global $wgUser;
1172 $fname = 'Article::insertNewArticle';
1173 wfProfileIn( $fname );
1175 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1176 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1177 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1178 wfProfileOut( $fname );
1179 return false;
1182 $ns = $this->mTitle->getNamespace();
1183 $ttl = $this->mTitle->getDBkey();
1185 # If this is a comment, add the summary as headline
1186 if($comment && $summary!="") {
1187 $text="== {$summary} ==\n\n".$text;
1189 $text = $this->preSaveTransform( $text );
1192 # Set statistics members
1193 # We work out if it's countable after PST to avoid counter drift
1194 # when articles are created with {{subst:}}
1195 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1196 $this->mTotalAdjustment = 1;
1198 /* Silently ignore minoredit if not allowed */
1199 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1200 $now = wfTimestampNow();
1202 $dbw =& wfGetDB( DB_MASTER );
1204 # Add the page record; stake our claim on this title!
1205 $newid = $this->insertOn( $dbw );
1207 # Save the revision text...
1208 $revision = new Revision( array(
1209 'page' => $newid,
1210 'comment' => $summary,
1211 'minor_edit' => $isminor,
1212 'text' => $text
1213 ) );
1214 $revisionId = $revision->insertOn( $dbw );
1216 $this->mTitle->resetArticleID( $newid );
1218 # Update the page record with revision data
1219 $this->updateRevisionOn( $dbw, $revision, 0 );
1221 Article::onArticleCreate( $this->mTitle );
1222 if(!$suppressRC) {
1223 require_once( 'RecentChange.php' );
1224 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1225 '', strlen( $text ), $revisionId );
1226 # Mark as patrolled if the user can and has the option set
1227 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1228 RecentChange::markPatrolled( $rcid );
1232 if ($watchthis) {
1233 if(!$this->mTitle->userIsWatching()) $this->doWatch();
1234 } else {
1235 if ( $this->mTitle->userIsWatching() ) {
1236 $this->doUnwatch();
1240 # The talk page isn't in the regular link tables, so we need to update manually:
1241 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1242 $dbw->update( 'page',
1243 array( 'page_touched' => $dbw->timestamp($now) ),
1244 array( 'page_namespace' => $talkns,
1245 'page_title' => $ttl ),
1246 $fname );
1248 # standard deferred updates
1249 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1251 $oldid = 0; # new article
1252 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1254 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1255 $summary, $isminor,
1256 $watchthis, NULL ) );
1257 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1258 $summary, $isminor,
1259 $watchthis, NULL ) );
1260 wfProfileOut( $fname );
1263 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1264 $this->replaceSection( $section, $text, $summary, $edittime );
1268 * @return string Complete article text, or null if error
1270 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1271 $fname = 'Article::replaceSection';
1272 wfProfileIn( $fname );
1274 if ($section != '') {
1275 if( is_null( $edittime ) ) {
1276 $rev = Revision::newFromTitle( $this->mTitle );
1277 } else {
1278 $dbw =& wfGetDB( DB_MASTER );
1279 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1281 if( is_null( $rev ) ) {
1282 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1283 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1284 return null;
1286 $oldtext = $rev->getText();
1288 if($section=='new') {
1289 if($summary) $subject="== {$summary} ==\n\n";
1290 $text=$oldtext."\n\n".$subject.$text;
1291 } else {
1293 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1294 # comments to be stripped as well)
1295 $striparray=array();
1296 $parser=new Parser();
1297 $parser->mOutputType=OT_WIKI;
1298 $parser->mOptions = new ParserOptions();
1299 $oldtext=$parser->strip($oldtext, $striparray, true);
1301 # now that we can be sure that no pseudo-sections are in the source,
1302 # split it up
1303 # Unfortunately we can't simply do a preg_replace because that might
1304 # replace the wrong section, so we have to use the section counter instead
1305 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1306 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1307 $secs[$section*2]=$text."\n\n"; // replace with edited
1309 # section 0 is top (intro) section
1310 if($section!=0) {
1312 # headline of old section - we need to go through this section
1313 # to determine if there are any subsections that now need to
1314 # be erased, as the mother section has been replaced with
1315 # the text of all subsections.
1316 $headline=$secs[$section*2-1];
1317 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1318 $hlevel=$matches[1];
1320 # determine headline level for wikimarkup headings
1321 if(strpos($hlevel,'=')!==false) {
1322 $hlevel=strlen($hlevel);
1325 $secs[$section*2-1]=''; // erase old headline
1326 $count=$section+1;
1327 $break=false;
1328 while(!empty($secs[$count*2-1]) && !$break) {
1330 $subheadline=$secs[$count*2-1];
1331 preg_match(
1332 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1333 $subhlevel=$matches[1];
1334 if(strpos($subhlevel,'=')!==false) {
1335 $subhlevel=strlen($subhlevel);
1337 if($subhlevel > $hlevel) {
1338 // erase old subsections
1339 $secs[$count*2-1]='';
1340 $secs[$count*2]='';
1342 if($subhlevel <= $hlevel) {
1343 $break=true;
1345 $count++;
1350 $text=join('',$secs);
1351 # reinsert the stuff that we stripped out earlier
1352 $text=$parser->unstrip($text,$striparray);
1353 $text=$parser->unstripNoWiki($text,$striparray);
1357 wfProfileOut( $fname );
1358 return $text;
1362 * Change an existing article. Puts the previous version back into the old table, updates RC
1363 * and all necessary caches, mostly via the deferred update array.
1365 * It is possible to call this function from a command-line script, but note that you should
1366 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1368 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1369 global $wgUser, $wgDBtransactions, $wgUseSquid;
1370 global $wgPostCommitUpdateList, $wgUseFileCache;
1372 $fname = 'Article::updateArticle';
1373 wfProfileIn( $fname );
1374 $good = true;
1376 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1377 &$summary, &$minor,
1378 &$watchthis, &$sectionanchor ) ) ) {
1379 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1380 wfProfileOut( $fname );
1381 return false;
1384 $isminor = $minor && $wgUser->isAllowed('minoredit');
1385 $redir = (int)$this->isRedirect( $text );
1387 $text = $this->preSaveTransform( $text );
1388 $dbw =& wfGetDB( DB_MASTER );
1389 $now = wfTimestampNow();
1391 # Update article, but only if changed.
1393 # It's important that we either rollback or complete, otherwise an attacker could
1394 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1395 # could conceivably have the same effect, especially if cur is locked for long periods.
1396 if( !$wgDBtransactions ) {
1397 $userAbort = ignore_user_abort( true );
1400 $oldtext = $this->getContent();
1401 $oldsize = strlen( $oldtext );
1402 $newsize = strlen( $text );
1403 $lastRevision = 0;
1404 $revisionId = 0;
1406 if ( 0 != strcmp( $text, $oldtext ) ) {
1407 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1408 - (int)$this->isCountable( $oldtext );
1409 $this->mTotalAdjustment = 0;
1410 $now = wfTimestampNow();
1412 $lastRevision = $dbw->selectField(
1413 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1415 $revision = new Revision( array(
1416 'page' => $this->getId(),
1417 'comment' => $summary,
1418 'minor_edit' => $isminor,
1419 'text' => $text
1420 ) );
1422 $dbw->immediateCommit();
1423 $dbw->begin();
1424 $revisionId = $revision->insertOn( $dbw );
1426 # Update page
1427 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1429 if( !$ok ) {
1430 /* Belated edit conflict! Run away!! */
1431 $good = false;
1432 $dbw->rollback();
1433 } else {
1434 # Update recentchanges and purge cache and whatnot
1435 require_once( 'RecentChange.php' );
1436 $bot = (int)($wgUser->isBot() || $forceBot);
1437 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1438 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1439 $revisionId );
1441 # Mark as patrolled if the user can do so and has it set in their options
1442 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1443 RecentChange::markPatrolled( $rcid );
1446 $dbw->commit();
1448 // Update caches outside the main transaction
1449 Article::onArticleEdit( $this->mTitle );
1451 } else {
1452 // Keep the same revision ID, but do some updates on it
1453 $revisionId = $this->getRevIdFetched();
1456 if( !$wgDBtransactions ) {
1457 ignore_user_abort( $userAbort );
1460 if ( $good ) {
1461 if ($watchthis) {
1462 if (!$this->mTitle->userIsWatching()) {
1463 $dbw->immediateCommit();
1464 $dbw->begin();
1465 $this->doWatch();
1466 $dbw->commit();
1468 } else {
1469 if ( $this->mTitle->userIsWatching() ) {
1470 $dbw->immediateCommit();
1471 $dbw->begin();
1472 $this->doUnwatch();
1473 $dbw->commit();
1476 # standard deferred updates
1477 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1480 $urls = array();
1481 # Invalidate caches of all articles using this article as a template
1483 # Template namespace
1484 # Purge all articles linking here
1485 $titles = $this->mTitle->getTemplateLinksTo();
1486 Title::touchArray( $titles );
1487 if ( $wgUseSquid ) {
1488 foreach ( $titles as $title ) {
1489 $urls[] = $title->getInternalURL();
1493 # Squid updates
1494 if ( $wgUseSquid ) {
1495 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1496 $u = new SquidUpdate( $urls );
1497 array_push( $wgPostCommitUpdateList, $u );
1500 # File cache
1501 if ( $wgUseFileCache ) {
1502 $cm = new CacheManager($this->mTitle);
1503 @unlink($cm->fileCacheName());
1506 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1508 wfRunHooks( 'ArticleSaveComplete',
1509 array( &$this, &$wgUser, $text,
1510 $summary, $minor,
1511 $watchthis, $sectionanchor ) );
1512 wfProfileOut( $fname );
1513 return $good;
1517 * After we've either updated or inserted the article, update
1518 * the link tables and redirect to the new page.
1520 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1521 global $wgOut;
1523 $fname = 'Article::showArticle';
1524 wfProfileIn( $fname );
1526 # Output the redirect
1527 if( $this->isRedirect( $text ) )
1528 $r = 'redirect=no';
1529 else
1530 $r = '';
1531 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1533 wfProfileOut( $fname );
1537 * Mark this particular edit as patrolled
1539 function markpatrolled() {
1540 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1541 $wgOut->setRobotpolicy( 'noindex,follow' );
1543 # Check RC patrol config. option
1544 if( !$wgUseRCPatrol ) {
1545 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1546 return;
1549 # Check permissions
1550 if( !$wgUser->isAllowed( 'patrol' ) ) {
1551 $wgOut->permissionRequired( 'patrol' );
1552 return;
1555 $rcid = $wgRequest->getVal( 'rcid' );
1556 if ( !is_null ( $rcid ) ) {
1557 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1558 require_once( 'RecentChange.php' );
1559 RecentChange::markPatrolled( $rcid );
1560 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1561 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1562 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1564 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1565 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1567 else {
1568 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1573 * User-interface handler for the "watch" action
1576 function watch() {
1578 global $wgUser, $wgOut;
1580 if ( $wgUser->isAnon() ) {
1581 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1582 return;
1584 if ( wfReadOnly() ) {
1585 $wgOut->readOnlyPage();
1586 return;
1589 if( $this->doWatch() ) {
1590 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1591 $wgOut->setRobotpolicy( 'noindex,follow' );
1593 $link = $this->mTitle->getPrefixedText();
1594 $text = wfMsg( 'addedwatchtext', $link );
1595 $wgOut->addWikiText( $text );
1598 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1602 * Add this page to $wgUser's watchlist
1603 * @return bool true on successful watch operation
1605 function doWatch() {
1606 global $wgUser;
1607 if( $wgUser->isAnon() ) {
1608 return false;
1611 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1612 $wgUser->addWatch( $this->mTitle );
1613 $wgUser->saveSettings();
1615 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1618 return false;
1622 * User interface handler for the "unwatch" action.
1624 function unwatch() {
1626 global $wgUser, $wgOut;
1628 if ( $wgUser->isAnon() ) {
1629 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1630 return;
1632 if ( wfReadOnly() ) {
1633 $wgOut->readOnlyPage();
1634 return;
1637 if( $this->doUnwatch() ) {
1638 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1639 $wgOut->setRobotpolicy( 'noindex,follow' );
1641 $link = $this->mTitle->getPrefixedText();
1642 $text = wfMsg( 'removedwatchtext', $link );
1643 $wgOut->addWikiText( $text );
1646 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1650 * Stop watching a page
1651 * @return bool true on successful unwatch
1653 function doUnwatch() {
1654 global $wgUser;
1655 if( $wgUser->isAnon() ) {
1656 return false;
1659 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1660 $wgUser->removeWatch( $this->mTitle );
1661 $wgUser->saveSettings();
1663 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1666 return false;
1670 * action=protect handler
1672 function protect() {
1673 require_once 'ProtectionForm.php';
1674 $form = new ProtectionForm( $this );
1675 $form->show();
1679 * action=unprotect handler (alias)
1681 function unprotect() {
1682 $this->protect();
1686 * Update the article's restriction field, and leave a log entry.
1688 * @param array $limit set of restriction keys
1689 * @param string $reason
1690 * @return bool true on success
1692 function updateRestrictions( $limit = array(), $reason = '' ) {
1693 global $wgUser, $wgRestrictionTypes, $wgContLang;
1695 $id = $this->mTitle->getArticleID();
1696 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1697 return false;
1700 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1701 # we expect a single selection, but the schema allows otherwise.
1702 $current = array();
1703 foreach( $wgRestrictionTypes as $action )
1704 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1706 $current = Article::flattenRestrictions( $current );
1707 $updated = Article::flattenRestrictions( $limit );
1709 $changed = ( $current != $updated );
1710 $protect = ( $updated != '' );
1712 # If nothing's changed, do nothing
1713 if( $changed ) {
1714 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1716 $dbw =& wfGetDB( DB_MASTER );
1718 # Prepare a null revision to be added to the history
1719 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1720 if( $reason )
1721 $comment .= ": $reason";
1722 if( $protect )
1723 $comment .= " [$updated]";
1724 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1725 $nullRevId = $nullRevision->insertOn( $dbw );
1727 # Update page record
1728 $dbw->update( 'page',
1729 array( /* SET */
1730 'page_touched' => $dbw->timestamp(),
1731 'page_restrictions' => $updated,
1732 'page_latest' => $nullRevId
1733 ), array( /* WHERE */
1734 'page_id' => $id
1735 ), 'Article::protect'
1737 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1739 # Update the protection log
1740 $log = new LogPage( 'protect' );
1741 if( $protect ) {
1742 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
1743 } else {
1744 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1747 } # End hook
1748 } # End "changed" check
1750 return true;
1754 * Take an array of page restrictions and flatten it to a string
1755 * suitable for insertion into the page_restrictions field.
1756 * @param array $limit
1757 * @return string
1758 * @access private
1760 function flattenRestrictions( $limit ) {
1761 if( !is_array( $limit ) ) {
1762 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1764 $bits = array();
1765 ksort( $limit );
1766 foreach( $limit as $action => $restrictions ) {
1767 if( $restrictions != '' ) {
1768 $bits[] = "$action=$restrictions";
1771 return implode( ':', $bits );
1775 * UI entry point for page deletion
1777 function delete() {
1778 global $wgUser, $wgOut, $wgRequest;
1779 $fname = 'Article::delete';
1780 $confirm = $wgRequest->wasPosted() &&
1781 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1782 $reason = $wgRequest->getText( 'wpReason' );
1784 # This code desperately needs to be totally rewritten
1786 # Check permissions
1787 if( $wgUser->isAllowed( 'delete' ) ) {
1788 if( $wgUser->isBlocked() ) {
1789 $wgOut->blockedPage();
1790 return;
1792 } else {
1793 $wgOut->permissionRequired( 'delete' );
1794 return;
1797 if( wfReadOnly() ) {
1798 $wgOut->readOnlyPage();
1799 return;
1802 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1804 # Better double-check that it hasn't been deleted yet!
1805 $dbw =& wfGetDB( DB_MASTER );
1806 $conds = $this->mTitle->pageCond();
1807 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1808 if ( $latest === false ) {
1809 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1810 return;
1813 if( $confirm ) {
1814 $this->doDelete( $reason );
1815 return;
1818 # determine whether this page has earlier revisions
1819 # and insert a warning if it does
1820 $maxRevisions = 20;
1821 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1823 if( count( $authors ) > 1 && !$confirm ) {
1824 $skin=$wgUser->getSkin();
1825 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1828 # If a single user is responsible for all revisions, find out who they are
1829 if ( count( $authors ) == $maxRevisions ) {
1830 // Query bailed out, too many revisions to find out if they're all the same
1831 $authorOfAll = false;
1832 } else {
1833 $authorOfAll = reset( $authors );
1834 foreach ( $authors as $author ) {
1835 if ( $authorOfAll != $author ) {
1836 $authorOfAll = false;
1837 break;
1841 # Fetch article text
1842 $rev = Revision::newFromTitle( $this->mTitle );
1844 if( !is_null( $rev ) ) {
1845 # if this is a mini-text, we can paste part of it into the deletion reason
1846 $text = $rev->getText();
1848 #if this is empty, an earlier revision may contain "useful" text
1849 $blanked = false;
1850 if( $text == '' ) {
1851 $prev = $rev->getPrevious();
1852 if( $prev ) {
1853 $text = $prev->getText();
1854 $blanked = true;
1858 $length = strlen( $text );
1860 # this should not happen, since it is not possible to store an empty, new
1861 # page. Let's insert a standard text in case it does, though
1862 if( $length == 0 && $reason === '' ) {
1863 $reason = wfMsgForContent( 'exblank' );
1866 if( $length < 500 && $reason === '' ) {
1867 # comment field=255, let's grep the first 150 to have some user
1868 # space left
1869 global $wgContLang;
1870 $text = $wgContLang->truncate( $text, 150, '...' );
1872 # let's strip out newlines
1873 $text = preg_replace( "/[\n\r]/", '', $text );
1875 if( !$blanked ) {
1876 if( $authorOfAll === false ) {
1877 $reason = wfMsgForContent( 'excontent', $text );
1878 } else {
1879 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1881 } else {
1882 $reason = wfMsgForContent( 'exbeforeblank', $text );
1887 return $this->confirmDelete( '', $reason );
1891 * Get the last N authors
1892 * @param int $num Number of revisions to get
1893 * @param string $revLatest The latest rev_id, selected from the master (optional)
1894 * @return array Array of authors, duplicates not removed
1896 function getLastNAuthors( $num, $revLatest = 0 ) {
1897 $fname = 'Article::getLastNAuthors';
1898 wfProfileIn( $fname );
1900 // First try the slave
1901 // If that doesn't have the latest revision, try the master
1902 $continue = 2;
1903 $db =& wfGetDB( DB_SLAVE );
1904 do {
1905 $res = $db->select( array( 'page', 'revision' ),
1906 array( 'rev_id', 'rev_user_text' ),
1907 array(
1908 'page_namespace' => $this->mTitle->getNamespace(),
1909 'page_title' => $this->mTitle->getDBkey(),
1910 'rev_page = page_id'
1911 ), $fname, $this->getSelectOptions( array(
1912 'ORDER BY' => 'rev_timestamp DESC',
1913 'LIMIT' => $num
1916 if ( !$res ) {
1917 wfProfileOut( $fname );
1918 return array();
1920 $row = $db->fetchObject( $res );
1921 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1922 $db =& wfGetDB( DB_MASTER );
1923 $continue--;
1924 } else {
1925 $continue = 0;
1927 } while ( $continue );
1929 $authors = array( $row->rev_user_text );
1930 while ( $row = $db->fetchObject( $res ) ) {
1931 $authors[] = $row->rev_user_text;
1933 wfProfileOut( $fname );
1934 return $authors;
1938 * Output deletion confirmation dialog
1940 function confirmDelete( $par, $reason ) {
1941 global $wgOut, $wgUser;
1943 wfDebug( "Article::confirmDelete\n" );
1945 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1946 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1947 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1948 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1950 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1952 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1953 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1954 $token = htmlspecialchars( $wgUser->editToken() );
1956 $wgOut->addHTML( "
1957 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1958 <table border='0'>
1959 <tr>
1960 <td align='right'>
1961 <label for='wpReason'>{$delcom}:</label>
1962 </td>
1963 <td align='left'>
1964 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1965 </td>
1966 </tr>
1967 <tr>
1968 <td>&nbsp;</td>
1969 <td>
1970 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1971 </td>
1972 </tr>
1973 </table>
1974 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1975 </form>\n" );
1977 $wgOut->returnToMain( false );
1982 * Perform a deletion and output success or failure messages
1984 function doDelete( $reason ) {
1985 global $wgOut, $wgUser;
1986 $fname = 'Article::doDelete';
1987 wfDebug( $fname."\n" );
1989 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1990 if ( $this->doDeleteArticle( $reason ) ) {
1991 $deleted = $this->mTitle->getPrefixedText();
1993 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1994 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1996 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1997 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1999 $wgOut->addWikiText( $text );
2000 $wgOut->returnToMain( false );
2001 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2002 } else {
2003 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2009 * Back-end article deletion
2010 * Deletes the article with database consistency, writes logs, purges caches
2011 * Returns success
2013 function doDeleteArticle( $reason ) {
2014 global $wgUseSquid, $wgDeferredUpdateList;
2015 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2017 $fname = 'Article::doDeleteArticle';
2018 wfDebug( $fname."\n" );
2020 $dbw =& wfGetDB( DB_MASTER );
2021 $ns = $this->mTitle->getNamespace();
2022 $t = $this->mTitle->getDBkey();
2023 $id = $this->mTitle->getArticleID();
2025 if ( $t == '' || $id == 0 ) {
2026 return false;
2029 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2030 array_push( $wgDeferredUpdateList, $u );
2032 $linksTo = $this->mTitle->getLinksTo();
2034 # Squid purging
2035 if ( $wgUseSquid ) {
2036 $urls = array(
2037 $this->mTitle->getInternalURL(),
2038 $this->mTitle->getInternalURL( 'history' )
2041 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
2042 array_push( $wgPostCommitUpdateList, $u );
2046 # Client and file cache invalidation
2047 Title::touchArray( $linksTo );
2050 // For now, shunt the revision data into the archive table.
2051 // Text is *not* removed from the text table; bulk storage
2052 // is left intact to avoid breaking block-compression or
2053 // immutable storage schemes.
2055 // For backwards compatibility, note that some older archive
2056 // table entries will have ar_text and ar_flags fields still.
2058 // In the future, we may keep revisions and mark them with
2059 // the rev_deleted field, which is reserved for this purpose.
2060 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2061 array(
2062 'ar_namespace' => 'page_namespace',
2063 'ar_title' => 'page_title',
2064 'ar_comment' => 'rev_comment',
2065 'ar_user' => 'rev_user',
2066 'ar_user_text' => 'rev_user_text',
2067 'ar_timestamp' => 'rev_timestamp',
2068 'ar_minor_edit' => 'rev_minor_edit',
2069 'ar_rev_id' => 'rev_id',
2070 'ar_text_id' => 'rev_text_id',
2071 ), array(
2072 'page_id' => $id,
2073 'page_id = rev_page'
2074 ), $fname
2077 # Now that it's safely backed up, delete it
2078 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2079 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2081 if ($wgUseTrackbacks)
2082 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2084 # Clean up recentchanges entries...
2085 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2087 # Finally, clean up the link tables
2088 $t = $this->mTitle->getPrefixedDBkey();
2090 Article::onArticleDelete( $this->mTitle );
2092 # Delete outgoing links
2093 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2094 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2095 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2096 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2097 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2099 # Log the deletion
2100 $log = new LogPage( 'delete' );
2101 $log->addEntry( 'delete', $this->mTitle, $reason );
2103 # Clear the cached article id so the interface doesn't act like we exist
2104 $this->mTitle->resetArticleID( 0 );
2105 $this->mTitle->mArticleID = 0;
2106 return true;
2110 * Revert a modification
2112 function rollback() {
2113 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2114 $fname = 'Article::rollback';
2116 if( $wgUser->isAllowed( 'rollback' ) ) {
2117 if( $wgUser->isBlocked() ) {
2118 $wgOut->blockedPage();
2119 return;
2121 } else {
2122 $wgOut->permissionRequired( 'rollback' );
2123 return;
2126 if ( wfReadOnly() ) {
2127 $wgOut->readOnlyPage( $this->getContent() );
2128 return;
2130 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2131 array( $this->mTitle->getPrefixedText(),
2132 $wgRequest->getVal( 'from' ) ) ) ) {
2133 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2134 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2135 return;
2137 $dbw =& wfGetDB( DB_MASTER );
2139 # Enhanced rollback, marks edits rc_bot=1
2140 $bot = $wgRequest->getBool( 'bot' );
2142 # Replace all this user's current edits with the next one down
2143 $tt = $this->mTitle->getDBKey();
2144 $n = $this->mTitle->getNamespace();
2146 # Get the last editor, lock table exclusively
2147 $dbw->begin();
2148 $current = Revision::newFromTitle( $this->mTitle );
2149 if( is_null( $current ) ) {
2150 # Something wrong... no page?
2151 $dbw->rollback();
2152 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2153 return;
2156 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2157 if( $from != $current->getUserText() ) {
2158 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2159 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2160 htmlspecialchars( $this->mTitle->getPrefixedText()),
2161 htmlspecialchars( $from ),
2162 htmlspecialchars( $current->getUserText() ) ) );
2163 if( $current->getComment() != '') {
2164 $wgOut->addHTML(
2165 wfMsg( 'editcomment',
2166 htmlspecialchars( $current->getComment() ) ) );
2168 return;
2171 # Get the last edit not by this guy
2172 $user = intval( $current->getUser() );
2173 $user_text = $dbw->addQuotes( $current->getUserText() );
2174 $s = $dbw->selectRow( 'revision',
2175 array( 'rev_id', 'rev_timestamp' ),
2176 array(
2177 'rev_page' => $current->getPage(),
2178 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2179 ), $fname,
2180 array(
2181 'USE INDEX' => 'page_timestamp',
2182 'ORDER BY' => 'rev_timestamp DESC' )
2184 if( $s === false ) {
2185 # Something wrong
2186 $dbw->rollback();
2187 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2188 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2189 return;
2192 $set = array();
2193 if ( $bot ) {
2194 # Mark all reverted edits as bot
2195 $set['rc_bot'] = 1;
2197 if ( $wgUseRCPatrol ) {
2198 # Mark all reverted edits as patrolled
2199 $set['rc_patrolled'] = 1;
2202 if ( $set ) {
2203 $dbw->update( 'recentchanges', $set,
2204 array( /* WHERE */
2205 'rc_cur_id' => $current->getPage(),
2206 'rc_user_text' => $current->getUserText(),
2207 "rc_timestamp > '{$s->rev_timestamp}'",
2208 ), $fname
2212 # Get the edit summary
2213 $target = Revision::newFromId( $s->rev_id );
2214 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2215 $newComment = $wgRequest->getText( 'summary', $newComment );
2217 # Save it!
2218 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2219 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2220 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2222 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2223 Article::onArticleEdit( $this->mTitle );
2225 $dbw->commit();
2226 $wgOut->returnToMain( false );
2231 * Do standard deferred updates after page view
2232 * @access private
2234 function viewUpdates() {
2235 global $wgDeferredUpdateList;
2237 if ( 0 != $this->getID() ) {
2238 global $wgDisableCounters;
2239 if( !$wgDisableCounters ) {
2240 Article::incViewCount( $this->getID() );
2241 $u = new SiteStatsUpdate( 1, 0, 0 );
2242 array_push( $wgDeferredUpdateList, $u );
2246 # Update newtalk / watchlist notification status
2247 global $wgUser;
2248 $wgUser->clearNotification( $this->mTitle );
2252 * Do standard deferred updates after page edit.
2253 * Every 1000th edit, prune the recent changes table.
2254 * @access private
2255 * @param string $text
2257 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2258 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2260 $fname = 'Article::editUpdates';
2261 wfProfileIn( $fname );
2263 # Parse the text
2264 $options = new ParserOptions;
2265 $options->setTidy(true);
2266 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2268 # Save it to the parser cache
2269 $parserCache =& ParserCache::singleton();
2270 $parserCache->save( $poutput, $this, $wgUser );
2272 # Update the links tables
2273 $u = new LinksUpdate( $this->mTitle, $poutput );
2274 $u->doUpdate();
2276 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2277 wfSeedRandom();
2278 if ( 0 == mt_rand( 0, 999 ) ) {
2279 # Periodically flush old entries from the recentchanges table.
2280 global $wgRCMaxAge;
2282 $dbw =& wfGetDB( DB_MASTER );
2283 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2284 $recentchanges = $dbw->tableName( 'recentchanges' );
2285 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2286 $dbw->query( $sql );
2290 $id = $this->getID();
2291 $title = $this->mTitle->getPrefixedDBkey();
2292 $shortTitle = $this->mTitle->getDBkey();
2294 if ( 0 == $id ) {
2295 wfProfileOut( $fname );
2296 return;
2299 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2300 array_push( $wgDeferredUpdateList, $u );
2301 $u = new SearchUpdate( $id, $title, $text );
2302 array_push( $wgDeferredUpdateList, $u );
2304 # If this is another user's talk page, update newtalk
2306 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2307 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2308 $other = User::newFromName( $shortTitle );
2309 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2310 // An anonymous user
2311 $other = new User();
2312 $other->setName( $shortTitle );
2314 if( $other ) {
2315 $other->setNewtalk( true );
2320 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2321 $wgMessageCache->replace( $shortTitle, $text );
2324 wfProfileOut( $fname );
2328 * Generate the navigation links when browsing through an article revisions
2329 * It shows the information as:
2330 * Revision as of <date>; view current revision
2331 * <- Previous version | Next Version ->
2333 * @access private
2334 * @param string $oldid Revision ID of this article revision
2336 function setOldSubtitle( $oldid=0 ) {
2337 global $wgLang, $wgOut, $wgUser;
2339 $current = ( $oldid == $this->mLatest );
2340 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2341 $sk = $wgUser->getSkin();
2342 $lnk = $current
2343 ? wfMsg( 'currentrevisionlink' )
2344 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2345 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2346 $prevlink = $prev
2347 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2348 : wfMsg( 'previousrevision' );
2349 $nextlink = $current
2350 ? wfMsg( 'nextrevision' )
2351 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2352 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2353 $wgOut->setSubtitle( $r );
2357 * This function is called right before saving the wikitext,
2358 * so we can do things like signatures and links-in-context.
2360 * @param string $text
2362 function preSaveTransform( $text ) {
2363 global $wgParser, $wgUser;
2364 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2367 /* Caching functions */
2370 * checkLastModified returns true if it has taken care of all
2371 * output to the client that is necessary for this request.
2372 * (that is, it has sent a cached version of the page)
2374 function tryFileCache() {
2375 static $called = false;
2376 if( $called ) {
2377 wfDebug( " tryFileCache() -- called twice!?\n" );
2378 return;
2380 $called = true;
2381 if($this->isFileCacheable()) {
2382 $touched = $this->mTouched;
2383 $cache = new CacheManager( $this->mTitle );
2384 if($cache->isFileCacheGood( $touched )) {
2385 wfDebug( " tryFileCache() - about to load\n" );
2386 $cache->loadFromFileCache();
2387 return true;
2388 } else {
2389 wfDebug( " tryFileCache() - starting buffer\n" );
2390 ob_start( array(&$cache, 'saveToFileCache' ) );
2392 } else {
2393 wfDebug( " tryFileCache() - not cacheable\n" );
2398 * Check if the page can be cached
2399 * @return bool
2401 function isFileCacheable() {
2402 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2403 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2405 return $wgUseFileCache
2406 and (!$wgShowIPinHeader)
2407 and ($this->getID() != 0)
2408 and ($wgUser->isAnon())
2409 and (!$wgUser->getNewtalk())
2410 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2411 and (empty( $action ) || $action == 'view')
2412 and (!isset($oldid))
2413 and (!isset($diff))
2414 and (!isset($redirect))
2415 and (!isset($printable))
2416 and (!$this->mRedirectedFrom);
2420 * Loads page_touched and returns a value indicating if it should be used
2423 function checkTouched() {
2424 $fname = 'Article::checkTouched';
2425 if( !$this->mDataLoaded ) {
2426 $this->loadPageData();
2428 return !$this->mIsRedirect;
2432 * Get the page_touched field
2434 function getTouched() {
2435 # Ensure that page data has been loaded
2436 if( !$this->mDataLoaded ) {
2437 $this->loadPageData();
2439 return $this->mTouched;
2443 * Get the page_latest field
2445 function getLatest() {
2446 if ( !$this->mDataLoaded ) {
2447 $this->loadPageData();
2449 return $this->mLatest;
2453 * Edit an article without doing all that other stuff
2454 * The article must already exist; link tables etc
2455 * are not updated, caches are not flushed.
2457 * @param string $text text submitted
2458 * @param string $comment comment submitted
2459 * @param bool $minor whereas it's a minor modification
2461 function quickEdit( $text, $comment = '', $minor = 0 ) {
2462 $fname = 'Article::quickEdit';
2463 wfProfileIn( $fname );
2465 $dbw =& wfGetDB( DB_MASTER );
2466 $dbw->begin();
2467 $revision = new Revision( array(
2468 'page' => $this->getId(),
2469 'text' => $text,
2470 'comment' => $comment,
2471 'minor_edit' => $minor ? 1 : 0,
2472 ) );
2473 $revisionId = $revision->insertOn( $dbw );
2474 $this->updateRevisionOn( $dbw, $revision );
2475 $dbw->commit();
2477 wfProfileOut( $fname );
2481 * Used to increment the view counter
2483 * @static
2484 * @param integer $id article id
2486 function incViewCount( $id ) {
2487 $id = intval( $id );
2488 global $wgHitcounterUpdateFreq;
2490 $dbw =& wfGetDB( DB_MASTER );
2491 $pageTable = $dbw->tableName( 'page' );
2492 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2493 $acchitsTable = $dbw->tableName( 'acchits' );
2495 if( $wgHitcounterUpdateFreq <= 1 ){ //
2496 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2497 return;
2500 # Not important enough to warrant an error page in case of failure
2501 $oldignore = $dbw->ignoreErrors( true );
2503 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2505 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2506 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2507 # Most of the time (or on SQL errors), skip row count check
2508 $dbw->ignoreErrors( $oldignore );
2509 return;
2512 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2513 $row = $dbw->fetchObject( $res );
2514 $rown = intval( $row->n );
2515 if( $rown >= $wgHitcounterUpdateFreq ){
2516 wfProfileIn( 'Article::incViewCount-collect' );
2517 $old_user_abort = ignore_user_abort( true );
2519 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2520 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2521 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2522 'GROUP BY hc_id');
2523 $dbw->query("DELETE FROM $hitcounterTable");
2524 $dbw->query('UNLOCK TABLES');
2525 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2526 'WHERE page_id = hc_id');
2527 $dbw->query("DROP TABLE $acchitsTable");
2529 ignore_user_abort( $old_user_abort );
2530 wfProfileOut( 'Article::incViewCount-collect' );
2532 $dbw->ignoreErrors( $oldignore );
2535 /**#@+
2536 * The onArticle*() functions are supposed to be a kind of hooks
2537 * which should be called whenever any of the specified actions
2538 * are done.
2540 * This is a good place to put code to clear caches, for instance.
2542 * This is called on page move and undelete, as well as edit
2543 * @static
2544 * @param $title_obj a title object
2547 function onArticleCreate($title_obj) {
2548 global $wgUseSquid, $wgPostCommitUpdateList;
2550 $title_obj->touchLinks();
2551 $titles = $title_obj->getLinksTo();
2553 # Purge squid
2554 if ( $wgUseSquid ) {
2555 $urls = $title_obj->getSquidURLs();
2556 foreach ( $titles as $linkTitle ) {
2557 $urls[] = $linkTitle->getInternalURL();
2559 $u = new SquidUpdate( $urls );
2560 array_push( $wgPostCommitUpdateList, $u );
2564 function onArticleDelete( $title ) {
2565 global $wgMessageCache;
2567 $title->touchLinks();
2569 if( $title->getNamespace() == NS_MEDIAWIKI) {
2570 $wgMessageCache->replace( $title->getDBkey(), false );
2575 * Purge caches on page update etc
2577 function onArticleEdit( $title ) {
2578 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2580 $urls = array();
2582 // Template namespace? Purge all articles linking here.
2583 // FIXME: When a templatelinks table arrives, use it for all includes.
2584 if ( $title->getNamespace() == NS_TEMPLATE) {
2585 $titles = $title->getLinksTo();
2586 Title::touchArray( $titles );
2587 if ( $wgUseSquid ) {
2588 foreach ( $titles as $link ) {
2589 $urls[] = $link->getInternalURL();
2594 # Squid updates
2595 if ( $wgUseSquid ) {
2596 $urls = array_merge( $urls, $title->getSquidURLs() );
2597 $u = new SquidUpdate( $urls );
2598 array_push( $wgPostCommitUpdateList, $u );
2601 # File cache
2602 if ( $wgUseFileCache ) {
2603 $cm = new CacheManager( $title );
2604 @unlink( $cm->fileCacheName() );
2608 /**#@-*/
2611 * Info about this page
2612 * Called for ?action=info when $wgAllowPageInfo is on.
2614 * @access public
2616 function info() {
2617 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2618 $fname = 'Article::info';
2620 if ( !$wgAllowPageInfo ) {
2621 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2622 return;
2625 $page = $this->mTitle->getSubjectPage();
2627 $wgOut->setPagetitle( $page->getPrefixedText() );
2628 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2630 # first, see if the page exists at all.
2631 $exists = $page->getArticleId() != 0;
2632 if( !$exists ) {
2633 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2634 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2635 } else {
2636 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2638 } else {
2639 $dbr =& wfGetDB( DB_SLAVE );
2640 $wl_clause = array(
2641 'wl_title' => $page->getDBkey(),
2642 'wl_namespace' => $page->getNamespace() );
2643 $numwatchers = $dbr->selectField(
2644 'watchlist',
2645 'COUNT(*)',
2646 $wl_clause,
2647 $fname,
2648 $this->getSelectOptions() );
2650 $pageInfo = $this->pageCountInfo( $page );
2651 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2653 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2654 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2655 if( $talkInfo ) {
2656 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2658 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2659 if( $talkInfo ) {
2660 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2662 $wgOut->addHTML( '</ul>' );
2668 * Return the total number of edits and number of unique editors
2669 * on a given page. If page does not exist, returns false.
2671 * @param Title $title
2672 * @return array
2673 * @access private
2675 function pageCountInfo( $title ) {
2676 $id = $title->getArticleId();
2677 if( $id == 0 ) {
2678 return false;
2681 $dbr =& wfGetDB( DB_SLAVE );
2683 $rev_clause = array( 'rev_page' => $id );
2684 $fname = 'Article::pageCountInfo';
2686 $edits = $dbr->selectField(
2687 'revision',
2688 'COUNT(rev_page)',
2689 $rev_clause,
2690 $fname,
2691 $this->getSelectOptions() );
2693 $authors = $dbr->selectField(
2694 'revision',
2695 'COUNT(DISTINCT rev_user_text)',
2696 $rev_clause,
2697 $fname,
2698 $this->getSelectOptions() );
2700 return array( 'edits' => $edits, 'authors' => $authors );
2704 * Return a list of templates used by this article.
2705 * Uses the templatelinks table
2707 * @return array Array of Title objects
2709 function getUsedTemplates() {
2710 $result = array();
2711 $id = $this->mTitle->getArticleID();
2712 if( $id == 0 ) {
2713 return array();
2716 $dbr =& wfGetDB( DB_SLAVE );
2717 $res = $dbr->select( array( 'templatelinks' ),
2718 array( 'tl_namespace', 'tl_title' ),
2719 array( 'tl_from' => $id ),
2720 'Article:getUsedTemplates' );
2721 if ( false !== $res ) {
2722 if ( $dbr->numRows( $res ) ) {
2723 while ( $row = $dbr->fetchObject( $res ) ) {
2724 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2728 $dbr->freeResult( $res );
2729 return $result;