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 ||
$wgRequest->getCheck( 'rdfrom' );
261 $this->mOldId
= $oldid;
262 $this->fetchContent( $oldid, $noredir, true );
267 * Fetch a page record with the given conditions
268 * @param Database $dbr
269 * @param array $conditions
272 function pageData( &$dbr, $conditions ) {
273 return $dbr->selectRow( 'page',
287 'Article::pageData' );
290 function pageDataFromTitle( &$dbr, $title ) {
291 return $this->pageData( $dbr, array(
292 'page_namespace' => $title->getNamespace(),
293 'page_title' => $title->getDBkey() ) );
296 function pageDataFromId( &$dbr, $id ) {
297 return $this->pageData( $dbr, array(
298 'page_id' => IntVal( $id ) ) );
302 * Get text of an article from database
303 * @param int $oldid 0 for whatever the latest revision is
304 * @param bool $noredir Set to true to avoid following redirects
305 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
308 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
309 if ( $this->mContentLoaded
) {
310 return $this->mContent
;
312 $dbr =& $this->getDB();
313 $fname = 'Article::fetchContent';
315 # Pre-fill content with error message so that if something
316 # fails we'll have something telling us what we intended.
317 $t = $this->mTitle
->getPrefixedText();
319 $t .= ',oldid='.$oldid;
321 if( isset( $redirect ) ) {
322 $redirect = ($redirect == 'no') ?
'no' : 'yes';
323 $t .= ',redirect='.$redirect;
325 $this->mContent
= wfMsg( 'missingarticle', $t );
328 $revision = Revision
::newFromId( $oldid );
329 if( is_null( $revision ) ) {
332 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
336 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
338 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
339 $revision = Revision
::newFromId( $data->page_latest
);
342 # If we got a redirect, follow it (unless we've been told
343 # not to by either the function parameter or the query
344 if ( !$oldid && !$noredir ) {
345 $rt = Title
::newFromRedirect( $revision->getText() );
346 # process if title object is valid and not special:userlogout
347 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
348 # Gotta hand redirects to special pages differently:
349 # Fill the HTTP response "Location" header and ignore
350 # the rest of the page we're on.
353 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
354 $source = $this->mTitle
->getFullURL( 'redirect=no' );
355 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
358 if ( $rt->getNamespace() == NS_SPECIAL
) {
359 $wgOut->redirect( $rt->getFullURL() );
363 $redirData = $this->pageDataFromTitle( $dbr, $rt );
365 $redirRev = Revision
::newFromId( $redirData->page_latest
);
366 if( !is_null( $redirRev ) ) {
367 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
370 $revision = $redirRev;
376 # if the title's different from expected, update...
379 if( !$this->mTitle
->equals( $wgTitle ) ) {
380 $wgTitle = $this->mTitle
;
384 # Back to the business at hand...
385 $this->mCounter
= $data->page_counter
;
386 $this->mTitle
->mRestrictions
= explode( ',', trim( $data->page_restrictions
) );
387 $this->mTitle
->mRestrictionsLoaded
= true;
388 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
390 $this->mContent
= $revision->getText();
392 $this->mUser
= $revision->getUser();
393 $this->mUserText
= $revision->getUserText();
394 $this->mComment
= $revision->getComment();
395 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
397 $this->mContentLoaded
= true;
398 return $this->mContent
;
402 * Gets the article text without using so many damn globals
403 * Returns false on error
405 * @param integer $oldid
407 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
408 return $this->fetchContent( $oldid, $noredir, false );
412 * Read/write accessor to select FOR UPDATE
414 function forUpdate( $x = NULL ) {
415 return wfSetVar( $this->mForUpdate
, $x );
419 * Get the database which should be used for reads
422 #if ( $this->mForUpdate ) {
423 return wfGetDB( DB_MASTER
);
425 # return wfGetDB( DB_SLAVE );
430 * Get options for all SELECT statements
431 * Can pass an option array, to which the class-wide options will be appended
433 function getSelectOptions( $options = '' ) {
434 if ( $this->mForUpdate
) {
435 if ( is_array( $options ) ) {
436 $options[] = 'FOR UPDATE';
438 $options = 'FOR UPDATE';
445 * Return the Article ID
448 if( $this->mTitle
) {
449 return $this->mTitle
->getArticleID();
456 * Get the view count for this article
458 function getCount() {
459 if ( -1 == $this->mCounter
) {
460 $id = $this->getID();
461 $dbr =& $this->getDB();
462 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
463 'Article::getCount', $this->getSelectOptions() );
465 return $this->mCounter
;
469 * Would the given text make this article a "good" article (i.e.,
470 * suitable for including in the article count)?
471 * @param string $text Text to analyze
472 * @return integer 1 if it can be counted else 0
474 function isCountable( $text ) {
475 global $wgUseCommaCount;
477 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
478 if ( $this->isRedirect( $text ) ) { return 0; }
479 $token = ($wgUseCommaCount ?
',' : '[[' );
480 if ( false === strstr( $text, $token ) ) { return 0; }
485 * Tests if the article text represents a redirect
487 function isRedirect( $text = false ) {
488 if ( $text === false ) {
489 $this->loadContent();
490 $titleObj = Title
::newFromRedirect( $this->mText
);
492 $titleObj = Title
::newFromRedirect( $text );
494 return $titleObj !== NULL;
498 * Loads everything except the text
499 * This isn't necessary for all uses, so it's only done if needed.
502 function loadLastEdit() {
505 if ( -1 != $this->mUser
)
508 # New or non-existent articles have no user information
509 $id = $this->getID();
510 if ( 0 == $id ) return;
512 $fname = 'Article::loadLastEdit';
514 $dbr =& $this->getDB();
515 $s = $dbr->selectRow( array( 'revision', 'page') ,
516 array( 'rev_user','rev_user_text','rev_timestamp', 'rev_comment','rev_minor_edit' ),
517 array( 'page_id' => $id, 'page_latest=rev_id' ), $fname, $this->getSelectOptions() );
519 if ( $s !== false ) {
520 $this->mUser
= $s->rev_user
;
521 $this->mUserText
= $s->rev_user_text
;
522 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->rev_timestamp
);
523 $this->mComment
= $s->rev_comment
;
524 $this->mMinorEdit
= $s->rev_minor_edit
;
528 function getTimestamp() {
529 $this->loadLastEdit();
530 return $this->mTimestamp
;
534 $this->loadLastEdit();
538 function getUserText() {
539 $this->loadLastEdit();
540 return $this->mUserText
;
543 function getComment() {
544 $this->loadLastEdit();
545 return $this->mComment
;
548 function getMinorEdit() {
549 $this->loadLastEdit();
550 return $this->mMinorEdit
;
553 function getContributors($limit = 0, $offset = 0) {
554 $fname = 'Article::getContributors';
556 # XXX: this is expensive; cache this info somewhere.
558 $title = $this->mTitle
;
560 $dbr =& $this->getDB();
561 $revTable = $dbr->tableName( 'revision' );
562 $userTable = $dbr->tableName( 'user' );
563 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
564 $ns = $title->getNamespace();
565 $user = $this->getUser();
566 $pageId = $this->getId();
568 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
569 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
570 WHERE rev_page = $pageId
571 AND rev_user != $user
572 GROUP BY rev_user, rev_user_text, user_real_name
573 ORDER BY timestamp DESC";
575 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
576 $sql .= ' '. $this->getSelectOptions();
578 $res = $dbr->query($sql, $fname);
580 while ( $line = $dbr->fetchObject( $res ) ) {
581 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
584 $dbr->freeResult($res);
589 * This is the default action of the script: just view the page of
593 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
594 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
595 global $wgEnotif, $wgParser;
596 $sk = $wgUser->getSkin();
598 $fname = 'Article::view';
599 wfProfileIn( $fname );
600 # Get variables from query string
601 $oldid = $this->getOldID();
602 $diff = $wgRequest->getVal( 'diff' );
603 $rcid = $wgRequest->getVal( 'rcid' );
604 $rdfrom = $wgRequest->getVal( 'rdfrom' );
606 $wgOut->setArticleFlag( true );
607 $wgOut->setRobotpolicy( 'index,follow' );
608 # If we got diff and oldid in the query, we want to see a
609 # diff page instead of the article.
611 if ( !is_null( $diff ) ) {
612 require_once( 'DifferenceEngine.php' );
613 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
614 $de = new DifferenceEngine( $oldid, $diff, $rcid );
617 # Run view updates for current revision only
618 $this->viewUpdates();
620 wfProfileOut( $fname );
623 if ( empty( $oldid ) && $this->checkTouched() ) {
624 if( $wgOut->checkLastModified( $this->mTouched
) ){
625 wfProfileOut( $fname );
627 } else if ( $this->tryFileCache() ) {
628 # tell wgOut that output is taken care of
630 $this->viewUpdates();
631 wfProfileOut( $fname );
635 # Should the parser cache be used?
636 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
644 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
648 if ( !$outputDone ) {
649 $text = $this->getContent( false ); # May change mTitle by following a redirect
651 # Another whitelist check in case oldid or redirects are altering the title
652 if ( !$this->mTitle
->userCanRead() ) {
653 $wgOut->loginToUse();
659 # We're looking at an old revision
661 if ( !empty( $oldid ) ) {
662 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
663 $wgOut->setRobotpolicy( 'noindex,follow' );
665 if ( '' != $this->mRedirectedFrom
) {
666 $sk = $wgUser->getSkin();
667 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
669 $s = wfMsg( 'redirectedfrom', $redir );
670 $wgOut->setSubtitle( $s );
672 # Can't cache redirects
674 } elseif ( !empty( $rdfrom ) ) {
675 global $wgRedirectSources;
676 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
677 $sk = $wgUser->getSkin();
678 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
679 $s = wfMsg( 'redirectedfrom', $redir );
680 $wgOut->setSubtitle( $s );
684 # wrap user css and user js in pre and don't parse
685 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
687 $this->mTitle
->getNamespace() == NS_USER
&&
688 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
690 $wgOut->addWikiText( wfMsg('clearyourcache'));
691 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
692 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
694 $imageUrl = $wgStylePath.'/common/images/redirect.png';
695 $targetUrl = $rt->escapeLocalURL();
696 $titleText = htmlspecialchars( $rt->getPrefixedText() );
697 $link = $sk->makeLinkObj( $rt );
699 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
700 '<span class="redirectText">'.$link.'</span>' );
702 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
703 $catlinks = $parseout->getCategoryLinks();
704 $wgOut->addCategoryLinks($catlinks);
705 $skin = $wgUser->getSkin();
706 } else if ( $pcache ) {
707 # Display content and save to parser cache
708 $wgOut->addPrimaryWikiText( $text, $this );
710 # Display content, don't attempt to save to parser cache
711 $wgOut->addWikiText( $text );
714 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
715 # If we have been passed an &rcid= parameter, we want to give the user a
716 # chance to mark this new article as patrolled.
717 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->isLoggedIn() &&
718 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
720 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
721 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
722 'action=markpatrolled&rcid='.$rcid )
726 # Put link titles into the link cache
727 $wgOut->transformBuffer();
729 # Add link titles as META keywords
730 $wgOut->addMetaTags() ;
732 $this->viewUpdates();
733 wfProfileOut( $fname );
735 $wgUser->clearNotification( $this->mTitle
);
739 * Insert a new empty page record for this article.
740 * This *must* be followed up by creating a revision
741 * and running $this->updateToLatest( $rev_id );
742 * or else the record will be left in a funky state.
743 * Best if all done inside a transaction.
745 * @param Database $dbw
746 * @return int The newly created page_id key
749 function insertOn( &$dbw ) {
750 $fname = 'Article::insertOn';
751 wfProfileIn( $fname );
753 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
754 $dbw->insert( 'page', array(
755 'page_id' => $page_id,
756 'page_namespace' => $this->mTitle
->getNamespace(),
757 'page_title' => $this->mTitle
->getDBkey(),
759 'page_restrictions' => '',
760 'page_is_redirect' => 0, # Will set this shortly...
762 'page_random' => wfRandom(),
763 'page_touched' => $dbw->timestamp(),
764 'page_latest' => 0, # Fill this in shortly...
766 $newid = $dbw->insertId();
768 $this->mTitle
->resetArticleId( $newid );
770 wfProfileOut( $fname );
775 * Update the page record to point to a newly saved revision.
777 * @param Database $dbw
778 * @param Revision $revision -- for ID number, and text used to set
779 length and redirect status fields
780 * @param int $lastRevision -- if given, will not overwrite the page field
781 * when different from the currently set value.
782 * Giving 0 indicates the new page flag should
784 * @return bool true on success, false on failure
787 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
788 $fname = 'Article::updateToRevision';
789 wfProfileIn( $fname );
791 $conditions = array( 'page_id' => $this->getId() );
792 if( !is_null( $lastRevision ) ) {
793 # An extra check against threads stepping on each other
794 $conditions['page_latest'] = $lastRevision;
796 $text = $revision->getText();
797 $dbw->update( 'page',
799 'page_latest' => $revision->getId(),
800 'page_touched' => $dbw->timestamp(),
801 'page_is_new' => ($lastRevision === 0) ?
0 : 1,
802 'page_is_redirect' => Article
::isRedirect( $text ),
803 'page_len' => strlen( $text ),
808 wfProfileOut( $fname );
809 return ( $dbw->affectedRows() != 0 );
813 * If the given revision is newer than the currently set page_latest,
814 * update the page record. Otherwise, do nothing.
816 * @param Database $dbw
817 * @param Revision $revision
819 function updateIfNewerOn( &$dbw, $revision ) {
820 $fname = 'Article::updateIfNewerOn';
821 wfProfileIn( $fname );
823 $row = $dbw->selectRow(
824 array( 'revision', 'page' ),
825 array( 'rev_id', 'rev_timestamp' ),
827 'page_id' => $this->getId(),
828 'page_latest=rev_id' ),
831 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
832 wfProfileOut( $fname );
835 $prev = $row->rev_id
;
837 # No or missing previous revision; mark the page as new
841 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
842 wfProfileOut( $fname );
847 * Theoretically we could defer these whole insert and update
848 * functions for after display, but that's taking a big leap
849 * of faith, and we want to be able to report database
850 * errors at some point.
853 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
854 global $wgOut, $wgUser;
855 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
857 $fname = 'Article::insertNewArticle';
859 $this->mCountAdjustment
= $this->isCountable( $text );
861 $ns = $this->mTitle
->getNamespace();
862 $ttl = $this->mTitle
->getDBkey();
863 $text = $this->preSaveTransform( $text );
864 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
866 $dbw =& wfGetDB( DB_MASTER
);
868 # Add the page record; stake our claim on this title!
869 $newid = $this->insertOn( $dbw );
871 # Save the revision text...
872 $revision = new Revision( array(
874 'comment' => $summary,
875 'minor_edit' => $isminor,
878 $revisionId = $revision->insertOn( $dbw );
880 $this->mTitle
->resetArticleID( $newid );
882 # Update the page record with revision data
883 $this->updateRevisionOn( $dbw, $revision, 0 );
885 Article
::onArticleCreate( $this->mTitle
);
886 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
889 if(!$this->mTitle
->userIsWatching()) $this->watch();
891 if ( $this->mTitle
->userIsWatching() ) {
896 # The talk page isn't in the regular link tables, so we need to update manually:
897 $talkns = $ns ^
1; # talk -> normal; normal -> talk
898 $dbw->update( 'page',
899 array( 'page_touched' => $dbw->timestamp($now) ),
900 array( 'page_namespace' => $talkns,
901 'page_title' => $ttl ),
904 # standard deferred updates
905 $this->editUpdates( $text, $summary, $isminor, $now );
907 $oldid = 0; # new article
908 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
912 * Fetch and uncompress the text for a given revision.
913 * Can ask by rev_id number or timestamp (set $field)
915 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
916 $fname = 'Article::fetchRevisionText';
917 $dbw =& wfGetDB( DB_MASTER
);
919 $rev = $dbw->addQuotes( $revId );
921 $rev = 'page_latest';
923 $result = $dbw->query(
924 sprintf( "SELECT old_text, old_flags
926 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
928 $dbw->tableName( 'page' ),
929 $dbw->tableName( 'revision' ),
930 $dbw->tableName( 'text' ),
931 IntVal( $this->mTitle
->getArticleId() ),
935 $obj = $dbw->fetchObject( $result );
936 $dbw->freeResult( $result );
937 $oldtext = Revision
::getRevisionText( $obj );
941 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
942 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
943 if( is_null( $edittime ) ) {
944 $oldtext = $this->fetchRevisionText();
946 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
948 if ($section != '') {
949 if($section=='new') {
950 if($summary) $subject="== {$summary} ==\n\n";
951 $text=$oldtext."\n\n".$subject.$text;
954 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
955 # comments to be stripped as well)
957 $parser=new Parser();
958 $parser->mOutputType
=OT_WIKI
;
959 $oldtext=$parser->strip($oldtext, $striparray, true);
961 # now that we can be sure that no pseudo-sections are in the source,
963 # Unfortunately we can't simply do a preg_replace because that might
964 # replace the wrong section, so we have to use the section counter instead
965 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
966 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
967 $secs[$section*2]=$text."\n\n"; // replace with edited
969 # section 0 is top (intro) section
972 # headline of old section - we need to go through this section
973 # to determine if there are any subsections that now need to
974 # be erased, as the mother section has been replaced with
975 # the text of all subsections.
976 $headline=$secs[$section*2-1];
977 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
980 # determine headline level for wikimarkup headings
981 if(strpos($hlevel,'=')!==false) {
982 $hlevel=strlen($hlevel);
985 $secs[$section*2-1]=''; // erase old headline
988 while(!empty($secs[$count*2-1]) && !$break) {
990 $subheadline=$secs[$count*2-1];
992 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
993 $subhlevel=$matches[1];
994 if(strpos($subhlevel,'=')!==false) {
995 $subhlevel=strlen($subhlevel);
997 if($subhlevel > $hlevel) {
998 // erase old subsections
999 $secs[$count*2-1]='';
1002 if($subhlevel <= $hlevel) {
1010 $text=join('',$secs);
1011 # reinsert the stuff that we stripped out earlier
1012 $text=$parser->unstrip($text,$striparray);
1013 $text=$parser->unstripNoWiki($text,$striparray);
1021 * Change an existing article. Puts the previous version back into the old table, updates RC
1022 * and all necessary caches, mostly via the deferred update array.
1024 * It is possible to call this function from a command-line script, but note that you should
1025 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1027 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1028 global $wgOut, $wgUser;
1029 global $wgDBtransactions, $wgMwRedir;
1030 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1032 $fname = 'Article::updateArticle';
1035 $isminor = ( $minor && $wgUser->isLoggedIn() );
1036 if ( $this->isRedirect( $text ) ) {
1037 # Remove all content but redirect
1038 # This could be done by reconstructing the redirect from a title given by
1039 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1041 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1043 $text = $m[1] . "\n";
1046 else { $redir = 0; }
1048 $text = $this->preSaveTransform( $text );
1049 $dbw =& wfGetDB( DB_MASTER
);
1051 # Update article, but only if changed.
1053 # It's important that we either rollback or complete, otherwise an attacker could
1054 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1055 # could conceivably have the same effect, especially if cur is locked for long periods.
1056 if( $wgDBtransactions ) {
1057 $dbw->query( 'BEGIN', $fname );
1059 $userAbort = ignore_user_abort( true );
1062 $oldtext = $this->getContent( true );
1064 if ( 0 != strcmp( $text, $oldtext ) ) {
1065 $this->mCountAdjustment
= $this->isCountable( $text )
1066 - $this->isCountable( $oldtext );
1067 $now = wfTimestampNow();
1069 $lastRevision = $dbw->selectField(
1070 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1072 $revision = new Revision( array(
1073 'page' => $this->getId(),
1074 'comment' => $summary,
1075 'minor_edit' => $isminor,
1078 $revisionId = $revision->insertOn( $dbw );
1081 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1084 /* Belated edit conflict! Run away!! */
1087 # Update recentchanges and purge cache and whatnot
1088 $bot = (int)($wgUser->isBot() ||
$forceBot);
1089 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1090 $lastRevision, $this->getTimestamp(), $bot );
1091 Article
::onArticleEdit( $this->mTitle
);
1095 if( $wgDBtransactions ) {
1096 $dbw->query( 'COMMIT', $fname );
1098 ignore_user_abort( $userAbort );
1103 if (!$this->mTitle
->userIsWatching()) $this->watch();
1105 if ( $this->mTitle
->userIsWatching() ) {
1109 # standard deferred updates
1110 $this->editUpdates( $text, $summary, $minor, $now );
1114 # Template namespace
1115 # Purge all articles linking here
1116 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1117 $titles = $this->mTitle
->getLinksTo();
1118 Title
::touchArray( $titles );
1119 if ( $wgUseSquid ) {
1120 foreach ( $titles as $title ) {
1121 $urls[] = $title->getInternalURL();
1127 if ( $wgUseSquid ) {
1128 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1129 $u = new SquidUpdate( $urls );
1130 array_push( $wgPostCommitUpdateList, $u );
1133 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1139 * After we've either updated or inserted the article, update
1140 * the link tables and redirect to the new page.
1142 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1143 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1145 $wgLinkCache = new LinkCache();
1147 $wgLinkCache->forUpdate( true );
1149 # Get old version of link table to allow incremental link updates
1150 $wgLinkCache->preFill( $this->mTitle
);
1151 $wgLinkCache->clear();
1153 # Parse the text and replace links with placeholders
1154 $wgOut = new OutputPage();
1155 $wgOut->addWikiText( $text );
1157 # Look up the links in the DB and add them to the link cache
1158 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1160 if( $this->isRedirect( $text ) )
1164 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1166 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1167 # this will be improved later (to-do)
1169 include_once( "UserMailer.php" );
1170 $wgEnotif = new EmailNotification ();
1171 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1175 * Mark this particular edit as patrolled
1177 function markpatrolled() {
1178 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1179 $wgOut->setRobotpolicy( 'noindex,follow' );
1181 if ( !$wgUseRCPatrol )
1183 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1186 if ( $wgUser->isAnon() )
1188 $wgOut->loginToUse();
1191 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1193 $wgOut->sysopRequired();
1196 $rcid = $wgRequest->getVal( 'rcid' );
1197 if ( !is_null ( $rcid ) )
1199 RecentChange
::markPatrolled( $rcid );
1200 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1201 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1203 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1204 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1208 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1214 * Add this page to $wgUser's watchlist
1219 global $wgUser, $wgOut;
1221 if ( $wgUser->isAnon() ) {
1222 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1225 if ( wfReadOnly() ) {
1226 $wgOut->readOnlyPage();
1230 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1232 $wgUser->addWatch( $this->mTitle
);
1233 $wgUser->saveSettings();
1235 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1237 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1238 $wgOut->setRobotpolicy( 'noindex,follow' );
1240 $link = $this->mTitle
->getPrefixedText();
1241 $text = wfMsg( 'addedwatchtext', $link );
1242 $wgOut->addWikiText( $text );
1245 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1249 * Stop watching a page
1252 function unwatch() {
1254 global $wgUser, $wgOut;
1256 if ( $wgUser->isAnon() ) {
1257 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1260 if ( wfReadOnly() ) {
1261 $wgOut->readOnlyPage();
1265 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1267 $wgUser->removeWatch( $this->mTitle
);
1268 $wgUser->saveSettings();
1270 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1272 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1273 $wgOut->setRobotpolicy( 'noindex,follow' );
1275 $link = $this->mTitle
->getPrefixedText();
1276 $text = wfMsg( 'removedwatchtext', $link );
1277 $wgOut->addWikiText( $text );
1280 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1286 function protect( $limit = 'sysop' ) {
1287 global $wgUser, $wgOut, $wgRequest;
1289 if ( ! $wgUser->isAllowed('protect') ) {
1290 $wgOut->sysopRequired();
1293 if ( wfReadOnly() ) {
1294 $wgOut->readOnlyPage();
1297 $id = $this->mTitle
->getArticleID();
1299 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1303 $confirm = $wgRequest->wasPosted() &&
1304 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1305 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1306 $reason = $wgRequest->getText( 'wpReasonProtect' );
1309 $dbw =& wfGetDB( DB_MASTER
);
1310 $dbw->update( 'page',
1312 'page_touched' => $dbw->timestamp(),
1313 'page_restrictions' => (string)$limit
1314 ), array( /* WHERE */
1316 ), 'Article::protect'
1319 $restrictions = "move=" . $limit;
1321 $restrictions .= ":edit=" . $limit;
1323 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1325 $dbw =& wfGetDB( DB_MASTER
);
1326 $dbw->update( 'page',
1328 'page_touched' => $dbw->timestamp(),
1329 'page_restrictions' => $restrictions
1330 ), array( /* WHERE */
1332 ), 'Article::protect'
1335 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1337 $log = new LogPage( 'protect' );
1338 if ( $limit === '' ) {
1339 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1341 $log->addEntry( 'protect', $this->mTitle
, $reason );
1343 $wgOut->redirect( $this->mTitle
->getFullURL() );
1347 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1348 return $this->confirmProtect( '', $reason, $limit );
1353 * Output protection confirmation dialog
1355 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1356 global $wgOut, $wgUser;
1358 wfDebug( "Article::confirmProtect\n" );
1360 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1361 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1367 if ( $limit === '' ) {
1368 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1369 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1370 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1371 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1372 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1374 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1375 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1376 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1377 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1378 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1379 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1382 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1383 $token = htmlspecialchars( $wgUser->editToken() );
1386 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1390 <label for='wpReasonProtect'>{$protcom}:</label>
1393 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1399 if($moveonly != '') {
1403 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1406 <label for='wpMoveOnly'>{$moveonly}</label>
1414 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1418 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1421 $wgOut->returnToMain( false );
1425 * Unprotect the pages
1427 function unprotect() {
1428 return $this->protect( '' );
1432 * UI entry point for page deletion
1435 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1436 $fname = 'Article::delete';
1437 $confirm = $wgRequest->wasPosted() &&
1438 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1439 $reason = $wgRequest->getText( 'wpReason' );
1441 # This code desperately needs to be totally rewritten
1444 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1445 $wgOut->sysopRequired();
1448 if ( wfReadOnly() ) {
1449 $wgOut->readOnlyPage();
1453 # Better double-check that it hasn't been deleted yet!
1454 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1455 if ( ( '' == trim( $this->mTitle
->getText() ) )
1456 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1457 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1462 $this->doDelete( $reason );
1466 # determine whether this page has earlier revisions
1467 # and insert a warning if it does
1468 # we select the text because it might be useful below
1469 $dbr =& $this->getDB();
1470 $ns = $this->mTitle
->getNamespace();
1471 $title = $this->mTitle
->getDBkey();
1472 $revisions = $dbr->select( array( 'page', 'revision' ),
1475 'page_namespace' => $ns,
1476 'page_title' => $title,
1477 'rev_page = page_id'
1478 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1481 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1482 $skin=$wgUser->getSkin();
1483 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1484 $wgOut->addHTML( $skin->historyLink() .'</b>');
1488 $s = $dbr->selectRow( array( 'page', 'text' ),
1489 array( 'old_text' ),
1491 'page_namespace' => $ns,
1492 'page_title' => $title,
1493 'page_latest = old_id'
1494 ), $fname, $this->getSelectOptions()
1497 if( $s !== false ) {
1498 # if this is a mini-text, we can paste part of it into the deletion reason
1500 #if this is empty, an earlier revision may contain "useful" text
1502 if($s->old_text
!= '') {
1506 $text = Revision
::getRevisionText( $old );
1512 $length=strlen($text);
1514 # this should not happen, since it is not possible to store an empty, new
1515 # page. Let's insert a standard text in case it does, though
1516 if($length == 0 && $reason === '') {
1517 $reason = wfMsg('exblank');
1520 if($length < 500 && $reason === '') {
1522 # comment field=255, let's grep the first 150 to have some user
1524 $text=substr($text,0,150);
1525 # let's strip out newlines and HTML tags
1526 $text=preg_replace('/\"/',"'",$text);
1527 $text=preg_replace('/\</','<',$text);
1528 $text=preg_replace('/\>/','>',$text);
1529 $text=preg_replace("/[\n\r]/",'',$text);
1531 $reason=wfMsg('excontent'). " '".$text;
1533 $reason=wfMsg('exbeforeblank') . " '".$text;
1535 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1540 return $this->confirmDelete( '', $reason );
1544 * Output deletion confirmation dialog
1546 function confirmDelete( $par, $reason ) {
1547 global $wgOut, $wgUser;
1549 wfDebug( "Article::confirmDelete\n" );
1551 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1552 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1553 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1554 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1556 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1558 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1559 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1560 $token = htmlspecialchars( $wgUser->editToken() );
1563 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1567 <label for='wpReason'>{$delcom}:</label>
1570 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1579 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1583 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1586 $wgOut->returnToMain( false );
1591 * Perform a deletion and output success or failure messages
1593 function doDelete( $reason ) {
1594 global $wgOut, $wgUser, $wgContLang;
1595 $fname = 'Article::doDelete';
1596 wfDebug( $fname."\n" );
1598 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1599 if ( $this->doDeleteArticle( $reason ) ) {
1600 $deleted = $this->mTitle
->getPrefixedText();
1602 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1603 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1605 $sk = $wgUser->getSkin();
1606 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1607 ':' . wfMsgForContent( 'dellogpage' ),
1608 wfMsg( 'deletionlog' ) );
1610 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1612 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1613 $wgOut->returnToMain( false );
1614 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1616 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1622 * Back-end article deletion
1623 * Deletes the article with database consistency, writes logs, purges caches
1626 function doDeleteArticle( $reason ) {
1628 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1630 $fname = 'Article::doDeleteArticle';
1631 wfDebug( $fname."\n" );
1633 $dbw =& wfGetDB( DB_MASTER
);
1634 $ns = $this->mTitle
->getNamespace();
1635 $t = $this->mTitle
->getDBkey();
1636 $id = $this->mTitle
->getArticleID();
1638 if ( $t == '' ||
$id == 0 ) {
1642 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1643 array_push( $wgDeferredUpdateList, $u );
1645 $linksTo = $this->mTitle
->getLinksTo();
1648 if ( $wgUseSquid ) {
1650 $this->mTitle
->getInternalURL(),
1651 $this->mTitle
->getInternalURL( 'history' )
1653 foreach ( $linksTo as $linkTo ) {
1654 $urls[] = $linkTo->getInternalURL();
1657 $u = new SquidUpdate( $urls );
1658 array_push( $wgPostCommitUpdateList, $u );
1662 # Client and file cache invalidation
1663 Title
::touchArray( $linksTo );
1665 # Move article and history to the "archive" table
1667 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1669 'ar_namespace' => 'page_namespace',
1670 'ar_title' => 'page_title',
1671 'ar_text' => 'old_text',
1672 'ar_comment' => 'rev_comment',
1673 'ar_user' => 'rev_user',
1674 'ar_user_text' => 'rev_user_text',
1675 'ar_timestamp' => 'rev_timestamp',
1676 'ar_minor_edit' => 'rev_minor_edit',
1677 'ar_flags' => 'old_flags',
1678 'ar_rev_id' => 'rev_id',
1680 'page_namespace' => $ns,
1682 'page_id = rev_page AND old_id = rev_id'
1686 # Now that it's safely backed up, delete it
1688 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1689 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1690 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1692 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1694 # Finally, clean up the link tables
1695 $t = $this->mTitle
->getPrefixedDBkey();
1697 Article
::onArticleDelete( $this->mTitle
);
1699 # Insert broken links
1700 $brokenLinks = array();
1701 foreach ( $linksTo as $titleObj ) {
1702 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1703 $linkID = $titleObj->getArticleID();
1704 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1706 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1709 $dbw->delete( 'links', array( 'l_to' => $id ) );
1710 $dbw->delete( 'links', array( 'l_from' => $id ) );
1711 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1712 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1713 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1716 $log = new LogPage( 'delete' );
1717 $log->addEntry( 'delete', $this->mTitle
, $reason );
1719 # Clear the cached article id so the interface doesn't act like we exist
1720 $this->mTitle
->resetArticleID( 0 );
1721 $this->mTitle
->mArticleID
= 0;
1726 * Revert a modification
1728 function rollback() {
1729 global $wgUser, $wgOut, $wgRequest;
1730 $fname = 'Article::rollback';
1732 if ( ! $wgUser->isAllowed('rollback') ) {
1733 $wgOut->sysopRequired();
1736 if ( wfReadOnly() ) {
1737 $wgOut->readOnlyPage( $this->getContent( true ) );
1740 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1741 array( $this->mTitle
->getPrefixedText(),
1742 $wgRequest->getVal( 'from' ) ) ) ) {
1743 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1744 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1747 $dbw =& wfGetDB( DB_MASTER
);
1749 # Enhanced rollback, marks edits rc_bot=1
1750 $bot = $wgRequest->getBool( 'bot' );
1752 # Replace all this user's current edits with the next one down
1753 $tt = $this->mTitle
->getDBKey();
1754 $n = $this->mTitle
->getNamespace();
1756 # Get the last editor, lock table exclusively
1758 $current = Revision
::newFromTitle( $this->mTitle
);
1759 if( is_null( $current ) ) {
1760 # Something wrong... no page?
1762 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1766 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1767 if( $from != $current->getUserText() ) {
1768 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1769 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1770 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1771 htmlspecialchars( $from ),
1772 htmlspecialchars( $current->getUserText() ) ) );
1773 if( $current->getComment() != '') {
1775 wfMsg( 'editcomment',
1776 htmlspecialchars( $current->getComment() ) ) );
1781 # Get the last edit not by this guy
1782 $user = IntVal( $current->getUser() );
1783 $user_text = $dbw->addQuotes( $current->getUserText() );
1784 $s = $dbw->selectRow( 'revision',
1785 array( 'rev_id', 'rev_timestamp' ),
1787 'rev_page' => $current->getPage(),
1788 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1791 'USE INDEX' => 'page_timestamp',
1792 'ORDER BY' => 'rev_timestamp DESC' )
1794 if( $s === false ) {
1797 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1798 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1803 # Mark all reverted edits as bot
1804 $dbw->update( 'recentchanges',
1807 ), array( /* WHERE */
1808 'rc_cur_id' => $current->getPage(),
1809 'rc_user_text' => $current->getUserText(),
1810 "rc_timestamp > '{$s->rev_timestamp}'",
1816 $target = Revision
::newFromId( $s->rev_id
);
1817 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1819 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1820 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1821 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1823 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1824 Article
::onArticleEdit( $this->mTitle
);
1827 $wgOut->returnToMain( false );
1832 * Do standard deferred updates after page view
1835 function viewUpdates() {
1836 global $wgDeferredUpdateList;
1838 if ( 0 != $this->getID() ) {
1839 global $wgDisableCounters;
1840 if( !$wgDisableCounters ) {
1841 Article
::incViewCount( $this->getID() );
1842 $u = new SiteStatsUpdate( 1, 0, 0 );
1843 array_push( $wgDeferredUpdateList, $u );
1847 # Update newtalk status if user is reading their own
1851 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1852 $this->mTitle
->getText() == $wgUser->getName()) {
1853 require_once( 'UserTalkUpdate.php' );
1854 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1859 * Do standard deferred updates after page edit.
1860 * Every 1000th edit, prune the recent changes table.
1862 * @param string $text
1864 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1865 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1866 global $wgMessageCache, $wgUser;
1869 if ( 0 == mt_rand( 0, 999 ) ) {
1870 # Periodically flush old entries from the recentchanges table.
1872 $dbw =& wfGetDB( DB_MASTER
);
1873 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1874 $recentchanges = $dbw->tableName( 'recentchanges' );
1875 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1876 $dbw->query( $sql );
1878 $id = $this->getID();
1879 $title = $this->mTitle
->getPrefixedDBkey();
1880 $shortTitle = $this->mTitle
->getDBkey();
1882 $adj = $this->mCountAdjustment
;
1885 $u = new LinksUpdate( $id, $title );
1886 array_push( $wgDeferredUpdateList, $u );
1887 $u = new SiteStatsUpdate( 0, 1, $adj );
1888 array_push( $wgDeferredUpdateList, $u );
1889 $u = new SearchUpdate( $id, $title, $text );
1890 array_push( $wgDeferredUpdateList, $u );
1892 # If this is another user's talk page,
1893 # create a watchlist entry for this page
1895 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1896 $shortTitle != $wgUser->getName()) {
1897 require_once( 'UserTalkUpdate.php' );
1898 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1901 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1902 $wgMessageCache->replace( $shortTitle, $text );
1908 * @todo document this function
1910 * @param string $oldid Revision ID of this article revision
1912 function setOldSubtitle( $oldid=0 ) {
1913 global $wgLang, $wgOut, $wgUser;
1915 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1916 $sk = $wgUser->getSkin();
1917 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1918 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1919 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1920 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1921 $wgOut->setSubtitle( $r );
1925 * This function is called right before saving the wikitext,
1926 * so we can do things like signatures and links-in-context.
1928 * @param string $text
1930 function preSaveTransform( $text ) {
1931 global $wgParser, $wgUser;
1932 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1935 /* Caching functions */
1938 * checkLastModified returns true if it has taken care of all
1939 * output to the client that is necessary for this request.
1940 * (that is, it has sent a cached version of the page)
1942 function tryFileCache() {
1943 static $called = false;
1945 wfDebug( " tryFileCache() -- called twice!?\n" );
1949 if($this->isFileCacheable()) {
1950 $touched = $this->mTouched
;
1951 $cache = new CacheManager( $this->mTitle
);
1952 if($cache->isFileCacheGood( $touched )) {
1954 wfDebug( " tryFileCache() - about to load\n" );
1955 $cache->loadFromFileCache();
1958 wfDebug( " tryFileCache() - starting buffer\n" );
1959 ob_start( array(&$cache, 'saveToFileCache' ) );
1962 wfDebug( " tryFileCache() - not cacheable\n" );
1967 * Check if the page can be cached
1970 function isFileCacheable() {
1971 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1972 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1974 return $wgUseFileCache
1975 and (!$wgShowIPinHeader)
1976 and ($this->getID() != 0)
1977 and ($wgUser->isAnon())
1978 and (!$wgUser->getNewtalk())
1979 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1980 and (empty( $action ) ||
$action == 'view')
1981 and (!isset($oldid))
1983 and (!isset($redirect))
1984 and (!isset($printable))
1985 and (!$this->mRedirectedFrom
);
1989 * Loads cur_touched and returns a value indicating if it should be used
1992 function checkTouched() {
1993 $fname = 'Article::checkTouched';
1994 $id = $this->getID();
1995 $dbr =& $this->getDB();
1996 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1997 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1998 if( $s !== false ) {
1999 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
2000 return !$s->page_is_redirect
;
2007 * Edit an article without doing all that other stuff
2008 * The article must already exist; link tables etc
2009 * are not updated, caches are not flushed.
2011 * @param string $text text submitted
2012 * @param string $comment comment submitted
2013 * @param bool $minor whereas it's a minor modification
2015 function quickEdit( $text, $comment = '', $minor = 0 ) {
2016 $fname = 'Article::quickEdit';
2017 wfProfileIn( $fname );
2019 $dbw =& wfGetDB( DB_MASTER
);
2021 $revision = new Revision( array(
2022 'page' => $this->getId(),
2024 'comment' => $comment,
2025 'minor_edit' => $minor ?
1 : 0,
2027 $revisionId = $revision->insertOn( $dbw );
2028 $this->updateRevisionOn( $dbw, $revision );
2031 wfProfileOut( $fname );
2035 * Used to increment the view counter
2038 * @param integer $id article id
2040 function incViewCount( $id ) {
2041 $id = intval( $id );
2042 global $wgHitcounterUpdateFreq;
2044 $dbw =& wfGetDB( DB_MASTER
);
2045 $pageTable = $dbw->tableName( 'page' );
2046 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2047 $acchitsTable = $dbw->tableName( 'acchits' );
2049 if( $wgHitcounterUpdateFreq <= 1 ){ //
2050 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2054 # Not important enough to warrant an error page in case of failure
2055 $oldignore = $dbw->ignoreErrors( true );
2057 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2059 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2060 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2061 # Most of the time (or on SQL errors), skip row count check
2062 $dbw->ignoreErrors( $oldignore );
2066 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2067 $row = $dbw->fetchObject( $res );
2068 $rown = intval( $row->n
);
2069 if( $rown >= $wgHitcounterUpdateFreq ){
2070 wfProfileIn( 'Article::incViewCount-collect' );
2071 $old_user_abort = ignore_user_abort( true );
2073 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2074 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2075 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2077 $dbw->query("DELETE FROM $hitcounterTable");
2078 $dbw->query('UNLOCK TABLES');
2079 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2080 'WHERE cur_id = hc_id');
2081 $dbw->query("DROP TABLE $acchitsTable");
2083 ignore_user_abort( $old_user_abort );
2084 wfProfileOut( 'Article::incViewCount-collect' );
2086 $dbw->ignoreErrors( $oldignore );
2090 * The onArticle*() functions are supposed to be a kind of hooks
2091 * which should be called whenever any of the specified actions
2094 * This is a good place to put code to clear caches, for instance.
2096 * This is called on page move and undelete, as well as edit
2098 * @param $title_obj a title object
2101 function onArticleCreate($title_obj) {
2102 global $wgUseSquid, $wgPostCommitUpdateList;
2104 $titles = $title_obj->getBrokenLinksTo();
2107 if ( $wgUseSquid ) {
2108 $urls = $title_obj->getSquidURLs();
2109 foreach ( $titles as $linkTitle ) {
2110 $urls[] = $linkTitle->getInternalURL();
2112 $u = new SquidUpdate( $urls );
2113 array_push( $wgPostCommitUpdateList, $u );
2116 # Clear persistent link cache
2117 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2120 function onArticleDelete($title_obj) {
2121 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2123 function onArticleEdit($title_obj) {
2124 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2129 * Info about this page
2130 * Called for ?action=info when $wgAllowPageInfo is on.
2135 global $wgLang, $wgOut, $wgAllowPageInfo;
2136 $fname = 'Article::info';
2138 if ( !$wgAllowPageInfo ) {
2139 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2143 $page = $this->mTitle
->getSubjectPage();
2145 $wgOut->setPagetitle( $page->getPrefixedText() );
2146 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2148 # first, see if the page exists at all.
2149 $exists = $page->getArticleId() != 0;
2151 $wgOut->addHTML( wfMsg('noarticletext') );
2153 $dbr =& $this->getDB( DB_SLAVE
);
2155 'wl_title' => $page->getDBkey(),
2156 'wl_namespace' => $page->getNamespace() );
2157 $numwatchers = $dbr->selectField(
2162 $this->getSelectOptions() );
2164 $pageInfo = $this->pageCountInfo( $page );
2165 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2167 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2168 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2170 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2172 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2174 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2176 $wgOut->addHTML( '</ul>' );
2182 * Return the total number of edits and number of unique editors
2183 * on a given page. If page does not exist, returns false.
2185 * @param Title $title
2189 function pageCountInfo( $title ) {
2190 $id = $title->getArticleId();
2195 $dbr =& $this->getDB( DB_SLAVE
);
2197 $rev_clause = array( 'rev_page' => $id );
2198 $fname = 'Article::pageCountInfo';
2200 $edits = $dbr->selectField(
2205 $this->getSelectOptions() );
2207 $authors = $dbr->selectField(
2209 'COUNT(DISTINCT rev_user_text)',
2212 $this->getSelectOptions() );
2214 return array( 'edits' => $edits, 'authors' => $authors );