9e2c9d064bf0740ad2356591b7637ec4ff0cbb53
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 $fname = 'Article::loadContent';
360 # Pre-fill content with error message so that if something
361 # fails we'll have something telling us what we intended.
363 $t = $this->mTitle
->getPrefixedText();
365 $this->mOldId
= $oldid;
366 $this->fetchContent( $oldid );
371 * Fetch a page record with the given conditions
372 * @param Database $dbr
373 * @param array $conditions
376 function pageData( &$dbr, $conditions ) {
389 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
390 $row = $dbr->selectRow( 'page',
393 'Article::pageData' );
394 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
399 * @param Database $dbr
400 * @param Title $title
402 function pageDataFromTitle( &$dbr, $title ) {
403 return $this->pageData( $dbr, array(
404 'page_namespace' => $title->getNamespace(),
405 'page_title' => $title->getDBkey() ) );
409 * @param Database $dbr
412 function pageDataFromId( &$dbr, $id ) {
413 return $this->pageData( $dbr, array( 'page_id' => $id ) );
417 * Set the general counter, title etc data loaded from
420 * @param object $data
423 function loadPageData( $data = 'fromdb' ) {
424 if ( $data === 'fromdb' ) {
425 $dbr =& $this->getDB();
426 $data = $this->pageDataFromId( $dbr, $this->getId() );
429 $lc =& LinkCache
::singleton();
431 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
433 $this->mTitle
->mArticleID
= $data->page_id
;
434 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
435 $this->mTitle
->mRestrictionsLoaded
= true;
437 $this->mCounter
= $data->page_counter
;
438 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
439 $this->mIsRedirect
= $data->page_is_redirect
;
440 $this->mLatest
= $data->page_latest
;
442 if ( is_object( $this->mTitle
) ) {
443 $lc->addBadLinkObj( $this->mTitle
);
445 $this->mTitle
->mArticleID
= 0;
448 $this->mDataLoaded
= true;
452 * Get text of an article from database
453 * Does *NOT* follow redirects.
454 * @param int $oldid 0 for whatever the latest revision is
457 function fetchContent( $oldid = 0 ) {
458 if ( $this->mContentLoaded
) {
459 return $this->mContent
;
462 $dbr =& $this->getDB();
463 $fname = 'Article::fetchContent';
465 # Pre-fill content with error message so that if something
466 # fails we'll have something telling us what we intended.
467 $t = $this->mTitle
->getPrefixedText();
469 $t .= ',oldid='.$oldid;
471 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
474 $revision = Revision
::newFromId( $oldid );
475 if( is_null( $revision ) ) {
476 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
479 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
481 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
484 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
485 $this->loadPageData( $data );
487 if( !$this->mDataLoaded
) {
488 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
490 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
493 $this->loadPageData( $data );
495 $revision = Revision
::newFromId( $this->mLatest
);
496 if( is_null( $revision ) ) {
497 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
502 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
503 // We should instead work with the Revision object when we need it...
504 $this->mContent
= $revision->userCan( MW_REV_DELETED_TEXT
) ?
$revision->getRawText() : "";
505 //$this->mContent = $revision->getText();
507 $this->mUser
= $revision->getUser();
508 $this->mUserText
= $revision->getUserText();
509 $this->mComment
= $revision->getComment();
510 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
512 $this->mRevIdFetched
= $revision->getID();
513 $this->mContentLoaded
= true;
514 $this->mRevision
=& $revision;
516 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
518 return $this->mContent
;
522 * Read/write accessor to select FOR UPDATE
524 * @param $x Mixed: FIXME
526 function forUpdate( $x = NULL ) {
527 return wfSetVar( $this->mForUpdate
, $x );
531 * Get the database which should be used for reads
536 $ret =& wfGetDB( DB_MASTER
);
541 * Get options for all SELECT statements
543 * @param $options Array: an optional options array which'll be appended to
545 * @return Array: options
547 function getSelectOptions( $options = '' ) {
548 if ( $this->mForUpdate
) {
549 if ( is_array( $options ) ) {
550 $options[] = 'FOR UPDATE';
552 $options = 'FOR UPDATE';
559 * @return int Page ID
562 if( $this->mTitle
) {
563 return $this->mTitle
->getArticleID();
570 * @return bool Whether or not the page exists in the database
573 return $this->getId() != 0;
577 * @return int The view count for the page
579 function getCount() {
580 if ( -1 == $this->mCounter
) {
581 $id = $this->getID();
585 $dbr =& wfGetDB( DB_SLAVE
);
586 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
587 'Article::getCount', $this->getSelectOptions() );
590 return $this->mCounter
;
594 * Determine whether a page would be suitable for being counted as an
595 * article in the site_stats table based on the title & its content
597 * @param $text String: text to analyze
600 function isCountable( $text ) {
601 global $wgUseCommaCount;
603 $token = $wgUseCommaCount ?
',' : '[[';
605 $this->mTitle
->getNamespace() == NS_MAIN
606 && ! $this->isRedirect( $text )
607 && in_string( $token, $text );
611 * Tests if the article text represents a redirect
613 * @param $text String: FIXME
616 function isRedirect( $text = false ) {
617 if ( $text === false ) {
618 $this->loadContent();
619 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
621 $titleObj = Title
::newFromRedirect( $text );
623 return $titleObj !== NULL;
627 * Returns true if the currently-referenced revision is the current edit
628 * to this page (and it exists).
631 function isCurrent() {
632 return $this->exists() &&
633 isset( $this->mRevision
) &&
634 $this->mRevision
->isCurrent();
638 * Loads everything except the text
639 * This isn't necessary for all uses, so it's only done if needed.
642 function loadLastEdit() {
643 if ( -1 != $this->mUser
)
646 # New or non-existent articles have no user information
647 $id = $this->getID();
648 if ( 0 == $id ) return;
650 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
651 if( !is_null( $this->mLastRevision
) ) {
652 $this->mUser
= $this->mLastRevision
->getUser();
653 $this->mUserText
= $this->mLastRevision
->getUserText();
654 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
655 $this->mComment
= $this->mLastRevision
->getComment();
656 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
657 $this->mRevIdFetched
= $this->mLastRevision
->getID();
661 function getTimestamp() {
662 // Check if the field has been filled by ParserCache::get()
663 if ( !$this->mTimestamp
) {
664 $this->loadLastEdit();
666 return wfTimestamp(TS_MW
, $this->mTimestamp
);
670 $this->loadLastEdit();
674 function getUserText() {
675 $this->loadLastEdit();
676 return $this->mUserText
;
679 function getComment() {
680 $this->loadLastEdit();
681 return $this->mComment
;
684 function getMinorEdit() {
685 $this->loadLastEdit();
686 return $this->mMinorEdit
;
689 function getRevIdFetched() {
690 $this->loadLastEdit();
691 return $this->mRevIdFetched
;
696 * @param $limit Integer: default 0.
697 * @param $offset Integer: default 0.
699 function getContributors($limit = 0, $offset = 0) {
700 $fname = 'Article::getContributors';
702 # XXX: this is expensive; cache this info somewhere.
704 $title = $this->mTitle
;
706 $dbr =& wfGetDB( DB_SLAVE
);
707 $revTable = $dbr->tableName( 'revision' );
708 $userTable = $dbr->tableName( 'user' );
709 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
710 $ns = $title->getNamespace();
711 $user = $this->getUser();
712 $pageId = $this->getId();
714 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
715 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
716 WHERE rev_page = $pageId
717 AND rev_user != $user
718 GROUP BY rev_user, rev_user_text, user_real_name
719 ORDER BY timestamp DESC";
721 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
722 $sql .= ' '. $this->getSelectOptions();
724 $res = $dbr->query($sql, $fname);
726 while ( $line = $dbr->fetchObject( $res ) ) {
727 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
730 $dbr->freeResult($res);
735 * This is the default action of the script: just view the page of
739 global $wgUser, $wgOut, $wgRequest, $wgContLang;
740 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
741 global $wgUseTrackbacks;
742 $sk = $wgUser->getSkin();
744 $fname = 'Article::view';
745 wfProfileIn( $fname );
746 $parserCache =& ParserCache
::singleton();
747 # Get variables from query string
748 $oldid = $this->getOldID();
750 # getOldID may want us to redirect somewhere else
751 if ( $this->mRedirectUrl
) {
752 $wgOut->redirect( $this->mRedirectUrl
);
753 wfProfileOut( $fname );
757 $diff = $wgRequest->getVal( 'diff' );
758 $rcid = $wgRequest->getVal( 'rcid' );
759 $rdfrom = $wgRequest->getVal( 'rdfrom' );
761 $wgOut->setArticleFlag( true );
762 $wgOut->setRobotpolicy( 'index,follow' );
763 # If we got diff and oldid in the query, we want to see a
764 # diff page instead of the article.
766 if ( !is_null( $diff ) ) {
767 require_once( 'DifferenceEngine.php' );
768 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
770 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
771 // DifferenceEngine directly fetched the revision:
772 $this->mRevIdFetched
= $de->mNewid
;
776 # Run view updates for current revision only
777 $this->viewUpdates();
779 wfProfileOut( $fname );
783 if ( empty( $oldid ) && $this->checkTouched() ) {
784 $wgOut->setETag($parserCache->getETag($this, $wgUser));
786 if( $wgOut->checkLastModified( $this->mTouched
) ){
787 wfProfileOut( $fname );
789 } else if ( $this->tryFileCache() ) {
790 # tell wgOut that output is taken care of
792 $this->viewUpdates();
793 wfProfileOut( $fname );
797 # Should the parser cache be used?
798 $pcache = $wgEnableParserCache &&
799 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
802 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
803 if ( $wgUser->getOption( 'stubthreshold' ) ) {
804 wfIncrStats( 'pcache_miss_stub' );
807 $wasRedirected = false;
808 if ( isset( $this->mRedirectedFrom
) ) {
809 // This is an internally redirected page view.
810 // We'll need a backlink to the source page for navigation.
811 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
812 $sk = $wgUser->getSkin();
813 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
814 $s = wfMsg( 'redirectedfrom', $redir );
815 $wgOut->setSubtitle( $s );
816 $wasRedirected = true;
818 } elseif ( !empty( $rdfrom ) ) {
819 // This is an externally redirected view, from some other wiki.
820 // If it was reported from a trusted site, supply a backlink.
821 global $wgRedirectSources;
822 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
823 $sk = $wgUser->getSkin();
824 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
825 $s = wfMsg( 'redirectedfrom', $redir );
826 $wgOut->setSubtitle( $s );
827 $wasRedirected = true;
833 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
837 if ( !$outputDone ) {
838 $text = $this->getContent();
839 if ( $text === false ) {
840 # Failed to load, replace text with error message
841 $t = $this->mTitle
->getPrefixedText();
843 $t .= ',oldid='.$oldid;
844 $text = wfMsg( 'missingarticle', $t );
846 $text = wfMsg( 'noarticletext', $t );
850 # Another whitelist check in case oldid is altering the title
851 if ( !$this->mTitle
->userCanRead() ) {
852 $wgOut->loginToUse();
857 # We're looking at an old revision
859 if ( !empty( $oldid ) ) {
860 $wgOut->setRobotpolicy( 'noindex,nofollow' );
861 if( is_null( $this->mRevision
) ) {
862 // FIXME: This would be a nice place to load the 'no such page' text.
864 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
865 if( $this->mRevision
->isDeleted( MW_REV_DELETED_TEXT
) ) {
866 if( !$this->mRevision
->userCan( MW_REV_DELETED_TEXT
) ) {
867 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
868 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
871 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
872 // and we are allowed to see...
881 * @fixme: this hook doesn't work most of the time, as it doesn't
882 * trigger when the parser cache is used.
884 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
885 $wgOut->setRevisionId( $this->getRevIdFetched() );
886 # wrap user css and user js in pre and don't parse
887 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
889 $this->mTitle
->getNamespace() == NS_USER
&&
890 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
892 $wgOut->addWikiText( wfMsg('clearyourcache'));
893 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
894 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
896 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
897 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
898 if( !$wasRedirected ) {
899 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
901 $targetUrl = $rt->escapeLocalURL();
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->isSysop()) {
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 );
1276 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1277 $this->replaceSection( $section, $text, $summary, $edittime );
1281 * @return string Complete article text, or null if error
1283 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1284 $fname = 'Article::replaceSection';
1285 wfProfileIn( $fname );
1287 if ($section != '') {
1288 if( is_null( $edittime ) ) {
1289 $rev = Revision
::newFromTitle( $this->mTitle
);
1291 $dbw =& wfGetDB( DB_MASTER
);
1292 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1294 if( is_null( $rev ) ) {
1295 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1296 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1299 $oldtext = $rev->getText();
1301 if($section=='new') {
1302 if($summary) $subject="== {$summary} ==\n\n";
1303 $text=$oldtext."\n\n".$subject.$text;
1306 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1307 # comments to be stripped as well)
1308 $striparray=array();
1309 $parser=new Parser();
1310 $parser->mOutputType
=OT_WIKI
;
1311 $parser->mOptions
= new ParserOptions();
1312 $oldtext=$parser->strip($oldtext, $striparray, true);
1314 # now that we can be sure that no pseudo-sections are in the source,
1316 # Unfortunately we can't simply do a preg_replace because that might
1317 # replace the wrong section, so we have to use the section counter instead
1318 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1319 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1320 $secs[$section*2]=$text."\n\n"; // replace with edited
1322 # section 0 is top (intro) section
1325 # headline of old section - we need to go through this section
1326 # to determine if there are any subsections that now need to
1327 # be erased, as the mother section has been replaced with
1328 # the text of all subsections.
1329 $headline=$secs[$section*2-1];
1330 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1331 $hlevel=$matches[1];
1333 # determine headline level for wikimarkup headings
1334 if(strpos($hlevel,'=')!==false) {
1335 $hlevel=strlen($hlevel);
1338 $secs[$section*2-1]=''; // erase old headline
1341 while(!empty($secs[$count*2-1]) && !$break) {
1343 $subheadline=$secs[$count*2-1];
1345 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1346 $subhlevel=$matches[1];
1347 if(strpos($subhlevel,'=')!==false) {
1348 $subhlevel=strlen($subhlevel);
1350 if($subhlevel > $hlevel) {
1351 // erase old subsections
1352 $secs[$count*2-1]='';
1355 if($subhlevel <= $hlevel) {
1363 $text=join('',$secs);
1364 # reinsert the stuff that we stripped out earlier
1365 $text=$parser->unstrip($text,$striparray);
1366 $text=$parser->unstripNoWiki($text,$striparray);
1370 wfProfileOut( $fname );
1375 * Change an existing article. Puts the previous version back into the old table, updates RC
1376 * and all necessary caches, mostly via the deferred update array.
1378 * It is possible to call this function from a command-line script, but note that you should
1379 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1381 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1382 global $wgUser, $wgDBtransactions, $wgUseSquid;
1383 global $wgPostCommitUpdateList, $wgUseFileCache;
1385 $fname = 'Article::updateArticle';
1386 wfProfileIn( $fname );
1389 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1391 &$watchthis, &$sectionanchor ) ) ) {
1392 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1393 wfProfileOut( $fname );
1397 $isminor = $minor && $wgUser->isAllowed('minoredit');
1398 $redir = (int)$this->isRedirect( $text );
1400 $text = $this->preSaveTransform( $text );
1401 $dbw =& wfGetDB( DB_MASTER
);
1402 $now = wfTimestampNow();
1404 # Update article, but only if changed.
1406 # It's important that we either rollback or complete, otherwise an attacker could
1407 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1408 # could conceivably have the same effect, especially if cur is locked for long periods.
1409 if( !$wgDBtransactions ) {
1410 $userAbort = ignore_user_abort( true );
1413 $oldtext = $this->getContent();
1414 $oldsize = strlen( $oldtext );
1415 $newsize = strlen( $text );
1419 if ( 0 != strcmp( $text, $oldtext ) ) {
1420 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1421 - (int)$this->isCountable( $oldtext );
1422 $this->mTotalAdjustment
= 0;
1423 $now = wfTimestampNow();
1425 $lastRevision = $dbw->selectField(
1426 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1428 $revision = new Revision( array(
1429 'page' => $this->getId(),
1430 'comment' => $summary,
1431 'minor_edit' => $isminor,
1435 $dbw->immediateCommit();
1437 $revisionId = $revision->insertOn( $dbw );
1440 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1443 /* Belated edit conflict! Run away!! */
1447 # Update recentchanges and purge cache and whatnot
1448 require_once( 'RecentChange.php' );
1449 $bot = (int)($wgUser->isBot() ||
$forceBot);
1450 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1451 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1454 # Mark as patrolled if the user can do so and has it set in their options
1455 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1456 RecentChange
::markPatrolled( $rcid );
1461 // Update caches outside the main transaction
1462 Article
::onArticleEdit( $this->mTitle
);
1465 // Keep the same revision ID, but do some updates on it
1466 $revisionId = $this->getRevIdFetched();
1469 if( !$wgDBtransactions ) {
1470 ignore_user_abort( $userAbort );
1475 if (!$this->mTitle
->userIsWatching()) {
1476 $dbw->immediateCommit();
1482 if ( $this->mTitle
->userIsWatching() ) {
1483 $dbw->immediateCommit();
1489 # standard deferred updates
1490 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1494 # Invalidate caches of all articles using this article as a template
1496 # Template namespace
1497 # Purge all articles linking here
1498 $titles = $this->mTitle
->getTemplateLinksTo();
1499 Title
::touchArray( $titles );
1500 if ( $wgUseSquid ) {
1501 foreach ( $titles as $title ) {
1502 $urls[] = $title->getInternalURL();
1507 if ( $wgUseSquid ) {
1508 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1509 $u = new SquidUpdate( $urls );
1510 array_push( $wgPostCommitUpdateList, $u );
1514 if ( $wgUseFileCache ) {
1515 $cm = new CacheManager($this->mTitle
);
1516 @unlink
($cm->fileCacheName());
1519 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1521 wfRunHooks( 'ArticleSaveComplete',
1522 array( &$this, &$wgUser, $text,
1524 $watchthis, $sectionanchor ) );
1525 wfProfileOut( $fname );
1530 * After we've either updated or inserted the article, update
1531 * the link tables and redirect to the new page.
1533 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1536 $fname = 'Article::showArticle';
1537 wfProfileIn( $fname );
1539 # Output the redirect
1540 if( $this->isRedirect( $text ) )
1544 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1546 wfProfileOut( $fname );
1550 * Mark this particular edit as patrolled
1552 function markpatrolled() {
1553 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1554 $wgOut->setRobotpolicy( 'noindex,follow' );
1556 # Check RC patrol config. option
1557 if( !$wgUseRCPatrol ) {
1558 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1563 if( !$wgUser->isAllowed( 'patrol' ) ) {
1564 $wgOut->permissionRequired( 'patrol' );
1568 $rcid = $wgRequest->getVal( 'rcid' );
1569 if ( !is_null ( $rcid ) ) {
1570 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1571 require_once( 'RecentChange.php' );
1572 RecentChange
::markPatrolled( $rcid );
1573 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1574 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1575 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1577 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1578 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1581 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1586 * User-interface handler for the "watch" action
1591 global $wgUser, $wgOut;
1593 if ( $wgUser->isAnon() ) {
1594 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1597 if ( wfReadOnly() ) {
1598 $wgOut->readOnlyPage();
1602 if( $this->doWatch() ) {
1603 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1604 $wgOut->setRobotpolicy( 'noindex,follow' );
1606 $link = $this->mTitle
->getPrefixedText();
1607 $text = wfMsg( 'addedwatchtext', $link );
1608 $wgOut->addWikiText( $text );
1611 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1615 * Add this page to $wgUser's watchlist
1616 * @return bool true on successful watch operation
1618 function doWatch() {
1620 if( $wgUser->isAnon() ) {
1624 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1625 $wgUser->addWatch( $this->mTitle
);
1626 $wgUser->saveSettings();
1628 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1635 * User interface handler for the "unwatch" action.
1637 function unwatch() {
1639 global $wgUser, $wgOut;
1641 if ( $wgUser->isAnon() ) {
1642 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1645 if ( wfReadOnly() ) {
1646 $wgOut->readOnlyPage();
1650 if( $this->doUnwatch() ) {
1651 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1652 $wgOut->setRobotpolicy( 'noindex,follow' );
1654 $link = $this->mTitle
->getPrefixedText();
1655 $text = wfMsg( 'removedwatchtext', $link );
1656 $wgOut->addWikiText( $text );
1659 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1663 * Stop watching a page
1664 * @return bool true on successful unwatch
1666 function doUnwatch() {
1668 if( $wgUser->isAnon() ) {
1672 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1673 $wgUser->removeWatch( $this->mTitle
);
1674 $wgUser->saveSettings();
1676 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1683 * action=protect handler
1685 function protect() {
1686 require_once 'ProtectionForm.php';
1687 $form = new ProtectionForm( $this );
1692 * action=unprotect handler (alias)
1694 function unprotect() {
1699 * Update the article's restriction field, and leave a log entry.
1701 * @param array $limit set of restriction keys
1702 * @param string $reason
1703 * @return bool true on success
1705 function updateRestrictions( $limit = array(), $reason = '' ) {
1706 global $wgUser, $wgRestrictionTypes, $wgContLang;
1708 $id = $this->mTitle
->getArticleID();
1709 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1713 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1714 # we expect a single selection, but the schema allows otherwise.
1716 foreach( $wgRestrictionTypes as $action )
1717 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1719 $current = Article
::flattenRestrictions( $current );
1720 $updated = Article
::flattenRestrictions( $limit );
1722 $changed = ( $current != $updated );
1723 $protect = ( $updated != '' );
1725 # If nothing's changed, do nothing
1727 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1729 $dbw =& wfGetDB( DB_MASTER
);
1731 # Prepare a null revision to be added to the history
1732 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1734 $comment .= ": $reason";
1736 $comment .= " [$updated]";
1737 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1738 $nullRevId = $nullRevision->insertOn( $dbw );
1740 # Update page record
1741 $dbw->update( 'page',
1743 'page_touched' => $dbw->timestamp(),
1744 'page_restrictions' => $updated,
1745 'page_latest' => $nullRevId
1746 ), array( /* WHERE */
1748 ), 'Article::protect'
1750 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1752 # Update the protection log
1753 $log = new LogPage( 'protect' );
1755 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1757 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1761 } # End "changed" check
1767 * Take an array of page restrictions and flatten it to a string
1768 * suitable for insertion into the page_restrictions field.
1769 * @param array $limit
1773 function flattenRestrictions( $limit ) {
1774 if( !is_array( $limit ) ) {
1775 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1779 foreach( $limit as $action => $restrictions ) {
1780 if( $restrictions != '' ) {
1781 $bits[] = "$action=$restrictions";
1784 return implode( ':', $bits );
1788 * UI entry point for page deletion
1791 global $wgUser, $wgOut, $wgRequest;
1792 $fname = 'Article::delete';
1793 $confirm = $wgRequest->wasPosted() &&
1794 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1795 $reason = $wgRequest->getText( 'wpReason' );
1797 # This code desperately needs to be totally rewritten
1800 if( $wgUser->isAllowed( 'delete' ) ) {
1801 if( $wgUser->isBlocked() ) {
1802 $wgOut->blockedPage();
1806 $wgOut->permissionRequired( 'delete' );
1810 if( wfReadOnly() ) {
1811 $wgOut->readOnlyPage();
1815 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1817 # Better double-check that it hasn't been deleted yet!
1818 $dbw =& wfGetDB( DB_MASTER
);
1819 $conds = $this->mTitle
->pageCond();
1820 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1821 if ( $latest === false ) {
1822 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1827 $this->doDelete( $reason );
1831 # determine whether this page has earlier revisions
1832 # and insert a warning if it does
1834 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1836 if( count( $authors ) > 1 && !$confirm ) {
1837 $skin=$wgUser->getSkin();
1838 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1841 # If a single user is responsible for all revisions, find out who they are
1842 if ( count( $authors ) == $maxRevisions ) {
1843 // Query bailed out, too many revisions to find out if they're all the same
1844 $authorOfAll = false;
1846 $authorOfAll = reset( $authors );
1847 foreach ( $authors as $author ) {
1848 if ( $authorOfAll != $author ) {
1849 $authorOfAll = false;
1854 # Fetch article text
1855 $rev = Revision
::newFromTitle( $this->mTitle
);
1857 if( !is_null( $rev ) ) {
1858 # if this is a mini-text, we can paste part of it into the deletion reason
1859 $text = $rev->getText();
1861 #if this is empty, an earlier revision may contain "useful" text
1864 $prev = $rev->getPrevious();
1866 $text = $prev->getText();
1871 $length = strlen( $text );
1873 # this should not happen, since it is not possible to store an empty, new
1874 # page. Let's insert a standard text in case it does, though
1875 if( $length == 0 && $reason === '' ) {
1876 $reason = wfMsgForContent( 'exblank' );
1879 if( $length < 500 && $reason === '' ) {
1880 # comment field=255, let's grep the first 150 to have some user
1883 $text = $wgContLang->truncate( $text, 150, '...' );
1885 # let's strip out newlines
1886 $text = preg_replace( "/[\n\r]/", '', $text );
1889 if( $authorOfAll === false ) {
1890 $reason = wfMsgForContent( 'excontent', $text );
1892 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1895 $reason = wfMsgForContent( 'exbeforeblank', $text );
1900 return $this->confirmDelete( '', $reason );
1904 * Get the last N authors
1905 * @param int $num Number of revisions to get
1906 * @param string $revLatest The latest rev_id, selected from the master (optional)
1907 * @return array Array of authors, duplicates not removed
1909 function getLastNAuthors( $num, $revLatest = 0 ) {
1910 $fname = 'Article::getLastNAuthors';
1911 wfProfileIn( $fname );
1913 // First try the slave
1914 // If that doesn't have the latest revision, try the master
1916 $db =& wfGetDB( DB_SLAVE
);
1918 $res = $db->select( array( 'page', 'revision' ),
1919 array( 'rev_id', 'rev_user_text' ),
1921 'page_namespace' => $this->mTitle
->getNamespace(),
1922 'page_title' => $this->mTitle
->getDBkey(),
1923 'rev_page = page_id'
1924 ), $fname, $this->getSelectOptions( array(
1925 'ORDER BY' => 'rev_timestamp DESC',
1930 wfProfileOut( $fname );
1933 $row = $db->fetchObject( $res );
1934 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1935 $db =& wfGetDB( DB_MASTER
);
1940 } while ( $continue );
1942 $authors = array( $row->rev_user_text
);
1943 while ( $row = $db->fetchObject( $res ) ) {
1944 $authors[] = $row->rev_user_text
;
1946 wfProfileOut( $fname );
1951 * Output deletion confirmation dialog
1953 function confirmDelete( $par, $reason ) {
1954 global $wgOut, $wgUser;
1956 wfDebug( "Article::confirmDelete\n" );
1958 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1959 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1960 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1961 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1963 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1965 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1966 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1967 $token = htmlspecialchars( $wgUser->editToken() );
1970 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1974 <label for='wpReason'>{$delcom}:</label>
1977 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1983 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1987 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1990 $wgOut->returnToMain( false );
1995 * Perform a deletion and output success or failure messages
1997 function doDelete( $reason ) {
1998 global $wgOut, $wgUser;
1999 $fname = 'Article::doDelete';
2000 wfDebug( $fname."\n" );
2002 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2003 if ( $this->doDeleteArticle( $reason ) ) {
2004 $deleted = $this->mTitle
->getPrefixedText();
2006 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2007 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2009 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2010 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2012 $wgOut->addWikiText( $text );
2013 $wgOut->returnToMain( false );
2014 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2016 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2022 * Back-end article deletion
2023 * Deletes the article with database consistency, writes logs, purges caches
2026 function doDeleteArticle( $reason ) {
2027 global $wgUseSquid, $wgDeferredUpdateList;
2028 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2030 $fname = 'Article::doDeleteArticle';
2031 wfDebug( $fname."\n" );
2033 $dbw =& wfGetDB( DB_MASTER
);
2034 $ns = $this->mTitle
->getNamespace();
2035 $t = $this->mTitle
->getDBkey();
2036 $id = $this->mTitle
->getArticleID();
2038 if ( $t == '' ||
$id == 0 ) {
2042 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2043 array_push( $wgDeferredUpdateList, $u );
2045 $linksTo = $this->mTitle
->getLinksTo();
2048 if ( $wgUseSquid ) {
2050 $this->mTitle
->getInternalURL(),
2051 $this->mTitle
->getInternalURL( 'history' )
2054 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2055 array_push( $wgPostCommitUpdateList, $u );
2059 # Client and file cache invalidation
2060 Title
::touchArray( $linksTo );
2063 // For now, shunt the revision data into the archive table.
2064 // Text is *not* removed from the text table; bulk storage
2065 // is left intact to avoid breaking block-compression or
2066 // immutable storage schemes.
2068 // For backwards compatibility, note that some older archive
2069 // table entries will have ar_text and ar_flags fields still.
2071 // In the future, we may keep revisions and mark them with
2072 // the rev_deleted field, which is reserved for this purpose.
2073 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2075 'ar_namespace' => 'page_namespace',
2076 'ar_title' => 'page_title',
2077 'ar_comment' => 'rev_comment',
2078 'ar_user' => 'rev_user',
2079 'ar_user_text' => 'rev_user_text',
2080 'ar_timestamp' => 'rev_timestamp',
2081 'ar_minor_edit' => 'rev_minor_edit',
2082 'ar_rev_id' => 'rev_id',
2083 'ar_text_id' => 'rev_text_id',
2086 'page_id = rev_page'
2090 # Now that it's safely backed up, delete it
2091 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2092 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2094 if ($wgUseTrackbacks)
2095 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2097 # Clean up recentchanges entries...
2098 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2100 # Finally, clean up the link tables
2101 $t = $this->mTitle
->getPrefixedDBkey();
2103 Article
::onArticleDelete( $this->mTitle
);
2105 # Delete outgoing links
2106 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2107 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2108 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2109 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2110 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2111 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2114 $log = new LogPage( 'delete' );
2115 $log->addEntry( 'delete', $this->mTitle
, $reason );
2117 # Clear the cached article id so the interface doesn't act like we exist
2118 $this->mTitle
->resetArticleID( 0 );
2119 $this->mTitle
->mArticleID
= 0;
2124 * Revert a modification
2126 function rollback() {
2127 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2128 $fname = 'Article::rollback';
2130 if( $wgUser->isAllowed( 'rollback' ) ) {
2131 if( $wgUser->isBlocked() ) {
2132 $wgOut->blockedPage();
2136 $wgOut->permissionRequired( 'rollback' );
2140 if ( wfReadOnly() ) {
2141 $wgOut->readOnlyPage( $this->getContent() );
2144 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2145 array( $this->mTitle
->getPrefixedText(),
2146 $wgRequest->getVal( 'from' ) ) ) ) {
2147 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2148 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2151 $dbw =& wfGetDB( DB_MASTER
);
2153 # Enhanced rollback, marks edits rc_bot=1
2154 $bot = $wgRequest->getBool( 'bot' );
2156 # Replace all this user's current edits with the next one down
2157 $tt = $this->mTitle
->getDBKey();
2158 $n = $this->mTitle
->getNamespace();
2160 # Get the last editor, lock table exclusively
2162 $current = Revision
::newFromTitle( $this->mTitle
);
2163 if( is_null( $current ) ) {
2164 # Something wrong... no page?
2166 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2170 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2171 if( $from != $current->getUserText() ) {
2172 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2173 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2174 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2175 htmlspecialchars( $from ),
2176 htmlspecialchars( $current->getUserText() ) ) );
2177 if( $current->getComment() != '') {
2179 wfMsg( 'editcomment',
2180 htmlspecialchars( $current->getComment() ) ) );
2185 # Get the last edit not by this guy
2186 $user = intval( $current->getUser() );
2187 $user_text = $dbw->addQuotes( $current->getUserText() );
2188 $s = $dbw->selectRow( 'revision',
2189 array( 'rev_id', 'rev_timestamp' ),
2191 'rev_page' => $current->getPage(),
2192 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2195 'USE INDEX' => 'page_timestamp',
2196 'ORDER BY' => 'rev_timestamp DESC' )
2198 if( $s === false ) {
2201 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2202 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2208 # Mark all reverted edits as bot
2211 if ( $wgUseRCPatrol ) {
2212 # Mark all reverted edits as patrolled
2213 $set['rc_patrolled'] = 1;
2217 $dbw->update( 'recentchanges', $set,
2219 'rc_cur_id' => $current->getPage(),
2220 'rc_user_text' => $current->getUserText(),
2221 "rc_timestamp > '{$s->rev_timestamp}'",
2226 # Get the edit summary
2227 $target = Revision
::newFromId( $s->rev_id
);
2228 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2229 $newComment = $wgRequest->getText( 'summary', $newComment );
2232 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2233 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2234 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2236 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2237 Article
::onArticleEdit( $this->mTitle
);
2240 $wgOut->returnToMain( false );
2245 * Do standard deferred updates after page view
2248 function viewUpdates() {
2249 global $wgDeferredUpdateList;
2251 if ( 0 != $this->getID() ) {
2252 global $wgDisableCounters;
2253 if( !$wgDisableCounters ) {
2254 Article
::incViewCount( $this->getID() );
2255 $u = new SiteStatsUpdate( 1, 0, 0 );
2256 array_push( $wgDeferredUpdateList, $u );
2260 # Update newtalk / watchlist notification status
2262 $wgUser->clearNotification( $this->mTitle
);
2266 * Do standard deferred updates after page edit.
2267 * Every 1000th edit, prune the recent changes table.
2269 * @param string $text
2271 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2272 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2274 $fname = 'Article::editUpdates';
2275 wfProfileIn( $fname );
2278 $options = new ParserOptions
;
2279 $options->setTidy(true);
2280 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2282 # Save it to the parser cache
2283 $parserCache =& ParserCache
::singleton();
2284 $parserCache->save( $poutput, $this, $wgUser );
2286 # Update the links tables
2287 $u = new LinksUpdate( $this->mTitle
, $poutput );
2290 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2292 if ( 0 == mt_rand( 0, 999 ) ) {
2293 # Periodically flush old entries from the recentchanges table.
2296 $dbw =& wfGetDB( DB_MASTER
);
2297 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2298 $recentchanges = $dbw->tableName( 'recentchanges' );
2299 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2300 $dbw->query( $sql );
2304 $id = $this->getID();
2305 $title = $this->mTitle
->getPrefixedDBkey();
2306 $shortTitle = $this->mTitle
->getDBkey();
2309 wfProfileOut( $fname );
2313 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2314 array_push( $wgDeferredUpdateList, $u );
2315 $u = new SearchUpdate( $id, $title, $text );
2316 array_push( $wgDeferredUpdateList, $u );
2318 # If this is another user's talk page, update newtalk
2320 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2321 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2322 $other = User
::newFromName( $shortTitle );
2323 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2324 // An anonymous user
2325 $other = new User();
2326 $other->setName( $shortTitle );
2329 $other->setNewtalk( true );
2334 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2335 $wgMessageCache->replace( $shortTitle, $text );
2338 wfProfileOut( $fname );
2342 * Generate the navigation links when browsing through an article revisions
2343 * It shows the information as:
2344 * Revision as of \<date\>; view current revision
2345 * \<- Previous version | Next Version -\>
2348 * @param string $oldid Revision ID of this article revision
2350 function setOldSubtitle( $oldid=0 ) {
2351 global $wgLang, $wgOut, $wgUser;
2353 $current = ( $oldid == $this->mLatest
);
2354 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2355 $sk = $wgUser->getSkin();
2357 ?
wfMsg( 'currentrevisionlink' )
2358 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2359 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2361 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2362 : wfMsg( 'previousrevision' );
2363 $nextlink = $current
2364 ?
wfMsg( 'nextrevision' )
2365 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2366 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2367 $wgOut->setSubtitle( $r );
2371 * This function is called right before saving the wikitext,
2372 * so we can do things like signatures and links-in-context.
2374 * @param string $text
2376 function preSaveTransform( $text ) {
2377 global $wgParser, $wgUser;
2378 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2381 /* Caching functions */
2384 * checkLastModified returns true if it has taken care of all
2385 * output to the client that is necessary for this request.
2386 * (that is, it has sent a cached version of the page)
2388 function tryFileCache() {
2389 static $called = false;
2391 wfDebug( " tryFileCache() -- called twice!?\n" );
2395 if($this->isFileCacheable()) {
2396 $touched = $this->mTouched
;
2397 $cache = new CacheManager( $this->mTitle
);
2398 if($cache->isFileCacheGood( $touched )) {
2399 wfDebug( " tryFileCache() - about to load\n" );
2400 $cache->loadFromFileCache();
2403 wfDebug( " tryFileCache() - starting buffer\n" );
2404 ob_start( array(&$cache, 'saveToFileCache' ) );
2407 wfDebug( " tryFileCache() - not cacheable\n" );
2412 * Check if the page can be cached
2415 function isFileCacheable() {
2416 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2417 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2419 return $wgUseFileCache
2420 and (!$wgShowIPinHeader)
2421 and ($this->getID() != 0)
2422 and ($wgUser->isAnon())
2423 and (!$wgUser->getNewtalk())
2424 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2425 and (empty( $action ) ||
$action == 'view')
2426 and (!isset($oldid))
2428 and (!isset($redirect))
2429 and (!isset($printable))
2430 and (!$this->mRedirectedFrom
);
2434 * Loads page_touched and returns a value indicating if it should be used
2437 function checkTouched() {
2438 $fname = 'Article::checkTouched';
2439 if( !$this->mDataLoaded
) {
2440 $this->loadPageData();
2442 return !$this->mIsRedirect
;
2446 * Get the page_touched field
2448 function getTouched() {
2449 # Ensure that page data has been loaded
2450 if( !$this->mDataLoaded
) {
2451 $this->loadPageData();
2453 return $this->mTouched
;
2457 * Get the page_latest field
2459 function getLatest() {
2460 if ( !$this->mDataLoaded
) {
2461 $this->loadPageData();
2463 return $this->mLatest
;
2467 * Edit an article without doing all that other stuff
2468 * The article must already exist; link tables etc
2469 * are not updated, caches are not flushed.
2471 * @param string $text text submitted
2472 * @param string $comment comment submitted
2473 * @param bool $minor whereas it's a minor modification
2475 function quickEdit( $text, $comment = '', $minor = 0 ) {
2476 $fname = 'Article::quickEdit';
2477 wfProfileIn( $fname );
2479 $dbw =& wfGetDB( DB_MASTER
);
2481 $revision = new Revision( array(
2482 'page' => $this->getId(),
2484 'comment' => $comment,
2485 'minor_edit' => $minor ?
1 : 0,
2487 $revisionId = $revision->insertOn( $dbw );
2488 $this->updateRevisionOn( $dbw, $revision );
2491 wfProfileOut( $fname );
2495 * Used to increment the view counter
2498 * @param integer $id article id
2500 function incViewCount( $id ) {
2501 $id = intval( $id );
2502 global $wgHitcounterUpdateFreq, $wgDBtype;
2504 $dbw =& wfGetDB( DB_MASTER
);
2505 $pageTable = $dbw->tableName( 'page' );
2506 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2507 $acchitsTable = $dbw->tableName( 'acchits' );
2509 if( $wgHitcounterUpdateFreq <= 1 ){ //
2510 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2514 # Not important enough to warrant an error page in case of failure
2515 $oldignore = $dbw->ignoreErrors( true );
2517 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2519 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2520 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2521 # Most of the time (or on SQL errors), skip row count check
2522 $dbw->ignoreErrors( $oldignore );
2526 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2527 $row = $dbw->fetchObject( $res );
2528 $rown = intval( $row->n
);
2529 if( $rown >= $wgHitcounterUpdateFreq ){
2530 wfProfileIn( 'Article::incViewCount-collect' );
2531 $old_user_abort = ignore_user_abort( true );
2533 if ($wgDBtype == 'mysql')
2534 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2535 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2536 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2537 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2539 $dbw->query("DELETE FROM $hitcounterTable");
2540 if ($wgDBtype == 'mysql')
2541 $dbw->query('UNLOCK TABLES');
2542 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2543 'WHERE page_id = hc_id');
2544 $dbw->query("DROP TABLE $acchitsTable");
2546 ignore_user_abort( $old_user_abort );
2547 wfProfileOut( 'Article::incViewCount-collect' );
2549 $dbw->ignoreErrors( $oldignore );
2553 * The onArticle*() functions are supposed to be a kind of hooks
2554 * which should be called whenever any of the specified actions
2557 * This is a good place to put code to clear caches, for instance.
2559 * This is called on page move and undelete, as well as edit
2561 * @param $title_obj a title object
2564 function onArticleCreate($title_obj) {
2565 global $wgUseSquid, $wgPostCommitUpdateList;
2567 $title_obj->touchLinks();
2568 $titles = $title_obj->getLinksTo();
2571 if ( $wgUseSquid ) {
2572 $urls = $title_obj->getSquidURLs();
2573 foreach ( $titles as $linkTitle ) {
2574 $urls[] = $linkTitle->getInternalURL();
2576 $u = new SquidUpdate( $urls );
2577 array_push( $wgPostCommitUpdateList, $u );
2581 function onArticleDelete( $title ) {
2582 global $wgMessageCache;
2584 $title->touchLinks();
2586 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2587 $wgMessageCache->replace( $title->getDBkey(), false );
2592 * Purge caches on page update etc
2594 function onArticleEdit( $title ) {
2595 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2599 // Template namespace? Purge all articles linking here.
2600 // FIXME: When a templatelinks table arrives, use it for all includes.
2601 if ( $title->getNamespace() == NS_TEMPLATE
) {
2602 $titles = $title->getLinksTo();
2603 Title
::touchArray( $titles );
2604 if ( $wgUseSquid ) {
2605 foreach ( $titles as $link ) {
2606 $urls[] = $link->getInternalURL();
2612 if ( $wgUseSquid ) {
2613 $urls = array_merge( $urls, $title->getSquidURLs() );
2614 $u = new SquidUpdate( $urls );
2615 array_push( $wgPostCommitUpdateList, $u );
2619 if ( $wgUseFileCache ) {
2620 $cm = new CacheManager( $title );
2621 @unlink
( $cm->fileCacheName() );
2628 * Info about this page
2629 * Called for ?action=info when $wgAllowPageInfo is on.
2634 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2635 $fname = 'Article::info';
2637 if ( !$wgAllowPageInfo ) {
2638 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2642 $page = $this->mTitle
->getSubjectPage();
2644 $wgOut->setPagetitle( $page->getPrefixedText() );
2645 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2647 # first, see if the page exists at all.
2648 $exists = $page->getArticleId() != 0;
2650 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2651 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2653 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2656 $dbr =& wfGetDB( DB_SLAVE
);
2658 'wl_title' => $page->getDBkey(),
2659 'wl_namespace' => $page->getNamespace() );
2660 $numwatchers = $dbr->selectField(
2665 $this->getSelectOptions() );
2667 $pageInfo = $this->pageCountInfo( $page );
2668 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2670 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2671 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2673 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2675 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2677 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2679 $wgOut->addHTML( '</ul>' );
2685 * Return the total number of edits and number of unique editors
2686 * on a given page. If page does not exist, returns false.
2688 * @param Title $title
2692 function pageCountInfo( $title ) {
2693 $id = $title->getArticleId();
2698 $dbr =& wfGetDB( DB_SLAVE
);
2700 $rev_clause = array( 'rev_page' => $id );
2701 $fname = 'Article::pageCountInfo';
2703 $edits = $dbr->selectField(
2708 $this->getSelectOptions() );
2710 $authors = $dbr->selectField(
2712 'COUNT(DISTINCT rev_user_text)',
2715 $this->getSelectOptions() );
2717 return array( 'edits' => $edits, 'authors' => $authors );
2721 * Return a list of templates used by this article.
2722 * Uses the templatelinks table
2724 * @return array Array of Title objects
2726 function getUsedTemplates() {
2728 $id = $this->mTitle
->getArticleID();
2733 $dbr =& wfGetDB( DB_SLAVE
);
2734 $res = $dbr->select( array( 'templatelinks' ),
2735 array( 'tl_namespace', 'tl_title' ),
2736 array( 'tl_from' => $id ),
2737 'Article:getUsedTemplates' );
2738 if ( false !== $res ) {
2739 if ( $dbr->numRows( $res ) ) {
2740 while ( $row = $dbr->fetchObject( $res ) ) {
2741 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2745 $dbr->freeResult( $res );