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->getArray( '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->getArray( '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 );
800 wfProfileOut( $fname );
802 # Run view updates for current revision only
803 $this->viewUpdates();
807 if ( empty( $oldid ) && $this->checkTouched() ) {
808 if( $wgOut->checkLastModified( $this->mTouched
) ){
810 } else if ( $this->tryFileCache() ) {
811 # tell wgOut that output is taken care of
813 $this->viewUpdates();
817 # Should the parser cache be used?
818 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
826 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
830 if ( !$outputDone ) {
831 $text = $this->getContent( false ); # May change mTitle by following a redirect
833 # Another whitelist check in case oldid or redirects are altering the title
834 if ( !$this->mTitle
->userCanRead() ) {
835 $wgOut->loginToUse();
841 # We're looking at an old revision
843 if ( !empty( $oldid ) ) {
844 $this->setOldSubtitle( $oldid );
845 $wgOut->setRobotpolicy( 'noindex,follow' );
847 if ( '' != $this->mRedirectedFrom
) {
848 $sk = $wgUser->getSkin();
849 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
851 $s = wfMsg( 'redirectedfrom', $redir );
852 $wgOut->setSubtitle( $s );
854 # Can't cache redirects
858 # wrap user css and user js in pre and don't parse
859 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
861 $this->mTitle
->getNamespace() == NS_USER
&&
862 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
864 $wgOut->addWikiText( wfMsg('clearyourcache'));
865 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
866 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
868 $imageUrl = $wgStylePath.'/common/images/redirect.png';
869 $targetUrl = $rt->escapeLocalURL();
870 $titleText = htmlspecialchars( $rt->getPrefixedText() );
871 $link = $sk->makeLinkObj( $rt );
872 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'">' .
873 '<span class="redirectText">'.$link.'</span>' );
874 } else if ( $pcache ) {
875 # Display content and save to parser cache
876 $wgOut->addPrimaryWikiText( $text, $this );
878 # Display content, don't attempt to save to parser cache
879 $wgOut->addWikiText( $text );
882 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
883 # If we have been passed an &rcid= parameter, we want to give the user a
884 # chance to mark this new article as patrolled.
885 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
886 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
888 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
889 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
890 'action=markpatrolled&rcid='.$rcid )
894 # Put link titles into the link cache
895 $wgOut->transformBuffer();
897 # Add link titles as META keywords
898 $wgOut->addMetaTags() ;
900 $this->viewUpdates();
901 wfProfileOut( $fname );
905 * Theoretically we could defer these whole insert and update
906 * functions for after display, but that's taking a big leap
907 * of faith, and we want to be able to report database
908 * errors at some point.
911 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
912 global $wgOut, $wgUser;
913 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
915 $fname = 'Article::insertNewArticle';
917 $this->mCountAdjustment
= $this->isCountable( $text );
919 $ns = $this->mTitle
->getNamespace();
920 $ttl = $this->mTitle
->getDBkey();
921 $text = $this->preSaveTransform( $text );
922 if ( $this->isRedirect( $text ) ) { $redir = 1; }
925 $now = wfTimestampNow();
926 $won = wfInvertTimestamp( $now );
929 $dbw =& wfGetDB( DB_MASTER
);
931 $cur_id = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
933 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
935 $dbw->insertArray( 'cur', array(
937 'cur_namespace' => $ns,
940 'cur_comment' => $summary,
941 'cur_user' => $wgUser->getID(),
942 'cur_timestamp' => $dbw->timestamp($now),
943 'cur_minor_edit' => $isminor,
945 'cur_restrictions' => '',
946 'cur_user_text' => $wgUser->getName(),
947 'cur_is_redirect' => $redir,
949 'cur_random' => $rand,
950 'cur_touched' => $dbw->timestamp($now),
951 'inverse_timestamp' => $won,
954 $newid = $dbw->insertId();
955 $this->mTitle
->resetArticleID( $newid );
957 Article
::onArticleCreate( $this->mTitle
);
958 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
961 if(!$this->mTitle
->userIsWatching()) $this->watch();
963 if ( $this->mTitle
->userIsWatching() ) {
968 # The talk page isn't in the regular link tables, so we need to update manually:
969 $talkns = $ns ^
1; # talk -> normal; normal -> talk
970 $dbw->updateArray( 'cur', array('cur_touched' => $dbw->timestamp($now) ),
971 array( 'cur_namespace' => $talkns, 'cur_title' => $ttl ), $fname );
973 # standard deferred updates
974 $this->editUpdates( $text );
976 $this->showArticle( $text, wfMsg( 'newarticle' ) );
981 * Side effects: loads last edit if $edittime is NULL
983 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
984 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
985 if(is_null($edittime)) {
986 $this->loadLastEdit();
987 $oldtext = $this->getContent( true );
989 $dbw =& wfGetDB( DB_MASTER
);
990 $ns = $this->mTitle
->getNamespace();
991 $title = $this->mTitle
->getDBkey();
992 $obj = $dbw->getArray( 'old',
993 array( 'old_text','old_flags'),
994 array( 'old_namespace' => $ns, 'old_title' => $title,
995 'old_timestamp' => $dbw->timestamp($edittime)),
997 $oldtext = Article
::getRevisionText( $obj );
999 if ($section != '') {
1000 if($section=='new') {
1001 if($summary) $subject="== {$summary} ==\n\n";
1002 $text=$oldtext."\n\n".$subject.$text;
1005 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1006 # comments to be stripped as well)
1007 $striparray=array();
1008 $parser=new Parser();
1009 $parser->mOutputType
=OT_WIKI
;
1010 $oldtext=$parser->strip($oldtext, $striparray, true);
1012 # now that we can be sure that no pseudo-sections are in the source,
1014 # Unfortunately we can't simply do a preg_replace because that might
1015 # replace the wrong section, so we have to use the section counter instead
1016 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1017 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1018 $secs[$section*2]=$text."\n\n"; // replace with edited
1020 # section 0 is top (intro) section
1023 # headline of old section - we need to go through this section
1024 # to determine if there are any subsections that now need to
1025 # be erased, as the mother section has been replaced with
1026 # the text of all subsections.
1027 $headline=$secs[$section*2-1];
1028 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1029 $hlevel=$matches[1];
1031 # determine headline level for wikimarkup headings
1032 if(strpos($hlevel,'=')!==false) {
1033 $hlevel=strlen($hlevel);
1036 $secs[$section*2-1]=''; // erase old headline
1039 while(!empty($secs[$count*2-1]) && !$break) {
1041 $subheadline=$secs[$count*2-1];
1043 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1044 $subhlevel=$matches[1];
1045 if(strpos($subhlevel,'=')!==false) {
1046 $subhlevel=strlen($subhlevel);
1048 if($subhlevel > $hlevel) {
1049 // erase old subsections
1050 $secs[$count*2-1]='';
1053 if($subhlevel <= $hlevel) {
1061 $text=join('',$secs);
1062 # reinsert the stuff that we stripped out earlier
1063 $text=$parser->unstrip($text,$striparray);
1064 $text=$parser->unstripNoWiki($text,$striparray);
1072 * Change an existing article. Puts the previous version back into the old table, updates RC
1073 * and all necessary caches, mostly via the deferred update array.
1075 * It is possible to call this function from a command-line script, but note that you should
1076 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1078 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1079 global $wgOut, $wgUser;
1080 global $wgDBtransactions, $wgMwRedir;
1081 global $wgUseSquid, $wgInternalServer;
1083 $fname = 'Article::updateArticle';
1086 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
1087 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
1088 if ( $this->isRedirect( $text ) ) {
1089 # Remove all content but redirect
1090 # This could be done by reconstructing the redirect from a title given by
1091 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1093 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1095 $text = $m[1] . "\n";
1098 else { $redir = 0; }
1100 $text = $this->preSaveTransform( $text );
1101 $dbw =& wfGetDB( DB_MASTER
);
1103 # Update article, but only if changed.
1105 # It's important that we either rollback or complete, otherwise an attacker could
1106 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1107 # could conceivably have the same effect, especially if cur is locked for long periods.
1108 if( $wgDBtransactions ) {
1109 $dbw->query( 'BEGIN', $fname );
1111 $userAbort = ignore_user_abort( true );
1114 $oldtext = $this->getContent( true );
1116 if ( 0 != strcmp( $text, $oldtext ) ) {
1117 $this->mCountAdjustment
= $this->isCountable( $text )
1118 - $this->isCountable( $oldtext );
1119 $now = wfTimestampNow();
1120 $won = wfInvertTimestamp( $now );
1122 # First update the cur row
1123 $dbw->updateArray( 'cur',
1125 'cur_text' => $text,
1126 'cur_comment' => $summary,
1127 'cur_minor_edit' => $me2,
1128 'cur_user' => $wgUser->getID(),
1129 'cur_timestamp' => $dbw->timestamp($now),
1130 'cur_user_text' => $wgUser->getName(),
1131 'cur_is_redirect' => $redir,
1133 'cur_touched' => $dbw->timestamp($now),
1134 'inverse_timestamp' => $won
1135 ), array( /* WHERE */
1136 'cur_id' => $this->getID(),
1137 'cur_timestamp' => $dbw->timestamp($this->getTimestamp())
1141 if( $dbw->affectedRows() == 0 ) {
1142 /* Belated edit conflict! Run away!! */
1145 # Now insert the previous revision into old
1147 # This overwrites $oldtext if revision compression is on
1148 $flags = Article
::compressRevisionText( $oldtext );
1150 $dbw->insertArray( 'old',
1152 'old_id' => $dbw->nextSequenceValue( 'old_old_id_seq' ),
1153 'old_namespace' => $this->mTitle
->getNamespace(),
1154 'old_title' => $this->mTitle
->getDBkey(),
1155 'old_text' => $oldtext,
1156 'old_comment' => $this->getComment(),
1157 'old_user' => $this->getUser(),
1158 'old_user_text' => $this->getUserText(),
1159 'old_timestamp' => $dbw->timestamp($this->getTimestamp()),
1160 'old_minor_edit' => $me1,
1161 'inverse_timestamp' => wfInvertTimestamp( $this->getTimestamp() ),
1162 'old_flags' => $flags,
1166 $oldid = $dbw->insertId();
1168 $bot = (int)($wgUser->isBot() ||
$forceBot);
1169 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1170 $oldid, $this->getTimestamp(), $bot );
1171 Article
::onArticleEdit( $this->mTitle
);
1175 if( $wgDBtransactions ) {
1176 $dbw->query( 'COMMIT', $fname );
1178 ignore_user_abort( $userAbort );
1183 if (!$this->mTitle
->userIsWatching()) $this->watch();
1185 if ( $this->mTitle
->userIsWatching() ) {
1189 # standard deferred updates
1190 $this->editUpdates( $text );
1194 # Template namespace
1195 # Purge all articles linking here
1196 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1197 $titles = $this->mTitle
->getLinksTo();
1198 Title
::touchArray( $titles );
1199 if ( $wgUseSquid ) {
1200 foreach ( $titles as $title ) {
1201 $urls[] = $title->getInternalURL();
1207 if ( $wgUseSquid ) {
1208 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1209 $u = new SquidUpdate( $urls );
1213 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1219 * After we've either updated or inserted the article, update
1220 * the link tables and redirect to the new page.
1222 function showArticle( $text, $subtitle , $sectionanchor = '' ) {
1223 global $wgOut, $wgUser, $wgLinkCache;
1225 $wgLinkCache = new LinkCache();
1227 $wgLinkCache->forUpdate( true );
1229 # Get old version of link table to allow incremental link updates
1230 $wgLinkCache->preFill( $this->mTitle
);
1231 $wgLinkCache->clear();
1233 # Parse the text and replace links with placeholders
1234 $wgOut = new OutputPage();
1235 $wgOut->addWikiText( $text );
1237 # Look up the links in the DB and add them to the link cache
1238 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1240 if( $this->isRedirect( $text ) )
1244 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1249 * @todo document this function a bit more
1251 function validate () {
1252 global $wgOut, $wgUseValidation;
1253 if( $wgUseValidation ) {
1254 require_once ( 'SpecialValidate.php' ) ;
1255 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1256 $wgOut->setRobotpolicy( 'noindex,follow' );
1257 if( $this->mTitle
->getNamespace() != 0 ) {
1258 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1261 $v = new Validation
;
1262 $v->validate_form( $this->mTitle
->getDBkey() );
1264 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1269 * Mark this particular edit as patrolled
1271 function markpatrolled() {
1272 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1273 $wgOut->setRobotpolicy( 'noindex,follow' );
1275 if ( !$wgUseRCPatrol )
1277 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1280 if ( $wgUser->getID() == 0 )
1282 $wgOut->loginToUse();
1285 if ( $wgOnlySysopsCanPatrol && !$wgUser->isSysop() )
1287 $wgOut->sysopRequired();
1290 $rcid = $wgRequest->getVal( 'rcid' );
1291 if ( !is_null ( $rcid ) )
1293 RecentChange
::markPatrolled( $rcid );
1294 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1295 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1296 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1300 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1306 * Add or remove this page to my watchlist based on value of $add
1308 function watch( $add = true ) {
1309 global $wgUser, $wgOut;
1310 global $wgDeferredUpdateList;
1312 if ( 0 == $wgUser->getID() ) {
1313 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1316 if ( wfReadOnly() ) {
1317 $wgOut->readOnlyPage();
1321 $wgUser->addWatch( $this->mTitle
);
1323 $wgUser->removeWatch( $this->mTitle
);
1325 $wgOut->setPagetitle( wfMsg( $add ?
'addedwatch' : 'removedwatch' ) );
1326 $wgOut->setRobotpolicy( 'noindex,follow' );
1328 $sk = $wgUser->getSkin() ;
1329 $link = $this->mTitle
->getPrefixedText();
1332 $text = wfMsg( 'addedwatchtext', $link );
1334 $text = wfMsg( 'removedwatchtext', $link );
1335 $wgOut->addWikiText( $text );
1337 $up = new UserUpdate();
1338 array_push( $wgDeferredUpdateList, $up );
1340 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1344 * Stop watching a page, it act just like a call to watch(false)
1346 function unwatch() {
1347 $this->watch( false );
1353 function protect( $limit = 'sysop' ) {
1354 global $wgUser, $wgOut, $wgRequest;
1356 if ( ! $wgUser->isSysop() ) {
1357 $wgOut->sysopRequired();
1360 if ( wfReadOnly() ) {
1361 $wgOut->readOnlyPage();
1364 $id = $this->mTitle
->getArticleID();
1366 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1370 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1371 $reason = $wgRequest->getText( 'wpReasonProtect' );
1374 $dbw =& wfGetDB( DB_MASTER
);
1375 $dbw->updateArray( 'cur',
1377 'cur_touched' => $dbw->timestamp(),
1378 'cur_restrictions' => (string)$limit
1379 ), array( /* WHERE */
1381 ), 'Article::protect'
1384 $log = new LogPage( 'protect' );
1385 if ( $limit === '' ) {
1386 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1388 $log->addEntry( 'protect', $this->mTitle
, $reason );
1390 $wgOut->redirect( $this->mTitle
->getFullURL() );
1393 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1394 return $this->confirmProtect( '', $reason, $limit );
1399 * Output protection confirmation dialog
1401 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1404 wfDebug( "Article::confirmProtect\n" );
1406 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1407 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1412 if ( $limit === '' ) {
1413 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1414 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1415 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1416 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1417 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1418 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1420 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1421 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1422 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1423 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1424 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1425 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1428 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1431 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1435 <label for='wpReasonProtect'>{$protcom}:</label>
1438 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1446 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1449 <label for='wpConfirmProtect'>{$check}</label>
1455 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1461 $wgOut->returnToMain( false );
1465 * Unprotect the pages
1467 function unprotect() {
1468 return $this->protect( '' );
1472 * UI entry point for page deletion
1475 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1476 $fname = 'Article::delete';
1477 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1478 $reason = $wgRequest->getText( 'wpReason' );
1480 # This code desperately needs to be totally rewritten
1483 if ( ( ! $wgUser->isSysop() ) ) {
1484 $wgOut->sysopRequired();
1487 if ( wfReadOnly() ) {
1488 $wgOut->readOnlyPage();
1492 # Better double-check that it hasn't been deleted yet!
1493 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1494 if ( ( '' == trim( $this->mTitle
->getText() ) )
1495 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1496 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1501 $this->doDelete( $reason );
1505 # determine whether this page has earlier revisions
1506 # and insert a warning if it does
1507 # we select the text because it might be useful below
1508 $dbr =& $this->getDB();
1509 $ns = $this->mTitle
->getNamespace();
1510 $title = $this->mTitle
->getDBkey();
1511 $old = $dbr->getArray( 'old',
1512 array( 'old_text', 'old_flags' ),
1514 'old_namespace' => $ns,
1515 'old_title' => $title,
1516 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1519 if( $old !== false && !$confirm ) {
1520 $skin=$wgUser->getSkin();
1521 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1522 $wgOut->addHTML( $skin->historyLink() .'</b>');
1526 $s = $dbr->getArray( 'cur',
1527 array( 'cur_text' ),
1529 'cur_namespace' => $ns,
1530 'cur_title' => $title,
1531 ), $fname, $this->getSelectOptions()
1534 if( $s !== false ) {
1535 # if this is a mini-text, we can paste part of it into the deletion reason
1537 #if this is empty, an earlier revision may contain "useful" text
1539 if($s->cur_text
!= '') {
1543 $text = Article
::getRevisionText( $old );
1549 $length=strlen($text);
1551 # this should not happen, since it is not possible to store an empty, new
1552 # page. Let's insert a standard text in case it does, though
1553 if($length == 0 && $reason === '') {
1554 $reason = wfMsg('exblank');
1557 if($length < 500 && $reason === '') {
1559 # comment field=255, let's grep the first 150 to have some user
1561 $text=substr($text,0,150);
1562 # let's strip out newlines and HTML tags
1563 $text=preg_replace('/\"/',"'",$text);
1564 $text=preg_replace('/\</','<',$text);
1565 $text=preg_replace('/\>/','>',$text);
1566 $text=preg_replace("/[\n\r]/",'',$text);
1568 $reason=wfMsg('excontent'). " '".$text;
1570 $reason=wfMsg('exbeforeblank') . " '".$text;
1572 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1577 return $this->confirmDelete( '', $reason );
1581 * Output deletion confirmation dialog
1583 function confirmDelete( $par, $reason ) {
1586 wfDebug( "Article::confirmDelete\n" );
1588 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1589 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1590 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1591 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1593 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1595 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1596 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1597 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1600 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1604 <label for='wpReason'>{$delcom}:</label>
1607 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1615 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1618 <label for='wpConfirm'>{$check}</label>
1624 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1630 $wgOut->returnToMain( false );
1635 * Perform a deletion and output success or failure messages
1637 function doDelete( $reason ) {
1638 global $wgOut, $wgUser, $wgContLang;
1639 $fname = 'Article::doDelete';
1640 wfDebug( $fname."\n" );
1642 if ( $this->doDeleteArticle( $reason ) ) {
1643 $deleted = $this->mTitle
->getPrefixedText();
1645 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1646 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1648 $sk = $wgUser->getSkin();
1649 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1650 ':' . wfMsgForContent( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1652 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1654 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1655 $wgOut->returnToMain( false );
1657 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1662 * Back-end article deletion
1663 * Deletes the article with database consistency, writes logs, purges caches
1666 function doDeleteArticle( $reason ) {
1668 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1670 $fname = 'Article::doDeleteArticle';
1671 wfDebug( $fname."\n" );
1673 $dbw =& wfGetDB( DB_MASTER
);
1674 $ns = $this->mTitle
->getNamespace();
1675 $t = $this->mTitle
->getDBkey();
1676 $id = $this->mTitle
->getArticleID();
1678 if ( $t == '' ||
$id == 0 ) {
1682 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1683 array_push( $wgDeferredUpdateList, $u );
1685 $linksTo = $this->mTitle
->getLinksTo();
1688 if ( $wgUseSquid ) {
1690 $this->mTitle
->getInternalURL(),
1691 $this->mTitle
->getInternalURL( 'history' )
1693 foreach ( $linksTo as $linkTo ) {
1694 $urls[] = $linkTo->getInternalURL();
1697 $u = new SquidUpdate( $urls );
1698 array_push( $wgDeferredUpdateList, $u );
1702 # Client and file cache invalidation
1703 Title
::touchArray( $linksTo );
1705 # Move article and history to the "archive" table
1706 $archiveTable = $dbw->tableName( 'archive' );
1707 $oldTable = $dbw->tableName( 'old' );
1708 $curTable = $dbw->tableName( 'cur' );
1709 $recentchangesTable = $dbw->tableName( 'recentchanges' );
1710 $linksTable = $dbw->tableName( 'links' );
1711 $brokenlinksTable = $dbw->tableName( 'brokenlinks' );
1713 $dbw->insertSelect( 'archive', 'cur',
1715 'ar_namespace' => 'cur_namespace',
1716 'ar_title' => 'cur_title',
1717 'ar_text' => 'cur_text',
1718 'ar_comment' => 'cur_comment',
1719 'ar_user' => 'cur_user',
1720 'ar_user_text' => 'cur_user_text',
1721 'ar_timestamp' => 'cur_timestamp',
1722 'ar_minor_edit' => 'cur_minor_edit',
1725 'cur_namespace' => $ns,
1730 $dbw->insertSelect( 'archive', 'old',
1732 'ar_namespace' => 'old_namespace',
1733 'ar_title' => 'old_title',
1734 'ar_text' => 'old_text',
1735 'ar_comment' => 'old_comment',
1736 'ar_user' => 'old_user',
1737 'ar_user_text' => 'old_user_text',
1738 'ar_timestamp' => 'old_timestamp',
1739 'ar_minor_edit' => 'old_minor_edit',
1740 'ar_flags' => 'old_flags'
1742 'old_namespace' => $ns,
1747 # Now that it's safely backed up, delete it
1749 $dbw->delete( 'cur', array( 'cur_namespace' => $ns, 'cur_title' => $t ), $fname );
1750 $dbw->delete( 'old', array( 'old_namespace' => $ns, 'old_title' => $t ), $fname );
1751 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1753 # Finally, clean up the link tables
1754 $t = $this->mTitle
->getPrefixedDBkey();
1756 Article
::onArticleDelete( $this->mTitle
);
1758 # Insert broken links
1759 $brokenLinks = array();
1760 foreach ( $linksTo as $titleObj ) {
1761 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1762 $linkID = $titleObj->getArticleID();
1763 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1765 $dbw->insertArray( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1768 $dbw->delete( 'links', array( 'l_to' => $id ) );
1769 $dbw->delete( 'links', array( 'l_from' => $id ) );
1770 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1771 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1772 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1775 $log = new LogPage( 'delete' );
1776 $log->addEntry( 'delete', $this->mTitle
, $reason );
1778 # Clear the cached article id so the interface doesn't act like we exist
1779 $this->mTitle
->resetArticleID( 0 );
1780 $this->mTitle
->mArticleID
= 0;
1785 * Revert a modification
1787 function rollback() {
1788 global $wgUser, $wgOut, $wgRequest;
1789 $fname = 'Article::rollback';
1791 if ( ! $wgUser->isSysop() ) {
1792 $wgOut->sysopRequired();
1795 if ( wfReadOnly() ) {
1796 $wgOut->readOnlyPage( $this->getContent( true ) );
1799 $dbw =& wfGetDB( DB_MASTER
);
1801 # Enhanced rollback, marks edits rc_bot=1
1802 $bot = $wgRequest->getBool( 'bot' );
1804 # Replace all this user's current edits with the next one down
1805 $tt = $this->mTitle
->getDBKey();
1806 $n = $this->mTitle
->getNamespace();
1808 # Get the last editor, lock table exclusively
1809 $s = $dbw->getArray( 'cur',
1810 array( 'cur_id','cur_user','cur_user_text','cur_comment' ),
1811 array( 'cur_title' => $tt, 'cur_namespace' => $n ),
1812 $fname, 'FOR UPDATE'
1814 if( $s === false ) {
1816 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1819 $ut = $dbw->strencode( $s->cur_user_text
);
1820 $uid = $s->cur_user
;
1823 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1824 if( $from != $s->cur_user_text
) {
1825 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1826 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1827 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1828 htmlspecialchars( $from ),
1829 htmlspecialchars( $s->cur_user_text
) ) );
1830 if($s->cur_comment
!= '') {
1832 wfMsg('editcomment',
1833 htmlspecialchars( $s->cur_comment
) ) );
1838 # Get the last edit not by this guy
1839 $s = $dbw->getArray( 'old',
1840 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1842 'old_namespace' => $n,
1844 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1845 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1847 if( $s === false ) {
1849 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1850 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1855 # Mark all reverted edits as bot
1856 $dbw->updateArray( 'recentchanges',
1859 ), array( /* WHERE */
1861 "rc_timestamp > '{$s->old_timestamp}'",
1867 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1868 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1869 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1870 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1871 $this->updateArticle( Article
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1872 Article
::onArticleEdit( $this->mTitle
);
1873 $wgOut->returnToMain( false );
1878 * Do standard deferred updates after page view
1881 function viewUpdates() {
1882 global $wgDeferredUpdateList;
1883 if ( 0 != $this->getID() ) {
1884 global $wgDisableCounters;
1885 if( !$wgDisableCounters ) {
1886 Article
::incViewCount( $this->getID() );
1887 $u = new SiteStatsUpdate( 1, 0, 0 );
1888 array_push( $wgDeferredUpdateList, $u );
1891 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(),
1892 $this->mTitle
->getDBkey() );
1893 array_push( $wgDeferredUpdateList, $u );
1897 * Do standard deferred updates after page edit.
1898 * Every 1000th edit, prune the recent changes table.
1900 * @param string $text
1902 function editUpdates( $text ) {
1903 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1904 global $wgMessageCache;
1907 if ( 0 == mt_rand( 0, 999 ) ) {
1908 $dbw =& wfGetDB( DB_MASTER
);
1909 $cutoff = $dbw->timestamp( time() - ( 7 * 86400 ) );
1910 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1911 $dbw->query( $sql );
1913 $id = $this->getID();
1914 $title = $this->mTitle
->getPrefixedDBkey();
1915 $shortTitle = $this->mTitle
->getDBkey();
1917 $adj = $this->mCountAdjustment
;
1920 $u = new LinksUpdate( $id, $title );
1921 array_push( $wgDeferredUpdateList, $u );
1922 $u = new SiteStatsUpdate( 0, 1, $adj );
1923 array_push( $wgDeferredUpdateList, $u );
1924 $u = new SearchUpdate( $id, $title, $text );
1925 array_push( $wgDeferredUpdateList, $u );
1927 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle );
1928 array_push( $wgDeferredUpdateList, $u );
1930 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1931 $wgMessageCache->replace( $shortTitle, $text );
1937 * @todo document this function
1939 * @param string $oldid Revision ID of this article revision
1941 function setOldSubtitle( $oldid=0 ) {
1942 global $wgLang, $wgOut, $wgUser;
1944 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1945 $sk = $wgUser->getSkin();
1946 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1947 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1948 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1949 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1950 $wgOut->setSubtitle( $r );
1954 * This function is called right before saving the wikitext,
1955 * so we can do things like signatures and links-in-context.
1957 * @param string $text
1959 function preSaveTransform( $text ) {
1960 global $wgParser, $wgUser;
1961 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1964 /* Caching functions */
1967 * checkLastModified returns true if it has taken care of all
1968 * output to the client that is necessary for this request.
1969 * (that is, it has sent a cached version of the page)
1971 function tryFileCache() {
1972 static $called = false;
1974 wfDebug( " tryFileCache() -- called twice!?\n" );
1978 if($this->isFileCacheable()) {
1979 $touched = $this->mTouched
;
1980 if( $this->mTitle
->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1981 # Expire the main page quicker
1982 $expire = wfUnix2Timestamp( time() - 3600 );
1983 $touched = max( $expire, $touched );
1985 $cache = new CacheManager( $this->mTitle
);
1986 if($cache->isFileCacheGood( $touched )) {
1988 wfDebug( " tryFileCache() - about to load\n" );
1989 $cache->loadFromFileCache();
1992 wfDebug( " tryFileCache() - starting buffer\n" );
1993 ob_start( array(&$cache, 'saveToFileCache' ) );
1996 wfDebug( " tryFileCache() - not cacheable\n" );
2001 * Check if the page can be cached
2004 function isFileCacheable() {
2005 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2006 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2008 return $wgUseFileCache
2009 and (!$wgShowIPinHeader)
2010 and ($this->getID() != 0)
2011 and ($wgUser->getId() == 0)
2012 and (!$wgUser->getNewtalk())
2013 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2014 and (empty( $action ) ||
$action == 'view')
2015 and (!isset($oldid))
2017 and (!isset($redirect))
2018 and (!isset($printable))
2019 and (!$this->mRedirectedFrom
);
2023 * Loads cur_touched and returns a value indicating if it should be used
2026 function checkTouched() {
2027 $fname = 'Article::checkTouched';
2028 $id = $this->getID();
2029 $dbr =& $this->getDB();
2030 $s = $dbr->getArray( 'cur', array( 'cur_touched', 'cur_is_redirect' ),
2031 array( 'cur_id' => $id ), $fname, $this->getSelectOptions() );
2032 if( $s !== false ) {
2033 $this->mTouched
= wfTimestamp(TS_MW
,$s->cur_touched
);
2034 return !$s->cur_is_redirect
;
2041 * Edit an article without doing all that other stuff
2043 * @param string $text text submitted
2044 * @param string $comment comment submitted
2045 * @param integer $minor whereas it's a minor modification
2047 function quickEdit( $text, $comment = '', $minor = 0 ) {
2049 $fname = 'Article::quickEdit';
2050 wfProfileIn( $fname );
2052 $dbw =& wfGetDB( DB_MASTER
);
2053 $ns = $this->mTitle
->getNamespace();
2054 $dbkey = $this->mTitle
->getDBkey();
2055 $encDbKey = $dbw->strencode( $dbkey );
2056 $timestamp = wfTimestampNow();
2059 $dbw->insertSelect( 'old', 'cur',
2061 'old_namespace' => 'cur_namespace',
2062 'old_title' => 'cur_title',
2063 'old_text' => 'cur_text',
2064 'old_comment' => 'cur_comment',
2065 'old_user' => 'cur_user',
2066 'old_user_text' => 'cur_user_text',
2067 'old_timestamp' => 'cur_timestamp',
2068 'inverse_timestamp' => '99999999999999-cur_timestamp',
2070 'cur_namespace' => $ns,
2071 'cur_title' => $dbkey,
2075 # Use the affected row count to determine if the article is new
2076 $numRows = $dbw->affectedRows();
2078 # Make an array of fields to be inserted
2080 'cur_text' => $text,
2081 'cur_timestamp' => $timestamp,
2082 'cur_user' => $wgUser->getID(),
2083 'cur_user_text' => $wgUser->getName(),
2084 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
2085 'cur_comment' => $comment,
2086 'cur_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
2087 'cur_minor_edit' => intval($minor),
2088 'cur_touched' => $dbw->timestamp($timestamp),
2093 $fields['cur_is_new'] = 0;
2094 $dbw->updateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
2096 # Insert new article
2097 $fields['cur_is_new'] = 1;
2098 $fields['cur_namespace'] = $ns;
2099 $fields['cur_title'] = $dbkey;
2100 $fields['cur_random'] = $rand = wfRandom();
2101 $dbw->insertArray( 'cur', $fields, $fname );
2103 wfProfileOut( $fname );
2107 * Used to increment the view counter
2110 * @param integer $id article id
2112 function incViewCount( $id ) {
2113 $id = intval( $id );
2114 global $wgHitcounterUpdateFreq;
2116 $dbw =& wfGetDB( DB_MASTER
);
2117 $curTable = $dbw->tableName( 'cur' );
2118 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2119 $acchitsTable = $dbw->tableName( 'acchits' );
2121 if( $wgHitcounterUpdateFreq <= 1 ){ //
2122 $dbw->query( "UPDATE $curTable SET cur_counter = cur_counter + 1 WHERE cur_id = $id" );
2126 # Not important enough to warrant an error page in case of failure
2127 $oldignore = $dbw->ignoreErrors( true );
2129 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2131 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2132 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2133 # Most of the time (or on SQL errors), skip row count check
2134 $dbw->ignoreErrors( $oldignore );
2138 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2139 $row = $dbw->fetchObject( $res );
2140 $rown = intval( $row->n
);
2141 if( $rown >= $wgHitcounterUpdateFreq ){
2142 wfProfileIn( 'Article::incViewCount-collect' );
2143 $old_user_abort = ignore_user_abort( true );
2145 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2146 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2147 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2149 $dbw->query("DELETE FROM $hitcounterTable");
2150 $dbw->query('UNLOCK TABLES');
2151 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2152 'WHERE cur_id = hc_id');
2153 $dbw->query("DROP TABLE $acchitsTable");
2155 ignore_user_abort( $old_user_abort );
2156 wfProfileOut( 'Article::incViewCount-collect' );
2158 $dbw->ignoreErrors( $oldignore );
2162 * The onArticle*() functions are supposed to be a kind of hooks
2163 * which should be called whenever any of the specified actions
2166 * This is a good place to put code to clear caches, for instance.
2168 * This is called on page move and undelete, as well as edit
2170 * @param $title_obj a title object
2173 function onArticleCreate($title_obj) {
2174 global $wgUseSquid, $wgDeferredUpdateList;
2176 $titles = $title_obj->getBrokenLinksTo();
2179 if ( $wgUseSquid ) {
2180 $urls = $title_obj->getSquidURLs();
2181 foreach ( $titles as $linkTitle ) {
2182 $urls[] = $linkTitle->getInternalURL();
2184 $u = new SquidUpdate( $urls );
2185 array_push( $wgDeferredUpdateList, $u );
2188 # Clear persistent link cache
2189 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2192 function onArticleDelete($title_obj) {
2193 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2195 function onArticleEdit($title_obj) {
2196 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2201 * Info about this page
2204 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2205 $fname = 'Article::info';
2207 if ( !$wgAllowPageInfo ) {
2208 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2212 $dbr =& $this->getDB();
2214 $basenamespace = $wgTitle->getNamespace() & (~
1);
2215 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2216 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2217 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2218 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2219 $wgOut->setPagetitle( $fullTitle );
2220 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2222 # first, see if the page exists at all.
2223 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2225 $wgOut->addHTML( wfMsg('noarticletext') );
2227 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2228 $this->getSelectOptions() );
2229 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2230 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2231 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2233 # to find number of distinct authors, we need to do some
2234 # funny stuff because of the cur/old table split:
2235 # - first, find the name of the 'cur' author
2236 # - then, find the number of *other* authors in 'old'
2239 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2240 $this->getSelectOptions() );
2242 # find number of 'old' authors excluding 'cur' author
2243 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2244 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2245 $this->getSelectOptions() ) +
1;
2247 # now for the Talk page ...
2248 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2249 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2252 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2256 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2257 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2259 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2263 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2264 $this->getSelectOptions() );
2265 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2266 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2267 $fname, $this->getSelectOptions() );
2269 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );