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 );
221 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
222 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
223 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
226 wfProfileOut( $fname );
227 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
229 if($action=='edit') {
231 if($section=='new') {
232 wfProfileOut( $fname );
236 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
237 # comments to be stripped as well)
238 $rv=$this->getSection($this->mContent
,$section);
239 wfProfileOut( $fname );
243 wfProfileOut( $fname );
244 return $this->mContent
;
249 # This function returns the text of a section, specified by a number ($section).
250 # A section is text under a heading like == Heading == or <h1>Heading</h1>, or
251 # the first section before any such heading (section 0).
253 # If a section contains subsections, these are also returned.
255 function getSection($text,$section) {
257 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
258 # comments to be stripped as well)
260 $parser=new Parser();
261 $parser->mOutputType
=OT_WIKI
;
262 $striptext=$parser->strip($text, $striparray, true);
264 # now that we can be sure that no pseudo-sections are in the source,
265 # split it up by section
268 '/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
270 PREG_SPLIT_DELIM_CAPTURE
);
274 $headline=$secs[$section*2-1];
275 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
278 # translate wiki heading into level
279 if(strpos($hlevel,'=')!==false) {
280 $hlevel=strlen($hlevel);
283 $rv=$headline. $secs[$section*2];
287 while(!empty($secs[$count*2-1]) && !$break) {
289 $subheadline=$secs[$count*2-1];
290 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
291 $subhlevel=$matches[1];
292 if(strpos($subhlevel,'=')!==false) {
293 $subhlevel=strlen($subhlevel);
295 if($subhlevel > $hlevel) {
296 $rv.=$subheadline.$secs[$count*2];
298 if($subhlevel <= $hlevel) {
305 # reinsert stripped tags
306 $rv=$parser->unstrip($rv,$striparray);
307 $rv=$parser->unstripNoWiki($rv,$striparray);
313 # Return an array of the columns of the "cur"-table
314 function &getCurContentFields() {
315 global $wgArticleCurContentFields;
316 if ( !$wgArticleCurContentFields ) {
317 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
318 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
320 return $wgArticleCurContentFields;
323 # Return an array of the columns of the "old"-table
324 function &getOldContentFields() {
325 global $wgArticleOldContentFields;
326 if ( !$wgArticleOldContentFields ) {
327 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
328 'old_user','old_user_text','old_comment','old_flags' );
330 return $wgArticleOldContentFields;
333 # Load the revision (including cur_text) into this object
334 function loadContent( $noredir = false )
336 global $wgOut, $wgMwRedir, $wgRequest;
338 $dbr =& wfGetDB( DB_SLAVE
);
340 $oldid = $wgRequest->getVal( 'oldid' );
341 $redirect = $wgRequest->getVal( 'redirect' );
343 if ( $this->mContentLoaded
) return;
344 $fname = 'Article::loadContent';
346 # Pre-fill content with error message so that if something
347 # fails we'll have something telling us what we intended.
349 $t = $this->mTitle
->getPrefixedText();
350 if ( isset( $oldid ) ) {
351 $oldid = IntVal( $oldid );
352 $t .= ",oldid={$oldid}";
354 if ( isset( $redirect ) ) {
355 $redirect = ($redirect == 'no') ?
'no' : 'yes';
356 $t .= ",redirect={$redirect}";
358 $this->mContent
= wfMsg( 'missingarticle', $t );
360 if ( ! $oldid ) { # Retrieve current version
361 $id = $this->getID();
362 if ( 0 == $id ) return;
364 $s = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname );
365 if ( $s === false ) {
369 # If we got a redirect, follow it (unless we've been told
370 # not to by either the function parameter or the query
371 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
372 $rt = Title
::newFromRedirect( $s->cur_text
);
374 # Gotta hand redirects to special pages differently:
375 # Fill the HTTP response "Location" header and ignore
376 # the rest of the page we're on.
378 if ( $rt->getInterwiki() != '' ) {
379 $wgOut->redirect( $rt->getFullURL() ) ;
382 if ( $rt->getNamespace() == NS_SPECIAL
) {
383 $wgOut->redirect( $rt->getFullURL() );
386 $rid = $rt->getArticleID();
388 $redirRow = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $rid ), $fname );
390 if ( $redirRow !== false ) {
391 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
399 $this->mContent
= $s->cur_text
;
400 $this->mUser
= $s->cur_user
;
401 $this->mUserText
= $s->cur_user_text
;
402 $this->mComment
= $s->cur_comment
;
403 $this->mCounter
= $s->cur_counter
;
404 $this->mTimestamp
= $s->cur_timestamp
;
405 $this->mTouched
= $s->cur_touched
;
406 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
407 $this->mTitle
->mRestrictionsLoaded
= true;
408 } else { # oldid set, retrieve historical version
409 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ), $fname );
410 if ( $s === false ) {
414 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
415 $this->mTitle
->getDBkey() != $s->old_title
) {
416 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
417 $this->mTitle
= $oldTitle;
418 $wgTitle = $oldTitle;
420 $this->mContent
= Article
::getRevisionText( $s );
421 $this->mUser
= $s->old_user
;
422 $this->mUserText
= $s->old_user_text
;
423 $this->mComment
= $s->old_comment
;
425 $this->mTimestamp
= $s->old_timestamp
;
427 $this->mContentLoaded
= true;
428 return $this->mContent
;
431 # Gets the article text without using so many damn globals
432 # Returns false on error
433 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
436 if ( $this->mContentLoaded
) {
437 return $this->mContent
;
439 $this->mContent
= false;
441 $fname = 'Article::getContentWithout';
442 $dbr =& wfGetDB( DB_SLAVE
);
444 if ( ! $oldid ) { # Retrieve current version
445 $id = $this->getID();
450 $s = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname );
451 if ( $s === false ) {
455 # If we got a redirect, follow it (unless we've been told
456 # not to by either the function parameter or the query
458 $rt = Title
::newFromRedirect( $s->cur_text
);
459 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
460 $rid = $rt->getArticleID();
462 $redirRow = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $rid ), $fname );
464 if ( $redirRow !== false ) {
465 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
473 $this->mContent
= $s->cur_text
;
474 $this->mUser
= $s->cur_user
;
475 $this->mUserText
= $s->cur_user_text
;
476 $this->mComment
= $s->cur_comment
;
477 $this->mCounter
= $s->cur_counter
;
478 $this->mTimestamp
= $s->cur_timestamp
;
479 $this->mTouched
= $s->cur_touched
;
480 $this->mTitle
->mRestrictions
= explode( ",", trim( $s->cur_restrictions
) );
481 $this->mTitle
->mRestrictionsLoaded
= true;
482 } else { # oldid set, retrieve historical version
483 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ) );
484 if ( $s === false ) {
487 $this->mContent
= Article
::getRevisionText( $s );
488 $this->mUser
= $s->old_user
;
489 $this->mUserText
= $s->old_user_text
;
490 $this->mComment
= $s->old_comment
;
492 $this->mTimestamp
= $s->old_timestamp
;
494 $this->mContentLoaded
= true;
495 return $this->mContent
;
499 if( $this->mTitle
) {
500 return $this->mTitle
->getArticleID();
508 if ( -1 == $this->mCounter
) {
509 $id = $this->getID();
510 $dbr =& wfGetDB( DB_SLAVE
);
511 $this->mCounter
= $dbr->getField( 'cur', 'cur_counter', "cur_id={$id}" );
513 return $this->mCounter
;
516 # Would the given text make this article a "good" article (i.e.,
517 # suitable for including in the article count)?
519 function isCountable( $text )
521 global $wgUseCommaCount, $wgMwRedir;
523 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
524 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
525 $token = ($wgUseCommaCount ?
',' : '[[' );
526 if ( false === strstr( $text, $token ) ) { return 0; }
530 # Loads everything from cur except cur_text
531 # This isn't necessary for all uses, so it's only done if needed.
533 /* private */ function loadLastEdit()
536 if ( -1 != $this->mUser
) return;
538 $fname = 'Article::loadLastEdit';
540 $dbr =& wfGetDB( DB_SLAVE
);
541 $s = $dbr->getArray( 'cur',
542 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
543 array( 'cur_id' => $this->getID() ), $fname );
545 if ( $s !== false ) {
546 $this->mUser
= $s->cur_user
;
547 $this->mUserText
= $s->cur_user_text
;
548 $this->mTimestamp
= $s->cur_timestamp
;
549 $this->mComment
= $s->cur_comment
;
550 $this->mMinorEdit
= $s->cur_minor_edit
;
554 function getTimestamp()
556 $this->loadLastEdit();
557 return $this->mTimestamp
;
562 $this->loadLastEdit();
566 function getUserText()
568 $this->loadLastEdit();
569 return $this->mUserText
;
572 function getComment()
574 $this->loadLastEdit();
575 return $this->mComment
;
578 function getMinorEdit()
580 $this->loadLastEdit();
581 return $this->mMinorEdit
;
584 function getContributors($limit = 0, $offset = 0)
586 $fname = 'Article::getContributors';
588 # XXX: this is expensive; cache this info somewhere.
590 $title = $this->mTitle
;
592 $dbr =& wfGetDB( DB_SLAVE
);
593 $oldTable = $dbr->tableName( 'old' );
594 $userTable = $dbr->tableName( 'user' );
595 $encDBkey = $dbr->strencode( $title->getDBkey() );
596 $ns = $title->getNamespace();
597 $user = $this->getUser();
599 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
600 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
601 WHERE old_namespace = $user
602 AND old_title = $encDBkey
603 AND old_user != $user
605 ORDER BY timestamp DESC";
608 $sql .= ' LIMIT '.$limit;
611 $res = $dbr->query($sql, $fname);
613 while ( $line = $dbr->fetchObject( $res ) ) {
614 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
617 $dbr->freeResult($res);
622 # This is the default action of the script: just view the page of
627 global $wgUser, $wgOut, $wgLang, $wgRequest, $wgMwRedir, $wgOnlySysopsCanPatrol;
628 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
629 $sk = $wgUser->getSkin();
631 $fname = 'Article::view';
632 wfProfileIn( $fname );
634 # Get variables from query string
635 $oldid = $wgRequest->getVal( 'oldid' );
636 $diff = $wgRequest->getVal( 'diff' );
637 $rcid = $wgRequest->getVal( 'rcid' );
639 $wgOut->setArticleFlag( true );
640 $wgOut->setRobotpolicy( 'index,follow' );
642 # If we got diff and oldid in the query, we want to see a
643 # diff page instead of the article.
645 if ( !is_null( $diff ) ) {
646 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
647 $de = new DifferenceEngine( intval($oldid), intval($diff), intval($rcid) );
649 wfProfileOut( $fname );
651 # Run view updates for current revision only
652 $this->viewUpdates();
657 if ( empty( $oldid ) && $this->checkTouched() ) {
658 if( $wgOut->checkLastModified( $this->mTouched
) ){
660 } else if ( $this->tryFileCache() ) {
661 # tell wgOut that output is taken care of
663 $this->viewUpdates();
668 # Should the parser cache be used?
669 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
677 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
682 if ( !$outputDone ) {
683 $text = $this->getContent( false ); # May change mTitle by following a redirect
685 # Another whitelist check in case oldid or redirects are altering the title
686 if ( !$this->mTitle
->userCanRead() ) {
687 $wgOut->loginToUse();
693 # We're looking at an old revision
695 if ( !empty( $oldid ) ) {
696 $this->setOldSubtitle();
697 $wgOut->setRobotpolicy( 'noindex,follow' );
699 if ( '' != $this->mRedirectedFrom
) {
700 $sk = $wgUser->getSkin();
701 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
703 $s = wfMsg( 'redirectedfrom', $redir );
704 $wgOut->setSubtitle( $s );
706 # Can't cache redirects
710 # wrap user css and user js in pre and don't parse
711 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
713 $this->mTitle
->getNamespace() == NS_USER
&&
714 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
716 $wgOut->addWikiText( wfMsg('clearyourcache'));
717 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
718 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
720 $imageUrl = "$wgStylePath/images/redirect.png";
721 $targetUrl = $rt->escapeLocalURL();
722 $titleText = htmlspecialchars( $rt->getPrefixedText() );
723 $link = $sk->makeLinkObj( $rt );
724 $wgOut->addHTML( "<img valign=\"center\" src=\"$imageUrl\">" .
725 "<span class=\"redirectText\">$link</span>" );
726 } else if ( $pcache ) {
727 # Display content and save to parser cache
728 $wgOut->addWikiText( $text, true, $this );
730 # Display content, don't attempt to save to parser cache
731 $wgOut->addWikiText( $text );
734 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
736 # If we have been passed an &rcid= parameter, we want to give the user a
737 # chance to mark this new article as patrolled.
738 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
739 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
741 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
742 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
743 "action=markpatrolled&rcid={$rcid}" )
747 # Add link titles as META keywords
748 $wgOut->addMetaTags() ;
750 $this->viewUpdates();
751 wfProfileOut( $fname );
754 # Theoretically we could defer these whole insert and update
755 # functions for after display, but that's taking a big leap
756 # of faith, and we want to be able to report database
757 # errors at some point.
759 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
761 global $wgOut, $wgUser, $wgMwRedir;
762 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
764 $fname = 'Article::insertNewArticle';
766 $this->mCountAdjustment
= $this->isCountable( $text );
768 $ns = $this->mTitle
->getNamespace();
769 $ttl = $this->mTitle
->getDBkey();
770 $text = $this->preSaveTransform( $text );
771 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
774 $now = wfTimestampNow();
775 $won = wfInvertTimestamp( $now );
777 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
778 $dbw =& wfGetDB( DB_MASTER
);
780 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
782 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
784 $dbw->insertArray( 'cur', array(
786 'cur_namespace' => $ns,
789 'cur_comment' => $summary,
790 'cur_user' => $wgUser->getID(),
791 'cur_timestamp' => $now,
792 'cur_minor_edit' => $isminor,
794 'cur_restrictions' => '',
795 'cur_user_text' => $wgUser->getName(),
796 'cur_is_redirect' => $redir,
798 'cur_random' => $rand,
799 'cur_touched' => $now,
800 'inverse_timestamp' => $won,
803 $newid = $dbw->insertId();
804 $this->mTitle
->resetArticleID( $newid );
806 Article
::onArticleCreate( $this->mTitle
);
807 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
810 if(!$this->mTitle
->userIsWatching()) $this->watch();
812 if ( $this->mTitle
->userIsWatching() ) {
817 # The talk page isn't in the regular link tables, so we need to update manually:
818 $talkns = $ns ^
1; # talk -> normal; normal -> talk
819 $dbw->updateArray( 'cur', array( 'cur_touched' => $now ), array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
821 # standard deferred updates
822 $this->editUpdates( $text );
824 $this->showArticle( $text, wfMsg( 'newarticle' ) );
828 /* Side effects: loads last edit */
829 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ''){
830 $this->loadLastEdit();
831 $oldtext = $this->getContent( true );
832 if ($section != '') {
833 if($section=='new') {
834 if($summary) $subject="== {$summary} ==\n\n";
835 $text=$oldtext."\n\n".$subject.$text;
838 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
839 # comments to be stripped as well)
841 $parser=new Parser();
842 $parser->mOutputType
=OT_WIKI
;
843 $oldtext=$parser->strip($oldtext, $striparray, true);
845 # now that we can be sure that no pseudo-sections are in the source,
847 # Unfortunately we can't simply do a preg_replace because that might
848 # replace the wrong section, so we have to use the section counter instead
849 $secs=preg_split('/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
850 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
851 $secs[$section*2]=$text."\n\n"; // replace with edited
853 # section 0 is top (intro) section
856 # headline of old section - we need to go through this section
857 # to determine if there are any subsections that now need to
858 # be erased, as the mother section has been replaced with
859 # the text of all subsections.
860 $headline=$secs[$section*2-1];
861 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
864 # determine headline level for wikimarkup headings
865 if(strpos($hlevel,'=')!==false) {
866 $hlevel=strlen($hlevel);
869 $secs[$section*2-1]=''; // erase old headline
872 while(!empty($secs[$count*2-1]) && !$break) {
874 $subheadline=$secs[$count*2-1];
876 '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
877 $subhlevel=$matches[1];
878 if(strpos($subhlevel,'=')!==false) {
879 $subhlevel=strlen($subhlevel);
881 if($subhlevel > $hlevel) {
882 // erase old subsections
883 $secs[$count*2-1]='';
886 if($subhlevel <= $hlevel) {
894 $text=join('',$secs);
895 # reinsert the stuff that we stripped out earlier
896 $text=$parser->unstrip($text,$striparray);
897 $text=$parser->unstripNoWiki($text,$striparray);
904 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' )
906 global $wgOut, $wgUser;
907 global $wgDBtransactions, $wgMwRedir;
908 global $wgUseSquid, $wgInternalServer;
910 $fname = 'Article::updateArticle';
913 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
914 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
915 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
917 $text = $m[1] . "\n"; # Remove all content but redirect
921 $text = $this->preSaveTransform( $text );
922 $dbw =& wfGetDB( DB_MASTER
);
924 # Update article, but only if changed.
926 # It's important that we either rollback or complete, otherwise an attacker could
927 # overwrite cur entries by sending precisely timed user aborts. Random bored users
928 # could conceivably have the same effect, especially if cur is locked for long periods.
929 if( $wgDBtransactions ) {
930 $dbw->query( 'BEGIN', $fname );
932 $userAbort = ignore_user_abort( true );
935 $oldtext = $this->getContent( true );
937 if ( 0 != strcmp( $text, $oldtext ) ) {
938 $this->mCountAdjustment
= $this->isCountable( $text )
939 - $this->isCountable( $oldtext );
940 $now = wfTimestampNow();
941 $won = wfInvertTimestamp( $now );
943 # First update the cur row
944 $dbw->updateArray( 'cur',
947 'cur_comment' => $summary,
948 'cur_minor_edit' => $me2,
949 'cur_user' => $wgUser->getID(),
950 'cur_timestamp' => $now,
951 'cur_user_text' => $wgUser->getName(),
952 'cur_is_redirect' => $redir,
954 'cur_touched' => $now,
955 'inverse_timestamp' => $won
956 ), array( /* WHERE */
957 'cur_id' => $this->getID(),
958 'cur_timestamp' => $this->getTimestamp()
962 if( $dbw->affectedRows() == 0 ) {
963 /* Belated edit conflict! Run away!! */
966 # Now insert the previous revision into old
968 # This overwrites $oldtext if revision compression is on
969 $flags = Article
::compressRevisionText( $oldtext );
971 $dbw->insertArray( 'old',
973 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
974 'old_namespace' => $this->mTitle
->getNamespace(),
975 'old_title' => $this->mTitle
->getDBkey(),
976 'old_text' => $oldtext,
977 'old_comment' => $this->getComment(),
978 'old_user' => $this->getUser(),
979 'old_user_text' => $this->getUserText(),
980 'old_timestamp' => $this->getTimestamp(),
981 'old_minor_edit' => $me1,
982 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
983 'old_flags' => $flags,
987 $oldid = $dbw->insertId();
989 $bot = (int)($wgUser->isBot() ||
$forceBot);
990 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
991 $oldid, $this->getTimestamp(), $bot );
992 Article
::onArticleEdit( $this->mTitle
);
996 if( $wgDBtransactions ) {
997 $dbw->query( 'COMMIT', $fname );
999 ignore_user_abort( $userAbort );
1004 if (!$this->mTitle
->userIsWatching()) $this->watch();
1006 if ( $this->mTitle
->userIsWatching() ) {
1010 # standard deferred updates
1011 $this->editUpdates( $text );
1015 # Template namespace
1016 # Purge all articles linking here
1017 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1018 $titles = $this->mTitle
->getLinksTo();
1019 Title
::touchArray( $titles );
1020 if ( $wgUseSquid ) {
1021 foreach ( $titles as $title ) {
1022 $urls[] = $title->getInternalURL();
1028 if ( $wgUseSquid ) {
1029 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1030 $u = new SquidUpdate( $urls );
1034 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1039 # After we've either updated or inserted the article, update
1040 # the link tables and redirect to the new page.
1042 function showArticle( $text, $subtitle , $sectionanchor = '' )
1044 global $wgOut, $wgUser, $wgLinkCache;
1047 $wgLinkCache = new LinkCache();
1049 $wgLinkCache->forUpdate( true );
1051 # Get old version of link table to allow incremental link updates
1052 $wgLinkCache->preFill( $this->mTitle
);
1053 $wgLinkCache->clear();
1055 # Switch on use of link cache in the skin
1056 $sk =& $wgUser->getSkin();
1057 $sk->postParseLinkColour( false );
1059 # Now update the link cache by parsing the text
1060 $wgOut = new OutputPage();
1061 $wgOut->addWikiText( $text );
1063 if( $wgMwRedir->matchStart( $text ) )
1067 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1072 function validate ()
1075 $wgOut->setPagetitle( wfMsg( 'validate' ) . ": " . $this->mTitle
->getPrefixedText() );
1076 $wgOut->setRobotpolicy( 'noindex,follow' );
1077 if ( $this->mTitle
->getNamespace() != 0 )
1079 $wgOut->addHTML ( wfMsg ( 'val_validate_article_namespace_only' ) ) ;
1082 $v = new Validation
;
1083 $v->validate_form ( $this->mTitle
->getDBkey() ) ;
1086 # Mark this particular edit as patrolled
1087 function markpatrolled()
1089 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
1090 $wgOut->setRobotpolicy( 'noindex,follow' );
1092 if ( !$wgUseRCPatrol )
1094 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1097 if ( $wgUser->getID() == 0 )
1099 $wgOut->loginToUse();
1102 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1104 $wgOut->sysopRequired();
1107 $rcid = $wgRequest->getVal( 'rcid' );
1108 if ( !is_null ( $rcid ) )
1110 RecentChange
::markPatrolled( $rcid );
1111 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1112 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1113 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1117 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1122 # Add this page to my watchlist
1123 function watch( $add = true )
1125 global $wgUser, $wgOut, $wgLang;
1126 global $wgDeferredUpdateList;
1128 if ( 0 == $wgUser->getID() ) {
1129 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1132 if ( wfReadOnly() ) {
1133 $wgOut->readOnlyPage();
1137 $wgUser->addWatch( $this->mTitle
);
1139 $wgUser->removeWatch( $this->mTitle
);
1141 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1142 $wgOut->setRobotpolicy( 'noindex,follow' );
1144 $sk = $wgUser->getSkin() ;
1145 $link = $this->mTitle
->getPrefixedText();
1148 $text = wfMsg( 'addedwatchtext', $link );
1150 $text = wfMsg( 'removedwatchtext', $link );
1151 $wgOut->addWikiText( $text );
1153 $up = new UserUpdate();
1154 array_push( $wgDeferredUpdateList, $up );
1156 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1161 $this->watch( false );
1164 function protect( $limit = 'sysop' )
1166 global $wgUser, $wgOut, $wgRequest;
1168 if ( ! $wgUser->isSysop() ) {
1169 $wgOut->sysopRequired();
1172 if ( wfReadOnly() ) {
1173 $wgOut->readOnlyPage();
1176 $id = $this->mTitle
->getArticleID();
1178 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1182 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1183 $reason = $wgRequest->getText( 'wpReasonProtect' );
1186 $dbw =& wfGetDB( DB_MASTER
);
1187 $dbw->updateArray( 'cur',
1189 'cur_touched' => wfTimestampNow(),
1190 'cur_restrictions' => (string)$limit
1191 ), array( /* WHERE */
1193 ), 'Article::protect'
1196 $log = new LogPage( wfMsg( 'protectlogpage' ), wfMsg( 'protectlogtext' ) );
1197 if ( $limit === "" ) {
1198 $log->addEntry( wfMsg( 'unprotectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1200 $log->addEntry( wfMsg( 'protectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1202 $wgOut->redirect( $this->mTitle
->getFullURL() );
1205 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1206 return $this->confirmProtect( '', $reason, $limit );
1210 # Output protection confirmation dialog
1211 function confirmProtect( $par, $reason, $limit = 'sysop' )
1215 wfDebug( "Article::confirmProtect\n" );
1217 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1218 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1223 if ( $limit === '' ) {
1224 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1225 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1226 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1227 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1228 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1229 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1231 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1232 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1233 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1234 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1235 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1236 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1239 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1242 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1246 <label for='wpReasonProtect'>{$protcom}:</label>
1249 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1257 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1260 <label for='wpConfirmProtect'>{$check}</label>
1266 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1272 $wgOut->returnToMain( false );
1275 function unprotect()
1277 return $this->protect( '' );
1280 # UI entry point for page deletion
1283 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1284 $fname = 'Article::delete';
1285 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1286 $reason = $wgRequest->getText( 'wpReason' );
1288 # This code desperately needs to be totally rewritten
1291 if ( ( ! $wgUser->isSysop() ) ) {
1292 $wgOut->sysopRequired();
1295 if ( wfReadOnly() ) {
1296 $wgOut->readOnlyPage();
1300 # Better double-check that it hasn't been deleted yet!
1301 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1302 if ( ( '' == trim( $this->mTitle
->getText() ) )
1303 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1304 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1309 $this->doDelete( $reason );
1313 # determine whether this page has earlier revisions
1314 # and insert a warning if it does
1315 # we select the text because it might be useful below
1316 $dbr =& wfGetDB( DB_SLAVE
);
1317 $ns = $this->mTitle
->getNamespace();
1318 $title = $this->mTitle
->getDBkey();
1319 $old = $dbr->getArray( 'old',
1320 array( 'old_text', 'old_flags' ),
1322 'old_namespace' => $ns,
1323 'old_title' => $title,
1324 ), $fname, array( 'ORDER BY' => 'inverse_timestamp' )
1327 if( $old !== false && !$confirm ) {
1328 $skin=$wgUser->getSkin();
1329 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1330 $wgOut->addHTML( $skin->historyLink() .'</b>');
1334 $s = $dbr->getArray( 'cur',
1335 array( 'cur_text' ),
1337 'cur_namespace' => $ns,
1338 'cur_title' => $title,
1342 if( $s !== false ) {
1343 # if this is a mini-text, we can paste part of it into the deletion reason
1345 #if this is empty, an earlier revision may contain "useful" text
1347 if($s->cur_text
!="") {
1351 $text = Article
::getRevisionText( $old );
1357 $length=strlen($text);
1359 # this should not happen, since it is not possible to store an empty, new
1360 # page. Let's insert a standard text in case it does, though
1361 if($length == 0 && $reason === '') {
1362 $reason = wfMsg('exblank');
1365 if($length < 500 && $reason === '') {
1367 # comment field=255, let's grep the first 150 to have some user
1369 $text=substr($text,0,150);
1370 # let's strip out newlines and HTML tags
1371 $text=preg_replace('/\"/',"'",$text);
1372 $text=preg_replace('/\</','<',$text);
1373 $text=preg_replace('/\>/','>',$text);
1374 $text=preg_replace("/[\n\r]/",'',$text);
1376 $reason=wfMsg('excontent'). " '".$text;
1378 $reason=wfMsg('exbeforeblank') . " '".$text;
1380 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1385 return $this->confirmDelete( '', $reason );
1388 # Output deletion confirmation dialog
1389 function confirmDelete( $par, $reason )
1393 wfDebug( "Article::confirmDelete\n" );
1395 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1396 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1397 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1398 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1400 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1402 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1403 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1404 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1407 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1411 <label for='wpReason'>{$delcom}:</label>
1414 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1422 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1425 <label for='wpConfirm'>{$check}</label>
1431 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1437 $wgOut->returnToMain( false );
1440 # Perform a deletion and output success or failure messages
1441 function doDelete( $reason )
1443 global $wgOut, $wgUser, $wgLang;
1444 $fname = 'Article::doDelete';
1445 wfDebug( "$fname\n" );
1447 if ( $this->doDeleteArticle( $reason ) ) {
1448 $deleted = $this->mTitle
->getPrefixedText();
1450 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1451 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1453 $sk = $wgUser->getSkin();
1454 $loglink = $sk->makeKnownLink( $wgLang->getNsText( NS_WIKIPEDIA
) .
1455 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1457 $text = wfMsg( "deletedtext", $deleted, $loglink );
1459 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1460 $wgOut->returnToMain( false );
1462 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1466 # Back-end article deletion
1467 # Deletes the article with database consistency, writes logs, purges caches
1469 function doDeleteArticle( $reason )
1471 global $wgUser, $wgLang;
1472 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1474 $fname = 'Article::doDeleteArticle';
1475 wfDebug( $fname."\n" );
1477 $dbw =& wfGetDB( DB_MASTER
);
1478 $ns = $this->mTitle
->getNamespace();
1479 $t = $this->mTitle
->getDBkey();
1480 $id = $this->mTitle
->getArticleID();
1482 if ( '' == $t ||
$id == 0 ) {
1486 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1487 array_push( $wgDeferredUpdateList, $u );
1489 $linksTo = $this->mTitle
->getLinksTo();
1492 if ( $wgUseSquid ) {
1494 $this->mTitle
->getInternalURL(),
1495 $this->mTitle
->getInternalURL( 'history' )
1497 foreach ( $linksTo as $linkTo ) {
1498 $urls[] = $linkTo->getInternalURL();
1501 $u = new SquidUpdate( $urls );
1502 array_push( $wgDeferredUpdateList, $u );
1506 # Client and file cache invalidation
1507 Title
::touchArray( $linksTo );
1509 # Move article and history to the "archive" table
1510 $archiveTable = $dbw->tableName( 'archive' );
1511 $oldTable = $dbw->tableName( 'old' );
1512 $curTable = $dbw->tableName( 'cur' );
1513 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1514 $linksTable = $dbw->tableName( 'links' );
1515 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1517 $dbw->insertSelect( 'archive', 'cur',
1519 'ar_namespace' => 'cur_namespace',
1520 'ar_title' => 'cur_title',
1521 'ar_text' => 'cur_text',
1522 'ar_comment' => 'cur_comment',
1523 'ar_user' => 'cur_user',
1524 'ar_user_text' => 'cur_user_text',
1525 'ar_timestamp' => 'cur_timestamp',
1526 'ar_minor_edit' => 'cur_minor_edit',
1529 'cur_namespace' => $ns,
1534 $dbw->insertSelect( 'archive', 'old',
1536 'ar_namespace' => 'old_namespace',
1537 'ar_title' => 'old_title',
1538 'ar_text' => 'old_text',
1539 'ar_comment' => 'old_comment',
1540 'ar_user' => 'old_user',
1541 'ar_user_text' => 'old_user_text',
1542 'ar_timestamp' => 'old_timestamp',
1543 'ar_minor_edit' => 'old_minor_edit',
1544 'ar_flags' => 'old_flags'
1546 'old_namespace' => $ns,
1551 # Now that it's safely backed up, delete it
1553 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1554 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1555 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1557 # Finally, clean up the link tables
1558 $t = $this->mTitle
->getPrefixedDBkey();
1560 Article
::onArticleDelete( $this->mTitle
);
1562 # Insert broken links
1563 $brokenLinks = array();
1564 foreach ( $linksTo as $titleObj ) {
1565 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1566 $linkID = $titleObj->getArticleID();
1567 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1569 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1572 $dbw->delete( 'links', array( 'l_to' => $id ) );
1573 $dbw->delete( 'links', array( 'l_from' => $id ) );
1574 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1575 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1576 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1579 $log = new LogPage( wfMsg( 'dellogpage' ), wfMsg( 'dellogpagetext' ) );
1580 $art = $this->mTitle
->getPrefixedText();
1581 $log->addEntry( wfMsg( 'deletedarticle', $art ), $reason );
1583 # Clear the cached article id so the interface doesn't act like we exist
1584 $this->mTitle
->resetArticleID( 0 );
1585 $this->mTitle
->mArticleID
= 0;
1591 global $wgUser, $wgLang, $wgOut, $wgRequest;
1592 $fname = "Article::rollback";
1594 if ( ! $wgUser->isSysop() ) {
1595 $wgOut->sysopRequired();
1598 if ( wfReadOnly() ) {
1599 $wgOut->readOnlyPage( $this->getContent( true ) );
1602 $dbw =& wfGetDB( DB_MASTER
);
1604 # Enhanced rollback, marks edits rc_bot=1
1605 $bot = $wgRequest->getBool( 'bot' );
1607 # Replace all this user's current edits with the next one down
1608 $tt = $this->mTitle
->getDBKey();
1609 $n = $this->mTitle
->getNamespace();
1611 # Get the last editor, lock table exclusively
1612 $s = $dbw->getArray( 'cur',
1613 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1614 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1615 $fname, 'FOR UPDATE'
1617 if( $s === false ) {
1619 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1622 $ut = $dbw->strencode( $s->cur_user_text
);
1623 $uid = $s->cur_user
;
1626 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1627 if( $from != $s->cur_user_text
) {
1628 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1629 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1630 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1631 htmlspecialchars( $from ),
1632 htmlspecialchars( $s->cur_user_text
) ) );
1633 if($s->cur_comment
!= '') {
1635 wfMsg('editcomment',
1636 htmlspecialchars( $s->cur_comment
) ) );
1641 # Get the last edit not by this guy
1642 $s = $dbw->getArray( 'old',
1643 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1645 'old_namespace' => $n,
1647 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1648 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1650 if( $s === false ) {
1652 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1653 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1658 # Mark all reverted edits as bot
1659 $dbw->updateArray( 'recentchanges',
1662 ), array( /* WHERE */
1664 "rc_timestamp > '{$s->old_timestamp}'",
1670 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1671 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1672 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1673 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1674 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1675 Article
::onArticleEdit( $this->mTitle
);
1676 $wgOut->returnToMain( false );
1680 # Do standard deferred updates after page view
1682 /* private */ function viewUpdates()
1684 global $wgDeferredUpdateList;
1685 if ( 0 != $this->getID() ) {
1686 global $wgDisableCounters;
1687 if( !$wgDisableCounters ) {
1688 Article
::incViewCount( $this->getID() );
1689 $u = new SiteStatsUpdate( 1, 0, 0 );
1690 array_push( $wgDeferredUpdateList, $u );
1693 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1694 $this->mTitle
->getDBkey() );
1695 array_push( $wgDeferredUpdateList, $u );
1698 # Do standard deferred updates after page edit.
1699 # Every 1000th edit, prune the recent changes table.
1701 /* private */ function editUpdates( $text )
1703 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1704 global $wgMessageCache;
1707 if ( 0 == mt_rand( 0, 999 ) ) {
1708 $dbw =& wfGetDB( DB_MASTER
);
1709 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1710 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1711 $dbw->query( $sql );
1713 $id = $this->getID();
1714 $title = $this->mTitle
->getPrefixedDBkey();
1715 $shortTitle = $this->mTitle
->getDBkey();
1717 $adj = $this->mCountAdjustment
;
1720 $u = new LinksUpdate( $id, $title );
1721 array_push( $wgDeferredUpdateList, $u );
1722 $u = new SiteStatsUpdate( 0, 1, $adj );
1723 array_push( $wgDeferredUpdateList, $u );
1724 $u = new SearchUpdate( $id, $title, $text );
1725 array_push( $wgDeferredUpdateList, $u );
1727 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1728 array_push( $wgDeferredUpdateList, $u );
1730 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1731 $wgMessageCache->replace( $shortTitle, $text );
1736 /* private */ function setOldSubtitle()
1738 global $wgLang, $wgOut;
1740 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1741 $r = wfMsg( 'revisionasof', $td );
1742 $wgOut->setSubtitle( "({$r})" );
1745 # This function is called right before saving the wikitext,
1746 # so we can do things like signatures and links-in-context.
1748 function preSaveTransform( $text )
1750 global $wgParser, $wgUser;
1751 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1754 /* Caching functions */
1756 # checkLastModified returns true if it has taken care of all
1757 # output to the client that is necessary for this request.
1758 # (that is, it has sent a cached version of the page)
1759 function tryFileCache() {
1760 static $called = false;
1762 wfDebug( " tryFileCache() -- called twice!?\n" );
1766 if($this->isFileCacheable()) {
1767 $touched = $this->mTouched
;
1768 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1769 # Expire the main page quicker
1770 $expire = wfUnix2Timestamp( time() - 3600 );
1771 $touched = max( $expire, $touched );
1773 $cache = new CacheManager( $this->mTitle
);
1774 if($cache->isFileCacheGood( $touched )) {
1776 wfDebug( " tryFileCache() - about to load\n" );
1777 $cache->loadFromFileCache();
1780 wfDebug( " tryFileCache() - starting buffer\n" );
1781 ob_start( array(&$cache, 'saveToFileCache' ) );
1784 wfDebug( " tryFileCache() - not cacheable\n" );
1788 function isFileCacheable() {
1789 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1790 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1792 return $wgUseFileCache
1793 and (!$wgShowIPinHeader)
1794 and ($this->getID() != 0)
1795 and ($wgUser->getId() == 0)
1796 and (!$wgUser->getNewtalk())
1797 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1798 and (empty( $action ) ||
$action == 'view')
1799 and (!isset($oldid))
1801 and (!isset($redirect))
1802 and (!isset($printable))
1803 and (!$this->mRedirectedFrom
);
1806 # Loads cur_touched and returns a value indicating if it should be used
1807 function checkTouched() {
1808 $fname = 'Article::checkTouched';
1810 $id = $this->getID();
1811 $dbr =& wfGetDB( DB_SLAVE
);
1812 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1813 array( 'cur_id' => $id ), $fname );
1814 if( $s !== false ) {
1815 $this->mTouched
= $s->cur_touched
;
1816 return !$s->cur_is_redirect
;
1822 # Edit an article without doing all that other stuff
1823 function quickEdit( $text, $comment = '', $minor = 0 ) {
1824 global $wgUser, $wgMwRedir;
1825 $fname = 'Article::quickEdit';
1826 wfProfileIn( $fname );
1828 $dbw =& wfGetDB( DB_MASTER
);
1829 $ns = $this->mTitle
->getNamespace();
1830 $dbkey = $this->mTitle
->getDBkey();
1831 $encDbKey = $dbw->strencode( $dbkey );
1832 $timestamp = wfTimestampNow();
1835 $dbw->insertSelect( 'old', 'cur',
1837 'old_namespace' => 'cur_namespace',
1838 'old_title' => 'cur_title',
1839 'old_text' => 'cur_text',
1840 'old_comment' => 'cur_comment',
1841 'old_user' => 'cur_user',
1842 'old_user_text' => 'cur_user_text',
1843 'old_timestamp' => 'cur_timestamp',
1844 'inverse_timestamp' => '99999999999999-cur_timestamp',
1846 'cur_namespace' => $ns,
1847 'cur_title' => $dbkey,
1851 # Use the affected row count to determine if the article is new
1852 $numRows = $dbw->affectedRows();
1854 # Make an array of fields to be inserted
1856 'cur_text' => $text,
1857 'cur_timestamp' => $timestamp,
1858 'cur_user' => $wgUser->getID(),
1859 'cur_user_text' => $wgUser->getName(),
1860 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1861 'cur_comment' => $comment,
1862 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ?
1 : 0,
1863 'cur_minor_edit' => intval($minor),
1864 'cur_touched' => $timestamp,
1869 $fields['cur_is_new'] = 0;
1870 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1872 # Insert new article
1873 $fields['cur_is_new'] = 1;
1874 $fields['cur_namespace'] = $ns;
1875 $fields['cur_title'] = $dbkey;
1876 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1877 $dbw->insertArray( 'cur', $fields, $fname );
1879 wfProfileOut( $fname );
1882 /* static */ function incViewCount( $id )
1884 $id = intval( $id );
1885 global $wgHitcounterUpdateFreq;
1887 $dbw =& wfGetDB( DB_MASTER
);
1888 $curTable = $dbw->tableName( 'cur' );
1889 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1890 $acchitsTable = $dbw->tableName( 'acchits' );
1892 if( $wgHitcounterUpdateFreq <= 1 ){ //
1893 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
1897 # Not important enough to warrant an error page in case of failure
1898 $oldignore = $dbw->ignoreErrors( true );
1900 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
1902 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
1903 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
1904 # Most of the time (or on SQL errors), skip row count check
1905 $dbw->ignoreErrors( $oldignore );
1909 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
1910 $row = $dbw->fetchObject( $res );
1911 $rown = intval( $row->n
);
1912 if( $rown >= $wgHitcounterUpdateFreq ){
1913 wfProfileIn( 'Article::incViewCount-collect' );
1914 $old_user_abort = ignore_user_abort( true );
1916 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
1917 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
1918 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
1920 $dbw->query("DELETE FROM $hitcounterTable");
1921 $dbw->query('UNLOCK TABLES');
1922 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
1923 'WHERE cur_id = hc_id');
1924 $dbw->query("DROP TABLE $acchitsTable");
1926 ignore_user_abort( $old_user_abort );
1927 wfProfileOut( 'Article::incViewCount-collect' );
1929 $dbw->ignoreErrors( $oldignore );
1932 # The onArticle*() functions are supposed to be a kind of hooks
1933 # which should be called whenever any of the specified actions
1936 # This is a good place to put code to clear caches, for instance.
1938 # This is called on page move and undelete, as well as edit
1939 /* static */ function onArticleCreate($title_obj){
1940 global $wgUseSquid, $wgDeferredUpdateList;
1942 $titles = $title_obj->getBrokenLinksTo();
1945 if ( $wgUseSquid ) {
1946 $urls = $title_obj->getSquidURLs();
1947 foreach ( $titles as $linkTitle ) {
1948 $urls[] = $linkTitle->getInternalURL();
1950 $u = new SquidUpdate( $urls );
1951 array_push( $wgDeferredUpdateList, $u );
1954 # Clear persistent link cache
1955 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1958 /* static */ function onArticleDelete($title_obj){
1959 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
1962 /* static */ function onArticleEdit($title_obj){
1963 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
1966 # Info about this page
1970 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgAllowPageInfo;
1971 $fname = 'Article::info';
1973 if ( !$wgAllowPageInfo ) {
1974 $wgOut->errorpage( "nosuchaction", "nosuchactiontext" );
1978 $dbr =& wfGetDB( DB_SLAVE
);
1980 $basenamespace = $wgTitle->getNamespace() & (~
1);
1981 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
1982 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
1983 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
1984 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
1985 $wgOut->setPagetitle( $fullTitle );
1986 $wgOut->setSubtitle( wfMsg( "infosubtitle" ));
1988 # first, see if the page exists at all.
1989 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname );
1991 $wgOut->addHTML( wfMsg("noarticletext") );
1993 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname );
1994 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . "</li>" );
1995 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname );
1996 $wgOut->addHTML( "<li>" . wfMsg("numedits", $old +
1) . "</li>");
1998 # to find number of distinct authors, we need to do some
1999 # funny stuff because of the cur/old table split:
2000 # - first, find the name of the 'cur' author
2001 # - then, find the number of *other* authors in 'old'
2004 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname );
2006 # find number of 'old' authors excluding 'cur' author
2007 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2008 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname ) +
1;
2010 # now for the Talk page ...
2011 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2012 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2015 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname );
2019 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname );
2020 $wgOut->addHTML( "<li>" . wfMsg("numtalkedits", $old +
1) . "</li>");
2022 $wgOut->addHTML( "<li>" . wfMsg("numauthors", $authors) . "</li>" );
2026 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname );
2027 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2028 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname );
2030 $wgOut->addHTML( "<li>" . wfMsg("numtalkauthors", $authors) . "</li></ul>" );