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' );
578 $rdfrom = $wgRequest->getVal( 'rdfrom' );
580 $wgOut->setArticleFlag( true );
581 $wgOut->setRobotpolicy( 'index,follow' );
582 # If we got diff and oldid in the query, we want to see a
583 # diff page instead of the article.
585 if ( !is_null( $diff ) ) {
586 require_once( 'DifferenceEngine.php' );
587 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
588 $de = new DifferenceEngine( $oldid, $diff, $rcid );
591 # Run view updates for current revision only
592 $this->viewUpdates();
594 wfProfileOut( $fname );
597 if ( empty( $oldid ) && $this->checkTouched() ) {
598 if( $wgOut->checkLastModified( $this->mTouched
) ){
599 wfProfileOut( $fname );
601 } else if ( $this->tryFileCache() ) {
602 # tell wgOut that output is taken care of
604 $this->viewUpdates();
605 wfProfileOut( $fname );
609 # Should the parser cache be used?
610 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
618 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
622 if ( !$outputDone ) {
623 $text = $this->getContent( false ); # May change mTitle by following a redirect
625 # Another whitelist check in case oldid or redirects are altering the title
626 if ( !$this->mTitle
->userCanRead() ) {
627 $wgOut->loginToUse();
633 # We're looking at an old revision
635 if ( !empty( $oldid ) ) {
636 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
637 $wgOut->setRobotpolicy( 'noindex,follow' );
639 if ( '' != $this->mRedirectedFrom
) {
640 $sk = $wgUser->getSkin();
641 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
643 $s = wfMsg( 'redirectedfrom', $redir );
644 $wgOut->setSubtitle( $s );
646 # Can't cache redirects
648 } elseif ( !empty( $rdfrom ) ) {
649 $sk = $wgUser->getSkin();
650 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
651 $s = wfMsg( 'redirectedfrom', $redir );
652 $wgOut->setSubtitle( $s );
655 # wrap user css and user js in pre and don't parse
656 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
658 $this->mTitle
->getNamespace() == NS_USER
&&
659 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
661 $wgOut->addWikiText( wfMsg('clearyourcache'));
662 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
663 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
665 $imageUrl = $wgStylePath.'/common/images/redirect.png';
666 $targetUrl = $rt->escapeLocalURL();
667 $titleText = htmlspecialchars( $rt->getPrefixedText() );
668 $link = $sk->makeLinkObj( $rt );
670 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
671 '<span class="redirectText">'.$link.'</span>' );
673 } else if ( $pcache ) {
674 # Display content and save to parser cache
675 $wgOut->addPrimaryWikiText( $text, $this );
677 # Display content, don't attempt to save to parser cache
678 $wgOut->addWikiText( $text );
681 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
682 # If we have been passed an &rcid= parameter, we want to give the user a
683 # chance to mark this new article as patrolled.
684 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->isLoggedIn() &&
685 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
687 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
688 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
689 'action=markpatrolled&rcid='.$rcid )
693 # Put link titles into the link cache
694 $wgOut->transformBuffer();
696 # Add link titles as META keywords
697 $wgOut->addMetaTags() ;
699 $this->viewUpdates();
700 wfProfileOut( $fname );
702 $wgUser->clearNotification( $this->mTitle
);
706 * Insert a new empty page record for this article.
707 * This *must* be followed up by creating a revision
708 * and running $this->updateToLatest( $rev_id );
709 * or else the record will be left in a funky state.
710 * Best if all done inside a transaction.
712 * @param Database $dbw
713 * @return int The newly created page_id key
716 function insertOn( &$dbw ) {
717 $fname = 'Article::insertOn';
718 wfProfileIn( $fname );
720 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
721 $dbw->insert( 'page', array(
722 'page_id' => $page_id,
723 'page_namespace' => $this->mTitle
->getNamespace(),
724 'page_title' => $this->mTitle
->getDBkey(),
726 'page_restrictions' => '',
727 'page_is_redirect' => 0, # Will set this shortly...
729 'page_random' => wfRandom(),
730 'page_touched' => $dbw->timestamp(),
731 'page_latest' => 0, # Fill this in shortly...
733 $newid = $dbw->insertId();
735 wfProfileOut( $fname );
740 * Update the page record to point to a newly saved revision.
742 * @param Database $dbw
744 * @param int $lastRevision
745 * @param bool $isRedirect
746 * @return bool true on success, false on failure
749 function updateRevisionOn( &$dbw, $revId, $lastRevision, $isRedirect = false ) {
750 $fname = 'Article::updateToRevision';
751 wfProfileIn( $fname );
753 $dbw->update( 'page',
755 'page_latest' => $revId,
756 'page_touched' => $dbw->timestamp(),
757 'page_is_new' => ($lastRevision == 0),
758 'page_is_redirect' => $isRedirect,
759 ), array( /* WHERE */
760 'page_id' => $this->getId(),
761 'page_latest' => $lastRevision, # Paranoia
765 wfProfileOut( $fname );
766 return ( $dbw->affectedRows() != 0 );
770 * Theoretically we could defer these whole insert and update
771 * functions for after display, but that's taking a big leap
772 * of faith, and we want to be able to report database
773 * errors at some point.
776 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
777 global $wgOut, $wgUser;
778 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
780 $fname = 'Article::insertNewArticle';
782 $this->mCountAdjustment
= $this->isCountable( $text );
784 $ns = $this->mTitle
->getNamespace();
785 $ttl = $this->mTitle
->getDBkey();
786 $text = $this->preSaveTransform( $text );
787 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
789 $dbw =& wfGetDB( DB_MASTER
);
791 # Add the page record; stake our claim on this title!
792 $newid = $this->insertOn( $dbw );
794 # Save the revision text...
795 $revision = new Revision( array(
797 'comment' => $summary,
798 'minor_edit' => $isminor,
801 $revisionId = $revision->insertOn( $dbw );
803 $this->mTitle
->resetArticleID( $newid );
805 # Update the page record with revision data
806 $this->updateRevisionOn( $dbw, $revisionId, 0, $this->isRedirect( $text ) );
808 Article
::onArticleCreate( $this->mTitle
);
809 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
812 if(!$this->mTitle
->userIsWatching()) $this->watch();
814 if ( $this->mTitle
->userIsWatching() ) {
819 # The talk page isn't in the regular link tables, so we need to update manually:
820 $talkns = $ns ^
1; # talk -> normal; normal -> talk
821 $dbw->update( 'page',
822 array( 'page_touched' => $dbw->timestamp($now) ),
823 array( 'page_namespace' => $talkns,
824 'page_title' => $ttl ),
827 # standard deferred updates
828 $this->editUpdates( $text, $summary, $isminor, $now );
830 $oldid = 0; # new article
831 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
835 * Fetch and uncompress the text for a given revision.
836 * Can ask by rev_id number or timestamp (set $field)
838 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
839 $fname = 'Article::fetchRevisionText';
840 $dbw =& wfGetDB( DB_MASTER
);
842 $rev = $dbw->addQuotes( $revId );
844 $rev = 'page_latest';
846 $result = $dbw->query(
847 sprintf( "SELECT old_text, old_flags
849 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
851 $dbw->tableName( 'page' ),
852 $dbw->tableName( 'revision' ),
853 $dbw->tableName( 'text' ),
854 IntVal( $this->mTitle
->getArticleId() ),
858 $obj = $dbw->fetchObject( $result );
859 $dbw->freeResult( $result );
860 $oldtext = Revision
::getRevisionText( $obj );
864 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
865 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
866 if( is_null( $edittime ) ) {
867 $oldtext = $this->fetchRevisionText();
869 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
871 if ($section != '') {
872 if($section=='new') {
873 if($summary) $subject="== {$summary} ==\n\n";
874 $text=$oldtext."\n\n".$subject.$text;
877 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
878 # comments to be stripped as well)
880 $parser=new Parser();
881 $parser->mOutputType
=OT_WIKI
;
882 $oldtext=$parser->strip($oldtext, $striparray, true);
884 # now that we can be sure that no pseudo-sections are in the source,
886 # Unfortunately we can't simply do a preg_replace because that might
887 # replace the wrong section, so we have to use the section counter instead
888 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
889 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
890 $secs[$section*2]=$text."\n\n"; // replace with edited
892 # section 0 is top (intro) section
895 # headline of old section - we need to go through this section
896 # to determine if there are any subsections that now need to
897 # be erased, as the mother section has been replaced with
898 # the text of all subsections.
899 $headline=$secs[$section*2-1];
900 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
903 # determine headline level for wikimarkup headings
904 if(strpos($hlevel,'=')!==false) {
905 $hlevel=strlen($hlevel);
908 $secs[$section*2-1]=''; // erase old headline
911 while(!empty($secs[$count*2-1]) && !$break) {
913 $subheadline=$secs[$count*2-1];
915 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
916 $subhlevel=$matches[1];
917 if(strpos($subhlevel,'=')!==false) {
918 $subhlevel=strlen($subhlevel);
920 if($subhlevel > $hlevel) {
921 // erase old subsections
922 $secs[$count*2-1]='';
925 if($subhlevel <= $hlevel) {
933 $text=join('',$secs);
934 # reinsert the stuff that we stripped out earlier
935 $text=$parser->unstrip($text,$striparray);
936 $text=$parser->unstripNoWiki($text,$striparray);
944 * Change an existing article. Puts the previous version back into the old table, updates RC
945 * and all necessary caches, mostly via the deferred update array.
947 * It is possible to call this function from a command-line script, but note that you should
948 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
950 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
951 global $wgOut, $wgUser;
952 global $wgDBtransactions, $wgMwRedir;
953 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
955 $fname = 'Article::updateArticle';
958 $isminor = ( $minor && $wgUser->isLoggedIn() );
959 if ( $this->isRedirect( $text ) ) {
960 # Remove all content but redirect
961 # This could be done by reconstructing the redirect from a title given by
962 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
964 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
966 $text = $m[1] . "\n";
971 $text = $this->preSaveTransform( $text );
972 $dbw =& wfGetDB( DB_MASTER
);
974 # Update article, but only if changed.
976 # It's important that we either rollback or complete, otherwise an attacker could
977 # overwrite cur entries by sending precisely timed user aborts. Random bored users
978 # could conceivably have the same effect, especially if cur is locked for long periods.
979 if( $wgDBtransactions ) {
980 $dbw->query( 'BEGIN', $fname );
982 $userAbort = ignore_user_abort( true );
985 $oldtext = $this->getContent( true );
987 if ( 0 != strcmp( $text, $oldtext ) ) {
988 $this->mCountAdjustment
= $this->isCountable( $text )
989 - $this->isCountable( $oldtext );
990 $now = wfTimestampNow();
992 $lastRevision = $dbw->selectField(
993 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
995 $revision = new Revision( array(
996 'page' => $this->getId(),
997 'comment' => $summary,
998 'minor_edit' => $isminor,
1001 $revisionId = $revision->insertOn( $dbw );
1004 $ok = $this->updateRevisionOn( $dbw, $revisionId, $lastRevision, $redir );
1007 /* Belated edit conflict! Run away!! */
1010 # Update recentchanges and purge cache and whatnot
1011 $bot = (int)($wgUser->isBot() ||
$forceBot);
1012 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1013 $lastRevision, $this->getTimestamp(), $bot );
1014 Article
::onArticleEdit( $this->mTitle
);
1018 if( $wgDBtransactions ) {
1019 $dbw->query( 'COMMIT', $fname );
1021 ignore_user_abort( $userAbort );
1026 if (!$this->mTitle
->userIsWatching()) $this->watch();
1028 if ( $this->mTitle
->userIsWatching() ) {
1032 # standard deferred updates
1033 $this->editUpdates( $text, $summary, $minor, $now );
1037 # Template namespace
1038 # Purge all articles linking here
1039 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1040 $titles = $this->mTitle
->getLinksTo();
1041 Title
::touchArray( $titles );
1042 if ( $wgUseSquid ) {
1043 foreach ( $titles as $title ) {
1044 $urls[] = $title->getInternalURL();
1050 if ( $wgUseSquid ) {
1051 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1052 $u = new SquidUpdate( $urls );
1053 array_push( $wgPostCommitUpdateList, $u );
1056 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1062 * After we've either updated or inserted the article, update
1063 * the link tables and redirect to the new page.
1065 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1066 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1068 $wgLinkCache = new LinkCache();
1070 $wgLinkCache->forUpdate( true );
1072 # Get old version of link table to allow incremental link updates
1073 $wgLinkCache->preFill( $this->mTitle
);
1074 $wgLinkCache->clear();
1076 # Parse the text and replace links with placeholders
1077 $wgOut = new OutputPage();
1078 $wgOut->addWikiText( $text );
1080 # Look up the links in the DB and add them to the link cache
1081 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1083 if( $this->isRedirect( $text ) )
1087 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1089 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1090 # this will be improved later (to-do)
1092 include_once( "UserMailer.php" );
1093 $wgEnotif = new EmailNotification ();
1094 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1098 * Mark this particular edit as patrolled
1100 function markpatrolled() {
1101 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1102 $wgOut->setRobotpolicy( 'noindex,follow' );
1104 if ( !$wgUseRCPatrol )
1106 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1109 if ( $wgUser->isAnon() )
1111 $wgOut->loginToUse();
1114 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1116 $wgOut->sysopRequired();
1119 $rcid = $wgRequest->getVal( 'rcid' );
1120 if ( !is_null ( $rcid ) )
1122 RecentChange
::markPatrolled( $rcid );
1123 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1124 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1126 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1127 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1131 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1137 * Add this page to $wgUser's watchlist
1142 global $wgUser, $wgOut;
1144 if ( $wgUser->isAnon() ) {
1145 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1148 if ( wfReadOnly() ) {
1149 $wgOut->readOnlyPage();
1153 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1155 $wgUser->addWatch( $this->mTitle
);
1156 $wgUser->saveSettings();
1158 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1160 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1161 $wgOut->setRobotpolicy( 'noindex,follow' );
1163 $link = $this->mTitle
->getPrefixedText();
1164 $text = wfMsg( 'addedwatchtext', $link );
1165 $wgOut->addWikiText( $text );
1168 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1172 * Stop watching a page
1175 function unwatch() {
1177 global $wgUser, $wgOut;
1179 if ( $wgUser->isAnon() ) {
1180 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1183 if ( wfReadOnly() ) {
1184 $wgOut->readOnlyPage();
1188 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1190 $wgUser->removeWatch( $this->mTitle
);
1191 $wgUser->saveSettings();
1193 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1195 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1196 $wgOut->setRobotpolicy( 'noindex,follow' );
1198 $link = $this->mTitle
->getPrefixedText();
1199 $text = wfMsg( 'removedwatchtext', $link );
1200 $wgOut->addWikiText( $text );
1203 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1209 function protect( $limit = 'sysop' ) {
1210 global $wgUser, $wgOut, $wgRequest;
1212 if ( ! $wgUser->isAllowed('protect') ) {
1213 $wgOut->sysopRequired();
1216 if ( wfReadOnly() ) {
1217 $wgOut->readOnlyPage();
1220 $id = $this->mTitle
->getArticleID();
1222 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1226 $confirm = $wgRequest->wasPosted() &&
1227 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1228 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1229 $reason = $wgRequest->getText( 'wpReasonProtect' );
1232 $dbw =& wfGetDB( DB_MASTER
);
1233 $dbw->update( 'page',
1235 'page_touched' => $dbw->timestamp(),
1236 'page_restrictions' => (string)$limit
1237 ), array( /* WHERE */
1239 ), 'Article::protect'
1242 $restrictions = "move=" . $limit;
1244 $restrictions .= ":edit=" . $limit;
1246 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1248 $dbw =& wfGetDB( DB_MASTER
);
1249 $dbw->update( 'page',
1251 'page_touched' => $dbw->timestamp(),
1252 'page_restrictions' => $restrictions
1253 ), array( /* WHERE */
1255 ), 'Article::protect'
1258 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1260 $log = new LogPage( 'protect' );
1261 if ( $limit === '' ) {
1262 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1264 $log->addEntry( 'protect', $this->mTitle
, $reason );
1266 $wgOut->redirect( $this->mTitle
->getFullURL() );
1270 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1271 return $this->confirmProtect( '', $reason, $limit );
1276 * Output protection confirmation dialog
1278 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1279 global $wgOut, $wgUser;
1281 wfDebug( "Article::confirmProtect\n" );
1283 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1284 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1290 if ( $limit === '' ) {
1291 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1292 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1293 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1294 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1295 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1297 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1298 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1299 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1300 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1301 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1302 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1305 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1306 $token = htmlspecialchars( $wgUser->editToken() );
1309 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1313 <label for='wpReasonProtect'>{$protcom}:</label>
1316 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1322 if($moveonly != '') {
1326 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1329 <label for='wpMoveOnly'>{$moveonly}</label>
1337 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1341 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1344 $wgOut->returnToMain( false );
1348 * Unprotect the pages
1350 function unprotect() {
1351 return $this->protect( '' );
1355 * UI entry point for page deletion
1358 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1359 $fname = 'Article::delete';
1360 $confirm = $wgRequest->wasPosted() &&
1361 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1362 $reason = $wgRequest->getText( 'wpReason' );
1364 # This code desperately needs to be totally rewritten
1367 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1368 $wgOut->sysopRequired();
1371 if ( wfReadOnly() ) {
1372 $wgOut->readOnlyPage();
1376 # Better double-check that it hasn't been deleted yet!
1377 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1378 if ( ( '' == trim( $this->mTitle
->getText() ) )
1379 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1380 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1385 $this->doDelete( $reason );
1389 # determine whether this page has earlier revisions
1390 # and insert a warning if it does
1391 # we select the text because it might be useful below
1392 $dbr =& $this->getDB();
1393 $ns = $this->mTitle
->getNamespace();
1394 $title = $this->mTitle
->getDBkey();
1395 $revisions = $dbr->select( array( 'page', 'revision' ),
1398 'page_namespace' => $ns,
1399 'page_title' => $title,
1400 'rev_page = page_id'
1401 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1404 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1405 $skin=$wgUser->getSkin();
1406 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1407 $wgOut->addHTML( $skin->historyLink() .'</b>');
1411 $s = $dbr->selectRow( array( 'page', 'text' ),
1412 array( 'old_text' ),
1414 'page_namespace' => $ns,
1415 'page_title' => $title,
1416 'page_latest = old_id'
1417 ), $fname, $this->getSelectOptions()
1420 if( $s !== false ) {
1421 # if this is a mini-text, we can paste part of it into the deletion reason
1423 #if this is empty, an earlier revision may contain "useful" text
1425 if($s->old_text
!= '') {
1429 $text = Revision
::getRevisionText( $old );
1435 $length=strlen($text);
1437 # this should not happen, since it is not possible to store an empty, new
1438 # page. Let's insert a standard text in case it does, though
1439 if($length == 0 && $reason === '') {
1440 $reason = wfMsg('exblank');
1443 if($length < 500 && $reason === '') {
1445 # comment field=255, let's grep the first 150 to have some user
1447 $text=substr($text,0,150);
1448 # let's strip out newlines and HTML tags
1449 $text=preg_replace('/\"/',"'",$text);
1450 $text=preg_replace('/\</','<',$text);
1451 $text=preg_replace('/\>/','>',$text);
1452 $text=preg_replace("/[\n\r]/",'',$text);
1454 $reason=wfMsg('excontent'). " '".$text;
1456 $reason=wfMsg('exbeforeblank') . " '".$text;
1458 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1463 return $this->confirmDelete( '', $reason );
1467 * Output deletion confirmation dialog
1469 function confirmDelete( $par, $reason ) {
1470 global $wgOut, $wgUser;
1472 wfDebug( "Article::confirmDelete\n" );
1474 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1475 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1476 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1477 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1479 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1481 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1482 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1483 $token = htmlspecialchars( $wgUser->editToken() );
1486 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1490 <label for='wpReason'>{$delcom}:</label>
1493 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1502 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1506 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1509 $wgOut->returnToMain( false );
1514 * Perform a deletion and output success or failure messages
1516 function doDelete( $reason ) {
1517 global $wgOut, $wgUser, $wgContLang;
1518 $fname = 'Article::doDelete';
1519 wfDebug( $fname."\n" );
1521 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1522 if ( $this->doDeleteArticle( $reason ) ) {
1523 $deleted = $this->mTitle
->getPrefixedText();
1525 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1526 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1528 $sk = $wgUser->getSkin();
1529 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1530 ':' . wfMsgForContent( 'dellogpage' ),
1531 wfMsg( 'deletionlog' ) );
1533 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1535 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1536 $wgOut->returnToMain( false );
1537 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1539 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1545 * Back-end article deletion
1546 * Deletes the article with database consistency, writes logs, purges caches
1549 function doDeleteArticle( $reason ) {
1551 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1553 $fname = 'Article::doDeleteArticle';
1554 wfDebug( $fname."\n" );
1556 $dbw =& wfGetDB( DB_MASTER
);
1557 $ns = $this->mTitle
->getNamespace();
1558 $t = $this->mTitle
->getDBkey();
1559 $id = $this->mTitle
->getArticleID();
1561 if ( $t == '' ||
$id == 0 ) {
1565 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1566 array_push( $wgDeferredUpdateList, $u );
1568 $linksTo = $this->mTitle
->getLinksTo();
1571 if ( $wgUseSquid ) {
1573 $this->mTitle
->getInternalURL(),
1574 $this->mTitle
->getInternalURL( 'history' )
1576 foreach ( $linksTo as $linkTo ) {
1577 $urls[] = $linkTo->getInternalURL();
1580 $u = new SquidUpdate( $urls );
1581 array_push( $wgPostCommitUpdateList, $u );
1585 # Client and file cache invalidation
1586 Title
::touchArray( $linksTo );
1588 # Move article and history to the "archive" table
1590 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1592 'ar_namespace' => 'page_namespace',
1593 'ar_title' => 'page_title',
1594 'ar_text' => 'old_text',
1595 'ar_comment' => 'rev_comment',
1596 'ar_user' => 'rev_user',
1597 'ar_user_text' => 'rev_user_text',
1598 'ar_timestamp' => 'rev_timestamp',
1599 'ar_minor_edit' => 'rev_minor_edit',
1602 'page_namespace' => $ns,
1604 'page_id = rev_page AND old_id = rev_id'
1608 # Now that it's safely backed up, delete it
1610 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1611 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1612 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1614 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1616 # Finally, clean up the link tables
1617 $t = $this->mTitle
->getPrefixedDBkey();
1619 Article
::onArticleDelete( $this->mTitle
);
1621 # Insert broken links
1622 $brokenLinks = array();
1623 foreach ( $linksTo as $titleObj ) {
1624 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1625 $linkID = $titleObj->getArticleID();
1626 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1628 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1631 $dbw->delete( 'links', array( 'l_to' => $id ) );
1632 $dbw->delete( 'links', array( 'l_from' => $id ) );
1633 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1634 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1635 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1638 $log = new LogPage( 'delete' );
1639 $log->addEntry( 'delete', $this->mTitle
, $reason );
1641 # Clear the cached article id so the interface doesn't act like we exist
1642 $this->mTitle
->resetArticleID( 0 );
1643 $this->mTitle
->mArticleID
= 0;
1648 * Revert a modification
1650 function rollback() {
1651 global $wgUser, $wgOut, $wgRequest;
1652 $fname = 'Article::rollback';
1654 if ( ! $wgUser->isAllowed('rollback') ) {
1655 $wgOut->sysopRequired();
1658 if ( wfReadOnly() ) {
1659 $wgOut->readOnlyPage( $this->getContent( true ) );
1662 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1663 array( $this->mTitle
->getPrefixedText(),
1664 $wgRequest->getVal( 'from' ) ) ) ) {
1665 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1666 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1669 $dbw =& wfGetDB( DB_MASTER
);
1671 # Enhanced rollback, marks edits rc_bot=1
1672 $bot = $wgRequest->getBool( 'bot' );
1674 # Replace all this user's current edits with the next one down
1675 $tt = $this->mTitle
->getDBKey();
1676 $n = $this->mTitle
->getNamespace();
1678 # Get the last editor, lock table exclusively
1679 $s = $dbw->selectRow( array( 'page', 'revision' ),
1680 array( 'page_id','rev_user','rev_user_text','rev_comment' ),
1681 array( 'page_title' => $tt, 'page_namespace' => $n ),
1682 $fname, 'FOR UPDATE'
1684 if( $s === false ) {
1686 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1689 $ut = $dbw->strencode( $s->cur_user_text
);
1690 $uid = $s->rev_user
;
1693 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1694 if( $from != $s->rev_user_text
) {
1695 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1696 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1697 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1698 htmlspecialchars( $from ),
1699 htmlspecialchars( $s->rev_user_text
) ) );
1700 if($s->rev_comment
!= '') {
1702 wfMsg('editcomment',
1703 htmlspecialchars( $s->rev_comment
) ) );
1708 # Get the last edit not by this guy
1709 $s = $dbw->selectRow( 'old',
1710 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1712 'old_namespace' => $n,
1714 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1715 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1717 if( $s === false ) {
1719 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1720 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1725 # Mark all reverted edits as bot
1726 $dbw->update( 'recentchanges',
1729 ), array( /* WHERE */
1731 "rc_timestamp > '{$s->old_timestamp}'",
1737 $newcomment = wfMsg( 'revertpage', $s->old_user_text
, $from );
1738 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1739 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1740 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1741 $this->updateArticle( Revision
::getRevisionText( $s ), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1742 Article
::onArticleEdit( $this->mTitle
);
1743 $wgOut->returnToMain( false );
1748 * Do standard deferred updates after page view
1751 function viewUpdates() {
1752 global $wgDeferredUpdateList;
1754 if ( 0 != $this->getID() ) {
1755 global $wgDisableCounters;
1756 if( !$wgDisableCounters ) {
1757 Article
::incViewCount( $this->getID() );
1758 $u = new SiteStatsUpdate( 1, 0, 0 );
1759 array_push( $wgDeferredUpdateList, $u );
1763 # Update newtalk status if user is reading their own
1767 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1768 $this->mTitle
->getText() == $wgUser->getName()) {
1769 require_once( 'UserTalkUpdate.php' );
1770 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1775 * Do standard deferred updates after page edit.
1776 * Every 1000th edit, prune the recent changes table.
1778 * @param string $text
1780 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1781 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1782 global $wgMessageCache, $wgUser;
1785 if ( 0 == mt_rand( 0, 999 ) ) {
1786 # Periodically flush old entries from the recentchanges table.
1788 $dbw =& wfGetDB( DB_MASTER
);
1789 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1790 $recentchanges = $dbw->tableName( 'recentchanges' );
1791 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1792 $dbw->query( $sql );
1794 $id = $this->getID();
1795 $title = $this->mTitle
->getPrefixedDBkey();
1796 $shortTitle = $this->mTitle
->getDBkey();
1798 $adj = $this->mCountAdjustment
;
1801 $u = new LinksUpdate( $id, $title );
1802 array_push( $wgDeferredUpdateList, $u );
1803 $u = new SiteStatsUpdate( 0, 1, $adj );
1804 array_push( $wgDeferredUpdateList, $u );
1805 $u = new SearchUpdate( $id, $title, $text );
1806 array_push( $wgDeferredUpdateList, $u );
1808 # If this is another user's talk page,
1809 # create a watchlist entry for this page
1811 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1812 $shortTitle != $wgUser->getName()) {
1813 require_once( 'UserTalkUpdate.php' );
1814 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1817 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1818 $wgMessageCache->replace( $shortTitle, $text );
1824 * @todo document this function
1826 * @param string $oldid Revision ID of this article revision
1828 function setOldSubtitle( $oldid=0 ) {
1829 global $wgLang, $wgOut, $wgUser;
1831 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1832 $sk = $wgUser->getSkin();
1833 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1834 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1835 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1836 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1837 $wgOut->setSubtitle( $r );
1841 * This function is called right before saving the wikitext,
1842 * so we can do things like signatures and links-in-context.
1844 * @param string $text
1846 function preSaveTransform( $text ) {
1847 global $wgParser, $wgUser;
1848 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1851 /* Caching functions */
1854 * checkLastModified returns true if it has taken care of all
1855 * output to the client that is necessary for this request.
1856 * (that is, it has sent a cached version of the page)
1858 function tryFileCache() {
1859 static $called = false;
1861 wfDebug( " tryFileCache() -- called twice!?\n" );
1865 if($this->isFileCacheable()) {
1866 $touched = $this->mTouched
;
1867 $cache = new CacheManager( $this->mTitle
);
1868 if($cache->isFileCacheGood( $touched )) {
1870 wfDebug( " tryFileCache() - about to load\n" );
1871 $cache->loadFromFileCache();
1874 wfDebug( " tryFileCache() - starting buffer\n" );
1875 ob_start( array(&$cache, 'saveToFileCache' ) );
1878 wfDebug( " tryFileCache() - not cacheable\n" );
1883 * Check if the page can be cached
1886 function isFileCacheable() {
1887 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1888 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1890 return $wgUseFileCache
1891 and (!$wgShowIPinHeader)
1892 and ($this->getID() != 0)
1893 and ($wgUser->isAnon())
1894 and (!$wgUser->getNewtalk())
1895 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1896 and (empty( $action ) ||
$action == 'view')
1897 and (!isset($oldid))
1899 and (!isset($redirect))
1900 and (!isset($printable))
1901 and (!$this->mRedirectedFrom
);
1905 * Loads cur_touched and returns a value indicating if it should be used
1908 function checkTouched() {
1909 $fname = 'Article::checkTouched';
1910 $id = $this->getID();
1911 $dbr =& $this->getDB();
1912 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1913 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1914 if( $s !== false ) {
1915 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
1916 return !$s->page_is_redirect
;
1923 * Edit an article without doing all that other stuff
1925 * @param string $text text submitted
1926 * @param string $comment comment submitted
1927 * @param integer $minor whereas it's a minor modification
1929 function quickEdit( $text, $comment = '', $minor = 0 ) {
1931 $fname = 'Article::quickEdit';
1933 #wfDebugDieBacktrace( "$fname called." );
1935 wfProfileIn( $fname );
1937 $dbw =& wfGetDB( DB_MASTER
);
1938 $ns = $this->mTitle
->getNamespace();
1939 $dbkey = $this->mTitle
->getDBkey();
1940 $encDbKey = $dbw->strencode( $dbkey );
1941 $timestamp = $dbw->timestamp();
1943 $dbw->insert( 'text', array(
1944 'old_text' => $text,
1945 'old_flags' => "" ), $fname );
1946 $text_id = $dbw->insertID();
1949 $dbw->update( 'page', array(
1951 'page_touched' => $timestamp,
1952 'page_is_redirect' => $this->isRedirect( $text ) ?
1 : 0,
1953 'page_latest' => $text_id ),
1954 array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1956 $page_id = $dbw->selectField( 'page', 'page_id', array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1959 $dbw->insert( 'revision', array(
1960 'rev_id' => $text_id,
1961 'rev_page' => $page_id,
1962 'rev_comment' => $comment,
1963 'rev_user' => $wgUser->getID(),
1964 'rev_user_text' => $wgUser->getName(),
1965 'rev_timestamp' => $timestamp,
1966 'rev_minor_edit' => intval($minor) ),
1968 wfProfileOut( $fname );
1972 * Used to increment the view counter
1975 * @param integer $id article id
1977 function incViewCount( $id ) {
1978 $id = intval( $id );
1979 global $wgHitcounterUpdateFreq;
1981 $dbw =& wfGetDB( DB_MASTER
);
1982 $pageTable = $dbw->tableName( 'page' );
1983 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1984 $acchitsTable = $dbw->tableName( 'acchits' );
1986 if( $wgHitcounterUpdateFreq <= 1 ){ //
1987 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
1991 # Not important enough to warrant an error page in case of failure
1992 $oldignore = $dbw->ignoreErrors( true );
1994 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
1996 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
1997 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
1998 # Most of the time (or on SQL errors), skip row count check
1999 $dbw->ignoreErrors( $oldignore );
2003 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2004 $row = $dbw->fetchObject( $res );
2005 $rown = intval( $row->n
);
2006 if( $rown >= $wgHitcounterUpdateFreq ){
2007 wfProfileIn( 'Article::incViewCount-collect' );
2008 $old_user_abort = ignore_user_abort( true );
2010 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2011 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2012 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2014 $dbw->query("DELETE FROM $hitcounterTable");
2015 $dbw->query('UNLOCK TABLES');
2016 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2017 'WHERE cur_id = hc_id');
2018 $dbw->query("DROP TABLE $acchitsTable");
2020 ignore_user_abort( $old_user_abort );
2021 wfProfileOut( 'Article::incViewCount-collect' );
2023 $dbw->ignoreErrors( $oldignore );
2027 * The onArticle*() functions are supposed to be a kind of hooks
2028 * which should be called whenever any of the specified actions
2031 * This is a good place to put code to clear caches, for instance.
2033 * This is called on page move and undelete, as well as edit
2035 * @param $title_obj a title object
2038 function onArticleCreate($title_obj) {
2039 global $wgUseSquid, $wgPostCommitUpdateList;
2041 $titles = $title_obj->getBrokenLinksTo();
2044 if ( $wgUseSquid ) {
2045 $urls = $title_obj->getSquidURLs();
2046 foreach ( $titles as $linkTitle ) {
2047 $urls[] = $linkTitle->getInternalURL();
2049 $u = new SquidUpdate( $urls );
2050 array_push( $wgPostCommitUpdateList, $u );
2053 # Clear persistent link cache
2054 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2057 function onArticleDelete($title_obj) {
2058 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2060 function onArticleEdit($title_obj) {
2061 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2066 * Info about this page
2067 * Called for ?action=info when $wgAllowPageInfo is on.
2072 global $wgLang, $wgOut, $wgAllowPageInfo;
2073 $fname = 'Article::info';
2075 if ( !$wgAllowPageInfo ) {
2076 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2080 $page = $this->mTitle
->getSubjectPage();
2082 $wgOut->setPagetitle( $page->getPrefixedText() );
2083 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2085 # first, see if the page exists at all.
2086 $exists = $page->getArticleId() != 0;
2088 $wgOut->addHTML( wfMsg('noarticletext') );
2090 $dbr =& $this->getDB( DB_SLAVE
);
2092 'wl_title' => $page->getDBkey(),
2093 'wl_namespace' => $page->getNamespace() );
2094 $numwatchers = $dbr->selectField(
2099 $this->getSelectOptions() );
2101 $pageInfo = $this->pageCountInfo( $page );
2102 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2104 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2105 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2107 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2109 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2111 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2113 $wgOut->addHTML( '</ul>' );
2119 * Return the total number of edits and number of unique editors
2120 * on a given page. If page does not exist, returns false.
2122 * @param Title $title
2126 function pageCountInfo( $title ) {
2127 $id = $title->getArticleId();
2132 $dbr =& $this->getDB( DB_SLAVE
);
2134 $rev_clause = array( 'rev_page' => $id );
2135 $fname = 'Article::pageCountInfo';
2137 $edits = $dbr->selectField(
2142 $this->getSelectOptions() );
2144 $authors = $dbr->selectField(
2146 'COUNT(DISTINCT rev_user_text)',
2149 $this->getSelectOptions() );
2151 return array( 'edits' => $edits, 'authors' => $authors );
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 );