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' );
1285 $restrictions = "move=" . $limit;
1287 $restrictions .= ":edit=" . $limit;
1289 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1291 $dbw =& wfGetDB( DB_MASTER
);
1292 $dbw->update( 'cur',
1294 'cur_touched' => $dbw->timestamp(),
1295 'cur_restrictions' => $restrictions
1296 ), array( /* WHERE */
1298 ), 'Article::protect'
1301 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1303 $log = new LogPage( 'protect' );
1304 if ( $limit === '' ) {
1305 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1307 $log->addEntry( 'protect', $this->mTitle
, $reason );
1309 $wgOut->redirect( $this->mTitle
->getFullURL() );
1313 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1314 return $this->confirmProtect( '', $reason, $limit );
1319 * Output protection confirmation dialog
1321 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1324 wfDebug( "Article::confirmProtect\n" );
1326 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1327 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1333 if ( $limit === '' ) {
1334 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1335 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1336 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1337 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1338 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1339 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1341 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1342 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1343 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1344 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1345 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1346 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1347 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1350 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1353 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1357 <label for='wpReasonProtect'>{$protcom}:</label>
1360 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1368 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1371 <label for='wpConfirmProtect'>{$check}</label>
1374 if($moveonly != '') {
1378 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1381 <label for='wpMoveOnly'>{$moveonly}</label>
1389 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1395 $wgOut->returnToMain( false );
1399 * Unprotect the pages
1401 function unprotect() {
1402 return $this->protect( '' );
1406 * UI entry point for page deletion
1409 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1410 $fname = 'Article::delete';
1411 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1412 $reason = $wgRequest->getText( 'wpReason' );
1414 # This code desperately needs to be totally rewritten
1417 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1418 $wgOut->sysopRequired();
1421 if ( wfReadOnly() ) {
1422 $wgOut->readOnlyPage();
1426 # Better double-check that it hasn't been deleted yet!
1427 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1428 if ( ( '' == trim( $this->mTitle
->getText() ) )
1429 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1430 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1435 $this->doDelete( $reason );
1439 # determine whether this page has earlier revisions
1440 # and insert a warning if it does
1441 # we select the text because it might be useful below
1442 $dbr =& $this->getDB();
1443 $ns = $this->mTitle
->getNamespace();
1444 $title = $this->mTitle
->getDBkey();
1445 $old = $dbr->selectRow( 'old',
1446 array( 'old_text', 'old_flags' ),
1448 'old_namespace' => $ns,
1449 'old_title' => $title,
1450 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1453 if( $old !== false && !$confirm ) {
1454 $skin=$wgUser->getSkin();
1455 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1456 $wgOut->addHTML( $skin->historyLink() .'</b>');
1460 $s = $dbr->selectRow( 'cur',
1461 array( 'cur_text' ),
1463 'cur_namespace' => $ns,
1464 'cur_title' => $title,
1465 ), $fname, $this->getSelectOptions()
1468 if( $s !== false ) {
1469 # if this is a mini-text, we can paste part of it into the deletion reason
1471 #if this is empty, an earlier revision may contain "useful" text
1473 if($s->cur_text
!= '') {
1477 $text = Article
::getRevisionText( $old );
1483 $length=strlen($text);
1485 # this should not happen, since it is not possible to store an empty, new
1486 # page. Let's insert a standard text in case it does, though
1487 if($length == 0 && $reason === '') {
1488 $reason = wfMsg('exblank');
1491 if($length < 500 && $reason === '') {
1493 # comment field=255, let's grep the first 150 to have some user
1495 $text=substr($text,0,150);
1496 # let's strip out newlines and HTML tags
1497 $text=preg_replace('/\"/',"'",$text);
1498 $text=preg_replace('/\</','<',$text);
1499 $text=preg_replace('/\>/','>',$text);
1500 $text=preg_replace("/[\n\r]/",'',$text);
1502 $reason=wfMsg('excontent'). " '".$text;
1504 $reason=wfMsg('exbeforeblank') . " '".$text;
1506 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1511 return $this->confirmDelete( '', $reason );
1515 * Output deletion confirmation dialog
1517 function confirmDelete( $par, $reason ) {
1520 wfDebug( "Article::confirmDelete\n" );
1522 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1523 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1524 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1525 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1527 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1529 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1530 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1531 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1534 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1538 <label for='wpReason'>{$delcom}:</label>
1541 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1549 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1552 <label for='wpConfirm'>{$check}</label>
1558 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1564 $wgOut->returnToMain( false );
1569 * Perform a deletion and output success or failure messages
1571 function doDelete( $reason ) {
1572 global $wgOut, $wgUser, $wgContLang;
1573 $fname = 'Article::doDelete';
1574 wfDebug( $fname."\n" );
1576 if ( $this->doDeleteArticle( $reason ) ) {
1577 $deleted = $this->mTitle
->getPrefixedText();
1579 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1580 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1582 $sk = $wgUser->getSkin();
1583 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1584 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1586 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1588 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1589 $wgOut->returnToMain( false );
1591 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1596 * Back-end article deletion
1597 * Deletes the article with database consistency, writes logs, purges caches
1600 function doDeleteArticle( $reason ) {
1602 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1604 $fname = 'Article::doDeleteArticle';
1605 wfDebug( $fname."\n" );
1607 $dbw =& wfGetDB( DB_MASTER
);
1608 $ns = $this->mTitle
->getNamespace();
1609 $t = $this->mTitle
->getDBkey();
1610 $id = $this->mTitle
->getArticleID();
1612 if ( $t == '' ||
$id == 0 ) {
1616 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1617 array_push( $wgDeferredUpdateList, $u );
1619 $linksTo = $this->mTitle
->getLinksTo();
1622 if ( $wgUseSquid ) {
1624 $this->mTitle
->getInternalURL(),
1625 $this->mTitle
->getInternalURL( 'history' )
1627 foreach ( $linksTo as $linkTo ) {
1628 $urls[] = $linkTo->getInternalURL();
1631 $u = new SquidUpdate( $urls );
1632 array_push( $wgDeferredUpdateList, $u );
1636 # Client and file cache invalidation
1637 Title
::touchArray( $linksTo );
1639 # Move article and history to the "archive" table
1640 $archiveTable = $dbw->tableName( 'archive' );
1641 $oldTable = $dbw->tableName( 'old' );
1642 $curTable = $dbw->tableName( 'cur' );
1643 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1644 $linksTable = $dbw->tableName( 'links' );
1645 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1647 $dbw->insertSelect( 'archive', 'cur',
1649 'ar_namespace' => 'cur_namespace',
1650 'ar_title' => 'cur_title',
1651 'ar_text' => 'cur_text',
1652 'ar_comment' => 'cur_comment',
1653 'ar_user' => 'cur_user',
1654 'ar_user_text' => 'cur_user_text',
1655 'ar_timestamp' => 'cur_timestamp',
1656 'ar_minor_edit' => 'cur_minor_edit',
1659 'cur_namespace' => $ns,
1664 $dbw->insertSelect( 'archive', 'old',
1666 'ar_namespace' => 'old_namespace',
1667 'ar_title' => 'old_title',
1668 'ar_text' => 'old_text',
1669 'ar_comment' => 'old_comment',
1670 'ar_user' => 'old_user',
1671 'ar_user_text' => 'old_user_text',
1672 'ar_timestamp' => 'old_timestamp',
1673 'ar_minor_edit' => 'old_minor_edit',
1674 'ar_flags' => 'old_flags'
1676 'old_namespace' => $ns,
1681 # Now that it's safely backed up, delete it
1683 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1684 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1685 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1687 # Finally, clean up the link tables
1688 $t = $this->mTitle
->getPrefixedDBkey();
1690 Article
::onArticleDelete( $this->mTitle
);
1692 # Insert broken links
1693 $brokenLinks = array();
1694 foreach ( $linksTo as $titleObj ) {
1695 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1696 $linkID = $titleObj->getArticleID();
1697 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1699 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1702 $dbw->delete( 'links', array( 'l_to' => $id ) );
1703 $dbw->delete( 'links', array( 'l_from' => $id ) );
1704 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1705 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1706 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1709 $log = new LogPage( 'delete' );
1710 $log->addEntry( 'delete', $this->mTitle
, $reason );
1712 # Clear the cached article id so the interface doesn't act like we exist
1713 $this->mTitle
->resetArticleID( 0 );
1714 $this->mTitle
->mArticleID
= 0;
1719 * Revert a modification
1721 function rollback() {
1722 global $wgUser, $wgOut, $wgRequest;
1723 $fname = 'Article::rollback';
1725 if ( ! $wgUser->isAllowed('rollback') ) {
1726 $wgOut->sysopRequired();
1729 if ( wfReadOnly() ) {
1730 $wgOut->readOnlyPage( $this->getContent( true ) );
1733 $dbw =& wfGetDB( DB_MASTER
);
1735 # Enhanced rollback, marks edits rc_bot=1
1736 $bot = $wgRequest->getBool( 'bot' );
1738 # Replace all this user's current edits with the next one down
1739 $tt = $this->mTitle
->getDBKey();
1740 $n = $this->mTitle
->getNamespace();
1742 # Get the last editor, lock table exclusively
1743 $s = $dbw->selectRow( 'cur',
1744 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1745 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1746 $fname, 'FOR UPDATE'
1748 if( $s === false ) {
1750 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1753 $ut = $dbw->strencode( $s->cur_user_text
);
1754 $uid = $s->cur_user
;
1757 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1758 if( $from != $s->cur_user_text
) {
1759 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1760 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1761 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1762 htmlspecialchars( $from ),
1763 htmlspecialchars( $s->cur_user_text
) ) );
1764 if($s->cur_comment
!= '') {
1766 wfMsg('editcomment',
1767 htmlspecialchars( $s->cur_comment
) ) );
1772 # Get the last edit not by this guy
1773 $s = $dbw->selectRow( 'old',
1774 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1776 'old_namespace' => $n,
1778 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1779 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1781 if( $s === false ) {
1783 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1784 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1789 # Mark all reverted edits as bot
1790 $dbw->update( 'recentchanges',
1793 ), array( /* WHERE */
1795 "rc_timestamp > '{$s->old_timestamp}'",
1801 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1802 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1803 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1804 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1805 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1806 Article
::onArticleEdit( $this->mTitle
);
1807 $wgOut->returnToMain( false );
1812 * Do standard deferred updates after page view
1815 function viewUpdates() {
1816 global $wgDeferredUpdateList;
1817 if ( 0 != $this->getID() ) {
1818 global $wgDisableCounters;
1819 if( !$wgDisableCounters ) {
1820 Article
::incViewCount( $this->getID() );
1821 $u = new SiteStatsUpdate( 1, 0, 0 );
1822 array_push( $wgDeferredUpdateList, $u );
1825 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1826 $this->mTitle
->getDBkey() );
1827 array_push( $wgDeferredUpdateList, $u );
1831 * Do standard deferred updates after page edit.
1832 * Every 1000th edit, prune the recent changes table.
1834 * @param string $text
1836 function editUpdates( $text ) {
1837 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1838 global $wgMessageCache;
1841 if ( 0 == mt_rand( 0, 999 ) ) {
1842 $dbw =& wfGetDB( DB_MASTER
);
1843 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1844 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1845 $dbw->query( $sql );
1847 $id = $this->getID();
1848 $title = $this->mTitle
->getPrefixedDBkey();
1849 $shortTitle = $this->mTitle
->getDBkey();
1851 $adj = $this->mCountAdjustment
;
1854 $u = new LinksUpdate( $id, $title );
1855 array_push( $wgDeferredUpdateList, $u );
1856 $u = new SiteStatsUpdate( 0, 1, $adj );
1857 array_push( $wgDeferredUpdateList, $u );
1858 $u = new SearchUpdate( $id, $title, $text );
1859 array_push( $wgDeferredUpdateList, $u );
1861 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1862 array_push( $wgDeferredUpdateList, $u );
1864 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1865 $wgMessageCache->replace( $shortTitle, $text );
1871 * @todo document this function
1873 * @param string $oldid Revision ID of this article revision
1875 function setOldSubtitle( $oldid=0 ) {
1876 global $wgLang, $wgOut, $wgUser;
1878 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1879 $sk = $wgUser->getSkin();
1880 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1881 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1882 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1883 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1884 $wgOut->setSubtitle( $r );
1888 * This function is called right before saving the wikitext,
1889 * so we can do things like signatures and links-in-context.
1891 * @param string $text
1893 function preSaveTransform( $text ) {
1894 global $wgParser, $wgUser;
1895 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1898 /* Caching functions */
1901 * checkLastModified returns true if it has taken care of all
1902 * output to the client that is necessary for this request.
1903 * (that is, it has sent a cached version of the page)
1905 function tryFileCache() {
1906 static $called = false;
1908 wfDebug( " tryFileCache() -- called twice!?\n" );
1912 if($this->isFileCacheable()) {
1913 $touched = $this->mTouched
;
1914 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1915 # Expire the main page quicker
1916 $expire = wfUnix2Timestamp( time() - 3600 );
1917 $touched = max( $expire, $touched );
1919 $cache = new CacheManager( $this->mTitle
);
1920 if($cache->isFileCacheGood( $touched )) {
1922 wfDebug( " tryFileCache() - about to load\n" );
1923 $cache->loadFromFileCache();
1926 wfDebug( " tryFileCache() - starting buffer\n" );
1927 ob_start( array(&$cache, 'saveToFileCache' ) );
1930 wfDebug( " tryFileCache() - not cacheable\n" );
1935 * Check if the page can be cached
1938 function isFileCacheable() {
1939 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1940 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1942 return $wgUseFileCache
1943 and (!$wgShowIPinHeader)
1944 and ($this->getID() != 0)
1945 and ($wgUser->getId() == 0)
1946 and (!$wgUser->getNewtalk())
1947 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1948 and (empty( $action ) ||
$action == 'view')
1949 and (!isset($oldid))
1951 and (!isset($redirect))
1952 and (!isset($printable))
1953 and (!$this->mRedirectedFrom
);
1957 * Loads cur_touched and returns a value indicating if it should be used
1960 function checkTouched() {
1961 $fname = 'Article::checkTouched';
1962 $id = $this->getID();
1963 $dbr =& $this->getDB();
1964 $s = $dbr->selectRow( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1965 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1966 if( $s !== false ) {
1967 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1968 return !$s->cur_is_redirect
;
1975 * Edit an article without doing all that other stuff
1977 * @param string $text text submitted
1978 * @param string $comment comment submitted
1979 * @param integer $minor whereas it's a minor modification
1981 function quickEdit( $text, $comment = '', $minor = 0 ) {
1983 $fname = 'Article::quickEdit';
1984 wfProfileIn( $fname );
1986 $dbw =& wfGetDB( DB_MASTER
);
1987 $ns = $this->mTitle
->getNamespace();
1988 $dbkey = $this->mTitle
->getDBkey();
1989 $encDbKey = $dbw->strencode( $dbkey );
1990 $timestamp = wfTimestampNow();
1993 $dbw->insertSelect( 'old', 'cur',
1995 'old_namespace' => 'cur_namespace',
1996 'old_title' => 'cur_title',
1997 'old_text' => 'cur_text',
1998 'old_comment' => 'cur_comment',
1999 'old_user' => 'cur_user',
2000 'old_user_text' => 'cur_user_text',
2001 'old_timestamp' => 'cur_timestamp',
2002 'inverse_timestamp' => '99999999999999-cur_timestamp',
2004 'cur_namespace' => $ns,
2005 'cur_title' => $dbkey,
2009 # Use the affected row count to determine if the article is new
2010 $numRows = $dbw->affectedRows();
2012 # Make an array of fields to be inserted
2014 'cur_text' => $text,
2015 'cur_timestamp' => $timestamp,
2016 'cur_user' => $wgUser->getID(),
2017 'cur_user_text' => $wgUser->getName(),
2018 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2019 'cur_comment' => $comment,
2020 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2021 'cur_minor_edit' => intval($minor),
2022 'cur_touched' => $dbw->timestamp($timestamp),
2027 $fields['cur_is_new'] = 0;
2028 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2030 # Insert new article
2031 $fields['cur_is_new'] = 1;
2032 $fields['cur_namespace'] = $ns;
2033 $fields['cur_title'] = $dbkey;
2034 $fields['cur_random'] = $rand = wfRandom();
2035 $dbw->insert( 'cur', $fields, $fname );
2037 wfProfileOut( $fname );
2041 * Used to increment the view counter
2044 * @param integer $id article id
2046 function incViewCount( $id ) {
2047 $id = intval( $id );
2048 global $wgHitcounterUpdateFreq;
2050 $dbw =& wfGetDB( DB_MASTER
);
2051 $curTable = $dbw->tableName( 'cur' );
2052 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2053 $acchitsTable = $dbw->tableName( 'acchits' );
2055 if( $wgHitcounterUpdateFreq <= 1 ){ //
2056 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2060 # Not important enough to warrant an error page in case of failure
2061 $oldignore = $dbw->ignoreErrors( true );
2063 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2065 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2066 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2067 # Most of the time (or on SQL errors), skip row count check
2068 $dbw->ignoreErrors( $oldignore );
2072 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2073 $row = $dbw->fetchObject( $res );
2074 $rown = intval( $row->n
);
2075 if( $rown >= $wgHitcounterUpdateFreq ){
2076 wfProfileIn( 'Article::incViewCount-collect' );
2077 $old_user_abort = ignore_user_abort( true );
2079 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2080 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2081 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2083 $dbw->query("DELETE FROM $hitcounterTable");
2084 $dbw->query('UNLOCK TABLES');
2085 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2086 'WHERE cur_id = hc_id');
2087 $dbw->query("DROP TABLE $acchitsTable");
2089 ignore_user_abort( $old_user_abort );
2090 wfProfileOut( 'Article::incViewCount-collect' );
2092 $dbw->ignoreErrors( $oldignore );
2096 * The onArticle*() functions are supposed to be a kind of hooks
2097 * which should be called whenever any of the specified actions
2100 * This is a good place to put code to clear caches, for instance.
2102 * This is called on page move and undelete, as well as edit
2104 * @param $title_obj a title object
2107 function onArticleCreate($title_obj) {
2108 global $wgUseSquid, $wgDeferredUpdateList;
2110 $titles = $title_obj->getBrokenLinksTo();
2113 if ( $wgUseSquid ) {
2114 $urls = $title_obj->getSquidURLs();
2115 foreach ( $titles as $linkTitle ) {
2116 $urls[] = $linkTitle->getInternalURL();
2118 $u = new SquidUpdate( $urls );
2119 array_push( $wgDeferredUpdateList, $u );
2122 # Clear persistent link cache
2123 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2126 function onArticleDelete($title_obj) {
2127 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2129 function onArticleEdit($title_obj) {
2130 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2135 * Info about this page
2138 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2139 $fname = 'Article::info';
2141 if ( !$wgAllowPageInfo ) {
2142 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2146 $dbr =& $this->getDB();
2148 $basenamespace = $wgTitle->getNamespace() & (~
1);
2149 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2150 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2151 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2152 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2153 $wgOut->setPagetitle( $fullTitle );
2154 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2156 # first, see if the page exists at all.
2157 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2159 $wgOut->addHTML( wfMsg('noarticletext') );
2161 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2162 $this->getSelectOptions() );
2163 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2164 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2165 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2167 # to find number of distinct authors, we need to do some
2168 # funny stuff because of the cur/old table split:
2169 # - first, find the name of the 'cur' author
2170 # - then, find the number of *other* authors in 'old'
2173 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2174 $this->getSelectOptions() );
2176 # find number of 'old' authors excluding 'cur' author
2177 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2178 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2179 $this->getSelectOptions() ) +
1;
2181 # now for the Talk page ...
2182 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2183 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2186 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2190 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2191 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2193 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2197 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2198 $this->getSelectOptions() );
2199 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2200 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2201 $fname, $this->getSelectOptions() );
2203 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );