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, $wgMwRedir, $wgRequest;
397 $dbr =& $this->getDB();
399 $oldid = $wgRequest->getVal( 'oldid' );
400 $redirect = $wgRequest->getVal( 'redirect' );
402 if ( $this->mContentLoaded
) return;
403 $fname = 'Article::loadContent';
405 # Pre-fill content with error message so that if something
406 # fails we'll have something telling us what we intended.
408 $t = $this->mTitle
->getPrefixedText();
409 if ( isset( $oldid ) ) {
410 $oldid = IntVal( $oldid );
411 $t .= ',oldid='.$oldid;
413 if ( isset( $redirect ) ) {
414 $redirect = ($redirect == 'no') ?
'no' : 'yes';
415 $t .= ',redirect='.$redirect;
417 $this->mContent
= wfMsg( 'missingarticle', $t );
419 if ( ! $oldid ) { # Retrieve current version
420 $id = $this->getID();
421 if ( 0 == $id ) return;
423 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
424 $this->getSelectOptions() );
425 if ( $s === false ) {
429 # If we got a redirect, follow it (unless we've been told
430 # not to by either the function parameter or the query
431 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
432 $rt = Title
::newFromRedirect( $s->cur_text
);
433 # process if title object is valid and not special:userlogout
434 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
435 # Gotta hand redirects to special pages differently:
436 # Fill the HTTP response "Location" header and ignore
437 # the rest of the page we're on.
439 if ( $rt->getInterwiki() != '' ) {
440 $wgOut->redirect( $rt->getFullURL() ) ;
443 if ( $rt->getNamespace() == NS_SPECIAL
) {
444 $wgOut->redirect( $rt->getFullURL() );
447 $rid = $rt->getArticleID();
449 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
450 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
452 if ( $redirRow !== false ) {
453 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
461 $this->mContent
= $s->cur_text
;
462 $this->mUser
= $s->cur_user
;
463 $this->mUserText
= $s->cur_user_text
;
464 $this->mComment
= $s->cur_comment
;
465 $this->mCounter
= $s->cur_counter
;
466 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
467 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
468 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
469 $this->mTitle
->mRestrictionsLoaded
= true;
470 } else { # oldid set, retrieve historical version
471 $s = $dbr->getArray( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
472 $fname, $this->getSelectOptions() );
473 if ( $s === false ) {
477 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
478 $this->mTitle
->getDBkey() != $s->old_title
) {
479 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
480 $this->mTitle
= $oldTitle;
481 $wgTitle = $oldTitle;
483 $this->mContent
= Article
::getRevisionText( $s );
484 $this->mUser
= $s->old_user
;
485 $this->mUserText
= $s->old_user_text
;
486 $this->mComment
= $s->old_comment
;
488 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
490 $this->mContentLoaded
= true;
491 return $this->mContent
;
495 * Gets the article text without using so many damn globals
496 * Returns false on error
498 * @param integer $oldid
501 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
504 if ( $this->mContentLoaded
) {
505 return $this->mContent
;
507 $this->mContent
= false;
509 $fname = 'Article::getContentWithout';
510 $dbr =& $this->getDB();
512 if ( ! $oldid ) { # Retrieve current version
513 $id = $this->getID();
518 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
519 $fname, $this->getSelectOptions() );
520 if ( $s === false ) {
524 # If we got a redirect, follow it (unless we've been told
525 # not to by either the function parameter or the query
527 $rt = Title
::newFromRedirect( $s->cur_text
);
528 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
529 $rid = $rt->getArticleID();
531 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
532 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
534 if ( $redirRow !== false ) {
535 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
543 $this->mContent
= $s->cur_text
;
544 $this->mUser
= $s->cur_user
;
545 $this->mUserText
= $s->cur_user_text
;
546 $this->mComment
= $s->cur_comment
;
547 $this->mCounter
= $s->cur_counter
;
548 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
549 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
550 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
551 $this->mTitle
->mRestrictionsLoaded
= true;
552 } else { # oldid set, retrieve historical version
553 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
554 $fname, $this->getSelectOptions() );
555 if ( $s === false ) {
558 $this->mContent
= Article
::getRevisionText( $s );
559 $this->mUser
= $s->old_user
;
560 $this->mUserText
= $s->old_user_text
;
561 $this->mComment
= $s->old_comment
;
563 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
565 $this->mContentLoaded
= true;
566 return $this->mContent
;
570 * Read/write accessor to select FOR UPDATE
572 function forUpdate( $x = NULL ) {
573 return wfSetVar( $this->mForUpdate
, $x );
577 * Get the database which should be used for reads
580 if ( $this->mForUpdate
) {
581 return wfGetDB( DB_MASTER
);
583 return wfGetDB( DB_SLAVE
);
588 * Get options for all SELECT statements
589 * Can pass an option array, to which the class-wide options will be appended
591 function getSelectOptions( $options = '' ) {
592 if ( $this->mForUpdate
) {
594 $options[] = 'FOR UPDATE';
596 $options = 'FOR UPDATE';
603 * Return the Article ID
606 if( $this->mTitle
) {
607 return $this->mTitle
->getArticleID();
614 * @todo document function
616 function getCount() {
617 if ( -1 == $this->mCounter
) {
618 $id = $this->getID();
619 $dbr =& $this->getDB();
620 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
621 'Article::getCount', $this->getSelectOptions() );
623 return $this->mCounter
;
627 * Would the given text make this article a "good" article (i.e.,
628 * suitable for including in the article count)?
630 function isCountable( $text ) {
631 global $wgUseCommaCount, $wgMwRedir;
633 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
634 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
635 $token = ($wgUseCommaCount ?
',' : '[[' );
636 if ( false === strstr( $text, $token ) ) { return 0; }
641 * Loads everything from cur except cur_text
642 * This isn't necessary for all uses, so it's only done if needed.
645 function loadLastEdit() {
647 if ( -1 != $this->mUser
) return;
649 $fname = 'Article::loadLastEdit';
651 $dbr =& $this->getDB();
652 $s = $dbr->getArray( 'cur',
653 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
654 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
656 if ( $s !== false ) {
657 $this->mUser
= $s->cur_user
;
658 $this->mUserText
= $s->cur_user_text
;
659 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
660 $this->mComment
= $s->cur_comment
;
661 $this->mMinorEdit
= $s->cur_minor_edit
;
665 function getTimestamp() {
666 $this->loadLastEdit();
667 return $this->mTimestamp
;
671 $this->loadLastEdit();
675 function getUserText() {
676 $this->loadLastEdit();
677 return $this->mUserText
;
680 function getComment() {
681 $this->loadLastEdit();
682 return $this->mComment
;
685 function getMinorEdit() {
686 $this->loadLastEdit();
687 return $this->mMinorEdit
;
690 function getContributors($limit = 0, $offset = 0) {
691 $fname = 'Article::getContributors';
693 # XXX: this is expensive; cache this info somewhere.
695 $title = $this->mTitle
;
697 $dbr =& $this->getDB();
698 $oldTable = $dbr->tableName( 'old' );
699 $userTable = $dbr->tableName( 'user' );
700 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
701 $ns = $title->getNamespace();
702 $user = $this->getUser();
704 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
705 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
706 WHERE old_namespace = $user
707 AND old_title = $encDBkey
708 AND old_user != $user
709 GROUP BY old_user, old_user_text, user_real_name
710 ORDER BY timestamp DESC";
712 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
713 $sql .= ' '. $this->getSelectOptions();
715 $res = $dbr->query($sql, $fname);
717 while ( $line = $dbr->fetchObject( $res ) ) {
718 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
721 $dbr->freeResult($res);
726 * This is the default action of the script: just view the page of
730 global $wgUser, $wgOut, $wgLang, $wgRequest, $wgMwRedir, $wgOnlySysopsCanPatrol;
731 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
732 $sk = $wgUser->getSkin();
734 $fname = 'Article::view';
735 wfProfileIn( $fname );
736 # Get variables from query string
737 $oldid = $wgRequest->getVal( 'oldid' );
738 $diff = $wgRequest->getVal( 'diff' );
739 $rcid = $wgRequest->getVal( 'rcid' );
741 $wgOut->setArticleFlag( true );
742 $wgOut->setRobotpolicy( 'index,follow' );
743 # If we got diff and oldid in the query, we want to see a
744 # diff page instead of the article.
746 if ( !is_null( $diff ) ) {
747 require_once( 'DifferenceEngine.php' );
748 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
749 $de = new DifferenceEngine( $oldid, $diff, $rcid );
751 wfProfileOut( $fname );
753 # Run view updates for current revision only
754 $this->viewUpdates();
758 if ( empty( $oldid ) && $this->checkTouched() ) {
759 if( $wgOut->checkLastModified( $this->mTouched
) ){
761 } else if ( $this->tryFileCache() ) {
762 # tell wgOut that output is taken care of
764 $this->viewUpdates();
768 # Should the parser cache be used?
769 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
777 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
781 if ( !$outputDone ) {
782 $text = $this->getContent( false ); # May change mTitle by following a redirect
784 # Another whitelist check in case oldid or redirects are altering the title
785 if ( !$this->mTitle
->userCanRead() ) {
786 $wgOut->loginToUse();
792 # We're looking at an old revision
794 if ( !empty( $oldid ) ) {
795 $this->setOldSubtitle();
796 $wgOut->setRobotpolicy( 'noindex,follow' );
798 if ( '' != $this->mRedirectedFrom
) {
799 $sk = $wgUser->getSkin();
800 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
802 $s = wfMsg( 'redirectedfrom', $redir );
803 $wgOut->setSubtitle( $s );
805 # Can't cache redirects
809 # wrap user css and user js in pre and don't parse
810 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
812 $this->mTitle
->getNamespace() == NS_USER
&&
813 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
815 $wgOut->addWikiText( wfMsg('clearyourcache'));
816 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
817 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
819 $imageUrl = $wgStylePath.'/common/images/redirect.png';
820 $targetUrl = $rt->escapeLocalURL();
821 $titleText = htmlspecialchars( $rt->getPrefixedText() );
822 $link = $sk->makeLinkObj( $rt );
823 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'">' .
824 '<span class="redirectText">'.$link.'</span>' );
825 } else if ( $pcache ) {
826 # Display content and save to parser cache
827 $wgOut->addPrimaryWikiText( $text, $this );
829 # Display content, don't attempt to save to parser cache
830 $wgOut->addWikiText( $text );
833 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
834 # If we have been passed an &rcid= parameter, we want to give the user a
835 # chance to mark this new article as patrolled.
836 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
837 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
839 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
840 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
841 'action=markpatrolled&rcid='.$rcid )
845 # Put link titles into the link cache
846 $wgOut->transformBuffer();
848 # Add link titles as META keywords
849 $wgOut->addMetaTags() ;
851 $this->viewUpdates();
852 wfProfileOut( $fname );
856 * Theoretically we could defer these whole insert and update
857 * functions for after display, but that's taking a big leap
858 * of faith, and we want to be able to report database
859 * errors at some point.
862 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
863 global $wgOut, $wgUser, $wgMwRedir;
864 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
866 $fname = 'Article::insertNewArticle';
868 $this->mCountAdjustment
= $this->isCountable( $text );
870 $ns = $this->mTitle
->getNamespace();
871 $ttl = $this->mTitle
->getDBkey();
872 $text = $this->preSaveTransform( $text );
873 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
876 $now = wfTimestampNow();
877 $won = wfInvertTimestamp( $now );
879 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
880 $dbw =& wfGetDB( DB_MASTER
);
882 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
884 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
886 $dbw->insertArray( 'cur', array(
888 'cur_namespace' => $ns,
891 'cur_comment' => $summary,
892 'cur_user' => $wgUser->getID(),
893 'cur_timestamp' => $dbw->timestamp($now),
894 'cur_minor_edit' => $isminor,
896 'cur_restrictions' => '',
897 'cur_user_text' => $wgUser->getName(),
898 'cur_is_redirect' => $redir,
900 'cur_random' => $rand,
901 'cur_touched' => $dbw->timestamp($now),
902 'inverse_timestamp' => $won,
905 $newid = $dbw->insertId();
906 $this->mTitle
->resetArticleID( $newid );
908 Article
::onArticleCreate( $this->mTitle
);
909 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
912 if(!$this->mTitle
->userIsWatching()) $this->watch();
914 if ( $this->mTitle
->userIsWatching() ) {
919 # The talk page isn't in the regular link tables, so we need to update manually:
920 $talkns = $ns ^
1; # talk -> normal; normal -> talk
921 $dbw->updateArray( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
922 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
924 # standard deferred updates
925 $this->editUpdates( $text );
927 $this->showArticle( $text, wfMsg( 'newarticle' ) );
932 * Side effects: loads last edit
934 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '') {
935 $this->loadLastEdit();
936 $oldtext = $this->getContent( true );
937 if ($section != '') {
938 if($section=='new') {
939 if($summary) $subject="== {$summary} ==\n\n";
940 $text=$oldtext."\n\n".$subject.$text;
943 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
944 # comments to be stripped as well)
946 $parser=new Parser();
947 $parser->mOutputType
=OT_WIKI
;
948 $oldtext=$parser->strip($oldtext, $striparray, true);
950 # now that we can be sure that no pseudo-sections are in the source,
952 # Unfortunately we can't simply do a preg_replace because that might
953 # replace the wrong section, so we have to use the section counter instead
954 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
955 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
956 $secs[$section*2]=$text."\n\n"; // replace with edited
958 # section 0 is top (intro) section
961 # headline of old section - we need to go through this section
962 # to determine if there are any subsections that now need to
963 # be erased, as the mother section has been replaced with
964 # the text of all subsections.
965 $headline=$secs[$section*2-1];
966 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
969 # determine headline level for wikimarkup headings
970 if(strpos($hlevel,'=')!==false) {
971 $hlevel=strlen($hlevel);
974 $secs[$section*2-1]=''; // erase old headline
977 while(!empty($secs[$count*2-1]) && !$break) {
979 $subheadline=$secs[$count*2-1];
981 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
982 $subhlevel=$matches[1];
983 if(strpos($subhlevel,'=')!==false) {
984 $subhlevel=strlen($subhlevel);
986 if($subhlevel > $hlevel) {
987 // erase old subsections
988 $secs[$count*2-1]='';
991 if($subhlevel <= $hlevel) {
999 $text=join('',$secs);
1000 # reinsert the stuff that we stripped out earlier
1001 $text=$parser->unstrip($text,$striparray);
1002 $text=$parser->unstripNoWiki($text,$striparray);
1010 * @todo document this function
1012 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1013 global $wgOut, $wgUser;
1014 global $wgDBtransactions, $wgMwRedir;
1015 global $wgUseSquid, $wgInternalServer;
1017 $fname = 'Article::updateArticle';
1020 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
1021 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
1022 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1024 $text = $m[1] . "\n"; # Remove all content but redirect
1026 else { $redir = 0; }
1028 $text = $this->preSaveTransform( $text );
1029 $dbw =& wfGetDB( DB_MASTER
);
1031 # Update article, but only if changed.
1033 # It's important that we either rollback or complete, otherwise an attacker could
1034 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1035 # could conceivably have the same effect, especially if cur is locked for long periods.
1036 if( $wgDBtransactions ) {
1037 $dbw->query( 'BEGIN', $fname );
1039 $userAbort = ignore_user_abort( true );
1042 $oldtext = $this->getContent( true );
1044 if ( 0 != strcmp( $text, $oldtext ) ) {
1045 $this->mCountAdjustment
= $this->isCountable( $text )
1046 - $this->isCountable( $oldtext );
1047 $now = wfTimestampNow();
1048 $won = wfInvertTimestamp( $now );
1050 # First update the cur row
1051 $dbw->updateArray( 'cur',
1053 'cur_text' => $text,
1054 'cur_comment' => $summary,
1055 'cur_minor_edit' => $me2,
1056 'cur_user' => $wgUser->getID(),
1057 'cur_timestamp' => $dbw->timestamp($now),
1058 'cur_user_text' => $wgUser->getName(),
1059 'cur_is_redirect' => $redir,
1061 'cur_touched' => $dbw->timestamp($now),
1062 'inverse_timestamp' => $won
1063 ), array( /* WHERE */
1064 'cur_id' => $this->getID(),
1065 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1069 if( $dbw->affectedRows() == 0 ) {
1070 /* Belated edit conflict! Run away!! */
1073 # Now insert the previous revision into old
1075 # This overwrites $oldtext if revision compression is on
1076 $flags = Article
::compressRevisionText( $oldtext );
1078 $dbw->insertArray( 'old',
1080 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1081 'old_namespace' => $this->mTitle
->getNamespace(),
1082 'old_title' => $this->mTitle
->getDBkey(),
1083 'old_text' => $oldtext,
1084 'old_comment' => $this->getComment(),
1085 'old_user' => $this->getUser(),
1086 'old_user_text' => $this->getUserText(),
1087 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1088 'old_minor_edit' => $me1,
1089 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1090 'old_flags' => $flags,
1094 $oldid = $dbw->insertId();
1096 $bot = (int)($wgUser->isBot() ||
$forceBot);
1097 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1098 $oldid, $this->getTimestamp(), $bot );
1099 Article
::onArticleEdit( $this->mTitle
);
1103 if( $wgDBtransactions ) {
1104 $dbw->query( 'COMMIT', $fname );
1106 ignore_user_abort( $userAbort );
1111 if (!$this->mTitle
->userIsWatching()) $this->watch();
1113 if ( $this->mTitle
->userIsWatching() ) {
1117 # standard deferred updates
1118 $this->editUpdates( $text );
1122 # Template namespace
1123 # Purge all articles linking here
1124 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1125 $titles = $this->mTitle
->getLinksTo();
1126 Title
::touchArray( $titles );
1127 if ( $wgUseSquid ) {
1128 foreach ( $titles as $title ) {
1129 $urls[] = $title->getInternalURL();
1135 if ( $wgUseSquid ) {
1136 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1137 $u = new SquidUpdate( $urls );
1141 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1147 * After we've either updated or inserted the article, update
1148 * the link tables and redirect to the new page.
1150 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1151 global $wgOut, $wgUser, $wgLinkCache;
1154 $wgLinkCache = new LinkCache();
1156 $wgLinkCache->forUpdate( true );
1158 # Get old version of link table to allow incremental link updates
1159 $wgLinkCache->preFill( $this->mTitle
);
1160 $wgLinkCache->clear();
1162 # Parse the text and replace links with placeholders
1163 $wgOut = new OutputPage();
1164 $wgOut->addWikiText( $text );
1166 # Look up the links in the DB and add them to the link cache
1167 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1169 if( $wgMwRedir->matchStart( $text ) )
1173 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1178 * @todo document this function a bit more
1180 function validate () {
1181 global $wgOut, $wgUseValidation;
1182 if( $wgUseValidation ) {
1183 require_once ( 'SpecialValidate.php' ) ;
1184 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1185 $wgOut->setRobotpolicy( 'noindex,follow' );
1186 if( $this->mTitle
->getNamespace() != 0 ) {
1187 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1190 $v = new Validation
;
1191 $v->validate_form( $this->mTitle
->getDBkey() );
1193 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1198 * Mark this particular edit as patrolled
1200 function markpatrolled() {
1201 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1202 $wgOut->setRobotpolicy( 'noindex,follow' );
1204 if ( !$wgUseRCPatrol )
1206 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1209 if ( $wgUser->getID() == 0 )
1211 $wgOut->loginToUse();
1214 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1216 $wgOut->sysopRequired();
1219 $rcid = $wgRequest->getVal( 'rcid' );
1220 if ( !is_null ( $rcid ) )
1222 RecentChange
::markPatrolled( $rcid );
1223 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1224 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1225 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1229 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1235 * Add or remove this page to my watchlist based on value of $add
1237 function watch( $add = true ) {
1238 global $wgUser, $wgOut, $wgLang;
1239 global $wgDeferredUpdateList;
1241 if ( 0 == $wgUser->getID() ) {
1242 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1245 if ( wfReadOnly() ) {
1246 $wgOut->readOnlyPage();
1250 $wgUser->addWatch( $this->mTitle
);
1252 $wgUser->removeWatch( $this->mTitle
);
1254 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1255 $wgOut->setRobotpolicy( 'noindex,follow' );
1257 $sk = $wgUser->getSkin() ;
1258 $link = $this->mTitle
->getPrefixedText();
1261 $text = wfMsg( 'addedwatchtext', $link );
1263 $text = wfMsg( 'removedwatchtext', $link );
1264 $wgOut->addWikiText( $text );
1266 $up = new UserUpdate();
1267 array_push( $wgDeferredUpdateList, $up );
1269 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1273 * Stop watching a page, it act just like a call to watch(false)
1275 function unwatch() {
1276 $this->watch( false );
1282 function protect( $limit = 'sysop' ) {
1283 global $wgUser, $wgOut, $wgRequest;
1285 if ( ! $wgUser->isSysop() ) {
1286 $wgOut->sysopRequired();
1289 if ( wfReadOnly() ) {
1290 $wgOut->readOnlyPage();
1293 $id = $this->mTitle
->getArticleID();
1295 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1299 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1300 $reason = $wgRequest->getText( 'wpReasonProtect' );
1303 $dbw =& wfGetDB( DB_MASTER
);
1304 $dbw->updateArray( 'cur',
1306 'cur_touched' => $dbw->timestamp(),
1307 'cur_restrictions' => (string)$limit
1308 ), array( /* WHERE */
1310 ), 'Article::protect'
1313 $log = new LogPage( 'protect' );
1314 if ( $limit === '' ) {
1315 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1317 $log->addEntry( 'protect', $this->mTitle
, $reason );
1319 $wgOut->redirect( $this->mTitle
->getFullURL() );
1322 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1323 return $this->confirmProtect( '', $reason, $limit );
1328 * Output protection confirmation dialog
1330 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1333 wfDebug( "Article::confirmProtect\n" );
1335 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1336 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1341 if ( $limit === '' ) {
1342 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1343 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1344 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1345 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1346 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1347 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1349 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1350 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1351 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1352 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1353 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1354 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1357 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1360 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1364 <label for='wpReasonProtect'>{$protcom}:</label>
1367 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1375 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1378 <label for='wpConfirmProtect'>{$check}</label>
1384 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1390 $wgOut->returnToMain( false );
1394 * Unprotect the pages
1396 function unprotect() {
1397 return $this->protect( '' );
1401 * UI entry point for page deletion
1404 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1405 $fname = 'Article::delete';
1406 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1407 $reason = $wgRequest->getText( 'wpReason' );
1409 # This code desperately needs to be totally rewritten
1412 if ( ( ! $wgUser->isSysop() ) ) {
1413 $wgOut->sysopRequired();
1416 if ( wfReadOnly() ) {
1417 $wgOut->readOnlyPage();
1421 # Better double-check that it hasn't been deleted yet!
1422 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1423 if ( ( '' == trim( $this->mTitle
->getText() ) )
1424 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1425 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1430 $this->doDelete( $reason );
1434 # determine whether this page has earlier revisions
1435 # and insert a warning if it does
1436 # we select the text because it might be useful below
1437 $dbr =& $this->getDB();
1438 $ns = $this->mTitle
->getNamespace();
1439 $title = $this->mTitle
->getDBkey();
1440 $old = $dbr->getArray( 'old',
1441 array( 'old_text', 'old_flags' ),
1443 'old_namespace' => $ns,
1444 'old_title' => $title,
1445 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1448 if( $old !== false && !$confirm ) {
1449 $skin=$wgUser->getSkin();
1450 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1451 $wgOut->addHTML( $skin->historyLink() .'</b>');
1455 $s = $dbr->getArray( 'cur',
1456 array( 'cur_text' ),
1458 'cur_namespace' => $ns,
1459 'cur_title' => $title,
1460 ), $fname, $this->getSelectOptions()
1463 if( $s !== false ) {
1464 # if this is a mini-text, we can paste part of it into the deletion reason
1466 #if this is empty, an earlier revision may contain "useful" text
1468 if($s->cur_text
!= '') {
1472 $text = Article
::getRevisionText( $old );
1478 $length=strlen($text);
1480 # this should not happen, since it is not possible to store an empty, new
1481 # page. Let's insert a standard text in case it does, though
1482 if($length == 0 && $reason === '') {
1483 $reason = wfMsg('exblank');
1486 if($length < 500 && $reason === '') {
1488 # comment field=255, let's grep the first 150 to have some user
1490 $text=substr($text,0,150);
1491 # let's strip out newlines and HTML tags
1492 $text=preg_replace('/\"/',"'",$text);
1493 $text=preg_replace('/\</','<',$text);
1494 $text=preg_replace('/\>/','>',$text);
1495 $text=preg_replace("/[\n\r]/",'',$text);
1497 $reason=wfMsg('excontent'). " '".$text;
1499 $reason=wfMsg('exbeforeblank') . " '".$text;
1501 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1506 return $this->confirmDelete( '', $reason );
1510 * Output deletion confirmation dialog
1512 function confirmDelete( $par, $reason ) {
1515 wfDebug( "Article::confirmDelete\n" );
1517 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1518 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1519 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1520 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1522 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1524 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1525 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1526 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1529 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1533 <label for='wpReason'>{$delcom}:</label>
1536 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1544 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1547 <label for='wpConfirm'>{$check}</label>
1553 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1559 $wgOut->returnToMain( false );
1564 * Perform a deletion and output success or failure messages
1566 function doDelete( $reason ) {
1567 global $wgOut, $wgUser, $wgLang;
1568 $fname = 'Article::doDelete';
1569 wfDebug( $fname."\n" );
1571 if ( $this->doDeleteArticle( $reason ) ) {
1572 $deleted = $this->mTitle
->getPrefixedText();
1574 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1575 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1577 $sk = $wgUser->getSkin();
1578 $loglink = $sk->makeKnownLink( $wgLang->getNsText( NS_PROJECT
) .
1579 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1581 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1583 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1584 $wgOut->returnToMain( false );
1586 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1591 * Back-end article deletion
1592 * Deletes the article with database consistency, writes logs, purges caches
1595 function doDeleteArticle( $reason ) {
1596 global $wgUser, $wgLang;
1597 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1599 $fname = 'Article::doDeleteArticle';
1600 wfDebug( $fname."\n" );
1602 $dbw =& wfGetDB( DB_MASTER
);
1603 $ns = $this->mTitle
->getNamespace();
1604 $t = $this->mTitle
->getDBkey();
1605 $id = $this->mTitle
->getArticleID();
1607 if ( $t == '' ||
$id == 0 ) {
1611 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1612 array_push( $wgDeferredUpdateList, $u );
1614 $linksTo = $this->mTitle
->getLinksTo();
1617 if ( $wgUseSquid ) {
1619 $this->mTitle
->getInternalURL(),
1620 $this->mTitle
->getInternalURL( 'history' )
1622 foreach ( $linksTo as $linkTo ) {
1623 $urls[] = $linkTo->getInternalURL();
1626 $u = new SquidUpdate( $urls );
1627 array_push( $wgDeferredUpdateList, $u );
1631 # Client and file cache invalidation
1632 Title
::touchArray( $linksTo );
1634 # Move article and history to the "archive" table
1635 $archiveTable = $dbw->tableName( 'archive' );
1636 $oldTable = $dbw->tableName( 'old' );
1637 $curTable = $dbw->tableName( 'cur' );
1638 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1639 $linksTable = $dbw->tableName( 'links' );
1640 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1642 $dbw->insertSelect( 'archive', 'cur',
1644 'ar_namespace' => 'cur_namespace',
1645 'ar_title' => 'cur_title',
1646 'ar_text' => 'cur_text',
1647 'ar_comment' => 'cur_comment',
1648 'ar_user' => 'cur_user',
1649 'ar_user_text' => 'cur_user_text',
1650 'ar_timestamp' => 'cur_timestamp',
1651 'ar_minor_edit' => 'cur_minor_edit',
1654 'cur_namespace' => $ns,
1659 $dbw->insertSelect( 'archive', 'old',
1661 'ar_namespace' => 'old_namespace',
1662 'ar_title' => 'old_title',
1663 'ar_text' => 'old_text',
1664 'ar_comment' => 'old_comment',
1665 'ar_user' => 'old_user',
1666 'ar_user_text' => 'old_user_text',
1667 'ar_timestamp' => 'old_timestamp',
1668 'ar_minor_edit' => 'old_minor_edit',
1669 'ar_flags' => 'old_flags'
1671 'old_namespace' => $ns,
1676 # Now that it's safely backed up, delete it
1678 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1679 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1680 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1682 # Finally, clean up the link tables
1683 $t = $this->mTitle
->getPrefixedDBkey();
1685 Article
::onArticleDelete( $this->mTitle
);
1687 # Insert broken links
1688 $brokenLinks = array();
1689 foreach ( $linksTo as $titleObj ) {
1690 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1691 $linkID = $titleObj->getArticleID();
1692 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1694 $dbw->insertArray( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1697 $dbw->delete( 'links', array( 'l_to' => $id ) );
1698 $dbw->delete( 'links', array( 'l_from' => $id ) );
1699 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1700 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1701 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1704 $log = new LogPage( 'delete' );
1705 $log->addEntry( 'delete', $this->mTitle
, $reason );
1707 # Clear the cached article id so the interface doesn't act like we exist
1708 $this->mTitle
->resetArticleID( 0 );
1709 $this->mTitle
->mArticleID
= 0;
1714 * Revert a modification
1716 function rollback() {
1717 global $wgUser, $wgLang, $wgOut, $wgRequest;
1718 $fname = 'Article::rollback';
1720 if ( ! $wgUser->isSysop() ) {
1721 $wgOut->sysopRequired();
1724 if ( wfReadOnly() ) {
1725 $wgOut->readOnlyPage( $this->getContent( true ) );
1728 $dbw =& wfGetDB( DB_MASTER
);
1730 # Enhanced rollback, marks edits rc_bot=1
1731 $bot = $wgRequest->getBool( 'bot' );
1733 # Replace all this user's current edits with the next one down
1734 $tt = $this->mTitle
->getDBKey();
1735 $n = $this->mTitle
->getNamespace();
1737 # Get the last editor, lock table exclusively
1738 $s = $dbw->getArray( 'cur',
1739 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1740 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1741 $fname, 'FOR UPDATE'
1743 if( $s === false ) {
1745 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1748 $ut = $dbw->strencode( $s->cur_user_text
);
1749 $uid = $s->cur_user
;
1752 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1753 if( $from != $s->cur_user_text
) {
1754 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1755 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1756 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1757 htmlspecialchars( $from ),
1758 htmlspecialchars( $s->cur_user_text
) ) );
1759 if($s->cur_comment
!= '') {
1761 wfMsg('editcomment',
1762 htmlspecialchars( $s->cur_comment
) ) );
1767 # Get the last edit not by this guy
1768 $s = $dbw->getArray( 'old',
1769 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1771 'old_namespace' => $n,
1773 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1774 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1776 if( $s === false ) {
1778 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1779 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1784 # Mark all reverted edits as bot
1785 $dbw->updateArray( 'recentchanges',
1788 ), array( /* WHERE */
1790 "rc_timestamp > '{$s->old_timestamp}'",
1796 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1797 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1798 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1799 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1800 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1801 Article
::onArticleEdit( $this->mTitle
);
1802 $wgOut->returnToMain( false );
1807 * Do standard deferred updates after page view
1810 function viewUpdates() {
1811 global $wgDeferredUpdateList;
1812 if ( 0 != $this->getID() ) {
1813 global $wgDisableCounters;
1814 if( !$wgDisableCounters ) {
1815 Article
::incViewCount( $this->getID() );
1816 $u = new SiteStatsUpdate( 1, 0, 0 );
1817 array_push( $wgDeferredUpdateList, $u );
1820 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1821 $this->mTitle
->getDBkey() );
1822 array_push( $wgDeferredUpdateList, $u );
1826 * Do standard deferred updates after page edit.
1827 * Every 1000th edit, prune the recent changes table.
1829 * @param string $text
1831 function editUpdates( $text ) {
1832 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1833 global $wgMessageCache;
1836 if ( 0 == mt_rand( 0, 999 ) ) {
1837 $dbw =& wfGetDB( DB_MASTER
);
1838 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1839 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1840 $dbw->query( $sql );
1842 $id = $this->getID();
1843 $title = $this->mTitle
->getPrefixedDBkey();
1844 $shortTitle = $this->mTitle
->getDBkey();
1846 $adj = $this->mCountAdjustment
;
1849 $u = new LinksUpdate( $id, $title );
1850 array_push( $wgDeferredUpdateList, $u );
1851 $u = new SiteStatsUpdate( 0, 1, $adj );
1852 array_push( $wgDeferredUpdateList, $u );
1853 $u = new SearchUpdate( $id, $title, $text );
1854 array_push( $wgDeferredUpdateList, $u );
1856 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1857 array_push( $wgDeferredUpdateList, $u );
1859 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1860 $wgMessageCache->replace( $shortTitle, $text );
1866 * @todo document this function
1869 function setOldSubtitle() {
1870 global $wgLang, $wgOut, $wgUser;
1872 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1873 $sk = $wgUser->getSkin();
1874 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1875 $r = wfMsg( 'revisionasofwithlink', $td, $lnk );
1876 $wgOut->setSubtitle( $r );
1880 * This function is called right before saving the wikitext,
1881 * so we can do things like signatures and links-in-context.
1883 * @param string $text
1885 function preSaveTransform( $text ) {
1886 global $wgParser, $wgUser;
1887 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1890 /* Caching functions */
1893 * checkLastModified returns true if it has taken care of all
1894 * output to the client that is necessary for this request.
1895 * (that is, it has sent a cached version of the page)
1897 function tryFileCache() {
1898 static $called = false;
1900 wfDebug( " tryFileCache() -- called twice!?\n" );
1904 if($this->isFileCacheable()) {
1905 $touched = $this->mTouched
;
1906 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1907 # Expire the main page quicker
1908 $expire = wfUnix2Timestamp( time() - 3600 );
1909 $touched = max( $expire, $touched );
1911 $cache = new CacheManager( $this->mTitle
);
1912 if($cache->isFileCacheGood( $touched )) {
1914 wfDebug( " tryFileCache() - about to load\n" );
1915 $cache->loadFromFileCache();
1918 wfDebug( " tryFileCache() - starting buffer\n" );
1919 ob_start( array(&$cache, 'saveToFileCache' ) );
1922 wfDebug( " tryFileCache() - not cacheable\n" );
1927 * Check if the page can be cached
1930 function isFileCacheable() {
1931 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1932 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1934 return $wgUseFileCache
1935 and (!$wgShowIPinHeader)
1936 and ($this->getID() != 0)
1937 and ($wgUser->getId() == 0)
1938 and (!$wgUser->getNewtalk())
1939 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1940 and (empty( $action ) ||
$action == 'view')
1941 and (!isset($oldid))
1943 and (!isset($redirect))
1944 and (!isset($printable))
1945 and (!$this->mRedirectedFrom
);
1949 * Loads cur_touched and returns a value indicating if it should be used
1952 function checkTouched() {
1953 $fname = 'Article::checkTouched';
1954 $id = $this->getID();
1955 $dbr =& $this->getDB();
1956 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
1957 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
1958 if( $s !== false ) {
1959 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
1960 return !$s->cur_is_redirect
;
1967 * Edit an article without doing all that other stuff
1969 * @param string $text text submitted
1970 * @param string $comment comment submitted
1971 * @param integer $minor whereas it's a minor modification
1973 function quickEdit( $text, $comment = '', $minor = 0 ) {
1974 global $wgUser, $wgMwRedir;
1975 $fname = 'Article::quickEdit';
1976 wfProfileIn( $fname );
1978 $dbw =& wfGetDB( DB_MASTER
);
1979 $ns = $this->mTitle
->getNamespace();
1980 $dbkey = $this->mTitle
->getDBkey();
1981 $encDbKey = $dbw->strencode( $dbkey );
1982 $timestamp = wfTimestampNow();
1985 $dbw->insertSelect( 'old', 'cur',
1987 'old_namespace' => 'cur_namespace',
1988 'old_title' => 'cur_title',
1989 'old_text' => 'cur_text',
1990 'old_comment' => 'cur_comment',
1991 'old_user' => 'cur_user',
1992 'old_user_text' => 'cur_user_text',
1993 'old_timestamp' => 'cur_timestamp',
1994 'inverse_timestamp' => '99999999999999-cur_timestamp',
1996 'cur_namespace' => $ns,
1997 'cur_title' => $dbkey,
2001 # Use the affected row count to determine if the article is new
2002 $numRows = $dbw->affectedRows();
2004 # Make an array of fields to be inserted
2006 'cur_text' => $text,
2007 'cur_timestamp' => $timestamp,
2008 'cur_user' => $wgUser->getID(),
2009 'cur_user_text' => $wgUser->getName(),
2010 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2011 'cur_comment' => $comment,
2012 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ?
1 : 0,
2013 'cur_minor_edit' => intval($minor),
2014 'cur_touched' => $dbw->timestamp($timestamp),
2019 $fields['cur_is_new'] = 0;
2020 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2022 # Insert new article
2023 $fields['cur_is_new'] = 1;
2024 $fields['cur_namespace'] = $ns;
2025 $fields['cur_title'] = $dbkey;
2026 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
2027 $dbw->insertArray( 'cur', $fields, $fname );
2029 wfProfileOut( $fname );
2033 * Used to increment the view counter
2036 * @param integer $id article id
2038 function incViewCount( $id ) {
2039 $id = intval( $id );
2040 global $wgHitcounterUpdateFreq;
2042 $dbw =& wfGetDB( DB_MASTER
);
2043 $curTable = $dbw->tableName( 'cur' );
2044 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2045 $acchitsTable = $dbw->tableName( 'acchits' );
2047 if( $wgHitcounterUpdateFreq <= 1 ){ //
2048 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2052 # Not important enough to warrant an error page in case of failure
2053 $oldignore = $dbw->ignoreErrors( true );
2055 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2057 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2058 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2059 # Most of the time (or on SQL errors), skip row count check
2060 $dbw->ignoreErrors( $oldignore );
2064 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2065 $row = $dbw->fetchObject( $res );
2066 $rown = intval( $row->n
);
2067 if( $rown >= $wgHitcounterUpdateFreq ){
2068 wfProfileIn( 'Article::incViewCount-collect' );
2069 $old_user_abort = ignore_user_abort( true );
2071 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2072 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2073 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2075 $dbw->query("DELETE FROM $hitcounterTable");
2076 $dbw->query('UNLOCK TABLES');
2077 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2078 'WHERE cur_id = hc_id');
2079 $dbw->query("DROP TABLE $acchitsTable");
2081 ignore_user_abort( $old_user_abort );
2082 wfProfileOut( 'Article::incViewCount-collect' );
2084 $dbw->ignoreErrors( $oldignore );
2088 * The onArticle*() functions are supposed to be a kind of hooks
2089 * which should be called whenever any of the specified actions
2092 * This is a good place to put code to clear caches, for instance.
2094 * This is called on page move and undelete, as well as edit
2096 * @param $title_obj a title object
2099 function onArticleCreate($title_obj) {
2100 global $wgUseSquid, $wgDeferredUpdateList;
2102 $titles = $title_obj->getBrokenLinksTo();
2105 if ( $wgUseSquid ) {
2106 $urls = $title_obj->getSquidURLs();
2107 foreach ( $titles as $linkTitle ) {
2108 $urls[] = $linkTitle->getInternalURL();
2110 $u = new SquidUpdate( $urls );
2111 array_push( $wgDeferredUpdateList, $u );
2114 # Clear persistent link cache
2115 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2118 function onArticleDelete($title_obj) {
2119 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2121 function onArticleEdit($title_obj) {
2122 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2127 * Info about this page
2130 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgAllowPageInfo;
2131 $fname = 'Article::info';
2133 if ( !$wgAllowPageInfo ) {
2134 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2138 $dbr =& $this->getDB();
2140 $basenamespace = $wgTitle->getNamespace() & (~
1);
2141 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2142 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2143 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2144 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2145 $wgOut->setPagetitle( $fullTitle );
2146 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2148 # first, see if the page exists at all.
2149 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2151 $wgOut->addHTML( wfMsg('noarticletext') );
2153 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2154 $this->getSelectOptions() );
2155 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2156 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2157 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2159 # to find number of distinct authors, we need to do some
2160 # funny stuff because of the cur/old table split:
2161 # - first, find the name of the 'cur' author
2162 # - then, find the number of *other* authors in 'old'
2165 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2166 $this->getSelectOptions() );
2168 # find number of 'old' authors excluding 'cur' author
2169 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2170 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2171 $this->getSelectOptions() ) +
1;
2173 # now for the Talk page ...
2174 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2175 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2178 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2182 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2183 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2185 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2189 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2190 $this->getSelectOptions() );
2191 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2192 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2193 $fname, $this->getSelectOptions() );
2195 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );