9 * Need the CacheManager to be loaded
11 require_once ( 'CacheManager.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
17 * Class representing a Wikipedia article and history.
19 * See design.doc for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
30 var $mContent, $mContentLoaded;
31 var $mUser, $mTimestamp, $mUserText;
32 var $mCounter, $mComment, $mCountAdjustment;
33 var $mMinorEdit, $mRedirectedFrom;
34 var $mTouched, $mFileCache, $mTitle;
40 * Constructor and clear the article
41 * @param mixed &$title
43 function Article( &$title ) {
44 $this->mTitle
=& $title;
53 $this->mContentLoaded
= false;
54 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
55 $this->mRedirectedFrom
= $this->mUserText
=
56 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
57 $this->mCountAdjustment
= 0;
58 $this->mTouched
= '19700101000000';
59 $this->mForUpdate
= false;
63 * Get revision text associated with an old or archive row
64 * $row is usually an object from wfFetchRow(), both the flags and the text
65 * field must be included
67 * @param integer $row Id of a row
68 * @param string $prefix table prefix (default 'old_')
69 * @return string $text|false the text requested
71 function getRevisionText( $row, $prefix = 'old_' ) {
73 $textField = $prefix . 'text';
74 $flagsField = $prefix . 'flags';
76 if( isset( $row->$flagsField ) ) {
77 $flags = explode( ',', $row->$flagsField );
82 if( isset( $row->$textField ) ) {
83 $text = $row->$textField;
88 if( in_array( 'gzip', $flags ) ) {
89 # Deal with optional compression of archived pages.
90 # This can be done periodically via maintenance/compressOld.php, and
91 # as pages are saved if $wgCompressRevisions is set.
92 $text = gzinflate( $text );
95 if( in_array( 'object', $flags ) ) {
96 # Generic compressed storage
97 $obj = unserialize( $text );
99 # Bugger, corrupted my test database by double-serializing
100 if ( !is_object( $obj ) ) {
101 $obj = unserialize( $obj );
104 $text = $obj->getText();
107 global $wgLegacyEncoding;
108 if( $wgLegacyEncoding && !in_array( 'utf-8', $flags ) ) {
109 # Old revisions kept around in a legacy encoding?
110 # Upconvert on demand.
111 global $wgInputEncoding, $wgContLang;
112 $text = $wgContLang->iconv( $wgLegacyEncoding, $wgInputEncoding, $text );
118 * If $wgCompressRevisions is enabled, we will compress data.
119 * The input string is modified in place.
120 * Return value is the flags field: contains 'gzip' if the
121 * data is compressed, and 'utf-8' if we're saving in UTF-8
125 * @param mixed $text reference to a text
128 function compressRevisionText( &$text ) {
129 global $wgCompressRevisions, $wgUseLatin1;
131 if( !$wgUseLatin1 ) {
132 # Revisions not marked this way will be converted
133 # on load if $wgLegacyCharset is set in the future.
136 if( $wgCompressRevisions ) {
137 if( function_exists( 'gzdeflate' ) ) {
138 $text = gzdeflate( $text );
141 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
144 return implode( ',', $flags );
148 * Note that getContent/loadContent may follow redirects if
149 * not told otherwise, and so may cause a change to mTitle.
152 * @return Return the text of this revision
154 function getContent( $noredir ) {
157 # Get variables from query string :P
158 $action = $wgRequest->getText( 'action', 'view' );
159 $section = $wgRequest->getText( 'section' );
161 $fname = 'Article::getContent';
162 wfProfileIn( $fname );
164 if ( 0 == $this->getID() ) {
165 if ( 'edit' == $action ) {
166 wfProfileOut( $fname );
167 return ''; # was "newarticletext", now moved above the box)
169 wfProfileOut( $fname );
170 return wfMsg( 'noarticletext' );
172 $this->loadContent( $noredir );
173 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
174 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
175 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
178 wfProfileOut( $fname );
179 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
181 if($action=='edit') {
183 if($section=='new') {
184 wfProfileOut( $fname );
188 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
189 # comments to be stripped as well)
190 $rv=$this->getSection($this->mContent
,$section);
191 wfProfileOut( $fname );
195 wfProfileOut( $fname );
196 return $this->mContent
;
202 * This function returns the text of a section, specified by a number ($section).
203 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
204 * the first section before any such heading (section 0).
206 * If a section contains subsections, these are also returned.
208 * @param string $text text to look in
209 * @param integer $section section number
210 * @return string text of the requested section
212 function getSection($text,$section) {
214 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
215 # comments to be stripped as well)
217 $parser=new Parser();
218 $parser->mOutputType
=OT_WIKI
;
219 $striptext=$parser->strip($text, $striparray, true);
221 # now that we can be sure that no pseudo-sections are in the source,
222 # split it up by section
225 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
227 PREG_SPLIT_DELIM_CAPTURE
);
231 $headline=$secs[$section*2-1];
232 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
235 # translate wiki heading into level
236 if(strpos($hlevel,'=')!==false) {
237 $hlevel=strlen($hlevel);
240 $rv=$headline. $secs[$section*2];
244 while(!empty($secs[$count*2-1]) && !$break) {
246 $subheadline=$secs[$count*2-1];
247 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
248 $subhlevel=$matches[1];
249 if(strpos($subhlevel,'=')!==false) {
250 $subhlevel=strlen($subhlevel);
252 if($subhlevel > $hlevel) {
253 $rv.=$subheadline.$secs[$count*2];
255 if($subhlevel <= $hlevel) {
262 # reinsert stripped tags
263 $rv=$parser->unstrip($rv,$striparray);
264 $rv=$parser->unstripNoWiki($rv,$striparray);
271 * Return an array of the columns of the "cur"-table
273 function &getCurContentFields() {
274 global $wgArticleCurContentFields;
275 if ( !$wgArticleCurContentFields ) {
276 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
277 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
279 return $wgArticleCurContentFields;
283 * Return an array of the columns of the "old"-table
285 function &getOldContentFields() {
286 global $wgArticleOldContentFields;
287 if ( !$wgArticleOldContentFields ) {
288 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
289 'old_user','old_user_text','old_comment','old_flags' );
291 return $wgArticleOldContentFields;
295 * Return the oldid of the article that is to be shown.
296 * For requests with a "direction", this is not the oldid of the
299 function getOldID() {
300 global $wgRequest, $wgOut;
303 if ( isset( $lastid ) ) {
307 $oldid = $wgRequest->getVal( 'oldid' );
308 if ( isset( $oldid ) ) {
309 $dbr =& $this->getDB();
310 $oldid = IntVal( $oldid );
311 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
312 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
316 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
318 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
319 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
328 return @$oldid; # "@" to be able to return "unset" without PHP complaining
333 * Load the revision (including cur_text) into this object
335 function loadContent( $noredir = false ) {
336 global $wgOut, $wgRequest;
338 if ( $this->mContentLoaded
) return;
340 $dbr =& $this->getDB();
342 $oldid = $this->getOldID();
343 $redirect = $wgRequest->getVal( 'redirect' );
345 $fname = 'Article::loadContent';
347 # Pre-fill content with error message so that if something
348 # fails we'll have something telling us what we intended.
350 $t = $this->mTitle
->getPrefixedText();
352 if ( isset( $oldid ) ) {
353 $t .= ',oldid='.$oldid;
355 if ( isset( $redirect ) ) {
356 $redirect = ($redirect == 'no') ?
'no' : 'yes';
357 $t .= ',redirect='.$redirect;
359 $this->mContent
= wfMsg( 'missingarticle', $t );
361 if ( ! $oldid ) { # Retrieve current version
362 $id = $this->getID();
363 if ( 0 == $id ) return;
365 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
366 $this->getSelectOptions() );
367 if ( $s === false ) {
371 # If we got a redirect, follow it (unless we've been told
372 # not to by either the function parameter or the query
373 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
374 $rt = Title
::newFromRedirect( $s->cur_text
);
375 # process if title object is valid and not special:userlogout
376 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
377 # Gotta hand redirects to special pages differently:
378 # Fill the HTTP response "Location" header and ignore
379 # the rest of the page we're on.
381 if ( $rt->getInterwiki() != '' ) {
382 $wgOut->redirect( $rt->getFullURL() ) ;
385 if ( $rt->getNamespace() == NS_SPECIAL
) {
386 $wgOut->redirect( $rt->getFullURL() );
389 $rid = $rt->getArticleID();
391 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
392 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
394 if ( $redirRow !== false ) {
395 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
403 $this->mContent
= $s->cur_text
;
404 $this->mUser
= $s->cur_user
;
405 $this->mUserText
= $s->cur_user_text
;
406 $this->mComment
= $s->cur_comment
;
407 $this->mCounter
= $s->cur_counter
;
408 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
409 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
410 $this->mTitle
->loadRestrictions( $s->cur_restrictions
);
411 } else { # oldid set, retrieve historical version
412 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
413 $fname, $this->getSelectOptions() );
414 if ( $s === false ) {
418 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
419 $this->mTitle
->getDBkey() != $s->old_title
) {
420 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
421 $this->mTitle
= $oldTitle;
422 $wgTitle = $oldTitle;
424 $this->mContent
= Article
::getRevisionText( $s );
425 $this->mUser
= $s->old_user
;
426 $this->mUserText
= $s->old_user_text
;
427 $this->mComment
= $s->old_comment
;
429 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
431 $this->mContentLoaded
= true;
432 return $this->mContent
;
436 * Gets the article text without using so many damn globals
437 * Returns false on error
439 * @param integer $oldid
441 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
442 if ( $this->mContentLoaded
) {
443 return $this->mContent
;
445 $this->mContent
= false;
447 $fname = 'Article::getContentWithout';
448 $dbr =& $this->getDB();
450 if ( ! $oldid ) { # Retrieve current version
451 $id = $this->getID();
456 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
457 $fname, $this->getSelectOptions() );
458 if ( $s === false ) {
462 # If we got a redirect, follow it (unless we've been told
463 # not to by either the function parameter or the query
465 $rt = Title
::newFromRedirect( $s->cur_text
);
466 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
467 $rid = $rt->getArticleID();
469 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
470 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
472 if ( $redirRow !== false ) {
473 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
481 $this->mContent
= $s->cur_text
;
482 $this->mUser
= $s->cur_user
;
483 $this->mUserText
= $s->cur_user_text
;
484 $this->mComment
= $s->cur_comment
;
485 $this->mCounter
= $s->cur_counter
;
486 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
487 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
488 $this->mTitle
->loadRestrictions( $s->cur_restrictions
);
489 } else { # oldid set, retrieve historical version
490 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
491 $fname, $this->getSelectOptions() );
492 if ( $s === false ) {
495 $this->mContent
= Article
::getRevisionText( $s );
496 $this->mUser
= $s->old_user
;
497 $this->mUserText
= $s->old_user_text
;
498 $this->mComment
= $s->old_comment
;
500 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
502 $this->mContentLoaded
= true;
503 return $this->mContent
;
507 * Read/write accessor to select FOR UPDATE
509 function forUpdate( $x = NULL ) {
510 return wfSetVar( $this->mForUpdate
, $x );
514 * Get the database which should be used for reads
517 if ( $this->mForUpdate
) {
518 return wfGetDB( DB_MASTER
);
520 return wfGetDB( DB_SLAVE
);
525 * Get options for all SELECT statements
526 * Can pass an option array, to which the class-wide options will be appended
528 function getSelectOptions( $options = '' ) {
529 if ( $this->mForUpdate
) {
531 $options[] = 'FOR UPDATE';
533 $options = 'FOR UPDATE';
540 * Return the Article ID
543 if( $this->mTitle
) {
544 return $this->mTitle
->getArticleID();
551 * Get the view count for this article
553 function getCount() {
554 if ( -1 == $this->mCounter
) {
555 $id = $this->getID();
556 $dbr =& $this->getDB();
557 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
558 'Article::getCount', $this->getSelectOptions() );
560 return $this->mCounter
;
564 * Would the given text make this article a "good" article (i.e.,
565 * suitable for including in the article count)?
567 function isCountable( $text ) {
568 global $wgUseCommaCount;
570 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
571 if ( $this->isRedirect( $text ) ) { return 0; }
572 $token = ($wgUseCommaCount ?
',' : '[[' );
573 if ( false === strstr( $text, $token ) ) { return 0; }
578 * Tests if the article text represents a redirect
580 function isRedirect( $text = false ) {
581 if ( $text === false ) {
582 $this->loadContent();
583 $titleObj = Title
::newFromRedirect( $this->mText
);
585 $titleObj = Title
::newFromRedirect( $text );
587 return $titleObj !== NULL;
591 * Loads everything from cur except cur_text
592 * This isn't necessary for all uses, so it's only done if needed.
595 function loadLastEdit() {
597 if ( -1 != $this->mUser
) return;
599 $fname = 'Article::loadLastEdit';
601 $dbr =& $this->getDB();
602 $s = $dbr->selectRow( 'cur',
603 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
604 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
606 if ( $s !== false ) {
607 $this->mUser
= $s->cur_user
;
608 $this->mUserText
= $s->cur_user_text
;
609 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
610 $this->mComment
= $s->cur_comment
;
611 $this->mMinorEdit
= $s->cur_minor_edit
;
615 function getTimestamp() {
616 $this->loadLastEdit();
617 return $this->mTimestamp
;
621 $this->loadLastEdit();
625 function getUserText() {
626 $this->loadLastEdit();
627 return $this->mUserText
;
630 function getComment() {
631 $this->loadLastEdit();
632 return $this->mComment
;
635 function getMinorEdit() {
636 $this->loadLastEdit();
637 return $this->mMinorEdit
;
640 function getContributors($limit = 0, $offset = 0) {
641 $fname = 'Article::getContributors';
643 # XXX: this is expensive; cache this info somewhere.
645 $title = $this->mTitle
;
647 $dbr =& $this->getDB();
648 $oldTable = $dbr->tableName( 'old' );
649 $userTable = $dbr->tableName( 'user' );
650 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
651 $ns = $title->getNamespace();
652 $user = $this->getUser();
654 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
655 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
656 WHERE old_namespace = $user
657 AND old_title = $encDBkey
658 AND old_user != $user
659 GROUP BY old_user, old_user_text, user_real_name
660 ORDER BY timestamp DESC";
662 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
663 $sql .= ' '. $this->getSelectOptions();
665 $res = $dbr->query($sql, $fname);
667 while ( $line = $dbr->fetchObject( $res ) ) {
668 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
671 $dbr->freeResult($res);
676 * This is the default action of the script: just view the page of
680 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
681 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
682 $sk = $wgUser->getSkin();
684 $fname = 'Article::view';
685 wfProfileIn( $fname );
686 # Get variables from query string
687 $oldid = $this->getOldID();
688 $diff = $wgRequest->getVal( 'diff' );
689 $rcid = $wgRequest->getVal( 'rcid' );
691 $wgOut->setArticleFlag( true );
692 $wgOut->setRobotpolicy( 'index,follow' );
693 # If we got diff and oldid in the query, we want to see a
694 # diff page instead of the article.
696 if ( !is_null( $diff ) ) {
697 require_once( 'DifferenceEngine.php' );
698 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
699 $de = new DifferenceEngine( $oldid, $diff, $rcid );
702 # Run view updates for current revision only
703 $this->viewUpdates();
705 wfProfileOut( $fname );
708 if ( empty( $oldid ) && $this->checkTouched() ) {
709 if( $wgOut->checkLastModified( $this->mTouched
) ){
710 wfProfileOut( $fname );
712 } else if ( $this->tryFileCache() ) {
713 # tell wgOut that output is taken care of
715 $this->viewUpdates();
716 wfProfileOut( $fname );
720 # Should the parser cache be used?
721 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
729 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
733 if ( !$outputDone ) {
734 $text = $this->getContent( false ); # May change mTitle by following a redirect
736 # Another whitelist check in case oldid or redirects are altering the title
737 if ( !$this->mTitle
->userCanRead() ) {
738 $wgOut->loginToUse();
744 # We're looking at an old revision
746 if ( !empty( $oldid ) ) {
747 $this->setOldSubtitle( $oldid );
748 $wgOut->setRobotpolicy( 'noindex,follow' );
750 if ( '' != $this->mRedirectedFrom
) {
751 $sk = $wgUser->getSkin();
752 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
754 $s = wfMsg( 'redirectedfrom', $redir );
755 $wgOut->setSubtitle( $s );
757 # Can't cache redirects
761 # wrap user css and user js in pre and don't parse
762 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
764 $this->mTitle
->getNamespace() == NS_USER
&&
765 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
767 $wgOut->addWikiText( wfMsg('clearyourcache'));
768 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
769 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
771 $imageUrl = $wgStylePath.'/common/images/redirect.png';
772 $targetUrl = $rt->escapeLocalURL();
773 $titleText = htmlspecialchars( $rt->getPrefixedText() );
774 $link = $sk->makeLinkObj( $rt );
776 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
777 '<span class="redirectText">'.$link.'</span>' );
779 } else if ( $pcache ) {
780 # Display content and save to parser cache
781 $wgOut->addPrimaryWikiText( $text, $this );
783 # Display content, don't attempt to save to parser cache
784 $wgOut->addWikiText( $text );
787 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
788 # If we have been passed an &rcid= parameter, we want to give the user a
789 # chance to mark this new article as patrolled.
790 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
791 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
793 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
794 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
795 'action=markpatrolled&rcid='.$rcid )
799 # Put link titles into the link cache
800 $wgOut->transformBuffer();
802 # Add link titles as META keywords
803 $wgOut->addMetaTags() ;
805 $this->viewUpdates();
806 wfProfileOut( $fname );
810 * Theoretically we could defer these whole insert and update
811 * functions for after display, but that's taking a big leap
812 * of faith, and we want to be able to report database
813 * errors at some point.
816 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
817 global $wgOut, $wgUser;
818 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
820 $fname = 'Article::insertNewArticle';
822 $this->mCountAdjustment
= $this->isCountable( $text );
824 $ns = $this->mTitle
->getNamespace();
825 $ttl = $this->mTitle
->getDBkey();
826 $text = $this->preSaveTransform( $text );
827 if ( $this->isRedirect( $text ) ) { $redir = 1; }
830 $now = wfTimestampNow();
831 $won = wfInvertTimestamp( $now );
834 $dbw =& wfGetDB( DB_MASTER
);
836 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
838 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
840 $dbw->insert( 'cur', array(
842 'cur_namespace' => $ns,
845 'cur_comment' => $summary,
846 'cur_user' => $wgUser->getID(),
847 'cur_timestamp' => $dbw->timestamp($now),
848 'cur_minor_edit' => $isminor,
850 'cur_restrictions' => '',
851 'cur_user_text' => $wgUser->getName(),
852 'cur_is_redirect' => $redir,
854 'cur_random' => $rand,
855 'cur_touched' => $dbw->timestamp($now),
856 'inverse_timestamp' => $won,
859 $newid = $dbw->insertId();
860 $this->mTitle
->resetArticleID( $newid );
862 Article
::onArticleCreate( $this->mTitle
);
863 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
866 if(!$this->mTitle
->userIsWatching()) $this->watch();
868 if ( $this->mTitle
->userIsWatching() ) {
873 # The talk page isn't in the regular link tables, so we need to update manually:
874 $talkns = $ns ^
1; # talk -> normal; normal -> talk
875 $dbw->update( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
876 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
878 # standard deferred updates
879 $this->editUpdates( $text );
881 $this->showArticle( $text, wfMsg( 'newarticle' ) );
886 * Side effects: loads last edit if $edittime is NULL
888 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
889 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
890 if(is_null($edittime)) {
891 $this->loadLastEdit();
892 $oldtext = $this->getContent( true );
894 $dbw =& wfGetDB( DB_MASTER
);
895 $ns = $this->mTitle
->getNamespace();
896 $title = $this->mTitle
->getDBkey();
897 $obj = $dbw->selectRow( 'old',
898 array( 'old_text','old_flags'),
899 array( 'old_namespace' => $ns, 'old_title' => $title,
900 'old_timestamp' => $dbw->timestamp($edittime)),
902 $oldtext = Article
::getRevisionText( $obj );
904 if ($section != '') {
905 if($section=='new') {
906 if($summary) $subject="== {$summary} ==\n\n";
907 $text=$oldtext."\n\n".$subject.$text;
910 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
911 # comments to be stripped as well)
913 $parser=new Parser();
914 $parser->mOutputType
=OT_WIKI
;
915 $oldtext=$parser->strip($oldtext, $striparray, true);
917 # now that we can be sure that no pseudo-sections are in the source,
919 # Unfortunately we can't simply do a preg_replace because that might
920 # replace the wrong section, so we have to use the section counter instead
921 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
922 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
923 $secs[$section*2]=$text."\n\n"; // replace with edited
925 # section 0 is top (intro) section
928 # headline of old section - we need to go through this section
929 # to determine if there are any subsections that now need to
930 # be erased, as the mother section has been replaced with
931 # the text of all subsections.
932 $headline=$secs[$section*2-1];
933 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
936 # determine headline level for wikimarkup headings
937 if(strpos($hlevel,'=')!==false) {
938 $hlevel=strlen($hlevel);
941 $secs[$section*2-1]=''; // erase old headline
944 while(!empty($secs[$count*2-1]) && !$break) {
946 $subheadline=$secs[$count*2-1];
948 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
949 $subhlevel=$matches[1];
950 if(strpos($subhlevel,'=')!==false) {
951 $subhlevel=strlen($subhlevel);
953 if($subhlevel > $hlevel) {
954 // erase old subsections
955 $secs[$count*2-1]='';
958 if($subhlevel <= $hlevel) {
966 $text=join('',$secs);
967 # reinsert the stuff that we stripped out earlier
968 $text=$parser->unstrip($text,$striparray);
969 $text=$parser->unstripNoWiki($text,$striparray);
977 * Change an existing article. Puts the previous version back into the old table, updates RC
978 * and all necessary caches, mostly via the deferred update array.
980 * It is possible to call this function from a command-line script, but note that you should
981 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
983 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
984 global $wgOut, $wgUser;
985 global $wgDBtransactions, $wgMwRedir;
986 global $wgUseSquid, $wgInternalServer;
988 $fname = 'Article::updateArticle';
991 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
992 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
993 if ( $this->isRedirect( $text ) ) {
994 # Remove all content but redirect
995 # This could be done by reconstructing the redirect from a title given by
996 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
998 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1000 $text = $m[1] . "\n";
1003 else { $redir = 0; }
1005 $text = $this->preSaveTransform( $text );
1006 $dbw =& wfGetDB( DB_MASTER
);
1008 # Update article, but only if changed.
1010 # It's important that we either rollback or complete, otherwise an attacker could
1011 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1012 # could conceivably have the same effect, especially if cur is locked for long periods.
1013 if( $wgDBtransactions ) {
1014 $dbw->query( 'BEGIN', $fname );
1016 $userAbort = ignore_user_abort( true );
1019 $oldtext = $this->getContent( true );
1021 if ( 0 != strcmp( $text, $oldtext ) ) {
1022 $this->mCountAdjustment
= $this->isCountable( $text )
1023 - $this->isCountable( $oldtext );
1024 $now = wfTimestampNow();
1025 $won = wfInvertTimestamp( $now );
1027 # First update the cur row
1028 $dbw->update( 'cur',
1030 'cur_text' => $text,
1031 'cur_comment' => $summary,
1032 'cur_minor_edit' => $me2,
1033 'cur_user' => $wgUser->getID(),
1034 'cur_timestamp' => $dbw->timestamp($now),
1035 'cur_user_text' => $wgUser->getName(),
1036 'cur_is_redirect' => $redir,
1038 'cur_touched' => $dbw->timestamp($now),
1039 'inverse_timestamp' => $won
1040 ), array( /* WHERE */
1041 'cur_id' => $this->getID(),
1042 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1046 if( $dbw->affectedRows() == 0 ) {
1047 /* Belated edit conflict! Run away!! */
1050 # Now insert the previous revision into old
1052 # This overwrites $oldtext if revision compression is on
1053 $flags = Article
::compressRevisionText( $oldtext );
1055 $dbw->insert( 'old',
1057 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1058 'old_namespace' => $this->mTitle
->getNamespace(),
1059 'old_title' => $this->mTitle
->getDBkey(),
1060 'old_text' => $oldtext,
1061 'old_comment' => $this->getComment(),
1062 'old_user' => $this->getUser(),
1063 'old_user_text' => $this->getUserText(),
1064 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1065 'old_minor_edit' => $me1,
1066 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1067 'old_flags' => $flags,
1071 $oldid = $dbw->insertId();
1073 $bot = (int)($wgUser->isBot() ||
$forceBot);
1074 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1075 $oldid, $this->getTimestamp(), $bot );
1076 Article
::onArticleEdit( $this->mTitle
);
1080 if( $wgDBtransactions ) {
1081 $dbw->query( 'COMMIT', $fname );
1083 ignore_user_abort( $userAbort );
1088 if (!$this->mTitle
->userIsWatching()) $this->watch();
1090 if ( $this->mTitle
->userIsWatching() ) {
1094 # standard deferred updates
1095 $this->editUpdates( $text );
1099 # Template namespace
1100 # Purge all articles linking here
1101 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1102 $titles = $this->mTitle
->getLinksTo();
1103 Title
::touchArray( $titles );
1104 if ( $wgUseSquid ) {
1105 foreach ( $titles as $title ) {
1106 $urls[] = $title->getInternalURL();
1112 if ( $wgUseSquid ) {
1113 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1114 $u = new SquidUpdate( $urls );
1118 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1124 * After we've either updated or inserted the article, update
1125 * the link tables and redirect to the new page.
1127 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1128 global $wgOut, $wgUser, $wgLinkCache;
1130 $wgLinkCache = new LinkCache();
1132 $wgLinkCache->forUpdate( true );
1134 # Get old version of link table to allow incremental link updates
1135 $wgLinkCache->preFill( $this->mTitle
);
1136 $wgLinkCache->clear();
1138 # Parse the text and replace links with placeholders
1139 $wgOut = new OutputPage();
1140 $wgOut->addWikiText( $text );
1142 # Look up the links in the DB and add them to the link cache
1143 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1145 if( $this->isRedirect( $text ) )
1149 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1154 * @todo document this function a bit more
1156 function validate () {
1157 global $wgOut, $wgUseValidation;
1158 if( $wgUseValidation ) {
1159 require_once ( 'SpecialValidate.php' ) ;
1160 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1161 $wgOut->setRobotpolicy( 'noindex,follow' );
1162 if( $this->mTitle
->getNamespace() != 0 ) {
1163 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1166 $v = new Validation
;
1167 $v->validate_form( $this->mTitle
->getDBkey() );
1169 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1174 * Mark this particular edit as patrolled
1176 function markpatrolled() {
1177 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1178 $wgOut->setRobotpolicy( 'noindex,follow' );
1180 if ( !$wgUseRCPatrol )
1182 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1185 if ( $wgUser->getID() == 0 )
1187 $wgOut->loginToUse();
1190 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1192 $wgOut->sysopRequired();
1195 $rcid = $wgRequest->getVal( 'rcid' );
1196 if ( !is_null ( $rcid ) )
1198 RecentChange
::markPatrolled( $rcid );
1199 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1200 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1201 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1205 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1211 * Add or remove this page to my watchlist based on value of $add
1213 function watch( $add = true ) {
1214 global $wgUser, $wgOut;
1215 global $wgDeferredUpdateList;
1217 if ( 0 == $wgUser->getID() ) {
1218 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1221 if ( wfReadOnly() ) {
1222 $wgOut->readOnlyPage();
1226 $wgUser->addWatch( $this->mTitle
);
1228 $wgUser->removeWatch( $this->mTitle
);
1230 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1231 $wgOut->setRobotpolicy( 'noindex,follow' );
1233 $sk = $wgUser->getSkin() ;
1234 $link = $this->mTitle
->getPrefixedText();
1237 $text = wfMsg( 'addedwatchtext', $link );
1239 $text = wfMsg( 'removedwatchtext', $link );
1240 $wgOut->addWikiText( $text );
1242 $up = new UserUpdate();
1243 array_push( $wgDeferredUpdateList, $up );
1245 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1249 * Stop watching a page, it act just like a call to watch(false)
1251 function unwatch() {
1252 $this->watch( false );
1258 function protect( $limit = 'sysop' ) {
1259 global $wgUser, $wgOut, $wgRequest;
1261 if ( ! $wgUser->isAllowed('protect') ) {
1262 $wgOut->sysopRequired();
1265 if ( wfReadOnly() ) {
1266 $wgOut->readOnlyPage();
1269 $id = $this->mTitle
->getArticleID();
1271 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1275 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1276 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1277 $reason = $wgRequest->getText( 'wpReasonProtect' );
1280 $restrictions = "move=" . $limit;
1282 $restrictions .= ":edit=" . $limit;
1285 $dbw =& wfGetDB( DB_MASTER
);
1286 $dbw->update( 'cur',
1288 'cur_touched' => $dbw->timestamp(),
1289 'cur_restrictions' => $restrictions
1290 ), array( /* WHERE */
1292 ), 'Article::protect'
1295 $log = new LogPage( 'protect' );
1296 if ( $limit === '' ) {
1297 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1299 $log->addEntry( 'protect', $this->mTitle
, $reason );
1301 $wgOut->redirect( $this->mTitle
->getFullURL() );
1304 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1305 return $this->confirmProtect( '', $reason, $limit );
1310 * Output protection confirmation dialog
1312 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1315 wfDebug( "Article::confirmProtect\n" );
1317 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1318 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1324 if ( $limit === '' ) {
1325 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1326 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1327 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1328 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1329 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1330 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1332 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1333 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1334 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1335 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1336 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1337 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1338 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1341 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1344 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1348 <label for='wpReasonProtect'>{$protcom}:</label>
1351 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1359 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1362 <label for='wpConfirmProtect'>{$check}</label>
1365 if($moveonly != '') {
1369 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1372 <label for='wpMoveOnly'>{$moveonly}</label>
1380 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1386 $wgOut->returnToMain( false );
1390 * Unprotect the pages
1392 function unprotect() {
1393 return $this->protect( '' );
1397 * UI entry point for page deletion
1400 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1401 $fname = 'Article::delete';
1402 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1403 $reason = $wgRequest->getText( 'wpReason' );
1405 # This code desperately needs to be totally rewritten
1408 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1409 $wgOut->sysopRequired();
1412 if ( wfReadOnly() ) {
1413 $wgOut->readOnlyPage();
1417 # Better double-check that it hasn't been deleted yet!
1418 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1419 if ( ( '' == trim( $this->mTitle
->getText() ) )
1420 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1421 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1426 $this->doDelete( $reason );
1430 # determine whether this page has earlier revisions
1431 # and insert a warning if it does
1432 # we select the text because it might be useful below
1433 $dbr =& $this->getDB();
1434 $ns = $this->mTitle
->getNamespace();
1435 $title = $this->mTitle
->getDBkey();
1436 $old = $dbr->selectRow( 'old',
1437 array( 'old_text', 'old_flags' ),
1439 'old_namespace' => $ns,
1440 'old_title' => $title,
1441 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1444 if( $old !== false && !$confirm ) {
1445 $skin=$wgUser->getSkin();
1446 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1447 $wgOut->addHTML( $skin->historyLink() .'</b>');
1451 $s = $dbr->selectRow( 'cur',
1452 array( 'cur_text' ),
1454 'cur_namespace' => $ns,
1455 'cur_title' => $title,
1456 ), $fname, $this->getSelectOptions()
1459 if( $s !== false ) {
1460 # if this is a mini-text, we can paste part of it into the deletion reason
1462 #if this is empty, an earlier revision may contain "useful" text
1464 if($s->cur_text
!= '') {
1468 $text = Article
::getRevisionText( $old );
1474 $length=strlen($text);
1476 # this should not happen, since it is not possible to store an empty, new
1477 # page. Let's insert a standard text in case it does, though
1478 if($length == 0 && $reason === '') {
1479 $reason = wfMsg('exblank');
1482 if($length < 500 && $reason === '') {
1484 # comment field=255, let's grep the first 150 to have some user
1486 $text=substr($text,0,150);
1487 # let's strip out newlines and HTML tags
1488 $text=preg_replace('/\"/',"'",$text);
1489 $text=preg_replace('/\</','<',$text);
1490 $text=preg_replace('/\>/','>',$text);
1491 $text=preg_replace("/[\n\r]/",'',$text);
1493 $reason=wfMsg('excontent'). " '".$text;
1495 $reason=wfMsg('exbeforeblank') . " '".$text;
1497 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1502 return $this->confirmDelete( '', $reason );
1506 * Output deletion confirmation dialog
1508 function confirmDelete( $par, $reason ) {
1511 wfDebug( "Article::confirmDelete\n" );
1513 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1514 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1515 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1516 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1518 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1520 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1521 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1522 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1525 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1529 <label for='wpReason'>{$delcom}:</label>
1532 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1540 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1543 <label for='wpConfirm'>{$check}</label>
1549 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1555 $wgOut->returnToMain( false );
1560 * Perform a deletion and output success or failure messages
1562 function doDelete( $reason ) {
1563 global $wgOut, $wgUser, $wgContLang;
1564 $fname = 'Article::doDelete';
1565 wfDebug( $fname."\n" );
1567 if ( $this->doDeleteArticle( $reason ) ) {
1568 $deleted = $this->mTitle
->getPrefixedText();
1570 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1571 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1573 $sk = $wgUser->getSkin();
1574 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1575 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1577 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1579 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1580 $wgOut->returnToMain( false );
1582 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1587 * Back-end article deletion
1588 * Deletes the article with database consistency, writes logs, purges caches
1591 function doDeleteArticle( $reason ) {
1593 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1595 $fname = 'Article::doDeleteArticle';
1596 wfDebug( $fname."\n" );
1598 $dbw =& wfGetDB( DB_MASTER
);
1599 $ns = $this->mTitle
->getNamespace();
1600 $t = $this->mTitle
->getDBkey();
1601 $id = $this->mTitle
->getArticleID();
1603 if ( $t == '' ||
$id == 0 ) {
1607 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1608 array_push( $wgDeferredUpdateList, $u );
1610 $linksTo = $this->mTitle
->getLinksTo();
1613 if ( $wgUseSquid ) {
1615 $this->mTitle
->getInternalURL(),
1616 $this->mTitle
->getInternalURL( 'history' )
1618 foreach ( $linksTo as $linkTo ) {
1619 $urls[] = $linkTo->getInternalURL();
1622 $u = new SquidUpdate( $urls );
1623 array_push( $wgDeferredUpdateList, $u );
1627 # Client and file cache invalidation
1628 Title
::touchArray( $linksTo );
1630 # Move article and history to the "archive" table
1631 $archiveTable = $dbw->tableName( 'archive' );
1632 $oldTable = $dbw->tableName( 'old' );
1633 $curTable = $dbw->tableName( 'cur' );
1634 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1635 $linksTable = $dbw->tableName( 'links' );
1636 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1638 $dbw->insertSelect( 'archive', 'cur',
1640 'ar_namespace' => 'cur_namespace',
1641 'ar_title' => 'cur_title',
1642 'ar_text' => 'cur_text',
1643 'ar_comment' => 'cur_comment',
1644 'ar_user' => 'cur_user',
1645 'ar_user_text' => 'cur_user_text',
1646 'ar_timestamp' => 'cur_timestamp',
1647 'ar_minor_edit' => 'cur_minor_edit',
1650 'cur_namespace' => $ns,
1655 $dbw->insertSelect( 'archive', 'old',
1657 'ar_namespace' => 'old_namespace',
1658 'ar_title' => 'old_title',
1659 'ar_text' => 'old_text',
1660 'ar_comment' => 'old_comment',
1661 'ar_user' => 'old_user',
1662 'ar_user_text' => 'old_user_text',
1663 'ar_timestamp' => 'old_timestamp',
1664 'ar_minor_edit' => 'old_minor_edit',
1665 'ar_flags' => 'old_flags'
1667 'old_namespace' => $ns,
1672 # Now that it's safely backed up, delete it
1674 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1675 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1676 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1678 # Finally, clean up the link tables
1679 $t = $this->mTitle
->getPrefixedDBkey();
1681 Article
::onArticleDelete( $this->mTitle
);
1683 # Insert broken links
1684 $brokenLinks = array();
1685 foreach ( $linksTo as $titleObj ) {
1686 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1687 $linkID = $titleObj->getArticleID();
1688 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1690 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1693 $dbw->delete( 'links', array( 'l_to' => $id ) );
1694 $dbw->delete( 'links', array( 'l_from' => $id ) );
1695 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1696 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1697 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1700 $log = new LogPage( 'delete' );
1701 $log->addEntry( 'delete', $this->mTitle
, $reason );
1703 # Clear the cached article id so the interface doesn't act like we exist
1704 $this->mTitle
->resetArticleID( 0 );
1705 $this->mTitle
->mArticleID
= 0;
1710 * Revert a modification
1712 function rollback() {
1713 global $wgUser, $wgOut, $wgRequest;
1714 $fname = 'Article::rollback';
1716 if ( ! $wgUser->isAllowed('rollback') ) {
1717 $wgOut->sysopRequired();
1720 if ( wfReadOnly() ) {
1721 $wgOut->readOnlyPage( $this->getContent( true ) );
1724 $dbw =& wfGetDB( DB_MASTER
);
1726 # Enhanced rollback, marks edits rc_bot=1
1727 $bot = $wgRequest->getBool( 'bot' );
1729 # Replace all this user's current edits with the next one down
1730 $tt = $this->mTitle
->getDBKey();
1731 $n = $this->mTitle
->getNamespace();
1733 # Get the last editor, lock table exclusively
1734 $s = $dbw->selectRow( 'cur',
1735 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1736 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1737 $fname, 'FOR UPDATE'
1739 if( $s === false ) {
1741 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1744 $ut = $dbw->strencode( $s->cur_user_text
);
1745 $uid = $s->cur_user
;
1748 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1749 if( $from != $s->cur_user_text
) {
1750 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1751 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1752 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1753 htmlspecialchars( $from ),
1754 htmlspecialchars( $s->cur_user_text
) ) );
1755 if($s->cur_comment
!= '') {
1757 wfMsg('editcomment',
1758 htmlspecialchars( $s->cur_comment
) ) );
1763 # Get the last edit not by this guy
1764 $s = $dbw->selectRow( 'old',
1765 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1767 'old_namespace' => $n,
1769 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1770 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1772 if( $s === false ) {
1774 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1775 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1780 # Mark all reverted edits as bot
1781 $dbw->update( 'recentchanges',
1784 ), array( /* WHERE */
1786 "rc_timestamp > '{$s->old_timestamp}'",
1792 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1793 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1794 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1795 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1796 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1797 Article
::onArticleEdit( $this->mTitle
);
1798 $wgOut->returnToMain( false );
1803 * Do standard deferred updates after page view
1806 function viewUpdates() {
1807 global $wgDeferredUpdateList;
1808 if ( 0 != $this->getID() ) {
1809 global $wgDisableCounters;
1810 if( !$wgDisableCounters ) {
1811 Article
::incViewCount( $this->getID() );
1812 $u = new SiteStatsUpdate( 1, 0, 0 );
1813 array_push( $wgDeferredUpdateList, $u );
1816 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1817 $this->mTitle
->getDBkey() );
1818 array_push( $wgDeferredUpdateList, $u );
1822 * Do standard deferred updates after page edit.
1823 * Every 1000th edit, prune the recent changes table.
1825 * @param string $text
1827 function editUpdates( $text ) {
1828 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1829 global $wgMessageCache;
1832 if ( 0 == mt_rand( 0, 999 ) ) {
1833 $dbw =& wfGetDB( DB_MASTER
);
1834 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1835 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1836 $dbw->query( $sql );
1838 $id = $this->getID();
1839 $title = $this->mTitle
->getPrefixedDBkey();
1840 $shortTitle = $this->mTitle
->getDBkey();
1842 $adj = $this->mCountAdjustment
;
1845 $u = new LinksUpdate( $id, $title );
1846 array_push( $wgDeferredUpdateList, $u );
1847 $u = new SiteStatsUpdate( 0, 1, $adj );
1848 array_push( $wgDeferredUpdateList, $u );
1849 $u = new SearchUpdate( $id, $title, $text );
1850 array_push( $wgDeferredUpdateList, $u );
1852 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1853 array_push( $wgDeferredUpdateList, $u );
1855 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1856 $wgMessageCache->replace( $shortTitle, $text );
1862 * @todo document this function
1864 * @param string $oldid Revision ID of this article revision
1866 function setOldSubtitle( $oldid=0 ) {
1867 global $wgLang, $wgOut, $wgUser;
1869 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1870 $sk = $wgUser->getSkin();
1871 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1872 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1873 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1874 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1875 $wgOut->setSubtitle( $r );
1879 * This function is called right before saving the wikitext,
1880 * so we can do things like signatures and links-in-context.
1882 * @param string $text
1884 function preSaveTransform( $text ) {
1885 global $wgParser, $wgUser;
1886 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1889 /* Caching functions */
1892 * checkLastModified returns true if it has taken care of all
1893 * output to the client that is necessary for this request.
1894 * (that is, it has sent a cached version of the page)
1896 function tryFileCache() {
1897 static $called = false;
1899 wfDebug( " tryFileCache() -- called twice!?\n" );
1903 if($this->isFileCacheable()) {
1904 $touched = $this->mTouched
;
1905 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1906 # Expire the main page quicker
1907 $expire = wfUnix2Timestamp( time() - 3600 );
1908 $touched = max( $expire, $touched );
1910 $cache = new CacheManager( $this->mTitle
);
1911 if($cache->isFileCacheGood( $touched )) {
1913 wfDebug( " tryFileCache() - about to load\n" );
1914 $cache->loadFromFileCache();
1917 wfDebug( " tryFileCache() - starting buffer\n" );
1918 ob_start( array(&$cache, 'saveToFileCache' ) );
1921 wfDebug( " tryFileCache() - not cacheable\n" );
1926 * Check if the page can be cached
1929 function isFileCacheable() {
1930 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1931 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1933 return $wgUseFileCache
1934 and (!$wgShowIPinHeader)
1935 and ($this->getID() != 0)
1936 and ($wgUser->getId() == 0)
1937 and (!$wgUser->getNewtalk())
1938 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1939 and (empty( $action ) ||
$action == 'view')
1940 and (!isset($oldid))
1942 and (!isset($redirect))
1943 and (!isset($printable))
1944 and (!$this->mRedirectedFrom
);
1948 * Loads cur_touched and returns a value indicating if it should be used
1951 function checkTouched() {
1952 $fname = 'Article::checkTouched';
1953 $id = $this->getID();
1954 $dbr =& $this->getDB();
1955 $s = $dbr->selectRow( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1956 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1957 if( $s !== false ) {
1958 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1959 return !$s->cur_is_redirect
;
1966 * Edit an article without doing all that other stuff
1968 * @param string $text text submitted
1969 * @param string $comment comment submitted
1970 * @param integer $minor whereas it's a minor modification
1972 function quickEdit( $text, $comment = '', $minor = 0 ) {
1974 $fname = 'Article::quickEdit';
1975 wfProfileIn( $fname );
1977 $dbw =& wfGetDB( DB_MASTER
);
1978 $ns = $this->mTitle
->getNamespace();
1979 $dbkey = $this->mTitle
->getDBkey();
1980 $encDbKey = $dbw->strencode( $dbkey );
1981 $timestamp = wfTimestampNow();
1984 $dbw->insertSelect( 'old', 'cur',
1986 'old_namespace' => 'cur_namespace',
1987 'old_title' => 'cur_title',
1988 'old_text' => 'cur_text',
1989 'old_comment' => 'cur_comment',
1990 'old_user' => 'cur_user',
1991 'old_user_text' => 'cur_user_text',
1992 'old_timestamp' => 'cur_timestamp',
1993 'inverse_timestamp' => '99999999999999-cur_timestamp',
1995 'cur_namespace' => $ns,
1996 'cur_title' => $dbkey,
2000 # Use the affected row count to determine if the article is new
2001 $numRows = $dbw->affectedRows();
2003 # Make an array of fields to be inserted
2005 'cur_text' => $text,
2006 'cur_timestamp' => $timestamp,
2007 'cur_user' => $wgUser->getID(),
2008 'cur_user_text' => $wgUser->getName(),
2009 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2010 'cur_comment' => $comment,
2011 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2012 'cur_minor_edit' => intval($minor),
2013 'cur_touched' => $dbw->timestamp($timestamp),
2018 $fields['cur_is_new'] = 0;
2019 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2021 # Insert new article
2022 $fields['cur_is_new'] = 1;
2023 $fields['cur_namespace'] = $ns;
2024 $fields['cur_title'] = $dbkey;
2025 $fields['cur_random'] = $rand = wfRandom();
2026 $dbw->insert( 'cur', $fields, $fname );
2028 wfProfileOut( $fname );
2032 * Used to increment the view counter
2035 * @param integer $id article id
2037 function incViewCount( $id ) {
2038 $id = intval( $id );
2039 global $wgHitcounterUpdateFreq;
2041 $dbw =& wfGetDB( DB_MASTER
);
2042 $curTable = $dbw->tableName( 'cur' );
2043 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2044 $acchitsTable = $dbw->tableName( 'acchits' );
2046 if( $wgHitcounterUpdateFreq <= 1 ){ //
2047 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2051 # Not important enough to warrant an error page in case of failure
2052 $oldignore = $dbw->ignoreErrors( true );
2054 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2056 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2057 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2058 # Most of the time (or on SQL errors), skip row count check
2059 $dbw->ignoreErrors( $oldignore );
2063 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2064 $row = $dbw->fetchObject( $res );
2065 $rown = intval( $row->n
);
2066 if( $rown >= $wgHitcounterUpdateFreq ){
2067 wfProfileIn( 'Article::incViewCount-collect' );
2068 $old_user_abort = ignore_user_abort( true );
2070 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2071 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2072 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2074 $dbw->query("DELETE FROM $hitcounterTable");
2075 $dbw->query('UNLOCK TABLES');
2076 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2077 'WHERE cur_id = hc_id');
2078 $dbw->query("DROP TABLE $acchitsTable");
2080 ignore_user_abort( $old_user_abort );
2081 wfProfileOut( 'Article::incViewCount-collect' );
2083 $dbw->ignoreErrors( $oldignore );
2087 * The onArticle*() functions are supposed to be a kind of hooks
2088 * which should be called whenever any of the specified actions
2091 * This is a good place to put code to clear caches, for instance.
2093 * This is called on page move and undelete, as well as edit
2095 * @param $title_obj a title object
2098 function onArticleCreate($title_obj) {
2099 global $wgUseSquid, $wgDeferredUpdateList;
2101 $titles = $title_obj->getBrokenLinksTo();
2104 if ( $wgUseSquid ) {
2105 $urls = $title_obj->getSquidURLs();
2106 foreach ( $titles as $linkTitle ) {
2107 $urls[] = $linkTitle->getInternalURL();
2109 $u = new SquidUpdate( $urls );
2110 array_push( $wgDeferredUpdateList, $u );
2113 # Clear persistent link cache
2114 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2117 function onArticleDelete($title_obj) {
2118 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2120 function onArticleEdit($title_obj) {
2121 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2126 * Info about this page
2129 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2130 $fname = 'Article::info';
2132 if ( !$wgAllowPageInfo ) {
2133 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2137 $dbr =& $this->getDB();
2139 $basenamespace = $wgTitle->getNamespace() & (~
1);
2140 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2141 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2142 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2143 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2144 $wgOut->setPagetitle( $fullTitle );
2145 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2147 # first, see if the page exists at all.
2148 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2150 $wgOut->addHTML( wfMsg('noarticletext') );
2152 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2153 $this->getSelectOptions() );
2154 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2155 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2156 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2158 # to find number of distinct authors, we need to do some
2159 # funny stuff because of the cur/old table split:
2160 # - first, find the name of the 'cur' author
2161 # - then, find the number of *other* authors in 'old'
2164 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2165 $this->getSelectOptions() );
2167 # find number of 'old' authors excluding 'cur' author
2168 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2169 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2170 $this->getSelectOptions() ) +
1;
2172 # now for the Talk page ...
2173 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2174 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2177 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2181 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2182 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2184 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2188 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2189 $this->getSelectOptions() );
2190 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2191 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2192 $fname, $this->getSelectOptions() );
2194 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );