4 # Class representing a Wikipedia article and history.
5 # See design.doc for an overview.
7 # Note: edit user interface and cache support functions have been
8 # moved to separate EditPage and CacheManager classes.
10 require_once ( 'CacheManager.php' );
11 include_once ( 'SpecialValidate.php' ) ;
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
17 /* private */ var $mContent, $mContentLoaded;
18 /* private */ var $mUser, $mTimestamp, $mUserText;
19 /* private */ var $mCounter, $mComment, $mCountAdjustment;
20 /* private */ var $mMinorEdit, $mRedirectedFrom;
21 /* private */ var $mTouched, $mFileCache, $mTitle;
22 /* private */ var $mId, $mTable;
24 function Article( &$title ) {
25 $this->mTitle
=& $title;
29 /* private */ function clear() {
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';
38 # Get revision text associated with an old or archive row
39 # $row is usually an object from wfFetchRow(), both the flags and the text field must be included
40 /* static */ function getRevisionText( $row, $prefix = 'old_' ) {
42 $textField = $prefix . 'text';
43 $flagsField = $prefix . 'flags';
45 if ( isset( $row->$flagsField ) ) {
46 $flags = explode( ",", $row->$flagsField );
51 if ( isset( $row->$textField ) ) {
52 $text = $row->$textField;
57 if ( in_array( 'link', $flags ) ) {
59 $text = Article
::followLink( $text );
60 } elseif ( in_array( 'gzip', $flags ) ) {
61 # Deal with optional compression of archived pages.
62 # This can be done periodically via maintenance/compressOld.php, and
63 # as pages are saved if $wgCompressRevisions is set.
64 return gzinflate( $text );
69 /* static */ function compressRevisionText( &$text ) {
70 global $wgCompressRevisions;
71 if( !$wgCompressRevisions ) {
74 if( !function_exists( 'gzdeflate' ) ) {
75 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
78 $text = gzdeflate( $text );
82 # Returns the text associated with a "link" type old table row
83 /* static */ function followLink( $link ) {
84 # Split the link into fields and values
85 $lines = explode( '\n', $link );
88 foreach ( $lines as $line ) {
90 if ( $line{0} == '#' ) {
94 if ( preg_match( '/^(.*?)\s*:\s*(.*)$/', $line, $matches ) ) {
95 $field = strtolower($matches[1]);
97 if ( $field == 'hash' ) {
99 } elseif ( $field == 'location' ) {
100 $locations[] = $value;
105 if ( $hash === '' ) {
109 # Look in each specified location for the text
111 foreach ( $locations as $location ) {
112 $text = Article
::fetchFromLocation( $location, $hash );
113 if ( $text !== false ) {
121 /* static */ function fetchFromLocation( $location, $hash ) {
122 global $wgLoadBalancer;
123 $fname = 'fetchFromLocation';
124 wfProfileIn( $fname );
126 $p = strpos( $location, ':' );
127 if ( $p === false ) {
128 wfProfileOut( $fname );
132 $type = substr( $location, 0, $p );
136 # MySQL locations are specified by mysql://<machineID>/<dbname>/<tblname>/<index>
137 # Machine ID 0 is the current connection
138 if ( preg_match( '/^mysql:\/\/(\d+)\/([A-Za-z_]+)\/([A-Za-z_]+)\/([A-Za-z_]+)$/',
139 $location, $matches ) ) {
140 $machineID = $matches[1];
141 $dbName = $matches[2];
142 $tblName = $matches[3];
143 $index = $matches[4];
144 if ( $machineID == 0 ) {
146 $db =& wfGetDB( DB_SLAVE
);
148 # Alternate connection
149 $db =& $wgLoadBalancer->getConnection( $machineID );
151 if ( array_key_exists( $machineId, $wgKnownMysqlServers ) ) {
152 # Try to open, return false on failure
153 $params = $wgKnownDBServers[$machineId];
154 $db = Database
::newFromParams( $params['server'], $params['user'], $params['password'],
155 $dbName, 1, DBO_IGNORE
);
158 if ( $db->isOpen() ) {
159 $index = $db->strencode( $index );
160 $res = $db->query( "SELECT blob_data FROM $dbName.$tblName WHERE blob_index='$index'", $fname );
161 $row = $db->fetchObject( $res );
162 $text = $row->text_data
;
167 # File locations are of the form file://<filename>, relative to the current directory
168 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
169 $filename = strstr( $location, 'file://' );
170 $text = @file_get_contents
( $matches[1] );
172 if ( $text !== false ) {
173 # Got text, now we need to interpret it
174 # The first line contains information about how to do this
175 $p = strpos( $text, '\n' );
176 $type = substr( $text, 0, $p );
177 $text = substr( $text, $p +
1 );
182 $text = gzinflate( $text );
185 $object = unserialize( $text );
186 $text = $object->getItem( $hash );
192 wfProfileOut( $fname );
196 # Note that getContent/loadContent may follow redirects if
197 # not told otherwise, and so may cause a change to mTitle.
199 # Return the text of this revision
200 function getContent( $noredir ) {
203 # Get variables from query string :P
204 $action = $wgRequest->getText( 'action', 'view' );
205 $section = $wgRequest->getText( 'section' );
207 $fname = 'Article::getContent';
208 wfProfileIn( $fname );
210 if ( 0 == $this->getID() ) {
211 if ( 'edit' == $action ) {
212 wfProfileOut( $fname );
213 return ''; # was "newarticletext", now moved above the box)
215 wfProfileOut( $fname );
216 return wfMsg( 'noarticletext' );
218 $this->loadContent( $noredir );
219 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
220 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
221 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
224 wfProfileOut( $fname );
225 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
227 if($action=='edit') {
229 if($section=='new') {
230 wfProfileOut( $fname );
234 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
235 # comments to be stripped as well)
236 $rv=$this->getSection($this->mContent
,$section);
237 wfProfileOut( $fname );
241 wfProfileOut( $fname );
242 return $this->mContent
;
247 # This function returns the text of a section, specified by a number ($section).
248 # A section is text under a heading like == Heading == or <h1>Heading</h1>, or
249 # the first section before any such heading (section 0).
251 # If a section contains subsections, these are also returned.
253 function getSection($text,$section) {
255 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
256 # comments to be stripped as well)
258 $parser=new Parser();
259 $parser->mOutputType
=OT_WIKI
;
260 $striptext=$parser->strip($text, $striparray, true);
262 # now that we can be sure that no pseudo-sections are in the source,
263 # split it up by section
266 '/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
268 PREG_SPLIT_DELIM_CAPTURE
);
272 $headline=$secs[$section*2-1];
273 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
276 # translate wiki heading into level
277 if(strpos($hlevel,'=')!==false) {
278 $hlevel=strlen($hlevel);
281 $rv=$headline. $secs[$section*2];
285 while(!empty($secs[$count*2-1]) && !$break) {
287 $subheadline=$secs[$count*2-1];
288 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
289 $subhlevel=$matches[1];
290 if(strpos($subhlevel,'=')!==false) {
291 $subhlevel=strlen($subhlevel);
293 if($subhlevel > $hlevel) {
294 $rv.=$subheadline.$secs[$count*2];
296 if($subhlevel <= $hlevel) {
303 # reinsert stripped tags
304 $rv=$parser->unstrip($rv,$striparray);
305 $rv=$parser->unstripNoWiki($rv,$striparray);
311 # Return an array of the columns of the "cur"-table
312 function &getCurContentFields() {
313 global $wgArticleCurContentFields;
314 if ( !$wgArticleCurContentFields ) {
315 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
316 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
318 return $wgArticleCurContentFields;
321 # Return an array of the columns of the "old"-table
322 function &getOldContentFields() {
323 global $wgArticleOldContentFields;
324 if ( !$wgArticleOldContentFields ) {
325 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
326 'old_user','old_user_text','old_comment','old_flags' );
328 return $wgArticleOldContentFields;
331 # Load the revision (including cur_text) into this object
332 function loadContent( $noredir = false ) {
333 global $wgOut, $wgMwRedir, $wgRequest;
335 $dbr =& wfGetDB( DB_SLAVE
);
337 $oldid = $wgRequest->getVal( 'oldid' );
338 $redirect = $wgRequest->getVal( 'redirect' );
340 if ( $this->mContentLoaded
) return;
341 $fname = 'Article::loadContent';
343 # Pre-fill content with error message so that if something
344 # fails we'll have something telling us what we intended.
346 $t = $this->mTitle
->getPrefixedText();
347 if ( isset( $oldid ) ) {
348 $oldid = IntVal( $oldid );
349 $t .= ",oldid={$oldid}";
351 if ( isset( $redirect ) ) {
352 $redirect = ($redirect == 'no') ?
'no' : 'yes';
353 $t .= ",redirect={$redirect}";
355 $this->mContent
= wfMsg( 'missingarticle', $t );
357 if ( ! $oldid ) { # Retrieve current version
358 $id = $this->getID();
359 if ( 0 == $id ) return;
361 $s = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname );
362 if ( $s === false ) {
366 # If we got a redirect, follow it (unless we've been told
367 # not to by either the function parameter or the query
368 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
369 $rt = Title
::newFromRedirect( $s->cur_text
);
370 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
371 # Gotta hand redirects to special pages differently:
372 # Fill the HTTP response "Location" header and ignore
373 # the rest of the page we're on.
375 if ( $rt->getInterwiki() != '' ) {
376 $wgOut->redirect( $rt->getFullURL() ) ;
379 if ( $rt->getNamespace() == NS_SPECIAL
) {
380 $wgOut->redirect( $rt->getFullURL() );
383 $rid = $rt->getArticleID();
385 $redirRow = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $rid ), $fname );
387 if ( $redirRow !== false ) {
388 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
396 $this->mContent
= $s->cur_text
;
397 $this->mUser
= $s->cur_user
;
398 $this->mUserText
= $s->cur_user_text
;
399 $this->mComment
= $s->cur_comment
;
400 $this->mCounter
= $s->cur_counter
;
401 $this->mTimestamp
= $s->cur_timestamp
;
402 $this->mTouched
= $s->cur_touched
;
403 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
404 $this->mTitle
->mRestrictionsLoaded
= true;
405 } else { # oldid set, retrieve historical version
406 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ), $fname );
407 if ( $s === false ) {
411 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
412 $this->mTitle
->getDBkey() != $s->old_title
) {
413 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
414 $this->mTitle
= $oldTitle;
415 $wgTitle = $oldTitle;
417 $this->mContent
= Article
::getRevisionText( $s );
418 $this->mUser
= $s->old_user
;
419 $this->mUserText
= $s->old_user_text
;
420 $this->mComment
= $s->old_comment
;
422 $this->mTimestamp
= $s->old_timestamp
;
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 ) {
433 if ( $this->mContentLoaded
) {
434 return $this->mContent
;
436 $this->mContent
= false;
438 $fname = 'Article::getContentWithout';
439 $dbr =& wfGetDB( DB_SLAVE
);
441 if ( ! $oldid ) { # Retrieve current version
442 $id = $this->getID();
447 $s = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname );
448 if ( $s === false ) {
452 # If we got a redirect, follow it (unless we've been told
453 # not to by either the function parameter or the query
455 $rt = Title
::newFromRedirect( $s->cur_text
);
456 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
457 $rid = $rt->getArticleID();
459 $redirRow = $dbr->getArray( 'cur', $this->getCurContentFields(), array( 'cur_id' => $rid ), $fname );
461 if ( $redirRow !== false ) {
462 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
470 $this->mContent
= $s->cur_text
;
471 $this->mUser
= $s->cur_user
;
472 $this->mUserText
= $s->cur_user_text
;
473 $this->mComment
= $s->cur_comment
;
474 $this->mCounter
= $s->cur_counter
;
475 $this->mTimestamp
= $s->cur_timestamp
;
476 $this->mTouched
= $s->cur_touched
;
477 $this->mTitle
->mRestrictions
= explode( ",", trim( $s->cur_restrictions
) );
478 $this->mTitle
->mRestrictionsLoaded
= true;
479 } else { # oldid set, retrieve historical version
480 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ) );
481 if ( $s === false ) {
484 $this->mContent
= Article
::getRevisionText( $s );
485 $this->mUser
= $s->old_user
;
486 $this->mUserText
= $s->old_user_text
;
487 $this->mComment
= $s->old_comment
;
489 $this->mTimestamp
= $s->old_timestamp
;
491 $this->mContentLoaded
= true;
492 return $this->mContent
;
496 if( $this->mTitle
) {
497 return $this->mTitle
->getArticleID();
503 function getCount() {
504 if ( -1 == $this->mCounter
) {
505 $id = $this->getID();
506 $dbr =& wfGetDB( DB_SLAVE
);
507 $this->mCounter
= $dbr->getField( 'cur', 'cur_counter', "cur_id={$id}" );
509 return $this->mCounter
;
512 # Would the given text make this article a "good" article (i.e.,
513 # suitable for including in the article count)?
514 function isCountable( $text ) {
515 global $wgUseCommaCount, $wgMwRedir;
517 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
518 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
519 $token = ($wgUseCommaCount ?
',' : '[[' );
520 if ( false === strstr( $text, $token ) ) { return 0; }
524 # Loads everything from cur except cur_text
525 # This isn't necessary for all uses, so it's only done if needed.
526 /* private */ function loadLastEdit() {
528 if ( -1 != $this->mUser
) return;
530 $fname = 'Article::loadLastEdit';
532 $dbr =& wfGetDB( DB_SLAVE
);
533 $s = $dbr->getArray( 'cur',
534 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
535 array( 'cur_id' => $this->getID() ), $fname );
537 if ( $s !== false ) {
538 $this->mUser
= $s->cur_user
;
539 $this->mUserText
= $s->cur_user_text
;
540 $this->mTimestamp
= $s->cur_timestamp
;
541 $this->mComment
= $s->cur_comment
;
542 $this->mMinorEdit
= $s->cur_minor_edit
;
546 function getTimestamp() {
547 $this->loadLastEdit();
548 return $this->mTimestamp
;
552 $this->loadLastEdit();
556 function getUserText() {
557 $this->loadLastEdit();
558 return $this->mUserText
;
561 function getComment() {
562 $this->loadLastEdit();
563 return $this->mComment
;
566 function getMinorEdit() {
567 $this->loadLastEdit();
568 return $this->mMinorEdit
;
571 function getContributors($limit = 0, $offset = 0) {
572 $fname = 'Article::getContributors';
574 # XXX: this is expensive; cache this info somewhere.
576 $title = $this->mTitle
;
578 $dbr =& wfGetDB( DB_SLAVE
);
579 $oldTable = $dbr->tableName( 'old' );
580 $userTable = $dbr->tableName( 'user' );
581 $encDBkey = $dbr->strencode( $title->getDBkey() );
582 $ns = $title->getNamespace();
583 $user = $this->getUser();
585 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
586 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
587 WHERE old_namespace = $user
588 AND old_title = $encDBkey
589 AND old_user != $user
591 ORDER BY timestamp DESC";
593 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
595 $res = $dbr->query($sql, $fname);
597 while ( $line = $dbr->fetchObject( $res ) ) {
598 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
601 $dbr->freeResult($res);
605 # This is the default action of the script: just view the page of
609 global $wgUser, $wgOut, $wgLang, $wgRequest, $wgMwRedir, $wgOnlySysopsCanPatrol;
610 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
611 $sk = $wgUser->getSkin();
613 $fname = 'Article::view';
614 wfProfileIn( $fname );
616 # Get variables from query string
617 $oldid = $wgRequest->getVal( 'oldid' );
618 $diff = $wgRequest->getVal( 'diff' );
619 $rcid = $wgRequest->getVal( 'rcid' );
621 $wgOut->setArticleFlag( true );
622 $wgOut->setRobotpolicy( 'index,follow' );
624 # If we got diff and oldid in the query, we want to see a
625 # diff page instead of the article.
627 if ( !is_null( $diff ) ) {
628 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
629 $de = new DifferenceEngine( intval($oldid), intval($diff), intval($rcid) );
631 wfProfileOut( $fname );
633 # Run view updates for current revision only
634 $this->viewUpdates();
639 if ( empty( $oldid ) && $this->checkTouched() ) {
640 if( $wgOut->checkLastModified( $this->mTouched
) ){
642 } else if ( $this->tryFileCache() ) {
643 # tell wgOut that output is taken care of
645 $this->viewUpdates();
650 # Should the parser cache be used?
651 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
659 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
664 if ( !$outputDone ) {
665 $text = $this->getContent( false ); # May change mTitle by following a redirect
667 # Another whitelist check in case oldid or redirects are altering the title
668 if ( !$this->mTitle
->userCanRead() ) {
669 $wgOut->loginToUse();
675 # We're looking at an old revision
677 if ( !empty( $oldid ) ) {
678 $this->setOldSubtitle();
679 $wgOut->setRobotpolicy( 'noindex,follow' );
681 if ( '' != $this->mRedirectedFrom
) {
682 $sk = $wgUser->getSkin();
683 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
685 $s = wfMsg( 'redirectedfrom', $redir );
686 $wgOut->setSubtitle( $s );
688 # Can't cache redirects
692 # wrap user css and user js in pre and don't parse
693 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
695 $this->mTitle
->getNamespace() == NS_USER
&&
696 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
698 $wgOut->addWikiText( wfMsg('clearyourcache'));
699 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
700 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
702 $imageUrl = "$wgStylePath/images/redirect.png";
703 $targetUrl = $rt->escapeLocalURL();
704 $titleText = htmlspecialchars( $rt->getPrefixedText() );
705 $link = $sk->makeLinkObj( $rt );
706 $wgOut->addHTML( "<img valign=\"center\" src=\"$imageUrl\">" .
707 "<span class=\"redirectText\">$link</span>" );
708 } else if ( $pcache ) {
709 # Display content and save to parser cache
710 $wgOut->addWikiText( $text, true, $this );
712 # Display content, don't attempt to save to parser cache
713 $wgOut->addWikiText( $text );
716 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
718 # If we have been passed an &rcid= parameter, we want to give the user a
719 # chance to mark this new article as patrolled.
720 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
721 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
723 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
724 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
725 "action=markpatrolled&rcid={$rcid}" )
729 # Put link titles into the link cache
730 $wgOut->replaceLinkHolders();
731 # Add link titles as META keywords
732 $wgOut->addMetaTags() ;
734 $this->viewUpdates();
735 wfProfileOut( $fname );
738 # Theoretically we could defer these whole insert and update
739 # functions for after display, but that's taking a big leap
740 # of faith, and we want to be able to report database
741 # errors at some point.
743 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
744 global $wgOut, $wgUser, $wgMwRedir;
745 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
747 $fname = 'Article::insertNewArticle';
749 $this->mCountAdjustment
= $this->isCountable( $text );
751 $ns = $this->mTitle
->getNamespace();
752 $ttl = $this->mTitle
->getDBkey();
753 $text = $this->preSaveTransform( $text );
754 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
757 $now = wfTimestampNow();
758 $won = wfInvertTimestamp( $now );
760 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
761 $dbw =& wfGetDB( DB_MASTER
);
763 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
765 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
767 $dbw->insertArray( 'cur', array(
769 'cur_namespace' => $ns,
772 'cur_comment' => $summary,
773 'cur_user' => $wgUser->getID(),
774 'cur_timestamp' => $now,
775 'cur_minor_edit' => $isminor,
777 'cur_restrictions' => '',
778 'cur_user_text' => $wgUser->getName(),
779 'cur_is_redirect' => $redir,
781 'cur_random' => $rand,
782 'cur_touched' => $now,
783 'inverse_timestamp' => $won,
786 $newid = $dbw->insertId();
787 $this->mTitle
->resetArticleID( $newid );
789 Article
::onArticleCreate( $this->mTitle
);
790 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
793 if(!$this->mTitle
->userIsWatching()) $this->watch();
795 if ( $this->mTitle
->userIsWatching() ) {
800 # The talk page isn't in the regular link tables, so we need to update manually:
801 $talkns = $ns ^
1; # talk -> normal; normal -> talk
802 $dbw->updateArray( 'cur', array( 'cur_touched' => $now ), array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
804 # standard deferred updates
805 $this->editUpdates( $text );
807 $this->showArticle( $text, wfMsg( 'newarticle' ) );
811 /* Side effects: loads last edit */
812 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '') {
813 $this->loadLastEdit();
814 $oldtext = $this->getContent( true );
815 if ($section != '') {
816 if($section=='new') {
817 if($summary) $subject="== {$summary} ==\n\n";
818 $text=$oldtext."\n\n".$subject.$text;
821 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
822 # comments to be stripped as well)
824 $parser=new Parser();
825 $parser->mOutputType
=OT_WIKI
;
826 $oldtext=$parser->strip($oldtext, $striparray, true);
828 # now that we can be sure that no pseudo-sections are in the source,
830 # Unfortunately we can't simply do a preg_replace because that might
831 # replace the wrong section, so we have to use the section counter instead
832 $secs=preg_split('/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
833 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
834 $secs[$section*2]=$text."\n\n"; // replace with edited
836 # section 0 is top (intro) section
839 # headline of old section - we need to go through this section
840 # to determine if there are any subsections that now need to
841 # be erased, as the mother section has been replaced with
842 # the text of all subsections.
843 $headline=$secs[$section*2-1];
844 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
847 # determine headline level for wikimarkup headings
848 if(strpos($hlevel,'=')!==false) {
849 $hlevel=strlen($hlevel);
852 $secs[$section*2-1]=''; // erase old headline
855 while(!empty($secs[$count*2-1]) && !$break) {
857 $subheadline=$secs[$count*2-1];
859 '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
860 $subhlevel=$matches[1];
861 if(strpos($subhlevel,'=')!==false) {
862 $subhlevel=strlen($subhlevel);
864 if($subhlevel > $hlevel) {
865 // erase old subsections
866 $secs[$count*2-1]='';
869 if($subhlevel <= $hlevel) {
877 $text=join('',$secs);
878 # reinsert the stuff that we stripped out earlier
879 $text=$parser->unstrip($text,$striparray);
880 $text=$parser->unstripNoWiki($text,$striparray);
887 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
888 global $wgOut, $wgUser;
889 global $wgDBtransactions, $wgMwRedir;
890 global $wgUseSquid, $wgInternalServer;
892 $fname = 'Article::updateArticle';
895 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
896 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
897 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
899 $text = $m[1] . "\n"; # Remove all content but redirect
903 $text = $this->preSaveTransform( $text );
904 $dbw =& wfGetDB( DB_MASTER
);
906 # Update article, but only if changed.
908 # It's important that we either rollback or complete, otherwise an attacker could
909 # overwrite cur entries by sending precisely timed user aborts. Random bored users
910 # could conceivably have the same effect, especially if cur is locked for long periods.
911 if( $wgDBtransactions ) {
912 $dbw->query( 'BEGIN', $fname );
914 $userAbort = ignore_user_abort( true );
917 $oldtext = $this->getContent( true );
919 if ( 0 != strcmp( $text, $oldtext ) ) {
920 $this->mCountAdjustment
= $this->isCountable( $text )
921 - $this->isCountable( $oldtext );
922 $now = wfTimestampNow();
923 $won = wfInvertTimestamp( $now );
925 # First update the cur row
926 $dbw->updateArray( 'cur',
929 'cur_comment' => $summary,
930 'cur_minor_edit' => $me2,
931 'cur_user' => $wgUser->getID(),
932 'cur_timestamp' => $now,
933 'cur_user_text' => $wgUser->getName(),
934 'cur_is_redirect' => $redir,
936 'cur_touched' => $now,
937 'inverse_timestamp' => $won
938 ), array( /* WHERE */
939 'cur_id' => $this->getID(),
940 'cur_timestamp' => $this->getTimestamp()
944 if( $dbw->affectedRows() == 0 ) {
945 /* Belated edit conflict! Run away!! */
948 # Now insert the previous revision into old
950 # This overwrites $oldtext if revision compression is on
951 $flags = Article
::compressRevisionText( $oldtext );
953 $dbw->insertArray( 'old',
955 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
956 'old_namespace' => $this->mTitle
->getNamespace(),
957 'old_title' => $this->mTitle
->getDBkey(),
958 'old_text' => $oldtext,
959 'old_comment' => $this->getComment(),
960 'old_user' => $this->getUser(),
961 'old_user_text' => $this->getUserText(),
962 'old_timestamp' => $this->getTimestamp(),
963 'old_minor_edit' => $me1,
964 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
965 'old_flags' => $flags,
969 $oldid = $dbw->insertId();
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
);
978 if( $wgDBtransactions ) {
979 $dbw->query( 'COMMIT', $fname );
981 ignore_user_abort( $userAbort );
986 if (!$this->mTitle
->userIsWatching()) $this->watch();
988 if ( $this->mTitle
->userIsWatching() ) {
992 # standard deferred updates
993 $this->editUpdates( $text );
998 # Purge all articles linking here
999 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1000 $titles = $this->mTitle
->getLinksTo();
1001 Title
::touchArray( $titles );
1002 if ( $wgUseSquid ) {
1003 foreach ( $titles as $title ) {
1004 $urls[] = $title->getInternalURL();
1010 if ( $wgUseSquid ) {
1011 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1012 $u = new SquidUpdate( $urls );
1016 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1021 # After we've either updated or inserted the article, update
1022 # the link tables and redirect to the new page.
1024 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1025 global $wgOut, $wgUser, $wgLinkCache;
1028 $wgLinkCache = new LinkCache();
1030 $wgLinkCache->forUpdate( true );
1032 # Get old version of link table to allow incremental link updates
1033 $wgLinkCache->preFill( $this->mTitle
);
1034 $wgLinkCache->clear();
1036 # Parse the text and replace links with placeholders
1037 $wgOut = new OutputPage();
1038 $wgOut->addWikiText( $text );
1040 # Look up the links in the DB and add them to the link cache
1041 $wgOut->replaceLinkHolders( RLH_FOR_UPDATE
);
1043 if( $wgMwRedir->matchStart( $text ) )
1047 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1052 function validate () {
1053 global $wgOut, $wgUseValidation;
1054 if( $wgUseValidation ) {
1055 $wgOut->setPagetitle( wfMsg( 'validate' ) . ": " . $this->mTitle
->getPrefixedText() );
1056 $wgOut->setRobotpolicy( 'noindex,follow' );
1057 if( $this->mTitle
->getNamespace() != 0 ) {
1058 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1061 $v = new Validation
;
1062 $v->validate_form( $this->mTitle
->getDBkey() );
1064 $wgOut->errorpage( "nosuchaction", "nosuchactiontext" );
1068 # Mark this particular edit as patrolled
1069 function markpatrolled() {
1070 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1071 $wgOut->setRobotpolicy( 'noindex,follow' );
1073 if ( !$wgUseRCPatrol )
1075 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1078 if ( $wgUser->getID() == 0 )
1080 $wgOut->loginToUse();
1083 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1085 $wgOut->sysopRequired();
1088 $rcid = $wgRequest->getVal( 'rcid' );
1089 if ( !is_null ( $rcid ) )
1091 RecentChange
::markPatrolled( $rcid );
1092 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1093 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1094 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1098 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1103 # Add this page to my watchlist
1105 function watch( $add = true ) {
1106 global $wgUser, $wgOut, $wgLang;
1107 global $wgDeferredUpdateList;
1109 if ( 0 == $wgUser->getID() ) {
1110 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1113 if ( wfReadOnly() ) {
1114 $wgOut->readOnlyPage();
1118 $wgUser->addWatch( $this->mTitle
);
1120 $wgUser->removeWatch( $this->mTitle
);
1122 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1123 $wgOut->setRobotpolicy( 'noindex,follow' );
1125 $sk = $wgUser->getSkin() ;
1126 $link = $this->mTitle
->getPrefixedText();
1129 $text = wfMsg( 'addedwatchtext', $link );
1131 $text = wfMsg( 'removedwatchtext', $link );
1132 $wgOut->addWikiText( $text );
1134 $up = new UserUpdate();
1135 array_push( $wgDeferredUpdateList, $up );
1137 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1140 function unwatch() {
1141 $this->watch( false );
1146 function protect( $limit = 'sysop' ) {
1147 global $wgUser, $wgOut, $wgRequest;
1149 if ( ! $wgUser->isSysop() ) {
1150 $wgOut->sysopRequired();
1153 if ( wfReadOnly() ) {
1154 $wgOut->readOnlyPage();
1157 $id = $this->mTitle
->getArticleID();
1159 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1163 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1164 $reason = $wgRequest->getText( 'wpReasonProtect' );
1167 $dbw =& wfGetDB( DB_MASTER
);
1168 $dbw->updateArray( 'cur',
1170 'cur_touched' => wfTimestampNow(),
1171 'cur_restrictions' => (string)$limit
1172 ), array( /* WHERE */
1174 ), 'Article::protect'
1177 $log = new LogPage( wfMsg( 'protectlogpage' ), wfMsg( 'protectlogtext' ) );
1178 if ( $limit === "" ) {
1179 $log->addEntry( wfMsg( 'unprotectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1181 $log->addEntry( wfMsg( 'protectedarticle', $this->mTitle
->getPrefixedText() ), $reason );
1183 $wgOut->redirect( $this->mTitle
->getFullURL() );
1186 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1187 return $this->confirmProtect( '', $reason, $limit );
1191 # Output protection confirmation dialog
1193 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1196 wfDebug( "Article::confirmProtect\n" );
1198 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1199 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1204 if ( $limit === '' ) {
1205 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1206 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1207 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1208 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1209 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1210 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1212 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1213 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1214 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1215 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1216 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1217 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1220 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1223 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1227 <label for='wpReasonProtect'>{$protcom}:</label>
1230 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1238 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1241 <label for='wpConfirmProtect'>{$check}</label>
1247 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1253 $wgOut->returnToMain( false );
1256 function unprotect() {
1257 return $this->protect( '' );
1260 # UI entry point for page deletion
1263 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1264 $fname = 'Article::delete';
1265 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1266 $reason = $wgRequest->getText( 'wpReason' );
1268 # This code desperately needs to be totally rewritten
1271 if ( ( ! $wgUser->isSysop() ) ) {
1272 $wgOut->sysopRequired();
1275 if ( wfReadOnly() ) {
1276 $wgOut->readOnlyPage();
1280 # Better double-check that it hasn't been deleted yet!
1281 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1282 if ( ( '' == trim( $this->mTitle
->getText() ) )
1283 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1284 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1289 $this->doDelete( $reason );
1293 # determine whether this page has earlier revisions
1294 # and insert a warning if it does
1295 # we select the text because it might be useful below
1296 $dbr =& wfGetDB( DB_SLAVE
);
1297 $ns = $this->mTitle
->getNamespace();
1298 $title = $this->mTitle
->getDBkey();
1299 $old = $dbr->getArray( 'old',
1300 array( 'old_text', 'old_flags' ),
1302 'old_namespace' => $ns,
1303 'old_title' => $title,
1304 ), $fname, array( 'ORDER BY' => 'inverse_timestamp' )
1307 if( $old !== false && !$confirm ) {
1308 $skin=$wgUser->getSkin();
1309 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1310 $wgOut->addHTML( $skin->historyLink() .'</b>');
1314 $s = $dbr->getArray( 'cur',
1315 array( 'cur_text' ),
1317 'cur_namespace' => $ns,
1318 'cur_title' => $title,
1322 if( $s !== false ) {
1323 # if this is a mini-text, we can paste part of it into the deletion reason
1325 #if this is empty, an earlier revision may contain "useful" text
1327 if($s->cur_text
!= '') {
1331 $text = Article
::getRevisionText( $old );
1337 $length=strlen($text);
1339 # this should not happen, since it is not possible to store an empty, new
1340 # page. Let's insert a standard text in case it does, though
1341 if($length == 0 && $reason === '') {
1342 $reason = wfMsg('exblank');
1345 if($length < 500 && $reason === '') {
1347 # comment field=255, let's grep the first 150 to have some user
1349 $text=substr($text,0,150);
1350 # let's strip out newlines and HTML tags
1351 $text=preg_replace('/\"/',"'",$text);
1352 $text=preg_replace('/\</','<',$text);
1353 $text=preg_replace('/\>/','>',$text);
1354 $text=preg_replace("/[\n\r]/",'',$text);
1356 $reason=wfMsg('excontent'). " '".$text;
1358 $reason=wfMsg('exbeforeblank') . " '".$text;
1360 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1365 return $this->confirmDelete( '', $reason );
1368 # Output deletion confirmation dialog
1370 function confirmDelete( $par, $reason ) {
1373 wfDebug( "Article::confirmDelete\n" );
1375 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1376 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1377 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1378 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1380 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1382 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1383 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1384 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1387 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1391 <label for='wpReason'>{$delcom}:</label>
1394 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1402 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1405 <label for='wpConfirm'>{$check}</label>
1411 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1417 $wgOut->returnToMain( false );
1421 # Perform a deletion and output success or failure messages
1423 function doDelete( $reason ) {
1424 global $wgOut, $wgUser, $wgLang;
1425 $fname = 'Article::doDelete';
1426 wfDebug( "$fname\n" );
1428 if ( $this->doDeleteArticle( $reason ) ) {
1429 $deleted = $this->mTitle
->getPrefixedText();
1431 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1432 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1434 $sk = $wgUser->getSkin();
1435 $loglink = $sk->makeKnownLink( $wgLang->getNsText( NS_WIKIPEDIA
) .
1436 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1438 $text = wfMsg( "deletedtext", $deleted, $loglink );
1440 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1441 $wgOut->returnToMain( false );
1443 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1447 # Back-end article deletion
1448 # Deletes the article with database consistency, writes logs, purges caches
1450 function doDeleteArticle( $reason ) {
1451 global $wgUser, $wgLang;
1452 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1454 $fname = 'Article::doDeleteArticle';
1455 wfDebug( $fname."\n" );
1457 $dbw =& wfGetDB( DB_MASTER
);
1458 $ns = $this->mTitle
->getNamespace();
1459 $t = $this->mTitle
->getDBkey();
1460 $id = $this->mTitle
->getArticleID();
1462 if ( $t == '' ||
$id == 0 ) {
1466 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1467 array_push( $wgDeferredUpdateList, $u );
1469 $linksTo = $this->mTitle
->getLinksTo();
1472 if ( $wgUseSquid ) {
1474 $this->mTitle
->getInternalURL(),
1475 $this->mTitle
->getInternalURL( 'history' )
1477 foreach ( $linksTo as $linkTo ) {
1478 $urls[] = $linkTo->getInternalURL();
1481 $u = new SquidUpdate( $urls );
1482 array_push( $wgDeferredUpdateList, $u );
1486 # Client and file cache invalidation
1487 Title
::touchArray( $linksTo );
1489 # Move article and history to the "archive" table
1490 $archiveTable = $dbw->tableName( 'archive' );
1491 $oldTable = $dbw->tableName( 'old' );
1492 $curTable = $dbw->tableName( 'cur' );
1493 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1494 $linksTable = $dbw->tableName( 'links' );
1495 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1497 $dbw->insertSelect( 'archive', 'cur',
1499 'ar_namespace' => 'cur_namespace',
1500 'ar_title' => 'cur_title',
1501 'ar_text' => 'cur_text',
1502 'ar_comment' => 'cur_comment',
1503 'ar_user' => 'cur_user',
1504 'ar_user_text' => 'cur_user_text',
1505 'ar_timestamp' => 'cur_timestamp',
1506 'ar_minor_edit' => 'cur_minor_edit',
1509 'cur_namespace' => $ns,
1514 $dbw->insertSelect( 'archive', 'old',
1516 'ar_namespace' => 'old_namespace',
1517 'ar_title' => 'old_title',
1518 'ar_text' => 'old_text',
1519 'ar_comment' => 'old_comment',
1520 'ar_user' => 'old_user',
1521 'ar_user_text' => 'old_user_text',
1522 'ar_timestamp' => 'old_timestamp',
1523 'ar_minor_edit' => 'old_minor_edit',
1524 'ar_flags' => 'old_flags'
1526 'old_namespace' => $ns,
1531 # Now that it's safely backed up, delete it
1533 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1534 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1535 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1537 # Finally, clean up the link tables
1538 $t = $this->mTitle
->getPrefixedDBkey();
1540 Article
::onArticleDelete( $this->mTitle
);
1542 # Insert broken links
1543 $brokenLinks = array();
1544 foreach ( $linksTo as $titleObj ) {
1545 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1546 $linkID = $titleObj->getArticleID();
1547 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1549 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1552 $dbw->delete( 'links', array( 'l_to' => $id ) );
1553 $dbw->delete( 'links', array( 'l_from' => $id ) );
1554 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1555 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1556 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1559 $log = new LogPage( wfMsg( 'dellogpage' ), wfMsg( 'dellogpagetext' ) );
1560 $art = $this->mTitle
->getPrefixedText();
1561 $log->addEntry( wfMsg( 'deletedarticle', $art ), $reason );
1563 # Clear the cached article id so the interface doesn't act like we exist
1564 $this->mTitle
->resetArticleID( 0 );
1565 $this->mTitle
->mArticleID
= 0;
1569 function rollback() {
1570 global $wgUser, $wgLang, $wgOut, $wgRequest;
1571 $fname = "Article::rollback";
1573 if ( ! $wgUser->isSysop() ) {
1574 $wgOut->sysopRequired();
1577 if ( wfReadOnly() ) {
1578 $wgOut->readOnlyPage( $this->getContent( true ) );
1581 $dbw =& wfGetDB( DB_MASTER
);
1583 # Enhanced rollback, marks edits rc_bot=1
1584 $bot = $wgRequest->getBool( 'bot' );
1586 # Replace all this user's current edits with the next one down
1587 $tt = $this->mTitle
->getDBKey();
1588 $n = $this->mTitle
->getNamespace();
1590 # Get the last editor, lock table exclusively
1591 $s = $dbw->getArray( 'cur',
1592 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1593 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1594 $fname, 'FOR UPDATE'
1596 if( $s === false ) {
1598 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1601 $ut = $dbw->strencode( $s->cur_user_text
);
1602 $uid = $s->cur_user
;
1605 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1606 if( $from != $s->cur_user_text
) {
1607 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1608 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1609 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1610 htmlspecialchars( $from ),
1611 htmlspecialchars( $s->cur_user_text
) ) );
1612 if($s->cur_comment
!= '') {
1614 wfMsg('editcomment',
1615 htmlspecialchars( $s->cur_comment
) ) );
1620 # Get the last edit not by this guy
1621 $s = $dbw->getArray( 'old',
1622 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1624 'old_namespace' => $n,
1626 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1627 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1629 if( $s === false ) {
1631 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1632 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1637 # Mark all reverted edits as bot
1638 $dbw->updateArray( 'recentchanges',
1641 ), array( /* WHERE */
1643 "rc_timestamp > '{$s->old_timestamp}'",
1649 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1650 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1651 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1652 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1653 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1654 Article
::onArticleEdit( $this->mTitle
);
1655 $wgOut->returnToMain( false );
1659 # Do standard deferred updates after page view
1661 /* private */ function viewUpdates() {
1662 global $wgDeferredUpdateList;
1663 if ( 0 != $this->getID() ) {
1664 global $wgDisableCounters;
1665 if( !$wgDisableCounters ) {
1666 Article
::incViewCount( $this->getID() );
1667 $u = new SiteStatsUpdate( 1, 0, 0 );
1668 array_push( $wgDeferredUpdateList, $u );
1671 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1672 $this->mTitle
->getDBkey() );
1673 array_push( $wgDeferredUpdateList, $u );
1676 # Do standard deferred updates after page edit.
1677 # Every 1000th edit, prune the recent changes table.
1679 /* private */ function editUpdates( $text ) {
1680 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1681 global $wgMessageCache;
1684 if ( 0 == mt_rand( 0, 999 ) ) {
1685 $dbw =& wfGetDB( DB_MASTER
);
1686 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1687 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1688 $dbw->query( $sql );
1690 $id = $this->getID();
1691 $title = $this->mTitle
->getPrefixedDBkey();
1692 $shortTitle = $this->mTitle
->getDBkey();
1694 $adj = $this->mCountAdjustment
;
1697 $u = new LinksUpdate( $id, $title );
1698 array_push( $wgDeferredUpdateList, $u );
1699 $u = new SiteStatsUpdate( 0, 1, $adj );
1700 array_push( $wgDeferredUpdateList, $u );
1701 $u = new SearchUpdate( $id, $title, $text );
1702 array_push( $wgDeferredUpdateList, $u );
1704 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1705 array_push( $wgDeferredUpdateList, $u );
1707 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1708 $wgMessageCache->replace( $shortTitle, $text );
1713 /* private */ function setOldSubtitle() {
1714 global $wgLang, $wgOut;
1716 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1717 $r = wfMsg( 'revisionasof', $td );
1718 $wgOut->setSubtitle( "({$r})" );
1721 # This function is called right before saving the wikitext,
1722 # so we can do things like signatures and links-in-context.
1724 function preSaveTransform( $text ) {
1725 global $wgParser, $wgUser;
1726 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1729 /* Caching functions */
1731 # checkLastModified returns true if it has taken care of all
1732 # output to the client that is necessary for this request.
1733 # (that is, it has sent a cached version of the page)
1734 function tryFileCache() {
1735 static $called = false;
1737 wfDebug( " tryFileCache() -- called twice!?\n" );
1741 if($this->isFileCacheable()) {
1742 $touched = $this->mTouched
;
1743 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1744 # Expire the main page quicker
1745 $expire = wfUnix2Timestamp( time() - 3600 );
1746 $touched = max( $expire, $touched );
1748 $cache = new CacheManager( $this->mTitle
);
1749 if($cache->isFileCacheGood( $touched )) {
1751 wfDebug( " tryFileCache() - about to load\n" );
1752 $cache->loadFromFileCache();
1755 wfDebug( " tryFileCache() - starting buffer\n" );
1756 ob_start( array(&$cache, 'saveToFileCache' ) );
1759 wfDebug( " tryFileCache() - not cacheable\n" );
1763 function isFileCacheable() {
1764 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1765 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1767 return $wgUseFileCache
1768 and (!$wgShowIPinHeader)
1769 and ($this->getID() != 0)
1770 and ($wgUser->getId() == 0)
1771 and (!$wgUser->getNewtalk())
1772 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1773 and (empty( $action ) ||
$action == 'view')
1774 and (!isset($oldid))
1776 and (!isset($redirect))
1777 and (!isset($printable))
1778 and (!$this->mRedirectedFrom
);
1781 # Loads cur_touched and returns a value indicating if it should be used
1782 function checkTouched() {
1783 $fname = 'Article::checkTouched';
1785 $id = $this->getID();
1786 $dbr =& wfGetDB( DB_SLAVE
);
1787 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1788 array( 'cur_id' => $id ), $fname );
1789 if( $s !== false ) {
1790 $this->mTouched
= $s->cur_touched
;
1791 return !$s->cur_is_redirect
;
1797 # Edit an article without doing all that other stuff
1798 function quickEdit( $text, $comment = '', $minor = 0 ) {
1799 global $wgUser, $wgMwRedir;
1800 $fname = 'Article::quickEdit';
1801 wfProfileIn( $fname );
1803 $dbw =& wfGetDB( DB_MASTER
);
1804 $ns = $this->mTitle
->getNamespace();
1805 $dbkey = $this->mTitle
->getDBkey();
1806 $encDbKey = $dbw->strencode( $dbkey );
1807 $timestamp = wfTimestampNow();
1810 $dbw->insertSelect( 'old', 'cur',
1812 'old_namespace' => 'cur_namespace',
1813 'old_title' => 'cur_title',
1814 'old_text' => 'cur_text',
1815 'old_comment' => 'cur_comment',
1816 'old_user' => 'cur_user',
1817 'old_user_text' => 'cur_user_text',
1818 'old_timestamp' => 'cur_timestamp',
1819 'inverse_timestamp' => '99999999999999-cur_timestamp',
1821 'cur_namespace' => $ns,
1822 'cur_title' => $dbkey,
1826 # Use the affected row count to determine if the article is new
1827 $numRows = $dbw->affectedRows();
1829 # Make an array of fields to be inserted
1831 'cur_text' => $text,
1832 'cur_timestamp' => $timestamp,
1833 'cur_user' => $wgUser->getID(),
1834 'cur_user_text' => $wgUser->getName(),
1835 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1836 'cur_comment' => $comment,
1837 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ?
1 : 0,
1838 'cur_minor_edit' => intval($minor),
1839 'cur_touched' => $timestamp,
1844 $fields['cur_is_new'] = 0;
1845 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1847 # Insert new article
1848 $fields['cur_is_new'] = 1;
1849 $fields['cur_namespace'] = $ns;
1850 $fields['cur_title'] = $dbkey;
1851 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1852 $dbw->insertArray( 'cur', $fields, $fname );
1854 wfProfileOut( $fname );
1857 /* static */ function incViewCount( $id ) {
1858 $id = intval( $id );
1859 global $wgHitcounterUpdateFreq;
1861 $dbw =& wfGetDB( DB_MASTER
);
1862 $curTable = $dbw->tableName( 'cur' );
1863 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1864 $acchitsTable = $dbw->tableName( 'acchits' );
1866 if( $wgHitcounterUpdateFreq <= 1 ){ //
1867 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
1871 # Not important enough to warrant an error page in case of failure
1872 $oldignore = $dbw->ignoreErrors( true );
1874 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
1876 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
1877 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
1878 # Most of the time (or on SQL errors), skip row count check
1879 $dbw->ignoreErrors( $oldignore );
1883 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
1884 $row = $dbw->fetchObject( $res );
1885 $rown = intval( $row->n
);
1886 if( $rown >= $wgHitcounterUpdateFreq ){
1887 wfProfileIn( 'Article::incViewCount-collect' );
1888 $old_user_abort = ignore_user_abort( true );
1890 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
1891 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
1892 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
1894 $dbw->query("DELETE FROM $hitcounterTable");
1895 $dbw->query('UNLOCK TABLES');
1896 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
1897 'WHERE cur_id = hc_id');
1898 $dbw->query("DROP TABLE $acchitsTable");
1900 ignore_user_abort( $old_user_abort );
1901 wfProfileOut( 'Article::incViewCount-collect' );
1903 $dbw->ignoreErrors( $oldignore );
1906 # The onArticle*() functions are supposed to be a kind of hooks
1907 # which should be called whenever any of the specified actions
1910 # This is a good place to put code to clear caches, for instance.
1912 # This is called on page move and undelete, as well as edit
1913 /* static */ function onArticleCreate($title_obj) {
1914 global $wgUseSquid, $wgDeferredUpdateList;
1916 $titles = $title_obj->getBrokenLinksTo();
1919 if ( $wgUseSquid ) {
1920 $urls = $title_obj->getSquidURLs();
1921 foreach ( $titles as $linkTitle ) {
1922 $urls[] = $linkTitle->getInternalURL();
1924 $u = new SquidUpdate( $urls );
1925 array_push( $wgDeferredUpdateList, $u );
1928 # Clear persistent link cache
1929 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1932 /* static */ function onArticleDelete($title_obj) {
1933 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
1936 /* static */ function onArticleEdit($title_obj) {
1937 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
1941 # Info about this page
1944 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgAllowPageInfo;
1945 $fname = 'Article::info';
1947 if ( !$wgAllowPageInfo ) {
1948 $wgOut->errorpage( "nosuchaction", "nosuchactiontext" );
1952 $dbr =& wfGetDB( DB_SLAVE
);
1954 $basenamespace = $wgTitle->getNamespace() & (~
1);
1955 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
1956 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
1957 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
1958 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
1959 $wgOut->setPagetitle( $fullTitle );
1960 $wgOut->setSubtitle( wfMsg( "infosubtitle" ));
1962 # first, see if the page exists at all.
1963 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname );
1965 $wgOut->addHTML( wfMsg("noarticletext") );
1967 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname );
1968 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . "</li>" );
1969 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname );
1970 $wgOut->addHTML( "<li>" . wfMsg("numedits", $old +
1) . "</li>");
1972 # to find number of distinct authors, we need to do some
1973 # funny stuff because of the cur/old table split:
1974 # - first, find the name of the 'cur' author
1975 # - then, find the number of *other* authors in 'old'
1978 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname );
1980 # find number of 'old' authors excluding 'cur' author
1981 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
1982 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname ) +
1;
1984 # now for the Talk page ...
1985 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
1986 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
1989 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname );
1993 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname );
1994 $wgOut->addHTML( "<li>" . wfMsg("numtalkedits", $old +
1) . "</li>");
1996 $wgOut->addHTML( "<li>" . wfMsg("numauthors", $authors) . "</li>" );
2000 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname );
2001 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2002 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname );
2004 $wgOut->addHTML( "<li>" . wfMsg("numtalkauthors", $authors) . "</li></ul>" );