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( 'gzip', $flags ) ) {
89 # Deal with optional compression of archived pages.
90 # This can be done periodically via maintenance/compressOld.php, and
91 # as pages are saved if $wgCompressRevisions is set.
92 $text = gzinflate( $text );
95 global $wgLegacyEncoding;
96 if( $wgLegacyEncoding && !in_array( 'utf-8', $flags ) ) {
97 # Old revisions kept around in a legacy encoding?
98 # Upconvert on demand.
99 global $wgInputEncoding, $wgContLang;
100 $text = $wgContLang->iconv( $wgLegacyEncoding, $wgInputEncoding, $text );
103 if( in_array( 'link', $flags ) ) {
105 $text = Article
::followLink( $text );
111 * If $wgCompressRevisions is enabled, we will compress data.
112 * The input string is modified in place.
113 * Return value is the flags field: contains 'gzip' if the
114 * data is compressed, and 'utf-8' if we're saving in UTF-8
118 * @param mixed $text reference to a text
121 function compressRevisionText( &$text ) {
122 global $wgCompressRevisions, $wgUseLatin1;
124 if( !$wgUseLatin1 ) {
125 # Revisions not marked this way will be converted
126 # on load if $wgLegacyCharset is set in the future.
129 if( $wgCompressRevisions ) {
130 if( function_exists( 'gzdeflate' ) ) {
131 $text = gzdeflate( $text );
134 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
137 return implode( ',', $flags );
141 * Returns the text associated with a "link" type old table row
144 * @return string $text|false
146 function followLink( $link ) {
147 # Split the link into fields and values
148 $lines = explode( '\n', $link );
150 $locations = array();
151 foreach ( $lines as $line ) {
153 if ( $line{0} == '#' ) {
157 if ( preg_match( '/^(.*?)\s*:\s*(.*)$/', $line, $matches ) ) {
158 $field = strtolower($matches[1]);
159 $value = $matches[2];
160 if ( $field == 'hash' ) {
162 } elseif ( $field == 'location' ) {
163 $locations[] = $value;
168 if ( $hash === '' ) {
172 # Look in each specified location for the text
174 foreach ( $locations as $location ) {
175 $text = Article
::fetchFromLocation( $location, $hash );
176 if ( $text !== false ) {
189 function fetchFromLocation( $location, $hash ) {
190 global $wgLoadBalancer;
191 $fname = 'fetchFromLocation';
192 wfProfileIn( $fname );
194 $p = strpos( $location, ':' );
195 if ( $p === false ) {
196 wfProfileOut( $fname );
200 $type = substr( $location, 0, $p );
204 # MySQL locations are specified by mysql://<machineID>/<dbname>/<tblname>/<index>
205 # Machine ID 0 is the current connection
206 if ( preg_match( '/^mysql:\/\/(\d+)\/([A-Za-z_]+)\/([A-Za-z_]+)\/([A-Za-z_]+)$/',
207 $location, $matches ) ) {
208 $machineID = $matches[1];
209 $dbName = $matches[2];
210 $tblName = $matches[3];
211 $index = $matches[4];
212 if ( $machineID == 0 ) {
214 $db =& $this->getDB();
216 # Alternate connection
217 $db =& $wgLoadBalancer->getConnection( $machineID );
219 if ( array_key_exists( $machineId, $wgKnownMysqlServers ) ) {
220 # Try to open, return false on failure
221 $params = $wgKnownDBServers[$machineId];
222 $db = Database
::newFromParams( $params['server'], $params['user'], $params['password'],
223 $dbName, 1, DBO_IGNORE
);
226 if ( $db->isOpen() ) {
227 $index = $db->strencode( $index );
228 $res = $db->query( "SELECT blob_data FROM $dbName.$tblName " .
229 "WHERE blob_index='$index' " . $this->getSelectOptions(), $fname );
230 $row = $db->fetchObject( $res );
231 $text = $row->text_data
;
236 # File locations are of the form file://<filename>, relative to the current directory
237 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
238 $filename = strstr( $location, 'file://' );
239 $text = @file_get_contents
( $matches[1] );
241 if ( $text !== false ) {
242 # Got text, now we need to interpret it
243 # The first line contains information about how to do this
244 $p = strpos( $text, '\n' );
245 $type = substr( $text, 0, $p );
246 $text = substr( $text, $p +
1 );
251 $text = gzinflate( $text );
254 $object = unserialize( $text );
255 $text = $object->getItem( $hash );
261 wfProfileOut( $fname );
266 * Note that getContent/loadContent may follow redirects if
267 * not told otherwise, and so may cause a change to mTitle.
270 * @return Return the text of this revision
272 function getContent( $noredir ) {
275 # Get variables from query string :P
276 $action = $wgRequest->getText( 'action', 'view' );
277 $section = $wgRequest->getText( 'section' );
279 $fname = 'Article::getContent';
280 wfProfileIn( $fname );
282 if ( 0 == $this->getID() ) {
283 if ( 'edit' == $action ) {
284 wfProfileOut( $fname );
285 return ''; # was "newarticletext", now moved above the box)
287 wfProfileOut( $fname );
288 return wfMsg( 'noarticletext' );
290 $this->loadContent( $noredir );
291 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
292 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
293 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
296 wfProfileOut( $fname );
297 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
299 if($action=='edit') {
301 if($section=='new') {
302 wfProfileOut( $fname );
306 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
307 # comments to be stripped as well)
308 $rv=$this->getSection($this->mContent
,$section);
309 wfProfileOut( $fname );
313 wfProfileOut( $fname );
314 return $this->mContent
;
320 * This function returns the text of a section, specified by a number ($section).
321 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
322 * the first section before any such heading (section 0).
324 * If a section contains subsections, these are also returned.
326 * @param string $text text to look in
327 * @param integer $section section number
328 * @return string text of the requested section
330 function getSection($text,$section) {
332 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
333 # comments to be stripped as well)
335 $parser=new Parser();
336 $parser->mOutputType
=OT_WIKI
;
337 $striptext=$parser->strip($text, $striparray, true);
339 # now that we can be sure that no pseudo-sections are in the source,
340 # split it up by section
343 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
345 PREG_SPLIT_DELIM_CAPTURE
);
349 $headline=$secs[$section*2-1];
350 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
353 # translate wiki heading into level
354 if(strpos($hlevel,'=')!==false) {
355 $hlevel=strlen($hlevel);
358 $rv=$headline. $secs[$section*2];
362 while(!empty($secs[$count*2-1]) && !$break) {
364 $subheadline=$secs[$count*2-1];
365 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
366 $subhlevel=$matches[1];
367 if(strpos($subhlevel,'=')!==false) {
368 $subhlevel=strlen($subhlevel);
370 if($subhlevel > $hlevel) {
371 $rv.=$subheadline.$secs[$count*2];
373 if($subhlevel <= $hlevel) {
380 # reinsert stripped tags
381 $rv=$parser->unstrip($rv,$striparray);
382 $rv=$parser->unstripNoWiki($rv,$striparray);
389 * Return an array of the columns of the "cur"-table
391 function &getCurContentFields() {
392 global $wgArticleCurContentFields;
393 if ( !$wgArticleCurContentFields ) {
394 $wgArticleCurContentFields = array( 'cur_text','cur_timestamp','cur_user', 'cur_user_text',
395 'cur_comment','cur_counter','cur_restrictions','cur_touched' );
397 return $wgArticleCurContentFields;
401 * Return an array of the columns of the "old"-table
403 function &getOldContentFields() {
404 global $wgArticleOldContentFields;
405 if ( !$wgArticleOldContentFields ) {
406 $wgArticleOldContentFields = array( 'old_namespace','old_title','old_text','old_timestamp',
407 'old_user','old_user_text','old_comment','old_flags' );
409 return $wgArticleOldContentFields;
413 * Load the revision (including cur_text) into this object
415 function loadContent( $noredir = false ) {
416 global $wgOut, $wgRequest;
418 if ( $this->mContentLoaded
) return;
420 $dbr =& $this->getDB();
422 $oldid = $wgRequest->getVal( 'oldid' );
423 $redirect = $wgRequest->getVal( 'redirect' );
425 $fname = 'Article::loadContent';
427 # Pre-fill content with error message so that if something
428 # fails we'll have something telling us what we intended.
430 $t = $this->mTitle
->getPrefixedText();
431 if ( isset( $oldid ) ) {
432 $oldid = IntVal( $oldid );
433 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
434 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
438 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
440 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
441 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
449 if ( isset( $oldid ) ) {
450 $t .= ',oldid='.$oldid;
452 if ( isset( $redirect ) ) {
453 $redirect = ($redirect == 'no') ?
'no' : 'yes';
454 $t .= ',redirect='.$redirect;
456 $this->mContent
= wfMsg( 'missingarticle', $t );
458 if ( ! $oldid ) { # Retrieve current version
459 $id = $this->getID();
460 if ( 0 == $id ) return;
462 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ), $fname,
463 $this->getSelectOptions() );
464 if ( $s === false ) {
468 # If we got a redirect, follow it (unless we've been told
469 # not to by either the function parameter or the query
470 if ( ( 'no' != $redirect ) && ( false == $noredir ) ) {
471 $rt = Title
::newFromRedirect( $s->cur_text
);
472 # process if title object is valid and not special:userlogout
473 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
474 # Gotta hand redirects to special pages differently:
475 # Fill the HTTP response "Location" header and ignore
476 # the rest of the page we're on.
478 if ( $rt->getInterwiki() != '' ) {
479 $wgOut->redirect( $rt->getFullURL() ) ;
482 if ( $rt->getNamespace() == NS_SPECIAL
) {
483 $wgOut->redirect( $rt->getFullURL() );
486 $rid = $rt->getArticleID();
488 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
489 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
491 if ( $redirRow !== false ) {
492 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
500 $this->mContent
= $s->cur_text
;
501 $this->mUser
= $s->cur_user
;
502 $this->mUserText
= $s->cur_user_text
;
503 $this->mComment
= $s->cur_comment
;
504 $this->mCounter
= $s->cur_counter
;
505 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
506 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
507 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
508 $this->mTitle
->mRestrictionsLoaded
= true;
509 } else { # oldid set, retrieve historical version
510 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
511 $fname, $this->getSelectOptions() );
512 if ( $s === false ) {
516 if( $this->mTitle
->getNamespace() != $s->old_namespace ||
517 $this->mTitle
->getDBkey() != $s->old_title
) {
518 $oldTitle = Title
::makeTitle( $s->old_namesapce
, $s->old_title
);
519 $this->mTitle
= $oldTitle;
520 $wgTitle = $oldTitle;
522 $this->mContent
= Article
::getRevisionText( $s );
523 $this->mUser
= $s->old_user
;
524 $this->mUserText
= $s->old_user_text
;
525 $this->mComment
= $s->old_comment
;
527 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
529 $this->mContentLoaded
= true;
530 return $this->mContent
;
534 * Gets the article text without using so many damn globals
535 * Returns false on error
537 * @param integer $oldid
539 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
540 if ( $this->mContentLoaded
) {
541 return $this->mContent
;
543 $this->mContent
= false;
545 $fname = 'Article::getContentWithout';
546 $dbr =& $this->getDB();
548 if ( ! $oldid ) { # Retrieve current version
549 $id = $this->getID();
554 $s = $dbr->selectRow( 'cur', $this->getCurContentFields(), array( 'cur_id' => $id ),
555 $fname, $this->getSelectOptions() );
556 if ( $s === false ) {
560 # If we got a redirect, follow it (unless we've been told
561 # not to by either the function parameter or the query
563 $rt = Title
::newFromRedirect( $s->cur_text
);
564 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != NS_SPECIAL
) {
565 $rid = $rt->getArticleID();
567 $redirRow = $dbr->selectRow( 'cur', $this->getCurContentFields(),
568 array( 'cur_id' => $rid ), $fname, $this->getSelectOptions() );
570 if ( $redirRow !== false ) {
571 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
579 $this->mContent
= $s->cur_text
;
580 $this->mUser
= $s->cur_user
;
581 $this->mUserText
= $s->cur_user_text
;
582 $this->mComment
= $s->cur_comment
;
583 $this->mCounter
= $s->cur_counter
;
584 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
585 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
586 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->cur_restrictions
) );
587 $this->mTitle
->mRestrictionsLoaded
= true;
588 } else { # oldid set, retrieve historical version
589 $s = $dbr->selectRow( 'old', $this->getOldContentFields(), array( 'old_id' => $oldid ),
590 $fname, $this->getSelectOptions() );
591 if ( $s === false ) {
594 $this->mContent
= Article
::getRevisionText( $s );
595 $this->mUser
= $s->old_user
;
596 $this->mUserText
= $s->old_user_text
;
597 $this->mComment
= $s->old_comment
;
599 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->old_timestamp
);
601 $this->mContentLoaded
= true;
602 return $this->mContent
;
606 * Read/write accessor to select FOR UPDATE
608 function forUpdate( $x = NULL ) {
609 return wfSetVar( $this->mForUpdate
, $x );
613 * Get the database which should be used for reads
616 if ( $this->mForUpdate
) {
617 return wfGetDB( DB_MASTER
);
619 return wfGetDB( DB_SLAVE
);
624 * Get options for all SELECT statements
625 * Can pass an option array, to which the class-wide options will be appended
627 function getSelectOptions( $options = '' ) {
628 if ( $this->mForUpdate
) {
630 $options[] = 'FOR UPDATE';
632 $options = 'FOR UPDATE';
639 * Return the Article ID
642 if( $this->mTitle
) {
643 return $this->mTitle
->getArticleID();
650 * Get the view count for this article
652 function getCount() {
653 if ( -1 == $this->mCounter
) {
654 $id = $this->getID();
655 $dbr =& $this->getDB();
656 $this->mCounter
= $dbr->selectField( 'cur', 'cur_counter', 'cur_id='.$id,
657 'Article::getCount', $this->getSelectOptions() );
659 return $this->mCounter
;
663 * Would the given text make this article a "good" article (i.e.,
664 * suitable for including in the article count)?
666 function isCountable( $text ) {
667 global $wgUseCommaCount;
669 if ( 0 != $this->mTitle
->getNamespace() ) { return 0; }
670 if ( $this->isRedirect( $text ) ) { return 0; }
671 $token = ($wgUseCommaCount ?
',' : '[[' );
672 if ( false === strstr( $text, $token ) ) { return 0; }
677 * Tests if the article text represents a redirect
679 function isRedirect( $text = false ) {
680 if ( $text === false ) {
681 $this->loadContent();
682 $titleObj = Title
::newFromRedirect( $this->mText
);
684 $titleObj = Title
::newFromRedirect( $text );
686 return $titleObj !== NULL;
690 * Loads everything from cur except cur_text
691 * This isn't necessary for all uses, so it's only done if needed.
694 function loadLastEdit() {
696 if ( -1 != $this->mUser
) return;
698 $fname = 'Article::loadLastEdit';
700 $dbr =& $this->getDB();
701 $s = $dbr->selectRow( 'cur',
702 array( 'cur_user','cur_user_text','cur_timestamp', 'cur_comment','cur_minor_edit' ),
703 array( 'cur_id' => $this->getID() ), $fname, $this->getSelectOptions() );
705 if ( $s !== false ) {
706 $this->mUser
= $s->cur_user
;
707 $this->mUserText
= $s->cur_user_text
;
708 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->cur_timestamp
);
709 $this->mComment
= $s->cur_comment
;
710 $this->mMinorEdit
= $s->cur_minor_edit
;
714 function getTimestamp() {
715 $this->loadLastEdit();
716 return $this->mTimestamp
;
720 $this->loadLastEdit();
724 function getUserText() {
725 $this->loadLastEdit();
726 return $this->mUserText
;
729 function getComment() {
730 $this->loadLastEdit();
731 return $this->mComment
;
734 function getMinorEdit() {
735 $this->loadLastEdit();
736 return $this->mMinorEdit
;
739 function getContributors($limit = 0, $offset = 0) {
740 $fname = 'Article::getContributors';
742 # XXX: this is expensive; cache this info somewhere.
744 $title = $this->mTitle
;
746 $dbr =& $this->getDB();
747 $oldTable = $dbr->tableName( 'old' );
748 $userTable = $dbr->tableName( 'user' );
749 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
750 $ns = $title->getNamespace();
751 $user = $this->getUser();
753 $sql = "SELECT old_user, old_user_text, user_real_name, MAX(old_timestamp) as timestamp
754 FROM $oldTable LEFT JOIN $userTable ON old_user = user_id
755 WHERE old_namespace = $user
756 AND old_title = $encDBkey
757 AND old_user != $user
758 GROUP BY old_user, old_user_text, user_real_name
759 ORDER BY timestamp DESC";
761 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
762 $sql .= ' '. $this->getSelectOptions();
764 $res = $dbr->query($sql, $fname);
766 while ( $line = $dbr->fetchObject( $res ) ) {
767 $contribs[] = array($line->old_user
, $line->old_user_text
, $line->user_real_name
);
770 $dbr->freeResult($res);
775 * This is the default action of the script: just view the page of
779 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol;
780 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
781 $sk = $wgUser->getSkin();
783 $fname = 'Article::view';
784 wfProfileIn( $fname );
785 # Get variables from query string
786 $oldid = $wgRequest->getVal( 'oldid' );
787 $diff = $wgRequest->getVal( 'diff' );
788 $rcid = $wgRequest->getVal( 'rcid' );
790 $wgOut->setArticleFlag( true );
791 $wgOut->setRobotpolicy( 'index,follow' );
792 # If we got diff and oldid in the query, we want to see a
793 # diff page instead of the article.
795 if ( !is_null( $diff ) ) {
796 require_once( 'DifferenceEngine.php' );
797 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
798 $de = new DifferenceEngine( $oldid, $diff, $rcid );
801 # Run view updates for current revision only
802 $this->viewUpdates();
804 wfProfileOut( $fname );
807 if ( empty( $oldid ) && $this->checkTouched() ) {
808 if( $wgOut->checkLastModified( $this->mTouched
) ){
809 wfProfileOut( $fname );
811 } else if ( $this->tryFileCache() ) {
812 # tell wgOut that output is taken care of
814 $this->viewUpdates();
815 wfProfileOut( $fname );
819 # Should the parser cache be used?
820 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
828 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
832 if ( !$outputDone ) {
833 $text = $this->getContent( false ); # May change mTitle by following a redirect
835 # Another whitelist check in case oldid or redirects are altering the title
836 if ( !$this->mTitle
->userCanRead() ) {
837 $wgOut->loginToUse();
843 # We're looking at an old revision
845 if ( !empty( $oldid ) ) {
846 $this->setOldSubtitle( $oldid );
847 $wgOut->setRobotpolicy( 'noindex,follow' );
849 if ( '' != $this->mRedirectedFrom
) {
850 $sk = $wgUser->getSkin();
851 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
853 $s = wfMsg( 'redirectedfrom', $redir );
854 $wgOut->setSubtitle( $s );
856 # Can't cache redirects
860 # wrap user css and user js in pre and don't parse
861 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
863 $this->mTitle
->getNamespace() == NS_USER
&&
864 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
866 $wgOut->addWikiText( wfMsg('clearyourcache'));
867 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
868 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
870 $imageUrl = $wgStylePath.'/common/images/redirect.png';
871 $targetUrl = $rt->escapeLocalURL();
872 $titleText = htmlspecialchars( $rt->getPrefixedText() );
873 $link = $sk->makeLinkObj( $rt );
874 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'">' .
875 '<span class="redirectText">'.$link.'</span>' );
876 } else if ( $pcache ) {
877 # Display content and save to parser cache
878 $wgOut->addPrimaryWikiText( $text, $this );
880 # Display content, don't attempt to save to parser cache
881 $wgOut->addWikiText( $text );
884 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
885 # If we have been passed an &rcid= parameter, we want to give the user a
886 # chance to mark this new article as patrolled.
887 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
888 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
890 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
891 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
892 'action=markpatrolled&rcid='.$rcid )
896 # Put link titles into the link cache
897 $wgOut->transformBuffer();
899 # Add link titles as META keywords
900 $wgOut->addMetaTags() ;
902 $this->viewUpdates();
903 wfProfileOut( $fname );
907 * Theoretically we could defer these whole insert and update
908 * functions for after display, but that's taking a big leap
909 * of faith, and we want to be able to report database
910 * errors at some point.
913 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
914 global $wgOut, $wgUser;
915 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
917 $fname = 'Article::insertNewArticle';
919 $this->mCountAdjustment
= $this->isCountable( $text );
921 $ns = $this->mTitle
->getNamespace();
922 $ttl = $this->mTitle
->getDBkey();
923 $text = $this->preSaveTransform( $text );
924 if ( $this->isRedirect( $text ) ) { $redir = 1; }
927 $now = wfTimestampNow();
928 $won = wfInvertTimestamp( $now );
931 $dbw =& wfGetDB( DB_MASTER
);
933 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
935 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
937 $dbw->insert( 'cur', array(
939 'cur_namespace' => $ns,
942 'cur_comment' => $summary,
943 'cur_user' => $wgUser->getID(),
944 'cur_timestamp' => $dbw->timestamp($now),
945 'cur_minor_edit' => $isminor,
947 'cur_restrictions' => '',
948 'cur_user_text' => $wgUser->getName(),
949 'cur_is_redirect' => $redir,
951 'cur_random' => $rand,
952 'cur_touched' => $dbw->timestamp($now),
953 'inverse_timestamp' => $won,
956 $newid = $dbw->insertId();
957 $this->mTitle
->resetArticleID( $newid );
959 Article
::onArticleCreate( $this->mTitle
);
960 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
963 if(!$this->mTitle
->userIsWatching()) $this->watch();
965 if ( $this->mTitle
->userIsWatching() ) {
970 # The talk page isn't in the regular link tables, so we need to update manually:
971 $talkns = $ns ^
1; # talk -> normal; normal -> talk
972 $dbw->update( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
973 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
975 # standard deferred updates
976 $this->editUpdates( $text );
978 $this->showArticle( $text, wfMsg( 'newarticle' ) );
983 * Side effects: loads last edit if $edittime is NULL
985 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
986 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
987 if(is_null($edittime)) {
988 $this->loadLastEdit();
989 $oldtext = $this->getContent( true );
991 $dbw =& wfGetDB( DB_MASTER
);
992 $ns = $this->mTitle
->getNamespace();
993 $title = $this->mTitle
->getDBkey();
994 $obj = $dbw->selectRow( 'old',
995 array( 'old_text','old_flags'),
996 array( 'old_namespace' => $ns, 'old_title' => $title,
997 'old_timestamp' => $dbw->timestamp($edittime)),
999 $oldtext = Article
::getRevisionText( $obj );
1001 if ($section != '') {
1002 if($section=='new') {
1003 if($summary) $subject="== {$summary} ==\n\n";
1004 $text=$oldtext."\n\n".$subject.$text;
1007 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1008 # comments to be stripped as well)
1009 $striparray=array();
1010 $parser=new Parser();
1011 $parser->mOutputType
=OT_WIKI
;
1012 $oldtext=$parser->strip($oldtext, $striparray, true);
1014 # now that we can be sure that no pseudo-sections are in the source,
1016 # Unfortunately we can't simply do a preg_replace because that might
1017 # replace the wrong section, so we have to use the section counter instead
1018 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1019 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1020 $secs[$section*2]=$text."\n\n"; // replace with edited
1022 # section 0 is top (intro) section
1025 # headline of old section - we need to go through this section
1026 # to determine if there are any subsections that now need to
1027 # be erased, as the mother section has been replaced with
1028 # the text of all subsections.
1029 $headline=$secs[$section*2-1];
1030 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1031 $hlevel=$matches[1];
1033 # determine headline level for wikimarkup headings
1034 if(strpos($hlevel,'=')!==false) {
1035 $hlevel=strlen($hlevel);
1038 $secs[$section*2-1]=''; // erase old headline
1041 while(!empty($secs[$count*2-1]) && !$break) {
1043 $subheadline=$secs[$count*2-1];
1045 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1046 $subhlevel=$matches[1];
1047 if(strpos($subhlevel,'=')!==false) {
1048 $subhlevel=strlen($subhlevel);
1050 if($subhlevel > $hlevel) {
1051 // erase old subsections
1052 $secs[$count*2-1]='';
1055 if($subhlevel <= $hlevel) {
1063 $text=join('',$secs);
1064 # reinsert the stuff that we stripped out earlier
1065 $text=$parser->unstrip($text,$striparray);
1066 $text=$parser->unstripNoWiki($text,$striparray);
1074 * Change an existing article. Puts the previous version back into the old table, updates RC
1075 * and all necessary caches, mostly via the deferred update array.
1077 * It is possible to call this function from a command-line script, but note that you should
1078 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1080 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1081 global $wgOut, $wgUser;
1082 global $wgDBtransactions, $wgMwRedir;
1083 global $wgUseSquid, $wgInternalServer;
1085 $fname = 'Article::updateArticle';
1088 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
1089 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
1090 if ( $this->isRedirect( $text ) ) {
1091 # Remove all content but redirect
1092 # This could be done by reconstructing the redirect from a title given by
1093 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1095 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1097 $text = $m[1] . "\n";
1100 else { $redir = 0; }
1102 $text = $this->preSaveTransform( $text );
1103 $dbw =& wfGetDB( DB_MASTER
);
1105 # Update article, but only if changed.
1107 # It's important that we either rollback or complete, otherwise an attacker could
1108 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1109 # could conceivably have the same effect, especially if cur is locked for long periods.
1110 if( $wgDBtransactions ) {
1111 $dbw->query( 'BEGIN', $fname );
1113 $userAbort = ignore_user_abort( true );
1116 $oldtext = $this->getContent( true );
1118 if ( 0 != strcmp( $text, $oldtext ) ) {
1119 $this->mCountAdjustment
= $this->isCountable( $text )
1120 - $this->isCountable( $oldtext );
1121 $now = wfTimestampNow();
1122 $won = wfInvertTimestamp( $now );
1124 # First update the cur row
1125 $dbw->update( 'cur',
1127 'cur_text' => $text,
1128 'cur_comment' => $summary,
1129 'cur_minor_edit' => $me2,
1130 'cur_user' => $wgUser->getID(),
1131 'cur_timestamp' => $dbw->timestamp($now),
1132 'cur_user_text' => $wgUser->getName(),
1133 'cur_is_redirect' => $redir,
1135 'cur_touched' => $dbw->timestamp($now),
1136 'inverse_timestamp' => $won
1137 ), array( /* WHERE */
1138 'cur_id' => $this->getID(),
1139 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1143 if( $dbw->affectedRows() == 0 ) {
1144 /* Belated edit conflict! Run away!! */
1147 # Now insert the previous revision into old
1149 # This overwrites $oldtext if revision compression is on
1150 $flags = Article
::compressRevisionText( $oldtext );
1152 $dbw->insert( 'old',
1154 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1155 'old_namespace' => $this->mTitle
->getNamespace(),
1156 'old_title' => $this->mTitle
->getDBkey(),
1157 'old_text' => $oldtext,
1158 'old_comment' => $this->getComment(),
1159 'old_user' => $this->getUser(),
1160 'old_user_text' => $this->getUserText(),
1161 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1162 'old_minor_edit' => $me1,
1163 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1164 'old_flags' => $flags,
1168 $oldid = $dbw->insertId();
1170 $bot = (int)($wgUser->isBot() ||
$forceBot);
1171 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1172 $oldid, $this->getTimestamp(), $bot );
1173 Article
::onArticleEdit( $this->mTitle
);
1177 if( $wgDBtransactions ) {
1178 $dbw->query( 'COMMIT', $fname );
1180 ignore_user_abort( $userAbort );
1185 if (!$this->mTitle
->userIsWatching()) $this->watch();
1187 if ( $this->mTitle
->userIsWatching() ) {
1191 # standard deferred updates
1192 $this->editUpdates( $text );
1196 # Template namespace
1197 # Purge all articles linking here
1198 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1199 $titles = $this->mTitle
->getLinksTo();
1200 Title
::touchArray( $titles );
1201 if ( $wgUseSquid ) {
1202 foreach ( $titles as $title ) {
1203 $urls[] = $title->getInternalURL();
1209 if ( $wgUseSquid ) {
1210 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1211 $u = new SquidUpdate( $urls );
1215 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1221 * After we've either updated or inserted the article, update
1222 * the link tables and redirect to the new page.
1224 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1225 global $wgOut, $wgUser, $wgLinkCache;
1227 $wgLinkCache = new LinkCache();
1229 $wgLinkCache->forUpdate( true );
1231 # Get old version of link table to allow incremental link updates
1232 $wgLinkCache->preFill( $this->mTitle
);
1233 $wgLinkCache->clear();
1235 # Parse the text and replace links with placeholders
1236 $wgOut = new OutputPage();
1237 $wgOut->addWikiText( $text );
1239 # Look up the links in the DB and add them to the link cache
1240 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1242 if( $this->isRedirect( $text ) )
1246 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1251 * @todo document this function a bit more
1253 function validate () {
1254 global $wgOut, $wgUseValidation;
1255 if( $wgUseValidation ) {
1256 require_once ( 'SpecialValidate.php' ) ;
1257 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1258 $wgOut->setRobotpolicy( 'noindex,follow' );
1259 if( $this->mTitle
->getNamespace() != 0 ) {
1260 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1263 $v = new Validation
;
1264 $v->validate_form( $this->mTitle
->getDBkey() );
1266 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1271 * Mark this particular edit as patrolled
1273 function markpatrolled() {
1274 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1275 $wgOut->setRobotpolicy( 'noindex,follow' );
1277 if ( !$wgUseRCPatrol )
1279 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1282 if ( $wgUser->getID() == 0 )
1284 $wgOut->loginToUse();
1287 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1289 $wgOut->sysopRequired();
1292 $rcid = $wgRequest->getVal( 'rcid' );
1293 if ( !is_null ( $rcid ) )
1295 RecentChange
::markPatrolled( $rcid );
1296 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1297 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1298 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1302 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1308 * Add or remove this page to my watchlist based on value of $add
1310 function watch( $add = true ) {
1311 global $wgUser, $wgOut;
1312 global $wgDeferredUpdateList;
1314 if ( 0 == $wgUser->getID() ) {
1315 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1318 if ( wfReadOnly() ) {
1319 $wgOut->readOnlyPage();
1323 $wgUser->addWatch( $this->mTitle
);
1325 $wgUser->removeWatch( $this->mTitle
);
1327 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1328 $wgOut->setRobotpolicy( 'noindex,follow' );
1330 $sk = $wgUser->getSkin() ;
1331 $link = $this->mTitle
->getPrefixedText();
1334 $text = wfMsg( 'addedwatchtext', $link );
1336 $text = wfMsg( 'removedwatchtext', $link );
1337 $wgOut->addWikiText( $text );
1339 $up = new UserUpdate();
1340 array_push( $wgDeferredUpdateList, $up );
1342 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1346 * Stop watching a page, it act just like a call to watch(false)
1348 function unwatch() {
1349 $this->watch( false );
1355 function protect( $limit = 'sysop' ) {
1356 global $wgUser, $wgOut, $wgRequest;
1358 if ( ! $wgUser->isSysop() ) {
1359 $wgOut->sysopRequired();
1362 if ( wfReadOnly() ) {
1363 $wgOut->readOnlyPage();
1366 $id = $this->mTitle
->getArticleID();
1368 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1372 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1373 $reason = $wgRequest->getText( 'wpReasonProtect' );
1376 $dbw =& wfGetDB( DB_MASTER
);
1377 $dbw->update( 'cur',
1379 'cur_touched' => $dbw->timestamp(),
1380 'cur_restrictions' => (string)$limit
1381 ), array( /* WHERE */
1383 ), 'Article::protect'
1386 $log = new LogPage( 'protect' );
1387 if ( $limit === '' ) {
1388 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1390 $log->addEntry( 'protect', $this->mTitle
, $reason );
1392 $wgOut->redirect( $this->mTitle
->getFullURL() );
1395 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1396 return $this->confirmProtect( '', $reason, $limit );
1401 * Output protection confirmation dialog
1403 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1406 wfDebug( "Article::confirmProtect\n" );
1408 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1409 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1414 if ( $limit === '' ) {
1415 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1416 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1417 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1418 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1419 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1420 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1422 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1423 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1424 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1425 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1426 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1427 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1430 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1433 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1437 <label for='wpReasonProtect'>{$protcom}:</label>
1440 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1448 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1451 <label for='wpConfirmProtect'>{$check}</label>
1457 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1463 $wgOut->returnToMain( false );
1467 * Unprotect the pages
1469 function unprotect() {
1470 return $this->protect( '' );
1474 * UI entry point for page deletion
1477 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1478 $fname = 'Article::delete';
1479 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1480 $reason = $wgRequest->getText( 'wpReason' );
1482 # This code desperately needs to be totally rewritten
1485 if ( ( ! $wgUser->isSysop() ) ) {
1486 $wgOut->sysopRequired();
1489 if ( wfReadOnly() ) {
1490 $wgOut->readOnlyPage();
1494 # Better double-check that it hasn't been deleted yet!
1495 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1496 if ( ( '' == trim( $this->mTitle
->getText() ) )
1497 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1498 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1503 $this->doDelete( $reason );
1507 # determine whether this page has earlier revisions
1508 # and insert a warning if it does
1509 # we select the text because it might be useful below
1510 $dbr =& $this->getDB();
1511 $ns = $this->mTitle
->getNamespace();
1512 $title = $this->mTitle
->getDBkey();
1513 $old = $dbr->selectRow( 'old',
1514 array( 'old_text', 'old_flags' ),
1516 'old_namespace' => $ns,
1517 'old_title' => $title,
1518 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1521 if( $old !== false && !$confirm ) {
1522 $skin=$wgUser->getSkin();
1523 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1524 $wgOut->addHTML( $skin->historyLink() .'</b>');
1528 $s = $dbr->selectRow( 'cur',
1529 array( 'cur_text' ),
1531 'cur_namespace' => $ns,
1532 'cur_title' => $title,
1533 ), $fname, $this->getSelectOptions()
1536 if( $s !== false ) {
1537 # if this is a mini-text, we can paste part of it into the deletion reason
1539 #if this is empty, an earlier revision may contain "useful" text
1541 if($s->cur_text
!= '') {
1545 $text = Article
::getRevisionText( $old );
1551 $length=strlen($text);
1553 # this should not happen, since it is not possible to store an empty, new
1554 # page. Let's insert a standard text in case it does, though
1555 if($length == 0 && $reason === '') {
1556 $reason = wfMsg('exblank');
1559 if($length < 500 && $reason === '') {
1561 # comment field=255, let's grep the first 150 to have some user
1563 $text=substr($text,0,150);
1564 # let's strip out newlines and HTML tags
1565 $text=preg_replace('/\"/',"'",$text);
1566 $text=preg_replace('/\</','<',$text);
1567 $text=preg_replace('/\>/','>',$text);
1568 $text=preg_replace("/[\n\r]/",'',$text);
1570 $reason=wfMsg('excontent'). " '".$text;
1572 $reason=wfMsg('exbeforeblank') . " '".$text;
1574 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1579 return $this->confirmDelete( '', $reason );
1583 * Output deletion confirmation dialog
1585 function confirmDelete( $par, $reason ) {
1588 wfDebug( "Article::confirmDelete\n" );
1590 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1591 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1592 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1593 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1595 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1597 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1598 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1599 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1602 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1606 <label for='wpReason'>{$delcom}:</label>
1609 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1617 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1620 <label for='wpConfirm'>{$check}</label>
1626 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1632 $wgOut->returnToMain( false );
1637 * Perform a deletion and output success or failure messages
1639 function doDelete( $reason ) {
1640 global $wgOut, $wgUser, $wgContLang;
1641 $fname = 'Article::doDelete';
1642 wfDebug( $fname."\n" );
1644 if ( $this->doDeleteArticle( $reason ) ) {
1645 $deleted = $this->mTitle
->getPrefixedText();
1647 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1648 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1650 $sk = $wgUser->getSkin();
1651 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1652 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1654 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1656 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1657 $wgOut->returnToMain( false );
1659 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1664 * Back-end article deletion
1665 * Deletes the article with database consistency, writes logs, purges caches
1668 function doDeleteArticle( $reason ) {
1670 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1672 $fname = 'Article::doDeleteArticle';
1673 wfDebug( $fname."\n" );
1675 $dbw =& wfGetDB( DB_MASTER
);
1676 $ns = $this->mTitle
->getNamespace();
1677 $t = $this->mTitle
->getDBkey();
1678 $id = $this->mTitle
->getArticleID();
1680 if ( $t == '' ||
$id == 0 ) {
1684 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1685 array_push( $wgDeferredUpdateList, $u );
1687 $linksTo = $this->mTitle
->getLinksTo();
1690 if ( $wgUseSquid ) {
1692 $this->mTitle
->getInternalURL(),
1693 $this->mTitle
->getInternalURL( 'history' )
1695 foreach ( $linksTo as $linkTo ) {
1696 $urls[] = $linkTo->getInternalURL();
1699 $u = new SquidUpdate( $urls );
1700 array_push( $wgDeferredUpdateList, $u );
1704 # Client and file cache invalidation
1705 Title
::touchArray( $linksTo );
1707 # Move article and history to the "archive" table
1708 $archiveTable = $dbw->tableName( 'archive' );
1709 $oldTable = $dbw->tableName( 'old' );
1710 $curTable = $dbw->tableName( 'cur' );
1711 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1712 $linksTable = $dbw->tableName( 'links' );
1713 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1715 $dbw->insertSelect( 'archive', 'cur',
1717 'ar_namespace' => 'cur_namespace',
1718 'ar_title' => 'cur_title',
1719 'ar_text' => 'cur_text',
1720 'ar_comment' => 'cur_comment',
1721 'ar_user' => 'cur_user',
1722 'ar_user_text' => 'cur_user_text',
1723 'ar_timestamp' => 'cur_timestamp',
1724 'ar_minor_edit' => 'cur_minor_edit',
1727 'cur_namespace' => $ns,
1732 $dbw->insertSelect( 'archive', 'old',
1734 'ar_namespace' => 'old_namespace',
1735 'ar_title' => 'old_title',
1736 'ar_text' => 'old_text',
1737 'ar_comment' => 'old_comment',
1738 'ar_user' => 'old_user',
1739 'ar_user_text' => 'old_user_text',
1740 'ar_timestamp' => 'old_timestamp',
1741 'ar_minor_edit' => 'old_minor_edit',
1742 'ar_flags' => 'old_flags'
1744 'old_namespace' => $ns,
1749 # Now that it's safely backed up, delete it
1751 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1752 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1753 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1755 # Finally, clean up the link tables
1756 $t = $this->mTitle
->getPrefixedDBkey();
1758 Article
::onArticleDelete( $this->mTitle
);
1760 # Insert broken links
1761 $brokenLinks = array();
1762 foreach ( $linksTo as $titleObj ) {
1763 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1764 $linkID = $titleObj->getArticleID();
1765 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1767 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1770 $dbw->delete( 'links', array( 'l_to' => $id ) );
1771 $dbw->delete( 'links', array( 'l_from' => $id ) );
1772 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1773 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1774 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1777 $log = new LogPage( 'delete' );
1778 $log->addEntry( 'delete', $this->mTitle
, $reason );
1780 # Clear the cached article id so the interface doesn't act like we exist
1781 $this->mTitle
->resetArticleID( 0 );
1782 $this->mTitle
->mArticleID
= 0;
1787 * Revert a modification
1789 function rollback() {
1790 global $wgUser, $wgOut, $wgRequest;
1791 $fname = 'Article::rollback';
1793 if ( ! $wgUser->isSysop() ) {
1794 $wgOut->sysopRequired();
1797 if ( wfReadOnly() ) {
1798 $wgOut->readOnlyPage( $this->getContent( true ) );
1801 $dbw =& wfGetDB( DB_MASTER
);
1803 # Enhanced rollback, marks edits rc_bot=1
1804 $bot = $wgRequest->getBool( 'bot' );
1806 # Replace all this user's current edits with the next one down
1807 $tt = $this->mTitle
->getDBKey();
1808 $n = $this->mTitle
->getNamespace();
1810 # Get the last editor, lock table exclusively
1811 $s = $dbw->selectRow( 'cur',
1812 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1813 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1814 $fname, 'FOR UPDATE'
1816 if( $s === false ) {
1818 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1821 $ut = $dbw->strencode( $s->cur_user_text
);
1822 $uid = $s->cur_user
;
1825 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1826 if( $from != $s->cur_user_text
) {
1827 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1828 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1829 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1830 htmlspecialchars( $from ),
1831 htmlspecialchars( $s->cur_user_text
) ) );
1832 if($s->cur_comment
!= '') {
1834 wfMsg('editcomment',
1835 htmlspecialchars( $s->cur_comment
) ) );
1840 # Get the last edit not by this guy
1841 $s = $dbw->selectRow( 'old',
1842 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1844 'old_namespace' => $n,
1846 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1847 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1849 if( $s === false ) {
1851 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1852 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1857 # Mark all reverted edits as bot
1858 $dbw->update( 'recentchanges',
1861 ), array( /* WHERE */
1863 "rc_timestamp > '{$s->old_timestamp}'",
1869 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1870 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1871 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1872 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1873 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1874 Article
::onArticleEdit( $this->mTitle
);
1875 $wgOut->returnToMain( false );
1880 * Do standard deferred updates after page view
1883 function viewUpdates() {
1884 global $wgDeferredUpdateList;
1885 if ( 0 != $this->getID() ) {
1886 global $wgDisableCounters;
1887 if( !$wgDisableCounters ) {
1888 Article
::incViewCount( $this->getID() );
1889 $u = new SiteStatsUpdate( 1, 0, 0 );
1890 array_push( $wgDeferredUpdateList, $u );
1893 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1894 $this->mTitle
->getDBkey() );
1895 array_push( $wgDeferredUpdateList, $u );
1899 * Do standard deferred updates after page edit.
1900 * Every 1000th edit, prune the recent changes table.
1902 * @param string $text
1904 function editUpdates( $text ) {
1905 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1906 global $wgMessageCache;
1909 if ( 0 == mt_rand( 0, 999 ) ) {
1910 $dbw =& wfGetDB( DB_MASTER
);
1911 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1912 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1913 $dbw->query( $sql );
1915 $id = $this->getID();
1916 $title = $this->mTitle
->getPrefixedDBkey();
1917 $shortTitle = $this->mTitle
->getDBkey();
1919 $adj = $this->mCountAdjustment
;
1922 $u = new LinksUpdate( $id, $title );
1923 array_push( $wgDeferredUpdateList, $u );
1924 $u = new SiteStatsUpdate( 0, 1, $adj );
1925 array_push( $wgDeferredUpdateList, $u );
1926 $u = new SearchUpdate( $id, $title, $text );
1927 array_push( $wgDeferredUpdateList, $u );
1929 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1930 array_push( $wgDeferredUpdateList, $u );
1932 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1933 $wgMessageCache->replace( $shortTitle, $text );
1939 * @todo document this function
1941 * @param string $oldid Revision ID of this article revision
1943 function setOldSubtitle( $oldid=0 ) {
1944 global $wgLang, $wgOut, $wgUser;
1946 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1947 $sk = $wgUser->getSkin();
1948 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1949 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1950 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1951 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1952 $wgOut->setSubtitle( $r );
1956 * This function is called right before saving the wikitext,
1957 * so we can do things like signatures and links-in-context.
1959 * @param string $text
1961 function preSaveTransform( $text ) {
1962 global $wgParser, $wgUser;
1963 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1966 /* Caching functions */
1969 * checkLastModified returns true if it has taken care of all
1970 * output to the client that is necessary for this request.
1971 * (that is, it has sent a cached version of the page)
1973 function tryFileCache() {
1974 static $called = false;
1976 wfDebug( " tryFileCache() -- called twice!?\n" );
1980 if($this->isFileCacheable()) {
1981 $touched = $this->mTouched
;
1982 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1983 # Expire the main page quicker
1984 $expire = wfUnix2Timestamp( time() - 3600 );
1985 $touched = max( $expire, $touched );
1987 $cache = new CacheManager( $this->mTitle
);
1988 if($cache->isFileCacheGood( $touched )) {
1990 wfDebug( " tryFileCache() - about to load\n" );
1991 $cache->loadFromFileCache();
1994 wfDebug( " tryFileCache() - starting buffer\n" );
1995 ob_start( array(&$cache, 'saveToFileCache' ) );
1998 wfDebug( " tryFileCache() - not cacheable\n" );
2003 * Check if the page can be cached
2006 function isFileCacheable() {
2007 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2008 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2010 return $wgUseFileCache
2011 and (!$wgShowIPinHeader)
2012 and ($this->getID() != 0)
2013 and ($wgUser->getId() == 0)
2014 and (!$wgUser->getNewtalk())
2015 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2016 and (empty( $action ) ||
$action == 'view')
2017 and (!isset($oldid))
2019 and (!isset($redirect))
2020 and (!isset($printable))
2021 and (!$this->mRedirectedFrom
);
2025 * Loads cur_touched and returns a value indicating if it should be used
2028 function checkTouched() {
2029 $fname = 'Article::checkTouched';
2030 $id = $this->getID();
2031 $dbr =& $this->getDB();
2032 $s = $dbr->selectRow( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
2033 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
2034 if( $s !== false ) {
2035 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
2036 return !$s->cur_is_redirect
;
2043 * Edit an article without doing all that other stuff
2045 * @param string $text text submitted
2046 * @param string $comment comment submitted
2047 * @param integer $minor whereas it's a minor modification
2049 function quickEdit( $text, $comment = '', $minor = 0 ) {
2051 $fname = 'Article::quickEdit';
2052 wfProfileIn( $fname );
2054 $dbw =& wfGetDB( DB_MASTER
);
2055 $ns = $this->mTitle
->getNamespace();
2056 $dbkey = $this->mTitle
->getDBkey();
2057 $encDbKey = $dbw->strencode( $dbkey );
2058 $timestamp = wfTimestampNow();
2061 $dbw->insertSelect( 'old', 'cur',
2063 'old_namespace' => 'cur_namespace',
2064 'old_title' => 'cur_title',
2065 'old_text' => 'cur_text',
2066 'old_comment' => 'cur_comment',
2067 'old_user' => 'cur_user',
2068 'old_user_text' => 'cur_user_text',
2069 'old_timestamp' => 'cur_timestamp',
2070 'inverse_timestamp' => '99999999999999-cur_timestamp',
2072 'cur_namespace' => $ns,
2073 'cur_title' => $dbkey,
2077 # Use the affected row count to determine if the article is new
2078 $numRows = $dbw->affectedRows();
2080 # Make an array of fields to be inserted
2082 'cur_text' => $text,
2083 'cur_timestamp' => $timestamp,
2084 'cur_user' => $wgUser->getID(),
2085 'cur_user_text' => $wgUser->getName(),
2086 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2087 'cur_comment' => $comment,
2088 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2089 'cur_minor_edit' => intval($minor),
2090 'cur_touched' => $dbw->timestamp($timestamp),
2095 $fields['cur_is_new'] = 0;
2096 $dbw->update( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2098 # Insert new article
2099 $fields['cur_is_new'] = 1;
2100 $fields['cur_namespace'] = $ns;
2101 $fields['cur_title'] = $dbkey;
2102 $fields['cur_random'] = $rand = wfRandom();
2103 $dbw->insert( 'cur', $fields, $fname );
2105 wfProfileOut( $fname );
2109 * Used to increment the view counter
2112 * @param integer $id article id
2114 function incViewCount( $id ) {
2115 $id = intval( $id );
2116 global $wgHitcounterUpdateFreq;
2118 $dbw =& wfGetDB( DB_MASTER
);
2119 $curTable = $dbw->tableName( 'cur' );
2120 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2121 $acchitsTable = $dbw->tableName( 'acchits' );
2123 if( $wgHitcounterUpdateFreq <= 1 ){ //
2124 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2128 # Not important enough to warrant an error page in case of failure
2129 $oldignore = $dbw->ignoreErrors( true );
2131 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2133 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2134 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2135 # Most of the time (or on SQL errors), skip row count check
2136 $dbw->ignoreErrors( $oldignore );
2140 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2141 $row = $dbw->fetchObject( $res );
2142 $rown = intval( $row->n
);
2143 if( $rown >= $wgHitcounterUpdateFreq ){
2144 wfProfileIn( 'Article::incViewCount-collect' );
2145 $old_user_abort = ignore_user_abort( true );
2147 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2148 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2149 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2151 $dbw->query("DELETE FROM $hitcounterTable");
2152 $dbw->query('UNLOCK TABLES');
2153 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2154 'WHERE cur_id = hc_id');
2155 $dbw->query("DROP TABLE $acchitsTable");
2157 ignore_user_abort( $old_user_abort );
2158 wfProfileOut( 'Article::incViewCount-collect' );
2160 $dbw->ignoreErrors( $oldignore );
2164 * The onArticle*() functions are supposed to be a kind of hooks
2165 * which should be called whenever any of the specified actions
2168 * This is a good place to put code to clear caches, for instance.
2170 * This is called on page move and undelete, as well as edit
2172 * @param $title_obj a title object
2175 function onArticleCreate($title_obj) {
2176 global $wgUseSquid, $wgDeferredUpdateList;
2178 $titles = $title_obj->getBrokenLinksTo();
2181 if ( $wgUseSquid ) {
2182 $urls = $title_obj->getSquidURLs();
2183 foreach ( $titles as $linkTitle ) {
2184 $urls[] = $linkTitle->getInternalURL();
2186 $u = new SquidUpdate( $urls );
2187 array_push( $wgDeferredUpdateList, $u );
2190 # Clear persistent link cache
2191 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2194 function onArticleDelete($title_obj) {
2195 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2197 function onArticleEdit($title_obj) {
2198 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2203 * Info about this page
2206 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2207 $fname = 'Article::info';
2209 if ( !$wgAllowPageInfo ) {
2210 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2214 $dbr =& $this->getDB();
2216 $basenamespace = $wgTitle->getNamespace() & (~
1);
2217 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2218 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2219 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2220 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2221 $wgOut->setPagetitle( $fullTitle );
2222 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2224 # first, see if the page exists at all.
2225 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2227 $wgOut->addHTML( wfMsg('noarticletext') );
2229 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2230 $this->getSelectOptions() );
2231 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2232 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2233 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2235 # to find number of distinct authors, we need to do some
2236 # funny stuff because of the cur/old table split:
2237 # - first, find the name of the 'cur' author
2238 # - then, find the number of *other* authors in 'old'
2241 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2242 $this->getSelectOptions() );
2244 # find number of 'old' authors excluding 'cur' author
2245 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2246 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2247 $this->getSelectOptions() ) +
1;
2249 # now for the Talk page ...
2250 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2251 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2254 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2258 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2259 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2261 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2265 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2266 $this->getSelectOptions() );
2267 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2268 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2269 $fname, $this->getSelectOptions() );
2271 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );