4 # Class representing a Wikipedia article and history.
5 # See design.doc for an overview.
7 # Note: edit user interface and cache support functions have been
8 # moved to separate EditPage and CacheManager classes.
10 require_once ( 'CacheManager.php' );
11 include_once ( 'SpecialValidate.php' ) ;
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
17 /* private */ var $mContent, $mContentLoaded;
18 /* private */ var $mUser, $mTimestamp, $mUserText;
19 /* private */ var $mCounter, $mComment, $mCountAdjustment;
20 /* private */ var $mMinorEdit, $mRedirectedFrom;
21 /* private */ var $mTouched, $mFileCache, $mTitle;
22 /* private */ var $mId, $mTable;
24 function Article( &$title ) {
25 $this->mTitle
=& $title;
29 /* private */ function clear()
31 $this->mContentLoaded
= false;
32 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
33 $this->mRedirectedFrom
= $this->mUserText
=
34 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
35 $this->mCountAdjustment
= 0;
36 $this->mTouched
= '19700101000000';
39 # Get revision text associated with an old or archive row
40 # $row is usually an object from wfFetchRow(), both the flags and the text field must be included
41 /* static */ function getRevisionText( $row, $prefix = 'old_' ) {
43 $textField = $prefix . 'text';
44 $flagsField = $prefix . 'flags';
46 if ( isset( $row->$flagsField ) ) {
47 $flags = explode( ",", $row->$flagsField );
52 if ( isset( $row->$textField ) ) {
53 $text = $row->$textField;
58 if ( in_array( 'link', $flags ) ) {
60 $text = Article
::followLink( $text );
61 } elseif ( in_array( 'gzip', $flags ) ) {
62 # Deal with optional compression of archived pages.
63 # This can be done periodically via maintenance/compressOld.php, and
64 # as pages are saved if $wgCompressRevisions is set.
65 return gzinflate( $text );
70 /* static */ function compressRevisionText( &$text ) {
71 global $wgCompressRevisions;
72 if( !$wgCompressRevisions ) {
75 if( !function_exists( 'gzdeflate' ) ) {
76 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
79 $text = gzdeflate( $text );
83 # Returns the text associated with a "link" type old table row
84 /* static */ function followLink( $link ) {
85 # Split the link into fields and values
86 $lines = explode( '\n', $link );
89 foreach ( $lines as $line ) {
91 if ( $line{0} == '#' ) {
95 if ( preg_match( '/^(.*?)\s*:\s*(.*)$/', $line, $matches ) ) {
96 $field = strtolower($matches[1]);
98 if ( $field == 'hash' ) {
100 } elseif ( $field == 'location' ) {
101 $locations[] = $value;
106 if ( $hash === '' ) {
110 # Look in each specified location for the text
112 foreach ( $locations as $location ) {
113 $text = Article
::fetchFromLocation( $location, $hash );
114 if ( $text !== false ) {
122 /* static */ function fetchFromLocation( $location, $hash ) {
123 global $wgLoadBalancer;
124 $fname = 'fetchFromLocation';
125 wfProfileIn( $fname );
127 $p = strpos( $location, ':' );
128 if ( $p === false ) {
129 wfProfileOut( $fname );
133 $type = substr( $location, 0, $p );
137 # MySQL locations are specified by mysql://<machineID>/<dbname>/<tblname>/<index>
138 # Machine ID 0 is the current connection
139 if ( preg_match( '/^mysql:\/\/(\d+)\/([A-Za-z_]+)\/([A-Za-z_]+)\/([A-Za-z_]+)$/',
140 $location, $matches ) ) {
141 $machineID = $matches[1];
142 $dbName = $matches[2];
143 $tblName = $matches[3];
144 $index = $matches[4];
145 if ( $machineID == 0 ) {
147 $db =& wfGetDB( DB_SLAVE
);
149 # Alternate connection
150 $db =& $wgLoadBalancer->getConnection( $machineID );
152 if ( array_key_exists( $machineId, $wgKnownMysqlServers ) ) {
153 # Try to open, return false on failure
154 $params = $wgKnownDBServers[$machineId];
155 $db = Database
::newFromParams( $params['server'], $params['user'], $params['password'],
156 $dbName, 1, DBO_IGNORE
);
159 if ( $db->isOpen() ) {
160 $index = $db->strencode( $index );
161 $res = $db->query( "SELECT blob_data FROM $dbName.$tblName WHERE blob_index='$index'", $fname );
162 $row = $db->fetchObject( $res );
163 $text = $row->text_data
;
168 # File locations are of the form file://<filename>, relative to the current directory
169 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
170 $filename = strstr( $location, 'file://' );
171 $text = @file_get_contents
( $matches[1] );
173 if ( $text !== false ) {
174 # Got text, now we need to interpret it
175 # The first line contains information about how to do this
176 $p = strpos( $text, '\n' );
177 $type = substr( $text, 0, $p );
178 $text = substr( $text, $p +
1 );
183 $text = gzinflate( $text );
186 $object = unserialize( $text );
187 $text = $object->getItem( $hash );
193 wfProfileOut( $fname );
197 # Note that getContent/loadContent may follow redirects if
198 # not told otherwise, and so may cause a change to mTitle.
200 # Return the text of this revision
201 function getContent( $noredir )
205 # Get variables from query string :P
206 $action = $wgRequest->getText( 'action', 'view' );
207 $section = $wgRequest->getText( 'section' );
209 $fname = 'Article::getContent';
210 wfProfileIn( $fname );
212 if ( 0 == $this->getID() ) {
213 if ( 'edit' == $action ) {
214 wfProfileOut( $fname );
215 return ''; # was "newarticletext", now moved above the box)
217 wfProfileOut( $fname );
218 return wfMsg( 'noarticletext' );
220 $this->loadContent( $noredir );
223 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
224 ( $this->mTitle
->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
225 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
229 wfProfileOut( $fname );
230 return $this->mContent
. "\n" .wfMsg('anontalkpagetext'); }
232 if($action=='edit') {
234 if($section=='new') {
235 wfProfileOut( $fname );
239 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
240 # comments to be stripped as well)
241 $rv=$this->getSection($this->mContent
,$section);
242 wfProfileOut( $fname );
246 wfProfileOut( $fname );
247 return $this->mContent
;
252 # This function returns the text of a section, specified by a number ($section).
253 # A section is text under a heading like == Heading == or <h1>Heading</h1>, or
254 # the first section before any such heading (section 0).
256 # If a section contains subsections, these are also returned.
258 function getSection($text,$section) {
260 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
261 # comments to be stripped as well)
263 $parser=new Parser();
264 $parser->mOutputType
=OT_WIKI
;
265 $striptext=$parser->strip($text, $striparray, true);
267 # now that we can be sure that no pseudo-sections are in the source,
268 # split it up by section
271 '/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
273 PREG_SPLIT_DELIM_CAPTURE
);
277 $headline=$secs[$section*2-1];
278 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
281 # translate wiki heading into level
282 if(strpos($hlevel,'=')!==false) {
283 $hlevel=strlen($hlevel);
286 $rv=$headline. $secs[$section*2];
290 while(!empty($secs[$count*2-1]) && !$break) {
292 $subheadline=$secs[$count*2-1];
293 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
294 $subhlevel=$matches[1];
295 if(strpos($subhlevel,'=')!==false) {
296 $subhlevel=strlen($subhlevel);
298 if($subhlevel > $hlevel) {
299 $rv.=$subheadline.$secs[$count*2];
301 if($subhlevel <= $hlevel) {
308 # reinsert stripped tags
309 $rv=$parser->unstrip($rv,$striparray);
310 $rv=$parser->unstripNoWiki($rv,$striparray);
316 # Return an array of the columns of the "cur"-table
317 function &getCurContentFields() {
318 global $wgArticleCurContentFields;
319 if ( !$wgArticleCurContentFields ) {
320 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
321 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
323 return $wgArticleCurContentFields;
326 # Return an array of the columns of the "old"-table
327 function &getOldContentFields() {
328 global $wgArticleOldContentFields;
329 if ( !$wgArticleOldContentFields ) {
330 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
331 'old_user','old_user_text','old_comment','old_flags' );
333 return $wgArticleOldContentFields;
336 # Load the revision (including cur_text) into this object
337 function loadContent( $noredir = false )
339 global $wgOut, $wgMwRedir, $wgRequest;
341 $dbr =& wfGetDB( DB_SLAVE
);
343 $oldid = $wgRequest->getVal( 'oldid' );
344 $redirect = $wgRequest->getVal( 'redirect' );
346 if ( $this->mContentLoaded
) return;
347 $fname = 'Article::loadContent';
349 # Pre-fill content with error message so that if something
350 # fails we'll have something telling us what we intended.
352 $t = $this->mTitle
->getPrefixedText();
353 if ( isset( $oldid ) ) {
354 $oldid = IntVal( $oldid );
355 $t .= ",oldid={$oldid}";
357 if ( isset( $redirect ) ) {
358 $redirect = ($redirect == 'no') ?
'no' : 'yes';
359 $t .= ",redirect={$redirect}";
361 $this->mContent
= wfMsg( 'missingarticle', $t );
363 if ( ! $oldid ) { # Retrieve current version
364 $id = $this->getID();
365 if ( 0 == $id ) return;
367 $s = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname );
368 if ( $s === false ) {
372 # If we got a redirect, follow it (unless we've been told
373 # not to by either the function parameter or the query
374 if ( ( 'no' != $redirect ) && ( false == $noredir ) &&
375 ( $wgMwRedir->matchStart( $s->cur_text
) ) ) {
376 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/',
377 $s->cur_text
, $m ) ) {
378 $rt = Title
::newFromText( $m[1] );
380 # Gotta hand redirects to special pages differently:
381 # Fill the HTTP response "Location" header and ignore
382 # the rest of the page we're on.
384 if ( $rt->getInterwiki() != '' ) {
385 $wgOut->redirect( $rt->getFullURL() ) ;
388 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
389 $wgOut->redirect( $rt->getFullURL() );
392 $rid = $rt->getArticleID();
394 $redirRow = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $rid ), $fname );
396 if ( $redirRow !== false ) {
397 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
406 $this->mContent
= $s->cur_text
;
407 $this->mUser
= $s->cur_user
;
408 $this->mUserText
= $s->cur_user_text
;
409 $this->mComment
= $s->cur_comment
;
410 $this->mCounter
= $s->cur_counter
;
411 $this->mTimestamp
= $s->cur_timestamp
;
412 $this->mTouched
= $s->cur_touched
;
413 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
414 $this->mTitle
->mRestrictionsLoaded
= true;
415 } else { # oldid set, retrieve historical version
416 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ), $fname );
417 if ( $s === false ) {
421 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
422 $this->mTitle
->getDBkey() != $s->old_title
) {
423 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
424 $this->mTitle
= $oldTitle;
425 $wgTitle = $oldTitle;
427 $this->mContent
= Article
::getRevisionText( $s );
428 $this->mUser
= $s->old_user
;
429 $this->mUserText
= $s->old_user_text
;
430 $this->mComment
= $s->old_comment
;
432 $this->mTimestamp
= $s->old_timestamp
;
434 $this->mContentLoaded
= true;
435 return $this->mContent
;
438 # Gets the article text without using so many damn globals
439 # Returns false on error
440 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
443 if ( $this->mContentLoaded
) {
444 return $this->mContent
;
446 $this->mContent
= false;
448 $fname = 'Article::getContentWithout';
449 $dbr =& wfGetDB( DB_SLAVE
);
451 if ( ! $oldid ) { # Retrieve current version
452 $id = $this->getID();
457 $s = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname );
458 if ( $s === false ) {
462 # If we got a redirect, follow it (unless we've been told
463 # not to by either the function parameter or the query
464 if ( !$noredir && $wgMwRedir->matchStart( $s->cur_text
) ) {
465 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/',
466 $s->cur_text
, $m ) ) {
467 $rt = Title
::newFromText( $m[1] );
468 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != Namespace::getSpecial() ) {
469 $rid = $rt->getArticleID();
471 $redirRow = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $rid ), $fname );
473 if ( $redirRow !== false ) {
474 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
483 $this->mContent
= $s->cur_text
;
484 $this->mUser
= $s->cur_user
;
485 $this->mUserText
= $s->cur_user_text
;
486 $this->mComment
= $s->cur_comment
;
487 $this->mCounter
= $s->cur_counter
;
488 $this->mTimestamp
= $s->cur_timestamp
;
489 $this->mTouched
= $s->cur_touched
;
490 $this->mTitle
->mRestrictions
= explode( ",", trim( $s->cur_restrictions
) );
491 $this->mTitle
->mRestrictionsLoaded
= true;
492 } else { # oldid set, retrieve historical version
493 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ) );
494 if ( $s === false ) {
497 $this->mContent
= Article
::getRevisionText( $s );
498 $this->mUser
= $s->old_user
;
499 $this->mUserText
= $s->old_user_text
;
500 $this->mComment
= $s->old_comment
;
502 $this->mTimestamp
= $s->old_timestamp
;
504 $this->mContentLoaded
= true;
505 return $this->mContent
;
509 if( $this->mTitle
) {
510 return $this->mTitle
->getArticleID();
518 if ( -1 == $this->mCounter
) {
519 $id = $this->getID();
520 $dbr =& wfGetDB( DB_SLAVE
);
521 $this->mCounter
= $dbr->getField( 'cur', 'cur_counter', "cur_id={$id}" );
523 return $this->mCounter
;
526 # Would the given text make this article a "good" article (i.e.,
527 # suitable for including in the article count)?
529 function isCountable( $text )
531 global $wgUseCommaCount, $wgMwRedir;
533 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
534 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
535 $token = ($wgUseCommaCount ?
',' : '[[' );
536 if ( false === strstr( $text, $token ) ) { return 0; }
540 # Loads everything from cur except cur_text
541 # This isn't necessary for all uses, so it's only done if needed.
543 /* private */ function loadLastEdit()
546 if ( -1 != $this->mUser
) return;
548 $fname = 'Article::loadLastEdit';
550 $dbr =& wfGetDB( DB_SLAVE
);
551 $s = $dbr->getArray( 'cur',
552 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
553 array( 'cur_id' => $this->getID() ), $fname );
555 if ( $s !== false ) {
556 $this->mUser
= $s->cur_user
;
557 $this->mUserText
= $s->cur_user_text
;
558 $this->mTimestamp
= $s->cur_timestamp
;
559 $this->mComment
= $s->cur_comment
;
560 $this->mMinorEdit
= $s->cur_minor_edit
;
564 function getTimestamp()
566 $this->loadLastEdit();
567 return $this->mTimestamp
;
572 $this->loadLastEdit();
576 function getUserText()
578 $this->loadLastEdit();
579 return $this->mUserText
;
582 function getComment()
584 $this->loadLastEdit();
585 return $this->mComment
;
588 function getMinorEdit()
590 $this->loadLastEdit();
591 return $this->mMinorEdit
;
594 function getContributors($limit = 0, $offset = 0)
596 $fname = 'Article::getContributors';
598 # XXX: this is expensive; cache this info somewhere.
600 $title = $this->mTitle
;
602 $dbr =& wfGetDB( DB_SLAVE
);
603 $oldTable = $dbr->tableName( 'old' );
604 $userTable = $dbr->tableName( 'user' );
605 $encDBkey = $dbr->strencode( $title->getDBkey() );
606 $ns = $title->getNamespace();
607 $user = $this->getUser();
609 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
610 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
611 WHERE old_namespace = $user
612 AND old_title = $encDBkey
613 AND old_user != $user
615 ORDER BY timestamp DESC";
618 $sql .= ' LIMIT '.$limit;
621 $res = $dbr->query($sql, $fname);
623 while ( $line = $dbr->fetchObject( $res ) ) {
624 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
627 $dbr->freeResult($res);
632 # This is the default action of the script: just view the page of
637 global $wgUser, $wgOut, $wgLang, $wgRequest;
638 global $wgLinkCache, $IP, $wgEnableParserCache;
640 $fname = 'Article::view';
641 wfProfileIn( $fname );
643 # Get variables from query string :P
644 $oldid = $wgRequest->getVal( 'oldid' );
645 $diff = $wgRequest->getVal( 'diff' );
647 $wgOut->setArticleFlag( true );
648 $wgOut->setRobotpolicy( 'index,follow' );
650 # If we got diff and oldid in the query, we want to see a
651 # diff page instead of the article.
653 if ( !is_null( $diff ) ) {
654 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
655 $de = new DifferenceEngine( intval($oldid), intval($diff) );
657 wfProfileOut( $fname );
659 # Run view updates for current revision only
660 $this->viewUpdates();
665 if ( empty( $oldid ) && $this->checkTouched() ) {
666 if( $wgOut->checkLastModified( $this->mTouched
) ){
668 } else if ( $this->tryFileCache() ) {
669 # tell wgOut that output is taken care of
671 $this->viewUpdates();
676 # Should the parser cache be used?
677 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
685 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
690 if ( !$outputDone ) {
691 $text = $this->getContent( false ); # May change mTitle by following a redirect
693 # Another whitelist check in case oldid or redirects are altering the title
694 if ( !$this->mTitle
->userCanRead() ) {
695 $wgOut->loginToUse();
701 # We're looking at an old revision
703 if ( !empty( $oldid ) ) {
704 $this->setOldSubtitle();
705 $wgOut->setRobotpolicy( 'noindex,follow' );
707 if ( '' != $this->mRedirectedFrom
) {
708 $sk = $wgUser->getSkin();
709 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
711 $s = wfMsg( 'redirectedfrom', $redir );
712 $wgOut->setSubtitle( $s );
714 # Can't cache redirects
718 # wrap user css and user js in pre and don't parse
719 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
721 $this->mTitle
->getNamespace() == Namespace::getUser() &&
722 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
724 $wgOut->addWikiText( wfMsg('clearyourcache'));
725 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
726 } else if ( $pcache ) {
727 $wgOut->addWikiText( $text, true, $this );
729 $wgOut->addWikiText( $text );
732 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
734 # Add link titles as META keywords
735 $wgOut->addMetaTags() ;
737 $this->viewUpdates();
738 wfProfileOut( $fname );
741 # Theoretically we could defer these whole insert and update
742 # functions for after display, but that's taking a big leap
743 # of faith, and we want to be able to report database
744 # errors at some point.
746 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
748 global $wgOut, $wgUser, $wgMwRedir;
749 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
751 $fname = 'Article::insertNewArticle';
753 $this->mCountAdjustment
= $this->isCountable( $text );
755 $ns = $this->mTitle
->getNamespace();
756 $ttl = $this->mTitle
->getDBkey();
757 $text = $this->preSaveTransform( $text );
758 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
761 $now = wfTimestampNow();
762 $won = wfInvertTimestamp( $now );
764 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
765 $dbw =& wfGetDB( DB_MASTER
);
767 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
769 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
771 $dbw->insertArray( 'cur', array(
773 'cur_namespace' => $ns,
776 'cur_comment' => $summary,
777 'cur_user' => $wgUser->getID(),
778 'cur_timestamp' => $now,
779 'cur_minor_edit' => $isminor,
781 'cur_restrictions' => '',
782 'cur_user_text' => $wgUser->getName(),
783 'cur_is_redirect' => $redir,
785 'cur_random' => $rand,
786 'cur_touched' => $now,
787 'inverse_timestamp' => $won,
790 $newid = $dbw->insertId();
791 $this->mTitle
->resetArticleID( $newid );
793 Article
::onArticleCreate( $this->mTitle
);
794 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
797 if(!$this->mTitle
->userIsWatching()) $this->watch();
799 if ( $this->mTitle
->userIsWatching() ) {
804 # The talk page isn't in the regular link tables, so we need to update manually:
805 $talkns = $ns ^
1; # talk -> normal; normal -> talk
806 $dbw->updateArray( 'cur', array( 'cur_touched' => $now ), array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
808 # standard deferred updates
809 $this->editUpdates( $text );
811 $this->showArticle( $text, wfMsg( 'newarticle' ) );
815 /* Side effects: loads last edit */
816 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ''){
817 $this->loadLastEdit();
818 $oldtext = $this->getContent( true );
819 if ($section != '') {
820 if($section=='new') {
821 if($summary) $subject="== {$summary} ==\n\n";
822 $text=$oldtext."\n\n".$subject.$text;
825 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
826 # comments to be stripped as well)
828 $parser=new Parser();
829 $parser->mOutputType
=OT_WIKI
;
830 $oldtext=$parser->strip($oldtext, $striparray, true);
832 # now that we can be sure that no pseudo-sections are in the source,
834 # Unfortunately we can't simply do a preg_replace because that might
835 # replace the wrong section, so we have to use the section counter instead
836 $secs=preg_split('/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
837 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
838 $secs[$section*2]=$text."\n\n"; // replace with edited
840 # section 0 is top (intro) section
843 # headline of old section - we need to go through this section
844 # to determine if there are any subsections that now need to
845 # be erased, as the mother section has been replaced with
846 # the text of all subsections.
847 $headline=$secs[$section*2-1];
848 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
851 # determine headline level for wikimarkup headings
852 if(strpos($hlevel,'=')!==false) {
853 $hlevel=strlen($hlevel);
856 $secs[$section*2-1]=''; // erase old headline
859 while(!empty($secs[$count*2-1]) && !$break) {
861 $subheadline=$secs[$count*2-1];
863 '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
864 $subhlevel=$matches[1];
865 if(strpos($subhlevel,'=')!==false) {
866 $subhlevel=strlen($subhlevel);
868 if($subhlevel > $hlevel) {
869 // erase old subsections
870 $secs[$count*2-1]='';
873 if($subhlevel <= $hlevel) {
881 $text=join('',$secs);
882 # reinsert the stuff that we stripped out earlier
883 $text=$parser->unstrip($text,$striparray);
884 $text=$parser->unstripNoWiki($text,$striparray);
891 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' )
893 global $wgOut, $wgUser;
894 global $wgDBtransactions, $wgMwRedir;
895 global $wgUseSquid, $wgInternalServer;
897 $fname = 'Article::updateArticle';
900 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
901 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
902 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
904 $text = $m[1] . "\n"; # Remove all content but redirect
908 $text = $this->preSaveTransform( $text );
909 $dbw =& wfGetDB( DB_MASTER
);
911 # Update article, but only if changed.
913 # It's important that we either rollback or complete, otherwise an attacker could
914 # overwrite cur entries by sending precisely timed user aborts. Random bored users
915 # could conceivably have the same effect, especially if cur is locked for long periods.
916 if( $wgDBtransactions ) {
917 $dbw->query( 'BEGIN', $fname );
919 $userAbort = ignore_user_abort( true );
922 $oldtext = $this->getContent( true );
924 if ( 0 != strcmp( $text, $oldtext ) ) {
925 $this->mCountAdjustment
= $this->isCountable( $text )
926 - $this->isCountable( $oldtext );
927 $now = wfTimestampNow();
928 $won = wfInvertTimestamp( $now );
930 # First update the cur row
931 $dbw->updateArray( 'cur',
934 'cur_comment' => $summary,
935 'cur_minor_edit' => $me2,
936 'cur_user' => $wgUser->getID(),
937 'cur_timestamp' => $now,
938 'cur_user_text' => $wgUser->getName(),
939 'cur_is_redirect' => $redir,
941 'cur_touched' => $now,
942 'inverse_timestamp' => $won
943 ), array( /* WHERE */
944 'cur_id' => $this->getID(),
945 'cur_timestamp' => $this->getTimestamp()
949 if( $dbw->affectedRows() == 0 ) {
950 /* Belated edit conflict! Run away!! */
953 # Now insert the previous revision into old
955 # This overwrites $oldtext if revision compression is on
956 $flags = Article
::compressRevisionText( $oldtext );
958 $dbw->insertArray( 'old',
960 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
961 'old_namespace' => $this->mTitle
->getNamespace(),
962 'old_title' => $this->mTitle
->getDBkey(),
963 'old_text' => $oldtext,
964 'old_comment' => $this->getComment(),
965 'old_user' => $this->getUser(),
966 'old_user_text' => $this->getUserText(),
967 'old_timestamp' => $this->getTimestamp(),
968 'old_minor_edit' => $me1,
969 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
970 'old_flags' => $flags,
974 $oldid = $dbw->insertId();
976 $bot = (int)($wgUser->isBot() ||
$forceBot);
977 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
978 $oldid, $this->getTimestamp(), $bot );
979 Article
::onArticleEdit( $this->mTitle
);
983 if( $wgDBtransactions ) {
984 $dbw->query( 'COMMIT', $fname );
986 ignore_user_abort( $userAbort );
991 if (!$this->mTitle
->userIsWatching()) $this->watch();
993 if ( $this->mTitle
->userIsWatching() ) {
997 # standard deferred updates
998 $this->editUpdates( $text );
1002 # Template namespace
1003 # Purge all articles linking here
1004 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1005 $titles = $this->mTitle
->getLinksTo();
1006 Title
::touchArray( $titles );
1007 if ( $wgUseSquid ) {
1008 foreach ( $titles as $title ) {
1009 $urls[] = $title->getInternalURL();
1015 if ( $wgUseSquid ) {
1016 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1017 $u = new SquidUpdate( $urls );
1021 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1026 # After we've either updated or inserted the article, update
1027 # the link tables and redirect to the new page.
1029 function showArticle( $text, $subtitle , $sectionanchor = '' )
1031 global $wgOut, $wgUser, $wgLinkCache;
1034 $wgLinkCache = new LinkCache();
1036 $wgLinkCache->forUpdate( true );
1038 # Get old version of link table to allow incremental link updates
1039 $wgLinkCache->preFill( $this->mTitle
);
1040 $wgLinkCache->clear();
1042 # Switch on use of link cache in the skin
1043 $sk =& $wgUser->getSkin();
1044 $sk->postParseLinkColour( false );
1046 # Now update the link cache by parsing the text
1047 $wgOut = new OutputPage();
1048 $wgOut->addWikiText( $text );
1050 if( $wgMwRedir->matchStart( $text ) )
1054 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1059 function validate ()
1062 $wgOut->setPagetitle( wfMsg( 'validate' ) . " : " . $this->mTitle
->getPrefixedText() );
1063 $wgOut->setRobotpolicy( 'noindex,follow' );
1064 if ( $this->mTitle
->getNamespace() != 0 )
1066 $wgOut->addHTML ( wfMsg ( 'val_validate_article_namespace_only' ) ) ;
1069 $v = new Validation
;
1070 $v->validate_form ( $this->mTitle
->getDBkey() ) ;
1073 # Add this page to my watchlist
1075 function watch( $add = true )
1077 global $wgUser, $wgOut, $wgLang;
1078 global $wgDeferredUpdateList;
1080 if ( 0 == $wgUser->getID() ) {
1081 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1084 if ( wfReadOnly() ) {
1085 $wgOut->readOnlyPage();
1089 $wgUser->addWatch( $this->mTitle
);
1091 $wgUser->removeWatch( $this->mTitle
);
1093 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1094 $wgOut->setRobotpolicy( 'noindex,follow' );
1096 $sk = $wgUser->getSkin() ;
1097 $link = $this->mTitle
->getPrefixedText();
1100 $text = wfMsg( 'addedwatchtext', $link );
1102 $text = wfMsg( 'removedwatchtext', $link );
1103 $wgOut->addWikiText( $text );
1105 $up = new UserUpdate();
1106 array_push( $wgDeferredUpdateList, $up );
1108 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1113 $this->watch( false );
1116 function protect( $limit = 'sysop' )
1118 global $wgUser, $wgOut, $wgRequest;
1120 if ( ! $wgUser->isSysop() ) {
1121 $wgOut->sysopRequired();
1124 if ( wfReadOnly() ) {
1125 $wgOut->readOnlyPage();
1128 $id = $this->mTitle
->getArticleID();
1130 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1134 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1135 $reason = $wgRequest->getText( 'wpReasonProtect' );
1138 $dbw =& wfGetDB( DB_MASTER
);
1139 $dbw->updateArray( 'cur',
1141 'cur_touched' => wfTimestampNow(),
1142 'cur_restrictions' => (string)$limit
1143 ), array( /* WHERE */
1145 ), 'Article::protect'
1148 $log = new LogPage( wfMsg( 'protectlogpage' ), wfMsg( 'protectlogtext' ) );
1149 if ( $limit === "" ) {
1150 $log->addEntry( wfMsg( 'unprotectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1152 $log->addEntry( wfMsg( 'protectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1154 $wgOut->redirect( $this->mTitle
->getFullURL() );
1157 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1158 return $this->confirmProtect( '', $reason, $limit );
1162 # Output protection confirmation dialog
1163 function confirmProtect( $par, $reason, $limit = 'sysop' )
1167 wfDebug( "Article::confirmProtect\n" );
1169 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1170 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1175 if ( $limit === '' ) {
1176 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1177 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1178 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1179 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1180 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1181 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1183 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1184 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1185 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1186 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1187 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1188 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1191 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1194 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1198 <label for='wpReasonProtect'>{$protcom}:</label>
1201 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1209 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1212 <label for='wpConfirmProtect'>{$check}</label>
1218 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1224 $wgOut->returnToMain( false );
1227 function unprotect()
1229 return $this->protect( '' );
1232 # UI entry point for page deletion
1235 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1236 $fname = 'Article::delete';
1237 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1238 $reason = $wgRequest->getText( 'wpReason' );
1240 # This code desperately needs to be totally rewritten
1243 if ( ( ! $wgUser->isSysop() ) ) {
1244 $wgOut->sysopRequired();
1247 if ( wfReadOnly() ) {
1248 $wgOut->readOnlyPage();
1252 # Better double-check that it hasn't been deleted yet!
1253 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1254 if ( ( '' == trim( $this->mTitle
->getText() ) )
1255 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1256 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1261 $this->doDelete( $reason );
1265 # determine whether this page has earlier revisions
1266 # and insert a warning if it does
1267 # we select the text because it might be useful below
1268 $dbr =& wfGetDB( DB_SLAVE
);
1269 $ns = $this->mTitle
->getNamespace();
1270 $title = $this->mTitle
->getDBkey();
1271 $old = $dbr->getArray( 'old',
1272 array( 'old_text', 'old_flags' ),
1274 'old_namespace' => $ns,
1275 'old_title' => $title,
1276 ), $fname, array( 'ORDER BY' => 'inverse_timestamp' )
1279 if( $old !== false && !$confirm ) {
1280 $skin=$wgUser->getSkin();
1281 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1282 $wgOut->addHTML( $skin->historyLink() .'</b>');
1286 $s = $dbr->getArray( 'cur',
1287 array( 'cur_text' ),
1289 'cur_namespace' => $ns,
1290 'cur_title' => $title,
1294 if( $s !== false ) {
1295 # if this is a mini-text, we can paste part of it into the deletion reason
1297 #if this is empty, an earlier revision may contain "useful" text
1299 if($s->cur_text
!="") {
1303 $text = Article
::getRevisionText( $old );
1309 $length=strlen($text);
1311 # this should not happen, since it is not possible to store an empty, new
1312 # page. Let's insert a standard text in case it does, though
1313 if($length == 0 && $reason === '') {
1314 $reason = wfMsg('exblank');
1317 if($length < 500 && $reason === '') {
1319 # comment field=255, let's grep the first 150 to have some user
1321 $text=substr($text,0,150);
1322 # let's strip out newlines and HTML tags
1323 $text=preg_replace('/\"/',"'",$text);
1324 $text=preg_replace('/\</','<',$text);
1325 $text=preg_replace('/\>/','>',$text);
1326 $text=preg_replace("/[\n\r]/",'',$text);
1328 $reason=wfMsg('excontent'). " '".$text;
1330 $reason=wfMsg('exbeforeblank') . " '".$text;
1332 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1337 return $this->confirmDelete( '', $reason );
1340 # Output deletion confirmation dialog
1341 function confirmDelete( $par, $reason )
1345 wfDebug( "Article::confirmDelete\n" );
1347 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1348 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1349 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1350 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1352 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1354 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1355 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1356 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1359 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1363 <label for='wpReason'>{$delcom}:</label>
1366 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1374 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1377 <label for='wpConfirm'>{$check}</label>
1383 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1389 $wgOut->returnToMain( false );
1392 # Perform a deletion and output success or failure messages
1393 function doDelete( $reason )
1395 global $wgOut, $wgUser, $wgLang;
1396 $fname = 'Article::doDelete';
1397 wfDebug( "$fname\n" );
1399 if ( $this->doDeleteArticle( $reason ) ) {
1400 $deleted = $this->mTitle
->getPrefixedText();
1402 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1403 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1405 $sk = $wgUser->getSkin();
1406 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1407 Namespace::getWikipedia() ) .
1408 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1410 $text = wfMsg( "deletedtext", $deleted, $loglink );
1412 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1413 $wgOut->returnToMain( false );
1415 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1419 # Back-end article deletion
1420 # Deletes the article with database consistency, writes logs, purges caches
1422 function doDeleteArticle( $reason )
1424 global $wgUser, $wgLang;
1425 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1427 $fname = 'Article::doDeleteArticle';
1428 wfDebug( $fname."\n" );
1430 $dbw =& wfGetDB( DB_MASTER
);
1431 $ns = $this->mTitle
->getNamespace();
1432 $t = $this->mTitle
->getDBkey();
1433 $id = $this->mTitle
->getArticleID();
1435 if ( '' == $t ||
$id == 0 ) {
1439 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1440 array_push( $wgDeferredUpdateList, $u );
1442 $linksTo = $this->mTitle
->getLinksTo();
1445 if ( $wgUseSquid ) {
1447 $this->mTitle
->getInternalURL(),
1448 $this->mTitle
->getInternalURL( 'history' )
1450 foreach ( $linksTo as $linkTo ) {
1451 $urls[] = $linkTo->getInternalURL();
1454 $u = new SquidUpdate( $urls );
1455 array_push( $wgDeferredUpdateList, $u );
1459 # Client and file cache invalidation
1460 Title
::touchArray( $linksTo );
1462 # Move article and history to the "archive" table
1463 $archiveTable = $dbw->tableName( 'archive' );
1464 $oldTable = $dbw->tableName( 'old' );
1465 $curTable = $dbw->tableName( 'cur' );
1466 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1467 $linksTable = $dbw->tableName( 'links' );
1468 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1470 $dbw->insertSelect( 'archive', 'cur',
1472 'ar_namespace' => 'cur_namespace',
1473 'ar_title' => 'cur_title',
1474 'ar_text' => 'cur_text',
1475 'ar_comment' => 'cur_comment',
1476 'ar_user' => 'cur_user',
1477 'ar_user_text' => 'cur_user_text',
1478 'ar_timestamp' => 'cur_timestamp',
1479 'ar_minor_edit' => 'cur_minor_edit',
1482 'cur_namespace' => $ns,
1487 $dbw->insertSelect( 'archive', 'old',
1489 'ar_namespace' => 'old_namespace',
1490 'ar_title' => 'old_title',
1491 'ar_text' => 'old_text',
1492 'ar_comment' => 'old_comment',
1493 'ar_user' => 'old_user',
1494 'ar_user_text' => 'old_user_text',
1495 'ar_timestamp' => 'old_timestamp',
1496 'ar_minor_edit' => 'old_minor_edit',
1497 'ar_flags' => 'old_flags'
1499 'old_namespace' => $ns,
1504 # Now that it's safely backed up, delete it
1506 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1507 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1508 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1510 # Finally, clean up the link tables
1511 $t = $this->mTitle
->getPrefixedDBkey();
1513 Article
::onArticleDelete( $this->mTitle
);
1515 # Insert broken links
1516 $brokenLinks = array();
1517 foreach ( $linksTo as $titleObj ) {
1518 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1519 $linkID = $titleObj->getArticleID();
1520 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1522 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1525 $dbw->delete( 'links', array( 'l_to' => $id ) );
1526 $dbw->delete( 'links', array( 'l_from' => $id ) );
1527 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1528 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1529 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1532 $log = new LogPage( wfMsg( 'dellogpage' ), wfMsg( 'dellogpagetext' ) );
1533 $art = $this->mTitle
->getPrefixedText();
1534 $log->addEntry( wfMsg( 'deletedarticle', $art ), $reason );
1536 # Clear the cached article id so the interface doesn't act like we exist
1537 $this->mTitle
->resetArticleID( 0 );
1538 $this->mTitle
->mArticleID
= 0;
1544 global $wgUser, $wgLang, $wgOut, $wgRequest;
1545 $fname = "Article::rollback";
1547 if ( ! $wgUser->isSysop() ) {
1548 $wgOut->sysopRequired();
1551 if ( wfReadOnly() ) {
1552 $wgOut->readOnlyPage( $this->getContent( true ) );
1555 $dbw =& wfGetDB( DB_MASTER
);
1557 # Enhanced rollback, marks edits rc_bot=1
1558 $bot = $wgRequest->getBool( 'bot' );
1560 # Replace all this user's current edits with the next one down
1561 $tt = $this->mTitle
->getDBKey();
1562 $n = $this->mTitle
->getNamespace();
1564 # Get the last editor, lock table exclusively
1565 $s = $dbw->getArray( 'cur',
1566 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1567 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1568 $fname, 'FOR UPDATE'
1570 if( $s === false ) {
1572 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1575 $ut = $dbw->strencode( $s->cur_user_text
);
1576 $uid = $s->cur_user
;
1579 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1580 if( $from != $s->cur_user_text
) {
1581 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1582 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1583 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1584 htmlspecialchars( $from ),
1585 htmlspecialchars( $s->cur_user_text
) ) );
1586 if($s->cur_comment
!= '') {
1588 wfMsg('editcomment',
1589 htmlspecialchars( $s->cur_comment
) ) );
1594 # Get the last edit not by this guy
1595 $s = $dbw->getArray( 'old',
1596 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1598 'old_namespace' => $n,
1600 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1601 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1603 if( $s === false ) {
1605 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1606 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1611 # Mark all reverted edits as bot
1612 $dbw->updateArray( 'recentchanges',
1615 ), array( /* WHERE */
1617 "rc_timestamp > '{$s->old_timestamp}'",
1623 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1624 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1625 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1626 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1627 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1628 Article
::onArticleEdit( $this->mTitle
);
1629 $wgOut->returnToMain( false );
1633 # Do standard deferred updates after page view
1635 /* private */ function viewUpdates()
1637 global $wgDeferredUpdateList;
1638 if ( 0 != $this->getID() ) {
1639 global $wgDisableCounters;
1640 if( !$wgDisableCounters ) {
1641 Article
::incViewCount( $this->getID() );
1642 $u = new SiteStatsUpdate( 1, 0, 0 );
1643 array_push( $wgDeferredUpdateList, $u );
1646 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1647 $this->mTitle
->getDBkey() );
1648 array_push( $wgDeferredUpdateList, $u );
1651 # Do standard deferred updates after page edit.
1652 # Every 1000th edit, prune the recent changes table.
1654 /* private */ function editUpdates( $text )
1656 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1657 global $wgMessageCache;
1660 if ( 0 == mt_rand( 0, 999 ) ) {
1661 $dbw =& wfGetDB( DB_MASTER
);
1662 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1663 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1664 $dbw->query( $sql );
1666 $id = $this->getID();
1667 $title = $this->mTitle
->getPrefixedDBkey();
1668 $shortTitle = $this->mTitle
->getDBkey();
1670 $adj = $this->mCountAdjustment
;
1673 $u = new LinksUpdate( $id, $title );
1674 array_push( $wgDeferredUpdateList, $u );
1675 $u = new SiteStatsUpdate( 0, 1, $adj );
1676 array_push( $wgDeferredUpdateList, $u );
1677 $u = new SearchUpdate( $id, $title, $text );
1678 array_push( $wgDeferredUpdateList, $u );
1680 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1681 array_push( $wgDeferredUpdateList, $u );
1683 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1684 $wgMessageCache->replace( $shortTitle, $text );
1689 /* private */ function setOldSubtitle()
1691 global $wgLang, $wgOut;
1693 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1694 $r = wfMsg( 'revisionasof', $td );
1695 $wgOut->setSubtitle( "({$r})" );
1698 # This function is called right before saving the wikitext,
1699 # so we can do things like signatures and links-in-context.
1701 function preSaveTransform( $text )
1703 global $wgParser, $wgUser;
1704 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1707 /* Caching functions */
1709 # checkLastModified returns true if it has taken care of all
1710 # output to the client that is necessary for this request.
1711 # (that is, it has sent a cached version of the page)
1712 function tryFileCache() {
1713 static $called = false;
1715 wfDebug( " tryFileCache() -- called twice!?\n" );
1719 if($this->isFileCacheable()) {
1720 $touched = $this->mTouched
;
1721 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1722 # Expire the main page quicker
1723 $expire = wfUnix2Timestamp( time() - 3600 );
1724 $touched = max( $expire, $touched );
1726 $cache = new CacheManager( $this->mTitle
);
1727 if($cache->isFileCacheGood( $touched )) {
1729 wfDebug( " tryFileCache() - about to load\n" );
1730 $cache->loadFromFileCache();
1733 wfDebug( " tryFileCache() - starting buffer\n" );
1734 ob_start( array(&$cache, 'saveToFileCache' ) );
1737 wfDebug( " tryFileCache() - not cacheable\n" );
1741 function isFileCacheable() {
1742 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1743 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1745 return $wgUseFileCache
1746 and (!$wgShowIPinHeader)
1747 and ($this->getID() != 0)
1748 and ($wgUser->getId() == 0)
1749 and (!$wgUser->getNewtalk())
1750 and ($this->mTitle
->getNamespace() != Namespace::getSpecial())
1751 and ($action == 'view' ||
empty( $action ))
1752 and (!isset($oldid))
1754 and (!isset($redirect))
1755 and (!isset($printable))
1756 and (!$this->mRedirectedFrom
);
1759 # Loads cur_touched and returns a value indicating if it should be used
1760 function checkTouched() {
1761 $fname = 'Article::checkTouched';
1763 $id = $this->getID();
1764 $dbr =& wfGetDB( DB_SLAVE
);
1765 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1766 array( 'cur_id' => $id ), $fname );
1767 if( $s !== false ) {
1768 $this->mTouched
= $s->cur_touched
;
1769 return !$s->cur_is_redirect
;
1775 # Edit an article without doing all that other stuff
1776 function quickEdit( $text, $comment = '', $minor = 0 ) {
1777 global $wgUser, $wgMwRedir;
1778 $fname = 'Article::quickEdit';
1779 wfProfileIn( $fname );
1781 $dbw =& wfGetDB( DB_MASTER
);
1782 $ns = $this->mTitle
->getNamespace();
1783 $dbkey = $this->mTitle
->getDBkey();
1784 $encDbKey = $dbw->strencode( $dbkey );
1785 $timestamp = wfTimestampNow();
1788 $dbw->insertSelect( 'old', 'cur',
1790 'old_namespace' => 'cur_namespace',
1791 'old_title' => 'cur_title',
1792 'old_text' => 'cur_text',
1793 'old_comment' => 'cur_comment',
1794 'old_user' => 'cur_user',
1795 'old_user_text' => 'cur_user_text',
1796 'old_timestamp' => 'cur_timestamp',
1797 'inverse_timestamp' => '99999999999999-cur_timestamp',
1799 'cur_namespace' => $ns,
1800 'cur_title' => $dbkey,
1804 # Use the affected row count to determine if the article is new
1805 $numRows = $dbw->affectedRows();
1807 # Make an array of fields to be inserted
1809 'cur_text' => $text,
1810 'cur_timestamp' => $timestamp,
1811 'cur_user' => $wgUser->getID(),
1812 'cur_user_text' => $wgUser->getName(),
1813 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1814 'cur_comment' => $comment,
1815 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ?
1 : 0,
1816 'cur_minor_edit' => intval($minor),
1817 'cur_touched' => $timestamp,
1822 $fields['cur_is_new'] = 0;
1823 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1825 # Insert new article
1826 $fields['cur_is_new'] = 1;
1827 $fields['cur_namespace'] = $ns;
1828 $fields['cur_title'] = $dbkey;
1829 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1830 $dbw->insertArray( 'cur', $fields, $fname );
1832 wfProfileOut( $fname );
1835 /* static */ function incViewCount( $id )
1837 $id = intval( $id );
1838 global $wgHitcounterUpdateFreq;
1840 $dbw =& wfGetDB( DB_MASTER
);
1841 $curTable = $dbw->tableName( 'cur' );
1842 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1843 $acchitsTable = $dbw->tableName( 'acchits' );
1845 if( $wgHitcounterUpdateFreq <= 1 ){ //
1846 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
1850 # Not important enough to warrant an error page in case of failure
1851 $oldignore = $dbw->ignoreErrors( true );
1853 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
1855 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
1856 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
1857 # Most of the time (or on SQL errors), skip row count check
1858 $dbw->ignoreErrors( $oldignore );
1862 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
1863 $row = $dbw->fetchObject( $res );
1864 $rown = intval( $row->n
);
1865 if( $rown >= $wgHitcounterUpdateFreq ){
1866 wfProfileIn( 'Article::incViewCount-collect' );
1867 $old_user_abort = ignore_user_abort( true );
1869 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
1870 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
1871 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
1873 $dbw->query("DELETE FROM $hitcounterTable");
1874 $dbw->query('UNLOCK TABLES');
1875 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
1876 'WHERE cur_id = hc_id');
1877 $dbw->query("DROP TABLE $acchitsTable");
1879 ignore_user_abort( $old_user_abort );
1880 wfProfileOut( 'Article::incViewCount-collect' );
1882 $dbw->ignoreErrors( $oldignore );
1885 # The onArticle*() functions are supposed to be a kind of hooks
1886 # which should be called whenever any of the specified actions
1889 # This is a good place to put code to clear caches, for instance.
1891 # This is called on page move and undelete, as well as edit
1892 /* static */ function onArticleCreate($title_obj){
1893 global $wgUseSquid, $wgDeferredUpdateList;
1895 $titles = $title_obj->getBrokenLinksTo();
1898 if ( $wgUseSquid ) {
1899 $urls = $title_obj->getSquidURLs();
1900 foreach ( $titles as $linkTitle ) {
1901 $urls[] = $linkTitle->getInternalURL();
1903 $u = new SquidUpdate( $urls );
1904 array_push( $wgDeferredUpdateList, $u );
1907 # Clear persistent link cache
1908 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1911 /* static */ function onArticleDelete($title_obj){
1912 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
1915 /* static */ function onArticleEdit($title_obj){
1916 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
1919 # Info about this page
1923 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgAllowPageInfo;
1924 $fname = 'Article::info';
1926 if ( !$wgAllowPageInfo ) {
1927 $wgOut->errorpage( "nosuchaction", "nosuchactiontext" );
1931 $dbr =& wfGetDB( DB_SLAVE
);
1933 $basenamespace = $wgTitle->getNamespace() & (~
1);
1934 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
1935 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
1936 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
1937 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
1938 $wgOut->setPagetitle( $fullTitle );
1939 $wgOut->setSubtitle( wfMsg( "infosubtitle" ));
1941 # first, see if the page exists at all.
1942 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname );
1944 $wgOut->addHTML( wfMsg("noarticletext") );
1946 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname );
1947 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . "</li>" );
1948 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname );
1949 $wgOut->addHTML( "<li>" . wfMsg("numedits", $old +
1) . "</li>");
1951 # to find number of distinct authors, we need to do some
1952 # funny stuff because of the cur/old table split:
1953 # - first, find the name of the 'cur' author
1954 # - then, find the number of *other* authors in 'old'
1957 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname );
1959 # find number of 'old' authors excluding 'cur' author
1960 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
1961 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname ) +
1;
1963 # now for the Talk page ...
1964 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
1965 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
1968 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname );
1972 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname );
1973 $wgOut->addHTML( "<li>" . wfMsg("numtalkedits", $old +
1) . "</li>");
1975 $wgOut->addHTML( "<li>" . wfMsg("numauthors", $authors) . "</li>" );
1979 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname );
1980 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
1981 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname );
1983 $wgOut->addHTML( "<li>" . wfMsg("numtalkauthors", $authors) . "</li></ul>" );