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_namespace','old_title','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
->getNamespace() != $s->old_namespace ||
479 $this->mTitle
->getDBkey() != $s->old_title
) {
480 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
481 $this->mTitle
= $oldTitle;
482 $wgTitle = $oldTitle;
484 $this->mContent
= Article
::getRevisionText( $s );
485 $this->mUser
= $s->old_user
;
486 $this->mUserText
= $s->old_user_text
;
487 $this->mComment
= $s->old_comment
;
489 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
491 $this->mContentLoaded
= true;
492 return $this->mContent
;
496 * Gets the article text without using so many damn globals
497 * Returns false on error
499 * @param integer $oldid
501 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
502 if ( $this->mContentLoaded
) {
503 return $this->mContent
;
505 $this->mContent
= false;
507 $fname = 'Article::getContentWithout';
508 $dbr =& $this->getDB();
510 if ( ! $oldid ) { # Retrieve current version
511 $id = $this->getID();
516 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
517 $fname, $this->getSelectOptions() );
518 if ( $s === false ) {
522 # If we got a redirect, follow it (unless we've been told
523 # not to by either the function parameter or the query
525 $rt = Title
::newFromRedirect( $s->cur_text
);
526 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
527 $rid = $rt->getArticleID();
529 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
530 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
532 if ( $redirRow !== false ) {
533 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
541 $this->mContent
= $s->cur_text
;
542 $this->mUser
= $s->cur_user
;
543 $this->mUserText
= $s->cur_user_text
;
544 $this->mComment
= $s->cur_comment
;
545 $this->mCounter
= $s->cur_counter
;
546 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
547 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
548 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
549 $this->mTitle
->mRestrictionsLoaded
= true;
550 } else { # oldid set, retrieve historical version
551 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
552 $fname, $this->getSelectOptions() );
553 if ( $s === false ) {
556 $this->mContent
= Article
::getRevisionText( $s );
557 $this->mUser
= $s->old_user
;
558 $this->mUserText
= $s->old_user_text
;
559 $this->mComment
= $s->old_comment
;
561 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
563 $this->mContentLoaded
= true;
564 return $this->mContent
;
568 * Read/write accessor to select FOR UPDATE
570 function forUpdate( $x = NULL ) {
571 return wfSetVar( $this->mForUpdate
, $x );
575 * Get the database which should be used for reads
578 if ( $this->mForUpdate
) {
579 return wfGetDB( DB_MASTER
);
581 return wfGetDB( DB_SLAVE
);
586 * Get options for all SELECT statements
587 * Can pass an option array, to which the class-wide options will be appended
589 function getSelectOptions( $options = '' ) {
590 if ( $this->mForUpdate
) {
592 $options[] = 'FOR UPDATE';
594 $options = 'FOR UPDATE';
601 * Return the Article ID
604 if( $this->mTitle
) {
605 return $this->mTitle
->getArticleID();
612 * Get the view count for this article
614 function getCount() {
615 if ( -1 == $this->mCounter
) {
616 $id = $this->getID();
617 $dbr =& $this->getDB();
618 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
619 'Article::getCount', $this->getSelectOptions() );
621 return $this->mCounter
;
625 * Would the given text make this article a "good" article (i.e.,
626 * suitable for including in the article count)?
628 function isCountable( $text ) {
629 global $wgUseCommaCount;
631 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
632 if ( $this->isRedirect( $text ) ) { return 0; }
633 $token = ($wgUseCommaCount ?
',' : '[[' );
634 if ( false === strstr( $text, $token ) ) { return 0; }
639 * Tests if the article text represents a redirect
641 function isRedirect( $text = false ) {
642 if ( $text === false ) {
643 $this->loadContent();
644 $titleObj = Title
::newFromRedirect( $this->mText
);
646 $titleObj = Title
::newFromRedirect( $text );
648 return $titleObj !== NULL;
652 * Loads everything from cur except cur_text
653 * This isn't necessary for all uses, so it's only done if needed.
656 function loadLastEdit() {
658 if ( -1 != $this->mUser
) return;
660 $fname = 'Article::loadLastEdit';
662 $dbr =& $this->getDB();
663 $s = $dbr->getArray( 'cur',
664 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
665 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
667 if ( $s !== false ) {
668 $this->mUser
= $s->cur_user
;
669 $this->mUserText
= $s->cur_user_text
;
670 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
671 $this->mComment
= $s->cur_comment
;
672 $this->mMinorEdit
= $s->cur_minor_edit
;
676 function getTimestamp() {
677 $this->loadLastEdit();
678 return $this->mTimestamp
;
682 $this->loadLastEdit();
686 function getUserText() {
687 $this->loadLastEdit();
688 return $this->mUserText
;
691 function getComment() {
692 $this->loadLastEdit();
693 return $this->mComment
;
696 function getMinorEdit() {
697 $this->loadLastEdit();
698 return $this->mMinorEdit
;
701 function getContributors($limit = 0, $offset = 0) {
702 $fname = 'Article::getContributors';
704 # XXX: this is expensive; cache this info somewhere.
706 $title = $this->mTitle
;
708 $dbr =& $this->getDB();
709 $oldTable = $dbr->tableName( 'old' );
710 $userTable = $dbr->tableName( 'user' );
711 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
712 $ns = $title->getNamespace();
713 $user = $this->getUser();
715 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
716 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
717 WHERE old_namespace = $user
718 AND old_title = $encDBkey
719 AND old_user != $user
720 GROUP BY old_user, old_user_text, user_real_name
721 ORDER BY timestamp DESC";
723 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
724 $sql .= ' '. $this->getSelectOptions();
726 $res = $dbr->query($sql, $fname);
728 while ( $line = $dbr->fetchObject( $res ) ) {
729 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
732 $dbr->freeResult($res);
737 * This is the default action of the script: just view the page of
741 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol;
742 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
743 $sk = $wgUser->getSkin();
745 $fname = 'Article::view';
746 wfProfileIn( $fname );
747 # Get variables from query string
748 $oldid = $wgRequest->getVal( 'oldid' );
749 $diff = $wgRequest->getVal( 'diff' );
750 $rcid = $wgRequest->getVal( 'rcid' );
752 $wgOut->setArticleFlag( true );
753 $wgOut->setRobotpolicy( 'index,follow' );
754 # If we got diff and oldid in the query, we want to see a
755 # diff page instead of the article.
757 if ( !is_null( $diff ) ) {
758 require_once( 'DifferenceEngine.php' );
759 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
760 $de = new DifferenceEngine( $oldid, $diff, $rcid );
762 wfProfileOut( $fname );
764 # Run view updates for current revision only
765 $this->viewUpdates();
769 if ( empty( $oldid ) && $this->checkTouched() ) {
770 if( $wgOut->checkLastModified( $this->mTouched
) ){
772 } else if ( $this->tryFileCache() ) {
773 # tell wgOut that output is taken care of
775 $this->viewUpdates();
779 # Should the parser cache be used?
780 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
788 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
792 if ( !$outputDone ) {
793 $text = $this->getContent( false ); # May change mTitle by following a redirect
795 # Another whitelist check in case oldid or redirects are altering the title
796 if ( !$this->mTitle
->userCanRead() ) {
797 $wgOut->loginToUse();
803 # We're looking at an old revision
805 if ( !empty( $oldid ) ) {
806 $this->setOldSubtitle();
807 $wgOut->setRobotpolicy( 'noindex,follow' );
809 if ( '' != $this->mRedirectedFrom
) {
810 $sk = $wgUser->getSkin();
811 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
813 $s = wfMsg( 'redirectedfrom', $redir );
814 $wgOut->setSubtitle( $s );
816 # Can't cache redirects
820 # wrap user css and user js in pre and don't parse
821 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
823 $this->mTitle
->getNamespace() == NS_USER
&&
824 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
826 $wgOut->addWikiText( wfMsg('clearyourcache'));
827 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
828 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
830 $imageUrl = $wgStylePath.'/common/images/redirect.png';
831 $targetUrl = $rt->escapeLocalURL();
832 $titleText = htmlspecialchars( $rt->getPrefixedText() );
833 $link = $sk->makeLinkObj( $rt );
834 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'">' .
835 '<span class="redirectText">'.$link.'</span>' );
836 } else if ( $pcache ) {
837 # Display content and save to parser cache
838 $wgOut->addPrimaryWikiText( $text, $this );
840 # Display content, don't attempt to save to parser cache
841 $wgOut->addWikiText( $text );
844 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
845 # If we have been passed an &rcid= parameter, we want to give the user a
846 # chance to mark this new article as patrolled.
847 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
848 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
850 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
851 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
852 'action=markpatrolled&rcid='.$rcid )
856 # Put link titles into the link cache
857 $wgOut->transformBuffer();
859 # Add link titles as META keywords
860 $wgOut->addMetaTags() ;
862 $this->viewUpdates();
863 wfProfileOut( $fname );
867 * Theoretically we could defer these whole insert and update
868 * functions for after display, but that's taking a big leap
869 * of faith, and we want to be able to report database
870 * errors at some point.
873 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
874 global $wgOut, $wgUser;
875 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
877 $fname = 'Article::insertNewArticle';
879 $this->mCountAdjustment
= $this->isCountable( $text );
881 $ns = $this->mTitle
->getNamespace();
882 $ttl = $this->mTitle
->getDBkey();
883 $text = $this->preSaveTransform( $text );
884 if ( $this->isRedirect( $text ) ) { $redir = 1; }
887 $now = wfTimestampNow();
888 $won = wfInvertTimestamp( $now );
890 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
891 $dbw =& wfGetDB( DB_MASTER
);
893 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
895 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
897 $dbw->insertArray( 'cur', array(
899 'cur_namespace' => $ns,
902 'cur_comment' => $summary,
903 'cur_user' => $wgUser->getID(),
904 'cur_timestamp' => $dbw->timestamp($now),
905 'cur_minor_edit' => $isminor,
907 'cur_restrictions' => '',
908 'cur_user_text' => $wgUser->getName(),
909 'cur_is_redirect' => $redir,
911 'cur_random' => $rand,
912 'cur_touched' => $dbw->timestamp($now),
913 'inverse_timestamp' => $won,
916 $newid = $dbw->insertId();
917 $this->mTitle
->resetArticleID( $newid );
919 Article
::onArticleCreate( $this->mTitle
);
920 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
923 if(!$this->mTitle
->userIsWatching()) $this->watch();
925 if ( $this->mTitle
->userIsWatching() ) {
930 # The talk page isn't in the regular link tables, so we need to update manually:
931 $talkns = $ns ^
1; # talk -> normal; normal -> talk
932 $dbw->updateArray( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
933 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
935 # standard deferred updates
936 $this->editUpdates( $text );
938 $this->showArticle( $text, wfMsg( 'newarticle' ) );
943 * Side effects: loads last edit if $edittime is NULL
945 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
946 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
947 if(is_null($edittime)) {
948 $this->loadLastEdit();
949 $oldtext = $this->getContent( true );
951 $dbw =& wfGetDB( DB_MASTER
);
952 $ns = $this->mTitle
->getNamespace();
953 $title = $this->mTitle
->getDBkey();
954 $obj = $dbw->getArray( 'old',
955 array( 'old_text','old_flags'),
956 array( 'old_namespace' => $ns, 'old_title' => $title,
957 'old_timestamp' => $dbw->timestamp($edittime)),
959 $oldtext = Article
::getRevisionText( $obj );
961 if ($section != '') {
962 if($section=='new') {
963 if($summary) $subject="== {$summary} ==\n\n";
964 $text=$oldtext."\n\n".$subject.$text;
967 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
968 # comments to be stripped as well)
970 $parser=new Parser();
971 $parser->mOutputType
=OT_WIKI
;
972 $oldtext=$parser->strip($oldtext, $striparray, true);
974 # now that we can be sure that no pseudo-sections are in the source,
976 # Unfortunately we can't simply do a preg_replace because that might
977 # replace the wrong section, so we have to use the section counter instead
978 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
979 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
980 $secs[$section*2]=$text."\n\n"; // replace with edited
982 # section 0 is top (intro) section
985 # headline of old section - we need to go through this section
986 # to determine if there are any subsections that now need to
987 # be erased, as the mother section has been replaced with
988 # the text of all subsections.
989 $headline=$secs[$section*2-1];
990 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
993 # determine headline level for wikimarkup headings
994 if(strpos($hlevel,'=')!==false) {
995 $hlevel=strlen($hlevel);
998 $secs[$section*2-1]=''; // erase old headline
1001 while(!empty($secs[$count*2-1]) && !$break) {
1003 $subheadline=$secs[$count*2-1];
1005 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1006 $subhlevel=$matches[1];
1007 if(strpos($subhlevel,'=')!==false) {
1008 $subhlevel=strlen($subhlevel);
1010 if($subhlevel > $hlevel) {
1011 // erase old subsections
1012 $secs[$count*2-1]='';
1015 if($subhlevel <= $hlevel) {
1023 $text=join('',$secs);
1024 # reinsert the stuff that we stripped out earlier
1025 $text=$parser->unstrip($text,$striparray);
1026 $text=$parser->unstripNoWiki($text,$striparray);
1034 * Change an existing article. Puts the previous version back into the old table, updates RC
1035 * and all necessary caches, mostly via the deferred update array.
1037 * It is possible to call this function from a command-line script, but note that you should
1038 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1040 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1041 global $wgOut, $wgUser;
1042 global $wgDBtransactions, $wgMwRedir;
1043 global $wgUseSquid, $wgInternalServer;
1045 $fname = 'Article::updateArticle';
1048 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
1049 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
1050 if ( $this->isRedirect( $text ) ) {
1051 # Remove all content but redirect
1052 # This could be done by reconstructing the redirect from a title given by
1053 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1055 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1057 $text = $m[1] . "\n";
1060 else { $redir = 0; }
1062 $text = $this->preSaveTransform( $text );
1063 $dbw =& wfGetDB( DB_MASTER
);
1065 # Update article, but only if changed.
1067 # It's important that we either rollback or complete, otherwise an attacker could
1068 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1069 # could conceivably have the same effect, especially if cur is locked for long periods.
1070 if( $wgDBtransactions ) {
1071 $dbw->query( 'BEGIN', $fname );
1073 $userAbort = ignore_user_abort( true );
1076 $oldtext = $this->getContent( true );
1078 if ( 0 != strcmp( $text, $oldtext ) ) {
1079 $this->mCountAdjustment
= $this->isCountable( $text )
1080 - $this->isCountable( $oldtext );
1081 $now = wfTimestampNow();
1082 $won = wfInvertTimestamp( $now );
1084 # First update the cur row
1085 $dbw->updateArray( 'cur',
1087 'cur_text' => $text,
1088 'cur_comment' => $summary,
1089 'cur_minor_edit' => $me2,
1090 'cur_user' => $wgUser->getID(),
1091 'cur_timestamp' => $dbw->timestamp($now),
1092 'cur_user_text' => $wgUser->getName(),
1093 'cur_is_redirect' => $redir,
1095 'cur_touched' => $dbw->timestamp($now),
1096 'inverse_timestamp' => $won
1097 ), array( /* WHERE */
1098 'cur_id' => $this->getID(),
1099 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1103 if( $dbw->affectedRows() == 0 ) {
1104 /* Belated edit conflict! Run away!! */
1107 # Now insert the previous revision into old
1109 # This overwrites $oldtext if revision compression is on
1110 $flags = Article
::compressRevisionText( $oldtext );
1112 $dbw->insertArray( 'old',
1114 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1115 'old_namespace' => $this->mTitle
->getNamespace(),
1116 'old_title' => $this->mTitle
->getDBkey(),
1117 'old_text' => $oldtext,
1118 'old_comment' => $this->getComment(),
1119 'old_user' => $this->getUser(),
1120 'old_user_text' => $this->getUserText(),
1121 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1122 'old_minor_edit' => $me1,
1123 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1124 'old_flags' => $flags,
1128 $oldid = $dbw->insertId();
1130 $bot = (int)($wgUser->isBot() ||
$forceBot);
1131 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1132 $oldid, $this->getTimestamp(), $bot );
1133 Article
::onArticleEdit( $this->mTitle
);
1137 if( $wgDBtransactions ) {
1138 $dbw->query( 'COMMIT', $fname );
1140 ignore_user_abort( $userAbort );
1145 if (!$this->mTitle
->userIsWatching()) $this->watch();
1147 if ( $this->mTitle
->userIsWatching() ) {
1151 # standard deferred updates
1152 $this->editUpdates( $text );
1156 # Template namespace
1157 # Purge all articles linking here
1158 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1159 $titles = $this->mTitle
->getLinksTo();
1160 Title
::touchArray( $titles );
1161 if ( $wgUseSquid ) {
1162 foreach ( $titles as $title ) {
1163 $urls[] = $title->getInternalURL();
1169 if ( $wgUseSquid ) {
1170 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1171 $u = new SquidUpdate( $urls );
1175 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1181 * After we've either updated or inserted the article, update
1182 * the link tables and redirect to the new page.
1184 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1185 global $wgOut, $wgUser, $wgLinkCache;
1187 $wgLinkCache = new LinkCache();
1189 $wgLinkCache->forUpdate( true );
1191 # Get old version of link table to allow incremental link updates
1192 $wgLinkCache->preFill( $this->mTitle
);
1193 $wgLinkCache->clear();
1195 # Parse the text and replace links with placeholders
1196 $wgOut = new OutputPage();
1197 $wgOut->addWikiText( $text );
1199 # Look up the links in the DB and add them to the link cache
1200 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1202 if( $this->isRedirect( $text ) )
1206 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1211 * @todo document this function a bit more
1213 function validate () {
1214 global $wgOut, $wgUseValidation;
1215 if( $wgUseValidation ) {
1216 require_once ( 'SpecialValidate.php' ) ;
1217 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1218 $wgOut->setRobotpolicy( 'noindex,follow' );
1219 if( $this->mTitle
->getNamespace() != 0 ) {
1220 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1223 $v = new Validation
;
1224 $v->validate_form( $this->mTitle
->getDBkey() );
1226 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1231 * Mark this particular edit as patrolled
1233 function markpatrolled() {
1234 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1235 $wgOut->setRobotpolicy( 'noindex,follow' );
1237 if ( !$wgUseRCPatrol )
1239 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1242 if ( $wgUser->getID() == 0 )
1244 $wgOut->loginToUse();
1247 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1249 $wgOut->sysopRequired();
1252 $rcid = $wgRequest->getVal( 'rcid' );
1253 if ( !is_null ( $rcid ) )
1255 RecentChange
::markPatrolled( $rcid );
1256 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1257 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1258 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1262 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1268 * Add or remove this page to my watchlist based on value of $add
1270 function watch( $add = true ) {
1271 global $wgUser, $wgOut;
1272 global $wgDeferredUpdateList;
1274 if ( 0 == $wgUser->getID() ) {
1275 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1278 if ( wfReadOnly() ) {
1279 $wgOut->readOnlyPage();
1283 $wgUser->addWatch( $this->mTitle
);
1285 $wgUser->removeWatch( $this->mTitle
);
1287 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1288 $wgOut->setRobotpolicy( 'noindex,follow' );
1290 $sk = $wgUser->getSkin() ;
1291 $link = $this->mTitle
->getPrefixedText();
1294 $text = wfMsg( 'addedwatchtext', $link );
1296 $text = wfMsg( 'removedwatchtext', $link );
1297 $wgOut->addWikiText( $text );
1299 $up = new UserUpdate();
1300 array_push( $wgDeferredUpdateList, $up );
1302 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1306 * Stop watching a page, it act just like a call to watch(false)
1308 function unwatch() {
1309 $this->watch( false );
1315 function protect( $limit = 'sysop' ) {
1316 global $wgUser, $wgOut, $wgRequest;
1318 if ( ! $wgUser->isSysop() ) {
1319 $wgOut->sysopRequired();
1322 if ( wfReadOnly() ) {
1323 $wgOut->readOnlyPage();
1326 $id = $this->mTitle
->getArticleID();
1328 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1332 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1333 $reason = $wgRequest->getText( 'wpReasonProtect' );
1336 $dbw =& wfGetDB( DB_MASTER
);
1337 $dbw->updateArray( 'cur',
1339 'cur_touched' => $dbw->timestamp(),
1340 'cur_restrictions' => (string)$limit
1341 ), array( /* WHERE */
1343 ), 'Article::protect'
1346 $log = new LogPage( 'protect' );
1347 if ( $limit === '' ) {
1348 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1350 $log->addEntry( 'protect', $this->mTitle
, $reason );
1352 $wgOut->redirect( $this->mTitle
->getFullURL() );
1355 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1356 return $this->confirmProtect( '', $reason, $limit );
1361 * Output protection confirmation dialog
1363 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1366 wfDebug( "Article::confirmProtect\n" );
1368 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1369 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1374 if ( $limit === '' ) {
1375 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1376 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1377 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1378 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1379 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1380 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1382 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1383 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1384 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1385 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1386 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1387 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1390 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1393 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1397 <label for='wpReasonProtect'>{$protcom}:</label>
1400 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1408 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1411 <label for='wpConfirmProtect'>{$check}</label>
1417 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1423 $wgOut->returnToMain( false );
1427 * Unprotect the pages
1429 function unprotect() {
1430 return $this->protect( '' );
1434 * UI entry point for page deletion
1437 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1438 $fname = 'Article::delete';
1439 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1440 $reason = $wgRequest->getText( 'wpReason' );
1442 # This code desperately needs to be totally rewritten
1445 if ( ( ! $wgUser->isSysop() ) ) {
1446 $wgOut->sysopRequired();
1449 if ( wfReadOnly() ) {
1450 $wgOut->readOnlyPage();
1454 # Better double-check that it hasn't been deleted yet!
1455 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1456 if ( ( '' == trim( $this->mTitle
->getText() ) )
1457 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1458 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1463 $this->doDelete( $reason );
1467 # determine whether this page has earlier revisions
1468 # and insert a warning if it does
1469 # we select the text because it might be useful below
1470 $dbr =& $this->getDB();
1471 $ns = $this->mTitle
->getNamespace();
1472 $title = $this->mTitle
->getDBkey();
1473 $old = $dbr->getArray( 'old',
1474 array( 'old_text', 'old_flags' ),
1476 'old_namespace' => $ns,
1477 'old_title' => $title,
1478 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1481 if( $old !== false && !$confirm ) {
1482 $skin=$wgUser->getSkin();
1483 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1484 $wgOut->addHTML( $skin->historyLink() .'</b>');
1488 $s = $dbr->getArray( 'cur',
1489 array( 'cur_text' ),
1491 'cur_namespace' => $ns,
1492 'cur_title' => $title,
1493 ), $fname, $this->getSelectOptions()
1496 if( $s !== false ) {
1497 # if this is a mini-text, we can paste part of it into the deletion reason
1499 #if this is empty, an earlier revision may contain "useful" text
1501 if($s->cur_text
!= '') {
1505 $text = Article
::getRevisionText( $old );
1511 $length=strlen($text);
1513 # this should not happen, since it is not possible to store an empty, new
1514 # page. Let's insert a standard text in case it does, though
1515 if($length == 0 && $reason === '') {
1516 $reason = wfMsg('exblank');
1519 if($length < 500 && $reason === '') {
1521 # comment field=255, let's grep the first 150 to have some user
1523 $text=substr($text,0,150);
1524 # let's strip out newlines and HTML tags
1525 $text=preg_replace('/\"/',"'",$text);
1526 $text=preg_replace('/\</','<',$text);
1527 $text=preg_replace('/\>/','>',$text);
1528 $text=preg_replace("/[\n\r]/",'',$text);
1530 $reason=wfMsg('excontent'). " '".$text;
1532 $reason=wfMsg('exbeforeblank') . " '".$text;
1534 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1539 return $this->confirmDelete( '', $reason );
1543 * Output deletion confirmation dialog
1545 function confirmDelete( $par, $reason ) {
1548 wfDebug( "Article::confirmDelete\n" );
1550 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1551 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1552 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1553 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1555 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1557 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1558 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1559 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1562 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1566 <label for='wpReason'>{$delcom}:</label>
1569 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1577 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1580 <label for='wpConfirm'>{$check}</label>
1586 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1592 $wgOut->returnToMain( false );
1597 * Perform a deletion and output success or failure messages
1599 function doDelete( $reason ) {
1600 global $wgOut, $wgUser, $wgContLang;
1601 $fname = 'Article::doDelete';
1602 wfDebug( $fname."\n" );
1604 if ( $this->doDeleteArticle( $reason ) ) {
1605 $deleted = $this->mTitle
->getPrefixedText();
1607 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1608 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1610 $sk = $wgUser->getSkin();
1611 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1612 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1614 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1616 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1617 $wgOut->returnToMain( false );
1619 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1624 * Back-end article deletion
1625 * Deletes the article with database consistency, writes logs, purges caches
1628 function doDeleteArticle( $reason ) {
1630 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1632 $fname = 'Article::doDeleteArticle';
1633 wfDebug( $fname."\n" );
1635 $dbw =& wfGetDB( DB_MASTER
);
1636 $ns = $this->mTitle
->getNamespace();
1637 $t = $this->mTitle
->getDBkey();
1638 $id = $this->mTitle
->getArticleID();
1640 if ( $t == '' ||
$id == 0 ) {
1644 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1645 array_push( $wgDeferredUpdateList, $u );
1647 $linksTo = $this->mTitle
->getLinksTo();
1650 if ( $wgUseSquid ) {
1652 $this->mTitle
->getInternalURL(),
1653 $this->mTitle
->getInternalURL( 'history' )
1655 foreach ( $linksTo as $linkTo ) {
1656 $urls[] = $linkTo->getInternalURL();
1659 $u = new SquidUpdate( $urls );
1660 array_push( $wgDeferredUpdateList, $u );
1664 # Client and file cache invalidation
1665 Title
::touchArray( $linksTo );
1667 # Move article and history to the "archive" table
1668 $archiveTable = $dbw->tableName( 'archive' );
1669 $oldTable = $dbw->tableName( 'old' );
1670 $curTable = $dbw->tableName( 'cur' );
1671 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1672 $linksTable = $dbw->tableName( 'links' );
1673 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1675 $dbw->insertSelect( 'archive', 'cur',
1677 'ar_namespace' => 'cur_namespace',
1678 'ar_title' => 'cur_title',
1679 'ar_text' => 'cur_text',
1680 'ar_comment' => 'cur_comment',
1681 'ar_user' => 'cur_user',
1682 'ar_user_text' => 'cur_user_text',
1683 'ar_timestamp' => 'cur_timestamp',
1684 'ar_minor_edit' => 'cur_minor_edit',
1687 'cur_namespace' => $ns,
1692 $dbw->insertSelect( 'archive', 'old',
1694 'ar_namespace' => 'old_namespace',
1695 'ar_title' => 'old_title',
1696 'ar_text' => 'old_text',
1697 'ar_comment' => 'old_comment',
1698 'ar_user' => 'old_user',
1699 'ar_user_text' => 'old_user_text',
1700 'ar_timestamp' => 'old_timestamp',
1701 'ar_minor_edit' => 'old_minor_edit',
1702 'ar_flags' => 'old_flags'
1704 'old_namespace' => $ns,
1709 # Now that it's safely backed up, delete it
1711 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1712 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1713 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1715 # Finally, clean up the link tables
1716 $t = $this->mTitle
->getPrefixedDBkey();
1718 Article
::onArticleDelete( $this->mTitle
);
1720 # Insert broken links
1721 $brokenLinks = array();
1722 foreach ( $linksTo as $titleObj ) {
1723 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1724 $linkID = $titleObj->getArticleID();
1725 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1727 $dbw->insertArray( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1730 $dbw->delete( 'links', array( 'l_to' => $id ) );
1731 $dbw->delete( 'links', array( 'l_from' => $id ) );
1732 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1733 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1734 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1737 $log = new LogPage( 'delete' );
1738 $log->addEntry( 'delete', $this->mTitle
, $reason );
1740 # Clear the cached article id so the interface doesn't act like we exist
1741 $this->mTitle
->resetArticleID( 0 );
1742 $this->mTitle
->mArticleID
= 0;
1747 * Revert a modification
1749 function rollback() {
1750 global $wgUser, $wgOut, $wgRequest;
1751 $fname = 'Article::rollback';
1753 if ( ! $wgUser->isSysop() ) {
1754 $wgOut->sysopRequired();
1757 if ( wfReadOnly() ) {
1758 $wgOut->readOnlyPage( $this->getContent( true ) );
1761 $dbw =& wfGetDB( DB_MASTER
);
1763 # Enhanced rollback, marks edits rc_bot=1
1764 $bot = $wgRequest->getBool( 'bot' );
1766 # Replace all this user's current edits with the next one down
1767 $tt = $this->mTitle
->getDBKey();
1768 $n = $this->mTitle
->getNamespace();
1770 # Get the last editor, lock table exclusively
1771 $s = $dbw->getArray( 'cur',
1772 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1773 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1774 $fname, 'FOR UPDATE'
1776 if( $s === false ) {
1778 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1781 $ut = $dbw->strencode( $s->cur_user_text
);
1782 $uid = $s->cur_user
;
1785 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1786 if( $from != $s->cur_user_text
) {
1787 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1788 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1789 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1790 htmlspecialchars( $from ),
1791 htmlspecialchars( $s->cur_user_text
) ) );
1792 if($s->cur_comment
!= '') {
1794 wfMsg('editcomment',
1795 htmlspecialchars( $s->cur_comment
) ) );
1800 # Get the last edit not by this guy
1801 $s = $dbw->getArray( 'old',
1802 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1804 'old_namespace' => $n,
1806 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1807 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1809 if( $s === false ) {
1811 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1812 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1817 # Mark all reverted edits as bot
1818 $dbw->updateArray( 'recentchanges',
1821 ), array( /* WHERE */
1823 "rc_timestamp > '{$s->old_timestamp}'",
1829 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1830 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1831 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1832 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1833 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1834 Article
::onArticleEdit( $this->mTitle
);
1835 $wgOut->returnToMain( false );
1840 * Do standard deferred updates after page view
1843 function viewUpdates() {
1844 global $wgDeferredUpdateList;
1845 if ( 0 != $this->getID() ) {
1846 global $wgDisableCounters;
1847 if( !$wgDisableCounters ) {
1848 Article
::incViewCount( $this->getID() );
1849 $u = new SiteStatsUpdate( 1, 0, 0 );
1850 array_push( $wgDeferredUpdateList, $u );
1853 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1854 $this->mTitle
->getDBkey() );
1855 array_push( $wgDeferredUpdateList, $u );
1859 * Do standard deferred updates after page edit.
1860 * Every 1000th edit, prune the recent changes table.
1862 * @param string $text
1864 function editUpdates( $text ) {
1865 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1866 global $wgMessageCache;
1869 if ( 0 == mt_rand( 0, 999 ) ) {
1870 $dbw =& wfGetDB( DB_MASTER
);
1871 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1872 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1873 $dbw->query( $sql );
1875 $id = $this->getID();
1876 $title = $this->mTitle
->getPrefixedDBkey();
1877 $shortTitle = $this->mTitle
->getDBkey();
1879 $adj = $this->mCountAdjustment
;
1882 $u = new LinksUpdate( $id, $title );
1883 array_push( $wgDeferredUpdateList, $u );
1884 $u = new SiteStatsUpdate( 0, 1, $adj );
1885 array_push( $wgDeferredUpdateList, $u );
1886 $u = new SearchUpdate( $id, $title, $text );
1887 array_push( $wgDeferredUpdateList, $u );
1889 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1890 array_push( $wgDeferredUpdateList, $u );
1892 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1893 $wgMessageCache->replace( $shortTitle, $text );
1899 * @todo document this function
1902 function setOldSubtitle() {
1903 global $wgLang, $wgOut, $wgUser;
1905 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1906 $sk = $wgUser->getSkin();
1907 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1908 $r = wfMsg( 'revisionasofwithlink', $td, $lnk );
1909 $wgOut->setSubtitle( $r );
1913 * This function is called right before saving the wikitext,
1914 * so we can do things like signatures and links-in-context.
1916 * @param string $text
1918 function preSaveTransform( $text ) {
1919 global $wgParser, $wgUser;
1920 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1923 /* Caching functions */
1926 * checkLastModified returns true if it has taken care of all
1927 * output to the client that is necessary for this request.
1928 * (that is, it has sent a cached version of the page)
1930 function tryFileCache() {
1931 static $called = false;
1933 wfDebug( " tryFileCache() -- called twice!?\n" );
1937 if($this->isFileCacheable()) {
1938 $touched = $this->mTouched
;
1939 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1940 # Expire the main page quicker
1941 $expire = wfUnix2Timestamp( time() - 3600 );
1942 $touched = max( $expire, $touched );
1944 $cache = new CacheManager( $this->mTitle
);
1945 if($cache->isFileCacheGood( $touched )) {
1947 wfDebug( " tryFileCache() - about to load\n" );
1948 $cache->loadFromFileCache();
1951 wfDebug( " tryFileCache() - starting buffer\n" );
1952 ob_start( array(&$cache, 'saveToFileCache' ) );
1955 wfDebug( " tryFileCache() - not cacheable\n" );
1960 * Check if the page can be cached
1963 function isFileCacheable() {
1964 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1965 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1967 return $wgUseFileCache
1968 and (!$wgShowIPinHeader)
1969 and ($this->getID() != 0)
1970 and ($wgUser->getId() == 0)
1971 and (!$wgUser->getNewtalk())
1972 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1973 and (empty( $action ) ||
$action == 'view')
1974 and (!isset($oldid))
1976 and (!isset($redirect))
1977 and (!isset($printable))
1978 and (!$this->mRedirectedFrom
);
1982 * Loads cur_touched and returns a value indicating if it should be used
1985 function checkTouched() {
1986 $fname = 'Article::checkTouched';
1987 $id = $this->getID();
1988 $dbr =& $this->getDB();
1989 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1990 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1991 if( $s !== false ) {
1992 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1993 return !$s->cur_is_redirect
;
2000 * Edit an article without doing all that other stuff
2002 * @param string $text text submitted
2003 * @param string $comment comment submitted
2004 * @param integer $minor whereas it's a minor modification
2006 function quickEdit( $text, $comment = '', $minor = 0 ) {
2008 $fname = 'Article::quickEdit';
2009 wfProfileIn( $fname );
2011 $dbw =& wfGetDB( DB_MASTER
);
2012 $ns = $this->mTitle
->getNamespace();
2013 $dbkey = $this->mTitle
->getDBkey();
2014 $encDbKey = $dbw->strencode( $dbkey );
2015 $timestamp = wfTimestampNow();
2018 $dbw->insertSelect( 'old', 'cur',
2020 'old_namespace' => 'cur_namespace',
2021 'old_title' => 'cur_title',
2022 'old_text' => 'cur_text',
2023 'old_comment' => 'cur_comment',
2024 'old_user' => 'cur_user',
2025 'old_user_text' => 'cur_user_text',
2026 'old_timestamp' => 'cur_timestamp',
2027 'inverse_timestamp' => '99999999999999-cur_timestamp',
2029 'cur_namespace' => $ns,
2030 'cur_title' => $dbkey,
2034 # Use the affected row count to determine if the article is new
2035 $numRows = $dbw->affectedRows();
2037 # Make an array of fields to be inserted
2039 'cur_text' => $text,
2040 'cur_timestamp' => $timestamp,
2041 'cur_user' => $wgUser->getID(),
2042 'cur_user_text' => $wgUser->getName(),
2043 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2044 'cur_comment' => $comment,
2045 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2046 'cur_minor_edit' => intval($minor),
2047 'cur_touched' => $dbw->timestamp($timestamp),
2052 $fields['cur_is_new'] = 0;
2053 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2055 # Insert new article
2056 $fields['cur_is_new'] = 1;
2057 $fields['cur_namespace'] = $ns;
2058 $fields['cur_title'] = $dbkey;
2059 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
2060 $dbw->insertArray( 'cur', $fields, $fname );
2062 wfProfileOut( $fname );
2066 * Used to increment the view counter
2069 * @param integer $id article id
2071 function incViewCount( $id ) {
2072 $id = intval( $id );
2073 global $wgHitcounterUpdateFreq;
2075 $dbw =& wfGetDB( DB_MASTER
);
2076 $curTable = $dbw->tableName( 'cur' );
2077 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2078 $acchitsTable = $dbw->tableName( 'acchits' );
2080 if( $wgHitcounterUpdateFreq <= 1 ){ //
2081 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2085 # Not important enough to warrant an error page in case of failure
2086 $oldignore = $dbw->ignoreErrors( true );
2088 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2090 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2091 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2092 # Most of the time (or on SQL errors), skip row count check
2093 $dbw->ignoreErrors( $oldignore );
2097 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2098 $row = $dbw->fetchObject( $res );
2099 $rown = intval( $row->n
);
2100 if( $rown >= $wgHitcounterUpdateFreq ){
2101 wfProfileIn( 'Article::incViewCount-collect' );
2102 $old_user_abort = ignore_user_abort( true );
2104 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2105 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2106 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2108 $dbw->query("DELETE FROM $hitcounterTable");
2109 $dbw->query('UNLOCK TABLES');
2110 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2111 'WHERE cur_id = hc_id');
2112 $dbw->query("DROP TABLE $acchitsTable");
2114 ignore_user_abort( $old_user_abort );
2115 wfProfileOut( 'Article::incViewCount-collect' );
2117 $dbw->ignoreErrors( $oldignore );
2121 * The onArticle*() functions are supposed to be a kind of hooks
2122 * which should be called whenever any of the specified actions
2125 * This is a good place to put code to clear caches, for instance.
2127 * This is called on page move and undelete, as well as edit
2129 * @param $title_obj a title object
2132 function onArticleCreate($title_obj) {
2133 global $wgUseSquid, $wgDeferredUpdateList;
2135 $titles = $title_obj->getBrokenLinksTo();
2138 if ( $wgUseSquid ) {
2139 $urls = $title_obj->getSquidURLs();
2140 foreach ( $titles as $linkTitle ) {
2141 $urls[] = $linkTitle->getInternalURL();
2143 $u = new SquidUpdate( $urls );
2144 array_push( $wgDeferredUpdateList, $u );
2147 # Clear persistent link cache
2148 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2151 function onArticleDelete($title_obj) {
2152 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2154 function onArticleEdit($title_obj) {
2155 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2160 * Info about this page
2163 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2164 $fname = 'Article::info';
2166 if ( !$wgAllowPageInfo ) {
2167 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2171 $dbr =& $this->getDB();
2173 $basenamespace = $wgTitle->getNamespace() & (~
1);
2174 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2175 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2176 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2177 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2178 $wgOut->setPagetitle( $fullTitle );
2179 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2181 # first, see if the page exists at all.
2182 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2184 $wgOut->addHTML( wfMsg('noarticletext') );
2186 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2187 $this->getSelectOptions() );
2188 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2189 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2190 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2192 # to find number of distinct authors, we need to do some
2193 # funny stuff because of the cur/old table split:
2194 # - first, find the name of the 'cur' author
2195 # - then, find the number of *other* authors in 'old'
2198 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2199 $this->getSelectOptions() );
2201 # find number of 'old' authors excluding 'cur' author
2202 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2203 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2204 $this->getSelectOptions() ) +
1;
2206 # now for the Talk page ...
2207 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2208 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2211 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2215 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2216 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2218 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2222 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2223 $this->getSelectOptions() );
2224 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2225 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2226 $fname, $this->getSelectOptions() );
2228 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );