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->mContentLoaded
= false;
62 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
63 $this->mRedirectedFrom
= $this->mUserText
=
64 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
65 $this->mCountAdjustment
= 0;
66 $this->mTouched
= '19700101000000';
67 $this->mForUpdate
= false;
71 * Note that getContent/loadContent may follow redirects if
72 * not told otherwise, and so may cause a change to mTitle.
75 * @return Return the text of this revision
77 function getContent( $noredir ) {
80 # Get variables from query string :P
81 $action = $wgRequest->getText( 'action', 'view' );
82 $section = $wgRequest->getText( 'section' );
84 $fname = 'Article::getContent';
85 wfProfileIn( $fname );
87 if ( 0 == $this->getID() ) {
88 if ( 'edit' == $action ) {
89 wfProfileOut( $fname );
90 return ''; # was "newarticletext", now moved above the box)
92 wfProfileOut( $fname );
93 return wfMsg( 'noarticletext' );
95 $this->loadContent( $noredir );
96 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
97 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
98 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
101 wfProfileOut( $fname );
102 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
104 if($action=='edit') {
106 if($section=='new') {
107 wfProfileOut( $fname );
111 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
112 # comments to be stripped as well)
113 $rv=$this->getSection($this->mContent
,$section);
114 wfProfileOut( $fname );
118 wfProfileOut( $fname );
119 return $this->mContent
;
125 * This function returns the text of a section, specified by a number ($section).
126 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
127 * the first section before any such heading (section 0).
129 * If a section contains subsections, these are also returned.
131 * @param string $text text to look in
132 * @param integer $section section number
133 * @return string text of the requested section
135 function getSection($text,$section) {
137 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
138 # comments to be stripped as well)
140 $parser=new Parser();
141 $parser->mOutputType
=OT_WIKI
;
142 $striptext=$parser->strip($text, $striparray, true);
144 # now that we can be sure that no pseudo-sections are in the source,
145 # split it up by section
148 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
150 PREG_SPLIT_DELIM_CAPTURE
);
154 $headline=$secs[$section*2-1];
155 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
158 # translate wiki heading into level
159 if(strpos($hlevel,'=')!==false) {
160 $hlevel=strlen($hlevel);
163 $rv=$headline. $secs[$section*2];
167 while(!empty($secs[$count*2-1]) && !$break) {
169 $subheadline=$secs[$count*2-1];
170 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
171 $subhlevel=$matches[1];
172 if(strpos($subhlevel,'=')!==false) {
173 $subhlevel=strlen($subhlevel);
175 if($subhlevel > $hlevel) {
176 $rv.=$subheadline.$secs[$count*2];
178 if($subhlevel <= $hlevel) {
185 # reinsert stripped tags
186 $rv=$parser->unstrip($rv,$striparray);
187 $rv=$parser->unstripNoWiki($rv,$striparray);
194 * Return an array of the columns of the "cur"-table
196 function getContentFields() {
197 return $wgArticleContentFields = array(
198 'old_text','old_flags',
199 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
200 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
204 * Return the oldid of the article that is to be shown.
205 * For requests with a "direction", this is not the oldid of the
208 function getOldID() {
209 global $wgRequest, $wgOut;
212 if ( isset( $lastid ) ) {
216 $oldid = $wgRequest->getVal( 'oldid' );
217 if ( isset( $oldid ) ) {
218 $oldid = IntVal( $oldid );
219 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
220 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
224 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
226 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
227 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
236 return @$oldid; # "@" to be able to return "unset" without PHP complaining
241 * Load the revision (including cur_text) into this object
243 function loadContent( $noredir = false ) {
244 global $wgOut, $wgRequest;
246 if ( $this->mContentLoaded
) return;
249 $oldid = $this->getOldID();
250 $redirect = $wgRequest->getVal( 'redirect' );
252 $fname = 'Article::loadContent';
254 # Pre-fill content with error message so that if something
255 # fails we'll have something telling us what we intended.
257 $t = $this->mTitle
->getPrefixedText();
259 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no');
260 $this->mOldId
= $oldid;
261 $this->fetchContent( $oldid, $noredir, true );
266 * Fetch a page record with the given conditions
267 * @param Database $dbr
268 * @param array $conditions
271 function pageData( &$dbr, $conditions ) {
272 return $dbr->selectRow( 'page',
286 'Article::pageData' );
289 function pageDataFromTitle( &$dbr, $title ) {
290 return $this->pageData( $dbr, array(
291 'page_namespace' => $title->getNamespace(),
292 'page_title' => $title->getDBkey() ) );
295 function pageDataFromId( &$dbr, $id ) {
296 return $this->pageData( $dbr, array(
297 'page_id' => IntVal( $id ) ) );
301 * Get text of an article from database
302 * @param int $oldid 0 for whatever the latest revision is
303 * @param bool $noredir Set to true to avoid following redirects
304 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
307 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
308 if ( $this->mContentLoaded
) {
309 return $this->mContent
;
311 $dbr =& $this->getDB();
312 $fname = 'Article::fetchContent';
314 # Pre-fill content with error message so that if something
315 # fails we'll have something telling us what we intended.
316 $t = $this->mTitle
->getPrefixedText();
318 $t .= ',oldid='.$oldid;
320 if( isset( $redirect ) ) {
321 $redirect = ($redirect == 'no') ?
'no' : 'yes';
322 $t .= ',redirect='.$redirect;
324 $this->mContent
= wfMsg( 'missingarticle', $t );
327 $revision = Revision
::newFromId( $oldid );
328 if( is_null( $revision ) ) {
331 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
335 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
337 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
338 $revision = Revision
::newFromId( $data->page_latest
);
341 # If we got a redirect, follow it (unless we've been told
342 # not to by either the function parameter or the query
343 if ( !$oldid && !$noredir ) {
344 $rt = Title
::newFromRedirect( $revision->getText() );
345 # process if title object is valid and not special:userlogout
346 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
347 # Gotta hand redirects to special pages differently:
348 # Fill the HTTP response "Location" header and ignore
349 # the rest of the page we're on.
352 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
353 $wgOut->redirect( $rt->getFullURL() ) ;
356 if ( $rt->getNamespace() == NS_SPECIAL
) {
357 $wgOut->redirect( $rt->getFullURL() );
361 $redirData = $this->pageDataFromTitle( $dbr, $rt );
363 $redirRev = Revision
::newFromId( $redirData->page_latest
);
364 if( !is_null( $redirRev ) ) {
365 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
368 $revision = $redirRev;
374 # if the title's different from expected, update...
377 if( !$this->mTitle
->equals( $wgTitle ) ) {
378 $wgTitle = $this->mTitle
;
382 # Back to the business at hand...
383 $this->mCounter
= $data->page_counter
;
384 $this->mTitle
->mRestrictions
= explode( ',', trim( $data->page_restrictions
) );
385 $this->mTitle
->mRestrictionsLoaded
= true;
386 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
388 $this->mContent
= $revision->getText();
390 $this->mUser
= $revision->getUser();
391 $this->mUserText
= $revision->getUserText();
392 $this->mComment
= $revision->getComment();
393 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
395 $this->mContentLoaded
= true;
396 return $this->mContent
;
400 * Gets the article text without using so many damn globals
401 * Returns false on error
403 * @param integer $oldid
405 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
406 return $this->fetchContent( $oldid, $noredir, false );
410 * Read/write accessor to select FOR UPDATE
412 function forUpdate( $x = NULL ) {
413 return wfSetVar( $this->mForUpdate
, $x );
417 * Get the database which should be used for reads
420 #if ( $this->mForUpdate ) {
421 return wfGetDB( DB_MASTER
);
423 # return wfGetDB( DB_SLAVE );
428 * Get options for all SELECT statements
429 * Can pass an option array, to which the class-wide options will be appended
431 function getSelectOptions( $options = '' ) {
432 if ( $this->mForUpdate
) {
433 if ( is_array( $options ) ) {
434 $options[] = 'FOR UPDATE';
436 $options = 'FOR UPDATE';
443 * Return the Article ID
446 if( $this->mTitle
) {
447 return $this->mTitle
->getArticleID();
454 * Get the view count for this article
456 function getCount() {
457 if ( -1 == $this->mCounter
) {
458 $id = $this->getID();
459 $dbr =& $this->getDB();
460 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
461 'Article::getCount', $this->getSelectOptions() );
463 return $this->mCounter
;
467 * Would the given text make this article a "good" article (i.e.,
468 * suitable for including in the article count)?
469 * @param string $text Text to analyze
470 * @return integer 1 if it can be counted else 0
472 function isCountable( $text ) {
473 global $wgUseCommaCount;
475 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
476 if ( $this->isRedirect( $text ) ) { return 0; }
477 $token = ($wgUseCommaCount ?
',' : '[[' );
478 if ( false === strstr( $text, $token ) ) { return 0; }
483 * Tests if the article text represents a redirect
485 function isRedirect( $text = false ) {
486 if ( $text === false ) {
487 $this->loadContent();
488 $titleObj = Title
::newFromRedirect( $this->mText
);
490 $titleObj = Title
::newFromRedirect( $text );
492 return $titleObj !== NULL;
496 * Loads everything except the text
497 * This isn't necessary for all uses, so it's only done if needed.
500 function loadLastEdit() {
503 if ( -1 != $this->mUser
)
506 # New or non-existent articles have no user information
507 $id = $this->getID();
508 if ( 0 == $id ) return;
510 $fname = 'Article::loadLastEdit';
512 $dbr =& $this->getDB();
513 $s = $dbr->selectRow( array( 'revision', 'page') ,
514 array( 'rev_user','rev_user_text','rev_timestamp', 'rev_comment','rev_minor_edit' ),
515 array( 'page_id' => $id, 'page_latest=rev_id' ), $fname, $this->getSelectOptions() );
517 if ( $s !== false ) {
518 $this->mUser
= $s->rev_user
;
519 $this->mUserText
= $s->rev_user_text
;
520 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->rev_timestamp
);
521 $this->mComment
= $s->rev_comment
;
522 $this->mMinorEdit
= $s->rev_minor_edit
;
526 function getTimestamp() {
527 $this->loadLastEdit();
528 return $this->mTimestamp
;
532 $this->loadLastEdit();
536 function getUserText() {
537 $this->loadLastEdit();
538 return $this->mUserText
;
541 function getComment() {
542 $this->loadLastEdit();
543 return $this->mComment
;
546 function getMinorEdit() {
547 $this->loadLastEdit();
548 return $this->mMinorEdit
;
551 function getContributors($limit = 0, $offset = 0) {
552 $fname = 'Article::getContributors';
554 # XXX: this is expensive; cache this info somewhere.
556 $title = $this->mTitle
;
558 $dbr =& $this->getDB();
559 $revTable = $dbr->tableName( 'revision' );
560 $userTable = $dbr->tableName( 'user' );
561 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
562 $ns = $title->getNamespace();
563 $user = $this->getUser();
564 $pageId = $this->getId();
566 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
567 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
568 WHERE rev_page = $pageId
569 AND rev_user != $user
570 GROUP BY rev_user, rev_user_text, user_real_name
571 ORDER BY timestamp DESC";
573 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
574 $sql .= ' '. $this->getSelectOptions();
576 $res = $dbr->query($sql, $fname);
578 while ( $line = $dbr->fetchObject( $res ) ) {
579 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
582 $dbr->freeResult($res);
587 * This is the default action of the script: just view the page of
591 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
592 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
593 global $wgEnotif, $wgParser;
594 $sk = $wgUser->getSkin();
596 $fname = 'Article::view';
597 wfProfileIn( $fname );
598 # Get variables from query string
599 $oldid = $this->getOldID();
600 $diff = $wgRequest->getVal( 'diff' );
601 $rcid = $wgRequest->getVal( 'rcid' );
602 $rdfrom = $wgRequest->getVal( 'rdfrom' );
604 $wgOut->setArticleFlag( true );
605 $wgOut->setRobotpolicy( 'index,follow' );
606 # If we got diff and oldid in the query, we want to see a
607 # diff page instead of the article.
609 if ( !is_null( $diff ) ) {
610 require_once( 'DifferenceEngine.php' );
611 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
612 $de = new DifferenceEngine( $oldid, $diff, $rcid );
615 # Run view updates for current revision only
616 $this->viewUpdates();
618 wfProfileOut( $fname );
621 if ( empty( $oldid ) && $this->checkTouched() ) {
622 if( $wgOut->checkLastModified( $this->mTouched
) ){
623 wfProfileOut( $fname );
625 } else if ( $this->tryFileCache() ) {
626 # tell wgOut that output is taken care of
628 $this->viewUpdates();
629 wfProfileOut( $fname );
633 # Should the parser cache be used?
634 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
642 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
646 if ( !$outputDone ) {
647 $text = $this->getContent( false ); # May change mTitle by following a redirect
649 # Another whitelist check in case oldid or redirects are altering the title
650 if ( !$this->mTitle
->userCanRead() ) {
651 $wgOut->loginToUse();
657 # We're looking at an old revision
659 if ( !empty( $oldid ) ) {
660 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
661 $wgOut->setRobotpolicy( 'noindex,follow' );
663 if ( '' != $this->mRedirectedFrom
) {
664 $sk = $wgUser->getSkin();
665 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
667 $s = wfMsg( 'redirectedfrom', $redir );
668 $wgOut->setSubtitle( $s );
670 # Can't cache redirects
672 } elseif ( !empty( $rdfrom ) ) {
673 $sk = $wgUser->getSkin();
674 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
675 $s = wfMsg( 'redirectedfrom', $redir );
676 $wgOut->setSubtitle( $s );
679 # wrap user css and user js in pre and don't parse
680 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
682 $this->mTitle
->getNamespace() == NS_USER
&&
683 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
685 $wgOut->addWikiText( wfMsg('clearyourcache'));
686 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
687 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
689 $imageUrl = $wgStylePath.'/common/images/redirect.png';
690 $targetUrl = $rt->escapeLocalURL();
691 $titleText = htmlspecialchars( $rt->getPrefixedText() );
692 $link = $sk->makeLinkObj( $rt );
694 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
695 '<span class="redirectText">'.$link.'</span>' );
697 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
698 $catlinks = $parseout->getCategoryLinks();
699 $wgOut->addCategoryLinks($catlinks);
700 $skin = $wgUser->getSkin();
701 } else if ( $pcache ) {
702 # Display content and save to parser cache
703 $wgOut->addPrimaryWikiText( $text, $this );
705 # Display content, don't attempt to save to parser cache
706 $wgOut->addWikiText( $text );
709 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
710 # If we have been passed an &rcid= parameter, we want to give the user a
711 # chance to mark this new article as patrolled.
712 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->isLoggedIn() &&
713 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
715 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
716 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
717 'action=markpatrolled&rcid='.$rcid )
721 # Put link titles into the link cache
722 $wgOut->transformBuffer();
724 # Add link titles as META keywords
725 $wgOut->addMetaTags() ;
727 $this->viewUpdates();
728 wfProfileOut( $fname );
730 $wgUser->clearNotification( $this->mTitle
);
734 * Insert a new empty page record for this article.
735 * This *must* be followed up by creating a revision
736 * and running $this->updateToLatest( $rev_id );
737 * or else the record will be left in a funky state.
738 * Best if all done inside a transaction.
740 * @param Database $dbw
741 * @return int The newly created page_id key
744 function insertOn( &$dbw ) {
745 $fname = 'Article::insertOn';
746 wfProfileIn( $fname );
748 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
749 $dbw->insert( 'page', array(
750 'page_id' => $page_id,
751 'page_namespace' => $this->mTitle
->getNamespace(),
752 'page_title' => $this->mTitle
->getDBkey(),
754 'page_restrictions' => '',
755 'page_is_redirect' => 0, # Will set this shortly...
757 'page_random' => wfRandom(),
758 'page_touched' => $dbw->timestamp(),
759 'page_latest' => 0, # Fill this in shortly...
761 $newid = $dbw->insertId();
763 $this->mTitle
->resetArticleId( $newid );
765 wfProfileOut( $fname );
770 * Update the page record to point to a newly saved revision.
772 * @param Database $dbw
773 * @param Revision $revision -- for ID number, and text used to set
774 length and redirect status fields
775 * @param int $lastRevision -- if given, will not overwrite the page field
776 * when different from the currently set value.
777 * Giving 0 indicates the new page flag should
779 * @return bool true on success, false on failure
782 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
783 $fname = 'Article::updateToRevision';
784 wfProfileIn( $fname );
786 $conditions = array( 'page_id' => $this->getId() );
787 if( !is_null( $lastRevision ) ) {
788 # An extra check against threads stepping on each other
789 $conditions['page_latest'] = $lastRevision;
791 $text = $revision->getText();
792 $dbw->update( 'page',
794 'page_latest' => $revision->getId(),
795 'page_touched' => $dbw->timestamp(),
796 'page_is_new' => ($lastRevision === 0) ?
0 : 1,
797 'page_is_redirect' => Article
::isRedirect( $text ),
798 'page_len' => strlen( $text ),
803 wfProfileOut( $fname );
804 return ( $dbw->affectedRows() != 0 );
808 * If the given revision is newer than the currently set page_latest,
809 * update the page record. Otherwise, do nothing.
811 * @param Database $dbw
812 * @param Revision $revision
814 function updateIfNewerOn( &$dbw, $revision ) {
815 $fname = 'Article::updateIfNewerOn';
816 wfProfileIn( $fname );
818 $row = $dbw->selectRow(
819 array( 'revision', 'page' ),
820 array( 'rev_id', 'rev_timestamp' ),
822 'page_id' => $this->getId(),
823 'page_latest=rev_id' ),
826 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
827 wfProfileOut( $fname );
830 $prev = $row->rev_id
;
832 # No or missing previous revision; mark the page as new
836 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
837 wfProfileOut( $fname );
842 * Theoretically we could defer these whole insert and update
843 * functions for after display, but that's taking a big leap
844 * of faith, and we want to be able to report database
845 * errors at some point.
848 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
849 global $wgOut, $wgUser;
850 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
852 $fname = 'Article::insertNewArticle';
854 $this->mCountAdjustment
= $this->isCountable( $text );
856 $ns = $this->mTitle
->getNamespace();
857 $ttl = $this->mTitle
->getDBkey();
858 $text = $this->preSaveTransform( $text );
859 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
861 $dbw =& wfGetDB( DB_MASTER
);
863 # Add the page record; stake our claim on this title!
864 $newid = $this->insertOn( $dbw );
866 # Save the revision text...
867 $revision = new Revision( array(
869 'comment' => $summary,
870 'minor_edit' => $isminor,
873 $revisionId = $revision->insertOn( $dbw );
875 $this->mTitle
->resetArticleID( $newid );
877 # Update the page record with revision data
878 $this->updateRevisionOn( $dbw, $revision, 0 );
880 Article
::onArticleCreate( $this->mTitle
);
881 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
884 if(!$this->mTitle
->userIsWatching()) $this->watch();
886 if ( $this->mTitle
->userIsWatching() ) {
891 # The talk page isn't in the regular link tables, so we need to update manually:
892 $talkns = $ns ^
1; # talk -> normal; normal -> talk
893 $dbw->update( 'page',
894 array( 'page_touched' => $dbw->timestamp($now) ),
895 array( 'page_namespace' => $talkns,
896 'page_title' => $ttl ),
899 # standard deferred updates
900 $this->editUpdates( $text, $summary, $isminor, $now );
902 $oldid = 0; # new article
903 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
907 * Fetch and uncompress the text for a given revision.
908 * Can ask by rev_id number or timestamp (set $field)
910 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
911 $fname = 'Article::fetchRevisionText';
912 $dbw =& wfGetDB( DB_MASTER
);
914 $rev = $dbw->addQuotes( $revId );
916 $rev = 'page_latest';
918 $result = $dbw->query(
919 sprintf( "SELECT old_text, old_flags
921 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
923 $dbw->tableName( 'page' ),
924 $dbw->tableName( 'revision' ),
925 $dbw->tableName( 'text' ),
926 IntVal( $this->mTitle
->getArticleId() ),
930 $obj = $dbw->fetchObject( $result );
931 $dbw->freeResult( $result );
932 $oldtext = Revision
::getRevisionText( $obj );
936 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
937 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
938 if( is_null( $edittime ) ) {
939 $oldtext = $this->fetchRevisionText();
941 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
943 if ($section != '') {
944 if($section=='new') {
945 if($summary) $subject="== {$summary} ==\n\n";
946 $text=$oldtext."\n\n".$subject.$text;
949 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
950 # comments to be stripped as well)
952 $parser=new Parser();
953 $parser->mOutputType
=OT_WIKI
;
954 $oldtext=$parser->strip($oldtext, $striparray, true);
956 # now that we can be sure that no pseudo-sections are in the source,
958 # Unfortunately we can't simply do a preg_replace because that might
959 # replace the wrong section, so we have to use the section counter instead
960 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
961 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
962 $secs[$section*2]=$text."\n\n"; // replace with edited
964 # section 0 is top (intro) section
967 # headline of old section - we need to go through this section
968 # to determine if there are any subsections that now need to
969 # be erased, as the mother section has been replaced with
970 # the text of all subsections.
971 $headline=$secs[$section*2-1];
972 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
975 # determine headline level for wikimarkup headings
976 if(strpos($hlevel,'=')!==false) {
977 $hlevel=strlen($hlevel);
980 $secs[$section*2-1]=''; // erase old headline
983 while(!empty($secs[$count*2-1]) && !$break) {
985 $subheadline=$secs[$count*2-1];
987 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
988 $subhlevel=$matches[1];
989 if(strpos($subhlevel,'=')!==false) {
990 $subhlevel=strlen($subhlevel);
992 if($subhlevel > $hlevel) {
993 // erase old subsections
994 $secs[$count*2-1]='';
997 if($subhlevel <= $hlevel) {
1005 $text=join('',$secs);
1006 # reinsert the stuff that we stripped out earlier
1007 $text=$parser->unstrip($text,$striparray);
1008 $text=$parser->unstripNoWiki($text,$striparray);
1016 * Change an existing article. Puts the previous version back into the old table, updates RC
1017 * and all necessary caches, mostly via the deferred update array.
1019 * It is possible to call this function from a command-line script, but note that you should
1020 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1022 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1023 global $wgOut, $wgUser;
1024 global $wgDBtransactions, $wgMwRedir;
1025 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1027 $fname = 'Article::updateArticle';
1030 $isminor = ( $minor && $wgUser->isLoggedIn() );
1031 if ( $this->isRedirect( $text ) ) {
1032 # Remove all content but redirect
1033 # This could be done by reconstructing the redirect from a title given by
1034 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1036 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1038 $text = $m[1] . "\n";
1041 else { $redir = 0; }
1043 $text = $this->preSaveTransform( $text );
1044 $dbw =& wfGetDB( DB_MASTER
);
1046 # Update article, but only if changed.
1048 # It's important that we either rollback or complete, otherwise an attacker could
1049 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1050 # could conceivably have the same effect, especially if cur is locked for long periods.
1051 if( $wgDBtransactions ) {
1052 $dbw->query( 'BEGIN', $fname );
1054 $userAbort = ignore_user_abort( true );
1057 $oldtext = $this->getContent( true );
1059 if ( 0 != strcmp( $text, $oldtext ) ) {
1060 $this->mCountAdjustment
= $this->isCountable( $text )
1061 - $this->isCountable( $oldtext );
1062 $now = wfTimestampNow();
1064 $lastRevision = $dbw->selectField(
1065 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1067 $revision = new Revision( array(
1068 'page' => $this->getId(),
1069 'comment' => $summary,
1070 'minor_edit' => $isminor,
1073 $revisionId = $revision->insertOn( $dbw );
1076 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1079 /* Belated edit conflict! Run away!! */
1082 # Update recentchanges and purge cache and whatnot
1083 $bot = (int)($wgUser->isBot() ||
$forceBot);
1084 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1085 $lastRevision, $this->getTimestamp(), $bot );
1086 Article
::onArticleEdit( $this->mTitle
);
1090 if( $wgDBtransactions ) {
1091 $dbw->query( 'COMMIT', $fname );
1093 ignore_user_abort( $userAbort );
1098 if (!$this->mTitle
->userIsWatching()) $this->watch();
1100 if ( $this->mTitle
->userIsWatching() ) {
1104 # standard deferred updates
1105 $this->editUpdates( $text, $summary, $minor, $now );
1109 # Template namespace
1110 # Purge all articles linking here
1111 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1112 $titles = $this->mTitle
->getLinksTo();
1113 Title
::touchArray( $titles );
1114 if ( $wgUseSquid ) {
1115 foreach ( $titles as $title ) {
1116 $urls[] = $title->getInternalURL();
1122 if ( $wgUseSquid ) {
1123 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1124 $u = new SquidUpdate( $urls );
1125 array_push( $wgPostCommitUpdateList, $u );
1128 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1134 * After we've either updated or inserted the article, update
1135 * the link tables and redirect to the new page.
1137 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1138 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1140 $wgLinkCache = new LinkCache();
1142 $wgLinkCache->forUpdate( true );
1144 # Get old version of link table to allow incremental link updates
1145 $wgLinkCache->preFill( $this->mTitle
);
1146 $wgLinkCache->clear();
1148 # Parse the text and replace links with placeholders
1149 $wgOut = new OutputPage();
1150 $wgOut->addWikiText( $text );
1152 # Look up the links in the DB and add them to the link cache
1153 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1155 if( $this->isRedirect( $text ) )
1159 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1161 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1162 # this will be improved later (to-do)
1164 include_once( "UserMailer.php" );
1165 $wgEnotif = new EmailNotification ();
1166 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1170 * Mark this particular edit as patrolled
1172 function markpatrolled() {
1173 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1174 $wgOut->setRobotpolicy( 'noindex,follow' );
1176 if ( !$wgUseRCPatrol )
1178 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1181 if ( $wgUser->isAnon() )
1183 $wgOut->loginToUse();
1186 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1188 $wgOut->sysopRequired();
1191 $rcid = $wgRequest->getVal( 'rcid' );
1192 if ( !is_null ( $rcid ) )
1194 RecentChange
::markPatrolled( $rcid );
1195 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1196 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1198 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1199 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1203 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1209 * Add this page to $wgUser's watchlist
1214 global $wgUser, $wgOut;
1216 if ( $wgUser->isAnon() ) {
1217 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1220 if ( wfReadOnly() ) {
1221 $wgOut->readOnlyPage();
1225 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1227 $wgUser->addWatch( $this->mTitle
);
1228 $wgUser->saveSettings();
1230 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1232 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1233 $wgOut->setRobotpolicy( 'noindex,follow' );
1235 $link = $this->mTitle
->getPrefixedText();
1236 $text = wfMsg( 'addedwatchtext', $link );
1237 $wgOut->addWikiText( $text );
1240 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1244 * Stop watching a page
1247 function unwatch() {
1249 global $wgUser, $wgOut;
1251 if ( $wgUser->isAnon() ) {
1252 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1255 if ( wfReadOnly() ) {
1256 $wgOut->readOnlyPage();
1260 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1262 $wgUser->removeWatch( $this->mTitle
);
1263 $wgUser->saveSettings();
1265 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1267 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1268 $wgOut->setRobotpolicy( 'noindex,follow' );
1270 $link = $this->mTitle
->getPrefixedText();
1271 $text = wfMsg( 'removedwatchtext', $link );
1272 $wgOut->addWikiText( $text );
1275 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1281 function protect( $limit = 'sysop' ) {
1282 global $wgUser, $wgOut, $wgRequest;
1284 if ( ! $wgUser->isAllowed('protect') ) {
1285 $wgOut->sysopRequired();
1288 if ( wfReadOnly() ) {
1289 $wgOut->readOnlyPage();
1292 $id = $this->mTitle
->getArticleID();
1294 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1298 $confirm = $wgRequest->wasPosted() &&
1299 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1300 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1301 $reason = $wgRequest->getText( 'wpReasonProtect' );
1304 $dbw =& wfGetDB( DB_MASTER
);
1305 $dbw->update( 'page',
1307 'page_touched' => $dbw->timestamp(),
1308 'page_restrictions' => (string)$limit
1309 ), array( /* WHERE */
1311 ), 'Article::protect'
1314 $restrictions = "move=" . $limit;
1316 $restrictions .= ":edit=" . $limit;
1318 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1320 $dbw =& wfGetDB( DB_MASTER
);
1321 $dbw->update( 'page',
1323 'page_touched' => $dbw->timestamp(),
1324 'page_restrictions' => $restrictions
1325 ), array( /* WHERE */
1327 ), 'Article::protect'
1330 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1332 $log = new LogPage( 'protect' );
1333 if ( $limit === '' ) {
1334 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1336 $log->addEntry( 'protect', $this->mTitle
, $reason );
1338 $wgOut->redirect( $this->mTitle
->getFullURL() );
1342 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1343 return $this->confirmProtect( '', $reason, $limit );
1348 * Output protection confirmation dialog
1350 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1351 global $wgOut, $wgUser;
1353 wfDebug( "Article::confirmProtect\n" );
1355 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1356 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1362 if ( $limit === '' ) {
1363 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1364 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1365 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1366 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1367 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1369 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1370 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1371 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1372 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1373 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1374 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1377 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1378 $token = htmlspecialchars( $wgUser->editToken() );
1381 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1385 <label for='wpReasonProtect'>{$protcom}:</label>
1388 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1394 if($moveonly != '') {
1398 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1401 <label for='wpMoveOnly'>{$moveonly}</label>
1409 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1413 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1416 $wgOut->returnToMain( false );
1420 * Unprotect the pages
1422 function unprotect() {
1423 return $this->protect( '' );
1427 * UI entry point for page deletion
1430 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1431 $fname = 'Article::delete';
1432 $confirm = $wgRequest->wasPosted() &&
1433 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1434 $reason = $wgRequest->getText( 'wpReason' );
1436 # This code desperately needs to be totally rewritten
1439 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1440 $wgOut->sysopRequired();
1443 if ( wfReadOnly() ) {
1444 $wgOut->readOnlyPage();
1448 # Better double-check that it hasn't been deleted yet!
1449 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1450 if ( ( '' == trim( $this->mTitle
->getText() ) )
1451 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1452 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1457 $this->doDelete( $reason );
1461 # determine whether this page has earlier revisions
1462 # and insert a warning if it does
1463 # we select the text because it might be useful below
1464 $dbr =& $this->getDB();
1465 $ns = $this->mTitle
->getNamespace();
1466 $title = $this->mTitle
->getDBkey();
1467 $revisions = $dbr->select( array( 'page', 'revision' ),
1470 'page_namespace' => $ns,
1471 'page_title' => $title,
1472 'rev_page = page_id'
1473 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1476 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1477 $skin=$wgUser->getSkin();
1478 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1479 $wgOut->addHTML( $skin->historyLink() .'</b>');
1483 $s = $dbr->selectRow( array( 'page', 'text' ),
1484 array( 'old_text' ),
1486 'page_namespace' => $ns,
1487 'page_title' => $title,
1488 'page_latest = old_id'
1489 ), $fname, $this->getSelectOptions()
1492 if( $s !== false ) {
1493 # if this is a mini-text, we can paste part of it into the deletion reason
1495 #if this is empty, an earlier revision may contain "useful" text
1497 if($s->old_text
!= '') {
1501 $text = Revision
::getRevisionText( $old );
1507 $length=strlen($text);
1509 # this should not happen, since it is not possible to store an empty, new
1510 # page. Let's insert a standard text in case it does, though
1511 if($length == 0 && $reason === '') {
1512 $reason = wfMsg('exblank');
1515 if($length < 500 && $reason === '') {
1517 # comment field=255, let's grep the first 150 to have some user
1519 $text=substr($text,0,150);
1520 # let's strip out newlines and HTML tags
1521 $text=preg_replace('/\"/',"'",$text);
1522 $text=preg_replace('/\</','<',$text);
1523 $text=preg_replace('/\>/','>',$text);
1524 $text=preg_replace("/[\n\r]/",'',$text);
1526 $reason=wfMsg('excontent'). " '".$text;
1528 $reason=wfMsg('exbeforeblank') . " '".$text;
1530 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1535 return $this->confirmDelete( '', $reason );
1539 * Output deletion confirmation dialog
1541 function confirmDelete( $par, $reason ) {
1542 global $wgOut, $wgUser;
1544 wfDebug( "Article::confirmDelete\n" );
1546 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1547 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1548 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1549 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1551 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1553 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1554 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1555 $token = htmlspecialchars( $wgUser->editToken() );
1558 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1562 <label for='wpReason'>{$delcom}:</label>
1565 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1574 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1578 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1581 $wgOut->returnToMain( false );
1586 * Perform a deletion and output success or failure messages
1588 function doDelete( $reason ) {
1589 global $wgOut, $wgUser, $wgContLang;
1590 $fname = 'Article::doDelete';
1591 wfDebug( $fname."\n" );
1593 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1594 if ( $this->doDeleteArticle( $reason ) ) {
1595 $deleted = $this->mTitle
->getPrefixedText();
1597 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1598 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1600 $sk = $wgUser->getSkin();
1601 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1602 ':' . wfMsgForContent( 'dellogpage' ),
1603 wfMsg( 'deletionlog' ) );
1605 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1607 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1608 $wgOut->returnToMain( false );
1609 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1611 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1617 * Back-end article deletion
1618 * Deletes the article with database consistency, writes logs, purges caches
1621 function doDeleteArticle( $reason ) {
1623 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1625 $fname = 'Article::doDeleteArticle';
1626 wfDebug( $fname."\n" );
1628 $dbw =& wfGetDB( DB_MASTER
);
1629 $ns = $this->mTitle
->getNamespace();
1630 $t = $this->mTitle
->getDBkey();
1631 $id = $this->mTitle
->getArticleID();
1633 if ( $t == '' ||
$id == 0 ) {
1637 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1638 array_push( $wgDeferredUpdateList, $u );
1640 $linksTo = $this->mTitle
->getLinksTo();
1643 if ( $wgUseSquid ) {
1645 $this->mTitle
->getInternalURL(),
1646 $this->mTitle
->getInternalURL( 'history' )
1648 foreach ( $linksTo as $linkTo ) {
1649 $urls[] = $linkTo->getInternalURL();
1652 $u = new SquidUpdate( $urls );
1653 array_push( $wgPostCommitUpdateList, $u );
1657 # Client and file cache invalidation
1658 Title
::touchArray( $linksTo );
1660 # Move article and history to the "archive" table
1662 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1664 'ar_namespace' => 'page_namespace',
1665 'ar_title' => 'page_title',
1666 'ar_text' => 'old_text',
1667 'ar_comment' => 'rev_comment',
1668 'ar_user' => 'rev_user',
1669 'ar_user_text' => 'rev_user_text',
1670 'ar_timestamp' => 'rev_timestamp',
1671 'ar_minor_edit' => 'rev_minor_edit',
1672 'ar_flags' => 'old_flags',
1673 'ar_rev_id' => 'rev_id',
1675 'page_namespace' => $ns,
1677 'page_id = rev_page AND old_id = rev_id'
1681 # Now that it's safely backed up, delete it
1683 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1684 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1685 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1687 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1689 # Finally, clean up the link tables
1690 $t = $this->mTitle
->getPrefixedDBkey();
1692 Article
::onArticleDelete( $this->mTitle
);
1694 # Insert broken links
1695 $brokenLinks = array();
1696 foreach ( $linksTo as $titleObj ) {
1697 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1698 $linkID = $titleObj->getArticleID();
1699 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1701 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1704 $dbw->delete( 'links', array( 'l_to' => $id ) );
1705 $dbw->delete( 'links', array( 'l_from' => $id ) );
1706 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1707 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1708 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1711 $log = new LogPage( 'delete' );
1712 $log->addEntry( 'delete', $this->mTitle
, $reason );
1714 # Clear the cached article id so the interface doesn't act like we exist
1715 $this->mTitle
->resetArticleID( 0 );
1716 $this->mTitle
->mArticleID
= 0;
1721 * Revert a modification
1723 function rollback() {
1724 global $wgUser, $wgOut, $wgRequest;
1725 $fname = 'Article::rollback';
1727 if ( ! $wgUser->isAllowed('rollback') ) {
1728 $wgOut->sysopRequired();
1731 if ( wfReadOnly() ) {
1732 $wgOut->readOnlyPage( $this->getContent( true ) );
1735 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1736 array( $this->mTitle
->getPrefixedText(),
1737 $wgRequest->getVal( 'from' ) ) ) ) {
1738 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1739 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1742 $dbw =& wfGetDB( DB_MASTER
);
1744 # Enhanced rollback, marks edits rc_bot=1
1745 $bot = $wgRequest->getBool( 'bot' );
1747 # Replace all this user's current edits with the next one down
1748 $tt = $this->mTitle
->getDBKey();
1749 $n = $this->mTitle
->getNamespace();
1751 # Get the last editor, lock table exclusively
1753 $current = Revision
::newFromTitle( $this->mTitle
);
1754 if( is_null( $current ) ) {
1755 # Something wrong... no page?
1757 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1761 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1762 if( $from != $current->getUserText() ) {
1763 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1764 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1765 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1766 htmlspecialchars( $from ),
1767 htmlspecialchars( $current->getUserText() ) ) );
1768 if( $current->getComment() != '') {
1770 wfMsg( 'editcomment',
1771 htmlspecialchars( $current->getComment() ) ) );
1776 # Get the last edit not by this guy
1777 $user = IntVal( $current->getUser() );
1778 $user_text = $dbw->addQuotes( $current->getUserText() );
1779 $s = $dbw->selectRow( 'revision',
1780 array( 'rev_id', 'rev_timestamp' ),
1782 'rev_page' => $current->getPage(),
1783 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1786 'USE INDEX' => 'page_timestamp',
1787 'ORDER BY' => 'rev_timestamp DESC' )
1789 if( $s === false ) {
1792 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1793 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1798 # Mark all reverted edits as bot
1799 $dbw->update( 'recentchanges',
1802 ), array( /* WHERE */
1803 'rc_cur_id' => $current->getPage(),
1804 'rc_user_text' => $current->getUserText(),
1805 "rc_timestamp > '{$s->rev_timestamp}'",
1811 $target = Revision
::newFromId( $s->rev_id
);
1812 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1814 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1815 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1816 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1818 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1819 Article
::onArticleEdit( $this->mTitle
);
1822 $wgOut->returnToMain( false );
1827 * Do standard deferred updates after page view
1830 function viewUpdates() {
1831 global $wgDeferredUpdateList;
1833 if ( 0 != $this->getID() ) {
1834 global $wgDisableCounters;
1835 if( !$wgDisableCounters ) {
1836 Article
::incViewCount( $this->getID() );
1837 $u = new SiteStatsUpdate( 1, 0, 0 );
1838 array_push( $wgDeferredUpdateList, $u );
1842 # Update newtalk status if user is reading their own
1846 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1847 $this->mTitle
->getText() == $wgUser->getName()) {
1848 require_once( 'UserTalkUpdate.php' );
1849 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1854 * Do standard deferred updates after page edit.
1855 * Every 1000th edit, prune the recent changes table.
1857 * @param string $text
1859 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1860 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1861 global $wgMessageCache, $wgUser;
1864 if ( 0 == mt_rand( 0, 999 ) ) {
1865 # Periodically flush old entries from the recentchanges table.
1867 $dbw =& wfGetDB( DB_MASTER
);
1868 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1869 $recentchanges = $dbw->tableName( 'recentchanges' );
1870 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1871 $dbw->query( $sql );
1873 $id = $this->getID();
1874 $title = $this->mTitle
->getPrefixedDBkey();
1875 $shortTitle = $this->mTitle
->getDBkey();
1877 $adj = $this->mCountAdjustment
;
1880 $u = new LinksUpdate( $id, $title );
1881 array_push( $wgDeferredUpdateList, $u );
1882 $u = new SiteStatsUpdate( 0, 1, $adj );
1883 array_push( $wgDeferredUpdateList, $u );
1884 $u = new SearchUpdate( $id, $title, $text );
1885 array_push( $wgDeferredUpdateList, $u );
1887 # If this is another user's talk page,
1888 # create a watchlist entry for this page
1890 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1891 $shortTitle != $wgUser->getName()) {
1892 require_once( 'UserTalkUpdate.php' );
1893 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1896 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1897 $wgMessageCache->replace( $shortTitle, $text );
1903 * @todo document this function
1905 * @param string $oldid Revision ID of this article revision
1907 function setOldSubtitle( $oldid=0 ) {
1908 global $wgLang, $wgOut, $wgUser;
1910 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1911 $sk = $wgUser->getSkin();
1912 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1913 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1914 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1915 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1916 $wgOut->setSubtitle( $r );
1920 * This function is called right before saving the wikitext,
1921 * so we can do things like signatures and links-in-context.
1923 * @param string $text
1925 function preSaveTransform( $text ) {
1926 global $wgParser, $wgUser;
1927 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1930 /* Caching functions */
1933 * checkLastModified returns true if it has taken care of all
1934 * output to the client that is necessary for this request.
1935 * (that is, it has sent a cached version of the page)
1937 function tryFileCache() {
1938 static $called = false;
1940 wfDebug( " tryFileCache() -- called twice!?\n" );
1944 if($this->isFileCacheable()) {
1945 $touched = $this->mTouched
;
1946 $cache = new CacheManager( $this->mTitle
);
1947 if($cache->isFileCacheGood( $touched )) {
1949 wfDebug( " tryFileCache() - about to load\n" );
1950 $cache->loadFromFileCache();
1953 wfDebug( " tryFileCache() - starting buffer\n" );
1954 ob_start( array(&$cache, 'saveToFileCache' ) );
1957 wfDebug( " tryFileCache() - not cacheable\n" );
1962 * Check if the page can be cached
1965 function isFileCacheable() {
1966 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1967 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1969 return $wgUseFileCache
1970 and (!$wgShowIPinHeader)
1971 and ($this->getID() != 0)
1972 and ($wgUser->isAnon())
1973 and (!$wgUser->getNewtalk())
1974 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1975 and (empty( $action ) ||
$action == 'view')
1976 and (!isset($oldid))
1978 and (!isset($redirect))
1979 and (!isset($printable))
1980 and (!$this->mRedirectedFrom
);
1984 * Loads cur_touched and returns a value indicating if it should be used
1987 function checkTouched() {
1988 $fname = 'Article::checkTouched';
1989 $id = $this->getID();
1990 $dbr =& $this->getDB();
1991 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1992 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1993 if( $s !== false ) {
1994 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
1995 return !$s->page_is_redirect
;
2002 * Edit an article without doing all that other stuff
2003 * The article must already exist; link tables etc
2004 * are not updated, caches are not flushed.
2006 * @param string $text text submitted
2007 * @param string $comment comment submitted
2008 * @param bool $minor whereas it's a minor modification
2010 function quickEdit( $text, $comment = '', $minor = 0 ) {
2011 $fname = 'Article::quickEdit';
2012 wfProfileIn( $fname );
2014 $dbw =& wfGetDB( DB_MASTER
);
2016 $revision = new Revision( array(
2017 'page' => $this->getId(),
2019 'comment' => $comment,
2020 'minor_edit' => $minor ?
1 : 0,
2022 $revisionId = $revision->insertOn( $dbw );
2023 $this->updateRevisionOn( $dbw, $revision );
2026 wfProfileOut( $fname );
2030 * Used to increment the view counter
2033 * @param integer $id article id
2035 function incViewCount( $id ) {
2036 $id = intval( $id );
2037 global $wgHitcounterUpdateFreq;
2039 $dbw =& wfGetDB( DB_MASTER
);
2040 $pageTable = $dbw->tableName( 'page' );
2041 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2042 $acchitsTable = $dbw->tableName( 'acchits' );
2044 if( $wgHitcounterUpdateFreq <= 1 ){ //
2045 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2049 # Not important enough to warrant an error page in case of failure
2050 $oldignore = $dbw->ignoreErrors( true );
2052 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2054 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2055 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2056 # Most of the time (or on SQL errors), skip row count check
2057 $dbw->ignoreErrors( $oldignore );
2061 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2062 $row = $dbw->fetchObject( $res );
2063 $rown = intval( $row->n
);
2064 if( $rown >= $wgHitcounterUpdateFreq ){
2065 wfProfileIn( 'Article::incViewCount-collect' );
2066 $old_user_abort = ignore_user_abort( true );
2068 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2069 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2070 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2072 $dbw->query("DELETE FROM $hitcounterTable");
2073 $dbw->query('UNLOCK TABLES');
2074 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2075 'WHERE cur_id = hc_id');
2076 $dbw->query("DROP TABLE $acchitsTable");
2078 ignore_user_abort( $old_user_abort );
2079 wfProfileOut( 'Article::incViewCount-collect' );
2081 $dbw->ignoreErrors( $oldignore );
2085 * The onArticle*() functions are supposed to be a kind of hooks
2086 * which should be called whenever any of the specified actions
2089 * This is a good place to put code to clear caches, for instance.
2091 * This is called on page move and undelete, as well as edit
2093 * @param $title_obj a title object
2096 function onArticleCreate($title_obj) {
2097 global $wgUseSquid, $wgPostCommitUpdateList;
2099 $titles = $title_obj->getBrokenLinksTo();
2102 if ( $wgUseSquid ) {
2103 $urls = $title_obj->getSquidURLs();
2104 foreach ( $titles as $linkTitle ) {
2105 $urls[] = $linkTitle->getInternalURL();
2107 $u = new SquidUpdate( $urls );
2108 array_push( $wgPostCommitUpdateList, $u );
2111 # Clear persistent link cache
2112 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2115 function onArticleDelete($title_obj) {
2116 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2118 function onArticleEdit($title_obj) {
2119 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2124 * Info about this page
2125 * Called for ?action=info when $wgAllowPageInfo is on.
2130 global $wgLang, $wgOut, $wgAllowPageInfo;
2131 $fname = 'Article::info';
2133 if ( !$wgAllowPageInfo ) {
2134 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2138 $page = $this->mTitle
->getSubjectPage();
2140 $wgOut->setPagetitle( $page->getPrefixedText() );
2141 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2143 # first, see if the page exists at all.
2144 $exists = $page->getArticleId() != 0;
2146 $wgOut->addHTML( wfMsg('noarticletext') );
2148 $dbr =& $this->getDB( DB_SLAVE
);
2150 'wl_title' => $page->getDBkey(),
2151 'wl_namespace' => $page->getNamespace() );
2152 $numwatchers = $dbr->selectField(
2157 $this->getSelectOptions() );
2159 $pageInfo = $this->pageCountInfo( $page );
2160 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2162 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2163 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2165 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2167 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2169 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2171 $wgOut->addHTML( '</ul>' );
2177 * Return the total number of edits and number of unique editors
2178 * on a given page. If page does not exist, returns false.
2180 * @param Title $title
2184 function pageCountInfo( $title ) {
2185 $id = $title->getArticleId();
2190 $dbr =& $this->getDB( DB_SLAVE
);
2192 $rev_clause = array( 'rev_page' => $id );
2193 $fname = 'Article::pageCountInfo';
2195 $edits = $dbr->selectField(
2200 $this->getSelectOptions() );
2202 $authors = $dbr->selectField(
2204 'COUNT(DISTINCT rev_user_text)',
2207 $this->getSelectOptions() );
2209 return array( 'edits' => $edits, 'authors' => $authors );