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.
29 private $mComment; //!<
30 private $mContent; //!<
31 private $mContentLoaded; //!<
32 private $mCounter; //!<
33 private $mFileCache; //!<
34 private $mForUpdate; //!<
35 private $mGoodAdjustment; //!<
37 private $mLatest; //!<
38 private $mMinorEdit; //!<
40 private $mRedirectedFrom; //!<
41 private $mRedirectUrl; //!<
42 private $mRevIdFetched; //!<
43 private $mRevision; //!<
45 private $mTimestamp; //!<
46 private $mTotalAdjustment; //!<
48 private $mUserText; //!<
52 public $mTouched; //!<
56 * Constructor and clear the article
57 * @param $title Reference to a Title object.
58 * @param $oldId Integer revision ID, null to fetch from request, zero for current
60 function Article( &$title, $oldId = null ) {
61 $this->mTitle
=& $title;
62 $this->mOldId
= $oldId;
67 * Tell the page view functions that this view was redirected
68 * from another page on the wiki.
69 * @param $from Title object.
71 function setRedirectedFrom( $from ) {
72 $this->mRedirectedFrom
= $from;
76 * @return mixed false, Title of in-wiki target, or string with URL
78 function followRedirect() {
79 $text = $this->getContent();
80 $rt = Title
::newFromRedirect( $text );
82 # process if title object is valid and not special:userlogout
84 if( $rt->getInterwiki() != '' ) {
85 if( $rt->isLocal() ) {
86 // Offsite wikis need an HTTP redirect.
88 // This can be hard to reverse and may produce loops,
89 // so they may be disabled in the site configuration.
91 $source = $this->mTitle
->getFullURL( 'redirect=no' );
92 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
95 if( $rt->getNamespace() == NS_SPECIAL
) {
96 // Gotta hand redirects to special pages differently:
97 // Fill the HTTP response "Location" header and ignore
98 // the rest of the page we're on.
100 // This can be hard to reverse, so they may be disabled.
102 if( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) {
105 return $rt->getFullURL();
112 // No or invalid redirect
117 * get the title object of the article
119 function getTitle() {
120 return $this->mTitle
;
128 $this->mDataLoaded
= false;
129 $this->mContentLoaded
= false;
131 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
132 $this->mRedirectedFrom
= null; # Title object if set
134 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
135 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
136 $this->mTouched
= '19700101000000';
137 $this->mForUpdate
= false;
138 $this->mIsRedirect
= false;
139 $this->mRevIdFetched
= 0;
140 $this->mRedirectUrl
= false;
141 $this->mLatest
= false;
145 * Note that getContent/loadContent do not follow redirects anymore.
146 * If you need to fetch redirectable content easily, try
147 * the shortcut in Article::followContent()
149 * @todo There are still side-effects in this!
150 * In general, you should use the Revision class, not Article,
151 * to fetch text for purposes other than page views.
153 * @return Return the text of this revision
155 function getContent() {
156 global $wgRequest, $wgUser, $wgOut;
158 # Get variables from query string :P
159 $action = $wgRequest->getText( 'action', 'view' );
160 $section = $wgRequest->getText( 'section' );
161 $preload = $wgRequest->getText( 'preload' );
163 $fname = 'Article::getContent';
164 wfProfileIn( $fname );
166 if ( 0 == $this->getID() ) {
167 if ( 'edit' == $action ) {
168 wfProfileOut( $fname );
170 # If requested, preload some text.
171 $text=$this->getPreloadedText($preload);
173 # We used to put MediaWiki:Newarticletext here if
174 # $text was empty at this point.
175 # This is now shown above the edit box instead.
178 wfProfileOut( $fname );
179 $wgOut->setRobotpolicy( 'noindex,nofollow' );
181 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
182 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
184 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
187 return "<div class='noarticletext'>$ret</div>";
189 $this->loadContent();
190 if($action=='edit') {
192 if($section=='new') {
193 wfProfileOut( $fname );
194 $text=$this->getPreloadedText($preload);
198 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
199 # comments to be stripped as well)
200 $rv=$this->getSection($this->mContent
,$section);
201 wfProfileOut( $fname );
205 wfProfileOut( $fname );
206 return $this->mContent
;
211 * Get the contents of a page from its title and remove includeonly tags
213 * @param $preload String: the title of the page.
214 * @return string The contents of the page.
216 function getPreloadedText($preload) {
217 if ( $preload === '' )
220 $preloadTitle = Title
::newFromText( $preload );
221 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
222 $rev=Revision
::newFromTitle($preloadTitle);
223 if ( is_object( $rev ) ) {
224 $text = $rev->getText();
225 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
226 // its own mini-parser! -ævar
227 $text = preg_replace( '~</?includeonly>~', '', $text );
236 * This function returns the text of a section, specified by a number ($section).
237 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
238 * the first section before any such heading (section 0).
240 * If a section contains subsections, these are also returned.
242 * @param $text String: text to look in
243 * @param $section Integer: section number
244 * @return string text of the requested section
246 function getSection($text,$section) {
248 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
249 # comments to be stripped as well)
251 $parser=new Parser();
252 $parser->mOutputType
=OT_WIKI
;
253 $parser->mOptions
= new ParserOptions();
254 $striptext=$parser->strip($text, $striparray, true);
256 # now that we can be sure that no pseudo-sections are in the source,
257 # split it up by section
260 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
262 PREG_SPLIT_DELIM_CAPTURE
);
266 $headline=$secs[$section*2-1];
267 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
270 # translate wiki heading into level
271 if(strpos($hlevel,'=')!==false) {
272 $hlevel=strlen($hlevel);
275 $rv=$headline. $secs[$section*2];
279 while(!empty($secs[$count*2-1]) && !$break) {
281 $subheadline=$secs[$count*2-1];
282 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
283 $subhlevel=$matches[1];
284 if(strpos($subhlevel,'=')!==false) {
285 $subhlevel=strlen($subhlevel);
287 if($subhlevel > $hlevel) {
288 $rv.=$subheadline.$secs[$count*2];
290 if($subhlevel <= $hlevel) {
297 # reinsert stripped tags
298 $rv=$parser->unstrip($rv,$striparray);
299 $rv=$parser->unstripNoWiki($rv,$striparray);
306 * @return int The oldid of the article that is to be shown, 0 for the
309 function getOldID() {
310 if ( is_null( $this->mOldId
) ) {
311 $this->mOldId
= $this->getOldIDFromRequest();
313 return $this->mOldId
;
317 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
319 * @return int The old id for the request
321 function getOldIDFromRequest() {
323 $this->mRedirectUrl
= false;
324 $oldid = $wgRequest->getVal( 'oldid' );
325 if ( isset( $oldid ) ) {
326 $oldid = intval( $oldid );
327 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
328 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
332 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
334 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
335 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
352 * Load the revision (including text) into this object
354 function loadContent() {
355 if ( $this->mContentLoaded
) return;
358 $oldid = $this->getOldID();
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
;
695 * @todo Document, fixme $offset never used.
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 #Â fixme unused $titleText :
903 $titleText = htmlspecialchars( $rt->getPrefixedText() );
904 $link = $sk->makeLinkObj( $rt );
906 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
907 '<span class="redirectText">'.$link.'</span>' );
909 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
910 $wgOut->addParserOutputNoText( $parseout );
911 } else if ( $pcache ) {
912 # Display content and save to parser cache
913 $wgOut->addPrimaryWikiText( $text, $this );
915 # Display content, don't attempt to save to parser cache
917 # Don't show section-edit links on old revisions... this way lies madness.
918 if( !$this->isCurrent() ) {
919 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
921 # Display content and don't save to parser cache
922 $wgOut->addPrimaryWikiText( $text, $this, false );
924 if( !$this->isCurrent() ) {
925 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
929 /* title may have been set from the cache */
930 $t = $wgOut->getPageTitle();
932 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
935 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
936 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
937 User
::isIP( $this->mTitle
->getText() ) ) {
938 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
941 # If we have been passed an &rcid= parameter, we want to give the user a
942 # chance to mark this new article as patrolled.
943 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
945 "<div class='patrollink'>" .
946 wfMsg ( 'markaspatrolledlink',
947 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
954 if ($wgUseTrackbacks)
955 $this->addTrackbacks();
957 $this->viewUpdates();
958 wfProfileOut( $fname );
961 function addTrackbacks() {
962 global $wgOut, $wgUser;
964 $dbr =& wfGetDB(DB_SLAVE
);
966 /* FROM */ 'trackbacks',
967 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
968 /* WHERE */ array('tb_page' => $this->getID())
971 if (!$dbr->numrows($tbs))
975 while ($o = $dbr->fetchObject($tbs)) {
977 if ($wgUser->isAllowed( 'trackback' )) {
978 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
979 . $o->tb_id
. "&token=" . $wgUser->editToken());
980 $rmvtxt = wfMsg('trackbackremove', $delurl);
982 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
989 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
992 function deletetrackback() {
993 global $wgUser, $wgRequest, $wgOut, $wgTitle;
995 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
996 $wgOut->addWikitext(wfMsg('sessionfailure'));
1000 if ((!$wgUser->isAllowed('delete'))) {
1001 $wgOut->sysopRequired();
1006 $wgOut->readOnlyPage();
1010 $db =& wfGetDB(DB_MASTER
);
1011 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1012 $wgTitle->invalidateCache();
1013 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1019 $wgOut->setArticleBodyOnly(true);
1024 * Handle action=purge
1027 global $wgUser, $wgRequest, $wgOut;
1029 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1030 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1034 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1035 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1036 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1037 $msg = str_replace( '$1',
1038 "<form method=\"post\" action=\"$action\">\n" .
1039 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1040 "</form>\n", $msg );
1042 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1043 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1044 $wgOut->addHTML( $msg );
1049 * Perform the actions of a page purging
1051 function doPurge() {
1053 // Invalidate the cache
1054 $this->mTitle
->invalidateCache();
1056 if ( $wgUseSquid ) {
1057 // Commit the transaction before the purge is sent
1058 $dbw = wfGetDB( DB_MASTER
);
1059 $dbw->immediateCommit();
1062 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1063 $update->doUpdate();
1069 * Insert a new empty page record for this article.
1070 * This *must* be followed up by creating a revision
1071 * and running $this->updateToLatest( $rev_id );
1072 * or else the record will be left in a funky state.
1073 * Best if all done inside a transaction.
1075 * @param Database $dbw
1076 * @param string $restrictions
1077 * @return int The newly created page_id key
1080 function insertOn( &$dbw, $restrictions = '' ) {
1081 $fname = 'Article::insertOn';
1082 wfProfileIn( $fname );
1084 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1085 $dbw->insert( 'page', array(
1086 'page_id' => $page_id,
1087 'page_namespace' => $this->mTitle
->getNamespace(),
1088 'page_title' => $this->mTitle
->getDBkey(),
1089 'page_counter' => 0,
1090 'page_restrictions' => $restrictions,
1091 'page_is_redirect' => 0, # Will set this shortly...
1093 'page_random' => wfRandom(),
1094 'page_touched' => $dbw->timestamp(),
1095 'page_latest' => 0, # Fill this in shortly...
1096 'page_len' => 0, # Fill this in shortly...
1098 $newid = $dbw->insertId();
1100 $this->mTitle
->resetArticleId( $newid );
1102 wfProfileOut( $fname );
1107 * Update the page record to point to a newly saved revision.
1109 * @param Database $dbw
1110 * @param Revision $revision For ID number, and text used to set
1111 length and redirect status fields
1112 * @param int $lastRevision If given, will not overwrite the page field
1113 * when different from the currently set value.
1114 * Giving 0 indicates the new page flag should
1116 * @return bool true on success, false on failure
1119 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1120 $fname = 'Article::updateToRevision';
1121 wfProfileIn( $fname );
1123 $conditions = array( 'page_id' => $this->getId() );
1124 if( !is_null( $lastRevision ) ) {
1125 # An extra check against threads stepping on each other
1126 $conditions['page_latest'] = $lastRevision;
1129 $text = $revision->getText();
1130 $dbw->update( 'page',
1132 'page_latest' => $revision->getId(),
1133 'page_touched' => $dbw->timestamp(),
1134 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1135 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1136 'page_len' => strlen( $text ),
1141 wfProfileOut( $fname );
1142 return ( $dbw->affectedRows() != 0 );
1146 * If the given revision is newer than the currently set page_latest,
1147 * update the page record. Otherwise, do nothing.
1149 * @param Database $dbw
1150 * @param Revision $revision
1152 function updateIfNewerOn( &$dbw, $revision ) {
1153 $fname = 'Article::updateIfNewerOn';
1154 wfProfileIn( $fname );
1156 $row = $dbw->selectRow(
1157 array( 'revision', 'page' ),
1158 array( 'rev_id', 'rev_timestamp' ),
1160 'page_id' => $this->getId(),
1161 'page_latest=rev_id' ),
1164 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1165 wfProfileOut( $fname );
1168 $prev = $row->rev_id
;
1170 # No or missing previous revision; mark the page as new
1174 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1175 wfProfileOut( $fname );
1180 * Insert a new article into the database
1183 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1186 $fname = 'Article::insertNewArticle';
1187 wfProfileIn( $fname );
1189 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1190 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1191 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1192 wfProfileOut( $fname );
1196 $ns = $this->mTitle
->getNamespace();
1197 $ttl = $this->mTitle
->getDBkey();
1199 # If this is a comment, add the summary as headline
1200 if($comment && $summary!="") {
1201 $text="== {$summary} ==\n\n".$text;
1203 $text = $this->preSaveTransform( $text );
1206 # Set statistics members
1207 # We work out if it's countable after PST to avoid counter drift
1208 # when articles are created with {{subst:}}
1209 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1210 $this->mTotalAdjustment
= 1;
1212 /* Silently ignore minoredit if not allowed */
1213 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1214 $now = wfTimestampNow();
1216 $dbw =& wfGetDB( DB_MASTER
);
1218 # Add the page record; stake our claim on this title!
1219 $newid = $this->insertOn( $dbw );
1221 # Save the revision text...
1222 $revision = new Revision( array(
1224 'comment' => $summary,
1225 'minor_edit' => $isminor,
1228 $revisionId = $revision->insertOn( $dbw );
1230 $this->mTitle
->resetArticleID( $newid );
1232 # Update the page record with revision data
1233 $this->updateRevisionOn( $dbw, $revision, 0 );
1235 Article
::onArticleCreate( $this->mTitle
);
1237 require_once( 'RecentChange.php' );
1238 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1239 '', strlen( $text ), $revisionId );
1240 # Mark as patrolled if the user can and has the option set
1241 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1242 RecentChange
::markPatrolled( $rcid );
1247 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1249 if ( $this->mTitle
->userIsWatching() ) {
1254 # The talk page isn't in the regular link tables, so we need to update manually:
1255 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1256 $dbw->update( 'page',
1257 array( 'page_touched' => $dbw->timestamp($now) ),
1258 array( 'page_namespace' => $talkns,
1259 'page_title' => $ttl ),
1262 # standard deferred updates
1263 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1265 $oldid = 0; # new article
1266 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1268 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1270 $watchthis, NULL ) );
1271 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1273 $watchthis, NULL ) );
1274 wfProfileOut( $fname );
1278 * @return string Complete article text, or null if error
1280 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1281 $fname = 'Article::replaceSection';
1282 wfProfileIn( $fname );
1284 if ($section != '') {
1285 if( is_null( $edittime ) ) {
1286 $rev = Revision
::newFromTitle( $this->mTitle
);
1288 $dbw =& wfGetDB( DB_MASTER
);
1289 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1291 if( is_null( $rev ) ) {
1292 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1293 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1296 $oldtext = $rev->getText();
1298 if($section=='new') {
1299 if($summary) $subject="== {$summary} ==\n\n";
1300 $text=$oldtext."\n\n".$subject.$text;
1303 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1304 # comments to be stripped as well)
1305 $striparray=array();
1306 $parser=new Parser();
1307 $parser->mOutputType
=OT_WIKI
;
1308 $parser->mOptions
= new ParserOptions();
1309 $oldtext=$parser->strip($oldtext, $striparray, true);
1311 # now that we can be sure that no pseudo-sections are in the source,
1313 # Unfortunately we can't simply do a preg_replace because that might
1314 # replace the wrong section, so we have to use the section counter instead
1315 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1316 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1317 $secs[$section*2]=$text."\n\n"; // replace with edited
1319 # section 0 is top (intro) section
1322 # headline of old section - we need to go through this section
1323 # to determine if there are any subsections that now need to
1324 # be erased, as the mother section has been replaced with
1325 # the text of all subsections.
1326 $headline=$secs[$section*2-1];
1327 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1328 $hlevel=$matches[1];
1330 # determine headline level for wikimarkup headings
1331 if(strpos($hlevel,'=')!==false) {
1332 $hlevel=strlen($hlevel);
1335 $secs[$section*2-1]=''; // erase old headline
1338 while(!empty($secs[$count*2-1]) && !$break) {
1340 $subheadline=$secs[$count*2-1];
1342 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1343 $subhlevel=$matches[1];
1344 if(strpos($subhlevel,'=')!==false) {
1345 $subhlevel=strlen($subhlevel);
1347 if($subhlevel > $hlevel) {
1348 // erase old subsections
1349 $secs[$count*2-1]='';
1352 if($subhlevel <= $hlevel) {
1360 $text=join('',$secs);
1361 # reinsert the stuff that we stripped out earlier
1362 $text=$parser->unstrip($text,$striparray);
1363 $text=$parser->unstripNoWiki($text,$striparray);
1367 wfProfileOut( $fname );
1372 * Change an existing article. Puts the previous version back into the old table, updates RC
1373 * and all necessary caches, mostly via the deferred update array.
1375 * It is possible to call this function from a command-line script, but note that you should
1376 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1378 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1379 global $wgUser, $wgDBtransactions, $wgUseSquid;
1380 global $wgPostCommitUpdateList, $wgUseFileCache;
1382 $fname = 'Article::updateArticle';
1383 wfProfileIn( $fname );
1386 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1388 &$watchthis, &$sectionanchor ) ) ) {
1389 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1390 wfProfileOut( $fname );
1394 $isminor = $minor && $wgUser->isAllowed('minoredit');
1396 $text = $this->preSaveTransform( $text );
1397 $dbw =& wfGetDB( DB_MASTER
);
1398 $now = wfTimestampNow();
1400 # Update article, but only if changed.
1402 # It's important that we either rollback or complete, otherwise an attacker could
1403 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1404 # could conceivably have the same effect, especially if cur is locked for long periods.
1405 if( !$wgDBtransactions ) {
1406 $userAbort = ignore_user_abort( true );
1409 $oldtext = $this->getContent();
1410 $oldsize = strlen( $oldtext );
1411 $newsize = strlen( $text );
1415 if ( 0 != strcmp( $text, $oldtext ) ) {
1416 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1417 - (int)$this->isCountable( $oldtext );
1418 $this->mTotalAdjustment
= 0;
1419 $now = wfTimestampNow();
1421 $lastRevision = $dbw->selectField(
1422 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1424 $revision = new Revision( array(
1425 'page' => $this->getId(),
1426 'comment' => $summary,
1427 'minor_edit' => $isminor,
1431 $dbw->immediateCommit();
1433 $revisionId = $revision->insertOn( $dbw );
1436 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1439 /* Belated edit conflict! Run away!! */
1443 # Update recentchanges and purge cache and whatnot
1444 require_once( 'RecentChange.php' );
1445 $bot = (int)($wgUser->isBot() ||
$forceBot);
1446 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1447 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1450 # Mark as patrolled if the user can do so and has it set in their options
1451 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1452 RecentChange
::markPatrolled( $rcid );
1457 // Update caches outside the main transaction
1458 Article
::onArticleEdit( $this->mTitle
);
1461 // Keep the same revision ID, but do some updates on it
1462 $revisionId = $this->getRevIdFetched();
1465 if( !$wgDBtransactions ) {
1466 ignore_user_abort( $userAbort );
1471 if (!$this->mTitle
->userIsWatching()) {
1472 $dbw->immediateCommit();
1478 if ( $this->mTitle
->userIsWatching() ) {
1479 $dbw->immediateCommit();
1485 # standard deferred updates
1486 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1490 # Invalidate caches of all articles using this article as a template
1492 # Template namespace
1493 # Purge all articles linking here
1494 $titles = $this->mTitle
->getTemplateLinksTo();
1495 Title
::touchArray( $titles );
1496 if ( $wgUseSquid ) {
1497 foreach ( $titles as $title ) {
1498 $urls[] = $title->getInternalURL();
1503 if ( $wgUseSquid ) {
1504 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1505 $u = new SquidUpdate( $urls );
1506 array_push( $wgPostCommitUpdateList, $u );
1510 if ( $wgUseFileCache ) {
1511 $cm = new CacheManager($this->mTitle
);
1512 @unlink
($cm->fileCacheName());
1515 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1517 wfRunHooks( 'ArticleSaveComplete',
1518 array( &$this, &$wgUser, $text,
1520 $watchthis, $sectionanchor ) );
1521 wfProfileOut( $fname );
1526 * After we've either updated or inserted the article, update
1527 * the link tables and redirect to the new page.
1528 * @todo FIXME some function arguments never used
1530 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1533 $fname = 'Article::showArticle';
1534 wfProfileIn( $fname );
1536 # Output the redirect
1537 if( $this->isRedirect( $text ) )
1541 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1543 wfProfileOut( $fname );
1547 * Mark this particular edit as patrolled
1549 function markpatrolled() {
1550 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1551 $wgOut->setRobotpolicy( 'noindex,follow' );
1553 # Check RC patrol config. option
1554 if( !$wgUseRCPatrol ) {
1555 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1560 if( !$wgUser->isAllowed( 'patrol' ) ) {
1561 $wgOut->permissionRequired( 'patrol' );
1565 $rcid = $wgRequest->getVal( 'rcid' );
1566 if ( !is_null ( $rcid ) ) {
1567 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1568 require_once( 'RecentChange.php' );
1569 RecentChange
::markPatrolled( $rcid );
1570 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1571 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1572 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1574 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1575 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1578 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1583 * User-interface handler for the "watch" action
1588 global $wgUser, $wgOut;
1590 if ( $wgUser->isAnon() ) {
1591 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1594 if ( wfReadOnly() ) {
1595 $wgOut->readOnlyPage();
1599 if( $this->doWatch() ) {
1600 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1601 $wgOut->setRobotpolicy( 'noindex,follow' );
1603 $link = $this->mTitle
->getPrefixedText();
1604 $text = wfMsg( 'addedwatchtext', $link );
1605 $wgOut->addWikiText( $text );
1608 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1612 * Add this page to $wgUser's watchlist
1613 * @return bool true on successful watch operation
1615 function doWatch() {
1617 if( $wgUser->isAnon() ) {
1621 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1622 $wgUser->addWatch( $this->mTitle
);
1623 $wgUser->saveSettings();
1625 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1632 * User interface handler for the "unwatch" action.
1634 function unwatch() {
1636 global $wgUser, $wgOut;
1638 if ( $wgUser->isAnon() ) {
1639 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1642 if ( wfReadOnly() ) {
1643 $wgOut->readOnlyPage();
1647 if( $this->doUnwatch() ) {
1648 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1649 $wgOut->setRobotpolicy( 'noindex,follow' );
1651 $link = $this->mTitle
->getPrefixedText();
1652 $text = wfMsg( 'removedwatchtext', $link );
1653 $wgOut->addWikiText( $text );
1656 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1660 * Stop watching a page
1661 * @return bool true on successful unwatch
1663 function doUnwatch() {
1665 if( $wgUser->isAnon() ) {
1669 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1670 $wgUser->removeWatch( $this->mTitle
);
1671 $wgUser->saveSettings();
1673 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1680 * action=protect handler
1682 function protect() {
1683 require_once 'ProtectionForm.php';
1684 $form = new ProtectionForm( $this );
1689 * action=unprotect handler (alias)
1691 function unprotect() {
1696 * Update the article's restriction field, and leave a log entry.
1698 * @param array $limit set of restriction keys
1699 * @param string $reason
1700 * @return bool true on success
1702 function updateRestrictions( $limit = array(), $reason = '' ) {
1703 global $wgUser, $wgRestrictionTypes, $wgContLang;
1705 $id = $this->mTitle
->getArticleID();
1706 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1710 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1711 # we expect a single selection, but the schema allows otherwise.
1713 foreach( $wgRestrictionTypes as $action )
1714 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1716 $current = Article
::flattenRestrictions( $current );
1717 $updated = Article
::flattenRestrictions( $limit );
1719 $changed = ( $current != $updated );
1720 $protect = ( $updated != '' );
1722 # If nothing's changed, do nothing
1724 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1726 $dbw =& wfGetDB( DB_MASTER
);
1728 # Prepare a null revision to be added to the history
1729 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1731 $comment .= ": $reason";
1733 $comment .= " [$updated]";
1734 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1735 $nullRevId = $nullRevision->insertOn( $dbw );
1737 # Update page record
1738 $dbw->update( 'page',
1740 'page_touched' => $dbw->timestamp(),
1741 'page_restrictions' => $updated,
1742 'page_latest' => $nullRevId
1743 ), array( /* WHERE */
1745 ), 'Article::protect'
1747 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1749 # Update the protection log
1750 $log = new LogPage( 'protect' );
1752 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1754 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1758 } # End "changed" check
1764 * Take an array of page restrictions and flatten it to a string
1765 * suitable for insertion into the page_restrictions field.
1766 * @param array $limit
1770 function flattenRestrictions( $limit ) {
1771 if( !is_array( $limit ) ) {
1772 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1776 foreach( $limit as $action => $restrictions ) {
1777 if( $restrictions != '' ) {
1778 $bits[] = "$action=$restrictions";
1781 return implode( ':', $bits );
1785 * UI entry point for page deletion
1788 global $wgUser, $wgOut, $wgRequest;
1789 $fname = 'Article::delete';
1790 $confirm = $wgRequest->wasPosted() &&
1791 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1792 $reason = $wgRequest->getText( 'wpReason' );
1794 # This code desperately needs to be totally rewritten
1797 if( $wgUser->isAllowed( 'delete' ) ) {
1798 if( $wgUser->isBlocked() ) {
1799 $wgOut->blockedPage();
1803 $wgOut->permissionRequired( 'delete' );
1807 if( wfReadOnly() ) {
1808 $wgOut->readOnlyPage();
1812 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1814 # Better double-check that it hasn't been deleted yet!
1815 $dbw =& wfGetDB( DB_MASTER
);
1816 $conds = $this->mTitle
->pageCond();
1817 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1818 if ( $latest === false ) {
1819 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1824 $this->doDelete( $reason );
1828 # determine whether this page has earlier revisions
1829 # and insert a warning if it does
1831 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1833 if( count( $authors ) > 1 && !$confirm ) {
1834 $skin=$wgUser->getSkin();
1835 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1838 # If a single user is responsible for all revisions, find out who they are
1839 if ( count( $authors ) == $maxRevisions ) {
1840 // Query bailed out, too many revisions to find out if they're all the same
1841 $authorOfAll = false;
1843 $authorOfAll = reset( $authors );
1844 foreach ( $authors as $author ) {
1845 if ( $authorOfAll != $author ) {
1846 $authorOfAll = false;
1851 # Fetch article text
1852 $rev = Revision
::newFromTitle( $this->mTitle
);
1854 if( !is_null( $rev ) ) {
1855 # if this is a mini-text, we can paste part of it into the deletion reason
1856 $text = $rev->getText();
1858 #if this is empty, an earlier revision may contain "useful" text
1861 $prev = $rev->getPrevious();
1863 $text = $prev->getText();
1868 $length = strlen( $text );
1870 # this should not happen, since it is not possible to store an empty, new
1871 # page. Let's insert a standard text in case it does, though
1872 if( $length == 0 && $reason === '' ) {
1873 $reason = wfMsgForContent( 'exblank' );
1876 if( $length < 500 && $reason === '' ) {
1877 # comment field=255, let's grep the first 150 to have some user
1880 $text = $wgContLang->truncate( $text, 150, '...' );
1882 # let's strip out newlines
1883 $text = preg_replace( "/[\n\r]/", '', $text );
1886 if( $authorOfAll === false ) {
1887 $reason = wfMsgForContent( 'excontent', $text );
1889 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1892 $reason = wfMsgForContent( 'exbeforeblank', $text );
1897 return $this->confirmDelete( '', $reason );
1901 * Get the last N authors
1902 * @param int $num Number of revisions to get
1903 * @param string $revLatest The latest rev_id, selected from the master (optional)
1904 * @return array Array of authors, duplicates not removed
1906 function getLastNAuthors( $num, $revLatest = 0 ) {
1907 $fname = 'Article::getLastNAuthors';
1908 wfProfileIn( $fname );
1910 // First try the slave
1911 // If that doesn't have the latest revision, try the master
1913 $db =& wfGetDB( DB_SLAVE
);
1915 $res = $db->select( array( 'page', 'revision' ),
1916 array( 'rev_id', 'rev_user_text' ),
1918 'page_namespace' => $this->mTitle
->getNamespace(),
1919 'page_title' => $this->mTitle
->getDBkey(),
1920 'rev_page = page_id'
1921 ), $fname, $this->getSelectOptions( array(
1922 'ORDER BY' => 'rev_timestamp DESC',
1927 wfProfileOut( $fname );
1930 $row = $db->fetchObject( $res );
1931 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1932 $db =& wfGetDB( DB_MASTER
);
1937 } while ( $continue );
1939 $authors = array( $row->rev_user_text
);
1940 while ( $row = $db->fetchObject( $res ) ) {
1941 $authors[] = $row->rev_user_text
;
1943 wfProfileOut( $fname );
1948 * Output deletion confirmation dialog
1950 function confirmDelete( $par, $reason ) {
1951 global $wgOut, $wgUser;
1953 wfDebug( "Article::confirmDelete\n" );
1955 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1956 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1957 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1958 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1960 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1962 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1963 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1964 $token = htmlspecialchars( $wgUser->editToken() );
1967 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1971 <label for='wpReason'>{$delcom}:</label>
1974 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1980 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1984 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1987 $wgOut->returnToMain( false );
1992 * Perform a deletion and output success or failure messages
1994 function doDelete( $reason ) {
1995 global $wgOut, $wgUser;
1996 $fname = 'Article::doDelete';
1997 wfDebug( $fname."\n" );
1999 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2000 if ( $this->doDeleteArticle( $reason ) ) {
2001 $deleted = $this->mTitle
->getPrefixedText();
2003 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2004 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2006 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2007 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2009 $wgOut->addWikiText( $text );
2010 $wgOut->returnToMain( false );
2011 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2013 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2019 * Back-end article deletion
2020 * Deletes the article with database consistency, writes logs, purges caches
2023 function doDeleteArticle( $reason ) {
2024 global $wgUseSquid, $wgDeferredUpdateList;
2025 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2027 $fname = 'Article::doDeleteArticle';
2028 wfDebug( $fname."\n" );
2030 $dbw =& wfGetDB( DB_MASTER
);
2031 $ns = $this->mTitle
->getNamespace();
2032 $t = $this->mTitle
->getDBkey();
2033 $id = $this->mTitle
->getArticleID();
2035 if ( $t == '' ||
$id == 0 ) {
2039 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2040 array_push( $wgDeferredUpdateList, $u );
2042 $linksTo = $this->mTitle
->getLinksTo();
2045 if ( $wgUseSquid ) {
2047 $this->mTitle
->getInternalURL(),
2048 $this->mTitle
->getInternalURL( 'history' )
2051 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2052 array_push( $wgPostCommitUpdateList, $u );
2056 # Client and file cache invalidation
2057 Title
::touchArray( $linksTo );
2060 // For now, shunt the revision data into the archive table.
2061 // Text is *not* removed from the text table; bulk storage
2062 // is left intact to avoid breaking block-compression or
2063 // immutable storage schemes.
2065 // For backwards compatibility, note that some older archive
2066 // table entries will have ar_text and ar_flags fields still.
2068 // In the future, we may keep revisions and mark them with
2069 // the rev_deleted field, which is reserved for this purpose.
2070 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2072 'ar_namespace' => 'page_namespace',
2073 'ar_title' => 'page_title',
2074 'ar_comment' => 'rev_comment',
2075 'ar_user' => 'rev_user',
2076 'ar_user_text' => 'rev_user_text',
2077 'ar_timestamp' => 'rev_timestamp',
2078 'ar_minor_edit' => 'rev_minor_edit',
2079 'ar_rev_id' => 'rev_id',
2080 'ar_text_id' => 'rev_text_id',
2083 'page_id = rev_page'
2087 # Now that it's safely backed up, delete it
2088 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2089 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2091 if ($wgUseTrackbacks)
2092 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2094 # Clean up recentchanges entries...
2095 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2097 # Finally, clean up the link tables
2098 $t = $this->mTitle
->getPrefixedDBkey();
2100 Article
::onArticleDelete( $this->mTitle
);
2102 # Delete outgoing links
2103 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2104 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2105 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2106 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2107 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2108 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2111 $log = new LogPage( 'delete' );
2112 $log->addEntry( 'delete', $this->mTitle
, $reason );
2114 # Clear the cached article id so the interface doesn't act like we exist
2115 $this->mTitle
->resetArticleID( 0 );
2116 $this->mTitle
->mArticleID
= 0;
2121 * Revert a modification
2123 function rollback() {
2124 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2125 $fname = 'Article::rollback';
2127 if( $wgUser->isAllowed( 'rollback' ) ) {
2128 if( $wgUser->isBlocked() ) {
2129 $wgOut->blockedPage();
2133 $wgOut->permissionRequired( 'rollback' );
2137 if ( wfReadOnly() ) {
2138 $wgOut->readOnlyPage( $this->getContent() );
2141 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2142 array( $this->mTitle
->getPrefixedText(),
2143 $wgRequest->getVal( 'from' ) ) ) ) {
2144 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2145 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2148 $dbw =& wfGetDB( DB_MASTER
);
2150 # Enhanced rollback, marks edits rc_bot=1
2151 $bot = $wgRequest->getBool( 'bot' );
2153 # Replace all this user's current edits with the next one down
2154 $tt = $this->mTitle
->getDBKey();
2155 $n = $this->mTitle
->getNamespace();
2157 # Get the last editor, lock table exclusively
2159 $current = Revision
::newFromTitle( $this->mTitle
);
2160 if( is_null( $current ) ) {
2161 # Something wrong... no page?
2163 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2167 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2168 if( $from != $current->getUserText() ) {
2169 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2170 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2171 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2172 htmlspecialchars( $from ),
2173 htmlspecialchars( $current->getUserText() ) ) );
2174 if( $current->getComment() != '') {
2176 wfMsg( 'editcomment',
2177 htmlspecialchars( $current->getComment() ) ) );
2182 # Get the last edit not by this guy
2183 $user = intval( $current->getUser() );
2184 $user_text = $dbw->addQuotes( $current->getUserText() );
2185 $s = $dbw->selectRow( 'revision',
2186 array( 'rev_id', 'rev_timestamp' ),
2188 'rev_page' => $current->getPage(),
2189 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2192 'USE INDEX' => 'page_timestamp',
2193 'ORDER BY' => 'rev_timestamp DESC' )
2195 if( $s === false ) {
2198 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2199 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2205 # Mark all reverted edits as bot
2208 if ( $wgUseRCPatrol ) {
2209 # Mark all reverted edits as patrolled
2210 $set['rc_patrolled'] = 1;
2214 $dbw->update( 'recentchanges', $set,
2216 'rc_cur_id' => $current->getPage(),
2217 'rc_user_text' => $current->getUserText(),
2218 "rc_timestamp > '{$s->rev_timestamp}'",
2223 # Get the edit summary
2224 $target = Revision
::newFromId( $s->rev_id
);
2225 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2226 $newComment = $wgRequest->getText( 'summary', $newComment );
2229 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2230 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2231 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2233 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2234 Article
::onArticleEdit( $this->mTitle
);
2237 $wgOut->returnToMain( false );
2242 * Do standard deferred updates after page view
2245 function viewUpdates() {
2246 global $wgDeferredUpdateList;
2248 if ( 0 != $this->getID() ) {
2249 global $wgDisableCounters;
2250 if( !$wgDisableCounters ) {
2251 Article
::incViewCount( $this->getID() );
2252 $u = new SiteStatsUpdate( 1, 0, 0 );
2253 array_push( $wgDeferredUpdateList, $u );
2257 # Update newtalk / watchlist notification status
2259 $wgUser->clearNotification( $this->mTitle
);
2263 * Do standard deferred updates after page edit.
2264 * Every 1000th edit, prune the recent changes table.
2266 * @param string $text
2268 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2269 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2271 $fname = 'Article::editUpdates';
2272 wfProfileIn( $fname );
2275 $options = new ParserOptions
;
2276 $options->setTidy(true);
2277 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2279 # Save it to the parser cache
2280 $parserCache =& ParserCache
::singleton();
2281 $parserCache->save( $poutput, $this, $wgUser );
2283 # Update the links tables
2284 $u = new LinksUpdate( $this->mTitle
, $poutput );
2287 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2289 if ( 0 == mt_rand( 0, 999 ) ) {
2290 # Periodically flush old entries from the recentchanges table.
2293 $dbw =& wfGetDB( DB_MASTER
);
2294 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2295 $recentchanges = $dbw->tableName( 'recentchanges' );
2296 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2297 $dbw->query( $sql );
2301 $id = $this->getID();
2302 $title = $this->mTitle
->getPrefixedDBkey();
2303 $shortTitle = $this->mTitle
->getDBkey();
2306 wfProfileOut( $fname );
2310 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2311 array_push( $wgDeferredUpdateList, $u );
2312 $u = new SearchUpdate( $id, $title, $text );
2313 array_push( $wgDeferredUpdateList, $u );
2315 # If this is another user's talk page, update newtalk
2317 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2318 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2319 $other = User
::newFromName( $shortTitle );
2320 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2321 // An anonymous user
2322 $other = new User();
2323 $other->setName( $shortTitle );
2326 $other->setNewtalk( true );
2331 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2332 $wgMessageCache->replace( $shortTitle, $text );
2335 wfProfileOut( $fname );
2339 * Generate the navigation links when browsing through an article revisions
2340 * It shows the information as:
2341 * Revision as of \<date\>; view current revision
2342 * \<- Previous version | Next Version -\>
2345 * @param string $oldid Revision ID of this article revision
2347 function setOldSubtitle( $oldid=0 ) {
2348 global $wgLang, $wgOut, $wgUser;
2350 $current = ( $oldid == $this->mLatest
);
2351 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2352 $sk = $wgUser->getSkin();
2354 ?
wfMsg( 'currentrevisionlink' )
2355 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2356 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2358 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2359 : wfMsg( 'previousrevision' );
2360 $nextlink = $current
2361 ?
wfMsg( 'nextrevision' )
2362 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2363 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2364 $wgOut->setSubtitle( $r );
2368 * This function is called right before saving the wikitext,
2369 * so we can do things like signatures and links-in-context.
2371 * @param string $text
2373 function preSaveTransform( $text ) {
2374 global $wgParser, $wgUser;
2375 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2378 /* Caching functions */
2381 * checkLastModified returns true if it has taken care of all
2382 * output to the client that is necessary for this request.
2383 * (that is, it has sent a cached version of the page)
2385 function tryFileCache() {
2386 static $called = false;
2388 wfDebug( " tryFileCache() -- called twice!?\n" );
2392 if($this->isFileCacheable()) {
2393 $touched = $this->mTouched
;
2394 $cache = new CacheManager( $this->mTitle
);
2395 if($cache->isFileCacheGood( $touched )) {
2396 wfDebug( " tryFileCache() - about to load\n" );
2397 $cache->loadFromFileCache();
2400 wfDebug( " tryFileCache() - starting buffer\n" );
2401 ob_start( array(&$cache, 'saveToFileCache' ) );
2404 wfDebug( " tryFileCache() - not cacheable\n" );
2409 * Check if the page can be cached
2412 function isFileCacheable() {
2413 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2414 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2416 return $wgUseFileCache
2417 and (!$wgShowIPinHeader)
2418 and ($this->getID() != 0)
2419 and ($wgUser->isAnon())
2420 and (!$wgUser->getNewtalk())
2421 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2422 and (empty( $action ) ||
$action == 'view')
2423 and (!isset($oldid))
2425 and (!isset($redirect))
2426 and (!isset($printable))
2427 and (!$this->mRedirectedFrom
);
2431 * Loads page_touched and returns a value indicating if it should be used
2434 function checkTouched() {
2435 $fname = 'Article::checkTouched';
2436 if( !$this->mDataLoaded
) {
2437 $this->loadPageData();
2439 return !$this->mIsRedirect
;
2443 * Get the page_touched field
2445 function getTouched() {
2446 # Ensure that page data has been loaded
2447 if( !$this->mDataLoaded
) {
2448 $this->loadPageData();
2450 return $this->mTouched
;
2454 * Get the page_latest field
2456 function getLatest() {
2457 if ( !$this->mDataLoaded
) {
2458 $this->loadPageData();
2460 return $this->mLatest
;
2464 * Edit an article without doing all that other stuff
2465 * The article must already exist; link tables etc
2466 * are not updated, caches are not flushed.
2468 * @param string $text text submitted
2469 * @param string $comment comment submitted
2470 * @param bool $minor whereas it's a minor modification
2472 function quickEdit( $text, $comment = '', $minor = 0 ) {
2473 $fname = 'Article::quickEdit';
2474 wfProfileIn( $fname );
2476 $dbw =& wfGetDB( DB_MASTER
);
2478 $revision = new Revision( array(
2479 'page' => $this->getId(),
2481 'comment' => $comment,
2482 'minor_edit' => $minor ?
1 : 0,
2484 # fixme : $revisionId never used
2485 $revisionId = $revision->insertOn( $dbw );
2486 $this->updateRevisionOn( $dbw, $revision );
2489 wfProfileOut( $fname );
2493 * Used to increment the view counter
2496 * @param integer $id article id
2498 function incViewCount( $id ) {
2499 $id = intval( $id );
2500 global $wgHitcounterUpdateFreq, $wgDBtype;
2502 $dbw =& wfGetDB( DB_MASTER
);
2503 $pageTable = $dbw->tableName( 'page' );
2504 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2505 $acchitsTable = $dbw->tableName( 'acchits' );
2507 if( $wgHitcounterUpdateFreq <= 1 ){ //
2508 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2512 # Not important enough to warrant an error page in case of failure
2513 $oldignore = $dbw->ignoreErrors( true );
2515 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2517 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2518 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2519 # Most of the time (or on SQL errors), skip row count check
2520 $dbw->ignoreErrors( $oldignore );
2524 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2525 $row = $dbw->fetchObject( $res );
2526 $rown = intval( $row->n
);
2527 if( $rown >= $wgHitcounterUpdateFreq ){
2528 wfProfileIn( 'Article::incViewCount-collect' );
2529 $old_user_abort = ignore_user_abort( true );
2531 if ($wgDBtype == 'mysql')
2532 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2533 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2534 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2535 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2537 $dbw->query("DELETE FROM $hitcounterTable");
2538 if ($wgDBtype == 'mysql')
2539 $dbw->query('UNLOCK TABLES');
2540 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2541 'WHERE page_id = hc_id');
2542 $dbw->query("DROP TABLE $acchitsTable");
2544 ignore_user_abort( $old_user_abort );
2545 wfProfileOut( 'Article::incViewCount-collect' );
2547 $dbw->ignoreErrors( $oldignore );
2551 * The onArticle*() functions are supposed to be a kind of hooks
2552 * which should be called whenever any of the specified actions
2555 * This is a good place to put code to clear caches, for instance.
2557 * This is called on page move and undelete, as well as edit
2559 * @param $title_obj a title object
2562 function onArticleCreate($title_obj) {
2563 global $wgUseSquid, $wgPostCommitUpdateList;
2565 $title_obj->touchLinks();
2566 $titles = $title_obj->getLinksTo();
2569 if ( $wgUseSquid ) {
2570 $urls = $title_obj->getSquidURLs();
2571 foreach ( $titles as $linkTitle ) {
2572 $urls[] = $linkTitle->getInternalURL();
2574 $u = new SquidUpdate( $urls );
2575 array_push( $wgPostCommitUpdateList, $u );
2579 function onArticleDelete( $title ) {
2580 global $wgMessageCache;
2582 $title->touchLinks();
2584 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2585 $wgMessageCache->replace( $title->getDBkey(), false );
2590 * Purge caches on page update etc
2592 function onArticleEdit( $title ) {
2593 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2597 // Template namespace? Purge all articles linking here.
2598 // FIXME: When a templatelinks table arrives, use it for all includes.
2599 if ( $title->getNamespace() == NS_TEMPLATE
) {
2600 $titles = $title->getLinksTo();
2601 Title
::touchArray( $titles );
2602 if ( $wgUseSquid ) {
2603 foreach ( $titles as $link ) {
2604 $urls[] = $link->getInternalURL();
2610 if ( $wgUseSquid ) {
2611 $urls = array_merge( $urls, $title->getSquidURLs() );
2612 $u = new SquidUpdate( $urls );
2613 array_push( $wgPostCommitUpdateList, $u );
2617 if ( $wgUseFileCache ) {
2618 $cm = new CacheManager( $title );
2619 @unlink
( $cm->fileCacheName() );
2626 * Info about this page
2627 * Called for ?action=info when $wgAllowPageInfo is on.
2632 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2633 $fname = 'Article::info';
2635 if ( !$wgAllowPageInfo ) {
2636 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2640 $page = $this->mTitle
->getSubjectPage();
2642 $wgOut->setPagetitle( $page->getPrefixedText() );
2643 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2645 # first, see if the page exists at all.
2646 $exists = $page->getArticleId() != 0;
2648 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2649 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2651 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2654 $dbr =& wfGetDB( DB_SLAVE
);
2656 'wl_title' => $page->getDBkey(),
2657 'wl_namespace' => $page->getNamespace() );
2658 $numwatchers = $dbr->selectField(
2663 $this->getSelectOptions() );
2665 $pageInfo = $this->pageCountInfo( $page );
2666 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2668 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2669 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2671 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2673 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2675 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2677 $wgOut->addHTML( '</ul>' );
2683 * Return the total number of edits and number of unique editors
2684 * on a given page. If page does not exist, returns false.
2686 * @param Title $title
2690 function pageCountInfo( $title ) {
2691 $id = $title->getArticleId();
2696 $dbr =& wfGetDB( DB_SLAVE
);
2698 $rev_clause = array( 'rev_page' => $id );
2699 $fname = 'Article::pageCountInfo';
2701 $edits = $dbr->selectField(
2706 $this->getSelectOptions() );
2708 $authors = $dbr->selectField(
2710 'COUNT(DISTINCT rev_user_text)',
2713 $this->getSelectOptions() );
2715 return array( 'edits' => $edits, 'authors' => $authors );
2719 * Return a list of templates used by this article.
2720 * Uses the templatelinks table
2722 * @return array Array of Title objects
2724 function getUsedTemplates() {
2726 $id = $this->mTitle
->getArticleID();
2731 $dbr =& wfGetDB( DB_SLAVE
);
2732 $res = $dbr->select( array( 'templatelinks' ),
2733 array( 'tl_namespace', 'tl_title' ),
2734 array( 'tl_from' => $id ),
2735 'Article:getUsedTemplates' );
2736 if ( false !== $res ) {
2737 if ( $dbr->numRows( $res ) ) {
2738 while ( $row = $dbr->fetchObject( $res ) ) {
2739 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2743 $dbr->freeResult( $res );