9 * Need the CacheManager to be loaded
11 require_once ( 'CacheManager.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.
30 var $mContent, $mContentLoaded;
31 var $mUser, $mTimestamp, $mUserText;
32 var $mCounter, $mComment, $mCountAdjustment;
33 var $mMinorEdit, $mRedirectedFrom;
34 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 * Get revision text associated with an old or archive row
64 * $row is usually an object from wfFetchRow(), both the flags and the text
65 * field must be included
67 * @param integer $row Id of a row
68 * @param string $prefix table prefix (default 'old_')
69 * @return string $text|false the text requested
71 function getRevisionText( $row, $prefix = 'old_' ) {
73 $textField = $prefix . 'text';
74 $flagsField = $prefix . 'flags';
76 if( isset( $row->$flagsField ) ) {
77 $flags = explode( ',', $row->$flagsField );
82 if( isset( $row->$textField ) ) {
83 $text = $row->$textField;
88 if( in_array( 'gzip', $flags ) ) {
89 # Deal with optional compression of archived pages.
90 # This can be done periodically via maintenance/compressOld.php, and
91 # as pages are saved if $wgCompressRevisions is set.
92 $text = gzinflate( $text );
95 if( in_array( 'object', $flags ) ) {
96 # Generic compressed storage
97 $obj = unserialize( $text );
99 # Bugger, corrupted my test database by double-serializing
100 if ( !is_object( $obj ) ) {
101 $obj = unserialize( $obj );
104 $text = $obj->getText();
107 global $wgLegacyEncoding;
108 if( $wgLegacyEncoding && !in_array( 'utf-8', $flags ) ) {
109 # Old revisions kept around in a legacy encoding?
110 # Upconvert on demand.
111 global $wgInputEncoding, $wgContLang;
112 $text = $wgContLang->iconv( $wgLegacyEncoding, $wgInputEncoding, $text );
118 * If $wgCompressRevisions is enabled, we will compress data.
119 * The input string is modified in place.
120 * Return value is the flags field: contains 'gzip' if the
121 * data is compressed, and 'utf-8' if we're saving in UTF-8
125 * @param mixed $text reference to a text
128 function compressRevisionText( &$text ) {
129 global $wgCompressRevisions, $wgUseLatin1;
131 if( !$wgUseLatin1 ) {
132 # Revisions not marked this way will be converted
133 # on load if $wgLegacyCharset is set in the future.
136 if( $wgCompressRevisions ) {
137 if( function_exists( 'gzdeflate' ) ) {
138 $text = gzdeflate( $text );
141 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
144 return implode( ',', $flags );
148 * Note that getContent/loadContent may follow redirects if
149 * not told otherwise, and so may cause a change to mTitle.
152 * @return Return the text of this revision
154 function getContent( $noredir ) {
157 # Get variables from query string :P
158 $action = $wgRequest->getText( 'action', 'view' );
159 $section = $wgRequest->getText( 'section' );
161 $fname = 'Article::getContent';
162 wfProfileIn( $fname );
164 if ( 0 == $this->getID() ) {
165 if ( 'edit' == $action ) {
166 wfProfileOut( $fname );
167 return ''; # was "newarticletext", now moved above the box)
169 wfProfileOut( $fname );
170 return wfMsg( 'noarticletext' );
172 $this->loadContent( $noredir );
173 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
174 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
175 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
178 wfProfileOut( $fname );
179 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
181 if($action=='edit') {
183 if($section=='new') {
184 wfProfileOut( $fname );
188 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
189 # comments to be stripped as well)
190 $rv=$this->getSection($this->mContent
,$section);
191 wfProfileOut( $fname );
195 wfProfileOut( $fname );
196 return $this->mContent
;
202 * This function returns the text of a section, specified by a number ($section).
203 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
204 * the first section before any such heading (section 0).
206 * If a section contains subsections, these are also returned.
208 * @param string $text text to look in
209 * @param integer $section section number
210 * @return string text of the requested section
212 function getSection($text,$section) {
214 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
215 # comments to be stripped as well)
217 $parser=new Parser();
218 $parser->mOutputType
=OT_WIKI
;
219 $striptext=$parser->strip($text, $striparray, true);
221 # now that we can be sure that no pseudo-sections are in the source,
222 # split it up by section
225 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
227 PREG_SPLIT_DELIM_CAPTURE
);
231 $headline=$secs[$section*2-1];
232 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
235 # translate wiki heading into level
236 if(strpos($hlevel,'=')!==false) {
237 $hlevel=strlen($hlevel);
240 $rv=$headline. $secs[$section*2];
244 while(!empty($secs[$count*2-1]) && !$break) {
246 $subheadline=$secs[$count*2-1];
247 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
248 $subhlevel=$matches[1];
249 if(strpos($subhlevel,'=')!==false) {
250 $subhlevel=strlen($subhlevel);
252 if($subhlevel > $hlevel) {
253 $rv.=$subheadline.$secs[$count*2];
255 if($subhlevel <= $hlevel) {
262 # reinsert stripped tags
263 $rv=$parser->unstrip($rv,$striparray);
264 $rv=$parser->unstripNoWiki($rv,$striparray);
271 * Return an array of the columns of the "cur"-table
273 function &getCurContentFields() {
274 global $wgArticleCurContentFields;
275 if ( !$wgArticleCurContentFields ) {
276 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
277 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
279 return $wgArticleCurContentFields;
283 * Return an array of the columns of the "old"-table
285 function &getOldContentFields() {
286 global $wgArticleOldContentFields;
287 if ( !$wgArticleOldContentFields ) {
288 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
289 'old_user','old_user_text','old_comment','old_flags' );
291 return $wgArticleOldContentFields;
295 * Load the revision (including cur_text) into this object
297 function loadContent( $noredir = false ) {
298 global $wgOut, $wgRequest;
300 if ( $this->mContentLoaded
) return;
302 $dbr =& $this->getDB();
304 $oldid = $wgRequest->getVal( 'oldid' );
305 $redirect = $wgRequest->getVal( 'redirect' );
307 $fname = 'Article::loadContent';
309 # Pre-fill content with error message so that if something
310 # fails we'll have something telling us what we intended.
312 $t = $this->mTitle
->getPrefixedText();
313 if ( isset( $oldid ) ) {
314 $oldid = IntVal( $oldid );
315 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
316 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
320 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
322 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
323 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
331 if ( isset( $oldid ) ) {
332 $t .= ',oldid='.$oldid;
334 if ( isset( $redirect ) ) {
335 $redirect = ($redirect == 'no') ?
'no' : 'yes';
336 $t .= ',redirect='.$redirect;
338 $this->mContent
= wfMsg( 'missingarticle', $t );
340 if ( ! $oldid ) { # Retrieve current version
341 $id = $this->getID();
342 if ( 0 == $id ) return;
344 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
345 $this->getSelectOptions() );
346 if ( $s === false ) {
350 # If we got a redirect, follow it (unless we've been told
351 # not to by either the function parameter or the query
352 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
353 $rt = Title
::newFromRedirect( $s->cur_text
);
354 # process if title object is valid and not special:userlogout
355 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
356 # Gotta hand redirects to special pages differently:
357 # Fill the HTTP response "Location" header and ignore
358 # the rest of the page we're on.
360 if ( $rt->getInterwiki() != '' ) {
361 $wgOut->redirect( $rt->getFullURL() ) ;
364 if ( $rt->getNamespace() == NS_SPECIAL
) {
365 $wgOut->redirect( $rt->getFullURL() );
368 $rid = $rt->getArticleID();
370 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
371 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
373 if ( $redirRow !== false ) {
374 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
382 $this->mContent
= $s->cur_text
;
383 $this->mUser
= $s->cur_user
;
384 $this->mUserText
= $s->cur_user_text
;
385 $this->mComment
= $s->cur_comment
;
386 $this->mCounter
= $s->cur_counter
;
387 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
388 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
389 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
390 $this->mTitle
->mRestrictionsLoaded
= true;
391 } else { # oldid set, retrieve historical version
392 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
393 $fname, $this->getSelectOptions() );
394 if ( $s === false ) {
398 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
399 $this->mTitle
->getDBkey() != $s->old_title
) {
400 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
401 $this->mTitle
= $oldTitle;
402 $wgTitle = $oldTitle;
404 $this->mContent
= Article
::getRevisionText( $s );
405 $this->mUser
= $s->old_user
;
406 $this->mUserText
= $s->old_user_text
;
407 $this->mComment
= $s->old_comment
;
409 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
411 $this->mContentLoaded
= true;
412 return $this->mContent
;
416 * Gets the article text without using so many damn globals
417 * Returns false on error
419 * @param integer $oldid
421 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
422 if ( $this->mContentLoaded
) {
423 return $this->mContent
;
425 $this->mContent
= false;
427 $fname = 'Article::getContentWithout';
428 $dbr =& $this->getDB();
430 if ( ! $oldid ) { # Retrieve current version
431 $id = $this->getID();
436 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
437 $fname, $this->getSelectOptions() );
438 if ( $s === false ) {
442 # If we got a redirect, follow it (unless we've been told
443 # not to by either the function parameter or the query
445 $rt = Title
::newFromRedirect( $s->cur_text
);
446 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
447 $rid = $rt->getArticleID();
449 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
450 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
452 if ( $redirRow !== false ) {
453 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
461 $this->mContent
= $s->cur_text
;
462 $this->mUser
= $s->cur_user
;
463 $this->mUserText
= $s->cur_user_text
;
464 $this->mComment
= $s->cur_comment
;
465 $this->mCounter
= $s->cur_counter
;
466 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
467 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
468 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
469 $this->mTitle
->mRestrictionsLoaded
= true;
470 } else { # oldid set, retrieve historical version
471 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
472 $fname, $this->getSelectOptions() );
473 if ( $s === false ) {
476 $this->mContent
= Article
::getRevisionText( $s );
477 $this->mUser
= $s->old_user
;
478 $this->mUserText
= $s->old_user_text
;
479 $this->mComment
= $s->old_comment
;
481 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
483 $this->mContentLoaded
= true;
484 return $this->mContent
;
488 * Read/write accessor to select FOR UPDATE
490 function forUpdate( $x = NULL ) {
491 return wfSetVar( $this->mForUpdate
, $x );
495 * Get the database which should be used for reads
498 if ( $this->mForUpdate
) {
499 return wfGetDB( DB_MASTER
);
501 return wfGetDB( DB_SLAVE
);
506 * Get options for all SELECT statements
507 * Can pass an option array, to which the class-wide options will be appended
509 function getSelectOptions( $options = '' ) {
510 if ( $this->mForUpdate
) {
512 $options[] = 'FOR UPDATE';
514 $options = 'FOR UPDATE';
521 * Return the Article ID
524 if( $this->mTitle
) {
525 return $this->mTitle
->getArticleID();
532 * Get the view count for this article
534 function getCount() {
535 if ( -1 == $this->mCounter
) {
536 $id = $this->getID();
537 $dbr =& $this->getDB();
538 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
539 'Article::getCount', $this->getSelectOptions() );
541 return $this->mCounter
;
545 * Would the given text make this article a "good" article (i.e.,
546 * suitable for including in the article count)?
548 function isCountable( $text ) {
549 global $wgUseCommaCount;
551 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
552 if ( $this->isRedirect( $text ) ) { return 0; }
553 $token = ($wgUseCommaCount ?
',' : '[[' );
554 if ( false === strstr( $text, $token ) ) { return 0; }
559 * Tests if the article text represents a redirect
561 function isRedirect( $text = false ) {
562 if ( $text === false ) {
563 $this->loadContent();
564 $titleObj = Title
::newFromRedirect( $this->mText
);
566 $titleObj = Title
::newFromRedirect( $text );
568 return $titleObj !== NULL;
572 * Loads everything from cur except cur_text
573 * This isn't necessary for all uses, so it's only done if needed.
576 function loadLastEdit() {
578 if ( -1 != $this->mUser
) return;
580 $fname = 'Article::loadLastEdit';
582 $dbr =& $this->getDB();
583 $s = $dbr->selectRow( 'cur',
584 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
585 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
587 if ( $s !== false ) {
588 $this->mUser
= $s->cur_user
;
589 $this->mUserText
= $s->cur_user_text
;
590 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
591 $this->mComment
= $s->cur_comment
;
592 $this->mMinorEdit
= $s->cur_minor_edit
;
596 function getTimestamp() {
597 $this->loadLastEdit();
598 return $this->mTimestamp
;
602 $this->loadLastEdit();
606 function getUserText() {
607 $this->loadLastEdit();
608 return $this->mUserText
;
611 function getComment() {
612 $this->loadLastEdit();
613 return $this->mComment
;
616 function getMinorEdit() {
617 $this->loadLastEdit();
618 return $this->mMinorEdit
;
621 function getContributors($limit = 0, $offset = 0) {
622 $fname = 'Article::getContributors';
624 # XXX: this is expensive; cache this info somewhere.
626 $title = $this->mTitle
;
628 $dbr =& $this->getDB();
629 $oldTable = $dbr->tableName( 'old' );
630 $userTable = $dbr->tableName( 'user' );
631 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
632 $ns = $title->getNamespace();
633 $user = $this->getUser();
635 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
636 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
637 WHERE old_namespace = $user
638 AND old_title = $encDBkey
639 AND old_user != $user
640 GROUP BY old_user, old_user_text, user_real_name
641 ORDER BY timestamp DESC";
643 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
644 $sql .= ' '. $this->getSelectOptions();
646 $res = $dbr->query($sql, $fname);
648 while ( $line = $dbr->fetchObject( $res ) ) {
649 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
652 $dbr->freeResult($res);
657 * This is the default action of the script: just view the page of
661 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol;
662 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
663 $sk = $wgUser->getSkin();
665 $fname = 'Article::view';
666 wfProfileIn( $fname );
667 # Get variables from query string
668 $oldid = $wgRequest->getVal( 'oldid' );
669 $diff = $wgRequest->getVal( 'diff' );
670 $rcid = $wgRequest->getVal( 'rcid' );
672 $wgOut->setArticleFlag( true );
673 $wgOut->setRobotpolicy( 'index,follow' );
674 # If we got diff and oldid in the query, we want to see a
675 # diff page instead of the article.
677 if ( !is_null( $diff ) ) {
678 require_once( 'DifferenceEngine.php' );
679 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
680 $de = new DifferenceEngine( $oldid, $diff, $rcid );
683 # Run view updates for current revision only
684 $this->viewUpdates();
686 wfProfileOut( $fname );
689 if ( empty( $oldid ) && $this->checkTouched() ) {
690 if( $wgOut->checkLastModified( $this->mTouched
) ){
691 wfProfileOut( $fname );
693 } else if ( $this->tryFileCache() ) {
694 # tell wgOut that output is taken care of
696 $this->viewUpdates();
697 wfProfileOut( $fname );
701 # Should the parser cache be used?
702 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
710 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
714 if ( !$outputDone ) {
715 $text = $this->getContent( false ); # May change mTitle by following a redirect
717 # Another whitelist check in case oldid or redirects are altering the title
718 if ( !$this->mTitle
->userCanRead() ) {
719 $wgOut->loginToUse();
725 # We're looking at an old revision
727 if ( !empty( $oldid ) ) {
728 $this->setOldSubtitle( $oldid );
729 $wgOut->setRobotpolicy( 'noindex,follow' );
731 if ( '' != $this->mRedirectedFrom
) {
732 $sk = $wgUser->getSkin();
733 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
735 $s = wfMsg( 'redirectedfrom', $redir );
736 $wgOut->setSubtitle( $s );
738 # Can't cache redirects
742 # wrap user css and user js in pre and don't parse
743 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
745 $this->mTitle
->getNamespace() == NS_USER
&&
746 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
748 $wgOut->addWikiText( wfMsg('clearyourcache'));
749 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
750 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
752 $imageUrl = $wgStylePath.'/common/images/redirect.png';
753 $targetUrl = $rt->escapeLocalURL();
754 $titleText = htmlspecialchars( $rt->getPrefixedText() );
755 $link = $sk->makeLinkObj( $rt );
756 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" />' .
757 '<span class="redirectText">'.$link.'</span>' );
758 } else if ( $pcache ) {
759 # Display content and save to parser cache
760 $wgOut->addPrimaryWikiText( $text, $this );
762 # Display content, don't attempt to save to parser cache
763 $wgOut->addWikiText( $text );
766 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
767 # If we have been passed an &rcid= parameter, we want to give the user a
768 # chance to mark this new article as patrolled.
769 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
770 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
772 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
773 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
774 'action=markpatrolled&rcid='.$rcid )
778 # Put link titles into the link cache
779 $wgOut->transformBuffer();
781 # Add link titles as META keywords
782 $wgOut->addMetaTags() ;
784 $this->viewUpdates();
785 wfProfileOut( $fname );
789 * Theoretically we could defer these whole insert and update
790 * functions for after display, but that's taking a big leap
791 * of faith, and we want to be able to report database
792 * errors at some point.
795 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
796 global $wgOut, $wgUser;
797 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
799 $fname = 'Article::insertNewArticle';
801 $this->mCountAdjustment
= $this->isCountable( $text );
803 $ns = $this->mTitle
->getNamespace();
804 $ttl = $this->mTitle
->getDBkey();
805 $text = $this->preSaveTransform( $text );
806 if ( $this->isRedirect( $text ) ) { $redir = 1; }
809 $now = wfTimestampNow();
810 $won = wfInvertTimestamp( $now );
813 $dbw =& wfGetDB( DB_MASTER
);
815 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
817 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
819 $dbw->insert( 'cur', array(
821 'cur_namespace' => $ns,
824 'cur_comment' => $summary,
825 'cur_user' => $wgUser->getID(),
826 'cur_timestamp' => $dbw->timestamp($now),
827 'cur_minor_edit' => $isminor,
829 'cur_restrictions' => '',
830 'cur_user_text' => $wgUser->getName(),
831 'cur_is_redirect' => $redir,
833 'cur_random' => $rand,
834 'cur_touched' => $dbw->timestamp($now),
835 'inverse_timestamp' => $won,
838 $newid = $dbw->insertId();
839 $this->mTitle
->resetArticleID( $newid );
841 Article
::onArticleCreate( $this->mTitle
);
842 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
845 if(!$this->mTitle
->userIsWatching()) $this->watch();
847 if ( $this->mTitle
->userIsWatching() ) {
852 # The talk page isn't in the regular link tables, so we need to update manually:
853 $talkns = $ns ^
1; # talk -> normal; normal -> talk
854 $dbw->update( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
855 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
857 # standard deferred updates
858 $this->editUpdates( $text );
860 $this->showArticle( $text, wfMsg( 'newarticle' ) );
865 * Side effects: loads last edit if $edittime is NULL
867 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
868 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
869 if(is_null($edittime)) {
870 $this->loadLastEdit();
871 $oldtext = $this->getContent( true );
873 $dbw =& wfGetDB( DB_MASTER
);
874 $ns = $this->mTitle
->getNamespace();
875 $title = $this->mTitle
->getDBkey();
876 $obj = $dbw->selectRow( 'old',
877 array( 'old_text','old_flags'),
878 array( 'old_namespace' => $ns, 'old_title' => $title,
879 'old_timestamp' => $dbw->timestamp($edittime)),
881 $oldtext = Article
::getRevisionText( $obj );
883 if ($section != '') {
884 if($section=='new') {
885 if($summary) $subject="== {$summary} ==\n\n";
886 $text=$oldtext."\n\n".$subject.$text;
889 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
890 # comments to be stripped as well)
892 $parser=new Parser();
893 $parser->mOutputType
=OT_WIKI
;
894 $oldtext=$parser->strip($oldtext, $striparray, true);
896 # now that we can be sure that no pseudo-sections are in the source,
898 # Unfortunately we can't simply do a preg_replace because that might
899 # replace the wrong section, so we have to use the section counter instead
900 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
901 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
902 $secs[$section*2]=$text."\n\n"; // replace with edited
904 # section 0 is top (intro) section
907 # headline of old section - we need to go through this section
908 # to determine if there are any subsections that now need to
909 # be erased, as the mother section has been replaced with
910 # the text of all subsections.
911 $headline=$secs[$section*2-1];
912 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
915 # determine headline level for wikimarkup headings
916 if(strpos($hlevel,'=')!==false) {
917 $hlevel=strlen($hlevel);
920 $secs[$section*2-1]=''; // erase old headline
923 while(!empty($secs[$count*2-1]) && !$break) {
925 $subheadline=$secs[$count*2-1];
927 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
928 $subhlevel=$matches[1];
929 if(strpos($subhlevel,'=')!==false) {
930 $subhlevel=strlen($subhlevel);
932 if($subhlevel > $hlevel) {
933 // erase old subsections
934 $secs[$count*2-1]='';
937 if($subhlevel <= $hlevel) {
945 $text=join('',$secs);
946 # reinsert the stuff that we stripped out earlier
947 $text=$parser->unstrip($text,$striparray);
948 $text=$parser->unstripNoWiki($text,$striparray);
956 * Change an existing article. Puts the previous version back into the old table, updates RC
957 * and all necessary caches, mostly via the deferred update array.
959 * It is possible to call this function from a command-line script, but note that you should
960 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
962 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
963 global $wgOut, $wgUser;
964 global $wgDBtransactions, $wgMwRedir;
965 global $wgUseSquid, $wgInternalServer;
967 $fname = 'Article::updateArticle';
970 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
971 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
972 if ( $this->isRedirect( $text ) ) {
973 # Remove all content but redirect
974 # This could be done by reconstructing the redirect from a title given by
975 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
977 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
979 $text = $m[1] . "\n";
984 $text = $this->preSaveTransform( $text );
985 $dbw =& wfGetDB( DB_MASTER
);
987 # Update article, but only if changed.
989 # It's important that we either rollback or complete, otherwise an attacker could
990 # overwrite cur entries by sending precisely timed user aborts. Random bored users
991 # could conceivably have the same effect, especially if cur is locked for long periods.
992 if( $wgDBtransactions ) {
993 $dbw->query( 'BEGIN', $fname );
995 $userAbort = ignore_user_abort( true );
998 $oldtext = $this->getContent( true );
1000 if ( 0 != strcmp( $text, $oldtext ) ) {
1001 $this->mCountAdjustment
= $this->isCountable( $text )
1002 - $this->isCountable( $oldtext );
1003 $now = wfTimestampNow();
1004 $won = wfInvertTimestamp( $now );
1006 # First update the cur row
1007 $dbw->update( 'cur',
1009 'cur_text' => $text,
1010 'cur_comment' => $summary,
1011 'cur_minor_edit' => $me2,
1012 'cur_user' => $wgUser->getID(),
1013 'cur_timestamp' => $dbw->timestamp($now),
1014 'cur_user_text' => $wgUser->getName(),
1015 'cur_is_redirect' => $redir,
1017 'cur_touched' => $dbw->timestamp($now),
1018 'inverse_timestamp' => $won
1019 ), array( /* WHERE */
1020 'cur_id' => $this->getID(),
1021 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1025 if( $dbw->affectedRows() == 0 ) {
1026 /* Belated edit conflict! Run away!! */
1029 # Now insert the previous revision into old
1031 # This overwrites $oldtext if revision compression is on
1032 $flags = Article
::compressRevisionText( $oldtext );
1034 $dbw->insert( 'old',
1036 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1037 'old_namespace' => $this->mTitle
->getNamespace(),
1038 'old_title' => $this->mTitle
->getDBkey(),
1039 'old_text' => $oldtext,
1040 'old_comment' => $this->getComment(),
1041 'old_user' => $this->getUser(),
1042 'old_user_text' => $this->getUserText(),
1043 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1044 'old_minor_edit' => $me1,
1045 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1046 'old_flags' => $flags,
1050 $oldid = $dbw->insertId();
1052 $bot = (int)($wgUser->isBot() ||
$forceBot);
1053 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1054 $oldid, $this->getTimestamp(), $bot );
1055 Article
::onArticleEdit( $this->mTitle
);
1059 if( $wgDBtransactions ) {
1060 $dbw->query( 'COMMIT', $fname );
1062 ignore_user_abort( $userAbort );
1067 if (!$this->mTitle
->userIsWatching()) $this->watch();
1069 if ( $this->mTitle
->userIsWatching() ) {
1073 # standard deferred updates
1074 $this->editUpdates( $text );
1078 # Template namespace
1079 # Purge all articles linking here
1080 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1081 $titles = $this->mTitle
->getLinksTo();
1082 Title
::touchArray( $titles );
1083 if ( $wgUseSquid ) {
1084 foreach ( $titles as $title ) {
1085 $urls[] = $title->getInternalURL();
1091 if ( $wgUseSquid ) {
1092 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1093 $u = new SquidUpdate( $urls );
1097 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1103 * After we've either updated or inserted the article, update
1104 * the link tables and redirect to the new page.
1106 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1107 global $wgOut, $wgUser, $wgLinkCache;
1109 $wgLinkCache = new LinkCache();
1111 $wgLinkCache->forUpdate( true );
1113 # Get old version of link table to allow incremental link updates
1114 $wgLinkCache->preFill( $this->mTitle
);
1115 $wgLinkCache->clear();
1117 # Parse the text and replace links with placeholders
1118 $wgOut = new OutputPage();
1119 $wgOut->addWikiText( $text );
1121 # Look up the links in the DB and add them to the link cache
1122 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1124 if( $this->isRedirect( $text ) )
1128 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1133 * @todo document this function a bit more
1135 function validate () {
1136 global $wgOut, $wgUseValidation;
1137 if( $wgUseValidation ) {
1138 require_once ( 'SpecialValidate.php' ) ;
1139 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1140 $wgOut->setRobotpolicy( 'noindex,follow' );
1141 if( $this->mTitle
->getNamespace() != 0 ) {
1142 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1145 $v = new Validation
;
1146 $v->validate_form( $this->mTitle
->getDBkey() );
1148 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1153 * Mark this particular edit as patrolled
1155 function markpatrolled() {
1156 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1157 $wgOut->setRobotpolicy( 'noindex,follow' );
1159 if ( !$wgUseRCPatrol )
1161 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1164 if ( $wgUser->getID() == 0 )
1166 $wgOut->loginToUse();
1169 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1171 $wgOut->sysopRequired();
1174 $rcid = $wgRequest->getVal( 'rcid' );
1175 if ( !is_null ( $rcid ) )
1177 RecentChange
::markPatrolled( $rcid );
1178 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1179 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1180 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1184 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1190 * Add or remove this page to my watchlist based on value of $add
1192 function watch( $add = true ) {
1193 global $wgUser, $wgOut;
1194 global $wgDeferredUpdateList;
1196 if ( 0 == $wgUser->getID() ) {
1197 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1200 if ( wfReadOnly() ) {
1201 $wgOut->readOnlyPage();
1205 $wgUser->addWatch( $this->mTitle
);
1207 $wgUser->removeWatch( $this->mTitle
);
1209 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1210 $wgOut->setRobotpolicy( 'noindex,follow' );
1212 $sk = $wgUser->getSkin() ;
1213 $link = $this->mTitle
->getPrefixedText();
1216 $text = wfMsg( 'addedwatchtext', $link );
1218 $text = wfMsg( 'removedwatchtext', $link );
1219 $wgOut->addWikiText( $text );
1221 $up = new UserUpdate();
1222 array_push( $wgDeferredUpdateList, $up );
1224 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1228 * Stop watching a page, it act just like a call to watch(false)
1230 function unwatch() {
1231 $this->watch( false );
1237 function protect( $limit = 'sysop' ) {
1238 global $wgUser, $wgOut, $wgRequest;
1240 if ( ! $wgUser->isAllowed('protect') ) {
1241 $wgOut->sysopRequired();
1244 if ( wfReadOnly() ) {
1245 $wgOut->readOnlyPage();
1248 $id = $this->mTitle
->getArticleID();
1250 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1254 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1255 $reason = $wgRequest->getText( 'wpReasonProtect' );
1258 $dbw =& wfGetDB( DB_MASTER
);
1259 $dbw->update( 'cur',
1261 'cur_touched' => $dbw->timestamp(),
1262 'cur_restrictions' => (string)$limit
1263 ), array( /* WHERE */
1265 ), 'Article::protect'
1268 $log = new LogPage( 'protect' );
1269 if ( $limit === '' ) {
1270 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1272 $log->addEntry( 'protect', $this->mTitle
, $reason );
1274 $wgOut->redirect( $this->mTitle
->getFullURL() );
1277 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1278 return $this->confirmProtect( '', $reason, $limit );
1283 * Output protection confirmation dialog
1285 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1288 wfDebug( "Article::confirmProtect\n" );
1290 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1291 $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 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1309 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1312 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1315 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1319 <label for='wpReasonProtect'>{$protcom}:</label>
1322 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1330 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1333 <label for='wpConfirmProtect'>{$check}</label>
1339 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1345 $wgOut->returnToMain( false );
1349 * Unprotect the pages
1351 function unprotect() {
1352 return $this->protect( '' );
1356 * UI entry point for page deletion
1359 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1360 $fname = 'Article::delete';
1361 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1362 $reason = $wgRequest->getText( 'wpReason' );
1364 # This code desperately needs to be totally rewritten
1367 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1368 $wgOut->sysopRequired();
1371 if ( wfReadOnly() ) {
1372 $wgOut->readOnlyPage();
1376 # Better double-check that it hasn't been deleted yet!
1377 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1378 if ( ( '' == trim( $this->mTitle
->getText() ) )
1379 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1380 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1385 $this->doDelete( $reason );
1389 # determine whether this page has earlier revisions
1390 # and insert a warning if it does
1391 # we select the text because it might be useful below
1392 $dbr =& $this->getDB();
1393 $ns = $this->mTitle
->getNamespace();
1394 $title = $this->mTitle
->getDBkey();
1395 $old = $dbr->selectRow( 'old',
1396 array( 'old_text', 'old_flags' ),
1398 'old_namespace' => $ns,
1399 'old_title' => $title,
1400 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1403 if( $old !== false && !$confirm ) {
1404 $skin=$wgUser->getSkin();
1405 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1406 $wgOut->addHTML( $skin->historyLink() .'</b>');
1410 $s = $dbr->selectRow( 'cur',
1411 array( 'cur_text' ),
1413 'cur_namespace' => $ns,
1414 'cur_title' => $title,
1415 ), $fname, $this->getSelectOptions()
1418 if( $s !== false ) {
1419 # if this is a mini-text, we can paste part of it into the deletion reason
1421 #if this is empty, an earlier revision may contain "useful" text
1423 if($s->cur_text
!= '') {
1427 $text = Article
::getRevisionText( $old );
1433 $length=strlen($text);
1435 # this should not happen, since it is not possible to store an empty, new
1436 # page. Let's insert a standard text in case it does, though
1437 if($length == 0 && $reason === '') {
1438 $reason = wfMsg('exblank');
1441 if($length < 500 && $reason === '') {
1443 # comment field=255, let's grep the first 150 to have some user
1445 $text=substr($text,0,150);
1446 # let's strip out newlines and HTML tags
1447 $text=preg_replace('/\"/',"'",$text);
1448 $text=preg_replace('/\</','<',$text);
1449 $text=preg_replace('/\>/','>',$text);
1450 $text=preg_replace("/[\n\r]/",'',$text);
1452 $reason=wfMsg('excontent'). " '".$text;
1454 $reason=wfMsg('exbeforeblank') . " '".$text;
1456 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1461 return $this->confirmDelete( '', $reason );
1465 * Output deletion confirmation dialog
1467 function confirmDelete( $par, $reason ) {
1470 wfDebug( "Article::confirmDelete\n" );
1472 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1473 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1474 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1475 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1477 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1479 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1480 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1481 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1484 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1488 <label for='wpReason'>{$delcom}:</label>
1491 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1499 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1502 <label for='wpConfirm'>{$check}</label>
1508 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1514 $wgOut->returnToMain( false );
1519 * Perform a deletion and output success or failure messages
1521 function doDelete( $reason ) {
1522 global $wgOut, $wgUser, $wgContLang;
1523 $fname = 'Article::doDelete';
1524 wfDebug( $fname."\n" );
1526 if ( $this->doDeleteArticle( $reason ) ) {
1527 $deleted = $this->mTitle
->getPrefixedText();
1529 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1530 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1532 $sk = $wgUser->getSkin();
1533 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1534 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1536 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1538 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1539 $wgOut->returnToMain( false );
1541 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1546 * Back-end article deletion
1547 * Deletes the article with database consistency, writes logs, purges caches
1550 function doDeleteArticle( $reason ) {
1552 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1554 $fname = 'Article::doDeleteArticle';
1555 wfDebug( $fname."\n" );
1557 $dbw =& wfGetDB( DB_MASTER
);
1558 $ns = $this->mTitle
->getNamespace();
1559 $t = $this->mTitle
->getDBkey();
1560 $id = $this->mTitle
->getArticleID();
1562 if ( $t == '' ||
$id == 0 ) {
1566 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1567 array_push( $wgDeferredUpdateList, $u );
1569 $linksTo = $this->mTitle
->getLinksTo();
1572 if ( $wgUseSquid ) {
1574 $this->mTitle
->getInternalURL(),
1575 $this->mTitle
->getInternalURL( 'history' )
1577 foreach ( $linksTo as $linkTo ) {
1578 $urls[] = $linkTo->getInternalURL();
1581 $u = new SquidUpdate( $urls );
1582 array_push( $wgDeferredUpdateList, $u );
1586 # Client and file cache invalidation
1587 Title
::touchArray( $linksTo );
1589 # Move article and history to the "archive" table
1590 $archiveTable = $dbw->tableName( 'archive' );
1591 $oldTable = $dbw->tableName( 'old' );
1592 $curTable = $dbw->tableName( 'cur' );
1593 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1594 $linksTable = $dbw->tableName( 'links' );
1595 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1597 $dbw->insertSelect( 'archive', 'cur',
1599 'ar_namespace' => 'cur_namespace',
1600 'ar_title' => 'cur_title',
1601 'ar_text' => 'cur_text',
1602 'ar_comment' => 'cur_comment',
1603 'ar_user' => 'cur_user',
1604 'ar_user_text' => 'cur_user_text',
1605 'ar_timestamp' => 'cur_timestamp',
1606 'ar_minor_edit' => 'cur_minor_edit',
1609 'cur_namespace' => $ns,
1614 $dbw->insertSelect( 'archive', 'old',
1616 'ar_namespace' => 'old_namespace',
1617 'ar_title' => 'old_title',
1618 'ar_text' => 'old_text',
1619 'ar_comment' => 'old_comment',
1620 'ar_user' => 'old_user',
1621 'ar_user_text' => 'old_user_text',
1622 'ar_timestamp' => 'old_timestamp',
1623 'ar_minor_edit' => 'old_minor_edit',
1624 'ar_flags' => 'old_flags'
1626 'old_namespace' => $ns,
1631 # Now that it's safely backed up, delete it
1633 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1634 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1635 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1637 # Finally, clean up the link tables
1638 $t = $this->mTitle
->getPrefixedDBkey();
1640 Article
::onArticleDelete( $this->mTitle
);
1642 # Insert broken links
1643 $brokenLinks = array();
1644 foreach ( $linksTo as $titleObj ) {
1645 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1646 $linkID = $titleObj->getArticleID();
1647 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1649 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1652 $dbw->delete( 'links', array( 'l_to' => $id ) );
1653 $dbw->delete( 'links', array( 'l_from' => $id ) );
1654 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1655 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1656 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1659 $log = new LogPage( 'delete' );
1660 $log->addEntry( 'delete', $this->mTitle
, $reason );
1662 # Clear the cached article id so the interface doesn't act like we exist
1663 $this->mTitle
->resetArticleID( 0 );
1664 $this->mTitle
->mArticleID
= 0;
1669 * Revert a modification
1671 function rollback() {
1672 global $wgUser, $wgOut, $wgRequest;
1673 $fname = 'Article::rollback';
1675 if ( ! $wgUser->isAllowed('rollback') ) {
1676 $wgOut->sysopRequired();
1679 if ( wfReadOnly() ) {
1680 $wgOut->readOnlyPage( $this->getContent( true ) );
1683 $dbw =& wfGetDB( DB_MASTER
);
1685 # Enhanced rollback, marks edits rc_bot=1
1686 $bot = $wgRequest->getBool( 'bot' );
1688 # Replace all this user's current edits with the next one down
1689 $tt = $this->mTitle
->getDBKey();
1690 $n = $this->mTitle
->getNamespace();
1692 # Get the last editor, lock table exclusively
1693 $s = $dbw->selectRow( 'cur',
1694 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1695 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1696 $fname, 'FOR UPDATE'
1698 if( $s === false ) {
1700 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1703 $ut = $dbw->strencode( $s->cur_user_text
);
1704 $uid = $s->cur_user
;
1707 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1708 if( $from != $s->cur_user_text
) {
1709 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1710 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1711 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1712 htmlspecialchars( $from ),
1713 htmlspecialchars( $s->cur_user_text
) ) );
1714 if($s->cur_comment
!= '') {
1716 wfMsg('editcomment',
1717 htmlspecialchars( $s->cur_comment
) ) );
1722 # Get the last edit not by this guy
1723 $s = $dbw->selectRow( 'old',
1724 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1726 'old_namespace' => $n,
1728 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1729 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1731 if( $s === false ) {
1733 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1734 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1739 # Mark all reverted edits as bot
1740 $dbw->update( 'recentchanges',
1743 ), array( /* WHERE */
1745 "rc_timestamp > '{$s->old_timestamp}'",
1751 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1752 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1753 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1754 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1755 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1756 Article
::onArticleEdit( $this->mTitle
);
1757 $wgOut->returnToMain( false );
1762 * Do standard deferred updates after page view
1765 function viewUpdates() {
1766 global $wgDeferredUpdateList;
1767 if ( 0 != $this->getID() ) {
1768 global $wgDisableCounters;
1769 if( !$wgDisableCounters ) {
1770 Article
::incViewCount( $this->getID() );
1771 $u = new SiteStatsUpdate( 1, 0, 0 );
1772 array_push( $wgDeferredUpdateList, $u );
1775 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1776 $this->mTitle
->getDBkey() );
1777 array_push( $wgDeferredUpdateList, $u );
1781 * Do standard deferred updates after page edit.
1782 * Every 1000th edit, prune the recent changes table.
1784 * @param string $text
1786 function editUpdates( $text ) {
1787 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1788 global $wgMessageCache;
1791 if ( 0 == mt_rand( 0, 999 ) ) {
1792 $dbw =& wfGetDB( DB_MASTER
);
1793 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1794 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1795 $dbw->query( $sql );
1797 $id = $this->getID();
1798 $title = $this->mTitle
->getPrefixedDBkey();
1799 $shortTitle = $this->mTitle
->getDBkey();
1801 $adj = $this->mCountAdjustment
;
1804 $u = new LinksUpdate( $id, $title );
1805 array_push( $wgDeferredUpdateList, $u );
1806 $u = new SiteStatsUpdate( 0, 1, $adj );
1807 array_push( $wgDeferredUpdateList, $u );
1808 $u = new SearchUpdate( $id, $title, $text );
1809 array_push( $wgDeferredUpdateList, $u );
1811 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1812 array_push( $wgDeferredUpdateList, $u );
1814 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1815 $wgMessageCache->replace( $shortTitle, $text );
1821 * @todo document this function
1823 * @param string $oldid Revision ID of this article revision
1825 function setOldSubtitle( $oldid=0 ) {
1826 global $wgLang, $wgOut, $wgUser;
1828 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1829 $sk = $wgUser->getSkin();
1830 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1831 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1832 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1833 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1834 $wgOut->setSubtitle( $r );
1838 * This function is called right before saving the wikitext,
1839 * so we can do things like signatures and links-in-context.
1841 * @param string $text
1843 function preSaveTransform( $text ) {
1844 global $wgParser, $wgUser;
1845 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1848 /* Caching functions */
1851 * checkLastModified returns true if it has taken care of all
1852 * output to the client that is necessary for this request.
1853 * (that is, it has sent a cached version of the page)
1855 function tryFileCache() {
1856 static $called = false;
1858 wfDebug( " tryFileCache() -- called twice!?\n" );
1862 if($this->isFileCacheable()) {
1863 $touched = $this->mTouched
;
1864 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1865 # Expire the main page quicker
1866 $expire = wfUnix2Timestamp( time() - 3600 );
1867 $touched = max( $expire, $touched );
1869 $cache = new CacheManager( $this->mTitle
);
1870 if($cache->isFileCacheGood( $touched )) {
1872 wfDebug( " tryFileCache() - about to load\n" );
1873 $cache->loadFromFileCache();
1876 wfDebug( " tryFileCache() - starting buffer\n" );
1877 ob_start( array(&$cache, 'saveToFileCache' ) );
1880 wfDebug( " tryFileCache() - not cacheable\n" );
1885 * Check if the page can be cached
1888 function isFileCacheable() {
1889 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1890 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1892 return $wgUseFileCache
1893 and (!$wgShowIPinHeader)
1894 and ($this->getID() != 0)
1895 and ($wgUser->getId() == 0)
1896 and (!$wgUser->getNewtalk())
1897 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1898 and (empty( $action ) ||
$action == 'view')
1899 and (!isset($oldid))
1901 and (!isset($redirect))
1902 and (!isset($printable))
1903 and (!$this->mRedirectedFrom
);
1907 * Loads cur_touched and returns a value indicating if it should be used
1910 function checkTouched() {
1911 $fname = 'Article::checkTouched';
1912 $id = $this->getID();
1913 $dbr =& $this->getDB();
1914 $s = $dbr->selectRow( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1915 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1916 if( $s !== false ) {
1917 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1918 return !$s->cur_is_redirect
;
1925 * Edit an article without doing all that other stuff
1927 * @param string $text text submitted
1928 * @param string $comment comment submitted
1929 * @param integer $minor whereas it's a minor modification
1931 function quickEdit( $text, $comment = '', $minor = 0 ) {
1933 $fname = 'Article::quickEdit';
1934 wfProfileIn( $fname );
1936 $dbw =& wfGetDB( DB_MASTER
);
1937 $ns = $this->mTitle
->getNamespace();
1938 $dbkey = $this->mTitle
->getDBkey();
1939 $encDbKey = $dbw->strencode( $dbkey );
1940 $timestamp = wfTimestampNow();
1943 $dbw->insertSelect( 'old', 'cur',
1945 'old_namespace' => 'cur_namespace',
1946 'old_title' => 'cur_title',
1947 'old_text' => 'cur_text',
1948 'old_comment' => 'cur_comment',
1949 'old_user' => 'cur_user',
1950 'old_user_text' => 'cur_user_text',
1951 'old_timestamp' => 'cur_timestamp',
1952 'inverse_timestamp' => '99999999999999-cur_timestamp',
1954 'cur_namespace' => $ns,
1955 'cur_title' => $dbkey,
1959 # Use the affected row count to determine if the article is new
1960 $numRows = $dbw->affectedRows();
1962 # Make an array of fields to be inserted
1964 'cur_text' => $text,
1965 'cur_timestamp' => $timestamp,
1966 'cur_user' => $wgUser->getID(),
1967 'cur_user_text' => $wgUser->getName(),
1968 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1969 'cur_comment' => $comment,
1970 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
1971 'cur_minor_edit' => intval($minor),
1972 'cur_touched' => $dbw->timestamp($timestamp),
1977 $fields['cur_is_new'] = 0;
1978 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1980 # Insert new article
1981 $fields['cur_is_new'] = 1;
1982 $fields['cur_namespace'] = $ns;
1983 $fields['cur_title'] = $dbkey;
1984 $fields['cur_random'] = $rand = wfRandom();
1985 $dbw->insert( 'cur', $fields, $fname );
1987 wfProfileOut( $fname );
1991 * Used to increment the view counter
1994 * @param integer $id article id
1996 function incViewCount( $id ) {
1997 $id = intval( $id );
1998 global $wgHitcounterUpdateFreq;
2000 $dbw =& wfGetDB( DB_MASTER
);
2001 $curTable = $dbw->tableName( 'cur' );
2002 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2003 $acchitsTable = $dbw->tableName( 'acchits' );
2005 if( $wgHitcounterUpdateFreq <= 1 ){ //
2006 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2010 # Not important enough to warrant an error page in case of failure
2011 $oldignore = $dbw->ignoreErrors( true );
2013 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2015 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2016 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2017 # Most of the time (or on SQL errors), skip row count check
2018 $dbw->ignoreErrors( $oldignore );
2022 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2023 $row = $dbw->fetchObject( $res );
2024 $rown = intval( $row->n
);
2025 if( $rown >= $wgHitcounterUpdateFreq ){
2026 wfProfileIn( 'Article::incViewCount-collect' );
2027 $old_user_abort = ignore_user_abort( true );
2029 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2030 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2031 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2033 $dbw->query("DELETE FROM $hitcounterTable");
2034 $dbw->query('UNLOCK TABLES');
2035 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2036 'WHERE cur_id = hc_id');
2037 $dbw->query("DROP TABLE $acchitsTable");
2039 ignore_user_abort( $old_user_abort );
2040 wfProfileOut( 'Article::incViewCount-collect' );
2042 $dbw->ignoreErrors( $oldignore );
2046 * The onArticle*() functions are supposed to be a kind of hooks
2047 * which should be called whenever any of the specified actions
2050 * This is a good place to put code to clear caches, for instance.
2052 * This is called on page move and undelete, as well as edit
2054 * @param $title_obj a title object
2057 function onArticleCreate($title_obj) {
2058 global $wgUseSquid, $wgDeferredUpdateList;
2060 $titles = $title_obj->getBrokenLinksTo();
2063 if ( $wgUseSquid ) {
2064 $urls = $title_obj->getSquidURLs();
2065 foreach ( $titles as $linkTitle ) {
2066 $urls[] = $linkTitle->getInternalURL();
2068 $u = new SquidUpdate( $urls );
2069 array_push( $wgDeferredUpdateList, $u );
2072 # Clear persistent link cache
2073 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2076 function onArticleDelete($title_obj) {
2077 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2079 function onArticleEdit($title_obj) {
2080 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2085 * Info about this page
2088 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2089 $fname = 'Article::info';
2091 if ( !$wgAllowPageInfo ) {
2092 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2096 $dbr =& $this->getDB();
2098 $basenamespace = $wgTitle->getNamespace() & (~
1);
2099 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2100 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2101 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2102 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2103 $wgOut->setPagetitle( $fullTitle );
2104 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2106 # first, see if the page exists at all.
2107 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2109 $wgOut->addHTML( wfMsg('noarticletext') );
2111 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2112 $this->getSelectOptions() );
2113 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2114 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2115 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2117 # to find number of distinct authors, we need to do some
2118 # funny stuff because of the cur/old table split:
2119 # - first, find the name of the 'cur' author
2120 # - then, find the number of *other* authors in 'old'
2123 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2124 $this->getSelectOptions() );
2126 # find number of 'old' authors excluding 'cur' author
2127 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2128 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2129 $this->getSelectOptions() ) +
1;
2131 # now for the Talk page ...
2132 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2133 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2136 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2140 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2141 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2143 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2147 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2148 $this->getSelectOptions() );
2149 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2150 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2151 $fname, $this->getSelectOptions() );
2153 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );