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 );
349 * Load the revision (including text) into this object
351 function loadContent() {
352 if ( $this->mContentLoaded
) return;
355 $oldid = $this->getOldID();
357 $fname = 'Article::loadContent';
359 # Pre-fill content with error message so that if something
360 # fails we'll have something telling us what we intended.
362 $t = $this->mTitle
->getPrefixedText();
364 $this->mOldId
= $oldid;
365 $this->fetchContent( $oldid );
370 * Fetch a page record with the given conditions
371 * @param Database $dbr
372 * @param array $conditions
375 function pageData( &$dbr, $conditions ) {
388 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
389 $row = $dbr->selectRow( 'page',
392 'Article::pageData' );
393 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
398 * @param Database $dbr
399 * @param Title $title
401 function pageDataFromTitle( &$dbr, $title ) {
402 return $this->pageData( $dbr, array(
403 'page_namespace' => $title->getNamespace(),
404 'page_title' => $title->getDBkey() ) );
408 * @param Database $dbr
411 function pageDataFromId( &$dbr, $id ) {
412 return $this->pageData( $dbr, array( 'page_id' => $id ) );
416 * Set the general counter, title etc data loaded from
419 * @param object $data
422 function loadPageData( $data = 'fromdb' ) {
423 if ( $data === 'fromdb' ) {
424 $dbr =& $this->getDB();
425 $data = $this->pageDataFromId( $dbr, $this->getId() );
428 $lc =& LinkCache
::singleton();
430 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
432 $this->mTitle
->mArticleID
= $data->page_id
;
433 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
434 $this->mTitle
->mRestrictionsLoaded
= true;
436 $this->mCounter
= $data->page_counter
;
437 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
438 $this->mIsRedirect
= $data->page_is_redirect
;
439 $this->mLatest
= $data->page_latest
;
441 if ( is_object( $this->mTitle
) ) {
442 $lc->addBadLinkObj( $this->mTitle
);
444 $this->mTitle
->mArticleID
= 0;
447 $this->mDataLoaded
= true;
451 * Get text of an article from database
452 * Does *NOT* follow redirects.
453 * @param int $oldid 0 for whatever the latest revision is
456 function fetchContent( $oldid = 0 ) {
457 if ( $this->mContentLoaded
) {
458 return $this->mContent
;
461 $dbr =& $this->getDB();
462 $fname = 'Article::fetchContent';
464 # Pre-fill content with error message so that if something
465 # fails we'll have something telling us what we intended.
466 $t = $this->mTitle
->getPrefixedText();
468 $t .= ',oldid='.$oldid;
470 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
473 $revision = Revision
::newFromId( $oldid );
474 if( is_null( $revision ) ) {
475 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
478 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
480 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
483 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
484 $this->loadPageData( $data );
486 if( !$this->mDataLoaded
) {
487 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
489 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
492 $this->loadPageData( $data );
494 $revision = Revision
::newFromId( $this->mLatest
);
495 if( is_null( $revision ) ) {
496 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
501 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
502 // We should instead work with the Revision object when we need it...
503 $this->mContent
= $revision->userCan( MW_REV_DELETED_TEXT
) ?
$revision->getRawText() : "";
504 //$this->mContent = $revision->getText();
506 $this->mUser
= $revision->getUser();
507 $this->mUserText
= $revision->getUserText();
508 $this->mComment
= $revision->getComment();
509 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
511 $this->mRevIdFetched
= $revision->getID();
512 $this->mContentLoaded
= true;
513 $this->mRevision
=& $revision;
515 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
517 return $this->mContent
;
521 * Read/write accessor to select FOR UPDATE
523 * @param $x Mixed: FIXME
525 function forUpdate( $x = NULL ) {
526 return wfSetVar( $this->mForUpdate
, $x );
530 * Get the database which should be used for reads
535 $ret =& wfGetDB( DB_MASTER
);
540 * Get options for all SELECT statements
542 * @param $options Array: an optional options array which'll be appended to
544 * @return Array: options
546 function getSelectOptions( $options = '' ) {
547 if ( $this->mForUpdate
) {
548 if ( is_array( $options ) ) {
549 $options[] = 'FOR UPDATE';
551 $options = 'FOR UPDATE';
558 * @return int Page ID
561 if( $this->mTitle
) {
562 return $this->mTitle
->getArticleID();
569 * @return bool Whether or not the page exists in the database
572 return $this->getId() != 0;
576 * @return int The view count for the page
578 function getCount() {
579 if ( -1 == $this->mCounter
) {
580 $id = $this->getID();
584 $dbr =& wfGetDB( DB_SLAVE
);
585 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
586 'Article::getCount', $this->getSelectOptions() );
589 return $this->mCounter
;
593 * Determine whether a page would be suitable for being counted as an
594 * article in the site_stats table based on the title & its content
596 * @param $text String: text to analyze
599 function isCountable( $text ) {
600 global $wgUseCommaCount;
602 $token = $wgUseCommaCount ?
',' : '[[';
604 $this->mTitle
->getNamespace() == NS_MAIN
605 && ! $this->isRedirect( $text )
606 && in_string( $token, $text );
610 * Tests if the article text represents a redirect
612 * @param $text String: FIXME
615 function isRedirect( $text = false ) {
616 if ( $text === false ) {
617 $this->loadContent();
618 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
620 $titleObj = Title
::newFromRedirect( $text );
622 return $titleObj !== NULL;
626 * Returns true if the currently-referenced revision is the current edit
627 * to this page (and it exists).
630 function isCurrent() {
631 return $this->exists() &&
632 isset( $this->mRevision
) &&
633 $this->mRevision
->isCurrent();
637 * Loads everything except the text
638 * This isn't necessary for all uses, so it's only done if needed.
641 function loadLastEdit() {
642 if ( -1 != $this->mUser
)
645 # New or non-existent articles have no user information
646 $id = $this->getID();
647 if ( 0 == $id ) return;
649 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
650 if( !is_null( $this->mLastRevision
) ) {
651 $this->mUser
= $this->mLastRevision
->getUser();
652 $this->mUserText
= $this->mLastRevision
->getUserText();
653 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
654 $this->mComment
= $this->mLastRevision
->getComment();
655 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
656 $this->mRevIdFetched
= $this->mLastRevision
->getID();
660 function getTimestamp() {
661 // Check if the field has been filled by ParserCache::get()
662 if ( !$this->mTimestamp
) {
663 $this->loadLastEdit();
665 return wfTimestamp(TS_MW
, $this->mTimestamp
);
669 $this->loadLastEdit();
673 function getUserText() {
674 $this->loadLastEdit();
675 return $this->mUserText
;
678 function getComment() {
679 $this->loadLastEdit();
680 return $this->mComment
;
683 function getMinorEdit() {
684 $this->loadLastEdit();
685 return $this->mMinorEdit
;
688 function getRevIdFetched() {
689 $this->loadLastEdit();
690 return $this->mRevIdFetched
;
695 * @param $limit Integer: default 0.
696 * @param $offset Integer: default 0.
698 function getContributors($limit = 0, $offset = 0) {
699 $fname = 'Article::getContributors';
701 # XXX: this is expensive; cache this info somewhere.
703 $title = $this->mTitle
;
705 $dbr =& wfGetDB( DB_SLAVE
);
706 $revTable = $dbr->tableName( 'revision' );
707 $userTable = $dbr->tableName( 'user' );
708 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
709 $ns = $title->getNamespace();
710 $user = $this->getUser();
711 $pageId = $this->getId();
713 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
714 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
715 WHERE rev_page = $pageId
716 AND rev_user != $user
717 GROUP BY rev_user, rev_user_text, user_real_name
718 ORDER BY timestamp DESC";
720 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
721 $sql .= ' '. $this->getSelectOptions();
723 $res = $dbr->query($sql, $fname);
725 while ( $line = $dbr->fetchObject( $res ) ) {
726 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
729 $dbr->freeResult($res);
734 * This is the default action of the script: just view the page of
738 global $wgUser, $wgOut, $wgRequest, $wgContLang;
739 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
740 global $wgUseTrackbacks;
741 $sk = $wgUser->getSkin();
743 $fname = 'Article::view';
744 wfProfileIn( $fname );
745 $parserCache =& ParserCache
::singleton();
746 # Get variables from query string
747 $oldid = $this->getOldID();
749 # getOldID may want us to redirect somewhere else
750 if ( $this->mRedirectUrl
) {
751 $wgOut->redirect( $this->mRedirectUrl
);
752 wfProfileOut( $fname );
756 $diff = $wgRequest->getVal( 'diff' );
757 $rcid = $wgRequest->getVal( 'rcid' );
758 $rdfrom = $wgRequest->getVal( 'rdfrom' );
760 $wgOut->setArticleFlag( true );
761 $wgOut->setRobotpolicy( 'index,follow' );
762 # If we got diff and oldid in the query, we want to see a
763 # diff page instead of the article.
765 if ( !is_null( $diff ) ) {
766 require_once( 'DifferenceEngine.php' );
767 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
769 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
770 // DifferenceEngine directly fetched the revision:
771 $this->mRevIdFetched
= $de->mNewid
;
775 # Run view updates for current revision only
776 $this->viewUpdates();
778 wfProfileOut( $fname );
782 if ( empty( $oldid ) && $this->checkTouched() ) {
783 $wgOut->setETag($parserCache->getETag($this, $wgUser));
785 if( $wgOut->checkLastModified( $this->mTouched
) ){
786 wfProfileOut( $fname );
788 } else if ( $this->tryFileCache() ) {
789 # tell wgOut that output is taken care of
791 $this->viewUpdates();
792 wfProfileOut( $fname );
796 # Should the parser cache be used?
797 $pcache = $wgEnableParserCache &&
798 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
801 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
802 if ( $wgUser->getOption( 'stubthreshold' ) ) {
803 wfIncrStats( 'pcache_miss_stub' );
806 $wasRedirected = false;
807 if ( isset( $this->mRedirectedFrom
) ) {
808 // This is an internally redirected page view.
809 // We'll need a backlink to the source page for navigation.
810 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
811 $sk = $wgUser->getSkin();
812 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
813 $s = wfMsg( 'redirectedfrom', $redir );
814 $wgOut->setSubtitle( $s );
815 $wasRedirected = true;
817 } elseif ( !empty( $rdfrom ) ) {
818 // This is an externally redirected view, from some other wiki.
819 // If it was reported from a trusted site, supply a backlink.
820 global $wgRedirectSources;
821 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
822 $sk = $wgUser->getSkin();
823 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
824 $s = wfMsg( 'redirectedfrom', $redir );
825 $wgOut->setSubtitle( $s );
826 $wasRedirected = true;
832 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
836 if ( !$outputDone ) {
837 $text = $this->getContent();
838 if ( $text === false ) {
839 # Failed to load, replace text with error message
840 $t = $this->mTitle
->getPrefixedText();
842 $t .= ',oldid='.$oldid;
843 $text = wfMsg( 'missingarticle', $t );
845 $text = wfMsg( 'noarticletext', $t );
849 # Another whitelist check in case oldid is altering the title
850 if ( !$this->mTitle
->userCanRead() ) {
851 $wgOut->loginToUse();
856 # We're looking at an old revision
858 if ( !empty( $oldid ) ) {
859 $wgOut->setRobotpolicy( 'noindex,nofollow' );
860 if( is_null( $this->mRevision
) ) {
861 // FIXME: This would be a nice place to load the 'no such page' text.
863 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
864 if( $this->mRevision
->isDeleted( MW_REV_DELETED_TEXT
) ) {
865 if( !$this->mRevision
->userCan( MW_REV_DELETED_TEXT
) ) {
866 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
867 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
870 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
871 // and we are allowed to see...
880 * @fixme: this hook doesn't work most of the time, as it doesn't
881 * trigger when the parser cache is used.
883 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
884 $wgOut->setRevisionId( $this->getRevIdFetched() );
885 # wrap user css and user js in pre and don't parse
886 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
888 $this->mTitle
->getNamespace() == NS_USER
&&
889 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
891 $wgOut->addWikiText( wfMsg('clearyourcache'));
892 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
893 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
895 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
896 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
897 if( !$wasRedirected ) {
898 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
900 $targetUrl = $rt->escapeLocalURL();
901 $titleText = htmlspecialchars( $rt->getPrefixedText() );
902 $link = $sk->makeLinkObj( $rt );
904 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
905 '<span class="redirectText">'.$link.'</span>' );
907 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
908 $wgOut->addParserOutputNoText( $parseout );
909 } else if ( $pcache ) {
910 # Display content and save to parser cache
911 $wgOut->addPrimaryWikiText( $text, $this );
913 # Display content, don't attempt to save to parser cache
915 # Don't show section-edit links on old revisions... this way lies madness.
916 if( !$this->isCurrent() ) {
917 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
919 # Display content and don't save to parser cache
920 $wgOut->addPrimaryWikiText( $text, $this, false );
922 if( !$this->isCurrent() ) {
923 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
927 /* title may have been set from the cache */
928 $t = $wgOut->getPageTitle();
930 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
933 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
934 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
935 User
::isIP( $this->mTitle
->getText() ) ) {
936 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
939 # If we have been passed an &rcid= parameter, we want to give the user a
940 # chance to mark this new article as patrolled.
941 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
943 "<div class='patrollink'>" .
944 wfMsg ( 'markaspatrolledlink',
945 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
952 if ($wgUseTrackbacks)
953 $this->addTrackbacks();
955 $this->viewUpdates();
956 wfProfileOut( $fname );
959 function addTrackbacks() {
960 global $wgOut, $wgUser;
962 $dbr =& wfGetDB(DB_SLAVE
);
964 /* FROM */ 'trackbacks',
965 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
966 /* WHERE */ array('tb_page' => $this->getID())
969 if (!$dbr->numrows($tbs))
973 while ($o = $dbr->fetchObject($tbs)) {
975 if ($wgUser->isSysop()) {
976 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
977 . $o->tb_id
. "&token=" . $wgUser->editToken());
978 $rmvtxt = wfMsg('trackbackremove', $delurl);
980 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
987 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
990 function deletetrackback() {
991 global $wgUser, $wgRequest, $wgOut, $wgTitle;
993 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
994 $wgOut->addWikitext(wfMsg('sessionfailure'));
998 if ((!$wgUser->isAllowed('delete'))) {
999 $wgOut->sysopRequired();
1004 $wgOut->readOnlyPage();
1008 $db =& wfGetDB(DB_MASTER
);
1009 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1010 $wgTitle->invalidateCache();
1011 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1017 $wgOut->setArticleBodyOnly(true);
1022 * Handle action=purge
1025 global $wgUser, $wgRequest, $wgOut;
1027 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1028 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1032 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1033 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1034 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1035 $msg = str_replace( '$1',
1036 "<form method=\"post\" action=\"$action\">\n" .
1037 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1038 "</form>\n", $msg );
1040 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1041 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1042 $wgOut->addHTML( $msg );
1047 * Perform the actions of a page purging
1049 function doPurge() {
1051 // Invalidate the cache
1052 $this->mTitle
->invalidateCache();
1054 if ( $wgUseSquid ) {
1055 // Commit the transaction before the purge is sent
1056 $dbw = wfGetDB( DB_MASTER
);
1057 $dbw->immediateCommit();
1060 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1061 $update->doUpdate();
1067 * Insert a new empty page record for this article.
1068 * This *must* be followed up by creating a revision
1069 * and running $this->updateToLatest( $rev_id );
1070 * or else the record will be left in a funky state.
1071 * Best if all done inside a transaction.
1073 * @param Database $dbw
1074 * @param string $restrictions
1075 * @return int The newly created page_id key
1078 function insertOn( &$dbw, $restrictions = '' ) {
1079 $fname = 'Article::insertOn';
1080 wfProfileIn( $fname );
1082 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1083 $dbw->insert( 'page', array(
1084 'page_id' => $page_id,
1085 'page_namespace' => $this->mTitle
->getNamespace(),
1086 'page_title' => $this->mTitle
->getDBkey(),
1087 'page_counter' => 0,
1088 'page_restrictions' => $restrictions,
1089 'page_is_redirect' => 0, # Will set this shortly...
1091 'page_random' => wfRandom(),
1092 'page_touched' => $dbw->timestamp(),
1093 'page_latest' => 0, # Fill this in shortly...
1094 'page_len' => 0, # Fill this in shortly...
1096 $newid = $dbw->insertId();
1098 $this->mTitle
->resetArticleId( $newid );
1100 wfProfileOut( $fname );
1105 * Update the page record to point to a newly saved revision.
1107 * @param Database $dbw
1108 * @param Revision $revision For ID number, and text used to set
1109 length and redirect status fields
1110 * @param int $lastRevision If given, will not overwrite the page field
1111 * when different from the currently set value.
1112 * Giving 0 indicates the new page flag should
1114 * @return bool true on success, false on failure
1117 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1118 $fname = 'Article::updateToRevision';
1119 wfProfileIn( $fname );
1121 $conditions = array( 'page_id' => $this->getId() );
1122 if( !is_null( $lastRevision ) ) {
1123 # An extra check against threads stepping on each other
1124 $conditions['page_latest'] = $lastRevision;
1127 $text = $revision->getText();
1128 $dbw->update( 'page',
1130 'page_latest' => $revision->getId(),
1131 'page_touched' => $dbw->timestamp(),
1132 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1133 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1134 'page_len' => strlen( $text ),
1139 wfProfileOut( $fname );
1140 return ( $dbw->affectedRows() != 0 );
1144 * If the given revision is newer than the currently set page_latest,
1145 * update the page record. Otherwise, do nothing.
1147 * @param Database $dbw
1148 * @param Revision $revision
1150 function updateIfNewerOn( &$dbw, $revision ) {
1151 $fname = 'Article::updateIfNewerOn';
1152 wfProfileIn( $fname );
1154 $row = $dbw->selectRow(
1155 array( 'revision', 'page' ),
1156 array( 'rev_id', 'rev_timestamp' ),
1158 'page_id' => $this->getId(),
1159 'page_latest=rev_id' ),
1162 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1163 wfProfileOut( $fname );
1166 $prev = $row->rev_id
;
1168 # No or missing previous revision; mark the page as new
1172 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1173 wfProfileOut( $fname );
1178 * Insert a new article into the database
1181 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1184 $fname = 'Article::insertNewArticle';
1185 wfProfileIn( $fname );
1187 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1188 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1189 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1190 wfProfileOut( $fname );
1194 $ns = $this->mTitle
->getNamespace();
1195 $ttl = $this->mTitle
->getDBkey();
1197 # If this is a comment, add the summary as headline
1198 if($comment && $summary!="") {
1199 $text="== {$summary} ==\n\n".$text;
1201 $text = $this->preSaveTransform( $text );
1204 # Set statistics members
1205 # We work out if it's countable after PST to avoid counter drift
1206 # when articles are created with {{subst:}}
1207 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1208 $this->mTotalAdjustment
= 1;
1210 /* Silently ignore minoredit if not allowed */
1211 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1212 $now = wfTimestampNow();
1214 $dbw =& wfGetDB( DB_MASTER
);
1216 # Add the page record; stake our claim on this title!
1217 $newid = $this->insertOn( $dbw );
1219 # Save the revision text...
1220 $revision = new Revision( array(
1222 'comment' => $summary,
1223 'minor_edit' => $isminor,
1226 $revisionId = $revision->insertOn( $dbw );
1228 $this->mTitle
->resetArticleID( $newid );
1230 # Update the page record with revision data
1231 $this->updateRevisionOn( $dbw, $revision, 0 );
1233 Article
::onArticleCreate( $this->mTitle
);
1235 require_once( 'RecentChange.php' );
1236 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1237 '', strlen( $text ), $revisionId );
1238 # Mark as patrolled if the user can and has the option set
1239 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1240 RecentChange
::markPatrolled( $rcid );
1245 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1247 if ( $this->mTitle
->userIsWatching() ) {
1252 # The talk page isn't in the regular link tables, so we need to update manually:
1253 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1254 $dbw->update( 'page',
1255 array( 'page_touched' => $dbw->timestamp($now) ),
1256 array( 'page_namespace' => $talkns,
1257 'page_title' => $ttl ),
1260 # standard deferred updates
1261 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1263 $oldid = 0; # new article
1264 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1266 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1268 $watchthis, NULL ) );
1269 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1271 $watchthis, NULL ) );
1272 wfProfileOut( $fname );
1275 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1276 $this->replaceSection( $section, $text, $summary, $edittime );
1280 * @return string Complete article text, or null if error
1282 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1283 $fname = 'Article::replaceSection';
1284 wfProfileIn( $fname );
1286 if ($section != '') {
1287 if( is_null( $edittime ) ) {
1288 $rev = Revision
::newFromTitle( $this->mTitle
);
1290 $dbw =& wfGetDB( DB_MASTER
);
1291 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1293 if( is_null( $rev ) ) {
1294 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1295 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1298 $oldtext = $rev->getText();
1300 if($section=='new') {
1301 if($summary) $subject="== {$summary} ==\n\n";
1302 $text=$oldtext."\n\n".$subject.$text;
1305 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1306 # comments to be stripped as well)
1307 $striparray=array();
1308 $parser=new Parser();
1309 $parser->mOutputType
=OT_WIKI
;
1310 $parser->mOptions
= new ParserOptions();
1311 $oldtext=$parser->strip($oldtext, $striparray, true);
1313 # now that we can be sure that no pseudo-sections are in the source,
1315 # Unfortunately we can't simply do a preg_replace because that might
1316 # replace the wrong section, so we have to use the section counter instead
1317 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1318 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1319 $secs[$section*2]=$text."\n\n"; // replace with edited
1321 # section 0 is top (intro) section
1324 # headline of old section - we need to go through this section
1325 # to determine if there are any subsections that now need to
1326 # be erased, as the mother section has been replaced with
1327 # the text of all subsections.
1328 $headline=$secs[$section*2-1];
1329 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1330 $hlevel=$matches[1];
1332 # determine headline level for wikimarkup headings
1333 if(strpos($hlevel,'=')!==false) {
1334 $hlevel=strlen($hlevel);
1337 $secs[$section*2-1]=''; // erase old headline
1340 while(!empty($secs[$count*2-1]) && !$break) {
1342 $subheadline=$secs[$count*2-1];
1344 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1345 $subhlevel=$matches[1];
1346 if(strpos($subhlevel,'=')!==false) {
1347 $subhlevel=strlen($subhlevel);
1349 if($subhlevel > $hlevel) {
1350 // erase old subsections
1351 $secs[$count*2-1]='';
1354 if($subhlevel <= $hlevel) {
1362 $text=join('',$secs);
1363 # reinsert the stuff that we stripped out earlier
1364 $text=$parser->unstrip($text,$striparray);
1365 $text=$parser->unstripNoWiki($text,$striparray);
1369 wfProfileOut( $fname );
1374 * Change an existing article. Puts the previous version back into the old table, updates RC
1375 * and all necessary caches, mostly via the deferred update array.
1377 * It is possible to call this function from a command-line script, but note that you should
1378 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1380 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1381 global $wgUser, $wgDBtransactions, $wgUseSquid;
1382 global $wgPostCommitUpdateList, $wgUseFileCache;
1384 $fname = 'Article::updateArticle';
1385 wfProfileIn( $fname );
1388 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1390 &$watchthis, &$sectionanchor ) ) ) {
1391 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1392 wfProfileOut( $fname );
1396 $isminor = $minor && $wgUser->isAllowed('minoredit');
1397 $redir = (int)$this->isRedirect( $text );
1399 $text = $this->preSaveTransform( $text );
1400 $dbw =& wfGetDB( DB_MASTER
);
1401 $now = wfTimestampNow();
1403 # Update article, but only if changed.
1405 # It's important that we either rollback or complete, otherwise an attacker could
1406 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1407 # could conceivably have the same effect, especially if cur is locked for long periods.
1408 if( !$wgDBtransactions ) {
1409 $userAbort = ignore_user_abort( true );
1412 $oldtext = $this->getContent();
1413 $oldsize = strlen( $oldtext );
1414 $newsize = strlen( $text );
1418 if ( 0 != strcmp( $text, $oldtext ) ) {
1419 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1420 - (int)$this->isCountable( $oldtext );
1421 $this->mTotalAdjustment
= 0;
1422 $now = wfTimestampNow();
1424 $lastRevision = $dbw->selectField(
1425 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1427 $revision = new Revision( array(
1428 'page' => $this->getId(),
1429 'comment' => $summary,
1430 'minor_edit' => $isminor,
1434 $dbw->immediateCommit();
1436 $revisionId = $revision->insertOn( $dbw );
1439 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1442 /* Belated edit conflict! Run away!! */
1446 # Update recentchanges and purge cache and whatnot
1447 require_once( 'RecentChange.php' );
1448 $bot = (int)($wgUser->isBot() ||
$forceBot);
1449 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1450 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1453 # Mark as patrolled if the user can do so and has it set in their options
1454 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1455 RecentChange
::markPatrolled( $rcid );
1460 // Update caches outside the main transaction
1461 Article
::onArticleEdit( $this->mTitle
);
1464 // Keep the same revision ID, but do some updates on it
1465 $revisionId = $this->getRevIdFetched();
1468 if( !$wgDBtransactions ) {
1469 ignore_user_abort( $userAbort );
1474 if (!$this->mTitle
->userIsWatching()) {
1475 $dbw->immediateCommit();
1481 if ( $this->mTitle
->userIsWatching() ) {
1482 $dbw->immediateCommit();
1488 # standard deferred updates
1489 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1493 # Invalidate caches of all articles using this article as a template
1495 # Template namespace
1496 # Purge all articles linking here
1497 $titles = $this->mTitle
->getTemplateLinksTo();
1498 Title
::touchArray( $titles );
1499 if ( $wgUseSquid ) {
1500 foreach ( $titles as $title ) {
1501 $urls[] = $title->getInternalURL();
1506 if ( $wgUseSquid ) {
1507 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1508 $u = new SquidUpdate( $urls );
1509 array_push( $wgPostCommitUpdateList, $u );
1513 if ( $wgUseFileCache ) {
1514 $cm = new CacheManager($this->mTitle
);
1515 @unlink
($cm->fileCacheName());
1518 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1520 wfRunHooks( 'ArticleSaveComplete',
1521 array( &$this, &$wgUser, $text,
1523 $watchthis, $sectionanchor ) );
1524 wfProfileOut( $fname );
1529 * After we've either updated or inserted the article, update
1530 * the link tables and redirect to the new page.
1532 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1535 $fname = 'Article::showArticle';
1536 wfProfileIn( $fname );
1538 # Output the redirect
1539 if( $this->isRedirect( $text ) )
1543 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1545 wfProfileOut( $fname );
1549 * Mark this particular edit as patrolled
1551 function markpatrolled() {
1552 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1553 $wgOut->setRobotpolicy( 'noindex,follow' );
1555 # Check RC patrol config. option
1556 if( !$wgUseRCPatrol ) {
1557 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1562 if( !$wgUser->isAllowed( 'patrol' ) ) {
1563 $wgOut->permissionRequired( 'patrol' );
1567 $rcid = $wgRequest->getVal( 'rcid' );
1568 if ( !is_null ( $rcid ) ) {
1569 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1570 require_once( 'RecentChange.php' );
1571 RecentChange
::markPatrolled( $rcid );
1572 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1573 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1574 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1576 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1577 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1580 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1585 * User-interface handler for the "watch" action
1590 global $wgUser, $wgOut;
1592 if ( $wgUser->isAnon() ) {
1593 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1596 if ( wfReadOnly() ) {
1597 $wgOut->readOnlyPage();
1601 if( $this->doWatch() ) {
1602 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1603 $wgOut->setRobotpolicy( 'noindex,follow' );
1605 $link = $this->mTitle
->getPrefixedText();
1606 $text = wfMsg( 'addedwatchtext', $link );
1607 $wgOut->addWikiText( $text );
1610 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1614 * Add this page to $wgUser's watchlist
1615 * @return bool true on successful watch operation
1617 function doWatch() {
1619 if( $wgUser->isAnon() ) {
1623 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1624 $wgUser->addWatch( $this->mTitle
);
1625 $wgUser->saveSettings();
1627 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1634 * User interface handler for the "unwatch" action.
1636 function unwatch() {
1638 global $wgUser, $wgOut;
1640 if ( $wgUser->isAnon() ) {
1641 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1644 if ( wfReadOnly() ) {
1645 $wgOut->readOnlyPage();
1649 if( $this->doUnwatch() ) {
1650 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1651 $wgOut->setRobotpolicy( 'noindex,follow' );
1653 $link = $this->mTitle
->getPrefixedText();
1654 $text = wfMsg( 'removedwatchtext', $link );
1655 $wgOut->addWikiText( $text );
1658 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1662 * Stop watching a page
1663 * @return bool true on successful unwatch
1665 function doUnwatch() {
1667 if( $wgUser->isAnon() ) {
1671 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1672 $wgUser->removeWatch( $this->mTitle
);
1673 $wgUser->saveSettings();
1675 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1682 * action=protect handler
1684 function protect() {
1685 require_once 'ProtectionForm.php';
1686 $form = new ProtectionForm( $this );
1691 * action=unprotect handler (alias)
1693 function unprotect() {
1698 * Update the article's restriction field, and leave a log entry.
1700 * @param array $limit set of restriction keys
1701 * @param string $reason
1702 * @return bool true on success
1704 function updateRestrictions( $limit = array(), $reason = '' ) {
1705 global $wgUser, $wgRestrictionTypes, $wgContLang;
1707 $id = $this->mTitle
->getArticleID();
1708 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1712 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1713 # we expect a single selection, but the schema allows otherwise.
1715 foreach( $wgRestrictionTypes as $action )
1716 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1718 $current = Article
::flattenRestrictions( $current );
1719 $updated = Article
::flattenRestrictions( $limit );
1721 $changed = ( $current != $updated );
1722 $protect = ( $updated != '' );
1724 # If nothing's changed, do nothing
1726 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1728 $dbw =& wfGetDB( DB_MASTER
);
1730 # Prepare a null revision to be added to the history
1731 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1733 $comment .= ": $reason";
1735 $comment .= " [$updated]";
1736 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1737 $nullRevId = $nullRevision->insertOn( $dbw );
1739 # Update page record
1740 $dbw->update( 'page',
1742 'page_touched' => $dbw->timestamp(),
1743 'page_restrictions' => $updated,
1744 'page_latest' => $nullRevId
1745 ), array( /* WHERE */
1747 ), 'Article::protect'
1749 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1751 # Update the protection log
1752 $log = new LogPage( 'protect' );
1754 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1756 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1760 } # End "changed" check
1766 * Take an array of page restrictions and flatten it to a string
1767 * suitable for insertion into the page_restrictions field.
1768 * @param array $limit
1772 function flattenRestrictions( $limit ) {
1773 if( !is_array( $limit ) ) {
1774 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1778 foreach( $limit as $action => $restrictions ) {
1779 if( $restrictions != '' ) {
1780 $bits[] = "$action=$restrictions";
1783 return implode( ':', $bits );
1787 * UI entry point for page deletion
1790 global $wgUser, $wgOut, $wgRequest;
1791 $fname = 'Article::delete';
1792 $confirm = $wgRequest->wasPosted() &&
1793 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1794 $reason = $wgRequest->getText( 'wpReason' );
1796 # This code desperately needs to be totally rewritten
1799 if( $wgUser->isAllowed( 'delete' ) ) {
1800 if( $wgUser->isBlocked() ) {
1801 $wgOut->blockedPage();
1805 $wgOut->permissionRequired( 'delete' );
1809 if( wfReadOnly() ) {
1810 $wgOut->readOnlyPage();
1814 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1816 # Better double-check that it hasn't been deleted yet!
1817 $dbw =& wfGetDB( DB_MASTER
);
1818 $conds = $this->mTitle
->pageCond();
1819 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1820 if ( $latest === false ) {
1821 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1826 $this->doDelete( $reason );
1830 # determine whether this page has earlier revisions
1831 # and insert a warning if it does
1833 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1835 if( count( $authors ) > 1 && !$confirm ) {
1836 $skin=$wgUser->getSkin();
1837 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1840 # If a single user is responsible for all revisions, find out who they are
1841 if ( count( $authors ) == $maxRevisions ) {
1842 // Query bailed out, too many revisions to find out if they're all the same
1843 $authorOfAll = false;
1845 $authorOfAll = reset( $authors );
1846 foreach ( $authors as $author ) {
1847 if ( $authorOfAll != $author ) {
1848 $authorOfAll = false;
1853 # Fetch article text
1854 $rev = Revision
::newFromTitle( $this->mTitle
);
1856 if( !is_null( $rev ) ) {
1857 # if this is a mini-text, we can paste part of it into the deletion reason
1858 $text = $rev->getText();
1860 #if this is empty, an earlier revision may contain "useful" text
1863 $prev = $rev->getPrevious();
1865 $text = $prev->getText();
1870 $length = strlen( $text );
1872 # this should not happen, since it is not possible to store an empty, new
1873 # page. Let's insert a standard text in case it does, though
1874 if( $length == 0 && $reason === '' ) {
1875 $reason = wfMsgForContent( 'exblank' );
1878 if( $length < 500 && $reason === '' ) {
1879 # comment field=255, let's grep the first 150 to have some user
1882 $text = $wgContLang->truncate( $text, 150, '...' );
1884 # let's strip out newlines
1885 $text = preg_replace( "/[\n\r]/", '', $text );
1888 if( $authorOfAll === false ) {
1889 $reason = wfMsgForContent( 'excontent', $text );
1891 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1894 $reason = wfMsgForContent( 'exbeforeblank', $text );
1899 return $this->confirmDelete( '', $reason );
1903 * Get the last N authors
1904 * @param int $num Number of revisions to get
1905 * @param string $revLatest The latest rev_id, selected from the master (optional)
1906 * @return array Array of authors, duplicates not removed
1908 function getLastNAuthors( $num, $revLatest = 0 ) {
1909 $fname = 'Article::getLastNAuthors';
1910 wfProfileIn( $fname );
1912 // First try the slave
1913 // If that doesn't have the latest revision, try the master
1915 $db =& wfGetDB( DB_SLAVE
);
1917 $res = $db->select( array( 'page', 'revision' ),
1918 array( 'rev_id', 'rev_user_text' ),
1920 'page_namespace' => $this->mTitle
->getNamespace(),
1921 'page_title' => $this->mTitle
->getDBkey(),
1922 'rev_page = page_id'
1923 ), $fname, $this->getSelectOptions( array(
1924 'ORDER BY' => 'rev_timestamp DESC',
1929 wfProfileOut( $fname );
1932 $row = $db->fetchObject( $res );
1933 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1934 $db =& wfGetDB( DB_MASTER
);
1939 } while ( $continue );
1941 $authors = array( $row->rev_user_text
);
1942 while ( $row = $db->fetchObject( $res ) ) {
1943 $authors[] = $row->rev_user_text
;
1945 wfProfileOut( $fname );
1950 * Output deletion confirmation dialog
1952 function confirmDelete( $par, $reason ) {
1953 global $wgOut, $wgUser;
1955 wfDebug( "Article::confirmDelete\n" );
1957 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1958 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1959 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1960 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1962 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1964 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1965 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1966 $token = htmlspecialchars( $wgUser->editToken() );
1969 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1973 <label for='wpReason'>{$delcom}:</label>
1976 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1982 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1986 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1989 $wgOut->returnToMain( false );
1994 * Perform a deletion and output success or failure messages
1996 function doDelete( $reason ) {
1997 global $wgOut, $wgUser;
1998 $fname = 'Article::doDelete';
1999 wfDebug( $fname."\n" );
2001 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2002 if ( $this->doDeleteArticle( $reason ) ) {
2003 $deleted = $this->mTitle
->getPrefixedText();
2005 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2006 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2008 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2009 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2011 $wgOut->addWikiText( $text );
2012 $wgOut->returnToMain( false );
2013 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2015 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2021 * Back-end article deletion
2022 * Deletes the article with database consistency, writes logs, purges caches
2025 function doDeleteArticle( $reason ) {
2026 global $wgUseSquid, $wgDeferredUpdateList;
2027 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2029 $fname = 'Article::doDeleteArticle';
2030 wfDebug( $fname."\n" );
2032 $dbw =& wfGetDB( DB_MASTER
);
2033 $ns = $this->mTitle
->getNamespace();
2034 $t = $this->mTitle
->getDBkey();
2035 $id = $this->mTitle
->getArticleID();
2037 if ( $t == '' ||
$id == 0 ) {
2041 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2042 array_push( $wgDeferredUpdateList, $u );
2044 $linksTo = $this->mTitle
->getLinksTo();
2047 if ( $wgUseSquid ) {
2049 $this->mTitle
->getInternalURL(),
2050 $this->mTitle
->getInternalURL( 'history' )
2053 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2054 array_push( $wgPostCommitUpdateList, $u );
2058 # Client and file cache invalidation
2059 Title
::touchArray( $linksTo );
2062 // For now, shunt the revision data into the archive table.
2063 // Text is *not* removed from the text table; bulk storage
2064 // is left intact to avoid breaking block-compression or
2065 // immutable storage schemes.
2067 // For backwards compatibility, note that some older archive
2068 // table entries will have ar_text and ar_flags fields still.
2070 // In the future, we may keep revisions and mark them with
2071 // the rev_deleted field, which is reserved for this purpose.
2072 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2074 'ar_namespace' => 'page_namespace',
2075 'ar_title' => 'page_title',
2076 'ar_comment' => 'rev_comment',
2077 'ar_user' => 'rev_user',
2078 'ar_user_text' => 'rev_user_text',
2079 'ar_timestamp' => 'rev_timestamp',
2080 'ar_minor_edit' => 'rev_minor_edit',
2081 'ar_rev_id' => 'rev_id',
2082 'ar_text_id' => 'rev_text_id',
2085 'page_id = rev_page'
2089 # Now that it's safely backed up, delete it
2090 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2091 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2093 if ($wgUseTrackbacks)
2094 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2096 # Clean up recentchanges entries...
2097 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2099 # Finally, clean up the link tables
2100 $t = $this->mTitle
->getPrefixedDBkey();
2102 Article
::onArticleDelete( $this->mTitle
);
2104 # Delete outgoing links
2105 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2106 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2107 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2108 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2109 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2110 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2113 $log = new LogPage( 'delete' );
2114 $log->addEntry( 'delete', $this->mTitle
, $reason );
2116 # Clear the cached article id so the interface doesn't act like we exist
2117 $this->mTitle
->resetArticleID( 0 );
2118 $this->mTitle
->mArticleID
= 0;
2123 * Revert a modification
2125 function rollback() {
2126 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2127 $fname = 'Article::rollback';
2129 if( $wgUser->isAllowed( 'rollback' ) ) {
2130 if( $wgUser->isBlocked() ) {
2131 $wgOut->blockedPage();
2135 $wgOut->permissionRequired( 'rollback' );
2139 if ( wfReadOnly() ) {
2140 $wgOut->readOnlyPage( $this->getContent() );
2143 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2144 array( $this->mTitle
->getPrefixedText(),
2145 $wgRequest->getVal( 'from' ) ) ) ) {
2146 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2147 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2150 $dbw =& wfGetDB( DB_MASTER
);
2152 # Enhanced rollback, marks edits rc_bot=1
2153 $bot = $wgRequest->getBool( 'bot' );
2155 # Replace all this user's current edits with the next one down
2156 $tt = $this->mTitle
->getDBKey();
2157 $n = $this->mTitle
->getNamespace();
2159 # Get the last editor, lock table exclusively
2161 $current = Revision
::newFromTitle( $this->mTitle
);
2162 if( is_null( $current ) ) {
2163 # Something wrong... no page?
2165 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2169 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2170 if( $from != $current->getUserText() ) {
2171 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2172 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2173 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2174 htmlspecialchars( $from ),
2175 htmlspecialchars( $current->getUserText() ) ) );
2176 if( $current->getComment() != '') {
2178 wfMsg( 'editcomment',
2179 htmlspecialchars( $current->getComment() ) ) );
2184 # Get the last edit not by this guy
2185 $user = intval( $current->getUser() );
2186 $user_text = $dbw->addQuotes( $current->getUserText() );
2187 $s = $dbw->selectRow( 'revision',
2188 array( 'rev_id', 'rev_timestamp' ),
2190 'rev_page' => $current->getPage(),
2191 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2194 'USE INDEX' => 'page_timestamp',
2195 'ORDER BY' => 'rev_timestamp DESC' )
2197 if( $s === false ) {
2200 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2201 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2207 # Mark all reverted edits as bot
2210 if ( $wgUseRCPatrol ) {
2211 # Mark all reverted edits as patrolled
2212 $set['rc_patrolled'] = 1;
2216 $dbw->update( 'recentchanges', $set,
2218 'rc_cur_id' => $current->getPage(),
2219 'rc_user_text' => $current->getUserText(),
2220 "rc_timestamp > '{$s->rev_timestamp}'",
2225 # Get the edit summary
2226 $target = Revision
::newFromId( $s->rev_id
);
2227 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2228 $newComment = $wgRequest->getText( 'summary', $newComment );
2231 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2232 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2233 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2235 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2236 Article
::onArticleEdit( $this->mTitle
);
2239 $wgOut->returnToMain( false );
2244 * Do standard deferred updates after page view
2247 function viewUpdates() {
2248 global $wgDeferredUpdateList;
2250 if ( 0 != $this->getID() ) {
2251 global $wgDisableCounters;
2252 if( !$wgDisableCounters ) {
2253 Article
::incViewCount( $this->getID() );
2254 $u = new SiteStatsUpdate( 1, 0, 0 );
2255 array_push( $wgDeferredUpdateList, $u );
2259 # Update newtalk / watchlist notification status
2261 $wgUser->clearNotification( $this->mTitle
);
2265 * Do standard deferred updates after page edit.
2266 * Every 1000th edit, prune the recent changes table.
2268 * @param string $text
2270 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2271 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2273 $fname = 'Article::editUpdates';
2274 wfProfileIn( $fname );
2277 $options = new ParserOptions
;
2278 $options->setTidy(true);
2279 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2281 # Save it to the parser cache
2282 $parserCache =& ParserCache
::singleton();
2283 $parserCache->save( $poutput, $this, $wgUser );
2285 # Update the links tables
2286 $u = new LinksUpdate( $this->mTitle
, $poutput );
2289 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2291 if ( 0 == mt_rand( 0, 999 ) ) {
2292 # Periodically flush old entries from the recentchanges table.
2295 $dbw =& wfGetDB( DB_MASTER
);
2296 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2297 $recentchanges = $dbw->tableName( 'recentchanges' );
2298 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2299 $dbw->query( $sql );
2303 $id = $this->getID();
2304 $title = $this->mTitle
->getPrefixedDBkey();
2305 $shortTitle = $this->mTitle
->getDBkey();
2308 wfProfileOut( $fname );
2312 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2313 array_push( $wgDeferredUpdateList, $u );
2314 $u = new SearchUpdate( $id, $title, $text );
2315 array_push( $wgDeferredUpdateList, $u );
2317 # If this is another user's talk page, update newtalk
2319 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2320 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2321 $other = User
::newFromName( $shortTitle );
2322 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2323 // An anonymous user
2324 $other = new User();
2325 $other->setName( $shortTitle );
2328 $other->setNewtalk( true );
2333 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2334 $wgMessageCache->replace( $shortTitle, $text );
2337 wfProfileOut( $fname );
2341 * Generate the navigation links when browsing through an article revisions
2342 * It shows the information as:
2343 * Revision as of \<date\>; view current revision
2344 * \<- Previous version | Next Version -\>
2347 * @param string $oldid Revision ID of this article revision
2349 function setOldSubtitle( $oldid=0 ) {
2350 global $wgLang, $wgOut, $wgUser;
2352 $current = ( $oldid == $this->mLatest
);
2353 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2354 $sk = $wgUser->getSkin();
2356 ?
wfMsg( 'currentrevisionlink' )
2357 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2358 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2360 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2361 : wfMsg( 'previousrevision' );
2362 $nextlink = $current
2363 ?
wfMsg( 'nextrevision' )
2364 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2365 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2366 $wgOut->setSubtitle( $r );
2370 * This function is called right before saving the wikitext,
2371 * so we can do things like signatures and links-in-context.
2373 * @param string $text
2375 function preSaveTransform( $text ) {
2376 global $wgParser, $wgUser;
2377 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2380 /* Caching functions */
2383 * checkLastModified returns true if it has taken care of all
2384 * output to the client that is necessary for this request.
2385 * (that is, it has sent a cached version of the page)
2387 function tryFileCache() {
2388 static $called = false;
2390 wfDebug( " tryFileCache() -- called twice!?\n" );
2394 if($this->isFileCacheable()) {
2395 $touched = $this->mTouched
;
2396 $cache = new CacheManager( $this->mTitle
);
2397 if($cache->isFileCacheGood( $touched )) {
2398 wfDebug( " tryFileCache() - about to load\n" );
2399 $cache->loadFromFileCache();
2402 wfDebug( " tryFileCache() - starting buffer\n" );
2403 ob_start( array(&$cache, 'saveToFileCache' ) );
2406 wfDebug( " tryFileCache() - not cacheable\n" );
2411 * Check if the page can be cached
2414 function isFileCacheable() {
2415 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2416 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2418 return $wgUseFileCache
2419 and (!$wgShowIPinHeader)
2420 and ($this->getID() != 0)
2421 and ($wgUser->isAnon())
2422 and (!$wgUser->getNewtalk())
2423 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2424 and (empty( $action ) ||
$action == 'view')
2425 and (!isset($oldid))
2427 and (!isset($redirect))
2428 and (!isset($printable))
2429 and (!$this->mRedirectedFrom
);
2433 * Loads page_touched and returns a value indicating if it should be used
2436 function checkTouched() {
2437 $fname = 'Article::checkTouched';
2438 if( !$this->mDataLoaded
) {
2439 $this->loadPageData();
2441 return !$this->mIsRedirect
;
2445 * Get the page_touched field
2447 function getTouched() {
2448 # Ensure that page data has been loaded
2449 if( !$this->mDataLoaded
) {
2450 $this->loadPageData();
2452 return $this->mTouched
;
2456 * Get the page_latest field
2458 function getLatest() {
2459 if ( !$this->mDataLoaded
) {
2460 $this->loadPageData();
2462 return $this->mLatest
;
2466 * Edit an article without doing all that other stuff
2467 * The article must already exist; link tables etc
2468 * are not updated, caches are not flushed.
2470 * @param string $text text submitted
2471 * @param string $comment comment submitted
2472 * @param bool $minor whereas it's a minor modification
2474 function quickEdit( $text, $comment = '', $minor = 0 ) {
2475 $fname = 'Article::quickEdit';
2476 wfProfileIn( $fname );
2478 $dbw =& wfGetDB( DB_MASTER
);
2480 $revision = new Revision( array(
2481 'page' => $this->getId(),
2483 'comment' => $comment,
2484 'minor_edit' => $minor ?
1 : 0,
2486 $revisionId = $revision->insertOn( $dbw );
2487 $this->updateRevisionOn( $dbw, $revision );
2490 wfProfileOut( $fname );
2494 * Used to increment the view counter
2497 * @param integer $id article id
2499 function incViewCount( $id ) {
2500 $id = intval( $id );
2501 global $wgHitcounterUpdateFreq, $wgDBtype;
2503 $dbw =& wfGetDB( DB_MASTER
);
2504 $pageTable = $dbw->tableName( 'page' );
2505 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2506 $acchitsTable = $dbw->tableName( 'acchits' );
2508 if( $wgHitcounterUpdateFreq <= 1 ){ //
2509 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2513 # Not important enough to warrant an error page in case of failure
2514 $oldignore = $dbw->ignoreErrors( true );
2516 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2518 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2519 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2520 # Most of the time (or on SQL errors), skip row count check
2521 $dbw->ignoreErrors( $oldignore );
2525 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2526 $row = $dbw->fetchObject( $res );
2527 $rown = intval( $row->n
);
2528 if( $rown >= $wgHitcounterUpdateFreq ){
2529 wfProfileIn( 'Article::incViewCount-collect' );
2530 $old_user_abort = ignore_user_abort( true );
2532 if ($wgDBtype == 'mysql')
2533 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2534 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2535 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2536 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2538 $dbw->query("DELETE FROM $hitcounterTable");
2539 if ($wgDBtype == 'mysql')
2540 $dbw->query('UNLOCK TABLES');
2541 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2542 'WHERE page_id = hc_id');
2543 $dbw->query("DROP TABLE $acchitsTable");
2545 ignore_user_abort( $old_user_abort );
2546 wfProfileOut( 'Article::incViewCount-collect' );
2548 $dbw->ignoreErrors( $oldignore );
2552 * The onArticle*() functions are supposed to be a kind of hooks
2553 * which should be called whenever any of the specified actions
2556 * This is a good place to put code to clear caches, for instance.
2558 * This is called on page move and undelete, as well as edit
2560 * @param $title_obj a title object
2563 function onArticleCreate($title_obj) {
2564 global $wgUseSquid, $wgPostCommitUpdateList;
2566 $title_obj->touchLinks();
2567 $titles = $title_obj->getLinksTo();
2570 if ( $wgUseSquid ) {
2571 $urls = $title_obj->getSquidURLs();
2572 foreach ( $titles as $linkTitle ) {
2573 $urls[] = $linkTitle->getInternalURL();
2575 $u = new SquidUpdate( $urls );
2576 array_push( $wgPostCommitUpdateList, $u );
2580 function onArticleDelete( $title ) {
2581 global $wgMessageCache;
2583 $title->touchLinks();
2585 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2586 $wgMessageCache->replace( $title->getDBkey(), false );
2591 * Purge caches on page update etc
2593 function onArticleEdit( $title ) {
2594 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2598 // Template namespace? Purge all articles linking here.
2599 // FIXME: When a templatelinks table arrives, use it for all includes.
2600 if ( $title->getNamespace() == NS_TEMPLATE
) {
2601 $titles = $title->getLinksTo();
2602 Title
::touchArray( $titles );
2603 if ( $wgUseSquid ) {
2604 foreach ( $titles as $link ) {
2605 $urls[] = $link->getInternalURL();
2611 if ( $wgUseSquid ) {
2612 $urls = array_merge( $urls, $title->getSquidURLs() );
2613 $u = new SquidUpdate( $urls );
2614 array_push( $wgPostCommitUpdateList, $u );
2618 if ( $wgUseFileCache ) {
2619 $cm = new CacheManager( $title );
2620 @unlink
( $cm->fileCacheName() );
2627 * Info about this page
2628 * Called for ?action=info when $wgAllowPageInfo is on.
2633 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2634 $fname = 'Article::info';
2636 if ( !$wgAllowPageInfo ) {
2637 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2641 $page = $this->mTitle
->getSubjectPage();
2643 $wgOut->setPagetitle( $page->getPrefixedText() );
2644 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2646 # first, see if the page exists at all.
2647 $exists = $page->getArticleId() != 0;
2649 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2650 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2652 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2655 $dbr =& wfGetDB( DB_SLAVE
);
2657 'wl_title' => $page->getDBkey(),
2658 'wl_namespace' => $page->getNamespace() );
2659 $numwatchers = $dbr->selectField(
2664 $this->getSelectOptions() );
2666 $pageInfo = $this->pageCountInfo( $page );
2667 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2669 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2670 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2672 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2674 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2676 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2678 $wgOut->addHTML( '</ul>' );
2684 * Return the total number of edits and number of unique editors
2685 * on a given page. If page does not exist, returns false.
2687 * @param Title $title
2691 function pageCountInfo( $title ) {
2692 $id = $title->getArticleId();
2697 $dbr =& wfGetDB( DB_SLAVE
);
2699 $rev_clause = array( 'rev_page' => $id );
2700 $fname = 'Article::pageCountInfo';
2702 $edits = $dbr->selectField(
2707 $this->getSelectOptions() );
2709 $authors = $dbr->selectField(
2711 'COUNT(DISTINCT rev_user_text)',
2714 $this->getSelectOptions() );
2716 return array( 'edits' => $edits, 'authors' => $authors );
2720 * Return a list of templates used by this article.
2721 * Uses the templatelinks table
2723 * @return array Array of Title objects
2725 function getUsedTemplates() {
2727 $id = $this->mTitle
->getArticleID();
2732 $dbr =& wfGetDB( DB_SLAVE
);
2733 $res = $dbr->select( array( 'templatelinks' ),
2734 array( 'tl_namespace', 'tl_title' ),
2735 array( 'tl_from' => $id ),
2736 'Article:getUsedTemplates' );
2737 if ( false !== $res ) {
2738 if ( $dbr->numRows( $res ) ) {
2739 while ( $row = $dbr->fetchObject( $res ) ) {
2740 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2744 $dbr->freeResult( $res );