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() != '' && $rt->isLocal() ) {
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 # New or non-existent articles have no user information
483 $id = $this->getID();
484 if ( 0 == $id ) return;
486 $fname = 'Article::loadLastEdit';
488 $dbr =& $this->getDB();
489 $s = $dbr->selectRow( array( 'revision', 'page') ,
490 array( 'rev_user','rev_user_text','rev_timestamp', 'rev_comment','rev_minor_edit' ),
491 array( 'page_id' => $id, 'page_latest=rev_id' ), $fname, $this->getSelectOptions() );
493 if ( $s !== false ) {
494 $this->mUser
= $s->rev_user
;
495 $this->mUserText
= $s->rev_user_text
;
496 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->rev_timestamp
);
497 $this->mComment
= $s->rev_comment
;
498 $this->mMinorEdit
= $s->rev_minor_edit
;
502 function getTimestamp() {
503 $this->loadLastEdit();
504 return $this->mTimestamp
;
508 $this->loadLastEdit();
512 function getUserText() {
513 $this->loadLastEdit();
514 return $this->mUserText
;
517 function getComment() {
518 $this->loadLastEdit();
519 return $this->mComment
;
522 function getMinorEdit() {
523 $this->loadLastEdit();
524 return $this->mMinorEdit
;
527 function getContributors($limit = 0, $offset = 0) {
528 $fname = 'Article::getContributors';
530 # XXX: this is expensive; cache this info somewhere.
532 $title = $this->mTitle
;
534 $dbr =& $this->getDB();
535 $revTable = $dbr->tableName( 'revision' );
536 $userTable = $dbr->tableName( 'user' );
537 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
538 $ns = $title->getNamespace();
539 $user = $this->getUser();
540 $pageId = $this->getId();
542 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
543 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
544 WHERE rev_page = $pageId
545 AND rev_user != $user
546 GROUP BY rev_user, rev_user_text, user_real_name
547 ORDER BY timestamp DESC";
549 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
550 $sql .= ' '. $this->getSelectOptions();
552 $res = $dbr->query($sql, $fname);
554 while ( $line = $dbr->fetchObject( $res ) ) {
555 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
558 $dbr->freeResult($res);
563 * This is the default action of the script: just view the page of
567 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
568 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
570 $sk = $wgUser->getSkin();
572 $fname = 'Article::view';
573 wfProfileIn( $fname );
574 # Get variables from query string
575 $oldid = $this->getOldID();
576 $diff = $wgRequest->getVal( 'diff' );
577 $rcid = $wgRequest->getVal( 'rcid' );
579 $wgOut->setArticleFlag( true );
580 $wgOut->setRobotpolicy( 'index,follow' );
581 # If we got diff and oldid in the query, we want to see a
582 # diff page instead of the article.
584 if ( !is_null( $diff ) ) {
585 require_once( 'DifferenceEngine.php' );
586 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
587 $de = new DifferenceEngine( $oldid, $diff, $rcid );
590 # Run view updates for current revision only
591 $this->viewUpdates();
593 wfProfileOut( $fname );
596 if ( empty( $oldid ) && $this->checkTouched() ) {
597 if( $wgOut->checkLastModified( $this->mTouched
) ){
598 wfProfileOut( $fname );
600 } else if ( $this->tryFileCache() ) {
601 # tell wgOut that output is taken care of
603 $this->viewUpdates();
604 wfProfileOut( $fname );
608 # Should the parser cache be used?
609 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
617 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
621 if ( !$outputDone ) {
622 $text = $this->getContent( false ); # May change mTitle by following a redirect
624 # Another whitelist check in case oldid or redirects are altering the title
625 if ( !$this->mTitle
->userCanRead() ) {
626 $wgOut->loginToUse();
632 # We're looking at an old revision
634 if ( !empty( $oldid ) ) {
635 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
636 $wgOut->setRobotpolicy( 'noindex,follow' );
638 if ( '' != $this->mRedirectedFrom
) {
639 $sk = $wgUser->getSkin();
640 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
642 $s = wfMsg( 'redirectedfrom', $redir );
643 $wgOut->setSubtitle( $s );
645 # Can't cache redirects
649 # wrap user css and user js in pre and don't parse
650 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
652 $this->mTitle
->getNamespace() == NS_USER
&&
653 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
655 $wgOut->addWikiText( wfMsg('clearyourcache'));
656 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
657 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
659 $imageUrl = $wgStylePath.'/common/images/redirect.png';
660 $targetUrl = $rt->escapeLocalURL();
661 $titleText = htmlspecialchars( $rt->getPrefixedText() );
662 $link = $sk->makeLinkObj( $rt );
664 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
665 '<span class="redirectText">'.$link.'</span>' );
667 } else if ( $pcache ) {
668 # Display content and save to parser cache
669 $wgOut->addPrimaryWikiText( $text, $this );
671 # Display content, don't attempt to save to parser cache
672 $wgOut->addWikiText( $text );
675 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
676 # If we have been passed an &rcid= parameter, we want to give the user a
677 # chance to mark this new article as patrolled.
678 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->isLoggedIn() &&
679 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
681 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
682 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
683 'action=markpatrolled&rcid='.$rcid )
687 # Put link titles into the link cache
688 $wgOut->transformBuffer();
690 # Add link titles as META keywords
691 $wgOut->addMetaTags() ;
693 $this->viewUpdates();
694 wfProfileOut( $fname );
696 $wgUser->clearNotification( $this->mTitle
);
700 * Theoretically we could defer these whole insert and update
701 * functions for after display, but that's taking a big leap
702 * of faith, and we want to be able to report database
703 * errors at some point.
706 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
707 global $wgOut, $wgUser;
708 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
710 $fname = 'Article::insertNewArticle';
712 $this->mCountAdjustment
= $this->isCountable( $text );
714 $ns = $this->mTitle
->getNamespace();
715 $ttl = $this->mTitle
->getDBkey();
716 $text = $this->preSaveTransform( $text );
717 if ( $this->isRedirect( $text ) ) { $redir = 1; }
720 $now = wfTimestampNow();
721 $won = wfInvertTimestamp( $now );
724 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
727 $flags = Revision
::compressRevisionText( $mungedText );
729 $dbw =& wfGetDB( DB_MASTER
);
731 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
732 $dbw->insert( 'text', array(
734 'old_text' => $mungedText,
735 'old_flags' => $flags,
737 $revisionId = $dbw->insertId();
739 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
740 $dbw->insert( 'page', array(
741 'page_id' => $page_id,
742 'page_namespace' => $ns,
743 'page_title' => $ttl,
745 'page_restrictions' => '',
746 'page_is_redirect' => $redir,
748 'page_random' => $rand,
749 'page_touched' => $dbw->timestamp($now),
750 'page_latest' => $revisionId,
752 $newid = $dbw->insertId();
754 $dbw->insert( 'revision', array(
755 'rev_page' => $newid,
756 'rev_id' => $revisionId,
757 'rev_comment' => $summary,
758 'rev_user' => $wgUser->getID(),
759 'rev_timestamp' => $dbw->timestamp($now),
760 'rev_minor_edit' => $isminor,
761 'rev_user_text' => $wgUser->getName(),
762 'inverse_timestamp' => $won,
765 $this->mTitle
->resetArticleID( $newid );
767 Article
::onArticleCreate( $this->mTitle
);
768 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
771 if(!$this->mTitle
->userIsWatching()) $this->watch();
773 if ( $this->mTitle
->userIsWatching() ) {
778 # The talk page isn't in the regular link tables, so we need to update manually:
779 $talkns = $ns ^
1; # talk -> normal; normal -> talk
780 $dbw->update( 'page',
781 array( 'page_touched' => $dbw->timestamp($now) ),
782 array( 'page_namespace' => $talkns,
783 'page_title' => $ttl ),
786 # standard deferred updates
787 $this->editUpdates( $text, $summary, $isminor, $now );
789 $oldid = 0; # new article
790 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
794 * Fetch and uncompress the text for a given revision.
795 * Can ask by rev_id number or timestamp (set $field)
797 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
798 $fname = 'Article::fetchRevisionText';
799 $dbw =& wfGetDB( DB_MASTER
);
801 $rev = $dbw->addQuotes( $revId );
803 $rev = 'page_latest';
805 $result = $dbw->query(
806 sprintf( "SELECT old_text, old_flags
808 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
810 $dbw->tableName( 'page' ),
811 $dbw->tableName( 'revision' ),
812 $dbw->tableName( 'text' ),
813 IntVal( $this->mTitle
->getArticleId() ),
817 $obj = $dbw->fetchObject( $result );
818 $dbw->freeResult( $result );
819 $oldtext = Revision
::getRevisionText( $obj );
823 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
824 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
825 if( is_null( $edittime ) ) {
826 $oldtext = $this->fetchRevisionText();
828 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
830 if ($section != '') {
831 if($section=='new') {
832 if($summary) $subject="== {$summary} ==\n\n";
833 $text=$oldtext."\n\n".$subject.$text;
836 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
837 # comments to be stripped as well)
839 $parser=new Parser();
840 $parser->mOutputType
=OT_WIKI
;
841 $oldtext=$parser->strip($oldtext, $striparray, true);
843 # now that we can be sure that no pseudo-sections are in the source,
845 # Unfortunately we can't simply do a preg_replace because that might
846 # replace the wrong section, so we have to use the section counter instead
847 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
848 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
849 $secs[$section*2]=$text."\n\n"; // replace with edited
851 # section 0 is top (intro) section
854 # headline of old section - we need to go through this section
855 # to determine if there are any subsections that now need to
856 # be erased, as the mother section has been replaced with
857 # the text of all subsections.
858 $headline=$secs[$section*2-1];
859 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
862 # determine headline level for wikimarkup headings
863 if(strpos($hlevel,'=')!==false) {
864 $hlevel=strlen($hlevel);
867 $secs[$section*2-1]=''; // erase old headline
870 while(!empty($secs[$count*2-1]) && !$break) {
872 $subheadline=$secs[$count*2-1];
874 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
875 $subhlevel=$matches[1];
876 if(strpos($subhlevel,'=')!==false) {
877 $subhlevel=strlen($subhlevel);
879 if($subhlevel > $hlevel) {
880 // erase old subsections
881 $secs[$count*2-1]='';
884 if($subhlevel <= $hlevel) {
892 $text=join('',$secs);
893 # reinsert the stuff that we stripped out earlier
894 $text=$parser->unstrip($text,$striparray);
895 $text=$parser->unstripNoWiki($text,$striparray);
903 * Change an existing article. Puts the previous version back into the old table, updates RC
904 * and all necessary caches, mostly via the deferred update array.
906 * It is possible to call this function from a command-line script, but note that you should
907 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
909 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
910 global $wgOut, $wgUser;
911 global $wgDBtransactions, $wgMwRedir;
912 global $wgUseSquid, $wgInternalServer;
914 $fname = 'Article::updateArticle';
917 if ( $this->mMinorEdit
) { $me1 = 1; } else { $me1 = 0; }
918 if ( $minor && $wgUser->isLoggedIn() ) { $me2 = 1; } else { $me2 = 0; }
919 if ( $this->isRedirect( $text ) ) {
920 # Remove all content but redirect
921 # This could be done by reconstructing the redirect from a title given by
922 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
924 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
926 $text = $m[1] . "\n";
931 $text = $this->preSaveTransform( $text );
932 $dbw =& wfGetDB( DB_MASTER
);
934 # Update article, but only if changed.
936 # It's important that we either rollback or complete, otherwise an attacker could
937 # overwrite cur entries by sending precisely timed user aborts. Random bored users
938 # could conceivably have the same effect, especially if cur is locked for long periods.
939 if( $wgDBtransactions ) {
940 $dbw->query( 'BEGIN', $fname );
942 $userAbort = ignore_user_abort( true );
945 $oldtext = $this->getContent( true );
947 if ( 0 != strcmp( $text, $oldtext ) ) {
948 $this->mCountAdjustment
= $this->isCountable( $text )
949 - $this->isCountable( $oldtext );
950 $now = wfTimestampNow();
951 $won = wfInvertTimestamp( $now );
954 $flags = Revision
::compressRevisionText( $mungedText );
956 $lastRevision = $dbw->selectField(
957 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
959 # Record the text to the text table
960 $old_id = $dbw->nextSequenceValue( 'text_old_id_val' );
961 $dbw->insert( 'text',
964 'old_text' => $mungedText,
965 'old_flags' => $flags,
968 $revisionId = $dbw->insertId();
970 # Record the edit in revisions
971 $dbw->insert( 'revision',
973 'rev_id' => $revisionId,
974 'rev_page' => $this->getID(),
975 'rev_comment' => $summary,
976 'rev_minor_edit' => $me2,
977 'rev_user' => $wgUser->getID(),
978 'rev_user_text' => $wgUser->getName(),
979 'rev_timestamp' => $dbw->timestamp( $now ),
980 'inverse_timestamp' => $won
985 $dbw->update( 'page',
987 'page_latest' => $revisionId,
988 'page_touched' => $dbw->timestamp( $now ),
990 'page_is_redirect' => $redir,
991 ), array( /* WHERE */
992 'page_id' => $this->getID(),
993 'page_latest' => $lastRevision, # Paranoia
997 if( $dbw->affectedRows() == 0 ) {
998 /* Belated edit conflict! Run away!! */
1001 # Update recentchanges and purge cache and whatnot
1002 $bot = (int)($wgUser->isBot() ||
$forceBot);
1003 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1004 $lastRevision, $this->getTimestamp(), $bot );
1005 Article
::onArticleEdit( $this->mTitle
);
1009 if( $wgDBtransactions ) {
1010 $dbw->query( 'COMMIT', $fname );
1012 ignore_user_abort( $userAbort );
1017 if (!$this->mTitle
->userIsWatching()) $this->watch();
1019 if ( $this->mTitle
->userIsWatching() ) {
1023 # standard deferred updates
1024 $this->editUpdates( $text, $summary, $minor, $now );
1028 # Template namespace
1029 # Purge all articles linking here
1030 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1031 $titles = $this->mTitle
->getLinksTo();
1032 Title
::touchArray( $titles );
1033 if ( $wgUseSquid ) {
1034 foreach ( $titles as $title ) {
1035 $urls[] = $title->getInternalURL();
1041 if ( $wgUseSquid ) {
1042 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1043 $u = new SquidUpdate( $urls );
1047 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1053 * After we've either updated or inserted the article, update
1054 * the link tables and redirect to the new page.
1056 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1057 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1059 $wgLinkCache = new LinkCache();
1061 $wgLinkCache->forUpdate( true );
1063 # Get old version of link table to allow incremental link updates
1064 $wgLinkCache->preFill( $this->mTitle
);
1065 $wgLinkCache->clear();
1067 # Parse the text and replace links with placeholders
1068 $wgOut = new OutputPage();
1069 $wgOut->addWikiText( $text );
1071 # Look up the links in the DB and add them to the link cache
1072 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1074 if( $this->isRedirect( $text ) )
1078 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1080 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1081 # this will be improved later (to-do)
1083 include_once( "UserMailer.php" );
1084 $wgEnotif = new EmailNotification ();
1085 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1089 * Mark this particular edit as patrolled
1091 function markpatrolled() {
1092 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1093 $wgOut->setRobotpolicy( 'noindex,follow' );
1095 if ( !$wgUseRCPatrol )
1097 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1100 if ( $wgUser->isAnon() )
1102 $wgOut->loginToUse();
1105 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1107 $wgOut->sysopRequired();
1110 $rcid = $wgRequest->getVal( 'rcid' );
1111 if ( !is_null ( $rcid ) )
1113 RecentChange
::markPatrolled( $rcid );
1114 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1115 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1117 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1118 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1122 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1128 * Add this page to $wgUser's watchlist
1133 global $wgUser, $wgOut;
1135 if ( $wgUser->isAnon() ) {
1136 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1139 if ( wfReadOnly() ) {
1140 $wgOut->readOnlyPage();
1144 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1146 $wgUser->addWatch( $this->mTitle
);
1147 $wgUser->saveSettings();
1149 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1151 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1152 $wgOut->setRobotpolicy( 'noindex,follow' );
1154 $link = $this->mTitle
->getPrefixedText();
1155 $text = wfMsg( 'addedwatchtext', $link );
1156 $wgOut->addWikiText( $text );
1159 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1163 * Stop watching a page
1166 function unwatch() {
1168 global $wgUser, $wgOut;
1170 if ( $wgUser->isAnon() ) {
1171 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1174 if ( wfReadOnly() ) {
1175 $wgOut->readOnlyPage();
1179 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1181 $wgUser->removeWatch( $this->mTitle
);
1182 $wgUser->saveSettings();
1184 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1186 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1187 $wgOut->setRobotpolicy( 'noindex,follow' );
1189 $link = $this->mTitle
->getPrefixedText();
1190 $text = wfMsg( 'removedwatchtext', $link );
1191 $wgOut->addWikiText( $text );
1194 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1200 function protect( $limit = 'sysop' ) {
1201 global $wgUser, $wgOut, $wgRequest;
1203 if ( ! $wgUser->isAllowed('protect') ) {
1204 $wgOut->sysopRequired();
1207 if ( wfReadOnly() ) {
1208 $wgOut->readOnlyPage();
1211 $id = $this->mTitle
->getArticleID();
1213 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1217 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) &&
1218 $wgRequest->wasPosted() &&
1219 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1220 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1221 $reason = $wgRequest->getText( 'wpReasonProtect' );
1224 $dbw =& wfGetDB( DB_MASTER
);
1225 $dbw->update( 'page',
1227 'page_touched' => $dbw->timestamp(),
1228 'page_restrictions' => (string)$limit
1229 ), array( /* WHERE */
1231 ), 'Article::protect'
1234 $restrictions = "move=" . $limit;
1236 $restrictions .= ":edit=" . $limit;
1238 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1240 $dbw =& wfGetDB( DB_MASTER
);
1241 $dbw->update( 'page',
1243 'page_touched' => $dbw->timestamp(),
1244 'page_restrictions' => $restrictions
1245 ), array( /* WHERE */
1247 ), 'Article::protect'
1250 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1252 $log = new LogPage( 'protect' );
1253 if ( $limit === '' ) {
1254 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1256 $log->addEntry( 'protect', $this->mTitle
, $reason );
1258 $wgOut->redirect( $this->mTitle
->getFullURL() );
1262 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1263 return $this->confirmProtect( '', $reason, $limit );
1268 * Output protection confirmation dialog
1270 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1271 global $wgOut, $wgUser;
1273 wfDebug( "Article::confirmProtect\n" );
1275 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1276 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1282 if ( $limit === '' ) {
1283 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1284 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1285 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1286 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1287 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1288 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1290 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1291 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1292 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1293 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1294 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1295 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1296 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1299 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1300 $token = htmlspecialchars( $wgUser->editToken() );
1303 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1307 <label for='wpReasonProtect'>{$protcom}:</label>
1310 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1318 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1321 <label for='wpConfirmProtect'>{$check}</label>
1324 if($moveonly != '') {
1328 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1331 <label for='wpMoveOnly'>{$moveonly}</label>
1339 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1343 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1346 $wgOut->returnToMain( false );
1350 * Unprotect the pages
1352 function unprotect() {
1353 return $this->protect( '' );
1357 * UI entry point for page deletion
1360 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1361 $fname = 'Article::delete';
1362 $confirm = $wgRequest->getBool( 'wpConfirm' ) &&
1363 $wgRequest->wasPosted() &&
1364 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1365 $reason = $wgRequest->getText( 'wpReason' );
1367 # This code desperately needs to be totally rewritten
1370 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1371 $wgOut->sysopRequired();
1374 if ( wfReadOnly() ) {
1375 $wgOut->readOnlyPage();
1379 # Better double-check that it hasn't been deleted yet!
1380 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1381 if ( ( '' == trim( $this->mTitle
->getText() ) )
1382 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1383 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1388 $this->doDelete( $reason );
1392 # determine whether this page has earlier revisions
1393 # and insert a warning if it does
1394 # we select the text because it might be useful below
1395 $dbr =& $this->getDB();
1396 $ns = $this->mTitle
->getNamespace();
1397 $title = $this->mTitle
->getDBkey();
1398 $revisions = $dbr->select( array( 'page', 'revision' ),
1401 'page_namespace' => $ns,
1402 'page_title' => $title,
1403 'rev_page = page_id'
1404 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1407 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1408 $skin=$wgUser->getSkin();
1409 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1410 $wgOut->addHTML( $skin->historyLink() .'</b>');
1414 $s = $dbr->selectRow( array( 'page', 'text' ),
1415 array( 'old_text' ),
1417 'page_namespace' => $ns,
1418 'page_title' => $title,
1419 'page_latest = old_id'
1420 ), $fname, $this->getSelectOptions()
1423 if( $s !== false ) {
1424 # if this is a mini-text, we can paste part of it into the deletion reason
1426 #if this is empty, an earlier revision may contain "useful" text
1428 if($s->old_text
!= '') {
1432 $text = Revision
::getRevisionText( $old );
1438 $length=strlen($text);
1440 # this should not happen, since it is not possible to store an empty, new
1441 # page. Let's insert a standard text in case it does, though
1442 if($length == 0 && $reason === '') {
1443 $reason = wfMsg('exblank');
1446 if($length < 500 && $reason === '') {
1448 # comment field=255, let's grep the first 150 to have some user
1450 $text=substr($text,0,150);
1451 # let's strip out newlines and HTML tags
1452 $text=preg_replace('/\"/',"'",$text);
1453 $text=preg_replace('/\</','<',$text);
1454 $text=preg_replace('/\>/','>',$text);
1455 $text=preg_replace("/[\n\r]/",'',$text);
1457 $reason=wfMsg('excontent'). " '".$text;
1459 $reason=wfMsg('exbeforeblank') . " '".$text;
1461 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1466 return $this->confirmDelete( '', $reason );
1470 * Output deletion confirmation dialog
1472 function confirmDelete( $par, $reason ) {
1473 global $wgOut, $wgUser;
1475 wfDebug( "Article::confirmDelete\n" );
1477 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1478 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1479 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1480 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1482 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1484 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1485 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1486 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1487 $token = htmlspecialchars( $wgUser->editToken() );
1490 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1494 <label for='wpReason'>{$delcom}:</label>
1497 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1505 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1508 <label for='wpConfirm'>{$check}</label>
1514 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1518 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1521 $wgOut->returnToMain( false );
1526 * Perform a deletion and output success or failure messages
1528 function doDelete( $reason ) {
1529 global $wgOut, $wgUser, $wgContLang;
1530 $fname = 'Article::doDelete';
1531 wfDebug( $fname."\n" );
1533 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1534 if ( $this->doDeleteArticle( $reason ) ) {
1535 $deleted = $this->mTitle
->getPrefixedText();
1537 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1538 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1540 $sk = $wgUser->getSkin();
1541 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1542 ':' . wfMsgForContent( 'dellogpage' ),
1543 wfMsg( 'deletionlog' ) );
1545 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1547 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1548 $wgOut->returnToMain( false );
1549 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1551 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1557 * Back-end article deletion
1558 * Deletes the article with database consistency, writes logs, purges caches
1561 function doDeleteArticle( $reason ) {
1563 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1565 $fname = 'Article::doDeleteArticle';
1566 wfDebug( $fname."\n" );
1568 $dbw =& wfGetDB( DB_MASTER
);
1569 $ns = $this->mTitle
->getNamespace();
1570 $t = $this->mTitle
->getDBkey();
1571 $id = $this->mTitle
->getArticleID();
1573 if ( $t == '' ||
$id == 0 ) {
1577 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1578 array_push( $wgDeferredUpdateList, $u );
1580 $linksTo = $this->mTitle
->getLinksTo();
1583 if ( $wgUseSquid ) {
1585 $this->mTitle
->getInternalURL(),
1586 $this->mTitle
->getInternalURL( 'history' )
1588 foreach ( $linksTo as $linkTo ) {
1589 $urls[] = $linkTo->getInternalURL();
1592 $u = new SquidUpdate( $urls );
1593 array_push( $wgDeferredUpdateList, $u );
1597 # Client and file cache invalidation
1598 Title
::touchArray( $linksTo );
1600 # Move article and history to the "archive" table
1602 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1604 'ar_namespace' => 'page_namespace',
1605 'ar_title' => 'page_title',
1606 'ar_text' => 'old_text',
1607 'ar_comment' => 'rev_comment',
1608 'ar_user' => 'rev_user',
1609 'ar_user_text' => 'rev_user_text',
1610 'ar_timestamp' => 'rev_timestamp',
1611 'ar_minor_edit' => 'rev_minor_edit',
1614 'page_namespace' => $ns,
1616 'page_id = rev_page AND old_id = rev_id'
1620 # Now that it's safely backed up, delete it
1622 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1623 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1624 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1626 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1628 # Finally, clean up the link tables
1629 $t = $this->mTitle
->getPrefixedDBkey();
1631 Article
::onArticleDelete( $this->mTitle
);
1633 # Insert broken links
1634 $brokenLinks = array();
1635 foreach ( $linksTo as $titleObj ) {
1636 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1637 $linkID = $titleObj->getArticleID();
1638 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1640 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1643 $dbw->delete( 'links', array( 'l_to' => $id ) );
1644 $dbw->delete( 'links', array( 'l_from' => $id ) );
1645 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1646 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1647 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1650 $log = new LogPage( 'delete' );
1651 $log->addEntry( 'delete', $this->mTitle
, $reason );
1653 # Clear the cached article id so the interface doesn't act like we exist
1654 $this->mTitle
->resetArticleID( 0 );
1655 $this->mTitle
->mArticleID
= 0;
1660 * Revert a modification
1662 function rollback() {
1663 global $wgUser, $wgOut, $wgRequest;
1664 $fname = 'Article::rollback';
1666 if ( ! $wgUser->isAllowed('rollback') ) {
1667 $wgOut->sysopRequired();
1670 if ( wfReadOnly() ) {
1671 $wgOut->readOnlyPage( $this->getContent( true ) );
1674 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1675 array( $this->mTitle
->getPrefixedText(),
1676 $wgRequest->getVal( 'from' ) ) ) ) {
1677 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1678 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1681 $dbw =& wfGetDB( DB_MASTER
);
1683 # Enhanced rollback, marks edits rc_bot=1
1684 $bot = $wgRequest->getBool( 'bot' );
1686 # Replace all this user's current edits with the next one down
1687 $tt = $this->mTitle
->getDBKey();
1688 $n = $this->mTitle
->getNamespace();
1690 # Get the last editor, lock table exclusively
1691 $s = $dbw->selectRow( array( 'page', 'revision' ),
1692 array( 'page_id','rev_user','rev_user_text','rev_comment' ),
1693 array( 'page_title' => $tt, 'page_namespace' => $n ),
1694 $fname, 'FOR UPDATE'
1696 if( $s === false ) {
1698 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1701 $ut = $dbw->strencode( $s->cur_user_text
);
1702 $uid = $s->rev_user
;
1705 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1706 if( $from != $s->rev_user_text
) {
1707 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1708 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1709 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1710 htmlspecialchars( $from ),
1711 htmlspecialchars( $s->rev_user_text
) ) );
1712 if($s->rev_comment
!= '') {
1714 wfMsg('editcomment',
1715 htmlspecialchars( $s->rev_comment
) ) );
1720 # Get the last edit not by this guy
1721 $s = $dbw->selectRow( 'old',
1722 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1724 'old_namespace' => $n,
1726 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1727 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1729 if( $s === false ) {
1731 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1732 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1737 # Mark all reverted edits as bot
1738 $dbw->update( 'recentchanges',
1741 ), array( /* WHERE */
1743 "rc_timestamp > '{$s->old_timestamp}'",
1749 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1750 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1751 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1752 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1753 $this->updateArticle( Revision
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1754 Article
::onArticleEdit( $this->mTitle
);
1755 $wgOut->returnToMain( false );
1760 * Do standard deferred updates after page view
1763 function viewUpdates() {
1764 global $wgDeferredUpdateList;
1766 if ( 0 != $this->getID() ) {
1767 global $wgDisableCounters;
1768 if( !$wgDisableCounters ) {
1769 Article
::incViewCount( $this->getID() );
1770 $u = new SiteStatsUpdate( 1, 0, 0 );
1771 array_push( $wgDeferredUpdateList, $u );
1775 # Update newtalk status if user is reading their own
1779 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1780 $this->mTitle
->getText() == $wgUser->getName()) {
1781 require_once( 'UserTalkUpdate.php' );
1782 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1787 * Do standard deferred updates after page edit.
1788 * Every 1000th edit, prune the recent changes table.
1790 * @param string $text
1792 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1793 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1794 global $wgMessageCache, $wgUser;
1797 if ( 0 == mt_rand( 0, 999 ) ) {
1798 # Periodically flush old entries from the recentchanges table.
1800 $dbw =& wfGetDB( DB_MASTER
);
1801 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1802 $recentchanges = $dbw->tableName( 'recentchanges' );
1803 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1804 $dbw->query( $sql );
1806 $id = $this->getID();
1807 $title = $this->mTitle
->getPrefixedDBkey();
1808 $shortTitle = $this->mTitle
->getDBkey();
1810 $adj = $this->mCountAdjustment
;
1813 $u = new LinksUpdate( $id, $title );
1814 array_push( $wgDeferredUpdateList, $u );
1815 $u = new SiteStatsUpdate( 0, 1, $adj );
1816 array_push( $wgDeferredUpdateList, $u );
1817 $u = new SearchUpdate( $id, $title, $text );
1818 array_push( $wgDeferredUpdateList, $u );
1820 # If this is another user's talk page,
1821 # create a watchlist entry for this page
1823 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1824 $shortTitle != $wgUser->getName()) {
1825 require_once( 'UserTalkUpdate.php' );
1826 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1829 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1830 $wgMessageCache->replace( $shortTitle, $text );
1836 * @todo document this function
1838 * @param string $oldid Revision ID of this article revision
1840 function setOldSubtitle( $oldid=0 ) {
1841 global $wgLang, $wgOut, $wgUser;
1843 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1844 $sk = $wgUser->getSkin();
1845 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1846 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1847 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1848 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1849 $wgOut->setSubtitle( $r );
1853 * This function is called right before saving the wikitext,
1854 * so we can do things like signatures and links-in-context.
1856 * @param string $text
1858 function preSaveTransform( $text ) {
1859 global $wgParser, $wgUser;
1860 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1863 /* Caching functions */
1866 * checkLastModified returns true if it has taken care of all
1867 * output to the client that is necessary for this request.
1868 * (that is, it has sent a cached version of the page)
1870 function tryFileCache() {
1871 static $called = false;
1873 wfDebug( " tryFileCache() -- called twice!?\n" );
1877 if($this->isFileCacheable()) {
1878 $touched = $this->mTouched
;
1879 $cache = new CacheManager( $this->mTitle
);
1880 if($cache->isFileCacheGood( $touched )) {
1882 wfDebug( " tryFileCache() - about to load\n" );
1883 $cache->loadFromFileCache();
1886 wfDebug( " tryFileCache() - starting buffer\n" );
1887 ob_start( array(&$cache, 'saveToFileCache' ) );
1890 wfDebug( " tryFileCache() - not cacheable\n" );
1895 * Check if the page can be cached
1898 function isFileCacheable() {
1899 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1900 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1902 return $wgUseFileCache
1903 and (!$wgShowIPinHeader)
1904 and ($this->getID() != 0)
1905 and ($wgUser->isAnon())
1906 and (!$wgUser->getNewtalk())
1907 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1908 and (empty( $action ) ||
$action == 'view')
1909 and (!isset($oldid))
1911 and (!isset($redirect))
1912 and (!isset($printable))
1913 and (!$this->mRedirectedFrom
);
1917 * Loads cur_touched and returns a value indicating if it should be used
1920 function checkTouched() {
1921 $fname = 'Article::checkTouched';
1922 $id = $this->getID();
1923 $dbr =& $this->getDB();
1924 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1925 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1926 if( $s !== false ) {
1927 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
1928 return !$s->page_is_redirect
;
1935 * Edit an article without doing all that other stuff
1937 * @param string $text text submitted
1938 * @param string $comment comment submitted
1939 * @param integer $minor whereas it's a minor modification
1941 function quickEdit( $text, $comment = '', $minor = 0 ) {
1943 $fname = 'Article::quickEdit';
1945 #wfDebugDieBacktrace( "$fname called." );
1947 wfProfileIn( $fname );
1949 $dbw =& wfGetDB( DB_MASTER
);
1950 $ns = $this->mTitle
->getNamespace();
1951 $dbkey = $this->mTitle
->getDBkey();
1952 $encDbKey = $dbw->strencode( $dbkey );
1953 $timestamp = $dbw->timestamp();
1955 $dbw->insert( 'text', array(
1956 'old_text' => $text,
1957 'old_flags' => "" ), $fname );
1958 $text_id = $dbw->insertID();
1961 $dbw->update( 'page', array(
1963 'page_touched' => $timestamp,
1964 'page_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
1965 'page_latest' => $text_id ),
1966 array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1968 $page_id = $dbw->selectField( 'page', 'page_id', array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1971 $dbw->insert( 'revision', array(
1972 'rev_id' => $text_id,
1973 'rev_page' => $page_id,
1974 'rev_comment' => $comment,
1975 'rev_user' => $wgUser->getID(),
1976 'rev_user_text' => $wgUser->getName(),
1977 'rev_timestamp' => $timestamp,
1978 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1979 'rev_minor_edit' => intval($minor) ),
1981 wfProfileOut( $fname );
1985 * Used to increment the view counter
1988 * @param integer $id article id
1990 function incViewCount( $id ) {
1991 $id = intval( $id );
1992 global $wgHitcounterUpdateFreq;
1994 $dbw =& wfGetDB( DB_MASTER
);
1995 $pageTable = $dbw->tableName( 'page' );
1996 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1997 $acchitsTable = $dbw->tableName( 'acchits' );
1999 if( $wgHitcounterUpdateFreq <= 1 ){ //
2000 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2004 # Not important enough to warrant an error page in case of failure
2005 $oldignore = $dbw->ignoreErrors( true );
2007 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2009 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2010 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2011 # Most of the time (or on SQL errors), skip row count check
2012 $dbw->ignoreErrors( $oldignore );
2016 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2017 $row = $dbw->fetchObject( $res );
2018 $rown = intval( $row->n
);
2019 if( $rown >= $wgHitcounterUpdateFreq ){
2020 wfProfileIn( 'Article::incViewCount-collect' );
2021 $old_user_abort = ignore_user_abort( true );
2023 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2024 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2025 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2027 $dbw->query("DELETE FROM $hitcounterTable");
2028 $dbw->query('UNLOCK TABLES');
2029 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2030 'WHERE cur_id = hc_id');
2031 $dbw->query("DROP TABLE $acchitsTable");
2033 ignore_user_abort( $old_user_abort );
2034 wfProfileOut( 'Article::incViewCount-collect' );
2036 $dbw->ignoreErrors( $oldignore );
2040 * The onArticle*() functions are supposed to be a kind of hooks
2041 * which should be called whenever any of the specified actions
2044 * This is a good place to put code to clear caches, for instance.
2046 * This is called on page move and undelete, as well as edit
2048 * @param $title_obj a title object
2051 function onArticleCreate($title_obj) {
2052 global $wgUseSquid, $wgDeferredUpdateList;
2054 $titles = $title_obj->getBrokenLinksTo();
2057 if ( $wgUseSquid ) {
2058 $urls = $title_obj->getSquidURLs();
2059 foreach ( $titles as $linkTitle ) {
2060 $urls[] = $linkTitle->getInternalURL();
2062 $u = new SquidUpdate( $urls );
2063 array_push( $wgDeferredUpdateList, $u );
2066 # Clear persistent link cache
2067 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2070 function onArticleDelete($title_obj) {
2071 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2073 function onArticleEdit($title_obj) {
2074 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2079 * Info about this page
2082 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2083 $fname = 'Article::info';
2085 wfDebugDieBacktrace( 'This function is apparently not called by any other PHP file and might be obsolete.' );
2087 if ( !$wgAllowPageInfo ) {
2088 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2092 $dbr =& $this->getDB();
2094 $basenamespace = $wgTitle->getNamespace() & (~
1);
2095 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2096 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2097 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2098 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2099 $wgOut->setPagetitle( $fullTitle );
2100 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2102 # first, see if the page exists at all.
2103 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2105 $wgOut->addHTML( wfMsg('noarticletext') );
2107 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2108 $this->getSelectOptions() );
2109 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2110 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2111 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old +
1) . '</li>');
2113 # to find number of distinct authors, we need to do some
2114 # funny stuff because of the cur/old table split:
2115 # - first, find the name of the 'cur' author
2116 # - then, find the number of *other* authors in 'old'
2119 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2120 $this->getSelectOptions() );
2122 # find number of 'old' authors excluding 'cur' author
2123 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2124 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2125 $this->getSelectOptions() ) +
1;
2127 # now for the Talk page ...
2128 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+
1 );
2129 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+
1 );
2132 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2136 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2137 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old +
1) . '</li>');
2139 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2143 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2144 $this->getSelectOptions() );
2145 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2146 $old_clause +
array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2147 $fname, $this->getSelectOptions() );
2149 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );
2156 * Check whether an article is a stub
2159 * @param integer $articleID ID of the article that is to be checked
2161 function wfArticleIsStub( $articleID ) {
2163 $fname = 'wfArticleIsStub';
2165 wfDebugDieBacktrace( 'This function seems to be unused. Pending removal.' );
2167 $threshold = $wgUser->getOption('stubthreshold') ;
2168 if ( $threshold > 0 ) {
2169 $dbr =& wfGetDB( DB_SLAVE
);
2170 $s = $dbr->selectRow( array('page', 'text'),
2171 array( 'LENGTH(old_text) AS len', 'page_namespace', 'page_is_redirect' ),
2172 array( 'page_id' => $articleID, "page.page_latest=text.old_id" ),
2174 if ( $s == false OR $s->page_is_redirect
OR $s->page_namespace
!= NS_MAIN
) {
2178 return ( $size < $threshold );