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_' ) {
72 $fname = 'Article::getRevisionText';
73 wfProfileIn( $fname );
76 $textField = $prefix . 'text';
77 $flagsField = $prefix . 'flags';
79 if( isset( $row->$flagsField ) ) {
80 $flags = explode( ',', $row->$flagsField );
85 if( isset( $row->$textField ) ) {
86 $text = $row->$textField;
91 if( in_array( 'gzip', $flags ) ) {
92 # Deal with optional compression of archived pages.
93 # This can be done periodically via maintenance/compressOld.php, and
94 # as pages are saved if $wgCompressRevisions is set.
95 $text = gzinflate( $text );
98 if( in_array( 'object', $flags ) ) {
99 # Generic compressed storage
100 $obj = unserialize( $text );
102 # Bugger, corrupted my test database by double-serializing
103 if ( !is_object( $obj ) ) {
104 $obj = unserialize( $obj );
107 $text = $obj->getText();
110 global $wgLegacyEncoding;
111 if( $wgLegacyEncoding && !in_array( 'utf-8', $flags ) ) {
112 # Old revisions kept around in a legacy encoding?
113 # Upconvert on demand.
114 global $wgInputEncoding, $wgContLang;
115 $text = $wgContLang->iconv( $wgLegacyEncoding, $wgInputEncoding, $text );
117 wfProfileOut( $fname );
122 * If $wgCompressRevisions is enabled, we will compress data.
123 * The input string is modified in place.
124 * Return value is the flags field: contains 'gzip' if the
125 * data is compressed, and 'utf-8' if we're saving in UTF-8
129 * @param mixed $text reference to a text
132 function compressRevisionText( &$text ) {
133 global $wgCompressRevisions, $wgUseLatin1;
135 if( !$wgUseLatin1 ) {
136 # Revisions not marked this way will be converted
137 # on load if $wgLegacyCharset is set in the future.
140 if( $wgCompressRevisions ) {
141 if( function_exists( 'gzdeflate' ) ) {
142 $text = gzdeflate( $text );
145 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
148 return implode( ',', $flags );
152 * Note that getContent/loadContent may follow redirects if
153 * not told otherwise, and so may cause a change to mTitle.
156 * @return Return the text of this revision
158 function getContent( $noredir ) {
161 # Get variables from query string :P
162 $action = $wgRequest->getText( 'action', 'view' );
163 $section = $wgRequest->getText( 'section' );
165 $fname = 'Article::getContent';
166 wfProfileIn( $fname );
168 if ( 0 == $this->getID() ) {
169 if ( 'edit' == $action ) {
170 wfProfileOut( $fname );
171 return ''; # was "newarticletext", now moved above the box)
173 wfProfileOut( $fname );
174 return wfMsg( 'noarticletext' );
176 $this->loadContent( $noredir );
177 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
178 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
179 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
182 wfProfileOut( $fname );
183 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
185 if($action=='edit') {
187 if($section=='new') {
188 wfProfileOut( $fname );
192 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
193 # comments to be stripped as well)
194 $rv=$this->getSection($this->mContent
,$section);
195 wfProfileOut( $fname );
199 wfProfileOut( $fname );
200 return $this->mContent
;
206 * This function returns the text of a section, specified by a number ($section).
207 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
208 * the first section before any such heading (section 0).
210 * If a section contains subsections, these are also returned.
212 * @param string $text text to look in
213 * @param integer $section section number
214 * @return string text of the requested section
216 function getSection($text,$section) {
218 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
219 # comments to be stripped as well)
221 $parser=new Parser();
222 $parser->mOutputType
=OT_WIKI
;
223 $striptext=$parser->strip($text, $striparray, true);
225 # now that we can be sure that no pseudo-sections are in the source,
226 # split it up by section
229 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
231 PREG_SPLIT_DELIM_CAPTURE
);
235 $headline=$secs[$section*2-1];
236 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
239 # translate wiki heading into level
240 if(strpos($hlevel,'=')!==false) {
241 $hlevel=strlen($hlevel);
244 $rv=$headline. $secs[$section*2];
248 while(!empty($secs[$count*2-1]) && !$break) {
250 $subheadline=$secs[$count*2-1];
251 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
252 $subhlevel=$matches[1];
253 if(strpos($subhlevel,'=')!==false) {
254 $subhlevel=strlen($subhlevel);
256 if($subhlevel > $hlevel) {
257 $rv.=$subheadline.$secs[$count*2];
259 if($subhlevel <= $hlevel) {
266 # reinsert stripped tags
267 $rv=$parser->unstrip($rv,$striparray);
268 $rv=$parser->unstripNoWiki($rv,$striparray);
275 * Return an array of the columns of the "cur"-table
277 function &getCurContentFields() {
278 global $wgArticleCurContentFields;
279 if ( !$wgArticleCurContentFields ) {
280 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
281 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
283 return $wgArticleCurContentFields;
287 * Return an array of the columns of the "old"-table
289 function &getOldContentFields() {
290 global $wgArticleOldContentFields;
291 if ( !$wgArticleOldContentFields ) {
292 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
293 'old_user','old_user_text','old_comment','old_flags' );
295 return $wgArticleOldContentFields;
299 * Return the oldid of the article that is to be shown.
300 * For requests with a "direction", this is not the oldid of the
303 function getOldID() {
304 global $wgRequest, $wgOut;
307 if ( isset( $lastid ) ) {
311 $oldid = $wgRequest->getVal( 'oldid' );
312 if ( isset( $oldid ) ) {
313 $dbr =& $this->getDB();
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 );
332 return @$oldid; # "@" to be able to return "unset" without PHP complaining
337 * Load the revision (including cur_text) into this object
339 function loadContent( $noredir = false ) {
340 global $wgOut, $wgRequest;
342 if ( $this->mContentLoaded
) return;
344 $dbr =& $this->getDB();
346 $oldid = $this->getOldID();
347 $redirect = $wgRequest->getVal( 'redirect' );
349 $fname = 'Article::loadContent';
351 # Pre-fill content with error message so that if something
352 # fails we'll have something telling us what we intended.
354 $t = $this->mTitle
->getPrefixedText();
356 if ( isset( $oldid ) ) {
357 $t .= ',oldid='.$oldid;
359 if ( isset( $redirect ) ) {
360 $redirect = ($redirect == 'no') ?
'no' : 'yes';
361 $t .= ',redirect='.$redirect;
363 $this->mContent
= wfMsg( 'missingarticle', $t );
365 if ( ! $oldid ) { # Retrieve current version
366 $id = $this->getID();
367 if ( 0 == $id ) return;
369 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
370 $this->getSelectOptions() );
371 if ( $s === false ) {
375 # If we got a redirect, follow it (unless we've been told
376 # not to by either the function parameter or the query
377 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
378 $rt = Title
::newFromRedirect( $s->cur_text
);
379 # process if title object is valid and not special:userlogout
380 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
381 # Gotta hand redirects to special pages differently:
382 # Fill the HTTP response "Location" header and ignore
383 # the rest of the page we're on.
385 if ( $rt->getInterwiki() != '' ) {
386 $wgOut->redirect( $rt->getFullURL() ) ;
389 if ( $rt->getNamespace() == NS_SPECIAL
) {
390 $wgOut->redirect( $rt->getFullURL() );
393 $rid = $rt->getArticleID();
395 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
396 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
398 if ( $redirRow !== false ) {
399 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
407 $this->mContent
= $s->cur_text
;
408 $this->mUser
= $s->cur_user
;
409 $this->mUserText
= $s->cur_user_text
;
410 $this->mComment
= $s->cur_comment
;
411 $this->mCounter
= $s->cur_counter
;
412 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
413 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
414 $this->mTitle
->loadRestrictions( $s->cur_restrictions
);
415 } else { # oldid set, retrieve historical version
416 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
417 $fname, $this->getSelectOptions() );
418 if ( $s === false ) {
422 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
423 $this->mTitle
->getDBkey() != $s->old_title
) {
424 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
425 $this->mTitle
= $oldTitle;
426 $wgTitle = $oldTitle;
428 $this->mContent
= Article
::getRevisionText( $s );
429 $this->mUser
= $s->old_user
;
430 $this->mUserText
= $s->old_user_text
;
431 $this->mComment
= $s->old_comment
;
433 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
435 $this->mContentLoaded
= true;
436 return $this->mContent
;
440 * Gets the article text without using so many damn globals
441 * Returns false on error
443 * @param integer $oldid
445 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
446 if ( $this->mContentLoaded
) {
447 return $this->mContent
;
449 $this->mContent
= false;
451 $fname = 'Article::getContentWithout';
452 $dbr =& $this->getDB();
454 if ( ! $oldid ) { # Retrieve current version
455 $id = $this->getID();
460 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
461 $fname, $this->getSelectOptions() );
462 if ( $s === false ) {
466 # If we got a redirect, follow it (unless we've been told
467 # not to by either the function parameter or the query
469 $rt = Title
::newFromRedirect( $s->cur_text
);
470 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
471 $rid = $rt->getArticleID();
473 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
474 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
476 if ( $redirRow !== false ) {
477 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
485 $this->mContent
= $s->cur_text
;
486 $this->mUser
= $s->cur_user
;
487 $this->mUserText
= $s->cur_user_text
;
488 $this->mComment
= $s->cur_comment
;
489 $this->mCounter
= $s->cur_counter
;
490 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
491 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
492 $this->mTitle
->loadRestrictions( $s->cur_restrictions
);
493 } else { # oldid set, retrieve historical version
494 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
495 $fname, $this->getSelectOptions() );
496 if ( $s === false ) {
499 $this->mContent
= Article
::getRevisionText( $s );
500 $this->mUser
= $s->old_user
;
501 $this->mUserText
= $s->old_user_text
;
502 $this->mComment
= $s->old_comment
;
504 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
506 $this->mContentLoaded
= true;
507 return $this->mContent
;
511 * Read/write accessor to select FOR UPDATE
513 function forUpdate( $x = NULL ) {
514 return wfSetVar( $this->mForUpdate
, $x );
518 * Get the database which should be used for reads
521 if ( $this->mForUpdate
) {
522 return wfGetDB( DB_MASTER
);
524 return wfGetDB( DB_SLAVE
);
529 * Get options for all SELECT statements
530 * Can pass an option array, to which the class-wide options will be appended
532 function getSelectOptions( $options = '' ) {
533 if ( $this->mForUpdate
) {
535 $options[] = 'FOR UPDATE';
537 $options = 'FOR UPDATE';
544 * Return the Article ID
547 if( $this->mTitle
) {
548 return $this->mTitle
->getArticleID();
555 * Get the view count for this article
557 function getCount() {
558 if ( -1 == $this->mCounter
) {
559 $id = $this->getID();
560 $dbr =& $this->getDB();
561 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
562 'Article::getCount', $this->getSelectOptions() );
564 return $this->mCounter
;
568 * Would the given text make this article a "good" article (i.e.,
569 * suitable for including in the article count)?
571 function isCountable( $text ) {
572 global $wgUseCommaCount;
574 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
575 if ( $this->isRedirect( $text ) ) { return 0; }
576 $token = ($wgUseCommaCount ?
',' : '[[' );
577 if ( false === strstr( $text, $token ) ) { return 0; }
582 * Tests if the article text represents a redirect
584 function isRedirect( $text = false ) {
585 if ( $text === false ) {
586 $this->loadContent();
587 $titleObj = Title
::newFromRedirect( $this->mText
);
589 $titleObj = Title
::newFromRedirect( $text );
591 return $titleObj !== NULL;
595 * Loads everything from cur except cur_text
596 * This isn't necessary for all uses, so it's only done if needed.
599 function loadLastEdit() {
601 if ( -1 != $this->mUser
) return;
603 $fname = 'Article::loadLastEdit';
605 $dbr =& $this->getDB();
606 $s = $dbr->selectRow( 'cur',
607 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
608 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
610 if ( $s !== false ) {
611 $this->mUser
= $s->cur_user
;
612 $this->mUserText
= $s->cur_user_text
;
613 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
614 $this->mComment
= $s->cur_comment
;
615 $this->mMinorEdit
= $s->cur_minor_edit
;
619 function getTimestamp() {
620 $this->loadLastEdit();
621 return $this->mTimestamp
;
625 $this->loadLastEdit();
629 function getUserText() {
630 $this->loadLastEdit();
631 return $this->mUserText
;
634 function getComment() {
635 $this->loadLastEdit();
636 return $this->mComment
;
639 function getMinorEdit() {
640 $this->loadLastEdit();
641 return $this->mMinorEdit
;
644 function getContributors($limit = 0, $offset = 0) {
645 $fname = 'Article::getContributors';
647 # XXX: this is expensive; cache this info somewhere.
649 $title = $this->mTitle
;
651 $dbr =& $this->getDB();
652 $oldTable = $dbr->tableName( 'old' );
653 $userTable = $dbr->tableName( 'user' );
654 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
655 $ns = $title->getNamespace();
656 $user = $this->getUser();
658 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
659 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
660 WHERE old_namespace = $user
661 AND old_title = $encDBkey
662 AND old_user != $user
663 GROUP BY old_user, old_user_text, user_real_name
664 ORDER BY timestamp DESC";
666 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
667 $sql .= ' '. $this->getSelectOptions();
669 $res = $dbr->query($sql, $fname);
671 while ( $line = $dbr->fetchObject( $res ) ) {
672 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
675 $dbr->freeResult($res);
680 * This is the default action of the script: just view the page of
684 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
685 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
686 $sk = $wgUser->getSkin();
688 $fname = 'Article::view';
689 wfProfileIn( $fname );
690 # Get variables from query string
691 $oldid = $this->getOldID();
692 $diff = $wgRequest->getVal( 'diff' );
693 $rcid = $wgRequest->getVal( 'rcid' );
695 $wgOut->setArticleFlag( true );
696 $wgOut->setRobotpolicy( 'index,follow' );
697 # If we got diff and oldid in the query, we want to see a
698 # diff page instead of the article.
700 if ( !is_null( $diff ) ) {
701 require_once( 'DifferenceEngine.php' );
702 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
703 $de = new DifferenceEngine( $oldid, $diff, $rcid );
706 # Run view updates for current revision only
707 $this->viewUpdates();
709 wfProfileOut( $fname );
712 if ( empty( $oldid ) && $this->checkTouched() ) {
713 if( $wgOut->checkLastModified( $this->mTouched
) ){
714 wfProfileOut( $fname );
716 } else if ( $this->tryFileCache() ) {
717 # tell wgOut that output is taken care of
719 $this->viewUpdates();
720 wfProfileOut( $fname );
724 # Should the parser cache be used?
725 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
733 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
737 if ( !$outputDone ) {
738 $text = $this->getContent( false ); # May change mTitle by following a redirect
740 # Another whitelist check in case oldid or redirects are altering the title
741 if ( !$this->mTitle
->userCanRead() ) {
742 $wgOut->loginToUse();
748 # We're looking at an old revision
750 if ( !empty( $oldid ) ) {
751 $this->setOldSubtitle( $oldid );
752 $wgOut->setRobotpolicy( 'noindex,follow' );
754 if ( '' != $this->mRedirectedFrom
) {
755 $sk = $wgUser->getSkin();
756 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
758 $s = wfMsg( 'redirectedfrom', $redir );
759 $wgOut->setSubtitle( $s );
761 # Can't cache redirects
765 # wrap user css and user js in pre and don't parse
766 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
768 $this->mTitle
->getNamespace() == NS_USER
&&
769 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
771 $wgOut->addWikiText( wfMsg('clearyourcache'));
772 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
773 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
775 $imageUrl = $wgStylePath.'/common/images/redirect.png';
776 $targetUrl = $rt->escapeLocalURL();
777 $titleText = htmlspecialchars( $rt->getPrefixedText() );
778 $link = $sk->makeLinkObj( $rt );
780 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
781 '<span class="redirectText">'.$link.'</span>' );
783 } else if ( $pcache ) {
784 # Display content and save to parser cache
785 $wgOut->addPrimaryWikiText( $text, $this );
787 # Display content, don't attempt to save to parser cache
788 $wgOut->addWikiText( $text );
791 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
792 # If we have been passed an &rcid= parameter, we want to give the user a
793 # chance to mark this new article as patrolled.
794 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
795 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
797 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
798 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
799 'action=markpatrolled&rcid='.$rcid )
803 # Put link titles into the link cache
804 $wgOut->transformBuffer();
806 # Add link titles as META keywords
807 $wgOut->addMetaTags() ;
809 $this->viewUpdates();
810 wfProfileOut( $fname );
814 * Theoretically we could defer these whole insert and update
815 * functions for after display, but that's taking a big leap
816 * of faith, and we want to be able to report database
817 * errors at some point.
820 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
821 global $wgOut, $wgUser;
822 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
824 $fname = 'Article::insertNewArticle';
826 $this->mCountAdjustment
= $this->isCountable( $text );
828 $ns = $this->mTitle
->getNamespace();
829 $ttl = $this->mTitle
->getDBkey();
830 $text = $this->preSaveTransform( $text );
831 if ( $this->isRedirect( $text ) ) { $redir = 1; }
834 $now = wfTimestampNow();
835 $won = wfInvertTimestamp( $now );
838 $dbw =& wfGetDB( DB_MASTER
);
840 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
842 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
844 $dbw->insert( 'cur', array(
846 'cur_namespace' => $ns,
849 'cur_comment' => $summary,
850 'cur_user' => $wgUser->getID(),
851 'cur_timestamp' => $dbw->timestamp($now),
852 'cur_minor_edit' => $isminor,
854 'cur_restrictions' => '',
855 'cur_user_text' => $wgUser->getName(),
856 'cur_is_redirect' => $redir,
858 'cur_random' => $rand,
859 'cur_touched' => $dbw->timestamp($now),
860 'inverse_timestamp' => $won,
863 $newid = $dbw->insertId();
864 $this->mTitle
->resetArticleID( $newid );
866 Article
::onArticleCreate( $this->mTitle
);
867 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
870 if(!$this->mTitle
->userIsWatching()) $this->watch();
872 if ( $this->mTitle
->userIsWatching() ) {
877 # The talk page isn't in the regular link tables, so we need to update manually:
878 $talkns = $ns ^
1; # talk -> normal; normal -> talk
879 $dbw->update( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
880 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
882 # standard deferred updates
883 $this->editUpdates( $text );
885 $this->showArticle( $text, wfMsg( 'newarticle' ) );
890 * Side effects: loads last edit if $edittime is NULL
892 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
893 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
894 if(is_null($edittime)) {
895 $this->loadLastEdit();
896 $oldtext = $this->getContent( true );
898 $dbw =& wfGetDB( DB_MASTER
);
899 $ns = $this->mTitle
->getNamespace();
900 $title = $this->mTitle
->getDBkey();
901 $obj = $dbw->selectRow( 'old',
902 array( 'old_text','old_flags'),
903 array( 'old_namespace' => $ns, 'old_title' => $title,
904 'old_timestamp' => $dbw->timestamp($edittime)),
906 $oldtext = Article
::getRevisionText( $obj );
908 if ($section != '') {
909 if($section=='new') {
910 if($summary) $subject="== {$summary} ==\n\n";
911 $text=$oldtext."\n\n".$subject.$text;
914 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
915 # comments to be stripped as well)
917 $parser=new Parser();
918 $parser->mOutputType
=OT_WIKI
;
919 $oldtext=$parser->strip($oldtext, $striparray, true);
921 # now that we can be sure that no pseudo-sections are in the source,
923 # Unfortunately we can't simply do a preg_replace because that might
924 # replace the wrong section, so we have to use the section counter instead
925 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
926 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
927 $secs[$section*2]=$text."\n\n"; // replace with edited
929 # section 0 is top (intro) section
932 # headline of old section - we need to go through this section
933 # to determine if there are any subsections that now need to
934 # be erased, as the mother section has been replaced with
935 # the text of all subsections.
936 $headline=$secs[$section*2-1];
937 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
940 # determine headline level for wikimarkup headings
941 if(strpos($hlevel,'=')!==false) {
942 $hlevel=strlen($hlevel);
945 $secs[$section*2-1]=''; // erase old headline
948 while(!empty($secs[$count*2-1]) && !$break) {
950 $subheadline=$secs[$count*2-1];
952 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
953 $subhlevel=$matches[1];
954 if(strpos($subhlevel,'=')!==false) {
955 $subhlevel=strlen($subhlevel);
957 if($subhlevel > $hlevel) {
958 // erase old subsections
959 $secs[$count*2-1]='';
962 if($subhlevel <= $hlevel) {
970 $text=join('',$secs);
971 # reinsert the stuff that we stripped out earlier
972 $text=$parser->unstrip($text,$striparray);
973 $text=$parser->unstripNoWiki($text,$striparray);
981 * Change an existing article. Puts the previous version back into the old table, updates RC
982 * and all necessary caches, mostly via the deferred update array.
984 * It is possible to call this function from a command-line script, but note that you should
985 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
987 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
988 global $wgOut, $wgUser;
989 global $wgDBtransactions, $wgMwRedir;
990 global $wgUseSquid, $wgInternalServer;
992 $fname = 'Article::updateArticle';
995 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
996 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
997 if ( $this->isRedirect( $text ) ) {
998 # Remove all content but redirect
999 # This could be done by reconstructing the redirect from a title given by
1000 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1002 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1004 $text = $m[1] . "\n";
1007 else { $redir = 0; }
1009 $text = $this->preSaveTransform( $text );
1010 $dbw =& wfGetDB( DB_MASTER
);
1012 # Update article, but only if changed.
1014 # It's important that we either rollback or complete, otherwise an attacker could
1015 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1016 # could conceivably have the same effect, especially if cur is locked for long periods.
1017 if( $wgDBtransactions ) {
1018 $dbw->query( 'BEGIN', $fname );
1020 $userAbort = ignore_user_abort( true );
1023 $oldtext = $this->getContent( true );
1025 if ( 0 != strcmp( $text, $oldtext ) ) {
1026 $this->mCountAdjustment
= $this->isCountable( $text )
1027 - $this->isCountable( $oldtext );
1028 $now = wfTimestampNow();
1029 $won = wfInvertTimestamp( $now );
1031 # First update the cur row
1032 $dbw->update( 'cur',
1034 'cur_text' => $text,
1035 'cur_comment' => $summary,
1036 'cur_minor_edit' => $me2,
1037 'cur_user' => $wgUser->getID(),
1038 'cur_timestamp' => $dbw->timestamp($now),
1039 'cur_user_text' => $wgUser->getName(),
1040 'cur_is_redirect' => $redir,
1042 'cur_touched' => $dbw->timestamp($now),
1043 'inverse_timestamp' => $won
1044 ), array( /* WHERE */
1045 'cur_id' => $this->getID(),
1046 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1050 if( $dbw->affectedRows() == 0 ) {
1051 /* Belated edit conflict! Run away!! */
1054 # Now insert the previous revision into old
1056 # This overwrites $oldtext if revision compression is on
1057 $flags = Article
::compressRevisionText( $oldtext );
1059 $dbw->insert( 'old',
1061 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1062 'old_namespace' => $this->mTitle
->getNamespace(),
1063 'old_title' => $this->mTitle
->getDBkey(),
1064 'old_text' => $oldtext,
1065 'old_comment' => $this->getComment(),
1066 'old_user' => $this->getUser(),
1067 'old_user_text' => $this->getUserText(),
1068 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1069 'old_minor_edit' => $me1,
1070 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1071 'old_flags' => $flags,
1075 $oldid = $dbw->insertId();
1077 $bot = (int)($wgUser->isBot() ||
$forceBot);
1078 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1079 $oldid, $this->getTimestamp(), $bot );
1080 Article
::onArticleEdit( $this->mTitle
);
1084 if( $wgDBtransactions ) {
1085 $dbw->query( 'COMMIT', $fname );
1087 ignore_user_abort( $userAbort );
1092 if (!$this->mTitle
->userIsWatching()) $this->watch();
1094 if ( $this->mTitle
->userIsWatching() ) {
1098 # standard deferred updates
1099 $this->editUpdates( $text );
1103 # Template namespace
1104 # Purge all articles linking here
1105 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1106 $titles = $this->mTitle
->getLinksTo();
1107 Title
::touchArray( $titles );
1108 if ( $wgUseSquid ) {
1109 foreach ( $titles as $title ) {
1110 $urls[] = $title->getInternalURL();
1116 if ( $wgUseSquid ) {
1117 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1118 $u = new SquidUpdate( $urls );
1122 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1128 * After we've either updated or inserted the article, update
1129 * the link tables and redirect to the new page.
1131 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1132 global $wgOut, $wgUser, $wgLinkCache;
1134 $wgLinkCache = new LinkCache();
1136 $wgLinkCache->forUpdate( true );
1138 # Get old version of link table to allow incremental link updates
1139 $wgLinkCache->preFill( $this->mTitle
);
1140 $wgLinkCache->clear();
1142 # Parse the text and replace links with placeholders
1143 $wgOut = new OutputPage();
1144 $wgOut->addWikiText( $text );
1146 # Look up the links in the DB and add them to the link cache
1147 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1149 if( $this->isRedirect( $text ) )
1153 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1158 * @todo document this function a bit more
1160 function validate () {
1161 global $wgOut, $wgUseValidation;
1162 if( $wgUseValidation ) {
1163 require_once ( 'SpecialValidate.php' ) ;
1164 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1165 $wgOut->setRobotpolicy( 'noindex,follow' );
1166 if( $this->mTitle
->getNamespace() != 0 ) {
1167 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1170 $v = new Validation
;
1171 $v->validate_form( $this->mTitle
->getDBkey() );
1173 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1178 * Mark this particular edit as patrolled
1180 function markpatrolled() {
1181 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1182 $wgOut->setRobotpolicy( 'noindex,follow' );
1184 if ( !$wgUseRCPatrol )
1186 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1189 if ( $wgUser->getID() == 0 )
1191 $wgOut->loginToUse();
1194 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1196 $wgOut->sysopRequired();
1199 $rcid = $wgRequest->getVal( 'rcid' );
1200 if ( !is_null ( $rcid ) )
1202 RecentChange
::markPatrolled( $rcid );
1203 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1204 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1205 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1209 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1215 * Add or remove this page to my watchlist based on value of $add
1217 function watch( $add = true ) {
1218 global $wgUser, $wgOut;
1219 global $wgDeferredUpdateList;
1221 if ( 0 == $wgUser->getID() ) {
1222 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1225 if ( wfReadOnly() ) {
1226 $wgOut->readOnlyPage();
1230 $wgUser->addWatch( $this->mTitle
);
1232 $wgUser->removeWatch( $this->mTitle
);
1234 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1235 $wgOut->setRobotpolicy( 'noindex,follow' );
1237 $sk = $wgUser->getSkin() ;
1238 $link = $this->mTitle
->getPrefixedText();
1241 $text = wfMsg( 'addedwatchtext', $link );
1243 $text = wfMsg( 'removedwatchtext', $link );
1244 $wgOut->addWikiText( $text );
1246 $up = new UserUpdate();
1247 array_push( $wgDeferredUpdateList, $up );
1249 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1253 * Stop watching a page, it act just like a call to watch(false)
1255 function unwatch() {
1256 $this->watch( false );
1262 function protect( $limit = 'sysop' ) {
1263 global $wgUser, $wgOut, $wgRequest;
1265 if ( ! $wgUser->isAllowed('protect') ) {
1266 $wgOut->sysopRequired();
1269 if ( wfReadOnly() ) {
1270 $wgOut->readOnlyPage();
1273 $id = $this->mTitle
->getArticleID();
1275 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1279 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1280 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1281 $reason = $wgRequest->getText( 'wpReasonProtect' );
1284 $restrictions = "move=" . $limit;
1286 $restrictions .= ":edit=" . $limit;
1289 $dbw =& wfGetDB( DB_MASTER
);
1290 $dbw->update( 'cur',
1292 'cur_touched' => $dbw->timestamp(),
1293 'cur_restrictions' => $restrictions
1294 ), array( /* WHERE */
1296 ), 'Article::protect'
1299 $log = new LogPage( 'protect' );
1300 if ( $limit === '' ) {
1301 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1303 $log->addEntry( 'protect', $this->mTitle
, $reason );
1305 $wgOut->redirect( $this->mTitle
->getFullURL() );
1308 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1309 return $this->confirmProtect( '', $reason, $limit );
1314 * Output protection confirmation dialog
1316 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1319 wfDebug( "Article::confirmProtect\n" );
1321 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1322 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1328 if ( $limit === '' ) {
1329 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1330 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1331 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1332 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1333 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1334 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1336 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1337 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1338 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1339 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1340 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1341 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1342 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1345 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1348 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1352 <label for='wpReasonProtect'>{$protcom}:</label>
1355 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1363 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1366 <label for='wpConfirmProtect'>{$check}</label>
1369 if($moveonly != '') {
1373 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1376 <label for='wpMoveOnly'>{$moveonly}</label>
1384 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1390 $wgOut->returnToMain( false );
1394 * Unprotect the pages
1396 function unprotect() {
1397 return $this->protect( '' );
1401 * UI entry point for page deletion
1404 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1405 $fname = 'Article::delete';
1406 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1407 $reason = $wgRequest->getText( 'wpReason' );
1409 # This code desperately needs to be totally rewritten
1412 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1413 $wgOut->sysopRequired();
1416 if ( wfReadOnly() ) {
1417 $wgOut->readOnlyPage();
1421 # Better double-check that it hasn't been deleted yet!
1422 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1423 if ( ( '' == trim( $this->mTitle
->getText() ) )
1424 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1425 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1430 $this->doDelete( $reason );
1434 # determine whether this page has earlier revisions
1435 # and insert a warning if it does
1436 # we select the text because it might be useful below
1437 $dbr =& $this->getDB();
1438 $ns = $this->mTitle
->getNamespace();
1439 $title = $this->mTitle
->getDBkey();
1440 $old = $dbr->selectRow( 'old',
1441 array( 'old_text', 'old_flags' ),
1443 'old_namespace' => $ns,
1444 'old_title' => $title,
1445 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1448 if( $old !== false && !$confirm ) {
1449 $skin=$wgUser->getSkin();
1450 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1451 $wgOut->addHTML( $skin->historyLink() .'</b>');
1455 $s = $dbr->selectRow( 'cur',
1456 array( 'cur_text' ),
1458 'cur_namespace' => $ns,
1459 'cur_title' => $title,
1460 ), $fname, $this->getSelectOptions()
1463 if( $s !== false ) {
1464 # if this is a mini-text, we can paste part of it into the deletion reason
1466 #if this is empty, an earlier revision may contain "useful" text
1468 if($s->cur_text
!= '') {
1472 $text = Article
::getRevisionText( $old );
1478 $length=strlen($text);
1480 # this should not happen, since it is not possible to store an empty, new
1481 # page. Let's insert a standard text in case it does, though
1482 if($length == 0 && $reason === '') {
1483 $reason = wfMsg('exblank');
1486 if($length < 500 && $reason === '') {
1488 # comment field=255, let's grep the first 150 to have some user
1490 $text=substr($text,0,150);
1491 # let's strip out newlines and HTML tags
1492 $text=preg_replace('/\"/',"'",$text);
1493 $text=preg_replace('/\</','<',$text);
1494 $text=preg_replace('/\>/','>',$text);
1495 $text=preg_replace("/[\n\r]/",'',$text);
1497 $reason=wfMsg('excontent'). " '".$text;
1499 $reason=wfMsg('exbeforeblank') . " '".$text;
1501 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1506 return $this->confirmDelete( '', $reason );
1510 * Output deletion confirmation dialog
1512 function confirmDelete( $par, $reason ) {
1515 wfDebug( "Article::confirmDelete\n" );
1517 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1518 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1519 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1520 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1522 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1524 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1525 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1526 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1529 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1533 <label for='wpReason'>{$delcom}:</label>
1536 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1544 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1547 <label for='wpConfirm'>{$check}</label>
1553 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1559 $wgOut->returnToMain( false );
1564 * Perform a deletion and output success or failure messages
1566 function doDelete( $reason ) {
1567 global $wgOut, $wgUser, $wgContLang;
1568 $fname = 'Article::doDelete';
1569 wfDebug( $fname."\n" );
1571 if ( $this->doDeleteArticle( $reason ) ) {
1572 $deleted = $this->mTitle
->getPrefixedText();
1574 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1575 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1577 $sk = $wgUser->getSkin();
1578 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1579 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1581 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1583 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1584 $wgOut->returnToMain( false );
1586 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1591 * Back-end article deletion
1592 * Deletes the article with database consistency, writes logs, purges caches
1595 function doDeleteArticle( $reason ) {
1597 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1599 $fname = 'Article::doDeleteArticle';
1600 wfDebug( $fname."\n" );
1602 $dbw =& wfGetDB( DB_MASTER
);
1603 $ns = $this->mTitle
->getNamespace();
1604 $t = $this->mTitle
->getDBkey();
1605 $id = $this->mTitle
->getArticleID();
1607 if ( $t == '' ||
$id == 0 ) {
1611 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1612 array_push( $wgDeferredUpdateList, $u );
1614 $linksTo = $this->mTitle
->getLinksTo();
1617 if ( $wgUseSquid ) {
1619 $this->mTitle
->getInternalURL(),
1620 $this->mTitle
->getInternalURL( 'history' )
1622 foreach ( $linksTo as $linkTo ) {
1623 $urls[] = $linkTo->getInternalURL();
1626 $u = new SquidUpdate( $urls );
1627 array_push( $wgDeferredUpdateList, $u );
1631 # Client and file cache invalidation
1632 Title
::touchArray( $linksTo );
1634 # Move article and history to the "archive" table
1635 $archiveTable = $dbw->tableName( 'archive' );
1636 $oldTable = $dbw->tableName( 'old' );
1637 $curTable = $dbw->tableName( 'cur' );
1638 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1639 $linksTable = $dbw->tableName( 'links' );
1640 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1642 $dbw->insertSelect( 'archive', 'cur',
1644 'ar_namespace' => 'cur_namespace',
1645 'ar_title' => 'cur_title',
1646 'ar_text' => 'cur_text',
1647 'ar_comment' => 'cur_comment',
1648 'ar_user' => 'cur_user',
1649 'ar_user_text' => 'cur_user_text',
1650 'ar_timestamp' => 'cur_timestamp',
1651 'ar_minor_edit' => 'cur_minor_edit',
1654 'cur_namespace' => $ns,
1659 $dbw->insertSelect( 'archive', 'old',
1661 'ar_namespace' => 'old_namespace',
1662 'ar_title' => 'old_title',
1663 'ar_text' => 'old_text',
1664 'ar_comment' => 'old_comment',
1665 'ar_user' => 'old_user',
1666 'ar_user_text' => 'old_user_text',
1667 'ar_timestamp' => 'old_timestamp',
1668 'ar_minor_edit' => 'old_minor_edit',
1669 'ar_flags' => 'old_flags'
1671 'old_namespace' => $ns,
1676 # Now that it's safely backed up, delete it
1678 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1679 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1680 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1682 # Finally, clean up the link tables
1683 $t = $this->mTitle
->getPrefixedDBkey();
1685 Article
::onArticleDelete( $this->mTitle
);
1687 # Insert broken links
1688 $brokenLinks = array();
1689 foreach ( $linksTo as $titleObj ) {
1690 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1691 $linkID = $titleObj->getArticleID();
1692 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1694 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1697 $dbw->delete( 'links', array( 'l_to' => $id ) );
1698 $dbw->delete( 'links', array( 'l_from' => $id ) );
1699 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1700 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1701 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1704 $log = new LogPage( 'delete' );
1705 $log->addEntry( 'delete', $this->mTitle
, $reason );
1707 # Clear the cached article id so the interface doesn't act like we exist
1708 $this->mTitle
->resetArticleID( 0 );
1709 $this->mTitle
->mArticleID
= 0;
1714 * Revert a modification
1716 function rollback() {
1717 global $wgUser, $wgOut, $wgRequest;
1718 $fname = 'Article::rollback';
1720 if ( ! $wgUser->isAllowed('rollback') ) {
1721 $wgOut->sysopRequired();
1724 if ( wfReadOnly() ) {
1725 $wgOut->readOnlyPage( $this->getContent( true ) );
1728 $dbw =& wfGetDB( DB_MASTER
);
1730 # Enhanced rollback, marks edits rc_bot=1
1731 $bot = $wgRequest->getBool( 'bot' );
1733 # Replace all this user's current edits with the next one down
1734 $tt = $this->mTitle
->getDBKey();
1735 $n = $this->mTitle
->getNamespace();
1737 # Get the last editor, lock table exclusively
1738 $s = $dbw->selectRow( 'cur',
1739 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1740 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1741 $fname, 'FOR UPDATE'
1743 if( $s === false ) {
1745 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1748 $ut = $dbw->strencode( $s->cur_user_text
);
1749 $uid = $s->cur_user
;
1752 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1753 if( $from != $s->cur_user_text
) {
1754 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1755 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1756 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1757 htmlspecialchars( $from ),
1758 htmlspecialchars( $s->cur_user_text
) ) );
1759 if($s->cur_comment
!= '') {
1761 wfMsg('editcomment',
1762 htmlspecialchars( $s->cur_comment
) ) );
1767 # Get the last edit not by this guy
1768 $s = $dbw->selectRow( 'old',
1769 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1771 'old_namespace' => $n,
1773 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1774 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1776 if( $s === false ) {
1778 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1779 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1784 # Mark all reverted edits as bot
1785 $dbw->update( 'recentchanges',
1788 ), array( /* WHERE */
1790 "rc_timestamp > '{$s->old_timestamp}'",
1796 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1797 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1798 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1799 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1800 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1801 Article
::onArticleEdit( $this->mTitle
);
1802 $wgOut->returnToMain( false );
1807 * Do standard deferred updates after page view
1810 function viewUpdates() {
1811 global $wgDeferredUpdateList;
1812 if ( 0 != $this->getID() ) {
1813 global $wgDisableCounters;
1814 if( !$wgDisableCounters ) {
1815 Article
::incViewCount( $this->getID() );
1816 $u = new SiteStatsUpdate( 1, 0, 0 );
1817 array_push( $wgDeferredUpdateList, $u );
1820 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1821 $this->mTitle
->getDBkey() );
1822 array_push( $wgDeferredUpdateList, $u );
1826 * Do standard deferred updates after page edit.
1827 * Every 1000th edit, prune the recent changes table.
1829 * @param string $text
1831 function editUpdates( $text ) {
1832 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1833 global $wgMessageCache;
1836 if ( 0 == mt_rand( 0, 999 ) ) {
1837 $dbw =& wfGetDB( DB_MASTER
);
1838 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1839 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1840 $dbw->query( $sql );
1842 $id = $this->getID();
1843 $title = $this->mTitle
->getPrefixedDBkey();
1844 $shortTitle = $this->mTitle
->getDBkey();
1846 $adj = $this->mCountAdjustment
;
1849 $u = new LinksUpdate( $id, $title );
1850 array_push( $wgDeferredUpdateList, $u );
1851 $u = new SiteStatsUpdate( 0, 1, $adj );
1852 array_push( $wgDeferredUpdateList, $u );
1853 $u = new SearchUpdate( $id, $title, $text );
1854 array_push( $wgDeferredUpdateList, $u );
1856 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1857 array_push( $wgDeferredUpdateList, $u );
1859 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1860 $wgMessageCache->replace( $shortTitle, $text );
1866 * @todo document this function
1868 * @param string $oldid Revision ID of this article revision
1870 function setOldSubtitle( $oldid=0 ) {
1871 global $wgLang, $wgOut, $wgUser;
1873 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1874 $sk = $wgUser->getSkin();
1875 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1876 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1877 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1878 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1879 $wgOut->setSubtitle( $r );
1883 * This function is called right before saving the wikitext,
1884 * so we can do things like signatures and links-in-context.
1886 * @param string $text
1888 function preSaveTransform( $text ) {
1889 global $wgParser, $wgUser;
1890 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1893 /* Caching functions */
1896 * checkLastModified returns true if it has taken care of all
1897 * output to the client that is necessary for this request.
1898 * (that is, it has sent a cached version of the page)
1900 function tryFileCache() {
1901 static $called = false;
1903 wfDebug( " tryFileCache() -- called twice!?\n" );
1907 if($this->isFileCacheable()) {
1908 $touched = $this->mTouched
;
1909 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1910 # Expire the main page quicker
1911 $expire = wfUnix2Timestamp( time() - 3600 );
1912 $touched = max( $expire, $touched );
1914 $cache = new CacheManager( $this->mTitle
);
1915 if($cache->isFileCacheGood( $touched )) {
1917 wfDebug( " tryFileCache() - about to load\n" );
1918 $cache->loadFromFileCache();
1921 wfDebug( " tryFileCache() - starting buffer\n" );
1922 ob_start( array(&$cache, 'saveToFileCache' ) );
1925 wfDebug( " tryFileCache() - not cacheable\n" );
1930 * Check if the page can be cached
1933 function isFileCacheable() {
1934 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1935 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1937 return $wgUseFileCache
1938 and (!$wgShowIPinHeader)
1939 and ($this->getID() != 0)
1940 and ($wgUser->getId() == 0)
1941 and (!$wgUser->getNewtalk())
1942 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1943 and (empty( $action ) ||
$action == 'view')
1944 and (!isset($oldid))
1946 and (!isset($redirect))
1947 and (!isset($printable))
1948 and (!$this->mRedirectedFrom
);
1952 * Loads cur_touched and returns a value indicating if it should be used
1955 function checkTouched() {
1956 $fname = 'Article::checkTouched';
1957 $id = $this->getID();
1958 $dbr =& $this->getDB();
1959 $s = $dbr->selectRow( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1960 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1961 if( $s !== false ) {
1962 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1963 return !$s->cur_is_redirect
;
1970 * Edit an article without doing all that other stuff
1972 * @param string $text text submitted
1973 * @param string $comment comment submitted
1974 * @param integer $minor whereas it's a minor modification
1976 function quickEdit( $text, $comment = '', $minor = 0 ) {
1978 $fname = 'Article::quickEdit';
1979 wfProfileIn( $fname );
1981 $dbw =& wfGetDB( DB_MASTER
);
1982 $ns = $this->mTitle
->getNamespace();
1983 $dbkey = $this->mTitle
->getDBkey();
1984 $encDbKey = $dbw->strencode( $dbkey );
1985 $timestamp = wfTimestampNow();
1988 $dbw->insertSelect( 'old', 'cur',
1990 'old_namespace' => 'cur_namespace',
1991 'old_title' => 'cur_title',
1992 'old_text' => 'cur_text',
1993 'old_comment' => 'cur_comment',
1994 'old_user' => 'cur_user',
1995 'old_user_text' => 'cur_user_text',
1996 'old_timestamp' => 'cur_timestamp',
1997 'inverse_timestamp' => '99999999999999-cur_timestamp',
1999 'cur_namespace' => $ns,
2000 'cur_title' => $dbkey,
2004 # Use the affected row count to determine if the article is new
2005 $numRows = $dbw->affectedRows();
2007 # Make an array of fields to be inserted
2009 'cur_text' => $text,
2010 'cur_timestamp' => $timestamp,
2011 'cur_user' => $wgUser->getID(),
2012 'cur_user_text' => $wgUser->getName(),
2013 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2014 'cur_comment' => $comment,
2015 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2016 'cur_minor_edit' => intval($minor),
2017 'cur_touched' => $dbw->timestamp($timestamp),
2022 $fields['cur_is_new'] = 0;
2023 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2025 # Insert new article
2026 $fields['cur_is_new'] = 1;
2027 $fields['cur_namespace'] = $ns;
2028 $fields['cur_title'] = $dbkey;
2029 $fields['cur_random'] = $rand = wfRandom();
2030 $dbw->insert( 'cur', $fields, $fname );
2032 wfProfileOut( $fname );
2036 * Used to increment the view counter
2039 * @param integer $id article id
2041 function incViewCount( $id ) {
2042 $id = intval( $id );
2043 global $wgHitcounterUpdateFreq;
2045 $dbw =& wfGetDB( DB_MASTER
);
2046 $curTable = $dbw->tableName( 'cur' );
2047 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2048 $acchitsTable = $dbw->tableName( 'acchits' );
2050 if( $wgHitcounterUpdateFreq <= 1 ){ //
2051 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2055 # Not important enough to warrant an error page in case of failure
2056 $oldignore = $dbw->ignoreErrors( true );
2058 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2060 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2061 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2062 # Most of the time (or on SQL errors), skip row count check
2063 $dbw->ignoreErrors( $oldignore );
2067 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2068 $row = $dbw->fetchObject( $res );
2069 $rown = intval( $row->n
);
2070 if( $rown >= $wgHitcounterUpdateFreq ){
2071 wfProfileIn( 'Article::incViewCount-collect' );
2072 $old_user_abort = ignore_user_abort( true );
2074 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2075 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2076 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2078 $dbw->query("DELETE FROM $hitcounterTable");
2079 $dbw->query('UNLOCK TABLES');
2080 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2081 'WHERE cur_id = hc_id');
2082 $dbw->query("DROP TABLE $acchitsTable");
2084 ignore_user_abort( $old_user_abort );
2085 wfProfileOut( 'Article::incViewCount-collect' );
2087 $dbw->ignoreErrors( $oldignore );
2091 * The onArticle*() functions are supposed to be a kind of hooks
2092 * which should be called whenever any of the specified actions
2095 * This is a good place to put code to clear caches, for instance.
2097 * This is called on page move and undelete, as well as edit
2099 * @param $title_obj a title object
2102 function onArticleCreate($title_obj) {
2103 global $wgUseSquid, $wgDeferredUpdateList;
2105 $titles = $title_obj->getBrokenLinksTo();
2108 if ( $wgUseSquid ) {
2109 $urls = $title_obj->getSquidURLs();
2110 foreach ( $titles as $linkTitle ) {
2111 $urls[] = $linkTitle->getInternalURL();
2113 $u = new SquidUpdate( $urls );
2114 array_push( $wgDeferredUpdateList, $u );
2117 # Clear persistent link cache
2118 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2121 function onArticleDelete($title_obj) {
2122 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2124 function onArticleEdit($title_obj) {
2125 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2130 * Info about this page
2133 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2134 $fname = 'Article::info';
2136 if ( !$wgAllowPageInfo ) {
2137 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2141 $dbr =& $this->getDB();
2143 $basenamespace = $wgTitle->getNamespace() & (~
1);
2144 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2145 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2146 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2147 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2148 $wgOut->setPagetitle( $fullTitle );
2149 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2151 # first, see if the page exists at all.
2152 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2154 $wgOut->addHTML( wfMsg('noarticletext') );
2156 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2157 $this->getSelectOptions() );
2158 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2159 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2160 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2162 # to find number of distinct authors, we need to do some
2163 # funny stuff because of the cur/old table split:
2164 # - first, find the name of the 'cur' author
2165 # - then, find the number of *other* authors in 'old'
2168 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2169 $this->getSelectOptions() );
2171 # find number of 'old' authors excluding 'cur' author
2172 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2173 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2174 $this->getSelectOptions() ) +
1;
2176 # now for the Talk page ...
2177 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2178 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2181 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2185 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2186 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2188 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2192 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2193 $this->getSelectOptions() );
2194 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2195 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2196 $fname, $this->getSelectOptions() );
2198 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );