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;
53 $this->mContentLoaded
= false;
54 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
55 $this->mRedirectedFrom
= $this->mUserText
=
56 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
57 $this->mCountAdjustment
= 0;
58 $this->mTouched
= '19700101000000';
59 $this->mForUpdate
= false;
63 * Note that getContent/loadContent may follow redirects if
64 * not told otherwise, and so may cause a change to mTitle.
67 * @return Return the text of this revision
69 function getContent( $noredir ) {
72 # Get variables from query string :P
73 $action = $wgRequest->getText( 'action', 'view' );
74 $section = $wgRequest->getText( 'section' );
76 $fname = 'Article::getContent';
77 wfProfileIn( $fname );
79 if ( 0 == $this->getID() ) {
80 if ( 'edit' == $action ) {
81 wfProfileOut( $fname );
82 return ''; # was "newarticletext", now moved above the box)
84 wfProfileOut( $fname );
85 return wfMsg( 'noarticletext' );
87 $this->loadContent( $noredir );
88 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
89 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
90 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
93 wfProfileOut( $fname );
94 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
99 wfProfileOut( $fname );
103 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
104 # comments to be stripped as well)
105 $rv=$this->getSection($this->mContent
,$section);
106 wfProfileOut( $fname );
110 wfProfileOut( $fname );
111 return $this->mContent
;
117 * This function returns the text of a section, specified by a number ($section).
118 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
119 * the first section before any such heading (section 0).
121 * If a section contains subsections, these are also returned.
123 * @param string $text text to look in
124 * @param integer $section section number
125 * @return string text of the requested section
127 function getSection($text,$section) {
129 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
130 # comments to be stripped as well)
132 $parser=new Parser();
133 $parser->mOutputType
=OT_WIKI
;
134 $striptext=$parser->strip($text, $striparray, true);
136 # now that we can be sure that no pseudo-sections are in the source,
137 # split it up by section
140 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
142 PREG_SPLIT_DELIM_CAPTURE
);
146 $headline=$secs[$section*2-1];
147 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
150 # translate wiki heading into level
151 if(strpos($hlevel,'=')!==false) {
152 $hlevel=strlen($hlevel);
155 $rv=$headline. $secs[$section*2];
159 while(!empty($secs[$count*2-1]) && !$break) {
161 $subheadline=$secs[$count*2-1];
162 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
163 $subhlevel=$matches[1];
164 if(strpos($subhlevel,'=')!==false) {
165 $subhlevel=strlen($subhlevel);
167 if($subhlevel > $hlevel) {
168 $rv.=$subheadline.$secs[$count*2];
170 if($subhlevel <= $hlevel) {
177 # reinsert stripped tags
178 $rv=$parser->unstrip($rv,$striparray);
179 $rv=$parser->unstripNoWiki($rv,$striparray);
186 * Return an array of the columns of the "cur"-table
188 function getContentFields() {
189 return $wgArticleContentFields = array(
190 'old_text','old_flags',
191 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
192 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
196 * Return the oldid of the article that is to be shown.
197 * For requests with a "direction", this is not the oldid of the
200 function getOldID() {
201 global $wgRequest, $wgOut;
204 if ( isset( $lastid ) ) {
208 $oldid = $wgRequest->getVal( 'oldid' );
209 if ( isset( $oldid ) ) {
210 $dbr =& $this->getDB();
211 $oldid = IntVal( $oldid );
212 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
213 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
217 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
219 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
220 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
229 return @$oldid; # "@" to be able to return "unset" without PHP complaining
234 * Load the revision (including cur_text) into this object
236 function loadContent( $noredir = false ) {
237 global $wgOut, $wgRequest;
239 if ( $this->mContentLoaded
) return;
241 $dbr =& $this->getDB();
243 $oldid = $this->getOldID();
244 $redirect = $wgRequest->getVal( 'redirect' );
246 $fname = 'Article::loadContent';
248 # Pre-fill content with error message so that if something
249 # fails we'll have something telling us what we intended.
251 $t = $this->mTitle
->getPrefixedText();
253 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no');
254 $this->mOldId
= $oldid;
255 $this->fetchContent( $oldid, $noredir, true );
259 * @param int $oldid 0 for whatever the latest revision is
260 * @param bool $noredir Set to true to avoid following redirects
261 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
264 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
265 if ( $this->mContentLoaded
) {
266 return $this->mContent
;
268 $dbr =& $this->getDB();
269 $fname = 'Article::fetchContent';
271 # Pre-fill content with error message so that if something
272 # fails we'll have something telling us what we intended.
273 $t = $this->mTitle
->getPrefixedText();
275 $t .= ',oldid='.$oldid;
277 if( isset( $redirect ) ) {
278 $redirect = ($redirect == 'no') ?
'no' : 'yes';
279 $t .= ',redirect='.$redirect;
281 $this->mContent
= wfMsg( 'missingarticle', $t );
284 # Retrieve current version
285 $id = $this->getID();
290 $s = $dbr->selectRow( array( 'text', 'revision', 'page' ),
291 $this->getContentFields(),
292 "page_id='$id' AND rev_page=page_id AND rev_id=page_latest AND old_id=rev_id",
293 $fname, $this->getSelectOptions() );
295 # Historical revision
296 $s = $dbr->selectRow( array( 'text', 'revision', 'page' ),
297 $this->getContentFields(),
298 "rev_page=page_id AND rev_id='$oldid' AND old_id=rev_id",
299 $fname, $this->getSelectOptions() );
301 if ( $s === false ) {
305 # If we got a redirect, follow it (unless we've been told
306 # not to by either the function parameter or the query
307 if ( !$oldid && !$noredir ) {
308 $rt = Title
::newFromRedirect( Revision
::getRevisionText( $s ) );
309 # process if title object is valid and not special:userlogout
310 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
311 # Gotta hand redirects to special pages differently:
312 # Fill the HTTP response "Location" header and ignore
313 # the rest of the page we're on.
316 if ( $rt->getInterwiki() != '' ) {
317 $wgOut->redirect( $rt->getFullURL() ) ;
320 if ( $rt->getNamespace() == NS_SPECIAL
) {
321 $wgOut->redirect( $rt->getFullURL() );
325 $rid = $rt->getArticleID();
327 $redirRow = $dbr->selectRow( array( 'text', 'revision', 'page' ),
328 $this->getContentFields(),
329 "page_id='$rid' AND rev_page=page_id AND rev_id=page_latest AND old_id=rev_id",
330 $fname, $this->getSelectOptions() );
332 if ( $redirRow !== false ) {
333 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
341 # if the title's different from expected, update...
343 ( $this->mTitle
->getNamespace() != $s->page_namespace ||
344 $this->mTitle
->getDBkey() != $s->page_title
) ) {
345 $oldTitle = Title
::makeTitle( $s->page_namesapce
, $s->page_title
);
346 $this->mTitle
= $oldTitle;
348 $wgTitle = $oldTitle;
351 # Back to the business at hand...
352 $this->mCounter
= $s->page_counter
;
353 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->page_restrictions
) );
354 $this->mTitle
->mRestrictionsLoaded
= true;
355 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
357 $this->mContent
= Revision
::getRevisionText( $s );
359 $this->mUser
= $s->rev_user
;
360 $this->mUserText
= $s->rev_user_text
;
361 $this->mComment
= $s->rev_comment
;
362 $this->mTimestamp
= wfTimestamp( TS_MW
, $s->rev_timestamp
);
364 $this->mContentLoaded
= true;
365 return $this->mContent
;
369 * Gets the article text without using so many damn globals
370 * Returns false on error
372 * @param integer $oldid
374 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
375 return $this->fetchContent( $oldid, $noredir, false );
379 * Read/write accessor to select FOR UPDATE
381 function forUpdate( $x = NULL ) {
382 return wfSetVar( $this->mForUpdate
, $x );
386 * Get the database which should be used for reads
389 if ( $this->mForUpdate
) {
390 return wfGetDB( DB_MASTER
);
392 return wfGetDB( DB_SLAVE
);
397 * Get options for all SELECT statements
398 * Can pass an option array, to which the class-wide options will be appended
400 function getSelectOptions( $options = '' ) {
401 if ( $this->mForUpdate
) {
403 $options[] = 'FOR UPDATE';
405 $options = 'FOR UPDATE';
412 * Return the Article ID
415 if( $this->mTitle
) {
416 return $this->mTitle
->getArticleID();
423 * Get the view count for this article
425 function getCount() {
426 if ( -1 == $this->mCounter
) {
427 $id = $this->getID();
428 $dbr =& $this->getDB();
429 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
430 'Article::getCount', $this->getSelectOptions() );
432 return $this->mCounter
;
436 * Would the given text make this article a "good" article (i.e.,
437 * suitable for including in the article count)?
439 function isCountable( $text ) {
440 global $wgUseCommaCount;
442 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
443 if ( $this->isRedirect( $text ) ) { return 0; }
444 $token = ($wgUseCommaCount ?
',' : '[[' );
445 if ( false === strstr( $text, $token ) ) { return 0; }
450 * Tests if the article text represents a redirect
452 function isRedirect( $text = false ) {
453 if ( $text === false ) {
454 $this->loadContent();
455 $titleObj = Title
::newFromRedirect( $this->mText
);
457 $titleObj = Title
::newFromRedirect( $text );
459 return $titleObj !== NULL;
463 * Loads everything except the text
464 * This isn't necessary for all uses, so it's only done if needed.
467 function loadLastEdit() {
470 if ( -1 != $this->mUser
)
473 $fname = 'Article::loadLastEdit';
475 $dbr =& $this->getDB();
476 $s = $dbr->selectRow( array( 'revision', 'page') ,
477 array( 'rev_user','rev_user_text','rev_timestamp', 'rev_comment','rev_minor_edit' ),
478 array( 'page_id' => $this->getID(), 'page_latest=rev_id' ), $fname, $this->getSelectOptions() );
480 if ( $s !== false ) {
481 $this->mUser
= $s->rev_user
;
482 $this->mUserText
= $s->rev_user_text
;
483 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->rev_timestamp
);
484 $this->mComment
= $s->rev_comment
;
485 $this->mMinorEdit
= $s->rev_minor_edit
;
489 function getTimestamp() {
490 $this->loadLastEdit();
491 return $this->mTimestamp
;
495 $this->loadLastEdit();
499 function getUserText() {
500 $this->loadLastEdit();
501 return $this->mUserText
;
504 function getComment() {
505 $this->loadLastEdit();
506 return $this->mComment
;
509 function getMinorEdit() {
510 $this->loadLastEdit();
511 return $this->mMinorEdit
;
514 function getContributors($limit = 0, $offset = 0) {
515 $fname = 'Article::getContributors';
517 # XXX: this is expensive; cache this info somewhere.
519 $title = $this->mTitle
;
521 $dbr =& $this->getDB();
522 $revTable = $dbr->tableName( 'revision' );
523 $userTable = $dbr->tableName( 'user' );
524 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
525 $ns = $title->getNamespace();
526 $user = $this->getUser();
528 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
529 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
530 WHERE rev_page = $pageId
531 AND old_user != $user
532 GROUP BY rev_user, rev_user_text, user_real_name
533 ORDER BY timestamp DESC";
535 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
536 $sql .= ' '. $this->getSelectOptions();
538 $res = $dbr->query($sql, $fname);
540 while ( $line = $dbr->fetchObject( $res ) ) {
541 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
544 $dbr->freeResult($res);
549 * This is the default action of the script: just view the page of
553 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
554 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
556 $sk = $wgUser->getSkin();
558 $fname = 'Article::view';
559 wfProfileIn( $fname );
560 # Get variables from query string
561 $oldid = $this->getOldID();
562 $diff = $wgRequest->getVal( 'diff' );
563 $rcid = $wgRequest->getVal( 'rcid' );
565 $wgOut->setArticleFlag( true );
566 $wgOut->setRobotpolicy( 'index,follow' );
567 # If we got diff and oldid in the query, we want to see a
568 # diff page instead of the article.
570 if ( !is_null( $diff ) ) {
571 require_once( 'DifferenceEngine.php' );
572 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
573 $de = new DifferenceEngine( $oldid, $diff, $rcid );
576 # Run view updates for current revision only
577 $this->viewUpdates();
579 wfProfileOut( $fname );
582 if ( empty( $oldid ) && $this->checkTouched() ) {
583 if( $wgOut->checkLastModified( $this->mTouched
) ){
584 wfProfileOut( $fname );
586 } else if ( $this->tryFileCache() ) {
587 # tell wgOut that output is taken care of
589 $this->viewUpdates();
590 wfProfileOut( $fname );
594 # Should the parser cache be used?
595 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
603 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
607 if ( !$outputDone ) {
608 $text = $this->getContent( false ); # May change mTitle by following a redirect
610 # Another whitelist check in case oldid or redirects are altering the title
611 if ( !$this->mTitle
->userCanRead() ) {
612 $wgOut->loginToUse();
618 # We're looking at an old revision
620 if ( !empty( $oldid ) ) {
621 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
622 $wgOut->setRobotpolicy( 'noindex,follow' );
624 if ( '' != $this->mRedirectedFrom
) {
625 $sk = $wgUser->getSkin();
626 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
628 $s = wfMsg( 'redirectedfrom', $redir );
629 $wgOut->setSubtitle( $s );
631 # Can't cache redirects
635 # wrap user css and user js in pre and don't parse
636 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
638 $this->mTitle
->getNamespace() == NS_USER
&&
639 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
641 $wgOut->addWikiText( wfMsg('clearyourcache'));
642 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
643 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
645 $imageUrl = $wgStylePath.'/common/images/redirect.png';
646 $targetUrl = $rt->escapeLocalURL();
647 $titleText = htmlspecialchars( $rt->getPrefixedText() );
648 $link = $sk->makeLinkObj( $rt );
650 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
651 '<span class="redirectText">'.$link.'</span>' );
653 } else if ( $pcache ) {
654 # Display content and save to parser cache
655 $wgOut->addPrimaryWikiText( $text, $this );
657 # Display content, don't attempt to save to parser cache
658 $wgOut->addWikiText( $text );
661 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
662 # If we have been passed an &rcid= parameter, we want to give the user a
663 # chance to mark this new article as patrolled.
664 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
665 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
667 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
668 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
669 'action=markpatrolled&rcid='.$rcid )
673 # Put link titles into the link cache
674 $wgOut->transformBuffer();
676 # Add link titles as META keywords
677 $wgOut->addMetaTags() ;
679 $this->viewUpdates();
680 wfProfileOut( $fname );
682 $wgUser->clearNotification( $this->mTitle
);
686 * Theoretically we could defer these whole insert and update
687 * functions for after display, but that's taking a big leap
688 * of faith, and we want to be able to report database
689 * errors at some point.
692 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
693 global $wgOut, $wgUser;
694 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
696 $fname = 'Article::insertNewArticle';
698 $this->mCountAdjustment
= $this->isCountable( $text );
700 $ns = $this->mTitle
->getNamespace();
701 $ttl = $this->mTitle
->getDBkey();
702 $text = $this->preSaveTransform( $text );
703 if ( $this->isRedirect( $text ) ) { $redir = 1; }
706 $now = wfTimestampNow();
707 $won = wfInvertTimestamp( $now );
710 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
713 $flags = Revision
::compressRevisionText( $mungedText );
715 $dbw =& wfGetDB( DB_MASTER
);
717 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
718 $dbw->insert( 'text', array(
720 'old_text' => $mungedText,
721 'old_flags' => $flags,
723 $revisionId = $dbw->insertId();
725 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
726 $dbw->insert( 'page', array(
727 'page_id' => $page_id,
728 'page_namespace' => $ns,
729 'page_title' => $ttl,
731 'page_restrictions' => '',
732 'page_is_redirect' => $redir,
734 'page_random' => $rand,
735 'page_touched' => $dbw->timestamp($now),
736 'page_latest' => $revisionId,
738 $newid = $dbw->insertId();
740 $dbw->insert( 'revision', array(
741 'rev_page' => $newid,
742 'rev_id' => $revisionId,
743 'rev_comment' => $summary,
744 'rev_user' => $wgUser->getID(),
745 'rev_timestamp' => $dbw->timestamp($now),
746 'rev_minor_edit' => $isminor,
747 'rev_user_text' => $wgUser->getName(),
748 'inverse_timestamp' => $won,
751 $this->mTitle
->resetArticleID( $newid );
753 Article
::onArticleCreate( $this->mTitle
);
754 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
757 if(!$this->mTitle
->userIsWatching()) $this->watch();
759 if ( $this->mTitle
->userIsWatching() ) {
764 # The talk page isn't in the regular link tables, so we need to update manually:
765 $talkns = $ns ^
1; # talk -> normal; normal -> talk
766 $dbw->update( 'page',
767 array( 'page_touched' => $dbw->timestamp($now) ),
768 array( 'page_namespace' => $talkns,
769 'page_title' => $ttl ),
772 # standard deferred updates
773 $this->editUpdates( $text, $summary, $isminor, $now );
775 $oldid = 0; # new article
776 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
780 * Fetch and uncompress the text for a given revision.
781 * Can ask by rev_id number or timestamp (set $field)
783 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
784 $fname = 'Article::fetchRevisionText';
785 $dbw =& wfGetDB( DB_MASTER
);
787 $rev = $dbw->addQuotes( $revId );
789 $rev = 'page_latest';
791 $result = $dbw->query(
792 sprintf( "SELECT old_text, old_flags
794 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
796 $dbw->tableName( 'page' ),
797 $dbw->tableName( 'revision' ),
798 $dbw->tableName( 'text' ),
799 IntVal( $this->mTitle
->getArticleId() ),
803 $obj = $dbw->fetchObject( $result );
804 $dbw->freeResult( $result );
805 $oldtext = Revision
::getRevisionText( $obj );
809 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
810 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
811 if( is_null( $edittime ) ) {
812 $oldtext = $this->fetchRevisionText();
814 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
816 if ($section != '') {
817 if($section=='new') {
818 if($summary) $subject="== {$summary} ==\n\n";
819 $text=$oldtext."\n\n".$subject.$text;
822 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
823 # comments to be stripped as well)
825 $parser=new Parser();
826 $parser->mOutputType
=OT_WIKI
;
827 $oldtext=$parser->strip($oldtext, $striparray, true);
829 # now that we can be sure that no pseudo-sections are in the source,
831 # Unfortunately we can't simply do a preg_replace because that might
832 # replace the wrong section, so we have to use the section counter instead
833 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
834 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
835 $secs[$section*2]=$text."\n\n"; // replace with edited
837 # section 0 is top (intro) section
840 # headline of old section - we need to go through this section
841 # to determine if there are any subsections that now need to
842 # be erased, as the mother section has been replaced with
843 # the text of all subsections.
844 $headline=$secs[$section*2-1];
845 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
848 # determine headline level for wikimarkup headings
849 if(strpos($hlevel,'=')!==false) {
850 $hlevel=strlen($hlevel);
853 $secs[$section*2-1]=''; // erase old headline
856 while(!empty($secs[$count*2-1]) && !$break) {
858 $subheadline=$secs[$count*2-1];
860 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
861 $subhlevel=$matches[1];
862 if(strpos($subhlevel,'=')!==false) {
863 $subhlevel=strlen($subhlevel);
865 if($subhlevel > $hlevel) {
866 // erase old subsections
867 $secs[$count*2-1]='';
870 if($subhlevel <= $hlevel) {
878 $text=join('',$secs);
879 # reinsert the stuff that we stripped out earlier
880 $text=$parser->unstrip($text,$striparray);
881 $text=$parser->unstripNoWiki($text,$striparray);
889 * Change an existing article. Puts the previous version back into the old table, updates RC
890 * and all necessary caches, mostly via the deferred update array.
892 * It is possible to call this function from a command-line script, but note that you should
893 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
895 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
896 global $wgOut, $wgUser;
897 global $wgDBtransactions, $wgMwRedir;
898 global $wgUseSquid, $wgInternalServer;
900 $fname = 'Article::updateArticle';
903 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
904 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
905 if ( $this->isRedirect( $text ) ) {
906 # Remove all content but redirect
907 # This could be done by reconstructing the redirect from a title given by
908 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
910 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
912 $text = $m[1] . "\n";
917 $text = $this->preSaveTransform( $text );
918 $dbw =& wfGetDB( DB_MASTER
);
920 # Update article, but only if changed.
922 # It's important that we either rollback or complete, otherwise an attacker could
923 # overwrite cur entries by sending precisely timed user aborts. Random bored users
924 # could conceivably have the same effect, especially if cur is locked for long periods.
925 if( $wgDBtransactions ) {
926 $dbw->query( 'BEGIN', $fname );
928 $userAbort = ignore_user_abort( true );
931 $oldtext = $this->getContent( true );
933 if ( 0 != strcmp( $text, $oldtext ) ) {
934 $this->mCountAdjustment
= $this->isCountable( $text )
935 - $this->isCountable( $oldtext );
936 $now = wfTimestampNow();
937 $won = wfInvertTimestamp( $now );
940 $flags = Revision
::compressRevisionText( $newtext );
942 $lastRevision = $dbw->selectField(
943 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
945 # Record the text to the text table
946 $old_id = $dbw->nextSequenceValue( 'text_old_id_val' );
947 $dbw->insert( 'text',
950 'old_text' => $mungedText,
951 'old_flags' => $flags,
954 $revisionId = $dbw->insertId();
956 # Record the edit in revisions
957 $dbw->insert( 'revision',
959 'rev_id' => $revisionId,
960 'rev_page' => $this->getID(),
961 'rev_comment' => $summary,
962 'rev_minor_edit' => $me2,
963 'rev_user' => $wgUser->getID(),
964 'rev_user_text' => $wgUser->getName(),
965 'rev_timestamp' => $dbw->timestamp( $now ),
966 'inverse_timestamp' => $won
971 $dbw->update( 'page',
973 'page_latest' => $revisionId,
974 'page_touched' => $dbw->timestamp( $now ),
976 'page_is_redirect' => $redir,
977 ), array( /* WHERE */
978 'page_id' => $this->getID(),
979 'page_latest' => $lastRevision, # Paranoia
983 if( $dbw->affectedRows() == 0 ) {
984 /* Belated edit conflict! Run away!! */
987 # Update recentchanges and purge cache and whatnot
988 $bot = (int)($wgUser->isBot() ||
$forceBot);
989 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
990 $lastRevision, $this->getTimestamp(), $bot );
991 Article
::onArticleEdit( $this->mTitle
);
995 if( $wgDBtransactions ) {
996 $dbw->query( 'COMMIT', $fname );
998 ignore_user_abort( $userAbort );
1003 if (!$this->mTitle
->userIsWatching()) $this->watch();
1005 if ( $this->mTitle
->userIsWatching() ) {
1009 # standard deferred updates
1010 $this->editUpdates( $text, $summary, $minor, $now );
1014 # Template namespace
1015 # Purge all articles linking here
1016 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1017 $titles = $this->mTitle
->getLinksTo();
1018 Title
::touchArray( $titles );
1019 if ( $wgUseSquid ) {
1020 foreach ( $titles as $title ) {
1021 $urls[] = $title->getInternalURL();
1027 if ( $wgUseSquid ) {
1028 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1029 $u = new SquidUpdate( $urls );
1033 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $revisionId );
1039 * After we've either updated or inserted the article, update
1040 * the link tables and redirect to the new page.
1042 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1043 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1045 $wgLinkCache = new LinkCache();
1047 $wgLinkCache->forUpdate( true );
1049 # Get old version of link table to allow incremental link updates
1050 $wgLinkCache->preFill( $this->mTitle
);
1051 $wgLinkCache->clear();
1053 # Parse the text and replace links with placeholders
1054 $wgOut = new OutputPage();
1055 $wgOut->addWikiText( $text );
1057 # Look up the links in the DB and add them to the link cache
1058 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1060 if( $this->isRedirect( $text ) )
1064 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1066 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1067 # this will be improved later (to-do)
1069 include_once( "UserMailer.php" );
1070 $wgEnotif = new EmailNotification ();
1071 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1076 * @todo document this function a bit more
1078 function validate () {
1079 global $wgOut, $wgUseValidation;
1080 if( $wgUseValidation ) {
1081 require_once ( 'SpecialValidate.php' ) ;
1082 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1083 $wgOut->setRobotpolicy( 'noindex,follow' );
1084 if( $this->mTitle
->getNamespace() != 0 ) {
1085 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1088 $v = new Validation
;
1089 $v->validate_form( $this->mTitle
->getDBkey() );
1091 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1096 * Mark this particular edit as patrolled
1098 function markpatrolled() {
1099 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1100 $wgOut->setRobotpolicy( 'noindex,follow' );
1102 if ( !$wgUseRCPatrol )
1104 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1107 if ( $wgUser->getID() == 0 )
1109 $wgOut->loginToUse();
1112 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1114 $wgOut->sysopRequired();
1117 $rcid = $wgRequest->getVal( 'rcid' );
1118 if ( !is_null ( $rcid ) )
1120 RecentChange
::markPatrolled( $rcid );
1121 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1122 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1124 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1125 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1129 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1135 * Add this page to $wgUser's watchlist
1140 global $wgUser, $wgOut;
1142 if ( 0 == $wgUser->getID() ) {
1143 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1146 if ( wfReadOnly() ) {
1147 $wgOut->readOnlyPage();
1151 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1153 $wgUser->addWatch( $this->mTitle
);
1154 $wgUser->saveSettings();
1156 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1158 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1159 $wgOut->setRobotpolicy( 'noindex,follow' );
1161 $link = $this->mTitle
->getPrefixedText();
1162 $text = wfMsg( 'addedwatchtext', $link );
1163 $wgOut->addWikiText( $text );
1166 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1170 * Stop watching a page
1173 function unwatch() {
1175 global $wgUser, $wgOut;
1177 if ( 0 == $wgUser->getID() ) {
1178 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1181 if ( wfReadOnly() ) {
1182 $wgOut->readOnlyPage();
1186 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1188 $wgUser->removeWatch( $this->mTitle
);
1189 $wgUser->saveSettings();
1191 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1193 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1194 $wgOut->setRobotpolicy( 'noindex,follow' );
1196 $link = $this->mTitle
->getPrefixedText();
1197 $text = wfMsg( 'removedwatchtext', $link );
1198 $wgOut->addWikiText( $text );
1201 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1207 function protect( $limit = 'sysop' ) {
1208 global $wgUser, $wgOut, $wgRequest;
1210 if ( ! $wgUser->isAllowed('protect') ) {
1211 $wgOut->sysopRequired();
1214 if ( wfReadOnly() ) {
1215 $wgOut->readOnlyPage();
1218 $id = $this->mTitle
->getArticleID();
1220 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1224 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1225 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1226 $reason = $wgRequest->getText( 'wpReasonProtect' );
1229 $dbw =& wfGetDB( DB_MASTER
);
1230 $dbw->update( 'page',
1232 'page_touched' => $dbw->timestamp(),
1233 'page_restrictions' => (string)$limit
1234 ), array( /* WHERE */
1236 ), 'Article::protect'
1239 $restrictions = "move=" . $limit;
1241 $restrictions .= ":edit=" . $limit;
1243 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1245 $dbw =& wfGetDB( DB_MASTER
);
1246 $dbw->update( 'cur',
1248 'cur_touched' => $dbw->timestamp(),
1249 'cur_restrictions' => $restrictions
1250 ), array( /* WHERE */
1252 ), 'Article::protect'
1255 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1257 $log = new LogPage( 'protect' );
1258 if ( $limit === '' ) {
1259 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1261 $log->addEntry( 'protect', $this->mTitle
, $reason );
1263 $wgOut->redirect( $this->mTitle
->getFullURL() );
1267 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1268 return $this->confirmProtect( '', $reason, $limit );
1273 * Output protection confirmation dialog
1275 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1278 wfDebug( "Article::confirmProtect\n" );
1280 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1281 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1287 if ( $limit === '' ) {
1288 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1289 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1290 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1291 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1292 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1293 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1295 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1296 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1297 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1298 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1299 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1300 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1301 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1304 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1307 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1311 <label for='wpReasonProtect'>{$protcom}:</label>
1314 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1322 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1325 <label for='wpConfirmProtect'>{$check}</label>
1328 if($moveonly != '') {
1332 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1335 <label for='wpMoveOnly'>{$moveonly}</label>
1343 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1349 $wgOut->returnToMain( false );
1353 * Unprotect the pages
1355 function unprotect() {
1356 return $this->protect( '' );
1360 * UI entry point for page deletion
1363 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1364 $fname = 'Article::delete';
1365 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1366 $reason = $wgRequest->getText( 'wpReason' );
1368 # This code desperately needs to be totally rewritten
1371 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1372 $wgOut->sysopRequired();
1375 if ( wfReadOnly() ) {
1376 $wgOut->readOnlyPage();
1380 # Better double-check that it hasn't been deleted yet!
1381 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1382 if ( ( '' == trim( $this->mTitle
->getText() ) )
1383 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1384 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1389 $this->doDelete( $reason );
1393 # determine whether this page has earlier revisions
1394 # and insert a warning if it does
1395 # we select the text because it might be useful below
1396 $dbr =& $this->getDB();
1397 $ns = $this->mTitle
->getNamespace();
1398 $title = $this->mTitle
->getDBkey();
1399 $old = $dbr->selectRow( 'old',
1400 array( 'old_text', 'old_flags' ),
1402 'old_namespace' => $ns,
1403 'old_title' => $title,
1404 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1407 if( $old !== false && !$confirm ) {
1408 $skin=$wgUser->getSkin();
1409 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1410 $wgOut->addHTML( $skin->historyLink() .'</b>');
1414 $s = $dbr->selectRow( 'cur',
1415 array( 'cur_text' ),
1417 'cur_namespace' => $ns,
1418 'cur_title' => $title,
1419 ), $fname, $this->getSelectOptions()
1422 if( $s !== false ) {
1423 # if this is a mini-text, we can paste part of it into the deletion reason
1425 #if this is empty, an earlier revision may contain "useful" text
1427 if($s->cur_text
!= '') {
1431 $text = Revision
::getRevisionText( $old );
1437 $length=strlen($text);
1439 # this should not happen, since it is not possible to store an empty, new
1440 # page. Let's insert a standard text in case it does, though
1441 if($length == 0 && $reason === '') {
1442 $reason = wfMsg('exblank');
1445 if($length < 500 && $reason === '') {
1447 # comment field=255, let's grep the first 150 to have some user
1449 $text=substr($text,0,150);
1450 # let's strip out newlines and HTML tags
1451 $text=preg_replace('/\"/',"'",$text);
1452 $text=preg_replace('/\</','<',$text);
1453 $text=preg_replace('/\>/','>',$text);
1454 $text=preg_replace("/[\n\r]/",'',$text);
1456 $reason=wfMsg('excontent'). " '".$text;
1458 $reason=wfMsg('exbeforeblank') . " '".$text;
1460 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1465 return $this->confirmDelete( '', $reason );
1469 * Output deletion confirmation dialog
1471 function confirmDelete( $par, $reason ) {
1474 wfDebug( "Article::confirmDelete\n" );
1476 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1477 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1478 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1479 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1481 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1483 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1484 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1485 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1488 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1492 <label for='wpReason'>{$delcom}:</label>
1495 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1503 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1506 <label for='wpConfirm'>{$check}</label>
1512 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1518 $wgOut->returnToMain( false );
1523 * Perform a deletion and output success or failure messages
1525 function doDelete( $reason ) {
1526 global $wgOut, $wgUser, $wgContLang;
1527 $fname = 'Article::doDelete';
1528 wfDebug( $fname."\n" );
1530 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1531 if ( $this->doDeleteArticle( $reason ) ) {
1532 $deleted = $this->mTitle
->getPrefixedText();
1534 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1535 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1537 $sk = $wgUser->getSkin();
1538 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1539 ':' . wfMsgForContent( 'dellogpage' ),
1540 wfMsg( 'deletionlog' ) );
1542 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1544 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1545 $wgOut->returnToMain( false );
1546 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1548 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1554 * Back-end article deletion
1555 * Deletes the article with database consistency, writes logs, purges caches
1558 function doDeleteArticle( $reason ) {
1560 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1562 $fname = 'Article::doDeleteArticle';
1563 wfDebug( $fname."\n" );
1565 $dbw =& wfGetDB( DB_MASTER
);
1566 $ns = $this->mTitle
->getNamespace();
1567 $t = $this->mTitle
->getDBkey();
1568 $id = $this->mTitle
->getArticleID();
1570 if ( $t == '' ||
$id == 0 ) {
1574 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1575 array_push( $wgDeferredUpdateList, $u );
1577 $linksTo = $this->mTitle
->getLinksTo();
1580 if ( $wgUseSquid ) {
1582 $this->mTitle
->getInternalURL(),
1583 $this->mTitle
->getInternalURL( 'history' )
1585 foreach ( $linksTo as $linkTo ) {
1586 $urls[] = $linkTo->getInternalURL();
1589 $u = new SquidUpdate( $urls );
1590 array_push( $wgDeferredUpdateList, $u );
1594 # Client and file cache invalidation
1595 Title
::touchArray( $linksTo );
1597 # Move article and history to the "archive" table
1598 $archiveTable = $dbw->tableName( 'archive' );
1599 $oldTable = $dbw->tableName( 'old' );
1600 $curTable = $dbw->tableName( 'cur' );
1601 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1602 $linksTable = $dbw->tableName( 'links' );
1603 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1605 $dbw->insertSelect( 'archive', 'cur',
1607 'ar_namespace' => 'cur_namespace',
1608 'ar_title' => 'cur_title',
1609 'ar_text' => 'cur_text',
1610 'ar_comment' => 'cur_comment',
1611 'ar_user' => 'cur_user',
1612 'ar_user_text' => 'cur_user_text',
1613 'ar_timestamp' => 'cur_timestamp',
1614 'ar_minor_edit' => 'cur_minor_edit',
1617 'cur_namespace' => $ns,
1622 $dbw->insertSelect( 'archive', 'old',
1624 'ar_namespace' => 'old_namespace',
1625 'ar_title' => 'old_title',
1626 'ar_text' => 'old_text',
1627 'ar_comment' => 'old_comment',
1628 'ar_user' => 'old_user',
1629 'ar_user_text' => 'old_user_text',
1630 'ar_timestamp' => 'old_timestamp',
1631 'ar_minor_edit' => 'old_minor_edit',
1632 'ar_flags' => 'old_flags'
1634 'old_namespace' => $ns,
1639 # Now that it's safely backed up, delete it
1641 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1642 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1643 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1645 # Finally, clean up the link tables
1646 $t = $this->mTitle
->getPrefixedDBkey();
1648 Article
::onArticleDelete( $this->mTitle
);
1650 # Insert broken links
1651 $brokenLinks = array();
1652 foreach ( $linksTo as $titleObj ) {
1653 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1654 $linkID = $titleObj->getArticleID();
1655 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1657 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1660 $dbw->delete( 'links', array( 'l_to' => $id ) );
1661 $dbw->delete( 'links', array( 'l_from' => $id ) );
1662 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1663 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1664 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1667 $log = new LogPage( 'delete' );
1668 $log->addEntry( 'delete', $this->mTitle
, $reason );
1670 # Clear the cached article id so the interface doesn't act like we exist
1671 $this->mTitle
->resetArticleID( 0 );
1672 $this->mTitle
->mArticleID
= 0;
1677 * Revert a modification
1679 function rollback() {
1680 global $wgUser, $wgOut, $wgRequest;
1681 $fname = 'Article::rollback';
1683 if ( ! $wgUser->isAllowed('rollback') ) {
1684 $wgOut->sysopRequired();
1687 if ( wfReadOnly() ) {
1688 $wgOut->readOnlyPage( $this->getContent( true ) );
1691 $dbw =& wfGetDB( DB_MASTER
);
1693 # Enhanced rollback, marks edits rc_bot=1
1694 $bot = $wgRequest->getBool( 'bot' );
1696 # Replace all this user's current edits with the next one down
1697 $tt = $this->mTitle
->getDBKey();
1698 $n = $this->mTitle
->getNamespace();
1700 # Get the last editor, lock table exclusively
1701 $s = $dbw->selectRow( 'cur',
1702 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1703 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1704 $fname, 'FOR UPDATE'
1706 if( $s === false ) {
1708 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1711 $ut = $dbw->strencode( $s->cur_user_text
);
1712 $uid = $s->cur_user
;
1715 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1716 if( $from != $s->cur_user_text
) {
1717 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1718 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1719 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1720 htmlspecialchars( $from ),
1721 htmlspecialchars( $s->cur_user_text
) ) );
1722 if($s->cur_comment
!= '') {
1724 wfMsg('editcomment',
1725 htmlspecialchars( $s->cur_comment
) ) );
1730 # Get the last edit not by this guy
1731 $s = $dbw->selectRow( 'old',
1732 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1734 'old_namespace' => $n,
1736 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1737 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1739 if( $s === false ) {
1741 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1742 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1747 # Mark all reverted edits as bot
1748 $dbw->update( 'recentchanges',
1751 ), array( /* WHERE */
1753 "rc_timestamp > '{$s->old_timestamp}'",
1759 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1760 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1761 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1762 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1763 $this->updateArticle( Revision
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1764 Article
::onArticleEdit( $this->mTitle
);
1765 $wgOut->returnToMain( false );
1770 * Do standard deferred updates after page view
1773 function viewUpdates() {
1774 global $wgDeferredUpdateList;
1776 if ( 0 != $this->getID() ) {
1777 global $wgDisableCounters;
1778 if( !$wgDisableCounters ) {
1779 Article
::incViewCount( $this->getID() );
1780 $u = new SiteStatsUpdate( 1, 0, 0 );
1781 array_push( $wgDeferredUpdateList, $u );
1785 # Update newtalk status if user is reading their own
1789 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1790 $this->mTitle
->getText() == $wgUser->getName()) {
1791 require_once( 'UserTalkUpdate.php' );
1792 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1797 * Do standard deferred updates after page edit.
1798 * Every 1000th edit, prune the recent changes table.
1800 * @param string $text
1802 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1803 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1804 global $wgMessageCache, $wgUser;
1807 if ( 0 == mt_rand( 0, 999 ) ) {
1808 $dbw =& wfGetDB( DB_MASTER
);
1809 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1810 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1811 $dbw->query( $sql );
1813 $id = $this->getID();
1814 $title = $this->mTitle
->getPrefixedDBkey();
1815 $shortTitle = $this->mTitle
->getDBkey();
1817 $adj = $this->mCountAdjustment
;
1820 $u = new LinksUpdate( $id, $title );
1821 array_push( $wgDeferredUpdateList, $u );
1822 $u = new SiteStatsUpdate( 0, 1, $adj );
1823 array_push( $wgDeferredUpdateList, $u );
1824 $u = new SearchUpdate( $id, $title, $text );
1825 array_push( $wgDeferredUpdateList, $u );
1827 # If this is another user's talk page,
1828 # create a watchlist entry for this page
1830 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1831 $shortTitle != $wgUser->getName()) {
1832 require_once( 'UserTalkUpdate.php' );
1833 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1836 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1837 $wgMessageCache->replace( $shortTitle, $text );
1843 * @todo document this function
1845 * @param string $oldid Revision ID of this article revision
1847 function setOldSubtitle( $oldid=0 ) {
1848 global $wgLang, $wgOut, $wgUser;
1850 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1851 $sk = $wgUser->getSkin();
1852 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1853 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1854 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1855 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1856 $wgOut->setSubtitle( $r );
1860 * This function is called right before saving the wikitext,
1861 * so we can do things like signatures and links-in-context.
1863 * @param string $text
1865 function preSaveTransform( $text ) {
1866 global $wgParser, $wgUser;
1867 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1870 /* Caching functions */
1873 * checkLastModified returns true if it has taken care of all
1874 * output to the client that is necessary for this request.
1875 * (that is, it has sent a cached version of the page)
1877 function tryFileCache() {
1878 static $called = false;
1880 wfDebug( " tryFileCache() -- called twice!?\n" );
1884 if($this->isFileCacheable()) {
1885 $touched = $this->mTouched
;
1886 $cache = new CacheManager( $this->mTitle
);
1887 if($cache->isFileCacheGood( $touched )) {
1889 wfDebug( " tryFileCache() - about to load\n" );
1890 $cache->loadFromFileCache();
1893 wfDebug( " tryFileCache() - starting buffer\n" );
1894 ob_start( array(&$cache, 'saveToFileCache' ) );
1897 wfDebug( " tryFileCache() - not cacheable\n" );
1902 * Check if the page can be cached
1905 function isFileCacheable() {
1906 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1907 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1909 return $wgUseFileCache
1910 and (!$wgShowIPinHeader)
1911 and ($this->getID() != 0)
1912 and ($wgUser->getId() == 0)
1913 and (!$wgUser->getNewtalk())
1914 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1915 and (empty( $action ) ||
$action == 'view')
1916 and (!isset($oldid))
1918 and (!isset($redirect))
1919 and (!isset($printable))
1920 and (!$this->mRedirectedFrom
);
1924 * Loads cur_touched and returns a value indicating if it should be used
1927 function checkTouched() {
1928 $fname = 'Article::checkTouched';
1929 $id = $this->getID();
1930 $dbr =& $this->getDB();
1931 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1932 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1933 if( $s !== false ) {
1934 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
1935 return !$s->page_is_redirect
;
1942 * Edit an article without doing all that other stuff
1944 * @param string $text text submitted
1945 * @param string $comment comment submitted
1946 * @param integer $minor whereas it's a minor modification
1948 function quickEdit( $text, $comment = '', $minor = 0 ) {
1950 $fname = 'Article::quickEdit';
1952 #wfDebugDieBacktrace( "$fname called." );
1954 wfProfileIn( $fname );
1956 $dbw =& wfGetDB( DB_MASTER
);
1957 $ns = $this->mTitle
->getNamespace();
1958 $dbkey = $this->mTitle
->getDBkey();
1959 $encDbKey = $dbw->strencode( $dbkey );
1960 $timestamp = wfTimestampNow();
1962 $dbw->insert( 'text', array(
1963 'old_text' => $text,
1964 'old_flags' => "" ), $fname );
1965 $text_id = $dbw->insertID();
1968 $dbw->update( 'page', array(
1970 'page_touched' => $timestamp,
1971 'page_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
1972 'page_latest' => $text_id ),
1973 array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1975 $page_id = $dbw->selectField( 'page', 'page_id', array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1978 $dbw->insert( 'revision', array(
1979 'rev_id' => $text_id,
1980 'rev_page' => $page_id,
1981 'rev_comment' => $comment,
1982 'rev_user' => $wgUser->getID(),
1983 'rev_user_text' => $wgUser->getName(),
1984 'rev_timestamp' => $timestamp,
1985 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1986 'rev_minor_edit' => intval($minor) ),
1990 $dbw->insertSelect( 'old', 'cur',
1992 'old_namespace' => 'cur_namespace',
1993 'old_title' => 'cur_title',
1994 'old_text' => 'cur_text',
1995 'old_comment' => 'cur_comment',
1996 'old_user' => 'cur_user',
1997 'old_user_text' => 'cur_user_text',
1998 'old_timestamp' => 'cur_timestamp',
1999 'inverse_timestamp' => '99999999999999-cur_timestamp',
2001 'cur_namespace' => $ns,
2002 'cur_title' => $dbkey,
2006 # Use the affected row count to determine if the article is new
2007 $numRows = $dbw->affectedRows();
2009 # Make an array of fields to be inserted
2011 'cur_text' => $text,
2012 'cur_timestamp' => $timestamp,
2013 'cur_user' => $wgUser->getID(),
2014 'cur_user_text' => $wgUser->getName(),
2015 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2016 'cur_comment' => $comment,
2017 'cur_is_redirect' => $this->isRedirect( $text ) ? 1 : 0,
2018 'cur_minor_edit' => intval($minor),
2019 'cur_touched' => $dbw->timestamp($timestamp),
2024 $fields['cur_is_new'] = 0;
2025 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2027 # Insert new article
2028 $fields['cur_is_new'] = 1;
2029 $fields['cur_namespace'] = $ns;
2030 $fields['cur_title'] = $dbkey;
2031 $fields['cur_random'] = $rand = wfRandom();
2032 $dbw->insert( 'cur', $fields, $fname );
2035 wfProfileOut( $fname );
2039 * Used to increment the view counter
2042 * @param integer $id article id
2044 function incViewCount( $id ) {
2045 $id = intval( $id );
2046 global $wgHitcounterUpdateFreq;
2048 $dbw =& wfGetDB( DB_MASTER
);
2049 $pageTable = $dbw->tableName( 'page' );
2050 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2051 $acchitsTable = $dbw->tableName( 'acchits' );
2053 if( $wgHitcounterUpdateFreq <= 1 ){ //
2054 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2058 # Not important enough to warrant an error page in case of failure
2059 $oldignore = $dbw->ignoreErrors( true );
2061 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2063 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2064 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2065 # Most of the time (or on SQL errors), skip row count check
2066 $dbw->ignoreErrors( $oldignore );
2070 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2071 $row = $dbw->fetchObject( $res );
2072 $rown = intval( $row->n
);
2073 if( $rown >= $wgHitcounterUpdateFreq ){
2074 wfProfileIn( 'Article::incViewCount-collect' );
2075 $old_user_abort = ignore_user_abort( true );
2077 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2078 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2079 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2081 $dbw->query("DELETE FROM $hitcounterTable");
2082 $dbw->query('UNLOCK TABLES');
2083 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2084 'WHERE cur_id = hc_id');
2085 $dbw->query("DROP TABLE $acchitsTable");
2087 ignore_user_abort( $old_user_abort );
2088 wfProfileOut( 'Article::incViewCount-collect' );
2090 $dbw->ignoreErrors( $oldignore );
2094 * The onArticle*() functions are supposed to be a kind of hooks
2095 * which should be called whenever any of the specified actions
2098 * This is a good place to put code to clear caches, for instance.
2100 * This is called on page move and undelete, as well as edit
2102 * @param $title_obj a title object
2105 function onArticleCreate($title_obj) {
2106 global $wgUseSquid, $wgDeferredUpdateList;
2108 $titles = $title_obj->getBrokenLinksTo();
2111 if ( $wgUseSquid ) {
2112 $urls = $title_obj->getSquidURLs();
2113 foreach ( $titles as $linkTitle ) {
2114 $urls[] = $linkTitle->getInternalURL();
2116 $u = new SquidUpdate( $urls );
2117 array_push( $wgDeferredUpdateList, $u );
2120 # Clear persistent link cache
2121 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2124 function onArticleDelete($title_obj) {
2125 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2127 function onArticleEdit($title_obj) {
2128 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2133 * Info about this page
2136 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2137 $fname = 'Article::info';
2139 if ( !$wgAllowPageInfo ) {
2140 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2144 $dbr =& $this->getDB();
2146 $basenamespace = $wgTitle->getNamespace() & (~
1);
2147 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2148 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2149 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2150 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2151 $wgOut->setPagetitle( $fullTitle );
2152 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2154 # first, see if the page exists at all.
2155 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2157 $wgOut->addHTML( wfMsg('noarticletext') );
2159 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2160 $this->getSelectOptions() );
2161 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2162 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2163 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2165 # to find number of distinct authors, we need to do some
2166 # funny stuff because of the cur/old table split:
2167 # - first, find the name of the 'cur' author
2168 # - then, find the number of *other* authors in 'old'
2171 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2172 $this->getSelectOptions() );
2174 # find number of 'old' authors excluding 'cur' author
2175 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2176 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2177 $this->getSelectOptions() ) +
1;
2179 # now for the Talk page ...
2180 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2181 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2184 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2188 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2189 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2191 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2195 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2196 $this->getSelectOptions() );
2197 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2198 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2199 $fname, $this->getSelectOptions() );
2201 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );
2208 * Check whether an article is a stub
2211 * @param integer $articleID ID of the article that is to be checked
2213 function wfArticleIsStub( $articleID ) {
2215 $fname = 'wfArticleIsStub';
2217 $threshold = $wgUser->getOption('stubthreshold') ;
2218 if ( $threshold > 0 ) {
2219 $dbr =& wfGetDB( DB_SLAVE
);
2220 $s = $dbr->selectRow( array('page', 'text'),
2221 array( 'LENGTH(old_text) AS len', 'page_namespace', 'page_is_redirect' ),
2222 array( 'page_id' => $articleID, "page.page_latest=text.old_id" ),
2224 if ( $s == false OR $s->page_is_redirect
OR $s->page_namespace
!= 0 ) {
2228 return ( $size < $threshold );