8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
22 var $mContentLoaded; //!<
25 var $mGoodAdjustment; //!<
29 var $mRedirectedFrom; //!<
30 var $mRedirectUrl; //!<
31 var $mRevIdFetched; //!<
35 var $mTotalAdjustment; //!<
42 * Constructor and clear the article
43 * @param $title Reference to a Title object.
44 * @param $oldId Integer revision ID, null to fetch from request, zero for current
46 function Article( &$title, $oldId = null ) {
47 $this->mTitle
=& $title;
48 $this->mOldId
= $oldId;
53 * Tell the page view functions that this view was redirected
54 * from another page on the wiki.
55 * @param $from Title object.
57 function setRedirectedFrom( $from ) {
58 $this->mRedirectedFrom
= $from;
62 * @return mixed false, Title of in-wiki target, or string with URL
64 function followRedirect() {
65 $text = $this->getContent();
66 $rt = Title
::newFromRedirect( $text );
68 # process if title object is valid and not special:userlogout
70 if( $rt->getInterwiki() != '' ) {
71 if( $rt->isLocal() ) {
72 // Offsite wikis need an HTTP redirect.
74 // This can be hard to reverse and may produce loops,
75 // so they may be disabled in the site configuration.
77 $source = $this->mTitle
->getFullURL( 'redirect=no' );
78 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
81 if( $rt->getNamespace() == NS_SPECIAL
) {
82 // Gotta handle redirects to special pages differently:
83 // Fill the HTTP response "Location" header and ignore
84 // the rest of the page we're on.
86 // This can be hard to reverse, so they may be disabled.
88 if( $rt->isSpecial( 'Userlogout' ) ) {
91 return $rt->getFullURL();
98 // No or invalid redirect
103 * get the title object of the article
105 function getTitle() {
106 return $this->mTitle
;
114 $this->mDataLoaded
= false;
115 $this->mContentLoaded
= false;
117 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
118 $this->mRedirectedFrom
= null; # Title object if set
120 $this->mTimestamp
= $this->mComment
= '';
121 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
122 $this->mTouched
= '19700101000000';
123 $this->mForUpdate
= false;
124 $this->mIsRedirect
= false;
125 $this->mRevIdFetched
= 0;
126 $this->mRedirectUrl
= false;
127 $this->mLatest
= false;
131 * Note that getContent/loadContent do not follow redirects anymore.
132 * If you need to fetch redirectable content easily, try
133 * the shortcut in Article::followContent()
135 * @todo There are still side-effects in this!
136 * In general, you should use the Revision class, not Article,
137 * to fetch text for purposes other than page views.
139 * @return Return the text of this revision
141 function getContent() {
142 global $wgUser, $wgOut;
144 wfProfileIn( __METHOD__
);
146 if ( 0 == $this->getID() ) {
147 wfProfileOut( __METHOD__
);
148 $wgOut->setRobotpolicy( 'noindex,nofollow' );
150 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
151 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
153 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
156 return "<div class='noarticletext'>$ret</div>";
158 $this->loadContent();
159 wfProfileOut( __METHOD__
);
160 return $this->mContent
;
165 * This function returns the text of a section, specified by a number ($section).
166 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
167 * the first section before any such heading (section 0).
169 * If a section contains subsections, these are also returned.
171 * @param $text String: text to look in
172 * @param $section Integer: section number
173 * @return string text of the requested section
176 function getSection($text,$section) {
178 return $wgParser->getSection( $text, $section );
182 * @return int The oldid of the article that is to be shown, 0 for the
185 function getOldID() {
186 if ( is_null( $this->mOldId
) ) {
187 $this->mOldId
= $this->getOldIDFromRequest();
189 return $this->mOldId
;
193 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
195 * @return int The old id for the request
197 function getOldIDFromRequest() {
199 $this->mRedirectUrl
= false;
200 $oldid = $wgRequest->getVal( 'oldid' );
201 if ( isset( $oldid ) ) {
202 $oldid = intval( $oldid );
203 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
204 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
208 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
210 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
211 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
229 * Load the revision (including text) into this object
231 function loadContent() {
232 if ( $this->mContentLoaded
) return;
235 $oldid = $this->getOldID();
237 # Pre-fill content with error message so that if something
238 # fails we'll have something telling us what we intended.
239 $this->mOldId
= $oldid;
240 $this->fetchContent( $oldid );
245 * Fetch a page record with the given conditions
246 * @param Database $dbr
247 * @param array $conditions
250 function pageData( &$dbr, $conditions ) {
263 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
264 $row = $dbr->selectRow( 'page',
267 'Article::pageData' );
268 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
273 * @param Database $dbr
274 * @param Title $title
276 function pageDataFromTitle( &$dbr, $title ) {
277 return $this->pageData( $dbr, array(
278 'page_namespace' => $title->getNamespace(),
279 'page_title' => $title->getDBkey() ) );
283 * @param Database $dbr
286 function pageDataFromId( &$dbr, $id ) {
287 return $this->pageData( $dbr, array( 'page_id' => $id ) );
291 * Set the general counter, title etc data loaded from
294 * @param object $data
297 function loadPageData( $data = 'fromdb' ) {
298 if ( $data === 'fromdb' ) {
299 $dbr =& $this->getDB();
300 $data = $this->pageDataFromId( $dbr, $this->getId() );
303 $lc =& LinkCache
::singleton();
305 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
307 $this->mTitle
->mArticleID
= $data->page_id
;
308 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
309 $this->mTitle
->mRestrictionsLoaded
= true;
311 $this->mCounter
= $data->page_counter
;
312 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
313 $this->mIsRedirect
= $data->page_is_redirect
;
314 $this->mLatest
= $data->page_latest
;
316 if ( is_object( $this->mTitle
) ) {
317 $lc->addBadLinkObj( $this->mTitle
);
319 $this->mTitle
->mArticleID
= 0;
322 $this->mDataLoaded
= true;
326 * Get text of an article from database
327 * Does *NOT* follow redirects.
328 * @param int $oldid 0 for whatever the latest revision is
331 function fetchContent( $oldid = 0 ) {
332 if ( $this->mContentLoaded
) {
333 return $this->mContent
;
336 $dbr =& $this->getDB();
338 # Pre-fill content with error message so that if something
339 # fails we'll have something telling us what we intended.
340 $t = $this->mTitle
->getPrefixedText();
342 $t .= ',oldid='.$oldid;
344 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
347 $revision = Revision
::newFromId( $oldid );
348 if( is_null( $revision ) ) {
349 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
352 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
354 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
357 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
358 $this->loadPageData( $data );
360 if( !$this->mDataLoaded
) {
361 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
363 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
366 $this->loadPageData( $data );
368 $revision = Revision
::newFromId( $this->mLatest
);
369 if( is_null( $revision ) ) {
370 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
375 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
376 // We should instead work with the Revision object when we need it...
377 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
378 //$this->mContent = $revision->getText();
380 $this->mUser
= $revision->getUser();
381 $this->mUserText
= $revision->getUserText();
382 $this->mComment
= $revision->getComment();
383 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
385 $this->mRevIdFetched
= $revision->getID();
386 $this->mContentLoaded
= true;
387 $this->mRevision
=& $revision;
389 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
391 return $this->mContent
;
395 * Read/write accessor to select FOR UPDATE
397 * @param $x Mixed: FIXME
399 function forUpdate( $x = NULL ) {
400 return wfSetVar( $this->mForUpdate
, $x );
404 * Get the database which should be used for reads
409 $ret =& wfGetDB( DB_MASTER
);
414 * Get options for all SELECT statements
416 * @param $options Array: an optional options array which'll be appended to
418 * @return Array: options
420 function getSelectOptions( $options = '' ) {
421 if ( $this->mForUpdate
) {
422 if ( is_array( $options ) ) {
423 $options[] = 'FOR UPDATE';
425 $options = 'FOR UPDATE';
432 * @return int Page ID
435 if( $this->mTitle
) {
436 return $this->mTitle
->getArticleID();
443 * @return bool Whether or not the page exists in the database
446 return $this->getId() != 0;
450 * @return int The view count for the page
452 function getCount() {
453 if ( -1 == $this->mCounter
) {
454 $id = $this->getID();
458 $dbr =& wfGetDB( DB_SLAVE
);
459 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
460 'Article::getCount', $this->getSelectOptions() );
463 return $this->mCounter
;
467 * Determine whether a page would be suitable for being counted as an
468 * article in the site_stats table based on the title & its content
470 * @param $text String: text to analyze
473 function isCountable( $text ) {
474 global $wgUseCommaCount, $wgContentNamespaces;
476 $token = $wgUseCommaCount ?
',' : '[[';
478 array_search( $this->mTitle
->getNamespace(), $wgContentNamespaces ) !== false
479 && ! $this->isRedirect( $text )
480 && in_string( $token, $text );
484 * Tests if the article text represents a redirect
486 * @param $text String: FIXME
489 function isRedirect( $text = false ) {
490 if ( $text === false ) {
491 $this->loadContent();
492 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
494 $titleObj = Title
::newFromRedirect( $text );
496 return $titleObj !== NULL;
500 * Returns true if the currently-referenced revision is the current edit
501 * to this page (and it exists).
504 function isCurrent() {
505 return $this->exists() &&
506 isset( $this->mRevision
) &&
507 $this->mRevision
->isCurrent();
511 * Loads everything except the text
512 * This isn't necessary for all uses, so it's only done if needed.
515 function loadLastEdit() {
516 if ( -1 != $this->mUser
)
519 # New or non-existent articles have no user information
520 $id = $this->getID();
521 if ( 0 == $id ) return;
523 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
524 if( !is_null( $this->mLastRevision
) ) {
525 $this->mUser
= $this->mLastRevision
->getUser();
526 $this->mUserText
= $this->mLastRevision
->getUserText();
527 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
528 $this->mComment
= $this->mLastRevision
->getComment();
529 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
530 $this->mRevIdFetched
= $this->mLastRevision
->getID();
534 function getTimestamp() {
535 // Check if the field has been filled by ParserCache::get()
536 if ( !$this->mTimestamp
) {
537 $this->loadLastEdit();
539 return wfTimestamp(TS_MW
, $this->mTimestamp
);
543 $this->loadLastEdit();
547 function getUserText() {
548 $this->loadLastEdit();
549 return $this->mUserText
;
552 function getComment() {
553 $this->loadLastEdit();
554 return $this->mComment
;
557 function getMinorEdit() {
558 $this->loadLastEdit();
559 return $this->mMinorEdit
;
562 function getRevIdFetched() {
563 $this->loadLastEdit();
564 return $this->mRevIdFetched
;
568 * @todo Document, fixme $offset never used.
569 * @param $limit Integer: default 0.
570 * @param $offset Integer: default 0.
572 function getContributors($limit = 0, $offset = 0) {
573 # XXX: this is expensive; cache this info somewhere.
576 $dbr =& wfGetDB( DB_SLAVE
);
577 $revTable = $dbr->tableName( 'revision' );
578 $userTable = $dbr->tableName( 'user' );
579 $user = $this->getUser();
580 $pageId = $this->getId();
582 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
583 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
584 WHERE rev_page = $pageId
585 AND rev_user != $user
586 GROUP BY rev_user, rev_user_text, user_real_name
587 ORDER BY timestamp DESC";
589 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
590 $sql .= ' '. $this->getSelectOptions();
592 $res = $dbr->query($sql, __METHOD__
);
594 while ( $line = $dbr->fetchObject( $res ) ) {
595 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
598 $dbr->freeResult($res);
603 * This is the default action of the script: just view the page of
607 global $wgUser, $wgOut, $wgRequest, $wgContLang;
608 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
609 global $wgUseTrackbacks, $wgNamespaceRobotPolicies;
610 $sk = $wgUser->getSkin();
612 wfProfileIn( __METHOD__
);
614 $parserCache =& ParserCache
::singleton();
615 $ns = $this->mTitle
->getNamespace(); # shortcut
617 # Get variables from query string
618 $oldid = $this->getOldID();
620 # getOldID may want us to redirect somewhere else
621 if ( $this->mRedirectUrl
) {
622 $wgOut->redirect( $this->mRedirectUrl
);
623 wfProfileOut( __METHOD__
);
627 $diff = $wgRequest->getVal( 'diff' );
628 $rcid = $wgRequest->getVal( 'rcid' );
629 $rdfrom = $wgRequest->getVal( 'rdfrom' );
631 $wgOut->setArticleFlag( true );
632 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
633 $policy = $wgNamespaceRobotPolicies[$ns];
635 $policy = 'index,follow';
637 $wgOut->setRobotpolicy( $policy );
639 # If we got diff and oldid in the query, we want to see a
640 # diff page instead of the article.
642 if ( !is_null( $diff ) ) {
643 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
645 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
646 // DifferenceEngine directly fetched the revision:
647 $this->mRevIdFetched
= $de->mNewid
;
650 // Needed to get the page's current revision
651 $this->loadPageData();
652 if( $diff == 0 ||
$diff == $this->mLatest
) {
653 # Run view updates for current revision only
654 $this->viewUpdates();
656 wfProfileOut( __METHOD__
);
660 if ( empty( $oldid ) && $this->checkTouched() ) {
661 $wgOut->setETag($parserCache->getETag($this, $wgUser));
663 if( $wgOut->checkLastModified( $this->mTouched
) ){
664 wfProfileOut( __METHOD__
);
666 } else if ( $this->tryFileCache() ) {
667 # tell wgOut that output is taken care of
669 $this->viewUpdates();
670 wfProfileOut( __METHOD__
);
675 # Should the parser cache be used?
676 $pcache = $wgEnableParserCache &&
677 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
680 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
681 if ( $wgUser->getOption( 'stubthreshold' ) ) {
682 wfIncrStats( 'pcache_miss_stub' );
685 $wasRedirected = false;
686 if ( isset( $this->mRedirectedFrom
) ) {
687 // This is an internally redirected page view.
688 // We'll need a backlink to the source page for navigation.
689 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
690 $sk = $wgUser->getSkin();
691 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
692 $s = wfMsg( 'redirectedfrom', $redir );
693 $wgOut->setSubtitle( $s );
695 // Set the fragment if one was specified in the redirect
696 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
697 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
698 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
700 $wasRedirected = true;
702 } elseif ( !empty( $rdfrom ) ) {
703 // This is an externally redirected view, from some other wiki.
704 // If it was reported from a trusted site, supply a backlink.
705 global $wgRedirectSources;
706 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
707 $sk = $wgUser->getSkin();
708 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
709 $s = wfMsg( 'redirectedfrom', $redir );
710 $wgOut->setSubtitle( $s );
711 $wasRedirected = true;
717 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
718 wfRunHooks( 'ArticleViewHeader', array( &$this ) );
722 if ( !$outputDone ) {
723 $text = $this->getContent();
724 if ( $text === false ) {
725 # Failed to load, replace text with error message
726 $t = $this->mTitle
->getPrefixedText();
728 $t .= ',oldid='.$oldid;
729 $text = wfMsg( 'missingarticle', $t );
731 $text = wfMsg( 'noarticletext', $t );
735 # Another whitelist check in case oldid is altering the title
736 if ( !$this->mTitle
->userCanRead() ) {
737 $wgOut->loginToUse();
742 # We're looking at an old revision
744 if ( !empty( $oldid ) ) {
745 $wgOut->setRobotpolicy( 'noindex,nofollow' );
746 if( is_null( $this->mRevision
) ) {
747 // FIXME: This would be a nice place to load the 'no such page' text.
749 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
750 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
751 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
752 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
753 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
756 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
757 // and we are allowed to see...
766 * @fixme: this hook doesn't work most of the time, as it doesn't
767 * trigger when the parser cache is used.
769 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
770 $wgOut->setRevisionId( $this->getRevIdFetched() );
771 # wrap user css and user js in pre and don't parse
772 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
775 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
777 $wgOut->addWikiText( wfMsg('clearyourcache'));
778 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
779 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
781 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
782 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
783 # Don't overwrite the subtitle if this was an old revision
784 if( !$wasRedirected && $this->isCurrent() ) {
785 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
787 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
789 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
790 '<span class="redirectText">'.$link.'</span>' );
792 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
793 $wgOut->addParserOutputNoText( $parseout );
794 } else if ( $pcache ) {
795 # Display content and save to parser cache
796 $wgOut->addPrimaryWikiText( $text, $this );
798 # Display content, don't attempt to save to parser cache
799 # Don't show section-edit links on old revisions... this way lies madness.
800 if( !$this->isCurrent() ) {
801 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
803 # Display content and don't save to parser cache
804 $wgOut->addPrimaryWikiText( $text, $this, false );
806 if( !$this->isCurrent() ) {
807 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
811 /* title may have been set from the cache */
812 $t = $wgOut->getPageTitle();
814 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
817 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
818 if( $ns == NS_USER_TALK
&&
819 User
::isIP( $this->mTitle
->getText() ) ) {
820 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
823 # If we have been passed an &rcid= parameter, we want to give the user a
824 # chance to mark this new article as patrolled.
825 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
827 "<div class='patrollink'>" .
828 wfMsg ( 'markaspatrolledlink',
829 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
836 if ($wgUseTrackbacks)
837 $this->addTrackbacks();
839 $this->viewUpdates();
840 wfProfileOut( __METHOD__
);
843 function addTrackbacks() {
844 global $wgOut, $wgUser;
846 $dbr =& wfGetDB(DB_SLAVE
);
848 /* FROM */ 'trackbacks',
849 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
850 /* WHERE */ array('tb_page' => $this->getID())
853 if (!$dbr->numrows($tbs))
857 while ($o = $dbr->fetchObject($tbs)) {
859 if ($wgUser->isAllowed( 'trackback' )) {
860 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
861 . $o->tb_id
. "&token=" . $wgUser->editToken());
862 $rmvtxt = wfMsg('trackbackremove', $delurl);
864 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
871 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
874 function deletetrackback() {
875 global $wgUser, $wgRequest, $wgOut, $wgTitle;
877 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
878 $wgOut->addWikitext(wfMsg('sessionfailure'));
882 if ((!$wgUser->isAllowed('delete'))) {
883 $wgOut->permissionRequired( 'delete' );
888 $wgOut->readOnlyPage();
892 $db =& wfGetDB(DB_MASTER
);
893 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
894 $wgTitle->invalidateCache();
895 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
901 $wgOut->setArticleBodyOnly(true);
906 * Handle action=purge
909 global $wgUser, $wgRequest, $wgOut;
911 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
912 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
916 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
917 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
918 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
919 $msg = str_replace( '$1',
920 "<form method=\"post\" action=\"$action\">\n" .
921 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
924 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
925 $wgOut->setRobotpolicy( 'noindex,nofollow' );
926 $wgOut->addHTML( $msg );
931 * Perform the actions of a page purging
935 // Invalidate the cache
936 $this->mTitle
->invalidateCache();
939 // Commit the transaction before the purge is sent
940 $dbw = wfGetDB( DB_MASTER
);
941 $dbw->immediateCommit();
944 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
951 * Insert a new empty page record for this article.
952 * This *must* be followed up by creating a revision
953 * and running $this->updateToLatest( $rev_id );
954 * or else the record will be left in a funky state.
955 * Best if all done inside a transaction.
957 * @param Database $dbw
958 * @param string $restrictions
959 * @return int The newly created page_id key
962 function insertOn( &$dbw, $restrictions = '' ) {
963 wfProfileIn( __METHOD__
);
965 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
966 $dbw->insert( 'page', array(
967 'page_id' => $page_id,
968 'page_namespace' => $this->mTitle
->getNamespace(),
969 'page_title' => $this->mTitle
->getDBkey(),
971 'page_restrictions' => $restrictions,
972 'page_is_redirect' => 0, # Will set this shortly...
974 'page_random' => wfRandom(),
975 'page_touched' => $dbw->timestamp(),
976 'page_latest' => 0, # Fill this in shortly...
977 'page_len' => 0, # Fill this in shortly...
979 $newid = $dbw->insertId();
981 $this->mTitle
->resetArticleId( $newid );
983 wfProfileOut( __METHOD__
);
988 * Update the page record to point to a newly saved revision.
990 * @param Database $dbw
991 * @param Revision $revision For ID number, and text used to set
992 length and redirect status fields
993 * @param int $lastRevision If given, will not overwrite the page field
994 * when different from the currently set value.
995 * Giving 0 indicates the new page flag should
997 * @param bool $lastRevIsRedirect If given, will optimize adding and
998 * removing rows in redirect table.
999 * @return bool true on success, false on failure
1002 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1003 wfProfileIn( __METHOD__
);
1005 $text = $revision->getText();
1006 $rt = Title
::newFromRedirect( $text );
1008 $conditions = array( 'page_id' => $this->getId() );
1009 if( !is_null( $lastRevision ) ) {
1010 # An extra check against threads stepping on each other
1011 $conditions['page_latest'] = $lastRevision;
1014 $dbw->update( 'page',
1016 'page_latest' => $revision->getId(),
1017 'page_touched' => $dbw->timestamp(),
1018 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1019 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1020 'page_len' => strlen( $text ),
1025 $result = $dbw->affectedRows() != 0;
1028 // FIXME: Should the result from updateRedirectOn() be returned instead?
1029 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1032 wfProfileOut( __METHOD__
);
1037 * Add row to the redirect table if this is a redirect, remove otherwise.
1039 * @param Database $dbw
1040 * @param $redirectTitle a title object pointing to the redirect target,
1041 * or NULL if this is not a redirect
1042 * @param bool $lastRevIsRedirect If given, will optimize adding and
1043 * removing rows in redirect table.
1044 * @return bool true on success, false on failure
1047 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1049 // Always update redirects (target link might have changed)
1050 // Update/Insert if we don't know if the last revision was a redirect or not
1051 // Delete if changing from redirect to non-redirect
1052 $isRedirect = !is_null($redirectTitle);
1053 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1055 wfProfileIn( __METHOD__
);
1059 // This title is a redirect, Add/Update row in the redirect table
1060 $set = array( /* SET */
1061 'rd_namespace' => $redirectTitle->getNamespace(),
1062 'rd_title' => $redirectTitle->getDBkey(),
1063 'rd_from' => $this->getId(),
1066 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1068 // This is not a redirect, remove row from redirect table
1069 $where = array( 'rd_from' => $this->getId() );
1070 $dbw->delete( 'redirect', $where, __METHOD__
);
1073 wfProfileOut( __METHOD__
);
1074 return ( $dbw->affectedRows() != 0 );
1081 * If the given revision is newer than the currently set page_latest,
1082 * update the page record. Otherwise, do nothing.
1084 * @param Database $dbw
1085 * @param Revision $revision
1087 function updateIfNewerOn( &$dbw, $revision ) {
1088 wfProfileIn( __METHOD__
);
1090 $row = $dbw->selectRow(
1091 array( 'revision', 'page' ),
1092 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1094 'page_id' => $this->getId(),
1095 'page_latest=rev_id' ),
1098 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1099 wfProfileOut( __METHOD__
);
1102 $prev = $row->rev_id
;
1103 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1105 # No or missing previous revision; mark the page as new
1107 $lastRevIsRedirect = null;
1110 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1111 wfProfileOut( __METHOD__
);
1116 * @return string Complete article text, or null if error
1118 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1119 wfProfileIn( __METHOD__
);
1121 if( $section == '' ) {
1122 // Whole-page edit; let the text through unmolested.
1124 if( is_null( $edittime ) ) {
1125 $rev = Revision
::newFromTitle( $this->mTitle
);
1127 $dbw =& wfGetDB( DB_MASTER
);
1128 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1130 if( is_null( $rev ) ) {
1131 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1132 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1135 $oldtext = $rev->getText();
1137 if($section=='new') {
1138 if($summary) $subject="== {$summary} ==\n\n";
1139 $text=$oldtext."\n\n".$subject.$text;
1142 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1146 wfProfileOut( __METHOD__
);
1151 * @deprecated use Article::doEdit()
1153 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1154 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1155 ( $isminor ? EDIT_MINOR
: 0 ) |
1156 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1158 # If this is a comment, add the summary as headline
1159 if ( $comment && $summary != "" ) {
1160 $text = "== {$summary} ==\n\n".$text;
1163 $this->doEdit( $text, $summary, $flags );
1165 $dbw =& wfGetDB( DB_MASTER
);
1167 if (!$this->mTitle
->userIsWatching()) {
1173 if ( $this->mTitle
->userIsWatching() ) {
1179 $this->doRedirect( $this->isRedirect( $text ) );
1183 * @deprecated use Article::doEdit()
1185 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1186 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1187 ( $minor ? EDIT_MINOR
: 0 ) |
1188 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1190 $good = $this->doEdit( $text, $summary, $flags );
1192 $dbw =& wfGetDB( DB_MASTER
);
1194 if (!$this->mTitle
->userIsWatching()) {
1200 if ( $this->mTitle
->userIsWatching() ) {
1207 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1215 * Change an existing article or create a new article. Updates RC and all necessary caches,
1216 * optionally via the deferred update array.
1218 * $wgUser must be set before calling this function.
1220 * @param string $text New text
1221 * @param string $summary Edit summary
1222 * @param integer $flags bitfield:
1224 * Article is known or assumed to be non-existent, create a new one
1226 * Article is known or assumed to be pre-existing, update it
1228 * Mark this edit minor, if the user is allowed to do so
1230 * Do not log the change in recentchanges
1232 * Mark the edit a "bot" edit regardless of user rights
1233 * EDIT_DEFER_UPDATES
1234 * Defer some of the updates until the end of index.php
1236 * Fill in blank summaries with generated text where possible
1238 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1239 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1240 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1241 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1242 * to MediaWiki's performance-optimised locking strategy.
1244 * @return bool success
1246 function doEdit( $text, $summary, $flags = 0 ) {
1247 global $wgUser, $wgDBtransactions;
1249 wfProfileIn( __METHOD__
);
1252 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1253 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1255 $flags |
= EDIT_UPDATE
;
1261 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1262 &$summary, $flags & EDIT_MINOR
,
1263 null, null, &$flags ) ) )
1265 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1266 wfProfileOut( __METHOD__
);
1270 # Silently ignore EDIT_MINOR if not allowed
1271 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1272 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1274 $oldtext = $this->getContent();
1275 $oldsize = strlen( $oldtext );
1276 $newsize = strlen( $text );
1278 # Provide autosummaries if one is not provided.
1279 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1280 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1282 $text = $this->preSaveTransform( $text );
1284 $dbw =& wfGetDB( DB_MASTER
);
1285 $now = wfTimestampNow();
1287 if ( $flags & EDIT_UPDATE
) {
1288 # Update article, but only if changed.
1290 # Make sure the revision is either completely inserted or not inserted at all
1291 if( !$wgDBtransactions ) {
1292 $userAbort = ignore_user_abort( true );
1298 if ( 0 != strcmp( $text, $oldtext ) ) {
1299 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1300 - (int)$this->isCountable( $oldtext );
1301 $this->mTotalAdjustment
= 0;
1303 $lastRevision = $dbw->selectField(
1304 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1306 if ( !$lastRevision ) {
1307 # Article gone missing
1308 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1309 wfProfileOut( __METHOD__
);
1313 $revision = new Revision( array(
1314 'page' => $this->getId(),
1315 'comment' => $summary,
1316 'minor_edit' => $isminor,
1321 $revisionId = $revision->insertOn( $dbw );
1324 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1327 /* Belated edit conflict! Run away!! */
1331 # Update recentchanges
1332 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1333 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1334 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1337 # Mark as patrolled if the user can do so and has it set in their options
1338 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1339 RecentChange
::markPatrolled( $rcid );
1345 // Keep the same revision ID, but do some updates on it
1346 $revisionId = $this->getRevIdFetched();
1347 // Update page_touched, this is usually implicit in the page update
1348 // Other cache updates are done in onArticleEdit()
1349 $this->mTitle
->invalidateCache();
1352 if( !$wgDBtransactions ) {
1353 ignore_user_abort( $userAbort );
1357 # Invalidate cache of this article and all pages using this article
1358 # as a template. Partly deferred.
1359 Article
::onArticleEdit( $this->mTitle
);
1361 # Update links tables, site stats, etc.
1362 $changed = ( strcmp( $oldtext, $text ) != 0 );
1363 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1366 # Create new article
1368 # Set statistics members
1369 # We work out if it's countable after PST to avoid counter drift
1370 # when articles are created with {{subst:}}
1371 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1372 $this->mTotalAdjustment
= 1;
1376 # Add the page record; stake our claim on this title!
1377 # This will fail with a database query exception if the article already exists
1378 $newid = $this->insertOn( $dbw );
1380 # Save the revision text...
1381 $revision = new Revision( array(
1383 'comment' => $summary,
1384 'minor_edit' => $isminor,
1387 $revisionId = $revision->insertOn( $dbw );
1389 $this->mTitle
->resetArticleID( $newid );
1391 # Update the page record with revision data
1392 $this->updateRevisionOn( $dbw, $revision, 0 );
1394 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1395 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1396 '', strlen( $text ), $revisionId );
1397 # Mark as patrolled if the user can and has the option set
1398 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1399 RecentChange
::markPatrolled( $rcid );
1404 # Update links, etc.
1405 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1408 Article
::onArticleCreate( $this->mTitle
);
1410 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1411 $summary, $flags & EDIT_MINOR
,
1412 null, null, &$flags ) );
1415 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1419 wfRunHooks( 'ArticleSaveComplete',
1420 array( &$this, &$wgUser, $text,
1421 $summary, $flags & EDIT_MINOR
,
1422 null, null, &$flags ) );
1424 wfProfileOut( __METHOD__
);
1429 * @deprecated wrapper for doRedirect
1431 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1432 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1436 * Output a redirect back to the article.
1437 * This is typically used after an edit.
1439 * @param boolean $noRedir Add redirect=no
1440 * @param string $sectionAnchor section to redirect to, including "#"
1442 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1445 $query = 'redirect=no';
1449 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1453 * Mark this particular edit as patrolled
1455 function markpatrolled() {
1456 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1457 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1459 # Check RC patrol config. option
1460 if( !$wgUseRCPatrol ) {
1461 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1466 if( !$wgUser->isAllowed( 'patrol' ) ) {
1467 $wgOut->permissionRequired( 'patrol' );
1471 $rcid = $wgRequest->getVal( 'rcid' );
1472 if ( !is_null ( $rcid ) ) {
1473 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1474 RecentChange
::markPatrolled( $rcid );
1475 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1476 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1477 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1479 $rcTitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1480 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1483 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1488 * User-interface handler for the "watch" action
1493 global $wgUser, $wgOut;
1495 if ( $wgUser->isAnon() ) {
1496 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1499 if ( wfReadOnly() ) {
1500 $wgOut->readOnlyPage();
1504 if( $this->doWatch() ) {
1505 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1506 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1508 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1509 $text = wfMsg( 'addedwatchtext', $link );
1510 $wgOut->addWikiText( $text );
1513 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1517 * Add this page to $wgUser's watchlist
1518 * @return bool true on successful watch operation
1520 function doWatch() {
1522 if( $wgUser->isAnon() ) {
1526 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1527 $wgUser->addWatch( $this->mTitle
);
1529 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1536 * User interface handler for the "unwatch" action.
1538 function unwatch() {
1540 global $wgUser, $wgOut;
1542 if ( $wgUser->isAnon() ) {
1543 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1546 if ( wfReadOnly() ) {
1547 $wgOut->readOnlyPage();
1551 if( $this->doUnwatch() ) {
1552 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1553 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1555 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1556 $text = wfMsg( 'removedwatchtext', $link );
1557 $wgOut->addWikiText( $text );
1560 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1564 * Stop watching a page
1565 * @return bool true on successful unwatch
1567 function doUnwatch() {
1569 if( $wgUser->isAnon() ) {
1573 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1574 $wgUser->removeWatch( $this->mTitle
);
1576 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1583 * action=protect handler
1585 function protect() {
1586 $form = new ProtectionForm( $this );
1591 * action=unprotect handler (alias)
1593 function unprotect() {
1598 * Update the article's restriction field, and leave a log entry.
1600 * @param array $limit set of restriction keys
1601 * @param string $reason
1602 * @return bool true on success
1604 function updateRestrictions( $limit = array(), $reason = '' ) {
1605 global $wgUser, $wgRestrictionTypes, $wgContLang;
1607 $id = $this->mTitle
->getArticleID();
1608 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1612 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1613 # we expect a single selection, but the schema allows otherwise.
1615 foreach( $wgRestrictionTypes as $action )
1616 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1618 $current = Article
::flattenRestrictions( $current );
1619 $updated = Article
::flattenRestrictions( $limit );
1621 $changed = ( $current != $updated );
1622 $protect = ( $updated != '' );
1624 # If nothing's changed, do nothing
1626 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1628 $dbw =& wfGetDB( DB_MASTER
);
1630 # Prepare a null revision to be added to the history
1631 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1633 $comment .= ": $reason";
1635 $comment .= " [$updated]";
1636 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1637 $nullRevId = $nullRevision->insertOn( $dbw );
1639 # Update page record
1640 $dbw->update( 'page',
1642 'page_touched' => $dbw->timestamp(),
1643 'page_restrictions' => $updated,
1644 'page_latest' => $nullRevId
1645 ), array( /* WHERE */
1647 ), 'Article::protect'
1649 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1651 # Update the protection log
1652 $log = new LogPage( 'protect' );
1654 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1656 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1660 } # End "changed" check
1666 * Take an array of page restrictions and flatten it to a string
1667 * suitable for insertion into the page_restrictions field.
1668 * @param array $limit
1672 function flattenRestrictions( $limit ) {
1673 if( !is_array( $limit ) ) {
1674 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1678 foreach( $limit as $action => $restrictions ) {
1679 if( $restrictions != '' ) {
1680 $bits[] = "$action=$restrictions";
1683 return implode( ':', $bits );
1687 * UI entry point for page deletion
1690 global $wgUser, $wgOut, $wgRequest;
1691 $confirm = $wgRequest->wasPosted() &&
1692 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1693 $reason = $wgRequest->getText( 'wpReason' );
1695 # This code desperately needs to be totally rewritten
1698 if( $wgUser->isAllowed( 'delete' ) ) {
1699 if( $wgUser->isBlocked( !$confirm ) ) {
1700 $wgOut->blockedPage();
1704 $wgOut->permissionRequired( 'delete' );
1708 if( wfReadOnly() ) {
1709 $wgOut->readOnlyPage();
1713 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1715 # Better double-check that it hasn't been deleted yet!
1716 $dbw =& wfGetDB( DB_MASTER
);
1717 $conds = $this->mTitle
->pageCond();
1718 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1719 if ( $latest === false ) {
1720 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1725 $this->doDelete( $reason );
1729 # determine whether this page has earlier revisions
1730 # and insert a warning if it does
1732 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1734 if( count( $authors ) > 1 && !$confirm ) {
1735 $skin=$wgUser->getSkin();
1736 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1739 # If a single user is responsible for all revisions, find out who they are
1740 if ( count( $authors ) == $maxRevisions ) {
1741 // Query bailed out, too many revisions to find out if they're all the same
1742 $authorOfAll = false;
1744 $authorOfAll = reset( $authors );
1745 foreach ( $authors as $author ) {
1746 if ( $authorOfAll != $author ) {
1747 $authorOfAll = false;
1752 # Fetch article text
1753 $rev = Revision
::newFromTitle( $this->mTitle
);
1755 if( !is_null( $rev ) ) {
1756 # if this is a mini-text, we can paste part of it into the deletion reason
1757 $text = $rev->getText();
1759 #if this is empty, an earlier revision may contain "useful" text
1762 $prev = $rev->getPrevious();
1764 $text = $prev->getText();
1769 $length = strlen( $text );
1771 # this should not happen, since it is not possible to store an empty, new
1772 # page. Let's insert a standard text in case it does, though
1773 if( $length == 0 && $reason === '' ) {
1774 $reason = wfMsgForContent( 'exblank' );
1777 if( $length < 500 && $reason === '' ) {
1778 # comment field=255, let's grep the first 150 to have some user
1781 $text = $wgContLang->truncate( $text, 150, '...' );
1783 # let's strip out newlines
1784 $text = preg_replace( "/[\n\r]/", '', $text );
1787 if( $authorOfAll === false ) {
1788 $reason = wfMsgForContent( 'excontent', $text );
1790 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1793 $reason = wfMsgForContent( 'exbeforeblank', $text );
1798 return $this->confirmDelete( '', $reason );
1802 * Get the last N authors
1803 * @param int $num Number of revisions to get
1804 * @param string $revLatest The latest rev_id, selected from the master (optional)
1805 * @return array Array of authors, duplicates not removed
1807 function getLastNAuthors( $num, $revLatest = 0 ) {
1808 wfProfileIn( __METHOD__
);
1810 // First try the slave
1811 // If that doesn't have the latest revision, try the master
1813 $db =& wfGetDB( DB_SLAVE
);
1815 $res = $db->select( array( 'page', 'revision' ),
1816 array( 'rev_id', 'rev_user_text' ),
1818 'page_namespace' => $this->mTitle
->getNamespace(),
1819 'page_title' => $this->mTitle
->getDBkey(),
1820 'rev_page = page_id'
1821 ), __METHOD__
, $this->getSelectOptions( array(
1822 'ORDER BY' => 'rev_timestamp DESC',
1827 wfProfileOut( __METHOD__
);
1830 $row = $db->fetchObject( $res );
1831 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1832 $db =& wfGetDB( DB_MASTER
);
1837 } while ( $continue );
1839 $authors = array( $row->rev_user_text
);
1840 while ( $row = $db->fetchObject( $res ) ) {
1841 $authors[] = $row->rev_user_text
;
1843 wfProfileOut( __METHOD__
);
1848 * Output deletion confirmation dialog
1850 function confirmDelete( $par, $reason ) {
1851 global $wgOut, $wgUser;
1853 wfDebug( "Article::confirmDelete\n" );
1855 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1856 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1857 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1858 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1860 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1862 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1863 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1864 $token = htmlspecialchars( $wgUser->editToken() );
1867 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1871 <label for='wpReason'>{$delcom}:</label>
1874 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1880 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" />
1884 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1887 $wgOut->returnToMain( false );
1892 * Perform a deletion and output success or failure messages
1894 function doDelete( $reason ) {
1895 global $wgOut, $wgUser;
1896 wfDebug( __METHOD__
."\n" );
1898 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1899 if ( $this->doDeleteArticle( $reason ) ) {
1900 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1902 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1903 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1905 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1906 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1908 $wgOut->addWikiText( $text );
1909 $wgOut->returnToMain( false );
1910 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1912 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1918 * Back-end article deletion
1919 * Deletes the article with database consistency, writes logs, purges caches
1922 function doDeleteArticle( $reason ) {
1923 global $wgUseSquid, $wgDeferredUpdateList;
1924 global $wgUseTrackbacks;
1926 wfDebug( __METHOD__
."\n" );
1928 $dbw =& wfGetDB( DB_MASTER
);
1929 $ns = $this->mTitle
->getNamespace();
1930 $t = $this->mTitle
->getDBkey();
1931 $id = $this->mTitle
->getArticleID();
1933 if ( $t == '' ||
$id == 0 ) {
1937 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1938 array_push( $wgDeferredUpdateList, $u );
1940 // For now, shunt the revision data into the archive table.
1941 // Text is *not* removed from the text table; bulk storage
1942 // is left intact to avoid breaking block-compression or
1943 // immutable storage schemes.
1945 // For backwards compatibility, note that some older archive
1946 // table entries will have ar_text and ar_flags fields still.
1948 // In the future, we may keep revisions and mark them with
1949 // the rev_deleted field, which is reserved for this purpose.
1950 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1952 'ar_namespace' => 'page_namespace',
1953 'ar_title' => 'page_title',
1954 'ar_comment' => 'rev_comment',
1955 'ar_user' => 'rev_user',
1956 'ar_user_text' => 'rev_user_text',
1957 'ar_timestamp' => 'rev_timestamp',
1958 'ar_minor_edit' => 'rev_minor_edit',
1959 'ar_rev_id' => 'rev_id',
1960 'ar_text_id' => 'rev_text_id',
1963 'page_id = rev_page'
1967 # Now that it's safely backed up, delete it
1968 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1970 # If using cascading deletes, we can skip some explicit deletes
1971 if ( !$dbw->cascadingDeletes() ) {
1973 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1975 if ($wgUseTrackbacks)
1976 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
1978 # Delete outgoing links
1979 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1980 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1981 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1982 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1983 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1984 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1985 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
1988 # If using cleanup triggers, we can skip some manual deletes
1989 if ( !$dbw->cleanupTriggers() ) {
1991 # Clean up recentchanges entries...
1992 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
1996 Article
::onArticleDelete( $this->mTitle
);
1999 $log = new LogPage( 'delete' );
2000 $log->addEntry( 'delete', $this->mTitle
, $reason );
2002 # Clear the cached article id so the interface doesn't act like we exist
2003 $this->mTitle
->resetArticleID( 0 );
2004 $this->mTitle
->mArticleID
= 0;
2009 * Revert a modification
2011 function rollback() {
2012 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2014 if( $wgUser->isAllowed( 'rollback' ) ) {
2015 if( $wgUser->isBlocked() ) {
2016 $wgOut->blockedPage();
2020 $wgOut->permissionRequired( 'rollback' );
2024 if ( wfReadOnly() ) {
2025 $wgOut->readOnlyPage( $this->getContent() );
2028 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2029 array( $this->mTitle
->getPrefixedText(),
2030 $wgRequest->getVal( 'from' ) ) ) ) {
2031 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2032 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2035 $dbw =& wfGetDB( DB_MASTER
);
2037 # Enhanced rollback, marks edits rc_bot=1
2038 $bot = $wgRequest->getBool( 'bot' );
2040 # Replace all this user's current edits with the next one down
2042 # Get the last editor
2043 $current = Revision
::newFromTitle( $this->mTitle
);
2044 if( is_null( $current ) ) {
2045 # Something wrong... no page?
2046 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2050 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2051 if( $from != $current->getUserText() ) {
2052 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2053 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2054 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2055 htmlspecialchars( $from ),
2056 htmlspecialchars( $current->getUserText() ) ) );
2057 if( $current->getComment() != '') {
2059 wfMsg( 'editcomment',
2060 htmlspecialchars( $current->getComment() ) ) );
2065 # Get the last edit not by this guy
2066 $user = intval( $current->getUser() );
2067 $user_text = $dbw->addQuotes( $current->getUserText() );
2068 $s = $dbw->selectRow( 'revision',
2069 array( 'rev_id', 'rev_timestamp' ),
2071 'rev_page' => $current->getPage(),
2072 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2075 'USE INDEX' => 'page_timestamp',
2076 'ORDER BY' => 'rev_timestamp DESC' )
2078 if( $s === false ) {
2080 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2081 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2087 # Mark all reverted edits as bot
2090 if ( $wgUseRCPatrol ) {
2091 # Mark all reverted edits as patrolled
2092 $set['rc_patrolled'] = 1;
2096 $dbw->update( 'recentchanges', $set,
2098 'rc_cur_id' => $current->getPage(),
2099 'rc_user_text' => $current->getUserText(),
2100 "rc_timestamp > '{$s->rev_timestamp}'",
2105 # Get the edit summary
2106 $target = Revision
::newFromId( $s->rev_id
);
2107 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2108 $newComment = $wgRequest->getText( 'summary', $newComment );
2111 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2112 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2113 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2115 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2117 $wgOut->returnToMain( false );
2122 * Do standard deferred updates after page view
2125 function viewUpdates() {
2126 global $wgDeferredUpdateList;
2128 if ( 0 != $this->getID() ) {
2129 global $wgDisableCounters;
2130 if( !$wgDisableCounters ) {
2131 Article
::incViewCount( $this->getID() );
2132 $u = new SiteStatsUpdate( 1, 0, 0 );
2133 array_push( $wgDeferredUpdateList, $u );
2137 # Update newtalk / watchlist notification status
2139 $wgUser->clearNotification( $this->mTitle
);
2143 * Do standard deferred updates after page edit.
2144 * Update links tables, site stats, search index and message cache.
2145 * Every 1000th edit, prune the recent changes table.
2148 * @param $text New text of the article
2149 * @param $summary Edit summary
2150 * @param $minoredit Minor edit
2151 * @param $timestamp_of_pagechange Timestamp associated with the page change
2152 * @param $newid rev_id value of the new revision
2153 * @param $changed Whether or not the content actually changed
2155 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2156 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2158 wfProfileIn( __METHOD__
);
2161 $options = new ParserOptions
;
2162 $options->setTidy(true);
2163 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2165 # Save it to the parser cache
2166 $parserCache =& ParserCache
::singleton();
2167 $parserCache->save( $poutput, $this, $wgUser );
2169 # Update the links tables
2170 $u = new LinksUpdate( $this->mTitle
, $poutput );
2173 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2175 if ( 0 == mt_rand( 0, 999 ) ) {
2176 # Periodically flush old entries from the recentchanges table.
2179 $dbw =& wfGetDB( DB_MASTER
);
2180 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2181 $recentchanges = $dbw->tableName( 'recentchanges' );
2182 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2183 $dbw->query( $sql );
2187 $id = $this->getID();
2188 $title = $this->mTitle
->getPrefixedDBkey();
2189 $shortTitle = $this->mTitle
->getDBkey();
2192 wfProfileOut( __METHOD__
);
2196 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2197 array_push( $wgDeferredUpdateList, $u );
2198 $u = new SearchUpdate( $id, $title, $text );
2199 array_push( $wgDeferredUpdateList, $u );
2201 # If this is another user's talk page, update newtalk
2202 # Don't do this if $changed = false otherwise some idiot can null-edit a
2203 # load of user talk pages and piss people off, nor if it's a minor edit
2204 # by a properly-flagged bot.
2205 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2206 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2207 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2208 $other = User
::newFromName( $shortTitle );
2209 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2210 // An anonymous user
2211 $other = new User();
2212 $other->setName( $shortTitle );
2215 $other->setNewtalk( true );
2220 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2221 $wgMessageCache->replace( $shortTitle, $text );
2224 wfProfileOut( __METHOD__
);
2228 * Perform article updates on a special page creation.
2230 * @param Revision $rev
2232 * @fixme This is a shitty interface function. Kill it and replace the
2233 * other shitty functions like editUpdates and such so it's not needed
2236 function createUpdates( $rev ) {
2237 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2238 $this->mTotalAdjustment
= 1;
2239 $this->editUpdates( $rev->getText(), $rev->getComment(),
2240 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2244 * Generate the navigation links when browsing through an article revisions
2245 * It shows the information as:
2246 * Revision as of \<date\>; view current revision
2247 * \<- Previous version | Next Version -\>
2250 * @param string $oldid Revision ID of this article revision
2252 function setOldSubtitle( $oldid=0 ) {
2253 global $wgLang, $wgOut, $wgUser;
2255 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2259 $revision = Revision
::newFromId( $oldid );
2261 $current = ( $oldid == $this->mLatest
);
2262 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2263 $sk = $wgUser->getSkin();
2265 ?
wfMsg( 'currentrevisionlink' )
2266 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2269 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2270 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2272 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2273 : wfMsg( 'previousrevision' );
2275 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2277 $nextlink = $current
2278 ?
wfMsg( 'nextrevision' )
2279 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2280 $nextdiff = $current
2282 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2284 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2285 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2287 $r = "\n\t\t\t\t<div id=\"mw-revision-info\">" . wfMsg( 'revision-info', $td, $userlinks ) . "</div>\n" .
2288 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2289 $wgOut->setSubtitle( $r );
2293 * This function is called right before saving the wikitext,
2294 * so we can do things like signatures and links-in-context.
2296 * @param string $text
2298 function preSaveTransform( $text ) {
2299 global $wgParser, $wgUser;
2300 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2303 /* Caching functions */
2306 * checkLastModified returns true if it has taken care of all
2307 * output to the client that is necessary for this request.
2308 * (that is, it has sent a cached version of the page)
2310 function tryFileCache() {
2311 static $called = false;
2313 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2317 if($this->isFileCacheable()) {
2318 $touched = $this->mTouched
;
2319 $cache = new HTMLFileCache( $this->mTitle
);
2320 if($cache->isFileCacheGood( $touched )) {
2321 wfDebug( "Article::tryFileCache(): about to load file\n" );
2322 $cache->loadFromFileCache();
2325 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2326 ob_start( array(&$cache, 'saveToFileCache' ) );
2329 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2334 * Check if the page can be cached
2337 function isFileCacheable() {
2338 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2339 $action = $wgRequest->getVal( 'action' );
2340 $oldid = $wgRequest->getVal( 'oldid' );
2341 $diff = $wgRequest->getVal( 'diff' );
2342 $redirect = $wgRequest->getVal( 'redirect' );
2343 $printable = $wgRequest->getVal( 'printable' );
2345 return $wgUseFileCache
2346 and (!$wgShowIPinHeader)
2347 and ($this->getID() != 0)
2348 and ($wgUser->isAnon())
2349 and (!$wgUser->getNewtalk())
2350 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2351 and (empty( $action ) ||
$action == 'view')
2352 and (!isset($oldid))
2354 and (!isset($redirect))
2355 and (!isset($printable))
2356 and (!$this->mRedirectedFrom
);
2360 * Loads page_touched and returns a value indicating if it should be used
2363 function checkTouched() {
2364 if( !$this->mDataLoaded
) {
2365 $this->loadPageData();
2367 return !$this->mIsRedirect
;
2371 * Get the page_touched field
2373 function getTouched() {
2374 # Ensure that page data has been loaded
2375 if( !$this->mDataLoaded
) {
2376 $this->loadPageData();
2378 return $this->mTouched
;
2382 * Get the page_latest field
2384 function getLatest() {
2385 if ( !$this->mDataLoaded
) {
2386 $this->loadPageData();
2388 return $this->mLatest
;
2392 * Edit an article without doing all that other stuff
2393 * The article must already exist; link tables etc
2394 * are not updated, caches are not flushed.
2396 * @param string $text text submitted
2397 * @param string $comment comment submitted
2398 * @param bool $minor whereas it's a minor modification
2400 function quickEdit( $text, $comment = '', $minor = 0 ) {
2401 wfProfileIn( __METHOD__
);
2403 $dbw =& wfGetDB( DB_MASTER
);
2405 $revision = new Revision( array(
2406 'page' => $this->getId(),
2408 'comment' => $comment,
2409 'minor_edit' => $minor ?
1 : 0,
2411 $revision->insertOn( $dbw );
2412 $this->updateRevisionOn( $dbw, $revision );
2415 wfProfileOut( __METHOD__
);
2419 * Used to increment the view counter
2422 * @param integer $id article id
2424 function incViewCount( $id ) {
2425 $id = intval( $id );
2426 global $wgHitcounterUpdateFreq, $wgDBtype;
2428 $dbw =& wfGetDB( DB_MASTER
);
2429 $pageTable = $dbw->tableName( 'page' );
2430 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2431 $acchitsTable = $dbw->tableName( 'acchits' );
2433 if( $wgHitcounterUpdateFreq <= 1 ) {
2434 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2438 # Not important enough to warrant an error page in case of failure
2439 $oldignore = $dbw->ignoreErrors( true );
2441 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2443 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2444 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2445 # Most of the time (or on SQL errors), skip row count check
2446 $dbw->ignoreErrors( $oldignore );
2450 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2451 $row = $dbw->fetchObject( $res );
2452 $rown = intval( $row->n
);
2453 if( $rown >= $wgHitcounterUpdateFreq ){
2454 wfProfileIn( 'Article::incViewCount-collect' );
2455 $old_user_abort = ignore_user_abort( true );
2457 if ($wgDBtype == 'mysql')
2458 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2459 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2460 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS".
2461 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2463 $dbw->query("DELETE FROM $hitcounterTable");
2464 if ($wgDBtype == 'mysql') {
2465 $dbw->query('UNLOCK TABLES');
2466 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2467 'WHERE page_id = hc_id');
2470 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2471 "FROM $acchitsTable WHERE page_id = hc_id");
2473 $dbw->query("DROP TABLE $acchitsTable");
2475 ignore_user_abort( $old_user_abort );
2476 wfProfileOut( 'Article::incViewCount-collect' );
2478 $dbw->ignoreErrors( $oldignore );
2482 * The onArticle*() functions are supposed to be a kind of hooks
2483 * which should be called whenever any of the specified actions
2486 * This is a good place to put code to clear caches, for instance.
2488 * This is called on page move and undelete, as well as edit
2490 * @param $title_obj a title object
2493 static function onArticleCreate($title) {
2494 # The talk page isn't in the regular link tables, so we need to update manually:
2495 if ( $title->isTalkPage() ) {
2496 $other = $title->getSubjectPage();
2498 $other = $title->getTalkPage();
2500 $other->invalidateCache();
2501 $other->purgeSquid();
2503 $title->touchLinks();
2504 $title->purgeSquid();
2507 static function onArticleDelete( $title ) {
2508 global $wgUseFileCache, $wgMessageCache;
2510 $title->touchLinks();
2511 $title->purgeSquid();
2514 if ( $wgUseFileCache ) {
2515 $cm = new HTMLFileCache( $title );
2516 @unlink
( $cm->fileCacheName() );
2519 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2520 $wgMessageCache->replace( $title->getDBkey(), false );
2525 * Purge caches on page update etc
2527 static function onArticleEdit( $title ) {
2528 global $wgDeferredUpdateList, $wgUseFileCache;
2530 // Invalidate caches of articles which include this page
2531 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2532 $wgDeferredUpdateList[] = $update;
2534 # Purge squid for this page only
2535 $title->purgeSquid();
2538 if ( $wgUseFileCache ) {
2539 $cm = new HTMLFileCache( $title );
2540 @unlink
( $cm->fileCacheName() );
2547 * Info about this page
2548 * Called for ?action=info when $wgAllowPageInfo is on.
2553 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2555 if ( !$wgAllowPageInfo ) {
2556 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2560 $page = $this->mTitle
->getSubjectPage();
2562 $wgOut->setPagetitle( $page->getPrefixedText() );
2563 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2565 # first, see if the page exists at all.
2566 $exists = $page->getArticleId() != 0;
2568 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2569 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2571 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2574 $dbr =& wfGetDB( DB_SLAVE
);
2576 'wl_title' => $page->getDBkey(),
2577 'wl_namespace' => $page->getNamespace() );
2578 $numwatchers = $dbr->selectField(
2583 $this->getSelectOptions() );
2585 $pageInfo = $this->pageCountInfo( $page );
2586 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2588 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2589 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2591 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2593 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2595 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2597 $wgOut->addHTML( '</ul>' );
2603 * Return the total number of edits and number of unique editors
2604 * on a given page. If page does not exist, returns false.
2606 * @param Title $title
2610 function pageCountInfo( $title ) {
2611 $id = $title->getArticleId();
2616 $dbr =& wfGetDB( DB_SLAVE
);
2618 $rev_clause = array( 'rev_page' => $id );
2620 $edits = $dbr->selectField(
2625 $this->getSelectOptions() );
2627 $authors = $dbr->selectField(
2629 'COUNT(DISTINCT rev_user_text)',
2632 $this->getSelectOptions() );
2634 return array( 'edits' => $edits, 'authors' => $authors );
2638 * Return a list of templates used by this article.
2639 * Uses the templatelinks table
2641 * @return array Array of Title objects
2643 function getUsedTemplates() {
2645 $id = $this->mTitle
->getArticleID();
2650 $dbr =& wfGetDB( DB_SLAVE
);
2651 $res = $dbr->select( array( 'templatelinks' ),
2652 array( 'tl_namespace', 'tl_title' ),
2653 array( 'tl_from' => $id ),
2654 'Article:getUsedTemplates' );
2655 if ( false !== $res ) {
2656 if ( $dbr->numRows( $res ) ) {
2657 while ( $row = $dbr->fetchObject( $res ) ) {
2658 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2662 $dbr->freeResult( $res );
2667 * Return an auto-generated summary if the text provided is a redirect.
2669 * @param string $text The wikitext to check
2670 * @return string '' or an appropriate summary
2672 public static function getRedirectAutosummary( $text ) {
2673 $rt = Title
::newFromRedirect( $text );
2674 if( is_object( $rt ) )
2675 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2681 * Return an auto-generated summary if the new text is much shorter than
2684 * @param string $oldtext The previous text of the page
2685 * @param string $text The submitted text of the page
2686 * @return string An appropriate autosummary, or an empty string.
2688 public static function getBlankingAutosummary( $oldtext, $text ) {
2689 if ($oldtext!='' && $text=='') {
2690 return wfMsgForContent('autosumm-blank');
2691 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2692 #Removing more than 90% of the article
2694 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2695 return wfMsgForContent('autosumm-replace', $truncatedtext);
2702 * Return an applicable autosummary if one exists for the given edit.
2703 * @param string $oldtext The previous text of the page.
2704 * @param string $newtext The submitted text of the page.
2705 * @param bitmask $flags A bitmask of flags submitted for the edit.
2706 * @return string An appropriate autosummary, or an empty string.
2708 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2710 # This code is UGLY UGLY UGLY.
2711 # Somebody PLEASE come up with a more elegant way to do it.
2713 #Redirect autosummaries
2714 $summary = self
::getRedirectAutosummary( $newtext );
2719 #Blanking autosummaries
2720 if (!($flags & EDIT_NEW
))
2721 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
2726 #New page autosummaries
2727 if ($flags & EDIT_NEW
&& strlen($newtext)) {
2728 #If they're making a new article, give its text, truncated, in the summary.
2730 $truncatedtext = $wgContLang->truncate( $newtext, max( 0, 200 -
2731 strlen( wfMsgForContent( 'autosumm-new') ) ), '...' );
2732 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );