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 if ( 0 == $this->getID() ) {
145 wfProfileOut( __METHOD__
);
146 $wgOut->setRobotpolicy( 'noindex,nofollow' );
148 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
149 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
151 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
154 return "<div class='noarticletext'>$ret</div>";
156 $this->loadContent();
157 wfProfileOut( __METHOD__
);
158 return $this->mContent
;
163 * This function returns the text of a section, specified by a number ($section).
164 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
165 * the first section before any such heading (section 0).
167 * If a section contains subsections, these are also returned.
169 * @param $text String: text to look in
170 * @param $section Integer: section number
171 * @return string text of the requested section
174 function getSection($text,$section) {
176 return $wgParser->getSection( $text, $section );
180 * @return int The oldid of the article that is to be shown, 0 for the
183 function getOldID() {
184 if ( is_null( $this->mOldId
) ) {
185 $this->mOldId
= $this->getOldIDFromRequest();
187 return $this->mOldId
;
191 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
193 * @return int The old id for the request
195 function getOldIDFromRequest() {
197 $this->mRedirectUrl
= false;
198 $oldid = $wgRequest->getVal( 'oldid' );
199 if ( isset( $oldid ) ) {
200 $oldid = intval( $oldid );
201 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
202 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
206 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
208 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
209 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
227 * Load the revision (including text) into this object
229 function loadContent() {
230 if ( $this->mContentLoaded
) return;
233 $oldid = $this->getOldID();
235 # Pre-fill content with error message so that if something
236 # fails we'll have something telling us what we intended.
237 $this->mOldId
= $oldid;
238 $this->fetchContent( $oldid );
243 * Fetch a page record with the given conditions
244 * @param Database $dbr
245 * @param array $conditions
248 function pageData( $dbr, $conditions ) {
261 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
262 $row = $dbr->selectRow( 'page',
265 'Article::pageData' );
266 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
271 * @param Database $dbr
272 * @param Title $title
274 function pageDataFromTitle( $dbr, $title ) {
275 return $this->pageData( $dbr, array(
276 'page_namespace' => $title->getNamespace(),
277 'page_title' => $title->getDBkey() ) );
281 * @param Database $dbr
284 function pageDataFromId( $dbr, $id ) {
285 return $this->pageData( $dbr, array( 'page_id' => $id ) );
289 * Set the general counter, title etc data loaded from
292 * @param object $data
295 function loadPageData( $data = 'fromdb' ) {
296 if ( $data === 'fromdb' ) {
297 $dbr = $this->getDB();
298 $data = $this->pageDataFromId( $dbr, $this->getId() );
301 $lc =& LinkCache
::singleton();
303 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
305 $this->mTitle
->mArticleID
= $data->page_id
;
307 # Old-fashioned restrictions.
308 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
310 $this->mCounter
= $data->page_counter
;
311 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
312 $this->mIsRedirect
= $data->page_is_redirect
;
313 $this->mLatest
= $data->page_latest
;
315 if ( is_object( $this->mTitle
) ) {
316 $lc->addBadLinkObj( $this->mTitle
);
318 $this->mTitle
->mArticleID
= 0;
321 $this->mDataLoaded
= true;
325 * Get text of an article from database
326 * Does *NOT* follow redirects.
327 * @param int $oldid 0 for whatever the latest revision is
330 function fetchContent( $oldid = 0 ) {
331 if ( $this->mContentLoaded
) {
332 return $this->mContent
;
335 $dbr = $this->getDB();
337 # Pre-fill content with error message so that if something
338 # fails we'll have something telling us what we intended.
339 $t = $this->mTitle
->getPrefixedText();
341 $t .= ',oldid='.$oldid;
343 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
346 $revision = Revision
::newFromId( $oldid );
347 if( is_null( $revision ) ) {
348 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
351 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
353 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
356 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
357 $this->loadPageData( $data );
359 if( !$this->mDataLoaded
) {
360 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
362 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
365 $this->loadPageData( $data );
367 $revision = Revision
::newFromId( $this->mLatest
);
368 if( is_null( $revision ) ) {
369 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
374 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
375 // We should instead work with the Revision object when we need it...
376 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
377 //$this->mContent = $revision->getText();
379 $this->mUser
= $revision->getUser();
380 $this->mUserText
= $revision->getUserText();
381 $this->mComment
= $revision->getComment();
382 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
384 $this->mRevIdFetched
= $revision->getID();
385 $this->mContentLoaded
= true;
386 $this->mRevision
=& $revision;
388 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
390 return $this->mContent
;
394 * Read/write accessor to select FOR UPDATE
396 * @param $x Mixed: FIXME
398 function forUpdate( $x = NULL ) {
399 return wfSetVar( $this->mForUpdate
, $x );
403 * Get the database which should be used for reads
408 return wfGetDB( DB_MASTER
);
412 * Get options for all SELECT statements
414 * @param $options Array: an optional options array which'll be appended to
416 * @return Array: options
418 function getSelectOptions( $options = '' ) {
419 if ( $this->mForUpdate
) {
420 if ( is_array( $options ) ) {
421 $options[] = 'FOR UPDATE';
423 $options = 'FOR UPDATE';
430 * @return int Page ID
433 if( $this->mTitle
) {
434 return $this->mTitle
->getArticleID();
441 * @return bool Whether or not the page exists in the database
444 return $this->getId() != 0;
448 * @return int The view count for the page
450 function getCount() {
451 if ( -1 == $this->mCounter
) {
452 $id = $this->getID();
456 $dbr = wfGetDB( DB_SLAVE
);
457 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
458 'Article::getCount', $this->getSelectOptions() );
461 return $this->mCounter
;
465 * Determine whether a page would be suitable for being counted as an
466 * article in the site_stats table based on the title & its content
468 * @param $text String: text to analyze
471 function isCountable( $text ) {
472 global $wgUseCommaCount;
474 $token = $wgUseCommaCount ?
',' : '[[';
476 $this->mTitle
->isContentPage()
477 && !$this->isRedirect( $text )
478 && in_string( $token, $text );
482 * Tests if the article text represents a redirect
484 * @param $text String: FIXME
487 function isRedirect( $text = false ) {
488 if ( $text === false ) {
489 $this->loadContent();
490 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
492 $titleObj = Title
::newFromRedirect( $text );
494 return $titleObj !== NULL;
498 * Returns true if the currently-referenced revision is the current edit
499 * to this page (and it exists).
502 function isCurrent() {
503 # If no oldid, this is the current version.
504 if ($this->getOldID() == 0)
507 return $this->exists() &&
508 isset( $this->mRevision
) &&
509 $this->mRevision
->isCurrent();
513 * Loads everything except the text
514 * This isn't necessary for all uses, so it's only done if needed.
517 function loadLastEdit() {
518 if ( -1 != $this->mUser
)
521 # New or non-existent articles have no user information
522 $id = $this->getID();
523 if ( 0 == $id ) return;
525 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
526 if( !is_null( $this->mLastRevision
) ) {
527 $this->mUser
= $this->mLastRevision
->getUser();
528 $this->mUserText
= $this->mLastRevision
->getUserText();
529 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
530 $this->mComment
= $this->mLastRevision
->getComment();
531 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
532 $this->mRevIdFetched
= $this->mLastRevision
->getID();
536 function getTimestamp() {
537 // Check if the field has been filled by ParserCache::get()
538 if ( !$this->mTimestamp
) {
539 $this->loadLastEdit();
541 return wfTimestamp(TS_MW
, $this->mTimestamp
);
545 $this->loadLastEdit();
549 function getUserText() {
550 $this->loadLastEdit();
551 return $this->mUserText
;
554 function getComment() {
555 $this->loadLastEdit();
556 return $this->mComment
;
559 function getMinorEdit() {
560 $this->loadLastEdit();
561 return $this->mMinorEdit
;
564 function getRevIdFetched() {
565 $this->loadLastEdit();
566 return $this->mRevIdFetched
;
570 * @todo Document, fixme $offset never used.
571 * @param $limit Integer: default 0.
572 * @param $offset Integer: default 0.
574 function getContributors($limit = 0, $offset = 0) {
575 # XXX: this is expensive; cache this info somewhere.
578 $dbr = wfGetDB( DB_SLAVE
);
579 $revTable = $dbr->tableName( 'revision' );
580 $userTable = $dbr->tableName( 'user' );
581 $user = $this->getUser();
582 $pageId = $this->getId();
584 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
585 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
586 WHERE rev_page = $pageId
587 AND rev_user != $user
588 GROUP BY rev_user, rev_user_text, user_real_name
589 ORDER BY timestamp DESC";
591 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
592 $sql .= ' '. $this->getSelectOptions();
594 $res = $dbr->query($sql, __METHOD__
);
596 while ( $line = $dbr->fetchObject( $res ) ) {
597 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
600 $dbr->freeResult($res);
605 * This is the default action of the script: just view the page of
609 global $wgUser, $wgOut, $wgRequest, $wgContLang;
610 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
611 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
612 $sk = $wgUser->getSkin();
614 wfProfileIn( __METHOD__
);
616 $parserCache =& ParserCache
::singleton();
617 $ns = $this->mTitle
->getNamespace(); # shortcut
619 # Get variables from query string
620 $oldid = $this->getOldID();
622 # getOldID may want us to redirect somewhere else
623 if ( $this->mRedirectUrl
) {
624 $wgOut->redirect( $this->mRedirectUrl
);
625 wfProfileOut( __METHOD__
);
629 $diff = $wgRequest->getVal( 'diff' );
630 $rcid = $wgRequest->getVal( 'rcid' );
631 $rdfrom = $wgRequest->getVal( 'rdfrom' );
632 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
634 $wgOut->setArticleFlag( true );
636 # Discourage indexing of printable versions, but encourage following
637 if( $wgOut->isPrintable() ) {
638 $policy = 'noindex,follow';
639 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
640 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
641 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
642 # Honour customised robot policies for this namespace
643 $policy = $wgNamespaceRobotPolicies[$ns];
645 # Default to encourage indexing and following links
646 $policy = 'index,follow';
648 $wgOut->setRobotPolicy( $policy );
650 # If we got diff and oldid in the query, we want to see a
651 # diff page instead of the article.
653 if ( !is_null( $diff ) ) {
654 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
656 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
657 // DifferenceEngine directly fetched the revision:
658 $this->mRevIdFetched
= $de->mNewid
;
659 $de->showDiffPage( $diffOnly );
661 // Needed to get the page's current revision
662 $this->loadPageData();
663 if( $diff == 0 ||
$diff == $this->mLatest
) {
664 # Run view updates for current revision only
665 $this->viewUpdates();
667 wfProfileOut( __METHOD__
);
671 if ( empty( $oldid ) && $this->checkTouched() ) {
672 $wgOut->setETag($parserCache->getETag($this, $wgUser));
674 if( $wgOut->checkLastModified( $this->mTouched
) ){
675 wfProfileOut( __METHOD__
);
677 } else if ( $this->tryFileCache() ) {
678 # tell wgOut that output is taken care of
680 $this->viewUpdates();
681 wfProfileOut( __METHOD__
);
686 # Should the parser cache be used?
687 $pcache = $wgEnableParserCache
688 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
691 && !$this->mTitle
->isCssOrJsPage()
692 && !$this->mTitle
->isCssJsSubpage();
693 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
694 if ( $wgUser->getOption( 'stubthreshold' ) ) {
695 wfIncrStats( 'pcache_miss_stub' );
698 $wasRedirected = false;
699 if ( isset( $this->mRedirectedFrom
) ) {
700 // This is an internally redirected page view.
701 // We'll need a backlink to the source page for navigation.
702 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
703 $sk = $wgUser->getSkin();
704 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
705 $s = wfMsg( 'redirectedfrom', $redir );
706 $wgOut->setSubtitle( $s );
708 // Set the fragment if one was specified in the redirect
709 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
710 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
711 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
713 $wasRedirected = true;
715 } elseif ( !empty( $rdfrom ) ) {
716 // This is an externally redirected view, from some other wiki.
717 // If it was reported from a trusted site, supply a backlink.
718 global $wgRedirectSources;
719 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
720 $sk = $wgUser->getSkin();
721 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
722 $s = wfMsg( 'redirectedfrom', $redir );
723 $wgOut->setSubtitle( $s );
724 $wasRedirected = true;
729 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
731 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
732 // Ensure that UI elements requiring revision ID have
733 // the correct version information.
734 $wgOut->setRevisionId( $this->mLatest
);
738 if ( !$outputDone ) {
739 $text = $this->getContent();
740 if ( $text === false ) {
741 # Failed to load, replace text with error message
742 $t = $this->mTitle
->getPrefixedText();
744 $t .= ',oldid='.$oldid;
745 $text = wfMsg( 'missingarticle', $t );
747 $text = wfMsg( 'noarticletext', $t );
751 # Another whitelist check in case oldid is altering the title
752 if ( !$this->mTitle
->userCanRead() ) {
753 $wgOut->loginToUse();
758 # We're looking at an old revision
760 if ( !empty( $oldid ) ) {
761 $wgOut->setRobotpolicy( 'noindex,nofollow' );
762 if( is_null( $this->mRevision
) ) {
763 // FIXME: This would be a nice place to load the 'no such page' text.
765 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
766 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
767 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
768 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
769 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
772 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
773 // and we are allowed to see...
781 $wgOut->setRevisionId( $this->getRevIdFetched() );
783 // Pages containing custom CSS or JavaScript get special treatment
784 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
785 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
787 // Give hooks a chance to customise the output
788 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
789 // Wrap the whole lot in a <pre> and don't parse
790 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
791 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
792 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
793 $wgOut->addHtml( "\n</pre>\n" );
798 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
800 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
801 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
802 # Don't overwrite the subtitle if this was an old revision
803 if( !$wasRedirected && $this->isCurrent() ) {
804 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
806 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
808 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
809 '<span class="redirectText">'.$link.'</span>' );
811 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
812 $wgOut->addParserOutputNoText( $parseout );
813 } else if ( $pcache ) {
814 # Display content and save to parser cache
815 $this->outputWikiText( $text );
817 # Display content, don't attempt to save to parser cache
818 # Don't show section-edit links on old revisions... this way lies madness.
819 if( !$this->isCurrent() ) {
820 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
822 # Display content and don't save to parser cache
823 # With timing hack -- TS 2006-07-26
825 $this->outputWikiText( $text, false );
830 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
831 $this->mTitle
->getPrefixedDBkey()));
834 if( !$this->isCurrent() ) {
835 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
840 /* title may have been set from the cache */
841 $t = $wgOut->getPageTitle();
843 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
846 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
847 if( $ns == NS_USER_TALK
&&
848 User
::isIP( $this->mTitle
->getText() ) ) {
849 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
852 # If we have been passed an &rcid= parameter, we want to give the user a
853 # chance to mark this new article as patrolled.
854 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
856 "<div class='patrollink'>" .
857 wfMsgHtml( 'markaspatrolledlink',
858 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
859 "action=markpatrolled&rcid=$rcid" )
866 if ($wgUseTrackbacks)
867 $this->addTrackbacks();
869 $this->viewUpdates();
870 wfProfileOut( __METHOD__
);
873 function addTrackbacks() {
874 global $wgOut, $wgUser;
876 $dbr = wfGetDB(DB_SLAVE
);
878 /* FROM */ 'trackbacks',
879 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
880 /* WHERE */ array('tb_page' => $this->getID())
883 if (!$dbr->numrows($tbs))
887 while ($o = $dbr->fetchObject($tbs)) {
889 if ($wgUser->isAllowed( 'trackback' )) {
890 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
891 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
892 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
894 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
901 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
904 function deletetrackback() {
905 global $wgUser, $wgRequest, $wgOut, $wgTitle;
907 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
908 $wgOut->addWikitext(wfMsg('sessionfailure'));
912 if ((!$wgUser->isAllowed('delete'))) {
913 $wgOut->permissionRequired( 'delete' );
918 $wgOut->readOnlyPage();
922 $db = wfGetDB(DB_MASTER
);
923 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
924 $wgTitle->invalidateCache();
925 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
931 $wgOut->setArticleBodyOnly(true);
936 * Handle action=purge
939 global $wgUser, $wgRequest, $wgOut;
941 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
942 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
946 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
947 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
948 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
949 $msg = str_replace( '$1',
950 "<form method=\"post\" action=\"$action\">\n" .
951 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
954 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
955 $wgOut->setRobotpolicy( 'noindex,nofollow' );
956 $wgOut->addHTML( $msg );
961 * Perform the actions of a page purging
965 // Invalidate the cache
966 $this->mTitle
->invalidateCache();
969 // Commit the transaction before the purge is sent
970 $dbw = wfGetDB( DB_MASTER
);
971 $dbw->immediateCommit();
974 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
981 * Insert a new empty page record for this article.
982 * This *must* be followed up by creating a revision
983 * and running $this->updateToLatest( $rev_id );
984 * or else the record will be left in a funky state.
985 * Best if all done inside a transaction.
987 * @param Database $dbw
988 * @return int The newly created page_id key
991 function insertOn( $dbw ) {
992 wfProfileIn( __METHOD__
);
994 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
995 $dbw->insert( 'page', array(
996 'page_id' => $page_id,
997 'page_namespace' => $this->mTitle
->getNamespace(),
998 'page_title' => $this->mTitle
->getDBkey(),
1000 'page_restrictions' => '',
1001 'page_is_redirect' => 0, # Will set this shortly...
1003 'page_random' => wfRandom(),
1004 'page_touched' => $dbw->timestamp(),
1005 'page_latest' => 0, # Fill this in shortly...
1006 'page_len' => 0, # Fill this in shortly...
1008 $newid = $dbw->insertId();
1010 $this->mTitle
->resetArticleId( $newid );
1012 wfProfileOut( __METHOD__
);
1017 * Update the page record to point to a newly saved revision.
1019 * @param Database $dbw
1020 * @param Revision $revision For ID number, and text used to set
1021 length and redirect status fields
1022 * @param int $lastRevision If given, will not overwrite the page field
1023 * when different from the currently set value.
1024 * Giving 0 indicates the new page flag should
1026 * @param bool $lastRevIsRedirect If given, will optimize adding and
1027 * removing rows in redirect table.
1028 * @return bool true on success, false on failure
1031 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1032 wfProfileIn( __METHOD__
);
1034 $text = $revision->getText();
1035 $rt = Title
::newFromRedirect( $text );
1037 $conditions = array( 'page_id' => $this->getId() );
1038 if( !is_null( $lastRevision ) ) {
1039 # An extra check against threads stepping on each other
1040 $conditions['page_latest'] = $lastRevision;
1043 $dbw->update( 'page',
1045 'page_latest' => $revision->getId(),
1046 'page_touched' => $dbw->timestamp(),
1047 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1048 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1049 'page_len' => strlen( $text ),
1054 $result = $dbw->affectedRows() != 0;
1057 // FIXME: Should the result from updateRedirectOn() be returned instead?
1058 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1061 wfProfileOut( __METHOD__
);
1066 * Add row to the redirect table if this is a redirect, remove otherwise.
1068 * @param Database $dbw
1069 * @param $redirectTitle a title object pointing to the redirect target,
1070 * or NULL if this is not a redirect
1071 * @param bool $lastRevIsRedirect If given, will optimize adding and
1072 * removing rows in redirect table.
1073 * @return bool true on success, false on failure
1076 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1078 // Always update redirects (target link might have changed)
1079 // Update/Insert if we don't know if the last revision was a redirect or not
1080 // Delete if changing from redirect to non-redirect
1081 $isRedirect = !is_null($redirectTitle);
1082 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1084 wfProfileIn( __METHOD__
);
1088 // This title is a redirect, Add/Update row in the redirect table
1089 $set = array( /* SET */
1090 'rd_namespace' => $redirectTitle->getNamespace(),
1091 'rd_title' => $redirectTitle->getDBkey(),
1092 'rd_from' => $this->getId(),
1095 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1097 // This is not a redirect, remove row from redirect table
1098 $where = array( 'rd_from' => $this->getId() );
1099 $dbw->delete( 'redirect', $where, __METHOD__
);
1102 wfProfileOut( __METHOD__
);
1103 return ( $dbw->affectedRows() != 0 );
1110 * If the given revision is newer than the currently set page_latest,
1111 * update the page record. Otherwise, do nothing.
1113 * @param Database $dbw
1114 * @param Revision $revision
1116 function updateIfNewerOn( &$dbw, $revision ) {
1117 wfProfileIn( __METHOD__
);
1119 $row = $dbw->selectRow(
1120 array( 'revision', 'page' ),
1121 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1123 'page_id' => $this->getId(),
1124 'page_latest=rev_id' ),
1127 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1128 wfProfileOut( __METHOD__
);
1131 $prev = $row->rev_id
;
1132 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1134 # No or missing previous revision; mark the page as new
1136 $lastRevIsRedirect = null;
1139 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1140 wfProfileOut( __METHOD__
);
1145 * @return string Complete article text, or null if error
1147 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1148 wfProfileIn( __METHOD__
);
1150 if( $section == '' ) {
1151 // Whole-page edit; let the text through unmolested.
1153 if( is_null( $edittime ) ) {
1154 $rev = Revision
::newFromTitle( $this->mTitle
);
1156 $dbw = wfGetDB( DB_MASTER
);
1157 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1159 if( is_null( $rev ) ) {
1160 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1161 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1164 $oldtext = $rev->getText();
1166 if( $section == 'new' ) {
1167 # Inserting a new section
1168 $subject = $summary ?
"== {$summary} ==\n\n" : '';
1169 $text = strlen( trim( $oldtext ) ) > 0
1170 ?
"{$oldtext}\n\n{$subject}{$text}"
1171 : "{$subject}{$text}";
1173 # Replacing an existing section; roll out the big guns
1175 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1180 wfProfileOut( __METHOD__
);
1185 * @deprecated use Article::doEdit()
1187 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1188 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1189 ( $isminor ? EDIT_MINOR
: 0 ) |
1190 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1192 # If this is a comment, add the summary as headline
1193 if ( $comment && $summary != "" ) {
1194 $text = "== {$summary} ==\n\n".$text;
1197 $this->doEdit( $text, $summary, $flags );
1199 $dbw = wfGetDB( DB_MASTER
);
1201 if (!$this->mTitle
->userIsWatching()) {
1207 if ( $this->mTitle
->userIsWatching() ) {
1213 $this->doRedirect( $this->isRedirect( $text ) );
1217 * @deprecated use Article::doEdit()
1219 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1220 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1221 ( $minor ? EDIT_MINOR
: 0 ) |
1222 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1224 $good = $this->doEdit( $text, $summary, $flags );
1226 $dbw = wfGetDB( DB_MASTER
);
1228 if (!$this->mTitle
->userIsWatching()) {
1234 if ( $this->mTitle
->userIsWatching() ) {
1241 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1249 * Change an existing article or create a new article. Updates RC and all necessary caches,
1250 * optionally via the deferred update array.
1252 * $wgUser must be set before calling this function.
1254 * @param string $text New text
1255 * @param string $summary Edit summary
1256 * @param integer $flags bitfield:
1258 * Article is known or assumed to be non-existent, create a new one
1260 * Article is known or assumed to be pre-existing, update it
1262 * Mark this edit minor, if the user is allowed to do so
1264 * Do not log the change in recentchanges
1266 * Mark the edit a "bot" edit regardless of user rights
1267 * EDIT_DEFER_UPDATES
1268 * Defer some of the updates until the end of index.php
1270 * Fill in blank summaries with generated text where possible
1272 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1273 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1274 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1275 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1276 * to MediaWiki's performance-optimised locking strategy.
1278 * @return bool success
1280 function doEdit( $text, $summary, $flags = 0 ) {
1281 global $wgUser, $wgDBtransactions;
1283 wfProfileIn( __METHOD__
);
1286 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1287 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1289 $flags |
= EDIT_UPDATE
;
1295 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1296 &$summary, $flags & EDIT_MINOR
,
1297 null, null, &$flags ) ) )
1299 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1300 wfProfileOut( __METHOD__
);
1304 # Silently ignore EDIT_MINOR if not allowed
1305 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1306 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1308 $oldtext = $this->getContent();
1309 $oldsize = strlen( $oldtext );
1311 # Provide autosummaries if one is not provided.
1312 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1313 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1315 $text = $this->preSaveTransform( $text );
1316 $newsize = strlen( $text );
1318 $dbw = wfGetDB( DB_MASTER
);
1319 $now = wfTimestampNow();
1321 if ( $flags & EDIT_UPDATE
) {
1322 # Update article, but only if changed.
1324 # Make sure the revision is either completely inserted or not inserted at all
1325 if( !$wgDBtransactions ) {
1326 $userAbort = ignore_user_abort( true );
1332 if ( 0 != strcmp( $text, $oldtext ) ) {
1333 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1334 - (int)$this->isCountable( $oldtext );
1335 $this->mTotalAdjustment
= 0;
1337 $lastRevision = $dbw->selectField(
1338 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1340 if ( !$lastRevision ) {
1341 # Article gone missing
1342 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1343 wfProfileOut( __METHOD__
);
1347 $revision = new Revision( array(
1348 'page' => $this->getId(),
1349 'comment' => $summary,
1350 'minor_edit' => $isminor,
1355 $revisionId = $revision->insertOn( $dbw );
1358 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1361 /* Belated edit conflict! Run away!! */
1365 # Update recentchanges
1366 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1367 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1368 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1371 # Mark as patrolled if the user can do so
1372 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1373 RecentChange
::markPatrolled( $rcid );
1374 PatrolLog
::record( $rcid, true );
1377 $wgUser->incEditCount();
1381 // Keep the same revision ID, but do some updates on it
1382 $revisionId = $this->getRevIdFetched();
1383 // Update page_touched, this is usually implicit in the page update
1384 // Other cache updates are done in onArticleEdit()
1385 $this->mTitle
->invalidateCache();
1388 if( !$wgDBtransactions ) {
1389 ignore_user_abort( $userAbort );
1393 # Invalidate cache of this article and all pages using this article
1394 # as a template. Partly deferred.
1395 Article
::onArticleEdit( $this->mTitle
);
1397 # Update links tables, site stats, etc.
1398 $changed = ( strcmp( $oldtext, $text ) != 0 );
1399 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1402 # Create new article
1404 # Set statistics members
1405 # We work out if it's countable after PST to avoid counter drift
1406 # when articles are created with {{subst:}}
1407 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1408 $this->mTotalAdjustment
= 1;
1412 # Add the page record; stake our claim on this title!
1413 # This will fail with a database query exception if the article already exists
1414 $newid = $this->insertOn( $dbw );
1416 # Save the revision text...
1417 $revision = new Revision( array(
1419 'comment' => $summary,
1420 'minor_edit' => $isminor,
1423 $revisionId = $revision->insertOn( $dbw );
1425 $this->mTitle
->resetArticleID( $newid );
1427 # Update the page record with revision data
1428 $this->updateRevisionOn( $dbw, $revision, 0 );
1430 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1431 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1432 '', strlen( $text ), $revisionId );
1433 # Mark as patrolled if the user can
1434 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1435 RecentChange
::markPatrolled( $rcid );
1436 PatrolLog
::record( $rcid, true );
1439 $wgUser->incEditCount();
1442 # Update links, etc.
1443 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1446 Article
::onArticleCreate( $this->mTitle
);
1448 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1449 $summary, $flags & EDIT_MINOR
,
1450 null, null, &$flags ) );
1453 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1457 wfRunHooks( 'ArticleSaveComplete',
1458 array( &$this, &$wgUser, $text,
1459 $summary, $flags & EDIT_MINOR
,
1460 null, null, &$flags ) );
1462 wfProfileOut( __METHOD__
);
1467 * @deprecated wrapper for doRedirect
1469 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1470 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1474 * Output a redirect back to the article.
1475 * This is typically used after an edit.
1477 * @param boolean $noRedir Add redirect=no
1478 * @param string $sectionAnchor section to redirect to, including "#"
1480 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1483 $query = 'redirect=no';
1487 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1491 * Mark this particular edit as patrolled
1493 function markpatrolled() {
1494 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1495 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1497 # Check RC patrol config. option
1498 if( !$wgUseRCPatrol ) {
1499 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1504 if( !$wgUser->isAllowed( 'patrol' ) ) {
1505 $wgOut->permissionRequired( 'patrol' );
1509 # If we haven't been given an rc_id value, we can't do anything
1510 $rcid = $wgRequest->getVal( 'rcid' );
1512 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1516 # Handle the 'MarkPatrolled' hook
1517 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1521 $return = SpecialPage
::getTitleFor( 'Recentchanges' );
1522 # If it's left up to us, check that the user is allowed to patrol this edit
1523 # If the user has the "autopatrol" right, then we'll assume there are no
1524 # other conditions stopping them doing so
1525 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1526 $rc = RecentChange
::newFromId( $rcid );
1527 # Graceful error handling, as we've done before here...
1528 # (If the recent change doesn't exist, then it doesn't matter whether
1529 # the user is allowed to patrol it or not; nothing is going to happen
1530 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1531 # The user made this edit, and can't patrol it
1532 # Tell them so, and then back off
1533 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1534 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1535 $wgOut->returnToMain( false, $return );
1540 # Mark the edit as patrolled
1541 RecentChange
::markPatrolled( $rcid );
1542 PatrolLog
::record( $rcid );
1543 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1546 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1547 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1548 $wgOut->returnToMain( false, $return );
1552 * User-interface handler for the "watch" action
1557 global $wgUser, $wgOut;
1559 if ( $wgUser->isAnon() ) {
1560 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1563 if ( wfReadOnly() ) {
1564 $wgOut->readOnlyPage();
1568 if( $this->doWatch() ) {
1569 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1570 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1572 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1573 $text = wfMsg( 'addedwatchtext', $link );
1574 $wgOut->addWikiText( $text );
1577 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1581 * Add this page to $wgUser's watchlist
1582 * @return bool true on successful watch operation
1584 function doWatch() {
1586 if( $wgUser->isAnon() ) {
1590 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1591 $wgUser->addWatch( $this->mTitle
);
1593 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1600 * User interface handler for the "unwatch" action.
1602 function unwatch() {
1604 global $wgUser, $wgOut;
1606 if ( $wgUser->isAnon() ) {
1607 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1610 if ( wfReadOnly() ) {
1611 $wgOut->readOnlyPage();
1615 if( $this->doUnwatch() ) {
1616 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1617 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1619 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1620 $text = wfMsg( 'removedwatchtext', $link );
1621 $wgOut->addWikiText( $text );
1624 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1628 * Stop watching a page
1629 * @return bool true on successful unwatch
1631 function doUnwatch() {
1633 if( $wgUser->isAnon() ) {
1637 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1638 $wgUser->removeWatch( $this->mTitle
);
1640 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1647 * action=protect handler
1649 function protect() {
1650 $form = new ProtectionForm( $this );
1655 * action=unprotect handler (alias)
1657 function unprotect() {
1662 * Update the article's restriction field, and leave a log entry.
1664 * @param array $limit set of restriction keys
1665 * @param string $reason
1666 * @return bool true on success
1668 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1669 global $wgUser, $wgRestrictionTypes, $wgContLang;
1671 $id = $this->mTitle
->getArticleID();
1672 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1680 // Take this opportunity to purge out expired restrictions
1681 Title
::purgeExpiredRestrictions();
1683 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1684 # we expect a single selection, but the schema allows otherwise.
1686 foreach( $wgRestrictionTypes as $action )
1687 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1689 $current = Article
::flattenRestrictions( $current );
1690 $updated = Article
::flattenRestrictions( $limit );
1692 $changed = ( $current != $updated );
1693 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1694 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1695 $protect = ( $updated != '' );
1697 # If nothing's changed, do nothing
1699 global $wgGroupPermissions;
1700 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1702 $dbw = wfGetDB( DB_MASTER
);
1704 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1706 $expiry_description = '';
1707 if ( $encodedExpiry != 'infinity' ) {
1708 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1711 # Prepare a null revision to be added to the history
1712 $modified = $current != '' && $protect;
1714 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1716 $comment_type = 'unprotectedarticle';
1718 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1720 foreach( $limit as $action => $restrictions ) {
1721 # Check if the group level required to edit also can protect pages
1722 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1723 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1726 $cascade_description = '';
1728 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1732 $comment .= ": $reason";
1734 $comment .= " [$updated]";
1735 if ( $expiry_description && $protect )
1736 $comment .= "$expiry_description";
1738 $comment .= "$cascade_description";
1740 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1741 $nullRevId = $nullRevision->insertOn( $dbw );
1743 # Update restrictions table
1744 foreach( $limit as $action => $restrictions ) {
1745 if ($restrictions != '' ) {
1746 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1747 array( 'pr_page' => $id, 'pr_type' => $action
1748 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1749 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1751 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1752 'pr_type' => $action ), __METHOD__
);
1756 # Update page record
1757 $dbw->update( 'page',
1759 'page_touched' => $dbw->timestamp(),
1760 'page_restrictions' => '',
1761 'page_latest' => $nullRevId
1762 ), array( /* WHERE */
1764 ), 'Article::protect'
1766 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1768 # Update the protection log
1769 $log = new LogPage( 'protect' );
1772 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1774 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1778 } # End "changed" check
1784 * Take an array of page restrictions and flatten it to a string
1785 * suitable for insertion into the page_restrictions field.
1786 * @param array $limit
1790 function flattenRestrictions( $limit ) {
1791 if( !is_array( $limit ) ) {
1792 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1796 foreach( $limit as $action => $restrictions ) {
1797 if( $restrictions != '' ) {
1798 $bits[] = "$action=$restrictions";
1801 return implode( ':', $bits );
1805 * UI entry point for page deletion
1808 global $wgUser, $wgOut, $wgRequest;
1809 $confirm = $wgRequest->wasPosted() &&
1810 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1811 $reason = $wgRequest->getText( 'wpReason' );
1813 # This code desperately needs to be totally rewritten
1816 if( $wgUser->isAllowed( 'delete' ) ) {
1817 if( $wgUser->isBlocked( !$confirm ) ) {
1818 $wgOut->blockedPage();
1822 $wgOut->permissionRequired( 'delete' );
1826 if( wfReadOnly() ) {
1827 $wgOut->readOnlyPage();
1831 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1833 # Better double-check that it hasn't been deleted yet!
1834 $dbw = wfGetDB( DB_MASTER
);
1835 $conds = $this->mTitle
->pageCond();
1836 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1837 if ( $latest === false ) {
1838 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1843 $this->doDelete( $reason );
1844 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1846 } elseif( $this->mTitle
->userIsWatching() ) {
1852 # determine whether this page has earlier revisions
1853 # and insert a warning if it does
1855 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1857 if( count( $authors ) > 1 && !$confirm ) {
1858 $skin=$wgUser->getSkin();
1859 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1862 # If a single user is responsible for all revisions, find out who they are
1863 if ( count( $authors ) == $maxRevisions ) {
1864 // Query bailed out, too many revisions to find out if they're all the same
1865 $authorOfAll = false;
1867 $authorOfAll = reset( $authors );
1868 foreach ( $authors as $author ) {
1869 if ( $authorOfAll != $author ) {
1870 $authorOfAll = false;
1875 # Fetch article text
1876 $rev = Revision
::newFromTitle( $this->mTitle
);
1878 if( !is_null( $rev ) ) {
1879 # if this is a mini-text, we can paste part of it into the deletion reason
1880 $text = $rev->getText();
1882 #if this is empty, an earlier revision may contain "useful" text
1885 $prev = $rev->getPrevious();
1887 $text = $prev->getText();
1892 $length = strlen( $text );
1894 # this should not happen, since it is not possible to store an empty, new
1895 # page. Let's insert a standard text in case it does, though
1896 if( $length == 0 && $reason === '' ) {
1897 $reason = wfMsgForContent( 'exblank' );
1900 if( $reason === '' ) {
1901 # comment field=255, let's grep the first 150 to have some user
1904 $text = $wgContLang->truncate( $text, 150, '...' );
1906 # let's strip out newlines
1907 $text = preg_replace( "/[\n\r]/", '', $text );
1910 if( $authorOfAll === false ) {
1911 $reason = wfMsgForContent( 'excontent', $text );
1913 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1916 $reason = wfMsgForContent( 'exbeforeblank', $text );
1921 return $this->confirmDelete( '', $reason );
1925 * Get the last N authors
1926 * @param int $num Number of revisions to get
1927 * @param string $revLatest The latest rev_id, selected from the master (optional)
1928 * @return array Array of authors, duplicates not removed
1930 function getLastNAuthors( $num, $revLatest = 0 ) {
1931 wfProfileIn( __METHOD__
);
1933 // First try the slave
1934 // If that doesn't have the latest revision, try the master
1936 $db = wfGetDB( DB_SLAVE
);
1938 $res = $db->select( array( 'page', 'revision' ),
1939 array( 'rev_id', 'rev_user_text' ),
1941 'page_namespace' => $this->mTitle
->getNamespace(),
1942 'page_title' => $this->mTitle
->getDBkey(),
1943 'rev_page = page_id'
1944 ), __METHOD__
, $this->getSelectOptions( array(
1945 'ORDER BY' => 'rev_timestamp DESC',
1950 wfProfileOut( __METHOD__
);
1953 $row = $db->fetchObject( $res );
1954 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1955 $db = wfGetDB( DB_MASTER
);
1960 } while ( $continue );
1962 $authors = array( $row->rev_user_text
);
1963 while ( $row = $db->fetchObject( $res ) ) {
1964 $authors[] = $row->rev_user_text
;
1966 wfProfileOut( __METHOD__
);
1971 * Output deletion confirmation dialog
1973 function confirmDelete( $par, $reason ) {
1974 global $wgOut, $wgUser;
1976 wfDebug( "Article::confirmDelete\n" );
1978 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1979 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1980 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1981 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1983 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1985 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1986 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1987 $token = htmlspecialchars( $wgUser->editToken() );
1988 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
1991 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1995 <label for='wpReason'>{$delcom}:</label>
1998 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
2008 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2012 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2015 $wgOut->returnToMain( false );
2017 $this->showLogExtract( $wgOut );
2022 * Show relevant lines from the deletion log
2024 function showLogExtract( $out ) {
2025 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2026 $logViewer = new LogViewer(
2029 array( 'page' => $this->mTitle
->getPrefixedText(),
2030 'type' => 'delete' ) ) ) );
2031 $logViewer->showList( $out );
2036 * Perform a deletion and output success or failure messages
2038 function doDelete( $reason ) {
2039 global $wgOut, $wgUser;
2040 wfDebug( __METHOD__
."\n" );
2042 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2043 if ( $this->doDeleteArticle( $reason ) ) {
2044 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2046 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2047 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2049 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2050 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2052 $wgOut->addWikiText( $text );
2053 $wgOut->returnToMain( false );
2054 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2056 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2062 * Back-end article deletion
2063 * Deletes the article with database consistency, writes logs, purges caches
2066 function doDeleteArticle( $reason ) {
2067 global $wgUseSquid, $wgDeferredUpdateList;
2068 global $wgUseTrackbacks;
2070 wfDebug( __METHOD__
."\n" );
2072 $dbw = wfGetDB( DB_MASTER
);
2073 $ns = $this->mTitle
->getNamespace();
2074 $t = $this->mTitle
->getDBkey();
2075 $id = $this->mTitle
->getArticleID();
2077 if ( $t == '' ||
$id == 0 ) {
2081 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2082 array_push( $wgDeferredUpdateList, $u );
2084 // For now, shunt the revision data into the archive table.
2085 // Text is *not* removed from the text table; bulk storage
2086 // is left intact to avoid breaking block-compression or
2087 // immutable storage schemes.
2089 // For backwards compatibility, note that some older archive
2090 // table entries will have ar_text and ar_flags fields still.
2092 // In the future, we may keep revisions and mark them with
2093 // the rev_deleted field, which is reserved for this purpose.
2094 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2096 'ar_namespace' => 'page_namespace',
2097 'ar_title' => 'page_title',
2098 'ar_comment' => 'rev_comment',
2099 'ar_user' => 'rev_user',
2100 'ar_user_text' => 'rev_user_text',
2101 'ar_timestamp' => 'rev_timestamp',
2102 'ar_minor_edit' => 'rev_minor_edit',
2103 'ar_rev_id' => 'rev_id',
2104 'ar_text_id' => 'rev_text_id',
2105 'ar_text' => '\'\'', // Be explicit to appease
2106 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2107 'ar_len' => 'rev_len'
2110 'page_id = rev_page'
2114 # Delete restrictions for it
2115 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2117 # Now that it's safely backed up, delete it
2118 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2120 # If using cascading deletes, we can skip some explicit deletes
2121 if ( !$dbw->cascadingDeletes() ) {
2123 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2125 if ($wgUseTrackbacks)
2126 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2128 # Delete outgoing links
2129 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2130 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2131 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2132 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2133 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2134 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2135 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2138 # If using cleanup triggers, we can skip some manual deletes
2139 if ( !$dbw->cleanupTriggers() ) {
2141 # Clean up recentchanges entries...
2142 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2146 Article
::onArticleDelete( $this->mTitle
);
2149 $log = new LogPage( 'delete' );
2150 $log->addEntry( 'delete', $this->mTitle
, $reason );
2152 # Clear the cached article id so the interface doesn't act like we exist
2153 $this->mTitle
->resetArticleID( 0 );
2154 $this->mTitle
->mArticleID
= 0;
2159 * Revert a modification
2161 function rollback() {
2162 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2164 if( $wgUser->isAllowed( 'rollback' ) ) {
2165 if( $wgUser->isBlocked() ) {
2166 $wgOut->blockedPage();
2170 $wgOut->permissionRequired( 'rollback' );
2174 if ( wfReadOnly() ) {
2175 $wgOut->readOnlyPage( $this->getContent() );
2178 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2179 array( $this->mTitle
->getPrefixedText(),
2180 $wgRequest->getVal( 'from' ) ) ) ) {
2181 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2182 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2185 $dbw = wfGetDB( DB_MASTER
);
2187 # Enhanced rollback, marks edits rc_bot=1
2188 $bot = $wgRequest->getBool( 'bot' );
2190 # Replace all this user's current edits with the next one down
2192 # Get the last editor
2193 $current = Revision
::newFromTitle( $this->mTitle
);
2194 if( is_null( $current ) ) {
2195 # Something wrong... no page?
2196 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2200 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2201 if( $from != $current->getUserText() ) {
2202 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2203 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2204 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2205 htmlspecialchars( $from ),
2206 htmlspecialchars( $current->getUserText() ) ) );
2207 if( $current->getComment() != '') {
2209 wfMsg( 'editcomment',
2210 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2215 # Get the last edit not by this guy
2216 $user = intval( $current->getUser() );
2217 $user_text = $dbw->addQuotes( $current->getUserText() );
2218 $s = $dbw->selectRow( 'revision',
2219 array( 'rev_id', 'rev_timestamp' ),
2221 'rev_page' => $current->getPage(),
2222 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2225 'USE INDEX' => 'page_timestamp',
2226 'ORDER BY' => 'rev_timestamp DESC' )
2228 if( $s === false ) {
2230 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2231 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2237 # Mark all reverted edits as bot
2240 if ( $wgUseRCPatrol ) {
2241 # Mark all reverted edits as patrolled
2242 $set['rc_patrolled'] = 1;
2246 $dbw->update( 'recentchanges', $set,
2248 'rc_cur_id' => $current->getPage(),
2249 'rc_user_text' => $current->getUserText(),
2250 "rc_timestamp > '{$s->rev_timestamp}'",
2255 # Get the edit summary
2256 $target = Revision
::newFromId( $s->rev_id
);
2257 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2258 $newComment = $wgRequest->getText( 'summary', $newComment );
2261 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2262 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2263 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2265 $flags = EDIT_UPDATE | EDIT_MINOR
;
2267 $flags |
= EDIT_FORCE_BOT
;
2268 if(!$this->doEdit( $target->getText(), $newComment, $flags))
2269 ; # todo: this error case has not been handled? Use db transactions?
2271 $wgOut->returnToMain( false );
2276 * Do standard deferred updates after page view
2279 function viewUpdates() {
2280 global $wgDeferredUpdateList;
2282 if ( 0 != $this->getID() ) {
2283 global $wgDisableCounters;
2284 if( !$wgDisableCounters ) {
2285 Article
::incViewCount( $this->getID() );
2286 $u = new SiteStatsUpdate( 1, 0, 0 );
2287 array_push( $wgDeferredUpdateList, $u );
2291 # Update newtalk / watchlist notification status
2293 $wgUser->clearNotification( $this->mTitle
);
2297 * Do standard deferred updates after page edit.
2298 * Update links tables, site stats, search index and message cache.
2299 * Every 1000th edit, prune the recent changes table.
2302 * @param $text New text of the article
2303 * @param $summary Edit summary
2304 * @param $minoredit Minor edit
2305 * @param $timestamp_of_pagechange Timestamp associated with the page change
2306 * @param $newid rev_id value of the new revision
2307 * @param $changed Whether or not the content actually changed
2309 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2310 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2312 wfProfileIn( __METHOD__
);
2315 $options = new ParserOptions
;
2316 $options->setTidy(true);
2317 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2319 # Save it to the parser cache
2320 $parserCache =& ParserCache
::singleton();
2321 $parserCache->save( $poutput, $this, $wgUser );
2323 # Update the links tables
2324 $u = new LinksUpdate( $this->mTitle
, $poutput );
2327 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2329 if ( 0 == mt_rand( 0, 99 ) ) {
2330 # Periodically flush old entries from the recentchanges table.
2333 $dbw = wfGetDB( DB_MASTER
);
2334 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2335 $recentchanges = $dbw->tableName( 'recentchanges' );
2336 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2337 $dbw->query( $sql );
2341 $id = $this->getID();
2342 $title = $this->mTitle
->getPrefixedDBkey();
2343 $shortTitle = $this->mTitle
->getDBkey();
2346 wfProfileOut( __METHOD__
);
2350 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2351 array_push( $wgDeferredUpdateList, $u );
2352 $u = new SearchUpdate( $id, $title, $text );
2353 array_push( $wgDeferredUpdateList, $u );
2355 # If this is another user's talk page, update newtalk
2356 # Don't do this if $changed = false otherwise some idiot can null-edit a
2357 # load of user talk pages and piss people off, nor if it's a minor edit
2358 # by a properly-flagged bot.
2359 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2360 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2361 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2362 $other = User
::newFromName( $shortTitle );
2363 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2364 // An anonymous user
2365 $other = new User();
2366 $other->setName( $shortTitle );
2369 $other->setNewtalk( true );
2374 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2375 $wgMessageCache->replace( $shortTitle, $text );
2378 wfProfileOut( __METHOD__
);
2382 * Perform article updates on a special page creation.
2384 * @param Revision $rev
2386 * @todo This is a shitty interface function. Kill it and replace the
2387 * other shitty functions like editUpdates and such so it's not needed
2390 function createUpdates( $rev ) {
2391 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2392 $this->mTotalAdjustment
= 1;
2393 $this->editUpdates( $rev->getText(), $rev->getComment(),
2394 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2398 * Generate the navigation links when browsing through an article revisions
2399 * It shows the information as:
2400 * Revision as of \<date\>; view current revision
2401 * \<- Previous version | Next Version -\>
2404 * @param string $oldid Revision ID of this article revision
2406 function setOldSubtitle( $oldid=0 ) {
2407 global $wgLang, $wgOut, $wgUser;
2409 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2413 $revision = Revision
::newFromId( $oldid );
2415 $current = ( $oldid == $this->mLatest
);
2416 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2417 $sk = $wgUser->getSkin();
2419 ?
wfMsg( 'currentrevisionlink' )
2420 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2423 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2424 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2426 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2427 : wfMsg( 'previousrevision' );
2429 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2431 $nextlink = $current
2432 ?
wfMsg( 'nextrevision' )
2433 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2434 $nextdiff = $current
2436 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2438 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2439 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2441 $m = wfMsg( 'revision-info-current' );
2442 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2443 ?
'revision-info-current'
2446 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2447 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2448 $wgOut->setSubtitle( $r );
2452 * This function is called right before saving the wikitext,
2453 * so we can do things like signatures and links-in-context.
2455 * @param string $text
2457 function preSaveTransform( $text ) {
2458 global $wgParser, $wgUser;
2459 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2462 /* Caching functions */
2465 * checkLastModified returns true if it has taken care of all
2466 * output to the client that is necessary for this request.
2467 * (that is, it has sent a cached version of the page)
2469 function tryFileCache() {
2470 static $called = false;
2472 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2476 if($this->isFileCacheable()) {
2477 $touched = $this->mTouched
;
2478 $cache = new HTMLFileCache( $this->mTitle
);
2479 if($cache->isFileCacheGood( $touched )) {
2480 wfDebug( "Article::tryFileCache(): about to load file\n" );
2481 $cache->loadFromFileCache();
2484 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2485 ob_start( array(&$cache, 'saveToFileCache' ) );
2488 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2493 * Check if the page can be cached
2496 function isFileCacheable() {
2497 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2498 $action = $wgRequest->getVal( 'action' );
2499 $oldid = $wgRequest->getVal( 'oldid' );
2500 $diff = $wgRequest->getVal( 'diff' );
2501 $redirect = $wgRequest->getVal( 'redirect' );
2502 $printable = $wgRequest->getVal( 'printable' );
2503 $page = $wgRequest->getVal( 'page' );
2505 //check for non-standard user language; this covers uselang,
2506 //and extensions for auto-detecting user language.
2507 $ulang = $wgLang->getCode();
2508 $clang = $wgContLang->getCode();
2510 $cacheable = $wgUseFileCache
2511 && (!$wgShowIPinHeader)
2512 && ($this->getID() != 0)
2513 && ($wgUser->isAnon())
2514 && (!$wgUser->getNewtalk())
2515 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2516 && (empty( $action ) ||
$action == 'view')
2519 && (!isset($redirect))
2520 && (!isset($printable))
2522 && (!$this->mRedirectedFrom
)
2523 && ($ulang === $clang);
2526 //extension may have reason to disable file caching on some pages.
2527 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2534 * Loads page_touched and returns a value indicating if it should be used
2537 function checkTouched() {
2538 if( !$this->mDataLoaded
) {
2539 $this->loadPageData();
2541 return !$this->mIsRedirect
;
2545 * Get the page_touched field
2547 function getTouched() {
2548 # Ensure that page data has been loaded
2549 if( !$this->mDataLoaded
) {
2550 $this->loadPageData();
2552 return $this->mTouched
;
2556 * Get the page_latest field
2558 function getLatest() {
2559 if ( !$this->mDataLoaded
) {
2560 $this->loadPageData();
2562 return $this->mLatest
;
2566 * Edit an article without doing all that other stuff
2567 * The article must already exist; link tables etc
2568 * are not updated, caches are not flushed.
2570 * @param string $text text submitted
2571 * @param string $comment comment submitted
2572 * @param bool $minor whereas it's a minor modification
2574 function quickEdit( $text, $comment = '', $minor = 0 ) {
2575 wfProfileIn( __METHOD__
);
2577 $dbw = wfGetDB( DB_MASTER
);
2579 $revision = new Revision( array(
2580 'page' => $this->getId(),
2582 'comment' => $comment,
2583 'minor_edit' => $minor ?
1 : 0,
2585 $revision->insertOn( $dbw );
2586 $this->updateRevisionOn( $dbw, $revision );
2589 wfProfileOut( __METHOD__
);
2593 * Used to increment the view counter
2596 * @param integer $id article id
2598 function incViewCount( $id ) {
2599 $id = intval( $id );
2600 global $wgHitcounterUpdateFreq, $wgDBtype;
2602 $dbw = wfGetDB( DB_MASTER
);
2603 $pageTable = $dbw->tableName( 'page' );
2604 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2605 $acchitsTable = $dbw->tableName( 'acchits' );
2607 if( $wgHitcounterUpdateFreq <= 1 ) {
2608 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2612 # Not important enough to warrant an error page in case of failure
2613 $oldignore = $dbw->ignoreErrors( true );
2615 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2617 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2618 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2619 # Most of the time (or on SQL errors), skip row count check
2620 $dbw->ignoreErrors( $oldignore );
2624 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2625 $row = $dbw->fetchObject( $res );
2626 $rown = intval( $row->n
);
2627 if( $rown >= $wgHitcounterUpdateFreq ){
2628 wfProfileIn( 'Article::incViewCount-collect' );
2629 $old_user_abort = ignore_user_abort( true );
2631 if ($wgDBtype == 'mysql')
2632 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2633 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2634 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2635 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2637 $dbw->query("DELETE FROM $hitcounterTable");
2638 if ($wgDBtype == 'mysql') {
2639 $dbw->query('UNLOCK TABLES');
2640 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2641 'WHERE page_id = hc_id');
2644 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2645 "FROM $acchitsTable WHERE page_id = hc_id");
2647 $dbw->query("DROP TABLE $acchitsTable");
2649 ignore_user_abort( $old_user_abort );
2650 wfProfileOut( 'Article::incViewCount-collect' );
2652 $dbw->ignoreErrors( $oldignore );
2656 * The onArticle*() functions are supposed to be a kind of hooks
2657 * which should be called whenever any of the specified actions
2660 * This is a good place to put code to clear caches, for instance.
2662 * This is called on page move and undelete, as well as edit
2664 * @param $title_obj a title object
2667 static function onArticleCreate($title) {
2668 # The talk page isn't in the regular link tables, so we need to update manually:
2669 if ( $title->isTalkPage() ) {
2670 $other = $title->getSubjectPage();
2672 $other = $title->getTalkPage();
2674 $other->invalidateCache();
2675 $other->purgeSquid();
2677 $title->touchLinks();
2678 $title->purgeSquid();
2681 static function onArticleDelete( $title ) {
2682 global $wgUseFileCache, $wgMessageCache;
2684 $title->touchLinks();
2685 $title->purgeSquid();
2688 if ( $wgUseFileCache ) {
2689 $cm = new HTMLFileCache( $title );
2690 @unlink
( $cm->fileCacheName() );
2693 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2694 $wgMessageCache->replace( $title->getDBkey(), false );
2699 * Purge caches on page update etc
2701 static function onArticleEdit( $title ) {
2702 global $wgDeferredUpdateList, $wgUseFileCache;
2704 // Invalidate caches of articles which include this page
2705 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2706 $wgDeferredUpdateList[] = $update;
2708 # Purge squid for this page only
2709 $title->purgeSquid();
2712 if ( $wgUseFileCache ) {
2713 $cm = new HTMLFileCache( $title );
2714 @unlink
( $cm->fileCacheName() );
2721 * Info about this page
2722 * Called for ?action=info when $wgAllowPageInfo is on.
2727 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2729 if ( !$wgAllowPageInfo ) {
2730 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2734 $page = $this->mTitle
->getSubjectPage();
2736 $wgOut->setPagetitle( $page->getPrefixedText() );
2737 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2739 # first, see if the page exists at all.
2740 $exists = $page->getArticleId() != 0;
2742 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2743 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2745 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2748 $dbr = wfGetDB( DB_SLAVE
);
2750 'wl_title' => $page->getDBkey(),
2751 'wl_namespace' => $page->getNamespace() );
2752 $numwatchers = $dbr->selectField(
2757 $this->getSelectOptions() );
2759 $pageInfo = $this->pageCountInfo( $page );
2760 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2762 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2763 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2765 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2767 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2769 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2771 $wgOut->addHTML( '</ul>' );
2777 * Return the total number of edits and number of unique editors
2778 * on a given page. If page does not exist, returns false.
2780 * @param Title $title
2784 function pageCountInfo( $title ) {
2785 $id = $title->getArticleId();
2790 $dbr = wfGetDB( DB_SLAVE
);
2792 $rev_clause = array( 'rev_page' => $id );
2794 $edits = $dbr->selectField(
2799 $this->getSelectOptions() );
2801 $authors = $dbr->selectField(
2803 'COUNT(DISTINCT rev_user_text)',
2806 $this->getSelectOptions() );
2808 return array( 'edits' => $edits, 'authors' => $authors );
2812 * Return a list of templates used by this article.
2813 * Uses the templatelinks table
2815 * @return array Array of Title objects
2817 function getUsedTemplates() {
2819 $id = $this->mTitle
->getArticleID();
2824 $dbr = wfGetDB( DB_SLAVE
);
2825 $res = $dbr->select( array( 'templatelinks' ),
2826 array( 'tl_namespace', 'tl_title' ),
2827 array( 'tl_from' => $id ),
2828 'Article:getUsedTemplates' );
2829 if ( false !== $res ) {
2830 if ( $dbr->numRows( $res ) ) {
2831 while ( $row = $dbr->fetchObject( $res ) ) {
2832 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2836 $dbr->freeResult( $res );
2841 * Return an auto-generated summary if the text provided is a redirect.
2843 * @param string $text The wikitext to check
2844 * @return string '' or an appropriate summary
2846 public static function getRedirectAutosummary( $text ) {
2847 $rt = Title
::newFromRedirect( $text );
2848 if( is_object( $rt ) )
2849 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2855 * Return an auto-generated summary if the new text is much shorter than
2858 * @param string $oldtext The previous text of the page
2859 * @param string $text The submitted text of the page
2860 * @return string An appropriate autosummary, or an empty string.
2862 public static function getBlankingAutosummary( $oldtext, $text ) {
2863 if ($oldtext!='' && $text=='') {
2864 return wfMsgForContent('autosumm-blank');
2865 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2866 #Removing more than 90% of the article
2868 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2869 return wfMsgForContent('autosumm-replace', $truncatedtext);
2876 * Return an applicable autosummary if one exists for the given edit.
2877 * @param string $oldtext The previous text of the page.
2878 * @param string $newtext The submitted text of the page.
2879 * @param bitmask $flags A bitmask of flags submitted for the edit.
2880 * @return string An appropriate autosummary, or an empty string.
2882 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2884 # This code is UGLY UGLY UGLY.
2885 # Somebody PLEASE come up with a more elegant way to do it.
2887 #Redirect autosummaries
2888 $summary = self
::getRedirectAutosummary( $newtext );
2893 #Blanking autosummaries
2894 if (!($flags & EDIT_NEW
))
2895 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
2900 #New page autosummaries
2901 if ($flags & EDIT_NEW
&& strlen($newtext)) {
2902 #If they're making a new article, give its text, truncated, in the summary.
2904 $truncatedtext = $wgContLang->truncate(
2905 str_replace("\n", ' ', $newtext),
2906 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2908 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2918 * Add the primary page-view wikitext to the output buffer
2919 * Saves the text into the parser cache if possible.
2920 * Updates templatelinks if it is out of date.
2922 * @param string $text
2923 * @param bool $cache
2925 public function outputWikiText( $text, $cache = true ) {
2926 global $wgParser, $wgUser, $wgOut;
2928 $popts = $wgOut->parserOptions();
2929 $popts->setTidy(true);
2930 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
2931 $popts, true, true, $this->getRevIdFetched() );
2932 $popts->setTidy(false);
2933 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
2934 $parserCache =& ParserCache
::singleton();
2935 $parserCache->save( $parserOutput, $this, $wgUser );
2938 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
2939 // templatelinks table may have become out of sync,
2940 // especially if using variable-based transclusions.
2941 // For paranoia, check if things have changed and if
2942 // so apply updates to the database. This will ensure
2943 // that cascaded protections apply as soon as the changes
2946 # Get templates from templatelinks
2947 $id = $this->mTitle
->getArticleID();
2949 $tlTemplates = array();
2951 $dbr = wfGetDB( DB_SLAVE
);
2952 $res = $dbr->select( array( 'templatelinks' ),
2953 array( 'tl_namespace', 'tl_title' ),
2954 array( 'tl_from' => $id ),
2955 'Article:getUsedTemplates' );
2959 if ( false !== $res ) {
2960 if ( $dbr->numRows( $res ) ) {
2961 while ( $row = $dbr->fetchObject( $res ) ) {
2962 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
2967 # Get templates from parser output.
2968 $poTemplates_allns = $parserOutput->getTemplates();
2970 $poTemplates = array ();
2971 foreach ( $poTemplates_allns as $ns_templates ) {
2972 $poTemplates = array_merge( $poTemplates, $ns_templates );
2976 $templates_diff = array_diff( $poTemplates, $tlTemplates );
2978 if ( count( $templates_diff ) > 0 ) {
2979 # Whee, link updates time.
2980 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
2982 $dbw = wfGetDb( DB_MASTER
);
2991 $wgOut->addParserOutput( $parserOutput );