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 $t = $v->validatePageForm ( $this , $revision ) ;
1256 $wgOut->addHTML ( $t ) ;
1260 * Add this page to $wgUser's watchlist
1265 global $wgUser, $wgOut;
1267 if ( $wgUser->isAnon() ) {
1268 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1271 if ( wfReadOnly() ) {
1272 $wgOut->readOnlyPage();
1276 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1278 $wgUser->addWatch( $this->mTitle
);
1279 $wgUser->saveSettings();
1281 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1283 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1284 $wgOut->setRobotpolicy( 'noindex,follow' );
1286 $link = $this->mTitle
->getPrefixedText();
1287 $text = wfMsg( 'addedwatchtext', $link );
1288 $wgOut->addWikiText( $text );
1291 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1295 * Stop watching a page
1298 function unwatch() {
1300 global $wgUser, $wgOut;
1302 if ( $wgUser->isAnon() ) {
1303 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1306 if ( wfReadOnly() ) {
1307 $wgOut->readOnlyPage();
1311 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1313 $wgUser->removeWatch( $this->mTitle
);
1314 $wgUser->saveSettings();
1316 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1318 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1319 $wgOut->setRobotpolicy( 'noindex,follow' );
1321 $link = $this->mTitle
->getPrefixedText();
1322 $text = wfMsg( 'removedwatchtext', $link );
1323 $wgOut->addWikiText( $text );
1326 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1332 function protect( $limit = 'sysop' ) {
1333 global $wgUser, $wgOut, $wgRequest;
1335 if ( ! $wgUser->isAllowed('protect') ) {
1336 $wgOut->sysopRequired();
1339 if ( wfReadOnly() ) {
1340 $wgOut->readOnlyPage();
1343 $id = $this->mTitle
->getArticleID();
1345 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1349 $confirm = $wgRequest->wasPosted() &&
1350 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1351 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1352 $reason = $wgRequest->getText( 'wpReasonProtect' );
1355 $dbw =& wfGetDB( DB_MASTER
);
1356 $dbw->update( 'page',
1358 'page_touched' => $dbw->timestamp(),
1359 'page_restrictions' => (string)$limit
1360 ), array( /* WHERE */
1362 ), 'Article::protect'
1365 $restrictions = "move=" . $limit;
1367 $restrictions .= ":edit=" . $limit;
1369 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1371 $dbw =& wfGetDB( DB_MASTER
);
1372 $dbw->update( 'page',
1374 'page_touched' => $dbw->timestamp(),
1375 'page_restrictions' => $restrictions
1376 ), array( /* WHERE */
1378 ), 'Article::protect'
1381 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1383 $log = new LogPage( 'protect' );
1384 if ( $limit === '' ) {
1385 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1387 $log->addEntry( 'protect', $this->mTitle
, $reason );
1389 $wgOut->redirect( $this->mTitle
->getFullURL() );
1393 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1394 return $this->confirmProtect( '', $reason, $limit );
1399 * Output protection confirmation dialog
1401 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1402 global $wgOut, $wgUser;
1404 wfDebug( "Article::confirmProtect\n" );
1406 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1407 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1413 if ( $limit === '' ) {
1414 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1415 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1416 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1417 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1418 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1420 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1421 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1422 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1423 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1424 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1425 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1428 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1429 $token = htmlspecialchars( $wgUser->editToken() );
1432 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1436 <label for='wpReasonProtect'>{$protcom}:</label>
1439 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1445 if($moveonly != '') {
1449 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1452 <label for='wpMoveOnly'>{$moveonly}</label>
1460 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1464 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1467 $wgOut->returnToMain( false );
1471 * Unprotect the pages
1473 function unprotect() {
1474 return $this->protect( '' );
1478 * UI entry point for page deletion
1481 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1482 $fname = 'Article::delete';
1483 $confirm = $wgRequest->wasPosted() &&
1484 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1485 $reason = $wgRequest->getText( 'wpReason' );
1487 # This code desperately needs to be totally rewritten
1490 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1491 $wgOut->sysopRequired();
1494 if ( wfReadOnly() ) {
1495 $wgOut->readOnlyPage();
1499 # Better double-check that it hasn't been deleted yet!
1500 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1501 if ( ( '' == trim( $this->mTitle
->getText() ) )
1502 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1503 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1508 $this->doDelete( $reason );
1512 # determine whether this page has earlier revisions
1513 # and insert a warning if it does
1514 # we select the text because it might be useful below
1515 $dbr =& $this->getDB();
1516 $ns = $this->mTitle
->getNamespace();
1517 $title = $this->mTitle
->getDBkey();
1518 $revisions = $dbr->select( array( 'page', 'revision' ),
1521 'page_namespace' => $ns,
1522 'page_title' => $title,
1523 'rev_page = page_id'
1524 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1527 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1528 $skin=$wgUser->getSkin();
1529 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1530 $wgOut->addHTML( $skin->historyLink() .'</b>');
1534 $s = $dbr->selectRow( array( 'page', 'text' ),
1535 array( 'old_text' ),
1537 'page_namespace' => $ns,
1538 'page_title' => $title,
1539 'page_latest = old_id'
1540 ), $fname, $this->getSelectOptions()
1543 if( $s !== false ) {
1544 # if this is a mini-text, we can paste part of it into the deletion reason
1546 #if this is empty, an earlier revision may contain "useful" text
1548 if($s->old_text
!= '') {
1552 $text = Revision
::getRevisionText( $old );
1558 $length=strlen($text);
1560 # this should not happen, since it is not possible to store an empty, new
1561 # page. Let's insert a standard text in case it does, though
1562 if($length == 0 && $reason === '') {
1563 $reason = wfMsg('exblank');
1566 if($length < 500 && $reason === '') {
1568 # comment field=255, let's grep the first 150 to have some user
1570 $text=substr($text,0,150);
1571 # let's strip out newlines and HTML tags
1572 $text=preg_replace('/\"/',"'",$text);
1573 $text=preg_replace('/\</','<',$text);
1574 $text=preg_replace('/\>/','>',$text);
1575 $text=preg_replace("/[\n\r]/",'',$text);
1577 $reason=wfMsg('excontent'). " '".$text;
1579 $reason=wfMsg('exbeforeblank') . " '".$text;
1581 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1586 return $this->confirmDelete( '', $reason );
1590 * Output deletion confirmation dialog
1592 function confirmDelete( $par, $reason ) {
1593 global $wgOut, $wgUser;
1595 wfDebug( "Article::confirmDelete\n" );
1597 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1598 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1599 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1600 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1602 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1604 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1605 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1606 $token = htmlspecialchars( $wgUser->editToken() );
1609 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1613 <label for='wpReason'>{$delcom}:</label>
1616 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1625 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1629 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1632 $wgOut->returnToMain( false );
1637 * Perform a deletion and output success or failure messages
1639 function doDelete( $reason ) {
1640 global $wgOut, $wgUser, $wgContLang;
1641 $fname = 'Article::doDelete';
1642 wfDebug( $fname."\n" );
1644 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1645 if ( $this->doDeleteArticle( $reason ) ) {
1646 $deleted = $this->mTitle
->getPrefixedText();
1648 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1649 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1651 $sk = $wgUser->getSkin();
1652 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1653 ':' . wfMsgForContent( 'dellogpage' ),
1654 wfMsg( 'deletionlog' ) );
1656 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1658 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1659 $wgOut->returnToMain( false );
1660 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1662 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1668 * Back-end article deletion
1669 * Deletes the article with database consistency, writes logs, purges caches
1672 function doDeleteArticle( $reason ) {
1674 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1676 $fname = 'Article::doDeleteArticle';
1677 wfDebug( $fname."\n" );
1679 $dbw =& wfGetDB( DB_MASTER
);
1680 $ns = $this->mTitle
->getNamespace();
1681 $t = $this->mTitle
->getDBkey();
1682 $id = $this->mTitle
->getArticleID();
1684 if ( $t == '' ||
$id == 0 ) {
1688 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1689 array_push( $wgDeferredUpdateList, $u );
1691 $linksTo = $this->mTitle
->getLinksTo();
1694 if ( $wgUseSquid ) {
1696 $this->mTitle
->getInternalURL(),
1697 $this->mTitle
->getInternalURL( 'history' )
1699 foreach ( $linksTo as $linkTo ) {
1700 $urls[] = $linkTo->getInternalURL();
1703 $u = new SquidUpdate( $urls );
1704 array_push( $wgPostCommitUpdateList, $u );
1708 # Client and file cache invalidation
1709 Title
::touchArray( $linksTo );
1711 # Move article and history to the "archive" table
1713 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1715 'ar_namespace' => 'page_namespace',
1716 'ar_title' => 'page_title',
1717 'ar_text' => 'old_text',
1718 'ar_comment' => 'rev_comment',
1719 'ar_user' => 'rev_user',
1720 'ar_user_text' => 'rev_user_text',
1721 'ar_timestamp' => 'rev_timestamp',
1722 'ar_minor_edit' => 'rev_minor_edit',
1723 'ar_flags' => 'old_flags',
1724 'ar_rev_id' => 'rev_id',
1726 'page_namespace' => $ns,
1728 'page_id = rev_page AND old_id = rev_id'
1732 # Now that it's safely backed up, delete it
1734 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1735 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1736 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1738 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1740 # Finally, clean up the link tables
1741 $t = $this->mTitle
->getPrefixedDBkey();
1743 Article
::onArticleDelete( $this->mTitle
);
1745 # Insert broken links
1746 $brokenLinks = array();
1747 foreach ( $linksTo as $titleObj ) {
1748 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1749 $linkID = $titleObj->getArticleID();
1750 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1752 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1755 $dbw->delete( 'links', array( 'l_to' => $id ) );
1756 $dbw->delete( 'links', array( 'l_from' => $id ) );
1757 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1758 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1759 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1762 $log = new LogPage( 'delete' );
1763 $log->addEntry( 'delete', $this->mTitle
, $reason );
1765 # Clear the cached article id so the interface doesn't act like we exist
1766 $this->mTitle
->resetArticleID( 0 );
1767 $this->mTitle
->mArticleID
= 0;
1772 * Revert a modification
1774 function rollback() {
1775 global $wgUser, $wgOut, $wgRequest;
1776 $fname = 'Article::rollback';
1778 if ( ! $wgUser->isAllowed('rollback') ) {
1779 $wgOut->sysopRequired();
1782 if ( wfReadOnly() ) {
1783 $wgOut->readOnlyPage( $this->getContent( true ) );
1786 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1787 array( $this->mTitle
->getPrefixedText(),
1788 $wgRequest->getVal( 'from' ) ) ) ) {
1789 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1790 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1793 $dbw =& wfGetDB( DB_MASTER
);
1795 # Enhanced rollback, marks edits rc_bot=1
1796 $bot = $wgRequest->getBool( 'bot' );
1798 # Replace all this user's current edits with the next one down
1799 $tt = $this->mTitle
->getDBKey();
1800 $n = $this->mTitle
->getNamespace();
1802 # Get the last editor, lock table exclusively
1804 $current = Revision
::newFromTitle( $this->mTitle
);
1805 if( is_null( $current ) ) {
1806 # Something wrong... no page?
1808 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1812 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1813 if( $from != $current->getUserText() ) {
1814 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1815 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1816 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1817 htmlspecialchars( $from ),
1818 htmlspecialchars( $current->getUserText() ) ) );
1819 if( $current->getComment() != '') {
1821 wfMsg( 'editcomment',
1822 htmlspecialchars( $current->getComment() ) ) );
1827 # Get the last edit not by this guy
1828 $user = IntVal( $current->getUser() );
1829 $user_text = $dbw->addQuotes( $current->getUserText() );
1830 $s = $dbw->selectRow( 'revision',
1831 array( 'rev_id', 'rev_timestamp' ),
1833 'rev_page' => $current->getPage(),
1834 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1837 'USE INDEX' => 'page_timestamp',
1838 'ORDER BY' => 'rev_timestamp DESC' )
1840 if( $s === false ) {
1843 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1844 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1849 # Mark all reverted edits as bot
1850 $dbw->update( 'recentchanges',
1853 ), array( /* WHERE */
1854 'rc_cur_id' => $current->getPage(),
1855 'rc_user_text' => $current->getUserText(),
1856 "rc_timestamp > '{$s->rev_timestamp}'",
1862 $target = Revision
::newFromId( $s->rev_id
);
1863 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1865 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1866 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1867 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1869 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1870 Article
::onArticleEdit( $this->mTitle
);
1873 $wgOut->returnToMain( false );
1878 * Do standard deferred updates after page view
1881 function viewUpdates() {
1882 global $wgDeferredUpdateList;
1884 if ( 0 != $this->getID() ) {
1885 global $wgDisableCounters;
1886 if( !$wgDisableCounters ) {
1887 Article
::incViewCount( $this->getID() );
1888 $u = new SiteStatsUpdate( 1, 0, 0 );
1889 array_push( $wgDeferredUpdateList, $u );
1893 # Update newtalk status if user is reading their own
1897 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1898 $this->mTitle
->getText() == $wgUser->getName()) {
1899 require_once( 'UserTalkUpdate.php' );
1900 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1902 $wgUser->clearNotification( $this->mTitle
);
1908 * Do standard deferred updates after page edit.
1909 * Every 1000th edit, prune the recent changes table.
1911 * @param string $text
1913 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1914 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1915 global $wgMessageCache, $wgUser;
1918 if ( 0 == mt_rand( 0, 999 ) ) {
1919 # Periodically flush old entries from the recentchanges table.
1921 $dbw =& wfGetDB( DB_MASTER
);
1922 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1923 $recentchanges = $dbw->tableName( 'recentchanges' );
1924 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1925 $dbw->query( $sql );
1927 $id = $this->getID();
1928 $title = $this->mTitle
->getPrefixedDBkey();
1929 $shortTitle = $this->mTitle
->getDBkey();
1931 $adj = $this->mCountAdjustment
;
1934 $u = new LinksUpdate( $id, $title );
1935 array_push( $wgDeferredUpdateList, $u );
1936 $u = new SiteStatsUpdate( 0, 1, $adj );
1937 array_push( $wgDeferredUpdateList, $u );
1938 $u = new SearchUpdate( $id, $title, $text );
1939 array_push( $wgDeferredUpdateList, $u );
1941 # If this is another user's talk page,
1942 # create a watchlist entry for this page
1944 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1945 $shortTitle != $wgUser->getName()) {
1946 require_once( 'UserTalkUpdate.php' );
1947 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1950 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1951 $wgMessageCache->replace( $shortTitle, $text );
1957 * @todo document this function
1959 * @param string $oldid Revision ID of this article revision
1961 function setOldSubtitle( $oldid=0 ) {
1962 global $wgLang, $wgOut, $wgUser;
1964 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1965 $sk = $wgUser->getSkin();
1966 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1967 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1968 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1969 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1970 $wgOut->setSubtitle( $r );
1974 * This function is called right before saving the wikitext,
1975 * so we can do things like signatures and links-in-context.
1977 * @param string $text
1979 function preSaveTransform( $text ) {
1980 global $wgParser, $wgUser;
1981 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1984 /* Caching functions */
1987 * checkLastModified returns true if it has taken care of all
1988 * output to the client that is necessary for this request.
1989 * (that is, it has sent a cached version of the page)
1991 function tryFileCache() {
1992 static $called = false;
1994 wfDebug( " tryFileCache() -- called twice!?\n" );
1998 if($this->isFileCacheable()) {
1999 $touched = $this->mTouched
;
2000 $cache = new CacheManager( $this->mTitle
);
2001 if($cache->isFileCacheGood( $touched )) {
2003 wfDebug( " tryFileCache() - about to load\n" );
2004 $cache->loadFromFileCache();
2007 wfDebug( " tryFileCache() - starting buffer\n" );
2008 ob_start( array(&$cache, 'saveToFileCache' ) );
2011 wfDebug( " tryFileCache() - not cacheable\n" );
2016 * Check if the page can be cached
2019 function isFileCacheable() {
2020 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2021 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2023 return $wgUseFileCache
2024 and (!$wgShowIPinHeader)
2025 and ($this->getID() != 0)
2026 and ($wgUser->isAnon())
2027 and (!$wgUser->getNewtalk())
2028 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2029 and (empty( $action ) ||
$action == 'view')
2030 and (!isset($oldid))
2032 and (!isset($redirect))
2033 and (!isset($printable))
2034 and (!$this->mRedirectedFrom
);
2038 * Loads cur_touched and returns a value indicating if it should be used
2041 function checkTouched() {
2042 $fname = 'Article::checkTouched';
2043 if( !$this->mDataLoaded
) {
2044 $dbr =& $this->getDB();
2045 $data = $this->pageDataFromId( $dbr, $this->getId() );
2047 $this->loadPageData( $data );
2050 return !$this->mIsRedirect
;
2054 * Edit an article without doing all that other stuff
2055 * The article must already exist; link tables etc
2056 * are not updated, caches are not flushed.
2058 * @param string $text text submitted
2059 * @param string $comment comment submitted
2060 * @param bool $minor whereas it's a minor modification
2062 function quickEdit( $text, $comment = '', $minor = 0 ) {
2063 $fname = 'Article::quickEdit';
2064 wfProfileIn( $fname );
2066 $dbw =& wfGetDB( DB_MASTER
);
2068 $revision = new Revision( array(
2069 'page' => $this->getId(),
2071 'comment' => $comment,
2072 'minor_edit' => $minor ?
1 : 0,
2074 $revisionId = $revision->insertOn( $dbw );
2075 $this->updateRevisionOn( $dbw, $revision );
2078 wfProfileOut( $fname );
2082 * Used to increment the view counter
2085 * @param integer $id article id
2087 function incViewCount( $id ) {
2088 $id = intval( $id );
2089 global $wgHitcounterUpdateFreq;
2091 $dbw =& wfGetDB( DB_MASTER
);
2092 $pageTable = $dbw->tableName( 'page' );
2093 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2094 $acchitsTable = $dbw->tableName( 'acchits' );
2096 if( $wgHitcounterUpdateFreq <= 1 ){ //
2097 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2101 # Not important enough to warrant an error page in case of failure
2102 $oldignore = $dbw->ignoreErrors( true );
2104 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2106 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2107 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2108 # Most of the time (or on SQL errors), skip row count check
2109 $dbw->ignoreErrors( $oldignore );
2113 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2114 $row = $dbw->fetchObject( $res );
2115 $rown = intval( $row->n
);
2116 if( $rown >= $wgHitcounterUpdateFreq ){
2117 wfProfileIn( 'Article::incViewCount-collect' );
2118 $old_user_abort = ignore_user_abort( true );
2120 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2121 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2122 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2124 $dbw->query("DELETE FROM $hitcounterTable");
2125 $dbw->query('UNLOCK TABLES');
2126 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2127 'WHERE cur_id = hc_id');
2128 $dbw->query("DROP TABLE $acchitsTable");
2130 ignore_user_abort( $old_user_abort );
2131 wfProfileOut( 'Article::incViewCount-collect' );
2133 $dbw->ignoreErrors( $oldignore );
2137 * The onArticle*() functions are supposed to be a kind of hooks
2138 * which should be called whenever any of the specified actions
2141 * This is a good place to put code to clear caches, for instance.
2143 * This is called on page move and undelete, as well as edit
2145 * @param $title_obj a title object
2148 function onArticleCreate($title_obj) {
2149 global $wgUseSquid, $wgPostCommitUpdateList;
2151 $titles = $title_obj->getBrokenLinksTo();
2154 if ( $wgUseSquid ) {
2155 $urls = $title_obj->getSquidURLs();
2156 foreach ( $titles as $linkTitle ) {
2157 $urls[] = $linkTitle->getInternalURL();
2159 $u = new SquidUpdate( $urls );
2160 array_push( $wgPostCommitUpdateList, $u );
2163 # Clear persistent link cache
2164 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2167 function onArticleDelete($title_obj) {
2168 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2170 function onArticleEdit($title_obj) {
2171 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2176 * Info about this page
2177 * Called for ?action=info when $wgAllowPageInfo is on.
2182 global $wgLang, $wgOut, $wgAllowPageInfo;
2183 $fname = 'Article::info';
2185 if ( !$wgAllowPageInfo ) {
2186 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2190 $page = $this->mTitle
->getSubjectPage();
2192 $wgOut->setPagetitle( $page->getPrefixedText() );
2193 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2195 # first, see if the page exists at all.
2196 $exists = $page->getArticleId() != 0;
2198 $wgOut->addHTML( wfMsg('noarticletext') );
2200 $dbr =& $this->getDB( DB_SLAVE
);
2202 'wl_title' => $page->getDBkey(),
2203 'wl_namespace' => $page->getNamespace() );
2204 $numwatchers = $dbr->selectField(
2209 $this->getSelectOptions() );
2211 $pageInfo = $this->pageCountInfo( $page );
2212 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2214 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2215 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2217 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2219 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2221 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2223 $wgOut->addHTML( '</ul>' );
2229 * Return the total number of edits and number of unique editors
2230 * on a given page. If page does not exist, returns false.
2232 * @param Title $title
2236 function pageCountInfo( $title ) {
2237 $id = $title->getArticleId();
2242 $dbr =& $this->getDB( DB_SLAVE
);
2244 $rev_clause = array( 'rev_page' => $id );
2245 $fname = 'Article::pageCountInfo';
2247 $edits = $dbr->selectField(
2252 $this->getSelectOptions() );
2254 $authors = $dbr->selectField(
2256 'COUNT(DISTINCT rev_user_text)',
2259 $this->getSelectOptions() );
2261 return array( 'edits' => $edits, 'authors' => $authors );