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 $dbr =& $this->getDB();
219 $oldid = IntVal( $oldid );
220 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
221 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
225 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
227 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
228 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
237 return @$oldid; # "@" to be able to return "unset" without PHP complaining
242 * Load the revision (including cur_text) into this object
244 function loadContent( $noredir = false ) {
245 global $wgOut, $wgRequest;
247 if ( $this->mContentLoaded
) return;
249 $dbr =& $this->getDB();
251 $oldid = $this->getOldID();
252 $redirect = $wgRequest->getVal( 'redirect' );
254 $fname = 'Article::loadContent';
256 # Pre-fill content with error message so that if something
257 # fails we'll have something telling us what we intended.
259 $t = $this->mTitle
->getPrefixedText();
261 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no');
262 $this->mOldId
= $oldid;
263 $this->fetchContent( $oldid, $noredir, true );
267 * @param int $oldid 0 for whatever the latest revision is
268 * @param bool $noredir Set to true to avoid following redirects
269 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
272 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
273 if ( $this->mContentLoaded
) {
274 return $this->mContent
;
276 $dbr =& $this->getDB();
277 $fname = 'Article::fetchContent';
279 # Pre-fill content with error message so that if something
280 # fails we'll have something telling us what we intended.
281 $t = $this->mTitle
->getPrefixedText();
283 $t .= ',oldid='.$oldid;
285 if( isset( $redirect ) ) {
286 $redirect = ($redirect == 'no') ?
'no' : 'yes';
287 $t .= ',redirect='.$redirect;
289 $this->mContent
= wfMsg( 'missingarticle', $t );
292 # Retrieve current version
293 $id = $this->getID();
298 $s = $dbr->selectRow( array( 'text', 'revision', 'page' ),
299 $this->getContentFields(),
300 "page_id='$id' AND rev_page=page_id AND rev_id=page_latest AND old_id=rev_id",
301 $fname, $this->getSelectOptions() );
303 # Historical revision
304 $s = $dbr->selectRow( array( 'text', 'revision', 'page' ),
305 $this->getContentFields(),
306 "rev_page=page_id AND rev_id='$oldid' AND old_id=rev_id",
307 $fname, $this->getSelectOptions() );
309 if ( $s === false ) {
313 # If we got a redirect, follow it (unless we've been told
314 # not to by either the function parameter or the query
315 if ( !$oldid && !$noredir ) {
316 $rt = Title
::newFromRedirect( Revision
::getRevisionText( $s ) );
317 # process if title object is valid and not special:userlogout
318 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
319 # Gotta hand redirects to special pages differently:
320 # Fill the HTTP response "Location" header and ignore
321 # the rest of the page we're on.
324 if ( $rt->getInterwiki() != '' ) {
325 $wgOut->redirect( $rt->getFullURL() ) ;
328 if ( $rt->getNamespace() == NS_SPECIAL
) {
329 $wgOut->redirect( $rt->getFullURL() );
333 $rid = $rt->getArticleID();
335 $redirRow = $dbr->selectRow( array( 'text', 'revision', 'page' ),
336 $this->getContentFields(),
337 "page_id='$rid' AND rev_page=page_id AND rev_id=page_latest AND old_id=rev_id",
338 $fname, $this->getSelectOptions() );
340 if ( $redirRow !== false ) {
341 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
349 # if the title's different from expected, update...
351 ( $this->mTitle
->getNamespace() != $s->page_namespace ||
352 $this->mTitle
->getDBkey() != $s->page_title
) ) {
353 $oldTitle = Title
::makeTitle( $s->page_namesapce
, $s->page_title
);
354 $this->mTitle
= $oldTitle;
356 $wgTitle = $oldTitle;
359 # Back to the business at hand...
360 $this->mCounter
= $s->page_counter
;
361 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->page_restrictions
) );
362 $this->mTitle
->mRestrictionsLoaded
= true;
363 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
365 $this->mContent
= Revision
::getRevisionText( $s );
367 $this->mUser
= $s->rev_user
;
368 $this->mUserText
= $s->rev_user_text
;
369 $this->mComment
= $s->rev_comment
;
370 $this->mTimestamp
= wfTimestamp( TS_MW
, $s->rev_timestamp
);
372 $this->mContentLoaded
= true;
373 return $this->mContent
;
377 * Gets the article text without using so many damn globals
378 * Returns false on error
380 * @param integer $oldid
382 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
383 return $this->fetchContent( $oldid, $noredir, false );
387 * Read/write accessor to select FOR UPDATE
389 function forUpdate( $x = NULL ) {
390 return wfSetVar( $this->mForUpdate
, $x );
394 * Get the database which should be used for reads
397 if ( $this->mForUpdate
) {
398 return wfGetDB( DB_MASTER
);
400 return wfGetDB( DB_SLAVE
);
405 * Get options for all SELECT statements
406 * Can pass an option array, to which the class-wide options will be appended
408 function getSelectOptions( $options = '' ) {
409 if ( $this->mForUpdate
) {
411 $options[] = 'FOR UPDATE';
413 $options = 'FOR UPDATE';
420 * Return the Article ID
423 if( $this->mTitle
) {
424 return $this->mTitle
->getArticleID();
431 * Get the view count for this article
433 function getCount() {
434 if ( -1 == $this->mCounter
) {
435 $id = $this->getID();
436 $dbr =& $this->getDB();
437 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
438 'Article::getCount', $this->getSelectOptions() );
440 return $this->mCounter
;
444 * Would the given text make this article a "good" article (i.e.,
445 * suitable for including in the article count)?
447 function isCountable( $text ) {
448 global $wgUseCommaCount;
450 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
451 if ( $this->isRedirect( $text ) ) { return 0; }
452 $token = ($wgUseCommaCount ?
',' : '[[' );
453 if ( false === strstr( $text, $token ) ) { return 0; }
458 * Tests if the article text represents a redirect
460 function isRedirect( $text = false ) {
461 if ( $text === false ) {
462 $this->loadContent();
463 $titleObj = Title
::newFromRedirect( $this->mText
);
465 $titleObj = Title
::newFromRedirect( $text );
467 return $titleObj !== NULL;
471 * Loads everything except the text
472 * This isn't necessary for all uses, so it's only done if needed.
475 function loadLastEdit() {
478 if ( -1 != $this->mUser
)
481 $fname = 'Article::loadLastEdit';
483 $dbr =& $this->getDB();
484 $s = $dbr->selectRow( array( 'revision', 'page') ,
485 array( 'rev_user','rev_user_text','rev_timestamp', 'rev_comment','rev_minor_edit' ),
486 array( 'page_id' => $this->getID(), 'page_latest=rev_id' ), $fname, $this->getSelectOptions() );
488 if ( $s !== false ) {
489 $this->mUser
= $s->rev_user
;
490 $this->mUserText
= $s->rev_user_text
;
491 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->rev_timestamp
);
492 $this->mComment
= $s->rev_comment
;
493 $this->mMinorEdit
= $s->rev_minor_edit
;
497 function getTimestamp() {
498 $this->loadLastEdit();
499 return $this->mTimestamp
;
503 $this->loadLastEdit();
507 function getUserText() {
508 $this->loadLastEdit();
509 return $this->mUserText
;
512 function getComment() {
513 $this->loadLastEdit();
514 return $this->mComment
;
517 function getMinorEdit() {
518 $this->loadLastEdit();
519 return $this->mMinorEdit
;
522 function getContributors($limit = 0, $offset = 0) {
523 $fname = 'Article::getContributors';
525 # XXX: this is expensive; cache this info somewhere.
527 $title = $this->mTitle
;
529 $dbr =& $this->getDB();
530 $revTable = $dbr->tableName( 'revision' );
531 $userTable = $dbr->tableName( 'user' );
532 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
533 $ns = $title->getNamespace();
534 $user = $this->getUser();
536 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
537 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
538 WHERE rev_page = $pageId
539 AND old_user != $user
540 GROUP BY rev_user, rev_user_text, user_real_name
541 ORDER BY timestamp DESC";
543 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
544 $sql .= ' '. $this->getSelectOptions();
546 $res = $dbr->query($sql, $fname);
548 while ( $line = $dbr->fetchObject( $res ) ) {
549 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
552 $dbr->freeResult($res);
557 * This is the default action of the script: just view the page of
561 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
562 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
564 $sk = $wgUser->getSkin();
566 $fname = 'Article::view';
567 wfProfileIn( $fname );
568 # Get variables from query string
569 $oldid = $this->getOldID();
570 $diff = $wgRequest->getVal( 'diff' );
571 $rcid = $wgRequest->getVal( 'rcid' );
573 $wgOut->setArticleFlag( true );
574 $wgOut->setRobotpolicy( 'index,follow' );
575 # If we got diff and oldid in the query, we want to see a
576 # diff page instead of the article.
578 if ( !is_null( $diff ) ) {
579 require_once( 'DifferenceEngine.php' );
580 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
581 $de = new DifferenceEngine( $oldid, $diff, $rcid );
584 # Run view updates for current revision only
585 $this->viewUpdates();
587 wfProfileOut( $fname );
590 if ( empty( $oldid ) && $this->checkTouched() ) {
591 if( $wgOut->checkLastModified( $this->mTouched
) ){
592 wfProfileOut( $fname );
594 } else if ( $this->tryFileCache() ) {
595 # tell wgOut that output is taken care of
597 $this->viewUpdates();
598 wfProfileOut( $fname );
602 # Should the parser cache be used?
603 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
611 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
615 if ( !$outputDone ) {
616 $text = $this->getContent( false ); # May change mTitle by following a redirect
618 # Another whitelist check in case oldid or redirects are altering the title
619 if ( !$this->mTitle
->userCanRead() ) {
620 $wgOut->loginToUse();
626 # We're looking at an old revision
628 if ( !empty( $oldid ) ) {
629 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
630 $wgOut->setRobotpolicy( 'noindex,follow' );
632 if ( '' != $this->mRedirectedFrom
) {
633 $sk = $wgUser->getSkin();
634 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
636 $s = wfMsg( 'redirectedfrom', $redir );
637 $wgOut->setSubtitle( $s );
639 # Can't cache redirects
643 # wrap user css and user js in pre and don't parse
644 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
646 $this->mTitle
->getNamespace() == NS_USER
&&
647 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
649 $wgOut->addWikiText( wfMsg('clearyourcache'));
650 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
651 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
653 $imageUrl = $wgStylePath.'/common/images/redirect.png';
654 $targetUrl = $rt->escapeLocalURL();
655 $titleText = htmlspecialchars( $rt->getPrefixedText() );
656 $link = $sk->makeLinkObj( $rt );
658 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
659 '<span class="redirectText">'.$link.'</span>' );
661 } else if ( $pcache ) {
662 # Display content and save to parser cache
663 $wgOut->addPrimaryWikiText( $text, $this );
665 # Display content, don't attempt to save to parser cache
666 $wgOut->addWikiText( $text );
669 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
670 # If we have been passed an &rcid= parameter, we want to give the user a
671 # chance to mark this new article as patrolled.
672 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
673 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
675 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
676 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
677 'action=markpatrolled&rcid='.$rcid )
681 # Put link titles into the link cache
682 $wgOut->transformBuffer();
684 # Add link titles as META keywords
685 $wgOut->addMetaTags() ;
687 $this->viewUpdates();
688 wfProfileOut( $fname );
690 $wgUser->clearNotification( $this->mTitle
);
694 * Theoretically we could defer these whole insert and update
695 * functions for after display, but that's taking a big leap
696 * of faith, and we want to be able to report database
697 * errors at some point.
700 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
701 global $wgOut, $wgUser;
702 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
704 $fname = 'Article::insertNewArticle';
706 $this->mCountAdjustment
= $this->isCountable( $text );
708 $ns = $this->mTitle
->getNamespace();
709 $ttl = $this->mTitle
->getDBkey();
710 $text = $this->preSaveTransform( $text );
711 if ( $this->isRedirect( $text ) ) { $redir = 1; }
714 $now = wfTimestampNow();
715 $won = wfInvertTimestamp( $now );
718 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
721 $flags = Revision
::compressRevisionText( $mungedText );
723 $dbw =& wfGetDB( DB_MASTER
);
725 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
726 $dbw->insert( 'text', array(
728 'old_text' => $mungedText,
729 'old_flags' => $flags,
731 $revisionId = $dbw->insertId();
733 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
734 $dbw->insert( 'page', array(
735 'page_id' => $page_id,
736 'page_namespace' => $ns,
737 'page_title' => $ttl,
739 'page_restrictions' => '',
740 'page_is_redirect' => $redir,
742 'page_random' => $rand,
743 'page_touched' => $dbw->timestamp($now),
744 'page_latest' => $revisionId,
746 $newid = $dbw->insertId();
748 $dbw->insert( 'revision', array(
749 'rev_page' => $newid,
750 'rev_id' => $revisionId,
751 'rev_comment' => $summary,
752 'rev_user' => $wgUser->getID(),
753 'rev_timestamp' => $dbw->timestamp($now),
754 'rev_minor_edit' => $isminor,
755 'rev_user_text' => $wgUser->getName(),
756 'inverse_timestamp' => $won,
759 $this->mTitle
->resetArticleID( $newid );
761 Article
::onArticleCreate( $this->mTitle
);
762 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
765 if(!$this->mTitle
->userIsWatching()) $this->watch();
767 if ( $this->mTitle
->userIsWatching() ) {
772 # The talk page isn't in the regular link tables, so we need to update manually:
773 $talkns = $ns ^
1; # talk -> normal; normal -> talk
774 $dbw->update( 'page',
775 array( 'page_touched' => $dbw->timestamp($now) ),
776 array( 'page_namespace' => $talkns,
777 'page_title' => $ttl ),
780 # standard deferred updates
781 $this->editUpdates( $text, $summary, $isminor, $now );
783 $oldid = 0; # new article
784 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
788 * Fetch and uncompress the text for a given revision.
789 * Can ask by rev_id number or timestamp (set $field)
791 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
792 $fname = 'Article::fetchRevisionText';
793 $dbw =& wfGetDB( DB_MASTER
);
795 $rev = $dbw->addQuotes( $revId );
797 $rev = 'page_latest';
799 $result = $dbw->query(
800 sprintf( "SELECT old_text, old_flags
802 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
804 $dbw->tableName( 'page' ),
805 $dbw->tableName( 'revision' ),
806 $dbw->tableName( 'text' ),
807 IntVal( $this->mTitle
->getArticleId() ),
811 $obj = $dbw->fetchObject( $result );
812 $dbw->freeResult( $result );
813 $oldtext = Revision
::getRevisionText( $obj );
817 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
818 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
819 if( is_null( $edittime ) ) {
820 $oldtext = $this->fetchRevisionText();
822 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
824 if ($section != '') {
825 if($section=='new') {
826 if($summary) $subject="== {$summary} ==\n\n";
827 $text=$oldtext."\n\n".$subject.$text;
830 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
831 # comments to be stripped as well)
833 $parser=new Parser();
834 $parser->mOutputType
=OT_WIKI
;
835 $oldtext=$parser->strip($oldtext, $striparray, true);
837 # now that we can be sure that no pseudo-sections are in the source,
839 # Unfortunately we can't simply do a preg_replace because that might
840 # replace the wrong section, so we have to use the section counter instead
841 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
842 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
843 $secs[$section*2]=$text."\n\n"; // replace with edited
845 # section 0 is top (intro) section
848 # headline of old section - we need to go through this section
849 # to determine if there are any subsections that now need to
850 # be erased, as the mother section has been replaced with
851 # the text of all subsections.
852 $headline=$secs[$section*2-1];
853 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
856 # determine headline level for wikimarkup headings
857 if(strpos($hlevel,'=')!==false) {
858 $hlevel=strlen($hlevel);
861 $secs[$section*2-1]=''; // erase old headline
864 while(!empty($secs[$count*2-1]) && !$break) {
866 $subheadline=$secs[$count*2-1];
868 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
869 $subhlevel=$matches[1];
870 if(strpos($subhlevel,'=')!==false) {
871 $subhlevel=strlen($subhlevel);
873 if($subhlevel > $hlevel) {
874 // erase old subsections
875 $secs[$count*2-1]='';
878 if($subhlevel <= $hlevel) {
886 $text=join('',$secs);
887 # reinsert the stuff that we stripped out earlier
888 $text=$parser->unstrip($text,$striparray);
889 $text=$parser->unstripNoWiki($text,$striparray);
897 * Change an existing article. Puts the previous version back into the old table, updates RC
898 * and all necessary caches, mostly via the deferred update array.
900 * It is possible to call this function from a command-line script, but note that you should
901 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
903 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
904 global $wgOut, $wgUser;
905 global $wgDBtransactions, $wgMwRedir;
906 global $wgUseSquid, $wgInternalServer;
908 $fname = 'Article::updateArticle';
911 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
912 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
913 if ( $this->isRedirect( $text ) ) {
914 # Remove all content but redirect
915 # This could be done by reconstructing the redirect from a title given by
916 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
918 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
920 $text = $m[1] . "\n";
925 $text = $this->preSaveTransform( $text );
926 $dbw =& wfGetDB( DB_MASTER
);
928 # Update article, but only if changed.
930 # It's important that we either rollback or complete, otherwise an attacker could
931 # overwrite cur entries by sending precisely timed user aborts. Random bored users
932 # could conceivably have the same effect, especially if cur is locked for long periods.
933 if( $wgDBtransactions ) {
934 $dbw->query( 'BEGIN', $fname );
936 $userAbort = ignore_user_abort( true );
939 $oldtext = $this->getContent( true );
941 if ( 0 != strcmp( $text, $oldtext ) ) {
942 $this->mCountAdjustment
= $this->isCountable( $text )
943 - $this->isCountable( $oldtext );
944 $now = wfTimestampNow();
945 $won = wfInvertTimestamp( $now );
948 $flags = Revision
::compressRevisionText( $newtext );
950 $lastRevision = $dbw->selectField(
951 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
953 # Record the text to the text table
954 $old_id = $dbw->nextSequenceValue( 'text_old_id_val' );
955 $dbw->insert( 'text',
958 'old_text' => $mungedText,
959 'old_flags' => $flags,
962 $revisionId = $dbw->insertId();
964 # Record the edit in revisions
965 $dbw->insert( 'revision',
967 'rev_id' => $revisionId,
968 'rev_page' => $this->getID(),
969 'rev_comment' => $summary,
970 'rev_minor_edit' => $me2,
971 'rev_user' => $wgUser->getID(),
972 'rev_user_text' => $wgUser->getName(),
973 'rev_timestamp' => $dbw->timestamp( $now ),
974 'inverse_timestamp' => $won
979 $dbw->update( 'page',
981 'page_latest' => $revisionId,
982 'page_touched' => $dbw->timestamp( $now ),
984 'page_is_redirect' => $redir,
985 ), array( /* WHERE */
986 'page_id' => $this->getID(),
987 'page_latest' => $lastRevision, # Paranoia
991 if( $dbw->affectedRows() == 0 ) {
992 /* Belated edit conflict! Run away!! */
995 # Update recentchanges and purge cache and whatnot
996 $bot = (int)($wgUser->isBot() ||
$forceBot);
997 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
998 $lastRevision, $this->getTimestamp(), $bot );
999 Article
::onArticleEdit( $this->mTitle
);
1003 if( $wgDBtransactions ) {
1004 $dbw->query( 'COMMIT', $fname );
1006 ignore_user_abort( $userAbort );
1011 if (!$this->mTitle
->userIsWatching()) $this->watch();
1013 if ( $this->mTitle
->userIsWatching() ) {
1017 # standard deferred updates
1018 $this->editUpdates( $text, $summary, $minor, $now );
1022 # Template namespace
1023 # Purge all articles linking here
1024 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1025 $titles = $this->mTitle
->getLinksTo();
1026 Title
::touchArray( $titles );
1027 if ( $wgUseSquid ) {
1028 foreach ( $titles as $title ) {
1029 $urls[] = $title->getInternalURL();
1035 if ( $wgUseSquid ) {
1036 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1037 $u = new SquidUpdate( $urls );
1041 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $revisionId );
1047 * After we've either updated or inserted the article, update
1048 * the link tables and redirect to the new page.
1050 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1051 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1053 $wgLinkCache = new LinkCache();
1055 $wgLinkCache->forUpdate( true );
1057 # Get old version of link table to allow incremental link updates
1058 $wgLinkCache->preFill( $this->mTitle
);
1059 $wgLinkCache->clear();
1061 # Parse the text and replace links with placeholders
1062 $wgOut = new OutputPage();
1063 $wgOut->addWikiText( $text );
1065 # Look up the links in the DB and add them to the link cache
1066 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1068 if( $this->isRedirect( $text ) )
1072 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1074 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1075 # this will be improved later (to-do)
1077 include_once( "UserMailer.php" );
1078 $wgEnotif = new EmailNotification ();
1079 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1084 * @todo document this function a bit more
1086 function validate () {
1087 global $wgOut, $wgUseValidation;
1088 if( $wgUseValidation ) {
1089 require_once ( 'SpecialValidate.php' ) ;
1090 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1091 $wgOut->setRobotpolicy( 'noindex,follow' );
1092 if( $this->mTitle
->getNamespace() != 0 ) {
1093 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1096 $v = new Validation
;
1097 $v->validate_form( $this->mTitle
->getDBkey() );
1099 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1104 * Mark this particular edit as patrolled
1106 function markpatrolled() {
1107 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1108 $wgOut->setRobotpolicy( 'noindex,follow' );
1110 if ( !$wgUseRCPatrol )
1112 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1115 if ( $wgUser->getID() == 0 )
1117 $wgOut->loginToUse();
1120 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1122 $wgOut->sysopRequired();
1125 $rcid = $wgRequest->getVal( 'rcid' );
1126 if ( !is_null ( $rcid ) )
1128 RecentChange
::markPatrolled( $rcid );
1129 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1130 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1132 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1133 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1137 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1143 * Add this page to $wgUser's watchlist
1148 global $wgUser, $wgOut;
1150 if ( 0 == $wgUser->getID() ) {
1151 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1154 if ( wfReadOnly() ) {
1155 $wgOut->readOnlyPage();
1159 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1161 $wgUser->addWatch( $this->mTitle
);
1162 $wgUser->saveSettings();
1164 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1166 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1167 $wgOut->setRobotpolicy( 'noindex,follow' );
1169 $link = $this->mTitle
->getPrefixedText();
1170 $text = wfMsg( 'addedwatchtext', $link );
1171 $wgOut->addWikiText( $text );
1174 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1178 * Stop watching a page
1181 function unwatch() {
1183 global $wgUser, $wgOut;
1185 if ( 0 == $wgUser->getID() ) {
1186 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1189 if ( wfReadOnly() ) {
1190 $wgOut->readOnlyPage();
1194 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1196 $wgUser->removeWatch( $this->mTitle
);
1197 $wgUser->saveSettings();
1199 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1201 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1202 $wgOut->setRobotpolicy( 'noindex,follow' );
1204 $link = $this->mTitle
->getPrefixedText();
1205 $text = wfMsg( 'removedwatchtext', $link );
1206 $wgOut->addWikiText( $text );
1209 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1215 function protect( $limit = 'sysop' ) {
1216 global $wgUser, $wgOut, $wgRequest;
1218 if ( ! $wgUser->isAllowed('protect') ) {
1219 $wgOut->sysopRequired();
1222 if ( wfReadOnly() ) {
1223 $wgOut->readOnlyPage();
1226 $id = $this->mTitle
->getArticleID();
1228 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1232 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1233 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1234 $reason = $wgRequest->getText( 'wpReasonProtect' );
1237 $dbw =& wfGetDB( DB_MASTER
);
1238 $dbw->update( 'page',
1240 'page_touched' => $dbw->timestamp(),
1241 'page_restrictions' => (string)$limit
1242 ), array( /* WHERE */
1244 ), 'Article::protect'
1247 $restrictions = "move=" . $limit;
1249 $restrictions .= ":edit=" . $limit;
1251 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1253 $dbw =& wfGetDB( DB_MASTER
);
1254 $dbw->update( 'page',
1256 'page_touched' => $dbw->timestamp(),
1257 'page_restrictions' => $restrictions
1258 ), array( /* WHERE */
1260 ), 'Article::protect'
1263 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1265 $log = new LogPage( 'protect' );
1266 if ( $limit === '' ) {
1267 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1269 $log->addEntry( 'protect', $this->mTitle
, $reason );
1271 $wgOut->redirect( $this->mTitle
->getFullURL() );
1275 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1276 return $this->confirmProtect( '', $reason, $limit );
1281 * Output protection confirmation dialog
1283 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1286 wfDebug( "Article::confirmProtect\n" );
1288 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1289 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1295 if ( $limit === '' ) {
1296 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1297 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1298 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1299 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1300 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1301 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1303 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1304 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1305 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1306 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1307 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1308 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1309 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1312 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1315 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1319 <label for='wpReasonProtect'>{$protcom}:</label>
1322 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1330 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1333 <label for='wpConfirmProtect'>{$check}</label>
1336 if($moveonly != '') {
1340 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1343 <label for='wpMoveOnly'>{$moveonly}</label>
1351 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1357 $wgOut->returnToMain( false );
1361 * Unprotect the pages
1363 function unprotect() {
1364 return $this->protect( '' );
1368 * UI entry point for page deletion
1371 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1372 $fname = 'Article::delete';
1373 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1374 $reason = $wgRequest->getText( 'wpReason' );
1376 # This code desperately needs to be totally rewritten
1379 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1380 $wgOut->sysopRequired();
1383 if ( wfReadOnly() ) {
1384 $wgOut->readOnlyPage();
1388 # Better double-check that it hasn't been deleted yet!
1389 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1390 if ( ( '' == trim( $this->mTitle
->getText() ) )
1391 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1392 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1397 $this->doDelete( $reason );
1401 # determine whether this page has earlier revisions
1402 # and insert a warning if it does
1403 # we select the text because it might be useful below
1404 $dbr =& $this->getDB();
1405 $ns = $this->mTitle
->getNamespace();
1406 $title = $this->mTitle
->getDBkey();
1407 $old = $dbr->selectRow( 'old',
1408 array( 'old_text', 'old_flags' ),
1410 'old_namespace' => $ns,
1411 'old_title' => $title,
1412 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1415 if( $old !== false && !$confirm ) {
1416 $skin=$wgUser->getSkin();
1417 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1418 $wgOut->addHTML( $skin->historyLink() .'</b>');
1422 $s = $dbr->selectRow( 'cur',
1423 array( 'cur_text' ),
1425 'cur_namespace' => $ns,
1426 'cur_title' => $title,
1427 ), $fname, $this->getSelectOptions()
1430 if( $s !== false ) {
1431 # if this is a mini-text, we can paste part of it into the deletion reason
1433 #if this is empty, an earlier revision may contain "useful" text
1435 if($s->cur_text
!= '') {
1439 $text = Revision
::getRevisionText( $old );
1445 $length=strlen($text);
1447 # this should not happen, since it is not possible to store an empty, new
1448 # page. Let's insert a standard text in case it does, though
1449 if($length == 0 && $reason === '') {
1450 $reason = wfMsg('exblank');
1453 if($length < 500 && $reason === '') {
1455 # comment field=255, let's grep the first 150 to have some user
1457 $text=substr($text,0,150);
1458 # let's strip out newlines and HTML tags
1459 $text=preg_replace('/\"/',"'",$text);
1460 $text=preg_replace('/\</','<',$text);
1461 $text=preg_replace('/\>/','>',$text);
1462 $text=preg_replace("/[\n\r]/",'',$text);
1464 $reason=wfMsg('excontent'). " '".$text;
1466 $reason=wfMsg('exbeforeblank') . " '".$text;
1468 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1473 return $this->confirmDelete( '', $reason );
1477 * Output deletion confirmation dialog
1479 function confirmDelete( $par, $reason ) {
1482 wfDebug( "Article::confirmDelete\n" );
1484 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1485 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1486 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1487 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1489 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1491 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1492 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1493 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1496 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1500 <label for='wpReason'>{$delcom}:</label>
1503 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1511 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1514 <label for='wpConfirm'>{$check}</label>
1520 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1526 $wgOut->returnToMain( false );
1531 * Perform a deletion and output success or failure messages
1533 function doDelete( $reason ) {
1534 global $wgOut, $wgUser, $wgContLang;
1535 $fname = 'Article::doDelete';
1536 wfDebug( $fname."\n" );
1538 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1539 if ( $this->doDeleteArticle( $reason ) ) {
1540 $deleted = $this->mTitle
->getPrefixedText();
1542 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1543 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1545 $sk = $wgUser->getSkin();
1546 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1547 ':' . wfMsgForContent( 'dellogpage' ),
1548 wfMsg( 'deletionlog' ) );
1550 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1552 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1553 $wgOut->returnToMain( false );
1554 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1556 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1562 * Back-end article deletion
1563 * Deletes the article with database consistency, writes logs, purges caches
1566 function doDeleteArticle( $reason ) {
1568 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1570 $fname = 'Article::doDeleteArticle';
1571 wfDebug( $fname."\n" );
1573 $dbw =& wfGetDB( DB_MASTER
);
1574 $ns = $this->mTitle
->getNamespace();
1575 $t = $this->mTitle
->getDBkey();
1576 $id = $this->mTitle
->getArticleID();
1578 if ( $t == '' ||
$id == 0 ) {
1582 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1583 array_push( $wgDeferredUpdateList, $u );
1585 $linksTo = $this->mTitle
->getLinksTo();
1588 if ( $wgUseSquid ) {
1590 $this->mTitle
->getInternalURL(),
1591 $this->mTitle
->getInternalURL( 'history' )
1593 foreach ( $linksTo as $linkTo ) {
1594 $urls[] = $linkTo->getInternalURL();
1597 $u = new SquidUpdate( $urls );
1598 array_push( $wgDeferredUpdateList, $u );
1602 # Client and file cache invalidation
1603 Title
::touchArray( $linksTo );
1605 # Move article and history to the "archive" table
1606 $archiveTable = $dbw->tableName( 'archive' );
1607 $oldTable = $dbw->tableName( 'old' );
1608 $curTable = $dbw->tableName( 'cur' );
1609 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1610 $linksTable = $dbw->tableName( 'links' );
1611 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1613 $dbw->insertSelect( 'archive', 'cur',
1615 'ar_namespace' => 'cur_namespace',
1616 'ar_title' => 'cur_title',
1617 'ar_text' => 'cur_text',
1618 'ar_comment' => 'cur_comment',
1619 'ar_user' => 'cur_user',
1620 'ar_user_text' => 'cur_user_text',
1621 'ar_timestamp' => 'cur_timestamp',
1622 'ar_minor_edit' => 'cur_minor_edit',
1625 'cur_namespace' => $ns,
1630 $dbw->insertSelect( 'archive', 'old',
1632 'ar_namespace' => 'old_namespace',
1633 'ar_title' => 'old_title',
1634 'ar_text' => 'old_text',
1635 'ar_comment' => 'old_comment',
1636 'ar_user' => 'old_user',
1637 'ar_user_text' => 'old_user_text',
1638 'ar_timestamp' => 'old_timestamp',
1639 'ar_minor_edit' => 'old_minor_edit',
1640 'ar_flags' => 'old_flags'
1642 'old_namespace' => $ns,
1647 # Now that it's safely backed up, delete it
1649 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1650 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1651 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1653 # Finally, clean up the link tables
1654 $t = $this->mTitle
->getPrefixedDBkey();
1656 Article
::onArticleDelete( $this->mTitle
);
1658 # Insert broken links
1659 $brokenLinks = array();
1660 foreach ( $linksTo as $titleObj ) {
1661 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1662 $linkID = $titleObj->getArticleID();
1663 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1665 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1668 $dbw->delete( 'links', array( 'l_to' => $id ) );
1669 $dbw->delete( 'links', array( 'l_from' => $id ) );
1670 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1671 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1672 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1675 $log = new LogPage( 'delete' );
1676 $log->addEntry( 'delete', $this->mTitle
, $reason );
1678 # Clear the cached article id so the interface doesn't act like we exist
1679 $this->mTitle
->resetArticleID( 0 );
1680 $this->mTitle
->mArticleID
= 0;
1685 * Revert a modification
1687 function rollback() {
1688 global $wgUser, $wgOut, $wgRequest;
1689 $fname = 'Article::rollback';
1691 if ( ! $wgUser->isAllowed('rollback') ) {
1692 $wgOut->sysopRequired();
1695 if ( wfReadOnly() ) {
1696 $wgOut->readOnlyPage( $this->getContent( true ) );
1699 $dbw =& wfGetDB( DB_MASTER
);
1701 # Enhanced rollback, marks edits rc_bot=1
1702 $bot = $wgRequest->getBool( 'bot' );
1704 # Replace all this user's current edits with the next one down
1705 $tt = $this->mTitle
->getDBKey();
1706 $n = $this->mTitle
->getNamespace();
1708 # Get the last editor, lock table exclusively
1709 $s = $dbw->selectRow( 'cur',
1710 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1711 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1712 $fname, 'FOR UPDATE'
1714 if( $s === false ) {
1716 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1719 $ut = $dbw->strencode( $s->cur_user_text
);
1720 $uid = $s->cur_user
;
1723 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1724 if( $from != $s->cur_user_text
) {
1725 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1726 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1727 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1728 htmlspecialchars( $from ),
1729 htmlspecialchars( $s->cur_user_text
) ) );
1730 if($s->cur_comment
!= '') {
1732 wfMsg('editcomment',
1733 htmlspecialchars( $s->cur_comment
) ) );
1738 # Get the last edit not by this guy
1739 $s = $dbw->selectRow( 'old',
1740 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1742 'old_namespace' => $n,
1744 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1745 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1747 if( $s === false ) {
1749 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1750 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1755 # Mark all reverted edits as bot
1756 $dbw->update( 'recentchanges',
1759 ), array( /* WHERE */
1761 "rc_timestamp > '{$s->old_timestamp}'",
1767 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1768 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1769 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1770 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1771 $this->updateArticle( Revision
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1772 Article
::onArticleEdit( $this->mTitle
);
1773 $wgOut->returnToMain( false );
1778 * Do standard deferred updates after page view
1781 function viewUpdates() {
1782 global $wgDeferredUpdateList;
1784 if ( 0 != $this->getID() ) {
1785 global $wgDisableCounters;
1786 if( !$wgDisableCounters ) {
1787 Article
::incViewCount( $this->getID() );
1788 $u = new SiteStatsUpdate( 1, 0, 0 );
1789 array_push( $wgDeferredUpdateList, $u );
1793 # Update newtalk status if user is reading their own
1797 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1798 $this->mTitle
->getText() == $wgUser->getName()) {
1799 require_once( 'UserTalkUpdate.php' );
1800 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1805 * Do standard deferred updates after page edit.
1806 * Every 1000th edit, prune the recent changes table.
1808 * @param string $text
1810 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1811 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1812 global $wgMessageCache, $wgUser;
1815 if ( 0 == mt_rand( 0, 999 ) ) {
1816 $dbw =& wfGetDB( DB_MASTER
);
1817 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1818 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1819 $dbw->query( $sql );
1821 $id = $this->getID();
1822 $title = $this->mTitle
->getPrefixedDBkey();
1823 $shortTitle = $this->mTitle
->getDBkey();
1825 $adj = $this->mCountAdjustment
;
1828 $u = new LinksUpdate( $id, $title );
1829 array_push( $wgDeferredUpdateList, $u );
1830 $u = new SiteStatsUpdate( 0, 1, $adj );
1831 array_push( $wgDeferredUpdateList, $u );
1832 $u = new SearchUpdate( $id, $title, $text );
1833 array_push( $wgDeferredUpdateList, $u );
1835 # If this is another user's talk page,
1836 # create a watchlist entry for this page
1838 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1839 $shortTitle != $wgUser->getName()) {
1840 require_once( 'UserTalkUpdate.php' );
1841 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1844 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1845 $wgMessageCache->replace( $shortTitle, $text );
1851 * @todo document this function
1853 * @param string $oldid Revision ID of this article revision
1855 function setOldSubtitle( $oldid=0 ) {
1856 global $wgLang, $wgOut, $wgUser;
1858 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1859 $sk = $wgUser->getSkin();
1860 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1861 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1862 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1863 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1864 $wgOut->setSubtitle( $r );
1868 * This function is called right before saving the wikitext,
1869 * so we can do things like signatures and links-in-context.
1871 * @param string $text
1873 function preSaveTransform( $text ) {
1874 global $wgParser, $wgUser;
1875 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1878 /* Caching functions */
1881 * checkLastModified returns true if it has taken care of all
1882 * output to the client that is necessary for this request.
1883 * (that is, it has sent a cached version of the page)
1885 function tryFileCache() {
1886 static $called = false;
1888 wfDebug( " tryFileCache() -- called twice!?\n" );
1892 if($this->isFileCacheable()) {
1893 $touched = $this->mTouched
;
1894 $cache = new CacheManager( $this->mTitle
);
1895 if($cache->isFileCacheGood( $touched )) {
1897 wfDebug( " tryFileCache() - about to load\n" );
1898 $cache->loadFromFileCache();
1901 wfDebug( " tryFileCache() - starting buffer\n" );
1902 ob_start( array(&$cache, 'saveToFileCache' ) );
1905 wfDebug( " tryFileCache() - not cacheable\n" );
1910 * Check if the page can be cached
1913 function isFileCacheable() {
1914 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1915 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1917 return $wgUseFileCache
1918 and (!$wgShowIPinHeader)
1919 and ($this->getID() != 0)
1920 and ($wgUser->getId() == 0)
1921 and (!$wgUser->getNewtalk())
1922 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1923 and (empty( $action ) ||
$action == 'view')
1924 and (!isset($oldid))
1926 and (!isset($redirect))
1927 and (!isset($printable))
1928 and (!$this->mRedirectedFrom
);
1932 * Loads cur_touched and returns a value indicating if it should be used
1935 function checkTouched() {
1936 $fname = 'Article::checkTouched';
1937 $id = $this->getID();
1938 $dbr =& $this->getDB();
1939 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1940 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1941 if( $s !== false ) {
1942 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
1943 return !$s->page_is_redirect
;
1950 * Edit an article without doing all that other stuff
1952 * @param string $text text submitted
1953 * @param string $comment comment submitted
1954 * @param integer $minor whereas it's a minor modification
1956 function quickEdit( $text, $comment = '', $minor = 0 ) {
1958 $fname = 'Article::quickEdit';
1960 #wfDebugDieBacktrace( "$fname called." );
1962 wfProfileIn( $fname );
1964 $dbw =& wfGetDB( DB_MASTER
);
1965 $ns = $this->mTitle
->getNamespace();
1966 $dbkey = $this->mTitle
->getDBkey();
1967 $encDbKey = $dbw->strencode( $dbkey );
1968 $timestamp = wfTimestampNow();
1970 $dbw->insert( 'text', array(
1971 'old_text' => $text,
1972 'old_flags' => "" ), $fname );
1973 $text_id = $dbw->insertID();
1976 $dbw->update( 'page', array(
1978 'page_touched' => $timestamp,
1979 'page_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
1980 'page_latest' => $text_id ),
1981 array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1983 $page_id = $dbw->selectField( 'page', 'page_id', array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1986 $dbw->insert( 'revision', array(
1987 'rev_id' => $text_id,
1988 'rev_page' => $page_id,
1989 'rev_comment' => $comment,
1990 'rev_user' => $wgUser->getID(),
1991 'rev_user_text' => $wgUser->getName(),
1992 'rev_timestamp' => $timestamp,
1993 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1994 'rev_minor_edit' => intval($minor) ),
1998 $dbw->insertSelect( 'old', 'cur',
2000 'old_namespace' => 'cur_namespace',
2001 'old_title' => 'cur_title',
2002 'old_text' => 'cur_text',
2003 'old_comment' => 'cur_comment',
2004 'old_user' => 'cur_user',
2005 'old_user_text' => 'cur_user_text',
2006 'old_timestamp' => 'cur_timestamp',
2007 'inverse_timestamp' => '99999999999999-cur_timestamp',
2009 'cur_namespace' => $ns,
2010 'cur_title' => $dbkey,
2014 # Use the affected row count to determine if the article is new
2015 $numRows = $dbw->affectedRows();
2017 # Make an array of fields to be inserted
2019 'cur_text' => $text,
2020 'cur_timestamp' => $timestamp,
2021 'cur_user' => $wgUser->getID(),
2022 'cur_user_text' => $wgUser->getName(),
2023 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2024 'cur_comment' => $comment,
2025 'cur_is_redirect' => $this->isRedirect( $text ) ? 1 : 0,
2026 'cur_minor_edit' => intval($minor),
2027 'cur_touched' => $dbw->timestamp($timestamp),
2032 $fields['cur_is_new'] = 0;
2033 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2035 # Insert new article
2036 $fields['cur_is_new'] = 1;
2037 $fields['cur_namespace'] = $ns;
2038 $fields['cur_title'] = $dbkey;
2039 $fields['cur_random'] = $rand = wfRandom();
2040 $dbw->insert( 'cur', $fields, $fname );
2043 wfProfileOut( $fname );
2047 * Used to increment the view counter
2050 * @param integer $id article id
2052 function incViewCount( $id ) {
2053 $id = intval( $id );
2054 global $wgHitcounterUpdateFreq;
2056 $dbw =& wfGetDB( DB_MASTER
);
2057 $pageTable = $dbw->tableName( 'page' );
2058 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2059 $acchitsTable = $dbw->tableName( 'acchits' );
2061 if( $wgHitcounterUpdateFreq <= 1 ){ //
2062 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2066 # Not important enough to warrant an error page in case of failure
2067 $oldignore = $dbw->ignoreErrors( true );
2069 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2071 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2072 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2073 # Most of the time (or on SQL errors), skip row count check
2074 $dbw->ignoreErrors( $oldignore );
2078 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2079 $row = $dbw->fetchObject( $res );
2080 $rown = intval( $row->n
);
2081 if( $rown >= $wgHitcounterUpdateFreq ){
2082 wfProfileIn( 'Article::incViewCount-collect' );
2083 $old_user_abort = ignore_user_abort( true );
2085 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2086 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2087 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2089 $dbw->query("DELETE FROM $hitcounterTable");
2090 $dbw->query('UNLOCK TABLES');
2091 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2092 'WHERE cur_id = hc_id');
2093 $dbw->query("DROP TABLE $acchitsTable");
2095 ignore_user_abort( $old_user_abort );
2096 wfProfileOut( 'Article::incViewCount-collect' );
2098 $dbw->ignoreErrors( $oldignore );
2102 * The onArticle*() functions are supposed to be a kind of hooks
2103 * which should be called whenever any of the specified actions
2106 * This is a good place to put code to clear caches, for instance.
2108 * This is called on page move and undelete, as well as edit
2110 * @param $title_obj a title object
2113 function onArticleCreate($title_obj) {
2114 global $wgUseSquid, $wgDeferredUpdateList;
2116 $titles = $title_obj->getBrokenLinksTo();
2119 if ( $wgUseSquid ) {
2120 $urls = $title_obj->getSquidURLs();
2121 foreach ( $titles as $linkTitle ) {
2122 $urls[] = $linkTitle->getInternalURL();
2124 $u = new SquidUpdate( $urls );
2125 array_push( $wgDeferredUpdateList, $u );
2128 # Clear persistent link cache
2129 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2132 function onArticleDelete($title_obj) {
2133 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2135 function onArticleEdit($title_obj) {
2136 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2141 * Info about this page
2144 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2145 $fname = 'Article::info';
2147 if ( !$wgAllowPageInfo ) {
2148 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2152 $dbr =& $this->getDB();
2154 $basenamespace = $wgTitle->getNamespace() & (~
1);
2155 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2156 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2157 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2158 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2159 $wgOut->setPagetitle( $fullTitle );
2160 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2162 # first, see if the page exists at all.
2163 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2165 $wgOut->addHTML( wfMsg('noarticletext') );
2167 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2168 $this->getSelectOptions() );
2169 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2170 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2171 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2173 # to find number of distinct authors, we need to do some
2174 # funny stuff because of the cur/old table split:
2175 # - first, find the name of the 'cur' author
2176 # - then, find the number of *other* authors in 'old'
2179 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2180 $this->getSelectOptions() );
2182 # find number of 'old' authors excluding 'cur' author
2183 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2184 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2185 $this->getSelectOptions() ) +
1;
2187 # now for the Talk page ...
2188 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2189 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2192 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2196 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2197 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2199 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2203 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2204 $this->getSelectOptions() );
2205 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2206 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2207 $fname, $this->getSelectOptions() );
2209 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );
2216 * Check whether an article is a stub
2219 * @param integer $articleID ID of the article that is to be checked
2221 function wfArticleIsStub( $articleID ) {
2223 $fname = 'wfArticleIsStub';
2225 $threshold = $wgUser->getOption('stubthreshold') ;
2226 if ( $threshold > 0 ) {
2227 $dbr =& wfGetDB( DB_SLAVE
);
2228 $s = $dbr->selectRow( array('page', 'text'),
2229 array( 'LENGTH(old_text) AS len', 'page_namespace', 'page_is_redirect' ),
2230 array( 'page_id' => $articleID, "page.page_latest=text.old_id" ),
2232 if ( $s == false OR $s->page_is_redirect
OR $s->page_namespace
!= 0 ) {
2236 return ( $size < $threshold );