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 # The default policy. Dev note: make sure you change the documentation
636 # in DefaultSettings.php before changing it.
637 $policy = 'index,follow';
639 $wgOut->setRobotpolicy( $policy );
641 # If we got diff and oldid in the query, we want to see a
642 # diff page instead of the article.
644 if ( !is_null( $diff ) ) {
645 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
647 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
648 // DifferenceEngine directly fetched the revision:
649 $this->mRevIdFetched
= $de->mNewid
;
652 // Needed to get the page's current revision
653 $this->loadPageData();
654 if( $diff == 0 ||
$diff == $this->mLatest
) {
655 # Run view updates for current revision only
656 $this->viewUpdates();
658 wfProfileOut( __METHOD__
);
662 if ( empty( $oldid ) && $this->checkTouched() ) {
663 $wgOut->setETag($parserCache->getETag($this, $wgUser));
665 if( $wgOut->checkLastModified( $this->mTouched
) ){
666 wfProfileOut( __METHOD__
);
668 } else if ( $this->tryFileCache() ) {
669 # tell wgOut that output is taken care of
671 $this->viewUpdates();
672 wfProfileOut( __METHOD__
);
677 # Should the parser cache be used?
678 $pcache = $wgEnableParserCache &&
679 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
682 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
683 if ( $wgUser->getOption( 'stubthreshold' ) ) {
684 wfIncrStats( 'pcache_miss_stub' );
687 $wasRedirected = false;
688 if ( isset( $this->mRedirectedFrom
) ) {
689 // This is an internally redirected page view.
690 // We'll need a backlink to the source page for navigation.
691 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
692 $sk = $wgUser->getSkin();
693 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
694 $s = wfMsg( 'redirectedfrom', $redir );
695 $wgOut->setSubtitle( $s );
697 // Set the fragment if one was specified in the redirect
698 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
699 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
700 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
702 $wasRedirected = true;
704 } elseif ( !empty( $rdfrom ) ) {
705 // This is an externally redirected view, from some other wiki.
706 // If it was reported from a trusted site, supply a backlink.
707 global $wgRedirectSources;
708 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
709 $sk = $wgUser->getSkin();
710 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
711 $s = wfMsg( 'redirectedfrom', $redir );
712 $wgOut->setSubtitle( $s );
713 $wasRedirected = true;
719 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
720 wfRunHooks( 'ArticleViewHeader', array( &$this ) );
724 if ( !$outputDone ) {
725 $text = $this->getContent();
726 if ( $text === false ) {
727 # Failed to load, replace text with error message
728 $t = $this->mTitle
->getPrefixedText();
730 $t .= ',oldid='.$oldid;
731 $text = wfMsg( 'missingarticle', $t );
733 $text = wfMsg( 'noarticletext', $t );
737 # Another whitelist check in case oldid is altering the title
738 if ( !$this->mTitle
->userCanRead() ) {
739 $wgOut->loginToUse();
744 # We're looking at an old revision
746 if ( !empty( $oldid ) ) {
747 $wgOut->setRobotpolicy( 'noindex,nofollow' );
748 if( is_null( $this->mRevision
) ) {
749 // FIXME: This would be a nice place to load the 'no such page' text.
751 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
752 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
753 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
754 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
755 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
758 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
759 // and we are allowed to see...
768 * @fixme: this hook doesn't work most of the time, as it doesn't
769 * trigger when the parser cache is used.
771 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
772 $wgOut->setRevisionId( $this->getRevIdFetched() );
773 # wrap user css and user js in pre and don't parse
774 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
777 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
779 $wgOut->addWikiText( wfMsg('clearyourcache'));
780 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
781 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
783 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
784 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
785 # Don't overwrite the subtitle if this was an old revision
786 if( !$wasRedirected && $this->isCurrent() ) {
787 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
789 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
791 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
792 '<span class="redirectText">'.$link.'</span>' );
794 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
795 $wgOut->addParserOutputNoText( $parseout );
796 } else if ( $pcache ) {
797 # Display content and save to parser cache
798 $wgOut->addPrimaryWikiText( $text, $this );
800 # Display content, don't attempt to save to parser cache
801 # Don't show section-edit links on old revisions... this way lies madness.
802 if( !$this->isCurrent() ) {
803 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
805 # Display content and don't save to parser cache
806 $wgOut->addPrimaryWikiText( $text, $this, false );
808 if( !$this->isCurrent() ) {
809 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
813 /* title may have been set from the cache */
814 $t = $wgOut->getPageTitle();
816 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
819 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
820 if( $ns == NS_USER_TALK
&&
821 User
::isIP( $this->mTitle
->getText() ) ) {
822 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
825 # If we have been passed an &rcid= parameter, we want to give the user a
826 # chance to mark this new article as patrolled.
827 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
829 "<div class='patrollink'>" .
830 wfMsg ( 'markaspatrolledlink',
831 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
838 if ($wgUseTrackbacks)
839 $this->addTrackbacks();
841 $this->viewUpdates();
842 wfProfileOut( __METHOD__
);
845 function addTrackbacks() {
846 global $wgOut, $wgUser;
848 $dbr =& wfGetDB(DB_SLAVE
);
850 /* FROM */ 'trackbacks',
851 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
852 /* WHERE */ array('tb_page' => $this->getID())
855 if (!$dbr->numrows($tbs))
859 while ($o = $dbr->fetchObject($tbs)) {
861 if ($wgUser->isAllowed( 'trackback' )) {
862 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
863 . $o->tb_id
. "&token=" . $wgUser->editToken());
864 $rmvtxt = wfMsg('trackbackremove', $delurl);
866 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
873 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
876 function deletetrackback() {
877 global $wgUser, $wgRequest, $wgOut, $wgTitle;
879 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
880 $wgOut->addWikitext(wfMsg('sessionfailure'));
884 if ((!$wgUser->isAllowed('delete'))) {
885 $wgOut->permissionRequired( 'delete' );
890 $wgOut->readOnlyPage();
894 $db =& wfGetDB(DB_MASTER
);
895 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
896 $wgTitle->invalidateCache();
897 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
903 $wgOut->setArticleBodyOnly(true);
908 * Handle action=purge
911 global $wgUser, $wgRequest, $wgOut;
913 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
914 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
918 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
919 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
920 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
921 $msg = str_replace( '$1',
922 "<form method=\"post\" action=\"$action\">\n" .
923 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
926 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
927 $wgOut->setRobotpolicy( 'noindex,nofollow' );
928 $wgOut->addHTML( $msg );
933 * Perform the actions of a page purging
937 // Invalidate the cache
938 $this->mTitle
->invalidateCache();
941 // Commit the transaction before the purge is sent
942 $dbw = wfGetDB( DB_MASTER
);
943 $dbw->immediateCommit();
946 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
953 * Insert a new empty page record for this article.
954 * This *must* be followed up by creating a revision
955 * and running $this->updateToLatest( $rev_id );
956 * or else the record will be left in a funky state.
957 * Best if all done inside a transaction.
959 * @param Database $dbw
960 * @param string $restrictions
961 * @return int The newly created page_id key
964 function insertOn( &$dbw, $restrictions = '' ) {
965 wfProfileIn( __METHOD__
);
967 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
968 $dbw->insert( 'page', array(
969 'page_id' => $page_id,
970 'page_namespace' => $this->mTitle
->getNamespace(),
971 'page_title' => $this->mTitle
->getDBkey(),
973 'page_restrictions' => $restrictions,
974 'page_is_redirect' => 0, # Will set this shortly...
976 'page_random' => wfRandom(),
977 'page_touched' => $dbw->timestamp(),
978 'page_latest' => 0, # Fill this in shortly...
979 'page_len' => 0, # Fill this in shortly...
981 $newid = $dbw->insertId();
983 $this->mTitle
->resetArticleId( $newid );
985 wfProfileOut( __METHOD__
);
990 * Update the page record to point to a newly saved revision.
992 * @param Database $dbw
993 * @param Revision $revision For ID number, and text used to set
994 length and redirect status fields
995 * @param int $lastRevision If given, will not overwrite the page field
996 * when different from the currently set value.
997 * Giving 0 indicates the new page flag should
999 * @param bool $lastRevIsRedirect If given, will optimize adding and
1000 * removing rows in redirect table.
1001 * @return bool true on success, false on failure
1004 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1005 wfProfileIn( __METHOD__
);
1007 $text = $revision->getText();
1008 $rt = Title
::newFromRedirect( $text );
1010 $conditions = array( 'page_id' => $this->getId() );
1011 if( !is_null( $lastRevision ) ) {
1012 # An extra check against threads stepping on each other
1013 $conditions['page_latest'] = $lastRevision;
1016 $dbw->update( 'page',
1018 'page_latest' => $revision->getId(),
1019 'page_touched' => $dbw->timestamp(),
1020 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1021 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1022 'page_len' => strlen( $text ),
1027 $result = $dbw->affectedRows() != 0;
1030 // FIXME: Should the result from updateRedirectOn() be returned instead?
1031 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1034 wfProfileOut( __METHOD__
);
1039 * Add row to the redirect table if this is a redirect, remove otherwise.
1041 * @param Database $dbw
1042 * @param $redirectTitle a title object pointing to the redirect target,
1043 * or NULL if this is not a redirect
1044 * @param bool $lastRevIsRedirect If given, will optimize adding and
1045 * removing rows in redirect table.
1046 * @return bool true on success, false on failure
1049 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1051 // Always update redirects (target link might have changed)
1052 // Update/Insert if we don't know if the last revision was a redirect or not
1053 // Delete if changing from redirect to non-redirect
1054 $isRedirect = !is_null($redirectTitle);
1055 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1057 wfProfileIn( __METHOD__
);
1061 // This title is a redirect, Add/Update row in the redirect table
1062 $set = array( /* SET */
1063 'rd_namespace' => $redirectTitle->getNamespace(),
1064 'rd_title' => $redirectTitle->getDBkey(),
1065 'rd_from' => $this->getId(),
1068 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1070 // This is not a redirect, remove row from redirect table
1071 $where = array( 'rd_from' => $this->getId() );
1072 $dbw->delete( 'redirect', $where, __METHOD__
);
1075 wfProfileOut( __METHOD__
);
1076 return ( $dbw->affectedRows() != 0 );
1083 * If the given revision is newer than the currently set page_latest,
1084 * update the page record. Otherwise, do nothing.
1086 * @param Database $dbw
1087 * @param Revision $revision
1089 function updateIfNewerOn( &$dbw, $revision ) {
1090 wfProfileIn( __METHOD__
);
1092 $row = $dbw->selectRow(
1093 array( 'revision', 'page' ),
1094 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1096 'page_id' => $this->getId(),
1097 'page_latest=rev_id' ),
1100 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1101 wfProfileOut( __METHOD__
);
1104 $prev = $row->rev_id
;
1105 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1107 # No or missing previous revision; mark the page as new
1109 $lastRevIsRedirect = null;
1112 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1113 wfProfileOut( __METHOD__
);
1118 * @return string Complete article text, or null if error
1120 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1121 wfProfileIn( __METHOD__
);
1123 if( $section == '' ) {
1124 // Whole-page edit; let the text through unmolested.
1126 if( is_null( $edittime ) ) {
1127 $rev = Revision
::newFromTitle( $this->mTitle
);
1129 $dbw =& wfGetDB( DB_MASTER
);
1130 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1132 if( is_null( $rev ) ) {
1133 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1134 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1137 $oldtext = $rev->getText();
1139 if( $section == 'new' ) {
1140 # Inserting a new section
1141 $subject = $summary ?
"== {$summary} ==\n\n" : '';
1142 $text = strlen( trim( $oldtext ) ) > 0
1143 ?
"{$oldtext}\n\n{$subject}{$text}"
1144 : "{$subject}{$text}";
1146 # Replacing an existing section; roll out the big guns
1148 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1153 wfProfileOut( __METHOD__
);
1158 * @deprecated use Article::doEdit()
1160 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1161 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1162 ( $isminor ? EDIT_MINOR
: 0 ) |
1163 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1165 # If this is a comment, add the summary as headline
1166 if ( $comment && $summary != "" ) {
1167 $text = "== {$summary} ==\n\n".$text;
1170 $this->doEdit( $text, $summary, $flags );
1172 $dbw =& wfGetDB( DB_MASTER
);
1174 if (!$this->mTitle
->userIsWatching()) {
1180 if ( $this->mTitle
->userIsWatching() ) {
1186 $this->doRedirect( $this->isRedirect( $text ) );
1190 * @deprecated use Article::doEdit()
1192 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1193 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1194 ( $minor ? EDIT_MINOR
: 0 ) |
1195 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1197 $good = $this->doEdit( $text, $summary, $flags );
1199 $dbw =& wfGetDB( DB_MASTER
);
1201 if (!$this->mTitle
->userIsWatching()) {
1207 if ( $this->mTitle
->userIsWatching() ) {
1214 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1222 * Change an existing article or create a new article. Updates RC and all necessary caches,
1223 * optionally via the deferred update array.
1225 * $wgUser must be set before calling this function.
1227 * @param string $text New text
1228 * @param string $summary Edit summary
1229 * @param integer $flags bitfield:
1231 * Article is known or assumed to be non-existent, create a new one
1233 * Article is known or assumed to be pre-existing, update it
1235 * Mark this edit minor, if the user is allowed to do so
1237 * Do not log the change in recentchanges
1239 * Mark the edit a "bot" edit regardless of user rights
1240 * EDIT_DEFER_UPDATES
1241 * Defer some of the updates until the end of index.php
1243 * Fill in blank summaries with generated text where possible
1245 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1246 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1247 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1248 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1249 * to MediaWiki's performance-optimised locking strategy.
1251 * @return bool success
1253 function doEdit( $text, $summary, $flags = 0 ) {
1254 global $wgUser, $wgDBtransactions;
1256 wfProfileIn( __METHOD__
);
1259 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1260 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1262 $flags |
= EDIT_UPDATE
;
1268 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1269 &$summary, $flags & EDIT_MINOR
,
1270 null, null, &$flags ) ) )
1272 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1273 wfProfileOut( __METHOD__
);
1277 # Silently ignore EDIT_MINOR if not allowed
1278 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1279 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1281 $oldtext = $this->getContent();
1282 $oldsize = strlen( $oldtext );
1284 # Provide autosummaries if one is not provided.
1285 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1286 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1288 $text = $this->preSaveTransform( $text );
1289 $newsize = strlen( $text );
1291 $dbw =& wfGetDB( DB_MASTER
);
1292 $now = wfTimestampNow();
1294 if ( $flags & EDIT_UPDATE
) {
1295 # Update article, but only if changed.
1297 # Make sure the revision is either completely inserted or not inserted at all
1298 if( !$wgDBtransactions ) {
1299 $userAbort = ignore_user_abort( true );
1305 if ( 0 != strcmp( $text, $oldtext ) ) {
1306 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1307 - (int)$this->isCountable( $oldtext );
1308 $this->mTotalAdjustment
= 0;
1310 $lastRevision = $dbw->selectField(
1311 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1313 if ( !$lastRevision ) {
1314 # Article gone missing
1315 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1316 wfProfileOut( __METHOD__
);
1320 $revision = new Revision( array(
1321 'page' => $this->getId(),
1322 'comment' => $summary,
1323 'minor_edit' => $isminor,
1328 $revisionId = $revision->insertOn( $dbw );
1331 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1334 /* Belated edit conflict! Run away!! */
1338 # Update recentchanges
1339 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1340 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1341 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1344 # Mark as patrolled if the user can do so
1345 if( $wgUser->isAllowed( 'autopatrol' ) ) {
1346 RecentChange
::markPatrolled( $rcid );
1349 $wgUser->incEditCount();
1353 // Keep the same revision ID, but do some updates on it
1354 $revisionId = $this->getRevIdFetched();
1355 // Update page_touched, this is usually implicit in the page update
1356 // Other cache updates are done in onArticleEdit()
1357 $this->mTitle
->invalidateCache();
1360 if( !$wgDBtransactions ) {
1361 ignore_user_abort( $userAbort );
1365 # Invalidate cache of this article and all pages using this article
1366 # as a template. Partly deferred.
1367 Article
::onArticleEdit( $this->mTitle
);
1369 # Update links tables, site stats, etc.
1370 $changed = ( strcmp( $oldtext, $text ) != 0 );
1371 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1374 # Create new article
1376 # Set statistics members
1377 # We work out if it's countable after PST to avoid counter drift
1378 # when articles are created with {{subst:}}
1379 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1380 $this->mTotalAdjustment
= 1;
1384 # Add the page record; stake our claim on this title!
1385 # This will fail with a database query exception if the article already exists
1386 $newid = $this->insertOn( $dbw );
1388 # Save the revision text...
1389 $revision = new Revision( array(
1391 'comment' => $summary,
1392 'minor_edit' => $isminor,
1395 $revisionId = $revision->insertOn( $dbw );
1397 $this->mTitle
->resetArticleID( $newid );
1399 # Update the page record with revision data
1400 $this->updateRevisionOn( $dbw, $revision, 0 );
1402 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1403 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1404 '', strlen( $text ), $revisionId );
1405 # Mark as patrolled if the user can
1406 if( $wgUser->isAllowed( 'autopatrol' ) ) {
1407 RecentChange
::markPatrolled( $rcid );
1410 $wgUser->incEditCount();
1413 # Update links, etc.
1414 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1417 Article
::onArticleCreate( $this->mTitle
);
1419 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1420 $summary, $flags & EDIT_MINOR
,
1421 null, null, &$flags ) );
1424 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1428 wfRunHooks( 'ArticleSaveComplete',
1429 array( &$this, &$wgUser, $text,
1430 $summary, $flags & EDIT_MINOR
,
1431 null, null, &$flags ) );
1433 wfProfileOut( __METHOD__
);
1438 * @deprecated wrapper for doRedirect
1440 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1441 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1445 * Output a redirect back to the article.
1446 * This is typically used after an edit.
1448 * @param boolean $noRedir Add redirect=no
1449 * @param string $sectionAnchor section to redirect to, including "#"
1451 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1454 $query = 'redirect=no';
1458 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1462 * Mark this particular edit as patrolled
1464 function markpatrolled() {
1465 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1466 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1468 # Check RC patrol config. option
1469 if( !$wgUseRCPatrol ) {
1470 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1475 if( !$wgUser->isAllowed( 'patrol' ) ) {
1476 $wgOut->permissionRequired( 'patrol' );
1480 # If we haven't been given an rc_id value, we can't do anything
1481 $rcid = $wgRequest->getVal( 'rcid' );
1483 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1487 # Handle the 'MarkPatrolled' hook
1488 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1492 $return = SpecialPage
::getTitleFor( 'Recentchanges' );
1493 # If it's left up to us, check that the user is allowed to patrol this edit
1494 # If the user has the "autopatrol" right, then we'll assume there are no
1495 # other conditions stopping them doing so
1496 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1497 $rc = RecentChange
::newFromId( $rcid );
1498 # Graceful error handling, as we've done before here...
1499 # (If the recent change doesn't exist, then it doesn't matter whether
1500 # the user is allowed to patrol it or not; nothing is going to happen
1501 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1502 # The user made this edit, and can't patrol it
1503 # Tell them so, and then back off
1504 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1505 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1506 $wgOut->returnToMain( false, $return );
1511 # Mark the edit as patrolled
1512 RecentChange
::markPatrolled( $rcid );
1513 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1516 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1517 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1518 $wgOut->returnToMain( false, $return );
1522 * User-interface handler for the "watch" action
1527 global $wgUser, $wgOut;
1529 if ( $wgUser->isAnon() ) {
1530 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1533 if ( wfReadOnly() ) {
1534 $wgOut->readOnlyPage();
1538 if( $this->doWatch() ) {
1539 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1540 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1542 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1543 $text = wfMsg( 'addedwatchtext', $link );
1544 $wgOut->addWikiText( $text );
1547 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1551 * Add this page to $wgUser's watchlist
1552 * @return bool true on successful watch operation
1554 function doWatch() {
1556 if( $wgUser->isAnon() ) {
1560 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1561 $wgUser->addWatch( $this->mTitle
);
1563 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1570 * User interface handler for the "unwatch" action.
1572 function unwatch() {
1574 global $wgUser, $wgOut;
1576 if ( $wgUser->isAnon() ) {
1577 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1580 if ( wfReadOnly() ) {
1581 $wgOut->readOnlyPage();
1585 if( $this->doUnwatch() ) {
1586 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1587 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1589 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1590 $text = wfMsg( 'removedwatchtext', $link );
1591 $wgOut->addWikiText( $text );
1594 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1598 * Stop watching a page
1599 * @return bool true on successful unwatch
1601 function doUnwatch() {
1603 if( $wgUser->isAnon() ) {
1607 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1608 $wgUser->removeWatch( $this->mTitle
);
1610 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1617 * action=protect handler
1619 function protect() {
1620 $form = new ProtectionForm( $this );
1625 * action=unprotect handler (alias)
1627 function unprotect() {
1632 * Update the article's restriction field, and leave a log entry.
1634 * @param array $limit set of restriction keys
1635 * @param string $reason
1636 * @return bool true on success
1638 function updateRestrictions( $limit = array(), $reason = '' ) {
1639 global $wgUser, $wgRestrictionTypes, $wgContLang;
1641 $id = $this->mTitle
->getArticleID();
1642 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1646 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1647 # we expect a single selection, but the schema allows otherwise.
1649 foreach( $wgRestrictionTypes as $action )
1650 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1652 $current = Article
::flattenRestrictions( $current );
1653 $updated = Article
::flattenRestrictions( $limit );
1655 $changed = ( $current != $updated );
1656 $protect = ( $updated != '' );
1658 # If nothing's changed, do nothing
1660 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1662 $dbw =& wfGetDB( DB_MASTER
);
1664 # Prepare a null revision to be added to the history
1665 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1667 $comment .= ": $reason";
1669 $comment .= " [$updated]";
1670 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1671 $nullRevId = $nullRevision->insertOn( $dbw );
1673 # Update page record
1674 $dbw->update( 'page',
1676 'page_touched' => $dbw->timestamp(),
1677 'page_restrictions' => $updated,
1678 'page_latest' => $nullRevId
1679 ), array( /* WHERE */
1681 ), 'Article::protect'
1683 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1685 # Update the protection log
1686 $log = new LogPage( 'protect' );
1688 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1690 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1694 } # End "changed" check
1700 * Take an array of page restrictions and flatten it to a string
1701 * suitable for insertion into the page_restrictions field.
1702 * @param array $limit
1706 function flattenRestrictions( $limit ) {
1707 if( !is_array( $limit ) ) {
1708 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1712 foreach( $limit as $action => $restrictions ) {
1713 if( $restrictions != '' ) {
1714 $bits[] = "$action=$restrictions";
1717 return implode( ':', $bits );
1721 * UI entry point for page deletion
1724 global $wgUser, $wgOut, $wgRequest;
1725 $confirm = $wgRequest->wasPosted() &&
1726 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1727 $reason = $wgRequest->getText( 'wpReason' );
1729 # This code desperately needs to be totally rewritten
1732 if( $wgUser->isAllowed( 'delete' ) ) {
1733 if( $wgUser->isBlocked( !$confirm ) ) {
1734 $wgOut->blockedPage();
1738 $wgOut->permissionRequired( 'delete' );
1742 if( wfReadOnly() ) {
1743 $wgOut->readOnlyPage();
1747 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1749 # Better double-check that it hasn't been deleted yet!
1750 $dbw =& wfGetDB( DB_MASTER
);
1751 $conds = $this->mTitle
->pageCond();
1752 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1753 if ( $latest === false ) {
1754 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1759 $this->doDelete( $reason );
1760 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1762 } elseif( $this->mTitle
->userIsWatching() ) {
1768 # determine whether this page has earlier revisions
1769 # and insert a warning if it does
1771 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1773 if( count( $authors ) > 1 && !$confirm ) {
1774 $skin=$wgUser->getSkin();
1775 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1778 # If a single user is responsible for all revisions, find out who they are
1779 if ( count( $authors ) == $maxRevisions ) {
1780 // Query bailed out, too many revisions to find out if they're all the same
1781 $authorOfAll = false;
1783 $authorOfAll = reset( $authors );
1784 foreach ( $authors as $author ) {
1785 if ( $authorOfAll != $author ) {
1786 $authorOfAll = false;
1791 # Fetch article text
1792 $rev = Revision
::newFromTitle( $this->mTitle
);
1794 if( !is_null( $rev ) ) {
1795 # if this is a mini-text, we can paste part of it into the deletion reason
1796 $text = $rev->getText();
1798 #if this is empty, an earlier revision may contain "useful" text
1801 $prev = $rev->getPrevious();
1803 $text = $prev->getText();
1808 $length = strlen( $text );
1810 # this should not happen, since it is not possible to store an empty, new
1811 # page. Let's insert a standard text in case it does, though
1812 if( $length == 0 && $reason === '' ) {
1813 $reason = wfMsgForContent( 'exblank' );
1816 if( $length < 500 && $reason === '' ) {
1817 # comment field=255, let's grep the first 150 to have some user
1820 $text = $wgContLang->truncate( $text, 150, '...' );
1822 # let's strip out newlines
1823 $text = preg_replace( "/[\n\r]/", '', $text );
1826 if( $authorOfAll === false ) {
1827 $reason = wfMsgForContent( 'excontent', $text );
1829 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1832 $reason = wfMsgForContent( 'exbeforeblank', $text );
1837 return $this->confirmDelete( '', $reason );
1841 * Get the last N authors
1842 * @param int $num Number of revisions to get
1843 * @param string $revLatest The latest rev_id, selected from the master (optional)
1844 * @return array Array of authors, duplicates not removed
1846 function getLastNAuthors( $num, $revLatest = 0 ) {
1847 wfProfileIn( __METHOD__
);
1849 // First try the slave
1850 // If that doesn't have the latest revision, try the master
1852 $db =& wfGetDB( DB_SLAVE
);
1854 $res = $db->select( array( 'page', 'revision' ),
1855 array( 'rev_id', 'rev_user_text' ),
1857 'page_namespace' => $this->mTitle
->getNamespace(),
1858 'page_title' => $this->mTitle
->getDBkey(),
1859 'rev_page = page_id'
1860 ), __METHOD__
, $this->getSelectOptions( array(
1861 'ORDER BY' => 'rev_timestamp DESC',
1866 wfProfileOut( __METHOD__
);
1869 $row = $db->fetchObject( $res );
1870 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1871 $db =& wfGetDB( DB_MASTER
);
1876 } while ( $continue );
1878 $authors = array( $row->rev_user_text
);
1879 while ( $row = $db->fetchObject( $res ) ) {
1880 $authors[] = $row->rev_user_text
;
1882 wfProfileOut( __METHOD__
);
1887 * Output deletion confirmation dialog
1889 function confirmDelete( $par, $reason ) {
1890 global $wgOut, $wgUser;
1892 wfDebug( "Article::confirmDelete\n" );
1894 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1895 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1896 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1897 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1899 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1901 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1902 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1903 $token = htmlspecialchars( $wgUser->editToken() );
1904 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
1907 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1911 <label for='wpReason'>{$delcom}:</label>
1914 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
1924 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
1928 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1931 $wgOut->returnToMain( false );
1936 * Perform a deletion and output success or failure messages
1938 function doDelete( $reason ) {
1939 global $wgOut, $wgUser;
1940 wfDebug( __METHOD__
."\n" );
1942 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1943 if ( $this->doDeleteArticle( $reason ) ) {
1944 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1946 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1947 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1949 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1950 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1952 $wgOut->addWikiText( $text );
1953 $wgOut->returnToMain( false );
1954 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1956 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1962 * Back-end article deletion
1963 * Deletes the article with database consistency, writes logs, purges caches
1966 function doDeleteArticle( $reason ) {
1967 global $wgUseSquid, $wgDeferredUpdateList;
1968 global $wgUseTrackbacks;
1970 wfDebug( __METHOD__
."\n" );
1972 $dbw =& wfGetDB( DB_MASTER
);
1973 $ns = $this->mTitle
->getNamespace();
1974 $t = $this->mTitle
->getDBkey();
1975 $id = $this->mTitle
->getArticleID();
1977 if ( $t == '' ||
$id == 0 ) {
1981 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1982 array_push( $wgDeferredUpdateList, $u );
1984 // For now, shunt the revision data into the archive table.
1985 // Text is *not* removed from the text table; bulk storage
1986 // is left intact to avoid breaking block-compression or
1987 // immutable storage schemes.
1989 // For backwards compatibility, note that some older archive
1990 // table entries will have ar_text and ar_flags fields still.
1992 // In the future, we may keep revisions and mark them with
1993 // the rev_deleted field, which is reserved for this purpose.
1994 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1996 'ar_namespace' => 'page_namespace',
1997 'ar_title' => 'page_title',
1998 'ar_comment' => 'rev_comment',
1999 'ar_user' => 'rev_user',
2000 'ar_user_text' => 'rev_user_text',
2001 'ar_timestamp' => 'rev_timestamp',
2002 'ar_minor_edit' => 'rev_minor_edit',
2003 'ar_rev_id' => 'rev_id',
2004 'ar_text_id' => 'rev_text_id',
2005 'ar_text' => '\'\'', // Be explicit to appease
2006 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2009 'page_id = rev_page'
2013 # Now that it's safely backed up, delete it
2014 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2016 # If using cascading deletes, we can skip some explicit deletes
2017 if ( !$dbw->cascadingDeletes() ) {
2019 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2021 if ($wgUseTrackbacks)
2022 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2024 # Delete outgoing links
2025 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2026 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2027 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2028 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2029 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2030 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2031 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2034 # If using cleanup triggers, we can skip some manual deletes
2035 if ( !$dbw->cleanupTriggers() ) {
2037 # Clean up recentchanges entries...
2038 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2042 Article
::onArticleDelete( $this->mTitle
);
2045 $log = new LogPage( 'delete' );
2046 $log->addEntry( 'delete', $this->mTitle
, $reason );
2048 # Clear the cached article id so the interface doesn't act like we exist
2049 $this->mTitle
->resetArticleID( 0 );
2050 $this->mTitle
->mArticleID
= 0;
2055 * Revert a modification
2057 function rollback() {
2058 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2060 if( $wgUser->isAllowed( 'rollback' ) ) {
2061 if( $wgUser->isBlocked() ) {
2062 $wgOut->blockedPage();
2066 $wgOut->permissionRequired( 'rollback' );
2070 if ( wfReadOnly() ) {
2071 $wgOut->readOnlyPage( $this->getContent() );
2074 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2075 array( $this->mTitle
->getPrefixedText(),
2076 $wgRequest->getVal( 'from' ) ) ) ) {
2077 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2078 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2081 $dbw =& wfGetDB( DB_MASTER
);
2083 # Enhanced rollback, marks edits rc_bot=1
2084 $bot = $wgRequest->getBool( 'bot' );
2086 # Replace all this user's current edits with the next one down
2088 # Get the last editor
2089 $current = Revision
::newFromTitle( $this->mTitle
);
2090 if( is_null( $current ) ) {
2091 # Something wrong... no page?
2092 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2096 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2097 if( $from != $current->getUserText() ) {
2098 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2099 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2100 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2101 htmlspecialchars( $from ),
2102 htmlspecialchars( $current->getUserText() ) ) );
2103 if( $current->getComment() != '') {
2105 wfMsg( 'editcomment',
2106 htmlspecialchars( $current->getComment() ) ) );
2111 # Get the last edit not by this guy
2112 $user = intval( $current->getUser() );
2113 $user_text = $dbw->addQuotes( $current->getUserText() );
2114 $s = $dbw->selectRow( 'revision',
2115 array( 'rev_id', 'rev_timestamp' ),
2117 'rev_page' => $current->getPage(),
2118 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2121 'USE INDEX' => 'page_timestamp',
2122 'ORDER BY' => 'rev_timestamp DESC' )
2124 if( $s === false ) {
2126 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2127 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2133 # Mark all reverted edits as bot
2136 if ( $wgUseRCPatrol ) {
2137 # Mark all reverted edits as patrolled
2138 $set['rc_patrolled'] = 1;
2142 $dbw->update( 'recentchanges', $set,
2144 'rc_cur_id' => $current->getPage(),
2145 'rc_user_text' => $current->getUserText(),
2146 "rc_timestamp > '{$s->rev_timestamp}'",
2151 # Get the edit summary
2152 $target = Revision
::newFromId( $s->rev_id
);
2153 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2154 $newComment = $wgRequest->getText( 'summary', $newComment );
2157 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2158 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2159 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2161 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2163 $wgOut->returnToMain( false );
2168 * Do standard deferred updates after page view
2171 function viewUpdates() {
2172 global $wgDeferredUpdateList;
2174 if ( 0 != $this->getID() ) {
2175 global $wgDisableCounters;
2176 if( !$wgDisableCounters ) {
2177 Article
::incViewCount( $this->getID() );
2178 $u = new SiteStatsUpdate( 1, 0, 0 );
2179 array_push( $wgDeferredUpdateList, $u );
2183 # Update newtalk / watchlist notification status
2185 $wgUser->clearNotification( $this->mTitle
);
2189 * Do standard deferred updates after page edit.
2190 * Update links tables, site stats, search index and message cache.
2191 * Every 1000th edit, prune the recent changes table.
2194 * @param $text New text of the article
2195 * @param $summary Edit summary
2196 * @param $minoredit Minor edit
2197 * @param $timestamp_of_pagechange Timestamp associated with the page change
2198 * @param $newid rev_id value of the new revision
2199 * @param $changed Whether or not the content actually changed
2201 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2202 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2204 wfProfileIn( __METHOD__
);
2207 $options = new ParserOptions
;
2208 $options->setTidy(true);
2209 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2211 # Save it to the parser cache
2212 $parserCache =& ParserCache
::singleton();
2213 $parserCache->save( $poutput, $this, $wgUser );
2215 # Update the links tables
2216 $u = new LinksUpdate( $this->mTitle
, $poutput );
2219 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2221 if ( 0 == mt_rand( 0, 999 ) ) {
2222 # Periodically flush old entries from the recentchanges table.
2225 $dbw =& wfGetDB( DB_MASTER
);
2226 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2227 $recentchanges = $dbw->tableName( 'recentchanges' );
2228 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2229 $dbw->query( $sql );
2233 $id = $this->getID();
2234 $title = $this->mTitle
->getPrefixedDBkey();
2235 $shortTitle = $this->mTitle
->getDBkey();
2238 wfProfileOut( __METHOD__
);
2242 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2243 array_push( $wgDeferredUpdateList, $u );
2244 $u = new SearchUpdate( $id, $title, $text );
2245 array_push( $wgDeferredUpdateList, $u );
2247 # If this is another user's talk page, update newtalk
2248 # Don't do this if $changed = false otherwise some idiot can null-edit a
2249 # load of user talk pages and piss people off, nor if it's a minor edit
2250 # by a properly-flagged bot.
2251 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2252 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2253 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2254 $other = User
::newFromName( $shortTitle );
2255 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2256 // An anonymous user
2257 $other = new User();
2258 $other->setName( $shortTitle );
2261 $other->setNewtalk( true );
2266 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2267 $wgMessageCache->replace( $shortTitle, $text );
2270 wfProfileOut( __METHOD__
);
2274 * Perform article updates on a special page creation.
2276 * @param Revision $rev
2278 * @fixme This is a shitty interface function. Kill it and replace the
2279 * other shitty functions like editUpdates and such so it's not needed
2282 function createUpdates( $rev ) {
2283 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2284 $this->mTotalAdjustment
= 1;
2285 $this->editUpdates( $rev->getText(), $rev->getComment(),
2286 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2290 * Generate the navigation links when browsing through an article revisions
2291 * It shows the information as:
2292 * Revision as of \<date\>; view current revision
2293 * \<- Previous version | Next Version -\>
2296 * @param string $oldid Revision ID of this article revision
2298 function setOldSubtitle( $oldid=0 ) {
2299 global $wgLang, $wgOut, $wgUser;
2301 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2305 $revision = Revision
::newFromId( $oldid );
2307 $current = ( $oldid == $this->mLatest
);
2308 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2309 $sk = $wgUser->getSkin();
2311 ?
wfMsg( 'currentrevisionlink' )
2312 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2315 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2316 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2318 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2319 : wfMsg( 'previousrevision' );
2321 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2323 $nextlink = $current
2324 ?
wfMsg( 'nextrevision' )
2325 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2326 $nextdiff = $current
2328 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2330 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2331 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2333 $r = "\n\t\t\t\t<div id=\"mw-revision-info\">" . wfMsg( 'revision-info', $td, $userlinks ) . "</div>\n" .
2334 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2335 $wgOut->setSubtitle( $r );
2339 * This function is called right before saving the wikitext,
2340 * so we can do things like signatures and links-in-context.
2342 * @param string $text
2344 function preSaveTransform( $text ) {
2345 global $wgParser, $wgUser;
2346 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2349 /* Caching functions */
2352 * checkLastModified returns true if it has taken care of all
2353 * output to the client that is necessary for this request.
2354 * (that is, it has sent a cached version of the page)
2356 function tryFileCache() {
2357 static $called = false;
2359 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2363 if($this->isFileCacheable()) {
2364 $touched = $this->mTouched
;
2365 $cache = new HTMLFileCache( $this->mTitle
);
2366 if($cache->isFileCacheGood( $touched )) {
2367 wfDebug( "Article::tryFileCache(): about to load file\n" );
2368 $cache->loadFromFileCache();
2371 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2372 ob_start( array(&$cache, 'saveToFileCache' ) );
2375 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2380 * Check if the page can be cached
2383 function isFileCacheable() {
2384 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2385 $action = $wgRequest->getVal( 'action' );
2386 $oldid = $wgRequest->getVal( 'oldid' );
2387 $diff = $wgRequest->getVal( 'diff' );
2388 $redirect = $wgRequest->getVal( 'redirect' );
2389 $printable = $wgRequest->getVal( 'printable' );
2391 return $wgUseFileCache
2392 and (!$wgShowIPinHeader)
2393 and ($this->getID() != 0)
2394 and ($wgUser->isAnon())
2395 and (!$wgUser->getNewtalk())
2396 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2397 and (empty( $action ) ||
$action == 'view')
2398 and (!isset($oldid))
2400 and (!isset($redirect))
2401 and (!isset($printable))
2402 and (!$this->mRedirectedFrom
);
2406 * Loads page_touched and returns a value indicating if it should be used
2409 function checkTouched() {
2410 if( !$this->mDataLoaded
) {
2411 $this->loadPageData();
2413 return !$this->mIsRedirect
;
2417 * Get the page_touched field
2419 function getTouched() {
2420 # Ensure that page data has been loaded
2421 if( !$this->mDataLoaded
) {
2422 $this->loadPageData();
2424 return $this->mTouched
;
2428 * Get the page_latest field
2430 function getLatest() {
2431 if ( !$this->mDataLoaded
) {
2432 $this->loadPageData();
2434 return $this->mLatest
;
2438 * Edit an article without doing all that other stuff
2439 * The article must already exist; link tables etc
2440 * are not updated, caches are not flushed.
2442 * @param string $text text submitted
2443 * @param string $comment comment submitted
2444 * @param bool $minor whereas it's a minor modification
2446 function quickEdit( $text, $comment = '', $minor = 0 ) {
2447 wfProfileIn( __METHOD__
);
2449 $dbw =& wfGetDB( DB_MASTER
);
2451 $revision = new Revision( array(
2452 'page' => $this->getId(),
2454 'comment' => $comment,
2455 'minor_edit' => $minor ?
1 : 0,
2457 $revision->insertOn( $dbw );
2458 $this->updateRevisionOn( $dbw, $revision );
2461 wfProfileOut( __METHOD__
);
2465 * Used to increment the view counter
2468 * @param integer $id article id
2470 function incViewCount( $id ) {
2471 $id = intval( $id );
2472 global $wgHitcounterUpdateFreq, $wgDBtype;
2474 $dbw =& wfGetDB( DB_MASTER
);
2475 $pageTable = $dbw->tableName( 'page' );
2476 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2477 $acchitsTable = $dbw->tableName( 'acchits' );
2479 if( $wgHitcounterUpdateFreq <= 1 ) {
2480 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2484 # Not important enough to warrant an error page in case of failure
2485 $oldignore = $dbw->ignoreErrors( true );
2487 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2489 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2490 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2491 # Most of the time (or on SQL errors), skip row count check
2492 $dbw->ignoreErrors( $oldignore );
2496 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2497 $row = $dbw->fetchObject( $res );
2498 $rown = intval( $row->n
);
2499 if( $rown >= $wgHitcounterUpdateFreq ){
2500 wfProfileIn( 'Article::incViewCount-collect' );
2501 $old_user_abort = ignore_user_abort( true );
2503 if ($wgDBtype == 'mysql')
2504 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2505 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2506 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2507 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2509 $dbw->query("DELETE FROM $hitcounterTable");
2510 if ($wgDBtype == 'mysql') {
2511 $dbw->query('UNLOCK TABLES');
2512 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2513 'WHERE page_id = hc_id');
2516 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2517 "FROM $acchitsTable WHERE page_id = hc_id");
2519 $dbw->query("DROP TABLE $acchitsTable");
2521 ignore_user_abort( $old_user_abort );
2522 wfProfileOut( 'Article::incViewCount-collect' );
2524 $dbw->ignoreErrors( $oldignore );
2528 * The onArticle*() functions are supposed to be a kind of hooks
2529 * which should be called whenever any of the specified actions
2532 * This is a good place to put code to clear caches, for instance.
2534 * This is called on page move and undelete, as well as edit
2536 * @param $title_obj a title object
2539 static function onArticleCreate($title) {
2540 # The talk page isn't in the regular link tables, so we need to update manually:
2541 if ( $title->isTalkPage() ) {
2542 $other = $title->getSubjectPage();
2544 $other = $title->getTalkPage();
2546 $other->invalidateCache();
2547 $other->purgeSquid();
2549 $title->touchLinks();
2550 $title->purgeSquid();
2553 static function onArticleDelete( $title ) {
2554 global $wgUseFileCache, $wgMessageCache;
2556 $title->touchLinks();
2557 $title->purgeSquid();
2560 if ( $wgUseFileCache ) {
2561 $cm = new HTMLFileCache( $title );
2562 @unlink
( $cm->fileCacheName() );
2565 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2566 $wgMessageCache->replace( $title->getDBkey(), false );
2571 * Purge caches on page update etc
2573 static function onArticleEdit( $title ) {
2574 global $wgDeferredUpdateList, $wgUseFileCache;
2576 // Invalidate caches of articles which include this page
2577 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2578 $wgDeferredUpdateList[] = $update;
2580 # Purge squid for this page only
2581 $title->purgeSquid();
2584 if ( $wgUseFileCache ) {
2585 $cm = new HTMLFileCache( $title );
2586 @unlink
( $cm->fileCacheName() );
2593 * Info about this page
2594 * Called for ?action=info when $wgAllowPageInfo is on.
2599 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2601 if ( !$wgAllowPageInfo ) {
2602 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2606 $page = $this->mTitle
->getSubjectPage();
2608 $wgOut->setPagetitle( $page->getPrefixedText() );
2609 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2611 # first, see if the page exists at all.
2612 $exists = $page->getArticleId() != 0;
2614 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2615 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2617 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2620 $dbr =& wfGetDB( DB_SLAVE
);
2622 'wl_title' => $page->getDBkey(),
2623 'wl_namespace' => $page->getNamespace() );
2624 $numwatchers = $dbr->selectField(
2629 $this->getSelectOptions() );
2631 $pageInfo = $this->pageCountInfo( $page );
2632 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2634 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2635 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2637 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2639 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2641 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2643 $wgOut->addHTML( '</ul>' );
2649 * Return the total number of edits and number of unique editors
2650 * on a given page. If page does not exist, returns false.
2652 * @param Title $title
2656 function pageCountInfo( $title ) {
2657 $id = $title->getArticleId();
2662 $dbr =& wfGetDB( DB_SLAVE
);
2664 $rev_clause = array( 'rev_page' => $id );
2666 $edits = $dbr->selectField(
2671 $this->getSelectOptions() );
2673 $authors = $dbr->selectField(
2675 'COUNT(DISTINCT rev_user_text)',
2678 $this->getSelectOptions() );
2680 return array( 'edits' => $edits, 'authors' => $authors );
2684 * Return a list of templates used by this article.
2685 * Uses the templatelinks table
2687 * @return array Array of Title objects
2689 function getUsedTemplates() {
2691 $id = $this->mTitle
->getArticleID();
2696 $dbr =& wfGetDB( DB_SLAVE
);
2697 $res = $dbr->select( array( 'templatelinks' ),
2698 array( 'tl_namespace', 'tl_title' ),
2699 array( 'tl_from' => $id ),
2700 'Article:getUsedTemplates' );
2701 if ( false !== $res ) {
2702 if ( $dbr->numRows( $res ) ) {
2703 while ( $row = $dbr->fetchObject( $res ) ) {
2704 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2708 $dbr->freeResult( $res );
2713 * Return an auto-generated summary if the text provided is a redirect.
2715 * @param string $text The wikitext to check
2716 * @return string '' or an appropriate summary
2718 public static function getRedirectAutosummary( $text ) {
2719 $rt = Title
::newFromRedirect( $text );
2720 if( is_object( $rt ) )
2721 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2727 * Return an auto-generated summary if the new text is much shorter than
2730 * @param string $oldtext The previous text of the page
2731 * @param string $text The submitted text of the page
2732 * @return string An appropriate autosummary, or an empty string.
2734 public static function getBlankingAutosummary( $oldtext, $text ) {
2735 if ($oldtext!='' && $text=='') {
2736 return wfMsgForContent('autosumm-blank');
2737 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2738 #Removing more than 90% of the article
2740 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2741 return wfMsgForContent('autosumm-replace', $truncatedtext);
2748 * Return an applicable autosummary if one exists for the given edit.
2749 * @param string $oldtext The previous text of the page.
2750 * @param string $newtext The submitted text of the page.
2751 * @param bitmask $flags A bitmask of flags submitted for the edit.
2752 * @return string An appropriate autosummary, or an empty string.
2754 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2756 # This code is UGLY UGLY UGLY.
2757 # Somebody PLEASE come up with a more elegant way to do it.
2759 #Redirect autosummaries
2760 $summary = self
::getRedirectAutosummary( $newtext );
2765 #Blanking autosummaries
2766 if (!($flags & EDIT_NEW
))
2767 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
2772 #New page autosummaries
2773 if ($flags & EDIT_NEW
&& strlen($newtext)) {
2774 #If they're making a new article, give its text, truncated, in the summary.
2776 $truncatedtext = $wgContLang->truncate(
2777 str_replace("\n", ' ', $newtext),
2778 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2780 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );