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 string $text -- used to set length and redirect status if given
745 * @param int $lastRevision -- if given, will not overwrite the page field
746 * when different from the currently set value.
747 * Giving 0 indicates the new page flag should
749 * @return bool true on success, false on failure
752 function updateRevisionOn( &$dbw, $revId, $text = '', $lastRevision = null ) {
753 $fname = 'Article::updateToRevision';
754 wfProfileIn( $fname );
756 $conditions = array( 'page_id' => $this->getId() );
757 if( !is_null( $lastRevision ) ) {
758 # An extra check against threads stepping on each other
759 $conditions['page_latest'] = $lastRevision;
761 $dbw->update( 'page',
763 'page_latest' => $revId,
764 'page_touched' => $dbw->timestamp(),
765 'page_is_new' => ($lastRevision === 0) ?
0 : 1,
766 'page_is_redirect' => Article
::isRedirect( $text ),
767 'page_len' => strlen( $text ),
772 wfProfileOut( $fname );
773 return ( $dbw->affectedRows() != 0 );
777 * Theoretically we could defer these whole insert and update
778 * functions for after display, but that's taking a big leap
779 * of faith, and we want to be able to report database
780 * errors at some point.
783 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
784 global $wgOut, $wgUser;
785 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
787 $fname = 'Article::insertNewArticle';
789 $this->mCountAdjustment
= $this->isCountable( $text );
791 $ns = $this->mTitle
->getNamespace();
792 $ttl = $this->mTitle
->getDBkey();
793 $text = $this->preSaveTransform( $text );
794 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
796 $dbw =& wfGetDB( DB_MASTER
);
798 # Add the page record; stake our claim on this title!
799 $newid = $this->insertOn( $dbw );
801 # Save the revision text...
802 $revision = new Revision( array(
804 'comment' => $summary,
805 'minor_edit' => $isminor,
808 $revisionId = $revision->insertOn( $dbw );
810 $this->mTitle
->resetArticleID( $newid );
812 # Update the page record with revision data
813 $this->updateRevisionOn( $dbw, $revisionId, $text, 0 );
815 Article
::onArticleCreate( $this->mTitle
);
816 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
819 if(!$this->mTitle
->userIsWatching()) $this->watch();
821 if ( $this->mTitle
->userIsWatching() ) {
826 # The talk page isn't in the regular link tables, so we need to update manually:
827 $talkns = $ns ^
1; # talk -> normal; normal -> talk
828 $dbw->update( 'page',
829 array( 'page_touched' => $dbw->timestamp($now) ),
830 array( 'page_namespace' => $talkns,
831 'page_title' => $ttl ),
834 # standard deferred updates
835 $this->editUpdates( $text, $summary, $isminor, $now );
837 $oldid = 0; # new article
838 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
842 * Fetch and uncompress the text for a given revision.
843 * Can ask by rev_id number or timestamp (set $field)
845 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
846 $fname = 'Article::fetchRevisionText';
847 $dbw =& wfGetDB( DB_MASTER
);
849 $rev = $dbw->addQuotes( $revId );
851 $rev = 'page_latest';
853 $result = $dbw->query(
854 sprintf( "SELECT old_text, old_flags
856 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
858 $dbw->tableName( 'page' ),
859 $dbw->tableName( 'revision' ),
860 $dbw->tableName( 'text' ),
861 IntVal( $this->mTitle
->getArticleId() ),
865 $obj = $dbw->fetchObject( $result );
866 $dbw->freeResult( $result );
867 $oldtext = Revision
::getRevisionText( $obj );
871 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
872 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
873 if( is_null( $edittime ) ) {
874 $oldtext = $this->fetchRevisionText();
876 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
878 if ($section != '') {
879 if($section=='new') {
880 if($summary) $subject="== {$summary} ==\n\n";
881 $text=$oldtext."\n\n".$subject.$text;
884 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
885 # comments to be stripped as well)
887 $parser=new Parser();
888 $parser->mOutputType
=OT_WIKI
;
889 $oldtext=$parser->strip($oldtext, $striparray, true);
891 # now that we can be sure that no pseudo-sections are in the source,
893 # Unfortunately we can't simply do a preg_replace because that might
894 # replace the wrong section, so we have to use the section counter instead
895 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
896 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
897 $secs[$section*2]=$text."\n\n"; // replace with edited
899 # section 0 is top (intro) section
902 # headline of old section - we need to go through this section
903 # to determine if there are any subsections that now need to
904 # be erased, as the mother section has been replaced with
905 # the text of all subsections.
906 $headline=$secs[$section*2-1];
907 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
910 # determine headline level for wikimarkup headings
911 if(strpos($hlevel,'=')!==false) {
912 $hlevel=strlen($hlevel);
915 $secs[$section*2-1]=''; // erase old headline
918 while(!empty($secs[$count*2-1]) && !$break) {
920 $subheadline=$secs[$count*2-1];
922 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
923 $subhlevel=$matches[1];
924 if(strpos($subhlevel,'=')!==false) {
925 $subhlevel=strlen($subhlevel);
927 if($subhlevel > $hlevel) {
928 // erase old subsections
929 $secs[$count*2-1]='';
932 if($subhlevel <= $hlevel) {
940 $text=join('',$secs);
941 # reinsert the stuff that we stripped out earlier
942 $text=$parser->unstrip($text,$striparray);
943 $text=$parser->unstripNoWiki($text,$striparray);
951 * Change an existing article. Puts the previous version back into the old table, updates RC
952 * and all necessary caches, mostly via the deferred update array.
954 * It is possible to call this function from a command-line script, but note that you should
955 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
957 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
958 global $wgOut, $wgUser;
959 global $wgDBtransactions, $wgMwRedir;
960 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
962 $fname = 'Article::updateArticle';
965 $isminor = ( $minor && $wgUser->isLoggedIn() );
966 if ( $this->isRedirect( $text ) ) {
967 # Remove all content but redirect
968 # This could be done by reconstructing the redirect from a title given by
969 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
971 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
973 $text = $m[1] . "\n";
978 $text = $this->preSaveTransform( $text );
979 $dbw =& wfGetDB( DB_MASTER
);
981 # Update article, but only if changed.
983 # It's important that we either rollback or complete, otherwise an attacker could
984 # overwrite cur entries by sending precisely timed user aborts. Random bored users
985 # could conceivably have the same effect, especially if cur is locked for long periods.
986 if( $wgDBtransactions ) {
987 $dbw->query( 'BEGIN', $fname );
989 $userAbort = ignore_user_abort( true );
992 $oldtext = $this->getContent( true );
994 if ( 0 != strcmp( $text, $oldtext ) ) {
995 $this->mCountAdjustment
= $this->isCountable( $text )
996 - $this->isCountable( $oldtext );
997 $now = wfTimestampNow();
999 $lastRevision = $dbw->selectField(
1000 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1002 $revision = new Revision( array(
1003 'page' => $this->getId(),
1004 'comment' => $summary,
1005 'minor_edit' => $isminor,
1008 $revisionId = $revision->insertOn( $dbw );
1011 $ok = $this->updateRevisionOn( $dbw, $revisionId, $text, $lastRevision );
1014 /* Belated edit conflict! Run away!! */
1017 # Update recentchanges and purge cache and whatnot
1018 $bot = (int)($wgUser->isBot() ||
$forceBot);
1019 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1020 $lastRevision, $this->getTimestamp(), $bot );
1021 Article
::onArticleEdit( $this->mTitle
);
1025 if( $wgDBtransactions ) {
1026 $dbw->query( 'COMMIT', $fname );
1028 ignore_user_abort( $userAbort );
1033 if (!$this->mTitle
->userIsWatching()) $this->watch();
1035 if ( $this->mTitle
->userIsWatching() ) {
1039 # standard deferred updates
1040 $this->editUpdates( $text, $summary, $minor, $now );
1044 # Template namespace
1045 # Purge all articles linking here
1046 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1047 $titles = $this->mTitle
->getLinksTo();
1048 Title
::touchArray( $titles );
1049 if ( $wgUseSquid ) {
1050 foreach ( $titles as $title ) {
1051 $urls[] = $title->getInternalURL();
1057 if ( $wgUseSquid ) {
1058 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1059 $u = new SquidUpdate( $urls );
1060 array_push( $wgPostCommitUpdateList, $u );
1063 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1069 * After we've either updated or inserted the article, update
1070 * the link tables and redirect to the new page.
1072 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1073 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1075 $wgLinkCache = new LinkCache();
1077 $wgLinkCache->forUpdate( true );
1079 # Get old version of link table to allow incremental link updates
1080 $wgLinkCache->preFill( $this->mTitle
);
1081 $wgLinkCache->clear();
1083 # Parse the text and replace links with placeholders
1084 $wgOut = new OutputPage();
1085 $wgOut->addWikiText( $text );
1087 # Look up the links in the DB and add them to the link cache
1088 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1090 if( $this->isRedirect( $text ) )
1094 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1096 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1097 # this will be improved later (to-do)
1099 include_once( "UserMailer.php" );
1100 $wgEnotif = new EmailNotification ();
1101 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1105 * Mark this particular edit as patrolled
1107 function markpatrolled() {
1108 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1109 $wgOut->setRobotpolicy( 'noindex,follow' );
1111 if ( !$wgUseRCPatrol )
1113 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1116 if ( $wgUser->isAnon() )
1118 $wgOut->loginToUse();
1121 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1123 $wgOut->sysopRequired();
1126 $rcid = $wgRequest->getVal( 'rcid' );
1127 if ( !is_null ( $rcid ) )
1129 RecentChange
::markPatrolled( $rcid );
1130 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1131 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1133 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1134 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1138 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1144 * Add this page to $wgUser's watchlist
1149 global $wgUser, $wgOut;
1151 if ( $wgUser->isAnon() ) {
1152 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1155 if ( wfReadOnly() ) {
1156 $wgOut->readOnlyPage();
1160 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1162 $wgUser->addWatch( $this->mTitle
);
1163 $wgUser->saveSettings();
1165 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1167 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1168 $wgOut->setRobotpolicy( 'noindex,follow' );
1170 $link = $this->mTitle
->getPrefixedText();
1171 $text = wfMsg( 'addedwatchtext', $link );
1172 $wgOut->addWikiText( $text );
1175 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1179 * Stop watching a page
1182 function unwatch() {
1184 global $wgUser, $wgOut;
1186 if ( $wgUser->isAnon() ) {
1187 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1190 if ( wfReadOnly() ) {
1191 $wgOut->readOnlyPage();
1195 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1197 $wgUser->removeWatch( $this->mTitle
);
1198 $wgUser->saveSettings();
1200 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1202 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1203 $wgOut->setRobotpolicy( 'noindex,follow' );
1205 $link = $this->mTitle
->getPrefixedText();
1206 $text = wfMsg( 'removedwatchtext', $link );
1207 $wgOut->addWikiText( $text );
1210 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1216 function protect( $limit = 'sysop' ) {
1217 global $wgUser, $wgOut, $wgRequest;
1219 if ( ! $wgUser->isAllowed('protect') ) {
1220 $wgOut->sysopRequired();
1223 if ( wfReadOnly() ) {
1224 $wgOut->readOnlyPage();
1227 $id = $this->mTitle
->getArticleID();
1229 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1233 $confirm = $wgRequest->wasPosted() &&
1234 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1235 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1236 $reason = $wgRequest->getText( 'wpReasonProtect' );
1239 $dbw =& wfGetDB( DB_MASTER
);
1240 $dbw->update( 'page',
1242 'page_touched' => $dbw->timestamp(),
1243 'page_restrictions' => (string)$limit
1244 ), array( /* WHERE */
1246 ), 'Article::protect'
1249 $restrictions = "move=" . $limit;
1251 $restrictions .= ":edit=" . $limit;
1253 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1255 $dbw =& wfGetDB( DB_MASTER
);
1256 $dbw->update( 'page',
1258 'page_touched' => $dbw->timestamp(),
1259 'page_restrictions' => $restrictions
1260 ), array( /* WHERE */
1262 ), 'Article::protect'
1265 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1267 $log = new LogPage( 'protect' );
1268 if ( $limit === '' ) {
1269 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1271 $log->addEntry( 'protect', $this->mTitle
, $reason );
1273 $wgOut->redirect( $this->mTitle
->getFullURL() );
1277 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1278 return $this->confirmProtect( '', $reason, $limit );
1283 * Output protection confirmation dialog
1285 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1286 global $wgOut, $wgUser;
1288 wfDebug( "Article::confirmProtect\n" );
1290 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1291 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1297 if ( $limit === '' ) {
1298 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1299 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1300 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1301 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1302 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1304 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1305 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1306 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1307 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1308 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1309 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1312 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1313 $token = htmlspecialchars( $wgUser->editToken() );
1316 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1320 <label for='wpReasonProtect'>{$protcom}:</label>
1323 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1329 if($moveonly != '') {
1333 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1336 <label for='wpMoveOnly'>{$moveonly}</label>
1344 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1348 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1351 $wgOut->returnToMain( false );
1355 * Unprotect the pages
1357 function unprotect() {
1358 return $this->protect( '' );
1362 * UI entry point for page deletion
1365 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1366 $fname = 'Article::delete';
1367 $confirm = $wgRequest->wasPosted() &&
1368 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1369 $reason = $wgRequest->getText( 'wpReason' );
1371 # This code desperately needs to be totally rewritten
1374 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1375 $wgOut->sysopRequired();
1378 if ( wfReadOnly() ) {
1379 $wgOut->readOnlyPage();
1383 # Better double-check that it hasn't been deleted yet!
1384 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1385 if ( ( '' == trim( $this->mTitle
->getText() ) )
1386 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1387 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1392 $this->doDelete( $reason );
1396 # determine whether this page has earlier revisions
1397 # and insert a warning if it does
1398 # we select the text because it might be useful below
1399 $dbr =& $this->getDB();
1400 $ns = $this->mTitle
->getNamespace();
1401 $title = $this->mTitle
->getDBkey();
1402 $revisions = $dbr->select( array( 'page', 'revision' ),
1405 'page_namespace' => $ns,
1406 'page_title' => $title,
1407 'rev_page = page_id'
1408 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1411 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1412 $skin=$wgUser->getSkin();
1413 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1414 $wgOut->addHTML( $skin->historyLink() .'</b>');
1418 $s = $dbr->selectRow( array( 'page', 'text' ),
1419 array( 'old_text' ),
1421 'page_namespace' => $ns,
1422 'page_title' => $title,
1423 'page_latest = old_id'
1424 ), $fname, $this->getSelectOptions()
1427 if( $s !== false ) {
1428 # if this is a mini-text, we can paste part of it into the deletion reason
1430 #if this is empty, an earlier revision may contain "useful" text
1432 if($s->old_text
!= '') {
1436 $text = Revision
::getRevisionText( $old );
1442 $length=strlen($text);
1444 # this should not happen, since it is not possible to store an empty, new
1445 # page. Let's insert a standard text in case it does, though
1446 if($length == 0 && $reason === '') {
1447 $reason = wfMsg('exblank');
1450 if($length < 500 && $reason === '') {
1452 # comment field=255, let's grep the first 150 to have some user
1454 $text=substr($text,0,150);
1455 # let's strip out newlines and HTML tags
1456 $text=preg_replace('/\"/',"'",$text);
1457 $text=preg_replace('/\</','<',$text);
1458 $text=preg_replace('/\>/','>',$text);
1459 $text=preg_replace("/[\n\r]/",'',$text);
1461 $reason=wfMsg('excontent'). " '".$text;
1463 $reason=wfMsg('exbeforeblank') . " '".$text;
1465 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1470 return $this->confirmDelete( '', $reason );
1474 * Output deletion confirmation dialog
1476 function confirmDelete( $par, $reason ) {
1477 global $wgOut, $wgUser;
1479 wfDebug( "Article::confirmDelete\n" );
1481 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1482 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1483 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1484 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1486 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1488 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1489 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1490 $token = htmlspecialchars( $wgUser->editToken() );
1493 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1497 <label for='wpReason'>{$delcom}:</label>
1500 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1509 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1513 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1516 $wgOut->returnToMain( false );
1521 * Perform a deletion and output success or failure messages
1523 function doDelete( $reason ) {
1524 global $wgOut, $wgUser, $wgContLang;
1525 $fname = 'Article::doDelete';
1526 wfDebug( $fname."\n" );
1528 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1529 if ( $this->doDeleteArticle( $reason ) ) {
1530 $deleted = $this->mTitle
->getPrefixedText();
1532 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1533 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1535 $sk = $wgUser->getSkin();
1536 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1537 ':' . wfMsgForContent( 'dellogpage' ),
1538 wfMsg( 'deletionlog' ) );
1540 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1542 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1543 $wgOut->returnToMain( false );
1544 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1546 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1552 * Back-end article deletion
1553 * Deletes the article with database consistency, writes logs, purges caches
1556 function doDeleteArticle( $reason ) {
1558 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1560 $fname = 'Article::doDeleteArticle';
1561 wfDebug( $fname."\n" );
1563 $dbw =& wfGetDB( DB_MASTER
);
1564 $ns = $this->mTitle
->getNamespace();
1565 $t = $this->mTitle
->getDBkey();
1566 $id = $this->mTitle
->getArticleID();
1568 if ( $t == '' ||
$id == 0 ) {
1572 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1573 array_push( $wgDeferredUpdateList, $u );
1575 $linksTo = $this->mTitle
->getLinksTo();
1578 if ( $wgUseSquid ) {
1580 $this->mTitle
->getInternalURL(),
1581 $this->mTitle
->getInternalURL( 'history' )
1583 foreach ( $linksTo as $linkTo ) {
1584 $urls[] = $linkTo->getInternalURL();
1587 $u = new SquidUpdate( $urls );
1588 array_push( $wgPostCommitUpdateList, $u );
1592 # Client and file cache invalidation
1593 Title
::touchArray( $linksTo );
1595 # Move article and history to the "archive" table
1597 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1599 'ar_namespace' => 'page_namespace',
1600 'ar_title' => 'page_title',
1601 'ar_text' => 'old_text',
1602 'ar_comment' => 'rev_comment',
1603 'ar_user' => 'rev_user',
1604 'ar_user_text' => 'rev_user_text',
1605 'ar_timestamp' => 'rev_timestamp',
1606 'ar_minor_edit' => 'rev_minor_edit',
1607 'ar_flags' => 'old_flags',
1608 'ar_rev_id' => 'rev_id',
1610 'page_namespace' => $ns,
1612 'page_id = rev_page AND old_id = rev_id'
1616 # Now that it's safely backed up, delete it
1618 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1619 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1620 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1622 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1624 # Finally, clean up the link tables
1625 $t = $this->mTitle
->getPrefixedDBkey();
1627 Article
::onArticleDelete( $this->mTitle
);
1629 # Insert broken links
1630 $brokenLinks = array();
1631 foreach ( $linksTo as $titleObj ) {
1632 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1633 $linkID = $titleObj->getArticleID();
1634 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1636 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1639 $dbw->delete( 'links', array( 'l_to' => $id ) );
1640 $dbw->delete( 'links', array( 'l_from' => $id ) );
1641 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1642 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1643 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1646 $log = new LogPage( 'delete' );
1647 $log->addEntry( 'delete', $this->mTitle
, $reason );
1649 # Clear the cached article id so the interface doesn't act like we exist
1650 $this->mTitle
->resetArticleID( 0 );
1651 $this->mTitle
->mArticleID
= 0;
1656 * Revert a modification
1658 function rollback() {
1659 global $wgUser, $wgOut, $wgRequest;
1660 $fname = 'Article::rollback';
1662 if ( ! $wgUser->isAllowed('rollback') ) {
1663 $wgOut->sysopRequired();
1666 if ( wfReadOnly() ) {
1667 $wgOut->readOnlyPage( $this->getContent( true ) );
1670 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1671 array( $this->mTitle
->getPrefixedText(),
1672 $wgRequest->getVal( 'from' ) ) ) ) {
1673 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1674 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1677 $dbw =& wfGetDB( DB_MASTER
);
1679 # Enhanced rollback, marks edits rc_bot=1
1680 $bot = $wgRequest->getBool( 'bot' );
1682 # Replace all this user's current edits with the next one down
1683 $tt = $this->mTitle
->getDBKey();
1684 $n = $this->mTitle
->getNamespace();
1686 # Get the last editor, lock table exclusively
1688 $current = Revision
::newFromTitle( $this->mTitle
);
1689 if( is_null( $current ) ) {
1690 # Something wrong... no page?
1692 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1696 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1697 if( $from != $current->getUserText() ) {
1698 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1699 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1700 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1701 htmlspecialchars( $from ),
1702 htmlspecialchars( $current->getUserText() ) ) );
1703 if( $current->getComment() != '') {
1705 wfMsg( 'editcomment',
1706 htmlspecialchars( $current->getComment() ) ) );
1711 # Get the last edit not by this guy
1712 $user = IntVal( $current->getUser() );
1713 $user_text = $dbw->addQuotes( $current->getUserText() );
1714 $s = $dbw->selectRow( 'revision',
1715 array( 'rev_id', 'rev_timestamp' ),
1717 'rev_page' => $current->getPage(),
1718 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1721 'USE INDEX' => 'page_timestamp',
1722 'ORDER BY' => 'rev_timestamp DESC' )
1724 if( $s === false ) {
1727 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1728 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1733 # Mark all reverted edits as bot
1734 $dbw->update( 'recentchanges',
1737 ), array( /* WHERE */
1738 'rc_cur_id' => $current->getPage(),
1739 'rc_user_text' => $current->getUserText(),
1740 "rc_timestamp > '{$s->rev_timestamp}'",
1746 $target = Revision
::newFromId( $s->rev_id
);
1747 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1749 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1750 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1751 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1753 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1754 Article
::onArticleEdit( $this->mTitle
);
1757 $wgOut->returnToMain( false );
1762 * Do standard deferred updates after page view
1765 function viewUpdates() {
1766 global $wgDeferredUpdateList;
1768 if ( 0 != $this->getID() ) {
1769 global $wgDisableCounters;
1770 if( !$wgDisableCounters ) {
1771 Article
::incViewCount( $this->getID() );
1772 $u = new SiteStatsUpdate( 1, 0, 0 );
1773 array_push( $wgDeferredUpdateList, $u );
1777 # Update newtalk status if user is reading their own
1781 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1782 $this->mTitle
->getText() == $wgUser->getName()) {
1783 require_once( 'UserTalkUpdate.php' );
1784 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1789 * Do standard deferred updates after page edit.
1790 * Every 1000th edit, prune the recent changes table.
1792 * @param string $text
1794 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1795 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1796 global $wgMessageCache, $wgUser;
1799 if ( 0 == mt_rand( 0, 999 ) ) {
1800 # Periodically flush old entries from the recentchanges table.
1802 $dbw =& wfGetDB( DB_MASTER
);
1803 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1804 $recentchanges = $dbw->tableName( 'recentchanges' );
1805 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1806 $dbw->query( $sql );
1808 $id = $this->getID();
1809 $title = $this->mTitle
->getPrefixedDBkey();
1810 $shortTitle = $this->mTitle
->getDBkey();
1812 $adj = $this->mCountAdjustment
;
1815 $u = new LinksUpdate( $id, $title );
1816 array_push( $wgDeferredUpdateList, $u );
1817 $u = new SiteStatsUpdate( 0, 1, $adj );
1818 array_push( $wgDeferredUpdateList, $u );
1819 $u = new SearchUpdate( $id, $title, $text );
1820 array_push( $wgDeferredUpdateList, $u );
1822 # If this is another user's talk page,
1823 # create a watchlist entry for this page
1825 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1826 $shortTitle != $wgUser->getName()) {
1827 require_once( 'UserTalkUpdate.php' );
1828 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1831 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1832 $wgMessageCache->replace( $shortTitle, $text );
1838 * @todo document this function
1840 * @param string $oldid Revision ID of this article revision
1842 function setOldSubtitle( $oldid=0 ) {
1843 global $wgLang, $wgOut, $wgUser;
1845 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1846 $sk = $wgUser->getSkin();
1847 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1848 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1849 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1850 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1851 $wgOut->setSubtitle( $r );
1855 * This function is called right before saving the wikitext,
1856 * so we can do things like signatures and links-in-context.
1858 * @param string $text
1860 function preSaveTransform( $text ) {
1861 global $wgParser, $wgUser;
1862 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1865 /* Caching functions */
1868 * checkLastModified returns true if it has taken care of all
1869 * output to the client that is necessary for this request.
1870 * (that is, it has sent a cached version of the page)
1872 function tryFileCache() {
1873 static $called = false;
1875 wfDebug( " tryFileCache() -- called twice!?\n" );
1879 if($this->isFileCacheable()) {
1880 $touched = $this->mTouched
;
1881 $cache = new CacheManager( $this->mTitle
);
1882 if($cache->isFileCacheGood( $touched )) {
1884 wfDebug( " tryFileCache() - about to load\n" );
1885 $cache->loadFromFileCache();
1888 wfDebug( " tryFileCache() - starting buffer\n" );
1889 ob_start( array(&$cache, 'saveToFileCache' ) );
1892 wfDebug( " tryFileCache() - not cacheable\n" );
1897 * Check if the page can be cached
1900 function isFileCacheable() {
1901 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1902 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1904 return $wgUseFileCache
1905 and (!$wgShowIPinHeader)
1906 and ($this->getID() != 0)
1907 and ($wgUser->isAnon())
1908 and (!$wgUser->getNewtalk())
1909 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1910 and (empty( $action ) ||
$action == 'view')
1911 and (!isset($oldid))
1913 and (!isset($redirect))
1914 and (!isset($printable))
1915 and (!$this->mRedirectedFrom
);
1919 * Loads cur_touched and returns a value indicating if it should be used
1922 function checkTouched() {
1923 $fname = 'Article::checkTouched';
1924 $id = $this->getID();
1925 $dbr =& $this->getDB();
1926 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1927 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1928 if( $s !== false ) {
1929 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
1930 return !$s->page_is_redirect
;
1937 * Edit an article without doing all that other stuff
1938 * The article must already exist; link tables etc
1939 * are not updated, caches are not flushed.
1941 * @param string $text text submitted
1942 * @param string $comment comment submitted
1943 * @param bool $minor whereas it's a minor modification
1945 function quickEdit( $text, $comment = '', $minor = 0 ) {
1946 $fname = 'Article::quickEdit';
1947 wfProfileIn( $fname );
1949 $dbw =& wfGetDB( DB_MASTER
);
1951 $revision = new Revision( array(
1952 'page' => $this->getId(),
1954 'comment' => $comment,
1955 'minor_edit' => $minor ?
1 : 0,
1957 $revisionId = $revision->insertOn( $dbw );
1958 $this->updateRevisionOn( $dbw, $revisionId, $text );
1961 wfProfileOut( $fname );
1965 * Used to increment the view counter
1968 * @param integer $id article id
1970 function incViewCount( $id ) {
1971 $id = intval( $id );
1972 global $wgHitcounterUpdateFreq;
1974 $dbw =& wfGetDB( DB_MASTER
);
1975 $pageTable = $dbw->tableName( 'page' );
1976 $hitcounterTable = $dbw->tableName( 'hitcounter' );
1977 $acchitsTable = $dbw->tableName( 'acchits' );
1979 if( $wgHitcounterUpdateFreq <= 1 ){ //
1980 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
1984 # Not important enough to warrant an error page in case of failure
1985 $oldignore = $dbw->ignoreErrors( true );
1987 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
1989 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
1990 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
1991 # Most of the time (or on SQL errors), skip row count check
1992 $dbw->ignoreErrors( $oldignore );
1996 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
1997 $row = $dbw->fetchObject( $res );
1998 $rown = intval( $row->n
);
1999 if( $rown >= $wgHitcounterUpdateFreq ){
2000 wfProfileIn( 'Article::incViewCount-collect' );
2001 $old_user_abort = ignore_user_abort( true );
2003 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2004 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2005 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2007 $dbw->query("DELETE FROM $hitcounterTable");
2008 $dbw->query('UNLOCK TABLES');
2009 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2010 'WHERE cur_id = hc_id');
2011 $dbw->query("DROP TABLE $acchitsTable");
2013 ignore_user_abort( $old_user_abort );
2014 wfProfileOut( 'Article::incViewCount-collect' );
2016 $dbw->ignoreErrors( $oldignore );
2020 * The onArticle*() functions are supposed to be a kind of hooks
2021 * which should be called whenever any of the specified actions
2024 * This is a good place to put code to clear caches, for instance.
2026 * This is called on page move and undelete, as well as edit
2028 * @param $title_obj a title object
2031 function onArticleCreate($title_obj) {
2032 global $wgUseSquid, $wgPostCommitUpdateList;
2034 $titles = $title_obj->getBrokenLinksTo();
2037 if ( $wgUseSquid ) {
2038 $urls = $title_obj->getSquidURLs();
2039 foreach ( $titles as $linkTitle ) {
2040 $urls[] = $linkTitle->getInternalURL();
2042 $u = new SquidUpdate( $urls );
2043 array_push( $wgPostCommitUpdateList, $u );
2046 # Clear persistent link cache
2047 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2050 function onArticleDelete($title_obj) {
2051 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2053 function onArticleEdit($title_obj) {
2054 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2059 * Info about this page
2060 * Called for ?action=info when $wgAllowPageInfo is on.
2065 global $wgLang, $wgOut, $wgAllowPageInfo;
2066 $fname = 'Article::info';
2068 if ( !$wgAllowPageInfo ) {
2069 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2073 $page = $this->mTitle
->getSubjectPage();
2075 $wgOut->setPagetitle( $page->getPrefixedText() );
2076 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2078 # first, see if the page exists at all.
2079 $exists = $page->getArticleId() != 0;
2081 $wgOut->addHTML( wfMsg('noarticletext') );
2083 $dbr =& $this->getDB( DB_SLAVE
);
2085 'wl_title' => $page->getDBkey(),
2086 'wl_namespace' => $page->getNamespace() );
2087 $numwatchers = $dbr->selectField(
2092 $this->getSelectOptions() );
2094 $pageInfo = $this->pageCountInfo( $page );
2095 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2097 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2098 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2100 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2102 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2104 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2106 $wgOut->addHTML( '</ul>' );
2112 * Return the total number of edits and number of unique editors
2113 * on a given page. If page does not exist, returns false.
2115 * @param Title $title
2119 function pageCountInfo( $title ) {
2120 $id = $title->getArticleId();
2125 $dbr =& $this->getDB( DB_SLAVE
);
2127 $rev_clause = array( 'rev_page' => $id );
2128 $fname = 'Article::pageCountInfo';
2130 $edits = $dbr->selectField(
2135 $this->getSelectOptions() );
2137 $authors = $dbr->selectField(
2139 'COUNT(DISTINCT rev_user_text)',
2142 $this->getSelectOptions() );
2144 return array( 'edits' => $edits, 'authors' => $authors );