8 * Need the CacheManager to be loaded
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.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.
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mCountAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
40 * Constructor and clear the article
41 * @param mixed &$title
43 function Article( &$title ) {
44 $this->mTitle
=& $title;
49 * get the title object of the article
61 $this->mContentLoaded
= false;
62 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
63 $this->mRedirectedFrom
= $this->mUserText
=
64 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
65 $this->mCountAdjustment
= 0;
66 $this->mTouched
= '19700101000000';
67 $this->mForUpdate
= false;
71 * Note that getContent/loadContent may follow redirects if
72 * not told otherwise, and so may cause a change to mTitle.
75 * @return Return the text of this revision
77 function getContent( $noredir ) {
80 # Get variables from query string :P
81 $action = $wgRequest->getText( 'action', 'view' );
82 $section = $wgRequest->getText( 'section' );
84 $fname = 'Article::getContent';
85 wfProfileIn( $fname );
87 if ( 0 == $this->getID() ) {
88 if ( 'edit' == $action ) {
89 wfProfileOut( $fname );
90 return ''; # was "newarticletext", now moved above the box)
92 wfProfileOut( $fname );
93 return wfMsg( 'noarticletext' );
95 $this->loadContent( $noredir );
96 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
97 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
98 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
101 wfProfileOut( $fname );
102 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
104 if($action=='edit') {
106 if($section=='new') {
107 wfProfileOut( $fname );
111 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
112 # comments to be stripped as well)
113 $rv=$this->getSection($this->mContent
,$section);
114 wfProfileOut( $fname );
118 wfProfileOut( $fname );
119 return $this->mContent
;
125 * This function returns the text of a section, specified by a number ($section).
126 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
127 * the first section before any such heading (section 0).
129 * If a section contains subsections, these are also returned.
131 * @param string $text text to look in
132 * @param integer $section section number
133 * @return string text of the requested section
135 function getSection($text,$section) {
137 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
138 # comments to be stripped as well)
140 $parser=new Parser();
141 $parser->mOutputType
=OT_WIKI
;
142 $striptext=$parser->strip($text, $striparray, true);
144 # now that we can be sure that no pseudo-sections are in the source,
145 # split it up by section
148 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
150 PREG_SPLIT_DELIM_CAPTURE
);
154 $headline=$secs[$section*2-1];
155 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
158 # translate wiki heading into level
159 if(strpos($hlevel,'=')!==false) {
160 $hlevel=strlen($hlevel);
163 $rv=$headline. $secs[$section*2];
167 while(!empty($secs[$count*2-1]) && !$break) {
169 $subheadline=$secs[$count*2-1];
170 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
171 $subhlevel=$matches[1];
172 if(strpos($subhlevel,'=')!==false) {
173 $subhlevel=strlen($subhlevel);
175 if($subhlevel > $hlevel) {
176 $rv.=$subheadline.$secs[$count*2];
178 if($subhlevel <= $hlevel) {
185 # reinsert stripped tags
186 $rv=$parser->unstrip($rv,$striparray);
187 $rv=$parser->unstripNoWiki($rv,$striparray);
194 * Return an array of the columns of the "cur"-table
196 function getContentFields() {
197 return $wgArticleContentFields = array(
198 'old_text','old_flags',
199 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
200 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
204 * Return the oldid of the article that is to be shown.
205 * For requests with a "direction", this is not the oldid of the
208 function getOldID() {
209 global $wgRequest, $wgOut;
212 if ( isset( $lastid ) ) {
216 $oldid = $wgRequest->getVal( 'oldid' );
217 if ( isset( $oldid ) ) {
218 $oldid = IntVal( $oldid );
219 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
220 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
224 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
226 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
227 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
236 return @$oldid; # "@" to be able to return "unset" without PHP complaining
241 * Load the revision (including cur_text) into this object
243 function loadContent( $noredir = false ) {
244 global $wgOut, $wgRequest;
246 if ( $this->mContentLoaded
) return;
249 $oldid = $this->getOldID();
250 $redirect = $wgRequest->getVal( 'redirect' );
252 $fname = 'Article::loadContent';
254 # Pre-fill content with error message so that if something
255 # fails we'll have something telling us what we intended.
257 $t = $this->mTitle
->getPrefixedText();
259 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no');
260 $this->mOldId
= $oldid;
261 $this->fetchContent( $oldid, $noredir, true );
265 * Get text of an article from database
266 * @param int $oldid 0 for whatever the latest revision is
267 * @param bool $noredir Set to true to avoid following redirects
268 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
271 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
272 if ( $this->mContentLoaded
) {
273 return $this->mContent
;
275 $dbr =& $this->getDB();
276 $fname = 'Article::fetchContent';
278 # Pre-fill content with error message so that if something
279 # fails we'll have something telling us what we intended.
280 $t = $this->mTitle
->getPrefixedText();
282 $t .= ',oldid='.$oldid;
284 if( isset( $redirect ) ) {
285 $redirect = ($redirect == 'no') ?
'no' : 'yes';
286 $t .= ',redirect='.$redirect;
288 $this->mContent
= wfMsg( 'missingarticle', $t );
291 # Retrieve current version
292 $id = $this->getID();
297 $s = $dbr->selectRow( array( 'text', 'revision', 'page' ),
298 $this->getContentFields(),
299 "page_id='$id' AND rev_page=page_id AND rev_id=page_latest AND old_id=rev_id",
300 $fname, $this->getSelectOptions() );
302 # Historical revision
303 $s = $dbr->selectRow( array( 'text', 'revision', 'page' ),
304 $this->getContentFields(),
305 "rev_page=page_id AND rev_id='$oldid' AND old_id=rev_id",
306 $fname, $this->getSelectOptions() );
308 if ( $s === false ) {
312 # If we got a redirect, follow it (unless we've been told
313 # not to by either the function parameter or the query
314 if ( !$oldid && !$noredir ) {
315 $rt = Title
::newFromRedirect( Revision
::getRevisionText( $s ) );
316 # process if title object is valid and not special:userlogout
317 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
318 # Gotta hand redirects to special pages differently:
319 # Fill the HTTP response "Location" header and ignore
320 # the rest of the page we're on.
323 if ( $rt->getInterwiki() != '' ) {
324 $wgOut->redirect( $rt->getFullURL() ) ;
327 if ( $rt->getNamespace() == NS_SPECIAL
) {
328 $wgOut->redirect( $rt->getFullURL() );
332 $rid = $rt->getArticleID();
334 $redirRow = $dbr->selectRow( array( 'text', 'revision', 'page' ),
335 $this->getContentFields(),
336 "page_id='$rid' AND rev_page=page_id AND rev_id=page_latest AND old_id=rev_id",
337 $fname, $this->getSelectOptions() );
339 if ( $redirRow !== false ) {
340 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
348 # if the title's different from expected, update...
350 ( $this->mTitle
->getNamespace() != $s->page_namespace ||
351 $this->mTitle
->getDBkey() != $s->page_title
) ) {
352 $oldTitle = Title
::makeTitle( $s->page_namesapce
, $s->page_title
);
353 $this->mTitle
= $oldTitle;
355 $wgTitle = $oldTitle;
358 # Back to the business at hand...
359 $this->mCounter
= $s->page_counter
;
360 $this->mTitle
->mRestrictions
= explode( ',', trim( $s->page_restrictions
) );
361 $this->mTitle
->mRestrictionsLoaded
= true;
362 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
364 $this->mContent
= Revision
::getRevisionText( $s );
366 $this->mUser
= $s->rev_user
;
367 $this->mUserText
= $s->rev_user_text
;
368 $this->mComment
= $s->rev_comment
;
369 $this->mTimestamp
= wfTimestamp( TS_MW
, $s->rev_timestamp
);
371 $this->mContentLoaded
= true;
372 return $this->mContent
;
376 * Gets the article text without using so many damn globals
377 * Returns false on error
379 * @param integer $oldid
381 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
382 return $this->fetchContent( $oldid, $noredir, false );
386 * Read/write accessor to select FOR UPDATE
388 function forUpdate( $x = NULL ) {
389 return wfSetVar( $this->mForUpdate
, $x );
393 * Get the database which should be used for reads
396 if ( $this->mForUpdate
) {
397 return wfGetDB( DB_MASTER
);
399 return wfGetDB( DB_SLAVE
);
404 * Get options for all SELECT statements
405 * Can pass an option array, to which the class-wide options will be appended
407 function getSelectOptions( $options = '' ) {
408 if ( $this->mForUpdate
) {
409 if ( is_array( $options ) ) {
410 $options[] = 'FOR UPDATE';
412 $options = 'FOR UPDATE';
419 * Return the Article ID
422 if( $this->mTitle
) {
423 return $this->mTitle
->getArticleID();
430 * Get the view count for this article
432 function getCount() {
433 if ( -1 == $this->mCounter
) {
434 $id = $this->getID();
435 $dbr =& $this->getDB();
436 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
437 'Article::getCount', $this->getSelectOptions() );
439 return $this->mCounter
;
443 * Would the given text make this article a "good" article (i.e.,
444 * suitable for including in the article count)?
445 * @param string $text Text to analyze
446 * @return integer 1 if it can be counted else 0
448 function isCountable( $text ) {
449 global $wgUseCommaCount;
451 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
452 if ( $this->isRedirect( $text ) ) { return 0; }
453 $token = ($wgUseCommaCount ?
',' : '[[' );
454 if ( false === strstr( $text, $token ) ) { return 0; }
459 * Tests if the article text represents a redirect
461 function isRedirect( $text = false ) {
462 if ( $text === false ) {
463 $this->loadContent();
464 $titleObj = Title
::newFromRedirect( $this->mText
);
466 $titleObj = Title
::newFromRedirect( $text );
468 return $titleObj !== NULL;
472 * Loads everything except the text
473 * This isn't necessary for all uses, so it's only done if needed.
476 function loadLastEdit() {
479 if ( -1 != $this->mUser
)
482 $fname = 'Article::loadLastEdit';
484 $dbr =& $this->getDB();
485 $s = $dbr->selectRow( array( 'revision', 'page') ,
486 array( 'rev_user','rev_user_text','rev_timestamp', 'rev_comment','rev_minor_edit' ),
487 array( 'page_id' => $this->getID(), 'page_latest=rev_id' ), $fname, $this->getSelectOptions() );
489 if ( $s !== false ) {
490 $this->mUser
= $s->rev_user
;
491 $this->mUserText
= $s->rev_user_text
;
492 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->rev_timestamp
);
493 $this->mComment
= $s->rev_comment
;
494 $this->mMinorEdit
= $s->rev_minor_edit
;
498 function getTimestamp() {
499 $this->loadLastEdit();
500 return $this->mTimestamp
;
504 $this->loadLastEdit();
508 function getUserText() {
509 $this->loadLastEdit();
510 return $this->mUserText
;
513 function getComment() {
514 $this->loadLastEdit();
515 return $this->mComment
;
518 function getMinorEdit() {
519 $this->loadLastEdit();
520 return $this->mMinorEdit
;
523 function getContributors($limit = 0, $offset = 0) {
524 $fname = 'Article::getContributors';
526 # XXX: this is expensive; cache this info somewhere.
528 $title = $this->mTitle
;
530 $dbr =& $this->getDB();
531 $revTable = $dbr->tableName( 'revision' );
532 $userTable = $dbr->tableName( 'user' );
533 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
534 $ns = $title->getNamespace();
535 $user = $this->getUser();
536 $pageId = $this->getId();
538 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
539 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
540 WHERE rev_page = $pageId
541 AND rev_user != $user
542 GROUP BY rev_user, rev_user_text, user_real_name
543 ORDER BY timestamp DESC";
545 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
546 $sql .= ' '. $this->getSelectOptions();
548 $res = $dbr->query($sql, $fname);
550 while ( $line = $dbr->fetchObject( $res ) ) {
551 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
554 $dbr->freeResult($res);
559 * This is the default action of the script: just view the page of
563 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
564 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
566 $sk = $wgUser->getSkin();
568 $fname = 'Article::view';
569 wfProfileIn( $fname );
570 # Get variables from query string
571 $oldid = $this->getOldID();
572 $diff = $wgRequest->getVal( 'diff' );
573 $rcid = $wgRequest->getVal( 'rcid' );
575 $wgOut->setArticleFlag( true );
576 $wgOut->setRobotpolicy( 'index,follow' );
577 # If we got diff and oldid in the query, we want to see a
578 # diff page instead of the article.
580 if ( !is_null( $diff ) ) {
581 require_once( 'DifferenceEngine.php' );
582 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
583 $de = new DifferenceEngine( $oldid, $diff, $rcid );
586 # Run view updates for current revision only
587 $this->viewUpdates();
589 wfProfileOut( $fname );
592 if ( empty( $oldid ) && $this->checkTouched() ) {
593 if( $wgOut->checkLastModified( $this->mTouched
) ){
594 wfProfileOut( $fname );
596 } else if ( $this->tryFileCache() ) {
597 # tell wgOut that output is taken care of
599 $this->viewUpdates();
600 wfProfileOut( $fname );
604 # Should the parser cache be used?
605 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
613 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
617 if ( !$outputDone ) {
618 $text = $this->getContent( false ); # May change mTitle by following a redirect
620 # Another whitelist check in case oldid or redirects are altering the title
621 if ( !$this->mTitle
->userCanRead() ) {
622 $wgOut->loginToUse();
628 # We're looking at an old revision
630 if ( !empty( $oldid ) ) {
631 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
632 $wgOut->setRobotpolicy( 'noindex,follow' );
634 if ( '' != $this->mRedirectedFrom
) {
635 $sk = $wgUser->getSkin();
636 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
638 $s = wfMsg( 'redirectedfrom', $redir );
639 $wgOut->setSubtitle( $s );
641 # Can't cache redirects
645 # wrap user css and user js in pre and don't parse
646 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
648 $this->mTitle
->getNamespace() == NS_USER
&&
649 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
651 $wgOut->addWikiText( wfMsg('clearyourcache'));
652 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
653 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
655 $imageUrl = $wgStylePath.'/common/images/redirect.png';
656 $targetUrl = $rt->escapeLocalURL();
657 $titleText = htmlspecialchars( $rt->getPrefixedText() );
658 $link = $sk->makeLinkObj( $rt );
660 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
661 '<span class="redirectText">'.$link.'</span>' );
663 } else if ( $pcache ) {
664 # Display content and save to parser cache
665 $wgOut->addPrimaryWikiText( $text, $this );
667 # Display content, don't attempt to save to parser cache
668 $wgOut->addWikiText( $text );
671 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
672 # If we have been passed an &rcid= parameter, we want to give the user a
673 # chance to mark this new article as patrolled.
674 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
675 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
677 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
678 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
679 'action=markpatrolled&rcid='.$rcid )
683 # Put link titles into the link cache
684 $wgOut->transformBuffer();
686 # Add link titles as META keywords
687 $wgOut->addMetaTags() ;
689 $this->viewUpdates();
690 wfProfileOut( $fname );
692 $wgUser->clearNotification( $this->mTitle
);
696 * Theoretically we could defer these whole insert and update
697 * functions for after display, but that's taking a big leap
698 * of faith, and we want to be able to report database
699 * errors at some point.
702 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
703 global $wgOut, $wgUser;
704 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
706 $fname = 'Article::insertNewArticle';
708 $this->mCountAdjustment
= $this->isCountable( $text );
710 $ns = $this->mTitle
->getNamespace();
711 $ttl = $this->mTitle
->getDBkey();
712 $text = $this->preSaveTransform( $text );
713 if ( $this->isRedirect( $text ) ) { $redir = 1; }
716 $now = wfTimestampNow();
717 $won = wfInvertTimestamp( $now );
720 $isminor = ( $isminor && $wgUser->getID() ) ?
1 : 0;
723 $flags = Revision
::compressRevisionText( $mungedText );
725 $dbw =& wfGetDB( DB_MASTER
);
727 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
728 $dbw->insert( 'text', array(
730 'old_text' => $mungedText,
731 'old_flags' => $flags,
733 $revisionId = $dbw->insertId();
735 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
736 $dbw->insert( 'page', array(
737 'page_id' => $page_id,
738 'page_namespace' => $ns,
739 'page_title' => $ttl,
741 'page_restrictions' => '',
742 'page_is_redirect' => $redir,
744 'page_random' => $rand,
745 'page_touched' => $dbw->timestamp($now),
746 'page_latest' => $revisionId,
748 $newid = $dbw->insertId();
750 $dbw->insert( 'revision', array(
751 'rev_page' => $newid,
752 'rev_id' => $revisionId,
753 'rev_comment' => $summary,
754 'rev_user' => $wgUser->getID(),
755 'rev_timestamp' => $dbw->timestamp($now),
756 'rev_minor_edit' => $isminor,
757 'rev_user_text' => $wgUser->getName(),
758 'inverse_timestamp' => $won,
761 $this->mTitle
->resetArticleID( $newid );
763 Article
::onArticleCreate( $this->mTitle
);
764 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
767 if(!$this->mTitle
->userIsWatching()) $this->watch();
769 if ( $this->mTitle
->userIsWatching() ) {
774 # The talk page isn't in the regular link tables, so we need to update manually:
775 $talkns = $ns ^
1; # talk -> normal; normal -> talk
776 $dbw->update( 'page',
777 array( 'page_touched' => $dbw->timestamp($now) ),
778 array( 'page_namespace' => $talkns,
779 'page_title' => $ttl ),
782 # standard deferred updates
783 $this->editUpdates( $text, $summary, $isminor, $now );
785 $oldid = 0; # new article
786 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
790 * Fetch and uncompress the text for a given revision.
791 * Can ask by rev_id number or timestamp (set $field)
793 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
794 $fname = 'Article::fetchRevisionText';
795 $dbw =& wfGetDB( DB_MASTER
);
797 $rev = $dbw->addQuotes( $revId );
799 $rev = 'page_latest';
801 $result = $dbw->query(
802 sprintf( "SELECT old_text, old_flags
804 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
806 $dbw->tableName( 'page' ),
807 $dbw->tableName( 'revision' ),
808 $dbw->tableName( 'text' ),
809 IntVal( $this->mTitle
->getArticleId() ),
813 $obj = $dbw->fetchObject( $result );
814 $dbw->freeResult( $result );
815 $oldtext = Revision
::getRevisionText( $obj );
819 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
820 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
821 if( is_null( $edittime ) ) {
822 $oldtext = $this->fetchRevisionText();
824 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
826 if ($section != '') {
827 if($section=='new') {
828 if($summary) $subject="== {$summary} ==\n\n";
829 $text=$oldtext."\n\n".$subject.$text;
832 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
833 # comments to be stripped as well)
835 $parser=new Parser();
836 $parser->mOutputType
=OT_WIKI
;
837 $oldtext=$parser->strip($oldtext, $striparray, true);
839 # now that we can be sure that no pseudo-sections are in the source,
841 # Unfortunately we can't simply do a preg_replace because that might
842 # replace the wrong section, so we have to use the section counter instead
843 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
844 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
845 $secs[$section*2]=$text."\n\n"; // replace with edited
847 # section 0 is top (intro) section
850 # headline of old section - we need to go through this section
851 # to determine if there are any subsections that now need to
852 # be erased, as the mother section has been replaced with
853 # the text of all subsections.
854 $headline=$secs[$section*2-1];
855 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
858 # determine headline level for wikimarkup headings
859 if(strpos($hlevel,'=')!==false) {
860 $hlevel=strlen($hlevel);
863 $secs[$section*2-1]=''; // erase old headline
866 while(!empty($secs[$count*2-1]) && !$break) {
868 $subheadline=$secs[$count*2-1];
870 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
871 $subhlevel=$matches[1];
872 if(strpos($subhlevel,'=')!==false) {
873 $subhlevel=strlen($subhlevel);
875 if($subhlevel > $hlevel) {
876 // erase old subsections
877 $secs[$count*2-1]='';
880 if($subhlevel <= $hlevel) {
888 $text=join('',$secs);
889 # reinsert the stuff that we stripped out earlier
890 $text=$parser->unstrip($text,$striparray);
891 $text=$parser->unstripNoWiki($text,$striparray);
899 * Change an existing article. Puts the previous version back into the old table, updates RC
900 * and all necessary caches, mostly via the deferred update array.
902 * It is possible to call this function from a command-line script, but note that you should
903 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
905 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
906 global $wgOut, $wgUser;
907 global $wgDBtransactions, $wgMwRedir;
908 global $wgUseSquid, $wgInternalServer;
910 $fname = 'Article::updateArticle';
913 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
914 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
915 if ( $this->isRedirect( $text ) ) {
916 # Remove all content but redirect
917 # This could be done by reconstructing the redirect from a title given by
918 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
920 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
922 $text = $m[1] . "\n";
927 $text = $this->preSaveTransform( $text );
928 $dbw =& wfGetDB( DB_MASTER
);
930 # Update article, but only if changed.
932 # It's important that we either rollback or complete, otherwise an attacker could
933 # overwrite cur entries by sending precisely timed user aborts. Random bored users
934 # could conceivably have the same effect, especially if cur is locked for long periods.
935 if( $wgDBtransactions ) {
936 $dbw->query( 'BEGIN', $fname );
938 $userAbort = ignore_user_abort( true );
941 $oldtext = $this->getContent( true );
943 if ( 0 != strcmp( $text, $oldtext ) ) {
944 $this->mCountAdjustment
= $this->isCountable( $text )
945 - $this->isCountable( $oldtext );
946 $now = wfTimestampNow();
947 $won = wfInvertTimestamp( $now );
950 $flags = Revision
::compressRevisionText( $newtext );
952 $lastRevision = $dbw->selectField(
953 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
955 # Record the text to the text table
956 $old_id = $dbw->nextSequenceValue( 'text_old_id_val' );
957 $dbw->insert( 'text',
960 'old_text' => $mungedText,
961 'old_flags' => $flags,
964 $revisionId = $dbw->insertId();
966 # Record the edit in revisions
967 $dbw->insert( 'revision',
969 'rev_id' => $revisionId,
970 'rev_page' => $this->getID(),
971 'rev_comment' => $summary,
972 'rev_minor_edit' => $me2,
973 'rev_user' => $wgUser->getID(),
974 'rev_user_text' => $wgUser->getName(),
975 'rev_timestamp' => $dbw->timestamp( $now ),
976 'inverse_timestamp' => $won
981 $dbw->update( 'page',
983 'page_latest' => $revisionId,
984 'page_touched' => $dbw->timestamp( $now ),
986 'page_is_redirect' => $redir,
987 ), array( /* WHERE */
988 'page_id' => $this->getID(),
989 'page_latest' => $lastRevision, # Paranoia
993 if( $dbw->affectedRows() == 0 ) {
994 /* Belated edit conflict! Run away!! */
997 # Update recentchanges and purge cache and whatnot
998 $bot = (int)($wgUser->isBot() ||
$forceBot);
999 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1000 $lastRevision, $this->getTimestamp(), $bot );
1001 Article
::onArticleEdit( $this->mTitle
);
1005 if( $wgDBtransactions ) {
1006 $dbw->query( 'COMMIT', $fname );
1008 ignore_user_abort( $userAbort );
1013 if (!$this->mTitle
->userIsWatching()) $this->watch();
1015 if ( $this->mTitle
->userIsWatching() ) {
1019 # standard deferred updates
1020 $this->editUpdates( $text, $summary, $minor, $now );
1024 # Template namespace
1025 # Purge all articles linking here
1026 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1027 $titles = $this->mTitle
->getLinksTo();
1028 Title
::touchArray( $titles );
1029 if ( $wgUseSquid ) {
1030 foreach ( $titles as $title ) {
1031 $urls[] = $title->getInternalURL();
1037 if ( $wgUseSquid ) {
1038 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1039 $u = new SquidUpdate( $urls );
1043 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1049 * After we've either updated or inserted the article, update
1050 * the link tables and redirect to the new page.
1052 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1053 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1055 $wgLinkCache = new LinkCache();
1057 $wgLinkCache->forUpdate( true );
1059 # Get old version of link table to allow incremental link updates
1060 $wgLinkCache->preFill( $this->mTitle
);
1061 $wgLinkCache->clear();
1063 # Parse the text and replace links with placeholders
1064 $wgOut = new OutputPage();
1065 $wgOut->addWikiText( $text );
1067 # Look up the links in the DB and add them to the link cache
1068 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1070 if( $this->isRedirect( $text ) )
1074 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1076 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1077 # this will be improved later (to-do)
1079 include_once( "UserMailer.php" );
1080 $wgEnotif = new EmailNotification ();
1081 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1086 * @todo document this function a bit more
1088 function validate () {
1089 global $wgOut, $wgUseValidation;
1090 if( $wgUseValidation ) {
1091 require_once ( 'SpecialValidate.php' ) ;
1092 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle
->getPrefixedText() );
1093 $wgOut->setRobotpolicy( 'noindex,follow' );
1094 if( $this->mTitle
->getNamespace() != 0 ) {
1095 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1098 $v = new Validation
;
1099 $v->validate_form( $this->mTitle
->getDBkey() );
1101 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1106 * Mark this particular edit as patrolled
1108 function markpatrolled() {
1109 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1110 $wgOut->setRobotpolicy( 'noindex,follow' );
1112 if ( !$wgUseRCPatrol )
1114 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1117 if ( $wgUser->getID() == 0 )
1119 $wgOut->loginToUse();
1122 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1124 $wgOut->sysopRequired();
1127 $rcid = $wgRequest->getVal( 'rcid' );
1128 if ( !is_null ( $rcid ) )
1130 RecentChange
::markPatrolled( $rcid );
1131 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1132 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1134 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1135 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1139 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1145 * Add this page to $wgUser's watchlist
1150 global $wgUser, $wgOut;
1152 if ( 0 == $wgUser->getID() ) {
1153 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1156 if ( wfReadOnly() ) {
1157 $wgOut->readOnlyPage();
1161 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1163 $wgUser->addWatch( $this->mTitle
);
1164 $wgUser->saveSettings();
1166 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1168 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1169 $wgOut->setRobotpolicy( 'noindex,follow' );
1171 $link = $this->mTitle
->getPrefixedText();
1172 $text = wfMsg( 'addedwatchtext', $link );
1173 $wgOut->addWikiText( $text );
1176 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1180 * Stop watching a page
1183 function unwatch() {
1185 global $wgUser, $wgOut;
1187 if ( 0 == $wgUser->getID() ) {
1188 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1191 if ( wfReadOnly() ) {
1192 $wgOut->readOnlyPage();
1196 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1198 $wgUser->removeWatch( $this->mTitle
);
1199 $wgUser->saveSettings();
1201 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1203 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1204 $wgOut->setRobotpolicy( 'noindex,follow' );
1206 $link = $this->mTitle
->getPrefixedText();
1207 $text = wfMsg( 'removedwatchtext', $link );
1208 $wgOut->addWikiText( $text );
1211 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1217 function protect( $limit = 'sysop' ) {
1218 global $wgUser, $wgOut, $wgRequest;
1220 if ( ! $wgUser->isAllowed('protect') ) {
1221 $wgOut->sysopRequired();
1224 if ( wfReadOnly() ) {
1225 $wgOut->readOnlyPage();
1228 $id = $this->mTitle
->getArticleID();
1230 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1234 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1235 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1236 $reason = $wgRequest->getText( 'wpReasonProtect' );
1239 $dbw =& wfGetDB( DB_MASTER
);
1240 $dbw->update( 'page',
1242 'page_touched' => $dbw->timestamp(),
1243 'page_restrictions' => (string)$limit
1244 ), array( /* WHERE */
1246 ), 'Article::protect'
1249 $restrictions = "move=" . $limit;
1251 $restrictions .= ":edit=" . $limit;
1253 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1255 $dbw =& wfGetDB( DB_MASTER
);
1256 $dbw->update( 'page',
1258 'page_touched' => $dbw->timestamp(),
1259 'page_restrictions' => $restrictions
1260 ), array( /* WHERE */
1262 ), 'Article::protect'
1265 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1267 $log = new LogPage( 'protect' );
1268 if ( $limit === '' ) {
1269 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1271 $log->addEntry( 'protect', $this->mTitle
, $reason );
1273 $wgOut->redirect( $this->mTitle
->getFullURL() );
1277 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1278 return $this->confirmProtect( '', $reason, $limit );
1283 * Output protection confirmation dialog
1285 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1288 wfDebug( "Article::confirmProtect\n" );
1290 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1291 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1297 if ( $limit === '' ) {
1298 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1299 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1300 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1301 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1302 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1303 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1305 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1306 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1307 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1308 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1309 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1310 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1311 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1314 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1317 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1321 <label for='wpReasonProtect'>{$protcom}:</label>
1324 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1332 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1335 <label for='wpConfirmProtect'>{$check}</label>
1338 if($moveonly != '') {
1342 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1345 <label for='wpMoveOnly'>{$moveonly}</label>
1353 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1359 $wgOut->returnToMain( false );
1363 * Unprotect the pages
1365 function unprotect() {
1366 return $this->protect( '' );
1370 * UI entry point for page deletion
1373 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1374 $fname = 'Article::delete';
1375 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1376 $reason = $wgRequest->getText( 'wpReason' );
1378 # This code desperately needs to be totally rewritten
1381 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1382 $wgOut->sysopRequired();
1385 if ( wfReadOnly() ) {
1386 $wgOut->readOnlyPage();
1390 # Better double-check that it hasn't been deleted yet!
1391 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1392 if ( ( '' == trim( $this->mTitle
->getText() ) )
1393 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1394 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1399 $this->doDelete( $reason );
1403 # determine whether this page has earlier revisions
1404 # and insert a warning if it does
1405 # we select the text because it might be useful below
1406 $dbr =& $this->getDB();
1407 $ns = $this->mTitle
->getNamespace();
1408 $title = $this->mTitle
->getDBkey();
1409 $revisions = $dbr->select( array( 'page', 'revision' ),
1412 'page_namespace' => $ns,
1413 'page_title' => $title,
1414 'rev_page = page_id'
1415 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1418 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1419 $skin=$wgUser->getSkin();
1420 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1421 $wgOut->addHTML( $skin->historyLink() .'</b>');
1425 $s = $dbr->selectRow( array( 'page', 'text' ),
1426 array( 'old_text' ),
1428 'page_namespace' => $ns,
1429 'page_title' => $title,
1430 'page_latest = old_id'
1431 ), $fname, $this->getSelectOptions()
1434 if( $s !== false ) {
1435 # if this is a mini-text, we can paste part of it into the deletion reason
1437 #if this is empty, an earlier revision may contain "useful" text
1439 if($s->old_text
!= '') {
1443 $text = Revision
::getRevisionText( $old );
1449 $length=strlen($text);
1451 # this should not happen, since it is not possible to store an empty, new
1452 # page. Let's insert a standard text in case it does, though
1453 if($length == 0 && $reason === '') {
1454 $reason = wfMsg('exblank');
1457 if($length < 500 && $reason === '') {
1459 # comment field=255, let's grep the first 150 to have some user
1461 $text=substr($text,0,150);
1462 # let's strip out newlines and HTML tags
1463 $text=preg_replace('/\"/',"'",$text);
1464 $text=preg_replace('/\</','<',$text);
1465 $text=preg_replace('/\>/','>',$text);
1466 $text=preg_replace("/[\n\r]/",'',$text);
1468 $reason=wfMsg('excontent'). " '".$text;
1470 $reason=wfMsg('exbeforeblank') . " '".$text;
1472 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1477 return $this->confirmDelete( '', $reason );
1481 * Output deletion confirmation dialog
1483 function confirmDelete( $par, $reason ) {
1486 wfDebug( "Article::confirmDelete\n" );
1488 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1489 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1490 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1491 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1493 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1495 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1496 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1497 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1500 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1504 <label for='wpReason'>{$delcom}:</label>
1507 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1515 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1518 <label for='wpConfirm'>{$check}</label>
1524 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1530 $wgOut->returnToMain( false );
1535 * Perform a deletion and output success or failure messages
1537 function doDelete( $reason ) {
1538 global $wgOut, $wgUser, $wgContLang;
1539 $fname = 'Article::doDelete';
1540 wfDebug( $fname."\n" );
1542 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1543 if ( $this->doDeleteArticle( $reason ) ) {
1544 $deleted = $this->mTitle
->getPrefixedText();
1546 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1547 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1549 $sk = $wgUser->getSkin();
1550 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1551 ':' . wfMsgForContent( 'dellogpage' ),
1552 wfMsg( 'deletionlog' ) );
1554 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1556 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1557 $wgOut->returnToMain( false );
1558 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1560 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1566 * Back-end article deletion
1567 * Deletes the article with database consistency, writes logs, purges caches
1570 function doDeleteArticle( $reason ) {
1572 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1574 $fname = 'Article::doDeleteArticle';
1575 wfDebug( $fname."\n" );
1577 $dbw =& wfGetDB( DB_MASTER
);
1578 $ns = $this->mTitle
->getNamespace();
1579 $t = $this->mTitle
->getDBkey();
1580 $id = $this->mTitle
->getArticleID();
1582 if ( $t == '' ||
$id == 0 ) {
1586 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1587 array_push( $wgDeferredUpdateList, $u );
1589 $linksTo = $this->mTitle
->getLinksTo();
1592 if ( $wgUseSquid ) {
1594 $this->mTitle
->getInternalURL(),
1595 $this->mTitle
->getInternalURL( 'history' )
1597 foreach ( $linksTo as $linkTo ) {
1598 $urls[] = $linkTo->getInternalURL();
1601 $u = new SquidUpdate( $urls );
1602 array_push( $wgDeferredUpdateList, $u );
1606 # Client and file cache invalidation
1607 Title
::touchArray( $linksTo );
1609 # Move article and history to the "archive" table
1611 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1613 'ar_namespace' => 'page_namespace',
1614 'ar_title' => 'page_title',
1615 'ar_text' => 'old_text',
1616 'ar_comment' => 'rev_comment',
1617 'ar_user' => 'rev_user',
1618 'ar_user_text' => 'rev_user_text',
1619 'ar_timestamp' => 'rev_timestamp',
1620 'ar_minor_edit' => 'rev_minor_edit',
1623 'page_namespace' => $ns,
1625 'page_id = rev_page AND old_id = rev_id'
1629 # Now that it's safely backed up, delete it
1631 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1632 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1633 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1635 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1637 # Finally, clean up the link tables
1638 $t = $this->mTitle
->getPrefixedDBkey();
1640 Article
::onArticleDelete( $this->mTitle
);
1642 # Insert broken links
1643 $brokenLinks = array();
1644 foreach ( $linksTo as $titleObj ) {
1645 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1646 $linkID = $titleObj->getArticleID();
1647 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1649 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1652 $dbw->delete( 'links', array( 'l_to' => $id ) );
1653 $dbw->delete( 'links', array( 'l_from' => $id ) );
1654 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1655 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1656 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1659 $log = new LogPage( 'delete' );
1660 $log->addEntry( 'delete', $this->mTitle
, $reason );
1662 # Clear the cached article id so the interface doesn't act like we exist
1663 $this->mTitle
->resetArticleID( 0 );
1664 $this->mTitle
->mArticleID
= 0;
1669 * Revert a modification
1671 function rollback() {
1672 global $wgUser, $wgOut, $wgRequest;
1673 $fname = 'Article::rollback';
1675 if ( ! $wgUser->isAllowed('rollback') ) {
1676 $wgOut->sysopRequired();
1679 if ( wfReadOnly() ) {
1680 $wgOut->readOnlyPage( $this->getContent( true ) );
1683 $dbw =& wfGetDB( DB_MASTER
);
1685 # Enhanced rollback, marks edits rc_bot=1
1686 $bot = $wgRequest->getBool( 'bot' );
1688 # Replace all this user's current edits with the next one down
1689 $tt = $this->mTitle
->getDBKey();
1690 $n = $this->mTitle
->getNamespace();
1692 # Get the last editor, lock table exclusively
1693 $s = $dbw->selectRow( array( 'page', 'revision' ),
1694 array( 'page_id','rev_user','rev_user_text','rev_comment' ),
1695 array( 'page_title' => $tt, 'page_namespace' => $n ),
1696 $fname, 'FOR UPDATE'
1698 if( $s === false ) {
1700 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1703 $ut = $dbw->strencode( $s->cur_user_text
);
1704 $uid = $s->rev_user
;
1707 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1708 if( $from != $s->rev_user_text
) {
1709 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1710 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1711 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1712 htmlspecialchars( $from ),
1713 htmlspecialchars( $s->rev_user_text
) ) );
1714 if($s->rev_comment
!= '') {
1716 wfMsg('editcomment',
1717 htmlspecialchars( $s->rev_comment
) ) );
1722 # Get the last edit not by this guy
1723 $s = $dbw->selectRow( 'old',
1724 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1726 'old_namespace' => $n,
1728 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1729 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1731 if( $s === false ) {
1733 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1734 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1739 # Mark all reverted edits as bot
1740 $dbw->update( 'recentchanges',
1743 ), array( /* WHERE */
1745 "rc_timestamp > '{$s->old_timestamp}'",
1751 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1752 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1753 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1754 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1755 $this->updateArticle( Revision
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1756 Article
::onArticleEdit( $this->mTitle
);
1757 $wgOut->returnToMain( false );
1762 * Do standard deferred updates after page view
1765 function viewUpdates() {
1766 global $wgDeferredUpdateList;
1768 if ( 0 != $this->getID() ) {
1769 global $wgDisableCounters;
1770 if( !$wgDisableCounters ) {
1771 Article
::incViewCount( $this->getID() );
1772 $u = new SiteStatsUpdate( 1, 0, 0 );
1773 array_push( $wgDeferredUpdateList, $u );
1777 # Update newtalk status if user is reading their own
1781 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1782 $this->mTitle
->getText() == $wgUser->getName()) {
1783 require_once( 'UserTalkUpdate.php' );
1784 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1789 * Do standard deferred updates after page edit.
1790 * Every 1000th edit, prune the recent changes table.
1792 * @param string $text
1794 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1795 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1796 global $wgMessageCache, $wgUser;
1799 if ( 0 == mt_rand( 0, 999 ) ) {
1800 # Periodically flush old entries from the recentchanges table.
1802 $dbw =& wfGetDB( DB_MASTER
);
1803 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1804 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1805 $dbw->query( $sql );
1807 $id = $this->getID();
1808 $title = $this->mTitle
->getPrefixedDBkey();
1809 $shortTitle = $this->mTitle
->getDBkey();
1811 $adj = $this->mCountAdjustment
;
1814 $u = new LinksUpdate( $id, $title );
1815 array_push( $wgDeferredUpdateList, $u );
1816 $u = new SiteStatsUpdate( 0, 1, $adj );
1817 array_push( $wgDeferredUpdateList, $u );
1818 $u = new SearchUpdate( $id, $title, $text );
1819 array_push( $wgDeferredUpdateList, $u );
1821 # If this is another user's talk page,
1822 # create a watchlist entry for this page
1824 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1825 $shortTitle != $wgUser->getName()) {
1826 require_once( 'UserTalkUpdate.php' );
1827 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1830 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1831 $wgMessageCache->replace( $shortTitle, $text );
1837 * @todo document this function
1839 * @param string $oldid Revision ID of this article revision
1841 function setOldSubtitle( $oldid=0 ) {
1842 global $wgLang, $wgOut, $wgUser;
1844 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1845 $sk = $wgUser->getSkin();
1846 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1847 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1848 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1849 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1850 $wgOut->setSubtitle( $r );
1854 * This function is called right before saving the wikitext,
1855 * so we can do things like signatures and links-in-context.
1857 * @param string $text
1859 function preSaveTransform( $text ) {
1860 global $wgParser, $wgUser;
1861 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1864 /* Caching functions */
1867 * checkLastModified returns true if it has taken care of all
1868 * output to the client that is necessary for this request.
1869 * (that is, it has sent a cached version of the page)
1871 function tryFileCache() {
1872 static $called = false;
1874 wfDebug( " tryFileCache() -- called twice!?\n" );
1878 if($this->isFileCacheable()) {
1879 $touched = $this->mTouched
;
1880 $cache = new CacheManager( $this->mTitle
);
1881 if($cache->isFileCacheGood( $touched )) {
1883 wfDebug( " tryFileCache() - about to load\n" );
1884 $cache->loadFromFileCache();
1887 wfDebug( " tryFileCache() - starting buffer\n" );
1888 ob_start( array(&$cache, 'saveToFileCache' ) );
1891 wfDebug( " tryFileCache() - not cacheable\n" );
1896 * Check if the page can be cached
1899 function isFileCacheable() {
1900 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1901 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1903 return $wgUseFileCache
1904 and (!$wgShowIPinHeader)
1905 and ($this->getID() != 0)
1906 and ($wgUser->getId() == 0)
1907 and (!$wgUser->getNewtalk())
1908 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1909 and (empty( $action ) ||
$action == 'view')
1910 and (!isset($oldid))
1912 and (!isset($redirect))
1913 and (!isset($printable))
1914 and (!$this->mRedirectedFrom
);
1918 * Loads cur_touched and returns a value indicating if it should be used
1921 function checkTouched() {
1922 $fname = 'Article::checkTouched';
1923 $id = $this->getID();
1924 $dbr =& $this->getDB();
1925 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1926 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1927 if( $s !== false ) {
1928 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
1929 return !$s->page_is_redirect
;
1936 * Edit an article without doing all that other stuff
1938 * @param string $text text submitted
1939 * @param string $comment comment submitted
1940 * @param integer $minor whereas it's a minor modification
1942 function quickEdit( $text, $comment = '', $minor = 0 ) {
1944 $fname = 'Article::quickEdit';
1946 #wfDebugDieBacktrace( "$fname called." );
1948 wfProfileIn( $fname );
1950 $dbw =& wfGetDB( DB_MASTER
);
1951 $ns = $this->mTitle
->getNamespace();
1952 $dbkey = $this->mTitle
->getDBkey();
1953 $encDbKey = $dbw->strencode( $dbkey );
1954 $timestamp = wfTimestampNow();
1956 $dbw->insert( 'text', array(
1957 'old_text' => $text,
1958 'old_flags' => "" ), $fname );
1959 $text_id = $dbw->insertID();
1962 $dbw->update( 'page', array(
1964 'page_touched' => $timestamp,
1965 'page_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
1966 'page_latest' => $text_id ),
1967 array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1969 $page_id = $dbw->selectField( 'page', 'page_id', array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1972 $dbw->insert( 'revision', array(
1973 'rev_id' => $text_id,
1974 'rev_page' => $page_id,
1975 'rev_comment' => $comment,
1976 'rev_user' => $wgUser->getID(),
1977 'rev_user_text' => $wgUser->getName(),
1978 'rev_timestamp' => $timestamp,
1979 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1980 'rev_minor_edit' => intval($minor) ),
1982 wfProfileOut( $fname );
1986 * Used to increment the view counter
1989 * @param integer $id article id
1991 function incViewCount( $id ) {
1992 $id = intval( $id );
1993 global $wgHitcounterUpdateFreq;
1995 $dbw =& wfGetDB( DB_MASTER
);
1996 $pageTable = $dbw->tableName( 'page' );
1997 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1998 $acchitsTable = $dbw->tableName( 'acchits' );
2000 if( $wgHitcounterUpdateFreq <= 1 ){ //
2001 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2005 # Not important enough to warrant an error page in case of failure
2006 $oldignore = $dbw->ignoreErrors( true );
2008 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2010 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2011 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2012 # Most of the time (or on SQL errors), skip row count check
2013 $dbw->ignoreErrors( $oldignore );
2017 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2018 $row = $dbw->fetchObject( $res );
2019 $rown = intval( $row->n
);
2020 if( $rown >= $wgHitcounterUpdateFreq ){
2021 wfProfileIn( 'Article::incViewCount-collect' );
2022 $old_user_abort = ignore_user_abort( true );
2024 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2025 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2026 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2028 $dbw->query("DELETE FROM $hitcounterTable");
2029 $dbw->query('UNLOCK TABLES');
2030 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2031 'WHERE cur_id = hc_id');
2032 $dbw->query("DROP TABLE $acchitsTable");
2034 ignore_user_abort( $old_user_abort );
2035 wfProfileOut( 'Article::incViewCount-collect' );
2037 $dbw->ignoreErrors( $oldignore );
2041 * The onArticle*() functions are supposed to be a kind of hooks
2042 * which should be called whenever any of the specified actions
2045 * This is a good place to put code to clear caches, for instance.
2047 * This is called on page move and undelete, as well as edit
2049 * @param $title_obj a title object
2052 function onArticleCreate($title_obj) {
2053 global $wgUseSquid, $wgDeferredUpdateList;
2055 $titles = $title_obj->getBrokenLinksTo();
2058 if ( $wgUseSquid ) {
2059 $urls = $title_obj->getSquidURLs();
2060 foreach ( $titles as $linkTitle ) {
2061 $urls[] = $linkTitle->getInternalURL();
2063 $u = new SquidUpdate( $urls );
2064 array_push( $wgDeferredUpdateList, $u );
2067 # Clear persistent link cache
2068 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2071 function onArticleDelete($title_obj) {
2072 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2074 function onArticleEdit($title_obj) {
2075 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2080 * Info about this page
2083 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2084 $fname = 'Article::info';
2086 wfDebugDieBacktrace( 'This function is apparently not called by any other PHP file and might be obsolete.' );
2088 if ( !$wgAllowPageInfo ) {
2089 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2093 $dbr =& $this->getDB();
2095 $basenamespace = $wgTitle->getNamespace() & (~
1);
2096 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2097 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2098 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2099 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2100 $wgOut->setPagetitle( $fullTitle );
2101 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2103 # first, see if the page exists at all.
2104 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2106 $wgOut->addHTML( wfMsg('noarticletext') );
2108 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2109 $this->getSelectOptions() );
2110 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2111 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2112 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2114 # to find number of distinct authors, we need to do some
2115 # funny stuff because of the cur/old table split:
2116 # - first, find the name of the 'cur' author
2117 # - then, find the number of *other* authors in 'old'
2120 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2121 $this->getSelectOptions() );
2123 # find number of 'old' authors excluding 'cur' author
2124 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2125 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2126 $this->getSelectOptions() ) +
1;
2128 # now for the Talk page ...
2129 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2130 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2133 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2137 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2138 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2140 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2144 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2145 $this->getSelectOptions() );
2146 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2147 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2148 $fname, $this->getSelectOptions() );
2150 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );
2157 * Check whether an article is a stub
2160 * @param integer $articleID ID of the article that is to be checked
2162 function wfArticleIsStub( $articleID ) {
2164 $fname = 'wfArticleIsStub';
2166 wfDebugDieBacktrace( 'This function seems to be unused. Pending removal.' );
2168 $threshold = $wgUser->getOption('stubthreshold') ;
2169 if ( $threshold > 0 ) {
2170 $dbr =& wfGetDB( DB_SLAVE
);
2171 $s = $dbr->selectRow( array('page', 'text'),
2172 array( 'LENGTH(old_text) AS len', 'page_namespace', 'page_is_redirect' ),
2173 array( 'page_id' => $articleID, "page.page_latest=text.old_id" ),
2175 if ( $s == false OR $s->page_is_redirect
OR $s->page_namespace
!= NS_MAIN
) {
2179 return ( $size < $threshold );