7 * Class representing a MediaWiki article and history.
9 * See design.txt for an overview.
10 * Note: edit user interface and cache support functions have been
11 * moved to separate EditPage and HTMLFileCache classes.
20 var $mContentLoaded; //!<
23 var $mGoodAdjustment; //!<
27 var $mRedirectedFrom; //!<
28 var $mRedirectUrl; //!<
29 var $mRevIdFetched; //!<
33 var $mTotalAdjustment; //!<
40 * Constructor and clear the article
41 * @param $title Reference to a Title object.
42 * @param $oldId Integer revision ID, null to fetch from request, zero for current
44 function __construct( &$title, $oldId = null ) {
45 $this->mTitle
=& $title;
46 $this->mOldId
= $oldId;
51 * Tell the page view functions that this view was redirected
52 * from another page on the wiki.
53 * @param $from Title object.
55 function setRedirectedFrom( $from ) {
56 $this->mRedirectedFrom
= $from;
60 * @return mixed false, Title of in-wiki target, or string with URL
62 function followRedirect() {
63 $text = $this->getContent();
64 $rt = Title
::newFromRedirect( $text );
66 # process if title object is valid and not special:userlogout
68 if( $rt->getInterwiki() != '' ) {
69 if( $rt->isLocal() ) {
70 // Offsite wikis need an HTTP redirect.
72 // This can be hard to reverse and may produce loops,
73 // so they may be disabled in the site configuration.
75 $source = $this->mTitle
->getFullURL( 'redirect=no' );
76 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
79 if( $rt->getNamespace() == NS_SPECIAL
) {
80 // Gotta handle redirects to special pages differently:
81 // Fill the HTTP response "Location" header and ignore
82 // the rest of the page we're on.
84 // This can be hard to reverse, so they may be disabled.
86 if( $rt->isSpecial( 'Userlogout' ) ) {
89 return $rt->getFullURL();
96 // No or invalid redirect
101 * get the title object of the article
103 function getTitle() {
104 return $this->mTitle
;
112 $this->mDataLoaded
= false;
113 $this->mContentLoaded
= false;
115 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
116 $this->mRedirectedFrom
= null; # Title object if set
118 $this->mTimestamp
= $this->mComment
= '';
119 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
120 $this->mTouched
= '19700101000000';
121 $this->mForUpdate
= false;
122 $this->mIsRedirect
= false;
123 $this->mRevIdFetched
= 0;
124 $this->mRedirectUrl
= false;
125 $this->mLatest
= false;
129 * Note that getContent/loadContent do not follow redirects anymore.
130 * If you need to fetch redirectable content easily, try
131 * the shortcut in Article::followContent()
133 * @todo There are still side-effects in this!
134 * In general, you should use the Revision class, not Article,
135 * to fetch text for purposes other than page views.
137 * @return Return the text of this revision
139 function getContent() {
140 global $wgUser, $wgOut;
142 wfProfileIn( __METHOD__
);
144 // We want to show the content even if the page doesn't exist, as long
145 // as the revision does (perhaps it's been moved and the redirect
146 // deleted: bug 10377)
147 if ( 0 == $this->getID() and !$this->mOldId
) {
148 wfProfileOut( __METHOD__
);
149 $wgOut->setRobotpolicy( 'noindex,nofollow' );
151 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
152 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
154 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
157 return "<div class='noarticletext'>$ret</div>";
159 $this->loadContent();
160 wfProfileOut( __METHOD__
);
161 return $this->mContent
;
166 * This function returns the text of a section, specified by a number ($section).
167 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
168 * the first section before any such heading (section 0).
170 * If a section contains subsections, these are also returned.
172 * @param $text String: text to look in
173 * @param $section Integer: section number
174 * @return string text of the requested section
177 function getSection($text,$section) {
179 return $wgParser->getSection( $text, $section );
183 * @return int The oldid of the article that is to be shown, 0 for the
186 function getOldID() {
187 if ( is_null( $this->mOldId
) ) {
188 $this->mOldId
= $this->getOldIDFromRequest();
190 return $this->mOldId
;
194 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
196 * @return int The old id for the request
198 function getOldIDFromRequest() {
200 $this->mRedirectUrl
= false;
201 $oldid = $wgRequest->getVal( 'oldid' );
202 if ( isset( $oldid ) ) {
203 $oldid = intval( $oldid );
204 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
205 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
209 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
211 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
212 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
230 * Load the revision (including text) into this object
232 function loadContent() {
233 if ( $this->mContentLoaded
) return;
236 $oldid = $this->getOldID();
238 # Pre-fill content with error message so that if something
239 # fails we'll have something telling us what we intended.
240 $this->mOldId
= $oldid;
241 $this->fetchContent( $oldid );
246 * Fetch a page record with the given conditions
247 * @param Database $dbr
248 * @param array $conditions
251 function pageData( $dbr, $conditions ) {
264 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
265 $row = $dbr->selectRow( 'page',
268 'Article::pageData' );
269 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
274 * @param Database $dbr
275 * @param Title $title
277 function pageDataFromTitle( $dbr, $title ) {
278 return $this->pageData( $dbr, array(
279 'page_namespace' => $title->getNamespace(),
280 'page_title' => $title->getDBkey() ) );
284 * @param Database $dbr
287 function pageDataFromId( $dbr, $id ) {
288 return $this->pageData( $dbr, array( 'page_id' => $id ) );
292 * Set the general counter, title etc data loaded from
295 * @param object $data
298 function loadPageData( $data = 'fromdb' ) {
299 if ( $data === 'fromdb' ) {
300 $dbr = $this->getDB();
301 $data = $this->pageDataFromId( $dbr, $this->getId() );
304 $lc =& LinkCache
::singleton();
306 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
308 $this->mTitle
->mArticleID
= $data->page_id
;
310 # Old-fashioned restrictions.
311 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
313 $this->mCounter
= $data->page_counter
;
314 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
315 $this->mIsRedirect
= $data->page_is_redirect
;
316 $this->mLatest
= $data->page_latest
;
318 if ( is_object( $this->mTitle
) ) {
319 $lc->addBadLinkObj( $this->mTitle
);
321 $this->mTitle
->mArticleID
= 0;
324 $this->mDataLoaded
= true;
328 * Get text of an article from database
329 * Does *NOT* follow redirects.
330 * @param int $oldid 0 for whatever the latest revision is
333 function fetchContent( $oldid = 0 ) {
334 if ( $this->mContentLoaded
) {
335 return $this->mContent
;
338 $dbr = $this->getDB();
340 # Pre-fill content with error message so that if something
341 # fails we'll have something telling us what we intended.
342 $t = $this->mTitle
->getPrefixedText();
344 $t .= ',oldid='.$oldid;
346 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
349 $revision = Revision
::newFromId( $oldid );
350 if( is_null( $revision ) ) {
351 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
354 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
356 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
359 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
360 $this->loadPageData( $data );
362 if( !$this->mDataLoaded
) {
363 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
365 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
368 $this->loadPageData( $data );
370 $revision = Revision
::newFromId( $this->mLatest
);
371 if( is_null( $revision ) ) {
372 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
377 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
378 // We should instead work with the Revision object when we need it...
379 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
380 //$this->mContent = $revision->getText();
382 $this->mUser
= $revision->getUser();
383 $this->mUserText
= $revision->getUserText();
384 $this->mComment
= $revision->getComment();
385 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
387 $this->mRevIdFetched
= $revision->getID();
388 $this->mContentLoaded
= true;
389 $this->mRevision
=& $revision;
391 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
393 return $this->mContent
;
397 * Read/write accessor to select FOR UPDATE
399 * @param $x Mixed: FIXME
401 function forUpdate( $x = NULL ) {
402 return wfSetVar( $this->mForUpdate
, $x );
406 * Get the database which should be used for reads
411 return wfGetDB( DB_MASTER
);
415 * Get options for all SELECT statements
417 * @param $options Array: an optional options array which'll be appended to
419 * @return Array: options
421 function getSelectOptions( $options = '' ) {
422 if ( $this->mForUpdate
) {
423 if ( is_array( $options ) ) {
424 $options[] = 'FOR UPDATE';
426 $options = 'FOR UPDATE';
433 * @return int Page ID
436 if( $this->mTitle
) {
437 return $this->mTitle
->getArticleID();
444 * @return bool Whether or not the page exists in the database
447 return $this->getId() != 0;
451 * @return int The view count for the page
453 function getCount() {
454 if ( -1 == $this->mCounter
) {
455 $id = $this->getID();
459 $dbr = wfGetDB( DB_SLAVE
);
460 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
461 'Article::getCount', $this->getSelectOptions() );
464 return $this->mCounter
;
468 * Determine whether a page would be suitable for being counted as an
469 * article in the site_stats table based on the title & its content
471 * @param $text String: text to analyze
474 function isCountable( $text ) {
475 global $wgUseCommaCount;
477 $token = $wgUseCommaCount ?
',' : '[[';
479 $this->mTitle
->isContentPage()
480 && !$this->isRedirect( $text )
481 && in_string( $token, $text );
485 * Tests if the article text represents a redirect
487 * @param $text String: FIXME
490 function isRedirect( $text = false ) {
491 if ( $text === false ) {
492 $this->loadContent();
493 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
495 $titleObj = Title
::newFromRedirect( $text );
497 return $titleObj !== NULL;
501 * Returns true if the currently-referenced revision is the current edit
502 * to this page (and it exists).
505 function isCurrent() {
506 # If no oldid, this is the current version.
507 if ($this->getOldID() == 0)
510 return $this->exists() &&
511 isset( $this->mRevision
) &&
512 $this->mRevision
->isCurrent();
516 * Loads everything except the text
517 * This isn't necessary for all uses, so it's only done if needed.
520 function loadLastEdit() {
521 if ( -1 != $this->mUser
)
524 # New or non-existent articles have no user information
525 $id = $this->getID();
526 if ( 0 == $id ) return;
528 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
529 if( !is_null( $this->mLastRevision
) ) {
530 $this->mUser
= $this->mLastRevision
->getUser();
531 $this->mUserText
= $this->mLastRevision
->getUserText();
532 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
533 $this->mComment
= $this->mLastRevision
->getComment();
534 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
535 $this->mRevIdFetched
= $this->mLastRevision
->getID();
539 function getTimestamp() {
540 // Check if the field has been filled by ParserCache::get()
541 if ( !$this->mTimestamp
) {
542 $this->loadLastEdit();
544 return wfTimestamp(TS_MW
, $this->mTimestamp
);
548 $this->loadLastEdit();
552 function getUserText() {
553 $this->loadLastEdit();
554 return $this->mUserText
;
557 function getComment() {
558 $this->loadLastEdit();
559 return $this->mComment
;
562 function getMinorEdit() {
563 $this->loadLastEdit();
564 return $this->mMinorEdit
;
567 function getRevIdFetched() {
568 $this->loadLastEdit();
569 return $this->mRevIdFetched
;
573 * @todo Document, fixme $offset never used.
574 * @param $limit Integer: default 0.
575 * @param $offset Integer: default 0.
577 function getContributors($limit = 0, $offset = 0) {
578 # XXX: this is expensive; cache this info somewhere.
581 $dbr = wfGetDB( DB_SLAVE
);
582 $revTable = $dbr->tableName( 'revision' );
583 $userTable = $dbr->tableName( 'user' );
584 $user = $this->getUser();
585 $pageId = $this->getId();
587 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
588 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
589 WHERE rev_page = $pageId
590 AND rev_user != $user
591 GROUP BY rev_user, rev_user_text, user_real_name
592 ORDER BY timestamp DESC";
594 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
595 $sql .= ' '. $this->getSelectOptions();
597 $res = $dbr->query($sql, __METHOD__
);
599 while ( $line = $dbr->fetchObject( $res ) ) {
600 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
603 $dbr->freeResult($res);
608 * This is the default action of the script: just view the page of
612 global $wgUser, $wgOut, $wgRequest, $wgContLang;
613 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
614 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
615 $sk = $wgUser->getSkin();
617 wfProfileIn( __METHOD__
);
619 $parserCache =& ParserCache
::singleton();
620 $ns = $this->mTitle
->getNamespace(); # shortcut
622 # Get variables from query string
623 $oldid = $this->getOldID();
625 # getOldID may want us to redirect somewhere else
626 if ( $this->mRedirectUrl
) {
627 $wgOut->redirect( $this->mRedirectUrl
);
628 wfProfileOut( __METHOD__
);
632 $diff = $wgRequest->getVal( 'diff' );
633 $rcid = $wgRequest->getVal( 'rcid' );
634 $rdfrom = $wgRequest->getVal( 'rdfrom' );
635 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
637 $wgOut->setArticleFlag( true );
639 # Discourage indexing of printable versions, but encourage following
640 if( $wgOut->isPrintable() ) {
641 $policy = 'noindex,follow';
642 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
643 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
644 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
645 # Honour customised robot policies for this namespace
646 $policy = $wgNamespaceRobotPolicies[$ns];
648 # Default to encourage indexing and following links
649 $policy = 'index,follow';
651 $wgOut->setRobotPolicy( $policy );
653 # If we got diff and oldid in the query, we want to see a
654 # diff page instead of the article.
656 if ( !is_null( $diff ) ) {
657 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
659 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
660 // DifferenceEngine directly fetched the revision:
661 $this->mRevIdFetched
= $de->mNewid
;
662 $de->showDiffPage( $diffOnly );
664 // Needed to get the page's current revision
665 $this->loadPageData();
666 if( $diff == 0 ||
$diff == $this->mLatest
) {
667 # Run view updates for current revision only
668 $this->viewUpdates();
670 wfProfileOut( __METHOD__
);
674 if ( empty( $oldid ) && $this->checkTouched() ) {
675 $wgOut->setETag($parserCache->getETag($this, $wgUser));
677 if( $wgOut->checkLastModified( $this->mTouched
) ){
678 wfProfileOut( __METHOD__
);
680 } else if ( $this->tryFileCache() ) {
681 # tell wgOut that output is taken care of
683 $this->viewUpdates();
684 wfProfileOut( __METHOD__
);
689 # Should the parser cache be used?
690 $pcache = $wgEnableParserCache &&
691 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
694 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
695 if ( $wgUser->getOption( 'stubthreshold' ) ) {
696 wfIncrStats( 'pcache_miss_stub' );
699 $wasRedirected = false;
700 if ( isset( $this->mRedirectedFrom
) ) {
701 // This is an internally redirected page view.
702 // We'll need a backlink to the source page for navigation.
703 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
704 $sk = $wgUser->getSkin();
705 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
706 $s = wfMsg( 'redirectedfrom', $redir );
707 $wgOut->setSubtitle( $s );
709 // Set the fragment if one was specified in the redirect
710 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
711 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
712 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
714 $wasRedirected = true;
716 } elseif ( !empty( $rdfrom ) ) {
717 // This is an externally redirected view, from some other wiki.
718 // If it was reported from a trusted site, supply a backlink.
719 global $wgRedirectSources;
720 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
721 $sk = $wgUser->getSkin();
722 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
723 $s = wfMsg( 'redirectedfrom', $redir );
724 $wgOut->setSubtitle( $s );
725 $wasRedirected = true;
730 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
732 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
733 // Ensure that UI elements requiring revision ID have
734 // the correct version information.
735 $wgOut->setRevisionId( $this->mLatest
);
739 if ( !$outputDone ) {
740 $text = $this->getContent();
741 if ( $text === false ) {
742 # Failed to load, replace text with error message
743 $t = $this->mTitle
->getPrefixedText();
745 $t .= ',oldid='.$oldid;
746 $text = wfMsg( 'missingarticle', $t );
748 $text = wfMsg( 'noarticletext', $t );
752 # Another whitelist check in case oldid is altering the title
753 if ( !$this->mTitle
->userCanRead() ) {
754 $wgOut->loginToUse();
759 # We're looking at an old revision
761 if ( !empty( $oldid ) ) {
762 $wgOut->setRobotpolicy( 'noindex,nofollow' );
763 if( is_null( $this->mRevision
) ) {
764 // FIXME: This would be a nice place to load the 'no such page' text.
766 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
767 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
768 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
769 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
770 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
773 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
774 // and we are allowed to see...
782 $wgOut->setRevisionId( $this->getRevIdFetched() );
783 // Wrap site/user css/js in pre and don't parse. User pages need
784 // to be subpages, site pages just need to end in ".css" or ".js".
786 // @todo: use $this->mTitle->isCssJsSubpage() when php is fixed/
787 // a workaround is found.
789 ($ns == NS_USER
and preg_match('#/\w+\.(css|js)$#',$this->mTitle
->getDBkey(),$matches))
790 or ($ns == NS_MEDIAWIKI
and preg_match('/.(css|js)$/', $this->mTitle
->getDBkey(), $matches))
792 $wgOut->addWikiText( wfMsg('clearyourcache'));
794 "<pre class=\"mw-code mw-{$matches[1]}\" dir=\"ltr\">"
795 .htmlspecialchars($this->mContent
)."\n</pre>"
797 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
799 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
800 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
801 # Don't overwrite the subtitle if this was an old revision
802 if( !$wasRedirected && $this->isCurrent() ) {
803 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
805 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
807 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
808 '<span class="redirectText">'.$link.'</span>' );
810 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
811 $wgOut->addParserOutputNoText( $parseout );
812 } else if ( $pcache ) {
813 # Display content and save to parser cache
814 $this->outputWikiText( $text );
816 # Display content, don't attempt to save to parser cache
817 # Don't show section-edit links on old revisions... this way lies madness.
818 if( !$this->isCurrent() ) {
819 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
821 # Display content and don't save to parser cache
822 # With timing hack -- TS 2006-07-26
824 $this->outputWikiText( $text, false );
829 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
830 $this->mTitle
->getPrefixedDBkey()));
833 if( !$this->isCurrent() ) {
834 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
839 /* title may have been set from the cache */
840 $t = $wgOut->getPageTitle();
842 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
845 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
846 if( $ns == NS_USER_TALK
&&
847 User
::isIP( $this->mTitle
->getText() ) ) {
848 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
851 # If we have been passed an &rcid= parameter, we want to give the user a
852 # chance to mark this new article as patrolled.
853 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
855 "<div class='patrollink'>" .
856 wfMsgHtml( 'markaspatrolledlink',
857 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
858 "action=markpatrolled&rcid=$rcid" )
865 if ($wgUseTrackbacks)
866 $this->addTrackbacks();
868 $this->viewUpdates();
869 wfProfileOut( __METHOD__
);
872 function addTrackbacks() {
873 global $wgOut, $wgUser;
875 $dbr = wfGetDB(DB_SLAVE
);
877 /* FROM */ 'trackbacks',
878 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
879 /* WHERE */ array('tb_page' => $this->getID())
882 if (!$dbr->numrows($tbs))
886 while ($o = $dbr->fetchObject($tbs)) {
888 if ($wgUser->isAllowed( 'trackback' )) {
889 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
890 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
891 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
893 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
900 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
903 function deletetrackback() {
904 global $wgUser, $wgRequest, $wgOut, $wgTitle;
906 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
907 $wgOut->addWikitext(wfMsg('sessionfailure'));
911 if ((!$wgUser->isAllowed('delete'))) {
912 $wgOut->permissionRequired( 'delete' );
917 $wgOut->readOnlyPage();
921 $db = wfGetDB(DB_MASTER
);
922 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
923 $wgTitle->invalidateCache();
924 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
930 $wgOut->setArticleBodyOnly(true);
935 * Handle action=purge
938 global $wgUser, $wgRequest, $wgOut;
940 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
941 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
945 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
946 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
947 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
948 $msg = str_replace( '$1',
949 "<form method=\"post\" action=\"$action\">\n" .
950 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
953 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
954 $wgOut->setRobotpolicy( 'noindex,nofollow' );
955 $wgOut->addHTML( $msg );
960 * Perform the actions of a page purging
964 // Invalidate the cache
965 $this->mTitle
->invalidateCache();
968 // Commit the transaction before the purge is sent
969 $dbw = wfGetDB( DB_MASTER
);
970 $dbw->immediateCommit();
973 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
980 * Insert a new empty page record for this article.
981 * This *must* be followed up by creating a revision
982 * and running $this->updateToLatest( $rev_id );
983 * or else the record will be left in a funky state.
984 * Best if all done inside a transaction.
986 * @param Database $dbw
987 * @return int The newly created page_id key
990 function insertOn( $dbw ) {
991 wfProfileIn( __METHOD__
);
993 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
994 $dbw->insert( 'page', array(
995 'page_id' => $page_id,
996 'page_namespace' => $this->mTitle
->getNamespace(),
997 'page_title' => $this->mTitle
->getDBkey(),
999 'page_restrictions' => '',
1000 'page_is_redirect' => 0, # Will set this shortly...
1002 'page_random' => wfRandom(),
1003 'page_touched' => $dbw->timestamp(),
1004 'page_latest' => 0, # Fill this in shortly...
1005 'page_len' => 0, # Fill this in shortly...
1007 $newid = $dbw->insertId();
1009 $this->mTitle
->resetArticleId( $newid );
1011 wfProfileOut( __METHOD__
);
1016 * Update the page record to point to a newly saved revision.
1018 * @param Database $dbw
1019 * @param Revision $revision For ID number, and text used to set
1020 length and redirect status fields
1021 * @param int $lastRevision If given, will not overwrite the page field
1022 * when different from the currently set value.
1023 * Giving 0 indicates the new page flag should
1025 * @param bool $lastRevIsRedirect If given, will optimize adding and
1026 * removing rows in redirect table.
1027 * @return bool true on success, false on failure
1030 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1031 wfProfileIn( __METHOD__
);
1033 $text = $revision->getText();
1034 $rt = Title
::newFromRedirect( $text );
1036 $conditions = array( 'page_id' => $this->getId() );
1037 if( !is_null( $lastRevision ) ) {
1038 # An extra check against threads stepping on each other
1039 $conditions['page_latest'] = $lastRevision;
1042 $dbw->update( 'page',
1044 'page_latest' => $revision->getId(),
1045 'page_touched' => $dbw->timestamp(),
1046 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1047 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1048 'page_len' => strlen( $text ),
1053 $result = $dbw->affectedRows() != 0;
1056 // FIXME: Should the result from updateRedirectOn() be returned instead?
1057 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1060 wfProfileOut( __METHOD__
);
1065 * Add row to the redirect table if this is a redirect, remove otherwise.
1067 * @param Database $dbw
1068 * @param $redirectTitle a title object pointing to the redirect target,
1069 * or NULL if this is not a redirect
1070 * @param bool $lastRevIsRedirect If given, will optimize adding and
1071 * removing rows in redirect table.
1072 * @return bool true on success, false on failure
1075 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1077 // Always update redirects (target link might have changed)
1078 // Update/Insert if we don't know if the last revision was a redirect or not
1079 // Delete if changing from redirect to non-redirect
1080 $isRedirect = !is_null($redirectTitle);
1081 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1083 wfProfileIn( __METHOD__
);
1087 // This title is a redirect, Add/Update row in the redirect table
1088 $set = array( /* SET */
1089 'rd_namespace' => $redirectTitle->getNamespace(),
1090 'rd_title' => $redirectTitle->getDBkey(),
1091 'rd_from' => $this->getId(),
1094 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1096 // This is not a redirect, remove row from redirect table
1097 $where = array( 'rd_from' => $this->getId() );
1098 $dbw->delete( 'redirect', $where, __METHOD__
);
1101 wfProfileOut( __METHOD__
);
1102 return ( $dbw->affectedRows() != 0 );
1109 * If the given revision is newer than the currently set page_latest,
1110 * update the page record. Otherwise, do nothing.
1112 * @param Database $dbw
1113 * @param Revision $revision
1115 function updateIfNewerOn( &$dbw, $revision ) {
1116 wfProfileIn( __METHOD__
);
1118 $row = $dbw->selectRow(
1119 array( 'revision', 'page' ),
1120 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1122 'page_id' => $this->getId(),
1123 'page_latest=rev_id' ),
1126 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1127 wfProfileOut( __METHOD__
);
1130 $prev = $row->rev_id
;
1131 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1133 # No or missing previous revision; mark the page as new
1135 $lastRevIsRedirect = null;
1138 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1139 wfProfileOut( __METHOD__
);
1144 * @return string Complete article text, or null if error
1146 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1147 wfProfileIn( __METHOD__
);
1149 if( $section == '' ) {
1150 // Whole-page edit; let the text through unmolested.
1152 if( is_null( $edittime ) ) {
1153 $rev = Revision
::newFromTitle( $this->mTitle
);
1155 $dbw = wfGetDB( DB_MASTER
);
1156 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1158 if( is_null( $rev ) ) {
1159 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1160 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1163 $oldtext = $rev->getText();
1165 if( $section == 'new' ) {
1166 # Inserting a new section
1167 $subject = $summary ?
"== {$summary} ==\n\n" : '';
1168 $text = strlen( trim( $oldtext ) ) > 0
1169 ?
"{$oldtext}\n\n{$subject}{$text}"
1170 : "{$subject}{$text}";
1172 # Replacing an existing section; roll out the big guns
1174 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1179 wfProfileOut( __METHOD__
);
1184 * @deprecated use Article::doEdit()
1186 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1187 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1188 ( $isminor ? EDIT_MINOR
: 0 ) |
1189 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1191 # If this is a comment, add the summary as headline
1192 if ( $comment && $summary != "" ) {
1193 $text = "== {$summary} ==\n\n".$text;
1196 $this->doEdit( $text, $summary, $flags );
1198 $dbw = wfGetDB( DB_MASTER
);
1200 if (!$this->mTitle
->userIsWatching()) {
1206 if ( $this->mTitle
->userIsWatching() ) {
1212 $this->doRedirect( $this->isRedirect( $text ) );
1216 * @deprecated use Article::doEdit()
1218 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1219 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1220 ( $minor ? EDIT_MINOR
: 0 ) |
1221 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1223 $good = $this->doEdit( $text, $summary, $flags );
1225 $dbw = wfGetDB( DB_MASTER
);
1227 if (!$this->mTitle
->userIsWatching()) {
1233 if ( $this->mTitle
->userIsWatching() ) {
1240 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1248 * Change an existing article or create a new article. Updates RC and all necessary caches,
1249 * optionally via the deferred update array.
1251 * $wgUser must be set before calling this function.
1253 * @param string $text New text
1254 * @param string $summary Edit summary
1255 * @param integer $flags bitfield:
1257 * Article is known or assumed to be non-existent, create a new one
1259 * Article is known or assumed to be pre-existing, update it
1261 * Mark this edit minor, if the user is allowed to do so
1263 * Do not log the change in recentchanges
1265 * Mark the edit a "bot" edit regardless of user rights
1266 * EDIT_DEFER_UPDATES
1267 * Defer some of the updates until the end of index.php
1269 * Fill in blank summaries with generated text where possible
1271 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1272 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1273 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1274 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1275 * to MediaWiki's performance-optimised locking strategy.
1277 * @return bool success
1279 function doEdit( $text, $summary, $flags = 0 ) {
1280 global $wgUser, $wgDBtransactions;
1282 wfProfileIn( __METHOD__
);
1285 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1286 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1288 $flags |
= EDIT_UPDATE
;
1294 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1295 &$summary, $flags & EDIT_MINOR
,
1296 null, null, &$flags ) ) )
1298 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1299 wfProfileOut( __METHOD__
);
1303 # Silently ignore EDIT_MINOR if not allowed
1304 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1305 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1307 $oldtext = $this->getContent();
1308 $oldsize = strlen( $oldtext );
1310 # Provide autosummaries if one is not provided.
1311 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1312 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1314 $text = $this->preSaveTransform( $text );
1315 $newsize = strlen( $text );
1317 $dbw = wfGetDB( DB_MASTER
);
1318 $now = wfTimestampNow();
1320 if ( $flags & EDIT_UPDATE
) {
1321 # Update article, but only if changed.
1323 # Make sure the revision is either completely inserted or not inserted at all
1324 if( !$wgDBtransactions ) {
1325 $userAbort = ignore_user_abort( true );
1331 if ( 0 != strcmp( $text, $oldtext ) ) {
1332 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1333 - (int)$this->isCountable( $oldtext );
1334 $this->mTotalAdjustment
= 0;
1336 $lastRevision = $dbw->selectField(
1337 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1339 if ( !$lastRevision ) {
1340 # Article gone missing
1341 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1342 wfProfileOut( __METHOD__
);
1346 $revision = new Revision( array(
1347 'page' => $this->getId(),
1348 'comment' => $summary,
1349 'minor_edit' => $isminor,
1354 $revisionId = $revision->insertOn( $dbw );
1357 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1360 /* Belated edit conflict! Run away!! */
1364 # Update recentchanges
1365 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1366 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1367 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1370 # Mark as patrolled if the user can do so
1371 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1372 RecentChange
::markPatrolled( $rcid );
1373 PatrolLog
::record( $rcid, true );
1376 $wgUser->incEditCount();
1380 // Keep the same revision ID, but do some updates on it
1381 $revisionId = $this->getRevIdFetched();
1382 // Update page_touched, this is usually implicit in the page update
1383 // Other cache updates are done in onArticleEdit()
1384 $this->mTitle
->invalidateCache();
1387 if( !$wgDBtransactions ) {
1388 ignore_user_abort( $userAbort );
1392 # Invalidate cache of this article and all pages using this article
1393 # as a template. Partly deferred.
1394 Article
::onArticleEdit( $this->mTitle
);
1396 # Update links tables, site stats, etc.
1397 $changed = ( strcmp( $oldtext, $text ) != 0 );
1398 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1401 # Create new article
1403 # Set statistics members
1404 # We work out if it's countable after PST to avoid counter drift
1405 # when articles are created with {{subst:}}
1406 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1407 $this->mTotalAdjustment
= 1;
1411 # Add the page record; stake our claim on this title!
1412 # This will fail with a database query exception if the article already exists
1413 $newid = $this->insertOn( $dbw );
1415 # Save the revision text...
1416 $revision = new Revision( array(
1418 'comment' => $summary,
1419 'minor_edit' => $isminor,
1422 $revisionId = $revision->insertOn( $dbw );
1424 $this->mTitle
->resetArticleID( $newid );
1426 # Update the page record with revision data
1427 $this->updateRevisionOn( $dbw, $revision, 0 );
1429 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1430 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1431 '', strlen( $text ), $revisionId );
1432 # Mark as patrolled if the user can
1433 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1434 RecentChange
::markPatrolled( $rcid );
1435 PatrolLog
::record( $rcid, true );
1438 $wgUser->incEditCount();
1441 # Update links, etc.
1442 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1445 Article
::onArticleCreate( $this->mTitle
);
1447 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1448 $summary, $flags & EDIT_MINOR
,
1449 null, null, &$flags ) );
1452 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1456 wfRunHooks( 'ArticleSaveComplete',
1457 array( &$this, &$wgUser, $text,
1458 $summary, $flags & EDIT_MINOR
,
1459 null, null, &$flags ) );
1461 wfProfileOut( __METHOD__
);
1466 * @deprecated wrapper for doRedirect
1468 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1469 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1473 * Output a redirect back to the article.
1474 * This is typically used after an edit.
1476 * @param boolean $noRedir Add redirect=no
1477 * @param string $sectionAnchor section to redirect to, including "#"
1479 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1482 $query = 'redirect=no';
1486 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1490 * Mark this particular edit as patrolled
1492 function markpatrolled() {
1493 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1494 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1496 # Check RC patrol config. option
1497 if( !$wgUseRCPatrol ) {
1498 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1503 if( !$wgUser->isAllowed( 'patrol' ) ) {
1504 $wgOut->permissionRequired( 'patrol' );
1508 # If we haven't been given an rc_id value, we can't do anything
1509 $rcid = $wgRequest->getVal( 'rcid' );
1511 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1515 # Handle the 'MarkPatrolled' hook
1516 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1520 $return = SpecialPage
::getTitleFor( 'Recentchanges' );
1521 # If it's left up to us, check that the user is allowed to patrol this edit
1522 # If the user has the "autopatrol" right, then we'll assume there are no
1523 # other conditions stopping them doing so
1524 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1525 $rc = RecentChange
::newFromId( $rcid );
1526 # Graceful error handling, as we've done before here...
1527 # (If the recent change doesn't exist, then it doesn't matter whether
1528 # the user is allowed to patrol it or not; nothing is going to happen
1529 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1530 # The user made this edit, and can't patrol it
1531 # Tell them so, and then back off
1532 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1533 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1534 $wgOut->returnToMain( false, $return );
1539 # Mark the edit as patrolled
1540 RecentChange
::markPatrolled( $rcid );
1541 PatrolLog
::record( $rcid );
1542 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1545 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1546 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1547 $wgOut->returnToMain( false, $return );
1551 * User-interface handler for the "watch" action
1556 global $wgUser, $wgOut;
1558 if ( $wgUser->isAnon() ) {
1559 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1562 if ( wfReadOnly() ) {
1563 $wgOut->readOnlyPage();
1567 if( $this->doWatch() ) {
1568 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1569 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1571 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1572 $text = wfMsg( 'addedwatchtext', $link );
1573 $wgOut->addWikiText( $text );
1576 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1580 * Add this page to $wgUser's watchlist
1581 * @return bool true on successful watch operation
1583 function doWatch() {
1585 if( $wgUser->isAnon() ) {
1589 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1590 $wgUser->addWatch( $this->mTitle
);
1592 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1599 * User interface handler for the "unwatch" action.
1601 function unwatch() {
1603 global $wgUser, $wgOut;
1605 if ( $wgUser->isAnon() ) {
1606 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1609 if ( wfReadOnly() ) {
1610 $wgOut->readOnlyPage();
1614 if( $this->doUnwatch() ) {
1615 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1616 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1618 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1619 $text = wfMsg( 'removedwatchtext', $link );
1620 $wgOut->addWikiText( $text );
1623 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1627 * Stop watching a page
1628 * @return bool true on successful unwatch
1630 function doUnwatch() {
1632 if( $wgUser->isAnon() ) {
1636 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1637 $wgUser->removeWatch( $this->mTitle
);
1639 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1646 * action=protect handler
1648 function protect() {
1649 $form = new ProtectionForm( $this );
1654 * action=unprotect handler (alias)
1656 function unprotect() {
1661 * Update the article's restriction field, and leave a log entry.
1663 * @param array $limit set of restriction keys
1664 * @param string $reason
1665 * @return bool true on success
1667 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1668 global $wgUser, $wgRestrictionTypes, $wgContLang;
1670 $id = $this->mTitle
->getArticleID();
1671 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1679 // Take this opportunity to purge out expired restrictions
1680 Title
::purgeExpiredRestrictions();
1682 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1683 # we expect a single selection, but the schema allows otherwise.
1685 foreach( $wgRestrictionTypes as $action )
1686 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1688 $current = Article
::flattenRestrictions( $current );
1689 $updated = Article
::flattenRestrictions( $limit );
1691 $changed = ( $current != $updated );
1692 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1693 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1694 $protect = ( $updated != '' );
1696 # If nothing's changed, do nothing
1698 global $wgGroupPermissions;
1699 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1701 $dbw = wfGetDB( DB_MASTER
);
1703 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1705 $expiry_description = '';
1706 if ( $encodedExpiry != 'infinity' ) {
1707 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1710 # Prepare a null revision to be added to the history
1711 $modified = $current != '' && $protect;
1713 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1715 $comment_type = 'unprotectedarticle';
1717 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1719 foreach( $limit as $action => $restrictions ) {
1720 # Check if the group level required to edit also can protect pages
1721 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1722 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1725 $cascade_description = '';
1727 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1731 $comment .= ": $reason";
1733 $comment .= " [$updated]";
1734 if ( $expiry_description && $protect )
1735 $comment .= "$expiry_description";
1737 $comment .= "$cascade_description";
1739 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1740 $nullRevId = $nullRevision->insertOn( $dbw );
1742 # Update restrictions table
1743 foreach( $limit as $action => $restrictions ) {
1744 if ($restrictions != '' ) {
1745 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1746 array( 'pr_page' => $id, 'pr_type' => $action
1747 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1748 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1750 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1751 'pr_type' => $action ), __METHOD__
);
1755 # Update page record
1756 $dbw->update( 'page',
1758 'page_touched' => $dbw->timestamp(),
1759 'page_restrictions' => '',
1760 'page_latest' => $nullRevId
1761 ), array( /* WHERE */
1763 ), 'Article::protect'
1765 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1767 # Update the protection log
1768 $log = new LogPage( 'protect' );
1771 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1773 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1777 } # End "changed" check
1783 * Take an array of page restrictions and flatten it to a string
1784 * suitable for insertion into the page_restrictions field.
1785 * @param array $limit
1789 function flattenRestrictions( $limit ) {
1790 if( !is_array( $limit ) ) {
1791 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1795 foreach( $limit as $action => $restrictions ) {
1796 if( $restrictions != '' ) {
1797 $bits[] = "$action=$restrictions";
1800 return implode( ':', $bits );
1804 * UI entry point for page deletion
1807 global $wgUser, $wgOut, $wgRequest;
1808 $confirm = $wgRequest->wasPosted() &&
1809 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1810 $reason = $wgRequest->getText( 'wpReason' );
1812 # This code desperately needs to be totally rewritten
1815 if( $wgUser->isAllowed( 'delete' ) ) {
1816 if( $wgUser->isBlocked( !$confirm ) ) {
1817 $wgOut->blockedPage();
1821 $wgOut->permissionRequired( 'delete' );
1825 if( wfReadOnly() ) {
1826 $wgOut->readOnlyPage();
1830 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1832 # Better double-check that it hasn't been deleted yet!
1833 $dbw = wfGetDB( DB_MASTER
);
1834 $conds = $this->mTitle
->pageCond();
1835 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1836 if ( $latest === false ) {
1837 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1842 $this->doDelete( $reason );
1843 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1845 } elseif( $this->mTitle
->userIsWatching() ) {
1851 # determine whether this page has earlier revisions
1852 # and insert a warning if it does
1854 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1856 if( count( $authors ) > 1 && !$confirm ) {
1857 $skin=$wgUser->getSkin();
1858 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1861 # If a single user is responsible for all revisions, find out who they are
1862 if ( count( $authors ) == $maxRevisions ) {
1863 // Query bailed out, too many revisions to find out if they're all the same
1864 $authorOfAll = false;
1866 $authorOfAll = reset( $authors );
1867 foreach ( $authors as $author ) {
1868 if ( $authorOfAll != $author ) {
1869 $authorOfAll = false;
1874 # Fetch article text
1875 $rev = Revision
::newFromTitle( $this->mTitle
);
1877 if( !is_null( $rev ) ) {
1878 # if this is a mini-text, we can paste part of it into the deletion reason
1879 $text = $rev->getText();
1881 #if this is empty, an earlier revision may contain "useful" text
1884 $prev = $rev->getPrevious();
1886 $text = $prev->getText();
1891 $length = strlen( $text );
1893 # this should not happen, since it is not possible to store an empty, new
1894 # page. Let's insert a standard text in case it does, though
1895 if( $length == 0 && $reason === '' ) {
1896 $reason = wfMsgForContent( 'exblank' );
1899 if( $reason === '' ) {
1900 # comment field=255, let's grep the first 150 to have some user
1903 $text = $wgContLang->truncate( $text, 150, '...' );
1905 # let's strip out newlines
1906 $text = preg_replace( "/[\n\r]/", '', $text );
1909 if( $authorOfAll === false ) {
1910 $reason = wfMsgForContent( 'excontent', $text );
1912 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1915 $reason = wfMsgForContent( 'exbeforeblank', $text );
1920 return $this->confirmDelete( '', $reason );
1924 * Get the last N authors
1925 * @param int $num Number of revisions to get
1926 * @param string $revLatest The latest rev_id, selected from the master (optional)
1927 * @return array Array of authors, duplicates not removed
1929 function getLastNAuthors( $num, $revLatest = 0 ) {
1930 wfProfileIn( __METHOD__
);
1932 // First try the slave
1933 // If that doesn't have the latest revision, try the master
1935 $db = wfGetDB( DB_SLAVE
);
1937 $res = $db->select( array( 'page', 'revision' ),
1938 array( 'rev_id', 'rev_user_text' ),
1940 'page_namespace' => $this->mTitle
->getNamespace(),
1941 'page_title' => $this->mTitle
->getDBkey(),
1942 'rev_page = page_id'
1943 ), __METHOD__
, $this->getSelectOptions( array(
1944 'ORDER BY' => 'rev_timestamp DESC',
1949 wfProfileOut( __METHOD__
);
1952 $row = $db->fetchObject( $res );
1953 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1954 $db = wfGetDB( DB_MASTER
);
1959 } while ( $continue );
1961 $authors = array( $row->rev_user_text
);
1962 while ( $row = $db->fetchObject( $res ) ) {
1963 $authors[] = $row->rev_user_text
;
1965 wfProfileOut( __METHOD__
);
1970 * Output deletion confirmation dialog
1972 function confirmDelete( $par, $reason ) {
1973 global $wgOut, $wgUser;
1975 wfDebug( "Article::confirmDelete\n" );
1977 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1978 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1979 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1980 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1982 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1984 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1985 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1986 $token = htmlspecialchars( $wgUser->editToken() );
1987 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
1990 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1994 <label for='wpReason'>{$delcom}:</label>
1997 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
2007 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2011 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2014 $wgOut->returnToMain( false );
2016 $this->showLogExtract( $wgOut );
2021 * Show relevant lines from the deletion log
2023 function showLogExtract( $out ) {
2024 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2025 $logViewer = new LogViewer(
2028 array( 'page' => $this->mTitle
->getPrefixedText(),
2029 'type' => 'delete' ) ) ) );
2030 $logViewer->showList( $out );
2035 * Perform a deletion and output success or failure messages
2037 function doDelete( $reason ) {
2038 global $wgOut, $wgUser;
2039 wfDebug( __METHOD__
."\n" );
2041 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2042 if ( $this->doDeleteArticle( $reason ) ) {
2043 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2045 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2046 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2048 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2049 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2051 $wgOut->addWikiText( $text );
2052 $wgOut->returnToMain( false );
2053 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2055 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2061 * Back-end article deletion
2062 * Deletes the article with database consistency, writes logs, purges caches
2065 function doDeleteArticle( $reason ) {
2066 global $wgUseSquid, $wgDeferredUpdateList;
2067 global $wgUseTrackbacks;
2069 wfDebug( __METHOD__
."\n" );
2071 $dbw = wfGetDB( DB_MASTER
);
2072 $ns = $this->mTitle
->getNamespace();
2073 $t = $this->mTitle
->getDBkey();
2074 $id = $this->mTitle
->getArticleID();
2076 if ( $t == '' ||
$id == 0 ) {
2080 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2081 array_push( $wgDeferredUpdateList, $u );
2083 // For now, shunt the revision data into the archive table.
2084 // Text is *not* removed from the text table; bulk storage
2085 // is left intact to avoid breaking block-compression or
2086 // immutable storage schemes.
2088 // For backwards compatibility, note that some older archive
2089 // table entries will have ar_text and ar_flags fields still.
2091 // In the future, we may keep revisions and mark them with
2092 // the rev_deleted field, which is reserved for this purpose.
2093 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2095 'ar_namespace' => 'page_namespace',
2096 'ar_title' => 'page_title',
2097 'ar_comment' => 'rev_comment',
2098 'ar_user' => 'rev_user',
2099 'ar_user_text' => 'rev_user_text',
2100 'ar_timestamp' => 'rev_timestamp',
2101 'ar_minor_edit' => 'rev_minor_edit',
2102 'ar_rev_id' => 'rev_id',
2103 'ar_text_id' => 'rev_text_id',
2104 'ar_text' => '\'\'', // Be explicit to appease
2105 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2106 'ar_len' => 'rev_len'
2109 'page_id = rev_page'
2113 # Delete restrictions for it
2114 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2116 # Now that it's safely backed up, delete it
2117 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2119 # If using cascading deletes, we can skip some explicit deletes
2120 if ( !$dbw->cascadingDeletes() ) {
2122 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2124 if ($wgUseTrackbacks)
2125 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2127 # Delete outgoing links
2128 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2129 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2130 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2131 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2132 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2133 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2134 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2137 # If using cleanup triggers, we can skip some manual deletes
2138 if ( !$dbw->cleanupTriggers() ) {
2140 # Clean up recentchanges entries...
2141 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2145 Article
::onArticleDelete( $this->mTitle
);
2148 $log = new LogPage( 'delete' );
2149 $log->addEntry( 'delete', $this->mTitle
, $reason );
2151 # Clear the cached article id so the interface doesn't act like we exist
2152 $this->mTitle
->resetArticleID( 0 );
2153 $this->mTitle
->mArticleID
= 0;
2158 * Revert a modification
2160 function rollback() {
2161 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2163 if( $wgUser->isAllowed( 'rollback' ) ) {
2164 if( $wgUser->isBlocked() ) {
2165 $wgOut->blockedPage();
2169 $wgOut->permissionRequired( 'rollback' );
2173 if ( wfReadOnly() ) {
2174 $wgOut->readOnlyPage( $this->getContent() );
2177 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2178 array( $this->mTitle
->getPrefixedText(),
2179 $wgRequest->getVal( 'from' ) ) ) ) {
2180 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2181 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2184 $dbw = wfGetDB( DB_MASTER
);
2186 # Enhanced rollback, marks edits rc_bot=1
2187 $bot = $wgRequest->getBool( 'bot' );
2189 # Replace all this user's current edits with the next one down
2191 # Get the last editor
2192 $current = Revision
::newFromTitle( $this->mTitle
);
2193 if( is_null( $current ) ) {
2194 # Something wrong... no page?
2195 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2199 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2200 if( $from != $current->getUserText() ) {
2201 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2202 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2203 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2204 htmlspecialchars( $from ),
2205 htmlspecialchars( $current->getUserText() ) ) );
2206 if( $current->getComment() != '') {
2208 wfMsg( 'editcomment',
2209 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2214 # Get the last edit not by this guy
2215 $user = intval( $current->getUser() );
2216 $user_text = $dbw->addQuotes( $current->getUserText() );
2217 $s = $dbw->selectRow( 'revision',
2218 array( 'rev_id', 'rev_timestamp' ),
2220 'rev_page' => $current->getPage(),
2221 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2224 'USE INDEX' => 'page_timestamp',
2225 'ORDER BY' => 'rev_timestamp DESC' )
2227 if( $s === false ) {
2229 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2230 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2236 # Mark all reverted edits as bot
2239 if ( $wgUseRCPatrol ) {
2240 # Mark all reverted edits as patrolled
2241 $set['rc_patrolled'] = 1;
2245 $dbw->update( 'recentchanges', $set,
2247 'rc_cur_id' => $current->getPage(),
2248 'rc_user_text' => $current->getUserText(),
2249 "rc_timestamp > '{$s->rev_timestamp}'",
2254 # Get the edit summary
2255 $target = Revision
::newFromId( $s->rev_id
);
2256 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2257 $newComment = $wgRequest->getText( 'summary', $newComment );
2260 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2261 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2262 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2264 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2266 $wgOut->returnToMain( false );
2271 * Do standard deferred updates after page view
2274 function viewUpdates() {
2275 global $wgDeferredUpdateList;
2277 if ( 0 != $this->getID() ) {
2278 global $wgDisableCounters;
2279 if( !$wgDisableCounters ) {
2280 Article
::incViewCount( $this->getID() );
2281 $u = new SiteStatsUpdate( 1, 0, 0 );
2282 array_push( $wgDeferredUpdateList, $u );
2286 # Update newtalk / watchlist notification status
2288 $wgUser->clearNotification( $this->mTitle
);
2292 * Do standard deferred updates after page edit.
2293 * Update links tables, site stats, search index and message cache.
2294 * Every 1000th edit, prune the recent changes table.
2297 * @param $text New text of the article
2298 * @param $summary Edit summary
2299 * @param $minoredit Minor edit
2300 * @param $timestamp_of_pagechange Timestamp associated with the page change
2301 * @param $newid rev_id value of the new revision
2302 * @param $changed Whether or not the content actually changed
2304 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2305 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2307 wfProfileIn( __METHOD__
);
2310 $options = new ParserOptions
;
2311 $options->setTidy(true);
2312 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2314 # Save it to the parser cache
2315 $parserCache =& ParserCache
::singleton();
2316 $parserCache->save( $poutput, $this, $wgUser );
2318 # Update the links tables
2319 $u = new LinksUpdate( $this->mTitle
, $poutput );
2322 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2324 if ( 0 == mt_rand( 0, 99 ) ) {
2325 # Periodically flush old entries from the recentchanges table.
2328 $dbw = wfGetDB( DB_MASTER
);
2329 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2330 $recentchanges = $dbw->tableName( 'recentchanges' );
2331 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2332 $dbw->query( $sql );
2336 $id = $this->getID();
2337 $title = $this->mTitle
->getPrefixedDBkey();
2338 $shortTitle = $this->mTitle
->getDBkey();
2341 wfProfileOut( __METHOD__
);
2345 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2346 array_push( $wgDeferredUpdateList, $u );
2347 $u = new SearchUpdate( $id, $title, $text );
2348 array_push( $wgDeferredUpdateList, $u );
2350 # If this is another user's talk page, update newtalk
2351 # Don't do this if $changed = false otherwise some idiot can null-edit a
2352 # load of user talk pages and piss people off, nor if it's a minor edit
2353 # by a properly-flagged bot.
2354 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2355 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2356 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2357 $other = User
::newFromName( $shortTitle );
2358 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2359 // An anonymous user
2360 $other = new User();
2361 $other->setName( $shortTitle );
2364 $other->setNewtalk( true );
2369 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2370 $wgMessageCache->replace( $shortTitle, $text );
2373 wfProfileOut( __METHOD__
);
2377 * Perform article updates on a special page creation.
2379 * @param Revision $rev
2381 * @todo This is a shitty interface function. Kill it and replace the
2382 * other shitty functions like editUpdates and such so it's not needed
2385 function createUpdates( $rev ) {
2386 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2387 $this->mTotalAdjustment
= 1;
2388 $this->editUpdates( $rev->getText(), $rev->getComment(),
2389 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2393 * Generate the navigation links when browsing through an article revisions
2394 * It shows the information as:
2395 * Revision as of \<date\>; view current revision
2396 * \<- Previous version | Next Version -\>
2399 * @param string $oldid Revision ID of this article revision
2401 function setOldSubtitle( $oldid=0 ) {
2402 global $wgLang, $wgOut, $wgUser;
2404 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2408 $revision = Revision
::newFromId( $oldid );
2410 $current = ( $oldid == $this->mLatest
);
2411 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2412 $sk = $wgUser->getSkin();
2414 ?
wfMsg( 'currentrevisionlink' )
2415 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2418 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2419 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2421 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2422 : wfMsg( 'previousrevision' );
2424 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2426 $nextlink = $current
2427 ?
wfMsg( 'nextrevision' )
2428 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2429 $nextdiff = $current
2431 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2433 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2434 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2436 $m = wfMsg( 'revision-info-current' );
2437 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2438 ?
'revision-info-current'
2441 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2442 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2443 $wgOut->setSubtitle( $r );
2447 * This function is called right before saving the wikitext,
2448 * so we can do things like signatures and links-in-context.
2450 * @param string $text
2452 function preSaveTransform( $text ) {
2453 global $wgParser, $wgUser;
2454 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2457 /* Caching functions */
2460 * checkLastModified returns true if it has taken care of all
2461 * output to the client that is necessary for this request.
2462 * (that is, it has sent a cached version of the page)
2464 function tryFileCache() {
2465 static $called = false;
2467 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2471 if($this->isFileCacheable()) {
2472 $touched = $this->mTouched
;
2473 $cache = new HTMLFileCache( $this->mTitle
);
2474 if($cache->isFileCacheGood( $touched )) {
2475 wfDebug( "Article::tryFileCache(): about to load file\n" );
2476 $cache->loadFromFileCache();
2479 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2480 ob_start( array(&$cache, 'saveToFileCache' ) );
2483 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2488 * Check if the page can be cached
2491 function isFileCacheable() {
2492 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2493 $action = $wgRequest->getVal( 'action' );
2494 $oldid = $wgRequest->getVal( 'oldid' );
2495 $diff = $wgRequest->getVal( 'diff' );
2496 $redirect = $wgRequest->getVal( 'redirect' );
2497 $printable = $wgRequest->getVal( 'printable' );
2498 $page = $wgRequest->getVal( 'page' );
2500 //check for non-standard user language; this covers uselang,
2501 //and extensions for auto-detecting user language.
2502 $ulang = $wgLang->getCode();
2503 $clang = $wgContLang->getCode();
2505 $cacheable = $wgUseFileCache
2506 && (!$wgShowIPinHeader)
2507 && ($this->getID() != 0)
2508 && ($wgUser->isAnon())
2509 && (!$wgUser->getNewtalk())
2510 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2511 && (empty( $action ) ||
$action == 'view')
2514 && (!isset($redirect))
2515 && (!isset($printable))
2517 && (!$this->mRedirectedFrom
)
2518 && ($ulang === $clang);
2521 //extension may have reason to disable file caching on some pages.
2522 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2529 * Loads page_touched and returns a value indicating if it should be used
2532 function checkTouched() {
2533 if( !$this->mDataLoaded
) {
2534 $this->loadPageData();
2536 return !$this->mIsRedirect
;
2540 * Get the page_touched field
2542 function getTouched() {
2543 # Ensure that page data has been loaded
2544 if( !$this->mDataLoaded
) {
2545 $this->loadPageData();
2547 return $this->mTouched
;
2551 * Get the page_latest field
2553 function getLatest() {
2554 if ( !$this->mDataLoaded
) {
2555 $this->loadPageData();
2557 return $this->mLatest
;
2561 * Edit an article without doing all that other stuff
2562 * The article must already exist; link tables etc
2563 * are not updated, caches are not flushed.
2565 * @param string $text text submitted
2566 * @param string $comment comment submitted
2567 * @param bool $minor whereas it's a minor modification
2569 function quickEdit( $text, $comment = '', $minor = 0 ) {
2570 wfProfileIn( __METHOD__
);
2572 $dbw = wfGetDB( DB_MASTER
);
2574 $revision = new Revision( array(
2575 'page' => $this->getId(),
2577 'comment' => $comment,
2578 'minor_edit' => $minor ?
1 : 0,
2580 $revision->insertOn( $dbw );
2581 $this->updateRevisionOn( $dbw, $revision );
2584 wfProfileOut( __METHOD__
);
2588 * Used to increment the view counter
2591 * @param integer $id article id
2593 function incViewCount( $id ) {
2594 $id = intval( $id );
2595 global $wgHitcounterUpdateFreq, $wgDBtype;
2597 $dbw = wfGetDB( DB_MASTER
);
2598 $pageTable = $dbw->tableName( 'page' );
2599 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2600 $acchitsTable = $dbw->tableName( 'acchits' );
2602 if( $wgHitcounterUpdateFreq <= 1 ) {
2603 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2607 # Not important enough to warrant an error page in case of failure
2608 $oldignore = $dbw->ignoreErrors( true );
2610 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2612 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2613 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2614 # Most of the time (or on SQL errors), skip row count check
2615 $dbw->ignoreErrors( $oldignore );
2619 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2620 $row = $dbw->fetchObject( $res );
2621 $rown = intval( $row->n
);
2622 if( $rown >= $wgHitcounterUpdateFreq ){
2623 wfProfileIn( 'Article::incViewCount-collect' );
2624 $old_user_abort = ignore_user_abort( true );
2626 if ($wgDBtype == 'mysql')
2627 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2628 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2629 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2630 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2632 $dbw->query("DELETE FROM $hitcounterTable");
2633 if ($wgDBtype == 'mysql') {
2634 $dbw->query('UNLOCK TABLES');
2635 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2636 'WHERE page_id = hc_id');
2639 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2640 "FROM $acchitsTable WHERE page_id = hc_id");
2642 $dbw->query("DROP TABLE $acchitsTable");
2644 ignore_user_abort( $old_user_abort );
2645 wfProfileOut( 'Article::incViewCount-collect' );
2647 $dbw->ignoreErrors( $oldignore );
2651 * The onArticle*() functions are supposed to be a kind of hooks
2652 * which should be called whenever any of the specified actions
2655 * This is a good place to put code to clear caches, for instance.
2657 * This is called on page move and undelete, as well as edit
2659 * @param $title_obj a title object
2662 static function onArticleCreate($title) {
2663 # The talk page isn't in the regular link tables, so we need to update manually:
2664 if ( $title->isTalkPage() ) {
2665 $other = $title->getSubjectPage();
2667 $other = $title->getTalkPage();
2669 $other->invalidateCache();
2670 $other->purgeSquid();
2672 $title->touchLinks();
2673 $title->purgeSquid();
2676 static function onArticleDelete( $title ) {
2677 global $wgUseFileCache, $wgMessageCache;
2679 $title->touchLinks();
2680 $title->purgeSquid();
2683 if ( $wgUseFileCache ) {
2684 $cm = new HTMLFileCache( $title );
2685 @unlink
( $cm->fileCacheName() );
2688 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2689 $wgMessageCache->replace( $title->getDBkey(), false );
2694 * Purge caches on page update etc
2696 static function onArticleEdit( $title ) {
2697 global $wgDeferredUpdateList, $wgUseFileCache;
2699 // Invalidate caches of articles which include this page
2700 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2701 $wgDeferredUpdateList[] = $update;
2703 # Purge squid for this page only
2704 $title->purgeSquid();
2707 if ( $wgUseFileCache ) {
2708 $cm = new HTMLFileCache( $title );
2709 @unlink
( $cm->fileCacheName() );
2716 * Info about this page
2717 * Called for ?action=info when $wgAllowPageInfo is on.
2722 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2724 if ( !$wgAllowPageInfo ) {
2725 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2729 $page = $this->mTitle
->getSubjectPage();
2731 $wgOut->setPagetitle( $page->getPrefixedText() );
2732 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2734 # first, see if the page exists at all.
2735 $exists = $page->getArticleId() != 0;
2737 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2738 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2740 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2743 $dbr = wfGetDB( DB_SLAVE
);
2745 'wl_title' => $page->getDBkey(),
2746 'wl_namespace' => $page->getNamespace() );
2747 $numwatchers = $dbr->selectField(
2752 $this->getSelectOptions() );
2754 $pageInfo = $this->pageCountInfo( $page );
2755 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2757 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2758 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2760 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2762 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2764 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2766 $wgOut->addHTML( '</ul>' );
2772 * Return the total number of edits and number of unique editors
2773 * on a given page. If page does not exist, returns false.
2775 * @param Title $title
2779 function pageCountInfo( $title ) {
2780 $id = $title->getArticleId();
2785 $dbr = wfGetDB( DB_SLAVE
);
2787 $rev_clause = array( 'rev_page' => $id );
2789 $edits = $dbr->selectField(
2794 $this->getSelectOptions() );
2796 $authors = $dbr->selectField(
2798 'COUNT(DISTINCT rev_user_text)',
2801 $this->getSelectOptions() );
2803 return array( 'edits' => $edits, 'authors' => $authors );
2807 * Return a list of templates used by this article.
2808 * Uses the templatelinks table
2810 * @return array Array of Title objects
2812 function getUsedTemplates() {
2814 $id = $this->mTitle
->getArticleID();
2819 $dbr = wfGetDB( DB_SLAVE
);
2820 $res = $dbr->select( array( 'templatelinks' ),
2821 array( 'tl_namespace', 'tl_title' ),
2822 array( 'tl_from' => $id ),
2823 'Article:getUsedTemplates' );
2824 if ( false !== $res ) {
2825 if ( $dbr->numRows( $res ) ) {
2826 while ( $row = $dbr->fetchObject( $res ) ) {
2827 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2831 $dbr->freeResult( $res );
2836 * Return an auto-generated summary if the text provided is a redirect.
2838 * @param string $text The wikitext to check
2839 * @return string '' or an appropriate summary
2841 public static function getRedirectAutosummary( $text ) {
2842 $rt = Title
::newFromRedirect( $text );
2843 if( is_object( $rt ) )
2844 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2850 * Return an auto-generated summary if the new text is much shorter than
2853 * @param string $oldtext The previous text of the page
2854 * @param string $text The submitted text of the page
2855 * @return string An appropriate autosummary, or an empty string.
2857 public static function getBlankingAutosummary( $oldtext, $text ) {
2858 if ($oldtext!='' && $text=='') {
2859 return wfMsgForContent('autosumm-blank');
2860 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2861 #Removing more than 90% of the article
2863 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2864 return wfMsgForContent('autosumm-replace', $truncatedtext);
2871 * Return an applicable autosummary if one exists for the given edit.
2872 * @param string $oldtext The previous text of the page.
2873 * @param string $newtext The submitted text of the page.
2874 * @param bitmask $flags A bitmask of flags submitted for the edit.
2875 * @return string An appropriate autosummary, or an empty string.
2877 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2879 # This code is UGLY UGLY UGLY.
2880 # Somebody PLEASE come up with a more elegant way to do it.
2882 #Redirect autosummaries
2883 $summary = self
::getRedirectAutosummary( $newtext );
2888 #Blanking autosummaries
2889 if (!($flags & EDIT_NEW
))
2890 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
2895 #New page autosummaries
2896 if ($flags & EDIT_NEW
&& strlen($newtext)) {
2897 #If they're making a new article, give its text, truncated, in the summary.
2899 $truncatedtext = $wgContLang->truncate(
2900 str_replace("\n", ' ', $newtext),
2901 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2903 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2913 * Add the primary page-view wikitext to the output buffer
2914 * Saves the text into the parser cache if possible.
2915 * Updates templatelinks if it is out of date.
2917 * @param string $text
2918 * @param bool $cache
2920 public function outputWikiText( $text, $cache = true ) {
2921 global $wgParser, $wgUser, $wgOut;
2923 $popts = $wgOut->parserOptions();
2924 $popts->setTidy(true);
2925 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
2926 $popts, true, true, $this->getRevIdFetched() );
2927 $popts->setTidy(false);
2928 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
2929 $parserCache =& ParserCache
::singleton();
2930 $parserCache->save( $parserOutput, $this, $wgUser );
2933 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
2934 // templatelinks table may have become out of sync,
2935 // especially if using variable-based transclusions.
2936 // For paranoia, check if things have changed and if
2937 // so apply updates to the database. This will ensure
2938 // that cascaded protections apply as soon as the changes
2941 # Get templates from templatelinks
2942 $id = $this->mTitle
->getArticleID();
2944 $tlTemplates = array();
2946 $dbr = wfGetDB( DB_SLAVE
);
2947 $res = $dbr->select( array( 'templatelinks' ),
2948 array( 'tl_namespace', 'tl_title' ),
2949 array( 'tl_from' => $id ),
2950 'Article:getUsedTemplates' );
2954 if ( false !== $res ) {
2955 if ( $dbr->numRows( $res ) ) {
2956 while ( $row = $dbr->fetchObject( $res ) ) {
2957 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
2962 # Get templates from parser output.
2963 $poTemplates_allns = $parserOutput->getTemplates();
2965 $poTemplates = array ();
2966 foreach ( $poTemplates_allns as $ns_templates ) {
2967 $poTemplates = array_merge( $poTemplates, $ns_templates );
2971 $templates_diff = array_diff( $poTemplates, $tlTemplates );
2973 if ( count( $templates_diff ) > 0 ) {
2974 # Whee, link updates time.
2975 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
2977 $dbw = wfGetDb( DB_MASTER
);
2986 $wgOut->addParserOutput( $parserOutput );