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' );
12 $wgArticleCurContentFields = false;
13 $wgArticleOldContentFields = false;
16 /* private */ var $mContent, $mContentLoaded;
17 /* private */ var $mUser, $mTimestamp, $mUserText;
18 /* private */ var $mCounter, $mComment, $mCountAdjustment;
19 /* private */ var $mMinorEdit, $mRedirectedFrom;
20 /* private */ var $mTouched, $mFileCache, $mTitle;
21 /* private */ var $mId, $mTable;
22 /* private */ var $mForUpdate;
24 function Article( &$title ) {
25 $this->mTitle
=& $title;
29 /* private */ function clear() {
30 $this->mContentLoaded
= false;
31 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
32 $this->mRedirectedFrom
= $this->mUserText
=
33 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
34 $this->mCountAdjustment
= 0;
35 $this->mTouched
= '19700101000000';
36 $this->mForUpdate
= false;
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 =& $this->getDB();
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 " .
162 "WHERE blob_index='$index' " . $this->getSelectOptions(), $fname );
163 $row = $db->fetchObject( $res );
164 $text = $row->text_data
;
169 # File locations are of the form file://<filename>, relative to the current directory
170 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
171 $filename = strstr( $location, 'file://' );
172 $text = @file_get_contents
( $matches[1] );
174 if ( $text !== false ) {
175 # Got text, now we need to interpret it
176 # The first line contains information about how to do this
177 $p = strpos( $text, '\n' );
178 $type = substr( $text, 0, $p );
179 $text = substr( $text, $p +
1 );
184 $text = gzinflate( $text );
187 $object = unserialize( $text );
188 $text = $object->getItem( $hash );
194 wfProfileOut( $fname );
198 # Note that getContent/loadContent may follow redirects if
199 # not told otherwise, and so may cause a change to mTitle.
201 # Return the text of this revision
202 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].*?' . '>)(?!\S)/mi',
270 PREG_SPLIT_DELIM_CAPTURE
);
274 $headline=$secs[$section*2-1];
275 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/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].*?' . '>(?!\S)/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 ) {
335 global $wgOut, $wgMwRedir, $wgRequest;
337 $dbr =& $this->getDB();
339 $oldid = $wgRequest->getVal( 'oldid' );
340 $redirect = $wgRequest->getVal( 'redirect' );
342 if ( $this->mContentLoaded
) return;
343 $fname = 'Article::loadContent';
345 # Pre-fill content with error message so that if something
346 # fails we'll have something telling us what we intended.
348 $t = $this->mTitle
->getPrefixedText();
349 if ( isset( $oldid ) ) {
350 $oldid = IntVal( $oldid );
351 $t .= ',oldid='.$oldid;
353 if ( isset( $redirect ) ) {
354 $redirect = ($redirect == 'no') ?
'no' : 'yes';
355 $t .= ',redirect='.$redirect;
357 $this->mContent
= wfMsg( 'missingarticle', $t );
359 if ( ! $oldid ) { # Retrieve current version
360 $id = $this->getID();
361 if ( 0 == $id ) return;
363 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
364 $this->getSelectOptions() );
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
);
373 # process if title object is valid and not special:userlogout
374 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
375 # Gotta hand redirects to special pages differently:
376 # Fill the HTTP response "Location" header and ignore
377 # the rest of the page we're on.
379 if ( $rt->getInterwiki() != '' ) {
380 $wgOut->redirect( $rt->getFullURL() ) ;
383 if ( $rt->getNamespace() == NS_SPECIAL
) {
384 $wgOut->redirect( $rt->getFullURL() );
387 $rid = $rt->getArticleID();
389 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
390 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
392 if ( $redirRow !== false ) {
393 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
401 $this->mContent
= $s->cur_text
;
402 $this->mUser
= $s->cur_user
;
403 $this->mUserText
= $s->cur_user_text
;
404 $this->mComment
= $s->cur_comment
;
405 $this->mCounter
= $s->cur_counter
;
406 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
407 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
408 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
409 $this->mTitle
->mRestrictionsLoaded
= true;
410 } else { # oldid set, retrieve historical version
411 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
412 $fname, $this->getSelectOptions() );
413 if ( $s === false ) {
417 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
418 $this->mTitle
->getDBkey() != $s->old_title
) {
419 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
420 $this->mTitle
= $oldTitle;
421 $wgTitle = $oldTitle;
423 $this->mContent
= Article
::getRevisionText( $s );
424 $this->mUser
= $s->old_user
;
425 $this->mUserText
= $s->old_user_text
;
426 $this->mComment
= $s->old_comment
;
428 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
430 $this->mContentLoaded
= true;
431 return $this->mContent
;
434 # Gets the article text without using so many damn globals
435 # Returns false on error
436 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
439 if ( $this->mContentLoaded
) {
440 return $this->mContent
;
442 $this->mContent
= false;
444 $fname = 'Article::getContentWithout';
445 $dbr =& $this->getDB();
447 if ( ! $oldid ) { # Retrieve current version
448 $id = $this->getID();
453 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
454 $fname, $this->getSelectOptions() );
455 if ( $s === false ) {
459 # If we got a redirect, follow it (unless we've been told
460 # not to by either the function parameter or the query
462 $rt = Title
::newFromRedirect( $s->cur_text
);
463 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
464 $rid = $rt->getArticleID();
466 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
467 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
469 if ( $redirRow !== false ) {
470 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
478 $this->mContent
= $s->cur_text
;
479 $this->mUser
= $s->cur_user
;
480 $this->mUserText
= $s->cur_user_text
;
481 $this->mComment
= $s->cur_comment
;
482 $this->mCounter
= $s->cur_counter
;
483 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
484 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
485 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
486 $this->mTitle
->mRestrictionsLoaded
= true;
487 } else { # oldid set, retrieve historical version
488 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
489 $fname, $this->getSelectOptions() );
490 if ( $s === false ) {
493 $this->mContent
= Article
::getRevisionText( $s );
494 $this->mUser
= $s->old_user
;
495 $this->mUserText
= $s->old_user_text
;
496 $this->mComment
= $s->old_comment
;
498 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
500 $this->mContentLoaded
= true;
501 return $this->mContent
;
504 # Read/write accessor to select FOR UPDATE
505 function forUpdate( $x = NULL ) {
506 return wfSetVar( $this->mForUpdate
, $x );
509 # Get the database which should be used for reads
511 if ( $this->mForUpdate
) {
512 return wfGetDB( DB_MASTER
);
514 return wfGetDB( DB_SLAVE
);
518 # Get options for all SELECT statements
519 # Can pass an option array, to which the class-wide options will be appended
520 function getSelectOptions( $options = '' ) {
521 if ( $this->mForUpdate
) {
523 $options[] = 'FOR UPDATE';
525 $options = 'FOR UPDATE';
532 if( $this->mTitle
) {
533 return $this->mTitle
->getArticleID();
539 function getCount() {
540 if ( -1 == $this->mCounter
) {
541 $id = $this->getID();
542 $dbr =& $this->getDB();
543 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
544 'Article::getCount', $this->getSelectOptions() );
546 return $this->mCounter
;
549 # Would the given text make this article a "good" article (i.e.,
550 # suitable for including in the article count)?
551 function isCountable( $text ) {
552 global $wgUseCommaCount, $wgMwRedir;
554 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
555 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
556 $token = ($wgUseCommaCount ?
',' : '[[' );
557 if ( false === strstr( $text, $token ) ) { return 0; }
561 # Loads everything from cur except cur_text
562 # This isn't necessary for all uses, so it's only done if needed.
563 /* private */ function loadLastEdit() {
565 if ( -1 != $this->mUser
) return;
567 $fname = 'Article::loadLastEdit';
569 $dbr =& $this->getDB();
570 $s = $dbr->getArray( 'cur',
571 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
572 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
574 if ( $s !== false ) {
575 $this->mUser
= $s->cur_user
;
576 $this->mUserText
= $s->cur_user_text
;
577 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
578 $this->mComment
= $s->cur_comment
;
579 $this->mMinorEdit
= $s->cur_minor_edit
;
583 function getTimestamp() {
584 $this->loadLastEdit();
585 return $this->mTimestamp
;
589 $this->loadLastEdit();
593 function getUserText() {
594 $this->loadLastEdit();
595 return $this->mUserText
;
598 function getComment() {
599 $this->loadLastEdit();
600 return $this->mComment
;
603 function getMinorEdit() {
604 $this->loadLastEdit();
605 return $this->mMinorEdit
;
608 function getContributors($limit = 0, $offset = 0) {
609 $fname = 'Article::getContributors';
611 # XXX: this is expensive; cache this info somewhere.
613 $title = $this->mTitle
;
615 $dbr =& $this->getDB();
616 $oldTable = $dbr->tableName( 'old' );
617 $userTable = $dbr->tableName( 'user' );
618 $encDBkey = $dbr->strencode( $title->getDBkey() );
619 $ns = $title->getNamespace();
620 $user = $this->getUser();
622 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
623 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
624 WHERE old_namespace = $user
625 AND old_title = $encDBkey
626 AND old_user != $user
628 ORDER BY timestamp DESC";
630 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
631 $sql .= ' '. $this->getSelectOptions();
633 $res = $dbr->query($sql, $fname);
635 while ( $line = $dbr->fetchObject( $res ) ) {
636 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
639 $dbr->freeResult($res);
643 # This is the default action of the script: just view the page of
647 global $wgUser, $wgOut, $wgLang, $wgRequest, $wgMwRedir, $wgOnlySysopsCanPatrol;
648 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
649 $sk = $wgUser->getSkin();
651 $fname = 'Article::view';
652 wfProfileIn( $fname );
653 # Get variables from query string
654 $oldid = $wgRequest->getVal( 'oldid' );
655 $diff = $wgRequest->getVal( 'diff' );
656 $rcid = $wgRequest->getVal( 'rcid' );
658 $wgOut->setArticleFlag( true );
659 $wgOut->setRobotpolicy( 'index,follow' );
660 # If we got diff and oldid in the query, we want to see a
661 # diff page instead of the article.
663 if ( !is_null( $diff ) ) {
664 require_once( 'DifferenceEngine.php' );
665 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
666 $de = new DifferenceEngine( $oldid, $diff, $rcid );
668 wfProfileOut( $fname );
670 # Run view updates for current revision only
671 $this->viewUpdates();
675 if ( empty( $oldid ) && $this->checkTouched() ) {
676 if( $wgOut->checkLastModified( $this->mTouched
) ){
678 } else if ( $this->tryFileCache() ) {
679 # tell wgOut that output is taken care of
681 $this->viewUpdates();
685 # Should the parser cache be used?
686 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
694 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
698 if ( !$outputDone ) {
699 $text = $this->getContent( false ); # May change mTitle by following a redirect
701 # Another whitelist check in case oldid or redirects are altering the title
702 if ( !$this->mTitle
->userCanRead() ) {
703 $wgOut->loginToUse();
709 # We're looking at an old revision
711 if ( !empty( $oldid ) ) {
712 $this->setOldSubtitle();
713 $wgOut->setRobotpolicy( 'noindex,follow' );
715 if ( '' != $this->mRedirectedFrom
) {
716 $sk = $wgUser->getSkin();
717 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
719 $s = wfMsg( 'redirectedfrom', $redir );
720 $wgOut->setSubtitle( $s );
722 # Can't cache redirects
726 # wrap user css and user js in pre and don't parse
727 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
729 $this->mTitle
->getNamespace() == NS_USER
&&
730 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
732 $wgOut->addWikiText( wfMsg('clearyourcache'));
733 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
734 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
736 $imageUrl = $wgStylePath.'/images/redirect.png';
737 $targetUrl = $rt->escapeLocalURL();
738 $titleText = htmlspecialchars( $rt->getPrefixedText() );
739 $link = $sk->makeLinkObj( $rt );
740 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'">' .
741 '<span class="redirectText">'.$link.'</span>' );
742 } else if ( $pcache ) {
743 # Display content and save to parser cache
744 $wgOut->addPrimaryWikiText( $text, $this );
746 # Display content, don't attempt to save to parser cache
747 $wgOut->addWikiText( $text );
750 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
751 # If we have been passed an &rcid= parameter, we want to give the user a
752 # chance to mark this new article as patrolled.
753 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
754 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
756 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
757 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
758 'action=markpatrolled&rcid='.$rcid )
762 # Put link titles into the link cache
763 $wgOut->transformBuffer();
765 # Add link titles as META keywords
766 $wgOut->addMetaTags() ;
768 $this->viewUpdates();
769 wfProfileOut( $fname );
772 # Theoretically we could defer these whole insert and update
773 # functions for after display, but that's taking a big leap
774 # of faith, and we want to be able to report database
775 # errors at some point.
777 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
778 global $wgOut, $wgUser, $wgMwRedir;
779 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
781 $fname = 'Article::insertNewArticle';
783 $this->mCountAdjustment
= $this->isCountable( $text );
785 $ns = $this->mTitle
->getNamespace();
786 $ttl = $this->mTitle
->getDBkey();
787 $text = $this->preSaveTransform( $text );
788 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
791 $now = wfTimestampNow();
792 $won = wfInvertTimestamp( $now );
794 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
795 $dbw =& wfGetDB( DB_MASTER
);
797 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
799 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
801 $dbw->insertArray( 'cur', array(
803 'cur_namespace' => $ns,
806 'cur_comment' => $summary,
807 'cur_user' => $wgUser->getID(),
808 'cur_timestamp' => $dbw->timestamp($now),
809 'cur_minor_edit' => $isminor,
811 'cur_restrictions' => '',
812 'cur_user_text' => $wgUser->getName(),
813 'cur_is_redirect' => $redir,
815 'cur_random' => $rand,
816 'cur_touched' => $dbw->timestamp($now),
817 'inverse_timestamp' => $won,
820 $newid = $dbw->insertId();
821 $this->mTitle
->resetArticleID( $newid );
823 Article
::onArticleCreate( $this->mTitle
);
824 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
827 if(!$this->mTitle
->userIsWatching()) $this->watch();
829 if ( $this->mTitle
->userIsWatching() ) {
834 # The talk page isn't in the regular link tables, so we need to update manually:
835 $talkns = $ns ^
1; # talk -> normal; normal -> talk
836 $dbw->updateArray( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
837 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
839 # standard deferred updates
840 $this->editUpdates( $text );
842 $this->showArticle( $text, wfMsg( 'newarticle' ) );
846 /* Side effects: loads last edit */
847 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '') {
848 $this->loadLastEdit();
849 $oldtext = $this->getContent( true );
850 if ($section != '') {
851 if($section=='new') {
852 if($summary) $subject="== {$summary} ==\n\n";
853 $text=$oldtext."\n\n".$subject.$text;
856 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
857 # comments to be stripped as well)
859 $parser=new Parser();
860 $parser->mOutputType
=OT_WIKI
;
861 $oldtext=$parser->strip($oldtext, $striparray, true);
863 # now that we can be sure that no pseudo-sections are in the source,
865 # Unfortunately we can't simply do a preg_replace because that might
866 # replace the wrong section, so we have to use the section counter instead
867 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
868 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
869 $secs[$section*2]=$text."\n\n"; // replace with edited
871 # section 0 is top (intro) section
874 # headline of old section - we need to go through this section
875 # to determine if there are any subsections that now need to
876 # be erased, as the mother section has been replaced with
877 # the text of all subsections.
878 $headline=$secs[$section*2-1];
879 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
882 # determine headline level for wikimarkup headings
883 if(strpos($hlevel,'=')!==false) {
884 $hlevel=strlen($hlevel);
887 $secs[$section*2-1]=''; // erase old headline
890 while(!empty($secs[$count*2-1]) && !$break) {
892 $subheadline=$secs[$count*2-1];
894 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
895 $subhlevel=$matches[1];
896 if(strpos($subhlevel,'=')!==false) {
897 $subhlevel=strlen($subhlevel);
899 if($subhlevel > $hlevel) {
900 // erase old subsections
901 $secs[$count*2-1]='';
904 if($subhlevel <= $hlevel) {
912 $text=join('',$secs);
913 # reinsert the stuff that we stripped out earlier
914 $text=$parser->unstrip($text,$striparray);
915 $text=$parser->unstripNoWiki($text,$striparray);
922 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
923 global $wgOut, $wgUser;
924 global $wgDBtransactions, $wgMwRedir;
925 global $wgUseSquid, $wgInternalServer;
927 $fname = 'Article::updateArticle';
930 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
931 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
932 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
934 $text = $m[1] . "\n"; # Remove all content but redirect
938 $text = $this->preSaveTransform( $text );
939 $dbw =& wfGetDB( DB_MASTER
);
941 # Update article, but only if changed.
943 # It's important that we either rollback or complete, otherwise an attacker could
944 # overwrite cur entries by sending precisely timed user aborts. Random bored users
945 # could conceivably have the same effect, especially if cur is locked for long periods.
946 if( $wgDBtransactions ) {
947 $dbw->query( 'BEGIN', $fname );
949 $userAbort = ignore_user_abort( true );
952 $oldtext = $this->getContent( true );
954 if ( 0 != strcmp( $text, $oldtext ) ) {
955 $this->mCountAdjustment
= $this->isCountable( $text )
956 - $this->isCountable( $oldtext );
957 $now = wfTimestampNow();
958 $won = wfInvertTimestamp( $now );
960 # First update the cur row
961 $dbw->updateArray( 'cur',
964 'cur_comment' => $summary,
965 'cur_minor_edit' => $me2,
966 'cur_user' => $wgUser->getID(),
967 'cur_timestamp' => $dbw->timestamp($now),
968 'cur_user_text' => $wgUser->getName(),
969 'cur_is_redirect' => $redir,
971 'cur_touched' => $dbw->timestamp($now),
972 'inverse_timestamp' => $won
973 ), array( /* WHERE */
974 'cur_id' => $this->getID(),
975 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
979 if( $dbw->affectedRows() == 0 ) {
980 /* Belated edit conflict! Run away!! */
983 # Now insert the previous revision into old
985 # This overwrites $oldtext if revision compression is on
986 $flags = Article
::compressRevisionText( $oldtext );
988 $dbw->insertArray( 'old',
990 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
991 'old_namespace' => $this->mTitle
->getNamespace(),
992 'old_title' => $this->mTitle
->getDBkey(),
993 'old_text' => $oldtext,
994 'old_comment' => $this->getComment(),
995 'old_user' => $this->getUser(),
996 'old_user_text' => $this->getUserText(),
997 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
998 'old_minor_edit' => $me1,
999 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1000 'old_flags' => $flags,
1004 $oldid = $dbw->insertId();
1006 $bot = (int)($wgUser->isBot() ||
$forceBot);
1007 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1008 $oldid, $this->getTimestamp(), $bot );
1009 Article
::onArticleEdit( $this->mTitle
);
1013 if( $wgDBtransactions ) {
1014 $dbw->query( 'COMMIT', $fname );
1016 ignore_user_abort( $userAbort );
1021 if (!$this->mTitle
->userIsWatching()) $this->watch();
1023 if ( $this->mTitle
->userIsWatching() ) {
1027 # standard deferred updates
1028 $this->editUpdates( $text );
1032 # Template namespace
1033 # Purge all articles linking here
1034 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1035 $titles = $this->mTitle
->getLinksTo();
1036 Title
::touchArray( $titles );
1037 if ( $wgUseSquid ) {
1038 foreach ( $titles as $title ) {
1039 $urls[] = $title->getInternalURL();
1045 if ( $wgUseSquid ) {
1046 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1047 $u = new SquidUpdate( $urls );
1051 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1056 # After we've either updated or inserted the article, update
1057 # the link tables and redirect to the new page.
1059 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1060 global $wgOut, $wgUser, $wgLinkCache;
1063 $wgLinkCache = new LinkCache();
1065 $wgLinkCache->forUpdate( true );
1067 # Get old version of link table to allow incremental link updates
1068 $wgLinkCache->preFill( $this->mTitle
);
1069 $wgLinkCache->clear();
1071 # Parse the text and replace links with placeholders
1072 $wgOut = new OutputPage();
1073 $wgOut->addWikiText( $text );
1075 # Look up the links in the DB and add them to the link cache
1076 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1078 if( $wgMwRedir->matchStart( $text ) )
1082 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1087 function validate () {
1088 global $wgOut, $wgUseValidation;
1089 if( $wgUseValidation ) {
1090 require_once ( 'SpecialValidate.php' ) ;
1091 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1092 $wgOut->setRobotpolicy( 'noindex,follow' );
1093 if( $this->mTitle
->getNamespace() != 0 ) {
1094 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1097 $v = new Validation
;
1098 $v->validate_form( $this->mTitle
->getDBkey() );
1100 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1104 # Mark this particular edit as patrolled
1105 function markpatrolled() {
1106 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1107 $wgOut->setRobotpolicy( 'noindex,follow' );
1109 if ( !$wgUseRCPatrol )
1111 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1114 if ( $wgUser->getID() == 0 )
1116 $wgOut->loginToUse();
1119 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1121 $wgOut->sysopRequired();
1124 $rcid = $wgRequest->getVal( 'rcid' );
1125 if ( !is_null ( $rcid ) )
1127 RecentChange
::markPatrolled( $rcid );
1128 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1129 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1130 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1134 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1139 # Add this page to my watchlist
1141 function watch( $add = true ) {
1142 global $wgUser, $wgOut, $wgLang;
1143 global $wgDeferredUpdateList;
1145 if ( 0 == $wgUser->getID() ) {
1146 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1149 if ( wfReadOnly() ) {
1150 $wgOut->readOnlyPage();
1154 $wgUser->addWatch( $this->mTitle
);
1156 $wgUser->removeWatch( $this->mTitle
);
1158 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1159 $wgOut->setRobotpolicy( 'noindex,follow' );
1161 $sk = $wgUser->getSkin() ;
1162 $link = $this->mTitle
->getPrefixedText();
1165 $text = wfMsg( 'addedwatchtext', $link );
1167 $text = wfMsg( 'removedwatchtext', $link );
1168 $wgOut->addWikiText( $text );
1170 $up = new UserUpdate();
1171 array_push( $wgDeferredUpdateList, $up );
1173 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1176 function unwatch() {
1177 $this->watch( false );
1182 function protect( $limit = 'sysop' ) {
1183 global $wgUser, $wgOut, $wgRequest;
1185 if ( ! $wgUser->isSysop() ) {
1186 $wgOut->sysopRequired();
1189 if ( wfReadOnly() ) {
1190 $wgOut->readOnlyPage();
1193 $id = $this->mTitle
->getArticleID();
1195 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1199 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1200 $reason = $wgRequest->getText( 'wpReasonProtect' );
1203 $dbw =& wfGetDB( DB_MASTER
);
1204 $dbw->updateArray( 'cur',
1206 'cur_touched' => $dbw->timestamp(),
1207 'cur_restrictions' => (string)$limit
1208 ), array( /* WHERE */
1210 ), 'Article::protect'
1213 $log = new LogPage( 'protect' );
1214 if ( $limit === '' ) {
1215 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1217 $log->addEntry( 'protect', $this->mTitle
, $reason );
1219 $wgOut->redirect( $this->mTitle
->getFullURL() );
1222 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1223 return $this->confirmProtect( '', $reason, $limit );
1227 # Output protection confirmation dialog
1229 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1232 wfDebug( "Article::confirmProtect\n" );
1234 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1235 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1240 if ( $limit === '' ) {
1241 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1242 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1243 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1244 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1245 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1246 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1248 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1249 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1250 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1251 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1252 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1253 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1256 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1259 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1263 <label for='wpReasonProtect'>{$protcom}:</label>
1266 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1274 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1277 <label for='wpConfirmProtect'>{$check}</label>
1283 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1289 $wgOut->returnToMain( false );
1292 function unprotect() {
1293 return $this->protect( '' );
1296 # UI entry point for page deletion
1299 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1300 $fname = 'Article::delete';
1301 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1302 $reason = $wgRequest->getText( 'wpReason' );
1304 # This code desperately needs to be totally rewritten
1307 if ( ( ! $wgUser->isSysop() ) ) {
1308 $wgOut->sysopRequired();
1311 if ( wfReadOnly() ) {
1312 $wgOut->readOnlyPage();
1316 # Better double-check that it hasn't been deleted yet!
1317 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1318 if ( ( '' == trim( $this->mTitle
->getText() ) )
1319 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1320 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1325 $this->doDelete( $reason );
1329 # determine whether this page has earlier revisions
1330 # and insert a warning if it does
1331 # we select the text because it might be useful below
1332 $dbr =& $this->getDB();
1333 $ns = $this->mTitle
->getNamespace();
1334 $title = $this->mTitle
->getDBkey();
1335 $old = $dbr->getArray( 'old',
1336 array( 'old_text', 'old_flags' ),
1338 'old_namespace' => $ns,
1339 'old_title' => $title,
1340 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1343 if( $old !== false && !$confirm ) {
1344 $skin=$wgUser->getSkin();
1345 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1346 $wgOut->addHTML( $skin->historyLink() .'</b>');
1350 $s = $dbr->getArray( 'cur',
1351 array( 'cur_text' ),
1353 'cur_namespace' => $ns,
1354 'cur_title' => $title,
1355 ), $fname, $this->getSelectOptions()
1358 if( $s !== false ) {
1359 # if this is a mini-text, we can paste part of it into the deletion reason
1361 #if this is empty, an earlier revision may contain "useful" text
1363 if($s->cur_text
!= '') {
1367 $text = Article
::getRevisionText( $old );
1373 $length=strlen($text);
1375 # this should not happen, since it is not possible to store an empty, new
1376 # page. Let's insert a standard text in case it does, though
1377 if($length == 0 && $reason === '') {
1378 $reason = wfMsg('exblank');
1381 if($length < 500 && $reason === '') {
1383 # comment field=255, let's grep the first 150 to have some user
1385 $text=substr($text,0,150);
1386 # let's strip out newlines and HTML tags
1387 $text=preg_replace('/\"/',"'",$text);
1388 $text=preg_replace('/\</','<',$text);
1389 $text=preg_replace('/\>/','>',$text);
1390 $text=preg_replace("/[\n\r]/",'',$text);
1392 $reason=wfMsg('excontent'). " '".$text;
1394 $reason=wfMsg('exbeforeblank') . " '".$text;
1396 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1401 return $this->confirmDelete( '', $reason );
1404 # Output deletion confirmation dialog
1406 function confirmDelete( $par, $reason ) {
1409 wfDebug( "Article::confirmDelete\n" );
1411 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1412 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1413 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1414 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1416 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1418 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1419 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1420 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1423 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1427 <label for='wpReason'>{$delcom}:</label>
1430 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1438 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1441 <label for='wpConfirm'>{$check}</label>
1447 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1453 $wgOut->returnToMain( false );
1457 # Perform a deletion and output success or failure messages
1459 function doDelete( $reason ) {
1460 global $wgOut, $wgUser, $wgLang;
1461 $fname = 'Article::doDelete';
1462 wfDebug( $fname."\n" );
1464 if ( $this->doDeleteArticle( $reason ) ) {
1465 $deleted = $this->mTitle
->getPrefixedText();
1467 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1468 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1470 $sk = $wgUser->getSkin();
1471 $loglink = $sk->makeKnownLink( $wgLang->getNsText( NS_PROJECT
) .
1472 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1474 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1476 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1477 $wgOut->returnToMain( false );
1479 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1483 # Back-end article deletion
1484 # Deletes the article with database consistency, writes logs, purges caches
1486 function doDeleteArticle( $reason ) {
1487 global $wgUser, $wgLang;
1488 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1490 $fname = 'Article::doDeleteArticle';
1491 wfDebug( $fname."\n" );
1493 $dbw =& wfGetDB( DB_MASTER
);
1494 $ns = $this->mTitle
->getNamespace();
1495 $t = $this->mTitle
->getDBkey();
1496 $id = $this->mTitle
->getArticleID();
1498 if ( $t == '' ||
$id == 0 ) {
1502 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1503 array_push( $wgDeferredUpdateList, $u );
1505 $linksTo = $this->mTitle
->getLinksTo();
1508 if ( $wgUseSquid ) {
1510 $this->mTitle
->getInternalURL(),
1511 $this->mTitle
->getInternalURL( 'history' )
1513 foreach ( $linksTo as $linkTo ) {
1514 $urls[] = $linkTo->getInternalURL();
1517 $u = new SquidUpdate( $urls );
1518 array_push( $wgDeferredUpdateList, $u );
1522 # Client and file cache invalidation
1523 Title
::touchArray( $linksTo );
1525 # Move article and history to the "archive" table
1526 $archiveTable = $dbw->tableName( 'archive' );
1527 $oldTable = $dbw->tableName( 'old' );
1528 $curTable = $dbw->tableName( 'cur' );
1529 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1530 $linksTable = $dbw->tableName( 'links' );
1531 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1533 $dbw->insertSelect( 'archive', 'cur',
1535 'ar_namespace' => 'cur_namespace',
1536 'ar_title' => 'cur_title',
1537 'ar_text' => 'cur_text',
1538 'ar_comment' => 'cur_comment',
1539 'ar_user' => 'cur_user',
1540 'ar_user_text' => 'cur_user_text',
1541 'ar_timestamp' => 'cur_timestamp',
1542 'ar_minor_edit' => 'cur_minor_edit',
1545 'cur_namespace' => $ns,
1550 $dbw->insertSelect( 'archive', 'old',
1552 'ar_namespace' => 'old_namespace',
1553 'ar_title' => 'old_title',
1554 'ar_text' => 'old_text',
1555 'ar_comment' => 'old_comment',
1556 'ar_user' => 'old_user',
1557 'ar_user_text' => 'old_user_text',
1558 'ar_timestamp' => 'old_timestamp',
1559 'ar_minor_edit' => 'old_minor_edit',
1560 'ar_flags' => 'old_flags'
1562 'old_namespace' => $ns,
1567 # Now that it's safely backed up, delete it
1569 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1570 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1571 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1573 # Finally, clean up the link tables
1574 $t = $this->mTitle
->getPrefixedDBkey();
1576 Article
::onArticleDelete( $this->mTitle
);
1578 # Insert broken links
1579 $brokenLinks = array();
1580 foreach ( $linksTo as $titleObj ) {
1581 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1582 $linkID = $titleObj->getArticleID();
1583 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1585 $dbw->insertArray( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1588 $dbw->delete( 'links', array( 'l_to' => $id ) );
1589 $dbw->delete( 'links', array( 'l_from' => $id ) );
1590 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1591 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1592 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1595 $log = new LogPage( 'delete' );
1596 $log->addEntry( 'delete', $this->mTitle
, $reason );
1598 # Clear the cached article id so the interface doesn't act like we exist
1599 $this->mTitle
->resetArticleID( 0 );
1600 $this->mTitle
->mArticleID
= 0;
1604 function rollback() {
1605 global $wgUser, $wgLang, $wgOut, $wgRequest;
1606 $fname = 'Article::rollback';
1608 if ( ! $wgUser->isSysop() ) {
1609 $wgOut->sysopRequired();
1612 if ( wfReadOnly() ) {
1613 $wgOut->readOnlyPage( $this->getContent( true ) );
1616 $dbw =& wfGetDB( DB_MASTER
);
1618 # Enhanced rollback, marks edits rc_bot=1
1619 $bot = $wgRequest->getBool( 'bot' );
1621 # Replace all this user's current edits with the next one down
1622 $tt = $this->mTitle
->getDBKey();
1623 $n = $this->mTitle
->getNamespace();
1625 # Get the last editor, lock table exclusively
1626 $s = $dbw->getArray( 'cur',
1627 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1628 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1629 $fname, 'FOR UPDATE'
1631 if( $s === false ) {
1633 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1636 $ut = $dbw->strencode( $s->cur_user_text
);
1637 $uid = $s->cur_user
;
1640 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1641 if( $from != $s->cur_user_text
) {
1642 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1643 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1644 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1645 htmlspecialchars( $from ),
1646 htmlspecialchars( $s->cur_user_text
) ) );
1647 if($s->cur_comment
!= '') {
1649 wfMsg('editcomment',
1650 htmlspecialchars( $s->cur_comment
) ) );
1655 # Get the last edit not by this guy
1656 $s = $dbw->getArray( 'old',
1657 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1659 'old_namespace' => $n,
1661 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1662 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1664 if( $s === false ) {
1666 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1667 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1672 # Mark all reverted edits as bot
1673 $dbw->updateArray( 'recentchanges',
1676 ), array( /* WHERE */
1678 "rc_timestamp > '{$s->old_timestamp}'",
1684 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1685 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1686 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1687 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1688 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1689 Article
::onArticleEdit( $this->mTitle
);
1690 $wgOut->returnToMain( false );
1694 # Do standard deferred updates after page view
1696 /* private */ function viewUpdates() {
1697 global $wgDeferredUpdateList;
1698 if ( 0 != $this->getID() ) {
1699 global $wgDisableCounters;
1700 if( !$wgDisableCounters ) {
1701 Article
::incViewCount( $this->getID() );
1702 $u = new SiteStatsUpdate( 1, 0, 0 );
1703 array_push( $wgDeferredUpdateList, $u );
1706 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1707 $this->mTitle
->getDBkey() );
1708 array_push( $wgDeferredUpdateList, $u );
1711 # Do standard deferred updates after page edit.
1712 # Every 1000th edit, prune the recent changes table.
1714 /* private */ function editUpdates( $text ) {
1715 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1716 global $wgMessageCache;
1719 if ( 0 == mt_rand( 0, 999 ) ) {
1720 $dbw =& wfGetDB( DB_MASTER
);
1721 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1722 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1723 $dbw->query( $sql );
1725 $id = $this->getID();
1726 $title = $this->mTitle
->getPrefixedDBkey();
1727 $shortTitle = $this->mTitle
->getDBkey();
1729 $adj = $this->mCountAdjustment
;
1732 $u = new LinksUpdate( $id, $title );
1733 array_push( $wgDeferredUpdateList, $u );
1734 $u = new SiteStatsUpdate( 0, 1, $adj );
1735 array_push( $wgDeferredUpdateList, $u );
1736 $u = new SearchUpdate( $id, $title, $text );
1737 array_push( $wgDeferredUpdateList, $u );
1739 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1740 array_push( $wgDeferredUpdateList, $u );
1742 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1743 $wgMessageCache->replace( $shortTitle, $text );
1748 /* private */ function setOldSubtitle() {
1749 global $wgLang, $wgOut, $wgUser;
1751 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1752 $sk = $wgUser->getSkin();
1753 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1754 $r = wfMsg( 'revisionasofwithlink', $td, $lnk );
1755 $wgOut->setSubtitle( $r );
1758 # This function is called right before saving the wikitext,
1759 # so we can do things like signatures and links-in-context.
1761 function preSaveTransform( $text ) {
1762 global $wgParser, $wgUser;
1763 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1766 /* Caching functions */
1768 # checkLastModified returns true if it has taken care of all
1769 # output to the client that is necessary for this request.
1770 # (that is, it has sent a cached version of the page)
1771 function tryFileCache() {
1772 static $called = false;
1774 wfDebug( " tryFileCache() -- called twice!?\n" );
1778 if($this->isFileCacheable()) {
1779 $touched = $this->mTouched
;
1780 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1781 # Expire the main page quicker
1782 $expire = wfUnix2Timestamp( time() - 3600 );
1783 $touched = max( $expire, $touched );
1785 $cache = new CacheManager( $this->mTitle
);
1786 if($cache->isFileCacheGood( $touched )) {
1788 wfDebug( " tryFileCache() - about to load\n" );
1789 $cache->loadFromFileCache();
1792 wfDebug( " tryFileCache() - starting buffer\n" );
1793 ob_start( array(&$cache, 'saveToFileCache' ) );
1796 wfDebug( " tryFileCache() - not cacheable\n" );
1800 function isFileCacheable() {
1801 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1802 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1804 return $wgUseFileCache
1805 and (!$wgShowIPinHeader)
1806 and ($this->getID() != 0)
1807 and ($wgUser->getId() == 0)
1808 and (!$wgUser->getNewtalk())
1809 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1810 and (empty( $action ) ||
$action == 'view')
1811 and (!isset($oldid))
1813 and (!isset($redirect))
1814 and (!isset($printable))
1815 and (!$this->mRedirectedFrom
);
1818 # Loads cur_touched and returns a value indicating if it should be used
1819 function checkTouched() {
1820 $fname = 'Article::checkTouched';
1821 $id = $this->getID();
1822 $dbr =& $this->getDB();
1823 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1824 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1825 if( $s !== false ) {
1826 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1827 return !$s->cur_is_redirect
;
1833 # Edit an article without doing all that other stuff
1834 function quickEdit( $text, $comment = '', $minor = 0 ) {
1835 global $wgUser, $wgMwRedir;
1836 $fname = 'Article::quickEdit';
1837 wfProfileIn( $fname );
1839 $dbw =& wfGetDB( DB_MASTER
);
1840 $ns = $this->mTitle
->getNamespace();
1841 $dbkey = $this->mTitle
->getDBkey();
1842 $encDbKey = $dbw->strencode( $dbkey );
1843 $timestamp = wfTimestampNow();
1846 $dbw->insertSelect( 'old', 'cur',
1848 'old_namespace' => 'cur_namespace',
1849 'old_title' => 'cur_title',
1850 'old_text' => 'cur_text',
1851 'old_comment' => 'cur_comment',
1852 'old_user' => 'cur_user',
1853 'old_user_text' => 'cur_user_text',
1854 'old_timestamp' => 'cur_timestamp',
1855 'inverse_timestamp' => '99999999999999-cur_timestamp',
1857 'cur_namespace' => $ns,
1858 'cur_title' => $dbkey,
1862 # Use the affected row count to determine if the article is new
1863 $numRows = $dbw->affectedRows();
1865 # Make an array of fields to be inserted
1867 'cur_text' => $text,
1868 'cur_timestamp' => $timestamp,
1869 'cur_user' => $wgUser->getID(),
1870 'cur_user_text' => $wgUser->getName(),
1871 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1872 'cur_comment' => $comment,
1873 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ?
1 : 0,
1874 'cur_minor_edit' => intval($minor),
1875 'cur_touched' => $dbw->timestamp($timestamp),
1880 $fields['cur_is_new'] = 0;
1881 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1883 # Insert new article
1884 $fields['cur_is_new'] = 1;
1885 $fields['cur_namespace'] = $ns;
1886 $fields['cur_title'] = $dbkey;
1887 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1888 $dbw->insertArray( 'cur', $fields, $fname );
1890 wfProfileOut( $fname );
1893 /* static */ function incViewCount( $id ) {
1894 $id = intval( $id );
1895 global $wgHitcounterUpdateFreq;
1897 $dbw =& wfGetDB( DB_MASTER
);
1898 $curTable = $dbw->tableName( 'cur' );
1899 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1900 $acchitsTable = $dbw->tableName( 'acchits' );
1902 if( $wgHitcounterUpdateFreq <= 1 ){ //
1903 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
1907 # Not important enough to warrant an error page in case of failure
1908 $oldignore = $dbw->ignoreErrors( true );
1910 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
1912 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
1913 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
1914 # Most of the time (or on SQL errors), skip row count check
1915 $dbw->ignoreErrors( $oldignore );
1919 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
1920 $row = $dbw->fetchObject( $res );
1921 $rown = intval( $row->n
);
1922 if( $rown >= $wgHitcounterUpdateFreq ){
1923 wfProfileIn( 'Article::incViewCount-collect' );
1924 $old_user_abort = ignore_user_abort( true );
1926 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
1927 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
1928 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
1930 $dbw->query("DELETE FROM $hitcounterTable");
1931 $dbw->query('UNLOCK TABLES');
1932 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
1933 'WHERE cur_id = hc_id');
1934 $dbw->query("DROP TABLE $acchitsTable");
1936 ignore_user_abort( $old_user_abort );
1937 wfProfileOut( 'Article::incViewCount-collect' );
1939 $dbw->ignoreErrors( $oldignore );
1942 # The onArticle*() functions are supposed to be a kind of hooks
1943 # which should be called whenever any of the specified actions
1946 # This is a good place to put code to clear caches, for instance.
1948 # This is called on page move and undelete, as well as edit
1949 /* static */ function onArticleCreate($title_obj) {
1950 global $wgUseSquid, $wgDeferredUpdateList;
1952 $titles = $title_obj->getBrokenLinksTo();
1955 if ( $wgUseSquid ) {
1956 $urls = $title_obj->getSquidURLs();
1957 foreach ( $titles as $linkTitle ) {
1958 $urls[] = $linkTitle->getInternalURL();
1960 $u = new SquidUpdate( $urls );
1961 array_push( $wgDeferredUpdateList, $u );
1964 # Clear persistent link cache
1965 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1968 /* static */ function onArticleDelete($title_obj) {
1969 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
1972 /* static */ function onArticleEdit($title_obj) {
1973 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
1977 # Info about this page
1980 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgAllowPageInfo;
1981 $fname = 'Article::info';
1983 if ( !$wgAllowPageInfo ) {
1984 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1988 $dbr =& $this->getDB();
1990 $basenamespace = $wgTitle->getNamespace() & (~
1);
1991 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
1992 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
1993 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
1994 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
1995 $wgOut->setPagetitle( $fullTitle );
1996 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
1998 # first, see if the page exists at all.
1999 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2001 $wgOut->addHTML( wfMsg('noarticletext') );
2003 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2004 $this->getSelectOptions() );
2005 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2006 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2007 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2009 # to find number of distinct authors, we need to do some
2010 # funny stuff because of the cur/old table split:
2011 # - first, find the name of the 'cur' author
2012 # - then, find the number of *other* authors in 'old'
2015 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2016 $this->getSelectOptions() );
2018 # find number of 'old' authors excluding 'cur' author
2019 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2020 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2021 $this->getSelectOptions() ) +
1;
2023 # now for the Talk page ...
2024 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2025 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2028 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2032 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2033 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2035 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2039 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2040 $this->getSelectOptions() );
2041 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2042 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2043 $fname, $this->getSelectOptions() );
2045 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );