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();
535 $pageId = $this->getId();
537 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
538 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
539 WHERE rev_page = $pageId
540 AND rev_user != $user
541 GROUP BY rev_user, rev_user_text, user_real_name
542 ORDER BY timestamp DESC";
544 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
545 $sql .= ' '. $this->getSelectOptions();
547 $res = $dbr->query($sql, $fname);
549 while ( $line = $dbr->fetchObject( $res ) ) {
550 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
553 $dbr->freeResult($res);
558 * This is the default action of the script: just view the page of
562 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
563 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
565 $sk = $wgUser->getSkin();
567 $fname = 'Article::view';
568 wfProfileIn( $fname );
569 # Get variables from query string
570 $oldid = $this->getOldID();
571 $diff = $wgRequest->getVal( 'diff' );
572 $rcid = $wgRequest->getVal( 'rcid' );
574 $wgOut->setArticleFlag( true );
575 $wgOut->setRobotpolicy( 'index,follow' );
576 # If we got diff and oldid in the query, we want to see a
577 # diff page instead of the article.
579 if ( !is_null( $diff ) ) {
580 require_once( 'DifferenceEngine.php' );
581 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
582 $de = new DifferenceEngine( $oldid, $diff, $rcid );
585 # Run view updates for current revision only
586 $this->viewUpdates();
588 wfProfileOut( $fname );
591 if ( empty( $oldid ) && $this->checkTouched() ) {
592 if( $wgOut->checkLastModified( $this->mTouched
) ){
593 wfProfileOut( $fname );
595 } else if ( $this->tryFileCache() ) {
596 # tell wgOut that output is taken care of
598 $this->viewUpdates();
599 wfProfileOut( $fname );
603 # Should the parser cache be used?
604 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
612 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
616 if ( !$outputDone ) {
617 $text = $this->getContent( false ); # May change mTitle by following a redirect
619 # Another whitelist check in case oldid or redirects are altering the title
620 if ( !$this->mTitle
->userCanRead() ) {
621 $wgOut->loginToUse();
627 # We're looking at an old revision
629 if ( !empty( $oldid ) ) {
630 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
631 $wgOut->setRobotpolicy( 'noindex,follow' );
633 if ( '' != $this->mRedirectedFrom
) {
634 $sk = $wgUser->getSkin();
635 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
637 $s = wfMsg( 'redirectedfrom', $redir );
638 $wgOut->setSubtitle( $s );
640 # Can't cache redirects
644 # wrap user css and user js in pre and don't parse
645 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
647 $this->mTitle
->getNamespace() == NS_USER
&&
648 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
650 $wgOut->addWikiText( wfMsg('clearyourcache'));
651 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
652 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
654 $imageUrl = $wgStylePath.'/common/images/redirect.png';
655 $targetUrl = $rt->escapeLocalURL();
656 $titleText = htmlspecialchars( $rt->getPrefixedText() );
657 $link = $sk->makeLinkObj( $rt );
659 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
660 '<span class="redirectText">'.$link.'</span>' );
662 } else if ( $pcache ) {
663 # Display content and save to parser cache
664 $wgOut->addPrimaryWikiText( $text, $this );
666 # Display content, don't attempt to save to parser cache
667 $wgOut->addWikiText( $text );
670 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
671 # If we have been passed an &rcid= parameter, we want to give the user a
672 # chance to mark this new article as patrolled.
673 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
674 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
676 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
677 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
678 'action=markpatrolled&rcid='.$rcid )
682 # Put link titles into the link cache
683 $wgOut->transformBuffer();
685 # Add link titles as META keywords
686 $wgOut->addMetaTags() ;
688 $this->viewUpdates();
689 wfProfileOut( $fname );
691 $wgUser->clearNotification( $this->mTitle
);
695 * Theoretically we could defer these whole insert and update
696 * functions for after display, but that's taking a big leap
697 * of faith, and we want to be able to report database
698 * errors at some point.
701 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
702 global $wgOut, $wgUser;
703 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
705 $fname = 'Article::insertNewArticle';
707 $this->mCountAdjustment
= $this->isCountable( $text );
709 $ns = $this->mTitle
->getNamespace();
710 $ttl = $this->mTitle
->getDBkey();
711 $text = $this->preSaveTransform( $text );
712 if ( $this->isRedirect( $text ) ) { $redir = 1; }
715 $now = wfTimestampNow();
716 $won = wfInvertTimestamp( $now );
719 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
722 $flags = Revision
::compressRevisionText( $mungedText );
724 $dbw =& wfGetDB( DB_MASTER
);
726 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
727 $dbw->insert( 'text', array(
729 'old_text' => $mungedText,
730 'old_flags' => $flags,
732 $revisionId = $dbw->insertId();
734 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
735 $dbw->insert( 'page', array(
736 'page_id' => $page_id,
737 'page_namespace' => $ns,
738 'page_title' => $ttl,
740 'page_restrictions' => '',
741 'page_is_redirect' => $redir,
743 'page_random' => $rand,
744 'page_touched' => $dbw->timestamp($now),
745 'page_latest' => $revisionId,
747 $newid = $dbw->insertId();
749 $dbw->insert( 'revision', array(
750 'rev_page' => $newid,
751 'rev_id' => $revisionId,
752 'rev_comment' => $summary,
753 'rev_user' => $wgUser->getID(),
754 'rev_timestamp' => $dbw->timestamp($now),
755 'rev_minor_edit' => $isminor,
756 'rev_user_text' => $wgUser->getName(),
757 'inverse_timestamp' => $won,
760 $this->mTitle
->resetArticleID( $newid );
762 Article
::onArticleCreate( $this->mTitle
);
763 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
766 if(!$this->mTitle
->userIsWatching()) $this->watch();
768 if ( $this->mTitle
->userIsWatching() ) {
773 # The talk page isn't in the regular link tables, so we need to update manually:
774 $talkns = $ns ^
1; # talk -> normal; normal -> talk
775 $dbw->update( 'page',
776 array( 'page_touched' => $dbw->timestamp($now) ),
777 array( 'page_namespace' => $talkns,
778 'page_title' => $ttl ),
781 # standard deferred updates
782 $this->editUpdates( $text, $summary, $isminor, $now );
784 $oldid = 0; # new article
785 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
789 * Fetch and uncompress the text for a given revision.
790 * Can ask by rev_id number or timestamp (set $field)
792 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
793 $fname = 'Article::fetchRevisionText';
794 $dbw =& wfGetDB( DB_MASTER
);
796 $rev = $dbw->addQuotes( $revId );
798 $rev = 'page_latest';
800 $result = $dbw->query(
801 sprintf( "SELECT old_text, old_flags
803 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
805 $dbw->tableName( 'page' ),
806 $dbw->tableName( 'revision' ),
807 $dbw->tableName( 'text' ),
808 IntVal( $this->mTitle
->getArticleId() ),
812 $obj = $dbw->fetchObject( $result );
813 $dbw->freeResult( $result );
814 $oldtext = Revision
::getRevisionText( $obj );
818 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
819 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
820 if( is_null( $edittime ) ) {
821 $oldtext = $this->fetchRevisionText();
823 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
825 if ($section != '') {
826 if($section=='new') {
827 if($summary) $subject="== {$summary} ==\n\n";
828 $text=$oldtext."\n\n".$subject.$text;
831 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
832 # comments to be stripped as well)
834 $parser=new Parser();
835 $parser->mOutputType
=OT_WIKI
;
836 $oldtext=$parser->strip($oldtext, $striparray, true);
838 # now that we can be sure that no pseudo-sections are in the source,
840 # Unfortunately we can't simply do a preg_replace because that might
841 # replace the wrong section, so we have to use the section counter instead
842 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
843 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
844 $secs[$section*2]=$text."\n\n"; // replace with edited
846 # section 0 is top (intro) section
849 # headline of old section - we need to go through this section
850 # to determine if there are any subsections that now need to
851 # be erased, as the mother section has been replaced with
852 # the text of all subsections.
853 $headline=$secs[$section*2-1];
854 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
857 # determine headline level for wikimarkup headings
858 if(strpos($hlevel,'=')!==false) {
859 $hlevel=strlen($hlevel);
862 $secs[$section*2-1]=''; // erase old headline
865 while(!empty($secs[$count*2-1]) && !$break) {
867 $subheadline=$secs[$count*2-1];
869 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
870 $subhlevel=$matches[1];
871 if(strpos($subhlevel,'=')!==false) {
872 $subhlevel=strlen($subhlevel);
874 if($subhlevel > $hlevel) {
875 // erase old subsections
876 $secs[$count*2-1]='';
879 if($subhlevel <= $hlevel) {
887 $text=join('',$secs);
888 # reinsert the stuff that we stripped out earlier
889 $text=$parser->unstrip($text,$striparray);
890 $text=$parser->unstripNoWiki($text,$striparray);
898 * Change an existing article. Puts the previous version back into the old table, updates RC
899 * and all necessary caches, mostly via the deferred update array.
901 * It is possible to call this function from a command-line script, but note that you should
902 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
904 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
905 global $wgOut, $wgUser;
906 global $wgDBtransactions, $wgMwRedir;
907 global $wgUseSquid, $wgInternalServer;
909 $fname = 'Article::updateArticle';
912 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
913 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
914 if ( $this->isRedirect( $text ) ) {
915 # Remove all content but redirect
916 # This could be done by reconstructing the redirect from a title given by
917 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
919 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
921 $text = $m[1] . "\n";
926 $text = $this->preSaveTransform( $text );
927 $dbw =& wfGetDB( DB_MASTER
);
929 # Update article, but only if changed.
931 # It's important that we either rollback or complete, otherwise an attacker could
932 # overwrite cur entries by sending precisely timed user aborts. Random bored users
933 # could conceivably have the same effect, especially if cur is locked for long periods.
934 if( $wgDBtransactions ) {
935 $dbw->query( 'BEGIN', $fname );
937 $userAbort = ignore_user_abort( true );
940 $oldtext = $this->getContent( true );
942 if ( 0 != strcmp( $text, $oldtext ) ) {
943 $this->mCountAdjustment
= $this->isCountable( $text )
944 - $this->isCountable( $oldtext );
945 $now = wfTimestampNow();
946 $won = wfInvertTimestamp( $now );
949 $flags = Revision
::compressRevisionText( $newtext );
951 $lastRevision = $dbw->selectField(
952 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
954 # Record the text to the text table
955 $old_id = $dbw->nextSequenceValue( 'text_old_id_val' );
956 $dbw->insert( 'text',
959 'old_text' => $mungedText,
960 'old_flags' => $flags,
963 $revisionId = $dbw->insertId();
965 # Record the edit in revisions
966 $dbw->insert( 'revision',
968 'rev_id' => $revisionId,
969 'rev_page' => $this->getID(),
970 'rev_comment' => $summary,
971 'rev_minor_edit' => $me2,
972 'rev_user' => $wgUser->getID(),
973 'rev_user_text' => $wgUser->getName(),
974 'rev_timestamp' => $dbw->timestamp( $now ),
975 'inverse_timestamp' => $won
980 $dbw->update( 'page',
982 'page_latest' => $revisionId,
983 'page_touched' => $dbw->timestamp( $now ),
985 'page_is_redirect' => $redir,
986 ), array( /* WHERE */
987 'page_id' => $this->getID(),
988 'page_latest' => $lastRevision, # Paranoia
992 if( $dbw->affectedRows() == 0 ) {
993 /* Belated edit conflict! Run away!! */
996 # Update recentchanges and purge cache and whatnot
997 $bot = (int)($wgUser->isBot() ||
$forceBot);
998 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
999 $lastRevision, $this->getTimestamp(), $bot );
1000 Article
::onArticleEdit( $this->mTitle
);
1004 if( $wgDBtransactions ) {
1005 $dbw->query( 'COMMIT', $fname );
1007 ignore_user_abort( $userAbort );
1012 if (!$this->mTitle
->userIsWatching()) $this->watch();
1014 if ( $this->mTitle
->userIsWatching() ) {
1018 # standard deferred updates
1019 $this->editUpdates( $text, $summary, $minor, $now );
1023 # Template namespace
1024 # Purge all articles linking here
1025 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1026 $titles = $this->mTitle
->getLinksTo();
1027 Title
::touchArray( $titles );
1028 if ( $wgUseSquid ) {
1029 foreach ( $titles as $title ) {
1030 $urls[] = $title->getInternalURL();
1036 if ( $wgUseSquid ) {
1037 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1038 $u = new SquidUpdate( $urls );
1042 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $revisionId );
1048 * After we've either updated or inserted the article, update
1049 * the link tables and redirect to the new page.
1051 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1052 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1054 $wgLinkCache = new LinkCache();
1056 $wgLinkCache->forUpdate( true );
1058 # Get old version of link table to allow incremental link updates
1059 $wgLinkCache->preFill( $this->mTitle
);
1060 $wgLinkCache->clear();
1062 # Parse the text and replace links with placeholders
1063 $wgOut = new OutputPage();
1064 $wgOut->addWikiText( $text );
1066 # Look up the links in the DB and add them to the link cache
1067 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1069 if( $this->isRedirect( $text ) )
1073 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1075 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1076 # this will be improved later (to-do)
1078 include_once( "UserMailer.php" );
1079 $wgEnotif = new EmailNotification ();
1080 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1085 * @todo document this function a bit more
1087 function validate () {
1088 global $wgOut, $wgUseValidation;
1089 if( $wgUseValidation ) {
1090 require_once ( 'SpecialValidate.php' ) ;
1091 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1092 $wgOut->setRobotpolicy( 'noindex,follow' );
1093 if( $this->mTitle
->getNamespace() != 0 ) {
1094 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1097 $v = new Validation
;
1098 $v->validate_form( $this->mTitle
->getDBkey() );
1100 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1105 * Mark this particular edit as patrolled
1107 function markpatrolled() {
1108 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1109 $wgOut->setRobotpolicy( 'noindex,follow' );
1111 if ( !$wgUseRCPatrol )
1113 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1116 if ( $wgUser->getID() == 0 )
1118 $wgOut->loginToUse();
1121 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1123 $wgOut->sysopRequired();
1126 $rcid = $wgRequest->getVal( 'rcid' );
1127 if ( !is_null ( $rcid ) )
1129 RecentChange
::markPatrolled( $rcid );
1130 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1131 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1133 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1134 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1138 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1144 * Add this page to $wgUser's watchlist
1149 global $wgUser, $wgOut;
1151 if ( 0 == $wgUser->getID() ) {
1152 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1155 if ( wfReadOnly() ) {
1156 $wgOut->readOnlyPage();
1160 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1162 $wgUser->addWatch( $this->mTitle
);
1163 $wgUser->saveSettings();
1165 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1167 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1168 $wgOut->setRobotpolicy( 'noindex,follow' );
1170 $link = $this->mTitle
->getPrefixedText();
1171 $text = wfMsg( 'addedwatchtext', $link );
1172 $wgOut->addWikiText( $text );
1175 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1179 * Stop watching a page
1182 function unwatch() {
1184 global $wgUser, $wgOut;
1186 if ( 0 == $wgUser->getID() ) {
1187 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1190 if ( wfReadOnly() ) {
1191 $wgOut->readOnlyPage();
1195 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1197 $wgUser->removeWatch( $this->mTitle
);
1198 $wgUser->saveSettings();
1200 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1202 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1203 $wgOut->setRobotpolicy( 'noindex,follow' );
1205 $link = $this->mTitle
->getPrefixedText();
1206 $text = wfMsg( 'removedwatchtext', $link );
1207 $wgOut->addWikiText( $text );
1210 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1216 function protect( $limit = 'sysop' ) {
1217 global $wgUser, $wgOut, $wgRequest;
1219 if ( ! $wgUser->isAllowed('protect') ) {
1220 $wgOut->sysopRequired();
1223 if ( wfReadOnly() ) {
1224 $wgOut->readOnlyPage();
1227 $id = $this->mTitle
->getArticleID();
1229 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1233 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1234 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1235 $reason = $wgRequest->getText( 'wpReasonProtect' );
1238 $dbw =& wfGetDB( DB_MASTER
);
1239 $dbw->update( 'page',
1241 'page_touched' => $dbw->timestamp(),
1242 'page_restrictions' => (string)$limit
1243 ), array( /* WHERE */
1245 ), 'Article::protect'
1248 $restrictions = "move=" . $limit;
1250 $restrictions .= ":edit=" . $limit;
1252 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1254 $dbw =& wfGetDB( DB_MASTER
);
1255 $dbw->update( 'page',
1257 'page_touched' => $dbw->timestamp(),
1258 'page_restrictions' => $restrictions
1259 ), array( /* WHERE */
1261 ), 'Article::protect'
1264 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1266 $log = new LogPage( 'protect' );
1267 if ( $limit === '' ) {
1268 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1270 $log->addEntry( 'protect', $this->mTitle
, $reason );
1272 $wgOut->redirect( $this->mTitle
->getFullURL() );
1276 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1277 return $this->confirmProtect( '', $reason, $limit );
1282 * Output protection confirmation dialog
1284 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1287 wfDebug( "Article::confirmProtect\n" );
1289 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1290 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1296 if ( $limit === '' ) {
1297 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1298 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1299 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1300 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1301 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1302 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1304 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1305 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1306 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1307 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1308 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1309 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1310 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1313 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1316 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1320 <label for='wpReasonProtect'>{$protcom}:</label>
1323 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1331 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1334 <label for='wpConfirmProtect'>{$check}</label>
1337 if($moveonly != '') {
1341 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1344 <label for='wpMoveOnly'>{$moveonly}</label>
1352 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1358 $wgOut->returnToMain( false );
1362 * Unprotect the pages
1364 function unprotect() {
1365 return $this->protect( '' );
1369 * UI entry point for page deletion
1372 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1373 $fname = 'Article::delete';
1374 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1375 $reason = $wgRequest->getText( 'wpReason' );
1377 # This code desperately needs to be totally rewritten
1380 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1381 $wgOut->sysopRequired();
1384 if ( wfReadOnly() ) {
1385 $wgOut->readOnlyPage();
1389 # Better double-check that it hasn't been deleted yet!
1390 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1391 if ( ( '' == trim( $this->mTitle
->getText() ) )
1392 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1393 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1398 $this->doDelete( $reason );
1402 # determine whether this page has earlier revisions
1403 # and insert a warning if it does
1404 # we select the text because it might be useful below
1405 $dbr =& $this->getDB();
1406 $ns = $this->mTitle
->getNamespace();
1407 $title = $this->mTitle
->getDBkey();
1408 $old = $dbr->selectRow( 'old',
1409 array( 'old_text', 'old_flags' ),
1411 'old_namespace' => $ns,
1412 'old_title' => $title,
1413 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1416 if( $old !== false && !$confirm ) {
1417 $skin=$wgUser->getSkin();
1418 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1419 $wgOut->addHTML( $skin->historyLink() .'</b>');
1423 $s = $dbr->selectRow( 'cur',
1424 array( 'cur_text' ),
1426 'cur_namespace' => $ns,
1427 'cur_title' => $title,
1428 ), $fname, $this->getSelectOptions()
1431 if( $s !== false ) {
1432 # if this is a mini-text, we can paste part of it into the deletion reason
1434 #if this is empty, an earlier revision may contain "useful" text
1436 if($s->cur_text
!= '') {
1440 $text = Revision
::getRevisionText( $old );
1446 $length=strlen($text);
1448 # this should not happen, since it is not possible to store an empty, new
1449 # page. Let's insert a standard text in case it does, though
1450 if($length == 0 && $reason === '') {
1451 $reason = wfMsg('exblank');
1454 if($length < 500 && $reason === '') {
1456 # comment field=255, let's grep the first 150 to have some user
1458 $text=substr($text,0,150);
1459 # let's strip out newlines and HTML tags
1460 $text=preg_replace('/\"/',"'",$text);
1461 $text=preg_replace('/\</','<',$text);
1462 $text=preg_replace('/\>/','>',$text);
1463 $text=preg_replace("/[\n\r]/",'',$text);
1465 $reason=wfMsg('excontent'). " '".$text;
1467 $reason=wfMsg('exbeforeblank') . " '".$text;
1469 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1474 return $this->confirmDelete( '', $reason );
1478 * Output deletion confirmation dialog
1480 function confirmDelete( $par, $reason ) {
1483 wfDebug( "Article::confirmDelete\n" );
1485 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1486 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1487 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1488 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1490 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1492 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1493 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1494 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1497 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1501 <label for='wpReason'>{$delcom}:</label>
1504 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1512 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1515 <label for='wpConfirm'>{$check}</label>
1521 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1527 $wgOut->returnToMain( false );
1532 * Perform a deletion and output success or failure messages
1534 function doDelete( $reason ) {
1535 global $wgOut, $wgUser, $wgContLang;
1536 $fname = 'Article::doDelete';
1537 wfDebug( $fname."\n" );
1539 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1540 if ( $this->doDeleteArticle( $reason ) ) {
1541 $deleted = $this->mTitle
->getPrefixedText();
1543 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1544 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1546 $sk = $wgUser->getSkin();
1547 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1548 ':' . wfMsgForContent( 'dellogpage' ),
1549 wfMsg( 'deletionlog' ) );
1551 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1553 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1554 $wgOut->returnToMain( false );
1555 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1557 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1563 * Back-end article deletion
1564 * Deletes the article with database consistency, writes logs, purges caches
1567 function doDeleteArticle( $reason ) {
1569 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1571 $fname = 'Article::doDeleteArticle';
1572 wfDebug( $fname."\n" );
1574 $dbw =& wfGetDB( DB_MASTER
);
1575 $ns = $this->mTitle
->getNamespace();
1576 $t = $this->mTitle
->getDBkey();
1577 $id = $this->mTitle
->getArticleID();
1579 if ( $t == '' ||
$id == 0 ) {
1583 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1584 array_push( $wgDeferredUpdateList, $u );
1586 $linksTo = $this->mTitle
->getLinksTo();
1589 if ( $wgUseSquid ) {
1591 $this->mTitle
->getInternalURL(),
1592 $this->mTitle
->getInternalURL( 'history' )
1594 foreach ( $linksTo as $linkTo ) {
1595 $urls[] = $linkTo->getInternalURL();
1598 $u = new SquidUpdate( $urls );
1599 array_push( $wgDeferredUpdateList, $u );
1603 # Client and file cache invalidation
1604 Title
::touchArray( $linksTo );
1606 # Move article and history to the "archive" table
1607 $archiveTable = $dbw->tableName( 'archive' );
1608 $oldTable = $dbw->tableName( 'old' );
1609 $curTable = $dbw->tableName( 'cur' );
1610 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1611 $linksTable = $dbw->tableName( 'links' );
1612 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1614 $dbw->insertSelect( 'archive', 'cur',
1616 'ar_namespace' => 'cur_namespace',
1617 'ar_title' => 'cur_title',
1618 'ar_text' => 'cur_text',
1619 'ar_comment' => 'cur_comment',
1620 'ar_user' => 'cur_user',
1621 'ar_user_text' => 'cur_user_text',
1622 'ar_timestamp' => 'cur_timestamp',
1623 'ar_minor_edit' => 'cur_minor_edit',
1626 'cur_namespace' => $ns,
1631 $dbw->insertSelect( 'archive', 'old',
1633 'ar_namespace' => 'old_namespace',
1634 'ar_title' => 'old_title',
1635 'ar_text' => 'old_text',
1636 'ar_comment' => 'old_comment',
1637 'ar_user' => 'old_user',
1638 'ar_user_text' => 'old_user_text',
1639 'ar_timestamp' => 'old_timestamp',
1640 'ar_minor_edit' => 'old_minor_edit',
1641 'ar_flags' => 'old_flags'
1643 'old_namespace' => $ns,
1648 # Now that it's safely backed up, delete it
1650 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1651 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1652 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1654 # Finally, clean up the link tables
1655 $t = $this->mTitle
->getPrefixedDBkey();
1657 Article
::onArticleDelete( $this->mTitle
);
1659 # Insert broken links
1660 $brokenLinks = array();
1661 foreach ( $linksTo as $titleObj ) {
1662 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1663 $linkID = $titleObj->getArticleID();
1664 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1666 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1669 $dbw->delete( 'links', array( 'l_to' => $id ) );
1670 $dbw->delete( 'links', array( 'l_from' => $id ) );
1671 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1672 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1673 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1676 $log = new LogPage( 'delete' );
1677 $log->addEntry( 'delete', $this->mTitle
, $reason );
1679 # Clear the cached article id so the interface doesn't act like we exist
1680 $this->mTitle
->resetArticleID( 0 );
1681 $this->mTitle
->mArticleID
= 0;
1686 * Revert a modification
1688 function rollback() {
1689 global $wgUser, $wgOut, $wgRequest;
1690 $fname = 'Article::rollback';
1692 if ( ! $wgUser->isAllowed('rollback') ) {
1693 $wgOut->sysopRequired();
1696 if ( wfReadOnly() ) {
1697 $wgOut->readOnlyPage( $this->getContent( true ) );
1700 $dbw =& wfGetDB( DB_MASTER
);
1702 # Enhanced rollback, marks edits rc_bot=1
1703 $bot = $wgRequest->getBool( 'bot' );
1705 # Replace all this user's current edits with the next one down
1706 $tt = $this->mTitle
->getDBKey();
1707 $n = $this->mTitle
->getNamespace();
1709 # Get the last editor, lock table exclusively
1710 $s = $dbw->selectRow( 'cur',
1711 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1712 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1713 $fname, 'FOR UPDATE'
1715 if( $s === false ) {
1717 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1720 $ut = $dbw->strencode( $s->cur_user_text
);
1721 $uid = $s->cur_user
;
1724 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1725 if( $from != $s->cur_user_text
) {
1726 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1727 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1728 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1729 htmlspecialchars( $from ),
1730 htmlspecialchars( $s->cur_user_text
) ) );
1731 if($s->cur_comment
!= '') {
1733 wfMsg('editcomment',
1734 htmlspecialchars( $s->cur_comment
) ) );
1739 # Get the last edit not by this guy
1740 $s = $dbw->selectRow( 'old',
1741 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1743 'old_namespace' => $n,
1745 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1746 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1748 if( $s === false ) {
1750 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1751 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1756 # Mark all reverted edits as bot
1757 $dbw->update( 'recentchanges',
1760 ), array( /* WHERE */
1762 "rc_timestamp > '{$s->old_timestamp}'",
1768 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1769 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1770 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1771 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1772 $this->updateArticle( Revision
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1773 Article
::onArticleEdit( $this->mTitle
);
1774 $wgOut->returnToMain( false );
1779 * Do standard deferred updates after page view
1782 function viewUpdates() {
1783 global $wgDeferredUpdateList;
1785 if ( 0 != $this->getID() ) {
1786 global $wgDisableCounters;
1787 if( !$wgDisableCounters ) {
1788 Article
::incViewCount( $this->getID() );
1789 $u = new SiteStatsUpdate( 1, 0, 0 );
1790 array_push( $wgDeferredUpdateList, $u );
1794 # Update newtalk status if user is reading their own
1798 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1799 $this->mTitle
->getText() == $wgUser->getName()) {
1800 require_once( 'UserTalkUpdate.php' );
1801 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1806 * Do standard deferred updates after page edit.
1807 * Every 1000th edit, prune the recent changes table.
1809 * @param string $text
1811 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1812 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1813 global $wgMessageCache, $wgUser;
1816 if ( 0 == mt_rand( 0, 999 ) ) {
1817 $dbw =& wfGetDB( DB_MASTER
);
1818 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1819 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1820 $dbw->query( $sql );
1822 $id = $this->getID();
1823 $title = $this->mTitle
->getPrefixedDBkey();
1824 $shortTitle = $this->mTitle
->getDBkey();
1826 $adj = $this->mCountAdjustment
;
1829 $u = new LinksUpdate( $id, $title );
1830 array_push( $wgDeferredUpdateList, $u );
1831 $u = new SiteStatsUpdate( 0, 1, $adj );
1832 array_push( $wgDeferredUpdateList, $u );
1833 $u = new SearchUpdate( $id, $title, $text );
1834 array_push( $wgDeferredUpdateList, $u );
1836 # If this is another user's talk page,
1837 # create a watchlist entry for this page
1839 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1840 $shortTitle != $wgUser->getName()) {
1841 require_once( 'UserTalkUpdate.php' );
1842 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1845 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1846 $wgMessageCache->replace( $shortTitle, $text );
1852 * @todo document this function
1854 * @param string $oldid Revision ID of this article revision
1856 function setOldSubtitle( $oldid=0 ) {
1857 global $wgLang, $wgOut, $wgUser;
1859 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1860 $sk = $wgUser->getSkin();
1861 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1862 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1863 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1864 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1865 $wgOut->setSubtitle( $r );
1869 * This function is called right before saving the wikitext,
1870 * so we can do things like signatures and links-in-context.
1872 * @param string $text
1874 function preSaveTransform( $text ) {
1875 global $wgParser, $wgUser;
1876 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1879 /* Caching functions */
1882 * checkLastModified returns true if it has taken care of all
1883 * output to the client that is necessary for this request.
1884 * (that is, it has sent a cached version of the page)
1886 function tryFileCache() {
1887 static $called = false;
1889 wfDebug( " tryFileCache() -- called twice!?\n" );
1893 if($this->isFileCacheable()) {
1894 $touched = $this->mTouched
;
1895 $cache = new CacheManager( $this->mTitle
);
1896 if($cache->isFileCacheGood( $touched )) {
1898 wfDebug( " tryFileCache() - about to load\n" );
1899 $cache->loadFromFileCache();
1902 wfDebug( " tryFileCache() - starting buffer\n" );
1903 ob_start( array(&$cache, 'saveToFileCache' ) );
1906 wfDebug( " tryFileCache() - not cacheable\n" );
1911 * Check if the page can be cached
1914 function isFileCacheable() {
1915 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1916 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1918 return $wgUseFileCache
1919 and (!$wgShowIPinHeader)
1920 and ($this->getID() != 0)
1921 and ($wgUser->getId() == 0)
1922 and (!$wgUser->getNewtalk())
1923 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1924 and (empty( $action ) ||
$action == 'view')
1925 and (!isset($oldid))
1927 and (!isset($redirect))
1928 and (!isset($printable))
1929 and (!$this->mRedirectedFrom
);
1933 * Loads cur_touched and returns a value indicating if it should be used
1936 function checkTouched() {
1937 $fname = 'Article::checkTouched';
1938 $id = $this->getID();
1939 $dbr =& $this->getDB();
1940 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1941 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1942 if( $s !== false ) {
1943 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
1944 return !$s->page_is_redirect
;
1951 * Edit an article without doing all that other stuff
1953 * @param string $text text submitted
1954 * @param string $comment comment submitted
1955 * @param integer $minor whereas it's a minor modification
1957 function quickEdit( $text, $comment = '', $minor = 0 ) {
1959 $fname = 'Article::quickEdit';
1961 #wfDebugDieBacktrace( "$fname called." );
1963 wfProfileIn( $fname );
1965 $dbw =& wfGetDB( DB_MASTER
);
1966 $ns = $this->mTitle
->getNamespace();
1967 $dbkey = $this->mTitle
->getDBkey();
1968 $encDbKey = $dbw->strencode( $dbkey );
1969 $timestamp = wfTimestampNow();
1971 $dbw->insert( 'text', array(
1972 'old_text' => $text,
1973 'old_flags' => "" ), $fname );
1974 $text_id = $dbw->insertID();
1977 $dbw->update( 'page', array(
1979 'page_touched' => $timestamp,
1980 'page_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
1981 'page_latest' => $text_id ),
1982 array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1984 $page_id = $dbw->selectField( 'page', 'page_id', array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1987 $dbw->insert( 'revision', array(
1988 'rev_id' => $text_id,
1989 'rev_page' => $page_id,
1990 'rev_comment' => $comment,
1991 'rev_user' => $wgUser->getID(),
1992 'rev_user_text' => $wgUser->getName(),
1993 'rev_timestamp' => $timestamp,
1994 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1995 'rev_minor_edit' => intval($minor) ),
1999 $dbw->insertSelect( 'old', 'cur',
2001 'old_namespace' => 'cur_namespace',
2002 'old_title' => 'cur_title',
2003 'old_text' => 'cur_text',
2004 'old_comment' => 'cur_comment',
2005 'old_user' => 'cur_user',
2006 'old_user_text' => 'cur_user_text',
2007 'old_timestamp' => 'cur_timestamp',
2008 'inverse_timestamp' => '99999999999999-cur_timestamp',
2010 'cur_namespace' => $ns,
2011 'cur_title' => $dbkey,
2015 # Use the affected row count to determine if the article is new
2016 $numRows = $dbw->affectedRows();
2018 # Make an array of fields to be inserted
2020 'cur_text' => $text,
2021 'cur_timestamp' => $timestamp,
2022 'cur_user' => $wgUser->getID(),
2023 'cur_user_text' => $wgUser->getName(),
2024 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2025 'cur_comment' => $comment,
2026 'cur_is_redirect' => $this->isRedirect( $text ) ? 1 : 0,
2027 'cur_minor_edit' => intval($minor),
2028 'cur_touched' => $dbw->timestamp($timestamp),
2033 $fields['cur_is_new'] = 0;
2034 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2036 # Insert new article
2037 $fields['cur_is_new'] = 1;
2038 $fields['cur_namespace'] = $ns;
2039 $fields['cur_title'] = $dbkey;
2040 $fields['cur_random'] = $rand = wfRandom();
2041 $dbw->insert( 'cur', $fields, $fname );
2044 wfProfileOut( $fname );
2048 * Used to increment the view counter
2051 * @param integer $id article id
2053 function incViewCount( $id ) {
2054 $id = intval( $id );
2055 global $wgHitcounterUpdateFreq;
2057 $dbw =& wfGetDB( DB_MASTER
);
2058 $pageTable = $dbw->tableName( 'page' );
2059 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2060 $acchitsTable = $dbw->tableName( 'acchits' );
2062 if( $wgHitcounterUpdateFreq <= 1 ){ //
2063 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2067 # Not important enough to warrant an error page in case of failure
2068 $oldignore = $dbw->ignoreErrors( true );
2070 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2072 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2073 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2074 # Most of the time (or on SQL errors), skip row count check
2075 $dbw->ignoreErrors( $oldignore );
2079 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2080 $row = $dbw->fetchObject( $res );
2081 $rown = intval( $row->n
);
2082 if( $rown >= $wgHitcounterUpdateFreq ){
2083 wfProfileIn( 'Article::incViewCount-collect' );
2084 $old_user_abort = ignore_user_abort( true );
2086 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2087 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2088 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2090 $dbw->query("DELETE FROM $hitcounterTable");
2091 $dbw->query('UNLOCK TABLES');
2092 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2093 'WHERE cur_id = hc_id');
2094 $dbw->query("DROP TABLE $acchitsTable");
2096 ignore_user_abort( $old_user_abort );
2097 wfProfileOut( 'Article::incViewCount-collect' );
2099 $dbw->ignoreErrors( $oldignore );
2103 * The onArticle*() functions are supposed to be a kind of hooks
2104 * which should be called whenever any of the specified actions
2107 * This is a good place to put code to clear caches, for instance.
2109 * This is called on page move and undelete, as well as edit
2111 * @param $title_obj a title object
2114 function onArticleCreate($title_obj) {
2115 global $wgUseSquid, $wgDeferredUpdateList;
2117 $titles = $title_obj->getBrokenLinksTo();
2120 if ( $wgUseSquid ) {
2121 $urls = $title_obj->getSquidURLs();
2122 foreach ( $titles as $linkTitle ) {
2123 $urls[] = $linkTitle->getInternalURL();
2125 $u = new SquidUpdate( $urls );
2126 array_push( $wgDeferredUpdateList, $u );
2129 # Clear persistent link cache
2130 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2133 function onArticleDelete($title_obj) {
2134 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2136 function onArticleEdit($title_obj) {
2137 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2142 * Info about this page
2145 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2146 $fname = 'Article::info';
2148 if ( !$wgAllowPageInfo ) {
2149 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2153 $dbr =& $this->getDB();
2155 $basenamespace = $wgTitle->getNamespace() & (~
1);
2156 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2157 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2158 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2159 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2160 $wgOut->setPagetitle( $fullTitle );
2161 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2163 # first, see if the page exists at all.
2164 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2166 $wgOut->addHTML( wfMsg('noarticletext') );
2168 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2169 $this->getSelectOptions() );
2170 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2171 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2172 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2174 # to find number of distinct authors, we need to do some
2175 # funny stuff because of the cur/old table split:
2176 # - first, find the name of the 'cur' author
2177 # - then, find the number of *other* authors in 'old'
2180 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2181 $this->getSelectOptions() );
2183 # find number of 'old' authors excluding 'cur' author
2184 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2185 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2186 $this->getSelectOptions() ) +
1;
2188 # now for the Talk page ...
2189 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2190 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2193 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2197 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2198 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2200 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2204 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2205 $this->getSelectOptions() );
2206 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2207 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2208 $fname, $this->getSelectOptions() );
2210 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );
2217 * Check whether an article is a stub
2220 * @param integer $articleID ID of the article that is to be checked
2222 function wfArticleIsStub( $articleID ) {
2224 $fname = 'wfArticleIsStub';
2226 $threshold = $wgUser->getOption('stubthreshold') ;
2227 if ( $threshold > 0 ) {
2228 $dbr =& wfGetDB( DB_SLAVE
);
2229 $s = $dbr->selectRow( array('page', 'text'),
2230 array( 'LENGTH(old_text) AS len', 'page_namespace', 'page_is_redirect' ),
2231 array( 'page_id' => $articleID, "page.page_latest=text.old_id" ),
2233 if ( $s == false OR $s->page_is_redirect
OR $s->page_namespace
!= 0 ) {
2237 return ( $size < $threshold );