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 );
661 if ( empty( $oldid ) && $this->checkTouched() ) {
662 if( $wgOut->checkLastModified( $this->mTouched
) ){
664 } else if ( $this->tryFileCache() ) {
665 # tell wgOut that output is taken care of
667 $this->viewUpdates();
672 # Should the parser cache be used?
673 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
681 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
686 if ( !$outputDone ) {
687 $text = $this->getContent( false ); # May change mTitle by following a redirect
689 # Another whitelist check in case oldid or redirects are altering the title
690 if ( !$this->mTitle
->userCanRead() ) {
691 $wgOut->loginToUse();
697 # We're looking at an old revision
699 if ( !empty( $oldid ) ) {
700 $this->setOldSubtitle();
701 $wgOut->setRobotpolicy( 'noindex,follow' );
703 if ( '' != $this->mRedirectedFrom
) {
704 $sk = $wgUser->getSkin();
705 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
707 $s = wfMsg( 'redirectedfrom', $redir );
708 $wgOut->setSubtitle( $s );
710 # Can't cache redirects
714 # wrap user css and user js in pre and don't parse
715 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
717 $this->mTitle
->getNamespace() == Namespace::getUser() &&
718 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
720 $wgOut->addWikiText( wfMsg('clearyourcache'));
721 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
722 } else if ( $pcache ) {
723 $wgOut->addWikiText( $text, true, $this );
725 $wgOut->addWikiText( $text );
728 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
730 # Add link titles as META keywords
731 $wgOut->addMetaTags() ;
733 $this->viewUpdates();
734 wfProfileOut( $fname );
737 # Theoretically we could defer these whole insert and update
738 # functions for after display, but that's taking a big leap
739 # of faith, and we want to be able to report database
740 # errors at some point.
742 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
744 global $wgOut, $wgUser, $wgMwRedir;
745 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
747 $fname = 'Article::insertNewArticle';
749 $this->mCountAdjustment
= $this->isCountable( $text );
751 $ns = $this->mTitle
->getNamespace();
752 $ttl = $this->mTitle
->getDBkey();
753 $text = $this->preSaveTransform( $text );
754 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
757 $now = wfTimestampNow();
758 $won = wfInvertTimestamp( $now );
760 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
761 $dbw =& wfGetDB( DB_MASTER
);
763 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
765 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
767 $dbw->insertArray( 'cur', array(
769 'cur_namespace' => $ns,
772 'cur_comment' => $summary,
773 'cur_user' => $wgUser->getID(),
774 'cur_timestamp' => $now,
775 'cur_minor_edit' => $isminor,
777 'cur_restrictions' => '',
778 'cur_user_text' => $wgUser->getName(),
779 'cur_is_redirect' => $redir,
781 'cur_random' => $rand,
782 'cur_touched' => $now,
783 'inverse_timestamp' => $won,
786 $newid = $dbw->insertId();
787 $this->mTitle
->resetArticleID( $newid );
789 Article
::onArticleCreate( $this->mTitle
);
790 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
793 if(!$this->mTitle
->userIsWatching()) $this->watch();
795 if ( $this->mTitle
->userIsWatching() ) {
800 # The talk page isn't in the regular link tables, so we need to update manually:
801 $talkns = $ns ^
1; # talk -> normal; normal -> talk
802 $dbw->updateArray( 'cur', array( 'cur_touched' => $now ), array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
804 # standard deferred updates
805 $this->editUpdates( $text );
807 $this->showArticle( $text, wfMsg( 'newarticle' ) );
811 /* Side effects: loads last edit */
812 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ''){
813 $this->loadLastEdit();
814 $oldtext = $this->getContent( true );
815 if ($section != '') {
816 if($section=='new') {
817 if($summary) $subject="== {$summary} ==\n\n";
818 $text=$oldtext."\n\n".$subject.$text;
821 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
822 # comments to be stripped as well)
824 $parser=new Parser();
825 $parser->mOutputType
=OT_WIKI
;
826 $oldtext=$parser->strip($oldtext, $striparray, true);
828 # now that we can be sure that no pseudo-sections are in the source,
830 # Unfortunately we can't simply do a preg_replace because that might
831 # replace the wrong section, so we have to use the section counter instead
832 $secs=preg_split('/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
833 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
834 $secs[$section*2]=$text."\n\n"; // replace with edited
836 # section 0 is top (intro) section
839 # headline of old section - we need to go through this section
840 # to determine if there are any subsections that now need to
841 # be erased, as the mother section has been replaced with
842 # the text of all subsections.
843 $headline=$secs[$section*2-1];
844 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
847 # determine headline level for wikimarkup headings
848 if(strpos($hlevel,'=')!==false) {
849 $hlevel=strlen($hlevel);
852 $secs[$section*2-1]=''; // erase old headline
855 while(!empty($secs[$count*2-1]) && !$break) {
857 $subheadline=$secs[$count*2-1];
859 '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
860 $subhlevel=$matches[1];
861 if(strpos($subhlevel,'=')!==false) {
862 $subhlevel=strlen($subhlevel);
864 if($subhlevel > $hlevel) {
865 // erase old subsections
866 $secs[$count*2-1]='';
869 if($subhlevel <= $hlevel) {
877 $text=join('',$secs);
878 # reinsert the stuff that we stripped out earlier
879 $text=$parser->unstrip($text,$striparray);
880 $text=$parser->unstripNoWiki($text,$striparray);
887 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' )
889 global $wgOut, $wgUser;
890 global $wgDBtransactions, $wgMwRedir;
891 global $wgUseSquid, $wgInternalServer;
893 $fname = 'Article::updateArticle';
896 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
897 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
898 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
900 $text = $m[1] . "\n"; # Remove all content but redirect
904 $text = $this->preSaveTransform( $text );
905 $dbw =& wfGetDB( DB_MASTER
);
907 # Update article, but only if changed.
909 # It's important that we either rollback or complete, otherwise an attacker could
910 # overwrite cur entries by sending precisely timed user aborts. Random bored users
911 # could conceivably have the same effect, especially if cur is locked for long periods.
912 if( $wgDBtransactions ) {
913 $dbw->query( 'BEGIN', $fname );
915 $userAbort = ignore_user_abort( true );
918 $oldtext = $this->getContent( true );
920 if ( 0 != strcmp( $text, $oldtext ) ) {
921 $this->mCountAdjustment
= $this->isCountable( $text )
922 - $this->isCountable( $oldtext );
923 $now = wfTimestampNow();
924 $won = wfInvertTimestamp( $now );
926 # First update the cur row
927 $dbw->updateArray( 'cur',
930 'cur_comment' => $summary,
931 'cur_minor_edit' => $me2,
932 'cur_user' => $wgUser->getID(),
933 'cur_timestamp' => $now,
934 'cur_user_text' => $wgUser->getName(),
935 'cur_is_redirect' => $redir,
937 'cur_touched' => $now,
938 'inverse_timestamp' => $won
939 ), array( /* WHERE */
940 'cur_id' => $this->getID(),
941 'cur_timestamp' => $this->getTimestamp()
945 if( $dbw->affectedRows() == 0 ) {
946 /* Belated edit conflict! Run away!! */
949 # Now insert the previous revision into old
951 # This overwrites $oldtext if revision compression is on
952 $flags = Article
::compressRevisionText( $oldtext );
954 $dbw->insertArray( 'old',
956 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
957 'old_namespace' => $this->mTitle
->getNamespace(),
958 'old_title' => $this->mTitle
->getDBkey(),
959 'old_text' => $oldtext,
960 'old_comment' => $this->getComment(),
961 'old_user' => $this->getUser(),
962 'old_user_text' => $this->getUserText(),
963 'old_timestamp' => $this->getTimestamp(),
964 'old_minor_edit' => $me1,
965 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
966 'old_flags' => $flags,
970 $oldid = $dbw->insertId();
972 $bot = (int)($wgUser->isBot() ||
$forceBot);
973 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
974 $oldid, $this->getTimestamp(), $bot );
975 Article
::onArticleEdit( $this->mTitle
);
979 if( $wgDBtransactions ) {
980 $dbw->query( 'COMMIT', $fname );
982 ignore_user_abort( $userAbort );
987 if (!$this->mTitle
->userIsWatching()) $this->watch();
989 if ( $this->mTitle
->userIsWatching() ) {
993 # standard deferred updates
994 $this->editUpdates( $text );
999 # Purge all articles linking here
1000 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1001 $titles = $this->mTitle
->getLinksTo();
1002 Title
::touchArray( $titles );
1003 if ( $wgUseSquid ) {
1004 foreach ( $titles as $title ) {
1005 $urls[] = $title->getInternalURL();
1011 if ( $wgUseSquid ) {
1012 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1013 $u = new SquidUpdate( $urls );
1017 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1022 # After we've either updated or inserted the article, update
1023 # the link tables and redirect to the new page.
1025 function showArticle( $text, $subtitle , $sectionanchor = '' )
1027 global $wgOut, $wgUser, $wgLinkCache;
1030 $wgLinkCache = new LinkCache();
1032 $wgLinkCache->forUpdate( true );
1034 # Get old version of link table to allow incremental link updates
1035 $wgLinkCache->preFill( $this->mTitle
);
1036 $wgLinkCache->clear();
1038 # Switch on use of link cache in the skin
1039 $sk =& $wgUser->getSkin();
1040 $sk->postParseLinkColour( false );
1042 # Now update the link cache by parsing the text
1043 $wgOut = new OutputPage();
1044 $wgOut->addWikiText( $text );
1046 if( $wgMwRedir->matchStart( $text ) )
1050 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1055 function validate ()
1058 $wgOut->setPagetitle( wfMsg( 'validate' ) . " : " . $this->mTitle
->getPrefixedText() );
1059 $wgOut->setRobotpolicy( 'noindex,follow' );
1060 if ( $this->mTitle
->getNamespace() != 0 )
1062 $wgOut->addHTML ( wfMsg ( 'val_validate_article_namespace_only' ) ) ;
1065 $v = new Validation
;
1066 $v->validate_form ( $this->mTitle
->getDBkey() ) ;
1069 # Add this page to my watchlist
1071 function watch( $add = true )
1073 global $wgUser, $wgOut, $wgLang;
1074 global $wgDeferredUpdateList;
1076 if ( 0 == $wgUser->getID() ) {
1077 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1080 if ( wfReadOnly() ) {
1081 $wgOut->readOnlyPage();
1085 $wgUser->addWatch( $this->mTitle
);
1087 $wgUser->removeWatch( $this->mTitle
);
1089 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1090 $wgOut->setRobotpolicy( 'noindex,follow' );
1092 $sk = $wgUser->getSkin() ;
1093 $link = $this->mTitle
->getPrefixedText();
1096 $text = wfMsg( 'addedwatchtext', $link );
1098 $text = wfMsg( 'removedwatchtext', $link );
1099 $wgOut->addWikiText( $text );
1101 $up = new UserUpdate();
1102 array_push( $wgDeferredUpdateList, $up );
1104 $wgOut->returnToMain( false );
1109 $this->watch( false );
1112 function protect( $limit = 'sysop' )
1114 global $wgUser, $wgOut, $wgRequest;
1116 if ( ! $wgUser->isSysop() ) {
1117 $wgOut->sysopRequired();
1120 if ( wfReadOnly() ) {
1121 $wgOut->readOnlyPage();
1124 $id = $this->mTitle
->getArticleID();
1126 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1130 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1131 $reason = $wgRequest->getText( 'wpReasonProtect' );
1134 $dbw =& wfGetDB( DB_MASTER
);
1135 $dbw->updateArray( 'cur',
1137 'cur_touched' => wfTimestampNow(),
1138 'cur_restrictions' => (string)$limit
1139 ), array( /* WHERE */
1141 ), 'Article::protect'
1144 $log = new LogPage( wfMsg( 'protectlogpage' ), wfMsg( 'protectlogtext' ) );
1145 if ( $limit === "" ) {
1146 $log->addEntry( wfMsg( 'unprotectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1148 $log->addEntry( wfMsg( 'protectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1150 $wgOut->redirect( $this->mTitle
->getFullURL() );
1153 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1154 return $this->confirmProtect( '', $reason, $limit );
1158 # Output protection confirmation dialog
1159 function confirmProtect( $par, $reason, $limit = 'sysop' )
1163 wfDebug( "Article::confirmProtect\n" );
1165 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1166 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1171 if ( $limit === '' ) {
1172 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1173 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1174 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1175 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1176 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1177 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1179 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1180 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1181 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1182 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1183 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1184 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1187 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1190 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1194 <label for='wpReasonProtect'>{$protcom}:</label>
1197 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1205 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1208 <label for='wpConfirmProtect'>{$check}</label>
1214 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1220 $wgOut->returnToMain( false );
1223 function unprotect()
1225 return $this->protect( '' );
1228 # UI entry point for page deletion
1231 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1232 $fname = 'Article::delete';
1233 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1234 $reason = $wgRequest->getText( 'wpReason' );
1236 # This code desperately needs to be totally rewritten
1239 if ( ( ! $wgUser->isSysop() ) ) {
1240 $wgOut->sysopRequired();
1243 if ( wfReadOnly() ) {
1244 $wgOut->readOnlyPage();
1248 # Better double-check that it hasn't been deleted yet!
1249 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1250 if ( ( '' == trim( $this->mTitle
->getText() ) )
1251 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1252 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1257 $this->doDelete( $reason );
1261 # determine whether this page has earlier revisions
1262 # and insert a warning if it does
1263 # we select the text because it might be useful below
1264 $dbr =& wfGetDB( DB_SLAVE
);
1265 $ns = $this->mTitle
->getNamespace();
1266 $title = $this->mTitle
->getDBkey();
1267 $old = $dbr->getArray( 'old',
1268 array( 'old_text', 'old_flags' ),
1270 'old_namespace' => $ns,
1271 'old_title' => $title,
1272 ), $fname, array( 'ORDER BY' => 'inverse_timestamp' )
1275 if( $old !== false && !$confirm ) {
1276 $skin=$wgUser->getSkin();
1277 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1278 $wgOut->addHTML( $skin->historyLink() .'</b>');
1282 $s = $dbr->getArray( 'cur',
1283 array( 'cur_text' ),
1285 'cur_namespace' => $ns,
1286 'cur_title' => $title,
1290 if( $s !== false ) {
1291 # if this is a mini-text, we can paste part of it into the deletion reason
1293 #if this is empty, an earlier revision may contain "useful" text
1295 if($s->cur_text
!="") {
1299 $text = Article
::getRevisionText( $old );
1305 $length=strlen($text);
1307 # this should not happen, since it is not possible to store an empty, new
1308 # page. Let's insert a standard text in case it does, though
1309 if($length == 0 && $reason === '') {
1310 $reason = wfMsg('exblank');
1313 if($length < 500 && $reason === '') {
1315 # comment field=255, let's grep the first 150 to have some user
1317 $text=substr($text,0,150);
1318 # let's strip out newlines and HTML tags
1319 $text=preg_replace('/\"/',"'",$text);
1320 $text=preg_replace('/\</','<',$text);
1321 $text=preg_replace('/\>/','>',$text);
1322 $text=preg_replace("/[\n\r]/",'',$text);
1324 $reason=wfMsg('excontent'). " '".$text;
1326 $reason=wfMsg('exbeforeblank') . " '".$text;
1328 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1333 return $this->confirmDelete( '', $reason );
1336 # Output deletion confirmation dialog
1337 function confirmDelete( $par, $reason )
1341 wfDebug( "Article::confirmDelete\n" );
1343 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1344 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1345 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1346 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1348 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1350 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1351 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1352 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1355 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1359 <label for='wpReason'>{$delcom}:</label>
1362 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1370 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1373 <label for='wpConfirm'>{$check}</label>
1379 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1385 $wgOut->returnToMain( false );
1388 # Perform a deletion and output success or failure messages
1389 function doDelete( $reason )
1391 global $wgOut, $wgUser, $wgLang;
1392 $fname = 'Article::doDelete';
1393 wfDebug( "$fname\n" );
1395 if ( $this->doDeleteArticle( $reason ) ) {
1396 $deleted = $this->mTitle
->getPrefixedText();
1398 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1399 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1401 $sk = $wgUser->getSkin();
1402 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1403 Namespace::getWikipedia() ) .
1404 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1406 $text = wfMsg( "deletedtext", $deleted, $loglink );
1408 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1409 $wgOut->returnToMain( false );
1411 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1415 # Back-end article deletion
1416 # Deletes the article with database consistency, writes logs, purges caches
1418 function doDeleteArticle( $reason )
1420 global $wgUser, $wgLang;
1421 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1423 $fname = 'Article::doDeleteArticle';
1424 wfDebug( $fname."\n" );
1426 $dbw =& wfGetDB( DB_MASTER
);
1427 $ns = $this->mTitle
->getNamespace();
1428 $t = $this->mTitle
->getDBkey();
1429 $id = $this->mTitle
->getArticleID();
1431 if ( '' == $t ||
$id == 0 ) {
1435 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1436 array_push( $wgDeferredUpdateList, $u );
1438 $linksTo = $this->mTitle
->getLinksTo();
1441 if ( $wgUseSquid ) {
1443 $this->mTitle
->getInternalURL(),
1444 $this->mTitle
->getInternalURL( 'history' )
1446 foreach ( $linksTo as $linkTo ) {
1447 $urls[] = $linkTo->getInternalURL();
1450 $u = new SquidUpdate( $urls );
1451 array_push( $wgDeferredUpdateList, $u );
1455 # Client and file cache invalidation
1456 Title
::touchArray( $linksTo );
1458 # Move article and history to the "archive" table
1459 $archiveTable = $dbw->tableName( 'archive' );
1460 $oldTable = $dbw->tableName( 'old' );
1461 $curTable = $dbw->tableName( 'cur' );
1462 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1463 $linksTable = $dbw->tableName( 'links' );
1464 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1466 $dbw->insertSelect( 'archive', 'cur',
1468 'ar_namespace' => 'cur_namespace',
1469 'ar_title' => 'cur_title',
1470 'ar_text' => 'cur_text',
1471 'ar_comment' => 'cur_comment',
1472 'ar_user' => 'cur_user',
1473 'ar_user_text' => 'cur_user_text',
1474 'ar_timestamp' => 'cur_timestamp',
1475 'ar_minor_edit' => 'cur_minor_edit',
1478 'cur_namespace' => $ns,
1483 $dbw->insertSelect( 'archive', 'old',
1485 'ar_namespace' => 'old_namespace',
1486 'ar_title' => 'old_title',
1487 'ar_text' => 'old_text',
1488 'ar_comment' => 'old_comment',
1489 'ar_user' => 'old_user',
1490 'ar_user_text' => 'old_user_text',
1491 'ar_timestamp' => 'old_timestamp',
1492 'ar_minor_edit' => 'old_minor_edit',
1493 'ar_flags' => 'old_flags'
1495 'old_namespace' => $ns,
1500 # Now that it's safely backed up, delete it
1502 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1503 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1504 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1506 # Finally, clean up the link tables
1507 $t = $this->mTitle
->getPrefixedDBkey();
1509 Article
::onArticleDelete( $this->mTitle
);
1511 # Insert broken links
1512 $brokenLinks = array();
1513 foreach ( $linksTo as $titleObj ) {
1514 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1515 $linkID = $titleObj->getArticleID();
1516 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1518 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1521 $dbw->delete( 'links', array( 'l_to' => $id ) );
1522 $dbw->delete( 'links', array( 'l_from' => $id ) );
1523 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1524 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1525 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1528 $log = new LogPage( wfMsg( 'dellogpage' ), wfMsg( 'dellogpagetext' ) );
1529 $art = $this->mTitle
->getPrefixedText();
1530 $log->addEntry( wfMsg( 'deletedarticle', $art ), $reason );
1532 # Clear the cached article id so the interface doesn't act like we exist
1533 $this->mTitle
->resetArticleID( 0 );
1534 $this->mTitle
->mArticleID
= 0;
1540 global $wgUser, $wgLang, $wgOut, $wgRequest;
1541 $fname = "Article::rollback";
1543 if ( ! $wgUser->isSysop() ) {
1544 $wgOut->sysopRequired();
1547 if ( wfReadOnly() ) {
1548 $wgOut->readOnlyPage( $this->getContent( true ) );
1551 $dbw =& wfGetDB( DB_MASTER
);
1553 # Enhanced rollback, marks edits rc_bot=1
1554 $bot = $wgRequest->getBool( 'bot' );
1556 # Replace all this user's current edits with the next one down
1557 $tt = $this->mTitle
->getDBKey();
1558 $n = $this->mTitle
->getNamespace();
1560 # Get the last editor, lock table exclusively
1561 $s = $dbw->getArray( 'cur',
1562 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1563 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1564 $fname, 'FOR UPDATE'
1566 if( $s === false ) {
1568 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1571 $ut = $dbw->strencode( $s->cur_user_text
);
1572 $uid = $s->cur_user
;
1575 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1576 if( $from != $s->cur_user_text
) {
1577 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1578 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1579 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1580 htmlspecialchars( $from ),
1581 htmlspecialchars( $s->cur_user_text
) ) );
1582 if($s->cur_comment
!= '') {
1584 wfMsg('editcomment',
1585 htmlspecialchars( $s->cur_comment
) ) );
1590 # Get the last edit not by this guy
1591 $s = $dbw->getArray( 'old',
1592 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1594 'old_namespace' => $n,
1596 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1597 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1599 if( $s === false ) {
1601 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1602 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1607 # Mark all reverted edits as bot
1608 $dbw->updateArray( 'recentchanges',
1611 ), array( /* WHERE */
1613 "rc_timestamp > '{$s->old_timestamp}'",
1619 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1620 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1621 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1622 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1623 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1624 Article
::onArticleEdit( $this->mTitle
);
1625 $wgOut->returnToMain( false );
1629 # Do standard deferred updates after page view
1631 /* private */ function viewUpdates()
1633 global $wgDeferredUpdateList;
1634 if ( 0 != $this->getID() ) {
1635 global $wgDisableCounters;
1636 if( !$wgDisableCounters ) {
1637 Article
::incViewCount( $this->getID() );
1638 $u = new SiteStatsUpdate( 1, 0, 0 );
1639 array_push( $wgDeferredUpdateList, $u );
1641 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1642 $this->mTitle
->getDBkey() );
1643 array_push( $wgDeferredUpdateList, $u );
1647 # Do standard deferred updates after page edit.
1648 # Every 1000th edit, prune the recent changes table.
1650 /* private */ function editUpdates( $text )
1652 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1653 global $wgMessageCache;
1656 if ( 0 == mt_rand( 0, 999 ) ) {
1657 $dbw =& wfGetDB( DB_MASTER
);
1658 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1659 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1660 $dbw->query( $sql );
1662 $id = $this->getID();
1663 $title = $this->mTitle
->getPrefixedDBkey();
1664 $shortTitle = $this->mTitle
->getDBkey();
1666 $adj = $this->mCountAdjustment
;
1669 $u = new LinksUpdate( $id, $title );
1670 array_push( $wgDeferredUpdateList, $u );
1671 $u = new SiteStatsUpdate( 0, 1, $adj );
1672 array_push( $wgDeferredUpdateList, $u );
1673 $u = new SearchUpdate( $id, $title, $text );
1674 array_push( $wgDeferredUpdateList, $u );
1676 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1677 array_push( $wgDeferredUpdateList, $u );
1679 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1680 $wgMessageCache->replace( $shortTitle, $text );
1685 /* private */ function setOldSubtitle()
1687 global $wgLang, $wgOut;
1689 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1690 $r = wfMsg( 'revisionasof', $td );
1691 $wgOut->setSubtitle( "({$r})" );
1694 # This function is called right before saving the wikitext,
1695 # so we can do things like signatures and links-in-context.
1697 function preSaveTransform( $text )
1699 global $wgParser, $wgUser;
1700 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1703 /* Caching functions */
1705 # checkLastModified returns true if it has taken care of all
1706 # output to the client that is necessary for this request.
1707 # (that is, it has sent a cached version of the page)
1708 function tryFileCache() {
1709 static $called = false;
1711 wfDebug( " tryFileCache() -- called twice!?\n" );
1715 if($this->isFileCacheable()) {
1716 $touched = $this->mTouched
;
1717 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1718 # Expire the main page quicker
1719 $expire = wfUnix2Timestamp( time() - 3600 );
1720 $touched = max( $expire, $touched );
1722 $cache = new CacheManager( $this->mTitle
);
1723 if($cache->isFileCacheGood( $touched )) {
1725 wfDebug( " tryFileCache() - about to load\n" );
1726 $cache->loadFromFileCache();
1729 wfDebug( " tryFileCache() - starting buffer\n" );
1730 ob_start( array(&$cache, 'saveToFileCache' ) );
1733 wfDebug( " tryFileCache() - not cacheable\n" );
1737 function isFileCacheable() {
1738 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1739 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1741 return $wgUseFileCache
1742 and (!$wgShowIPinHeader)
1743 and ($this->getID() != 0)
1744 and ($wgUser->getId() == 0)
1745 and (!$wgUser->getNewtalk())
1746 and ($this->mTitle
->getNamespace() != Namespace::getSpecial())
1747 and ($action == 'view' ||
empty( $action ))
1748 and (!isset($oldid))
1750 and (!isset($redirect))
1751 and (!isset($printable))
1752 and (!$this->mRedirectedFrom
);
1755 # Loads cur_touched and returns a value indicating if it should be used
1756 function checkTouched() {
1757 $fname = 'Article::checkTouched';
1759 $id = $this->getID();
1760 $dbr =& wfGetDB( DB_SLAVE
);
1761 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1762 array( 'cur_id' => $id ), $fname );
1763 if( $s !== false ) {
1764 $this->mTouched
= $s->cur_touched
;
1765 return !$s->cur_is_redirect
;
1771 # Edit an article without doing all that other stuff
1772 function quickEdit( $text, $comment = '', $minor = 0 ) {
1773 global $wgUser, $wgMwRedir;
1774 $fname = 'Article::quickEdit';
1775 wfProfileIn( $fname );
1777 $dbw =& wfGetDB( DB_MASTER
);
1778 $ns = $this->mTitle
->getNamespace();
1779 $dbkey = $this->mTitle
->getDBkey();
1780 $encDbKey = $dbw->strencode( $dbkey );
1781 $timestamp = wfTimestampNow();
1784 $dbw->insertSelect( 'old', 'cur',
1786 'old_namespace' => 'cur_namespace',
1787 'old_title' => 'cur_title',
1788 'old_text' => 'cur_text',
1789 'old_comment' => 'cur_comment',
1790 'old_user' => 'cur_user',
1791 'old_user_text' => 'cur_user_text',
1792 'old_timestamp' => 'cur_timestamp',
1793 'inverse_timestamp' => '99999999999999-cur_timestamp',
1795 'cur_namespace' => $ns,
1796 'cur_title' => $dbkey,
1800 # Use the affected row count to determine if the article is new
1801 $numRows = $dbw->affectedRows();
1803 # Make an array of fields to be inserted
1805 'cur_text' => $text,
1806 'cur_timestamp' => $timestamp,
1807 'cur_user' => $wgUser->getID(),
1808 'cur_user_text' => $wgUser->getName(),
1809 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1810 'cur_comment' => $comment,
1811 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ?
1 : 0,
1812 'cur_minor_edit' => intval($minor),
1813 'cur_touched' => $timestamp,
1818 $fields['cur_is_new'] = 0;
1819 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1821 # Insert new article
1822 $fields['cur_is_new'] = 1;
1823 $fields['cur_namespace'] = $ns;
1824 $fields['cur_title'] = $dbkey;
1825 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1826 $dbw->insertArray( 'cur', $fields, $fname );
1828 wfProfileOut( $fname );
1831 /* static */ function incViewCount( $id )
1833 $id = intval( $id );
1834 global $wgHitcounterUpdateFreq;
1836 $dbw =& wfGetDB( DB_MASTER
);
1837 $curTable = $dbw->tableName( 'cur' );
1838 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1839 $acchitsTable = $dbw->tableName( 'acchits' );
1841 if( $wgHitcounterUpdateFreq <= 1 ){ //
1842 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
1846 # Not important enough to warrant an error page in case of failure
1847 $oldignore = $dbw->setIgnoreErrors( true );
1849 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
1851 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
1852 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
1853 # Most of the time (or on SQL errors), skip row count check
1854 $dbw->setIgnoreErrors( $oldignore );
1858 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
1859 $row = $dbw->fetchObject( $res );
1860 $rown = intval( $row->n
);
1861 if( $rown >= $wgHitcounterUpdateFreq ){
1862 wfProfileIn( 'Article::incViewCount-collect' );
1863 $old_user_abort = ignore_user_abort( true );
1865 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
1866 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
1867 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
1869 $dbw->query("DELETE FROM $hitcounterTable");
1870 $dbw->query('UNLOCK TABLES');
1871 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
1872 'WHERE cur_id = hc_id');
1873 $dbw->query("DROP TABLE $acchitsTable");
1875 ignore_user_abort( $old_user_abort );
1876 wfProfileOut( 'Article::incViewCount-collect' );
1878 $dbw->setIgnoreErrors( $oldignore );
1881 # The onArticle*() functions are supposed to be a kind of hooks
1882 # which should be called whenever any of the specified actions
1885 # This is a good place to put code to clear caches, for instance.
1887 # This is called on page move and undelete, as well as edit
1888 /* static */ function onArticleCreate($title_obj){
1889 global $wgUseSquid, $wgDeferredUpdateList;
1891 $titles = $title_obj->getBrokenLinksTo();
1894 if ( $wgUseSquid ) {
1895 $urls = $title_obj->getSquidURLs();
1896 foreach ( $titles as $linkTitle ) {
1897 $urls[] = $linkTitle->getInternalURL();
1899 $u = new SquidUpdate( $urls );
1900 array_push( $wgDeferredUpdateList, $u );
1903 # Clear persistent link cache
1904 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1907 /* static */ function onArticleDelete($title_obj){
1908 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
1911 /* static */ function onArticleEdit($title_obj){
1912 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
1915 # Info about this page
1919 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgAllowPageInfo;
1920 $fname = 'Article::info';
1922 if ( !$wgAllowPageInfo ) {
1923 $wgOut->errorpage( "nosuchaction", "nosuchactiontext" );
1927 $dbr =& wfGetDB( DB_SLAVE
);
1929 $basenamespace = $wgTitle->getNamespace() & (~
1);
1930 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
1931 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
1932 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
1933 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
1934 $wgOut->setPagetitle( $fullTitle );
1935 $wgOut->setSubtitle( wfMsg( "infosubtitle" ));
1937 # first, see if the page exists at all.
1938 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname );
1940 $wgOut->addHTML( wfMsg("noarticletext") );
1942 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname );
1943 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . "</li>" );
1944 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname );
1945 $wgOut->addHTML( "<li>" . wfMsg("numedits", $old +
1) . "</li>");
1947 # to find number of distinct authors, we need to do some
1948 # funny stuff because of the cur/old table split:
1949 # - first, find the name of the 'cur' author
1950 # - then, find the number of *other* authors in 'old'
1953 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname );
1955 # find number of 'old' authors excluding 'cur' author
1956 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
1957 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname ) +
1;
1959 # now for the Talk page ...
1960 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
1961 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
1964 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname );
1968 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname );
1969 $wgOut->addHTML( "<li>" . wfMsg("numtalkedits", $old +
1) . "</li>");
1971 $wgOut->addHTML( "<li>" . wfMsg("numauthors", $authors) . "</li>" );
1975 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname );
1976 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
1977 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname );
1979 $wgOut->addHTML( "<li>" . wfMsg("numtalkauthors", $authors) . "</li></ul>" );