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( 'link', $flags ) ) {
90 $text = Article
::followLink( $text );
91 } elseif ( in_array( 'gzip', $flags ) ) {
92 # Deal with optional compression of archived pages.
93 # This can be done periodically via maintenance/compressOld.php, and
94 # as pages are saved if $wgCompressRevisions is set.
95 return gzinflate( $text );
101 * If $wgCompressRevisions is enabled, we will compress datas
103 * @param mixed $text reference to a text
104 * @return string 'gzip' if it get compressed, '' overwise
106 function compressRevisionText( &$text ) {
107 global $wgCompressRevisions;
108 if( !$wgCompressRevisions ) {
111 if( !function_exists( 'gzdeflate' ) ) {
112 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
115 $text = gzdeflate( $text );
120 * Returns the text associated with a "link" type old table row
123 * @return string $text|false
125 function followLink( $link ) {
126 # Split the link into fields and values
127 $lines = explode( '\n', $link );
129 $locations = array();
130 foreach ( $lines as $line ) {
132 if ( $line{0} == '#' ) {
136 if ( preg_match( '/^(.*?)\s*:\s*(.*)$/', $line, $matches ) ) {
137 $field = strtolower($matches[1]);
138 $value = $matches[2];
139 if ( $field == 'hash' ) {
141 } elseif ( $field == 'location' ) {
142 $locations[] = $value;
147 if ( $hash === '' ) {
151 # Look in each specified location for the text
153 foreach ( $locations as $location ) {
154 $text = Article
::fetchFromLocation( $location, $hash );
155 if ( $text !== false ) {
168 function fetchFromLocation( $location, $hash ) {
169 global $wgLoadBalancer;
170 $fname = 'fetchFromLocation';
171 wfProfileIn( $fname );
173 $p = strpos( $location, ':' );
174 if ( $p === false ) {
175 wfProfileOut( $fname );
179 $type = substr( $location, 0, $p );
183 # MySQL locations are specified by mysql://<machineID>/<dbname>/<tblname>/<index>
184 # Machine ID 0 is the current connection
185 if ( preg_match( '/^mysql:\/\/(\d+)\/([A-Za-z_]+)\/([A-Za-z_]+)\/([A-Za-z_]+)$/',
186 $location, $matches ) ) {
187 $machineID = $matches[1];
188 $dbName = $matches[2];
189 $tblName = $matches[3];
190 $index = $matches[4];
191 if ( $machineID == 0 ) {
193 $db =& $this->getDB();
195 # Alternate connection
196 $db =& $wgLoadBalancer->getConnection( $machineID );
198 if ( array_key_exists( $machineId, $wgKnownMysqlServers ) ) {
199 # Try to open, return false on failure
200 $params = $wgKnownDBServers[$machineId];
201 $db = Database
::newFromParams( $params['server'], $params['user'], $params['password'],
202 $dbName, 1, DBO_IGNORE
);
205 if ( $db->isOpen() ) {
206 $index = $db->strencode( $index );
207 $res = $db->query( "SELECT blob_data FROM $dbName.$tblName " .
208 "WHERE blob_index='$index' " . $this->getSelectOptions(), $fname );
209 $row = $db->fetchObject( $res );
210 $text = $row->text_data
;
215 # File locations are of the form file://<filename>, relative to the current directory
216 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
217 $filename = strstr( $location, 'file://' );
218 $text = @file_get_contents
( $matches[1] );
220 if ( $text !== false ) {
221 # Got text, now we need to interpret it
222 # The first line contains information about how to do this
223 $p = strpos( $text, '\n' );
224 $type = substr( $text, 0, $p );
225 $text = substr( $text, $p +
1 );
230 $text = gzinflate( $text );
233 $object = unserialize( $text );
234 $text = $object->getItem( $hash );
240 wfProfileOut( $fname );
245 * Note that getContent/loadContent may follow redirects if
246 * not told otherwise, and so may cause a change to mTitle.
249 * @return Return the text of this revision
251 function getContent( $noredir ) {
254 # Get variables from query string :P
255 $action = $wgRequest->getText( 'action', 'view' );
256 $section = $wgRequest->getText( 'section' );
258 $fname = 'Article::getContent';
259 wfProfileIn( $fname );
261 if ( 0 == $this->getID() ) {
262 if ( 'edit' == $action ) {
263 wfProfileOut( $fname );
264 return ''; # was "newarticletext", now moved above the box)
266 wfProfileOut( $fname );
267 return wfMsg( 'noarticletext' );
269 $this->loadContent( $noredir );
270 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
271 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
272 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
275 wfProfileOut( $fname );
276 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
278 if($action=='edit') {
280 if($section=='new') {
281 wfProfileOut( $fname );
285 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
286 # comments to be stripped as well)
287 $rv=$this->getSection($this->mContent
,$section);
288 wfProfileOut( $fname );
292 wfProfileOut( $fname );
293 return $this->mContent
;
299 * This function returns the text of a section, specified by a number ($section).
300 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
301 * the first section before any such heading (section 0).
303 * If a section contains subsections, these are also returned.
305 * @param string $text text to look in
306 * @param integer $section section number
307 * @return string text of the requested section
309 function getSection($text,$section) {
311 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
312 # comments to be stripped as well)
314 $parser=new Parser();
315 $parser->mOutputType
=OT_WIKI
;
316 $striptext=$parser->strip($text, $striparray, true);
318 # now that we can be sure that no pseudo-sections are in the source,
319 # split it up by section
322 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
324 PREG_SPLIT_DELIM_CAPTURE
);
328 $headline=$secs[$section*2-1];
329 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
332 # translate wiki heading into level
333 if(strpos($hlevel,'=')!==false) {
334 $hlevel=strlen($hlevel);
337 $rv=$headline. $secs[$section*2];
341 while(!empty($secs[$count*2-1]) && !$break) {
343 $subheadline=$secs[$count*2-1];
344 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
345 $subhlevel=$matches[1];
346 if(strpos($subhlevel,'=')!==false) {
347 $subhlevel=strlen($subhlevel);
349 if($subhlevel > $hlevel) {
350 $rv.=$subheadline.$secs[$count*2];
352 if($subhlevel <= $hlevel) {
359 # reinsert stripped tags
360 $rv=$parser->unstrip($rv,$striparray);
361 $rv=$parser->unstripNoWiki($rv,$striparray);
368 * Return an array of the columns of the "cur"-table
370 function &getCurContentFields() {
371 global $wgArticleCurContentFields;
372 if ( !$wgArticleCurContentFields ) {
373 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
374 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
376 return $wgArticleCurContentFields;
380 * Return an array of the columns of the "old"-table
382 function &getOldContentFields() {
383 global $wgArticleOldContentFields;
384 if ( !$wgArticleOldContentFields ) {
385 $wgArticleOldContentFields = array( 'old_articleid','old_text','old_timestamp',
386 'old_user','old_user_text','old_comment','old_flags' );
388 return $wgArticleOldContentFields;
392 * Load the revision (including cur_text) into this object
394 function loadContent( $noredir = false ) {
395 global $wgOut, $wgRequest;
397 if ( $this->mContentLoaded
) return;
399 $dbr =& $this->getDB();
401 $oldid = $wgRequest->getVal( 'oldid' );
402 $redirect = $wgRequest->getVal( 'redirect' );
404 $fname = 'Article::loadContent';
406 # Pre-fill content with error message so that if something
407 # fails we'll have something telling us what we intended.
409 $t = $this->mTitle
->getPrefixedText();
410 if ( isset( $oldid ) ) {
411 $oldid = IntVal( $oldid );
412 $t .= ',oldid='.$oldid;
414 if ( isset( $redirect ) ) {
415 $redirect = ($redirect == 'no') ?
'no' : 'yes';
416 $t .= ',redirect='.$redirect;
418 $this->mContent
= wfMsg( 'missingarticle', $t );
420 if ( ! $oldid ) { # Retrieve current version
421 $id = $this->getID();
422 if ( 0 == $id ) return;
424 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
425 $this->getSelectOptions() );
426 if ( $s === false ) {
430 # If we got a redirect, follow it (unless we've been told
431 # not to by either the function parameter or the query
432 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
433 $rt = Title
::newFromRedirect( $s->cur_text
);
434 # process if title object is valid and not special:userlogout
435 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
436 # Gotta hand redirects to special pages differently:
437 # Fill the HTTP response "Location" header and ignore
438 # the rest of the page we're on.
440 if ( $rt->getInterwiki() != '' ) {
441 $wgOut->redirect( $rt->getFullURL() ) ;
444 if ( $rt->getNamespace() == NS_SPECIAL
) {
445 $wgOut->redirect( $rt->getFullURL() );
448 $rid = $rt->getArticleID();
450 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
451 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
453 if ( $redirRow !== false ) {
454 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
462 $this->mContent
= $s->cur_text
;
463 $this->mUser
= $s->cur_user
;
464 $this->mUserText
= $s->cur_user_text
;
465 $this->mComment
= $s->cur_comment
;
466 $this->mCounter
= $s->cur_counter
;
467 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
468 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
469 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
470 $this->mTitle
->mRestrictionsLoaded
= true;
471 } else { # oldid set, retrieve historical version
472 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
473 $fname, $this->getSelectOptions() );
474 if ( $s === false ) {
478 if( $this->mTitle
->getArticleID() != $s->old_articleid
) {
479 $oldTitle = Title
::newFromID( $s->old_articleid
);
480 $this->mTitle
= $oldTitle;
481 $wgTitle = $oldTitle;
483 $this->mContent
= Article
::getRevisionText( $s );
484 $this->mUser
= $s->old_user
;
485 $this->mUserText
= $s->old_user_text
;
486 $this->mComment
= $s->old_comment
;
488 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
490 $this->mContentLoaded
= true;
491 return $this->mContent
;
495 * Gets the article text without using so many damn globals
496 * Returns false on error
498 * @param integer $oldid
500 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
501 if ( $this->mContentLoaded
) {
502 return $this->mContent
;
504 $this->mContent
= false;
506 $fname = 'Article::getContentWithout';
507 $dbr =& $this->getDB();
509 if ( ! $oldid ) { # Retrieve current version
510 $id = $this->getID();
515 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
516 $fname, $this->getSelectOptions() );
517 if ( $s === false ) {
521 # If we got a redirect, follow it (unless we've been told
522 # not to by either the function parameter or the query
524 $rt = Title
::newFromRedirect( $s->cur_text
);
525 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
526 $rid = $rt->getArticleID();
528 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
529 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
531 if ( $redirRow !== false ) {
532 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
540 $this->mContent
= $s->cur_text
;
541 $this->mUser
= $s->cur_user
;
542 $this->mUserText
= $s->cur_user_text
;
543 $this->mComment
= $s->cur_comment
;
544 $this->mCounter
= $s->cur_counter
;
545 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
546 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
547 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
548 $this->mTitle
->mRestrictionsLoaded
= true;
549 } else { # oldid set, retrieve historical version
550 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
551 $fname, $this->getSelectOptions() );
552 if ( $s === false ) {
555 $this->mContent
= Article
::getRevisionText( $s );
556 $this->mUser
= $s->old_user
;
557 $this->mUserText
= $s->old_user_text
;
558 $this->mComment
= $s->old_comment
;
560 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
562 $this->mContentLoaded
= true;
563 return $this->mContent
;
567 * Read/write accessor to select FOR UPDATE
569 function forUpdate( $x = NULL ) {
570 return wfSetVar( $this->mForUpdate
, $x );
574 * Get the database which should be used for reads
577 if ( $this->mForUpdate
) {
578 return wfGetDB( DB_MASTER
);
580 return wfGetDB( DB_SLAVE
);
585 * Get options for all SELECT statements
586 * Can pass an option array, to which the class-wide options will be appended
588 function getSelectOptions( $options = '' ) {
589 if ( $this->mForUpdate
) {
591 $options[] = 'FOR UPDATE';
593 $options = 'FOR UPDATE';
600 * Return the Article ID
603 if( $this->mTitle
) {
604 return $this->mTitle
->getArticleID();
611 * Get the view count for this article
613 function getCount() {
614 if ( -1 == $this->mCounter
) {
615 $id = $this->getID();
616 $dbr =& $this->getDB();
617 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
618 'Article::getCount', $this->getSelectOptions() );
620 return $this->mCounter
;
624 * Would the given text make this article a "good" article (i.e.,
625 * suitable for including in the article count)?
627 function isCountable( $text ) {
628 global $wgUseCommaCount;
630 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
631 if ( $this->isRedirect( $text ) ) { return 0; }
632 $token = ($wgUseCommaCount ?
',' : '[[' );
633 if ( false === strstr( $text, $token ) ) { return 0; }
638 * Tests if the article text represents a redirect
640 function isRedirect( $text = false ) {
641 if ( $text === false ) {
642 $this->loadContent();
643 $titleObj = Title
::newFromRedirect( $this->mText
);
645 $titleObj = Title
::newFromRedirect( $text );
647 return $titleObj !== NULL;
651 * Loads everything from cur except cur_text
652 * This isn't necessary for all uses, so it's only done if needed.
655 function loadLastEdit() {
657 if ( -1 != $this->mUser
) return;
659 $fname = 'Article::loadLastEdit';
661 $dbr =& $this->getDB();
662 $s = $dbr->getArray( 'cur',
663 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
664 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
666 if ( $s !== false ) {
667 $this->mUser
= $s->cur_user
;
668 $this->mUserText
= $s->cur_user_text
;
669 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
670 $this->mComment
= $s->cur_comment
;
671 $this->mMinorEdit
= $s->cur_minor_edit
;
675 function getTimestamp() {
676 $this->loadLastEdit();
677 return $this->mTimestamp
;
681 $this->loadLastEdit();
685 function getUserText() {
686 $this->loadLastEdit();
687 return $this->mUserText
;
690 function getComment() {
691 $this->loadLastEdit();
692 return $this->mComment
;
695 function getMinorEdit() {
696 $this->loadLastEdit();
697 return $this->mMinorEdit
;
700 function getContributors($limit = 0, $offset = 0) {
701 $fname = 'Article::getContributors';
703 # XXX: this is expensive; cache this info somewhere.
705 $title = $this->mTitle
;
707 $dbr =& $this->getDB();
708 $oldTable = $dbr->tableName( 'old' );
709 $userTable = $dbr->tableName( 'user' );
710 $artid = $title->getArticleID();
711 $ns = $title->getNamespace();
712 $user = $this->getUser();
714 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
715 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
716 WHERE old_articleid = $artid
717 AND old_user != $user
718 GROUP BY old_user, old_user_text, user_real_name
719 ORDER BY timestamp DESC";
721 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
722 $sql .= ' '. $this->getSelectOptions();
724 $res = $dbr->query($sql, $fname);
726 while ( $line = $dbr->fetchObject( $res ) ) {
727 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
730 $dbr->freeResult($res);
735 * This is the default action of the script: just view the page of
739 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol;
740 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
741 $sk = $wgUser->getSkin();
743 $fname = 'Article::view';
744 wfProfileIn( $fname );
745 # Get variables from query string
746 $oldid = $wgRequest->getVal( 'oldid' );
747 $diff = $wgRequest->getVal( 'diff' );
748 $rcid = $wgRequest->getVal( 'rcid' );
750 $wgOut->setArticleFlag( true );
751 $wgOut->setRobotpolicy( 'index,follow' );
752 # If we got diff and oldid in the query, we want to see a
753 # diff page instead of the article.
755 if ( !is_null( $diff ) ) {
756 require_once( 'DifferenceEngine.php' );
757 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
758 $de = new DifferenceEngine( $oldid, $diff, $rcid );
760 wfProfileOut( $fname );
762 # Run view updates for current revision only
763 $this->viewUpdates();
767 if ( empty( $oldid ) && $this->checkTouched() ) {
768 if( $wgOut->checkLastModified( $this->mTouched
) ){
770 } else if ( $this->tryFileCache() ) {
771 # tell wgOut that output is taken care of
773 $this->viewUpdates();
777 # Should the parser cache be used?
778 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
786 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
790 if ( !$outputDone ) {
791 $text = $this->getContent( false ); # May change mTitle by following a redirect
793 # Another whitelist check in case oldid or redirects are altering the title
794 if ( !$this->mTitle
->userCanRead() ) {
795 $wgOut->loginToUse();
801 # We're looking at an old revision
803 if ( !empty( $oldid ) ) {
804 $this->setOldSubtitle();
805 $wgOut->setRobotpolicy( 'noindex,follow' );
807 if ( '' != $this->mRedirectedFrom
) {
808 $sk = $wgUser->getSkin();
809 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
811 $s = wfMsg( 'redirectedfrom', $redir );
812 $wgOut->setSubtitle( $s );
814 # Can't cache redirects
818 # wrap user css and user js in pre and don't parse
819 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
821 $this->mTitle
->getNamespace() == NS_USER
&&
822 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
824 $wgOut->addWikiText( wfMsg('clearyourcache'));
825 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
826 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
828 $imageUrl = $wgStylePath.'/common/images/redirect.png';
829 $targetUrl = $rt->escapeLocalURL();
830 $titleText = htmlspecialchars( $rt->getPrefixedText() );
831 $link = $sk->makeLinkObj( $rt );
832 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'">' .
833 '<span class="redirectText">'.$link.'</span>' );
834 } else if ( $pcache ) {
835 # Display content and save to parser cache
836 $wgOut->addPrimaryWikiText( $text, $this );
838 # Display content, don't attempt to save to parser cache
839 $wgOut->addWikiText( $text );
842 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
843 # If we have been passed an &rcid= parameter, we want to give the user a
844 # chance to mark this new article as patrolled.
845 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
846 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
848 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
849 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
850 'action=markpatrolled&rcid='.$rcid )
854 # Put link titles into the link cache
855 $wgOut->transformBuffer();
857 # Add link titles as META keywords
858 $wgOut->addMetaTags() ;
860 $this->viewUpdates();
861 wfProfileOut( $fname );
865 * Theoretically we could defer these whole insert and update
866 * functions for after display, but that's taking a big leap
867 * of faith, and we want to be able to report database
868 * errors at some point.
871 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
872 global $wgOut, $wgUser;
873 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
875 $fname = 'Article::insertNewArticle';
877 $this->mCountAdjustment
= $this->isCountable( $text );
879 $ns = $this->mTitle
->getNamespace();
880 $ttl = $this->mTitle
->getDBkey();
881 $text = $this->preSaveTransform( $text );
882 if ( $this->isRedirect( $text ) ) { $redir = 1; }
885 $now = wfTimestampNow();
886 $won = wfInvertTimestamp( $now );
888 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
889 $dbw =& wfGetDB( DB_MASTER
);
891 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
893 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
895 $dbw->insertArray( 'cur', array(
897 'cur_namespace' => $ns,
900 'cur_comment' => $summary,
901 'cur_user' => $wgUser->getID(),
902 'cur_timestamp' => $dbw->timestamp($now),
903 'cur_minor_edit' => $isminor,
905 'cur_restrictions' => '',
906 'cur_user_text' => $wgUser->getName(),
907 'cur_is_redirect' => $redir,
909 'cur_random' => $rand,
910 'cur_touched' => $dbw->timestamp($now),
911 'inverse_timestamp' => $won,
914 $newid = $dbw->insertId();
915 $this->mTitle
->resetArticleID( $newid );
917 Article
::onArticleCreate( $this->mTitle
);
918 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
921 if(!$this->mTitle
->userIsWatching()) $this->watch();
923 if ( $this->mTitle
->userIsWatching() ) {
928 # The talk page isn't in the regular link tables, so we need to update manually:
929 $talkns = $ns ^
1; # talk -> normal; normal -> talk
930 $dbw->updateArray( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
931 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
933 # standard deferred updates
934 $this->editUpdates( $text );
936 $this->showArticle( $text, wfMsg( 'newarticle' ) );
941 * Side effects: loads last edit if $edittime is NULL
943 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
944 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
945 if(is_null($edittime)) {
946 $this->loadLastEdit();
947 $oldtext = $this->getContent( true );
949 $dbw =& wfGetDB( DB_MASTER
);
950 $ns = $this->mTitle
->getNamespace();
951 $title = $this->mTitle
->getDBkey();
952 $aid = $this->mTitle
->getArticleID();
953 $obj = $dbw->getArray( 'old',
954 array( 'old_text','old_flags'),
955 array( 'old_articleid' => $aid,
956 'old_timestamp' => $dbw->timestamp($edittime)),
958 $oldtext = Article
::getRevisionText( $obj );
960 if ($section != '') {
961 if($section=='new') {
962 if($summary) $subject="== {$summary} ==\n\n";
963 $text=$oldtext."\n\n".$subject.$text;
966 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
967 # comments to be stripped as well)
969 $parser=new Parser();
970 $parser->mOutputType
=OT_WIKI
;
971 $oldtext=$parser->strip($oldtext, $striparray, true);
973 # now that we can be sure that no pseudo-sections are in the source,
975 # Unfortunately we can't simply do a preg_replace because that might
976 # replace the wrong section, so we have to use the section counter instead
977 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
978 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
979 $secs[$section*2]=$text."\n\n"; // replace with edited
981 # section 0 is top (intro) section
984 # headline of old section - we need to go through this section
985 # to determine if there are any subsections that now need to
986 # be erased, as the mother section has been replaced with
987 # the text of all subsections.
988 $headline=$secs[$section*2-1];
989 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
992 # determine headline level for wikimarkup headings
993 if(strpos($hlevel,'=')!==false) {
994 $hlevel=strlen($hlevel);
997 $secs[$section*2-1]=''; // erase old headline
1000 while(!empty($secs[$count*2-1]) && !$break) {
1002 $subheadline=$secs[$count*2-1];
1004 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1005 $subhlevel=$matches[1];
1006 if(strpos($subhlevel,'=')!==false) {
1007 $subhlevel=strlen($subhlevel);
1009 if($subhlevel > $hlevel) {
1010 // erase old subsections
1011 $secs[$count*2-1]='';
1014 if($subhlevel <= $hlevel) {
1022 $text=join('',$secs);
1023 # reinsert the stuff that we stripped out earlier
1024 $text=$parser->unstrip($text,$striparray);
1025 $text=$parser->unstripNoWiki($text,$striparray);
1033 * Change an existing article. Puts the previous version back into the old table, updates RC
1034 * and all necessary caches, mostly via the deferred update array.
1036 * It is possible to call this function from a command-line script, but note that you should
1037 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1039 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1040 global $wgOut, $wgUser;
1041 global $wgDBtransactions, $wgMwRedir;
1042 global $wgUseSquid, $wgInternalServer;
1044 $fname = 'Article::updateArticle';
1047 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
1048 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
1049 if ( $this->isRedirect( $text ) ) {
1050 # Remove all content but redirect
1051 # This could be done by reconstructing the redirect from a title given by
1052 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1054 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1056 $text = $m[1] . "\n";
1059 else { $redir = 0; }
1061 $text = $this->preSaveTransform( $text );
1062 $dbw =& wfGetDB( DB_MASTER
);
1064 # Update article, but only if changed.
1066 # It's important that we either rollback or complete, otherwise an attacker could
1067 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1068 # could conceivably have the same effect, especially if cur is locked for long periods.
1069 if( $wgDBtransactions ) {
1070 $dbw->query( 'BEGIN', $fname );
1072 $userAbort = ignore_user_abort( true );
1075 $oldtext = $this->getContent( true );
1077 if ( 0 != strcmp( $text, $oldtext ) ) {
1078 $this->mCountAdjustment
= $this->isCountable( $text )
1079 - $this->isCountable( $oldtext );
1080 $now = wfTimestampNow();
1081 $won = wfInvertTimestamp( $now );
1083 # First update the cur row
1084 $dbw->updateArray( 'cur',
1086 'cur_text' => $text,
1087 'cur_comment' => $summary,
1088 'cur_minor_edit' => $me2,
1089 'cur_user' => $wgUser->getID(),
1090 'cur_timestamp' => $dbw->timestamp($now),
1091 'cur_user_text' => $wgUser->getName(),
1092 'cur_is_redirect' => $redir,
1094 'cur_touched' => $dbw->timestamp($now),
1095 'inverse_timestamp' => $won
1096 ), array( /* WHERE */
1097 'cur_id' => $this->getID(),
1098 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1102 if( $dbw->affectedRows() == 0 ) {
1103 /* Belated edit conflict! Run away!! */
1106 # Now insert the previous revision into old
1108 # This overwrites $oldtext if revision compression is on
1109 $flags = Article
::compressRevisionText( $oldtext );
1111 $dbw->insertArray( 'old',
1113 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1114 'old_articleid' => $this->mTitle
->getArticleID(),
1115 'old_text' => $oldtext,
1116 'old_comment' => $this->getComment(),
1117 'old_user' => $this->getUser(),
1118 'old_user_text' => $this->getUserText(),
1119 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1120 'old_minor_edit' => $me1,
1121 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1122 'old_flags' => $flags,
1126 $oldid = $dbw->insertId();
1128 $bot = (int)($wgUser->isBot() ||
$forceBot);
1129 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1130 $oldid, $this->getTimestamp(), $bot );
1131 Article
::onArticleEdit( $this->mTitle
);
1135 if( $wgDBtransactions ) {
1136 $dbw->query( 'COMMIT', $fname );
1138 ignore_user_abort( $userAbort );
1143 if (!$this->mTitle
->userIsWatching()) $this->watch();
1145 if ( $this->mTitle
->userIsWatching() ) {
1149 # standard deferred updates
1150 $this->editUpdates( $text );
1154 # Template namespace
1155 # Purge all articles linking here
1156 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1157 $titles = $this->mTitle
->getLinksTo();
1158 Title
::touchArray( $titles );
1159 if ( $wgUseSquid ) {
1160 foreach ( $titles as $title ) {
1161 $urls[] = $title->getInternalURL();
1167 if ( $wgUseSquid ) {
1168 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1169 $u = new SquidUpdate( $urls );
1173 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1179 * After we've either updated or inserted the article, update
1180 * the link tables and redirect to the new page.
1182 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1183 global $wgOut, $wgUser, $wgLinkCache;
1185 $wgLinkCache = new LinkCache();
1187 $wgLinkCache->forUpdate( true );
1189 # Get old version of link table to allow incremental link updates
1190 $wgLinkCache->preFill( $this->mTitle
);
1191 $wgLinkCache->clear();
1193 # Parse the text and replace links with placeholders
1194 $wgOut = new OutputPage();
1195 $wgOut->addWikiText( $text );
1197 # Look up the links in the DB and add them to the link cache
1198 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1200 if( $this->isRedirect( $text ) )
1204 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1209 * @todo document this function a bit more
1211 function validate () {
1212 global $wgOut, $wgUseValidation;
1213 if( $wgUseValidation ) {
1214 require_once ( 'SpecialValidate.php' ) ;
1215 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1216 $wgOut->setRobotpolicy( 'noindex,follow' );
1217 if( $this->mTitle
->getNamespace() != 0 ) {
1218 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1221 $v = new Validation
;
1222 $v->validate_form( $this->mTitle
->getDBkey() );
1224 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1229 * Mark this particular edit as patrolled
1231 function markpatrolled() {
1232 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1233 $wgOut->setRobotpolicy( 'noindex,follow' );
1235 if ( !$wgUseRCPatrol )
1237 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1240 if ( $wgUser->getID() == 0 )
1242 $wgOut->loginToUse();
1245 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1247 $wgOut->sysopRequired();
1250 $rcid = $wgRequest->getVal( 'rcid' );
1251 if ( !is_null ( $rcid ) )
1253 RecentChange
::markPatrolled( $rcid );
1254 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1255 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1256 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1260 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1266 * Add or remove this page to my watchlist based on value of $add
1268 function watch( $add = true ) {
1269 global $wgUser, $wgOut;
1270 global $wgDeferredUpdateList;
1272 if ( 0 == $wgUser->getID() ) {
1273 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1276 if ( wfReadOnly() ) {
1277 $wgOut->readOnlyPage();
1281 $wgUser->addWatch( $this->mTitle
);
1283 $wgUser->removeWatch( $this->mTitle
);
1285 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1286 $wgOut->setRobotpolicy( 'noindex,follow' );
1288 $sk = $wgUser->getSkin() ;
1289 $link = $this->mTitle
->getPrefixedText();
1292 $text = wfMsg( 'addedwatchtext', $link );
1294 $text = wfMsg( 'removedwatchtext', $link );
1295 $wgOut->addWikiText( $text );
1297 $up = new UserUpdate();
1298 array_push( $wgDeferredUpdateList, $up );
1300 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1304 * Stop watching a page, it act just like a call to watch(false)
1306 function unwatch() {
1307 $this->watch( false );
1313 function protect( $limit = 'sysop' ) {
1314 global $wgUser, $wgOut, $wgRequest;
1316 if ( ! $wgUser->isSysop() ) {
1317 $wgOut->sysopRequired();
1320 if ( wfReadOnly() ) {
1321 $wgOut->readOnlyPage();
1324 $id = $this->mTitle
->getArticleID();
1326 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1330 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1331 $reason = $wgRequest->getText( 'wpReasonProtect' );
1334 $dbw =& wfGetDB( DB_MASTER
);
1335 $dbw->updateArray( 'cur',
1337 'cur_touched' => $dbw->timestamp(),
1338 'cur_restrictions' => (string)$limit
1339 ), array( /* WHERE */
1341 ), 'Article::protect'
1344 $log = new LogPage( 'protect' );
1345 if ( $limit === '' ) {
1346 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1348 $log->addEntry( 'protect', $this->mTitle
, $reason );
1350 $wgOut->redirect( $this->mTitle
->getFullURL() );
1353 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1354 return $this->confirmProtect( '', $reason, $limit );
1359 * Output protection confirmation dialog
1361 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1364 wfDebug( "Article::confirmProtect\n" );
1366 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1367 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1372 if ( $limit === '' ) {
1373 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1374 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1375 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1376 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1377 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1378 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1380 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1381 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1382 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1383 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1384 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1385 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1388 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1391 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1395 <label for='wpReasonProtect'>{$protcom}:</label>
1398 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1406 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1409 <label for='wpConfirmProtect'>{$check}</label>
1415 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1421 $wgOut->returnToMain( false );
1425 * Unprotect the pages
1427 function unprotect() {
1428 return $this->protect( '' );
1432 * UI entry point for page deletion
1435 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1436 $fname = 'Article::delete';
1437 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1438 $reason = $wgRequest->getText( 'wpReason' );
1440 # This code desperately needs to be totally rewritten
1443 if ( ( ! $wgUser->isSysop() ) ) {
1444 $wgOut->sysopRequired();
1447 if ( wfReadOnly() ) {
1448 $wgOut->readOnlyPage();
1452 # Better double-check that it hasn't been deleted yet!
1453 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1454 if ( ( '' == trim( $this->mTitle
->getText() ) )
1455 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1456 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1461 $this->doDelete( $reason );
1465 # determine whether this page has earlier revisions
1466 # and insert a warning if it does
1467 # we select the text because it might be useful below
1468 $dbr =& $this->getDB();
1469 $ns = $this->mTitle
->getNamespace();
1470 $title = $this->mTitle
->getDBkey();
1471 $artid = $this->mTitle
->getArticleID();
1472 $old = $dbr->getArray( 'old',
1473 array( 'old_text', 'old_flags' ),
1474 array( 'old_articleid' => $artid ),
1475 $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1478 if( $old !== false && !$confirm ) {
1479 $skin=$wgUser->getSkin();
1480 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1481 $wgOut->addHTML( $skin->historyLink() .'</b>');
1485 $s = $dbr->getArray( 'cur',
1486 array( 'cur_text' ),
1488 'cur_namespace' => $ns,
1489 'cur_title' => $title,
1490 ), $fname, $this->getSelectOptions()
1493 if( $s !== false ) {
1494 # if this is a mini-text, we can paste part of it into the deletion reason
1496 #if this is empty, an earlier revision may contain "useful" text
1498 if($s->cur_text
!= '') {
1502 $text = Article
::getRevisionText( $old );
1508 $length=strlen($text);
1510 # this should not happen, since it is not possible to store an empty, new
1511 # page. Let's insert a standard text in case it does, though
1512 if($length == 0 && $reason === '') {
1513 $reason = wfMsg('exblank');
1516 if($length < 500 && $reason === '') {
1518 # comment field=255, let's grep the first 150 to have some user
1520 $text=substr($text,0,150);
1521 # let's strip out newlines and HTML tags
1522 $text=preg_replace('/\"/',"'",$text);
1523 $text=preg_replace('/\</','<',$text);
1524 $text=preg_replace('/\>/','>',$text);
1525 $text=preg_replace("/[\n\r]/",'',$text);
1527 $reason=wfMsg('excontent'). " '".$text;
1529 $reason=wfMsg('exbeforeblank') . " '".$text;
1531 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1536 return $this->confirmDelete( '', $reason );
1540 * Output deletion confirmation dialog
1542 function confirmDelete( $par, $reason ) {
1545 wfDebug( "Article::confirmDelete\n" );
1547 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1548 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1549 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1550 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1552 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1554 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1555 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1556 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1559 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1563 <label for='wpReason'>{$delcom}:</label>
1566 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1574 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1577 <label for='wpConfirm'>{$check}</label>
1583 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1589 $wgOut->returnToMain( false );
1594 * Perform a deletion and output success or failure messages
1596 function doDelete( $reason ) {
1597 global $wgOut, $wgUser, $wgContLang;
1598 $fname = 'Article::doDelete';
1599 wfDebug( $fname."\n" );
1601 if ( $this->doDeleteArticle( $reason ) ) {
1602 $deleted = $this->mTitle
->getPrefixedText();
1604 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1605 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1607 $sk = $wgUser->getSkin();
1608 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1609 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1611 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1613 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1614 $wgOut->returnToMain( false );
1616 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1621 * Back-end article deletion
1622 * Deletes the article with database consistency, writes logs, purges caches
1625 function doDeleteArticle( $reason ) {
1627 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1629 $fname = 'Article::doDeleteArticle';
1630 wfDebug( $fname."\n" );
1632 $dbw =& wfGetDB( DB_MASTER
);
1633 $ns = $this->mTitle
->getNamespace();
1634 $t = $this->mTitle
->getDBkey();
1635 $id = $this->mTitle
->getArticleID();
1637 if ( $t == '' ||
$id == 0 ) {
1641 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1642 array_push( $wgDeferredUpdateList, $u );
1644 $linksTo = $this->mTitle
->getLinksTo();
1647 if ( $wgUseSquid ) {
1649 $this->mTitle
->getInternalURL(),
1650 $this->mTitle
->getInternalURL( 'history' )
1652 foreach ( $linksTo as $linkTo ) {
1653 $urls[] = $linkTo->getInternalURL();
1656 $u = new SquidUpdate( $urls );
1657 array_push( $wgDeferredUpdateList, $u );
1661 # Client and file cache invalidation
1662 Title
::touchArray( $linksTo );
1664 # Move article and history to the "archive" table
1665 $archiveTable = $dbw->tableName( 'archive' );
1666 $oldTable = $dbw->tableName( 'old' );
1667 $curTable = $dbw->tableName( 'cur' );
1668 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1669 $linksTable = $dbw->tableName( 'links' );
1670 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1671 $artid = $this->mTitle
->getArticleID();
1673 $dbw->insertSelect( 'archive', 'cur',
1675 'ar_namespace' => 'cur_namespace',
1676 'ar_title' => 'cur_title',
1677 'ar_text' => 'cur_text',
1678 'ar_comment' => 'cur_comment',
1679 'ar_user' => 'cur_user',
1680 'ar_user_text' => 'cur_user_text',
1681 'ar_timestamp' => 'cur_timestamp',
1682 'ar_minor_edit' => 'cur_minor_edit',
1685 'cur_namespace' => $ns,
1690 $dbw->insertSelect( 'archive', 'cur,old',
1692 'ar_namespace' => 'cur_namespace',
1693 'ar_title' => 'cur_title',
1694 'ar_text' => 'old_text',
1695 'ar_comment' => 'old_comment',
1696 'ar_user' => 'old_user',
1697 'ar_user_text' => 'old_user_text',
1698 'ar_timestamp' => 'old_timestamp',
1699 'ar_minor_edit' => 'old_minor_edit',
1700 'ar_flags' => 'old_flags'
1702 'old_articleid' => $artid
1706 # Now that it's safely backed up, delete it
1708 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1709 $dbw->delete( 'old', array( 'old_articleid' => $artid ), $fname );
1710 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1712 # Finally, clean up the link tables
1713 $t = $this->mTitle
->getPrefixedDBkey();
1715 Article
::onArticleDelete( $this->mTitle
);
1717 # Insert broken links
1718 $brokenLinks = array();
1719 foreach ( $linksTo as $titleObj ) {
1720 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1721 $linkID = $titleObj->getArticleID();
1722 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1724 $dbw->insertArray( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1727 $dbw->delete( 'links', array( 'l_to' => $id ) );
1728 $dbw->delete( 'links', array( 'l_from' => $id ) );
1729 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1730 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1731 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1734 $log = new LogPage( 'delete' );
1735 $log->addEntry( 'delete', $this->mTitle
, $reason );
1737 # Clear the cached article id so the interface doesn't act like we exist
1738 $this->mTitle
->resetArticleID( 0 );
1739 $this->mTitle
->mArticleID
= 0;
1744 * Revert a modification
1746 function rollback() {
1747 global $wgUser, $wgOut, $wgRequest;
1748 $fname = 'Article::rollback';
1750 if ( ! $wgUser->isSysop() ) {
1751 $wgOut->sysopRequired();
1754 if ( wfReadOnly() ) {
1755 $wgOut->readOnlyPage( $this->getContent( true ) );
1758 $dbw =& wfGetDB( DB_MASTER
);
1760 # Enhanced rollback, marks edits rc_bot=1
1761 $bot = $wgRequest->getBool( 'bot' );
1763 # Replace all this user's current edits with the next one down
1764 $tt = $this->mTitle
->getDBKey();
1765 $n = $this->mTitle
->getNamespace();
1767 # Get the last editor, lock table exclusively
1768 $s = $dbw->getArray( 'cur',
1769 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1770 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1771 $fname, 'FOR UPDATE'
1773 if( $s === false ) {
1775 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1778 $ut = $dbw->strencode( $s->cur_user_text
);
1779 $uid = $s->cur_user
;
1782 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1783 if( $from != $s->cur_user_text
) {
1784 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1785 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1786 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1787 htmlspecialchars( $from ),
1788 htmlspecialchars( $s->cur_user_text
) ) );
1789 if($s->cur_comment
!= '') {
1791 wfMsg('editcomment',
1792 htmlspecialchars( $s->cur_comment
) ) );
1797 # Get the last edit not by this guy
1798 $s = $dbw->getArray( 'old',
1799 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1801 'old_articleid' => $pid,
1802 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1803 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'articleid_timestamp' )
1805 if( $s === false ) {
1807 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1808 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1813 # Mark all reverted edits as bot
1814 $dbw->updateArray( 'recentchanges',
1817 ), array( /* WHERE */
1819 "rc_timestamp > '{$s->old_timestamp}'",
1825 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1826 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1827 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1828 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1829 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1830 Article
::onArticleEdit( $this->mTitle
);
1831 $wgOut->returnToMain( false );
1836 * Do standard deferred updates after page view
1839 function viewUpdates() {
1840 global $wgDeferredUpdateList;
1841 if ( 0 != $this->getID() ) {
1842 global $wgDisableCounters;
1843 if( !$wgDisableCounters ) {
1844 Article
::incViewCount( $this->getID() );
1845 $u = new SiteStatsUpdate( 1, 0, 0 );
1846 array_push( $wgDeferredUpdateList, $u );
1849 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1850 $this->mTitle
->getDBkey() );
1851 array_push( $wgDeferredUpdateList, $u );
1855 * Do standard deferred updates after page edit.
1856 * Every 1000th edit, prune the recent changes table.
1858 * @param string $text
1860 function editUpdates( $text ) {
1861 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1862 global $wgMessageCache;
1865 if ( 0 == mt_rand( 0, 999 ) ) {
1866 $dbw =& wfGetDB( DB_MASTER
);
1867 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1868 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1869 $dbw->query( $sql );
1871 $id = $this->getID();
1872 $title = $this->mTitle
->getPrefixedDBkey();
1873 $shortTitle = $this->mTitle
->getDBkey();
1875 $adj = $this->mCountAdjustment
;
1878 $u = new LinksUpdate( $id, $title );
1879 array_push( $wgDeferredUpdateList, $u );
1880 $u = new SiteStatsUpdate( 0, 1, $adj );
1881 array_push( $wgDeferredUpdateList, $u );
1882 $u = new SearchUpdate( $id, $title, $text );
1883 array_push( $wgDeferredUpdateList, $u );
1885 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1886 array_push( $wgDeferredUpdateList, $u );
1888 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1889 $wgMessageCache->replace( $shortTitle, $text );
1895 * @todo document this function
1898 function setOldSubtitle() {
1899 global $wgLang, $wgOut, $wgUser;
1901 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1902 $sk = $wgUser->getSkin();
1903 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1904 $r = wfMsg( 'revisionasofwithlink', $td, $lnk );
1905 $wgOut->setSubtitle( $r );
1909 * This function is called right before saving the wikitext,
1910 * so we can do things like signatures and links-in-context.
1912 * @param string $text
1914 function preSaveTransform( $text ) {
1915 global $wgParser, $wgUser;
1916 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1919 /* Caching functions */
1922 * checkLastModified returns true if it has taken care of all
1923 * output to the client that is necessary for this request.
1924 * (that is, it has sent a cached version of the page)
1926 function tryFileCache() {
1927 static $called = false;
1929 wfDebug( " tryFileCache() -- called twice!?\n" );
1933 if($this->isFileCacheable()) {
1934 $touched = $this->mTouched
;
1935 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1936 # Expire the main page quicker
1937 $expire = wfUnix2Timestamp( time() - 3600 );
1938 $touched = max( $expire, $touched );
1940 $cache = new CacheManager( $this->mTitle
);
1941 if($cache->isFileCacheGood( $touched )) {
1943 wfDebug( " tryFileCache() - about to load\n" );
1944 $cache->loadFromFileCache();
1947 wfDebug( " tryFileCache() - starting buffer\n" );
1948 ob_start( array(&$cache, 'saveToFileCache' ) );
1951 wfDebug( " tryFileCache() - not cacheable\n" );
1956 * Check if the page can be cached
1959 function isFileCacheable() {
1960 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1961 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1963 return $wgUseFileCache
1964 and (!$wgShowIPinHeader)
1965 and ($this->getID() != 0)
1966 and ($wgUser->getId() == 0)
1967 and (!$wgUser->getNewtalk())
1968 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1969 and (empty( $action ) ||
$action == 'view')
1970 and (!isset($oldid))
1972 and (!isset($redirect))
1973 and (!isset($printable))
1974 and (!$this->mRedirectedFrom
);
1978 * Loads cur_touched and returns a value indicating if it should be used
1981 function checkTouched() {
1982 $fname = 'Article::checkTouched';
1983 $id = $this->getID();
1984 $dbr =& $this->getDB();
1985 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1986 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1987 if( $s !== false ) {
1988 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1989 return !$s->cur_is_redirect
;
1996 * Edit an article without doing all that other stuff
1998 * @param string $text text submitted
1999 * @param string $comment comment submitted
2000 * @param integer $minor whereas it's a minor modification
2002 function quickEdit( $text, $comment = '', $minor = 0 ) {
2004 $fname = 'Article::quickEdit';
2005 wfProfileIn( $fname );
2007 $dbw =& wfGetDB( DB_MASTER
);
2008 $ns = $this->mTitle
->getNamespace();
2009 $dbkey = $this->mTitle
->getDBkey();
2010 $encDbKey = $dbw->strencode( $dbkey );
2011 $timestamp = wfTimestampNow();
2014 $dbw->insertSelect( 'old', 'cur',
2016 'old_articleid' => 'cur_id',
2017 'old_text' => 'cur_text',
2018 'old_comment' => 'cur_comment',
2019 'old_user' => 'cur_user',
2020 'old_user_text' => 'cur_user_text',
2021 'old_timestamp' => 'cur_timestamp',
2022 'inverse_timestamp' => '99999999999999-cur_timestamp',
2024 'cur_namespace' => $ns,
2025 'cur_title' => $dbkey,
2029 # Use the affected row count to determine if the article is new
2030 $numRows = $dbw->affectedRows();
2032 # Make an array of fields to be inserted
2034 'cur_text' => $text,
2035 'cur_timestamp' => $timestamp,
2036 'cur_user' => $wgUser->getID(),
2037 'cur_user_text' => $wgUser->getName(),
2038 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2039 'cur_comment' => $comment,
2040 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2041 'cur_minor_edit' => intval($minor),
2042 'cur_touched' => $dbw->timestamp($timestamp),
2047 $fields['cur_is_new'] = 0;
2048 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2050 # Insert new article
2051 $fields['cur_is_new'] = 1;
2052 $fields['cur_namespace'] = $ns;
2053 $fields['cur_title'] = $dbkey;
2054 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
2055 $dbw->insertArray( 'cur', $fields, $fname );
2057 wfProfileOut( $fname );
2061 * Used to increment the view counter
2064 * @param integer $id article id
2066 function incViewCount( $id ) {
2067 $id = intval( $id );
2068 global $wgHitcounterUpdateFreq;
2070 $dbw =& wfGetDB( DB_MASTER
);
2071 $curTable = $dbw->tableName( 'cur' );
2072 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2073 $acchitsTable = $dbw->tableName( 'acchits' );
2075 if( $wgHitcounterUpdateFreq <= 1 ){ //
2076 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2080 # Not important enough to warrant an error page in case of failure
2081 $oldignore = $dbw->ignoreErrors( true );
2083 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2085 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2086 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2087 # Most of the time (or on SQL errors), skip row count check
2088 $dbw->ignoreErrors( $oldignore );
2092 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2093 $row = $dbw->fetchObject( $res );
2094 $rown = intval( $row->n
);
2095 if( $rown >= $wgHitcounterUpdateFreq ){
2096 wfProfileIn( 'Article::incViewCount-collect' );
2097 $old_user_abort = ignore_user_abort( true );
2099 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2100 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2101 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2103 $dbw->query("DELETE FROM $hitcounterTable");
2104 $dbw->query('UNLOCK TABLES');
2105 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2106 'WHERE cur_id = hc_id');
2107 $dbw->query("DROP TABLE $acchitsTable");
2109 ignore_user_abort( $old_user_abort );
2110 wfProfileOut( 'Article::incViewCount-collect' );
2112 $dbw->ignoreErrors( $oldignore );
2116 * The onArticle*() functions are supposed to be a kind of hooks
2117 * which should be called whenever any of the specified actions
2120 * This is a good place to put code to clear caches, for instance.
2122 * This is called on page move and undelete, as well as edit
2124 * @param $title_obj a title object
2127 function onArticleCreate($title_obj) {
2128 global $wgUseSquid, $wgDeferredUpdateList;
2130 $titles = $title_obj->getBrokenLinksTo();
2133 if ( $wgUseSquid ) {
2134 $urls = $title_obj->getSquidURLs();
2135 foreach ( $titles as $linkTitle ) {
2136 $urls[] = $linkTitle->getInternalURL();
2138 $u = new SquidUpdate( $urls );
2139 array_push( $wgDeferredUpdateList, $u );
2142 # Clear persistent link cache
2143 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2146 function onArticleDelete($title_obj) {
2147 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2149 function onArticleEdit($title_obj) {
2150 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2155 * Info about this page
2158 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2159 $fname = 'Article::info';
2161 if ( !$wgAllowPageInfo ) {
2162 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2166 $dbr =& $this->getDB();
2168 $basenamespace = $wgTitle->getNamespace() & (~
1);
2169 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2170 $old_clause = array( 'old_articleid' => $wgTitle->getArticleID() );
2171 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2172 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2173 $wgOut->setPagetitle( $fullTitle );
2174 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2176 # first, see if the page exists at all.
2177 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2179 $wgOut->addHTML( wfMsg('noarticletext') );
2181 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2182 $this->getSelectOptions() );
2183 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2184 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2185 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2187 # to find number of distinct authors, we need to do some
2188 # funny stuff because of the cur/old table split:
2189 # - first, find the name of the 'cur' author
2190 # - then, find the number of *other* authors in 'old'
2193 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2194 $this->getSelectOptions() );
2196 # find number of 'old' authors excluding 'cur' author
2197 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2198 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2199 $this->getSelectOptions() ) +
1;
2201 # now for the Talk page ...
2202 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2205 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2209 $oldartid = $dbr->selectField( 'cur', 'cur_id',
2210 $cur_clause, $fname, $this->getSelectOptions());
2211 $old_clause = array( 'old_articleid' => $oldartid );
2212 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2213 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2215 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2219 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2220 $this->getSelectOptions() );
2221 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2222 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2223 $fname, $this->getSelectOptions() );
2225 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );