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 Wikipedia article and history.
19 * See design.doc 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, $mCountAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
41 * Constructor and clear the article
42 * @param mixed &$title
44 function Article( &$title ) {
45 $this->mTitle
=& $title;
50 * get the title object of the article
62 $this->mDataLoaded
= false;
63 $this->mContentLoaded
= false;
65 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
66 $this->mRedirectedFrom
= $this->mUserText
=
67 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
68 $this->mCountAdjustment
= 0;
69 $this->mTouched
= '19700101000000';
70 $this->mForUpdate
= false;
71 $this->mIsRedirect
= false;
72 $this->mRevIdFetched
= 0;
76 * Note that getContent/loadContent may follow redirects if
77 * not told otherwise, and so may cause a change to mTitle.
80 * @return Return the text of this revision
82 function getContent( $noredir ) {
85 # Get variables from query string :P
86 $action = $wgRequest->getText( 'action', 'view' );
87 $section = $wgRequest->getText( 'section' );
89 $fname = 'Article::getContent';
90 wfProfileIn( $fname );
92 if ( 0 == $this->getID() ) {
93 if ( 'edit' == $action ) {
94 wfProfileOut( $fname );
95 return ''; # was "newarticletext", now moved above the box)
97 wfProfileOut( $fname );
98 return wfMsg( 'noarticletext' );
100 $this->loadContent( $noredir );
101 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
102 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
103 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
106 wfProfileOut( $fname );
107 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
109 if($action=='edit') {
111 if($section=='new') {
112 wfProfileOut( $fname );
116 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
117 # comments to be stripped as well)
118 $rv=$this->getSection($this->mContent
,$section);
119 wfProfileOut( $fname );
123 wfProfileOut( $fname );
124 return $this->mContent
;
130 * This function returns the text of a section, specified by a number ($section).
131 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
132 * the first section before any such heading (section 0).
134 * If a section contains subsections, these are also returned.
136 * @param string $text text to look in
137 * @param integer $section section number
138 * @return string text of the requested section
140 function getSection($text,$section) {
142 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
143 # comments to be stripped as well)
145 $parser=new Parser();
146 $parser->mOutputType
=OT_WIKI
;
147 $striptext=$parser->strip($text, $striparray, true);
149 # now that we can be sure that no pseudo-sections are in the source,
150 # split it up by section
153 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
155 PREG_SPLIT_DELIM_CAPTURE
);
159 $headline=$secs[$section*2-1];
160 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
163 # translate wiki heading into level
164 if(strpos($hlevel,'=')!==false) {
165 $hlevel=strlen($hlevel);
168 $rv=$headline. $secs[$section*2];
172 while(!empty($secs[$count*2-1]) && !$break) {
174 $subheadline=$secs[$count*2-1];
175 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
176 $subhlevel=$matches[1];
177 if(strpos($subhlevel,'=')!==false) {
178 $subhlevel=strlen($subhlevel);
180 if($subhlevel > $hlevel) {
181 $rv.=$subheadline.$secs[$count*2];
183 if($subhlevel <= $hlevel) {
190 # reinsert stripped tags
191 $rv=$parser->unstrip($rv,$striparray);
192 $rv=$parser->unstripNoWiki($rv,$striparray);
199 * Return an array of the columns of the "cur"-table
201 function getContentFields() {
202 return $wgArticleContentFields = array(
203 'old_text','old_flags',
204 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
205 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
209 * Return the oldid of the article that is to be shown.
210 * For requests with a "direction", this is not the oldid of the
213 function getOldID() {
214 global $wgRequest, $wgOut;
217 if ( isset( $lastid ) ) {
221 $oldid = $wgRequest->getVal( 'oldid' );
222 if ( isset( $oldid ) ) {
223 $oldid = IntVal( $oldid );
224 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
225 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
229 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
231 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
232 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
241 return @$oldid; # "@" to be able to return "unset" without PHP complaining
246 * Load the revision (including cur_text) into this object
248 function loadContent( $noredir = false ) {
249 global $wgOut, $wgRequest;
251 if ( $this->mContentLoaded
) return;
254 $oldid = $this->getOldID();
255 $redirect = $wgRequest->getVal( 'redirect' );
257 $fname = 'Article::loadContent';
259 # Pre-fill content with error message so that if something
260 # fails we'll have something telling us what we intended.
262 $t = $this->mTitle
->getPrefixedText();
264 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no')
265 ||
$wgRequest->getCheck( 'rdfrom' );
266 $this->mOldId
= $oldid;
267 $this->fetchContent( $oldid, $noredir, true );
272 * Fetch a page record with the given conditions
273 * @param Database $dbr
274 * @param array $conditions
277 function pageData( &$dbr, $conditions ) {
278 return $dbr->selectRow( 'page',
292 'Article::pageData' );
295 function pageDataFromTitle( &$dbr, $title ) {
296 return $this->pageData( $dbr, array(
297 'page_namespace' => $title->getNamespace(),
298 'page_title' => $title->getDBkey() ) );
301 function pageDataFromId( &$dbr, $id ) {
302 return $this->pageData( $dbr, array(
303 'page_id' => IntVal( $id ) ) );
307 * Set the general counter, title etc data loaded from
310 * @param object $data
313 function loadPageData( $data ) {
314 $this->mTitle
->mRestrictions
= explode( ',', trim( $data->page_restrictions
) );
315 $this->mTitle
->mRestrictionsLoaded
= true;
317 $this->mCounter
= $data->page_counter
;
318 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
319 $this->mIsRedirect
= $data->page_is_redirect
;
320 $this->mLatest
= $data->page_latest
;
322 $this->mDataLoaded
= true;
326 * Get text of an article from database
327 * @param int $oldid 0 for whatever the latest revision is
328 * @param bool $noredir Set to true to avoid following redirects
329 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
332 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
333 if ( $this->mContentLoaded
) {
334 return $this->mContent
;
336 $dbr =& $this->getDB();
337 $fname = 'Article::fetchContent';
339 # Pre-fill content with error message so that if something
340 # fails we'll have something telling us what we intended.
341 $t = $this->mTitle
->getPrefixedText();
343 $t .= ',oldid='.$oldid;
345 if( isset( $redirect ) ) {
346 $redirect = ($redirect == 'no') ?
'no' : 'yes';
347 $t .= ',redirect='.$redirect;
349 $this->mContent
= wfMsg( 'missingarticle', $t );
352 $revision = Revision
::newFromId( $oldid );
353 if( is_null( $revision ) ) {
354 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
357 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
359 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
362 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
363 $this->loadPageData( $data );
365 if( !$this->mDataLoaded
) {
366 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
368 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
371 $this->loadPageData( $data );
373 $revision = Revision
::newFromId( $this->mLatest
);
374 if( is_null( $revision ) ) {
375 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
380 # If we got a redirect, follow it (unless we've been told
381 # not to by either the function parameter or the query
382 if ( !$oldid && !$noredir ) {
383 $rt = Title
::newFromRedirect( $revision->getText() );
384 # process if title object is valid and not special:userlogout
385 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
386 # Gotta hand redirects to special pages differently:
387 # Fill the HTTP response "Location" header and ignore
388 # the rest of the page we're on.
391 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
392 $source = $this->mTitle
->getFullURL( 'redirect=no' );
393 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
396 if ( $rt->getNamespace() == NS_SPECIAL
) {
397 $wgOut->redirect( $rt->getFullURL() );
401 $redirData = $this->pageDataFromTitle( $dbr, $rt );
403 $redirRev = Revision
::newFromId( $redirData->page_latest
);
404 if( !is_null( $redirRev ) ) {
405 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
408 $this->loadPageData( $data );
409 $revision = $redirRev;
415 # if the title's different from expected, update...
418 if( !$this->mTitle
->equals( $wgTitle ) ) {
419 $wgTitle = $this->mTitle
;
423 # Back to the business at hand...
424 $this->mContent
= $revision->getText();
426 $this->mUser
= $revision->getUser();
427 $this->mUserText
= $revision->getUserText();
428 $this->mComment
= $revision->getComment();
429 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
431 $this->mRevIdFetched
= $revision->getID();
432 $this->mContentLoaded
= true;
434 return $this->mContent
;
438 * Gets the article text without using so many damn globals
439 * Returns false on error
441 * @param integer $oldid
443 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
444 return $this->fetchContent( $oldid, $noredir, false );
448 * Read/write accessor to select FOR UPDATE
450 function forUpdate( $x = NULL ) {
451 return wfSetVar( $this->mForUpdate
, $x );
455 * Get the database which should be used for reads
458 #if ( $this->mForUpdate ) {
459 return wfGetDB( DB_MASTER
);
461 # return wfGetDB( DB_SLAVE );
466 * Get options for all SELECT statements
467 * Can pass an option array, to which the class-wide options will be appended
469 function getSelectOptions( $options = '' ) {
470 if ( $this->mForUpdate
) {
471 if ( is_array( $options ) ) {
472 $options[] = 'FOR UPDATE';
474 $options = 'FOR UPDATE';
481 * Return the Article ID
484 if( $this->mTitle
) {
485 return $this->mTitle
->getArticleID();
492 * Get the view count for this article
494 function getCount() {
495 if ( -1 == $this->mCounter
) {
496 $id = $this->getID();
497 $dbr =& $this->getDB();
498 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
499 'Article::getCount', $this->getSelectOptions() );
501 return $this->mCounter
;
505 * Would the given text make this article a "good" article (i.e.,
506 * suitable for including in the article count)?
507 * @param string $text Text to analyze
508 * @return integer 1 if it can be counted else 0
510 function isCountable( $text ) {
511 global $wgUseCommaCount;
513 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
514 if ( $this->isRedirect( $text ) ) { return 0; }
515 $token = ($wgUseCommaCount ?
',' : '[[' );
516 if ( false === strstr( $text, $token ) ) { return 0; }
521 * Tests if the article text represents a redirect
523 function isRedirect( $text = false ) {
524 if ( $text === false ) {
525 $this->loadContent();
526 $titleObj = Title
::newFromRedirect( $this->fetchRevisionText() );
528 $titleObj = Title
::newFromRedirect( $text );
530 return $titleObj !== NULL;
534 * Loads everything except the text
535 * This isn't necessary for all uses, so it's only done if needed.
538 function loadLastEdit() {
541 if ( -1 != $this->mUser
)
544 # New or non-existent articles have no user information
545 $id = $this->getID();
546 if ( 0 == $id ) return;
548 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
549 if( !is_null( $this->mLastRevision
) ) {
550 $this->mUser
= $this->mLastRevision
->getUser();
551 $this->mUserText
= $this->mLastRevision
->getUserText();
552 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
553 $this->mComment
= $this->mLastRevision
->getComment();
554 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
558 function getTimestamp() {
559 $this->loadLastEdit();
560 return $this->mTimestamp
;
564 $this->loadLastEdit();
568 function getUserText() {
569 $this->loadLastEdit();
570 return $this->mUserText
;
573 function getComment() {
574 $this->loadLastEdit();
575 return $this->mComment
;
578 function getMinorEdit() {
579 $this->loadLastEdit();
580 return $this->mMinorEdit
;
583 function getRevIdFetched() {
584 $this->loadLastEdit();
585 return $this->mRevIdFetched
;
588 function getContributors($limit = 0, $offset = 0) {
589 $fname = 'Article::getContributors';
591 # XXX: this is expensive; cache this info somewhere.
593 $title = $this->mTitle
;
595 $dbr =& $this->getDB();
596 $revTable = $dbr->tableName( 'revision' );
597 $userTable = $dbr->tableName( 'user' );
598 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
599 $ns = $title->getNamespace();
600 $user = $this->getUser();
601 $pageId = $this->getId();
603 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
604 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
605 WHERE rev_page = $pageId
606 AND rev_user != $user
607 GROUP BY rev_user, rev_user_text, user_real_name
608 ORDER BY timestamp DESC";
610 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
611 $sql .= ' '. $this->getSelectOptions();
613 $res = $dbr->query($sql, $fname);
615 while ( $line = $dbr->fetchObject( $res ) ) {
616 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
619 $dbr->freeResult($res);
624 * This is the default action of the script: just view the page of
628 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
629 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
630 global $wgEnotif, $wgParser;
631 $sk = $wgUser->getSkin();
633 $fname = 'Article::view';
634 wfProfileIn( $fname );
635 # Get variables from query string
636 $oldid = $this->getOldID();
637 $diff = $wgRequest->getVal( 'diff' );
638 $rcid = $wgRequest->getVal( 'rcid' );
639 $rdfrom = $wgRequest->getVal( 'rdfrom' );
641 $wgOut->setArticleFlag( true );
642 $wgOut->setRobotpolicy( 'index,follow' );
643 # If we got diff and oldid in the query, we want to see a
644 # diff page instead of the article.
646 if ( !is_null( $diff ) ) {
647 require_once( 'DifferenceEngine.php' );
648 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
650 $de = new DifferenceEngine( $oldid, $diff, $rcid );
651 // DifferenceEngine directly fetched the revision:
652 $this->mRevIdFetched
= $de->mNewid
;
656 # Run view updates for current revision only
657 $this->viewUpdates();
659 wfProfileOut( $fname );
662 if ( empty( $oldid ) && $this->checkTouched() ) {
663 if( $wgOut->checkLastModified( $this->mTouched
) ){
664 wfProfileOut( $fname );
666 } else if ( $this->tryFileCache() ) {
667 # tell wgOut that output is taken care of
669 $this->viewUpdates();
670 wfProfileOut( $fname );
674 # Should the parser cache be used?
675 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
683 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
687 if ( !$outputDone ) {
688 $text = $this->getContent( false ); # May change mTitle by following a redirect
690 # Another whitelist check in case oldid or redirects are altering the title
691 if ( !$this->mTitle
->userCanRead() ) {
692 $wgOut->loginToUse();
698 # We're looking at an old revision
700 if ( !empty( $oldid ) ) {
701 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
702 $wgOut->setRobotpolicy( 'noindex,follow' );
704 if ( '' != $this->mRedirectedFrom
) {
705 $sk = $wgUser->getSkin();
706 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
708 $s = wfMsg( 'redirectedfrom', $redir );
709 $wgOut->setSubtitle( $s );
711 # Can't cache redirects
713 } elseif ( !empty( $rdfrom ) ) {
714 global $wgRedirectSources;
715 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
716 $sk = $wgUser->getSkin();
717 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
718 $s = wfMsg( 'redirectedfrom', $redir );
719 $wgOut->setSubtitle( $s );
723 # wrap user css and user js in pre and don't parse
724 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
726 $this->mTitle
->getNamespace() == NS_USER
&&
727 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
729 $wgOut->addWikiText( wfMsg('clearyourcache'));
730 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
731 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
733 $imageUrl = $wgStylePath.'/common/images/redirect.png';
734 $targetUrl = $rt->escapeLocalURL();
735 $titleText = htmlspecialchars( $rt->getPrefixedText() );
736 $link = $sk->makeLinkObj( $rt );
738 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
739 '<span class="redirectText">'.$link.'</span>' );
741 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
742 $catlinks = $parseout->getCategoryLinks();
743 $wgOut->addCategoryLinks($catlinks);
744 $skin = $wgUser->getSkin();
745 } else if ( $pcache ) {
746 # Display content and save to parser cache
747 $wgOut->addPrimaryWikiText( $text, $this );
749 # Display content, don't attempt to save to parser cache
750 $wgOut->addWikiText( $text );
753 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
754 # If we have been passed an &rcid= parameter, we want to give the user a
755 # chance to mark this new article as patrolled.
756 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->isLoggedIn() &&
757 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
759 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
760 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
761 'action=markpatrolled&rcid='.$rcid )
765 # Put link titles into the link cache
766 $wgOut->transformBuffer();
768 # Add link titles as META keywords
769 $wgOut->addMetaTags() ;
771 $this->viewUpdates();
772 wfProfileOut( $fname );
776 * Insert a new empty page record for this article.
777 * This *must* be followed up by creating a revision
778 * and running $this->updateToLatest( $rev_id );
779 * or else the record will be left in a funky state.
780 * Best if all done inside a transaction.
782 * @param Database $dbw
783 * @param string $restrictions
784 * @return int The newly created page_id key
787 function insertOn( &$dbw, $restrictions = '' ) {
788 $fname = 'Article::insertOn';
789 wfProfileIn( $fname );
791 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
792 $dbw->insert( 'page', array(
793 'page_id' => $page_id,
794 'page_namespace' => $this->mTitle
->getNamespace(),
795 'page_title' => $this->mTitle
->getDBkey(),
797 'page_restrictions' => $restrictions,
798 'page_is_redirect' => 0, # Will set this shortly...
800 'page_random' => wfRandom(),
801 'page_touched' => $dbw->timestamp(),
802 'page_latest' => 0, # Fill this in shortly...
804 $newid = $dbw->insertId();
806 $this->mTitle
->resetArticleId( $newid );
808 wfProfileOut( $fname );
813 * Update the page record to point to a newly saved revision.
815 * @param Database $dbw
816 * @param Revision $revision -- for ID number, and text used to set
817 length and redirect status fields
818 * @param int $lastRevision -- if given, will not overwrite the page field
819 * when different from the currently set value.
820 * Giving 0 indicates the new page flag should
822 * @return bool true on success, false on failure
825 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
826 $fname = 'Article::updateToRevision';
827 wfProfileIn( $fname );
829 $conditions = array( 'page_id' => $this->getId() );
830 if( !is_null( $lastRevision ) ) {
831 # An extra check against threads stepping on each other
832 $conditions['page_latest'] = $lastRevision;
834 $text = $revision->getText();
835 $dbw->update( 'page',
837 'page_latest' => $revision->getId(),
838 'page_touched' => $dbw->timestamp(),
839 'page_is_new' => ($lastRevision === 0) ?
0 : 1,
840 'page_is_redirect' => Article
::isRedirect( $text ),
841 'page_len' => strlen( $text ),
846 wfProfileOut( $fname );
847 return ( $dbw->affectedRows() != 0 );
851 * If the given revision is newer than the currently set page_latest,
852 * update the page record. Otherwise, do nothing.
854 * @param Database $dbw
855 * @param Revision $revision
857 function updateIfNewerOn( &$dbw, $revision ) {
858 $fname = 'Article::updateIfNewerOn';
859 wfProfileIn( $fname );
861 $row = $dbw->selectRow(
862 array( 'revision', 'page' ),
863 array( 'rev_id', 'rev_timestamp' ),
865 'page_id' => $this->getId(),
866 'page_latest=rev_id' ),
869 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
870 wfProfileOut( $fname );
873 $prev = $row->rev_id
;
875 # No or missing previous revision; mark the page as new
879 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
880 wfProfileOut( $fname );
885 * Theoretically we could defer these whole insert and update
886 * functions for after display, but that's taking a big leap
887 * of faith, and we want to be able to report database
888 * errors at some point.
891 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false ) {
892 global $wgOut, $wgUser;
893 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
895 $fname = 'Article::insertNewArticle';
897 $this->mCountAdjustment
= $this->isCountable( $text );
899 $ns = $this->mTitle
->getNamespace();
900 $ttl = $this->mTitle
->getDBkey();
901 $text = $this->preSaveTransform( $text );
902 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
904 $dbw =& wfGetDB( DB_MASTER
);
906 # Add the page record; stake our claim on this title!
907 $newid = $this->insertOn( $dbw );
909 # Save the revision text...
910 $revision = new Revision( array(
912 'comment' => $summary,
913 'minor_edit' => $isminor,
916 $revisionId = $revision->insertOn( $dbw );
918 $this->mTitle
->resetArticleID( $newid );
920 # Update the page record with revision data
921 $this->updateRevisionOn( $dbw, $revision, 0 );
923 Article
::onArticleCreate( $this->mTitle
);
925 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
929 if(!$this->mTitle
->userIsWatching()) $this->watch();
931 if ( $this->mTitle
->userIsWatching() ) {
936 # The talk page isn't in the regular link tables, so we need to update manually:
937 $talkns = $ns ^
1; # talk -> normal; normal -> talk
938 $dbw->update( 'page',
939 array( 'page_touched' => $dbw->timestamp($now) ),
940 array( 'page_namespace' => $talkns,
941 'page_title' => $ttl ),
944 # standard deferred updates
945 $this->editUpdates( $text, $summary, $isminor, $now );
947 $oldid = 0; # new article
948 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
952 * Fetch and uncompress the text for a given revision.
953 * Can ask by rev_id number or timestamp (set $field)
955 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
956 $fname = 'Article::fetchRevisionText';
957 $dbw =& wfGetDB( DB_MASTER
);
959 $rev = $dbw->addQuotes( $revId );
961 $rev = 'page_latest';
963 $result = $dbw->query(
964 sprintf( "SELECT old_text, old_flags
966 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
968 $dbw->tableName( 'page' ),
969 $dbw->tableName( 'revision' ),
970 $dbw->tableName( 'text' ),
971 IntVal( $this->mTitle
->getArticleId() ),
975 $obj = $dbw->fetchObject( $result );
976 $dbw->freeResult( $result );
977 $oldtext = Revision
::getRevisionText( $obj );
981 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
982 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
983 if( is_null( $edittime ) ) {
984 $oldtext = $this->fetchRevisionText();
986 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
988 if ($section != '') {
989 if($section=='new') {
990 if($summary) $subject="== {$summary} ==\n\n";
991 $text=$oldtext."\n\n".$subject.$text;
994 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
995 # comments to be stripped as well)
997 $parser=new Parser();
998 $parser->mOutputType
=OT_WIKI
;
999 $oldtext=$parser->strip($oldtext, $striparray, true);
1001 # now that we can be sure that no pseudo-sections are in the source,
1003 # Unfortunately we can't simply do a preg_replace because that might
1004 # replace the wrong section, so we have to use the section counter instead
1005 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1006 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1007 $secs[$section*2]=$text."\n\n"; // replace with edited
1009 # section 0 is top (intro) section
1012 # headline of old section - we need to go through this section
1013 # to determine if there are any subsections that now need to
1014 # be erased, as the mother section has been replaced with
1015 # the text of all subsections.
1016 $headline=$secs[$section*2-1];
1017 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1018 $hlevel=$matches[1];
1020 # determine headline level for wikimarkup headings
1021 if(strpos($hlevel,'=')!==false) {
1022 $hlevel=strlen($hlevel);
1025 $secs[$section*2-1]=''; // erase old headline
1028 while(!empty($secs[$count*2-1]) && !$break) {
1030 $subheadline=$secs[$count*2-1];
1032 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1033 $subhlevel=$matches[1];
1034 if(strpos($subhlevel,'=')!==false) {
1035 $subhlevel=strlen($subhlevel);
1037 if($subhlevel > $hlevel) {
1038 // erase old subsections
1039 $secs[$count*2-1]='';
1042 if($subhlevel <= $hlevel) {
1050 $text=join('',$secs);
1051 # reinsert the stuff that we stripped out earlier
1052 $text=$parser->unstrip($text,$striparray);
1053 $text=$parser->unstripNoWiki($text,$striparray);
1061 * Change an existing article. Puts the previous version back into the old table, updates RC
1062 * and all necessary caches, mostly via the deferred update array.
1064 * It is possible to call this function from a command-line script, but note that you should
1065 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1067 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1068 global $wgOut, $wgUser;
1069 global $wgDBtransactions, $wgMwRedir;
1070 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1072 $fname = 'Article::updateArticle';
1075 $isminor = ( $minor && $wgUser->isLoggedIn() );
1076 if ( $this->isRedirect( $text ) ) {
1077 # Remove all content but redirect
1078 # This could be done by reconstructing the redirect from a title given by
1079 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1081 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1083 $text = $m[1] . "\n";
1086 else { $redir = 0; }
1088 $text = $this->preSaveTransform( $text );
1089 $dbw =& wfGetDB( DB_MASTER
);
1091 # Update article, but only if changed.
1093 # It's important that we either rollback or complete, otherwise an attacker could
1094 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1095 # could conceivably have the same effect, especially if cur is locked for long periods.
1096 if( !$wgDBtransactions ) {
1097 $userAbort = ignore_user_abort( true );
1100 $oldtext = $this->getContent( true );
1102 if ( 0 != strcmp( $text, $oldtext ) ) {
1103 $this->mCountAdjustment
= $this->isCountable( $text )
1104 - $this->isCountable( $oldtext );
1105 $now = wfTimestampNow();
1107 $lastRevision = $dbw->selectField(
1108 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1110 $revision = new Revision( array(
1111 'page' => $this->getId(),
1112 'comment' => $summary,
1113 'minor_edit' => $isminor,
1116 $revisionId = $revision->insertOn( $dbw );
1119 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1122 /* Belated edit conflict! Run away!! */
1125 # Update recentchanges and purge cache and whatnot
1126 $bot = (int)($wgUser->isBot() ||
$forceBot);
1127 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1128 $lastRevision, $this->getTimestamp(), $bot );
1129 Article
::onArticleEdit( $this->mTitle
);
1133 if( !$wgDBtransactions ) {
1134 ignore_user_abort( $userAbort );
1139 if (!$this->mTitle
->userIsWatching()) $this->watch();
1141 if ( $this->mTitle
->userIsWatching() ) {
1145 # standard deferred updates
1146 $this->editUpdates( $text, $summary, $minor, $now );
1150 # Template namespace
1151 # Purge all articles linking here
1152 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1153 $titles = $this->mTitle
->getLinksTo();
1154 Title
::touchArray( $titles );
1155 if ( $wgUseSquid ) {
1156 foreach ( $titles as $title ) {
1157 $urls[] = $title->getInternalURL();
1163 if ( $wgUseSquid ) {
1164 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1165 $u = new SquidUpdate( $urls );
1166 array_push( $wgPostCommitUpdateList, $u );
1169 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1175 * After we've either updated or inserted the article, update
1176 * the link tables and redirect to the new page.
1178 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1179 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1181 $wgLinkCache = new LinkCache();
1183 $wgLinkCache->forUpdate( true );
1185 # Get old version of link table to allow incremental link updates
1186 $wgLinkCache->preFill( $this->mTitle
);
1187 $wgLinkCache->clear();
1189 # Parse the text and replace links with placeholders
1190 $wgOut = new OutputPage();
1191 $wgOut->addWikiText( $text );
1193 # Look up the links in the DB and add them to the link cache
1194 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1196 if( $this->isRedirect( $text ) )
1200 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1202 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1203 # this will be improved later (to-do)
1205 include_once( "UserMailer.php" );
1206 $wgEnotif = new EmailNotification ();
1207 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1211 * Mark this particular edit as patrolled
1213 function markpatrolled() {
1214 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1215 $wgOut->setRobotpolicy( 'noindex,follow' );
1217 if ( !$wgUseRCPatrol )
1219 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1222 if ( $wgUser->isAnon() )
1224 $wgOut->loginToUse();
1227 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1229 $wgOut->sysopRequired();
1232 $rcid = $wgRequest->getVal( 'rcid' );
1233 if ( !is_null ( $rcid ) )
1235 RecentChange
::markPatrolled( $rcid );
1236 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1237 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1239 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1240 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1244 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1251 function validate() {
1252 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1254 if ( !$wgUseValidation ) # Are we using article validation at all?
1256 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1260 $wgOut->setRobotpolicy( 'noindex,follow' );
1261 $revision = $wgRequest->getVal( 'revision' );
1263 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1265 $v = new Validation
;
1266 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1267 $t = $v->showList ( $this ) ;
1269 $t = $v->validatePageForm ( $this , $revision ) ;
1271 $wgOut->addHTML ( $t ) ;
1275 * Add this page to $wgUser's watchlist
1280 global $wgUser, $wgOut;
1282 if ( $wgUser->isAnon() ) {
1283 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1286 if ( wfReadOnly() ) {
1287 $wgOut->readOnlyPage();
1291 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1293 $wgUser->addWatch( $this->mTitle
);
1294 $wgUser->saveSettings();
1296 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1298 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1299 $wgOut->setRobotpolicy( 'noindex,follow' );
1301 $link = $this->mTitle
->getPrefixedText();
1302 $text = wfMsg( 'addedwatchtext', $link );
1303 $wgOut->addWikiText( $text );
1306 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1310 * Stop watching a page
1313 function unwatch() {
1315 global $wgUser, $wgOut;
1317 if ( $wgUser->isAnon() ) {
1318 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1321 if ( wfReadOnly() ) {
1322 $wgOut->readOnlyPage();
1326 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1328 $wgUser->removeWatch( $this->mTitle
);
1329 $wgUser->saveSettings();
1331 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1333 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1334 $wgOut->setRobotpolicy( 'noindex,follow' );
1336 $link = $this->mTitle
->getPrefixedText();
1337 $text = wfMsg( 'removedwatchtext', $link );
1338 $wgOut->addWikiText( $text );
1341 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1347 function protect( $limit = 'sysop' ) {
1348 global $wgUser, $wgOut, $wgRequest;
1350 if ( ! $wgUser->isAllowed('protect') ) {
1351 $wgOut->sysopRequired();
1354 if ( wfReadOnly() ) {
1355 $wgOut->readOnlyPage();
1358 $id = $this->mTitle
->getArticleID();
1360 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1364 $confirm = $wgRequest->wasPosted() &&
1365 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1366 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1367 $reason = $wgRequest->getText( 'wpReasonProtect' );
1370 $dbw =& wfGetDB( DB_MASTER
);
1371 $dbw->update( 'page',
1373 'page_touched' => $dbw->timestamp(),
1374 'page_restrictions' => (string)$limit
1375 ), array( /* WHERE */
1377 ), 'Article::protect'
1380 $restrictions = "move=" . $limit;
1382 $restrictions .= ":edit=" . $limit;
1384 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1386 $dbw =& wfGetDB( DB_MASTER
);
1387 $dbw->update( 'page',
1389 'page_touched' => $dbw->timestamp(),
1390 'page_restrictions' => $restrictions
1391 ), array( /* WHERE */
1393 ), 'Article::protect'
1396 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1398 $log = new LogPage( 'protect' );
1399 if ( $limit === '' ) {
1400 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1402 $log->addEntry( 'protect', $this->mTitle
, $reason );
1404 $wgOut->redirect( $this->mTitle
->getFullURL() );
1408 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1409 return $this->confirmProtect( '', $reason, $limit );
1414 * Output protection confirmation dialog
1416 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1417 global $wgOut, $wgUser;
1419 wfDebug( "Article::confirmProtect\n" );
1421 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1422 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1428 if ( $limit === '' ) {
1429 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1430 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1431 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1432 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1433 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1435 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1436 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1437 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1438 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1439 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1440 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1443 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1444 $token = htmlspecialchars( $wgUser->editToken() );
1447 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1451 <label for='wpReasonProtect'>{$protcom}:</label>
1454 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1457 if($moveonly != '') {
1461 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1464 <label for='wpMoveOnly'>{$moveonly}</label>
1472 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1476 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1479 $wgOut->returnToMain( false );
1483 * Unprotect the pages
1485 function unprotect() {
1486 return $this->protect( '' );
1490 * UI entry point for page deletion
1493 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1494 $fname = 'Article::delete';
1495 $confirm = $wgRequest->wasPosted() &&
1496 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1497 $reason = $wgRequest->getText( 'wpReason' );
1499 # This code desperately needs to be totally rewritten
1502 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1503 $wgOut->sysopRequired();
1506 if ( wfReadOnly() ) {
1507 $wgOut->readOnlyPage();
1511 # Better double-check that it hasn't been deleted yet!
1512 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1513 if ( ( '' == trim( $this->mTitle
->getText() ) )
1514 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1515 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1520 $this->doDelete( $reason );
1524 # determine whether this page has earlier revisions
1525 # and insert a warning if it does
1526 # we select the text because it might be useful below
1527 $dbr =& $this->getDB();
1528 $ns = $this->mTitle
->getNamespace();
1529 $title = $this->mTitle
->getDBkey();
1530 $revisions = $dbr->select( array( 'page', 'revision' ),
1533 'page_namespace' => $ns,
1534 'page_title' => $title,
1535 'rev_page = page_id'
1536 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1539 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1540 $skin=$wgUser->getSkin();
1541 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1542 $wgOut->addHTML( $skin->historyLink() .'</b>');
1546 $s = $dbr->selectRow( array( 'page', 'text' ),
1547 array( 'old_text' ),
1549 'page_namespace' => $ns,
1550 'page_title' => $title,
1551 'page_latest = old_id'
1552 ), $fname, $this->getSelectOptions()
1555 if( $s !== false ) {
1556 # if this is a mini-text, we can paste part of it into the deletion reason
1558 #if this is empty, an earlier revision may contain "useful" text
1560 if($s->old_text
!= '') {
1564 $text = Revision
::getRevisionText( $old );
1570 $length=strlen($text);
1572 # this should not happen, since it is not possible to store an empty, new
1573 # page. Let's insert a standard text in case it does, though
1574 if($length == 0 && $reason === '') {
1575 $reason = wfMsg('exblank');
1578 if($length < 500 && $reason === '') {
1580 # comment field=255, let's grep the first 150 to have some user
1582 $text=substr($text,0,150);
1583 # let's strip out newlines and HTML tags
1584 $text=preg_replace('/\"/',"'",$text);
1585 $text=preg_replace('/\</','<',$text);
1586 $text=preg_replace('/\>/','>',$text);
1587 $text=preg_replace("/[\n\r]/",'',$text);
1589 $reason=wfMsg('excontent'). " '".$text;
1591 $reason=wfMsg('exbeforeblank') . " '".$text;
1593 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1598 return $this->confirmDelete( '', $reason );
1602 * Output deletion confirmation dialog
1604 function confirmDelete( $par, $reason ) {
1605 global $wgOut, $wgUser;
1607 wfDebug( "Article::confirmDelete\n" );
1609 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1610 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1611 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1612 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1614 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1616 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1617 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1618 $token = htmlspecialchars( $wgUser->editToken() );
1621 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1625 <label for='wpReason'>{$delcom}:</label>
1628 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1634 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1638 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1641 $wgOut->returnToMain( false );
1646 * Perform a deletion and output success or failure messages
1648 function doDelete( $reason ) {
1649 global $wgOut, $wgUser, $wgContLang;
1650 $fname = 'Article::doDelete';
1651 wfDebug( $fname."\n" );
1653 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1654 if ( $this->doDeleteArticle( $reason ) ) {
1655 $deleted = $this->mTitle
->getPrefixedText();
1657 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1658 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1660 $sk = $wgUser->getSkin();
1661 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1662 ':' . wfMsgForContent( 'dellogpage' ),
1663 wfMsg( 'deletionlog' ) );
1665 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1667 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1668 $wgOut->returnToMain( false );
1669 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1671 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1677 * Back-end article deletion
1678 * Deletes the article with database consistency, writes logs, purges caches
1681 function doDeleteArticle( $reason ) {
1683 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1685 $fname = 'Article::doDeleteArticle';
1686 wfDebug( $fname."\n" );
1688 $dbw =& wfGetDB( DB_MASTER
);
1689 $ns = $this->mTitle
->getNamespace();
1690 $t = $this->mTitle
->getDBkey();
1691 $id = $this->mTitle
->getArticleID();
1693 if ( $t == '' ||
$id == 0 ) {
1697 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1698 array_push( $wgDeferredUpdateList, $u );
1700 $linksTo = $this->mTitle
->getLinksTo();
1703 if ( $wgUseSquid ) {
1705 $this->mTitle
->getInternalURL(),
1706 $this->mTitle
->getInternalURL( 'history' )
1708 foreach ( $linksTo as $linkTo ) {
1709 $urls[] = $linkTo->getInternalURL();
1712 $u = new SquidUpdate( $urls );
1713 array_push( $wgPostCommitUpdateList, $u );
1717 # Client and file cache invalidation
1718 Title
::touchArray( $linksTo );
1720 # Move article and history to the "archive" table
1722 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1724 'ar_namespace' => 'page_namespace',
1725 'ar_title' => 'page_title',
1726 'ar_text' => 'old_text',
1727 'ar_comment' => 'rev_comment',
1728 'ar_user' => 'rev_user',
1729 'ar_user_text' => 'rev_user_text',
1730 'ar_timestamp' => 'rev_timestamp',
1731 'ar_minor_edit' => 'rev_minor_edit',
1732 'ar_flags' => 'old_flags',
1733 'ar_rev_id' => 'rev_id',
1735 'page_namespace' => $ns,
1737 'page_id = rev_page AND old_id = rev_id'
1741 # Now that it's safely backed up, delete it
1743 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1744 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1745 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1747 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1749 # Finally, clean up the link tables
1750 $t = $this->mTitle
->getPrefixedDBkey();
1752 Article
::onArticleDelete( $this->mTitle
);
1754 # Insert broken links
1755 $brokenLinks = array();
1756 foreach ( $linksTo as $titleObj ) {
1757 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1758 $linkID = $titleObj->getArticleID();
1759 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1761 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1764 $dbw->delete( 'links', array( 'l_to' => $id ) );
1765 $dbw->delete( 'links', array( 'l_from' => $id ) );
1766 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1767 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1768 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1771 $log = new LogPage( 'delete' );
1772 $log->addEntry( 'delete', $this->mTitle
, $reason );
1774 # Clear the cached article id so the interface doesn't act like we exist
1775 $this->mTitle
->resetArticleID( 0 );
1776 $this->mTitle
->mArticleID
= 0;
1781 * Revert a modification
1783 function rollback() {
1784 global $wgUser, $wgOut, $wgRequest;
1785 $fname = 'Article::rollback';
1787 if ( ! $wgUser->isAllowed('rollback') ) {
1788 $wgOut->sysopRequired();
1791 if ( wfReadOnly() ) {
1792 $wgOut->readOnlyPage( $this->getContent( true ) );
1795 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1796 array( $this->mTitle
->getPrefixedText(),
1797 $wgRequest->getVal( 'from' ) ) ) ) {
1798 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1799 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1802 $dbw =& wfGetDB( DB_MASTER
);
1804 # Enhanced rollback, marks edits rc_bot=1
1805 $bot = $wgRequest->getBool( 'bot' );
1807 # Replace all this user's current edits with the next one down
1808 $tt = $this->mTitle
->getDBKey();
1809 $n = $this->mTitle
->getNamespace();
1811 # Get the last editor, lock table exclusively
1813 $current = Revision
::newFromTitle( $this->mTitle
);
1814 if( is_null( $current ) ) {
1815 # Something wrong... no page?
1817 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1821 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1822 if( $from != $current->getUserText() ) {
1823 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1824 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1825 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1826 htmlspecialchars( $from ),
1827 htmlspecialchars( $current->getUserText() ) ) );
1828 if( $current->getComment() != '') {
1830 wfMsg( 'editcomment',
1831 htmlspecialchars( $current->getComment() ) ) );
1836 # Get the last edit not by this guy
1837 $user = IntVal( $current->getUser() );
1838 $user_text = $dbw->addQuotes( $current->getUserText() );
1839 $s = $dbw->selectRow( 'revision',
1840 array( 'rev_id', 'rev_timestamp' ),
1842 'rev_page' => $current->getPage(),
1843 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1846 'USE INDEX' => 'page_timestamp',
1847 'ORDER BY' => 'rev_timestamp DESC' )
1849 if( $s === false ) {
1852 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1853 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1858 # Mark all reverted edits as bot
1859 $dbw->update( 'recentchanges',
1862 ), array( /* WHERE */
1863 'rc_cur_id' => $current->getPage(),
1864 'rc_user_text' => $current->getUserText(),
1865 "rc_timestamp > '{$s->rev_timestamp}'",
1871 $target = Revision
::newFromId( $s->rev_id
);
1872 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1874 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1875 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1876 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1878 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1879 Article
::onArticleEdit( $this->mTitle
);
1882 $wgOut->returnToMain( false );
1887 * Do standard deferred updates after page view
1890 function viewUpdates() {
1891 global $wgDeferredUpdateList;
1893 if ( 0 != $this->getID() ) {
1894 global $wgDisableCounters;
1895 if( !$wgDisableCounters ) {
1896 Article
::incViewCount( $this->getID() );
1897 $u = new SiteStatsUpdate( 1, 0, 0 );
1898 array_push( $wgDeferredUpdateList, $u );
1902 # Update newtalk status if user is reading their own
1906 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1907 $this->mTitle
->getText() == $wgUser->getName()) {
1908 require_once( 'UserTalkUpdate.php' );
1909 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1911 $wgUser->clearNotification( $this->mTitle
);
1917 * Do standard deferred updates after page edit.
1918 * Every 1000th edit, prune the recent changes table.
1920 * @param string $text
1922 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1923 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1924 global $wgMessageCache, $wgUser;
1927 if ( 0 == mt_rand( 0, 999 ) ) {
1928 # Periodically flush old entries from the recentchanges table.
1930 $dbw =& wfGetDB( DB_MASTER
);
1931 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1932 $recentchanges = $dbw->tableName( 'recentchanges' );
1933 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1934 $dbw->query( $sql );
1936 $id = $this->getID();
1937 $title = $this->mTitle
->getPrefixedDBkey();
1938 $shortTitle = $this->mTitle
->getDBkey();
1940 $adj = $this->mCountAdjustment
;
1943 $u = new LinksUpdate( $id, $title );
1944 array_push( $wgDeferredUpdateList, $u );
1945 $u = new SiteStatsUpdate( 0, 1, $adj );
1946 array_push( $wgDeferredUpdateList, $u );
1947 $u = new SearchUpdate( $id, $title, $text );
1948 array_push( $wgDeferredUpdateList, $u );
1950 # If this is another user's talk page,
1951 # create a watchlist entry for this page
1953 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1954 $shortTitle != $wgUser->getName()) {
1955 require_once( 'UserTalkUpdate.php' );
1956 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1959 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1960 $wgMessageCache->replace( $shortTitle, $text );
1966 * @todo document this function
1968 * @param string $oldid Revision ID of this article revision
1970 function setOldSubtitle( $oldid=0 ) {
1971 global $wgLang, $wgOut, $wgUser;
1973 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1974 $sk = $wgUser->getSkin();
1975 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1976 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1977 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1978 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1979 $wgOut->setSubtitle( $r );
1983 * This function is called right before saving the wikitext,
1984 * so we can do things like signatures and links-in-context.
1986 * @param string $text
1988 function preSaveTransform( $text ) {
1989 global $wgParser, $wgUser;
1990 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1993 /* Caching functions */
1996 * checkLastModified returns true if it has taken care of all
1997 * output to the client that is necessary for this request.
1998 * (that is, it has sent a cached version of the page)
2000 function tryFileCache() {
2001 static $called = false;
2003 wfDebug( " tryFileCache() -- called twice!?\n" );
2007 if($this->isFileCacheable()) {
2008 $touched = $this->mTouched
;
2009 $cache = new CacheManager( $this->mTitle
);
2010 if($cache->isFileCacheGood( $touched )) {
2012 wfDebug( " tryFileCache() - about to load\n" );
2013 $cache->loadFromFileCache();
2016 wfDebug( " tryFileCache() - starting buffer\n" );
2017 ob_start( array(&$cache, 'saveToFileCache' ) );
2020 wfDebug( " tryFileCache() - not cacheable\n" );
2025 * Check if the page can be cached
2028 function isFileCacheable() {
2029 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2030 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2032 return $wgUseFileCache
2033 and (!$wgShowIPinHeader)
2034 and ($this->getID() != 0)
2035 and ($wgUser->isAnon())
2036 and (!$wgUser->getNewtalk())
2037 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2038 and (empty( $action ) ||
$action == 'view')
2039 and (!isset($oldid))
2041 and (!isset($redirect))
2042 and (!isset($printable))
2043 and (!$this->mRedirectedFrom
);
2047 * Loads cur_touched and returns a value indicating if it should be used
2050 function checkTouched() {
2051 $fname = 'Article::checkTouched';
2052 if( !$this->mDataLoaded
) {
2053 $dbr =& $this->getDB();
2054 $data = $this->pageDataFromId( $dbr, $this->getId() );
2056 $this->loadPageData( $data );
2059 return !$this->mIsRedirect
;
2063 * Edit an article without doing all that other stuff
2064 * The article must already exist; link tables etc
2065 * are not updated, caches are not flushed.
2067 * @param string $text text submitted
2068 * @param string $comment comment submitted
2069 * @param bool $minor whereas it's a minor modification
2071 function quickEdit( $text, $comment = '', $minor = 0 ) {
2072 $fname = 'Article::quickEdit';
2073 wfProfileIn( $fname );
2075 $dbw =& wfGetDB( DB_MASTER
);
2077 $revision = new Revision( array(
2078 'page' => $this->getId(),
2080 'comment' => $comment,
2081 'minor_edit' => $minor ?
1 : 0,
2083 $revisionId = $revision->insertOn( $dbw );
2084 $this->updateRevisionOn( $dbw, $revision );
2087 wfProfileOut( $fname );
2091 * Used to increment the view counter
2094 * @param integer $id article id
2096 function incViewCount( $id ) {
2097 $id = intval( $id );
2098 global $wgHitcounterUpdateFreq;
2100 $dbw =& wfGetDB( DB_MASTER
);
2101 $pageTable = $dbw->tableName( 'page' );
2102 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2103 $acchitsTable = $dbw->tableName( 'acchits' );
2105 if( $wgHitcounterUpdateFreq <= 1 ){ //
2106 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2110 # Not important enough to warrant an error page in case of failure
2111 $oldignore = $dbw->ignoreErrors( true );
2113 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2115 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2116 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2117 # Most of the time (or on SQL errors), skip row count check
2118 $dbw->ignoreErrors( $oldignore );
2122 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2123 $row = $dbw->fetchObject( $res );
2124 $rown = intval( $row->n
);
2125 if( $rown >= $wgHitcounterUpdateFreq ){
2126 wfProfileIn( 'Article::incViewCount-collect' );
2127 $old_user_abort = ignore_user_abort( true );
2129 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2130 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2131 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2133 $dbw->query("DELETE FROM $hitcounterTable");
2134 $dbw->query('UNLOCK TABLES');
2135 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2136 'WHERE cur_id = hc_id');
2137 $dbw->query("DROP TABLE $acchitsTable");
2139 ignore_user_abort( $old_user_abort );
2140 wfProfileOut( 'Article::incViewCount-collect' );
2142 $dbw->ignoreErrors( $oldignore );
2146 * The onArticle*() functions are supposed to be a kind of hooks
2147 * which should be called whenever any of the specified actions
2150 * This is a good place to put code to clear caches, for instance.
2152 * This is called on page move and undelete, as well as edit
2154 * @param $title_obj a title object
2157 function onArticleCreate($title_obj) {
2158 global $wgUseSquid, $wgPostCommitUpdateList;
2160 $titles = $title_obj->getBrokenLinksTo();
2163 if ( $wgUseSquid ) {
2164 $urls = $title_obj->getSquidURLs();
2165 foreach ( $titles as $linkTitle ) {
2166 $urls[] = $linkTitle->getInternalURL();
2168 $u = new SquidUpdate( $urls );
2169 array_push( $wgPostCommitUpdateList, $u );
2172 # Clear persistent link cache
2173 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2176 function onArticleDelete($title_obj) {
2177 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2179 function onArticleEdit($title_obj) {
2180 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2185 * Info about this page
2186 * Called for ?action=info when $wgAllowPageInfo is on.
2191 global $wgLang, $wgOut, $wgAllowPageInfo;
2192 $fname = 'Article::info';
2194 if ( !$wgAllowPageInfo ) {
2195 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2199 $page = $this->mTitle
->getSubjectPage();
2201 $wgOut->setPagetitle( $page->getPrefixedText() );
2202 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2204 # first, see if the page exists at all.
2205 $exists = $page->getArticleId() != 0;
2207 $wgOut->addHTML( wfMsg('noarticletext') );
2209 $dbr =& $this->getDB( DB_SLAVE
);
2211 'wl_title' => $page->getDBkey(),
2212 'wl_namespace' => $page->getNamespace() );
2213 $numwatchers = $dbr->selectField(
2218 $this->getSelectOptions() );
2220 $pageInfo = $this->pageCountInfo( $page );
2221 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2223 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2224 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2226 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2228 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2230 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2232 $wgOut->addHTML( '</ul>' );
2238 * Return the total number of edits and number of unique editors
2239 * on a given page. If page does not exist, returns false.
2241 * @param Title $title
2245 function pageCountInfo( $title ) {
2246 $id = $title->getArticleId();
2251 $dbr =& $this->getDB( DB_SLAVE
);
2253 $rev_clause = array( 'rev_page' => $id );
2254 $fname = 'Article::pageCountInfo';
2256 $edits = $dbr->selectField(
2261 $this->getSelectOptions() );
2263 $authors = $dbr->selectField(
2265 'COUNT(DISTINCT rev_user_text)',
2268 $this->getSelectOptions() );
2270 return array( 'edits' => $edits, 'authors' => $authors );