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;
40 * Constructor and clear the article
41 * @param mixed &$title
43 function Article( &$title ) {
44 $this->mTitle
=& $title;
49 * get the title object of the article
61 $this->mDataLoaded
= false;
62 $this->mContentLoaded
= false;
64 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
65 $this->mRedirectedFrom
= $this->mUserText
=
66 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
67 $this->mCountAdjustment
= 0;
68 $this->mTouched
= '19700101000000';
69 $this->mForUpdate
= false;
70 $this->mIsRedirect
= false;
74 * Note that getContent/loadContent may follow redirects if
75 * not told otherwise, and so may cause a change to mTitle.
78 * @return Return the text of this revision
80 function getContent( $noredir ) {
83 # Get variables from query string :P
84 $action = $wgRequest->getText( 'action', 'view' );
85 $section = $wgRequest->getText( 'section' );
87 $fname = 'Article::getContent';
88 wfProfileIn( $fname );
90 if ( 0 == $this->getID() ) {
91 if ( 'edit' == $action ) {
92 wfProfileOut( $fname );
93 return ''; # was "newarticletext", now moved above the box)
95 wfProfileOut( $fname );
96 return wfMsg( 'noarticletext' );
98 $this->loadContent( $noredir );
99 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
100 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
101 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
104 wfProfileOut( $fname );
105 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
107 if($action=='edit') {
109 if($section=='new') {
110 wfProfileOut( $fname );
114 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
115 # comments to be stripped as well)
116 $rv=$this->getSection($this->mContent
,$section);
117 wfProfileOut( $fname );
121 wfProfileOut( $fname );
122 return $this->mContent
;
128 * This function returns the text of a section, specified by a number ($section).
129 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
130 * the first section before any such heading (section 0).
132 * If a section contains subsections, these are also returned.
134 * @param string $text text to look in
135 * @param integer $section section number
136 * @return string text of the requested section
138 function getSection($text,$section) {
140 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
141 # comments to be stripped as well)
143 $parser=new Parser();
144 $parser->mOutputType
=OT_WIKI
;
145 $striptext=$parser->strip($text, $striparray, true);
147 # now that we can be sure that no pseudo-sections are in the source,
148 # split it up by section
151 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
153 PREG_SPLIT_DELIM_CAPTURE
);
157 $headline=$secs[$section*2-1];
158 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
161 # translate wiki heading into level
162 if(strpos($hlevel,'=')!==false) {
163 $hlevel=strlen($hlevel);
166 $rv=$headline. $secs[$section*2];
170 while(!empty($secs[$count*2-1]) && !$break) {
172 $subheadline=$secs[$count*2-1];
173 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
174 $subhlevel=$matches[1];
175 if(strpos($subhlevel,'=')!==false) {
176 $subhlevel=strlen($subhlevel);
178 if($subhlevel > $hlevel) {
179 $rv.=$subheadline.$secs[$count*2];
181 if($subhlevel <= $hlevel) {
188 # reinsert stripped tags
189 $rv=$parser->unstrip($rv,$striparray);
190 $rv=$parser->unstripNoWiki($rv,$striparray);
197 * Return an array of the columns of the "cur"-table
199 function getContentFields() {
200 return $wgArticleContentFields = array(
201 'old_text','old_flags',
202 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
203 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
207 * Return the oldid of the article that is to be shown.
208 * For requests with a "direction", this is not the oldid of the
211 function getOldID() {
212 global $wgRequest, $wgOut;
215 if ( isset( $lastid ) ) {
219 $oldid = $wgRequest->getVal( 'oldid' );
220 if ( isset( $oldid ) ) {
221 $oldid = IntVal( $oldid );
222 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
223 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
227 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
229 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
230 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
239 return @$oldid; # "@" to be able to return "unset" without PHP complaining
244 * Load the revision (including cur_text) into this object
246 function loadContent( $noredir = false ) {
247 global $wgOut, $wgRequest;
249 if ( $this->mContentLoaded
) return;
252 $oldid = $this->getOldID();
253 $redirect = $wgRequest->getVal( 'redirect' );
255 $fname = 'Article::loadContent';
257 # Pre-fill content with error message so that if something
258 # fails we'll have something telling us what we intended.
260 $t = $this->mTitle
->getPrefixedText();
262 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no')
263 ||
$wgRequest->getCheck( 'rdfrom' );
264 $this->mOldId
= $oldid;
265 $this->fetchContent( $oldid, $noredir, true );
270 * Fetch a page record with the given conditions
271 * @param Database $dbr
272 * @param array $conditions
275 function pageData( &$dbr, $conditions ) {
276 return $dbr->selectRow( 'page',
290 'Article::pageData' );
293 function pageDataFromTitle( &$dbr, $title ) {
294 return $this->pageData( $dbr, array(
295 'page_namespace' => $title->getNamespace(),
296 'page_title' => $title->getDBkey() ) );
299 function pageDataFromId( &$dbr, $id ) {
300 return $this->pageData( $dbr, array(
301 'page_id' => IntVal( $id ) ) );
305 * Set the general counter, title etc data loaded from
308 * @param object $data
311 function loadPageData( $data ) {
312 $this->mTitle
->mRestrictions
= explode( ',', trim( $data->page_restrictions
) );
313 $this->mTitle
->mRestrictionsLoaded
= true;
315 $this->mCounter
= $data->page_counter
;
316 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
317 $this->mIsRedirect
= $data->page_is_redirect
;
318 $this->mLatest
= $data->page_latest
;
320 $this->mDataLoaded
= true;
324 * Get text of an article from database
325 * @param int $oldid 0 for whatever the latest revision is
326 * @param bool $noredir Set to true to avoid following redirects
327 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
330 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
331 if ( $this->mContentLoaded
) {
332 return $this->mContent
;
334 $dbr =& $this->getDB();
335 $fname = 'Article::fetchContent';
337 # Pre-fill content with error message so that if something
338 # fails we'll have something telling us what we intended.
339 $t = $this->mTitle
->getPrefixedText();
341 $t .= ',oldid='.$oldid;
343 if( isset( $redirect ) ) {
344 $redirect = ($redirect == 'no') ?
'no' : 'yes';
345 $t .= ',redirect='.$redirect;
347 $this->mContent
= wfMsg( 'missingarticle', $t );
350 $revision = Revision
::newFromId( $oldid );
351 if( is_null( $revision ) ) {
352 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
355 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
357 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
360 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
361 $this->loadPageData( $data );
363 if( !$this->mDataLoaded
) {
364 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
366 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
369 $this->loadPageData( $data );
371 $revision = Revision
::newFromId( $this->mLatest
);
372 if( is_null( $revision ) ) {
373 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
378 # If we got a redirect, follow it (unless we've been told
379 # not to by either the function parameter or the query
380 if ( !$oldid && !$noredir ) {
381 $rt = Title
::newFromRedirect( $revision->getText() );
382 # process if title object is valid and not special:userlogout
383 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
384 # Gotta hand redirects to special pages differently:
385 # Fill the HTTP response "Location" header and ignore
386 # the rest of the page we're on.
389 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
390 $source = $this->mTitle
->getFullURL( 'redirect=no' );
391 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
394 if ( $rt->getNamespace() == NS_SPECIAL
) {
395 $wgOut->redirect( $rt->getFullURL() );
399 $redirData = $this->pageDataFromTitle( $dbr, $rt );
401 $redirRev = Revision
::newFromId( $redirData->page_latest
);
402 if( !is_null( $redirRev ) ) {
403 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
406 $this->loadPageData( $data );
407 $revision = $redirRev;
413 # if the title's different from expected, update...
416 if( !$this->mTitle
->equals( $wgTitle ) ) {
417 $wgTitle = $this->mTitle
;
421 # Back to the business at hand...
422 $this->mContent
= $revision->getText();
424 $this->mUser
= $revision->getUser();
425 $this->mUserText
= $revision->getUserText();
426 $this->mComment
= $revision->getComment();
427 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
429 $this->mContentLoaded
= true;
430 return $this->mContent
;
434 * Gets the article text without using so many damn globals
435 * Returns false on error
437 * @param integer $oldid
439 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
440 return $this->fetchContent( $oldid, $noredir, false );
444 * Read/write accessor to select FOR UPDATE
446 function forUpdate( $x = NULL ) {
447 return wfSetVar( $this->mForUpdate
, $x );
451 * Get the database which should be used for reads
454 #if ( $this->mForUpdate ) {
455 return wfGetDB( DB_MASTER
);
457 # return wfGetDB( DB_SLAVE );
462 * Get options for all SELECT statements
463 * Can pass an option array, to which the class-wide options will be appended
465 function getSelectOptions( $options = '' ) {
466 if ( $this->mForUpdate
) {
467 if ( is_array( $options ) ) {
468 $options[] = 'FOR UPDATE';
470 $options = 'FOR UPDATE';
477 * Return the Article ID
480 if( $this->mTitle
) {
481 return $this->mTitle
->getArticleID();
488 * Get the view count for this article
490 function getCount() {
491 if ( -1 == $this->mCounter
) {
492 $id = $this->getID();
493 $dbr =& $this->getDB();
494 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
495 'Article::getCount', $this->getSelectOptions() );
497 return $this->mCounter
;
501 * Would the given text make this article a "good" article (i.e.,
502 * suitable for including in the article count)?
503 * @param string $text Text to analyze
504 * @return integer 1 if it can be counted else 0
506 function isCountable( $text ) {
507 global $wgUseCommaCount;
509 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
510 if ( $this->isRedirect( $text ) ) { return 0; }
511 $token = ($wgUseCommaCount ?
',' : '[[' );
512 if ( false === strstr( $text, $token ) ) { return 0; }
517 * Tests if the article text represents a redirect
519 function isRedirect( $text = false ) {
520 if ( $text === false ) {
521 $this->loadContent();
522 $titleObj = Title
::newFromRedirect( $this->mText
);
524 $titleObj = Title
::newFromRedirect( $text );
526 return $titleObj !== NULL;
530 * Loads everything except the text
531 * This isn't necessary for all uses, so it's only done if needed.
534 function loadLastEdit() {
537 if ( -1 != $this->mUser
)
540 # New or non-existent articles have no user information
541 $id = $this->getID();
542 if ( 0 == $id ) return;
544 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
545 if( !is_null( $this->mLastRevision
) ) {
546 $this->mUser
= $this->mLastRevision
->getUser();
547 $this->mUserText
= $this->mLastRevision
->getUserText();
548 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
549 $this->mComment
= $this->mLastRevision
->getComment();
550 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
554 function getTimestamp() {
555 $this->loadLastEdit();
556 return $this->mTimestamp
;
560 $this->loadLastEdit();
564 function getUserText() {
565 $this->loadLastEdit();
566 return $this->mUserText
;
569 function getComment() {
570 $this->loadLastEdit();
571 return $this->mComment
;
574 function getMinorEdit() {
575 $this->loadLastEdit();
576 return $this->mMinorEdit
;
579 function getContributors($limit = 0, $offset = 0) {
580 $fname = 'Article::getContributors';
582 # XXX: this is expensive; cache this info somewhere.
584 $title = $this->mTitle
;
586 $dbr =& $this->getDB();
587 $revTable = $dbr->tableName( 'revision' );
588 $userTable = $dbr->tableName( 'user' );
589 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
590 $ns = $title->getNamespace();
591 $user = $this->getUser();
592 $pageId = $this->getId();
594 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
595 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
596 WHERE rev_page = $pageId
597 AND rev_user != $user
598 GROUP BY rev_user, rev_user_text, user_real_name
599 ORDER BY timestamp DESC";
601 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
602 $sql .= ' '. $this->getSelectOptions();
604 $res = $dbr->query($sql, $fname);
606 while ( $line = $dbr->fetchObject( $res ) ) {
607 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
610 $dbr->freeResult($res);
615 * This is the default action of the script: just view the page of
619 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
620 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
621 global $wgEnotif, $wgParser;
622 $sk = $wgUser->getSkin();
624 $fname = 'Article::view';
625 wfProfileIn( $fname );
626 # Get variables from query string
627 $oldid = $this->getOldID();
628 $diff = $wgRequest->getVal( 'diff' );
629 $rcid = $wgRequest->getVal( 'rcid' );
630 $rdfrom = $wgRequest->getVal( 'rdfrom' );
632 $wgOut->setArticleFlag( true );
633 $wgOut->setRobotpolicy( 'index,follow' );
634 # If we got diff and oldid in the query, we want to see a
635 # diff page instead of the article.
637 if ( !is_null( $diff ) ) {
638 require_once( 'DifferenceEngine.php' );
639 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
640 $de = new DifferenceEngine( $oldid, $diff, $rcid );
643 # Run view updates for current revision only
644 $this->viewUpdates();
646 wfProfileOut( $fname );
649 if ( empty( $oldid ) && $this->checkTouched() ) {
650 if( $wgOut->checkLastModified( $this->mTouched
) ){
651 wfProfileOut( $fname );
653 } else if ( $this->tryFileCache() ) {
654 # tell wgOut that output is taken care of
656 $this->viewUpdates();
657 wfProfileOut( $fname );
661 # Should the parser cache be used?
662 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
670 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
674 if ( !$outputDone ) {
675 $text = $this->getContent( false ); # May change mTitle by following a redirect
677 # Another whitelist check in case oldid or redirects are altering the title
678 if ( !$this->mTitle
->userCanRead() ) {
679 $wgOut->loginToUse();
685 # We're looking at an old revision
687 if ( !empty( $oldid ) ) {
688 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
689 $wgOut->setRobotpolicy( 'noindex,follow' );
691 if ( '' != $this->mRedirectedFrom
) {
692 $sk = $wgUser->getSkin();
693 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
695 $s = wfMsg( 'redirectedfrom', $redir );
696 $wgOut->setSubtitle( $s );
698 # Can't cache redirects
700 } elseif ( !empty( $rdfrom ) ) {
701 global $wgRedirectSources;
702 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
703 $sk = $wgUser->getSkin();
704 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
705 $s = wfMsg( 'redirectedfrom', $redir );
706 $wgOut->setSubtitle( $s );
710 # wrap user css and user js in pre and don't parse
711 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
713 $this->mTitle
->getNamespace() == NS_USER
&&
714 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
716 $wgOut->addWikiText( wfMsg('clearyourcache'));
717 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
718 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
720 $imageUrl = $wgStylePath.'/common/images/redirect.png';
721 $targetUrl = $rt->escapeLocalURL();
722 $titleText = htmlspecialchars( $rt->getPrefixedText() );
723 $link = $sk->makeLinkObj( $rt );
725 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
726 '<span class="redirectText">'.$link.'</span>' );
728 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
729 $catlinks = $parseout->getCategoryLinks();
730 $wgOut->addCategoryLinks($catlinks);
731 $skin = $wgUser->getSkin();
732 } else if ( $pcache ) {
733 # Display content and save to parser cache
734 $wgOut->addPrimaryWikiText( $text, $this );
736 # Display content, don't attempt to save to parser cache
737 $wgOut->addWikiText( $text );
740 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
741 # If we have been passed an &rcid= parameter, we want to give the user a
742 # chance to mark this new article as patrolled.
743 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->isLoggedIn() &&
744 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
746 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
747 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
748 'action=markpatrolled&rcid='.$rcid )
752 # Put link titles into the link cache
753 $wgOut->transformBuffer();
755 # Add link titles as META keywords
756 $wgOut->addMetaTags() ;
758 $this->viewUpdates();
759 wfProfileOut( $fname );
763 * Insert a new empty page record for this article.
764 * This *must* be followed up by creating a revision
765 * and running $this->updateToLatest( $rev_id );
766 * or else the record will be left in a funky state.
767 * Best if all done inside a transaction.
769 * @param Database $dbw
770 * @return int The newly created page_id key
773 function insertOn( &$dbw ) {
774 $fname = 'Article::insertOn';
775 wfProfileIn( $fname );
777 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
778 $dbw->insert( 'page', array(
779 'page_id' => $page_id,
780 'page_namespace' => $this->mTitle
->getNamespace(),
781 'page_title' => $this->mTitle
->getDBkey(),
783 'page_restrictions' => '',
784 'page_is_redirect' => 0, # Will set this shortly...
786 'page_random' => wfRandom(),
787 'page_touched' => $dbw->timestamp(),
788 'page_latest' => 0, # Fill this in shortly...
790 $newid = $dbw->insertId();
792 $this->mTitle
->resetArticleId( $newid );
794 wfProfileOut( $fname );
799 * Update the page record to point to a newly saved revision.
801 * @param Database $dbw
802 * @param Revision $revision -- for ID number, and text used to set
803 length and redirect status fields
804 * @param int $lastRevision -- if given, will not overwrite the page field
805 * when different from the currently set value.
806 * Giving 0 indicates the new page flag should
808 * @return bool true on success, false on failure
811 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
812 $fname = 'Article::updateToRevision';
813 wfProfileIn( $fname );
815 $conditions = array( 'page_id' => $this->getId() );
816 if( !is_null( $lastRevision ) ) {
817 # An extra check against threads stepping on each other
818 $conditions['page_latest'] = $lastRevision;
820 $text = $revision->getText();
821 $dbw->update( 'page',
823 'page_latest' => $revision->getId(),
824 'page_touched' => $dbw->timestamp(),
825 'page_is_new' => ($lastRevision === 0) ?
0 : 1,
826 'page_is_redirect' => Article
::isRedirect( $text ),
827 'page_len' => strlen( $text ),
832 wfProfileOut( $fname );
833 return ( $dbw->affectedRows() != 0 );
837 * If the given revision is newer than the currently set page_latest,
838 * update the page record. Otherwise, do nothing.
840 * @param Database $dbw
841 * @param Revision $revision
843 function updateIfNewerOn( &$dbw, $revision ) {
844 $fname = 'Article::updateIfNewerOn';
845 wfProfileIn( $fname );
847 $row = $dbw->selectRow(
848 array( 'revision', 'page' ),
849 array( 'rev_id', 'rev_timestamp' ),
851 'page_id' => $this->getId(),
852 'page_latest=rev_id' ),
855 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
856 wfProfileOut( $fname );
859 $prev = $row->rev_id
;
861 # No or missing previous revision; mark the page as new
865 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
866 wfProfileOut( $fname );
871 * Theoretically we could defer these whole insert and update
872 * functions for after display, but that's taking a big leap
873 * of faith, and we want to be able to report database
874 * errors at some point.
877 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
878 global $wgOut, $wgUser;
879 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
881 $fname = 'Article::insertNewArticle';
883 $this->mCountAdjustment
= $this->isCountable( $text );
885 $ns = $this->mTitle
->getNamespace();
886 $ttl = $this->mTitle
->getDBkey();
887 $text = $this->preSaveTransform( $text );
888 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
890 $dbw =& wfGetDB( DB_MASTER
);
892 # Add the page record; stake our claim on this title!
893 $newid = $this->insertOn( $dbw );
895 # Save the revision text...
896 $revision = new Revision( array(
898 'comment' => $summary,
899 'minor_edit' => $isminor,
902 $revisionId = $revision->insertOn( $dbw );
904 $this->mTitle
->resetArticleID( $newid );
906 # Update the page record with revision data
907 $this->updateRevisionOn( $dbw, $revision, 0 );
909 Article
::onArticleCreate( $this->mTitle
);
910 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
913 if(!$this->mTitle
->userIsWatching()) $this->watch();
915 if ( $this->mTitle
->userIsWatching() ) {
920 # The talk page isn't in the regular link tables, so we need to update manually:
921 $talkns = $ns ^
1; # talk -> normal; normal -> talk
922 $dbw->update( 'page',
923 array( 'page_touched' => $dbw->timestamp($now) ),
924 array( 'page_namespace' => $talkns,
925 'page_title' => $ttl ),
928 # standard deferred updates
929 $this->editUpdates( $text, $summary, $isminor, $now );
931 $oldid = 0; # new article
932 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
936 * Fetch and uncompress the text for a given revision.
937 * Can ask by rev_id number or timestamp (set $field)
939 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
940 $fname = 'Article::fetchRevisionText';
941 $dbw =& wfGetDB( DB_MASTER
);
943 $rev = $dbw->addQuotes( $revId );
945 $rev = 'page_latest';
947 $result = $dbw->query(
948 sprintf( "SELECT old_text, old_flags
950 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
952 $dbw->tableName( 'page' ),
953 $dbw->tableName( 'revision' ),
954 $dbw->tableName( 'text' ),
955 IntVal( $this->mTitle
->getArticleId() ),
959 $obj = $dbw->fetchObject( $result );
960 $dbw->freeResult( $result );
961 $oldtext = Revision
::getRevisionText( $obj );
965 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
966 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
967 if( is_null( $edittime ) ) {
968 $oldtext = $this->fetchRevisionText();
970 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
972 if ($section != '') {
973 if($section=='new') {
974 if($summary) $subject="== {$summary} ==\n\n";
975 $text=$oldtext."\n\n".$subject.$text;
978 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
979 # comments to be stripped as well)
981 $parser=new Parser();
982 $parser->mOutputType
=OT_WIKI
;
983 $oldtext=$parser->strip($oldtext, $striparray, true);
985 # now that we can be sure that no pseudo-sections are in the source,
987 # Unfortunately we can't simply do a preg_replace because that might
988 # replace the wrong section, so we have to use the section counter instead
989 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
990 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
991 $secs[$section*2]=$text."\n\n"; // replace with edited
993 # section 0 is top (intro) section
996 # headline of old section - we need to go through this section
997 # to determine if there are any subsections that now need to
998 # be erased, as the mother section has been replaced with
999 # the text of all subsections.
1000 $headline=$secs[$section*2-1];
1001 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1002 $hlevel=$matches[1];
1004 # determine headline level for wikimarkup headings
1005 if(strpos($hlevel,'=')!==false) {
1006 $hlevel=strlen($hlevel);
1009 $secs[$section*2-1]=''; // erase old headline
1012 while(!empty($secs[$count*2-1]) && !$break) {
1014 $subheadline=$secs[$count*2-1];
1016 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1017 $subhlevel=$matches[1];
1018 if(strpos($subhlevel,'=')!==false) {
1019 $subhlevel=strlen($subhlevel);
1021 if($subhlevel > $hlevel) {
1022 // erase old subsections
1023 $secs[$count*2-1]='';
1026 if($subhlevel <= $hlevel) {
1034 $text=join('',$secs);
1035 # reinsert the stuff that we stripped out earlier
1036 $text=$parser->unstrip($text,$striparray);
1037 $text=$parser->unstripNoWiki($text,$striparray);
1045 * Change an existing article. Puts the previous version back into the old table, updates RC
1046 * and all necessary caches, mostly via the deferred update array.
1048 * It is possible to call this function from a command-line script, but note that you should
1049 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1051 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1052 global $wgOut, $wgUser;
1053 global $wgDBtransactions, $wgMwRedir;
1054 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1056 $fname = 'Article::updateArticle';
1059 $isminor = ( $minor && $wgUser->isLoggedIn() );
1060 if ( $this->isRedirect( $text ) ) {
1061 # Remove all content but redirect
1062 # This could be done by reconstructing the redirect from a title given by
1063 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1065 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1067 $text = $m[1] . "\n";
1070 else { $redir = 0; }
1072 $text = $this->preSaveTransform( $text );
1073 $dbw =& wfGetDB( DB_MASTER
);
1075 # Update article, but only if changed.
1077 # It's important that we either rollback or complete, otherwise an attacker could
1078 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1079 # could conceivably have the same effect, especially if cur is locked for long periods.
1080 if( $wgDBtransactions ) {
1081 $dbw->query( 'BEGIN', $fname );
1083 $userAbort = ignore_user_abort( true );
1086 $oldtext = $this->getContent( true );
1088 if ( 0 != strcmp( $text, $oldtext ) ) {
1089 $this->mCountAdjustment
= $this->isCountable( $text )
1090 - $this->isCountable( $oldtext );
1091 $now = wfTimestampNow();
1093 $lastRevision = $dbw->selectField(
1094 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1096 $revision = new Revision( array(
1097 'page' => $this->getId(),
1098 'comment' => $summary,
1099 'minor_edit' => $isminor,
1102 $revisionId = $revision->insertOn( $dbw );
1105 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1108 /* Belated edit conflict! Run away!! */
1111 # Update recentchanges and purge cache and whatnot
1112 $bot = (int)($wgUser->isBot() ||
$forceBot);
1113 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1114 $lastRevision, $this->getTimestamp(), $bot );
1115 Article
::onArticleEdit( $this->mTitle
);
1119 if( $wgDBtransactions ) {
1120 $dbw->query( 'COMMIT', $fname );
1122 ignore_user_abort( $userAbort );
1127 if (!$this->mTitle
->userIsWatching()) $this->watch();
1129 if ( $this->mTitle
->userIsWatching() ) {
1133 # standard deferred updates
1134 $this->editUpdates( $text, $summary, $minor, $now );
1138 # Template namespace
1139 # Purge all articles linking here
1140 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1141 $titles = $this->mTitle
->getLinksTo();
1142 Title
::touchArray( $titles );
1143 if ( $wgUseSquid ) {
1144 foreach ( $titles as $title ) {
1145 $urls[] = $title->getInternalURL();
1151 if ( $wgUseSquid ) {
1152 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1153 $u = new SquidUpdate( $urls );
1154 array_push( $wgPostCommitUpdateList, $u );
1157 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1163 * After we've either updated or inserted the article, update
1164 * the link tables and redirect to the new page.
1166 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1167 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1169 $wgLinkCache = new LinkCache();
1171 $wgLinkCache->forUpdate( true );
1173 # Get old version of link table to allow incremental link updates
1174 $wgLinkCache->preFill( $this->mTitle
);
1175 $wgLinkCache->clear();
1177 # Parse the text and replace links with placeholders
1178 $wgOut = new OutputPage();
1179 $wgOut->addWikiText( $text );
1181 # Look up the links in the DB and add them to the link cache
1182 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1184 if( $this->isRedirect( $text ) )
1188 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1190 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1191 # this will be improved later (to-do)
1193 include_once( "UserMailer.php" );
1194 $wgEnotif = new EmailNotification ();
1195 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1199 * Mark this particular edit as patrolled
1201 function markpatrolled() {
1202 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1203 $wgOut->setRobotpolicy( 'noindex,follow' );
1205 if ( !$wgUseRCPatrol )
1207 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1210 if ( $wgUser->isAnon() )
1212 $wgOut->loginToUse();
1215 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1217 $wgOut->sysopRequired();
1220 $rcid = $wgRequest->getVal( 'rcid' );
1221 if ( !is_null ( $rcid ) )
1223 RecentChange
::markPatrolled( $rcid );
1224 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1225 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1227 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1228 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1232 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1239 function validate() {
1240 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1242 if ( !$wgUseValidation ) # Are we using article validation at all?
1244 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1248 $wgOut->setRobotpolicy( 'noindex,follow' );
1249 $revision = $wgRequest->getVal( 'revision' );
1251 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1253 $v = new Validation
;
1254 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1255 $t = $v->showList ( $this ) ;
1257 $t = $v->validatePageForm ( $this , $revision ) ;
1259 $wgOut->addHTML ( $t ) ;
1263 * Add this page to $wgUser's watchlist
1268 global $wgUser, $wgOut;
1270 if ( $wgUser->isAnon() ) {
1271 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1274 if ( wfReadOnly() ) {
1275 $wgOut->readOnlyPage();
1279 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1281 $wgUser->addWatch( $this->mTitle
);
1282 $wgUser->saveSettings();
1284 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1286 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1287 $wgOut->setRobotpolicy( 'noindex,follow' );
1289 $link = $this->mTitle
->getPrefixedText();
1290 $text = wfMsg( 'addedwatchtext', $link );
1291 $wgOut->addWikiText( $text );
1294 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1298 * Stop watching a page
1301 function unwatch() {
1303 global $wgUser, $wgOut;
1305 if ( $wgUser->isAnon() ) {
1306 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1309 if ( wfReadOnly() ) {
1310 $wgOut->readOnlyPage();
1314 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1316 $wgUser->removeWatch( $this->mTitle
);
1317 $wgUser->saveSettings();
1319 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1321 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1322 $wgOut->setRobotpolicy( 'noindex,follow' );
1324 $link = $this->mTitle
->getPrefixedText();
1325 $text = wfMsg( 'removedwatchtext', $link );
1326 $wgOut->addWikiText( $text );
1329 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1335 function protect( $limit = 'sysop' ) {
1336 global $wgUser, $wgOut, $wgRequest;
1338 if ( ! $wgUser->isAllowed('protect') ) {
1339 $wgOut->sysopRequired();
1342 if ( wfReadOnly() ) {
1343 $wgOut->readOnlyPage();
1346 $id = $this->mTitle
->getArticleID();
1348 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1352 $confirm = $wgRequest->wasPosted() &&
1353 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1354 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1355 $reason = $wgRequest->getText( 'wpReasonProtect' );
1358 $dbw =& wfGetDB( DB_MASTER
);
1359 $dbw->update( 'page',
1361 'page_touched' => $dbw->timestamp(),
1362 'page_restrictions' => (string)$limit
1363 ), array( /* WHERE */
1365 ), 'Article::protect'
1368 $restrictions = "move=" . $limit;
1370 $restrictions .= ":edit=" . $limit;
1372 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1374 $dbw =& wfGetDB( DB_MASTER
);
1375 $dbw->update( 'page',
1377 'page_touched' => $dbw->timestamp(),
1378 'page_restrictions' => $restrictions
1379 ), array( /* WHERE */
1381 ), 'Article::protect'
1384 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1386 $log = new LogPage( 'protect' );
1387 if ( $limit === '' ) {
1388 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1390 $log->addEntry( 'protect', $this->mTitle
, $reason );
1392 $wgOut->redirect( $this->mTitle
->getFullURL() );
1396 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1397 return $this->confirmProtect( '', $reason, $limit );
1402 * Output protection confirmation dialog
1404 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1405 global $wgOut, $wgUser;
1407 wfDebug( "Article::confirmProtect\n" );
1409 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1410 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1416 if ( $limit === '' ) {
1417 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1418 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1419 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1420 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1421 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1423 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1424 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1425 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1426 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1427 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1428 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1431 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1432 $token = htmlspecialchars( $wgUser->editToken() );
1435 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1439 <label for='wpReasonProtect'>{$protcom}:</label>
1442 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1448 if($moveonly != '') {
1452 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1455 <label for='wpMoveOnly'>{$moveonly}</label>
1463 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1467 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1470 $wgOut->returnToMain( false );
1474 * Unprotect the pages
1476 function unprotect() {
1477 return $this->protect( '' );
1481 * UI entry point for page deletion
1484 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1485 $fname = 'Article::delete';
1486 $confirm = $wgRequest->wasPosted() &&
1487 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1488 $reason = $wgRequest->getText( 'wpReason' );
1490 # This code desperately needs to be totally rewritten
1493 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1494 $wgOut->sysopRequired();
1497 if ( wfReadOnly() ) {
1498 $wgOut->readOnlyPage();
1502 # Better double-check that it hasn't been deleted yet!
1503 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1504 if ( ( '' == trim( $this->mTitle
->getText() ) )
1505 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1506 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1511 $this->doDelete( $reason );
1515 # determine whether this page has earlier revisions
1516 # and insert a warning if it does
1517 # we select the text because it might be useful below
1518 $dbr =& $this->getDB();
1519 $ns = $this->mTitle
->getNamespace();
1520 $title = $this->mTitle
->getDBkey();
1521 $revisions = $dbr->select( array( 'page', 'revision' ),
1524 'page_namespace' => $ns,
1525 'page_title' => $title,
1526 'rev_page = page_id'
1527 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1530 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1531 $skin=$wgUser->getSkin();
1532 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1533 $wgOut->addHTML( $skin->historyLink() .'</b>');
1537 $s = $dbr->selectRow( array( 'page', 'text' ),
1538 array( 'old_text' ),
1540 'page_namespace' => $ns,
1541 'page_title' => $title,
1542 'page_latest = old_id'
1543 ), $fname, $this->getSelectOptions()
1546 if( $s !== false ) {
1547 # if this is a mini-text, we can paste part of it into the deletion reason
1549 #if this is empty, an earlier revision may contain "useful" text
1551 if($s->old_text
!= '') {
1555 $text = Revision
::getRevisionText( $old );
1561 $length=strlen($text);
1563 # this should not happen, since it is not possible to store an empty, new
1564 # page. Let's insert a standard text in case it does, though
1565 if($length == 0 && $reason === '') {
1566 $reason = wfMsg('exblank');
1569 if($length < 500 && $reason === '') {
1571 # comment field=255, let's grep the first 150 to have some user
1573 $text=substr($text,0,150);
1574 # let's strip out newlines and HTML tags
1575 $text=preg_replace('/\"/',"'",$text);
1576 $text=preg_replace('/\</','<',$text);
1577 $text=preg_replace('/\>/','>',$text);
1578 $text=preg_replace("/[\n\r]/",'',$text);
1580 $reason=wfMsg('excontent'). " '".$text;
1582 $reason=wfMsg('exbeforeblank') . " '".$text;
1584 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1589 return $this->confirmDelete( '', $reason );
1593 * Output deletion confirmation dialog
1595 function confirmDelete( $par, $reason ) {
1596 global $wgOut, $wgUser;
1598 wfDebug( "Article::confirmDelete\n" );
1600 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1601 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1602 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1603 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1605 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1607 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1608 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1609 $token = htmlspecialchars( $wgUser->editToken() );
1612 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1616 <label for='wpReason'>{$delcom}:</label>
1619 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1628 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1632 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1635 $wgOut->returnToMain( false );
1640 * Perform a deletion and output success or failure messages
1642 function doDelete( $reason ) {
1643 global $wgOut, $wgUser, $wgContLang;
1644 $fname = 'Article::doDelete';
1645 wfDebug( $fname."\n" );
1647 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1648 if ( $this->doDeleteArticle( $reason ) ) {
1649 $deleted = $this->mTitle
->getPrefixedText();
1651 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1652 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1654 $sk = $wgUser->getSkin();
1655 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1656 ':' . wfMsgForContent( 'dellogpage' ),
1657 wfMsg( 'deletionlog' ) );
1659 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1661 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1662 $wgOut->returnToMain( false );
1663 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1665 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1671 * Back-end article deletion
1672 * Deletes the article with database consistency, writes logs, purges caches
1675 function doDeleteArticle( $reason ) {
1677 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1679 $fname = 'Article::doDeleteArticle';
1680 wfDebug( $fname."\n" );
1682 $dbw =& wfGetDB( DB_MASTER
);
1683 $ns = $this->mTitle
->getNamespace();
1684 $t = $this->mTitle
->getDBkey();
1685 $id = $this->mTitle
->getArticleID();
1687 if ( $t == '' ||
$id == 0 ) {
1691 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1692 array_push( $wgDeferredUpdateList, $u );
1694 $linksTo = $this->mTitle
->getLinksTo();
1697 if ( $wgUseSquid ) {
1699 $this->mTitle
->getInternalURL(),
1700 $this->mTitle
->getInternalURL( 'history' )
1702 foreach ( $linksTo as $linkTo ) {
1703 $urls[] = $linkTo->getInternalURL();
1706 $u = new SquidUpdate( $urls );
1707 array_push( $wgPostCommitUpdateList, $u );
1711 # Client and file cache invalidation
1712 Title
::touchArray( $linksTo );
1714 # Move article and history to the "archive" table
1716 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1718 'ar_namespace' => 'page_namespace',
1719 'ar_title' => 'page_title',
1720 'ar_text' => 'old_text',
1721 'ar_comment' => 'rev_comment',
1722 'ar_user' => 'rev_user',
1723 'ar_user_text' => 'rev_user_text',
1724 'ar_timestamp' => 'rev_timestamp',
1725 'ar_minor_edit' => 'rev_minor_edit',
1726 'ar_flags' => 'old_flags',
1727 'ar_rev_id' => 'rev_id',
1729 'page_namespace' => $ns,
1731 'page_id = rev_page AND old_id = rev_id'
1735 # Now that it's safely backed up, delete it
1737 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1738 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1739 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1741 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1743 # Finally, clean up the link tables
1744 $t = $this->mTitle
->getPrefixedDBkey();
1746 Article
::onArticleDelete( $this->mTitle
);
1748 # Insert broken links
1749 $brokenLinks = array();
1750 foreach ( $linksTo as $titleObj ) {
1751 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1752 $linkID = $titleObj->getArticleID();
1753 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1755 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1758 $dbw->delete( 'links', array( 'l_to' => $id ) );
1759 $dbw->delete( 'links', array( 'l_from' => $id ) );
1760 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1761 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1762 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1765 $log = new LogPage( 'delete' );
1766 $log->addEntry( 'delete', $this->mTitle
, $reason );
1768 # Clear the cached article id so the interface doesn't act like we exist
1769 $this->mTitle
->resetArticleID( 0 );
1770 $this->mTitle
->mArticleID
= 0;
1775 * Revert a modification
1777 function rollback() {
1778 global $wgUser, $wgOut, $wgRequest;
1779 $fname = 'Article::rollback';
1781 if ( ! $wgUser->isAllowed('rollback') ) {
1782 $wgOut->sysopRequired();
1785 if ( wfReadOnly() ) {
1786 $wgOut->readOnlyPage( $this->getContent( true ) );
1789 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1790 array( $this->mTitle
->getPrefixedText(),
1791 $wgRequest->getVal( 'from' ) ) ) ) {
1792 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1793 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1796 $dbw =& wfGetDB( DB_MASTER
);
1798 # Enhanced rollback, marks edits rc_bot=1
1799 $bot = $wgRequest->getBool( 'bot' );
1801 # Replace all this user's current edits with the next one down
1802 $tt = $this->mTitle
->getDBKey();
1803 $n = $this->mTitle
->getNamespace();
1805 # Get the last editor, lock table exclusively
1807 $current = Revision
::newFromTitle( $this->mTitle
);
1808 if( is_null( $current ) ) {
1809 # Something wrong... no page?
1811 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1815 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1816 if( $from != $current->getUserText() ) {
1817 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1818 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1819 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1820 htmlspecialchars( $from ),
1821 htmlspecialchars( $current->getUserText() ) ) );
1822 if( $current->getComment() != '') {
1824 wfMsg( 'editcomment',
1825 htmlspecialchars( $current->getComment() ) ) );
1830 # Get the last edit not by this guy
1831 $user = IntVal( $current->getUser() );
1832 $user_text = $dbw->addQuotes( $current->getUserText() );
1833 $s = $dbw->selectRow( 'revision',
1834 array( 'rev_id', 'rev_timestamp' ),
1836 'rev_page' => $current->getPage(),
1837 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1840 'USE INDEX' => 'page_timestamp',
1841 'ORDER BY' => 'rev_timestamp DESC' )
1843 if( $s === false ) {
1846 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1847 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1852 # Mark all reverted edits as bot
1853 $dbw->update( 'recentchanges',
1856 ), array( /* WHERE */
1857 'rc_cur_id' => $current->getPage(),
1858 'rc_user_text' => $current->getUserText(),
1859 "rc_timestamp > '{$s->rev_timestamp}'",
1865 $target = Revision
::newFromId( $s->rev_id
);
1866 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1868 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1869 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1870 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1872 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1873 Article
::onArticleEdit( $this->mTitle
);
1876 $wgOut->returnToMain( false );
1881 * Do standard deferred updates after page view
1884 function viewUpdates() {
1885 global $wgDeferredUpdateList;
1887 if ( 0 != $this->getID() ) {
1888 global $wgDisableCounters;
1889 if( !$wgDisableCounters ) {
1890 Article
::incViewCount( $this->getID() );
1891 $u = new SiteStatsUpdate( 1, 0, 0 );
1892 array_push( $wgDeferredUpdateList, $u );
1896 # Update newtalk status if user is reading their own
1900 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1901 $this->mTitle
->getText() == $wgUser->getName()) {
1902 require_once( 'UserTalkUpdate.php' );
1903 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1905 $wgUser->clearNotification( $this->mTitle
);
1911 * Do standard deferred updates after page edit.
1912 * Every 1000th edit, prune the recent changes table.
1914 * @param string $text
1916 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1917 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1918 global $wgMessageCache, $wgUser;
1921 if ( 0 == mt_rand( 0, 999 ) ) {
1922 # Periodically flush old entries from the recentchanges table.
1924 $dbw =& wfGetDB( DB_MASTER
);
1925 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1926 $recentchanges = $dbw->tableName( 'recentchanges' );
1927 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1928 $dbw->query( $sql );
1930 $id = $this->getID();
1931 $title = $this->mTitle
->getPrefixedDBkey();
1932 $shortTitle = $this->mTitle
->getDBkey();
1934 $adj = $this->mCountAdjustment
;
1937 $u = new LinksUpdate( $id, $title );
1938 array_push( $wgDeferredUpdateList, $u );
1939 $u = new SiteStatsUpdate( 0, 1, $adj );
1940 array_push( $wgDeferredUpdateList, $u );
1941 $u = new SearchUpdate( $id, $title, $text );
1942 array_push( $wgDeferredUpdateList, $u );
1944 # If this is another user's talk page,
1945 # create a watchlist entry for this page
1947 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1948 $shortTitle != $wgUser->getName()) {
1949 require_once( 'UserTalkUpdate.php' );
1950 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1953 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1954 $wgMessageCache->replace( $shortTitle, $text );
1960 * @todo document this function
1962 * @param string $oldid Revision ID of this article revision
1964 function setOldSubtitle( $oldid=0 ) {
1965 global $wgLang, $wgOut, $wgUser;
1967 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1968 $sk = $wgUser->getSkin();
1969 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1970 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1971 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1972 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1973 $wgOut->setSubtitle( $r );
1977 * This function is called right before saving the wikitext,
1978 * so we can do things like signatures and links-in-context.
1980 * @param string $text
1982 function preSaveTransform( $text ) {
1983 global $wgParser, $wgUser;
1984 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1987 /* Caching functions */
1990 * checkLastModified returns true if it has taken care of all
1991 * output to the client that is necessary for this request.
1992 * (that is, it has sent a cached version of the page)
1994 function tryFileCache() {
1995 static $called = false;
1997 wfDebug( " tryFileCache() -- called twice!?\n" );
2001 if($this->isFileCacheable()) {
2002 $touched = $this->mTouched
;
2003 $cache = new CacheManager( $this->mTitle
);
2004 if($cache->isFileCacheGood( $touched )) {
2006 wfDebug( " tryFileCache() - about to load\n" );
2007 $cache->loadFromFileCache();
2010 wfDebug( " tryFileCache() - starting buffer\n" );
2011 ob_start( array(&$cache, 'saveToFileCache' ) );
2014 wfDebug( " tryFileCache() - not cacheable\n" );
2019 * Check if the page can be cached
2022 function isFileCacheable() {
2023 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2024 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2026 return $wgUseFileCache
2027 and (!$wgShowIPinHeader)
2028 and ($this->getID() != 0)
2029 and ($wgUser->isAnon())
2030 and (!$wgUser->getNewtalk())
2031 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2032 and (empty( $action ) ||
$action == 'view')
2033 and (!isset($oldid))
2035 and (!isset($redirect))
2036 and (!isset($printable))
2037 and (!$this->mRedirectedFrom
);
2041 * Loads cur_touched and returns a value indicating if it should be used
2044 function checkTouched() {
2045 $fname = 'Article::checkTouched';
2046 if( !$this->mDataLoaded
) {
2047 $dbr =& $this->getDB();
2048 $data = $this->pageDataFromId( $dbr, $this->getId() );
2050 $this->loadPageData( $data );
2053 return !$this->mIsRedirect
;
2057 * Edit an article without doing all that other stuff
2058 * The article must already exist; link tables etc
2059 * are not updated, caches are not flushed.
2061 * @param string $text text submitted
2062 * @param string $comment comment submitted
2063 * @param bool $minor whereas it's a minor modification
2065 function quickEdit( $text, $comment = '', $minor = 0 ) {
2066 $fname = 'Article::quickEdit';
2067 wfProfileIn( $fname );
2069 $dbw =& wfGetDB( DB_MASTER
);
2071 $revision = new Revision( array(
2072 'page' => $this->getId(),
2074 'comment' => $comment,
2075 'minor_edit' => $minor ?
1 : 0,
2077 $revisionId = $revision->insertOn( $dbw );
2078 $this->updateRevisionOn( $dbw, $revision );
2081 wfProfileOut( $fname );
2085 * Used to increment the view counter
2088 * @param integer $id article id
2090 function incViewCount( $id ) {
2091 $id = intval( $id );
2092 global $wgHitcounterUpdateFreq;
2094 $dbw =& wfGetDB( DB_MASTER
);
2095 $pageTable = $dbw->tableName( 'page' );
2096 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2097 $acchitsTable = $dbw->tableName( 'acchits' );
2099 if( $wgHitcounterUpdateFreq <= 1 ){ //
2100 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2104 # Not important enough to warrant an error page in case of failure
2105 $oldignore = $dbw->ignoreErrors( true );
2107 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2109 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2110 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2111 # Most of the time (or on SQL errors), skip row count check
2112 $dbw->ignoreErrors( $oldignore );
2116 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2117 $row = $dbw->fetchObject( $res );
2118 $rown = intval( $row->n
);
2119 if( $rown >= $wgHitcounterUpdateFreq ){
2120 wfProfileIn( 'Article::incViewCount-collect' );
2121 $old_user_abort = ignore_user_abort( true );
2123 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2124 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2125 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2127 $dbw->query("DELETE FROM $hitcounterTable");
2128 $dbw->query('UNLOCK TABLES');
2129 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2130 'WHERE cur_id = hc_id');
2131 $dbw->query("DROP TABLE $acchitsTable");
2133 ignore_user_abort( $old_user_abort );
2134 wfProfileOut( 'Article::incViewCount-collect' );
2136 $dbw->ignoreErrors( $oldignore );
2140 * The onArticle*() functions are supposed to be a kind of hooks
2141 * which should be called whenever any of the specified actions
2144 * This is a good place to put code to clear caches, for instance.
2146 * This is called on page move and undelete, as well as edit
2148 * @param $title_obj a title object
2151 function onArticleCreate($title_obj) {
2152 global $wgUseSquid, $wgPostCommitUpdateList;
2154 $titles = $title_obj->getBrokenLinksTo();
2157 if ( $wgUseSquid ) {
2158 $urls = $title_obj->getSquidURLs();
2159 foreach ( $titles as $linkTitle ) {
2160 $urls[] = $linkTitle->getInternalURL();
2162 $u = new SquidUpdate( $urls );
2163 array_push( $wgPostCommitUpdateList, $u );
2166 # Clear persistent link cache
2167 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2170 function onArticleDelete($title_obj) {
2171 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2173 function onArticleEdit($title_obj) {
2174 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2179 * Info about this page
2180 * Called for ?action=info when $wgAllowPageInfo is on.
2185 global $wgLang, $wgOut, $wgAllowPageInfo;
2186 $fname = 'Article::info';
2188 if ( !$wgAllowPageInfo ) {
2189 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2193 $page = $this->mTitle
->getSubjectPage();
2195 $wgOut->setPagetitle( $page->getPrefixedText() );
2196 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2198 # first, see if the page exists at all.
2199 $exists = $page->getArticleId() != 0;
2201 $wgOut->addHTML( wfMsg('noarticletext') );
2203 $dbr =& $this->getDB( DB_SLAVE
);
2205 'wl_title' => $page->getDBkey(),
2206 'wl_namespace' => $page->getNamespace() );
2207 $numwatchers = $dbr->selectField(
2212 $this->getSelectOptions() );
2214 $pageInfo = $this->pageCountInfo( $page );
2215 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2217 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2218 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2220 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2222 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2224 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2226 $wgOut->addHTML( '</ul>' );
2232 * Return the total number of edits and number of unique editors
2233 * on a given page. If page does not exist, returns false.
2235 * @param Title $title
2239 function pageCountInfo( $title ) {
2240 $id = $title->getArticleId();
2245 $dbr =& $this->getDB( DB_SLAVE
);
2247 $rev_clause = array( 'rev_page' => $id );
2248 $fname = 'Article::pageCountInfo';
2250 $edits = $dbr->selectField(
2255 $this->getSelectOptions() );
2257 $authors = $dbr->selectField(
2259 'COUNT(DISTINCT rev_user_text)',
2262 $this->getSelectOptions() );
2264 return array( 'edits' => $edits, 'authors' => $authors );