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 * Get the view count for this article
497 function getCount() {
498 if ( -1 == $this->mCounter
) {
499 $id = $this->getID();
500 $dbr =& $this->getDB();
501 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
502 'Article::getCount', $this->getSelectOptions() );
504 return $this->mCounter
;
508 * Would the given text make this article a "good" article (i.e.,
509 * suitable for including in the article count)?
510 * @param string $text Text to analyze
511 * @return integer 1 if it can be counted else 0
513 function isCountable( $text ) {
514 global $wgUseCommaCount;
516 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
517 if ( $this->isRedirect( $text ) ) { return 0; }
518 $token = ($wgUseCommaCount ?
',' : '[[' );
519 if ( false === strstr( $text, $token ) ) { return 0; }
524 * Tests if the article text represents a redirect
526 function isRedirect( $text = false ) {
527 if ( $text === false ) {
528 $this->loadContent();
529 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
531 $titleObj = Title
::newFromRedirect( $text );
533 return $titleObj !== NULL;
537 * Loads everything except the text
538 * This isn't necessary for all uses, so it's only done if needed.
541 function loadLastEdit() {
544 if ( -1 != $this->mUser
)
547 # New or non-existent articles have no user information
548 $id = $this->getID();
549 if ( 0 == $id ) return;
551 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
552 if( !is_null( $this->mLastRevision
) ) {
553 $this->mUser
= $this->mLastRevision
->getUser();
554 $this->mUserText
= $this->mLastRevision
->getUserText();
555 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
556 $this->mComment
= $this->mLastRevision
->getComment();
557 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
561 function getTimestamp() {
562 $this->loadLastEdit();
563 return $this->mTimestamp
;
567 $this->loadLastEdit();
571 function getUserText() {
572 $this->loadLastEdit();
573 return $this->mUserText
;
576 function getComment() {
577 $this->loadLastEdit();
578 return $this->mComment
;
581 function getMinorEdit() {
582 $this->loadLastEdit();
583 return $this->mMinorEdit
;
586 function getRevIdFetched() {
587 $this->loadLastEdit();
588 return $this->mRevIdFetched
;
591 function getContributors($limit = 0, $offset = 0) {
592 $fname = 'Article::getContributors';
594 # XXX: this is expensive; cache this info somewhere.
596 $title = $this->mTitle
;
598 $dbr =& $this->getDB();
599 $revTable = $dbr->tableName( 'revision' );
600 $userTable = $dbr->tableName( 'user' );
601 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
602 $ns = $title->getNamespace();
603 $user = $this->getUser();
604 $pageId = $this->getId();
606 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
607 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
608 WHERE rev_page = $pageId
609 AND rev_user != $user
610 GROUP BY rev_user, rev_user_text, user_real_name
611 ORDER BY timestamp DESC";
613 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
614 $sql .= ' '. $this->getSelectOptions();
616 $res = $dbr->query($sql, $fname);
618 while ( $line = $dbr->fetchObject( $res ) ) {
619 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
622 $dbr->freeResult($res);
627 * This is the default action of the script: just view the page of
631 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
632 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
633 global $wgEnotif, $wgParser;
634 $sk = $wgUser->getSkin();
636 $fname = 'Article::view';
637 wfProfileIn( $fname );
638 # Get variables from query string
639 $oldid = $this->getOldID();
640 $diff = $wgRequest->getVal( 'diff' );
641 $rcid = $wgRequest->getVal( 'rcid' );
642 $rdfrom = $wgRequest->getVal( 'rdfrom' );
644 $wgOut->setArticleFlag( true );
645 $wgOut->setRobotpolicy( 'index,follow' );
646 # If we got diff and oldid in the query, we want to see a
647 # diff page instead of the article.
649 if ( !is_null( $diff ) ) {
650 require_once( 'DifferenceEngine.php' );
651 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
653 $de = new DifferenceEngine( $oldid, $diff, $rcid );
654 // DifferenceEngine directly fetched the revision:
655 $this->mRevIdFetched
= $de->mNewid
;
659 # Run view updates for current revision only
660 $this->viewUpdates();
662 wfProfileOut( $fname );
665 if ( empty( $oldid ) && $this->checkTouched() ) {
666 if( $wgOut->checkLastModified( $this->mTouched
) ){
667 wfProfileOut( $fname );
669 } else if ( $this->tryFileCache() ) {
670 # tell wgOut that output is taken care of
672 $this->viewUpdates();
673 wfProfileOut( $fname );
677 # Should the parser cache be used?
678 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) && $this->getID() ) {
686 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
690 if ( !$outputDone ) {
691 $text = $this->getContent( false ); # May change mTitle by following a redirect
693 # Another whitelist check in case oldid or redirects are altering the title
694 if ( !$this->mTitle
->userCanRead() ) {
695 $wgOut->loginToUse();
701 # We're looking at an old revision
703 if ( !empty( $oldid ) ) {
704 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
705 $wgOut->setRobotpolicy( 'noindex,follow' );
707 if ( '' != $this->mRedirectedFrom
) {
708 $sk = $wgUser->getSkin();
709 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
711 $s = wfMsg( 'redirectedfrom', $redir );
712 $wgOut->setSubtitle( $s );
714 # Can't cache redirects
716 } elseif ( !empty( $rdfrom ) ) {
717 global $wgRedirectSources;
718 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
719 $sk = $wgUser->getSkin();
720 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
721 $s = wfMsg( 'redirectedfrom', $redir );
722 $wgOut->setSubtitle( $s );
726 # wrap user css and user js in pre and don't parse
727 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
729 $this->mTitle
->getNamespace() == NS_USER
&&
730 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
732 $wgOut->addWikiText( wfMsg('clearyourcache'));
733 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
734 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
736 $imageUrl = $wgStylePath.'/common/images/redirect.png';
737 $targetUrl = $rt->escapeLocalURL();
738 $titleText = htmlspecialchars( $rt->getPrefixedText() );
739 $link = $sk->makeLinkObj( $rt );
741 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
742 '<span class="redirectText">'.$link.'</span>' );
744 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
745 $catlinks = $parseout->getCategoryLinks();
746 $wgOut->addCategoryLinks($catlinks);
747 $skin = $wgUser->getSkin();
748 } else if ( $pcache ) {
749 # Display content and save to parser cache
750 $wgOut->addPrimaryWikiText( $text, $this );
752 # Display content, don't attempt to save to parser cache
753 $wgOut->addWikiText( $text );
756 /* title may have been set from the cache */
757 $t = $wgOut->getPageTitle();
759 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
762 # If we have been passed an &rcid= parameter, we want to give the user a
763 # chance to mark this new article as patrolled.
767 && $wgUser->isLoggedIn()
768 && ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
771 "<div class='patrollink'>" .
772 wfMsg ( 'markaspatrolledlink',
773 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
779 # Put link titles into the link cache
780 $wgOut->transformBuffer();
782 # Add link titles as META keywords
783 $wgOut->addMetaTags() ;
785 $this->viewUpdates();
786 wfProfileOut( $fname );
790 * Insert a new empty page record for this article.
791 * This *must* be followed up by creating a revision
792 * and running $this->updateToLatest( $rev_id );
793 * or else the record will be left in a funky state.
794 * Best if all done inside a transaction.
796 * @param Database $dbw
797 * @param string $restrictions
798 * @return int The newly created page_id key
801 function insertOn( &$dbw, $restrictions = '' ) {
802 $fname = 'Article::insertOn';
803 wfProfileIn( $fname );
805 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
806 $dbw->insert( 'page', array(
807 'page_id' => $page_id,
808 'page_namespace' => $this->mTitle
->getNamespace(),
809 'page_title' => $this->mTitle
->getDBkey(),
811 'page_restrictions' => $restrictions,
812 'page_is_redirect' => 0, # Will set this shortly...
814 'page_random' => wfRandom(),
815 'page_touched' => $dbw->timestamp(),
816 'page_latest' => 0, # Fill this in shortly...
818 $newid = $dbw->insertId();
820 $this->mTitle
->resetArticleId( $newid );
822 wfProfileOut( $fname );
827 * Update the page record to point to a newly saved revision.
829 * @param Database $dbw
830 * @param Revision $revision -- for ID number, and text used to set
831 length and redirect status fields
832 * @param int $lastRevision -- if given, will not overwrite the page field
833 * when different from the currently set value.
834 * Giving 0 indicates the new page flag should
836 * @return bool true on success, false on failure
839 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
840 $fname = 'Article::updateToRevision';
841 wfProfileIn( $fname );
843 $conditions = array( 'page_id' => $this->getId() );
844 if( !is_null( $lastRevision ) ) {
845 # An extra check against threads stepping on each other
846 $conditions['page_latest'] = $lastRevision;
848 $text = $revision->getText();
849 $dbw->update( 'page',
851 'page_latest' => $revision->getId(),
852 'page_touched' => $dbw->timestamp(),
853 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
854 'page_is_redirect' => Article
::isRedirect( $text ),
855 'page_len' => strlen( $text ),
860 wfProfileOut( $fname );
861 return ( $dbw->affectedRows() != 0 );
865 * If the given revision is newer than the currently set page_latest,
866 * update the page record. Otherwise, do nothing.
868 * @param Database $dbw
869 * @param Revision $revision
871 function updateIfNewerOn( &$dbw, $revision ) {
872 $fname = 'Article::updateIfNewerOn';
873 wfProfileIn( $fname );
875 $row = $dbw->selectRow(
876 array( 'revision', 'page' ),
877 array( 'rev_id', 'rev_timestamp' ),
879 'page_id' => $this->getId(),
880 'page_latest=rev_id' ),
883 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
884 wfProfileOut( $fname );
887 $prev = $row->rev_id
;
889 # No or missing previous revision; mark the page as new
893 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
894 wfProfileOut( $fname );
899 * Theoretically we could defer these whole insert and update
900 * functions for after display, but that's taking a big leap
901 * of faith, and we want to be able to report database
902 * errors at some point.
905 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false ) {
906 global $wgOut, $wgUser;
907 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
909 $fname = 'Article::insertNewArticle';
911 $this->mGoodAdjustment
= $this->isCountable( $text );
912 $this->mTotalAdjustment
= 1;
914 $ns = $this->mTitle
->getNamespace();
915 $ttl = $this->mTitle
->getDBkey();
916 $text = $this->preSaveTransform( $text );
917 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
918 $now = wfTimestampNow();
920 $dbw =& wfGetDB( DB_MASTER
);
922 # Add the page record; stake our claim on this title!
923 $newid = $this->insertOn( $dbw );
925 # Save the revision text...
926 $revision = new Revision( array(
928 'comment' => $summary,
929 'minor_edit' => $isminor,
932 $revisionId = $revision->insertOn( $dbw );
934 $this->mTitle
->resetArticleID( $newid );
936 # Update the page record with revision data
937 $this->updateRevisionOn( $dbw, $revision, 0 );
939 Article
::onArticleCreate( $this->mTitle
);
941 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
945 if(!$this->mTitle
->userIsWatching()) $this->watch();
947 if ( $this->mTitle
->userIsWatching() ) {
952 # The talk page isn't in the regular link tables, so we need to update manually:
953 $talkns = $ns ^
1; # talk -> normal; normal -> talk
954 $dbw->update( 'page',
955 array( 'page_touched' => $dbw->timestamp($now) ),
956 array( 'page_namespace' => $talkns,
957 'page_title' => $ttl ),
960 # standard deferred updates
961 $this->editUpdates( $text, $summary, $isminor, $now );
963 $oldid = 0; # new article
964 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
967 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
968 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
969 if ($section != '') {
970 if( is_null( $edittime ) ) {
971 $rev = Revision
::newFromTitle( $this->mTitle
);
973 $dbw =& wfGetDB( DB_MASTER
);
974 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
976 $oldtext = $rev->getText();
978 if($section=='new') {
979 if($summary) $subject="== {$summary} ==\n\n";
980 $text=$oldtext."\n\n".$subject.$text;
983 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
984 # comments to be stripped as well)
986 $parser=new Parser();
987 $parser->mOutputType
=OT_WIKI
;
988 $oldtext=$parser->strip($oldtext, $striparray, true);
990 # now that we can be sure that no pseudo-sections are in the source,
992 # Unfortunately we can't simply do a preg_replace because that might
993 # replace the wrong section, so we have to use the section counter instead
994 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
995 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
996 $secs[$section*2]=$text."\n\n"; // replace with edited
998 # section 0 is top (intro) section
1001 # headline of old section - we need to go through this section
1002 # to determine if there are any subsections that now need to
1003 # be erased, as the mother section has been replaced with
1004 # the text of all subsections.
1005 $headline=$secs[$section*2-1];
1006 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1007 $hlevel=$matches[1];
1009 # determine headline level for wikimarkup headings
1010 if(strpos($hlevel,'=')!==false) {
1011 $hlevel=strlen($hlevel);
1014 $secs[$section*2-1]=''; // erase old headline
1017 while(!empty($secs[$count*2-1]) && !$break) {
1019 $subheadline=$secs[$count*2-1];
1021 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1022 $subhlevel=$matches[1];
1023 if(strpos($subhlevel,'=')!==false) {
1024 $subhlevel=strlen($subhlevel);
1026 if($subhlevel > $hlevel) {
1027 // erase old subsections
1028 $secs[$count*2-1]='';
1031 if($subhlevel <= $hlevel) {
1039 $text=join('',$secs);
1040 # reinsert the stuff that we stripped out earlier
1041 $text=$parser->unstrip($text,$striparray);
1042 $text=$parser->unstripNoWiki($text,$striparray);
1050 * Change an existing article. Puts the previous version back into the old table, updates RC
1051 * and all necessary caches, mostly via the deferred update array.
1053 * It is possible to call this function from a command-line script, but note that you should
1054 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1056 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1057 global $wgOut, $wgUser;
1058 global $wgDBtransactions, $wgMwRedir;
1059 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1061 $fname = 'Article::updateArticle';
1064 $isminor = ( $minor && $wgUser->isLoggedIn() );
1065 if ( $this->isRedirect( $text ) ) {
1066 # Remove all content but redirect
1067 # This could be done by reconstructing the redirect from a title given by
1068 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1070 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1072 $text = $m[1] . "\n";
1075 else { $redir = 0; }
1077 $text = $this->preSaveTransform( $text );
1078 $dbw =& wfGetDB( DB_MASTER
);
1079 $now = wfTimestampNow();
1081 # Update article, but only if changed.
1083 # It's important that we either rollback or complete, otherwise an attacker could
1084 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1085 # could conceivably have the same effect, especially if cur is locked for long periods.
1086 if( !$wgDBtransactions ) {
1087 $userAbort = ignore_user_abort( true );
1090 $oldtext = $this->getContent( true );
1093 if ( 0 != strcmp( $text, $oldtext ) ) {
1094 $this->mGoodAdjustment
= $this->isCountable( $text )
1095 - $this->isCountable( $oldtext );
1096 $this->mTotalAdjustment
= 0;
1097 $now = wfTimestampNow();
1099 $lastRevision = $dbw->selectField(
1100 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1102 $revision = new Revision( array(
1103 'page' => $this->getId(),
1104 'comment' => $summary,
1105 'minor_edit' => $isminor,
1108 $revisionId = $revision->insertOn( $dbw );
1111 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1114 /* Belated edit conflict! Run away!! */
1117 # Update recentchanges and purge cache and whatnot
1118 $bot = (int)($wgUser->isBot() ||
$forceBot);
1119 RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1120 $lastRevision, $this->getTimestamp(), $bot );
1121 Article
::onArticleEdit( $this->mTitle
);
1125 if( !$wgDBtransactions ) {
1126 ignore_user_abort( $userAbort );
1131 if (!$this->mTitle
->userIsWatching()) $this->watch();
1133 if ( $this->mTitle
->userIsWatching() ) {
1137 # standard deferred updates
1138 $this->editUpdates( $text, $summary, $minor, $now );
1142 # Template namespace
1143 # Purge all articles linking here
1144 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1145 $titles = $this->mTitle
->getLinksTo();
1146 Title
::touchArray( $titles );
1147 if ( $wgUseSquid ) {
1148 foreach ( $titles as $title ) {
1149 $urls[] = $title->getInternalURL();
1155 if ( $wgUseSquid ) {
1156 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1157 $u = new SquidUpdate( $urls );
1158 array_push( $wgPostCommitUpdateList, $u );
1161 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1167 * After we've either updated or inserted the article, update
1168 * the link tables and redirect to the new page.
1170 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1171 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1172 global $wgUseEnotif;
1174 $wgLinkCache = new LinkCache();
1176 if ( !$wgUseDumbLinkUpdate ) {
1177 # Preload links to reduce lock time
1178 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS
) {
1179 $wgLinkCache->preFill( $this->mTitle
);
1180 $wgLinkCache->clear();
1184 # Parse the text and replace links with placeholders
1185 $wgOut = new OutputPage();
1187 # Pass the current title along in case we're creating a wiki page
1188 # which is different than the currently displayed one (e.g. image
1189 # pages created on file uploads); otherwise, link updates will
1191 $wgOut->addWikiTextWithTitle( $text, $this->mTitle
);
1193 if ( !$wgUseDumbLinkUpdate ) {
1194 # Move the current links back to the second register
1195 $wgLinkCache->swapRegisters();
1197 # Get old version of link table to allow incremental link updates
1198 # Lock this data now since it is needed for an update
1199 $wgLinkCache->forUpdate( true );
1200 $wgLinkCache->preFill( $this->mTitle
);
1202 # Swap this old version back into its rightful place
1203 $wgLinkCache->swapRegisters();
1206 if( $this->isRedirect( $text ) )
1210 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1212 if ( $wgUseEnotif ) {
1213 # this would be better as an extension hook
1214 include_once( "UserMailer.php" );
1215 $wgEnotif = new EmailNotification ();
1216 $wgEnotif->notifyOnPageChange( $this->mTitle
, $now, $summary, $me2, $oldid );
1221 * Mark this particular edit as patrolled
1223 function markpatrolled() {
1224 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1225 $wgOut->setRobotpolicy( 'noindex,follow' );
1227 if ( !$wgUseRCPatrol )
1229 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1232 if ( $wgUser->isAnon() )
1234 $wgOut->loginToUse();
1237 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1239 $wgOut->sysopRequired();
1242 $rcid = $wgRequest->getVal( 'rcid' );
1243 if ( !is_null ( $rcid ) )
1245 RecentChange
::markPatrolled( $rcid );
1246 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1247 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1249 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1250 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1254 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1261 function validate() {
1262 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1264 if ( !$wgUseValidation ) # Are we using article validation at all?
1266 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1270 $wgOut->setRobotpolicy( 'noindex,follow' );
1271 $revision = $wgRequest->getVal( 'revision' );
1273 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1275 $v = new Validation
;
1276 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1277 $t = $v->showList ( $this ) ;
1278 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1279 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1281 $t = $v->validatePageForm ( $this , $revision ) ;
1283 $wgOut->addHTML ( $t ) ;
1287 * Add this page to $wgUser's watchlist
1292 global $wgUser, $wgOut;
1294 if ( $wgUser->isAnon() ) {
1295 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1298 if ( wfReadOnly() ) {
1299 $wgOut->readOnlyPage();
1303 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1305 $wgUser->addWatch( $this->mTitle
);
1306 $wgUser->saveSettings();
1308 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1310 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1311 $wgOut->setRobotpolicy( 'noindex,follow' );
1313 $link = $this->mTitle
->getPrefixedText();
1314 $text = wfMsg( 'addedwatchtext', $link );
1315 $wgOut->addWikiText( $text );
1318 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1322 * Stop watching a page
1325 function unwatch() {
1327 global $wgUser, $wgOut;
1329 if ( $wgUser->isAnon() ) {
1330 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1333 if ( wfReadOnly() ) {
1334 $wgOut->readOnlyPage();
1338 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1340 $wgUser->removeWatch( $this->mTitle
);
1341 $wgUser->saveSettings();
1343 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1345 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1346 $wgOut->setRobotpolicy( 'noindex,follow' );
1348 $link = $this->mTitle
->getPrefixedText();
1349 $text = wfMsg( 'removedwatchtext', $link );
1350 $wgOut->addWikiText( $text );
1353 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1359 function protect( $limit = 'sysop' ) {
1360 global $wgUser, $wgOut, $wgRequest;
1362 if ( ! $wgUser->isAllowed('protect') ) {
1363 $wgOut->sysopRequired();
1366 if ( wfReadOnly() ) {
1367 $wgOut->readOnlyPage();
1370 $id = $this->mTitle
->getArticleID();
1372 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1376 $confirm = $wgRequest->wasPosted() &&
1377 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1378 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1379 $reason = $wgRequest->getText( 'wpReasonProtect' );
1382 $dbw =& wfGetDB( DB_MASTER
);
1383 $dbw->update( 'page',
1385 'page_touched' => $dbw->timestamp(),
1386 'page_restrictions' => (string)$limit
1387 ), array( /* WHERE */
1389 ), 'Article::protect'
1392 $restrictions = "move=" . $limit;
1394 $restrictions .= ":edit=" . $limit;
1396 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1398 $dbw =& wfGetDB( DB_MASTER
);
1399 $dbw->update( 'page',
1401 'page_touched' => $dbw->timestamp(),
1402 'page_restrictions' => $restrictions
1403 ), array( /* WHERE */
1405 ), 'Article::protect'
1408 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1410 $log = new LogPage( 'protect' );
1411 if ( $limit === '' ) {
1412 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1414 $log->addEntry( 'protect', $this->mTitle
, $reason );
1416 $wgOut->redirect( $this->mTitle
->getFullURL() );
1420 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1421 return $this->confirmProtect( '', $reason, $limit );
1426 * Output protection confirmation dialog
1428 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1429 global $wgOut, $wgUser;
1431 wfDebug( "Article::confirmProtect\n" );
1433 $sub = $this->mTitle
->getPrefixedText();
1434 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1440 if ( $limit === '' ) {
1441 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1442 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1443 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1444 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1445 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1447 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1448 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1449 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1450 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1451 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1452 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1455 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1456 $token = htmlspecialchars( $wgUser->editToken() );
1459 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1463 <label for='wpReasonProtect'>{$protcom}:</label>
1466 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1469 if($moveonly != '') {
1473 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1476 <label for='wpMoveOnly'>{$moveonly}</label>
1484 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1488 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1491 $wgOut->returnToMain( false );
1495 * Unprotect the pages
1497 function unprotect() {
1498 return $this->protect( '' );
1502 * UI entry point for page deletion
1505 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1506 $fname = 'Article::delete';
1507 $confirm = $wgRequest->wasPosted() &&
1508 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1509 $reason = $wgRequest->getText( 'wpReason' );
1511 # This code desperately needs to be totally rewritten
1514 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1515 $wgOut->sysopRequired();
1518 if( wfReadOnly() ) {
1519 $wgOut->readOnlyPage();
1523 # Better double-check that it hasn't been deleted yet!
1524 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1525 if( !$this->mTitle
->exists() ) {
1526 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1531 $this->doDelete( $reason );
1535 # determine whether this page has earlier revisions
1536 # and insert a warning if it does
1537 # we select the text because it might be useful below
1538 $dbr =& $this->getDB();
1539 $ns = $this->mTitle
->getNamespace();
1540 $title = $this->mTitle
->getDBkey();
1541 $revisions = $dbr->select( array( 'page', 'revision' ),
1542 array( 'rev_id', 'rev_user_text' ),
1544 'page_namespace' => $ns,
1545 'page_title' => $title,
1546 'rev_page = page_id'
1547 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1550 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1551 $skin=$wgUser->getSkin();
1552 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1553 $wgOut->addHTML( $skin->historyLink() .'</b>');
1557 $rev =& Revision
::newFromTitle( $this->mTitle
);
1559 # Fetch name(s) of contributors
1561 $all_same_user = true;
1562 while( $row = $dbr->fetchObject( $revisions ) ) {
1563 if( $rev_name != '' && $rev_name != $row->rev_user_text
) {
1564 $all_same_user = false;
1566 $rev_name = $row->rev_user_text
;
1570 if( !is_null( $rev ) ) {
1571 # if this is a mini-text, we can paste part of it into the deletion reason
1572 $text = $rev->getText();
1574 #if this is empty, an earlier revision may contain "useful" text
1577 $prev = $rev->getPrevious();
1579 $text = $prev->getText();
1584 $length = strlen( $text );
1586 # this should not happen, since it is not possible to store an empty, new
1587 # page. Let's insert a standard text in case it does, though
1588 if( $length == 0 && $reason === '' ) {
1589 $reason = wfMsg( 'exblank' );
1592 if( $length < 500 && $reason === '' ) {
1593 # comment field=255, let's grep the first 150 to have some user
1596 $text = $wgContLang->truncate( $text, 150, '...' );
1598 # let's strip out newlines
1599 $text = preg_replace( "/[\n\r]/", '', $text );
1602 if( !$all_same_user ) {
1603 $reason = wfMsg( 'excontent', $text );
1605 $reason = wfMsg( 'excontentauthor', $text, $rev_name );
1608 $reason = wfMsg( 'exbeforeblank', $text );
1613 return $this->confirmDelete( '', $reason );
1617 * Output deletion confirmation dialog
1619 function confirmDelete( $par, $reason ) {
1620 global $wgOut, $wgUser;
1622 wfDebug( "Article::confirmDelete\n" );
1624 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1625 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1626 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1627 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1629 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1631 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1632 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1633 $token = htmlspecialchars( $wgUser->editToken() );
1636 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1640 <label for='wpReason'>{$delcom}:</label>
1643 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1649 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1653 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1656 $wgOut->returnToMain( false );
1661 * Perform a deletion and output success or failure messages
1663 function doDelete( $reason ) {
1664 global $wgOut, $wgUser, $wgContLang;
1665 $fname = 'Article::doDelete';
1666 wfDebug( $fname."\n" );
1668 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1669 if ( $this->doDeleteArticle( $reason ) ) {
1670 $deleted = $this->mTitle
->getPrefixedText();
1672 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1673 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1675 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1676 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1678 $wgOut->addWikiText( $text );
1679 $wgOut->returnToMain( false );
1680 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1682 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1688 * Back-end article deletion
1689 * Deletes the article with database consistency, writes logs, purges caches
1692 function doDeleteArticle( $reason ) {
1694 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1696 $fname = 'Article::doDeleteArticle';
1697 wfDebug( $fname."\n" );
1699 $dbw =& wfGetDB( DB_MASTER
);
1700 $ns = $this->mTitle
->getNamespace();
1701 $t = $this->mTitle
->getDBkey();
1702 $id = $this->mTitle
->getArticleID();
1704 if ( $t == '' ||
$id == 0 ) {
1708 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1709 array_push( $wgDeferredUpdateList, $u );
1711 $linksTo = $this->mTitle
->getLinksTo();
1714 if ( $wgUseSquid ) {
1716 $this->mTitle
->getInternalURL(),
1717 $this->mTitle
->getInternalURL( 'history' )
1720 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
1721 array_push( $wgPostCommitUpdateList, $u );
1725 # Client and file cache invalidation
1726 Title
::touchArray( $linksTo );
1729 // For now, shunt the revision data into the archive table.
1730 // Text is *not* removed from the text table; bulk storage
1731 // is left intact to avoid breaking block-compression or
1732 // immutable storage schemes.
1734 // For backwards compatibility, note that some older archive
1735 // table entries will have ar_text and ar_flags fields still.
1737 // In the future, we may keep revisions and mark them with
1738 // the rev_deleted field, which is reserved for this purpose.
1739 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1741 'ar_namespace' => 'page_namespace',
1742 'ar_title' => 'page_title',
1743 'ar_comment' => 'rev_comment',
1744 'ar_user' => 'rev_user',
1745 'ar_user_text' => 'rev_user_text',
1746 'ar_timestamp' => 'rev_timestamp',
1747 'ar_minor_edit' => 'rev_minor_edit',
1748 'ar_rev_id' => 'rev_id',
1749 'ar_text_id' => 'rev_text_id',
1752 'page_id = rev_page'
1756 # Now that it's safely backed up, delete it
1757 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1758 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1760 # Clean up recentchanges entries...
1761 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1763 # Finally, clean up the link tables
1764 $t = $this->mTitle
->getPrefixedDBkey();
1766 Article
::onArticleDelete( $this->mTitle
);
1768 # Delete outgoing links
1769 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1770 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1771 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1774 $log = new LogPage( 'delete' );
1775 $log->addEntry( 'delete', $this->mTitle
, $reason );
1777 # Clear the cached article id so the interface doesn't act like we exist
1778 $this->mTitle
->resetArticleID( 0 );
1779 $this->mTitle
->mArticleID
= 0;
1784 * Revert a modification
1786 function rollback() {
1787 global $wgUser, $wgOut, $wgRequest;
1788 $fname = 'Article::rollback';
1790 if ( ! $wgUser->isAllowed('rollback') ) {
1791 $wgOut->sysopRequired();
1794 if ( wfReadOnly() ) {
1795 $wgOut->readOnlyPage( $this->getContent( true ) );
1798 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1799 array( $this->mTitle
->getPrefixedText(),
1800 $wgRequest->getVal( 'from' ) ) ) ) {
1801 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1802 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1805 $dbw =& wfGetDB( DB_MASTER
);
1807 # Enhanced rollback, marks edits rc_bot=1
1808 $bot = $wgRequest->getBool( 'bot' );
1810 # Replace all this user's current edits with the next one down
1811 $tt = $this->mTitle
->getDBKey();
1812 $n = $this->mTitle
->getNamespace();
1814 # Get the last editor, lock table exclusively
1816 $current = Revision
::newFromTitle( $this->mTitle
);
1817 if( is_null( $current ) ) {
1818 # Something wrong... no page?
1820 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1824 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1825 if( $from != $current->getUserText() ) {
1826 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1827 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1828 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1829 htmlspecialchars( $from ),
1830 htmlspecialchars( $current->getUserText() ) ) );
1831 if( $current->getComment() != '') {
1833 wfMsg( 'editcomment',
1834 htmlspecialchars( $current->getComment() ) ) );
1839 # Get the last edit not by this guy
1840 $user = IntVal( $current->getUser() );
1841 $user_text = $dbw->addQuotes( $current->getUserText() );
1842 $s = $dbw->selectRow( 'revision',
1843 array( 'rev_id', 'rev_timestamp' ),
1845 'rev_page' => $current->getPage(),
1846 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1849 'USE INDEX' => 'page_timestamp',
1850 'ORDER BY' => 'rev_timestamp DESC' )
1852 if( $s === false ) {
1855 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1856 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1861 # Mark all reverted edits as bot
1862 $dbw->update( 'recentchanges',
1865 ), array( /* WHERE */
1866 'rc_cur_id' => $current->getPage(),
1867 'rc_user_text' => $current->getUserText(),
1868 "rc_timestamp > '{$s->rev_timestamp}'",
1874 $target = Revision
::newFromId( $s->rev_id
);
1875 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1877 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1878 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1879 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1881 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1882 Article
::onArticleEdit( $this->mTitle
);
1885 $wgOut->returnToMain( false );
1890 * Do standard deferred updates after page view
1893 function viewUpdates() {
1894 global $wgDeferredUpdateList, $wgUseEnotif;
1896 if ( 0 != $this->getID() ) {
1897 global $wgDisableCounters;
1898 if( !$wgDisableCounters ) {
1899 Article
::incViewCount( $this->getID() );
1900 $u = new SiteStatsUpdate( 1, 0, 0 );
1901 array_push( $wgDeferredUpdateList, $u );
1905 # Update newtalk status if user is reading their own
1909 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1910 $this->mTitle
->getText() == $wgUser->getName())
1912 if ( $wgUseEnotif ) {
1913 require_once( 'UserTalkUpdate.php' );
1914 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1916 $wgUser->setNewtalk(0);
1917 $wgUser->saveNewtalk();
1919 } elseif ( $wgUseEnotif ) {
1920 $wgUser->clearNotification( $this->mTitle
);
1926 * Do standard deferred updates after page edit.
1927 * Every 1000th edit, prune the recent changes table.
1929 * @param string $text
1931 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1932 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1933 global $wgMessageCache, $wgUser, $wgUseEnotif;
1936 if ( 0 == mt_rand( 0, 999 ) ) {
1937 # Periodically flush old entries from the recentchanges table.
1939 $dbw =& wfGetDB( DB_MASTER
);
1940 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1941 $recentchanges = $dbw->tableName( 'recentchanges' );
1942 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1943 $dbw->query( $sql );
1945 $id = $this->getID();
1946 $title = $this->mTitle
->getPrefixedDBkey();
1947 $shortTitle = $this->mTitle
->getDBkey();
1950 $u = new LinksUpdate( $id, $title );
1951 array_push( $wgDeferredUpdateList, $u );
1952 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
1953 array_push( $wgDeferredUpdateList, $u );
1954 $u = new SearchUpdate( $id, $title, $text );
1955 array_push( $wgDeferredUpdateList, $u );
1957 # If this is another user's talk page, update newtalk
1959 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
1960 if ( $wgUseEnotif ) {
1961 require_once( 'UserTalkUpdate.php' );
1962 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary,
1963 $minoredit, $timestamp_of_pagechange);
1965 $other = User
::newFromName($shortTitle);
1966 $other->setNewtalk(1);
1967 $other->saveNewtalk();
1971 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1972 $wgMessageCache->replace( $shortTitle, $text );
1978 * @todo document this function
1980 * @param string $oldid Revision ID of this article revision
1982 function setOldSubtitle( $oldid=0 ) {
1983 global $wgLang, $wgOut, $wgUser;
1985 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1986 $sk = $wgUser->getSkin();
1987 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1988 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1989 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1990 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1991 $wgOut->setSubtitle( $r );
1995 * This function is called right before saving the wikitext,
1996 * so we can do things like signatures and links-in-context.
1998 * @param string $text
2000 function preSaveTransform( $text ) {
2001 global $wgParser, $wgUser;
2002 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2005 /* Caching functions */
2008 * checkLastModified returns true if it has taken care of all
2009 * output to the client that is necessary for this request.
2010 * (that is, it has sent a cached version of the page)
2012 function tryFileCache() {
2013 static $called = false;
2015 wfDebug( " tryFileCache() -- called twice!?\n" );
2019 if($this->isFileCacheable()) {
2020 $touched = $this->mTouched
;
2021 $cache = new CacheManager( $this->mTitle
);
2022 if($cache->isFileCacheGood( $touched )) {
2024 wfDebug( " tryFileCache() - about to load\n" );
2025 $cache->loadFromFileCache();
2028 wfDebug( " tryFileCache() - starting buffer\n" );
2029 ob_start( array(&$cache, 'saveToFileCache' ) );
2032 wfDebug( " tryFileCache() - not cacheable\n" );
2037 * Check if the page can be cached
2040 function isFileCacheable() {
2041 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2042 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2044 return $wgUseFileCache
2045 and (!$wgShowIPinHeader)
2046 and ($this->getID() != 0)
2047 and ($wgUser->isAnon())
2048 and (!$wgUser->getNewtalk())
2049 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2050 and (empty( $action ) ||
$action == 'view')
2051 and (!isset($oldid))
2053 and (!isset($redirect))
2054 and (!isset($printable))
2055 and (!$this->mRedirectedFrom
);
2059 * Loads cur_touched and returns a value indicating if it should be used
2062 function checkTouched() {
2063 $fname = 'Article::checkTouched';
2064 if( !$this->mDataLoaded
) {
2065 $dbr =& $this->getDB();
2066 $data = $this->pageDataFromId( $dbr, $this->getId() );
2068 $this->loadPageData( $data );
2071 return !$this->mIsRedirect
;
2075 * Edit an article without doing all that other stuff
2076 * The article must already exist; link tables etc
2077 * are not updated, caches are not flushed.
2079 * @param string $text text submitted
2080 * @param string $comment comment submitted
2081 * @param bool $minor whereas it's a minor modification
2083 function quickEdit( $text, $comment = '', $minor = 0 ) {
2084 $fname = 'Article::quickEdit';
2085 wfProfileIn( $fname );
2087 $dbw =& wfGetDB( DB_MASTER
);
2089 $revision = new Revision( array(
2090 'page' => $this->getId(),
2092 'comment' => $comment,
2093 'minor_edit' => $minor ?
1 : 0,
2095 $revisionId = $revision->insertOn( $dbw );
2096 $this->updateRevisionOn( $dbw, $revision );
2099 wfProfileOut( $fname );
2103 * Used to increment the view counter
2106 * @param integer $id article id
2108 function incViewCount( $id ) {
2109 $id = intval( $id );
2110 global $wgHitcounterUpdateFreq;
2112 $dbw =& wfGetDB( DB_MASTER
);
2113 $pageTable = $dbw->tableName( 'page' );
2114 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2115 $acchitsTable = $dbw->tableName( 'acchits' );
2117 if( $wgHitcounterUpdateFreq <= 1 ){ //
2118 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2122 # Not important enough to warrant an error page in case of failure
2123 $oldignore = $dbw->ignoreErrors( true );
2125 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2127 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2128 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2129 # Most of the time (or on SQL errors), skip row count check
2130 $dbw->ignoreErrors( $oldignore );
2134 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2135 $row = $dbw->fetchObject( $res );
2136 $rown = intval( $row->n
);
2137 if( $rown >= $wgHitcounterUpdateFreq ){
2138 wfProfileIn( 'Article::incViewCount-collect' );
2139 $old_user_abort = ignore_user_abort( true );
2141 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2142 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2143 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2145 $dbw->query("DELETE FROM $hitcounterTable");
2146 $dbw->query('UNLOCK TABLES');
2147 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2148 'WHERE page_id = hc_id');
2149 $dbw->query("DROP TABLE $acchitsTable");
2151 ignore_user_abort( $old_user_abort );
2152 wfProfileOut( 'Article::incViewCount-collect' );
2154 $dbw->ignoreErrors( $oldignore );
2158 * The onArticle*() functions are supposed to be a kind of hooks
2159 * which should be called whenever any of the specified actions
2162 * This is a good place to put code to clear caches, for instance.
2164 * This is called on page move and undelete, as well as edit
2166 * @param $title_obj a title object
2169 function onArticleCreate($title_obj) {
2170 global $wgUseSquid, $wgPostCommitUpdateList;
2172 $title_obj->touchLinks();
2173 $titles = $title_obj->getLinksTo();
2176 if ( $wgUseSquid ) {
2177 $urls = $title_obj->getSquidURLs();
2178 foreach ( $titles as $linkTitle ) {
2179 $urls[] = $linkTitle->getInternalURL();
2181 $u = new SquidUpdate( $urls );
2182 array_push( $wgPostCommitUpdateList, $u );
2186 function onArticleDelete($title_obj) {
2187 $title_obj->touchLinks();
2190 function onArticleEdit($title_obj) {
2191 // This would be an appropriate place to purge caches.
2192 // Why's this not in here now?
2198 * Info about this page
2199 * Called for ?action=info when $wgAllowPageInfo is on.
2204 global $wgLang, $wgOut, $wgAllowPageInfo;
2205 $fname = 'Article::info';
2207 if ( !$wgAllowPageInfo ) {
2208 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2212 $page = $this->mTitle
->getSubjectPage();
2214 $wgOut->setPagetitle( $page->getPrefixedText() );
2215 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2217 # first, see if the page exists at all.
2218 $exists = $page->getArticleId() != 0;
2220 $wgOut->addHTML( wfMsg('noarticletext') );
2222 $dbr =& $this->getDB( DB_SLAVE
);
2224 'wl_title' => $page->getDBkey(),
2225 'wl_namespace' => $page->getNamespace() );
2226 $numwatchers = $dbr->selectField(
2231 $this->getSelectOptions() );
2233 $pageInfo = $this->pageCountInfo( $page );
2234 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2236 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2237 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2239 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2241 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2243 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2245 $wgOut->addHTML( '</ul>' );
2251 * Return the total number of edits and number of unique editors
2252 * on a given page. If page does not exist, returns false.
2254 * @param Title $title
2258 function pageCountInfo( $title ) {
2259 $id = $title->getArticleId();
2264 $dbr =& $this->getDB( DB_SLAVE
);
2266 $rev_clause = array( 'rev_page' => $id );
2267 $fname = 'Article::pageCountInfo';
2269 $edits = $dbr->selectField(
2274 $this->getSelectOptions() );
2276 $authors = $dbr->selectField(
2278 'COUNT(DISTINCT rev_user_text)',
2281 $this->getSelectOptions() );
2283 return array( 'edits' => $edits, 'authors' => $authors );
2287 * Return a list of templates used by this article.
2288 * Uses the links table to find the templates
2292 function getUsedTemplates() {
2294 $id = $this->mTitle
->getArticleID();
2296 $db =& wfGetDB( DB_SLAVE
);
2297 $res = $db->select( array( 'pagelinks' ),
2298 array( 'pl_title' ),
2301 'pl_namespace' => NS_TEMPLATE
),
2302 'Article:getUsedTemplates' );
2303 if ( false !== $res ) {
2304 if ( $db->numRows( $res ) ) {
2305 while ( $row = $db->fetchObject( $res ) ) {
2306 $result[] = $row->pl_title
;
2310 $db->freeResult( $res );