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' );
13 /* private */ var $mContent, $mContentLoaded;
14 /* private */ var $mUser, $mTimestamp, $mUserText;
15 /* private */ var $mCounter, $mComment, $mCountAdjustment;
16 /* private */ var $mMinorEdit, $mRedirectedFrom;
17 /* private */ var $mTouched, $mFileCache, $mTitle;
18 /* private */ var $mId, $mTable;
20 function Article( &$title ) {
21 $this->mTitle
=& $title;
25 /* private */ function clear()
27 $this->mContentLoaded
= false;
28 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
29 $this->mRedirectedFrom
= $this->mUserText
=
30 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
31 $this->mCountAdjustment
= 0;
32 $this->mTouched
= '19700101000000';
35 # Get revision text associated with an old or archive row
36 # $row is usually an object from wfFetchRow(), both the flags and the text field must be included
37 /* static */ function getRevisionText( $row, $prefix = 'old_' ) {
39 $textField = $prefix . 'text';
40 $flagsField = $prefix . 'flags';
42 if ( isset( $row->$flagsField ) ) {
43 $flags = explode( ",", $row->$flagsField );
48 if ( isset( $row->$textField ) ) {
49 $text = $row->$textField;
54 if ( in_array( 'link', $flags ) ) {
56 $text = Article
::followLink( $text );
57 } elseif ( in_array( 'gzip', $flags ) ) {
58 # Deal with optional compression of archived pages.
59 # This can be done periodically via maintenance/compressOld.php, and
60 # as pages are saved if $wgCompressRevisions is set.
61 return gzinflate( $text );
66 /* static */ function compressRevisionText( &$text ) {
67 global $wgCompressRevisions;
68 if( !$wgCompressRevisions ) {
71 if( !function_exists( 'gzdeflate' ) ) {
72 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
75 $text = gzdeflate( $text );
79 # Returns the text associated with a "link" type old table row
80 /* static */ function followLink( $link ) {
81 # Split the link into fields and values
82 $lines = explode( '\n', $link );
85 foreach ( $lines as $line ) {
87 if ( $line{0} == '#' ) {
91 if ( preg_match( '/^(.*?)\s*:\s*(.*)$/', $line, $matches ) ) {
92 $field = strtolower($matches[1]);
94 if ( $field == 'hash' ) {
96 } elseif ( $field == 'location' ) {
97 $locations[] = $value;
102 if ( $hash === '' ) {
106 # Look in each specified location for the text
108 foreach ( $locations as $location ) {
109 $text = Article
::fetchFromLocation( $location, $hash );
110 if ( $text !== false ) {
118 /* static */ function fetchFromLocation( $location, $hash ) {
119 global $wgDatabase, $wgKnownDBServers;
120 $fname = 'fetchFromLocation';
121 wfProfileIn( $fname );
123 $p = strpos( $location, ':' );
124 if ( $p === false ) {
125 wfProfileOut( $fname );
129 $type = substr( $location, 0, $p );
133 # MySQL locations are specified by mysql://<machineID>/<dbname>/<tblname>/<index>
134 # Machine ID 0 is the current connection
135 if ( preg_match( '/^mysql:\/\/(\d+)\/([A-Za-z_]+)\/([A-Za-z_]+)\/([A-Za-z_]+)$/',
136 $location, $matches ) ) {
137 $machineID = $matches[1];
138 $dbName = $matches[2];
139 $tblName = $matches[3];
140 $index = $matches[4];
141 if ( $machineID == 0 ) {
145 # Alternate connection
146 $db =& $wgLoadBalancer->getConnection( $machineID );
148 if ( array_key_exists( $machineId, $wgKnownMysqlServers ) ) {
149 # Try to open, return false on failure
150 $params = $wgKnownDBServers[$machineId];
151 $db = Database
::newFromParams( $params['server'], $params['user'], $params['password'],
152 $dbName, 1, false, true, true );
155 if ( $db->isOpen() ) {
156 $index = wfStrencode( $index );
157 $res = $db->query( "SELECT blob_data FROM $dbName.$tblName WHERE blob_index='$index'", $fname );
158 $row = $db->fetchObject( $res );
159 $text = $row->text_data
;
164 # File locations are of the form file://<filename>, relative to the current directory
165 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
166 $filename = strstr( $location, 'file://' );
167 $text = @file_get_contents
( $matches[1] );
169 if ( $text !== false ) {
170 # Got text, now we need to interpret it
171 # The first line contains information about how to do this
172 $p = strpos( $text, '\n' );
173 $type = substr( $text, 0, $p );
174 $text = substr( $text, $p +
1 );
179 $text = gzinflate( $text );
182 $object = unserialize( $text );
183 $text = $object->getItem( $hash );
189 wfProfileOut( $fname );
193 # Note that getContent/loadContent may follow redirects if
194 # not told otherwise, and so may cause a change to mTitle.
196 # Return the text of this revision
197 function getContent( $noredir )
201 # Get variables from query string :P
202 $action = $wgRequest->getText( 'action', 'view' );
203 $section = $wgRequest->getText( 'section' );
205 $fname = 'Article::getContent';
206 wfProfileIn( $fname );
208 if ( 0 == $this->getID() ) {
209 if ( 'edit' == $action ) {
210 wfProfileOut( $fname );
211 return ''; # was "newarticletext", now moved above the box)
213 wfProfileOut( $fname );
214 return wfMsg( 'noarticletext' );
216 $this->loadContent( $noredir );
219 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
220 ( $this->mTitle
->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
221 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
225 wfProfileOut( $fname );
226 return $this->mContent
. "\n" .wfMsg('anontalkpagetext'); }
228 if($action=='edit') {
230 if($section=='new') {
231 wfProfileOut( $fname );
235 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
236 # comments to be stripped as well)
237 $rv=$this->getSection($this->mContent
,$section);
238 wfProfileOut( $fname );
242 wfProfileOut( $fname );
243 return $this->mContent
;
248 # This function returns the text of a section, specified by a number ($section).
249 # A section is text under a heading like == Heading == or <h1>Heading</h1>, or
250 # the first section before any such heading (section 0).
252 # If a section contains subsections, these are also returned.
254 function getSection($text,$section) {
256 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
257 # comments to be stripped as well)
259 $parser=new Parser();
260 $parser->mOutputType
=OT_WIKI
;
261 $striptext=$parser->strip($text, $striparray, true);
263 # now that we can be sure that no pseudo-sections are in the source,
264 # split it up by section
267 '/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
269 PREG_SPLIT_DELIM_CAPTURE
);
273 $headline=$secs[$section*2-1];
274 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
277 # translate wiki heading into level
278 if(strpos($hlevel,'=')!==false) {
279 $hlevel=strlen($hlevel);
282 $rv=$headline. $secs[$section*2];
286 while(!empty($secs[$count*2-1]) && !$break) {
288 $subheadline=$secs[$count*2-1];
289 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
290 $subhlevel=$matches[1];
291 if(strpos($subhlevel,'=')!==false) {
292 $subhlevel=strlen($subhlevel);
294 if($subhlevel > $hlevel) {
295 $rv.=$subheadline.$secs[$count*2];
297 if($subhlevel <= $hlevel) {
304 # reinsert stripped tags
305 $rv=$parser->unstrip($rv,$striparray);
306 $rv=$parser->unstripNoWiki($rv,$striparray);
313 # Load the revision (including cur_text) into this object
314 function loadContent( $noredir = false )
316 global $wgOut, $wgMwRedir, $wgRequest, $wgIsPg;
319 $oldid = $wgRequest->getVal( 'oldid' );
320 $redirect = $wgRequest->getVal( 'redirect' );
322 if ( $this->mContentLoaded
) return;
323 $fname = 'Article::loadContent';
325 # Pre-fill content with error message so that if something
326 # fails we'll have something telling us what we intended.
328 $t = $this->mTitle
->getPrefixedText();
329 if ( isset( $oldid ) ) {
330 $oldid = IntVal( $oldid );
331 $t .= ",oldid={$oldid}";
333 if ( isset( $redirect ) ) {
334 $redirect = ($redirect == 'no') ?
'no' : 'yes';
335 $t .= ",redirect={$redirect}";
337 $this->mContent
= wfMsg( 'missingarticle', $t );
339 if ( ! $oldid ) { # Retrieve current version
340 $id = $this->getID();
341 if ( 0 == $id ) return;
344 'cur_text,cur_timestamp,cur_user,cur_user_text,cur_comment,cur_counter,cur_restrictions,cur_touched ' .
345 "FROM cur WHERE cur_id={$id}";
347 $res = wfQuery( $sql, DB_READ
, $fname );
348 if ( 0 == wfNumRows( $res ) ) {
352 $s = wfFetchObject( $res );
353 # If we got a redirect, follow it (unless we've been told
354 # not to by either the function parameter or the query
355 if ( ( 'no' != $redirect ) && ( false == $noredir ) &&
356 ( $wgMwRedir->matchStart( $s->cur_text
) ) ) {
357 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/',
358 $s->cur_text
, $m ) ) {
359 $rt = Title
::newFromText( $m[1] );
361 # Gotta hand redirects to special pages differently:
362 # Fill the HTTP response "Location" header and ignore
363 # the rest of the page we're on.
365 if ( $rt->getInterwiki() != '' ) {
366 $wgOut->redirect( $rt->getFullURL() ) ;
369 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
370 $wgOut->redirect( $rt->getFullURL() );
373 $rid = $rt->getArticleID();
375 $sql = 'SELECT cur_text,cur_timestamp,cur_user,cur_user_text,cur_comment,' .
376 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
377 $res = wfQuery( $sql, DB_READ
, $fname );
379 if ( 0 != wfNumRows( $res ) ) {
380 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
382 $s = wfFetchObject( $res );
389 $this->mContent
= $s->cur_text
;
390 $this->mUser
= $s->cur_user
;
391 $this->mUserText
= $s->cur_user_text
;
392 $this->mComment
= $s->cur_comment
;
393 $this->mCounter
= $s->cur_counter
;
394 $this->mTimestamp
= $s->cur_timestamp
;
395 $this->mTouched
= $s->cur_touched
;
396 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
397 $this->mTitle
->mRestrictionsLoaded
= true;
398 wfFreeResult( $res );
399 } else { # oldid set, retrieve historical version
400 $oldtable=$wgIsPg?
'"old"':'old';
401 $sql = "SELECT old_namespace,old_title,old_text,old_timestamp,".
402 "old_user,old_user_text,old_comment,old_flags FROM old ".
403 "WHERE old_id={$oldid}";
404 $res = wfQuery( $sql, DB_READ
, $fname );
405 if ( 0 == wfNumRows( $res ) ) {
409 $s = wfFetchObject( $res );
410 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
411 $this->mTitle
->getDBkey() != $s->old_title
) {
412 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
413 $this->mTitle
= $oldTitle;
414 $wgTitle = $oldTitle;
416 $this->mContent
= Article
::getRevisionText( $s );
417 $this->mUser
= $s->old_user
;
418 $this->mUserText
= $s->old_user_text
;
419 $this->mComment
= $s->old_comment
;
421 $this->mTimestamp
= $s->old_timestamp
;
422 wfFreeResult( $res );
424 $this->mContentLoaded
= true;
425 return $this->mContent
;
428 # Gets the article text without using so many damn globals
429 # Returns false on error
430 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
431 global $wgMwRedir, $wgIsPg;
433 if ( $this->mContentLoaded
) {
434 return $this->mContent
;
436 $this->mContent
= false;
438 $fname = 'Article::loadContent';
440 if ( ! $oldid ) { # Retrieve current version
441 $id = $this->getID();
447 'cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched ' .
448 "FROM cur WHERE cur_id={$id}";
449 $res = wfQuery( $sql, DB_READ
, $fname );
450 if ( 0 == wfNumRows( $res ) ) {
454 $s = wfFetchObject( $res );
455 # If we got a redirect, follow it (unless we've been told
456 # not to by either the function parameter or the query
457 if ( !$noredir && $wgMwRedir->matchStart( $s->cur_text
) ) {
458 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/',
459 $s->cur_text
, $m ) ) {
460 $rt = Title
::newFromText( $m[1] );
461 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != Namespace::getSpecial() ) {
462 $rid = $rt->getArticleID();
464 $sql = 'SELECT cur_text,cur_timestamp,cur_user,' .
465 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
466 $res = wfQuery( $sql, DB_READ
, $fname );
468 if ( 0 != wfNumRows( $res ) ) {
469 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
471 $s = wfFetchObject( $res );
478 $this->mContent
= $s->cur_text
;
479 $this->mUser
= $s->cur_user
;
480 $this->mCounter
= $s->cur_counter
;
481 $this->mTimestamp
= $s->cur_timestamp
;
482 $this->mTouched
= $s->cur_touched
;
483 $this->mTitle
->mRestrictions
= explode( ",", trim( $s->cur_restrictions
) );
484 $this->mTitle
->mRestrictionsLoaded
= true;
485 wfFreeResult( $res );
486 } else { # oldid set, retrieve historical version
487 $oldtable=$wgIsPg?
'"old"':'old';
488 $sql = "SELECT old_text,old_timestamp,old_user,old_flags FROM $oldtable " .
489 "WHERE old_id={$oldid}";
490 $res = wfQuery( $sql, DB_READ
, $fname );
491 if ( 0 == wfNumRows( $res ) ) {
495 $s = wfFetchObject( $res );
496 $this->mContent
= Article
::getRevisionText( $s );
497 $this->mUser
= $s->old_user
;
499 $this->mTimestamp
= $s->old_timestamp
;
500 wfFreeResult( $res );
502 $this->mContentLoaded
= true;
503 return $this->mContent
;
507 if( $this->mTitle
) {
508 return $this->mTitle
->getArticleID();
516 if ( -1 == $this->mCounter
) {
517 $id = $this->getID();
518 $this->mCounter
= wfGetSQL( 'cur', 'cur_counter', "cur_id={$id}" );
520 return $this->mCounter
;
523 # Would the given text make this article a "good" article (i.e.,
524 # suitable for including in the article count)?
526 function isCountable( $text )
528 global $wgUseCommaCount, $wgMwRedir;
530 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
531 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
532 $token = ($wgUseCommaCount ?
',' : '[[' );
533 if ( false === strstr( $text, $token ) ) { return 0; }
537 # Loads everything from cur except cur_text
538 # This isn't necessary for all uses, so it's only done if needed.
540 /* private */ function loadLastEdit()
543 if ( -1 != $this->mUser
) return;
545 $sql = 'SELECT cur_user,cur_user_text,cur_timestamp,' .
546 'cur_comment,cur_minor_edit FROM cur WHERE ' .
547 'cur_id=' . $this->getID();
548 $res = wfQuery( $sql, DB_READ
, 'Article::loadLastEdit' );
550 if ( wfNumRows( $res ) > 0 ) {
551 $s = wfFetchObject( $res );
552 $this->mUser
= $s->cur_user
;
553 $this->mUserText
= $s->cur_user_text
;
554 $this->mTimestamp
= $s->cur_timestamp
;
555 $this->mComment
= $s->cur_comment
;
556 $this->mMinorEdit
= $s->cur_minor_edit
;
560 function getTimestamp()
562 $this->loadLastEdit();
563 return $this->mTimestamp
;
568 $this->loadLastEdit();
572 function getUserText()
574 $this->loadLastEdit();
575 return $this->mUserText
;
578 function getComment()
580 $this->loadLastEdit();
581 return $this->mComment
;
584 function getMinorEdit()
586 $this->loadLastEdit();
587 return $this->mMinorEdit
;
590 function getContributors($limit = 0, $offset = 0)
592 $fname = 'Article::getContributors';
594 # XXX: this is expensive; cache this info somewhere.
596 $title = $this->mTitle
;
600 $sql = 'SELECT old.old_user, old.old_user_text, ' .
601 ' user.user_real_name, MAX(old.old_timestamp) as timestamp' .
603 ' WHERE old.old_user = user.user_id ' .
604 ' AND old.old_namespace = ' . $title->getNamespace() .
605 ' AND old.old_title = "' . $title->getDBkey() . '"' .
606 ' AND old.old_user != 0 ' .
607 ' AND old.old_user != ' . $this->getUser() .
608 ' GROUP BY old.old_user ' .
609 ' ORDER BY timestamp DESC ';
612 $sql .= ' LIMIT '.$limit;
615 $res = wfQuery($sql, DB_READ
, $fname);
617 while ( $line = wfFetchObject( $res ) ) {
618 $contribs[$line->old_user
] =
619 array($line->old_user_text
, $line->user_real_name
);
622 # Count anonymous users
624 $res = wfQuery('SELECT COUNT(*) AS cnt ' .
626 ' WHERE old_namespace = ' . $title->getNamespace() .
627 " AND old_title = '" . $title->getDBkey() . "'" .
628 ' AND old_user = 0 ', DB_READ
, $fname);
630 while ( $line = wfFetchObject( $res ) ) {
631 $contribs[0] = array($line->cnt
, 'Anonymous');
637 # This is the default action of the script: just view the page of
642 global $wgUser, $wgOut, $wgLang, $wgRequest;
643 global $wgLinkCache, $IP, $wgEnableParserCache;
645 $fname = 'Article::view';
646 wfProfileIn( $fname );
648 # Get variables from query string :P
649 $oldid = $wgRequest->getVal( 'oldid' );
650 $diff = $wgRequest->getVal( 'diff' );
652 $wgOut->setArticleFlag( true );
653 $wgOut->setRobotpolicy( 'index,follow' );
655 # If we got diff and oldid in the query, we want to see a
656 # diff page instead of the article.
658 if ( !is_null( $diff ) ) {
659 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
660 $de = new DifferenceEngine( intval($oldid), intval($diff) );
662 wfProfileOut( $fname );
666 if ( !is_null( $oldid ) and $this->checkTouched() ) {
667 if( $wgOut->checkLastModified( $this->mTouched
) ){
669 } else if ( $this->tryFileCache() ) {
670 # tell wgOut that output is taken care of
672 $this->viewUpdates();
677 # Should the parser cache be used?
678 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
686 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
691 if ( !$outputDone ) {
692 $text = $this->getContent( false ); # May change mTitle by following a redirect
694 # Another whitelist check in case oldid or redirects are altering the title
695 if ( !$this->mTitle
->userCanRead() ) {
696 $wgOut->loginToUse();
702 # We're looking at an old revision
704 if ( !empty( $oldid ) ) {
705 $this->setOldSubtitle();
706 $wgOut->setRobotpolicy( 'noindex,follow' );
708 if ( '' != $this->mRedirectedFrom
) {
709 $sk = $wgUser->getSkin();
710 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
712 $s = wfMsg( 'redirectedfrom', $redir );
713 $wgOut->setSubtitle( $s );
715 # Can't cache redirects
719 $wgLinkCache->preFill( $this->mTitle
);
721 # wrap user css and user js in pre and don't parse
722 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
724 $this->mTitle
->getNamespace() == Namespace::getUser() &&
725 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
727 $wgOut->addWikiText( wfMsg('clearyourcache'));
728 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
729 } else if ( $pcache ) {
730 $wgOut->addWikiText( $text, true, $this );
732 $wgOut->addWikiText( $text );
735 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
737 # Add link titles as META keywords
738 $wgOut->addMetaTags() ;
740 $this->viewUpdates();
741 wfProfileOut( $fname );
744 # Theoretically we could defer these whole insert and update
745 # functions for after display, but that's taking a big leap
746 # of faith, and we want to be able to report database
747 # errors at some point.
749 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
751 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
752 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgIsPg, $wgIsMySQL;
754 $fname = 'Article::insertNewArticle';
756 $this->mCountAdjustment
= $this->isCountable( $text );
758 $ns = $this->mTitle
->getNamespace();
759 $ttl = $this->mTitle
->getDBkey();
760 $text = $this->preSaveTransform( $text );
761 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
764 $now = wfTimestampNow();
765 $won = wfInvertTimestamp( $now );
767 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
770 $cur_id_column="cur_id,";
771 $cur_id=wfGetSQL(""," nextval('cur_cur_id_seq')");
772 $cur_id_value="{$cur_id},";
779 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
780 $sql = "INSERT INTO cur ({$cur_id_column}cur_namespace,cur_title,cur_text," .
781 'cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter,' .
782 'cur_restrictions,cur_user_text,cur_is_redirect,' .
783 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$cur_id_value}{$ns},'" . wfStrencode( $ttl ) . "', '" .
784 wfStrencode( $text ) . "', '" .
785 wfStrencode( $summary ) . "', '" .
786 $wgUser->getID() . "', '{$now}', " .
787 $isminor . ", 0, '', '" .
788 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
789 $res = wfQuery( $sql, DB_WRITE
, $fname );
791 $newid = $wgIsPg?
$cur_id:wfInsertId();
792 $this->mTitle
->resetArticleID( $newid );
794 Article
::onArticleCreate( $this->mTitle
);
795 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
798 if(!$this->mTitle
->userIsWatching()) $this->watch();
800 if ( $this->mTitle
->userIsWatching() ) {
805 # The talk page isn't in the regular link tables, so we need to update manually:
806 $talkns = $ns ^
1; # talk -> normal; normal -> talk
807 $sql = "UPDATE cur set cur_touched='$now' WHERE cur_namespace=$talkns AND cur_title='" . wfStrencode( $ttl ) . "'";
808 wfQuery( $sql, DB_WRITE
);
810 # standard deferred updates
811 $this->editUpdates( $text );
813 $this->showArticle( $text, wfMsg( 'newarticle' ) );
817 /* Side effects: loads last edit */
818 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ''){
819 $this->loadLastEdit();
820 $oldtext = $this->getContent( true );
821 if ($section != '') {
822 if($section=='new') {
823 if($summary) $subject="== {$summary} ==\n\n";
824 $text=$oldtext."\n\n".$subject.$text;
827 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
828 # comments to be stripped as well)
830 $parser=new Parser();
831 $parser->mOutputType
=OT_WIKI
;
832 $oldtext=$parser->strip($oldtext, $striparray, true);
834 # now that we can be sure that no pseudo-sections are in the source,
836 # Unfortunately we can't simply do a preg_replace because that might
837 # replace the wrong section, so we have to use the section counter instead
838 $secs=preg_split('/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
839 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
840 $secs[$section*2]=$text."\n\n"; // replace with edited
842 # section 0 is top (intro) section
845 # headline of old section - we need to go through this section
846 # to determine if there are any subsections that now need to
847 # be erased, as the mother section has been replaced with
848 # the text of all subsections.
849 $headline=$secs[$section*2-1];
850 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
853 # determine headline level for wikimarkup headings
854 if(strpos($hlevel,'=')!==false) {
855 $hlevel=strlen($hlevel);
858 $secs[$section*2-1]=''; // erase old headline
861 while(!empty($secs[$count*2-1]) && !$break) {
863 $subheadline=$secs[$count*2-1];
865 '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
866 $subhlevel=$matches[1];
867 if(strpos($subhlevel,'=')!==false) {
868 $subhlevel=strlen($subhlevel);
870 if($subhlevel > $hlevel) {
871 // erase old subsections
872 $secs[$count*2-1]='';
875 if($subhlevel <= $hlevel) {
883 $text=join('',$secs);
884 # reinsert the stuff that we stripped out earlier
885 $text=$parser->unstrip($text,$striparray);
886 $text=$parser->unstripNoWiki($text,$striparray);
893 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' )
895 global $wgOut, $wgUser, $wgLinkCache;
896 global $wgDBtransactions, $wgMwRedir;
897 global $wgUseSquid, $wgInternalServer;
899 $fname = 'Article::updateArticle';
901 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
902 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
903 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
905 $text = $m[1] . "\n"; # Remove all content but redirect
909 $text = $this->preSaveTransform( $text );
911 # Update article, but only if changed.
913 if( $wgDBtransactions ) {
915 wfQuery( $sql, DB_WRITE
);
917 $oldtext = $this->getContent( true );
919 if ( 0 != strcmp( $text, $oldtext ) ) {
920 $this->mCountAdjustment
= $this->isCountable( $text )
921 - $this->isCountable( $oldtext );
923 $now = wfTimestampNow();
924 $won = wfInvertTimestamp( $now );
925 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
926 "',cur_comment='" . wfStrencode( $summary ) .
927 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
928 ",cur_timestamp='{$now}',cur_user_text='" .
929 wfStrencode( $wgUser->getName() ) .
930 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
931 "WHERE cur_id=" . $this->getID() .
932 " AND cur_timestamp='" . $this->getTimestamp() . "'";
933 $res = wfQuery( $sql, DB_WRITE
, $fname );
935 if( wfAffectedRows() == 0 ) {
936 /* Belated edit conflict! Run away!! */
940 # This overwrites $oldtext if revision compression is on
941 $flags = Article
::compressRevisionText( $oldtext );
943 $oldtable=$wgIsPg?
'"old"':'old';
946 $old_id_column='old_id,';
947 $old_id=wfGetSQL(""," nextval('old_old_id_seq')");
948 $old_id_value=$old_id.',';
955 $sql = "INSERT INTO $oldtable ({$old_id_column}old_namespace,old_title,old_text," .
956 'old_comment,old_user,old_user_text,old_timestamp,' .
957 'old_minor_edit,inverse_timestamp,old_flags) VALUES (' .
959 $this->mTitle
->getNamespace() . ", '" .
960 wfStrencode( $this->mTitle
->getDBkey() ) . "', '" .
961 wfStrencode( $oldtext ) . "', '" .
962 wfStrencode( $this->getComment() ) . "', " .
963 $this->getUser() . ", '" .
964 wfStrencode( $this->getUserText() ) . "', '" .
965 $this->getTimestamp() . "', " . $me1 . ", '" .
966 wfInvertTimestamp( $this->getTimestamp() ) . "','$flags')";
967 $res = wfQuery( $sql, DB_WRITE
, $fname );
969 $oldid = $wgIsPg?
$old_id:wfInsertId( $res );
971 $bot = (int)($wgUser->isBot() ||
$forceBot);
972 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
973 $oldid, $this->getTimestamp(), $bot );
974 Article
::onArticleEdit( $this->mTitle
);
977 if( $wgDBtransactions ) {
979 wfQuery( $sql, DB_WRITE
);
983 if (!$this->mTitle
->userIsWatching()) $this->watch();
985 if ( $this->mTitle
->userIsWatching() ) {
989 # standard deferred updates
990 $this->editUpdates( $text );
995 # Purge all articles linking here
996 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
997 $titles = $this->mTitle
->getLinksTo();
998 Title
::touchArray( $titles );
1000 foreach ( $titles as $title ) {
1001 $urls[] = $title->getInternalURL();
1007 if ( $wgUseSquid ) {
1008 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1009 $u = new SquidUpdate( $urls );
1013 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1017 # After we've either updated or inserted the article, update
1018 # the link tables and redirect to the new page.
1020 function showArticle( $text, $subtitle , $sectionanchor = '' )
1022 global $wgOut, $wgUser, $wgLinkCache;
1025 $wgLinkCache = new LinkCache();
1027 # Get old version of link table to allow incremental link updates
1028 $wgLinkCache->preFill( $this->mTitle
);
1029 $wgLinkCache->clear();
1031 # Now update the link cache by parsing the text
1032 $wgOut = new OutputPage();
1033 $wgOut->addWikiText( $text );
1035 if( $wgMwRedir->matchStart( $text ) )
1039 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1042 # Add this page to my watchlist
1044 function watch( $add = true )
1046 global $wgUser, $wgOut, $wgLang;
1047 global $wgDeferredUpdateList;
1049 if ( 0 == $wgUser->getID() ) {
1050 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1053 if ( wfReadOnly() ) {
1054 $wgOut->readOnlyPage();
1058 $wgUser->addWatch( $this->mTitle
);
1060 $wgUser->removeWatch( $this->mTitle
);
1062 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1063 $wgOut->setRobotpolicy( 'noindex,follow' );
1065 $sk = $wgUser->getSkin() ;
1066 $link = $this->mTitle
->getPrefixedText();
1069 $text = wfMsg( 'addedwatchtext', $link );
1071 $text = wfMsg( 'removedwatchtext', $link );
1072 $wgOut->addWikiText( $text );
1074 $up = new UserUpdate();
1075 array_push( $wgDeferredUpdateList, $up );
1077 $wgOut->returnToMain( false );
1082 $this->watch( false );
1085 function protect( $limit = 'sysop' )
1087 global $wgUser, $wgOut, $wgRequest;
1089 if ( ! $wgUser->isSysop() ) {
1090 $wgOut->sysopRequired();
1093 if ( wfReadOnly() ) {
1094 $wgOut->readOnlyPage();
1097 $id = $this->mTitle
->getArticleID();
1099 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1103 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1104 $reason = $wgRequest->getText( 'wpReasonProtect' );
1108 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
1109 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
1110 wfQuery( $sql, DB_WRITE
, 'Article::protect' );
1112 $log = new LogPage( wfMsg( 'protectlogpage' ), wfMsg( 'protectlogtext' ) );
1113 if ( $limit === "" ) {
1114 $log->addEntry( wfMsg( 'unprotectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1116 $log->addEntry( wfMsg( 'protectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1118 $wgOut->redirect( $this->mTitle
->getFullURL() );
1121 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1122 return $this->confirmProtect( '', $reason, $limit );
1126 # Output protection confirmation dialog
1127 function confirmProtect( $par, $reason, $limit = 'sysop' )
1131 wfDebug( "Article::confirmProtect\n" );
1133 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1134 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1139 if ( $limit === '' ) {
1140 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1141 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1142 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1143 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1144 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1146 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1147 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1148 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1149 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1150 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1153 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1156 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1160 <label for='wpReasonProtect'>{$protcom}:</label>
1163 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1171 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1174 <label for='wpConfirmProtect'>{$check}</label>
1180 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1186 $wgOut->returnToMain( false );
1189 function unprotect()
1191 return $this->protect( '' );
1194 # UI entry point for page deletion
1197 global $wgUser, $wgOut, $wgMessageCache, $wgRequest, $wgIsPg;
1198 $fname = 'Article::delete';
1199 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1200 $reason = $wgRequest->getText( 'wpReason' );
1202 # This code desperately needs to be totally rewritten
1205 if ( ( ! $wgUser->isSysop() ) ) {
1206 $wgOut->sysopRequired();
1209 if ( wfReadOnly() ) {
1210 $wgOut->readOnlyPage();
1214 # Better double-check that it hasn't been deleted yet!
1215 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1216 if ( ( '' == trim( $this->mTitle
->getText() ) )
1217 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1218 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1223 $this->doDelete( $reason );
1227 # determine whether this page has earlier revisions
1228 # and insert a warning if it does
1229 # we select the text because it might be useful below
1230 $ns = $this->mTitle
->getNamespace();
1231 $title = $this->mTitle
->getDBkey();
1232 $etitle = wfStrencode( $title );
1233 $oldtable=$wgIsPg?
'"old"':'old';
1234 $sql = "SELECT old_text,old_flags FROM $oldtable WHERE old_namespace=$ns and old_title='$etitle' ORDER BY inverse_timestamp LIMIT 1";
1235 $res = wfQuery( $sql, DB_READ
, $fname );
1236 if( ($old=wfFetchObject($res)) && !$confirm ) {
1237 $skin=$wgUser->getSkin();
1238 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1239 $wgOut->addHTML( $skin->historyLink() .'</b>');
1242 $sql="SELECT cur_text FROM cur WHERE cur_namespace=$ns and cur_title='$etitle'";
1243 $res=wfQuery($sql, DB_READ
, $fname);
1244 if( ($s=wfFetchObject($res))) {
1246 # if this is a mini-text, we can paste part of it into the deletion reason
1248 #if this is empty, an earlier revision may contain "useful" text
1250 if($s->cur_text
!="") {
1254 $text = Article
::getRevisionText( $old );
1260 $length=strlen($text);
1262 # this should not happen, since it is not possible to store an empty, new
1263 # page. Let's insert a standard text in case it does, though
1264 if($length == 0 && $reason === '') {
1265 $reason = wfMsg('exblank');
1268 if($length < 500 && $reason === '') {
1270 # comment field=255, let's grep the first 150 to have some user
1272 $text=substr($text,0,150);
1273 # let's strip out newlines and HTML tags
1274 $text=preg_replace('/\"/',"'",$text);
1275 $text=preg_replace('/\</','<',$text);
1276 $text=preg_replace('/\>/','>',$text);
1277 $text=preg_replace("/[\n\r]/",'',$text);
1279 $reason=wfMsg('excontent'). " '".$text;
1281 $reason=wfMsg('exbeforeblank') . " '".$text;
1283 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1288 return $this->confirmDelete( '', $reason );
1291 # Output deletion confirmation dialog
1292 function confirmDelete( $par, $reason )
1296 wfDebug( "Article::confirmDelete\n" );
1298 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1299 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1300 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1301 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1303 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1305 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1306 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1307 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1310 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1314 <label for='wpReason'>{$delcom}:</label>
1317 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1325 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1328 <label for='wpConfirm'>{$check}</label>
1334 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1340 $wgOut->returnToMain( false );
1343 # Perform a deletion and output success or failure messages
1344 function doDelete( $reason )
1346 global $wgOut, $wgUser, $wgLang;
1347 $fname = 'Article::doDelete';
1348 wfDebug( "$fname\n" );
1350 if ( $this->doDeleteArticle( $reason ) ) {
1351 $deleted = $this->mTitle
->getPrefixedText();
1353 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1354 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1356 $sk = $wgUser->getSkin();
1357 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1358 Namespace::getWikipedia() ) .
1359 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1361 $text = wfMsg( "deletedtext", $deleted, $loglink );
1363 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1364 $wgOut->returnToMain( false );
1366 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1370 # Back-end article deletion
1371 # Deletes the article with database consistency, writes logs, purges caches
1373 function doDeleteArticle( $reason )
1375 global $wgUser, $wgLang;
1376 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1378 $fname = 'Article::doDeleteArticle';
1379 wfDebug( $fname."\n" );
1381 $ns = $this->mTitle
->getNamespace();
1382 $t = wfStrencode( $this->mTitle
->getDBkey() );
1383 $id = $this->mTitle
->getArticleID();
1385 if ( '' == $t ||
$id == 0 ) {
1389 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1390 array_push( $wgDeferredUpdateList, $u );
1392 $linksTo = $this->mTitle
->getLinksTo();
1395 if ( $wgUseSquid ) {
1397 $this->mTitle
->getInternalURL(),
1398 $this->mTitle
->getInternalURL( 'history' )
1400 foreach ( $linksTo as $linkTo ) {
1401 $urls[] = $linkTo->getInternalURL();
1404 $u = new SquidUpdate( $urls );
1405 array_push( $wgDeferredUpdateList, $u );
1409 # Client and file cache invalidation
1410 Title
::touchArray( $linksTo );
1412 # Move article and history to the "archive" table
1413 $sql = 'INSERT INTO archive (ar_namespace,ar_title,ar_text,' .
1414 'ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit,' .
1415 'ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment,' .
1416 'cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur ' .
1417 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1418 wfQuery( $sql, DB_WRITE
, $fname );
1420 $sql = 'INSERT INTO archive (ar_namespace,ar_title,ar_text,' .
1421 'ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit,' .
1422 'ar_flags) SELECT old_namespace,old_title,old_text,old_comment,' .
1423 'old_user,old_user_text,old_timestamp,old_minor_edit,old_flags ' .
1424 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1425 wfQuery( $sql, DB_WRITE
, $fname );
1427 # Now that it's safely backed up, delete it
1429 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1431 wfQuery( $sql, DB_WRITE
, $fname );
1433 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1435 wfQuery( $sql, DB_WRITE
, $fname );
1437 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1439 wfQuery( $sql, DB_WRITE
, $fname );
1441 # Finally, clean up the link tables
1442 $t = wfStrencode( $this->mTitle
->getPrefixedDBkey() );
1444 Article
::onArticleDelete( $this->mTitle
);
1446 $sql = 'INSERT INTO brokenlinks (bl_from,bl_to) VALUES ';
1449 foreach ( $linksTo as $titleObj ) {
1450 if ( ! $first ) { $sql .= ','; }
1452 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1453 $linkID = $titleObj->getArticleID();
1454 $sql .= "({$linkID},'{$t}')";
1457 wfQuery( $sql, DB_WRITE
, $fname );
1460 $sql = "DELETE FROM links WHERE l_to={$id}";
1461 wfQuery( $sql, DB_WRITE
, $fname );
1463 $sql = "DELETE FROM links WHERE l_from={$id}";
1464 wfQuery( $sql, DB_WRITE
, $fname );
1466 $sql = "DELETE FROM imagelinks WHERE il_from={$id}";
1467 wfQuery( $sql, DB_WRITE
, $fname );
1469 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1470 wfQuery( $sql, DB_WRITE
, $fname );
1472 $sql = "DELETE FROM categorylinks WHERE cl_from={$id}";
1473 wfQuery( $sql, DB_WRITE
, $fname );
1475 $log = new LogPage( wfMsg( 'dellogpage' ), wfMsg( 'dellogpagetext' ) );
1476 $art = $this->mTitle
->getPrefixedText();
1477 $log->addEntry( wfMsg( 'deletedarticle', $art ), $reason );
1479 # Clear the cached article id so the interface doesn't act like we exist
1480 $this->mTitle
->resetArticleID( 0 );
1481 $this->mTitle
->mArticleID
= 0;
1487 global $wgUser, $wgLang, $wgOut, $wgRequest, $wgIsMySQL, $wgIsPg;
1489 if ( ! $wgUser->isSysop() ) {
1490 $wgOut->sysopRequired();
1493 if ( wfReadOnly() ) {
1494 $wgOut->readOnlyPage( $this->getContent( true ) );
1498 # Enhanced rollback, marks edits rc_bot=1
1499 $bot = $wgRequest->getBool( 'bot' );
1501 # Replace all this user's current edits with the next one down
1502 $tt = wfStrencode( $this->mTitle
->getDBKey() );
1503 $n = $this->mTitle
->getNamespace();
1505 # Get the last editor
1506 $sql = 'SELECT cur_id,cur_user,cur_user_text,cur_comment ' .
1507 "FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1508 $res = wfQuery( $sql, DB_READ
);
1509 if( ($x = wfNumRows( $res )) != 1 ) {
1511 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1514 $s = wfFetchObject( $res );
1515 $ut = wfStrencode( $s->cur_user_text
);
1516 $uid = $s->cur_user
;
1519 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1520 if( $from != $s->cur_user_text
) {
1521 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1522 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1523 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1524 htmlspecialchars( $from ),
1525 htmlspecialchars( $s->cur_user_text
) ) );
1526 if($s->cur_comment
!= '') {
1528 wfMsg('editcomment',
1529 htmlspecialchars( $s->cur_comment
) ) );
1534 # Get the last edit not by this guy
1536 $use_index=$wgIsMySQL?
"USE INDEX (name_title_timestamp)":"";
1537 $oldtable=$wgIsPg?
'"old"':'old';
1538 $sql = 'SELECT old_text,old_user,old_user_text,old_timestamp,old_flags ' .
1539 "FROM $oldtable {$use_index}" .
1540 "WHERE old_namespace={$n} AND old_title='{$tt}'" .
1541 "AND (old_user <> {$uid} OR old_user_text <> '{$ut}')" .
1542 'ORDER BY inverse_timestamp LIMIT 1';
1543 $res = wfQuery( $sql, DB_READ
);
1544 if( wfNumRows( $res ) != 1 ) {
1546 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1547 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1550 $s = wfFetchObject( $res );
1553 # Mark all reverted edits as bot
1554 $sql = 'UPDATE recentchanges SET rc_bot=1 WHERE' .
1555 "rc_cur_id=$pid AND rc_user=$uid AND rc_timestamp > '{$s->old_timestamp}'";
1556 wfQuery( $sql, DB_WRITE
, $fname );
1560 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1561 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1562 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1563 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1564 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1565 Article
::onArticleEdit( $this->mTitle
);
1566 $wgOut->returnToMain( false );
1570 # Do standard deferred updates after page view
1572 /* private */ function viewUpdates()
1574 global $wgDeferredUpdateList;
1575 if ( 0 != $this->getID() ) {
1576 global $wgDisableCounters;
1577 if( !$wgDisableCounters ) {
1578 Article
::incViewCount( $this->getID() );
1579 $u = new SiteStatsUpdate( 1, 0, 0 );
1580 array_push( $wgDeferredUpdateList, $u );
1582 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1583 $this->mTitle
->getDBkey() );
1584 array_push( $wgDeferredUpdateList, $u );
1588 # Do standard deferred updates after page edit.
1589 # Every 1000th edit, prune the recent changes table.
1591 /* private */ function editUpdates( $text )
1593 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1594 global $wgMessageCache;
1597 if ( 0 == mt_rand( 0, 999 ) ) {
1598 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1599 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1600 wfQuery( $sql, DB_WRITE
);
1602 $id = $this->getID();
1603 $title = $this->mTitle
->getPrefixedDBkey();
1604 $shortTitle = $this->mTitle
->getDBkey();
1606 $adj = $this->mCountAdjustment
;
1609 $u = new LinksUpdate( $id, $title );
1610 array_push( $wgDeferredUpdateList, $u );
1611 $u = new SiteStatsUpdate( 0, 1, $adj );
1612 array_push( $wgDeferredUpdateList, $u );
1613 $u = new SearchUpdate( $id, $title, $text );
1614 array_push( $wgDeferredUpdateList, $u );
1616 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1617 array_push( $wgDeferredUpdateList, $u );
1619 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1620 $wgMessageCache->replace( $shortTitle, $text );
1625 /* private */ function setOldSubtitle()
1627 global $wgLang, $wgOut;
1629 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1630 $r = wfMsg( 'revisionasof', $td );
1631 $wgOut->setSubtitle( "({$r})" );
1634 # This function is called right before saving the wikitext,
1635 # so we can do things like signatures and links-in-context.
1637 function preSaveTransform( $text )
1639 global $wgParser, $wgUser;
1640 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1643 /* Caching functions */
1645 # checkLastModified returns true if it has taken care of all
1646 # output to the client that is necessary for this request.
1647 # (that is, it has sent a cached version of the page)
1648 function tryFileCache() {
1649 static $called = false;
1651 wfDebug( " tryFileCache() -- called twice!?\n" );
1655 if($this->isFileCacheable()) {
1656 $touched = $this->mTouched
;
1657 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1658 # Expire the main page quicker
1659 $expire = wfUnix2Timestamp( time() - 3600 );
1660 $touched = max( $expire, $touched );
1662 $cache = new CacheManager( $this->mTitle
);
1663 if($cache->isFileCacheGood( $touched )) {
1665 wfDebug( " tryFileCache() - about to load\n" );
1666 $cache->loadFromFileCache();
1669 wfDebug( " tryFileCache() - starting buffer\n" );
1670 ob_start( array(&$cache, 'saveToFileCache' ) );
1673 wfDebug( " tryFileCache() - not cacheable\n" );
1677 function isFileCacheable() {
1678 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1679 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1681 return $wgUseFileCache
1682 and (!$wgShowIPinHeader)
1683 and ($this->getID() != 0)
1684 and ($wgUser->getId() == 0)
1685 and (!$wgUser->getNewtalk())
1686 and ($this->mTitle
->getNamespace() != Namespace::getSpecial())
1687 and ($action == 'view')
1688 and (!isset($oldid))
1690 and (!isset($redirect))
1691 and (!isset($printable))
1692 and (!$this->mRedirectedFrom
);
1695 # Loads cur_touched and returns a value indicating if it should be used
1696 function checkTouched() {
1697 $id = $this->getID();
1698 $sql = 'SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id='.$id;
1699 $res = wfQuery( $sql, DB_READ
, 'Article::checkTouched' );
1700 if( $s = wfFetchObject( $res ) ) {
1701 $this->mTouched
= $s->cur_touched
;
1702 return !$s->cur_is_redirect
;
1708 # Edit an article without doing all that other stuff
1709 function quickEdit( $text, $comment = '', $minor = 0 ) {
1710 global $wgUser, $wgMwRedir, $wgIsPg;
1711 $fname = 'Article::quickEdit';
1712 wfProfileIn( $fname );
1714 $ns = $this->mTitle
->getNamespace();
1715 $dbkey = $this->mTitle
->getDBkey();
1716 $encDbKey = wfStrencode( $dbkey );
1717 $timestamp = wfTimestampNow();
1720 $oldtable=$wgIsPg?
'"old"':'old';
1721 $sql = "INSERT INTO $oldtable (old_namespace,old_title,old_text,old_comment,old_user,old_user_text,old_timestamp,inverse_timestamp)
1722 SELECT cur_namespace,cur_title,cur_text,cur_comment,cur_user,cur_user_text,cur_timestamp,99999999999999-cur_timestamp
1723 FROM cur WHERE cur_namespace=$ns AND cur_title='$encDbKey'";
1724 wfQuery( $sql, DB_WRITE
);
1726 # Use the affected row count to determine if the article is new
1727 $numRows = wfAffectedRows();
1729 # Make an array of fields to be inserted
1731 'cur_text' => $text,
1732 'cur_timestamp' => $timestamp,
1733 'cur_user' => $wgUser->getID(),
1734 'cur_user_text' => $wgUser->getName(),
1735 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1736 'cur_comment' => $comment,
1737 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ?
1 : 0,
1738 'cur_minor_edit' => intval($minor),
1739 'cur_touched' => $timestamp,
1744 $fields['cur_is_new'] = 0;
1745 wfUpdateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1747 # Insert new article
1748 $fields['cur_is_new'] = 1;
1749 $fields['cur_namespace'] = $ns;
1750 $fields['cur_title'] = $dbkey;
1751 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1752 wfInsertArray( 'cur', $fields, $fname );
1754 wfProfileOut( $fname );
1757 /* static */ function incViewCount( $id )
1759 $id = intval( $id );
1760 global $wgHitcounterUpdateFreq;
1762 if( $wgHitcounterUpdateFreq <= 1 ){ //
1763 wfQuery('UPDATE cur SET cur_counter = cur_counter + 1 ' .
1764 'WHERE cur_id = '.$id, DB_WRITE
);
1768 # Not important enough to warrant an error page in case of failure
1769 $oldignore = wfIgnoreSQLErrors( true );
1771 wfQuery("INSERT INTO hitcounter (hc_id) VALUES ({$id})", DB_WRITE
);
1773 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
1774 if( (rand() %
$checkfreq != 0) or (wfLastErrno() != 0) ){
1775 # Most of the time (or on SQL errors), skip row count check
1776 wfIgnoreSQLErrors( $oldignore );
1780 $res = wfQuery('SELECT COUNT(*) as n FROM hitcounter', DB_WRITE
);
1781 $row = wfFetchObject( $res );
1782 $rown = intval( $row->n
);
1783 if( $rown >= $wgHitcounterUpdateFreq ){
1784 wfProfileIn( 'Article::incViewCount-collect' );
1785 $old_user_abort = ignore_user_abort( true );
1787 wfQuery('LOCK TABLES hitcounter WRITE', DB_WRITE
);
1788 wfQuery('CREATE TEMPORARY TABLE acchits TYPE=HEAP '.
1789 'SELECT hc_id,COUNT(*) AS hc_n FROM hitcounter '.
1790 'GROUP BY hc_id', DB_WRITE
);
1791 wfQuery('DELETE FROM hitcounter', DB_WRITE
);
1792 wfQuery('UNLOCK TABLES', DB_WRITE
);
1793 wfQuery('UPDATE cur,acchits SET cur_counter=cur_counter + hc_n '.
1794 'WHERE cur_id = hc_id', DB_WRITE
);
1795 wfQuery('DROP TABLE acchits', DB_WRITE
);
1797 ignore_user_abort( $old_user_abort );
1798 wfProfileOut( 'Article::incViewCount-collect' );
1800 wfIgnoreSQLErrors( $oldignore );
1803 # The onArticle*() functions are supposed to be a kind of hooks
1804 # which should be called whenever any of the specified actions
1807 # This is a good place to put code to clear caches, for instance.
1809 # This is called on page move and undelete, as well as edit
1810 /* static */ function onArticleCreate($title_obj){
1811 global $wgUseSquid, $wgDeferredUpdateList;
1813 $titles = $title_obj->getBrokenLinksTo();
1816 if ( $wgUseSquid ) {
1817 $urls = $title_obj->getSquidURLs();
1818 foreach ( $titles as $linkTitle ) {
1819 $urls[] = $linkTitle->getInternalURL();
1821 $u = new SquidUpdate( $urls );
1822 array_push( $wgDeferredUpdateList, $u );
1825 # Clear persistent link cache
1826 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1829 /* static */ function onArticleDelete($title_obj){
1830 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
1833 /* static */ function onArticleEdit($title_obj){
1834 LinkCache
::linksccClearPage( $title_obj->getArticleID() );