57a1fe0bdeaa9a6cdbdafa338942d3ac71604400
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 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
42 * Constructor and clear the article
43 * @param mixed &$title
45 function Article( &$title ) {
46 $this->mTitle
=& $title;
51 * get the title object of the article
63 $this->mDataLoaded
= false;
64 $this->mContentLoaded
= false;
66 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
67 $this->mRedirectedFrom
= $this->mUserText
=
68 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
69 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
70 $this->mTouched
= '19700101000000';
71 $this->mForUpdate
= false;
72 $this->mIsRedirect
= false;
73 $this->mRevIdFetched
= 0;
77 * Note that getContent/loadContent may follow redirects if
78 * not told otherwise, and so may cause a change to mTitle.
81 * @return Return the text of this revision
83 function getContent( $noredir ) {
84 global $wgRequest, $wgUser;
86 # Get variables from query string :P
87 $action = $wgRequest->getText( 'action', 'view' );
88 $section = $wgRequest->getText( 'section' );
90 $fname = 'Article::getContent';
91 wfProfileIn( $fname );
93 if ( 0 == $this->getID() ) {
94 if ( 'edit' == $action ) {
95 wfProfileOut( $fname );
96 return ''; # was "newarticletext", now moved above the box)
98 wfProfileOut( $fname );
99 return wfMsg( 'noarticletext' );
101 $this->loadContent( $noredir );
102 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
103 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
104 $wgUser->isIP($this->mTitle
->getText()) &&
107 wfProfileOut( $fname );
108 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
110 if($action=='edit') {
112 if($section=='new') {
113 wfProfileOut( $fname );
117 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
118 # comments to be stripped as well)
119 $rv=$this->getSection($this->mContent
,$section);
120 wfProfileOut( $fname );
124 wfProfileOut( $fname );
125 return $this->mContent
;
131 * This function returns the text of a section, specified by a number ($section).
132 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
133 * the first section before any such heading (section 0).
135 * If a section contains subsections, these are also returned.
137 * @param string $text text to look in
138 * @param integer $section section number
139 * @return string text of the requested section
141 function getSection($text,$section) {
143 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
144 # comments to be stripped as well)
146 $parser=new Parser();
147 $parser->mOutputType
=OT_WIKI
;
148 $striptext=$parser->strip($text, $striparray, true);
150 # now that we can be sure that no pseudo-sections are in the source,
151 # split it up by section
154 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
156 PREG_SPLIT_DELIM_CAPTURE
);
160 $headline=$secs[$section*2-1];
161 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
164 # translate wiki heading into level
165 if(strpos($hlevel,'=')!==false) {
166 $hlevel=strlen($hlevel);
169 $rv=$headline. $secs[$section*2];
173 while(!empty($secs[$count*2-1]) && !$break) {
175 $subheadline=$secs[$count*2-1];
176 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
177 $subhlevel=$matches[1];
178 if(strpos($subhlevel,'=')!==false) {
179 $subhlevel=strlen($subhlevel);
181 if($subhlevel > $hlevel) {
182 $rv.=$subheadline.$secs[$count*2];
184 if($subhlevel <= $hlevel) {
191 # reinsert stripped tags
192 $rv=$parser->unstrip($rv,$striparray);
193 $rv=$parser->unstripNoWiki($rv,$striparray);
200 * Return an array of the columns of the "cur"-table
202 function getContentFields() {
203 return $wgArticleContentFields = array(
204 'old_text','old_flags',
205 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
206 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
210 * Return the oldid of the article that is to be shown.
211 * For requests with a "direction", this is not the oldid of the
214 function getOldID() {
215 global $wgRequest, $wgOut;
218 if ( isset( $lastid ) ) {
222 $oldid = $wgRequest->getVal( 'oldid' );
223 if ( isset( $oldid ) ) {
224 $oldid = IntVal( $oldid );
225 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
226 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
230 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
232 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
233 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
242 return @$oldid; # "@" to be able to return "unset" without PHP complaining
247 * Load the revision (including cur_text) into this object
249 function loadContent( $noredir = false ) {
250 global $wgOut, $wgRequest;
252 if ( $this->mContentLoaded
) return;
255 $oldid = $this->getOldID();
256 $redirect = $wgRequest->getVal( 'redirect' );
258 $fname = 'Article::loadContent';
260 # Pre-fill content with error message so that if something
261 # fails we'll have something telling us what we intended.
263 $t = $this->mTitle
->getPrefixedText();
265 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no')
266 ||
$wgRequest->getCheck( 'rdfrom' );
267 $this->mOldId
= $oldid;
268 $this->fetchContent( $oldid, $noredir, true );
273 * Fetch a page record with the given conditions
274 * @param Database $dbr
275 * @param array $conditions
278 function pageData( &$dbr, $conditions ) {
279 return $dbr->selectRow( 'page',
293 'Article::pageData' );
296 function pageDataFromTitle( &$dbr, $title ) {
297 return $this->pageData( $dbr, array(
298 'page_namespace' => $title->getNamespace(),
299 'page_title' => $title->getDBkey() ) );
302 function pageDataFromId( &$dbr, $id ) {
303 return $this->pageData( $dbr, array(
304 'page_id' => IntVal( $id ) ) );
308 * Set the general counter, title etc data loaded from
311 * @param object $data
314 function loadPageData( $data ) {
315 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
316 $this->mTitle
->mRestrictionsLoaded
= true;
318 $this->mCounter
= $data->page_counter
;
319 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
320 $this->mIsRedirect
= $data->page_is_redirect
;
321 $this->mLatest
= $data->page_latest
;
323 $this->mDataLoaded
= true;
327 * Get text of an article from database
328 * @param int $oldid 0 for whatever the latest revision is
329 * @param bool $noredir Set to false to follow redirects
330 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
333 function fetchContent( $oldid = 0, $noredir = true, $globalTitle = false ) {
334 if ( $this->mContentLoaded
) {
335 return $this->mContent
;
337 $dbr =& $this->getDB();
338 $fname = 'Article::fetchContent';
340 # Pre-fill content with error message so that if something
341 # fails we'll have something telling us what we intended.
342 $t = $this->mTitle
->getPrefixedText();
344 $t .= ',oldid='.$oldid;
346 if( isset( $redirect ) ) {
347 $redirect = ($redirect == 'no') ?
'no' : 'yes';
348 $t .= ',redirect='.$redirect;
350 $this->mContent
= wfMsg( 'missingarticle', $t );
353 $revision = Revision
::newFromId( $oldid );
354 if( is_null( $revision ) ) {
355 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
358 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
360 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
363 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
364 $this->loadPageData( $data );
366 if( !$this->mDataLoaded
) {
367 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
369 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
372 $this->loadPageData( $data );
374 $revision = Revision
::newFromId( $this->mLatest
);
375 if( is_null( $revision ) ) {
376 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
381 # If we got a redirect, follow it (unless we've been told
382 # not to by either the function parameter or the query
383 if ( !$oldid && !$noredir ) {
384 $rt = Title
::newFromRedirect( $revision->getText() );
385 # process if title object is valid and not special:userlogout
386 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
387 # Gotta hand redirects to special pages differently:
388 # Fill the HTTP response "Location" header and ignore
389 # the rest of the page we're on.
390 global $wgDisableHardRedirects;
391 if( $globalTitle && !$wgDisableHardRedirects ) {
393 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
394 $source = $this->mTitle
->getFullURL( 'redirect=no' );
395 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
398 if ( $rt->getNamespace() == NS_SPECIAL
) {
399 $wgOut->redirect( $rt->getFullURL() );
403 $redirData = $this->pageDataFromTitle( $dbr, $rt );
405 $redirRev = Revision
::newFromId( $redirData->page_latest
);
406 if( !is_null( $redirRev ) ) {
407 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
410 $this->loadPageData( $data );
411 $revision = $redirRev;
417 # if the title's different from expected, update...
420 if( !$this->mTitle
->equals( $wgTitle ) ) {
421 $wgTitle = $this->mTitle
;
425 # Back to the business at hand...
426 $this->mContent
= $revision->getText();
428 $this->mUser
= $revision->getUser();
429 $this->mUserText
= $revision->getUserText();
430 $this->mComment
= $revision->getComment();
431 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
433 $this->mRevIdFetched
= $revision->getID();
434 $this->mContentLoaded
= true;
435 $this->mRevision
=& $revision;
437 return $this->mContent
;
441 * Gets the article text without using so many damn globals
442 * Returns false on error
444 * @param integer $oldid
446 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
447 return $this->fetchContent( $oldid, $noredir, false );
451 * Read/write accessor to select FOR UPDATE
453 function forUpdate( $x = NULL ) {
454 return wfSetVar( $this->mForUpdate
, $x );
458 * Get the database which should be used for reads
461 #if ( $this->mForUpdate ) {
462 return wfGetDB( DB_MASTER
);
464 # return wfGetDB( DB_SLAVE );
469 * Get options for all SELECT statements
470 * Can pass an option array, to which the class-wide options will be appended
472 function getSelectOptions( $options = '' ) {
473 if ( $this->mForUpdate
) {
474 if ( is_array( $options ) ) {
475 $options[] = 'FOR UPDATE';
477 $options = 'FOR UPDATE';
484 * Return the Article ID
487 if( $this->mTitle
) {
488 return $this->mTitle
->getArticleID();
495 * Returns true if this article exists in the database.
499 return $this->getId() != 0;
503 * Get the view count for this article
505 function getCount() {
506 if ( -1 == $this->mCounter
) {
507 $id = $this->getID();
508 $dbr =& $this->getDB();
509 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
510 'Article::getCount', $this->getSelectOptions() );
512 return $this->mCounter
;
516 * Would the given text make this article a "good" article (i.e.,
517 * suitable for including in the article count)?
518 * @param string $text Text to analyze
519 * @return integer 1 if it can be counted else 0
521 function isCountable( $text ) {
522 global $wgUseCommaCount;
524 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
525 if ( $this->isRedirect( $text ) ) { return 0; }
526 $token = ($wgUseCommaCount ?
',' : '[[' );
527 if ( false === strstr( $text, $token ) ) { return 0; }
532 * Tests if the article text represents a redirect
534 function isRedirect( $text = false ) {
535 if ( $text === false ) {
536 $this->loadContent();
537 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
539 $titleObj = Title
::newFromRedirect( $text );
541 return $titleObj !== NULL;
545 * Returns true if the currently-referenced revision is the current edit
546 * to this page (and it exists).
549 function isCurrent() {
550 return $this->exists() &&
551 isset( $this->mRevision
) &&
552 $this->mRevision
->isCurrent();
556 * Loads everything except the text
557 * This isn't necessary for all uses, so it's only done if needed.
560 function loadLastEdit() {
563 if ( -1 != $this->mUser
)
566 # New or non-existent articles have no user information
567 $id = $this->getID();
568 if ( 0 == $id ) return;
570 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
571 if( !is_null( $this->mLastRevision
) ) {
572 $this->mUser
= $this->mLastRevision
->getUser();
573 $this->mUserText
= $this->mLastRevision
->getUserText();
574 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
575 $this->mComment
= $this->mLastRevision
->getComment();
576 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
580 function getTimestamp() {
581 $this->loadLastEdit();
582 return $this->mTimestamp
;
586 $this->loadLastEdit();
590 function getUserText() {
591 $this->loadLastEdit();
592 return $this->mUserText
;
595 function getComment() {
596 $this->loadLastEdit();
597 return $this->mComment
;
600 function getMinorEdit() {
601 $this->loadLastEdit();
602 return $this->mMinorEdit
;
605 function getRevIdFetched() {
606 $this->loadLastEdit();
607 return $this->mRevIdFetched
;
610 function getContributors($limit = 0, $offset = 0) {
611 $fname = 'Article::getContributors';
613 # XXX: this is expensive; cache this info somewhere.
615 $title = $this->mTitle
;
617 $dbr =& $this->getDB();
618 $revTable = $dbr->tableName( 'revision' );
619 $userTable = $dbr->tableName( 'user' );
620 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
621 $ns = $title->getNamespace();
622 $user = $this->getUser();
623 $pageId = $this->getId();
625 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
626 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
627 WHERE rev_page = $pageId
628 AND rev_user != $user
629 GROUP BY rev_user, rev_user_text, user_real_name
630 ORDER BY timestamp DESC";
632 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
633 $sql .= ' '. $this->getSelectOptions();
635 $res = $dbr->query($sql, $fname);
637 while ( $line = $dbr->fetchObject( $res ) ) {
638 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
641 $dbr->freeResult($res);
646 * This is the default action of the script: just view the page of
650 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
651 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
652 global $wgEnotif, $wgParser, $wgParserCache;
653 $sk = $wgUser->getSkin();
655 $fname = 'Article::view';
656 wfProfileIn( $fname );
657 # Get variables from query string
658 $oldid = $this->getOldID();
659 $diff = $wgRequest->getVal( 'diff' );
660 $rcid = $wgRequest->getVal( 'rcid' );
661 $rdfrom = $wgRequest->getVal( 'rdfrom' );
663 $wgOut->setArticleFlag( true );
664 $wgOut->setRobotpolicy( 'index,follow' );
665 # If we got diff and oldid in the query, we want to see a
666 # diff page instead of the article.
668 if ( !is_null( $diff ) ) {
669 require_once( 'DifferenceEngine.php' );
670 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
672 $de = new DifferenceEngine( $oldid, $diff, $rcid );
673 // DifferenceEngine directly fetched the revision:
674 $this->mRevIdFetched
= $de->mNewid
;
678 # Run view updates for current revision only
679 $this->viewUpdates();
681 wfProfileOut( $fname );
685 if ( empty( $oldid ) && $this->checkTouched() ) {
686 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
688 if( $wgOut->checkLastModified( $this->mTouched
) ){
689 wfProfileOut( $fname );
691 } else if ( $this->tryFileCache() ) {
692 # tell wgOut that output is taken care of
694 $this->viewUpdates();
695 wfProfileOut( $fname );
699 # Should the parser cache be used?
700 $pcache = $wgEnableParserCache &&
701 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
704 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
708 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
712 if ( !$outputDone ) {
713 $text = $this->getContent( false ); # May change mTitle by following a redirect
715 # Another whitelist check in case oldid or redirects are altering the title
716 if ( !$this->mTitle
->userCanRead() ) {
717 $wgOut->loginToUse();
722 # We're looking at an old revision
724 if ( !empty( $oldid ) ) {
725 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
726 $wgOut->setRobotpolicy( 'noindex,follow' );
728 if ( '' != $this->mRedirectedFrom
) {
729 $sk = $wgUser->getSkin();
730 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
732 $s = wfMsg( 'redirectedfrom', $redir );
733 $wgOut->setSubtitle( $s );
735 # Can't cache redirects
737 } elseif ( !empty( $rdfrom ) ) {
738 global $wgRedirectSources;
739 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
740 $sk = $wgUser->getSkin();
741 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
742 $s = wfMsg( 'redirectedfrom', $redir );
743 $wgOut->setSubtitle( $s );
747 # wrap user css and user js in pre and don't parse
748 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
750 $this->mTitle
->getNamespace() == NS_USER
&&
751 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
753 $wgOut->addWikiText( wfMsg('clearyourcache'));
754 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
755 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
757 $imageUrl = $wgStylePath.'/common/images/redirect.png';
758 $targetUrl = $rt->escapeLocalURL();
759 $titleText = htmlspecialchars( $rt->getPrefixedText() );
760 $link = $sk->makeLinkObj( $rt );
762 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
763 '<span class="redirectText">'.$link.'</span>' );
765 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
766 $catlinks = $parseout->getCategoryLinks();
767 $wgOut->addCategoryLinks($catlinks);
768 $skin = $wgUser->getSkin();
769 } else if ( $pcache ) {
770 # Display content and save to parser cache
771 $wgOut->addPrimaryWikiText( $text, $this );
773 # Display content, don't attempt to save to parser cache
775 # Don't show section-edit links on old revisions... this way lies madness.
776 if( !$this->isCurrent() ) {
777 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
779 $wgOut->addWikiText( $text );
781 if( !$this->isCurrent() ) {
782 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
786 /* title may have been set from the cache */
787 $t = $wgOut->getPageTitle();
789 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
792 # If we have been passed an &rcid= parameter, we want to give the user a
793 # chance to mark this new article as patrolled.
797 && $wgUser->isLoggedIn()
798 && ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
801 "<div class='patrollink'>" .
802 wfMsg ( 'markaspatrolledlink',
803 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
809 # Put link titles into the link cache
810 $wgOut->transformBuffer();
812 # Add link titles as META keywords
813 $wgOut->addMetaTags() ;
815 $this->viewUpdates();
816 wfProfileOut( $fname );
820 * Insert a new empty page record for this article.
821 * This *must* be followed up by creating a revision
822 * and running $this->updateToLatest( $rev_id );
823 * or else the record will be left in a funky state.
824 * Best if all done inside a transaction.
826 * @param Database $dbw
827 * @param string $restrictions
828 * @return int The newly created page_id key
831 function insertOn( &$dbw, $restrictions = '' ) {
832 $fname = 'Article::insertOn';
833 wfProfileIn( $fname );
835 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
836 $dbw->insert( 'page', array(
837 'page_id' => $page_id,
838 'page_namespace' => $this->mTitle
->getNamespace(),
839 'page_title' => $this->mTitle
->getDBkey(),
841 'page_restrictions' => $restrictions,
842 'page_is_redirect' => 0, # Will set this shortly...
844 'page_random' => wfRandom(),
845 'page_touched' => $dbw->timestamp(),
846 'page_latest' => 0, # Fill this in shortly...
848 $newid = $dbw->insertId();
850 $this->mTitle
->resetArticleId( $newid );
852 wfProfileOut( $fname );
857 * Update the page record to point to a newly saved revision.
859 * @param Database $dbw
860 * @param Revision $revision -- for ID number, and text used to set
861 length and redirect status fields
862 * @param int $lastRevision -- if given, will not overwrite the page field
863 * when different from the currently set value.
864 * Giving 0 indicates the new page flag should
866 * @return bool true on success, false on failure
869 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
870 $fname = 'Article::updateToRevision';
871 wfProfileIn( $fname );
873 $conditions = array( 'page_id' => $this->getId() );
874 if( !is_null( $lastRevision ) ) {
875 # An extra check against threads stepping on each other
876 $conditions['page_latest'] = $lastRevision;
878 $text = $revision->getText();
879 $dbw->update( 'page',
881 'page_latest' => $revision->getId(),
882 'page_touched' => $dbw->timestamp(),
883 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
884 'page_is_redirect' => Article
::isRedirect( $text ),
885 'page_len' => strlen( $text ),
890 wfProfileOut( $fname );
891 return ( $dbw->affectedRows() != 0 );
895 * If the given revision is newer than the currently set page_latest,
896 * update the page record. Otherwise, do nothing.
898 * @param Database $dbw
899 * @param Revision $revision
901 function updateIfNewerOn( &$dbw, $revision ) {
902 $fname = 'Article::updateIfNewerOn';
903 wfProfileIn( $fname );
905 $row = $dbw->selectRow(
906 array( 'revision', 'page' ),
907 array( 'rev_id', 'rev_timestamp' ),
909 'page_id' => $this->getId(),
910 'page_latest=rev_id' ),
913 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
914 wfProfileOut( $fname );
917 $prev = $row->rev_id
;
919 # No or missing previous revision; mark the page as new
923 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
924 wfProfileOut( $fname );
929 * Theoretically we could defer these whole insert and update
930 * functions for after display, but that's taking a big leap
931 * of faith, and we want to be able to report database
932 * errors at some point.
935 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false ) {
936 global $wgOut, $wgUser;
937 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
939 $fname = 'Article::insertNewArticle';
941 $this->mGoodAdjustment
= $this->isCountable( $text );
942 $this->mTotalAdjustment
= 1;
944 $ns = $this->mTitle
->getNamespace();
945 $ttl = $this->mTitle
->getDBkey();
946 $text = $this->preSaveTransform( $text );
947 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
948 $now = wfTimestampNow();
950 $dbw =& wfGetDB( DB_MASTER
);
952 # Add the page record; stake our claim on this title!
953 $newid = $this->insertOn( $dbw );
955 # Save the revision text...
956 $revision = new Revision( array(
958 'comment' => $summary,
959 'minor_edit' => $isminor,
962 $revisionId = $revision->insertOn( $dbw );
964 $this->mTitle
->resetArticleID( $newid );
966 # Update the page record with revision data
967 $this->updateRevisionOn( $dbw, $revision, 0 );
969 Article
::onArticleCreate( $this->mTitle
);
971 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
972 '', strlen( $text ), $revisionId );
976 if(!$this->mTitle
->userIsWatching()) $this->watch();
978 if ( $this->mTitle
->userIsWatching() ) {
983 # The talk page isn't in the regular link tables, so we need to update manually:
984 $talkns = $ns ^
1; # talk -> normal; normal -> talk
985 $dbw->update( 'page',
986 array( 'page_touched' => $dbw->timestamp($now) ),
987 array( 'page_namespace' => $talkns,
988 'page_title' => $ttl ),
991 # standard deferred updates
992 $this->editUpdates( $text, $summary, $isminor, $now );
994 $oldid = 0; # new article
995 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
998 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
999 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
1000 if ($section != '') {
1001 if( is_null( $edittime ) ) {
1002 $rev = Revision
::newFromTitle( $this->mTitle
);
1004 $dbw =& wfGetDB( DB_MASTER
);
1005 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1007 $oldtext = $rev->getText();
1009 if($section=='new') {
1010 if($summary) $subject="== {$summary} ==\n\n";
1011 $text=$oldtext."\n\n".$subject.$text;
1014 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1015 # comments to be stripped as well)
1016 $striparray=array();
1017 $parser=new Parser();
1018 $parser->mOutputType
=OT_WIKI
;
1019 $oldtext=$parser->strip($oldtext, $striparray, true);
1021 # now that we can be sure that no pseudo-sections are in the source,
1023 # Unfortunately we can't simply do a preg_replace because that might
1024 # replace the wrong section, so we have to use the section counter instead
1025 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1026 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1027 $secs[$section*2]=$text."\n\n"; // replace with edited
1029 # section 0 is top (intro) section
1032 # headline of old section - we need to go through this section
1033 # to determine if there are any subsections that now need to
1034 # be erased, as the mother section has been replaced with
1035 # the text of all subsections.
1036 $headline=$secs[$section*2-1];
1037 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1038 $hlevel=$matches[1];
1040 # determine headline level for wikimarkup headings
1041 if(strpos($hlevel,'=')!==false) {
1042 $hlevel=strlen($hlevel);
1045 $secs[$section*2-1]=''; // erase old headline
1048 while(!empty($secs[$count*2-1]) && !$break) {
1050 $subheadline=$secs[$count*2-1];
1052 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1053 $subhlevel=$matches[1];
1054 if(strpos($subhlevel,'=')!==false) {
1055 $subhlevel=strlen($subhlevel);
1057 if($subhlevel > $hlevel) {
1058 // erase old subsections
1059 $secs[$count*2-1]='';
1062 if($subhlevel <= $hlevel) {
1070 $text=join('',$secs);
1071 # reinsert the stuff that we stripped out earlier
1072 $text=$parser->unstrip($text,$striparray);
1073 $text=$parser->unstripNoWiki($text,$striparray);
1081 * Change an existing article. Puts the previous version back into the old table, updates RC
1082 * and all necessary caches, mostly via the deferred update array.
1084 * It is possible to call this function from a command-line script, but note that you should
1085 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1087 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1088 global $wgOut, $wgUser;
1089 global $wgDBtransactions, $wgMwRedir;
1090 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1092 $fname = 'Article::updateArticle';
1095 $isminor = ( $minor && $wgUser->isLoggedIn() );
1096 if ( $this->isRedirect( $text ) ) {
1097 # Remove all content but redirect
1098 # This could be done by reconstructing the redirect from a title given by
1099 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1101 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1103 $text = $m[1] . "\n";
1106 else { $redir = 0; }
1108 $text = $this->preSaveTransform( $text );
1109 $dbw =& wfGetDB( DB_MASTER
);
1110 $now = wfTimestampNow();
1112 # Update article, but only if changed.
1114 # It's important that we either rollback or complete, otherwise an attacker could
1115 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1116 # could conceivably have the same effect, especially if cur is locked for long periods.
1117 if( !$wgDBtransactions ) {
1118 $userAbort = ignore_user_abort( true );
1121 $oldtext = $this->getContent( true );
1122 $oldsize = strlen( $oldtext );
1123 $newsize = strlen( $text );
1126 if ( 0 != strcmp( $text, $oldtext ) ) {
1127 $this->mGoodAdjustment
= $this->isCountable( $text )
1128 - $this->isCountable( $oldtext );
1129 $this->mTotalAdjustment
= 0;
1130 $now = wfTimestampNow();
1132 $lastRevision = $dbw->selectField(
1133 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1135 $revision = new Revision( array(
1136 'page' => $this->getId(),
1137 'comment' => $summary,
1138 'minor_edit' => $isminor,
1141 $revisionId = $revision->insertOn( $dbw );
1144 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1147 /* Belated edit conflict! Run away!! */
1150 # Update recentchanges and purge cache and whatnot
1151 $bot = (int)($wgUser->isBot() ||
$forceBot);
1152 RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1153 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1155 Article
::onArticleEdit( $this->mTitle
);
1159 if( !$wgDBtransactions ) {
1160 ignore_user_abort( $userAbort );
1165 if (!$this->mTitle
->userIsWatching()) $this->watch();
1167 if ( $this->mTitle
->userIsWatching() ) {
1171 # standard deferred updates
1172 $this->editUpdates( $text, $summary, $minor, $now );
1176 # Template namespace
1177 # Purge all articles linking here
1178 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1179 $titles = $this->mTitle
->getLinksTo();
1180 Title
::touchArray( $titles );
1181 if ( $wgUseSquid ) {
1182 foreach ( $titles as $title ) {
1183 $urls[] = $title->getInternalURL();
1189 if ( $wgUseSquid ) {
1190 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1191 $u = new SquidUpdate( $urls );
1192 array_push( $wgPostCommitUpdateList, $u );
1195 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1201 * After we've either updated or inserted the article, update
1202 * the link tables and redirect to the new page.
1204 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1205 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1206 global $wgUseEnotif;
1208 $wgLinkCache = new LinkCache();
1210 if ( !$wgUseDumbLinkUpdate ) {
1211 # Preload links to reduce lock time
1212 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS
) {
1213 $wgLinkCache->preFill( $this->mTitle
);
1214 $wgLinkCache->clear();
1218 # Parse the text and replace links with placeholders
1219 $wgOut = new OutputPage();
1221 # Pass the current title along in case we're creating a wiki page
1222 # which is different than the currently displayed one (e.g. image
1223 # pages created on file uploads); otherwise, link updates will
1225 $wgOut->addWikiTextWithTitle( $text, $this->mTitle
);
1227 if ( !$wgUseDumbLinkUpdate ) {
1228 # Move the current links back to the second register
1229 $wgLinkCache->swapRegisters();
1231 # Get old version of link table to allow incremental link updates
1232 # Lock this data now since it is needed for an update
1233 $wgLinkCache->forUpdate( true );
1234 $wgLinkCache->preFill( $this->mTitle
);
1236 # Swap this old version back into its rightful place
1237 $wgLinkCache->swapRegisters();
1240 if( $this->isRedirect( $text ) )
1244 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1246 if ( $wgUseEnotif ) {
1247 # this would be better as an extension hook
1248 include_once( "UserMailer.php" );
1249 $wgEnotif = new EmailNotification ();
1250 $wgEnotif->notifyOnPageChange( $this->mTitle
, $now, $summary, $me2, $oldid );
1255 * Mark this particular edit as patrolled
1257 function markpatrolled() {
1258 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1259 $wgOut->setRobotpolicy( 'noindex,follow' );
1261 if ( !$wgUseRCPatrol )
1263 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1266 if ( $wgUser->isAnon() )
1268 $wgOut->loginToUse();
1271 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1273 $wgOut->sysopRequired();
1276 $rcid = $wgRequest->getVal( 'rcid' );
1277 if ( !is_null ( $rcid ) )
1279 RecentChange
::markPatrolled( $rcid );
1280 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1281 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1283 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1284 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1288 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1295 function validate() {
1296 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1298 if ( !$wgUseValidation ) # Are we using article validation at all?
1300 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1304 $wgOut->setRobotpolicy( 'noindex,follow' );
1305 $revision = $wgRequest->getVal( 'revision' );
1307 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1309 $v = new Validation
;
1310 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1311 $t = $v->showList ( $this ) ;
1312 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1313 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1315 $t = $v->validatePageForm ( $this , $revision ) ;
1317 $wgOut->addHTML ( $t ) ;
1321 * Add this page to $wgUser's watchlist
1326 global $wgUser, $wgOut;
1328 if ( $wgUser->isAnon() ) {
1329 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1332 if ( wfReadOnly() ) {
1333 $wgOut->readOnlyPage();
1337 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1339 $wgUser->addWatch( $this->mTitle
);
1340 $wgUser->saveSettings();
1342 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1344 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1345 $wgOut->setRobotpolicy( 'noindex,follow' );
1347 $link = $this->mTitle
->getPrefixedText();
1348 $text = wfMsg( 'addedwatchtext', $link );
1349 $wgOut->addWikiText( $text );
1352 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1356 * Stop watching a page
1359 function unwatch() {
1361 global $wgUser, $wgOut;
1363 if ( $wgUser->isAnon() ) {
1364 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1367 if ( wfReadOnly() ) {
1368 $wgOut->readOnlyPage();
1372 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1374 $wgUser->removeWatch( $this->mTitle
);
1375 $wgUser->saveSettings();
1377 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1379 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1380 $wgOut->setRobotpolicy( 'noindex,follow' );
1382 $link = $this->mTitle
->getPrefixedText();
1383 $text = wfMsg( 'removedwatchtext', $link );
1384 $wgOut->addWikiText( $text );
1387 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1393 function protect( $limit = 'sysop' ) {
1394 global $wgUser, $wgOut, $wgRequest;
1396 if ( ! $wgUser->isAllowed('protect') ) {
1397 $wgOut->sysopRequired();
1400 if ( wfReadOnly() ) {
1401 $wgOut->readOnlyPage();
1404 $id = $this->mTitle
->getArticleID();
1406 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1410 $confirm = $wgRequest->wasPosted() &&
1411 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1412 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1413 $reason = $wgRequest->getText( 'wpReasonProtect' );
1416 $dbw =& wfGetDB( DB_MASTER
);
1417 $dbw->update( 'page',
1419 'page_touched' => $dbw->timestamp(),
1420 'page_restrictions' => (string)$limit
1421 ), array( /* WHERE */
1423 ), 'Article::protect'
1426 $restrictions = "move=" . $limit;
1428 $restrictions .= ":edit=" . $limit;
1430 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1432 $dbw =& wfGetDB( DB_MASTER
);
1433 $dbw->update( 'page',
1435 'page_touched' => $dbw->timestamp(),
1436 'page_restrictions' => $restrictions
1437 ), array( /* WHERE */
1439 ), 'Article::protect'
1442 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1444 $log = new LogPage( 'protect' );
1445 if ( $limit === '' ) {
1446 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1448 $log->addEntry( 'protect', $this->mTitle
, $reason );
1450 $wgOut->redirect( $this->mTitle
->getFullURL() );
1454 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1455 return $this->confirmProtect( '', $reason, $limit );
1460 * Output protection confirmation dialog
1462 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1463 global $wgOut, $wgUser;
1465 wfDebug( "Article::confirmProtect\n" );
1467 $sub = $this->mTitle
->getPrefixedText();
1468 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1474 if ( $limit === '' ) {
1475 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1476 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1477 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1478 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1479 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1481 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1482 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1483 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1484 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1485 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1486 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1489 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1490 $token = htmlspecialchars( $wgUser->editToken() );
1493 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1497 <label for='wpReasonProtect'>{$protcom}:</label>
1500 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1503 if($moveonly != '') {
1507 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1510 <label for='wpMoveOnly'>{$moveonly}</label>
1518 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1522 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1525 $wgOut->returnToMain( false );
1529 * Unprotect the pages
1531 function unprotect() {
1532 return $this->protect( '' );
1536 * UI entry point for page deletion
1539 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1540 $fname = 'Article::delete';
1541 $confirm = $wgRequest->wasPosted() &&
1542 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1543 $reason = $wgRequest->getText( 'wpReason' );
1545 # This code desperately needs to be totally rewritten
1548 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1549 $wgOut->sysopRequired();
1552 if( wfReadOnly() ) {
1553 $wgOut->readOnlyPage();
1557 # Better double-check that it hasn't been deleted yet!
1558 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1559 if( !$this->mTitle
->exists() ) {
1560 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1565 $this->doDelete( $reason );
1569 # determine whether this page has earlier revisions
1570 # and insert a warning if it does
1571 # we select the text because it might be useful below
1572 $dbr =& $this->getDB();
1573 $ns = $this->mTitle
->getNamespace();
1574 $title = $this->mTitle
->getDBkey();
1575 $revisions = $dbr->select( array( 'page', 'revision' ),
1576 array( 'rev_id', 'rev_user_text' ),
1578 'page_namespace' => $ns,
1579 'page_title' => $title,
1580 'rev_page = page_id'
1581 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1584 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1585 $skin=$wgUser->getSkin();
1586 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1587 $wgOut->addHTML( $skin->historyLink() .'</b>');
1591 $rev =& Revision
::newFromTitle( $this->mTitle
);
1593 # Fetch name(s) of contributors
1595 $all_same_user = true;
1596 while( $row = $dbr->fetchObject( $revisions ) ) {
1597 if( $rev_name != '' && $rev_name != $row->rev_user_text
) {
1598 $all_same_user = false;
1600 $rev_name = $row->rev_user_text
;
1604 if( !is_null( $rev ) ) {
1605 # if this is a mini-text, we can paste part of it into the deletion reason
1606 $text = $rev->getText();
1608 #if this is empty, an earlier revision may contain "useful" text
1611 $prev = $rev->getPrevious();
1613 $text = $prev->getText();
1618 $length = strlen( $text );
1620 # this should not happen, since it is not possible to store an empty, new
1621 # page. Let's insert a standard text in case it does, though
1622 if( $length == 0 && $reason === '' ) {
1623 $reason = wfMsg( 'exblank' );
1626 if( $length < 500 && $reason === '' ) {
1627 # comment field=255, let's grep the first 150 to have some user
1630 $text = $wgContLang->truncate( $text, 150, '...' );
1632 # let's strip out newlines
1633 $text = preg_replace( "/[\n\r]/", '', $text );
1636 if( !$all_same_user ) {
1637 $reason = wfMsg( 'excontent', $text );
1639 $reason = wfMsg( 'excontentauthor', $text, $rev_name );
1642 $reason = wfMsg( 'exbeforeblank', $text );
1647 return $this->confirmDelete( '', $reason );
1651 * Output deletion confirmation dialog
1653 function confirmDelete( $par, $reason ) {
1654 global $wgOut, $wgUser;
1656 wfDebug( "Article::confirmDelete\n" );
1658 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1659 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1660 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1661 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1663 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1665 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1666 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1667 $token = htmlspecialchars( $wgUser->editToken() );
1670 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1674 <label for='wpReason'>{$delcom}:</label>
1677 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1683 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1687 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1690 $wgOut->returnToMain( false );
1695 * Perform a deletion and output success or failure messages
1697 function doDelete( $reason ) {
1698 global $wgOut, $wgUser, $wgContLang;
1699 $fname = 'Article::doDelete';
1700 wfDebug( $fname."\n" );
1702 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1703 if ( $this->doDeleteArticle( $reason ) ) {
1704 $deleted = $this->mTitle
->getPrefixedText();
1706 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1707 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1709 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1710 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1712 $wgOut->addWikiText( $text );
1713 $wgOut->returnToMain( false );
1714 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1716 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1722 * Back-end article deletion
1723 * Deletes the article with database consistency, writes logs, purges caches
1726 function doDeleteArticle( $reason ) {
1728 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1730 $fname = 'Article::doDeleteArticle';
1731 wfDebug( $fname."\n" );
1733 $dbw =& wfGetDB( DB_MASTER
);
1734 $ns = $this->mTitle
->getNamespace();
1735 $t = $this->mTitle
->getDBkey();
1736 $id = $this->mTitle
->getArticleID();
1738 if ( $t == '' ||
$id == 0 ) {
1742 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1743 array_push( $wgDeferredUpdateList, $u );
1745 $linksTo = $this->mTitle
->getLinksTo();
1748 if ( $wgUseSquid ) {
1750 $this->mTitle
->getInternalURL(),
1751 $this->mTitle
->getInternalURL( 'history' )
1754 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
1755 array_push( $wgPostCommitUpdateList, $u );
1759 # Client and file cache invalidation
1760 Title
::touchArray( $linksTo );
1763 // For now, shunt the revision data into the archive table.
1764 // Text is *not* removed from the text table; bulk storage
1765 // is left intact to avoid breaking block-compression or
1766 // immutable storage schemes.
1768 // For backwards compatibility, note that some older archive
1769 // table entries will have ar_text and ar_flags fields still.
1771 // In the future, we may keep revisions and mark them with
1772 // the rev_deleted field, which is reserved for this purpose.
1773 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1775 'ar_namespace' => 'page_namespace',
1776 'ar_title' => 'page_title',
1777 'ar_comment' => 'rev_comment',
1778 'ar_user' => 'rev_user',
1779 'ar_user_text' => 'rev_user_text',
1780 'ar_timestamp' => 'rev_timestamp',
1781 'ar_minor_edit' => 'rev_minor_edit',
1782 'ar_rev_id' => 'rev_id',
1783 'ar_text_id' => 'rev_text_id',
1786 'page_id = rev_page'
1790 # Now that it's safely backed up, delete it
1791 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1792 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1794 # Clean up recentchanges entries...
1795 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1797 # Finally, clean up the link tables
1798 $t = $this->mTitle
->getPrefixedDBkey();
1800 Article
::onArticleDelete( $this->mTitle
);
1802 # Delete outgoing links
1803 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1804 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1805 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1808 $log = new LogPage( 'delete' );
1809 $log->addEntry( 'delete', $this->mTitle
, $reason );
1811 # Clear the cached article id so the interface doesn't act like we exist
1812 $this->mTitle
->resetArticleID( 0 );
1813 $this->mTitle
->mArticleID
= 0;
1818 * Revert a modification
1820 function rollback() {
1821 global $wgUser, $wgOut, $wgRequest;
1822 $fname = 'Article::rollback';
1824 if ( ! $wgUser->isAllowed('rollback') ) {
1825 $wgOut->sysopRequired();
1828 if ( wfReadOnly() ) {
1829 $wgOut->readOnlyPage( $this->getContent( true ) );
1832 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1833 array( $this->mTitle
->getPrefixedText(),
1834 $wgRequest->getVal( 'from' ) ) ) ) {
1835 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1836 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1839 $dbw =& wfGetDB( DB_MASTER
);
1841 # Enhanced rollback, marks edits rc_bot=1
1842 $bot = $wgRequest->getBool( 'bot' );
1844 # Replace all this user's current edits with the next one down
1845 $tt = $this->mTitle
->getDBKey();
1846 $n = $this->mTitle
->getNamespace();
1848 # Get the last editor, lock table exclusively
1850 $current = Revision
::newFromTitle( $this->mTitle
);
1851 if( is_null( $current ) ) {
1852 # Something wrong... no page?
1854 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1858 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1859 if( $from != $current->getUserText() ) {
1860 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1861 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1862 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1863 htmlspecialchars( $from ),
1864 htmlspecialchars( $current->getUserText() ) ) );
1865 if( $current->getComment() != '') {
1867 wfMsg( 'editcomment',
1868 htmlspecialchars( $current->getComment() ) ) );
1873 # Get the last edit not by this guy
1874 $user = IntVal( $current->getUser() );
1875 $user_text = $dbw->addQuotes( $current->getUserText() );
1876 $s = $dbw->selectRow( 'revision',
1877 array( 'rev_id', 'rev_timestamp' ),
1879 'rev_page' => $current->getPage(),
1880 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1883 'USE INDEX' => 'page_timestamp',
1884 'ORDER BY' => 'rev_timestamp DESC' )
1886 if( $s === false ) {
1889 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1890 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1895 # Mark all reverted edits as bot
1896 $dbw->update( 'recentchanges',
1899 ), array( /* WHERE */
1900 'rc_cur_id' => $current->getPage(),
1901 'rc_user_text' => $current->getUserText(),
1902 "rc_timestamp > '{$s->rev_timestamp}'",
1908 $target = Revision
::newFromId( $s->rev_id
);
1909 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1911 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1912 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1913 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1915 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1916 Article
::onArticleEdit( $this->mTitle
);
1919 $wgOut->returnToMain( false );
1924 * Do standard deferred updates after page view
1927 function viewUpdates() {
1928 global $wgDeferredUpdateList, $wgUseEnotif;
1930 if ( 0 != $this->getID() ) {
1931 global $wgDisableCounters;
1932 if( !$wgDisableCounters ) {
1933 Article
::incViewCount( $this->getID() );
1934 $u = new SiteStatsUpdate( 1, 0, 0 );
1935 array_push( $wgDeferredUpdateList, $u );
1939 # Update newtalk status if user is reading their own
1943 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1944 $this->mTitle
->getText() == $wgUser->getName())
1946 if ( $wgUseEnotif ) {
1947 require_once( 'UserTalkUpdate.php' );
1948 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1950 $wgUser->setNewtalk(0);
1951 $wgUser->saveNewtalk();
1953 } elseif ( $wgUseEnotif ) {
1954 $wgUser->clearNotification( $this->mTitle
);
1960 * Do standard deferred updates after page edit.
1961 * Every 1000th edit, prune the recent changes table.
1963 * @param string $text
1965 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1966 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1967 global $wgMessageCache, $wgUser, $wgUseEnotif;
1970 if ( 0 == mt_rand( 0, 999 ) ) {
1971 # Periodically flush old entries from the recentchanges table.
1973 $dbw =& wfGetDB( DB_MASTER
);
1974 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1975 $recentchanges = $dbw->tableName( 'recentchanges' );
1976 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1977 $dbw->query( $sql );
1979 $id = $this->getID();
1980 $title = $this->mTitle
->getPrefixedDBkey();
1981 $shortTitle = $this->mTitle
->getDBkey();
1984 $u = new LinksUpdate( $id, $title );
1985 array_push( $wgDeferredUpdateList, $u );
1986 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
1987 array_push( $wgDeferredUpdateList, $u );
1988 $u = new SearchUpdate( $id, $title, $text );
1989 array_push( $wgDeferredUpdateList, $u );
1991 # If this is another user's talk page, update newtalk
1993 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
1994 if ( $wgUseEnotif ) {
1995 require_once( 'UserTalkUpdate.php' );
1996 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary,
1997 $minoredit, $timestamp_of_pagechange);
1999 $other = User
::newFromName($shortTitle);
2001 $other->setNewtalk(1);
2002 $other->saveNewtalk();
2007 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2008 $wgMessageCache->replace( $shortTitle, $text );
2014 * @todo document this function
2016 * @param string $oldid Revision ID of this article revision
2018 function setOldSubtitle( $oldid=0 ) {
2019 global $wgLang, $wgOut, $wgUser;
2021 $current = ( $oldid == $this->mLatest
);
2022 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2023 $sk = $wgUser->getSkin();
2025 ?
wfMsg( 'currentrevisionlink' )
2026 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2027 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2028 $nextlink = $current
2029 ?
wfMsg( 'nextrevision' )
2030 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2031 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2032 $wgOut->setSubtitle( $r );
2036 * This function is called right before saving the wikitext,
2037 * so we can do things like signatures and links-in-context.
2039 * @param string $text
2041 function preSaveTransform( $text ) {
2042 global $wgParser, $wgUser;
2043 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2046 /* Caching functions */
2049 * checkLastModified returns true if it has taken care of all
2050 * output to the client that is necessary for this request.
2051 * (that is, it has sent a cached version of the page)
2053 function tryFileCache() {
2054 static $called = false;
2056 wfDebug( " tryFileCache() -- called twice!?\n" );
2060 if($this->isFileCacheable()) {
2061 $touched = $this->mTouched
;
2062 $cache = new CacheManager( $this->mTitle
);
2063 if($cache->isFileCacheGood( $touched )) {
2065 wfDebug( " tryFileCache() - about to load\n" );
2066 $cache->loadFromFileCache();
2069 wfDebug( " tryFileCache() - starting buffer\n" );
2070 ob_start( array(&$cache, 'saveToFileCache' ) );
2073 wfDebug( " tryFileCache() - not cacheable\n" );
2078 * Check if the page can be cached
2081 function isFileCacheable() {
2082 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2083 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2085 return $wgUseFileCache
2086 and (!$wgShowIPinHeader)
2087 and ($this->getID() != 0)
2088 and ($wgUser->isAnon())
2089 and (!$wgUser->getNewtalk())
2090 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2091 and (empty( $action ) ||
$action == 'view')
2092 and (!isset($oldid))
2094 and (!isset($redirect))
2095 and (!isset($printable))
2096 and (!$this->mRedirectedFrom
);
2100 * Loads cur_touched and returns a value indicating if it should be used
2103 function checkTouched() {
2104 $fname = 'Article::checkTouched';
2105 if( !$this->mDataLoaded
) {
2106 $dbr =& $this->getDB();
2107 $data = $this->pageDataFromId( $dbr, $this->getId() );
2109 $this->loadPageData( $data );
2112 return !$this->mIsRedirect
;
2116 * Edit an article without doing all that other stuff
2117 * The article must already exist; link tables etc
2118 * are not updated, caches are not flushed.
2120 * @param string $text text submitted
2121 * @param string $comment comment submitted
2122 * @param bool $minor whereas it's a minor modification
2124 function quickEdit( $text, $comment = '', $minor = 0 ) {
2125 $fname = 'Article::quickEdit';
2126 wfProfileIn( $fname );
2128 $dbw =& wfGetDB( DB_MASTER
);
2130 $revision = new Revision( array(
2131 'page' => $this->getId(),
2133 'comment' => $comment,
2134 'minor_edit' => $minor ?
1 : 0,
2136 $revisionId = $revision->insertOn( $dbw );
2137 $this->updateRevisionOn( $dbw, $revision );
2140 wfProfileOut( $fname );
2144 * Used to increment the view counter
2147 * @param integer $id article id
2149 function incViewCount( $id ) {
2150 $id = intval( $id );
2151 global $wgHitcounterUpdateFreq;
2153 $dbw =& wfGetDB( DB_MASTER
);
2154 $pageTable = $dbw->tableName( 'page' );
2155 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2156 $acchitsTable = $dbw->tableName( 'acchits' );
2158 if( $wgHitcounterUpdateFreq <= 1 ){ //
2159 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2163 # Not important enough to warrant an error page in case of failure
2164 $oldignore = $dbw->ignoreErrors( true );
2166 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2168 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2169 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2170 # Most of the time (or on SQL errors), skip row count check
2171 $dbw->ignoreErrors( $oldignore );
2175 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2176 $row = $dbw->fetchObject( $res );
2177 $rown = intval( $row->n
);
2178 if( $rown >= $wgHitcounterUpdateFreq ){
2179 wfProfileIn( 'Article::incViewCount-collect' );
2180 $old_user_abort = ignore_user_abort( true );
2182 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2183 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2184 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2186 $dbw->query("DELETE FROM $hitcounterTable");
2187 $dbw->query('UNLOCK TABLES');
2188 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2189 'WHERE page_id = hc_id');
2190 $dbw->query("DROP TABLE $acchitsTable");
2192 ignore_user_abort( $old_user_abort );
2193 wfProfileOut( 'Article::incViewCount-collect' );
2195 $dbw->ignoreErrors( $oldignore );
2199 * The onArticle*() functions are supposed to be a kind of hooks
2200 * which should be called whenever any of the specified actions
2203 * This is a good place to put code to clear caches, for instance.
2205 * This is called on page move and undelete, as well as edit
2207 * @param $title_obj a title object
2210 function onArticleCreate($title_obj) {
2211 global $wgUseSquid, $wgPostCommitUpdateList;
2213 $title_obj->touchLinks();
2214 $titles = $title_obj->getLinksTo();
2217 if ( $wgUseSquid ) {
2218 $urls = $title_obj->getSquidURLs();
2219 foreach ( $titles as $linkTitle ) {
2220 $urls[] = $linkTitle->getInternalURL();
2222 $u = new SquidUpdate( $urls );
2223 array_push( $wgPostCommitUpdateList, $u );
2227 function onArticleDelete($title_obj) {
2228 $title_obj->touchLinks();
2231 function onArticleEdit($title_obj) {
2232 // This would be an appropriate place to purge caches.
2233 // Why's this not in here now?
2239 * Info about this page
2240 * Called for ?action=info when $wgAllowPageInfo is on.
2245 global $wgLang, $wgOut, $wgAllowPageInfo;
2246 $fname = 'Article::info';
2248 if ( !$wgAllowPageInfo ) {
2249 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2253 $page = $this->mTitle
->getSubjectPage();
2255 $wgOut->setPagetitle( $page->getPrefixedText() );
2256 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2258 # first, see if the page exists at all.
2259 $exists = $page->getArticleId() != 0;
2261 $wgOut->addHTML( wfMsg('noarticletext') );
2263 $dbr =& $this->getDB( DB_SLAVE
);
2265 'wl_title' => $page->getDBkey(),
2266 'wl_namespace' => $page->getNamespace() );
2267 $numwatchers = $dbr->selectField(
2272 $this->getSelectOptions() );
2274 $pageInfo = $this->pageCountInfo( $page );
2275 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2277 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2278 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2280 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2282 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2284 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2286 $wgOut->addHTML( '</ul>' );
2292 * Return the total number of edits and number of unique editors
2293 * on a given page. If page does not exist, returns false.
2295 * @param Title $title
2299 function pageCountInfo( $title ) {
2300 $id = $title->getArticleId();
2305 $dbr =& $this->getDB( DB_SLAVE
);
2307 $rev_clause = array( 'rev_page' => $id );
2308 $fname = 'Article::pageCountInfo';
2310 $edits = $dbr->selectField(
2315 $this->getSelectOptions() );
2317 $authors = $dbr->selectField(
2319 'COUNT(DISTINCT rev_user_text)',
2322 $this->getSelectOptions() );
2324 return array( 'edits' => $edits, 'authors' => $authors );
2328 * Return a list of templates used by this article.
2329 * Uses the links table to find the templates
2333 function getUsedTemplates() {
2335 $id = $this->mTitle
->getArticleID();
2337 $db =& wfGetDB( DB_SLAVE
);
2338 $res = $db->select( array( 'pagelinks' ),
2339 array( 'pl_title' ),
2342 'pl_namespace' => NS_TEMPLATE
),
2343 'Article:getUsedTemplates' );
2344 if ( false !== $res ) {
2345 if ( $db->numRows( $res ) ) {
2346 while ( $row = $db->fetchObject( $res ) ) {
2347 $result[] = $row->pl_title
;
2351 $db->freeResult( $res );