8 * Need the CacheManager to be loaded
10 require_once ( 'CacheManager.php' );
12 $wgArticleCurContentFields = false;
13 $wgArticleOldContentFields = false;
16 * Class representing a Wikipedia article and history.
18 * See design.doc for an overview.
19 * Note: edit user interface and cache support functions have been
20 * moved to separate EditPage and CacheManager classes.
26 var $mContent, $mContentLoaded;
27 var $mUser, $mTimestamp, $mUserText;
28 var $mCounter, $mComment, $mCountAdjustment;
29 var $mMinorEdit, $mRedirectedFrom;
30 var $mTouched, $mFileCache, $mTitle;
36 * Constructor and clear the article
38 function Article( &$title ) {
39 $this->mTitle
=& $title;
48 $this->mContentLoaded
= false;
49 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
50 $this->mRedirectedFrom
= $this->mUserText
=
51 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
52 $this->mCountAdjustment
= 0;
53 $this->mTouched
= '19700101000000';
54 $this->mForUpdate
= false;
58 * Get revision text associated with an old or archive row
59 * $row is usually an object from wfFetchRow(), both the flags and the text
60 * field must be included
62 * @param integer $row Id of a row
63 * @param string $prefix table prefix (default 'old_')
64 * @return string $text the text requested
66 function getRevisionText( $row, $prefix = 'old_' ) {
68 $textField = $prefix . 'text';
69 $flagsField = $prefix . 'flags';
71 if ( isset( $row->$flagsField ) ) {
72 $flags = explode( ',', $row->$flagsField );
77 if ( isset( $row->$textField ) ) {
78 $text = $row->$textField;
83 if ( in_array( 'link', $flags ) ) {
85 $text = Article
::followLink( $text );
86 } elseif ( in_array( 'gzip', $flags ) ) {
87 # Deal with optional compression of archived pages.
88 # This can be done periodically via maintenance/compressOld.php, and
89 # as pages are saved if $wgCompressRevisions is set.
90 return gzinflate( $text );
96 * If $wgCompressRevisions is enabled, we will compress datas
98 * @param reference to a text
99 * @return string 'gzip' if it get compressed, '' overwise
101 function compressRevisionText( &$text ) {
102 global $wgCompressRevisions;
103 if( !$wgCompressRevisions ) {
106 if( !function_exists( 'gzdeflate' ) ) {
107 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
110 $text = gzdeflate( $text );
115 * Returns the text associated with a "link" type old table row
118 function followLink( $link ) {
119 # Split the link into fields and values
120 $lines = explode( '\n', $link );
122 $locations = array();
123 foreach ( $lines as $line ) {
125 if ( $line{0} == '#' ) {
129 if ( preg_match( '/^(.*?)\s*:\s*(.*)$/', $line, $matches ) ) {
130 $field = strtolower($matches[1]);
131 $value = $matches[2];
132 if ( $field == 'hash' ) {
134 } elseif ( $field == 'location' ) {
135 $locations[] = $value;
140 if ( $hash === '' ) {
144 # Look in each specified location for the text
146 foreach ( $locations as $location ) {
147 $text = Article
::fetchFromLocation( $location, $hash );
148 if ( $text !== false ) {
159 function fetchFromLocation( $location, $hash ) {
160 global $wgLoadBalancer;
161 $fname = 'fetchFromLocation';
162 wfProfileIn( $fname );
164 $p = strpos( $location, ':' );
165 if ( $p === false ) {
166 wfProfileOut( $fname );
170 $type = substr( $location, 0, $p );
174 # MySQL locations are specified by mysql://<machineID>/<dbname>/<tblname>/<index>
175 # Machine ID 0 is the current connection
176 if ( preg_match( '/^mysql:\/\/(\d+)\/([A-Za-z_]+)\/([A-Za-z_]+)\/([A-Za-z_]+)$/',
177 $location, $matches ) ) {
178 $machineID = $matches[1];
179 $dbName = $matches[2];
180 $tblName = $matches[3];
181 $index = $matches[4];
182 if ( $machineID == 0 ) {
184 $db =& $this->getDB();
186 # Alternate connection
187 $db =& $wgLoadBalancer->getConnection( $machineID );
189 if ( array_key_exists( $machineId, $wgKnownMysqlServers ) ) {
190 # Try to open, return false on failure
191 $params = $wgKnownDBServers[$machineId];
192 $db = Database
::newFromParams( $params['server'], $params['user'], $params['password'],
193 $dbName, 1, DBO_IGNORE
);
196 if ( $db->isOpen() ) {
197 $index = $db->strencode( $index );
198 $res = $db->query( "SELECT blob_data FROM $dbName.$tblName " .
199 "WHERE blob_index='$index' " . $this->getSelectOptions(), $fname );
200 $row = $db->fetchObject( $res );
201 $text = $row->text_data
;
206 # File locations are of the form file://<filename>, relative to the current directory
207 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
208 $filename = strstr( $location, 'file://' );
209 $text = @file_get_contents
( $matches[1] );
211 if ( $text !== false ) {
212 # Got text, now we need to interpret it
213 # The first line contains information about how to do this
214 $p = strpos( $text, '\n' );
215 $type = substr( $text, 0, $p );
216 $text = substr( $text, $p +
1 );
221 $text = gzinflate( $text );
224 $object = unserialize( $text );
225 $text = $object->getItem( $hash );
231 wfProfileOut( $fname );
236 * Note that getContent/loadContent may follow redirects if
237 * not told otherwise, and so may cause a change to mTitle.
239 * Return the text of this revision
241 function getContent( $noredir ) {
244 # Get variables from query string :P
245 $action = $wgRequest->getText( 'action', 'view' );
246 $section = $wgRequest->getText( 'section' );
248 $fname = 'Article::getContent';
249 wfProfileIn( $fname );
251 if ( 0 == $this->getID() ) {
252 if ( 'edit' == $action ) {
253 wfProfileOut( $fname );
254 return ''; # was "newarticletext", now moved above the box)
256 wfProfileOut( $fname );
257 return wfMsg( 'noarticletext' );
259 $this->loadContent( $noredir );
260 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
261 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
262 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
265 wfProfileOut( $fname );
266 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
268 if($action=='edit') {
270 if($section=='new') {
271 wfProfileOut( $fname );
275 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
276 # comments to be stripped as well)
277 $rv=$this->getSection($this->mContent
,$section);
278 wfProfileOut( $fname );
282 wfProfileOut( $fname );
283 return $this->mContent
;
289 * This function returns the text of a section, specified by a number ($section).
290 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
291 * the first section before any such heading (section 0).
293 * If a section contains subsections, these are also returned.
295 function getSection($text,$section) {
297 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
298 # comments to be stripped as well)
300 $parser=new Parser();
301 $parser->mOutputType
=OT_WIKI
;
302 $striptext=$parser->strip($text, $striparray, true);
304 # now that we can be sure that no pseudo-sections are in the source,
305 # split it up by section
308 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
310 PREG_SPLIT_DELIM_CAPTURE
);
314 $headline=$secs[$section*2-1];
315 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
318 # translate wiki heading into level
319 if(strpos($hlevel,'=')!==false) {
320 $hlevel=strlen($hlevel);
323 $rv=$headline. $secs[$section*2];
327 while(!empty($secs[$count*2-1]) && !$break) {
329 $subheadline=$secs[$count*2-1];
330 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
331 $subhlevel=$matches[1];
332 if(strpos($subhlevel,'=')!==false) {
333 $subhlevel=strlen($subhlevel);
335 if($subhlevel > $hlevel) {
336 $rv.=$subheadline.$secs[$count*2];
338 if($subhlevel <= $hlevel) {
345 # reinsert stripped tags
346 $rv=$parser->unstrip($rv,$striparray);
347 $rv=$parser->unstripNoWiki($rv,$striparray);
354 * Return an array of the columns of the "cur"-table
356 function &getCurContentFields() {
357 global $wgArticleCurContentFields;
358 if ( !$wgArticleCurContentFields ) {
359 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
360 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
362 return $wgArticleCurContentFields;
366 * Return an array of the columns of the "old"-table
368 function &getOldContentFields() {
369 global $wgArticleOldContentFields;
370 if ( !$wgArticleOldContentFields ) {
371 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
372 'old_user','old_user_text','old_comment','old_flags' );
374 return $wgArticleOldContentFields;
378 * Load the revision (including cur_text) into this object
380 function loadContent( $noredir = false ) {
381 global $wgOut, $wgMwRedir, $wgRequest;
383 $dbr =& $this->getDB();
385 $oldid = $wgRequest->getVal( 'oldid' );
386 $redirect = $wgRequest->getVal( 'redirect' );
388 if ( $this->mContentLoaded
) return;
389 $fname = 'Article::loadContent';
391 # Pre-fill content with error message so that if something
392 # fails we'll have something telling us what we intended.
394 $t = $this->mTitle
->getPrefixedText();
395 if ( isset( $oldid ) ) {
396 $oldid = IntVal( $oldid );
397 $t .= ',oldid='.$oldid;
399 if ( isset( $redirect ) ) {
400 $redirect = ($redirect == 'no') ?
'no' : 'yes';
401 $t .= ',redirect='.$redirect;
403 $this->mContent
= wfMsg( 'missingarticle', $t );
405 if ( ! $oldid ) { # Retrieve current version
406 $id = $this->getID();
407 if ( 0 == $id ) return;
409 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
410 $this->getSelectOptions() );
411 if ( $s === false ) {
415 # If we got a redirect, follow it (unless we've been told
416 # not to by either the function parameter or the query
417 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
418 $rt = Title
::newFromRedirect( $s->cur_text
);
419 # process if title object is valid and not special:userlogout
420 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
421 # Gotta hand redirects to special pages differently:
422 # Fill the HTTP response "Location" header and ignore
423 # the rest of the page we're on.
425 if ( $rt->getInterwiki() != '' ) {
426 $wgOut->redirect( $rt->getFullURL() ) ;
429 if ( $rt->getNamespace() == NS_SPECIAL
) {
430 $wgOut->redirect( $rt->getFullURL() );
433 $rid = $rt->getArticleID();
435 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
436 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
438 if ( $redirRow !== false ) {
439 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
447 $this->mContent
= $s->cur_text
;
448 $this->mUser
= $s->cur_user
;
449 $this->mUserText
= $s->cur_user_text
;
450 $this->mComment
= $s->cur_comment
;
451 $this->mCounter
= $s->cur_counter
;
452 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
453 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
454 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
455 $this->mTitle
->mRestrictionsLoaded
= true;
456 } else { # oldid set, retrieve historical version
457 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
458 $fname, $this->getSelectOptions() );
459 if ( $s === false ) {
463 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
464 $this->mTitle
->getDBkey() != $s->old_title
) {
465 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
466 $this->mTitle
= $oldTitle;
467 $wgTitle = $oldTitle;
469 $this->mContent
= Article
::getRevisionText( $s );
470 $this->mUser
= $s->old_user
;
471 $this->mUserText
= $s->old_user_text
;
472 $this->mComment
= $s->old_comment
;
474 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
476 $this->mContentLoaded
= true;
477 return $this->mContent
;
481 * Gets the article text without using so many damn globals
482 * Returns false on error
484 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
487 if ( $this->mContentLoaded
) {
488 return $this->mContent
;
490 $this->mContent
= false;
492 $fname = 'Article::getContentWithout';
493 $dbr =& $this->getDB();
495 if ( ! $oldid ) { # Retrieve current version
496 $id = $this->getID();
501 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
502 $fname, $this->getSelectOptions() );
503 if ( $s === false ) {
507 # If we got a redirect, follow it (unless we've been told
508 # not to by either the function parameter or the query
510 $rt = Title
::newFromRedirect( $s->cur_text
);
511 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
512 $rid = $rt->getArticleID();
514 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
515 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
517 if ( $redirRow !== false ) {
518 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
526 $this->mContent
= $s->cur_text
;
527 $this->mUser
= $s->cur_user
;
528 $this->mUserText
= $s->cur_user_text
;
529 $this->mComment
= $s->cur_comment
;
530 $this->mCounter
= $s->cur_counter
;
531 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
532 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
533 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
534 $this->mTitle
->mRestrictionsLoaded
= true;
535 } else { # oldid set, retrieve historical version
536 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
537 $fname, $this->getSelectOptions() );
538 if ( $s === false ) {
541 $this->mContent
= Article
::getRevisionText( $s );
542 $this->mUser
= $s->old_user
;
543 $this->mUserText
= $s->old_user_text
;
544 $this->mComment
= $s->old_comment
;
546 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
548 $this->mContentLoaded
= true;
549 return $this->mContent
;
553 * Read/write accessor to select FOR UPDATE
555 function forUpdate( $x = NULL ) {
556 return wfSetVar( $this->mForUpdate
, $x );
560 * Get the database which should be used for reads
563 if ( $this->mForUpdate
) {
564 return wfGetDB( DB_MASTER
);
566 return wfGetDB( DB_SLAVE
);
571 * Get options for all SELECT statements
572 * Can pass an option array, to which the class-wide options will be appended
574 function getSelectOptions( $options = '' ) {
575 if ( $this->mForUpdate
) {
577 $options[] = 'FOR UPDATE';
579 $options = 'FOR UPDATE';
586 * Return the Article ID
589 if( $this->mTitle
) {
590 return $this->mTitle
->getArticleID();
597 * @todo document function
599 function getCount() {
600 if ( -1 == $this->mCounter
) {
601 $id = $this->getID();
602 $dbr =& $this->getDB();
603 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
604 'Article::getCount', $this->getSelectOptions() );
606 return $this->mCounter
;
610 * Would the given text make this article a "good" article (i.e.,
611 * suitable for including in the article count)?
613 function isCountable( $text ) {
614 global $wgUseCommaCount, $wgMwRedir;
616 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
617 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
618 $token = ($wgUseCommaCount ?
',' : '[[' );
619 if ( false === strstr( $text, $token ) ) { return 0; }
624 * Loads everything from cur except cur_text
625 * This isn't necessary for all uses, so it's only done if needed.
628 function loadLastEdit() {
630 if ( -1 != $this->mUser
) return;
632 $fname = 'Article::loadLastEdit';
634 $dbr =& $this->getDB();
635 $s = $dbr->getArray( 'cur',
636 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
637 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
639 if ( $s !== false ) {
640 $this->mUser
= $s->cur_user
;
641 $this->mUserText
= $s->cur_user_text
;
642 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
643 $this->mComment
= $s->cur_comment
;
644 $this->mMinorEdit
= $s->cur_minor_edit
;
648 function getTimestamp() {
649 $this->loadLastEdit();
650 return $this->mTimestamp
;
654 $this->loadLastEdit();
658 function getUserText() {
659 $this->loadLastEdit();
660 return $this->mUserText
;
663 function getComment() {
664 $this->loadLastEdit();
665 return $this->mComment
;
668 function getMinorEdit() {
669 $this->loadLastEdit();
670 return $this->mMinorEdit
;
673 function getContributors($limit = 0, $offset = 0) {
674 $fname = 'Article::getContributors';
676 # XXX: this is expensive; cache this info somewhere.
678 $title = $this->mTitle
;
680 $dbr =& $this->getDB();
681 $oldTable = $dbr->tableName( 'old' );
682 $userTable = $dbr->tableName( 'user' );
683 $encDBkey = $dbr->strencode( $title->getDBkey() );
684 $ns = $title->getNamespace();
685 $user = $this->getUser();
687 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
688 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
689 WHERE old_namespace = $user
690 AND old_title = $encDBkey
691 AND old_user != $user
693 ORDER BY timestamp DESC";
695 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
696 $sql .= ' '. $this->getSelectOptions();
698 $res = $dbr->query($sql, $fname);
700 while ( $line = $dbr->fetchObject( $res ) ) {
701 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
704 $dbr->freeResult($res);
709 * This is the default action of the script: just view the page of
713 global $wgUser, $wgOut, $wgLang, $wgRequest, $wgMwRedir, $wgOnlySysopsCanPatrol;
714 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
715 $sk = $wgUser->getSkin();
717 $fname = 'Article::view';
718 wfProfileIn( $fname );
719 # Get variables from query string
720 $oldid = $wgRequest->getVal( 'oldid' );
721 $diff = $wgRequest->getVal( 'diff' );
722 $rcid = $wgRequest->getVal( 'rcid' );
724 $wgOut->setArticleFlag( true );
725 $wgOut->setRobotpolicy( 'index,follow' );
726 # If we got diff and oldid in the query, we want to see a
727 # diff page instead of the article.
729 if ( !is_null( $diff ) ) {
730 require_once( 'DifferenceEngine.php' );
731 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
732 $de = new DifferenceEngine( $oldid, $diff, $rcid );
734 wfProfileOut( $fname );
736 # Run view updates for current revision only
737 $this->viewUpdates();
741 if ( empty( $oldid ) && $this->checkTouched() ) {
742 if( $wgOut->checkLastModified( $this->mTouched
) ){
744 } else if ( $this->tryFileCache() ) {
745 # tell wgOut that output is taken care of
747 $this->viewUpdates();
751 # Should the parser cache be used?
752 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
760 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
764 if ( !$outputDone ) {
765 $text = $this->getContent( false ); # May change mTitle by following a redirect
767 # Another whitelist check in case oldid or redirects are altering the title
768 if ( !$this->mTitle
->userCanRead() ) {
769 $wgOut->loginToUse();
775 # We're looking at an old revision
777 if ( !empty( $oldid ) ) {
778 $this->setOldSubtitle();
779 $wgOut->setRobotpolicy( 'noindex,follow' );
781 if ( '' != $this->mRedirectedFrom
) {
782 $sk = $wgUser->getSkin();
783 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
785 $s = wfMsg( 'redirectedfrom', $redir );
786 $wgOut->setSubtitle( $s );
788 # Can't cache redirects
792 # wrap user css and user js in pre and don't parse
793 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
795 $this->mTitle
->getNamespace() == NS_USER
&&
796 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
798 $wgOut->addWikiText( wfMsg('clearyourcache'));
799 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
800 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
802 $imageUrl = $wgStylePath.'/images/redirect.png';
803 $targetUrl = $rt->escapeLocalURL();
804 $titleText = htmlspecialchars( $rt->getPrefixedText() );
805 $link = $sk->makeLinkObj( $rt );
806 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'">' .
807 '<span class="redirectText">'.$link.'</span>' );
808 } else if ( $pcache ) {
809 # Display content and save to parser cache
810 $wgOut->addPrimaryWikiText( $text, $this );
812 # Display content, don't attempt to save to parser cache
813 $wgOut->addWikiText( $text );
816 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
817 # If we have been passed an &rcid= parameter, we want to give the user a
818 # chance to mark this new article as patrolled.
819 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
820 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
822 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
823 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
824 'action=markpatrolled&rcid='.$rcid )
828 # Put link titles into the link cache
829 $wgOut->transformBuffer();
831 # Add link titles as META keywords
832 $wgOut->addMetaTags() ;
834 $this->viewUpdates();
835 wfProfileOut( $fname );
839 * Theoretically we could defer these whole insert and update
840 * functions for after display, but that's taking a big leap
841 * of faith, and we want to be able to report database
842 * errors at some point.
845 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
846 global $wgOut, $wgUser, $wgMwRedir;
847 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
849 $fname = 'Article::insertNewArticle';
851 $this->mCountAdjustment
= $this->isCountable( $text );
853 $ns = $this->mTitle
->getNamespace();
854 $ttl = $this->mTitle
->getDBkey();
855 $text = $this->preSaveTransform( $text );
856 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
859 $now = wfTimestampNow();
860 $won = wfInvertTimestamp( $now );
862 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
863 $dbw =& wfGetDB( DB_MASTER
);
865 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
867 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
869 $dbw->insertArray( 'cur', array(
871 'cur_namespace' => $ns,
874 'cur_comment' => $summary,
875 'cur_user' => $wgUser->getID(),
876 'cur_timestamp' => $dbw->timestamp($now),
877 'cur_minor_edit' => $isminor,
879 'cur_restrictions' => '',
880 'cur_user_text' => $wgUser->getName(),
881 'cur_is_redirect' => $redir,
883 'cur_random' => $rand,
884 'cur_touched' => $dbw->timestamp($now),
885 'inverse_timestamp' => $won,
888 $newid = $dbw->insertId();
889 $this->mTitle
->resetArticleID( $newid );
891 Article
::onArticleCreate( $this->mTitle
);
892 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
895 if(!$this->mTitle
->userIsWatching()) $this->watch();
897 if ( $this->mTitle
->userIsWatching() ) {
902 # The talk page isn't in the regular link tables, so we need to update manually:
903 $talkns = $ns ^
1; # talk -> normal; normal -> talk
904 $dbw->updateArray( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
905 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
907 # standard deferred updates
908 $this->editUpdates( $text );
910 $this->showArticle( $text, wfMsg( 'newarticle' ) );
915 * Side effects: loads last edit
917 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '') {
918 $this->loadLastEdit();
919 $oldtext = $this->getContent( true );
920 if ($section != '') {
921 if($section=='new') {
922 if($summary) $subject="== {$summary} ==\n\n";
923 $text=$oldtext."\n\n".$subject.$text;
926 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
927 # comments to be stripped as well)
929 $parser=new Parser();
930 $parser->mOutputType
=OT_WIKI
;
931 $oldtext=$parser->strip($oldtext, $striparray, true);
933 # now that we can be sure that no pseudo-sections are in the source,
935 # Unfortunately we can't simply do a preg_replace because that might
936 # replace the wrong section, so we have to use the section counter instead
937 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
938 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
939 $secs[$section*2]=$text."\n\n"; // replace with edited
941 # section 0 is top (intro) section
944 # headline of old section - we need to go through this section
945 # to determine if there are any subsections that now need to
946 # be erased, as the mother section has been replaced with
947 # the text of all subsections.
948 $headline=$secs[$section*2-1];
949 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
952 # determine headline level for wikimarkup headings
953 if(strpos($hlevel,'=')!==false) {
954 $hlevel=strlen($hlevel);
957 $secs[$section*2-1]=''; // erase old headline
960 while(!empty($secs[$count*2-1]) && !$break) {
962 $subheadline=$secs[$count*2-1];
964 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
965 $subhlevel=$matches[1];
966 if(strpos($subhlevel,'=')!==false) {
967 $subhlevel=strlen($subhlevel);
969 if($subhlevel > $hlevel) {
970 // erase old subsections
971 $secs[$count*2-1]='';
974 if($subhlevel <= $hlevel) {
982 $text=join('',$secs);
983 # reinsert the stuff that we stripped out earlier
984 $text=$parser->unstrip($text,$striparray);
985 $text=$parser->unstripNoWiki($text,$striparray);
993 * @todo document this function
995 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
996 global $wgOut, $wgUser;
997 global $wgDBtransactions, $wgMwRedir;
998 global $wgUseSquid, $wgInternalServer;
1000 $fname = 'Article::updateArticle';
1003 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
1004 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
1005 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1007 $text = $m[1] . "\n"; # Remove all content but redirect
1009 else { $redir = 0; }
1011 $text = $this->preSaveTransform( $text );
1012 $dbw =& wfGetDB( DB_MASTER
);
1014 # Update article, but only if changed.
1016 # It's important that we either rollback or complete, otherwise an attacker could
1017 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1018 # could conceivably have the same effect, especially if cur is locked for long periods.
1019 if( $wgDBtransactions ) {
1020 $dbw->query( 'BEGIN', $fname );
1022 $userAbort = ignore_user_abort( true );
1025 $oldtext = $this->getContent( true );
1027 if ( 0 != strcmp( $text, $oldtext ) ) {
1028 $this->mCountAdjustment
= $this->isCountable( $text )
1029 - $this->isCountable( $oldtext );
1030 $now = wfTimestampNow();
1031 $won = wfInvertTimestamp( $now );
1033 # First update the cur row
1034 $dbw->updateArray( 'cur',
1036 'cur_text' => $text,
1037 'cur_comment' => $summary,
1038 'cur_minor_edit' => $me2,
1039 'cur_user' => $wgUser->getID(),
1040 'cur_timestamp' => $dbw->timestamp($now),
1041 'cur_user_text' => $wgUser->getName(),
1042 'cur_is_redirect' => $redir,
1044 'cur_touched' => $dbw->timestamp($now),
1045 'inverse_timestamp' => $won
1046 ), array( /* WHERE */
1047 'cur_id' => $this->getID(),
1048 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1052 if( $dbw->affectedRows() == 0 ) {
1053 /* Belated edit conflict! Run away!! */
1056 # Now insert the previous revision into old
1058 # This overwrites $oldtext if revision compression is on
1059 $flags = Article
::compressRevisionText( $oldtext );
1061 $dbw->insertArray( 'old',
1063 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1064 'old_namespace' => $this->mTitle
->getNamespace(),
1065 'old_title' => $this->mTitle
->getDBkey(),
1066 'old_text' => $oldtext,
1067 'old_comment' => $this->getComment(),
1068 'old_user' => $this->getUser(),
1069 'old_user_text' => $this->getUserText(),
1070 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1071 'old_minor_edit' => $me1,
1072 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1073 'old_flags' => $flags,
1077 $oldid = $dbw->insertId();
1079 $bot = (int)($wgUser->isBot() ||
$forceBot);
1080 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1081 $oldid, $this->getTimestamp(), $bot );
1082 Article
::onArticleEdit( $this->mTitle
);
1086 if( $wgDBtransactions ) {
1087 $dbw->query( 'COMMIT', $fname );
1089 ignore_user_abort( $userAbort );
1094 if (!$this->mTitle
->userIsWatching()) $this->watch();
1096 if ( $this->mTitle
->userIsWatching() ) {
1100 # standard deferred updates
1101 $this->editUpdates( $text );
1105 # Template namespace
1106 # Purge all articles linking here
1107 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1108 $titles = $this->mTitle
->getLinksTo();
1109 Title
::touchArray( $titles );
1110 if ( $wgUseSquid ) {
1111 foreach ( $titles as $title ) {
1112 $urls[] = $title->getInternalURL();
1118 if ( $wgUseSquid ) {
1119 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1120 $u = new SquidUpdate( $urls );
1124 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1130 * After we've either updated or inserted the article, update
1131 * the link tables and redirect to the new page.
1133 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1134 global $wgOut, $wgUser, $wgLinkCache;
1137 $wgLinkCache = new LinkCache();
1139 $wgLinkCache->forUpdate( true );
1141 # Get old version of link table to allow incremental link updates
1142 $wgLinkCache->preFill( $this->mTitle
);
1143 $wgLinkCache->clear();
1145 # Parse the text and replace links with placeholders
1146 $wgOut = new OutputPage();
1147 $wgOut->addWikiText( $text );
1149 # Look up the links in the DB and add them to the link cache
1150 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1152 if( $wgMwRedir->matchStart( $text ) )
1156 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1161 * @todo document this function a bit more
1163 function validate () {
1164 global $wgOut, $wgUseValidation;
1165 if( $wgUseValidation ) {
1166 require_once ( 'SpecialValidate.php' ) ;
1167 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1168 $wgOut->setRobotpolicy( 'noindex,follow' );
1169 if( $this->mTitle
->getNamespace() != 0 ) {
1170 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1173 $v = new Validation
;
1174 $v->validate_form( $this->mTitle
->getDBkey() );
1176 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1181 * Mark this particular edit as patrolled
1183 function markpatrolled() {
1184 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1185 $wgOut->setRobotpolicy( 'noindex,follow' );
1187 if ( !$wgUseRCPatrol )
1189 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1192 if ( $wgUser->getID() == 0 )
1194 $wgOut->loginToUse();
1197 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1199 $wgOut->sysopRequired();
1202 $rcid = $wgRequest->getVal( 'rcid' );
1203 if ( !is_null ( $rcid ) )
1205 RecentChange
::markPatrolled( $rcid );
1206 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1207 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1208 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1212 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1218 * Add or remove this page to my watchlist based on value of $add
1220 function watch( $add = true ) {
1221 global $wgUser, $wgOut, $wgLang;
1222 global $wgDeferredUpdateList;
1224 if ( 0 == $wgUser->getID() ) {
1225 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1228 if ( wfReadOnly() ) {
1229 $wgOut->readOnlyPage();
1233 $wgUser->addWatch( $this->mTitle
);
1235 $wgUser->removeWatch( $this->mTitle
);
1237 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1238 $wgOut->setRobotpolicy( 'noindex,follow' );
1240 $sk = $wgUser->getSkin() ;
1241 $link = $this->mTitle
->getPrefixedText();
1244 $text = wfMsg( 'addedwatchtext', $link );
1246 $text = wfMsg( 'removedwatchtext', $link );
1247 $wgOut->addWikiText( $text );
1249 $up = new UserUpdate();
1250 array_push( $wgDeferredUpdateList, $up );
1252 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1256 * Stop watching a page, it act just like a call to watch(false)
1258 function unwatch() {
1259 $this->watch( false );
1265 function protect( $limit = 'sysop' ) {
1266 global $wgUser, $wgOut, $wgRequest;
1268 if ( ! $wgUser->isSysop() ) {
1269 $wgOut->sysopRequired();
1272 if ( wfReadOnly() ) {
1273 $wgOut->readOnlyPage();
1276 $id = $this->mTitle
->getArticleID();
1278 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1282 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1283 $reason = $wgRequest->getText( 'wpReasonProtect' );
1286 $dbw =& wfGetDB( DB_MASTER
);
1287 $dbw->updateArray( 'cur',
1289 'cur_touched' => $dbw->timestamp(),
1290 'cur_restrictions' => (string)$limit
1291 ), array( /* WHERE */
1293 ), 'Article::protect'
1296 $log = new LogPage( 'protect' );
1297 if ( $limit === '' ) {
1298 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1300 $log->addEntry( 'protect', $this->mTitle
, $reason );
1302 $wgOut->redirect( $this->mTitle
->getFullURL() );
1305 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1306 return $this->confirmProtect( '', $reason, $limit );
1311 * Output protection confirmation dialog
1313 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1316 wfDebug( "Article::confirmProtect\n" );
1318 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1319 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1324 if ( $limit === '' ) {
1325 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1326 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1327 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1328 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1329 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1330 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1332 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1333 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1334 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1335 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1336 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1337 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1340 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1343 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1347 <label for='wpReasonProtect'>{$protcom}:</label>
1350 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1358 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1361 <label for='wpConfirmProtect'>{$check}</label>
1367 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1373 $wgOut->returnToMain( false );
1377 * Unprotect the pages
1379 function unprotect() {
1380 return $this->protect( '' );
1384 * UI entry point for page deletion
1387 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1388 $fname = 'Article::delete';
1389 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1390 $reason = $wgRequest->getText( 'wpReason' );
1392 # This code desperately needs to be totally rewritten
1395 if ( ( ! $wgUser->isSysop() ) ) {
1396 $wgOut->sysopRequired();
1399 if ( wfReadOnly() ) {
1400 $wgOut->readOnlyPage();
1404 # Better double-check that it hasn't been deleted yet!
1405 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1406 if ( ( '' == trim( $this->mTitle
->getText() ) )
1407 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1408 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1413 $this->doDelete( $reason );
1417 # determine whether this page has earlier revisions
1418 # and insert a warning if it does
1419 # we select the text because it might be useful below
1420 $dbr =& $this->getDB();
1421 $ns = $this->mTitle
->getNamespace();
1422 $title = $this->mTitle
->getDBkey();
1423 $old = $dbr->getArray( 'old',
1424 array( 'old_text', 'old_flags' ),
1426 'old_namespace' => $ns,
1427 'old_title' => $title,
1428 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1431 if( $old !== false && !$confirm ) {
1432 $skin=$wgUser->getSkin();
1433 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1434 $wgOut->addHTML( $skin->historyLink() .'</b>');
1438 $s = $dbr->getArray( 'cur',
1439 array( 'cur_text' ),
1441 'cur_namespace' => $ns,
1442 'cur_title' => $title,
1443 ), $fname, $this->getSelectOptions()
1446 if( $s !== false ) {
1447 # if this is a mini-text, we can paste part of it into the deletion reason
1449 #if this is empty, an earlier revision may contain "useful" text
1451 if($s->cur_text
!= '') {
1455 $text = Article
::getRevisionText( $old );
1461 $length=strlen($text);
1463 # this should not happen, since it is not possible to store an empty, new
1464 # page. Let's insert a standard text in case it does, though
1465 if($length == 0 && $reason === '') {
1466 $reason = wfMsg('exblank');
1469 if($length < 500 && $reason === '') {
1471 # comment field=255, let's grep the first 150 to have some user
1473 $text=substr($text,0,150);
1474 # let's strip out newlines and HTML tags
1475 $text=preg_replace('/\"/',"'",$text);
1476 $text=preg_replace('/\</','<',$text);
1477 $text=preg_replace('/\>/','>',$text);
1478 $text=preg_replace("/[\n\r]/",'',$text);
1480 $reason=wfMsg('excontent'). " '".$text;
1482 $reason=wfMsg('exbeforeblank') . " '".$text;
1484 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1489 return $this->confirmDelete( '', $reason );
1493 * Output deletion confirmation dialog
1495 function confirmDelete( $par, $reason ) {
1498 wfDebug( "Article::confirmDelete\n" );
1500 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1501 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1502 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1503 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1505 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1507 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1508 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1509 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1512 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1516 <label for='wpReason'>{$delcom}:</label>
1519 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1527 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1530 <label for='wpConfirm'>{$check}</label>
1536 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1542 $wgOut->returnToMain( false );
1547 * Perform a deletion and output success or failure messages
1549 function doDelete( $reason ) {
1550 global $wgOut, $wgUser, $wgLang;
1551 $fname = 'Article::doDelete';
1552 wfDebug( $fname."\n" );
1554 if ( $this->doDeleteArticle( $reason ) ) {
1555 $deleted = $this->mTitle
->getPrefixedText();
1557 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1558 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1560 $sk = $wgUser->getSkin();
1561 $loglink = $sk->makeKnownLink( $wgLang->getNsText( NS_PROJECT
) .
1562 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1564 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1566 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1567 $wgOut->returnToMain( false );
1569 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1574 * Back-end article deletion
1575 * Deletes the article with database consistency, writes logs, purges caches
1578 function doDeleteArticle( $reason ) {
1579 global $wgUser, $wgLang;
1580 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1582 $fname = 'Article::doDeleteArticle';
1583 wfDebug( $fname."\n" );
1585 $dbw =& wfGetDB( DB_MASTER
);
1586 $ns = $this->mTitle
->getNamespace();
1587 $t = $this->mTitle
->getDBkey();
1588 $id = $this->mTitle
->getArticleID();
1590 if ( $t == '' ||
$id == 0 ) {
1594 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1595 array_push( $wgDeferredUpdateList, $u );
1597 $linksTo = $this->mTitle
->getLinksTo();
1600 if ( $wgUseSquid ) {
1602 $this->mTitle
->getInternalURL(),
1603 $this->mTitle
->getInternalURL( 'history' )
1605 foreach ( $linksTo as $linkTo ) {
1606 $urls[] = $linkTo->getInternalURL();
1609 $u = new SquidUpdate( $urls );
1610 array_push( $wgDeferredUpdateList, $u );
1614 # Client and file cache invalidation
1615 Title
::touchArray( $linksTo );
1617 # Move article and history to the "archive" table
1618 $archiveTable = $dbw->tableName( 'archive' );
1619 $oldTable = $dbw->tableName( 'old' );
1620 $curTable = $dbw->tableName( 'cur' );
1621 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1622 $linksTable = $dbw->tableName( 'links' );
1623 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1625 $dbw->insertSelect( 'archive', 'cur',
1627 'ar_namespace' => 'cur_namespace',
1628 'ar_title' => 'cur_title',
1629 'ar_text' => 'cur_text',
1630 'ar_comment' => 'cur_comment',
1631 'ar_user' => 'cur_user',
1632 'ar_user_text' => 'cur_user_text',
1633 'ar_timestamp' => 'cur_timestamp',
1634 'ar_minor_edit' => 'cur_minor_edit',
1637 'cur_namespace' => $ns,
1642 $dbw->insertSelect( 'archive', 'old',
1644 'ar_namespace' => 'old_namespace',
1645 'ar_title' => 'old_title',
1646 'ar_text' => 'old_text',
1647 'ar_comment' => 'old_comment',
1648 'ar_user' => 'old_user',
1649 'ar_user_text' => 'old_user_text',
1650 'ar_timestamp' => 'old_timestamp',
1651 'ar_minor_edit' => 'old_minor_edit',
1652 'ar_flags' => 'old_flags'
1654 'old_namespace' => $ns,
1659 # Now that it's safely backed up, delete it
1661 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1662 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1663 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1665 # Finally, clean up the link tables
1666 $t = $this->mTitle
->getPrefixedDBkey();
1668 Article
::onArticleDelete( $this->mTitle
);
1670 # Insert broken links
1671 $brokenLinks = array();
1672 foreach ( $linksTo as $titleObj ) {
1673 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1674 $linkID = $titleObj->getArticleID();
1675 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1677 $dbw->insertArray( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1680 $dbw->delete( 'links', array( 'l_to' => $id ) );
1681 $dbw->delete( 'links', array( 'l_from' => $id ) );
1682 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1683 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1684 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1687 $log = new LogPage( 'delete' );
1688 $log->addEntry( 'delete', $this->mTitle
, $reason );
1690 # Clear the cached article id so the interface doesn't act like we exist
1691 $this->mTitle
->resetArticleID( 0 );
1692 $this->mTitle
->mArticleID
= 0;
1697 * Revert a modification
1699 function rollback() {
1700 global $wgUser, $wgLang, $wgOut, $wgRequest;
1701 $fname = 'Article::rollback';
1703 if ( ! $wgUser->isSysop() ) {
1704 $wgOut->sysopRequired();
1707 if ( wfReadOnly() ) {
1708 $wgOut->readOnlyPage( $this->getContent( true ) );
1711 $dbw =& wfGetDB( DB_MASTER
);
1713 # Enhanced rollback, marks edits rc_bot=1
1714 $bot = $wgRequest->getBool( 'bot' );
1716 # Replace all this user's current edits with the next one down
1717 $tt = $this->mTitle
->getDBKey();
1718 $n = $this->mTitle
->getNamespace();
1720 # Get the last editor, lock table exclusively
1721 $s = $dbw->getArray( 'cur',
1722 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1723 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1724 $fname, 'FOR UPDATE'
1726 if( $s === false ) {
1728 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1731 $ut = $dbw->strencode( $s->cur_user_text
);
1732 $uid = $s->cur_user
;
1735 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1736 if( $from != $s->cur_user_text
) {
1737 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1738 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1739 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1740 htmlspecialchars( $from ),
1741 htmlspecialchars( $s->cur_user_text
) ) );
1742 if($s->cur_comment
!= '') {
1744 wfMsg('editcomment',
1745 htmlspecialchars( $s->cur_comment
) ) );
1750 # Get the last edit not by this guy
1751 $s = $dbw->getArray( 'old',
1752 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1754 'old_namespace' => $n,
1756 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1757 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1759 if( $s === false ) {
1761 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1762 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1767 # Mark all reverted edits as bot
1768 $dbw->updateArray( 'recentchanges',
1771 ), array( /* WHERE */
1773 "rc_timestamp > '{$s->old_timestamp}'",
1779 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1780 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1781 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1782 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1783 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1784 Article
::onArticleEdit( $this->mTitle
);
1785 $wgOut->returnToMain( false );
1790 * Do standard deferred updates after page view
1793 function viewUpdates() {
1794 global $wgDeferredUpdateList;
1795 if ( 0 != $this->getID() ) {
1796 global $wgDisableCounters;
1797 if( !$wgDisableCounters ) {
1798 Article
::incViewCount( $this->getID() );
1799 $u = new SiteStatsUpdate( 1, 0, 0 );
1800 array_push( $wgDeferredUpdateList, $u );
1803 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1804 $this->mTitle
->getDBkey() );
1805 array_push( $wgDeferredUpdateList, $u );
1809 * Do standard deferred updates after page edit.
1810 * Every 1000th edit, prune the recent changes table.
1813 function editUpdates( $text ) {
1814 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1815 global $wgMessageCache;
1818 if ( 0 == mt_rand( 0, 999 ) ) {
1819 $dbw =& wfGetDB( DB_MASTER
);
1820 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1821 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1822 $dbw->query( $sql );
1824 $id = $this->getID();
1825 $title = $this->mTitle
->getPrefixedDBkey();
1826 $shortTitle = $this->mTitle
->getDBkey();
1828 $adj = $this->mCountAdjustment
;
1831 $u = new LinksUpdate( $id, $title );
1832 array_push( $wgDeferredUpdateList, $u );
1833 $u = new SiteStatsUpdate( 0, 1, $adj );
1834 array_push( $wgDeferredUpdateList, $u );
1835 $u = new SearchUpdate( $id, $title, $text );
1836 array_push( $wgDeferredUpdateList, $u );
1838 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1839 array_push( $wgDeferredUpdateList, $u );
1841 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1842 $wgMessageCache->replace( $shortTitle, $text );
1848 * @todo document this function
1851 function setOldSubtitle() {
1852 global $wgLang, $wgOut, $wgUser;
1854 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1855 $sk = $wgUser->getSkin();
1856 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1857 $r = wfMsg( 'revisionasofwithlink', $td, $lnk );
1858 $wgOut->setSubtitle( $r );
1862 * This function is called right before saving the wikitext,
1863 * so we can do things like signatures and links-in-context.
1865 function preSaveTransform( $text ) {
1866 global $wgParser, $wgUser;
1867 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1870 /* Caching functions */
1872 # checkLastModified returns true if it has taken care of all
1873 # output to the client that is necessary for this request.
1874 # (that is, it has sent a cached version of the page)
1875 function tryFileCache() {
1876 static $called = false;
1878 wfDebug( " tryFileCache() -- called twice!?\n" );
1882 if($this->isFileCacheable()) {
1883 $touched = $this->mTouched
;
1884 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1885 # Expire the main page quicker
1886 $expire = wfUnix2Timestamp( time() - 3600 );
1887 $touched = max( $expire, $touched );
1889 $cache = new CacheManager( $this->mTitle
);
1890 if($cache->isFileCacheGood( $touched )) {
1892 wfDebug( " tryFileCache() - about to load\n" );
1893 $cache->loadFromFileCache();
1896 wfDebug( " tryFileCache() - starting buffer\n" );
1897 ob_start( array(&$cache, 'saveToFileCache' ) );
1900 wfDebug( " tryFileCache() - not cacheable\n" );
1904 function isFileCacheable() {
1905 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1906 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1908 return $wgUseFileCache
1909 and (!$wgShowIPinHeader)
1910 and ($this->getID() != 0)
1911 and ($wgUser->getId() == 0)
1912 and (!$wgUser->getNewtalk())
1913 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1914 and (empty( $action ) ||
$action == 'view')
1915 and (!isset($oldid))
1917 and (!isset($redirect))
1918 and (!isset($printable))
1919 and (!$this->mRedirectedFrom
);
1922 # Loads cur_touched and returns a value indicating if it should be used
1923 function checkTouched() {
1924 $fname = 'Article::checkTouched';
1925 $id = $this->getID();
1926 $dbr =& $this->getDB();
1927 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1928 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1929 if( $s !== false ) {
1930 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1931 return !$s->cur_is_redirect
;
1937 # Edit an article without doing all that other stuff
1938 function quickEdit( $text, $comment = '', $minor = 0 ) {
1939 global $wgUser, $wgMwRedir;
1940 $fname = 'Article::quickEdit';
1941 wfProfileIn( $fname );
1943 $dbw =& wfGetDB( DB_MASTER
);
1944 $ns = $this->mTitle
->getNamespace();
1945 $dbkey = $this->mTitle
->getDBkey();
1946 $encDbKey = $dbw->strencode( $dbkey );
1947 $timestamp = wfTimestampNow();
1950 $dbw->insertSelect( 'old', 'cur',
1952 'old_namespace' => 'cur_namespace',
1953 'old_title' => 'cur_title',
1954 'old_text' => 'cur_text',
1955 'old_comment' => 'cur_comment',
1956 'old_user' => 'cur_user',
1957 'old_user_text' => 'cur_user_text',
1958 'old_timestamp' => 'cur_timestamp',
1959 'inverse_timestamp' => '99999999999999-cur_timestamp',
1961 'cur_namespace' => $ns,
1962 'cur_title' => $dbkey,
1966 # Use the affected row count to determine if the article is new
1967 $numRows = $dbw->affectedRows();
1969 # Make an array of fields to be inserted
1971 'cur_text' => $text,
1972 'cur_timestamp' => $timestamp,
1973 'cur_user' => $wgUser->getID(),
1974 'cur_user_text' => $wgUser->getName(),
1975 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1976 'cur_comment' => $comment,
1977 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ?
1 : 0,
1978 'cur_minor_edit' => intval($minor),
1979 'cur_touched' => $dbw->timestamp($timestamp),
1984 $fields['cur_is_new'] = 0;
1985 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1987 # Insert new article
1988 $fields['cur_is_new'] = 1;
1989 $fields['cur_namespace'] = $ns;
1990 $fields['cur_title'] = $dbkey;
1991 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1992 $dbw->insertArray( 'cur', $fields, $fname );
1994 wfProfileOut( $fname );
1997 /* static */ function incViewCount( $id ) {
1998 $id = intval( $id );
1999 global $wgHitcounterUpdateFreq;
2001 $dbw =& wfGetDB( DB_MASTER
);
2002 $curTable = $dbw->tableName( 'cur' );
2003 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2004 $acchitsTable = $dbw->tableName( 'acchits' );
2006 if( $wgHitcounterUpdateFreq <= 1 ){ //
2007 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2011 # Not important enough to warrant an error page in case of failure
2012 $oldignore = $dbw->ignoreErrors( true );
2014 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2016 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2017 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2018 # Most of the time (or on SQL errors), skip row count check
2019 $dbw->ignoreErrors( $oldignore );
2023 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2024 $row = $dbw->fetchObject( $res );
2025 $rown = intval( $row->n
);
2026 if( $rown >= $wgHitcounterUpdateFreq ){
2027 wfProfileIn( 'Article::incViewCount-collect' );
2028 $old_user_abort = ignore_user_abort( true );
2030 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2031 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2032 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2034 $dbw->query("DELETE FROM $hitcounterTable");
2035 $dbw->query('UNLOCK TABLES');
2036 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2037 'WHERE cur_id = hc_id');
2038 $dbw->query("DROP TABLE $acchitsTable");
2040 ignore_user_abort( $old_user_abort );
2041 wfProfileOut( 'Article::incViewCount-collect' );
2043 $dbw->ignoreErrors( $oldignore );
2047 * The onArticle*() functions are supposed to be a kind of hooks
2048 * which should be called whenever any of the specified actions
2051 * This is a good place to put code to clear caches, for instance.
2053 * This is called on page move and undelete, as well as edit
2055 * @param $title_obj a title object
2057 function onArticleCreate($title_obj) {
2058 global $wgUseSquid, $wgDeferredUpdateList;
2060 $titles = $title_obj->getBrokenLinksTo();
2063 if ( $wgUseSquid ) {
2064 $urls = $title_obj->getSquidURLs();
2065 foreach ( $titles as $linkTitle ) {
2066 $urls[] = $linkTitle->getInternalURL();
2068 $u = new SquidUpdate( $urls );
2069 array_push( $wgDeferredUpdateList, $u );
2072 # Clear persistent link cache
2073 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2079 function onArticleDelete($title_obj) {
2080 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2086 function onArticleEdit($title_obj) {
2087 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2092 * Info about this page
2095 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgAllowPageInfo;
2096 $fname = 'Article::info';
2098 if ( !$wgAllowPageInfo ) {
2099 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2103 $dbr =& $this->getDB();
2105 $basenamespace = $wgTitle->getNamespace() & (~
1);
2106 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2107 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2108 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2109 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2110 $wgOut->setPagetitle( $fullTitle );
2111 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2113 # first, see if the page exists at all.
2114 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2116 $wgOut->addHTML( wfMsg('noarticletext') );
2118 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2119 $this->getSelectOptions() );
2120 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2121 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2122 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2124 # to find number of distinct authors, we need to do some
2125 # funny stuff because of the cur/old table split:
2126 # - first, find the name of the 'cur' author
2127 # - then, find the number of *other* authors in 'old'
2130 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2131 $this->getSelectOptions() );
2133 # find number of 'old' authors excluding 'cur' author
2134 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2135 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2136 $this->getSelectOptions() ) +
1;
2138 # now for the Talk page ...
2139 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2140 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2143 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2147 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2148 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2150 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2154 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2155 $this->getSelectOptions() );
2156 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2157 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2158 $fname, $this->getSelectOptions() );
2160 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );