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, $wgLang, $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
945 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
946 if(is_null($edittime)) {
947 $this->loadLastEdit();
948 $oldtext = $this->getContent( true );
950 $dbw =& wfGetDB( DB_MASTER
);
951 $ns = $this->mTitle
->getNamespace();
952 $title = $this->mTitle
->getDBkey();
953 $obj = $dbw->getArray( 'old',
954 array( 'old_text','old_flags'),
955 array( 'old_namespace' => $ns, 'old_title' => $title,
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_namespace' => $this->mTitle
->getNamespace(),
1115 'old_title' => $this->mTitle
->getDBkey(),
1116 'old_text' => $oldtext,
1117 'old_comment' => $this->getComment(),
1118 'old_user' => $this->getUser(),
1119 'old_user_text' => $this->getUserText(),
1120 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1121 'old_minor_edit' => $me1,
1122 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1123 'old_flags' => $flags,
1127 $oldid = $dbw->insertId();
1129 $bot = (int)($wgUser->isBot() ||
$forceBot);
1130 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1131 $oldid, $this->getTimestamp(), $bot );
1132 Article
::onArticleEdit( $this->mTitle
);
1136 if( $wgDBtransactions ) {
1137 $dbw->query( 'COMMIT', $fname );
1139 ignore_user_abort( $userAbort );
1144 if (!$this->mTitle
->userIsWatching()) $this->watch();
1146 if ( $this->mTitle
->userIsWatching() ) {
1150 # standard deferred updates
1151 $this->editUpdates( $text );
1155 # Template namespace
1156 # Purge all articles linking here
1157 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1158 $titles = $this->mTitle
->getLinksTo();
1159 Title
::touchArray( $titles );
1160 if ( $wgUseSquid ) {
1161 foreach ( $titles as $title ) {
1162 $urls[] = $title->getInternalURL();
1168 if ( $wgUseSquid ) {
1169 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1170 $u = new SquidUpdate( $urls );
1174 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1180 * After we've either updated or inserted the article, update
1181 * the link tables and redirect to the new page.
1183 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1184 global $wgOut, $wgUser, $wgLinkCache;
1186 $wgLinkCache = new LinkCache();
1188 $wgLinkCache->forUpdate( true );
1190 # Get old version of link table to allow incremental link updates
1191 $wgLinkCache->preFill( $this->mTitle
);
1192 $wgLinkCache->clear();
1194 # Parse the text and replace links with placeholders
1195 $wgOut = new OutputPage();
1196 $wgOut->addWikiText( $text );
1198 # Look up the links in the DB and add them to the link cache
1199 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1201 if( $this->isRedirect( $text ) )
1205 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1210 * @todo document this function a bit more
1212 function validate () {
1213 global $wgOut, $wgUseValidation;
1214 if( $wgUseValidation ) {
1215 require_once ( 'SpecialValidate.php' ) ;
1216 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1217 $wgOut->setRobotpolicy( 'noindex,follow' );
1218 if( $this->mTitle
->getNamespace() != 0 ) {
1219 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1222 $v = new Validation
;
1223 $v->validate_form( $this->mTitle
->getDBkey() );
1225 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1230 * Mark this particular edit as patrolled
1232 function markpatrolled() {
1233 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1234 $wgOut->setRobotpolicy( 'noindex,follow' );
1236 if ( !$wgUseRCPatrol )
1238 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1241 if ( $wgUser->getID() == 0 )
1243 $wgOut->loginToUse();
1246 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1248 $wgOut->sysopRequired();
1251 $rcid = $wgRequest->getVal( 'rcid' );
1252 if ( !is_null ( $rcid ) )
1254 RecentChange
::markPatrolled( $rcid );
1255 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1256 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1257 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1261 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1267 * Add or remove this page to my watchlist based on value of $add
1269 function watch( $add = true ) {
1270 global $wgUser, $wgOut, $wgLang;
1271 global $wgDeferredUpdateList;
1273 if ( 0 == $wgUser->getID() ) {
1274 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1277 if ( wfReadOnly() ) {
1278 $wgOut->readOnlyPage();
1282 $wgUser->addWatch( $this->mTitle
);
1284 $wgUser->removeWatch( $this->mTitle
);
1286 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1287 $wgOut->setRobotpolicy( 'noindex,follow' );
1289 $sk = $wgUser->getSkin() ;
1290 $link = $this->mTitle
->getPrefixedText();
1293 $text = wfMsg( 'addedwatchtext', $link );
1295 $text = wfMsg( 'removedwatchtext', $link );
1296 $wgOut->addWikiText( $text );
1298 $up = new UserUpdate();
1299 array_push( $wgDeferredUpdateList, $up );
1301 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1305 * Stop watching a page, it act just like a call to watch(false)
1307 function unwatch() {
1308 $this->watch( false );
1314 function protect( $limit = 'sysop' ) {
1315 global $wgUser, $wgOut, $wgRequest;
1317 if ( ! $wgUser->isSysop() ) {
1318 $wgOut->sysopRequired();
1321 if ( wfReadOnly() ) {
1322 $wgOut->readOnlyPage();
1325 $id = $this->mTitle
->getArticleID();
1327 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1331 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1332 $reason = $wgRequest->getText( 'wpReasonProtect' );
1335 $dbw =& wfGetDB( DB_MASTER
);
1336 $dbw->updateArray( 'cur',
1338 'cur_touched' => $dbw->timestamp(),
1339 'cur_restrictions' => (string)$limit
1340 ), array( /* WHERE */
1342 ), 'Article::protect'
1345 $log = new LogPage( 'protect' );
1346 if ( $limit === '' ) {
1347 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1349 $log->addEntry( 'protect', $this->mTitle
, $reason );
1351 $wgOut->redirect( $this->mTitle
->getFullURL() );
1354 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1355 return $this->confirmProtect( '', $reason, $limit );
1360 * Output protection confirmation dialog
1362 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1365 wfDebug( "Article::confirmProtect\n" );
1367 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1368 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1373 if ( $limit === '' ) {
1374 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1375 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1376 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1377 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1378 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1379 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1381 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1382 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1383 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1384 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1385 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1386 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1389 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1392 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1396 <label for='wpReasonProtect'>{$protcom}:</label>
1399 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1407 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1410 <label for='wpConfirmProtect'>{$check}</label>
1416 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1422 $wgOut->returnToMain( false );
1426 * Unprotect the pages
1428 function unprotect() {
1429 return $this->protect( '' );
1433 * UI entry point for page deletion
1436 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1437 $fname = 'Article::delete';
1438 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1439 $reason = $wgRequest->getText( 'wpReason' );
1441 # This code desperately needs to be totally rewritten
1444 if ( ( ! $wgUser->isSysop() ) ) {
1445 $wgOut->sysopRequired();
1448 if ( wfReadOnly() ) {
1449 $wgOut->readOnlyPage();
1453 # Better double-check that it hasn't been deleted yet!
1454 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1455 if ( ( '' == trim( $this->mTitle
->getText() ) )
1456 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1457 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1462 $this->doDelete( $reason );
1466 # determine whether this page has earlier revisions
1467 # and insert a warning if it does
1468 # we select the text because it might be useful below
1469 $dbr =& $this->getDB();
1470 $ns = $this->mTitle
->getNamespace();
1471 $title = $this->mTitle
->getDBkey();
1472 $old = $dbr->getArray( 'old',
1473 array( 'old_text', 'old_flags' ),
1475 'old_namespace' => $ns,
1476 'old_title' => $title,
1477 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1480 if( $old !== false && !$confirm ) {
1481 $skin=$wgUser->getSkin();
1482 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1483 $wgOut->addHTML( $skin->historyLink() .'</b>');
1487 $s = $dbr->getArray( 'cur',
1488 array( 'cur_text' ),
1490 'cur_namespace' => $ns,
1491 'cur_title' => $title,
1492 ), $fname, $this->getSelectOptions()
1495 if( $s !== false ) {
1496 # if this is a mini-text, we can paste part of it into the deletion reason
1498 #if this is empty, an earlier revision may contain "useful" text
1500 if($s->cur_text
!= '') {
1504 $text = Article
::getRevisionText( $old );
1510 $length=strlen($text);
1512 # this should not happen, since it is not possible to store an empty, new
1513 # page. Let's insert a standard text in case it does, though
1514 if($length == 0 && $reason === '') {
1515 $reason = wfMsg('exblank');
1518 if($length < 500 && $reason === '') {
1520 # comment field=255, let's grep the first 150 to have some user
1522 $text=substr($text,0,150);
1523 # let's strip out newlines and HTML tags
1524 $text=preg_replace('/\"/',"'",$text);
1525 $text=preg_replace('/\</','<',$text);
1526 $text=preg_replace('/\>/','>',$text);
1527 $text=preg_replace("/[\n\r]/",'',$text);
1529 $reason=wfMsg('excontent'). " '".$text;
1531 $reason=wfMsg('exbeforeblank') . " '".$text;
1533 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1538 return $this->confirmDelete( '', $reason );
1542 * Output deletion confirmation dialog
1544 function confirmDelete( $par, $reason ) {
1547 wfDebug( "Article::confirmDelete\n" );
1549 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1550 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1551 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1552 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1554 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1556 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1557 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1558 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1561 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1565 <label for='wpReason'>{$delcom}:</label>
1568 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1576 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1579 <label for='wpConfirm'>{$check}</label>
1585 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1591 $wgOut->returnToMain( false );
1596 * Perform a deletion and output success or failure messages
1598 function doDelete( $reason ) {
1599 global $wgOut, $wgUser, $wgLang;
1600 $fname = 'Article::doDelete';
1601 wfDebug( $fname."\n" );
1603 if ( $this->doDeleteArticle( $reason ) ) {
1604 $deleted = $this->mTitle
->getPrefixedText();
1606 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1607 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1609 $sk = $wgUser->getSkin();
1610 $loglink = $sk->makeKnownLink( $wgLang->getNsText( NS_PROJECT
) .
1611 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1613 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1615 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1616 $wgOut->returnToMain( false );
1618 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1623 * Back-end article deletion
1624 * Deletes the article with database consistency, writes logs, purges caches
1627 function doDeleteArticle( $reason ) {
1628 global $wgUser, $wgLang;
1629 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1631 $fname = 'Article::doDeleteArticle';
1632 wfDebug( $fname."\n" );
1634 $dbw =& wfGetDB( DB_MASTER
);
1635 $ns = $this->mTitle
->getNamespace();
1636 $t = $this->mTitle
->getDBkey();
1637 $id = $this->mTitle
->getArticleID();
1639 if ( $t == '' ||
$id == 0 ) {
1643 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1644 array_push( $wgDeferredUpdateList, $u );
1646 $linksTo = $this->mTitle
->getLinksTo();
1649 if ( $wgUseSquid ) {
1651 $this->mTitle
->getInternalURL(),
1652 $this->mTitle
->getInternalURL( 'history' )
1654 foreach ( $linksTo as $linkTo ) {
1655 $urls[] = $linkTo->getInternalURL();
1658 $u = new SquidUpdate( $urls );
1659 array_push( $wgDeferredUpdateList, $u );
1663 # Client and file cache invalidation
1664 Title
::touchArray( $linksTo );
1666 # Move article and history to the "archive" table
1667 $archiveTable = $dbw->tableName( 'archive' );
1668 $oldTable = $dbw->tableName( 'old' );
1669 $curTable = $dbw->tableName( 'cur' );
1670 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1671 $linksTable = $dbw->tableName( 'links' );
1672 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1674 $dbw->insertSelect( 'archive', 'cur',
1676 'ar_namespace' => 'cur_namespace',
1677 'ar_title' => 'cur_title',
1678 'ar_text' => 'cur_text',
1679 'ar_comment' => 'cur_comment',
1680 'ar_user' => 'cur_user',
1681 'ar_user_text' => 'cur_user_text',
1682 'ar_timestamp' => 'cur_timestamp',
1683 'ar_minor_edit' => 'cur_minor_edit',
1686 'cur_namespace' => $ns,
1691 $dbw->insertSelect( 'archive', 'old',
1693 'ar_namespace' => 'old_namespace',
1694 'ar_title' => 'old_title',
1695 'ar_text' => 'old_text',
1696 'ar_comment' => 'old_comment',
1697 'ar_user' => 'old_user',
1698 'ar_user_text' => 'old_user_text',
1699 'ar_timestamp' => 'old_timestamp',
1700 'ar_minor_edit' => 'old_minor_edit',
1701 'ar_flags' => 'old_flags'
1703 'old_namespace' => $ns,
1708 # Now that it's safely backed up, delete it
1710 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1711 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1712 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1714 # Finally, clean up the link tables
1715 $t = $this->mTitle
->getPrefixedDBkey();
1717 Article
::onArticleDelete( $this->mTitle
);
1719 # Insert broken links
1720 $brokenLinks = array();
1721 foreach ( $linksTo as $titleObj ) {
1722 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1723 $linkID = $titleObj->getArticleID();
1724 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1726 $dbw->insertArray( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1729 $dbw->delete( 'links', array( 'l_to' => $id ) );
1730 $dbw->delete( 'links', array( 'l_from' => $id ) );
1731 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1732 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1733 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1736 $log = new LogPage( 'delete' );
1737 $log->addEntry( 'delete', $this->mTitle
, $reason );
1739 # Clear the cached article id so the interface doesn't act like we exist
1740 $this->mTitle
->resetArticleID( 0 );
1741 $this->mTitle
->mArticleID
= 0;
1746 * Revert a modification
1748 function rollback() {
1749 global $wgUser, $wgLang, $wgOut, $wgRequest;
1750 $fname = 'Article::rollback';
1752 if ( ! $wgUser->isSysop() ) {
1753 $wgOut->sysopRequired();
1756 if ( wfReadOnly() ) {
1757 $wgOut->readOnlyPage( $this->getContent( true ) );
1760 $dbw =& wfGetDB( DB_MASTER
);
1762 # Enhanced rollback, marks edits rc_bot=1
1763 $bot = $wgRequest->getBool( 'bot' );
1765 # Replace all this user's current edits with the next one down
1766 $tt = $this->mTitle
->getDBKey();
1767 $n = $this->mTitle
->getNamespace();
1769 # Get the last editor, lock table exclusively
1770 $s = $dbw->getArray( 'cur',
1771 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1772 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1773 $fname, 'FOR UPDATE'
1775 if( $s === false ) {
1777 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1780 $ut = $dbw->strencode( $s->cur_user_text
);
1781 $uid = $s->cur_user
;
1784 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1785 if( $from != $s->cur_user_text
) {
1786 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1787 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1788 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1789 htmlspecialchars( $from ),
1790 htmlspecialchars( $s->cur_user_text
) ) );
1791 if($s->cur_comment
!= '') {
1793 wfMsg('editcomment',
1794 htmlspecialchars( $s->cur_comment
) ) );
1799 # Get the last edit not by this guy
1800 $s = $dbw->getArray( 'old',
1801 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1803 'old_namespace' => $n,
1805 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1806 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1808 if( $s === false ) {
1810 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1811 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1816 # Mark all reverted edits as bot
1817 $dbw->updateArray( 'recentchanges',
1820 ), array( /* WHERE */
1822 "rc_timestamp > '{$s->old_timestamp}'",
1828 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1829 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1830 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1831 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1832 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1833 Article
::onArticleEdit( $this->mTitle
);
1834 $wgOut->returnToMain( false );
1839 * Do standard deferred updates after page view
1842 function viewUpdates() {
1843 global $wgDeferredUpdateList;
1844 if ( 0 != $this->getID() ) {
1845 global $wgDisableCounters;
1846 if( !$wgDisableCounters ) {
1847 Article
::incViewCount( $this->getID() );
1848 $u = new SiteStatsUpdate( 1, 0, 0 );
1849 array_push( $wgDeferredUpdateList, $u );
1852 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1853 $this->mTitle
->getDBkey() );
1854 array_push( $wgDeferredUpdateList, $u );
1858 * Do standard deferred updates after page edit.
1859 * Every 1000th edit, prune the recent changes table.
1861 * @param string $text
1863 function editUpdates( $text ) {
1864 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1865 global $wgMessageCache;
1868 if ( 0 == mt_rand( 0, 999 ) ) {
1869 $dbw =& wfGetDB( DB_MASTER
);
1870 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1871 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1872 $dbw->query( $sql );
1874 $id = $this->getID();
1875 $title = $this->mTitle
->getPrefixedDBkey();
1876 $shortTitle = $this->mTitle
->getDBkey();
1878 $adj = $this->mCountAdjustment
;
1881 $u = new LinksUpdate( $id, $title );
1882 array_push( $wgDeferredUpdateList, $u );
1883 $u = new SiteStatsUpdate( 0, 1, $adj );
1884 array_push( $wgDeferredUpdateList, $u );
1885 $u = new SearchUpdate( $id, $title, $text );
1886 array_push( $wgDeferredUpdateList, $u );
1888 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1889 array_push( $wgDeferredUpdateList, $u );
1891 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1892 $wgMessageCache->replace( $shortTitle, $text );
1898 * @todo document this function
1901 function setOldSubtitle() {
1902 global $wgLang, $wgOut, $wgUser;
1904 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1905 $sk = $wgUser->getSkin();
1906 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1907 $r = wfMsg( 'revisionasofwithlink', $td, $lnk );
1908 $wgOut->setSubtitle( $r );
1912 * This function is called right before saving the wikitext,
1913 * so we can do things like signatures and links-in-context.
1915 * @param string $text
1917 function preSaveTransform( $text ) {
1918 global $wgParser, $wgUser;
1919 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1922 /* Caching functions */
1925 * checkLastModified returns true if it has taken care of all
1926 * output to the client that is necessary for this request.
1927 * (that is, it has sent a cached version of the page)
1929 function tryFileCache() {
1930 static $called = false;
1932 wfDebug( " tryFileCache() -- called twice!?\n" );
1936 if($this->isFileCacheable()) {
1937 $touched = $this->mTouched
;
1938 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1939 # Expire the main page quicker
1940 $expire = wfUnix2Timestamp( time() - 3600 );
1941 $touched = max( $expire, $touched );
1943 $cache = new CacheManager( $this->mTitle
);
1944 if($cache->isFileCacheGood( $touched )) {
1946 wfDebug( " tryFileCache() - about to load\n" );
1947 $cache->loadFromFileCache();
1950 wfDebug( " tryFileCache() - starting buffer\n" );
1951 ob_start( array(&$cache, 'saveToFileCache' ) );
1954 wfDebug( " tryFileCache() - not cacheable\n" );
1959 * Check if the page can be cached
1962 function isFileCacheable() {
1963 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1964 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1966 return $wgUseFileCache
1967 and (!$wgShowIPinHeader)
1968 and ($this->getID() != 0)
1969 and ($wgUser->getId() == 0)
1970 and (!$wgUser->getNewtalk())
1971 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1972 and (empty( $action ) ||
$action == 'view')
1973 and (!isset($oldid))
1975 and (!isset($redirect))
1976 and (!isset($printable))
1977 and (!$this->mRedirectedFrom
);
1981 * Loads cur_touched and returns a value indicating if it should be used
1984 function checkTouched() {
1985 $fname = 'Article::checkTouched';
1986 $id = $this->getID();
1987 $dbr =& $this->getDB();
1988 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1989 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1990 if( $s !== false ) {
1991 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1992 return !$s->cur_is_redirect
;
1999 * Edit an article without doing all that other stuff
2001 * @param string $text text submitted
2002 * @param string $comment comment submitted
2003 * @param integer $minor whereas it's a minor modification
2005 function quickEdit( $text, $comment = '', $minor = 0 ) {
2007 $fname = 'Article::quickEdit';
2008 wfProfileIn( $fname );
2010 $dbw =& wfGetDB( DB_MASTER
);
2011 $ns = $this->mTitle
->getNamespace();
2012 $dbkey = $this->mTitle
->getDBkey();
2013 $encDbKey = $dbw->strencode( $dbkey );
2014 $timestamp = wfTimestampNow();
2017 $dbw->insertSelect( 'old', 'cur',
2019 'old_namespace' => 'cur_namespace',
2020 'old_title' => 'cur_title',
2021 'old_text' => 'cur_text',
2022 'old_comment' => 'cur_comment',
2023 'old_user' => 'cur_user',
2024 'old_user_text' => 'cur_user_text',
2025 'old_timestamp' => 'cur_timestamp',
2026 'inverse_timestamp' => '99999999999999-cur_timestamp',
2028 'cur_namespace' => $ns,
2029 'cur_title' => $dbkey,
2033 # Use the affected row count to determine if the article is new
2034 $numRows = $dbw->affectedRows();
2036 # Make an array of fields to be inserted
2038 'cur_text' => $text,
2039 'cur_timestamp' => $timestamp,
2040 'cur_user' => $wgUser->getID(),
2041 'cur_user_text' => $wgUser->getName(),
2042 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2043 'cur_comment' => $comment,
2044 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2045 'cur_minor_edit' => intval($minor),
2046 'cur_touched' => $dbw->timestamp($timestamp),
2051 $fields['cur_is_new'] = 0;
2052 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2054 # Insert new article
2055 $fields['cur_is_new'] = 1;
2056 $fields['cur_namespace'] = $ns;
2057 $fields['cur_title'] = $dbkey;
2058 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
2059 $dbw->insertArray( 'cur', $fields, $fname );
2061 wfProfileOut( $fname );
2065 * Used to increment the view counter
2068 * @param integer $id article id
2070 function incViewCount( $id ) {
2071 $id = intval( $id );
2072 global $wgHitcounterUpdateFreq;
2074 $dbw =& wfGetDB( DB_MASTER
);
2075 $curTable = $dbw->tableName( 'cur' );
2076 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2077 $acchitsTable = $dbw->tableName( 'acchits' );
2079 if( $wgHitcounterUpdateFreq <= 1 ){ //
2080 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2084 # Not important enough to warrant an error page in case of failure
2085 $oldignore = $dbw->ignoreErrors( true );
2087 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2089 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2090 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2091 # Most of the time (or on SQL errors), skip row count check
2092 $dbw->ignoreErrors( $oldignore );
2096 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2097 $row = $dbw->fetchObject( $res );
2098 $rown = intval( $row->n
);
2099 if( $rown >= $wgHitcounterUpdateFreq ){
2100 wfProfileIn( 'Article::incViewCount-collect' );
2101 $old_user_abort = ignore_user_abort( true );
2103 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2104 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2105 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2107 $dbw->query("DELETE FROM $hitcounterTable");
2108 $dbw->query('UNLOCK TABLES');
2109 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2110 'WHERE cur_id = hc_id');
2111 $dbw->query("DROP TABLE $acchitsTable");
2113 ignore_user_abort( $old_user_abort );
2114 wfProfileOut( 'Article::incViewCount-collect' );
2116 $dbw->ignoreErrors( $oldignore );
2120 * The onArticle*() functions are supposed to be a kind of hooks
2121 * which should be called whenever any of the specified actions
2124 * This is a good place to put code to clear caches, for instance.
2126 * This is called on page move and undelete, as well as edit
2128 * @param $title_obj a title object
2131 function onArticleCreate($title_obj) {
2132 global $wgUseSquid, $wgDeferredUpdateList;
2134 $titles = $title_obj->getBrokenLinksTo();
2137 if ( $wgUseSquid ) {
2138 $urls = $title_obj->getSquidURLs();
2139 foreach ( $titles as $linkTitle ) {
2140 $urls[] = $linkTitle->getInternalURL();
2142 $u = new SquidUpdate( $urls );
2143 array_push( $wgDeferredUpdateList, $u );
2146 # Clear persistent link cache
2147 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2150 function onArticleDelete($title_obj) {
2151 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2153 function onArticleEdit($title_obj) {
2154 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2159 * Info about this page
2162 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgAllowPageInfo;
2163 $fname = 'Article::info';
2165 if ( !$wgAllowPageInfo ) {
2166 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2170 $dbr =& $this->getDB();
2172 $basenamespace = $wgTitle->getNamespace() & (~
1);
2173 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2174 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2175 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2176 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2177 $wgOut->setPagetitle( $fullTitle );
2178 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2180 # first, see if the page exists at all.
2181 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2183 $wgOut->addHTML( wfMsg('noarticletext') );
2185 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2186 $this->getSelectOptions() );
2187 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2188 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2189 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2191 # to find number of distinct authors, we need to do some
2192 # funny stuff because of the cur/old table split:
2193 # - first, find the name of the 'cur' author
2194 # - then, find the number of *other* authors in 'old'
2197 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2198 $this->getSelectOptions() );
2200 # find number of 'old' authors excluding 'cur' author
2201 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2202 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2203 $this->getSelectOptions() ) +
1;
2205 # now for the Talk page ...
2206 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2207 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2210 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2214 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2215 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2217 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2221 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2222 $this->getSelectOptions() );
2223 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2224 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2225 $fname, $this->getSelectOptions() );
2227 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );