8 * Need the CacheManager to be loaded
10 require_once ( 'CacheManager.php' );
12 $wgArticleCurContentFields = false;
13 $wgArticleOldContentFields = false;
16 * Class representing a Wikipedia article and history.
18 * See design.doc for an overview.
19 * Note: edit user interface and cache support functions have been
20 * moved to separate EditPage and CacheManager classes.
28 var $mContent, $mContentLoaded;
29 var $mUser, $mTimestamp, $mUserText;
30 var $mCounter, $mComment, $mCountAdjustment;
31 var $mMinorEdit, $mRedirectedFrom;
32 var $mTouched, $mFileCache, $mTitle;
38 * Constructor and clear the article
39 * @param mixed &$title
41 function Article( &$title ) {
42 $this->mTitle
=& $title;
51 $this->mContentLoaded
= false;
52 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
53 $this->mRedirectedFrom
= $this->mUserText
=
54 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
55 $this->mCountAdjustment
= 0;
56 $this->mTouched
= '19700101000000';
57 $this->mForUpdate
= false;
61 * Get revision text associated with an old or archive row
62 * $row is usually an object from wfFetchRow(), both the flags and the text
63 * field must be included
65 * @param integer $row Id of a row
66 * @param string $prefix table prefix (default 'old_')
67 * @return string $text|false the text requested
69 function getRevisionText( $row, $prefix = 'old_' ) {
70 $fname = 'Article::getRevisionText';
71 wfProfileIn( $fname );
74 $textField = $prefix . 'text';
75 $flagsField = $prefix . 'flags';
77 if( isset( $row->$flagsField ) ) {
78 $flags = explode( ',', $row->$flagsField );
83 if( isset( $row->$textField ) ) {
84 $text = $row->$textField;
89 if( in_array( 'gzip', $flags ) ) {
90 # Deal with optional compression of archived pages.
91 # This can be done periodically via maintenance/compressOld.php, and
92 # as pages are saved if $wgCompressRevisions is set.
93 $text = gzinflate( $text );
96 if( in_array( 'object', $flags ) ) {
97 # Generic compressed storage
98 $obj = unserialize( $text );
100 # Bugger, corrupted my test database by double-serializing
101 if ( !is_object( $obj ) ) {
102 $obj = unserialize( $obj );
105 $text = $obj->getText();
108 global $wgLegacyEncoding;
109 if( $wgLegacyEncoding && !in_array( 'utf-8', $flags ) ) {
110 # Old revisions kept around in a legacy encoding?
111 # Upconvert on demand.
112 global $wgInputEncoding, $wgContLang;
113 $text = $wgContLang->iconv( $wgLegacyEncoding, $wgInputEncoding, $text );
115 wfProfileOut( $fname );
120 * If $wgCompressRevisions is enabled, we will compress data.
121 * The input string is modified in place.
122 * Return value is the flags field: contains 'gzip' if the
123 * data is compressed, and 'utf-8' if we're saving in UTF-8
127 * @param mixed $text reference to a text
130 function compressRevisionText( &$text ) {
131 global $wgCompressRevisions, $wgUseLatin1;
133 if( !$wgUseLatin1 ) {
134 # Revisions not marked this way will be converted
135 # on load if $wgLegacyCharset is set in the future.
138 if( $wgCompressRevisions ) {
139 if( function_exists( 'gzdeflate' ) ) {
140 $text = gzdeflate( $text );
143 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
146 return implode( ',', $flags );
150 * Note that getContent/loadContent may follow redirects if
151 * not told otherwise, and so may cause a change to mTitle.
154 * @return Return the text of this revision
156 function getContent( $noredir ) {
159 # Get variables from query string :P
160 $action = $wgRequest->getText( 'action', 'view' );
161 $section = $wgRequest->getText( 'section' );
163 $fname = 'Article::getContent';
164 wfProfileIn( $fname );
166 if ( 0 == $this->getID() ) {
167 if ( 'edit' == $action ) {
168 wfProfileOut( $fname );
169 return ''; # was "newarticletext", now moved above the box)
171 wfProfileOut( $fname );
172 return wfMsg( 'noarticletext' );
174 $this->loadContent( $noredir );
175 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
176 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
177 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
180 wfProfileOut( $fname );
181 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
183 if($action=='edit') {
185 if($section=='new') {
186 wfProfileOut( $fname );
190 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
191 # comments to be stripped as well)
192 $rv=$this->getSection($this->mContent
,$section);
193 wfProfileOut( $fname );
197 wfProfileOut( $fname );
198 return $this->mContent
;
204 * This function returns the text of a section, specified by a number ($section).
205 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
206 * the first section before any such heading (section 0).
208 * If a section contains subsections, these are also returned.
210 * @param string $text text to look in
211 * @param integer $section section number
212 * @return string text of the requested section
214 function getSection($text,$section) {
216 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
217 # comments to be stripped as well)
219 $parser=new Parser();
220 $parser->mOutputType
=OT_WIKI
;
221 $striptext=$parser->strip($text, $striparray, true);
223 # now that we can be sure that no pseudo-sections are in the source,
224 # split it up by section
227 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
229 PREG_SPLIT_DELIM_CAPTURE
);
233 $headline=$secs[$section*2-1];
234 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
237 # translate wiki heading into level
238 if(strpos($hlevel,'=')!==false) {
239 $hlevel=strlen($hlevel);
242 $rv=$headline. $secs[$section*2];
246 while(!empty($secs[$count*2-1]) && !$break) {
248 $subheadline=$secs[$count*2-1];
249 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
250 $subhlevel=$matches[1];
251 if(strpos($subhlevel,'=')!==false) {
252 $subhlevel=strlen($subhlevel);
254 if($subhlevel > $hlevel) {
255 $rv.=$subheadline.$secs[$count*2];
257 if($subhlevel <= $hlevel) {
264 # reinsert stripped tags
265 $rv=$parser->unstrip($rv,$striparray);
266 $rv=$parser->unstripNoWiki($rv,$striparray);
273 * Return an array of the columns of the "cur"-table
275 function &getCurContentFields() {
276 global $wgArticleCurContentFields;
277 if ( !$wgArticleCurContentFields ) {
278 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
279 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
281 return $wgArticleCurContentFields;
285 * Return an array of the columns of the "old"-table
287 function &getOldContentFields() {
288 global $wgArticleOldContentFields;
289 if ( !$wgArticleOldContentFields ) {
290 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
291 'old_user','old_user_text','old_comment','old_flags' );
293 return $wgArticleOldContentFields;
297 * Return the oldid of the article that is to be shown.
298 * For requests with a "direction", this is not the oldid of the
301 function getOldID() {
302 global $wgRequest, $wgOut;
305 if ( isset( $lastid ) ) {
309 $oldid = $wgRequest->getVal( 'oldid' );
310 if ( isset( $oldid ) ) {
311 $dbr =& $this->getDB();
312 $oldid = IntVal( $oldid );
313 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
314 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
318 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
320 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
321 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
330 return @$oldid; # "@" to be able to return "unset" without PHP complaining
335 * Load the revision (including cur_text) into this object
337 function loadContent( $noredir = false ) {
338 global $wgOut, $wgRequest;
340 if ( $this->mContentLoaded
) return;
342 $dbr =& $this->getDB();
344 $oldid = $this->getOldID();
345 $redirect = $wgRequest->getVal( 'redirect' );
347 $fname = 'Article::loadContent';
349 # Pre-fill content with error message so that if something
350 # fails we'll have something telling us what we intended.
352 $t = $this->mTitle
->getPrefixedText();
354 if ( isset( $oldid ) ) {
355 $t .= ',oldid='.$oldid;
357 if ( isset( $redirect ) ) {
358 $redirect = ($redirect == 'no') ?
'no' : 'yes';
359 $t .= ',redirect='.$redirect;
361 $this->mContent
= wfMsg( 'missingarticle', $t );
363 if ( ! $oldid ) { # Retrieve current version
364 $id = $this->getID();
365 if ( 0 == $id ) return;
367 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
368 $this->getSelectOptions() );
369 if ( $s === false ) {
373 # If we got a redirect, follow it (unless we've been told
374 # not to by either the function parameter or the query
375 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
376 $rt = Title
::newFromRedirect( $s->cur_text
);
377 # process if title object is valid and not special:userlogout
378 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
379 # Gotta hand redirects to special pages differently:
380 # Fill the HTTP response "Location" header and ignore
381 # the rest of the page we're on.
383 if ( $rt->getInterwiki() != '' ) {
384 $wgOut->redirect( $rt->getFullURL() ) ;
387 if ( $rt->getNamespace() == NS_SPECIAL
) {
388 $wgOut->redirect( $rt->getFullURL() );
391 $rid = $rt->getArticleID();
393 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
394 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
396 if ( $redirRow !== false ) {
397 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
405 $this->mContent
= $s->cur_text
;
406 $this->mUser
= $s->cur_user
;
407 $this->mUserText
= $s->cur_user_text
;
408 $this->mComment
= $s->cur_comment
;
409 $this->mCounter
= $s->cur_counter
;
410 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
411 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
412 $this->mTitle
->loadRestrictions( $s->cur_restrictions
);
413 } else { # oldid set, retrieve historical version
414 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
415 $fname, $this->getSelectOptions() );
416 if ( $s === false ) {
420 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
421 $this->mTitle
->getDBkey() != $s->old_title
) {
422 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
423 $this->mTitle
= $oldTitle;
424 $wgTitle = $oldTitle;
426 $this->mContent
= Article
::getRevisionText( $s );
427 $this->mUser
= $s->old_user
;
428 $this->mUserText
= $s->old_user_text
;
429 $this->mComment
= $s->old_comment
;
431 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
433 $this->mContentLoaded
= true;
434 return $this->mContent
;
438 * Gets the article text without using so many damn globals
439 * Returns false on error
441 * @param integer $oldid
443 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
444 if ( $this->mContentLoaded
) {
445 return $this->mContent
;
447 $this->mContent
= false;
449 $fname = 'Article::getContentWithout';
450 $dbr =& $this->getDB();
452 if ( ! $oldid ) { # Retrieve current version
453 $id = $this->getID();
458 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
459 $fname, $this->getSelectOptions() );
460 if ( $s === false ) {
464 # If we got a redirect, follow it (unless we've been told
465 # not to by either the function parameter or the query
467 $rt = Title
::newFromRedirect( $s->cur_text
);
468 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
469 $rid = $rt->getArticleID();
471 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
472 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
474 if ( $redirRow !== false ) {
475 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
483 $this->mContent
= $s->cur_text
;
484 $this->mUser
= $s->cur_user
;
485 $this->mUserText
= $s->cur_user_text
;
486 $this->mComment
= $s->cur_comment
;
487 $this->mCounter
= $s->cur_counter
;
488 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
489 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
490 $this->mTitle
->loadRestrictions( $s->cur_restrictions
);
491 } else { # oldid set, retrieve historical version
492 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
493 $fname, $this->getSelectOptions() );
494 if ( $s === false ) {
497 $this->mContent
= Article
::getRevisionText( $s );
498 $this->mUser
= $s->old_user
;
499 $this->mUserText
= $s->old_user_text
;
500 $this->mComment
= $s->old_comment
;
502 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
504 $this->mContentLoaded
= true;
505 return $this->mContent
;
509 * Read/write accessor to select FOR UPDATE
511 function forUpdate( $x = NULL ) {
512 return wfSetVar( $this->mForUpdate
, $x );
516 * Get the database which should be used for reads
519 if ( $this->mForUpdate
) {
520 return wfGetDB( DB_MASTER
);
522 return wfGetDB( DB_SLAVE
);
527 * Get options for all SELECT statements
528 * Can pass an option array, to which the class-wide options will be appended
530 function getSelectOptions( $options = '' ) {
531 if ( $this->mForUpdate
) {
533 $options[] = 'FOR UPDATE';
535 $options = 'FOR UPDATE';
542 * Return the Article ID
545 if( $this->mTitle
) {
546 return $this->mTitle
->getArticleID();
553 * Get the view count for this article
555 function getCount() {
556 if ( -1 == $this->mCounter
) {
557 $id = $this->getID();
558 $dbr =& $this->getDB();
559 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
560 'Article::getCount', $this->getSelectOptions() );
562 return $this->mCounter
;
566 * Would the given text make this article a "good" article (i.e.,
567 * suitable for including in the article count)?
569 function isCountable( $text ) {
570 global $wgUseCommaCount;
572 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
573 if ( $this->isRedirect( $text ) ) { return 0; }
574 $token = ($wgUseCommaCount ?
',' : '[[' );
575 if ( false === strstr( $text, $token ) ) { return 0; }
580 * Tests if the article text represents a redirect
582 function isRedirect( $text = false ) {
583 if ( $text === false ) {
584 $this->loadContent();
585 $titleObj = Title
::newFromRedirect( $this->mText
);
587 $titleObj = Title
::newFromRedirect( $text );
589 return $titleObj !== NULL;
593 * Loads everything from cur except cur_text
594 * This isn't necessary for all uses, so it's only done if needed.
597 function loadLastEdit() {
599 if ( -1 != $this->mUser
) return;
601 $fname = 'Article::loadLastEdit';
603 $dbr =& $this->getDB();
604 $s = $dbr->selectRow( 'cur',
605 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
606 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
608 if ( $s !== false ) {
609 $this->mUser
= $s->cur_user
;
610 $this->mUserText
= $s->cur_user_text
;
611 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
612 $this->mComment
= $s->cur_comment
;
613 $this->mMinorEdit
= $s->cur_minor_edit
;
617 function getTimestamp() {
618 $this->loadLastEdit();
619 return $this->mTimestamp
;
623 $this->loadLastEdit();
627 function getUserText() {
628 $this->loadLastEdit();
629 return $this->mUserText
;
632 function getComment() {
633 $this->loadLastEdit();
634 return $this->mComment
;
637 function getMinorEdit() {
638 $this->loadLastEdit();
639 return $this->mMinorEdit
;
642 function getContributors($limit = 0, $offset = 0) {
643 $fname = 'Article::getContributors';
645 # XXX: this is expensive; cache this info somewhere.
647 $title = $this->mTitle
;
649 $dbr =& $this->getDB();
650 $oldTable = $dbr->tableName( 'old' );
651 $userTable = $dbr->tableName( 'user' );
652 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
653 $ns = $title->getNamespace();
654 $user = $this->getUser();
656 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
657 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
658 WHERE old_namespace = $user
659 AND old_title = $encDBkey
660 AND old_user != $user
661 GROUP BY old_user, old_user_text, user_real_name
662 ORDER BY timestamp DESC";
664 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
665 $sql .= ' '. $this->getSelectOptions();
667 $res = $dbr->query($sql, $fname);
669 while ( $line = $dbr->fetchObject( $res ) ) {
670 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
673 $dbr->freeResult($res);
678 * This is the default action of the script: just view the page of
682 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
683 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
685 $sk = $wgUser->getSkin();
687 $fname = 'Article::view';
688 wfProfileIn( $fname );
689 # Get variables from query string
690 $oldid = $this->getOldID();
691 $diff = $wgRequest->getVal( 'diff' );
692 $rcid = $wgRequest->getVal( 'rcid' );
694 $wgOut->setArticleFlag( true );
695 $wgOut->setRobotpolicy( 'index,follow' );
696 # If we got diff and oldid in the query, we want to see a
697 # diff page instead of the article.
699 if ( !is_null( $diff ) ) {
700 require_once( 'DifferenceEngine.php' );
701 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
702 $de = new DifferenceEngine( $oldid, $diff, $rcid );
705 # Run view updates for current revision only
706 $this->viewUpdates();
708 wfProfileOut( $fname );
711 if ( empty( $oldid ) && $this->checkTouched() ) {
712 if( $wgOut->checkLastModified( $this->mTouched
) ){
713 wfProfileOut( $fname );
715 } else if ( $this->tryFileCache() ) {
716 # tell wgOut that output is taken care of
718 $this->viewUpdates();
719 wfProfileOut( $fname );
723 # Should the parser cache be used?
724 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
732 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
736 if ( !$outputDone ) {
737 $text = $this->getContent( false ); # May change mTitle by following a redirect
739 # Another whitelist check in case oldid or redirects are altering the title
740 if ( !$this->mTitle
->userCanRead() ) {
741 $wgOut->loginToUse();
747 # We're looking at an old revision
749 if ( !empty( $oldid ) ) {
750 $this->setOldSubtitle( $oldid );
751 $wgOut->setRobotpolicy( 'noindex,follow' );
753 if ( '' != $this->mRedirectedFrom
) {
754 $sk = $wgUser->getSkin();
755 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
757 $s = wfMsg( 'redirectedfrom', $redir );
758 $wgOut->setSubtitle( $s );
760 # Can't cache redirects
764 # wrap user css and user js in pre and don't parse
765 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
767 $this->mTitle
->getNamespace() == NS_USER
&&
768 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
770 $wgOut->addWikiText( wfMsg('clearyourcache'));
771 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
772 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
774 $imageUrl = $wgStylePath.'/common/images/redirect.png';
775 $targetUrl = $rt->escapeLocalURL();
776 $titleText = htmlspecialchars( $rt->getPrefixedText() );
777 $link = $sk->makeLinkObj( $rt );
779 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
780 '<span class="redirectText">'.$link.'</span>' );
782 } else if ( $pcache ) {
783 # Display content and save to parser cache
784 $wgOut->addPrimaryWikiText( $text, $this );
786 # Display content, don't attempt to save to parser cache
787 $wgOut->addWikiText( $text );
790 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
791 # If we have been passed an &rcid= parameter, we want to give the user a
792 # chance to mark this new article as patrolled.
793 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
794 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
796 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
797 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
798 'action=markpatrolled&rcid='.$rcid )
802 # Put link titles into the link cache
803 $wgOut->transformBuffer();
805 # Add link titles as META keywords
806 $wgOut->addMetaTags() ;
808 $this->viewUpdates();
809 wfProfileOut( $fname );
811 $wgUser->clearNotification( $this->mTitle
);
815 * Theoretically we could defer these whole insert and update
816 * functions for after display, but that's taking a big leap
817 * of faith, and we want to be able to report database
818 * errors at some point.
821 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
822 global $wgOut, $wgUser;
823 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
825 $fname = 'Article::insertNewArticle';
827 $this->mCountAdjustment
= $this->isCountable( $text );
829 $ns = $this->mTitle
->getNamespace();
830 $ttl = $this->mTitle
->getDBkey();
831 $text = $this->preSaveTransform( $text );
832 if ( $this->isRedirect( $text ) ) { $redir = 1; }
835 $now = wfTimestampNow();
836 $won = wfInvertTimestamp( $now );
839 $dbw =& wfGetDB( DB_MASTER
);
841 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
843 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
845 $dbw->insert( 'cur', array(
847 'cur_namespace' => $ns,
850 'cur_comment' => $summary,
851 'cur_user' => $wgUser->getID(),
852 'cur_timestamp' => $dbw->timestamp($now),
853 'cur_minor_edit' => $isminor,
855 'cur_restrictions' => '',
856 'cur_user_text' => $wgUser->getName(),
857 'cur_is_redirect' => $redir,
859 'cur_random' => $rand,
860 'cur_touched' => $dbw->timestamp($now),
861 'inverse_timestamp' => $won,
864 $newid = $dbw->insertId();
865 $this->mTitle
->resetArticleID( $newid );
867 Article
::onArticleCreate( $this->mTitle
);
868 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
871 if(!$this->mTitle
->userIsWatching()) $this->watch();
873 if ( $this->mTitle
->userIsWatching() ) {
878 # The talk page isn't in the regular link tables, so we need to update manually:
879 $talkns = $ns ^
1; # talk -> normal; normal -> talk
880 $dbw->update( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
881 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
883 # standard deferred updates
884 $this->editUpdates( $text, $summary, $isminor, $now );
886 $oldid = 0; # new article
887 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
892 * Side effects: loads last edit if $edittime is NULL
894 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
895 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
896 if(is_null($edittime)) {
897 $this->loadLastEdit();
898 $oldtext = $this->getContent( true );
900 $dbw =& wfGetDB( DB_MASTER
);
901 $ns = $this->mTitle
->getNamespace();
902 $title = $this->mTitle
->getDBkey();
903 $obj = $dbw->selectRow( 'old',
904 array( 'old_text','old_flags'),
905 array( 'old_namespace' => $ns, 'old_title' => $title,
906 'old_timestamp' => $dbw->timestamp($edittime)),
908 $oldtext = Article
::getRevisionText( $obj );
910 if ($section != '') {
911 if($section=='new') {
912 if($summary) $subject="== {$summary} ==\n\n";
913 $text=$oldtext."\n\n".$subject.$text;
916 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
917 # comments to be stripped as well)
919 $parser=new Parser();
920 $parser->mOutputType
=OT_WIKI
;
921 $oldtext=$parser->strip($oldtext, $striparray, true);
923 # now that we can be sure that no pseudo-sections are in the source,
925 # Unfortunately we can't simply do a preg_replace because that might
926 # replace the wrong section, so we have to use the section counter instead
927 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
928 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
929 $secs[$section*2]=$text."\n\n"; // replace with edited
931 # section 0 is top (intro) section
934 # headline of old section - we need to go through this section
935 # to determine if there are any subsections that now need to
936 # be erased, as the mother section has been replaced with
937 # the text of all subsections.
938 $headline=$secs[$section*2-1];
939 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
942 # determine headline level for wikimarkup headings
943 if(strpos($hlevel,'=')!==false) {
944 $hlevel=strlen($hlevel);
947 $secs[$section*2-1]=''; // erase old headline
950 while(!empty($secs[$count*2-1]) && !$break) {
952 $subheadline=$secs[$count*2-1];
954 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
955 $subhlevel=$matches[1];
956 if(strpos($subhlevel,'=')!==false) {
957 $subhlevel=strlen($subhlevel);
959 if($subhlevel > $hlevel) {
960 // erase old subsections
961 $secs[$count*2-1]='';
964 if($subhlevel <= $hlevel) {
972 $text=join('',$secs);
973 # reinsert the stuff that we stripped out earlier
974 $text=$parser->unstrip($text,$striparray);
975 $text=$parser->unstripNoWiki($text,$striparray);
983 * Change an existing article. Puts the previous version back into the old table, updates RC
984 * and all necessary caches, mostly via the deferred update array.
986 * It is possible to call this function from a command-line script, but note that you should
987 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
989 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
990 global $wgOut, $wgUser;
991 global $wgDBtransactions, $wgMwRedir;
992 global $wgUseSquid, $wgInternalServer;
994 $fname = 'Article::updateArticle';
997 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
998 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
999 if ( $this->isRedirect( $text ) ) {
1000 # Remove all content but redirect
1001 # This could be done by reconstructing the redirect from a title given by
1002 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1004 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1006 $text = $m[1] . "\n";
1009 else { $redir = 0; }
1011 $text = $this->preSaveTransform( $text );
1012 $dbw =& wfGetDB( DB_MASTER
);
1014 # Update article, but only if changed.
1016 # It's important that we either rollback or complete, otherwise an attacker could
1017 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1018 # could conceivably have the same effect, especially if cur is locked for long periods.
1019 if( $wgDBtransactions ) {
1020 $dbw->query( 'BEGIN', $fname );
1022 $userAbort = ignore_user_abort( true );
1025 $oldtext = $this->getContent( true );
1027 if ( 0 != strcmp( $text, $oldtext ) ) {
1028 $this->mCountAdjustment
= $this->isCountable( $text )
1029 - $this->isCountable( $oldtext );
1030 $now = wfTimestampNow();
1031 $won = wfInvertTimestamp( $now );
1033 # First update the cur row
1034 $dbw->update( 'cur',
1036 'cur_text' => $text,
1037 'cur_comment' => $summary,
1038 'cur_minor_edit' => $me2,
1039 'cur_user' => $wgUser->getID(),
1040 'cur_timestamp' => $dbw->timestamp($now),
1041 'cur_user_text' => $wgUser->getName(),
1042 'cur_is_redirect' => $redir,
1044 'cur_touched' => $dbw->timestamp($now),
1045 'inverse_timestamp' => $won
1046 ), array( /* WHERE */
1047 'cur_id' => $this->getID(),
1048 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1052 if( $dbw->affectedRows() == 0 ) {
1053 /* Belated edit conflict! Run away!! */
1056 # Now insert the previous revision into old
1058 # This overwrites $oldtext if revision compression is on
1059 $flags = Article
::compressRevisionText( $oldtext );
1061 $dbw->insert( 'old',
1063 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1064 'old_namespace' => $this->mTitle
->getNamespace(),
1065 'old_title' => $this->mTitle
->getDBkey(),
1066 'old_text' => $oldtext,
1067 'old_comment' => $this->getComment(),
1068 'old_user' => $this->getUser(),
1069 'old_user_text' => $this->getUserText(),
1070 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1071 'old_minor_edit' => $me1,
1072 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1073 'old_flags' => $flags,
1077 $oldid = $dbw->insertId();
1079 $bot = (int)($wgUser->isBot() ||
$forceBot);
1080 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1081 $oldid, $this->getTimestamp(), $bot );
1082 Article
::onArticleEdit( $this->mTitle
);
1086 if( $wgDBtransactions ) {
1087 $dbw->query( 'COMMIT', $fname );
1089 ignore_user_abort( $userAbort );
1094 if (!$this->mTitle
->userIsWatching()) $this->watch();
1096 if ( $this->mTitle
->userIsWatching() ) {
1100 # standard deferred updates
1101 $this->editUpdates( $text, $summary, $minor, $now );
1105 # Template namespace
1106 # Purge all articles linking here
1107 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1108 $titles = $this->mTitle
->getLinksTo();
1109 Title
::touchArray( $titles );
1110 if ( $wgUseSquid ) {
1111 foreach ( $titles as $title ) {
1112 $urls[] = $title->getInternalURL();
1118 if ( $wgUseSquid ) {
1119 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1120 $u = new SquidUpdate( $urls );
1124 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $oldid );
1130 * After we've either updated or inserted the article, update
1131 * the link tables and redirect to the new page.
1133 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1134 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1136 $wgLinkCache = new LinkCache();
1138 $wgLinkCache->forUpdate( true );
1140 # Get old version of link table to allow incremental link updates
1141 $wgLinkCache->preFill( $this->mTitle
);
1142 $wgLinkCache->clear();
1144 # Parse the text and replace links with placeholders
1145 $wgOut = new OutputPage();
1146 $wgOut->addWikiText( $text );
1148 # Look up the links in the DB and add them to the link cache
1149 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1151 if( $this->isRedirect( $text ) )
1155 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1157 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1158 # this will be improved later (to-do)
1160 include_once( "UserMailer.php" );
1161 $wgEnotif = new EmailNotification ();
1162 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1167 * @todo document this function a bit more
1169 function validate () {
1170 global $wgOut, $wgUseValidation;
1171 if( $wgUseValidation ) {
1172 require_once ( 'SpecialValidate.php' ) ;
1173 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1174 $wgOut->setRobotpolicy( 'noindex,follow' );
1175 if( $this->mTitle
->getNamespace() != 0 ) {
1176 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1179 $v = new Validation
;
1180 $v->validate_form( $this->mTitle
->getDBkey() );
1182 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1187 * Mark this particular edit as patrolled
1189 function markpatrolled() {
1190 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1191 $wgOut->setRobotpolicy( 'noindex,follow' );
1193 if ( !$wgUseRCPatrol )
1195 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1198 if ( $wgUser->getID() == 0 )
1200 $wgOut->loginToUse();
1203 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1205 $wgOut->sysopRequired();
1208 $rcid = $wgRequest->getVal( 'rcid' );
1209 if ( !is_null ( $rcid ) )
1211 RecentChange
::markPatrolled( $rcid );
1212 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1213 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1215 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1216 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1220 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1226 * Add this page to $wgUser's watchlist
1231 global $wgUser, $wgOut;
1233 if ( 0 == $wgUser->getID() ) {
1234 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1237 if ( wfReadOnly() ) {
1238 $wgOut->readOnlyPage();
1242 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1244 $wgUser->addWatch( $this->mTitle
);
1245 $wgUser->saveSettings();
1247 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1249 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1250 $wgOut->setRobotpolicy( 'noindex,follow' );
1252 $link = $this->mTitle
->getPrefixedText();
1253 $text = wfMsg( 'addedwatchtext', $link );
1254 $wgOut->addWikiText( $text );
1257 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1261 * Stop watching a page
1264 function unwatch() {
1266 global $wgUser, $wgOut;
1268 if ( 0 == $wgUser->getID() ) {
1269 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1272 if ( wfReadOnly() ) {
1273 $wgOut->readOnlyPage();
1277 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1279 $wgUser->removeWatch( $this->mTitle
);
1280 $wgUser->saveSettings();
1282 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1284 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1285 $wgOut->setRobotpolicy( 'noindex,follow' );
1287 $link = $this->mTitle
->getPrefixedText();
1288 $text = wfMsg( 'removedwatchtext', $link );
1289 $wgOut->addWikiText( $text );
1292 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1298 function protect( $limit = 'sysop' ) {
1299 global $wgUser, $wgOut, $wgRequest;
1301 if ( ! $wgUser->isAllowed('protect') ) {
1302 $wgOut->sysopRequired();
1305 if ( wfReadOnly() ) {
1306 $wgOut->readOnlyPage();
1309 $id = $this->mTitle
->getArticleID();
1311 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1315 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1316 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1317 $reason = $wgRequest->getText( 'wpReasonProtect' );
1321 $restrictions = "move=" . $limit;
1323 $restrictions .= ":edit=" . $limit;
1325 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1327 $dbw =& wfGetDB( DB_MASTER
);
1328 $dbw->update( 'cur',
1330 'cur_touched' => $dbw->timestamp(),
1331 'cur_restrictions' => $restrictions
1332 ), array( /* WHERE */
1334 ), 'Article::protect'
1337 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1339 $log = new LogPage( 'protect' );
1340 if ( $limit === '' ) {
1341 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1343 $log->addEntry( 'protect', $this->mTitle
, $reason );
1345 $wgOut->redirect( $this->mTitle
->getFullURL() );
1349 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1350 return $this->confirmProtect( '', $reason, $limit );
1355 * Output protection confirmation dialog
1357 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1360 wfDebug( "Article::confirmProtect\n" );
1362 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1363 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1369 if ( $limit === '' ) {
1370 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1371 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1372 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1373 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1374 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1375 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1377 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1378 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1379 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1380 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1381 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1382 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1383 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1386 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1389 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1393 <label for='wpReasonProtect'>{$protcom}:</label>
1396 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1404 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1407 <label for='wpConfirmProtect'>{$check}</label>
1410 if($moveonly != '') {
1414 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1417 <label for='wpMoveOnly'>{$moveonly}</label>
1425 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1431 $wgOut->returnToMain( false );
1435 * Unprotect the pages
1437 function unprotect() {
1438 return $this->protect( '' );
1442 * UI entry point for page deletion
1445 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1446 $fname = 'Article::delete';
1447 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1448 $reason = $wgRequest->getText( 'wpReason' );
1450 # This code desperately needs to be totally rewritten
1453 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1454 $wgOut->sysopRequired();
1457 if ( wfReadOnly() ) {
1458 $wgOut->readOnlyPage();
1462 # Better double-check that it hasn't been deleted yet!
1463 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1464 if ( ( '' == trim( $this->mTitle
->getText() ) )
1465 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1466 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1471 $this->doDelete( $reason );
1475 # determine whether this page has earlier revisions
1476 # and insert a warning if it does
1477 # we select the text because it might be useful below
1478 $dbr =& $this->getDB();
1479 $ns = $this->mTitle
->getNamespace();
1480 $title = $this->mTitle
->getDBkey();
1481 $old = $dbr->selectRow( 'old',
1482 array( 'old_text', 'old_flags' ),
1484 'old_namespace' => $ns,
1485 'old_title' => $title,
1486 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1489 if( $old !== false && !$confirm ) {
1490 $skin=$wgUser->getSkin();
1491 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1492 $wgOut->addHTML( $skin->historyLink() .'</b>');
1496 $s = $dbr->selectRow( 'cur',
1497 array( 'cur_text' ),
1499 'cur_namespace' => $ns,
1500 'cur_title' => $title,
1501 ), $fname, $this->getSelectOptions()
1504 if( $s !== false ) {
1505 # if this is a mini-text, we can paste part of it into the deletion reason
1507 #if this is empty, an earlier revision may contain "useful" text
1509 if($s->cur_text
!= '') {
1513 $text = Article
::getRevisionText( $old );
1519 $length=strlen($text);
1521 # this should not happen, since it is not possible to store an empty, new
1522 # page. Let's insert a standard text in case it does, though
1523 if($length == 0 && $reason === '') {
1524 $reason = wfMsg('exblank');
1527 if($length < 500 && $reason === '') {
1529 # comment field=255, let's grep the first 150 to have some user
1531 $text=substr($text,0,150);
1532 # let's strip out newlines and HTML tags
1533 $text=preg_replace('/\"/',"'",$text);
1534 $text=preg_replace('/\</','<',$text);
1535 $text=preg_replace('/\>/','>',$text);
1536 $text=preg_replace("/[\n\r]/",'',$text);
1538 $reason=wfMsg('excontent'). " '".$text;
1540 $reason=wfMsg('exbeforeblank') . " '".$text;
1542 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1547 return $this->confirmDelete( '', $reason );
1551 * Output deletion confirmation dialog
1553 function confirmDelete( $par, $reason ) {
1556 wfDebug( "Article::confirmDelete\n" );
1558 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1559 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1560 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1561 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1563 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1565 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1566 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1567 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1570 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1574 <label for='wpReason'>{$delcom}:</label>
1577 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1585 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1588 <label for='wpConfirm'>{$check}</label>
1594 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1600 $wgOut->returnToMain( false );
1605 * Perform a deletion and output success or failure messages
1607 function doDelete( $reason ) {
1608 global $wgOut, $wgUser, $wgContLang;
1609 $fname = 'Article::doDelete';
1610 wfDebug( $fname."\n" );
1612 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1613 if ( $this->doDeleteArticle( $reason ) ) {
1614 $deleted = $this->mTitle
->getPrefixedText();
1616 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1617 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1619 $sk = $wgUser->getSkin();
1620 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1621 ':' . wfMsgForContent( 'dellogpage' ),
1622 wfMsg( 'deletionlog' ) );
1624 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1626 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1627 $wgOut->returnToMain( false );
1628 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1630 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1636 * Back-end article deletion
1637 * Deletes the article with database consistency, writes logs, purges caches
1640 function doDeleteArticle( $reason ) {
1642 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1644 $fname = 'Article::doDeleteArticle';
1645 wfDebug( $fname."\n" );
1647 $dbw =& wfGetDB( DB_MASTER
);
1648 $ns = $this->mTitle
->getNamespace();
1649 $t = $this->mTitle
->getDBkey();
1650 $id = $this->mTitle
->getArticleID();
1652 if ( $t == '' ||
$id == 0 ) {
1656 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1657 array_push( $wgDeferredUpdateList, $u );
1659 $linksTo = $this->mTitle
->getLinksTo();
1662 if ( $wgUseSquid ) {
1664 $this->mTitle
->getInternalURL(),
1665 $this->mTitle
->getInternalURL( 'history' )
1667 foreach ( $linksTo as $linkTo ) {
1668 $urls[] = $linkTo->getInternalURL();
1671 $u = new SquidUpdate( $urls );
1672 array_push( $wgDeferredUpdateList, $u );
1676 # Client and file cache invalidation
1677 Title
::touchArray( $linksTo );
1679 # Move article and history to the "archive" table
1680 $archiveTable = $dbw->tableName( 'archive' );
1681 $oldTable = $dbw->tableName( 'old' );
1682 $curTable = $dbw->tableName( 'cur' );
1683 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1684 $linksTable = $dbw->tableName( 'links' );
1685 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1687 $dbw->insertSelect( 'archive', 'cur',
1689 'ar_namespace' => 'cur_namespace',
1690 'ar_title' => 'cur_title',
1691 'ar_text' => 'cur_text',
1692 'ar_comment' => 'cur_comment',
1693 'ar_user' => 'cur_user',
1694 'ar_user_text' => 'cur_user_text',
1695 'ar_timestamp' => 'cur_timestamp',
1696 'ar_minor_edit' => 'cur_minor_edit',
1699 'cur_namespace' => $ns,
1704 $dbw->insertSelect( 'archive', 'old',
1706 'ar_namespace' => 'old_namespace',
1707 'ar_title' => 'old_title',
1708 'ar_text' => 'old_text',
1709 'ar_comment' => 'old_comment',
1710 'ar_user' => 'old_user',
1711 'ar_user_text' => 'old_user_text',
1712 'ar_timestamp' => 'old_timestamp',
1713 'ar_minor_edit' => 'old_minor_edit',
1714 'ar_flags' => 'old_flags'
1716 'old_namespace' => $ns,
1721 # Now that it's safely backed up, delete it
1723 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1724 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1725 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1727 # Finally, clean up the link tables
1728 $t = $this->mTitle
->getPrefixedDBkey();
1730 Article
::onArticleDelete( $this->mTitle
);
1732 # Insert broken links
1733 $brokenLinks = array();
1734 foreach ( $linksTo as $titleObj ) {
1735 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1736 $linkID = $titleObj->getArticleID();
1737 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1739 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1742 $dbw->delete( 'links', array( 'l_to' => $id ) );
1743 $dbw->delete( 'links', array( 'l_from' => $id ) );
1744 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1745 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1746 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1749 $log = new LogPage( 'delete' );
1750 $log->addEntry( 'delete', $this->mTitle
, $reason );
1752 # Clear the cached article id so the interface doesn't act like we exist
1753 $this->mTitle
->resetArticleID( 0 );
1754 $this->mTitle
->mArticleID
= 0;
1759 * Revert a modification
1761 function rollback() {
1762 global $wgUser, $wgOut, $wgRequest;
1763 $fname = 'Article::rollback';
1765 if ( ! $wgUser->isAllowed('rollback') ) {
1766 $wgOut->sysopRequired();
1769 if ( wfReadOnly() ) {
1770 $wgOut->readOnlyPage( $this->getContent( true ) );
1773 $dbw =& wfGetDB( DB_MASTER
);
1775 # Enhanced rollback, marks edits rc_bot=1
1776 $bot = $wgRequest->getBool( 'bot' );
1778 # Replace all this user's current edits with the next one down
1779 $tt = $this->mTitle
->getDBKey();
1780 $n = $this->mTitle
->getNamespace();
1782 # Get the last editor, lock table exclusively
1783 $s = $dbw->selectRow( 'cur',
1784 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1785 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1786 $fname, 'FOR UPDATE'
1788 if( $s === false ) {
1790 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1793 $ut = $dbw->strencode( $s->cur_user_text
);
1794 $uid = $s->cur_user
;
1797 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1798 if( $from != $s->cur_user_text
) {
1799 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1800 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1801 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1802 htmlspecialchars( $from ),
1803 htmlspecialchars( $s->cur_user_text
) ) );
1804 if($s->cur_comment
!= '') {
1806 wfMsg('editcomment',
1807 htmlspecialchars( $s->cur_comment
) ) );
1812 # Get the last edit not by this guy
1813 $s = $dbw->selectRow( 'old',
1814 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1816 'old_namespace' => $n,
1818 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1819 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1821 if( $s === false ) {
1823 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1824 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1829 # Mark all reverted edits as bot
1830 $dbw->update( 'recentchanges',
1833 ), array( /* WHERE */
1835 "rc_timestamp > '{$s->old_timestamp}'",
1841 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1842 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1843 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1844 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1845 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1846 Article
::onArticleEdit( $this->mTitle
);
1847 $wgOut->returnToMain( false );
1852 * Do standard deferred updates after page view
1855 function viewUpdates() {
1856 global $wgDeferredUpdateList;
1858 if ( 0 != $this->getID() ) {
1859 global $wgDisableCounters;
1860 if( !$wgDisableCounters ) {
1861 Article
::incViewCount( $this->getID() );
1862 $u = new SiteStatsUpdate( 1, 0, 0 );
1863 array_push( $wgDeferredUpdateList, $u );
1867 # Update newtalk status if user is reading their own
1871 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1872 $this->mTitle
->getText() == $wgUser->getName()) {
1873 require_once( 'UserTalkUpdate.php' );
1874 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1879 * Do standard deferred updates after page edit.
1880 * Every 1000th edit, prune the recent changes table.
1882 * @param string $text
1884 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1885 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1886 global $wgMessageCache, $wgUser;
1889 if ( 0 == mt_rand( 0, 999 ) ) {
1890 $dbw =& wfGetDB( DB_MASTER
);
1891 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1892 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1893 $dbw->query( $sql );
1895 $id = $this->getID();
1896 $title = $this->mTitle
->getPrefixedDBkey();
1897 $shortTitle = $this->mTitle
->getDBkey();
1899 $adj = $this->mCountAdjustment
;
1902 $u = new LinksUpdate( $id, $title );
1903 array_push( $wgDeferredUpdateList, $u );
1904 $u = new SiteStatsUpdate( 0, 1, $adj );
1905 array_push( $wgDeferredUpdateList, $u );
1906 $u = new SearchUpdate( $id, $title, $text );
1907 array_push( $wgDeferredUpdateList, $u );
1909 # If this is another user's talk page,
1910 # create a watchlist entry for this page
1912 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1913 $shortTitle != $wgUser->getName()) {
1914 require_once( 'UserTalkUpdate.php' );
1915 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1918 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1919 $wgMessageCache->replace( $shortTitle, $text );
1925 * @todo document this function
1927 * @param string $oldid Revision ID of this article revision
1929 function setOldSubtitle( $oldid=0 ) {
1930 global $wgLang, $wgOut, $wgUser;
1932 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1933 $sk = $wgUser->getSkin();
1934 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1935 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1936 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1937 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1938 $wgOut->setSubtitle( $r );
1942 * This function is called right before saving the wikitext,
1943 * so we can do things like signatures and links-in-context.
1945 * @param string $text
1947 function preSaveTransform( $text ) {
1948 global $wgParser, $wgUser;
1949 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1952 /* Caching functions */
1955 * checkLastModified returns true if it has taken care of all
1956 * output to the client that is necessary for this request.
1957 * (that is, it has sent a cached version of the page)
1959 function tryFileCache() {
1960 static $called = false;
1962 wfDebug( " tryFileCache() -- called twice!?\n" );
1966 if($this->isFileCacheable()) {
1967 $touched = $this->mTouched
;
1968 $cache = new CacheManager( $this->mTitle
);
1969 if($cache->isFileCacheGood( $touched )) {
1971 wfDebug( " tryFileCache() - about to load\n" );
1972 $cache->loadFromFileCache();
1975 wfDebug( " tryFileCache() - starting buffer\n" );
1976 ob_start( array(&$cache, 'saveToFileCache' ) );
1979 wfDebug( " tryFileCache() - not cacheable\n" );
1984 * Check if the page can be cached
1987 function isFileCacheable() {
1988 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1989 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1991 return $wgUseFileCache
1992 and (!$wgShowIPinHeader)
1993 and ($this->getID() != 0)
1994 and ($wgUser->getId() == 0)
1995 and (!$wgUser->getNewtalk())
1996 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1997 and (empty( $action ) ||
$action == 'view')
1998 and (!isset($oldid))
2000 and (!isset($redirect))
2001 and (!isset($printable))
2002 and (!$this->mRedirectedFrom
);
2006 * Loads cur_touched and returns a value indicating if it should be used
2009 function checkTouched() {
2010 $fname = 'Article::checkTouched';
2011 $id = $this->getID();
2012 $dbr =& $this->getDB();
2013 $s = $dbr->selectRow( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
2014 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
2015 if( $s !== false ) {
2016 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
2017 return !$s->cur_is_redirect
;
2024 * Edit an article without doing all that other stuff
2026 * @param string $text text submitted
2027 * @param string $comment comment submitted
2028 * @param integer $minor whereas it's a minor modification
2030 function quickEdit( $text, $comment = '', $minor = 0 ) {
2032 $fname = 'Article::quickEdit';
2033 wfProfileIn( $fname );
2035 $dbw =& wfGetDB( DB_MASTER
);
2036 $ns = $this->mTitle
->getNamespace();
2037 $dbkey = $this->mTitle
->getDBkey();
2038 $encDbKey = $dbw->strencode( $dbkey );
2039 $timestamp = wfTimestampNow();
2042 $dbw->insertSelect( 'old', 'cur',
2044 'old_namespace' => 'cur_namespace',
2045 'old_title' => 'cur_title',
2046 'old_text' => 'cur_text',
2047 'old_comment' => 'cur_comment',
2048 'old_user' => 'cur_user',
2049 'old_user_text' => 'cur_user_text',
2050 'old_timestamp' => 'cur_timestamp',
2051 'inverse_timestamp' => '99999999999999-cur_timestamp',
2053 'cur_namespace' => $ns,
2054 'cur_title' => $dbkey,
2058 # Use the affected row count to determine if the article is new
2059 $numRows = $dbw->affectedRows();
2061 # Make an array of fields to be inserted
2063 'cur_text' => $text,
2064 'cur_timestamp' => $timestamp,
2065 'cur_user' => $wgUser->getID(),
2066 'cur_user_text' => $wgUser->getName(),
2067 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2068 'cur_comment' => $comment,
2069 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2070 'cur_minor_edit' => intval($minor),
2071 'cur_touched' => $dbw->timestamp($timestamp),
2076 $fields['cur_is_new'] = 0;
2077 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2079 # Insert new article
2080 $fields['cur_is_new'] = 1;
2081 $fields['cur_namespace'] = $ns;
2082 $fields['cur_title'] = $dbkey;
2083 $fields['cur_random'] = $rand = wfRandom();
2084 $dbw->insert( 'cur', $fields, $fname );
2086 wfProfileOut( $fname );
2090 * Used to increment the view counter
2093 * @param integer $id article id
2095 function incViewCount( $id ) {
2096 $id = intval( $id );
2097 global $wgHitcounterUpdateFreq;
2099 $dbw =& wfGetDB( DB_MASTER
);
2100 $curTable = $dbw->tableName( 'cur' );
2101 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2102 $acchitsTable = $dbw->tableName( 'acchits' );
2104 if( $wgHitcounterUpdateFreq <= 1 ){ //
2105 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2109 # Not important enough to warrant an error page in case of failure
2110 $oldignore = $dbw->ignoreErrors( true );
2112 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2114 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2115 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2116 # Most of the time (or on SQL errors), skip row count check
2117 $dbw->ignoreErrors( $oldignore );
2121 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2122 $row = $dbw->fetchObject( $res );
2123 $rown = intval( $row->n
);
2124 if( $rown >= $wgHitcounterUpdateFreq ){
2125 wfProfileIn( 'Article::incViewCount-collect' );
2126 $old_user_abort = ignore_user_abort( true );
2128 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2129 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2130 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2132 $dbw->query("DELETE FROM $hitcounterTable");
2133 $dbw->query('UNLOCK TABLES');
2134 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2135 'WHERE cur_id = hc_id');
2136 $dbw->query("DROP TABLE $acchitsTable");
2138 ignore_user_abort( $old_user_abort );
2139 wfProfileOut( 'Article::incViewCount-collect' );
2141 $dbw->ignoreErrors( $oldignore );
2145 * The onArticle*() functions are supposed to be a kind of hooks
2146 * which should be called whenever any of the specified actions
2149 * This is a good place to put code to clear caches, for instance.
2151 * This is called on page move and undelete, as well as edit
2153 * @param $title_obj a title object
2156 function onArticleCreate($title_obj) {
2157 global $wgUseSquid, $wgDeferredUpdateList;
2159 $titles = $title_obj->getBrokenLinksTo();
2162 if ( $wgUseSquid ) {
2163 $urls = $title_obj->getSquidURLs();
2164 foreach ( $titles as $linkTitle ) {
2165 $urls[] = $linkTitle->getInternalURL();
2167 $u = new SquidUpdate( $urls );
2168 array_push( $wgDeferredUpdateList, $u );
2171 # Clear persistent link cache
2172 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2175 function onArticleDelete($title_obj) {
2176 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2178 function onArticleEdit($title_obj) {
2179 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2184 * Info about this page
2187 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2188 $fname = 'Article::info';
2190 if ( !$wgAllowPageInfo ) {
2191 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2195 $dbr =& $this->getDB();
2197 $basenamespace = $wgTitle->getNamespace() & (~
1);
2198 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2199 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2200 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2201 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2202 $wgOut->setPagetitle( $fullTitle );
2203 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2205 # first, see if the page exists at all.
2206 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2208 $wgOut->addHTML( wfMsg('noarticletext') );
2210 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2211 $this->getSelectOptions() );
2212 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2213 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2214 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2216 # to find number of distinct authors, we need to do some
2217 # funny stuff because of the cur/old table split:
2218 # - first, find the name of the 'cur' author
2219 # - then, find the number of *other* authors in 'old'
2222 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2223 $this->getSelectOptions() );
2225 # find number of 'old' authors excluding 'cur' author
2226 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2227 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2228 $this->getSelectOptions() ) +
1;
2230 # now for the Talk page ...
2231 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2232 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2235 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2239 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2240 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2242 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2246 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2247 $this->getSelectOptions() );
2248 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2249 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2250 $fname, $this->getSelectOptions() );
2252 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );