8 * Need the CacheManager to be loaded
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
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.
31 var $mContentLoaded; //!<
35 var $mGoodAdjustment; //!<
40 var $mRedirectedFrom; //!<
41 var $mRedirectUrl; //!<
42 var $mRevIdFetched; //!<
47 var $mTotalAdjustment; //!<
54 * Constructor and clear the article
55 * @param $title Reference to a Title object.
56 * @param $oldId Integer revision ID, null to fetch from request, zero for current
58 function Article( &$title, $oldId = null ) {
59 $this->mTitle
=& $title;
60 $this->mOldId
= $oldId;
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
69 function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom
= $from;
74 * @return mixed false, Title of in-wiki target, or string with URL
76 function followRedirect() {
77 $text = $this->getContent();
78 $rt = Title
::newFromRedirect( $text );
80 # process if title object is valid and not special:userlogout
82 if( $rt->getInterwiki() != '' ) {
83 if( $rt->isLocal() ) {
84 // Offsite wikis need an HTTP redirect.
86 // This can be hard to reverse and may produce loops,
87 // so they may be disabled in the site configuration.
89 $source = $this->mTitle
->getFullURL( 'redirect=no' );
90 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
93 if( $rt->getNamespace() == NS_SPECIAL
) {
94 // Gotta hand redirects to special pages differently:
95 // Fill the HTTP response "Location" header and ignore
96 // the rest of the page we're on.
98 // This can be hard to reverse, so they may be disabled.
100 if( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) {
103 return $rt->getFullURL();
110 // No or invalid redirect
115 * get the title object of the article
117 function getTitle() {
118 return $this->mTitle
;
126 $this->mDataLoaded
= false;
127 $this->mContentLoaded
= false;
129 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
130 $this->mRedirectedFrom
= null; # Title object if set
132 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
133 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
134 $this->mTouched
= '19700101000000';
135 $this->mForUpdate
= false;
136 $this->mIsRedirect
= false;
137 $this->mRevIdFetched
= 0;
138 $this->mRedirectUrl
= false;
139 $this->mLatest
= false;
143 * Note that getContent/loadContent do not follow redirects anymore.
144 * If you need to fetch redirectable content easily, try
145 * the shortcut in Article::followContent()
147 * @todo There are still side-effects in this!
148 * In general, you should use the Revision class, not Article,
149 * to fetch text for purposes other than page views.
151 * @return Return the text of this revision
153 function getContent() {
154 global $wgRequest, $wgUser, $wgOut;
156 # Get variables from query string :P
157 $action = $wgRequest->getText( 'action', 'view' );
158 $section = $wgRequest->getText( 'section' );
159 $preload = $wgRequest->getText( 'preload' );
161 $fname = 'Article::getContent';
162 wfProfileIn( $fname );
164 if ( 0 == $this->getID() ) {
165 if ( 'edit' == $action ) {
166 wfProfileOut( $fname );
168 # If requested, preload some text.
169 $text=$this->getPreloadedText($preload);
171 # We used to put MediaWiki:Newarticletext here if
172 # $text was empty at this point.
173 # This is now shown above the edit box instead.
176 wfProfileOut( $fname );
177 $wgOut->setRobotpolicy( 'noindex,nofollow' );
179 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
180 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
182 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
185 return "<div class='noarticletext'>$ret</div>";
187 $this->loadContent();
188 if($action=='edit') {
190 if($section=='new') {
191 wfProfileOut( $fname );
192 $text=$this->getPreloadedText($preload);
196 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
197 # comments to be stripped as well)
198 $rv=$this->getSection($this->mContent
,$section);
199 wfProfileOut( $fname );
203 wfProfileOut( $fname );
204 return $this->mContent
;
209 * Get the contents of a page from its title and remove includeonly tags
211 * @param $preload String: the title of the page.
212 * @return string The contents of the page.
214 function getPreloadedText($preload) {
215 if ( $preload === '' )
218 $preloadTitle = Title
::newFromText( $preload );
219 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
220 $rev=Revision
::newFromTitle($preloadTitle);
221 if ( is_object( $rev ) ) {
222 $text = $rev->getText();
223 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
224 // its own mini-parser! -ævar
225 $text = preg_replace( '~</?includeonly>~', '', $text );
234 * This function returns the text of a section, specified by a number ($section).
235 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
236 * the first section before any such heading (section 0).
238 * If a section contains subsections, these are also returned.
240 * @param $text String: text to look in
241 * @param $section Integer: section number
242 * @return string text of the requested section
244 function getSection($text,$section) {
246 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
247 # comments to be stripped as well)
249 $parser=new Parser();
250 $parser->mOutputType
=OT_WIKI
;
251 $parser->mOptions
= new ParserOptions();
252 $striptext=$parser->strip($text, $striparray, true);
254 # now that we can be sure that no pseudo-sections are in the source,
255 # split it up by section
258 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
260 PREG_SPLIT_DELIM_CAPTURE
);
264 $headline=$secs[$section*2-1];
265 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
268 # translate wiki heading into level
269 if(strpos($hlevel,'=')!==false) {
270 $hlevel=strlen($hlevel);
273 $rv=$headline. $secs[$section*2];
277 while(!empty($secs[$count*2-1]) && !$break) {
279 $subheadline=$secs[$count*2-1];
280 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
281 $subhlevel=$matches[1];
282 if(strpos($subhlevel,'=')!==false) {
283 $subhlevel=strlen($subhlevel);
285 if($subhlevel > $hlevel) {
286 $rv.=$subheadline.$secs[$count*2];
288 if($subhlevel <= $hlevel) {
295 # reinsert stripped tags
296 $rv=$parser->unstrip($rv,$striparray);
297 $rv=$parser->unstripNoWiki($rv,$striparray);
304 * @return int The oldid of the article that is to be shown, 0 for the
307 function getOldID() {
308 if ( is_null( $this->mOldId
) ) {
309 $this->mOldId
= $this->getOldIDFromRequest();
311 return $this->mOldId
;
315 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
317 * @return int The old id for the request
319 function getOldIDFromRequest() {
321 $this->mRedirectUrl
= false;
322 $oldid = $wgRequest->getVal( 'oldid' );
323 if ( isset( $oldid ) ) {
324 $oldid = intval( $oldid );
325 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
326 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
330 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
332 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
333 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
350 * Load the revision (including text) into this object
352 function loadContent() {
353 if ( $this->mContentLoaded
) return;
356 $oldid = $this->getOldID();
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
374 function pageData( &$dbr, $conditions ) {
387 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
388 $row = $dbr->selectRow( 'page',
391 'Article::pageData' );
392 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$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
410 function pageDataFromId( &$dbr, $id ) {
411 return $this->pageData( $dbr, array( 'page_id' => $id ) );
415 * Set the general counter, title etc data loaded from
418 * @param object $data
421 function loadPageData( $data = 'fromdb' ) {
422 if ( $data === 'fromdb' ) {
423 $dbr =& $this->getDB();
424 $data = $this->pageDataFromId( $dbr, $this->getId() );
427 $lc =& LinkCache
::singleton();
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
;
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
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();
467 $t .= ',oldid='.$oldid;
469 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
472 $revision = Revision
::newFromId( $oldid );
473 if( is_null( $revision ) ) {
474 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
477 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
479 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
482 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
483 $this->loadPageData( $data );
485 if( !$this->mDataLoaded
) {
486 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
488 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
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" );
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 $x Mixed: FIXME
524 function forUpdate( $x = NULL ) {
525 return wfSetVar( $this->mForUpdate
, $x );
529 * Get the database which should be used for reads
534 $ret =& wfGetDB( DB_MASTER
);
539 * Get options for all SELECT statements
541 * @param $options Array: an optional options array which'll be appended to
543 * @return Array: options
545 function getSelectOptions( $options = '' ) {
546 if ( $this->mForUpdate
) {
547 if ( is_array( $options ) ) {
548 $options[] = 'FOR UPDATE';
550 $options = 'FOR UPDATE';
557 * @return int Page ID
560 if( $this->mTitle
) {
561 return $this->mTitle
->getArticleID();
568 * @return bool Whether or not the page exists in the database
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();
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 $text String: text to analyze
598 function isCountable( $text ) {
599 global $wgUseCommaCount;
601 $token = $wgUseCommaCount ?
',' : '[[';
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 $text String: FIXME
614 function isRedirect( $text = false ) {
615 if ( $text === false ) {
616 $this->loadContent();
617 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
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).
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.
640 function loadLastEdit() {
641 if ( -1 != $this->mUser
)
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
);
668 $this->loadLastEdit();
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
;
693 * @todo Document, fixme $offset never used.
694 * @param $limit Integer: default 0.
695 * @param $offset Integer: default 0.
697 function getContributors($limit = 0, $offset = 0) {
698 $fname = 'Article::getContributors';
700 # XXX: this is expensive; cache this info somewhere.
702 $title = $this->mTitle
;
704 $dbr =& wfGetDB( DB_SLAVE
);
705 $revTable = $dbr->tableName( 'revision' );
706 $userTable = $dbr->tableName( 'user' );
707 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
708 $ns = $title->getNamespace();
709 $user = $this->getUser();
710 $pageId = $this->getId();
712 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
713 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
714 WHERE rev_page = $pageId
715 AND rev_user != $user
716 GROUP BY rev_user, rev_user_text, user_real_name
717 ORDER BY timestamp DESC";
719 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
720 $sql .= ' '. $this->getSelectOptions();
722 $res = $dbr->query($sql, $fname);
724 while ( $line = $dbr->fetchObject( $res ) ) {
725 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
728 $dbr->freeResult($res);
733 * This is the default action of the script: just view the page of
737 global $wgUser, $wgOut, $wgRequest, $wgContLang;
738 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
739 global $wgUseTrackbacks;
740 $sk = $wgUser->getSkin();
742 $fname = 'Article::view';
743 wfProfileIn( $fname );
744 $parserCache =& ParserCache
::singleton();
745 # Get variables from query string
746 $oldid = $this->getOldID();
748 # getOldID may want us to redirect somewhere else
749 if ( $this->mRedirectUrl
) {
750 $wgOut->redirect( $this->mRedirectUrl
);
751 wfProfileOut( $fname );
755 $diff = $wgRequest->getVal( 'diff' );
756 $rcid = $wgRequest->getVal( 'rcid' );
757 $rdfrom = $wgRequest->getVal( 'rdfrom' );
759 $wgOut->setArticleFlag( true );
760 $wgOut->setRobotpolicy( 'index,follow' );
761 # If we got diff and oldid in the query, we want to see a
762 # diff page instead of the article.
764 if ( !is_null( $diff ) ) {
765 require_once( 'DifferenceEngine.php' );
766 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
768 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
769 // DifferenceEngine directly fetched the revision:
770 $this->mRevIdFetched
= $de->mNewid
;
774 # Run view updates for current revision only
775 $this->viewUpdates();
777 wfProfileOut( $fname );
781 if ( empty( $oldid ) && $this->checkTouched() ) {
782 $wgOut->setETag($parserCache->getETag($this, $wgUser));
784 if( $wgOut->checkLastModified( $this->mTouched
) ){
785 wfProfileOut( $fname );
787 } else if ( $this->tryFileCache() ) {
788 # tell wgOut that output is taken care of
790 $this->viewUpdates();
791 wfProfileOut( $fname );
795 # Should the parser cache be used?
796 $pcache = $wgEnableParserCache &&
797 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
800 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
801 if ( $wgUser->getOption( 'stubthreshold' ) ) {
802 wfIncrStats( 'pcache_miss_stub' );
805 $wasRedirected = false;
806 if ( isset( $this->mRedirectedFrom
) ) {
807 // This is an internally redirected page view.
808 // We'll need a backlink to the source page for navigation.
809 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
810 $sk = $wgUser->getSkin();
811 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
812 $s = wfMsg( 'redirectedfrom', $redir );
813 $wgOut->setSubtitle( $s );
814 $wasRedirected = true;
816 } elseif ( !empty( $rdfrom ) ) {
817 // This is an externally redirected view, from some other wiki.
818 // If it was reported from a trusted site, supply a backlink.
819 global $wgRedirectSources;
820 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
821 $sk = $wgUser->getSkin();
822 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
823 $s = wfMsg( 'redirectedfrom', $redir );
824 $wgOut->setSubtitle( $s );
825 $wasRedirected = true;
831 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
835 if ( !$outputDone ) {
836 $text = $this->getContent();
837 if ( $text === false ) {
838 # Failed to load, replace text with error message
839 $t = $this->mTitle
->getPrefixedText();
841 $t .= ',oldid='.$oldid;
842 $text = wfMsg( 'missingarticle', $t );
844 $text = wfMsg( 'noarticletext', $t );
848 # Another whitelist check in case oldid is altering the title
849 if ( !$this->mTitle
->userCanRead() ) {
850 $wgOut->loginToUse();
855 # We're looking at an old revision
857 if ( !empty( $oldid ) ) {
858 $wgOut->setRobotpolicy( 'noindex,nofollow' );
859 if( is_null( $this->mRevision
) ) {
860 // FIXME: This would be a nice place to load the 'no such page' text.
862 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
863 if( $this->mRevision
->isDeleted( MW_REV_DELETED_TEXT
) ) {
864 if( !$this->mRevision
->userCan( MW_REV_DELETED_TEXT
) ) {
865 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
866 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
869 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
870 // and we are allowed to see...
879 * @fixme: this hook doesn't work most of the time, as it doesn't
880 * trigger when the parser cache is used.
882 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
883 $wgOut->setRevisionId( $this->getRevIdFetched() );
884 # wrap user css and user js in pre and don't parse
885 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
887 $this->mTitle
->getNamespace() == NS_USER
&&
888 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
890 $wgOut->addWikiText( wfMsg('clearyourcache'));
891 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
892 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
894 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
895 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
896 # Don't overwrite the subtitle if this was an old revision
897 if( !$wasRedirected && $this->isCurrent() ) {
898 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
900 $targetUrl = $rt->escapeLocalURL();
901 #Â fixme unused $titleText :
902 $titleText = htmlspecialchars( $rt->getPrefixedText() );
903 $link = $sk->makeLinkObj( $rt );
905 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
906 '<span class="redirectText">'.$link.'</span>' );
908 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
909 $wgOut->addParserOutputNoText( $parseout );
910 } else if ( $pcache ) {
911 # Display content and save to parser cache
912 $wgOut->addPrimaryWikiText( $text, $this );
914 # Display content, don't attempt to save to parser cache
916 # Don't show section-edit links on old revisions... this way lies madness.
917 if( !$this->isCurrent() ) {
918 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
920 # Display content and don't save to parser cache
921 $wgOut->addPrimaryWikiText( $text, $this, false );
923 if( !$this->isCurrent() ) {
924 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
928 /* title may have been set from the cache */
929 $t = $wgOut->getPageTitle();
931 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
934 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
935 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
936 User
::isIP( $this->mTitle
->getText() ) ) {
937 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
940 # If we have been passed an &rcid= parameter, we want to give the user a
941 # chance to mark this new article as patrolled.
942 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
944 "<div class='patrollink'>" .
945 wfMsg ( 'markaspatrolledlink',
946 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
953 if ($wgUseTrackbacks)
954 $this->addTrackbacks();
956 $this->viewUpdates();
957 wfProfileOut( $fname );
960 function addTrackbacks() {
961 global $wgOut, $wgUser;
963 $dbr =& wfGetDB(DB_SLAVE
);
965 /* FROM */ 'trackbacks',
966 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
967 /* WHERE */ array('tb_page' => $this->getID())
970 if (!$dbr->numrows($tbs))
974 while ($o = $dbr->fetchObject($tbs)) {
976 if ($wgUser->isAllowed( 'trackback' )) {
977 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
978 . $o->tb_id
. "&token=" . $wgUser->editToken());
979 $rmvtxt = wfMsg('trackbackremove', $delurl);
981 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
988 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
991 function deletetrackback() {
992 global $wgUser, $wgRequest, $wgOut, $wgTitle;
994 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
995 $wgOut->addWikitext(wfMsg('sessionfailure'));
999 if ((!$wgUser->isAllowed('delete'))) {
1000 $wgOut->sysopRequired();
1005 $wgOut->readOnlyPage();
1009 $db =& wfGetDB(DB_MASTER
);
1010 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1011 $wgTitle->invalidateCache();
1012 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1018 $wgOut->setArticleBodyOnly(true);
1023 * Handle action=purge
1026 global $wgUser, $wgRequest, $wgOut;
1028 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1029 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1033 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1034 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1035 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1036 $msg = str_replace( '$1',
1037 "<form method=\"post\" action=\"$action\">\n" .
1038 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1039 "</form>\n", $msg );
1041 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1042 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1043 $wgOut->addHTML( $msg );
1048 * Perform the actions of a page purging
1050 function doPurge() {
1052 // Invalidate the cache
1053 $this->mTitle
->invalidateCache();
1055 if ( $wgUseSquid ) {
1056 // Commit the transaction before the purge is sent
1057 $dbw = wfGetDB( DB_MASTER
);
1058 $dbw->immediateCommit();
1061 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1062 $update->doUpdate();
1068 * Insert a new empty page record for this article.
1069 * This *must* be followed up by creating a revision
1070 * and running $this->updateToLatest( $rev_id );
1071 * or else the record will be left in a funky state.
1072 * Best if all done inside a transaction.
1074 * @param Database $dbw
1075 * @param string $restrictions
1076 * @return int The newly created page_id key
1079 function insertOn( &$dbw, $restrictions = '' ) {
1080 $fname = 'Article::insertOn';
1081 wfProfileIn( $fname );
1083 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1084 $dbw->insert( 'page', array(
1085 'page_id' => $page_id,
1086 'page_namespace' => $this->mTitle
->getNamespace(),
1087 'page_title' => $this->mTitle
->getDBkey(),
1088 'page_counter' => 0,
1089 'page_restrictions' => $restrictions,
1090 'page_is_redirect' => 0, # Will set this shortly...
1092 'page_random' => wfRandom(),
1093 'page_touched' => $dbw->timestamp(),
1094 'page_latest' => 0, # Fill this in shortly...
1095 'page_len' => 0, # Fill this in shortly...
1097 $newid = $dbw->insertId();
1099 $this->mTitle
->resetArticleId( $newid );
1101 wfProfileOut( $fname );
1106 * Update the page record to point to a newly saved revision.
1108 * @param Database $dbw
1109 * @param Revision $revision For ID number, and text used to set
1110 length and redirect status fields
1111 * @param int $lastRevision If given, will not overwrite the page field
1112 * when different from the currently set value.
1113 * Giving 0 indicates the new page flag should
1115 * @return bool true on success, false on failure
1118 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1119 $fname = 'Article::updateToRevision';
1120 wfProfileIn( $fname );
1122 $conditions = array( 'page_id' => $this->getId() );
1123 if( !is_null( $lastRevision ) ) {
1124 # An extra check against threads stepping on each other
1125 $conditions['page_latest'] = $lastRevision;
1128 $text = $revision->getText();
1129 $dbw->update( 'page',
1131 'page_latest' => $revision->getId(),
1132 'page_touched' => $dbw->timestamp(),
1133 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1134 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1135 'page_len' => strlen( $text ),
1140 wfProfileOut( $fname );
1141 return ( $dbw->affectedRows() != 0 );
1145 * If the given revision is newer than the currently set page_latest,
1146 * update the page record. Otherwise, do nothing.
1148 * @param Database $dbw
1149 * @param Revision $revision
1151 function updateIfNewerOn( &$dbw, $revision ) {
1152 $fname = 'Article::updateIfNewerOn';
1153 wfProfileIn( $fname );
1155 $row = $dbw->selectRow(
1156 array( 'revision', 'page' ),
1157 array( 'rev_id', 'rev_timestamp' ),
1159 'page_id' => $this->getId(),
1160 'page_latest=rev_id' ),
1163 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1164 wfProfileOut( $fname );
1167 $prev = $row->rev_id
;
1169 # No or missing previous revision; mark the page as new
1173 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1174 wfProfileOut( $fname );
1179 * Insert a new article into the database
1182 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1185 $fname = 'Article::insertNewArticle';
1186 wfProfileIn( $fname );
1188 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1189 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1190 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1191 wfProfileOut( $fname );
1195 $ns = $this->mTitle
->getNamespace();
1196 $ttl = $this->mTitle
->getDBkey();
1198 # If this is a comment, add the summary as headline
1199 if($comment && $summary!="") {
1200 $text="== {$summary} ==\n\n".$text;
1202 $text = $this->preSaveTransform( $text );
1205 # Set statistics members
1206 # We work out if it's countable after PST to avoid counter drift
1207 # when articles are created with {{subst:}}
1208 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1209 $this->mTotalAdjustment
= 1;
1211 /* Silently ignore minoredit if not allowed */
1212 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1213 $now = wfTimestampNow();
1215 $dbw =& wfGetDB( DB_MASTER
);
1217 # Add the page record; stake our claim on this title!
1218 $newid = $this->insertOn( $dbw );
1220 # Save the revision text...
1221 $revision = new Revision( array(
1223 'comment' => $summary,
1224 'minor_edit' => $isminor,
1227 $revisionId = $revision->insertOn( $dbw );
1229 $this->mTitle
->resetArticleID( $newid );
1231 # Update the page record with revision data
1232 $this->updateRevisionOn( $dbw, $revision, 0 );
1234 Article
::onArticleCreate( $this->mTitle
);
1236 require_once( 'RecentChange.php' );
1237 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1238 '', strlen( $text ), $revisionId );
1239 # Mark as patrolled if the user can and has the option set
1240 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1241 RecentChange
::markPatrolled( $rcid );
1246 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1248 if ( $this->mTitle
->userIsWatching() ) {
1253 # The talk page isn't in the regular link tables, so we need to update manually:
1254 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1255 $dbw->update( 'page',
1256 array( 'page_touched' => $dbw->timestamp($now) ),
1257 array( 'page_namespace' => $talkns,
1258 'page_title' => $ttl ),
1261 # standard deferred updates
1262 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1264 $oldid = 0; # new article
1265 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1267 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1269 $watchthis, NULL ) );
1270 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1272 $watchthis, NULL ) );
1273 wfProfileOut( $fname );
1277 * @return string Complete article text, or null if error
1279 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1280 $fname = 'Article::replaceSection';
1281 wfProfileIn( $fname );
1283 if ($section != '') {
1284 if( is_null( $edittime ) ) {
1285 $rev = Revision
::newFromTitle( $this->mTitle
);
1287 $dbw =& wfGetDB( DB_MASTER
);
1288 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1290 if( is_null( $rev ) ) {
1291 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1292 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1295 $oldtext = $rev->getText();
1297 if($section=='new') {
1298 if($summary) $subject="== {$summary} ==\n\n";
1299 $text=$oldtext."\n\n".$subject.$text;
1302 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1303 # comments to be stripped as well)
1304 $striparray=array();
1305 $parser=new Parser();
1306 $parser->mOutputType
=OT_WIKI
;
1307 $parser->mOptions
= new ParserOptions();
1308 $oldtext=$parser->strip($oldtext, $striparray, true);
1310 # now that we can be sure that no pseudo-sections are in the source,
1312 # Unfortunately we can't simply do a preg_replace because that might
1313 # replace the wrong section, so we have to use the section counter instead
1314 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1315 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1316 $secs[$section*2]=$text."\n\n"; // replace with edited
1318 # section 0 is top (intro) section
1321 # headline of old section - we need to go through this section
1322 # to determine if there are any subsections that now need to
1323 # be erased, as the mother section has been replaced with
1324 # the text of all subsections.
1325 $headline=$secs[$section*2-1];
1326 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1327 $hlevel=$matches[1];
1329 # determine headline level for wikimarkup headings
1330 if(strpos($hlevel,'=')!==false) {
1331 $hlevel=strlen($hlevel);
1334 $secs[$section*2-1]=''; // erase old headline
1337 while(!empty($secs[$count*2-1]) && !$break) {
1339 $subheadline=$secs[$count*2-1];
1341 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1342 $subhlevel=$matches[1];
1343 if(strpos($subhlevel,'=')!==false) {
1344 $subhlevel=strlen($subhlevel);
1346 if($subhlevel > $hlevel) {
1347 // erase old subsections
1348 $secs[$count*2-1]='';
1351 if($subhlevel <= $hlevel) {
1359 $text=join('',$secs);
1360 # reinsert the stuff that we stripped out earlier
1361 $text=$parser->unstrip($text,$striparray);
1362 $text=$parser->unstripNoWiki($text,$striparray);
1366 wfProfileOut( $fname );
1371 * Change an existing article. Puts the previous version back into the old table, updates RC
1372 * and all necessary caches, mostly via the deferred update array.
1374 * It is possible to call this function from a command-line script, but note that you should
1375 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1377 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1378 global $wgUser, $wgDBtransactions, $wgUseSquid;
1379 global $wgPostCommitUpdateList, $wgUseFileCache;
1381 $fname = 'Article::updateArticle';
1382 wfProfileIn( $fname );
1385 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1387 &$watchthis, &$sectionanchor ) ) ) {
1388 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1389 wfProfileOut( $fname );
1393 $isminor = $minor && $wgUser->isAllowed('minoredit');
1395 $text = $this->preSaveTransform( $text );
1396 $dbw =& wfGetDB( DB_MASTER
);
1397 $now = wfTimestampNow();
1399 # Update article, but only if changed.
1401 # It's important that we either rollback or complete, otherwise an attacker could
1402 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1403 # could conceivably have the same effect, especially if cur is locked for long periods.
1404 if( !$wgDBtransactions ) {
1405 $userAbort = ignore_user_abort( true );
1408 $oldtext = $this->getContent();
1409 $oldsize = strlen( $oldtext );
1410 $newsize = strlen( $text );
1414 if ( 0 != strcmp( $text, $oldtext ) ) {
1415 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1416 - (int)$this->isCountable( $oldtext );
1417 $this->mTotalAdjustment
= 0;
1418 $now = wfTimestampNow();
1420 $lastRevision = $dbw->selectField(
1421 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1423 $revision = new Revision( array(
1424 'page' => $this->getId(),
1425 'comment' => $summary,
1426 'minor_edit' => $isminor,
1430 $dbw->immediateCommit();
1432 $revisionId = $revision->insertOn( $dbw );
1435 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1438 /* Belated edit conflict! Run away!! */
1442 # Update recentchanges and purge cache and whatnot
1443 require_once( 'RecentChange.php' );
1444 $bot = (int)($wgUser->isBot() ||
$forceBot);
1445 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1446 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1449 # Mark as patrolled if the user can do so and has it set in their options
1450 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1451 RecentChange
::markPatrolled( $rcid );
1456 // Update caches outside the main transaction
1457 Article
::onArticleEdit( $this->mTitle
);
1460 // Keep the same revision ID, but do some updates on it
1461 $revisionId = $this->getRevIdFetched();
1464 if( !$wgDBtransactions ) {
1465 ignore_user_abort( $userAbort );
1470 if (!$this->mTitle
->userIsWatching()) {
1471 $dbw->immediateCommit();
1477 if ( $this->mTitle
->userIsWatching() ) {
1478 $dbw->immediateCommit();
1484 # standard deferred updates
1485 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1489 # Invalidate caches of all articles using this article as a template
1491 # Template namespace
1492 # Purge all articles linking here
1493 $titles = $this->mTitle
->getTemplateLinksTo();
1494 Title
::touchArray( $titles );
1495 if ( $wgUseSquid ) {
1496 foreach ( $titles as $title ) {
1497 $urls[] = $title->getInternalURL();
1502 if ( $wgUseSquid ) {
1503 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1504 $u = new SquidUpdate( $urls );
1505 array_push( $wgPostCommitUpdateList, $u );
1509 if ( $wgUseFileCache ) {
1510 $cm = new CacheManager($this->mTitle
);
1511 @unlink
($cm->fileCacheName());
1514 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1516 wfRunHooks( 'ArticleSaveComplete',
1517 array( &$this, &$wgUser, $text,
1519 $watchthis, $sectionanchor ) );
1520 wfProfileOut( $fname );
1525 * After we've either updated or inserted the article, update
1526 * the link tables and redirect to the new page.
1527 * @todo FIXME some function arguments never used
1529 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1532 $fname = 'Article::showArticle';
1533 wfProfileIn( $fname );
1535 # Output the redirect
1536 if( $this->isRedirect( $text ) )
1540 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1542 wfProfileOut( $fname );
1546 * Mark this particular edit as patrolled
1548 function markpatrolled() {
1549 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1550 $wgOut->setRobotpolicy( 'noindex,follow' );
1552 # Check RC patrol config. option
1553 if( !$wgUseRCPatrol ) {
1554 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1559 if( !$wgUser->isAllowed( 'patrol' ) ) {
1560 $wgOut->permissionRequired( 'patrol' );
1564 $rcid = $wgRequest->getVal( 'rcid' );
1565 if ( !is_null ( $rcid ) ) {
1566 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1567 require_once( 'RecentChange.php' );
1568 RecentChange
::markPatrolled( $rcid );
1569 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1570 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1571 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1573 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1574 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1577 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1582 * User-interface handler for the "watch" action
1587 global $wgUser, $wgOut;
1589 if ( $wgUser->isAnon() ) {
1590 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1593 if ( wfReadOnly() ) {
1594 $wgOut->readOnlyPage();
1598 if( $this->doWatch() ) {
1599 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1600 $wgOut->setRobotpolicy( 'noindex,follow' );
1602 $link = $this->mTitle
->getPrefixedText();
1603 $text = wfMsg( 'addedwatchtext', $link );
1604 $wgOut->addWikiText( $text );
1607 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1611 * Add this page to $wgUser's watchlist
1612 * @return bool true on successful watch operation
1614 function doWatch() {
1616 if( $wgUser->isAnon() ) {
1620 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1621 $wgUser->addWatch( $this->mTitle
);
1622 $wgUser->saveSettings();
1624 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1631 * User interface handler for the "unwatch" action.
1633 function unwatch() {
1635 global $wgUser, $wgOut;
1637 if ( $wgUser->isAnon() ) {
1638 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1641 if ( wfReadOnly() ) {
1642 $wgOut->readOnlyPage();
1646 if( $this->doUnwatch() ) {
1647 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1648 $wgOut->setRobotpolicy( 'noindex,follow' );
1650 $link = $this->mTitle
->getPrefixedText();
1651 $text = wfMsg( 'removedwatchtext', $link );
1652 $wgOut->addWikiText( $text );
1655 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1659 * Stop watching a page
1660 * @return bool true on successful unwatch
1662 function doUnwatch() {
1664 if( $wgUser->isAnon() ) {
1668 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1669 $wgUser->removeWatch( $this->mTitle
);
1670 $wgUser->saveSettings();
1672 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1679 * action=protect handler
1681 function protect() {
1682 require_once 'ProtectionForm.php';
1683 $form = new ProtectionForm( $this );
1688 * action=unprotect handler (alias)
1690 function unprotect() {
1695 * Update the article's restriction field, and leave a log entry.
1697 * @param array $limit set of restriction keys
1698 * @param string $reason
1699 * @return bool true on success
1701 function updateRestrictions( $limit = array(), $reason = '' ) {
1702 global $wgUser, $wgRestrictionTypes, $wgContLang;
1704 $id = $this->mTitle
->getArticleID();
1705 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1709 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1710 # we expect a single selection, but the schema allows otherwise.
1712 foreach( $wgRestrictionTypes as $action )
1713 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1715 $current = Article
::flattenRestrictions( $current );
1716 $updated = Article
::flattenRestrictions( $limit );
1718 $changed = ( $current != $updated );
1719 $protect = ( $updated != '' );
1721 # If nothing's changed, do nothing
1723 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1725 $dbw =& wfGetDB( DB_MASTER
);
1727 # Prepare a null revision to be added to the history
1728 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1730 $comment .= ": $reason";
1732 $comment .= " [$updated]";
1733 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1734 $nullRevId = $nullRevision->insertOn( $dbw );
1736 # Update page record
1737 $dbw->update( 'page',
1739 'page_touched' => $dbw->timestamp(),
1740 'page_restrictions' => $updated,
1741 'page_latest' => $nullRevId
1742 ), array( /* WHERE */
1744 ), 'Article::protect'
1746 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1748 # Update the protection log
1749 $log = new LogPage( 'protect' );
1751 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1753 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1757 } # End "changed" check
1763 * Take an array of page restrictions and flatten it to a string
1764 * suitable for insertion into the page_restrictions field.
1765 * @param array $limit
1769 function flattenRestrictions( $limit ) {
1770 if( !is_array( $limit ) ) {
1771 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1775 foreach( $limit as $action => $restrictions ) {
1776 if( $restrictions != '' ) {
1777 $bits[] = "$action=$restrictions";
1780 return implode( ':', $bits );
1784 * UI entry point for page deletion
1787 global $wgUser, $wgOut, $wgRequest;
1788 $fname = 'Article::delete';
1789 $confirm = $wgRequest->wasPosted() &&
1790 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1791 $reason = $wgRequest->getText( 'wpReason' );
1793 # This code desperately needs to be totally rewritten
1796 if( $wgUser->isAllowed( 'delete' ) ) {
1797 if( $wgUser->isBlocked() ) {
1798 $wgOut->blockedPage();
1802 $wgOut->permissionRequired( 'delete' );
1806 if( wfReadOnly() ) {
1807 $wgOut->readOnlyPage();
1811 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1813 # Better double-check that it hasn't been deleted yet!
1814 $dbw =& wfGetDB( DB_MASTER
);
1815 $conds = $this->mTitle
->pageCond();
1816 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1817 if ( $latest === false ) {
1818 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1823 $this->doDelete( $reason );
1827 # determine whether this page has earlier revisions
1828 # and insert a warning if it does
1830 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1832 if( count( $authors ) > 1 && !$confirm ) {
1833 $skin=$wgUser->getSkin();
1834 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1837 # If a single user is responsible for all revisions, find out who they are
1838 if ( count( $authors ) == $maxRevisions ) {
1839 // Query bailed out, too many revisions to find out if they're all the same
1840 $authorOfAll = false;
1842 $authorOfAll = reset( $authors );
1843 foreach ( $authors as $author ) {
1844 if ( $authorOfAll != $author ) {
1845 $authorOfAll = false;
1850 # Fetch article text
1851 $rev = Revision
::newFromTitle( $this->mTitle
);
1853 if( !is_null( $rev ) ) {
1854 # if this is a mini-text, we can paste part of it into the deletion reason
1855 $text = $rev->getText();
1857 #if this is empty, an earlier revision may contain "useful" text
1860 $prev = $rev->getPrevious();
1862 $text = $prev->getText();
1867 $length = strlen( $text );
1869 # this should not happen, since it is not possible to store an empty, new
1870 # page. Let's insert a standard text in case it does, though
1871 if( $length == 0 && $reason === '' ) {
1872 $reason = wfMsgForContent( 'exblank' );
1875 if( $length < 500 && $reason === '' ) {
1876 # comment field=255, let's grep the first 150 to have some user
1879 $text = $wgContLang->truncate( $text, 150, '...' );
1881 # let's strip out newlines
1882 $text = preg_replace( "/[\n\r]/", '', $text );
1885 if( $authorOfAll === false ) {
1886 $reason = wfMsgForContent( 'excontent', $text );
1888 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1891 $reason = wfMsgForContent( 'exbeforeblank', $text );
1896 return $this->confirmDelete( '', $reason );
1900 * Get the last N authors
1901 * @param int $num Number of revisions to get
1902 * @param string $revLatest The latest rev_id, selected from the master (optional)
1903 * @return array Array of authors, duplicates not removed
1905 function getLastNAuthors( $num, $revLatest = 0 ) {
1906 $fname = 'Article::getLastNAuthors';
1907 wfProfileIn( $fname );
1909 // First try the slave
1910 // If that doesn't have the latest revision, try the master
1912 $db =& wfGetDB( DB_SLAVE
);
1914 $res = $db->select( array( 'page', 'revision' ),
1915 array( 'rev_id', 'rev_user_text' ),
1917 'page_namespace' => $this->mTitle
->getNamespace(),
1918 'page_title' => $this->mTitle
->getDBkey(),
1919 'rev_page = page_id'
1920 ), $fname, $this->getSelectOptions( array(
1921 'ORDER BY' => 'rev_timestamp DESC',
1926 wfProfileOut( $fname );
1929 $row = $db->fetchObject( $res );
1930 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1931 $db =& wfGetDB( DB_MASTER
);
1936 } while ( $continue );
1938 $authors = array( $row->rev_user_text
);
1939 while ( $row = $db->fetchObject( $res ) ) {
1940 $authors[] = $row->rev_user_text
;
1942 wfProfileOut( $fname );
1947 * Output deletion confirmation dialog
1949 function confirmDelete( $par, $reason ) {
1950 global $wgOut, $wgUser;
1952 wfDebug( "Article::confirmDelete\n" );
1954 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1955 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1956 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1957 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1959 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1961 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1962 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1963 $token = htmlspecialchars( $wgUser->editToken() );
1966 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1970 <label for='wpReason'>{$delcom}:</label>
1973 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1979 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1983 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1986 $wgOut->returnToMain( false );
1991 * Perform a deletion and output success or failure messages
1993 function doDelete( $reason ) {
1994 global $wgOut, $wgUser;
1995 $fname = 'Article::doDelete';
1996 wfDebug( $fname."\n" );
1998 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1999 if ( $this->doDeleteArticle( $reason ) ) {
2000 $deleted = $this->mTitle
->getPrefixedText();
2002 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2003 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2005 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2006 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2008 $wgOut->addWikiText( $text );
2009 $wgOut->returnToMain( false );
2010 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2012 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2018 * Back-end article deletion
2019 * Deletes the article with database consistency, writes logs, purges caches
2022 function doDeleteArticle( $reason ) {
2023 global $wgUseSquid, $wgDeferredUpdateList;
2024 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2026 $fname = 'Article::doDeleteArticle';
2027 wfDebug( $fname."\n" );
2029 $dbw =& wfGetDB( DB_MASTER
);
2030 $ns = $this->mTitle
->getNamespace();
2031 $t = $this->mTitle
->getDBkey();
2032 $id = $this->mTitle
->getArticleID();
2034 if ( $t == '' ||
$id == 0 ) {
2038 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2039 array_push( $wgDeferredUpdateList, $u );
2041 $linksTo = $this->mTitle
->getLinksTo();
2044 if ( $wgUseSquid ) {
2046 $this->mTitle
->getInternalURL(),
2047 $this->mTitle
->getInternalURL( 'history' )
2050 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2051 array_push( $wgPostCommitUpdateList, $u );
2055 # Client and file cache invalidation
2056 Title
::touchArray( $linksTo );
2059 // For now, shunt the revision data into the archive table.
2060 // Text is *not* removed from the text table; bulk storage
2061 // is left intact to avoid breaking block-compression or
2062 // immutable storage schemes.
2064 // For backwards compatibility, note that some older archive
2065 // table entries will have ar_text and ar_flags fields still.
2067 // In the future, we may keep revisions and mark them with
2068 // the rev_deleted field, which is reserved for this purpose.
2069 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2071 'ar_namespace' => 'page_namespace',
2072 'ar_title' => 'page_title',
2073 'ar_comment' => 'rev_comment',
2074 'ar_user' => 'rev_user',
2075 'ar_user_text' => 'rev_user_text',
2076 'ar_timestamp' => 'rev_timestamp',
2077 'ar_minor_edit' => 'rev_minor_edit',
2078 'ar_rev_id' => 'rev_id',
2079 'ar_text_id' => 'rev_text_id',
2082 'page_id = rev_page'
2086 # Now that it's safely backed up, delete it
2087 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2088 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2090 if ($wgUseTrackbacks)
2091 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2093 # Clean up recentchanges entries...
2094 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2096 # Finally, clean up the link tables
2097 $t = $this->mTitle
->getPrefixedDBkey();
2099 Article
::onArticleDelete( $this->mTitle
);
2101 # Delete outgoing links
2102 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2103 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2104 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2105 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2106 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2107 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2110 $log = new LogPage( 'delete' );
2111 $log->addEntry( 'delete', $this->mTitle
, $reason );
2113 # Clear the cached article id so the interface doesn't act like we exist
2114 $this->mTitle
->resetArticleID( 0 );
2115 $this->mTitle
->mArticleID
= 0;
2120 * Revert a modification
2122 function rollback() {
2123 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2124 $fname = 'Article::rollback';
2126 if( $wgUser->isAllowed( 'rollback' ) ) {
2127 if( $wgUser->isBlocked() ) {
2128 $wgOut->blockedPage();
2132 $wgOut->permissionRequired( 'rollback' );
2136 if ( wfReadOnly() ) {
2137 $wgOut->readOnlyPage( $this->getContent() );
2140 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2141 array( $this->mTitle
->getPrefixedText(),
2142 $wgRequest->getVal( 'from' ) ) ) ) {
2143 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2144 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2147 $dbw =& wfGetDB( DB_MASTER
);
2149 # Enhanced rollback, marks edits rc_bot=1
2150 $bot = $wgRequest->getBool( 'bot' );
2152 # Replace all this user's current edits with the next one down
2153 $tt = $this->mTitle
->getDBKey();
2154 $n = $this->mTitle
->getNamespace();
2156 # Get the last editor, lock table exclusively
2158 $current = Revision
::newFromTitle( $this->mTitle
);
2159 if( is_null( $current ) ) {
2160 # Something wrong... no page?
2162 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2166 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2167 if( $from != $current->getUserText() ) {
2168 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2169 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2170 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2171 htmlspecialchars( $from ),
2172 htmlspecialchars( $current->getUserText() ) ) );
2173 if( $current->getComment() != '') {
2175 wfMsg( 'editcomment',
2176 htmlspecialchars( $current->getComment() ) ) );
2181 # Get the last edit not by this guy
2182 $user = intval( $current->getUser() );
2183 $user_text = $dbw->addQuotes( $current->getUserText() );
2184 $s = $dbw->selectRow( 'revision',
2185 array( 'rev_id', 'rev_timestamp' ),
2187 'rev_page' => $current->getPage(),
2188 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2191 'USE INDEX' => 'page_timestamp',
2192 'ORDER BY' => 'rev_timestamp DESC' )
2194 if( $s === false ) {
2197 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2198 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2204 # Mark all reverted edits as bot
2207 if ( $wgUseRCPatrol ) {
2208 # Mark all reverted edits as patrolled
2209 $set['rc_patrolled'] = 1;
2213 $dbw->update( 'recentchanges', $set,
2215 'rc_cur_id' => $current->getPage(),
2216 'rc_user_text' => $current->getUserText(),
2217 "rc_timestamp > '{$s->rev_timestamp}'",
2222 # Get the edit summary
2223 $target = Revision
::newFromId( $s->rev_id
);
2224 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2225 $newComment = $wgRequest->getText( 'summary', $newComment );
2228 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2229 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2230 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2232 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2233 Article
::onArticleEdit( $this->mTitle
);
2236 $wgOut->returnToMain( false );
2241 * Do standard deferred updates after page view
2244 function viewUpdates() {
2245 global $wgDeferredUpdateList;
2247 if ( 0 != $this->getID() ) {
2248 global $wgDisableCounters;
2249 if( !$wgDisableCounters ) {
2250 Article
::incViewCount( $this->getID() );
2251 $u = new SiteStatsUpdate( 1, 0, 0 );
2252 array_push( $wgDeferredUpdateList, $u );
2256 # Update newtalk / watchlist notification status
2258 $wgUser->clearNotification( $this->mTitle
);
2262 * Do standard deferred updates after page edit.
2263 * Every 1000th edit, prune the recent changes table.
2265 * @param string $text
2267 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2268 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2270 $fname = 'Article::editUpdates';
2271 wfProfileIn( $fname );
2274 $options = new ParserOptions
;
2275 $options->setTidy(true);
2276 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2278 # Save it to the parser cache
2279 $parserCache =& ParserCache
::singleton();
2280 $parserCache->save( $poutput, $this, $wgUser );
2282 # Update the links tables
2283 $u = new LinksUpdate( $this->mTitle
, $poutput );
2286 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2288 if ( 0 == mt_rand( 0, 999 ) ) {
2289 # Periodically flush old entries from the recentchanges table.
2292 $dbw =& wfGetDB( DB_MASTER
);
2293 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2294 $recentchanges = $dbw->tableName( 'recentchanges' );
2295 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2296 $dbw->query( $sql );
2300 $id = $this->getID();
2301 $title = $this->mTitle
->getPrefixedDBkey();
2302 $shortTitle = $this->mTitle
->getDBkey();
2305 wfProfileOut( $fname );
2309 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2310 array_push( $wgDeferredUpdateList, $u );
2311 $u = new SearchUpdate( $id, $title, $text );
2312 array_push( $wgDeferredUpdateList, $u );
2314 # If this is another user's talk page, update newtalk
2316 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2317 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2318 $other = User
::newFromName( $shortTitle );
2319 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2320 // An anonymous user
2321 $other = new User();
2322 $other->setName( $shortTitle );
2325 $other->setNewtalk( true );
2330 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2331 $wgMessageCache->replace( $shortTitle, $text );
2334 wfProfileOut( $fname );
2338 * Generate the navigation links when browsing through an article revisions
2339 * It shows the information as:
2340 * Revision as of \<date\>; view current revision
2341 * \<- Previous version | Next Version -\>
2344 * @param string $oldid Revision ID of this article revision
2346 function setOldSubtitle( $oldid=0 ) {
2347 global $wgLang, $wgOut, $wgUser;
2349 $current = ( $oldid == $this->mLatest
);
2350 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2351 $sk = $wgUser->getSkin();
2353 ?
wfMsg( 'currentrevisionlink' )
2354 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2355 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2357 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2358 : wfMsg( 'previousrevision' );
2359 $nextlink = $current
2360 ?
wfMsg( 'nextrevision' )
2361 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2362 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2363 $wgOut->setSubtitle( $r );
2367 * This function is called right before saving the wikitext,
2368 * so we can do things like signatures and links-in-context.
2370 * @param string $text
2372 function preSaveTransform( $text ) {
2373 global $wgParser, $wgUser;
2374 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2377 /* Caching functions */
2380 * checkLastModified returns true if it has taken care of all
2381 * output to the client that is necessary for this request.
2382 * (that is, it has sent a cached version of the page)
2384 function tryFileCache() {
2385 static $called = false;
2387 wfDebug( " tryFileCache() -- called twice!?\n" );
2391 if($this->isFileCacheable()) {
2392 $touched = $this->mTouched
;
2393 $cache = new CacheManager( $this->mTitle
);
2394 if($cache->isFileCacheGood( $touched )) {
2395 wfDebug( " tryFileCache() - about to load\n" );
2396 $cache->loadFromFileCache();
2399 wfDebug( " tryFileCache() - starting buffer\n" );
2400 ob_start( array(&$cache, 'saveToFileCache' ) );
2403 wfDebug( " tryFileCache() - not cacheable\n" );
2408 * Check if the page can be cached
2411 function isFileCacheable() {
2412 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2413 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2415 return $wgUseFileCache
2416 and (!$wgShowIPinHeader)
2417 and ($this->getID() != 0)
2418 and ($wgUser->isAnon())
2419 and (!$wgUser->getNewtalk())
2420 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2421 and (empty( $action ) ||
$action == 'view')
2422 and (!isset($oldid))
2424 and (!isset($redirect))
2425 and (!isset($printable))
2426 and (!$this->mRedirectedFrom
);
2430 * Loads page_touched and returns a value indicating if it should be used
2433 function checkTouched() {
2434 $fname = 'Article::checkTouched';
2435 if( !$this->mDataLoaded
) {
2436 $this->loadPageData();
2438 return !$this->mIsRedirect
;
2442 * Get the page_touched field
2444 function getTouched() {
2445 # Ensure that page data has been loaded
2446 if( !$this->mDataLoaded
) {
2447 $this->loadPageData();
2449 return $this->mTouched
;
2453 * Get the page_latest field
2455 function getLatest() {
2456 if ( !$this->mDataLoaded
) {
2457 $this->loadPageData();
2459 return $this->mLatest
;
2463 * Edit an article without doing all that other stuff
2464 * The article must already exist; link tables etc
2465 * are not updated, caches are not flushed.
2467 * @param string $text text submitted
2468 * @param string $comment comment submitted
2469 * @param bool $minor whereas it's a minor modification
2471 function quickEdit( $text, $comment = '', $minor = 0 ) {
2472 $fname = 'Article::quickEdit';
2473 wfProfileIn( $fname );
2475 $dbw =& wfGetDB( DB_MASTER
);
2477 $revision = new Revision( array(
2478 'page' => $this->getId(),
2480 'comment' => $comment,
2481 'minor_edit' => $minor ?
1 : 0,
2483 # fixme : $revisionId never used
2484 $revisionId = $revision->insertOn( $dbw );
2485 $this->updateRevisionOn( $dbw, $revision );
2488 wfProfileOut( $fname );
2492 * Used to increment the view counter
2495 * @param integer $id article id
2497 function incViewCount( $id ) {
2498 $id = intval( $id );
2499 global $wgHitcounterUpdateFreq, $wgDBtype;
2501 $dbw =& wfGetDB( DB_MASTER
);
2502 $pageTable = $dbw->tableName( 'page' );
2503 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2504 $acchitsTable = $dbw->tableName( 'acchits' );
2506 if( $wgHitcounterUpdateFreq <= 1 ){ //
2507 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2511 # Not important enough to warrant an error page in case of failure
2512 $oldignore = $dbw->ignoreErrors( true );
2514 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2516 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2517 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2518 # Most of the time (or on SQL errors), skip row count check
2519 $dbw->ignoreErrors( $oldignore );
2523 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2524 $row = $dbw->fetchObject( $res );
2525 $rown = intval( $row->n
);
2526 if( $rown >= $wgHitcounterUpdateFreq ){
2527 wfProfileIn( 'Article::incViewCount-collect' );
2528 $old_user_abort = ignore_user_abort( true );
2530 if ($wgDBtype == 'mysql')
2531 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2532 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2533 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2534 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2536 $dbw->query("DELETE FROM $hitcounterTable");
2537 if ($wgDBtype == 'mysql')
2538 $dbw->query('UNLOCK TABLES');
2539 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2540 'WHERE page_id = hc_id');
2541 $dbw->query("DROP TABLE $acchitsTable");
2543 ignore_user_abort( $old_user_abort );
2544 wfProfileOut( 'Article::incViewCount-collect' );
2546 $dbw->ignoreErrors( $oldignore );
2550 * The onArticle*() functions are supposed to be a kind of hooks
2551 * which should be called whenever any of the specified actions
2554 * This is a good place to put code to clear caches, for instance.
2556 * This is called on page move and undelete, as well as edit
2558 * @param $title_obj a title object
2561 function onArticleCreate($title_obj) {
2562 global $wgUseSquid, $wgPostCommitUpdateList;
2564 $title_obj->touchLinks();
2565 $titles = $title_obj->getLinksTo();
2568 if ( $wgUseSquid ) {
2569 $urls = $title_obj->getSquidURLs();
2570 foreach ( $titles as $linkTitle ) {
2571 $urls[] = $linkTitle->getInternalURL();
2573 $u = new SquidUpdate( $urls );
2574 array_push( $wgPostCommitUpdateList, $u );
2578 function onArticleDelete( $title ) {
2579 global $wgMessageCache;
2581 $title->touchLinks();
2583 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2584 $wgMessageCache->replace( $title->getDBkey(), false );
2589 * Purge caches on page update etc
2591 function onArticleEdit( $title ) {
2592 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2596 // Template namespace? Purge all articles linking here.
2597 // FIXME: When a templatelinks table arrives, use it for all includes.
2598 if ( $title->getNamespace() == NS_TEMPLATE
) {
2599 $titles = $title->getLinksTo();
2600 Title
::touchArray( $titles );
2601 if ( $wgUseSquid ) {
2602 foreach ( $titles as $link ) {
2603 $urls[] = $link->getInternalURL();
2609 if ( $wgUseSquid ) {
2610 $urls = array_merge( $urls, $title->getSquidURLs() );
2611 $u = new SquidUpdate( $urls );
2612 array_push( $wgPostCommitUpdateList, $u );
2616 if ( $wgUseFileCache ) {
2617 $cm = new CacheManager( $title );
2618 @unlink
( $cm->fileCacheName() );
2625 * Info about this page
2626 * Called for ?action=info when $wgAllowPageInfo is on.
2631 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2632 $fname = 'Article::info';
2634 if ( !$wgAllowPageInfo ) {
2635 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2639 $page = $this->mTitle
->getSubjectPage();
2641 $wgOut->setPagetitle( $page->getPrefixedText() );
2642 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2644 # first, see if the page exists at all.
2645 $exists = $page->getArticleId() != 0;
2647 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2648 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2650 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2653 $dbr =& wfGetDB( DB_SLAVE
);
2655 'wl_title' => $page->getDBkey(),
2656 'wl_namespace' => $page->getNamespace() );
2657 $numwatchers = $dbr->selectField(
2662 $this->getSelectOptions() );
2664 $pageInfo = $this->pageCountInfo( $page );
2665 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2667 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2668 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2670 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2672 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2674 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2676 $wgOut->addHTML( '</ul>' );
2682 * Return the total number of edits and number of unique editors
2683 * on a given page. If page does not exist, returns false.
2685 * @param Title $title
2689 function pageCountInfo( $title ) {
2690 $id = $title->getArticleId();
2695 $dbr =& wfGetDB( DB_SLAVE
);
2697 $rev_clause = array( 'rev_page' => $id );
2698 $fname = 'Article::pageCountInfo';
2700 $edits = $dbr->selectField(
2705 $this->getSelectOptions() );
2707 $authors = $dbr->selectField(
2709 'COUNT(DISTINCT rev_user_text)',
2712 $this->getSelectOptions() );
2714 return array( 'edits' => $edits, 'authors' => $authors );
2718 * Return a list of templates used by this article.
2719 * Uses the templatelinks table
2721 * @return array Array of Title objects
2723 function getUsedTemplates() {
2725 $id = $this->mTitle
->getArticleID();
2730 $dbr =& wfGetDB( DB_SLAVE
);
2731 $res = $dbr->select( array( 'templatelinks' ),
2732 array( 'tl_namespace', 'tl_title' ),
2733 array( 'tl_from' => $id ),
2734 'Article:getUsedTemplates' );
2735 if ( false !== $res ) {
2736 if ( $dbr->numRows( $res ) ) {
2737 while ( $row = $dbr->fetchObject( $res ) ) {
2738 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2742 $dbr->freeResult( $res );