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 );
737 * Insert a new empty page record for this article.
738 * This *must* be followed up by creating a revision
739 * and running $this->updateToLatest( $rev_id );
740 * or else the record will be left in a funky state.
741 * Best if all done inside a transaction.
743 * @param Database $dbw
744 * @return int The newly created page_id key
747 function insertOn( &$dbw ) {
748 $fname = 'Article::insertOn';
749 wfProfileIn( $fname );
751 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
752 $dbw->insert( 'page', array(
753 'page_id' => $page_id,
754 'page_namespace' => $this->mTitle
->getNamespace(),
755 'page_title' => $this->mTitle
->getDBkey(),
757 'page_restrictions' => '',
758 'page_is_redirect' => 0, # Will set this shortly...
760 'page_random' => wfRandom(),
761 'page_touched' => $dbw->timestamp(),
762 'page_latest' => 0, # Fill this in shortly...
764 $newid = $dbw->insertId();
766 $this->mTitle
->resetArticleId( $newid );
768 wfProfileOut( $fname );
773 * Update the page record to point to a newly saved revision.
775 * @param Database $dbw
776 * @param Revision $revision -- for ID number, and text used to set
777 length and redirect status fields
778 * @param int $lastRevision -- if given, will not overwrite the page field
779 * when different from the currently set value.
780 * Giving 0 indicates the new page flag should
782 * @return bool true on success, false on failure
785 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
786 $fname = 'Article::updateToRevision';
787 wfProfileIn( $fname );
789 $conditions = array( 'page_id' => $this->getId() );
790 if( !is_null( $lastRevision ) ) {
791 # An extra check against threads stepping on each other
792 $conditions['page_latest'] = $lastRevision;
794 $text = $revision->getText();
795 $dbw->update( 'page',
797 'page_latest' => $revision->getId(),
798 'page_touched' => $dbw->timestamp(),
799 'page_is_new' => ($lastRevision === 0) ?
0 : 1,
800 'page_is_redirect' => Article
::isRedirect( $text ),
801 'page_len' => strlen( $text ),
806 wfProfileOut( $fname );
807 return ( $dbw->affectedRows() != 0 );
811 * If the given revision is newer than the currently set page_latest,
812 * update the page record. Otherwise, do nothing.
814 * @param Database $dbw
815 * @param Revision $revision
817 function updateIfNewerOn( &$dbw, $revision ) {
818 $fname = 'Article::updateIfNewerOn';
819 wfProfileIn( $fname );
821 $row = $dbw->selectRow(
822 array( 'revision', 'page' ),
823 array( 'rev_id', 'rev_timestamp' ),
825 'page_id' => $this->getId(),
826 'page_latest=rev_id' ),
829 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
830 wfProfileOut( $fname );
833 $prev = $row->rev_id
;
835 # No or missing previous revision; mark the page as new
839 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
840 wfProfileOut( $fname );
845 * Theoretically we could defer these whole insert and update
846 * functions for after display, but that's taking a big leap
847 * of faith, and we want to be able to report database
848 * errors at some point.
851 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
852 global $wgOut, $wgUser;
853 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
855 $fname = 'Article::insertNewArticle';
857 $this->mCountAdjustment
= $this->isCountable( $text );
859 $ns = $this->mTitle
->getNamespace();
860 $ttl = $this->mTitle
->getDBkey();
861 $text = $this->preSaveTransform( $text );
862 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
864 $dbw =& wfGetDB( DB_MASTER
);
866 # Add the page record; stake our claim on this title!
867 $newid = $this->insertOn( $dbw );
869 # Save the revision text...
870 $revision = new Revision( array(
872 'comment' => $summary,
873 'minor_edit' => $isminor,
876 $revisionId = $revision->insertOn( $dbw );
878 $this->mTitle
->resetArticleID( $newid );
880 # Update the page record with revision data
881 $this->updateRevisionOn( $dbw, $revision, 0 );
883 Article
::onArticleCreate( $this->mTitle
);
884 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
887 if(!$this->mTitle
->userIsWatching()) $this->watch();
889 if ( $this->mTitle
->userIsWatching() ) {
894 # The talk page isn't in the regular link tables, so we need to update manually:
895 $talkns = $ns ^
1; # talk -> normal; normal -> talk
896 $dbw->update( 'page',
897 array( 'page_touched' => $dbw->timestamp($now) ),
898 array( 'page_namespace' => $talkns,
899 'page_title' => $ttl ),
902 # standard deferred updates
903 $this->editUpdates( $text, $summary, $isminor, $now );
905 $oldid = 0; # new article
906 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
910 * Fetch and uncompress the text for a given revision.
911 * Can ask by rev_id number or timestamp (set $field)
913 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
914 $fname = 'Article::fetchRevisionText';
915 $dbw =& wfGetDB( DB_MASTER
);
917 $rev = $dbw->addQuotes( $revId );
919 $rev = 'page_latest';
921 $result = $dbw->query(
922 sprintf( "SELECT old_text, old_flags
924 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
926 $dbw->tableName( 'page' ),
927 $dbw->tableName( 'revision' ),
928 $dbw->tableName( 'text' ),
929 IntVal( $this->mTitle
->getArticleId() ),
933 $obj = $dbw->fetchObject( $result );
934 $dbw->freeResult( $result );
935 $oldtext = Revision
::getRevisionText( $obj );
939 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
940 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
941 if( is_null( $edittime ) ) {
942 $oldtext = $this->fetchRevisionText();
944 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
946 if ($section != '') {
947 if($section=='new') {
948 if($summary) $subject="== {$summary} ==\n\n";
949 $text=$oldtext."\n\n".$subject.$text;
952 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
953 # comments to be stripped as well)
955 $parser=new Parser();
956 $parser->mOutputType
=OT_WIKI
;
957 $oldtext=$parser->strip($oldtext, $striparray, true);
959 # now that we can be sure that no pseudo-sections are in the source,
961 # Unfortunately we can't simply do a preg_replace because that might
962 # replace the wrong section, so we have to use the section counter instead
963 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
964 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
965 $secs[$section*2]=$text."\n\n"; // replace with edited
967 # section 0 is top (intro) section
970 # headline of old section - we need to go through this section
971 # to determine if there are any subsections that now need to
972 # be erased, as the mother section has been replaced with
973 # the text of all subsections.
974 $headline=$secs[$section*2-1];
975 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
978 # determine headline level for wikimarkup headings
979 if(strpos($hlevel,'=')!==false) {
980 $hlevel=strlen($hlevel);
983 $secs[$section*2-1]=''; // erase old headline
986 while(!empty($secs[$count*2-1]) && !$break) {
988 $subheadline=$secs[$count*2-1];
990 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
991 $subhlevel=$matches[1];
992 if(strpos($subhlevel,'=')!==false) {
993 $subhlevel=strlen($subhlevel);
995 if($subhlevel > $hlevel) {
996 // erase old subsections
997 $secs[$count*2-1]='';
1000 if($subhlevel <= $hlevel) {
1008 $text=join('',$secs);
1009 # reinsert the stuff that we stripped out earlier
1010 $text=$parser->unstrip($text,$striparray);
1011 $text=$parser->unstripNoWiki($text,$striparray);
1019 * Change an existing article. Puts the previous version back into the old table, updates RC
1020 * and all necessary caches, mostly via the deferred update array.
1022 * It is possible to call this function from a command-line script, but note that you should
1023 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1025 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1026 global $wgOut, $wgUser;
1027 global $wgDBtransactions, $wgMwRedir;
1028 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1030 $fname = 'Article::updateArticle';
1033 $isminor = ( $minor && $wgUser->isLoggedIn() );
1034 if ( $this->isRedirect( $text ) ) {
1035 # Remove all content but redirect
1036 # This could be done by reconstructing the redirect from a title given by
1037 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1039 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1041 $text = $m[1] . "\n";
1044 else { $redir = 0; }
1046 $text = $this->preSaveTransform( $text );
1047 $dbw =& wfGetDB( DB_MASTER
);
1049 # Update article, but only if changed.
1051 # It's important that we either rollback or complete, otherwise an attacker could
1052 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1053 # could conceivably have the same effect, especially if cur is locked for long periods.
1054 if( $wgDBtransactions ) {
1055 $dbw->query( 'BEGIN', $fname );
1057 $userAbort = ignore_user_abort( true );
1060 $oldtext = $this->getContent( true );
1062 if ( 0 != strcmp( $text, $oldtext ) ) {
1063 $this->mCountAdjustment
= $this->isCountable( $text )
1064 - $this->isCountable( $oldtext );
1065 $now = wfTimestampNow();
1067 $lastRevision = $dbw->selectField(
1068 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1070 $revision = new Revision( array(
1071 'page' => $this->getId(),
1072 'comment' => $summary,
1073 'minor_edit' => $isminor,
1076 $revisionId = $revision->insertOn( $dbw );
1079 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1082 /* Belated edit conflict! Run away!! */
1085 # Update recentchanges and purge cache and whatnot
1086 $bot = (int)($wgUser->isBot() ||
$forceBot);
1087 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1088 $lastRevision, $this->getTimestamp(), $bot );
1089 Article
::onArticleEdit( $this->mTitle
);
1093 if( $wgDBtransactions ) {
1094 $dbw->query( 'COMMIT', $fname );
1096 ignore_user_abort( $userAbort );
1101 if (!$this->mTitle
->userIsWatching()) $this->watch();
1103 if ( $this->mTitle
->userIsWatching() ) {
1107 # standard deferred updates
1108 $this->editUpdates( $text, $summary, $minor, $now );
1112 # Template namespace
1113 # Purge all articles linking here
1114 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1115 $titles = $this->mTitle
->getLinksTo();
1116 Title
::touchArray( $titles );
1117 if ( $wgUseSquid ) {
1118 foreach ( $titles as $title ) {
1119 $urls[] = $title->getInternalURL();
1125 if ( $wgUseSquid ) {
1126 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1127 $u = new SquidUpdate( $urls );
1128 array_push( $wgPostCommitUpdateList, $u );
1131 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1137 * After we've either updated or inserted the article, update
1138 * the link tables and redirect to the new page.
1140 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1141 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1143 $wgLinkCache = new LinkCache();
1145 $wgLinkCache->forUpdate( true );
1147 # Get old version of link table to allow incremental link updates
1148 $wgLinkCache->preFill( $this->mTitle
);
1149 $wgLinkCache->clear();
1151 # Parse the text and replace links with placeholders
1152 $wgOut = new OutputPage();
1153 $wgOut->addWikiText( $text );
1155 # Look up the links in the DB and add them to the link cache
1156 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1158 if( $this->isRedirect( $text ) )
1162 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1164 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1165 # this will be improved later (to-do)
1167 include_once( "UserMailer.php" );
1168 $wgEnotif = new EmailNotification ();
1169 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1173 * Mark this particular edit as patrolled
1175 function markpatrolled() {
1176 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1177 $wgOut->setRobotpolicy( 'noindex,follow' );
1179 if ( !$wgUseRCPatrol )
1181 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1184 if ( $wgUser->isAnon() )
1186 $wgOut->loginToUse();
1189 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1191 $wgOut->sysopRequired();
1194 $rcid = $wgRequest->getVal( 'rcid' );
1195 if ( !is_null ( $rcid ) )
1197 RecentChange
::markPatrolled( $rcid );
1198 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1199 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1201 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1202 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1206 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1212 * Add this page to $wgUser's watchlist
1217 global $wgUser, $wgOut;
1219 if ( $wgUser->isAnon() ) {
1220 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1223 if ( wfReadOnly() ) {
1224 $wgOut->readOnlyPage();
1228 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1230 $wgUser->addWatch( $this->mTitle
);
1231 $wgUser->saveSettings();
1233 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1235 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1236 $wgOut->setRobotpolicy( 'noindex,follow' );
1238 $link = $this->mTitle
->getPrefixedText();
1239 $text = wfMsg( 'addedwatchtext', $link );
1240 $wgOut->addWikiText( $text );
1243 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1247 * Stop watching a page
1250 function unwatch() {
1252 global $wgUser, $wgOut;
1254 if ( $wgUser->isAnon() ) {
1255 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1258 if ( wfReadOnly() ) {
1259 $wgOut->readOnlyPage();
1263 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1265 $wgUser->removeWatch( $this->mTitle
);
1266 $wgUser->saveSettings();
1268 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1270 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1271 $wgOut->setRobotpolicy( 'noindex,follow' );
1273 $link = $this->mTitle
->getPrefixedText();
1274 $text = wfMsg( 'removedwatchtext', $link );
1275 $wgOut->addWikiText( $text );
1278 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1284 function protect( $limit = 'sysop' ) {
1285 global $wgUser, $wgOut, $wgRequest;
1287 if ( ! $wgUser->isAllowed('protect') ) {
1288 $wgOut->sysopRequired();
1291 if ( wfReadOnly() ) {
1292 $wgOut->readOnlyPage();
1295 $id = $this->mTitle
->getArticleID();
1297 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1301 $confirm = $wgRequest->wasPosted() &&
1302 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1303 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1304 $reason = $wgRequest->getText( 'wpReasonProtect' );
1307 $dbw =& wfGetDB( DB_MASTER
);
1308 $dbw->update( 'page',
1310 'page_touched' => $dbw->timestamp(),
1311 'page_restrictions' => (string)$limit
1312 ), array( /* WHERE */
1314 ), 'Article::protect'
1317 $restrictions = "move=" . $limit;
1319 $restrictions .= ":edit=" . $limit;
1321 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1323 $dbw =& wfGetDB( DB_MASTER
);
1324 $dbw->update( 'page',
1326 'page_touched' => $dbw->timestamp(),
1327 'page_restrictions' => $restrictions
1328 ), array( /* WHERE */
1330 ), 'Article::protect'
1333 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1335 $log = new LogPage( 'protect' );
1336 if ( $limit === '' ) {
1337 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1339 $log->addEntry( 'protect', $this->mTitle
, $reason );
1341 $wgOut->redirect( $this->mTitle
->getFullURL() );
1345 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1346 return $this->confirmProtect( '', $reason, $limit );
1351 * Output protection confirmation dialog
1353 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1354 global $wgOut, $wgUser;
1356 wfDebug( "Article::confirmProtect\n" );
1358 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1359 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1365 if ( $limit === '' ) {
1366 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1367 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1368 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1369 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1370 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1372 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1373 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1374 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1375 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1376 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1377 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1380 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1381 $token = htmlspecialchars( $wgUser->editToken() );
1384 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1388 <label for='wpReasonProtect'>{$protcom}:</label>
1391 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1397 if($moveonly != '') {
1401 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1404 <label for='wpMoveOnly'>{$moveonly}</label>
1412 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1416 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1419 $wgOut->returnToMain( false );
1423 * Unprotect the pages
1425 function unprotect() {
1426 return $this->protect( '' );
1430 * UI entry point for page deletion
1433 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1434 $fname = 'Article::delete';
1435 $confirm = $wgRequest->wasPosted() &&
1436 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1437 $reason = $wgRequest->getText( 'wpReason' );
1439 # This code desperately needs to be totally rewritten
1442 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1443 $wgOut->sysopRequired();
1446 if ( wfReadOnly() ) {
1447 $wgOut->readOnlyPage();
1451 # Better double-check that it hasn't been deleted yet!
1452 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1453 if ( ( '' == trim( $this->mTitle
->getText() ) )
1454 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1455 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1460 $this->doDelete( $reason );
1464 # determine whether this page has earlier revisions
1465 # and insert a warning if it does
1466 # we select the text because it might be useful below
1467 $dbr =& $this->getDB();
1468 $ns = $this->mTitle
->getNamespace();
1469 $title = $this->mTitle
->getDBkey();
1470 $revisions = $dbr->select( array( 'page', 'revision' ),
1473 'page_namespace' => $ns,
1474 'page_title' => $title,
1475 'rev_page = page_id'
1476 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1479 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1480 $skin=$wgUser->getSkin();
1481 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1482 $wgOut->addHTML( $skin->historyLink() .'</b>');
1486 $s = $dbr->selectRow( array( 'page', 'text' ),
1487 array( 'old_text' ),
1489 'page_namespace' => $ns,
1490 'page_title' => $title,
1491 'page_latest = old_id'
1492 ), $fname, $this->getSelectOptions()
1495 if( $s !== false ) {
1496 # if this is a mini-text, we can paste part of it into the deletion reason
1498 #if this is empty, an earlier revision may contain "useful" text
1500 if($s->old_text
!= '') {
1504 $text = Revision
::getRevisionText( $old );
1510 $length=strlen($text);
1512 # this should not happen, since it is not possible to store an empty, new
1513 # page. Let's insert a standard text in case it does, though
1514 if($length == 0 && $reason === '') {
1515 $reason = wfMsg('exblank');
1518 if($length < 500 && $reason === '') {
1520 # comment field=255, let's grep the first 150 to have some user
1522 $text=substr($text,0,150);
1523 # let's strip out newlines and HTML tags
1524 $text=preg_replace('/\"/',"'",$text);
1525 $text=preg_replace('/\</','<',$text);
1526 $text=preg_replace('/\>/','>',$text);
1527 $text=preg_replace("/[\n\r]/",'',$text);
1529 $reason=wfMsg('excontent'). " '".$text;
1531 $reason=wfMsg('exbeforeblank') . " '".$text;
1533 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1538 return $this->confirmDelete( '', $reason );
1542 * Output deletion confirmation dialog
1544 function confirmDelete( $par, $reason ) {
1545 global $wgOut, $wgUser;
1547 wfDebug( "Article::confirmDelete\n" );
1549 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1550 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1551 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1552 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1554 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1556 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1557 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1558 $token = htmlspecialchars( $wgUser->editToken() );
1561 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1565 <label for='wpReason'>{$delcom}:</label>
1568 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1577 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1581 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1584 $wgOut->returnToMain( false );
1589 * Perform a deletion and output success or failure messages
1591 function doDelete( $reason ) {
1592 global $wgOut, $wgUser, $wgContLang;
1593 $fname = 'Article::doDelete';
1594 wfDebug( $fname."\n" );
1596 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1597 if ( $this->doDeleteArticle( $reason ) ) {
1598 $deleted = $this->mTitle
->getPrefixedText();
1600 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1601 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1603 $sk = $wgUser->getSkin();
1604 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1605 ':' . wfMsgForContent( 'dellogpage' ),
1606 wfMsg( 'deletionlog' ) );
1608 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1610 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1611 $wgOut->returnToMain( false );
1612 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1614 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1620 * Back-end article deletion
1621 * Deletes the article with database consistency, writes logs, purges caches
1624 function doDeleteArticle( $reason ) {
1626 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1628 $fname = 'Article::doDeleteArticle';
1629 wfDebug( $fname."\n" );
1631 $dbw =& wfGetDB( DB_MASTER
);
1632 $ns = $this->mTitle
->getNamespace();
1633 $t = $this->mTitle
->getDBkey();
1634 $id = $this->mTitle
->getArticleID();
1636 if ( $t == '' ||
$id == 0 ) {
1640 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1641 array_push( $wgDeferredUpdateList, $u );
1643 $linksTo = $this->mTitle
->getLinksTo();
1646 if ( $wgUseSquid ) {
1648 $this->mTitle
->getInternalURL(),
1649 $this->mTitle
->getInternalURL( 'history' )
1651 foreach ( $linksTo as $linkTo ) {
1652 $urls[] = $linkTo->getInternalURL();
1655 $u = new SquidUpdate( $urls );
1656 array_push( $wgPostCommitUpdateList, $u );
1660 # Client and file cache invalidation
1661 Title
::touchArray( $linksTo );
1663 # Move article and history to the "archive" table
1665 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1667 'ar_namespace' => 'page_namespace',
1668 'ar_title' => 'page_title',
1669 'ar_text' => 'old_text',
1670 'ar_comment' => 'rev_comment',
1671 'ar_user' => 'rev_user',
1672 'ar_user_text' => 'rev_user_text',
1673 'ar_timestamp' => 'rev_timestamp',
1674 'ar_minor_edit' => 'rev_minor_edit',
1675 'ar_flags' => 'old_flags',
1676 'ar_rev_id' => 'rev_id',
1678 'page_namespace' => $ns,
1680 'page_id = rev_page AND old_id = rev_id'
1684 # Now that it's safely backed up, delete it
1686 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1687 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1688 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1690 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1692 # Finally, clean up the link tables
1693 $t = $this->mTitle
->getPrefixedDBkey();
1695 Article
::onArticleDelete( $this->mTitle
);
1697 # Insert broken links
1698 $brokenLinks = array();
1699 foreach ( $linksTo as $titleObj ) {
1700 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1701 $linkID = $titleObj->getArticleID();
1702 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1704 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1707 $dbw->delete( 'links', array( 'l_to' => $id ) );
1708 $dbw->delete( 'links', array( 'l_from' => $id ) );
1709 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1710 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1711 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1714 $log = new LogPage( 'delete' );
1715 $log->addEntry( 'delete', $this->mTitle
, $reason );
1717 # Clear the cached article id so the interface doesn't act like we exist
1718 $this->mTitle
->resetArticleID( 0 );
1719 $this->mTitle
->mArticleID
= 0;
1724 * Revert a modification
1726 function rollback() {
1727 global $wgUser, $wgOut, $wgRequest;
1728 $fname = 'Article::rollback';
1730 if ( ! $wgUser->isAllowed('rollback') ) {
1731 $wgOut->sysopRequired();
1734 if ( wfReadOnly() ) {
1735 $wgOut->readOnlyPage( $this->getContent( true ) );
1738 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1739 array( $this->mTitle
->getPrefixedText(),
1740 $wgRequest->getVal( 'from' ) ) ) ) {
1741 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1742 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1745 $dbw =& wfGetDB( DB_MASTER
);
1747 # Enhanced rollback, marks edits rc_bot=1
1748 $bot = $wgRequest->getBool( 'bot' );
1750 # Replace all this user's current edits with the next one down
1751 $tt = $this->mTitle
->getDBKey();
1752 $n = $this->mTitle
->getNamespace();
1754 # Get the last editor, lock table exclusively
1756 $current = Revision
::newFromTitle( $this->mTitle
);
1757 if( is_null( $current ) ) {
1758 # Something wrong... no page?
1760 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1764 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1765 if( $from != $current->getUserText() ) {
1766 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1767 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1768 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1769 htmlspecialchars( $from ),
1770 htmlspecialchars( $current->getUserText() ) ) );
1771 if( $current->getComment() != '') {
1773 wfMsg( 'editcomment',
1774 htmlspecialchars( $current->getComment() ) ) );
1779 # Get the last edit not by this guy
1780 $user = IntVal( $current->getUser() );
1781 $user_text = $dbw->addQuotes( $current->getUserText() );
1782 $s = $dbw->selectRow( 'revision',
1783 array( 'rev_id', 'rev_timestamp' ),
1785 'rev_page' => $current->getPage(),
1786 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1789 'USE INDEX' => 'page_timestamp',
1790 'ORDER BY' => 'rev_timestamp DESC' )
1792 if( $s === false ) {
1795 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1796 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1801 # Mark all reverted edits as bot
1802 $dbw->update( 'recentchanges',
1805 ), array( /* WHERE */
1806 'rc_cur_id' => $current->getPage(),
1807 'rc_user_text' => $current->getUserText(),
1808 "rc_timestamp > '{$s->rev_timestamp}'",
1814 $target = Revision
::newFromId( $s->rev_id
);
1815 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1817 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1818 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1819 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1821 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1822 Article
::onArticleEdit( $this->mTitle
);
1825 $wgOut->returnToMain( false );
1830 * Do standard deferred updates after page view
1833 function viewUpdates() {
1834 global $wgDeferredUpdateList;
1836 if ( 0 != $this->getID() ) {
1837 global $wgDisableCounters;
1838 if( !$wgDisableCounters ) {
1839 Article
::incViewCount( $this->getID() );
1840 $u = new SiteStatsUpdate( 1, 0, 0 );
1841 array_push( $wgDeferredUpdateList, $u );
1845 # Update newtalk status if user is reading their own
1849 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1850 $this->mTitle
->getText() == $wgUser->getName()) {
1851 require_once( 'UserTalkUpdate.php' );
1852 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1854 $wgUser->clearNotification( $this->mTitle
);
1860 * Do standard deferred updates after page edit.
1861 * Every 1000th edit, prune the recent changes table.
1863 * @param string $text
1865 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1866 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1867 global $wgMessageCache, $wgUser;
1870 if ( 0 == mt_rand( 0, 999 ) ) {
1871 # Periodically flush old entries from the recentchanges table.
1873 $dbw =& wfGetDB( DB_MASTER
);
1874 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1875 $recentchanges = $dbw->tableName( 'recentchanges' );
1876 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1877 $dbw->query( $sql );
1879 $id = $this->getID();
1880 $title = $this->mTitle
->getPrefixedDBkey();
1881 $shortTitle = $this->mTitle
->getDBkey();
1883 $adj = $this->mCountAdjustment
;
1886 $u = new LinksUpdate( $id, $title );
1887 array_push( $wgDeferredUpdateList, $u );
1888 $u = new SiteStatsUpdate( 0, 1, $adj );
1889 array_push( $wgDeferredUpdateList, $u );
1890 $u = new SearchUpdate( $id, $title, $text );
1891 array_push( $wgDeferredUpdateList, $u );
1893 # If this is another user's talk page,
1894 # create a watchlist entry for this page
1896 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1897 $shortTitle != $wgUser->getName()) {
1898 require_once( 'UserTalkUpdate.php' );
1899 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1902 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1903 $wgMessageCache->replace( $shortTitle, $text );
1909 * @todo document this function
1911 * @param string $oldid Revision ID of this article revision
1913 function setOldSubtitle( $oldid=0 ) {
1914 global $wgLang, $wgOut, $wgUser;
1916 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1917 $sk = $wgUser->getSkin();
1918 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1919 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1920 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1921 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1922 $wgOut->setSubtitle( $r );
1926 * This function is called right before saving the wikitext,
1927 * so we can do things like signatures and links-in-context.
1929 * @param string $text
1931 function preSaveTransform( $text ) {
1932 global $wgParser, $wgUser;
1933 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1936 /* Caching functions */
1939 * checkLastModified returns true if it has taken care of all
1940 * output to the client that is necessary for this request.
1941 * (that is, it has sent a cached version of the page)
1943 function tryFileCache() {
1944 static $called = false;
1946 wfDebug( " tryFileCache() -- called twice!?\n" );
1950 if($this->isFileCacheable()) {
1951 $touched = $this->mTouched
;
1952 $cache = new CacheManager( $this->mTitle
);
1953 if($cache->isFileCacheGood( $touched )) {
1955 wfDebug( " tryFileCache() - about to load\n" );
1956 $cache->loadFromFileCache();
1959 wfDebug( " tryFileCache() - starting buffer\n" );
1960 ob_start( array(&$cache, 'saveToFileCache' ) );
1963 wfDebug( " tryFileCache() - not cacheable\n" );
1968 * Check if the page can be cached
1971 function isFileCacheable() {
1972 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1973 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1975 return $wgUseFileCache
1976 and (!$wgShowIPinHeader)
1977 and ($this->getID() != 0)
1978 and ($wgUser->isAnon())
1979 and (!$wgUser->getNewtalk())
1980 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1981 and (empty( $action ) ||
$action == 'view')
1982 and (!isset($oldid))
1984 and (!isset($redirect))
1985 and (!isset($printable))
1986 and (!$this->mRedirectedFrom
);
1990 * Loads cur_touched and returns a value indicating if it should be used
1993 function checkTouched() {
1994 $fname = 'Article::checkTouched';
1995 $id = $this->getID();
1996 $dbr =& $this->getDB();
1997 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1998 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1999 if( $s !== false ) {
2000 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
2001 return !$s->page_is_redirect
;
2008 * Edit an article without doing all that other stuff
2009 * The article must already exist; link tables etc
2010 * are not updated, caches are not flushed.
2012 * @param string $text text submitted
2013 * @param string $comment comment submitted
2014 * @param bool $minor whereas it's a minor modification
2016 function quickEdit( $text, $comment = '', $minor = 0 ) {
2017 $fname = 'Article::quickEdit';
2018 wfProfileIn( $fname );
2020 $dbw =& wfGetDB( DB_MASTER
);
2022 $revision = new Revision( array(
2023 'page' => $this->getId(),
2025 'comment' => $comment,
2026 'minor_edit' => $minor ?
1 : 0,
2028 $revisionId = $revision->insertOn( $dbw );
2029 $this->updateRevisionOn( $dbw, $revision );
2032 wfProfileOut( $fname );
2036 * Used to increment the view counter
2039 * @param integer $id article id
2041 function incViewCount( $id ) {
2042 $id = intval( $id );
2043 global $wgHitcounterUpdateFreq;
2045 $dbw =& wfGetDB( DB_MASTER
);
2046 $pageTable = $dbw->tableName( 'page' );
2047 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2048 $acchitsTable = $dbw->tableName( 'acchits' );
2050 if( $wgHitcounterUpdateFreq <= 1 ){ //
2051 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2055 # Not important enough to warrant an error page in case of failure
2056 $oldignore = $dbw->ignoreErrors( true );
2058 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2060 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2061 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2062 # Most of the time (or on SQL errors), skip row count check
2063 $dbw->ignoreErrors( $oldignore );
2067 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2068 $row = $dbw->fetchObject( $res );
2069 $rown = intval( $row->n
);
2070 if( $rown >= $wgHitcounterUpdateFreq ){
2071 wfProfileIn( 'Article::incViewCount-collect' );
2072 $old_user_abort = ignore_user_abort( true );
2074 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2075 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2076 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2078 $dbw->query("DELETE FROM $hitcounterTable");
2079 $dbw->query('UNLOCK TABLES');
2080 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2081 'WHERE cur_id = hc_id');
2082 $dbw->query("DROP TABLE $acchitsTable");
2084 ignore_user_abort( $old_user_abort );
2085 wfProfileOut( 'Article::incViewCount-collect' );
2087 $dbw->ignoreErrors( $oldignore );
2091 * The onArticle*() functions are supposed to be a kind of hooks
2092 * which should be called whenever any of the specified actions
2095 * This is a good place to put code to clear caches, for instance.
2097 * This is called on page move and undelete, as well as edit
2099 * @param $title_obj a title object
2102 function onArticleCreate($title_obj) {
2103 global $wgUseSquid, $wgPostCommitUpdateList;
2105 $titles = $title_obj->getBrokenLinksTo();
2108 if ( $wgUseSquid ) {
2109 $urls = $title_obj->getSquidURLs();
2110 foreach ( $titles as $linkTitle ) {
2111 $urls[] = $linkTitle->getInternalURL();
2113 $u = new SquidUpdate( $urls );
2114 array_push( $wgPostCommitUpdateList, $u );
2117 # Clear persistent link cache
2118 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2121 function onArticleDelete($title_obj) {
2122 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2124 function onArticleEdit($title_obj) {
2125 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2130 * Info about this page
2131 * Called for ?action=info when $wgAllowPageInfo is on.
2136 global $wgLang, $wgOut, $wgAllowPageInfo;
2137 $fname = 'Article::info';
2139 if ( !$wgAllowPageInfo ) {
2140 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2144 $page = $this->mTitle
->getSubjectPage();
2146 $wgOut->setPagetitle( $page->getPrefixedText() );
2147 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2149 # first, see if the page exists at all.
2150 $exists = $page->getArticleId() != 0;
2152 $wgOut->addHTML( wfMsg('noarticletext') );
2154 $dbr =& $this->getDB( DB_SLAVE
);
2156 'wl_title' => $page->getDBkey(),
2157 'wl_namespace' => $page->getNamespace() );
2158 $numwatchers = $dbr->selectField(
2163 $this->getSelectOptions() );
2165 $pageInfo = $this->pageCountInfo( $page );
2166 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2168 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2169 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2171 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2173 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2175 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2177 $wgOut->addHTML( '</ul>' );
2183 * Return the total number of edits and number of unique editors
2184 * on a given page. If page does not exist, returns false.
2186 * @param Title $title
2190 function pageCountInfo( $title ) {
2191 $id = $title->getArticleId();
2196 $dbr =& $this->getDB( DB_SLAVE
);
2198 $rev_clause = array( 'rev_page' => $id );
2199 $fname = 'Article::pageCountInfo';
2201 $edits = $dbr->selectField(
2206 $this->getSelectOptions() );
2208 $authors = $dbr->selectField(
2210 'COUNT(DISTINCT rev_user_text)',
2213 $this->getSelectOptions() );
2215 return array( 'edits' => $edits, 'authors' => $authors );