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, $wgOut;
86 # Get variables from query string :P
87 $action = $wgRequest->getText( 'action', 'view' );
88 $section = $wgRequest->getText( 'section' );
89 $preload = $wgRequest->getText( 'preload' );
91 $fname = 'Article::getContent';
92 wfProfileIn( $fname );
94 if ( 0 == $this->getID() ) {
95 if ( 'edit' == $action ) {
96 wfProfileOut( $fname );
98 # If requested, preload some text.
99 $text=$this->getPreloadedText($preload);
101 # We used to put MediaWiki:Newarticletext here if
102 # $text was empty at this point.
103 # This is now shown above the edit box instead.
106 wfProfileOut( $fname );
107 $wgOut->setRobotpolicy( 'noindex,nofollow' );
108 return wfMsg( 'noarticletext' );
110 $this->loadContent( $noredir );
111 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
112 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
113 $wgUser->isIP($this->mTitle
->getText()) &&
116 wfProfileOut( $fname );
117 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
119 if($action=='edit') {
121 if($section=='new') {
122 wfProfileOut( $fname );
123 $text=$this->getPreloadedText($preload);
127 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
128 # comments to be stripped as well)
129 $rv=$this->getSection($this->mContent
,$section);
130 wfProfileOut( $fname );
134 wfProfileOut( $fname );
135 return $this->mContent
;
141 This function accepts a title string as parameter
142 ($preload). If this string is non-empty, it attempts
143 to fetch the current revision text.
145 function getPreloadedText($preload) {
147 $preloadTitle=Title
::newFromText($preload);
148 if(isset($preloadTitle) && $preloadTitle->userCanRead()) {
149 $rev=Revision
::newFromTitle($preloadTitle);
151 return $rev->getText();
159 * This function returns the text of a section, specified by a number ($section).
160 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
161 * the first section before any such heading (section 0).
163 * If a section contains subsections, these are also returned.
165 * @param string $text text to look in
166 * @param integer $section section number
167 * @return string text of the requested section
169 function getSection($text,$section) {
171 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
172 # comments to be stripped as well)
174 $parser=new Parser();
175 $parser->mOutputType
=OT_WIKI
;
176 $striptext=$parser->strip($text, $striparray, true);
178 # now that we can be sure that no pseudo-sections are in the source,
179 # split it up by section
182 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
184 PREG_SPLIT_DELIM_CAPTURE
);
188 $headline=$secs[$section*2-1];
189 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
192 # translate wiki heading into level
193 if(strpos($hlevel,'=')!==false) {
194 $hlevel=strlen($hlevel);
197 $rv=$headline. $secs[$section*2];
201 while(!empty($secs[$count*2-1]) && !$break) {
203 $subheadline=$secs[$count*2-1];
204 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
205 $subhlevel=$matches[1];
206 if(strpos($subhlevel,'=')!==false) {
207 $subhlevel=strlen($subhlevel);
209 if($subhlevel > $hlevel) {
210 $rv.=$subheadline.$secs[$count*2];
212 if($subhlevel <= $hlevel) {
219 # reinsert stripped tags
220 $rv=$parser->unstrip($rv,$striparray);
221 $rv=$parser->unstripNoWiki($rv,$striparray);
228 * Return an array of the columns of the "cur"-table
230 function getContentFields() {
231 return $wgArticleContentFields = array(
232 'old_text','old_flags',
233 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
234 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
238 * Return the oldid of the article that is to be shown.
239 * For requests with a "direction", this is not the oldid of the
242 function getOldID() {
243 global $wgRequest, $wgOut;
246 if ( isset( $lastid ) ) {
250 $oldid = $wgRequest->getVal( 'oldid' );
251 if ( isset( $oldid ) ) {
252 $oldid = IntVal( $oldid );
253 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
254 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
258 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
260 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
261 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
270 return @$oldid; # "@" to be able to return "unset" without PHP complaining
275 * Load the revision (including cur_text) into this object
277 function loadContent( $noredir = false ) {
278 global $wgOut, $wgRequest;
280 if ( $this->mContentLoaded
) return;
283 $oldid = $this->getOldID();
284 $redirect = $wgRequest->getVal( 'redirect' );
286 $fname = 'Article::loadContent';
288 # Pre-fill content with error message so that if something
289 # fails we'll have something telling us what we intended.
291 $t = $this->mTitle
->getPrefixedText();
293 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no')
294 ||
$wgRequest->getCheck( 'rdfrom' );
295 $this->mOldId
= $oldid;
296 $this->fetchContent( $oldid, $noredir, true );
301 * Fetch a page record with the given conditions
302 * @param Database $dbr
303 * @param array $conditions
306 function pageData( &$dbr, $conditions ) {
307 return $dbr->selectRow( 'page',
321 'Article::pageData' );
324 function pageDataFromTitle( &$dbr, $title ) {
325 return $this->pageData( $dbr, array(
326 'page_namespace' => $title->getNamespace(),
327 'page_title' => $title->getDBkey() ) );
330 function pageDataFromId( &$dbr, $id ) {
331 return $this->pageData( $dbr, array(
332 'page_id' => IntVal( $id ) ) );
336 * Set the general counter, title etc data loaded from
339 * @param object $data
342 function loadPageData( $data ) {
343 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
344 $this->mTitle
->mRestrictionsLoaded
= true;
346 $this->mCounter
= $data->page_counter
;
347 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
348 $this->mIsRedirect
= $data->page_is_redirect
;
349 $this->mLatest
= $data->page_latest
;
351 $this->mDataLoaded
= true;
355 * Get text of an article from database
356 * @param int $oldid 0 for whatever the latest revision is
357 * @param bool $noredir Set to false to follow redirects
358 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
361 function fetchContent( $oldid = 0, $noredir = true, $globalTitle = false ) {
362 if ( $this->mContentLoaded
) {
363 return $this->mContent
;
365 $dbr =& $this->getDB();
366 $fname = 'Article::fetchContent';
368 # Pre-fill content with error message so that if something
369 # fails we'll have something telling us what we intended.
370 $t = $this->mTitle
->getPrefixedText();
372 $t .= ',oldid='.$oldid;
374 if( isset( $redirect ) ) {
375 $redirect = ($redirect == 'no') ?
'no' : 'yes';
376 $t .= ',redirect='.$redirect;
378 $this->mContent
= wfMsg( 'missingarticle', $t );
381 $revision = Revision
::newFromId( $oldid );
382 if( is_null( $revision ) ) {
383 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
386 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
388 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
391 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
392 $this->loadPageData( $data );
394 if( !$this->mDataLoaded
) {
395 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
397 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
400 $this->loadPageData( $data );
402 $revision = Revision
::newFromId( $this->mLatest
);
403 if( is_null( $revision ) ) {
404 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
409 # If we got a redirect, follow it (unless we've been told
410 # not to by either the function parameter or the query
411 if ( !$oldid && !$noredir ) {
412 $rt = Title
::newFromRedirect( $revision->getText() );
413 # process if title object is valid and not special:userlogout
414 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
415 # Gotta hand redirects to special pages differently:
416 # Fill the HTTP response "Location" header and ignore
417 # the rest of the page we're on.
418 global $wgDisableHardRedirects;
419 if( $globalTitle && !$wgDisableHardRedirects ) {
421 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
422 $source = $this->mTitle
->getFullURL( 'redirect=no' );
423 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
426 if ( $rt->getNamespace() == NS_SPECIAL
) {
427 $wgOut->redirect( $rt->getFullURL() );
431 $redirData = $this->pageDataFromTitle( $dbr, $rt );
433 $redirRev = Revision
::newFromId( $redirData->page_latest
);
434 if( !is_null( $redirRev ) ) {
435 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
438 $this->loadPageData( $data );
439 $revision = $redirRev;
445 # if the title's different from expected, update...
448 if( !$this->mTitle
->equals( $wgTitle ) ) {
449 $wgTitle = $this->mTitle
;
453 # Back to the business at hand...
454 $this->mContent
= $revision->getText();
456 $this->mUser
= $revision->getUser();
457 $this->mUserText
= $revision->getUserText();
458 $this->mComment
= $revision->getComment();
459 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
461 $this->mRevIdFetched
= $revision->getID();
462 $this->mContentLoaded
= true;
463 $this->mRevision
=& $revision;
465 return $this->mContent
;
469 * Gets the article text without using so many damn globals
470 * Returns false on error
472 * @param integer $oldid
474 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
475 return $this->fetchContent( $oldid, $noredir, false );
479 * Read/write accessor to select FOR UPDATE
481 function forUpdate( $x = NULL ) {
482 return wfSetVar( $this->mForUpdate
, $x );
486 * Get the database which should be used for reads
489 #if ( $this->mForUpdate ) {
490 return wfGetDB( DB_MASTER
);
492 # return wfGetDB( DB_SLAVE );
497 * Get options for all SELECT statements
498 * Can pass an option array, to which the class-wide options will be appended
500 function getSelectOptions( $options = '' ) {
501 if ( $this->mForUpdate
) {
502 if ( is_array( $options ) ) {
503 $options[] = 'FOR UPDATE';
505 $options = 'FOR UPDATE';
512 * Return the Article ID
515 if( $this->mTitle
) {
516 return $this->mTitle
->getArticleID();
523 * Returns true if this article exists in the database.
527 return $this->getId() != 0;
531 * Get the view count for this article
533 function getCount() {
534 if ( -1 == $this->mCounter
) {
535 $id = $this->getID();
536 $dbr =& $this->getDB();
537 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
538 'Article::getCount', $this->getSelectOptions() );
540 return $this->mCounter
;
544 * Would the given text make this article a "good" article (i.e.,
545 * suitable for including in the article count)?
546 * @param string $text Text to analyze
547 * @return integer 1 if it can be counted else 0
549 function isCountable( $text ) {
550 global $wgUseCommaCount;
552 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
553 if ( $this->isRedirect( $text ) ) { return 0; }
554 $token = ($wgUseCommaCount ?
',' : '[[' );
555 if ( false === strstr( $text, $token ) ) { return 0; }
560 * Tests if the article text represents a redirect
562 function isRedirect( $text = false ) {
563 if ( $text === false ) {
564 $this->loadContent();
565 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
567 $titleObj = Title
::newFromRedirect( $text );
569 return $titleObj !== NULL;
573 * Returns true if the currently-referenced revision is the current edit
574 * to this page (and it exists).
577 function isCurrent() {
578 return $this->exists() &&
579 isset( $this->mRevision
) &&
580 $this->mRevision
->isCurrent();
584 * Loads everything except the text
585 * This isn't necessary for all uses, so it's only done if needed.
588 function loadLastEdit() {
591 if ( -1 != $this->mUser
)
594 # New or non-existent articles have no user information
595 $id = $this->getID();
596 if ( 0 == $id ) return;
598 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
599 if( !is_null( $this->mLastRevision
) ) {
600 $this->mUser
= $this->mLastRevision
->getUser();
601 $this->mUserText
= $this->mLastRevision
->getUserText();
602 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
603 $this->mComment
= $this->mLastRevision
->getComment();
604 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
608 function getTimestamp() {
609 $this->loadLastEdit();
610 return $this->mTimestamp
;
614 $this->loadLastEdit();
618 function getUserText() {
619 $this->loadLastEdit();
620 return $this->mUserText
;
623 function getComment() {
624 $this->loadLastEdit();
625 return $this->mComment
;
628 function getMinorEdit() {
629 $this->loadLastEdit();
630 return $this->mMinorEdit
;
633 function getRevIdFetched() {
634 $this->loadLastEdit();
635 return $this->mRevIdFetched
;
638 function getContributors($limit = 0, $offset = 0) {
639 $fname = 'Article::getContributors';
641 # XXX: this is expensive; cache this info somewhere.
643 $title = $this->mTitle
;
645 $dbr =& $this->getDB();
646 $revTable = $dbr->tableName( 'revision' );
647 $userTable = $dbr->tableName( 'user' );
648 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
649 $ns = $title->getNamespace();
650 $user = $this->getUser();
651 $pageId = $this->getId();
653 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
654 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
655 WHERE rev_page = $pageId
656 AND rev_user != $user
657 GROUP BY rev_user, rev_user_text, user_real_name
658 ORDER BY timestamp DESC";
660 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
661 $sql .= ' '. $this->getSelectOptions();
663 $res = $dbr->query($sql, $fname);
665 while ( $line = $dbr->fetchObject( $res ) ) {
666 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
669 $dbr->freeResult($res);
674 * This is the default action of the script: just view the page of
678 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
679 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
680 global $wgEnotif, $wgParser, $wgParserCache;
681 $sk = $wgUser->getSkin();
683 $fname = 'Article::view';
684 wfProfileIn( $fname );
685 # Get variables from query string
686 $oldid = $this->getOldID();
687 $diff = $wgRequest->getVal( 'diff' );
688 $rcid = $wgRequest->getVal( 'rcid' );
689 $rdfrom = $wgRequest->getVal( 'rdfrom' );
691 $wgOut->setArticleFlag( true );
692 $wgOut->setRobotpolicy( 'index,follow' );
693 # If we got diff and oldid in the query, we want to see a
694 # diff page instead of the article.
696 if ( !is_null( $diff ) ) {
697 require_once( 'DifferenceEngine.php' );
698 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
700 $de = new DifferenceEngine( $oldid, $diff, $rcid );
701 // DifferenceEngine directly fetched the revision:
702 $this->mRevIdFetched
= $de->mNewid
;
706 # Run view updates for current revision only
707 $this->viewUpdates();
709 wfProfileOut( $fname );
713 if ( empty( $oldid ) && $this->checkTouched() ) {
714 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
716 if( $wgOut->checkLastModified( $this->mTouched
) ){
717 wfProfileOut( $fname );
719 } else if ( $this->tryFileCache() ) {
720 # tell wgOut that output is taken care of
722 $this->viewUpdates();
723 wfProfileOut( $fname );
727 # Should the parser cache be used?
728 $pcache = $wgEnableParserCache &&
729 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
732 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
736 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
740 if ( !$outputDone ) {
741 $text = $this->getContent( false ); # May change mTitle by following a redirect
743 # Another whitelist check in case oldid or redirects are altering the title
744 if ( !$this->mTitle
->userCanRead() ) {
745 $wgOut->loginToUse();
750 # We're looking at an old revision
752 if ( !empty( $oldid ) ) {
753 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
754 $wgOut->setRobotpolicy( 'noindex,follow' );
756 if ( '' != $this->mRedirectedFrom
) {
757 $sk = $wgUser->getSkin();
758 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
760 $s = wfMsg( 'redirectedfrom', $redir );
761 $wgOut->setSubtitle( $s );
763 # Can't cache redirects
765 } elseif ( !empty( $rdfrom ) ) {
766 global $wgRedirectSources;
767 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
768 $sk = $wgUser->getSkin();
769 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
770 $s = wfMsg( 'redirectedfrom', $redir );
771 $wgOut->setSubtitle( $s );
775 # wrap user css and user js in pre and don't parse
776 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
778 $this->mTitle
->getNamespace() == NS_USER
&&
779 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
781 $wgOut->addWikiText( wfMsg('clearyourcache'));
782 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
783 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
785 $imageUrl = $wgStylePath.'/common/images/redirect.png';
786 $targetUrl = $rt->escapeLocalURL();
787 $titleText = htmlspecialchars( $rt->getPrefixedText() );
788 $link = $sk->makeLinkObj( $rt );
790 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
791 '<span class="redirectText">'.$link.'</span>' );
793 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
794 $catlinks = $parseout->getCategoryLinks();
795 $wgOut->addCategoryLinks($catlinks);
796 $skin = $wgUser->getSkin();
797 } else if ( $pcache ) {
798 # Display content and save to parser cache
799 $wgOut->addPrimaryWikiText( $text, $this );
801 # Display content, don't attempt to save to parser cache
803 # Don't show section-edit links on old revisions... this way lies madness.
804 if( !$this->isCurrent() ) {
805 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
807 $wgOut->addWikiText( $text );
809 if( !$this->isCurrent() ) {
810 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
814 /* title may have been set from the cache */
815 $t = $wgOut->getPageTitle();
817 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
820 # If we have been passed an &rcid= parameter, we want to give the user a
821 # chance to mark this new article as patrolled.
825 && $wgUser->isLoggedIn()
826 && ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
829 "<div class='patrollink'>" .
830 wfMsg ( 'markaspatrolledlink',
831 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
837 # Put link titles into the link cache
838 $wgOut->transformBuffer();
840 # Add link titles as META keywords
841 $wgOut->addMetaTags() ;
843 $this->viewUpdates();
844 wfProfileOut( $fname );
850 $wgOut->setArticleBodyOnly(true);
855 * Insert a new empty page record for this article.
856 * This *must* be followed up by creating a revision
857 * and running $this->updateToLatest( $rev_id );
858 * or else the record will be left in a funky state.
859 * Best if all done inside a transaction.
861 * @param Database $dbw
862 * @param string $restrictions
863 * @return int The newly created page_id key
866 function insertOn( &$dbw, $restrictions = '' ) {
867 $fname = 'Article::insertOn';
868 wfProfileIn( $fname );
870 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
871 $dbw->insert( 'page', array(
872 'page_id' => $page_id,
873 'page_namespace' => $this->mTitle
->getNamespace(),
874 'page_title' => $this->mTitle
->getDBkey(),
876 'page_restrictions' => $restrictions,
877 'page_is_redirect' => 0, # Will set this shortly...
879 'page_random' => wfRandom(),
880 'page_touched' => $dbw->timestamp(),
881 'page_latest' => 0, # Fill this in shortly...
883 $newid = $dbw->insertId();
885 $this->mTitle
->resetArticleId( $newid );
887 wfProfileOut( $fname );
892 * Update the page record to point to a newly saved revision.
894 * @param Database $dbw
895 * @param Revision $revision -- for ID number, and text used to set
896 length and redirect status fields
897 * @param int $lastRevision -- if given, will not overwrite the page field
898 * when different from the currently set value.
899 * Giving 0 indicates the new page flag should
901 * @return bool true on success, false on failure
904 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
905 $fname = 'Article::updateToRevision';
906 wfProfileIn( $fname );
908 $conditions = array( 'page_id' => $this->getId() );
909 if( !is_null( $lastRevision ) ) {
910 # An extra check against threads stepping on each other
911 $conditions['page_latest'] = $lastRevision;
913 $text = $revision->getText();
914 $dbw->update( 'page',
916 'page_latest' => $revision->getId(),
917 'page_touched' => $dbw->timestamp(),
918 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
919 'page_is_redirect' => Article
::isRedirect( $text ),
920 'page_len' => strlen( $text ),
925 wfProfileOut( $fname );
926 return ( $dbw->affectedRows() != 0 );
930 * If the given revision is newer than the currently set page_latest,
931 * update the page record. Otherwise, do nothing.
933 * @param Database $dbw
934 * @param Revision $revision
936 function updateIfNewerOn( &$dbw, $revision ) {
937 $fname = 'Article::updateIfNewerOn';
938 wfProfileIn( $fname );
940 $row = $dbw->selectRow(
941 array( 'revision', 'page' ),
942 array( 'rev_id', 'rev_timestamp' ),
944 'page_id' => $this->getId(),
945 'page_latest=rev_id' ),
948 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
949 wfProfileOut( $fname );
952 $prev = $row->rev_id
;
954 # No or missing previous revision; mark the page as new
958 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
959 wfProfileOut( $fname );
964 * Theoretically we could defer these whole insert and update
965 * functions for after display, but that's taking a big leap
966 * of faith, and we want to be able to report database
967 * errors at some point.
970 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
971 global $wgOut, $wgUser;
972 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
974 $fname = 'Article::insertNewArticle';
976 $this->mGoodAdjustment
= $this->isCountable( $text );
977 $this->mTotalAdjustment
= 1;
979 $ns = $this->mTitle
->getNamespace();
980 $ttl = $this->mTitle
->getDBkey();
982 # If this is a comment, add the summary as headline
983 if($comment && $summary!="") {
984 $text="== {$summary} ==\n\n".$text;
986 $text = $this->preSaveTransform( $text );
987 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
988 $now = wfTimestampNow();
990 $dbw =& wfGetDB( DB_MASTER
);
992 # Add the page record; stake our claim on this title!
993 $newid = $this->insertOn( $dbw );
995 # Save the revision text...
996 $revision = new Revision( array(
998 'comment' => $summary,
999 'minor_edit' => $isminor,
1002 $revisionId = $revision->insertOn( $dbw );
1004 $this->mTitle
->resetArticleID( $newid );
1006 # Update the page record with revision data
1007 $this->updateRevisionOn( $dbw, $revision, 0 );
1009 Article
::onArticleCreate( $this->mTitle
);
1011 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1012 '', strlen( $text ), $revisionId );
1016 if(!$this->mTitle
->userIsWatching()) $this->watch();
1018 if ( $this->mTitle
->userIsWatching() ) {
1023 # The talk page isn't in the regular link tables, so we need to update manually:
1024 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1025 $dbw->update( 'page',
1026 array( 'page_touched' => $dbw->timestamp($now) ),
1027 array( 'page_namespace' => $talkns,
1028 'page_title' => $ttl ),
1031 # standard deferred updates
1032 $this->editUpdates( $text, $summary, $isminor, $now );
1034 $oldid = 0; # new article
1035 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1038 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1039 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
1040 if ($section != '') {
1041 if( is_null( $edittime ) ) {
1042 $rev = Revision
::newFromTitle( $this->mTitle
);
1044 $dbw =& wfGetDB( DB_MASTER
);
1045 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1047 $oldtext = $rev->getText();
1049 if($section=='new') {
1050 if($summary) $subject="== {$summary} ==\n\n";
1051 $text=$oldtext."\n\n".$subject.$text;
1054 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1055 # comments to be stripped as well)
1056 $striparray=array();
1057 $parser=new Parser();
1058 $parser->mOutputType
=OT_WIKI
;
1059 $oldtext=$parser->strip($oldtext, $striparray, true);
1061 # now that we can be sure that no pseudo-sections are in the source,
1063 # Unfortunately we can't simply do a preg_replace because that might
1064 # replace the wrong section, so we have to use the section counter instead
1065 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1066 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1067 $secs[$section*2]=$text."\n\n"; // replace with edited
1069 # section 0 is top (intro) section
1072 # headline of old section - we need to go through this section
1073 # to determine if there are any subsections that now need to
1074 # be erased, as the mother section has been replaced with
1075 # the text of all subsections.
1076 $headline=$secs[$section*2-1];
1077 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1078 $hlevel=$matches[1];
1080 # determine headline level for wikimarkup headings
1081 if(strpos($hlevel,'=')!==false) {
1082 $hlevel=strlen($hlevel);
1085 $secs[$section*2-1]=''; // erase old headline
1088 while(!empty($secs[$count*2-1]) && !$break) {
1090 $subheadline=$secs[$count*2-1];
1092 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1093 $subhlevel=$matches[1];
1094 if(strpos($subhlevel,'=')!==false) {
1095 $subhlevel=strlen($subhlevel);
1097 if($subhlevel > $hlevel) {
1098 // erase old subsections
1099 $secs[$count*2-1]='';
1102 if($subhlevel <= $hlevel) {
1110 $text=join('',$secs);
1111 # reinsert the stuff that we stripped out earlier
1112 $text=$parser->unstrip($text,$striparray);
1113 $text=$parser->unstripNoWiki($text,$striparray);
1121 * Change an existing article. Puts the previous version back into the old table, updates RC
1122 * and all necessary caches, mostly via the deferred update array.
1124 * It is possible to call this function from a command-line script, but note that you should
1125 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1127 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1128 global $wgOut, $wgUser;
1129 global $wgDBtransactions, $wgMwRedir;
1130 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1132 $fname = 'Article::updateArticle';
1135 $isminor = ( $minor && $wgUser->isLoggedIn() );
1136 if ( $this->isRedirect( $text ) ) {
1137 # Remove all content but redirect
1138 # This could be done by reconstructing the redirect from a title given by
1139 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1141 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1143 $text = $m[1] . "\n";
1146 else { $redir = 0; }
1148 $text = $this->preSaveTransform( $text );
1149 $dbw =& wfGetDB( DB_MASTER
);
1150 $now = wfTimestampNow();
1152 # Update article, but only if changed.
1154 # It's important that we either rollback or complete, otherwise an attacker could
1155 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1156 # could conceivably have the same effect, especially if cur is locked for long periods.
1157 if( !$wgDBtransactions ) {
1158 $userAbort = ignore_user_abort( true );
1161 $oldtext = $this->getContent( true );
1162 $oldsize = strlen( $oldtext );
1163 $newsize = strlen( $text );
1166 if ( 0 != strcmp( $text, $oldtext ) ) {
1167 $this->mGoodAdjustment
= $this->isCountable( $text )
1168 - $this->isCountable( $oldtext );
1169 $this->mTotalAdjustment
= 0;
1170 $now = wfTimestampNow();
1172 $lastRevision = $dbw->selectField(
1173 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1175 $revision = new Revision( array(
1176 'page' => $this->getId(),
1177 'comment' => $summary,
1178 'minor_edit' => $isminor,
1181 $revisionId = $revision->insertOn( $dbw );
1184 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1187 /* Belated edit conflict! Run away!! */
1190 # Update recentchanges and purge cache and whatnot
1191 $bot = (int)($wgUser->isBot() ||
$forceBot);
1192 RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1193 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1195 Article
::onArticleEdit( $this->mTitle
);
1199 if( !$wgDBtransactions ) {
1200 ignore_user_abort( $userAbort );
1205 if (!$this->mTitle
->userIsWatching()) $this->watch();
1207 if ( $this->mTitle
->userIsWatching() ) {
1211 # standard deferred updates
1212 $this->editUpdates( $text, $summary, $minor, $now );
1216 # Template namespace
1217 # Purge all articles linking here
1218 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1219 $titles = $this->mTitle
->getLinksTo();
1220 Title
::touchArray( $titles );
1221 if ( $wgUseSquid ) {
1222 foreach ( $titles as $title ) {
1223 $urls[] = $title->getInternalURL();
1229 if ( $wgUseSquid ) {
1230 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1231 $u = new SquidUpdate( $urls );
1232 array_push( $wgPostCommitUpdateList, $u );
1235 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1241 * After we've either updated or inserted the article, update
1242 * the link tables and redirect to the new page.
1244 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1245 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1246 global $wgUseEnotif;
1248 $wgLinkCache = new LinkCache();
1250 if ( !$wgUseDumbLinkUpdate ) {
1251 # Preload links to reduce lock time
1252 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS
) {
1253 $wgLinkCache->preFill( $this->mTitle
);
1254 $wgLinkCache->clear();
1258 # Parse the text and replace links with placeholders
1259 $wgOut = new OutputPage();
1261 # Pass the current title along in case we're creating a wiki page
1262 # which is different than the currently displayed one (e.g. image
1263 # pages created on file uploads); otherwise, link updates will
1265 $wgOut->addWikiTextWithTitle( $text, $this->mTitle
);
1267 if ( !$wgUseDumbLinkUpdate ) {
1268 # Move the current links back to the second register
1269 $wgLinkCache->swapRegisters();
1271 # Get old version of link table to allow incremental link updates
1272 # Lock this data now since it is needed for an update
1273 $wgLinkCache->forUpdate( true );
1274 $wgLinkCache->preFill( $this->mTitle
);
1276 # Swap this old version back into its rightful place
1277 $wgLinkCache->swapRegisters();
1280 if( $this->isRedirect( $text ) )
1284 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1286 if ( $wgUseEnotif ) {
1287 # this would be better as an extension hook
1288 include_once( "UserMailer.php" );
1289 $wgEnotif = new EmailNotification ();
1290 $wgEnotif->notifyOnPageChange( $this->mTitle
, $now, $summary, $me2, $oldid );
1295 * Mark this particular edit as patrolled
1297 function markpatrolled() {
1298 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1299 $wgOut->setRobotpolicy( 'noindex,follow' );
1301 if ( !$wgUseRCPatrol )
1303 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1306 if ( $wgUser->isAnon() )
1308 $wgOut->loginToUse();
1311 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1313 $wgOut->sysopRequired();
1316 $rcid = $wgRequest->getVal( 'rcid' );
1317 if ( !is_null ( $rcid ) )
1319 RecentChange
::markPatrolled( $rcid );
1320 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1321 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1323 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1324 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1328 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1335 function validate() {
1336 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1338 if ( !$wgUseValidation ) # Are we using article validation at all?
1340 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1344 $wgOut->setRobotpolicy( 'noindex,follow' );
1345 $revision = $wgRequest->getVal( 'revision' );
1347 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1349 $v = new Validation
;
1350 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1351 $t = $v->showList ( $this ) ;
1352 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1353 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1355 $t = $v->validatePageForm ( $this , $revision ) ;
1357 $wgOut->addHTML ( $t ) ;
1361 * Add this page to $wgUser's watchlist
1366 global $wgUser, $wgOut;
1368 if ( $wgUser->isAnon() ) {
1369 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1372 if ( wfReadOnly() ) {
1373 $wgOut->readOnlyPage();
1377 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1379 $wgUser->addWatch( $this->mTitle
);
1380 $wgUser->saveSettings();
1382 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1384 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1385 $wgOut->setRobotpolicy( 'noindex,follow' );
1387 $link = $this->mTitle
->getPrefixedText();
1388 $text = wfMsg( 'addedwatchtext', $link );
1389 $wgOut->addWikiText( $text );
1392 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1396 * Stop watching a page
1399 function unwatch() {
1401 global $wgUser, $wgOut;
1403 if ( $wgUser->isAnon() ) {
1404 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1407 if ( wfReadOnly() ) {
1408 $wgOut->readOnlyPage();
1412 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1414 $wgUser->removeWatch( $this->mTitle
);
1415 $wgUser->saveSettings();
1417 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1419 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1420 $wgOut->setRobotpolicy( 'noindex,follow' );
1422 $link = $this->mTitle
->getPrefixedText();
1423 $text = wfMsg( 'removedwatchtext', $link );
1424 $wgOut->addWikiText( $text );
1427 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1433 function protect( $limit = 'sysop' ) {
1434 global $wgUser, $wgOut, $wgRequest;
1436 if ( ! $wgUser->isAllowed('protect') ) {
1437 $wgOut->sysopRequired();
1440 if ( wfReadOnly() ) {
1441 $wgOut->readOnlyPage();
1444 $id = $this->mTitle
->getArticleID();
1446 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1450 $confirm = $wgRequest->wasPosted() &&
1451 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1452 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1453 $reason = $wgRequest->getText( 'wpReasonProtect' );
1456 $dbw =& wfGetDB( DB_MASTER
);
1457 $dbw->update( 'page',
1459 'page_touched' => $dbw->timestamp(),
1460 'page_restrictions' => (string)$limit
1461 ), array( /* WHERE */
1463 ), 'Article::protect'
1466 $restrictions = "move=" . $limit;
1468 $restrictions .= ":edit=" . $limit;
1470 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1472 $dbw =& wfGetDB( DB_MASTER
);
1473 $dbw->update( 'page',
1475 'page_touched' => $dbw->timestamp(),
1476 'page_restrictions' => $restrictions
1477 ), array( /* WHERE */
1479 ), 'Article::protect'
1482 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1484 $log = new LogPage( 'protect' );
1485 if ( $limit === '' ) {
1486 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1488 $log->addEntry( 'protect', $this->mTitle
, $reason );
1490 $wgOut->redirect( $this->mTitle
->getFullURL() );
1494 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1495 return $this->confirmProtect( '', $reason, $limit );
1500 * Output protection confirmation dialog
1502 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1503 global $wgOut, $wgUser;
1505 wfDebug( "Article::confirmProtect\n" );
1507 $sub = $this->mTitle
->getPrefixedText();
1508 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1514 if ( $limit === '' ) {
1515 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1516 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1517 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1518 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1519 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1521 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1522 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1523 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1524 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1525 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1526 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1529 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1530 $token = htmlspecialchars( $wgUser->editToken() );
1533 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1537 <label for='wpReasonProtect'>{$protcom}:</label>
1540 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1543 if($moveonly != '') {
1547 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1550 <label for='wpMoveOnly'>{$moveonly}</label>
1558 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1562 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1565 $wgOut->returnToMain( false );
1569 * Unprotect the pages
1571 function unprotect() {
1572 return $this->protect( '' );
1576 * UI entry point for page deletion
1579 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1580 $fname = 'Article::delete';
1581 $confirm = $wgRequest->wasPosted() &&
1582 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1583 $reason = $wgRequest->getText( 'wpReason' );
1585 # This code desperately needs to be totally rewritten
1588 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1589 $wgOut->sysopRequired();
1592 if( wfReadOnly() ) {
1593 $wgOut->readOnlyPage();
1597 # Better double-check that it hasn't been deleted yet!
1598 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1599 if( !$this->mTitle
->exists() ) {
1600 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1605 $this->doDelete( $reason );
1609 # determine whether this page has earlier revisions
1610 # and insert a warning if it does
1611 # we select the text because it might be useful below
1612 $dbr =& $this->getDB();
1613 $ns = $this->mTitle
->getNamespace();
1614 $title = $this->mTitle
->getDBkey();
1615 $revisions = $dbr->select( array( 'page', 'revision' ),
1616 array( 'rev_id', 'rev_user_text' ),
1618 'page_namespace' => $ns,
1619 'page_title' => $title,
1620 'rev_page = page_id'
1621 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1624 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1625 $skin=$wgUser->getSkin();
1626 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1627 $wgOut->addHTML( $skin->historyLink() .'</b>');
1631 $rev =& Revision
::newFromTitle( $this->mTitle
);
1633 # Fetch name(s) of contributors
1635 $all_same_user = true;
1636 while( $row = $dbr->fetchObject( $revisions ) ) {
1637 if( $rev_name != '' && $rev_name != $row->rev_user_text
) {
1638 $all_same_user = false;
1640 $rev_name = $row->rev_user_text
;
1644 if( !is_null( $rev ) ) {
1645 # if this is a mini-text, we can paste part of it into the deletion reason
1646 $text = $rev->getText();
1648 #if this is empty, an earlier revision may contain "useful" text
1651 $prev = $rev->getPrevious();
1653 $text = $prev->getText();
1658 $length = strlen( $text );
1660 # this should not happen, since it is not possible to store an empty, new
1661 # page. Let's insert a standard text in case it does, though
1662 if( $length == 0 && $reason === '' ) {
1663 $reason = wfMsg( 'exblank' );
1666 if( $length < 500 && $reason === '' ) {
1667 # comment field=255, let's grep the first 150 to have some user
1670 $text = $wgContLang->truncate( $text, 150, '...' );
1672 # let's strip out newlines
1673 $text = preg_replace( "/[\n\r]/", '', $text );
1676 if( !$all_same_user ) {
1677 $reason = wfMsg( 'excontent', $text );
1679 $reason = wfMsg( 'excontentauthor', $text, $rev_name );
1682 $reason = wfMsg( 'exbeforeblank', $text );
1687 return $this->confirmDelete( '', $reason );
1691 * Output deletion confirmation dialog
1693 function confirmDelete( $par, $reason ) {
1694 global $wgOut, $wgUser;
1696 wfDebug( "Article::confirmDelete\n" );
1698 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1699 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1700 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1701 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1703 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1705 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1706 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1707 $token = htmlspecialchars( $wgUser->editToken() );
1710 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1714 <label for='wpReason'>{$delcom}:</label>
1717 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1723 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1727 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1730 $wgOut->returnToMain( false );
1735 * Perform a deletion and output success or failure messages
1737 function doDelete( $reason ) {
1738 global $wgOut, $wgUser, $wgContLang;
1739 $fname = 'Article::doDelete';
1740 wfDebug( $fname."\n" );
1742 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1743 if ( $this->doDeleteArticle( $reason ) ) {
1744 $deleted = $this->mTitle
->getPrefixedText();
1746 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1747 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1749 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1750 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1752 $wgOut->addWikiText( $text );
1753 $wgOut->returnToMain( false );
1754 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1756 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1762 * Back-end article deletion
1763 * Deletes the article with database consistency, writes logs, purges caches
1766 function doDeleteArticle( $reason ) {
1768 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1770 $fname = 'Article::doDeleteArticle';
1771 wfDebug( $fname."\n" );
1773 $dbw =& wfGetDB( DB_MASTER
);
1774 $ns = $this->mTitle
->getNamespace();
1775 $t = $this->mTitle
->getDBkey();
1776 $id = $this->mTitle
->getArticleID();
1778 if ( $t == '' ||
$id == 0 ) {
1782 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1783 array_push( $wgDeferredUpdateList, $u );
1785 $linksTo = $this->mTitle
->getLinksTo();
1788 if ( $wgUseSquid ) {
1790 $this->mTitle
->getInternalURL(),
1791 $this->mTitle
->getInternalURL( 'history' )
1794 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
1795 array_push( $wgPostCommitUpdateList, $u );
1799 # Client and file cache invalidation
1800 Title
::touchArray( $linksTo );
1803 // For now, shunt the revision data into the archive table.
1804 // Text is *not* removed from the text table; bulk storage
1805 // is left intact to avoid breaking block-compression or
1806 // immutable storage schemes.
1808 // For backwards compatibility, note that some older archive
1809 // table entries will have ar_text and ar_flags fields still.
1811 // In the future, we may keep revisions and mark them with
1812 // the rev_deleted field, which is reserved for this purpose.
1813 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1815 'ar_namespace' => 'page_namespace',
1816 'ar_title' => 'page_title',
1817 'ar_comment' => 'rev_comment',
1818 'ar_user' => 'rev_user',
1819 'ar_user_text' => 'rev_user_text',
1820 'ar_timestamp' => 'rev_timestamp',
1821 'ar_minor_edit' => 'rev_minor_edit',
1822 'ar_rev_id' => 'rev_id',
1823 'ar_text_id' => 'rev_text_id',
1826 'page_id = rev_page'
1830 # Now that it's safely backed up, delete it
1831 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1832 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1834 # Clean up recentchanges entries...
1835 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1837 # Finally, clean up the link tables
1838 $t = $this->mTitle
->getPrefixedDBkey();
1840 Article
::onArticleDelete( $this->mTitle
);
1842 # Delete outgoing links
1843 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1844 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1845 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1848 $log = new LogPage( 'delete' );
1849 $log->addEntry( 'delete', $this->mTitle
, $reason );
1851 # Clear the cached article id so the interface doesn't act like we exist
1852 $this->mTitle
->resetArticleID( 0 );
1853 $this->mTitle
->mArticleID
= 0;
1858 * Revert a modification
1860 function rollback() {
1861 global $wgUser, $wgOut, $wgRequest;
1862 $fname = 'Article::rollback';
1864 if ( ! $wgUser->isAllowed('rollback') ) {
1865 $wgOut->sysopRequired();
1868 if ( wfReadOnly() ) {
1869 $wgOut->readOnlyPage( $this->getContent( true ) );
1872 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1873 array( $this->mTitle
->getPrefixedText(),
1874 $wgRequest->getVal( 'from' ) ) ) ) {
1875 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1876 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1879 $dbw =& wfGetDB( DB_MASTER
);
1881 # Enhanced rollback, marks edits rc_bot=1
1882 $bot = $wgRequest->getBool( 'bot' );
1884 # Replace all this user's current edits with the next one down
1885 $tt = $this->mTitle
->getDBKey();
1886 $n = $this->mTitle
->getNamespace();
1888 # Get the last editor, lock table exclusively
1890 $current = Revision
::newFromTitle( $this->mTitle
);
1891 if( is_null( $current ) ) {
1892 # Something wrong... no page?
1894 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1898 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1899 if( $from != $current->getUserText() ) {
1900 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1901 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1902 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1903 htmlspecialchars( $from ),
1904 htmlspecialchars( $current->getUserText() ) ) );
1905 if( $current->getComment() != '') {
1907 wfMsg( 'editcomment',
1908 htmlspecialchars( $current->getComment() ) ) );
1913 # Get the last edit not by this guy
1914 $user = IntVal( $current->getUser() );
1915 $user_text = $dbw->addQuotes( $current->getUserText() );
1916 $s = $dbw->selectRow( 'revision',
1917 array( 'rev_id', 'rev_timestamp' ),
1919 'rev_page' => $current->getPage(),
1920 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1923 'USE INDEX' => 'page_timestamp',
1924 'ORDER BY' => 'rev_timestamp DESC' )
1926 if( $s === false ) {
1929 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1930 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1935 # Mark all reverted edits as bot
1936 $dbw->update( 'recentchanges',
1939 ), array( /* WHERE */
1940 'rc_cur_id' => $current->getPage(),
1941 'rc_user_text' => $current->getUserText(),
1942 "rc_timestamp > '{$s->rev_timestamp}'",
1948 $target = Revision
::newFromId( $s->rev_id
);
1949 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1951 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1952 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1953 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1955 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1956 Article
::onArticleEdit( $this->mTitle
);
1959 $wgOut->returnToMain( false );
1964 * Do standard deferred updates after page view
1967 function viewUpdates() {
1968 global $wgDeferredUpdateList, $wgUseEnotif;
1970 if ( 0 != $this->getID() ) {
1971 global $wgDisableCounters;
1972 if( !$wgDisableCounters ) {
1973 Article
::incViewCount( $this->getID() );
1974 $u = new SiteStatsUpdate( 1, 0, 0 );
1975 array_push( $wgDeferredUpdateList, $u );
1979 # Update newtalk status if user is reading their own
1983 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1984 $this->mTitle
->getText() == $wgUser->getName())
1986 if ( $wgUseEnotif ) {
1987 require_once( 'UserTalkUpdate.php' );
1988 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1990 $wgUser->setNewtalk(0);
1991 $wgUser->saveNewtalk();
1993 } elseif ( $wgUseEnotif ) {
1994 $wgUser->clearNotification( $this->mTitle
);
2000 * Do standard deferred updates after page edit.
2001 * Every 1000th edit, prune the recent changes table.
2003 * @param string $text
2005 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2006 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
2007 global $wgMessageCache, $wgUser, $wgUseEnotif;
2010 if ( 0 == mt_rand( 0, 999 ) ) {
2011 # Periodically flush old entries from the recentchanges table.
2013 $dbw =& wfGetDB( DB_MASTER
);
2014 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2015 $recentchanges = $dbw->tableName( 'recentchanges' );
2016 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2017 $dbw->query( $sql );
2019 $id = $this->getID();
2020 $title = $this->mTitle
->getPrefixedDBkey();
2021 $shortTitle = $this->mTitle
->getDBkey();
2024 $u = new LinksUpdate( $id, $title );
2025 array_push( $wgDeferredUpdateList, $u );
2026 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2027 array_push( $wgDeferredUpdateList, $u );
2028 $u = new SearchUpdate( $id, $title, $text );
2029 array_push( $wgDeferredUpdateList, $u );
2031 # If this is another user's talk page, update newtalk
2033 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2034 if ( $wgUseEnotif ) {
2035 require_once( 'UserTalkUpdate.php' );
2036 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary,
2037 $minoredit, $timestamp_of_pagechange);
2039 $other = User
::newFromName( $shortTitle );
2040 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2041 // An anonymous user
2042 $other = new User();
2043 $other->setName( $shortTitle );
2046 $other->setNewtalk(1);
2047 $other->saveNewtalk();
2052 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2053 $wgMessageCache->replace( $shortTitle, $text );
2059 * @todo document this function
2061 * @param string $oldid Revision ID of this article revision
2063 function setOldSubtitle( $oldid=0 ) {
2064 global $wgLang, $wgOut, $wgUser;
2066 $current = ( $oldid == $this->mLatest
);
2067 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2068 $sk = $wgUser->getSkin();
2070 ?
wfMsg( 'currentrevisionlink' )
2071 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2072 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2073 $nextlink = $current
2074 ?
wfMsg( 'nextrevision' )
2075 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2076 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2077 $wgOut->setSubtitle( $r );
2081 * This function is called right before saving the wikitext,
2082 * so we can do things like signatures and links-in-context.
2084 * @param string $text
2086 function preSaveTransform( $text ) {
2087 global $wgParser, $wgUser;
2088 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2091 /* Caching functions */
2094 * checkLastModified returns true if it has taken care of all
2095 * output to the client that is necessary for this request.
2096 * (that is, it has sent a cached version of the page)
2098 function tryFileCache() {
2099 static $called = false;
2101 wfDebug( " tryFileCache() -- called twice!?\n" );
2105 if($this->isFileCacheable()) {
2106 $touched = $this->mTouched
;
2107 $cache = new CacheManager( $this->mTitle
);
2108 if($cache->isFileCacheGood( $touched )) {
2110 wfDebug( " tryFileCache() - about to load\n" );
2111 $cache->loadFromFileCache();
2114 wfDebug( " tryFileCache() - starting buffer\n" );
2115 ob_start( array(&$cache, 'saveToFileCache' ) );
2118 wfDebug( " tryFileCache() - not cacheable\n" );
2123 * Check if the page can be cached
2126 function isFileCacheable() {
2127 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2128 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2130 return $wgUseFileCache
2131 and (!$wgShowIPinHeader)
2132 and ($this->getID() != 0)
2133 and ($wgUser->isAnon())
2134 and (!$wgUser->getNewtalk())
2135 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2136 and (empty( $action ) ||
$action == 'view')
2137 and (!isset($oldid))
2139 and (!isset($redirect))
2140 and (!isset($printable))
2141 and (!$this->mRedirectedFrom
);
2145 * Loads cur_touched and returns a value indicating if it should be used
2148 function checkTouched() {
2149 $fname = 'Article::checkTouched';
2150 if( !$this->mDataLoaded
) {
2151 $dbr =& $this->getDB();
2152 $data = $this->pageDataFromId( $dbr, $this->getId() );
2154 $this->loadPageData( $data );
2157 return !$this->mIsRedirect
;
2161 * Edit an article without doing all that other stuff
2162 * The article must already exist; link tables etc
2163 * are not updated, caches are not flushed.
2165 * @param string $text text submitted
2166 * @param string $comment comment submitted
2167 * @param bool $minor whereas it's a minor modification
2169 function quickEdit( $text, $comment = '', $minor = 0 ) {
2170 $fname = 'Article::quickEdit';
2171 wfProfileIn( $fname );
2173 $dbw =& wfGetDB( DB_MASTER
);
2175 $revision = new Revision( array(
2176 'page' => $this->getId(),
2178 'comment' => $comment,
2179 'minor_edit' => $minor ?
1 : 0,
2181 $revisionId = $revision->insertOn( $dbw );
2182 $this->updateRevisionOn( $dbw, $revision );
2185 wfProfileOut( $fname );
2189 * Used to increment the view counter
2192 * @param integer $id article id
2194 function incViewCount( $id ) {
2195 $id = intval( $id );
2196 global $wgHitcounterUpdateFreq;
2198 $dbw =& wfGetDB( DB_MASTER
);
2199 $pageTable = $dbw->tableName( 'page' );
2200 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2201 $acchitsTable = $dbw->tableName( 'acchits' );
2203 if( $wgHitcounterUpdateFreq <= 1 ){ //
2204 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2208 # Not important enough to warrant an error page in case of failure
2209 $oldignore = $dbw->ignoreErrors( true );
2211 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2213 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2214 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2215 # Most of the time (or on SQL errors), skip row count check
2216 $dbw->ignoreErrors( $oldignore );
2220 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2221 $row = $dbw->fetchObject( $res );
2222 $rown = intval( $row->n
);
2223 if( $rown >= $wgHitcounterUpdateFreq ){
2224 wfProfileIn( 'Article::incViewCount-collect' );
2225 $old_user_abort = ignore_user_abort( true );
2227 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2228 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2229 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2231 $dbw->query("DELETE FROM $hitcounterTable");
2232 $dbw->query('UNLOCK TABLES');
2233 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2234 'WHERE page_id = hc_id');
2235 $dbw->query("DROP TABLE $acchitsTable");
2237 ignore_user_abort( $old_user_abort );
2238 wfProfileOut( 'Article::incViewCount-collect' );
2240 $dbw->ignoreErrors( $oldignore );
2244 * The onArticle*() functions are supposed to be a kind of hooks
2245 * which should be called whenever any of the specified actions
2248 * This is a good place to put code to clear caches, for instance.
2250 * This is called on page move and undelete, as well as edit
2252 * @param $title_obj a title object
2255 function onArticleCreate($title_obj) {
2256 global $wgUseSquid, $wgPostCommitUpdateList;
2258 $title_obj->touchLinks();
2259 $titles = $title_obj->getLinksTo();
2262 if ( $wgUseSquid ) {
2263 $urls = $title_obj->getSquidURLs();
2264 foreach ( $titles as $linkTitle ) {
2265 $urls[] = $linkTitle->getInternalURL();
2267 $u = new SquidUpdate( $urls );
2268 array_push( $wgPostCommitUpdateList, $u );
2272 function onArticleDelete($title_obj) {
2273 $title_obj->touchLinks();
2276 function onArticleEdit($title_obj) {
2277 // This would be an appropriate place to purge caches.
2278 // Why's this not in here now?
2284 * Info about this page
2285 * Called for ?action=info when $wgAllowPageInfo is on.
2290 global $wgLang, $wgOut, $wgAllowPageInfo;
2291 $fname = 'Article::info';
2293 if ( !$wgAllowPageInfo ) {
2294 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2298 $page = $this->mTitle
->getSubjectPage();
2300 $wgOut->setPagetitle( $page->getPrefixedText() );
2301 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2303 # first, see if the page exists at all.
2304 $exists = $page->getArticleId() != 0;
2306 $wgOut->addHTML( wfMsg('noarticletext') );
2308 $dbr =& $this->getDB( DB_SLAVE
);
2310 'wl_title' => $page->getDBkey(),
2311 'wl_namespace' => $page->getNamespace() );
2312 $numwatchers = $dbr->selectField(
2317 $this->getSelectOptions() );
2319 $pageInfo = $this->pageCountInfo( $page );
2320 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2322 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2323 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2325 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2327 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2329 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2331 $wgOut->addHTML( '</ul>' );
2337 * Return the total number of edits and number of unique editors
2338 * on a given page. If page does not exist, returns false.
2340 * @param Title $title
2344 function pageCountInfo( $title ) {
2345 $id = $title->getArticleId();
2350 $dbr =& $this->getDB( DB_SLAVE
);
2352 $rev_clause = array( 'rev_page' => $id );
2353 $fname = 'Article::pageCountInfo';
2355 $edits = $dbr->selectField(
2360 $this->getSelectOptions() );
2362 $authors = $dbr->selectField(
2364 'COUNT(DISTINCT rev_user_text)',
2367 $this->getSelectOptions() );
2369 return array( 'edits' => $edits, 'authors' => $authors );
2373 * Return a list of templates used by this article.
2374 * Uses the links table to find the templates
2378 function getUsedTemplates() {
2380 $id = $this->mTitle
->getArticleID();
2382 $db =& wfGetDB( DB_SLAVE
);
2383 $res = $db->select( array( 'pagelinks' ),
2384 array( 'pl_title' ),
2387 'pl_namespace' => NS_TEMPLATE
),
2388 'Article:getUsedTemplates' );
2389 if ( false !== $res ) {
2390 if ( $db->numRows( $res ) ) {
2391 while ( $row = $db->fetchObject( $res ) ) {
2392 $result[] = $row->pl_title
;
2396 $db->freeResult( $res );