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 * Constants used by internal components to get rollback results
42 const SUCCESS
= 0; // Operation successful
43 const PERM_DENIED
= 1; // Permission denied
44 const BLOCKED
= 2; // User has been blocked
45 const READONLY
= 3; // Wiki is in read-only mode
46 const BAD_TOKEN
= 4; // Invalid token specified
47 const BAD_TITLE
= 5; // $this is not a valid Article
48 const ALREADY_ROLLED
= 6; // Someone else already rolled this back. $from and $summary will be set
49 const ONLY_AUTHOR
= 7; // User is the only author of the page
52 * Constructor and clear the article
53 * @param $title Reference to a Title object.
54 * @param $oldId Integer revision ID, null to fetch from request, zero for current
56 function __construct( &$title, $oldId = null ) {
57 $this->mTitle
=& $title;
58 $this->mOldId
= $oldId;
63 * Tell the page view functions that this view was redirected
64 * from another page on the wiki.
65 * @param $from Title object.
67 function setRedirectedFrom( $from ) {
68 $this->mRedirectedFrom
= $from;
72 * @return mixed false, Title of in-wiki target, or string with URL
74 function followRedirect() {
75 $text = $this->getContent();
76 $rt = Title
::newFromRedirect( $text );
78 # process if title object is valid and not special:userlogout
80 if( $rt->getInterwiki() != '' ) {
81 if( $rt->isLocal() ) {
82 // Offsite wikis need an HTTP redirect.
84 // This can be hard to reverse and may produce loops,
85 // so they may be disabled in the site configuration.
87 $source = $this->mTitle
->getFullURL( 'redirect=no' );
88 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
91 if( $rt->getNamespace() == NS_SPECIAL
) {
92 // Gotta handle redirects to special pages differently:
93 // Fill the HTTP response "Location" header and ignore
94 // the rest of the page we're on.
96 // This can be hard to reverse, so they may be disabled.
98 if( $rt->isSpecial( 'Userlogout' ) ) {
101 return $rt->getFullURL();
108 // No or invalid redirect
113 * get the title object of the article
115 function getTitle() {
116 return $this->mTitle
;
124 $this->mDataLoaded
= false;
125 $this->mContentLoaded
= false;
127 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
128 $this->mRedirectedFrom
= null; # Title object if set
130 $this->mTimestamp
= $this->mComment
= '';
131 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
132 $this->mTouched
= '19700101000000';
133 $this->mForUpdate
= false;
134 $this->mIsRedirect
= false;
135 $this->mRevIdFetched
= 0;
136 $this->mRedirectUrl
= false;
137 $this->mLatest
= false;
141 * Note that getContent/loadContent do not follow redirects anymore.
142 * If you need to fetch redirectable content easily, try
143 * the shortcut in Article::followContent()
145 * @todo There are still side-effects in this!
146 * In general, you should use the Revision class, not Article,
147 * to fetch text for purposes other than page views.
149 * @return Return the text of this revision
151 function getContent() {
152 global $wgUser, $wgOut;
154 wfProfileIn( __METHOD__
);
156 if ( 0 == $this->getID() ) {
157 wfProfileOut( __METHOD__
);
158 $wgOut->setRobotpolicy( 'noindex,nofollow' );
160 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
161 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
163 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
166 return "<div class='noarticletext'>$ret</div>";
168 $this->loadContent();
169 wfProfileOut( __METHOD__
);
170 return $this->mContent
;
175 * This function returns the text of a section, specified by a number ($section).
176 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
177 * the first section before any such heading (section 0).
179 * If a section contains subsections, these are also returned.
181 * @param $text String: text to look in
182 * @param $section Integer: section number
183 * @return string text of the requested section
186 function getSection($text,$section) {
188 return $wgParser->getSection( $text, $section );
192 * @return int The oldid of the article that is to be shown, 0 for the
195 function getOldID() {
196 if ( is_null( $this->mOldId
) ) {
197 $this->mOldId
= $this->getOldIDFromRequest();
199 return $this->mOldId
;
203 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
205 * @return int The old id for the request
207 function getOldIDFromRequest() {
209 $this->mRedirectUrl
= false;
210 $oldid = $wgRequest->getVal( 'oldid' );
211 if ( isset( $oldid ) ) {
212 $oldid = intval( $oldid );
213 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
214 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
218 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
220 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
221 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
239 * Load the revision (including text) into this object
241 function loadContent() {
242 if ( $this->mContentLoaded
) return;
245 $oldid = $this->getOldID();
247 # Pre-fill content with error message so that if something
248 # fails we'll have something telling us what we intended.
249 $this->mOldId
= $oldid;
250 $this->fetchContent( $oldid );
255 * Fetch a page record with the given conditions
256 * @param Database $dbr
257 * @param array $conditions
260 function pageData( $dbr, $conditions ) {
273 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
274 $row = $dbr->selectRow( 'page',
277 'Article::pageData' );
278 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
283 * @param Database $dbr
284 * @param Title $title
286 function pageDataFromTitle( $dbr, $title ) {
287 return $this->pageData( $dbr, array(
288 'page_namespace' => $title->getNamespace(),
289 'page_title' => $title->getDBkey() ) );
293 * @param Database $dbr
296 function pageDataFromId( $dbr, $id ) {
297 return $this->pageData( $dbr, array( 'page_id' => $id ) );
301 * Set the general counter, title etc data loaded from
304 * @param object $data
307 function loadPageData( $data = 'fromdb' ) {
308 if ( $data === 'fromdb' ) {
309 $dbr = $this->getDB();
310 $data = $this->pageDataFromId( $dbr, $this->getId() );
313 $lc =& LinkCache
::singleton();
315 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
317 $this->mTitle
->mArticleID
= $data->page_id
;
319 # Old-fashioned restrictions.
320 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
322 $this->mCounter
= $data->page_counter
;
323 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
324 $this->mIsRedirect
= $data->page_is_redirect
;
325 $this->mLatest
= $data->page_latest
;
327 if ( is_object( $this->mTitle
) ) {
328 $lc->addBadLinkObj( $this->mTitle
);
330 $this->mTitle
->mArticleID
= 0;
333 $this->mDataLoaded
= true;
337 * Get text of an article from database
338 * Does *NOT* follow redirects.
339 * @param int $oldid 0 for whatever the latest revision is
342 function fetchContent( $oldid = 0 ) {
343 if ( $this->mContentLoaded
) {
344 return $this->mContent
;
347 $dbr = $this->getDB();
349 # Pre-fill content with error message so that if something
350 # fails we'll have something telling us what we intended.
351 $t = $this->mTitle
->getPrefixedText();
353 $t .= ',oldid='.$oldid;
355 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
358 $revision = Revision
::newFromId( $oldid );
359 if( is_null( $revision ) ) {
360 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
363 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
365 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
368 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
369 $this->loadPageData( $data );
371 if( !$this->mDataLoaded
) {
372 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
374 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
377 $this->loadPageData( $data );
379 $revision = Revision
::newFromId( $this->mLatest
);
380 if( is_null( $revision ) ) {
381 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
386 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
387 // We should instead work with the Revision object when we need it...
388 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
389 //$this->mContent = $revision->getText();
391 $this->mUser
= $revision->getUser();
392 $this->mUserText
= $revision->getUserText();
393 $this->mComment
= $revision->getComment();
394 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
396 $this->mRevIdFetched
= $revision->getID();
397 $this->mContentLoaded
= true;
398 $this->mRevision
=& $revision;
400 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
402 return $this->mContent
;
406 * Read/write accessor to select FOR UPDATE
408 * @param $x Mixed: FIXME
410 function forUpdate( $x = NULL ) {
411 return wfSetVar( $this->mForUpdate
, $x );
415 * Get the database which should be used for reads
420 return wfGetDB( DB_MASTER
);
424 * Get options for all SELECT statements
426 * @param $options Array: an optional options array which'll be appended to
428 * @return Array: options
430 function getSelectOptions( $options = '' ) {
431 if ( $this->mForUpdate
) {
432 if ( is_array( $options ) ) {
433 $options[] = 'FOR UPDATE';
435 $options = 'FOR UPDATE';
442 * @return int Page ID
445 if( $this->mTitle
) {
446 return $this->mTitle
->getArticleID();
453 * @return bool Whether or not the page exists in the database
456 return $this->getId() != 0;
460 * @return int The view count for the page
462 function getCount() {
463 if ( -1 == $this->mCounter
) {
464 $id = $this->getID();
468 $dbr = wfGetDB( DB_SLAVE
);
469 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
470 'Article::getCount', $this->getSelectOptions() );
473 return $this->mCounter
;
477 * Determine whether a page would be suitable for being counted as an
478 * article in the site_stats table based on the title & its content
480 * @param $text String: text to analyze
483 function isCountable( $text ) {
484 global $wgUseCommaCount;
486 $token = $wgUseCommaCount ?
',' : '[[';
488 $this->mTitle
->isContentPage()
489 && !$this->isRedirect( $text )
490 && in_string( $token, $text );
494 * Tests if the article text represents a redirect
496 * @param $text String: FIXME
499 function isRedirect( $text = false ) {
500 if ( $text === false ) {
501 $this->loadContent();
502 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
504 $titleObj = Title
::newFromRedirect( $text );
506 return $titleObj !== NULL;
510 * Returns true if the currently-referenced revision is the current edit
511 * to this page (and it exists).
514 function isCurrent() {
515 # If no oldid, this is the current version.
516 if ($this->getOldID() == 0)
519 return $this->exists() &&
520 isset( $this->mRevision
) &&
521 $this->mRevision
->isCurrent();
525 * Loads everything except the text
526 * This isn't necessary for all uses, so it's only done if needed.
529 function loadLastEdit() {
530 if ( -1 != $this->mUser
)
533 # New or non-existent articles have no user information
534 $id = $this->getID();
535 if ( 0 == $id ) return;
537 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
538 if( !is_null( $this->mLastRevision
) ) {
539 $this->mUser
= $this->mLastRevision
->getUser();
540 $this->mUserText
= $this->mLastRevision
->getUserText();
541 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
542 $this->mComment
= $this->mLastRevision
->getComment();
543 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
544 $this->mRevIdFetched
= $this->mLastRevision
->getID();
548 function getTimestamp() {
549 // Check if the field has been filled by ParserCache::get()
550 if ( !$this->mTimestamp
) {
551 $this->loadLastEdit();
553 return wfTimestamp(TS_MW
, $this->mTimestamp
);
557 $this->loadLastEdit();
561 function getUserText() {
562 $this->loadLastEdit();
563 return $this->mUserText
;
566 function getComment() {
567 $this->loadLastEdit();
568 return $this->mComment
;
571 function getMinorEdit() {
572 $this->loadLastEdit();
573 return $this->mMinorEdit
;
576 function getRevIdFetched() {
577 $this->loadLastEdit();
578 return $this->mRevIdFetched
;
582 * @todo Document, fixme $offset never used.
583 * @param $limit Integer: default 0.
584 * @param $offset Integer: default 0.
586 function getContributors($limit = 0, $offset = 0) {
587 # XXX: this is expensive; cache this info somewhere.
590 $dbr = wfGetDB( DB_SLAVE
);
591 $revTable = $dbr->tableName( 'revision' );
592 $userTable = $dbr->tableName( 'user' );
593 $user = $this->getUser();
594 $pageId = $this->getId();
596 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
597 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
598 WHERE rev_page = $pageId
599 AND rev_user != $user
600 GROUP BY rev_user, rev_user_text, user_real_name
601 ORDER BY timestamp DESC";
603 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
604 $sql .= ' '. $this->getSelectOptions();
606 $res = $dbr->query($sql, __METHOD__
);
608 while ( $line = $dbr->fetchObject( $res ) ) {
609 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
612 $dbr->freeResult($res);
617 * This is the default action of the script: just view the page of
621 global $wgUser, $wgOut, $wgRequest, $wgContLang;
622 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
623 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
624 $sk = $wgUser->getSkin();
626 wfProfileIn( __METHOD__
);
628 $parserCache =& ParserCache
::singleton();
629 $ns = $this->mTitle
->getNamespace(); # shortcut
631 # Get variables from query string
632 $oldid = $this->getOldID();
634 # getOldID may want us to redirect somewhere else
635 if ( $this->mRedirectUrl
) {
636 $wgOut->redirect( $this->mRedirectUrl
);
637 wfProfileOut( __METHOD__
);
641 $diff = $wgRequest->getVal( 'diff' );
642 $rcid = $wgRequest->getVal( 'rcid' );
643 $rdfrom = $wgRequest->getVal( 'rdfrom' );
644 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
646 $wgOut->setArticleFlag( true );
648 # Discourage indexing of printable versions, but encourage following
649 if( $wgOut->isPrintable() ) {
650 $policy = 'noindex,follow';
651 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
652 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
653 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
654 # Honour customised robot policies for this namespace
655 $policy = $wgNamespaceRobotPolicies[$ns];
657 # Default to encourage indexing and following links
658 $policy = 'index,follow';
660 $wgOut->setRobotPolicy( $policy );
662 # If we got diff and oldid in the query, we want to see a
663 # diff page instead of the article.
665 if ( !is_null( $diff ) ) {
666 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
668 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
669 // DifferenceEngine directly fetched the revision:
670 $this->mRevIdFetched
= $de->mNewid
;
671 $de->showDiffPage( $diffOnly );
673 // Needed to get the page's current revision
674 $this->loadPageData();
675 if( $diff == 0 ||
$diff == $this->mLatest
) {
676 # Run view updates for current revision only
677 $this->viewUpdates();
679 wfProfileOut( __METHOD__
);
683 if ( empty( $oldid ) && $this->checkTouched() ) {
684 $wgOut->setETag($parserCache->getETag($this, $wgUser));
686 if( $wgOut->checkLastModified( $this->mTouched
) ){
687 wfProfileOut( __METHOD__
);
689 } else if ( $this->tryFileCache() ) {
690 # tell wgOut that output is taken care of
692 $this->viewUpdates();
693 wfProfileOut( __METHOD__
);
698 # Should the parser cache be used?
699 $pcache = $wgEnableParserCache
700 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
703 && !$this->mTitle
->isCssOrJsPage()
704 && !$this->mTitle
->isCssJsSubpage();
705 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
706 if ( $wgUser->getOption( 'stubthreshold' ) ) {
707 wfIncrStats( 'pcache_miss_stub' );
710 $wasRedirected = false;
711 if ( isset( $this->mRedirectedFrom
) ) {
712 // This is an internally redirected page view.
713 // We'll need a backlink to the source page for navigation.
714 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
715 $sk = $wgUser->getSkin();
716 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
717 $s = wfMsg( 'redirectedfrom', $redir );
718 $wgOut->setSubtitle( $s );
720 // Set the fragment if one was specified in the redirect
721 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
722 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
723 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
725 $wasRedirected = true;
727 } elseif ( !empty( $rdfrom ) ) {
728 // This is an externally redirected view, from some other wiki.
729 // If it was reported from a trusted site, supply a backlink.
730 global $wgRedirectSources;
731 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
732 $sk = $wgUser->getSkin();
733 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
734 $s = wfMsg( 'redirectedfrom', $redir );
735 $wgOut->setSubtitle( $s );
736 $wasRedirected = true;
741 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
743 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
744 // Ensure that UI elements requiring revision ID have
745 // the correct version information.
746 $wgOut->setRevisionId( $this->mLatest
);
750 if ( !$outputDone ) {
751 $text = $this->getContent();
752 if ( $text === false ) {
753 # Failed to load, replace text with error message
754 $t = $this->mTitle
->getPrefixedText();
756 $t .= ',oldid='.$oldid;
757 $text = wfMsg( 'missingarticle', $t );
759 $text = wfMsg( 'noarticletext', $t );
763 # Another whitelist check in case oldid is altering the title
764 if ( !$this->mTitle
->userCanRead() ) {
765 $wgOut->loginToUse();
770 # We're looking at an old revision
772 if ( !empty( $oldid ) ) {
773 $wgOut->setRobotpolicy( 'noindex,nofollow' );
774 if( is_null( $this->mRevision
) ) {
775 // FIXME: This would be a nice place to load the 'no such page' text.
777 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
778 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
779 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
780 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
781 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
784 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
785 // and we are allowed to see...
793 $wgOut->setRevisionId( $this->getRevIdFetched() );
795 // Pages containing custom CSS or JavaScript get special treatment
796 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
797 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
799 // Give hooks a chance to customise the output
800 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
801 // Wrap the whole lot in a <pre> and don't parse
802 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
803 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
804 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
805 $wgOut->addHtml( "\n</pre>\n" );
810 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
812 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
813 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
814 # Don't overwrite the subtitle if this was an old revision
815 if( !$wasRedirected && $this->isCurrent() ) {
816 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
818 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
820 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
821 '<span class="redirectText">'.$link.'</span>' );
823 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
824 $wgOut->addParserOutputNoText( $parseout );
825 } else if ( $pcache ) {
826 # Display content and save to parser cache
827 $this->outputWikiText( $text );
829 # Display content, don't attempt to save to parser cache
830 # Don't show section-edit links on old revisions... this way lies madness.
831 if( !$this->isCurrent() ) {
832 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
834 # Display content and don't save to parser cache
835 # With timing hack -- TS 2006-07-26
837 $this->outputWikiText( $text, false );
842 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
843 $this->mTitle
->getPrefixedDBkey()));
846 if( !$this->isCurrent() ) {
847 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
852 /* title may have been set from the cache */
853 $t = $wgOut->getPageTitle();
855 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
858 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
859 if( $ns == NS_USER_TALK
&&
860 User
::isIP( $this->mTitle
->getText() ) ) {
861 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
864 # If we have been passed an &rcid= parameter, we want to give the user a
865 # chance to mark this new article as patrolled.
866 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
868 "<div class='patrollink'>" .
869 wfMsgHtml( 'markaspatrolledlink',
870 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
871 "action=markpatrolled&rcid=$rcid" )
878 if ($wgUseTrackbacks)
879 $this->addTrackbacks();
881 $this->viewUpdates();
882 wfProfileOut( __METHOD__
);
885 function addTrackbacks() {
886 global $wgOut, $wgUser;
888 $dbr = wfGetDB(DB_SLAVE
);
890 /* FROM */ 'trackbacks',
891 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
892 /* WHERE */ array('tb_page' => $this->getID())
895 if (!$dbr->numrows($tbs))
899 while ($o = $dbr->fetchObject($tbs)) {
901 if ($wgUser->isAllowed( 'trackback' )) {
902 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
903 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
904 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
906 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
913 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
916 function deletetrackback() {
917 global $wgUser, $wgRequest, $wgOut, $wgTitle;
919 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
920 $wgOut->addWikitext(wfMsg('sessionfailure'));
924 if ((!$wgUser->isAllowed('delete'))) {
925 $wgOut->permissionRequired( 'delete' );
930 $wgOut->readOnlyPage();
934 $db = wfGetDB(DB_MASTER
);
935 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
936 $wgTitle->invalidateCache();
937 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
943 $wgOut->setArticleBodyOnly(true);
948 * Handle action=purge
951 global $wgUser, $wgRequest, $wgOut;
953 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
954 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
958 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
959 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
960 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
961 $msg = str_replace( '$1',
962 "<form method=\"post\" action=\"$action\">\n" .
963 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
966 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
967 $wgOut->setRobotpolicy( 'noindex,nofollow' );
968 $wgOut->addHTML( $msg );
973 * Perform the actions of a page purging
977 // Invalidate the cache
978 $this->mTitle
->invalidateCache();
981 // Commit the transaction before the purge is sent
982 $dbw = wfGetDB( DB_MASTER
);
983 $dbw->immediateCommit();
986 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
993 * Insert a new empty page record for this article.
994 * This *must* be followed up by creating a revision
995 * and running $this->updateToLatest( $rev_id );
996 * or else the record will be left in a funky state.
997 * Best if all done inside a transaction.
999 * @param Database $dbw
1000 * @return int The newly created page_id key
1003 function insertOn( $dbw ) {
1004 wfProfileIn( __METHOD__
);
1006 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1007 $dbw->insert( 'page', array(
1008 'page_id' => $page_id,
1009 'page_namespace' => $this->mTitle
->getNamespace(),
1010 'page_title' => $this->mTitle
->getDBkey(),
1011 'page_counter' => 0,
1012 'page_restrictions' => '',
1013 'page_is_redirect' => 0, # Will set this shortly...
1015 'page_random' => wfRandom(),
1016 'page_touched' => $dbw->timestamp(),
1017 'page_latest' => 0, # Fill this in shortly...
1018 'page_len' => 0, # Fill this in shortly...
1020 $newid = $dbw->insertId();
1022 $this->mTitle
->resetArticleId( $newid );
1024 wfProfileOut( __METHOD__
);
1029 * Update the page record to point to a newly saved revision.
1031 * @param Database $dbw
1032 * @param Revision $revision For ID number, and text used to set
1033 length and redirect status fields
1034 * @param int $lastRevision If given, will not overwrite the page field
1035 * when different from the currently set value.
1036 * Giving 0 indicates the new page flag should
1038 * @param bool $lastRevIsRedirect If given, will optimize adding and
1039 * removing rows in redirect table.
1040 * @return bool true on success, false on failure
1043 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1044 wfProfileIn( __METHOD__
);
1046 $text = $revision->getText();
1047 $rt = Title
::newFromRedirect( $text );
1049 $conditions = array( 'page_id' => $this->getId() );
1050 if( !is_null( $lastRevision ) ) {
1051 # An extra check against threads stepping on each other
1052 $conditions['page_latest'] = $lastRevision;
1055 $dbw->update( 'page',
1057 'page_latest' => $revision->getId(),
1058 'page_touched' => $dbw->timestamp(),
1059 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1060 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1061 'page_len' => strlen( $text ),
1066 $result = $dbw->affectedRows() != 0;
1069 // FIXME: Should the result from updateRedirectOn() be returned instead?
1070 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1073 wfProfileOut( __METHOD__
);
1078 * Add row to the redirect table if this is a redirect, remove otherwise.
1080 * @param Database $dbw
1081 * @param $redirectTitle a title object pointing to the redirect target,
1082 * or NULL if this is not a redirect
1083 * @param bool $lastRevIsRedirect If given, will optimize adding and
1084 * removing rows in redirect table.
1085 * @return bool true on success, false on failure
1088 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1090 // Always update redirects (target link might have changed)
1091 // Update/Insert if we don't know if the last revision was a redirect or not
1092 // Delete if changing from redirect to non-redirect
1093 $isRedirect = !is_null($redirectTitle);
1094 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1096 wfProfileIn( __METHOD__
);
1100 // This title is a redirect, Add/Update row in the redirect table
1101 $set = array( /* SET */
1102 'rd_namespace' => $redirectTitle->getNamespace(),
1103 'rd_title' => $redirectTitle->getDBkey(),
1104 'rd_from' => $this->getId(),
1107 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1109 // This is not a redirect, remove row from redirect table
1110 $where = array( 'rd_from' => $this->getId() );
1111 $dbw->delete( 'redirect', $where, __METHOD__
);
1114 wfProfileOut( __METHOD__
);
1115 return ( $dbw->affectedRows() != 0 );
1122 * If the given revision is newer than the currently set page_latest,
1123 * update the page record. Otherwise, do nothing.
1125 * @param Database $dbw
1126 * @param Revision $revision
1128 function updateIfNewerOn( &$dbw, $revision ) {
1129 wfProfileIn( __METHOD__
);
1131 $row = $dbw->selectRow(
1132 array( 'revision', 'page' ),
1133 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1135 'page_id' => $this->getId(),
1136 'page_latest=rev_id' ),
1139 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1140 wfProfileOut( __METHOD__
);
1143 $prev = $row->rev_id
;
1144 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1146 # No or missing previous revision; mark the page as new
1148 $lastRevIsRedirect = null;
1151 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1152 wfProfileOut( __METHOD__
);
1157 * @return string Complete article text, or null if error
1159 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1160 wfProfileIn( __METHOD__
);
1162 if( $section == '' ) {
1163 // Whole-page edit; let the text through unmolested.
1165 if( is_null( $edittime ) ) {
1166 $rev = Revision
::newFromTitle( $this->mTitle
);
1168 $dbw = wfGetDB( DB_MASTER
);
1169 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1171 if( is_null( $rev ) ) {
1172 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1173 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1176 $oldtext = $rev->getText();
1178 if( $section == 'new' ) {
1179 # Inserting a new section
1180 $subject = $summary ?
"== {$summary} ==\n\n" : '';
1181 $text = strlen( trim( $oldtext ) ) > 0
1182 ?
"{$oldtext}\n\n{$subject}{$text}"
1183 : "{$subject}{$text}";
1185 # Replacing an existing section; roll out the big guns
1187 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1192 wfProfileOut( __METHOD__
);
1197 * @deprecated use Article::doEdit()
1199 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1200 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1201 ( $isminor ? EDIT_MINOR
: 0 ) |
1202 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1204 # If this is a comment, add the summary as headline
1205 if ( $comment && $summary != "" ) {
1206 $text = "== {$summary} ==\n\n".$text;
1209 $this->doEdit( $text, $summary, $flags );
1211 $dbw = wfGetDB( DB_MASTER
);
1213 if (!$this->mTitle
->userIsWatching()) {
1219 if ( $this->mTitle
->userIsWatching() ) {
1225 $this->doRedirect( $this->isRedirect( $text ) );
1229 * @deprecated use Article::doEdit()
1231 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1232 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1233 ( $minor ? EDIT_MINOR
: 0 ) |
1234 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1236 $good = $this->doEdit( $text, $summary, $flags );
1238 $dbw = wfGetDB( DB_MASTER
);
1240 if (!$this->mTitle
->userIsWatching()) {
1246 if ( $this->mTitle
->userIsWatching() ) {
1253 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1261 * Change an existing article or create a new article. Updates RC and all necessary caches,
1262 * optionally via the deferred update array.
1264 * $wgUser must be set before calling this function.
1266 * @param string $text New text
1267 * @param string $summary Edit summary
1268 * @param integer $flags bitfield:
1270 * Article is known or assumed to be non-existent, create a new one
1272 * Article is known or assumed to be pre-existing, update it
1274 * Mark this edit minor, if the user is allowed to do so
1276 * Do not log the change in recentchanges
1278 * Mark the edit a "bot" edit regardless of user rights
1279 * EDIT_DEFER_UPDATES
1280 * Defer some of the updates until the end of index.php
1282 * Fill in blank summaries with generated text where possible
1284 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1285 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1286 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1287 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1288 * to MediaWiki's performance-optimised locking strategy.
1290 * @return bool success
1292 function doEdit( $text, $summary, $flags = 0 ) {
1293 global $wgUser, $wgDBtransactions;
1295 wfProfileIn( __METHOD__
);
1298 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1299 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1301 $flags |
= EDIT_UPDATE
;
1307 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1308 &$summary, $flags & EDIT_MINOR
,
1309 null, null, &$flags ) ) )
1311 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1312 wfProfileOut( __METHOD__
);
1316 # Silently ignore EDIT_MINOR if not allowed
1317 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1318 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1320 $oldtext = $this->getContent();
1321 $oldsize = strlen( $oldtext );
1323 # Provide autosummaries if one is not provided.
1324 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1325 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1327 $text = $this->preSaveTransform( $text );
1328 $newsize = strlen( $text );
1330 $dbw = wfGetDB( DB_MASTER
);
1331 $now = wfTimestampNow();
1333 if ( $flags & EDIT_UPDATE
) {
1334 # Update article, but only if changed.
1336 # Make sure the revision is either completely inserted or not inserted at all
1337 if( !$wgDBtransactions ) {
1338 $userAbort = ignore_user_abort( true );
1344 if ( 0 != strcmp( $text, $oldtext ) ) {
1345 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1346 - (int)$this->isCountable( $oldtext );
1347 $this->mTotalAdjustment
= 0;
1349 $lastRevision = $dbw->selectField(
1350 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1352 if ( !$lastRevision ) {
1353 # Article gone missing
1354 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1355 wfProfileOut( __METHOD__
);
1359 $revision = new Revision( array(
1360 'page' => $this->getId(),
1361 'comment' => $summary,
1362 'minor_edit' => $isminor,
1367 $revisionId = $revision->insertOn( $dbw );
1370 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1373 /* Belated edit conflict! Run away!! */
1377 # Update recentchanges
1378 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1379 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1380 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1383 # Mark as patrolled if the user can do so
1384 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1385 RecentChange
::markPatrolled( $rcid );
1386 PatrolLog
::record( $rcid, true );
1389 $wgUser->incEditCount();
1393 // Keep the same revision ID, but do some updates on it
1394 $revisionId = $this->getRevIdFetched();
1395 // Update page_touched, this is usually implicit in the page update
1396 // Other cache updates are done in onArticleEdit()
1397 $this->mTitle
->invalidateCache();
1400 if( !$wgDBtransactions ) {
1401 ignore_user_abort( $userAbort );
1405 # Invalidate cache of this article and all pages using this article
1406 # as a template. Partly deferred.
1407 Article
::onArticleEdit( $this->mTitle
);
1409 # Update links tables, site stats, etc.
1410 $changed = ( strcmp( $oldtext, $text ) != 0 );
1411 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1414 # Create new article
1416 # Set statistics members
1417 # We work out if it's countable after PST to avoid counter drift
1418 # when articles are created with {{subst:}}
1419 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1420 $this->mTotalAdjustment
= 1;
1424 # Add the page record; stake our claim on this title!
1425 # This will fail with a database query exception if the article already exists
1426 $newid = $this->insertOn( $dbw );
1428 # Save the revision text...
1429 $revision = new Revision( array(
1431 'comment' => $summary,
1432 'minor_edit' => $isminor,
1435 $revisionId = $revision->insertOn( $dbw );
1437 $this->mTitle
->resetArticleID( $newid );
1439 # Update the page record with revision data
1440 $this->updateRevisionOn( $dbw, $revision, 0 );
1442 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1443 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1444 '', strlen( $text ), $revisionId );
1445 # Mark as patrolled if the user can
1446 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1447 RecentChange
::markPatrolled( $rcid );
1448 PatrolLog
::record( $rcid, true );
1451 $wgUser->incEditCount();
1454 # Update links, etc.
1455 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1458 Article
::onArticleCreate( $this->mTitle
);
1460 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1461 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1464 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1468 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1469 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1471 wfProfileOut( __METHOD__
);
1476 * @deprecated wrapper for doRedirect
1478 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1479 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1483 * Output a redirect back to the article.
1484 * This is typically used after an edit.
1486 * @param boolean $noRedir Add redirect=no
1487 * @param string $sectionAnchor section to redirect to, including "#"
1489 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1492 $query = 'redirect=no';
1496 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1500 * Mark this particular edit as patrolled
1502 function markpatrolled() {
1503 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1504 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1506 # Check RC patrol config. option
1507 if( !$wgUseRCPatrol ) {
1508 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1513 if( !$wgUser->isAllowed( 'patrol' ) ) {
1514 $wgOut->permissionRequired( 'patrol' );
1518 # If we haven't been given an rc_id value, we can't do anything
1519 $rcid = $wgRequest->getVal( 'rcid' );
1521 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1525 # Handle the 'MarkPatrolled' hook
1526 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1530 $return = SpecialPage
::getTitleFor( 'Recentchanges' );
1531 # If it's left up to us, check that the user is allowed to patrol this edit
1532 # If the user has the "autopatrol" right, then we'll assume there are no
1533 # other conditions stopping them doing so
1534 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1535 $rc = RecentChange
::newFromId( $rcid );
1536 # Graceful error handling, as we've done before here...
1537 # (If the recent change doesn't exist, then it doesn't matter whether
1538 # the user is allowed to patrol it or not; nothing is going to happen
1539 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1540 # The user made this edit, and can't patrol it
1541 # Tell them so, and then back off
1542 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1543 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1544 $wgOut->returnToMain( false, $return );
1549 # Mark the edit as patrolled
1550 RecentChange
::markPatrolled( $rcid );
1551 PatrolLog
::record( $rcid );
1552 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1555 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1556 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1557 $wgOut->returnToMain( false, $return );
1561 * User-interface handler for the "watch" action
1566 global $wgUser, $wgOut;
1568 if ( $wgUser->isAnon() ) {
1569 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1572 if ( wfReadOnly() ) {
1573 $wgOut->readOnlyPage();
1577 if( $this->doWatch() ) {
1578 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1579 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1581 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1582 $text = wfMsg( 'addedwatchtext', $link );
1583 $wgOut->addWikiText( $text );
1586 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1590 * Add this page to $wgUser's watchlist
1591 * @return bool true on successful watch operation
1593 function doWatch() {
1595 if( $wgUser->isAnon() ) {
1599 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1600 $wgUser->addWatch( $this->mTitle
);
1602 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1609 * User interface handler for the "unwatch" action.
1611 function unwatch() {
1613 global $wgUser, $wgOut;
1615 if ( $wgUser->isAnon() ) {
1616 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1619 if ( wfReadOnly() ) {
1620 $wgOut->readOnlyPage();
1624 if( $this->doUnwatch() ) {
1625 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1626 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1628 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1629 $text = wfMsg( 'removedwatchtext', $link );
1630 $wgOut->addWikiText( $text );
1633 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1637 * Stop watching a page
1638 * @return bool true on successful unwatch
1640 function doUnwatch() {
1642 if( $wgUser->isAnon() ) {
1646 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1647 $wgUser->removeWatch( $this->mTitle
);
1649 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1656 * action=protect handler
1658 function protect() {
1659 $form = new ProtectionForm( $this );
1664 * action=unprotect handler (alias)
1666 function unprotect() {
1671 * Update the article's restriction field, and leave a log entry.
1673 * @param array $limit set of restriction keys
1674 * @param string $reason
1675 * @return bool true on success
1677 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1678 global $wgUser, $wgRestrictionTypes, $wgContLang;
1680 $id = $this->mTitle
->getArticleID();
1681 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1689 // Take this opportunity to purge out expired restrictions
1690 Title
::purgeExpiredRestrictions();
1692 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1693 # we expect a single selection, but the schema allows otherwise.
1695 foreach( $wgRestrictionTypes as $action )
1696 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1698 $current = Article
::flattenRestrictions( $current );
1699 $updated = Article
::flattenRestrictions( $limit );
1701 $changed = ( $current != $updated );
1702 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1703 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1704 $protect = ( $updated != '' );
1706 # If nothing's changed, do nothing
1708 global $wgGroupPermissions;
1709 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1711 $dbw = wfGetDB( DB_MASTER
);
1713 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1715 $expiry_description = '';
1716 if ( $encodedExpiry != 'infinity' ) {
1717 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1720 # Prepare a null revision to be added to the history
1721 $modified = $current != '' && $protect;
1723 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1725 $comment_type = 'unprotectedarticle';
1727 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1729 foreach( $limit as $action => $restrictions ) {
1730 # Check if the group level required to edit also can protect pages
1731 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1732 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1735 $cascade_description = '';
1737 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1741 $comment .= ": $reason";
1743 $comment .= " [$updated]";
1744 if ( $expiry_description && $protect )
1745 $comment .= "$expiry_description";
1747 $comment .= "$cascade_description";
1749 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1750 $nullRevId = $nullRevision->insertOn( $dbw );
1752 # Update restrictions table
1753 foreach( $limit as $action => $restrictions ) {
1754 if ($restrictions != '' ) {
1755 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1756 array( 'pr_page' => $id, 'pr_type' => $action
1757 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1758 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1760 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1761 'pr_type' => $action ), __METHOD__
);
1765 # Update page record
1766 $dbw->update( 'page',
1768 'page_touched' => $dbw->timestamp(),
1769 'page_restrictions' => '',
1770 'page_latest' => $nullRevId
1771 ), array( /* WHERE */
1773 ), 'Article::protect'
1775 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1777 # Update the protection log
1778 $log = new LogPage( 'protect' );
1781 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1783 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1787 } # End "changed" check
1793 * Take an array of page restrictions and flatten it to a string
1794 * suitable for insertion into the page_restrictions field.
1795 * @param array $limit
1799 function flattenRestrictions( $limit ) {
1800 if( !is_array( $limit ) ) {
1801 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1805 foreach( $limit as $action => $restrictions ) {
1806 if( $restrictions != '' ) {
1807 $bits[] = "$action=$restrictions";
1810 return implode( ':', $bits );
1814 * UI entry point for page deletion
1817 global $wgUser, $wgOut, $wgRequest;
1818 $confirm = $wgRequest->wasPosted() &&
1819 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1820 $reason = $wgRequest->getText( 'wpReason' );
1822 # This code desperately needs to be totally rewritten
1825 if( $wgUser->isAllowed( 'delete' ) ) {
1826 if( $wgUser->isBlocked( !$confirm ) ) {
1827 $wgOut->blockedPage();
1831 $wgOut->permissionRequired( 'delete' );
1835 if( wfReadOnly() ) {
1836 $wgOut->readOnlyPage();
1840 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1842 # Better double-check that it hasn't been deleted yet!
1843 $dbw = wfGetDB( DB_MASTER
);
1844 $conds = $this->mTitle
->pageCond();
1845 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1846 if ( $latest === false ) {
1847 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1852 $this->doDelete( $reason );
1853 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1855 } elseif( $this->mTitle
->userIsWatching() ) {
1861 # determine whether this page has earlier revisions
1862 # and insert a warning if it does
1864 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1866 if( count( $authors ) > 1 && !$confirm ) {
1867 $skin=$wgUser->getSkin();
1868 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1871 # If a single user is responsible for all revisions, find out who they are
1872 if ( count( $authors ) == $maxRevisions ) {
1873 // Query bailed out, too many revisions to find out if they're all the same
1874 $authorOfAll = false;
1876 $authorOfAll = reset( $authors );
1877 foreach ( $authors as $author ) {
1878 if ( $authorOfAll != $author ) {
1879 $authorOfAll = false;
1884 # Fetch article text
1885 $rev = Revision
::newFromTitle( $this->mTitle
);
1887 if( !is_null( $rev ) ) {
1888 # if this is a mini-text, we can paste part of it into the deletion reason
1889 $text = $rev->getText();
1891 #if this is empty, an earlier revision may contain "useful" text
1894 $prev = $rev->getPrevious();
1896 $text = $prev->getText();
1901 $length = strlen( $text );
1903 # this should not happen, since it is not possible to store an empty, new
1904 # page. Let's insert a standard text in case it does, though
1905 if( $length == 0 && $reason === '' ) {
1906 $reason = wfMsgForContent( 'exblank' );
1909 if( $reason === '' ) {
1910 # comment field=255, let's grep the first 150 to have some user
1913 $text = $wgContLang->truncate( $text, 150, '...' );
1915 # let's strip out newlines
1916 $text = preg_replace( "/[\n\r]/", '', $text );
1919 if( $authorOfAll === false ) {
1920 $reason = wfMsgForContent( 'excontent', $text );
1922 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1925 $reason = wfMsgForContent( 'exbeforeblank', $text );
1930 return $this->confirmDelete( '', $reason );
1934 * Get the last N authors
1935 * @param int $num Number of revisions to get
1936 * @param string $revLatest The latest rev_id, selected from the master (optional)
1937 * @return array Array of authors, duplicates not removed
1939 function getLastNAuthors( $num, $revLatest = 0 ) {
1940 wfProfileIn( __METHOD__
);
1942 // First try the slave
1943 // If that doesn't have the latest revision, try the master
1945 $db = wfGetDB( DB_SLAVE
);
1947 $res = $db->select( array( 'page', 'revision' ),
1948 array( 'rev_id', 'rev_user_text' ),
1950 'page_namespace' => $this->mTitle
->getNamespace(),
1951 'page_title' => $this->mTitle
->getDBkey(),
1952 'rev_page = page_id'
1953 ), __METHOD__
, $this->getSelectOptions( array(
1954 'ORDER BY' => 'rev_timestamp DESC',
1959 wfProfileOut( __METHOD__
);
1962 $row = $db->fetchObject( $res );
1963 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1964 $db = wfGetDB( DB_MASTER
);
1969 } while ( $continue );
1971 $authors = array( $row->rev_user_text
);
1972 while ( $row = $db->fetchObject( $res ) ) {
1973 $authors[] = $row->rev_user_text
;
1975 wfProfileOut( __METHOD__
);
1980 * Output deletion confirmation dialog
1982 function confirmDelete( $par, $reason ) {
1983 global $wgOut, $wgUser;
1985 wfDebug( "Article::confirmDelete\n" );
1987 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1988 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1989 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1990 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1992 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1994 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1995 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1996 $token = htmlspecialchars( $wgUser->editToken() );
1997 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
2000 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
2004 <label for='wpReason'>{$delcom}:</label>
2007 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
2017 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2021 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2024 $wgOut->returnToMain( false );
2026 $this->showLogExtract( $wgOut );
2031 * Show relevant lines from the deletion log
2033 function showLogExtract( $out ) {
2034 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2035 $logViewer = new LogViewer(
2038 array( 'page' => $this->mTitle
->getPrefixedText(),
2039 'type' => 'delete' ) ) ) );
2040 $logViewer->showList( $out );
2045 * Perform a deletion and output success or failure messages
2047 function doDelete( $reason ) {
2048 global $wgOut, $wgUser;
2049 wfDebug( __METHOD__
."\n" );
2051 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2052 if ( $this->doDeleteArticle( $reason ) ) {
2053 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2055 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2056 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2058 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2059 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2061 $wgOut->addWikiText( $text );
2062 $wgOut->returnToMain( false );
2063 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2065 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2071 * Back-end article deletion
2072 * Deletes the article with database consistency, writes logs, purges caches
2075 function doDeleteArticle( $reason ) {
2076 global $wgUseSquid, $wgDeferredUpdateList;
2077 global $wgUseTrackbacks;
2079 wfDebug( __METHOD__
."\n" );
2081 $dbw = wfGetDB( DB_MASTER
);
2082 $ns = $this->mTitle
->getNamespace();
2083 $t = $this->mTitle
->getDBkey();
2084 $id = $this->mTitle
->getArticleID();
2086 if ( $t == '' ||
$id == 0 ) {
2090 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2091 array_push( $wgDeferredUpdateList, $u );
2093 // For now, shunt the revision data into the archive table.
2094 // Text is *not* removed from the text table; bulk storage
2095 // is left intact to avoid breaking block-compression or
2096 // immutable storage schemes.
2098 // For backwards compatibility, note that some older archive
2099 // table entries will have ar_text and ar_flags fields still.
2101 // In the future, we may keep revisions and mark them with
2102 // the rev_deleted field, which is reserved for this purpose.
2103 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2105 'ar_namespace' => 'page_namespace',
2106 'ar_title' => 'page_title',
2107 'ar_comment' => 'rev_comment',
2108 'ar_user' => 'rev_user',
2109 'ar_user_text' => 'rev_user_text',
2110 'ar_timestamp' => 'rev_timestamp',
2111 'ar_minor_edit' => 'rev_minor_edit',
2112 'ar_rev_id' => 'rev_id',
2113 'ar_text_id' => 'rev_text_id',
2114 'ar_text' => '\'\'', // Be explicit to appease
2115 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2116 'ar_len' => 'rev_len',
2120 'page_id = rev_page'
2124 # Delete restrictions for it
2125 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2127 # Now that it's safely backed up, delete it
2128 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2130 # If using cascading deletes, we can skip some explicit deletes
2131 if ( !$dbw->cascadingDeletes() ) {
2133 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2135 if ($wgUseTrackbacks)
2136 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2138 # Delete outgoing links
2139 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2140 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2141 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2142 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2143 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2144 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2145 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2148 # If using cleanup triggers, we can skip some manual deletes
2149 if ( !$dbw->cleanupTriggers() ) {
2151 # Clean up recentchanges entries...
2152 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2156 Article
::onArticleDelete( $this->mTitle
);
2159 $log = new LogPage( 'delete' );
2160 $log->addEntry( 'delete', $this->mTitle
, $reason );
2162 # Clear the cached article id so the interface doesn't act like we exist
2163 $this->mTitle
->resetArticleID( 0 );
2164 $this->mTitle
->mArticleID
= 0;
2169 * Roll back the most recent consecutive set of edits to a page
2170 * from the same user; fails if there are no eligible edits to
2171 * roll back to, e.g. user is the sole contributor
2173 * @param string $fromP - Name of the user whose edits to rollback.
2174 * @param string $summary - Custom summary. Set to default summary if empty.
2175 * @param string $token - Rollback token.
2176 * @param bool $bot - If true, mark all reverted edits as bot.
2178 * @param array $resultDetails contains result-specific dict of additional values
2179 * ALREADY_ROLLED : 'current' (rev)
2180 * SUCCESS : 'summary' (str), 'current' (rev), 'target' (rev)
2182 * @return self::SUCCESS on succes, self::* on failure
2184 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2185 global $wgUser, $wgUseRCPatrol;
2186 $resultDetails = null;
2188 if( $wgUser->isAllowed( 'rollback' ) ) {
2189 if( $wgUser->isBlocked() ) {
2190 return self
::BLOCKED
;
2193 return self
::PERM_DENIED
;
2196 if ( wfReadOnly() ) {
2197 return self
::READONLY
;
2199 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2200 return self
::BAD_TOKEN
;
2202 $dbw = wfGetDB( DB_MASTER
);
2204 # Get the last editor
2205 $current = Revision
::newFromTitle( $this->mTitle
);
2206 if( is_null( $current ) ) {
2207 # Something wrong... no page?
2208 return self
::BAD_TITLE
;
2211 $from = str_replace( '_', ' ', $fromP );
2212 if( $from != $current->getUserText() ) {
2213 $resultDetails = array( 'current' => $current );
2214 return self
::ALREADY_ROLLED
;
2217 # Get the last edit not by this guy
2218 $user = intval( $current->getUser() );
2219 $user_text = $dbw->addQuotes( $current->getUserText() );
2220 $s = $dbw->selectRow( 'revision',
2221 array( 'rev_id', 'rev_timestamp' ),
2223 'rev_page' => $current->getPage(),
2224 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2227 'USE INDEX' => 'page_timestamp',
2228 'ORDER BY' => 'rev_timestamp DESC' )
2230 if( $s === false ) {
2232 return self
::ONLY_AUTHOR
;
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 if( empty( $summary ) )
2258 $summary = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2261 $flags = EDIT_UPDATE | EDIT_MINOR
;
2263 $flags |
= EDIT_FORCE_BOT
;
2264 $this->doEdit( $target->getText(), $summary, $flags );
2266 $resultDetails = array(
2267 'summary' => $summary,
2268 'current' => $current,
2269 'target' => $target,
2271 return self
::SUCCESS
;
2275 * User interface for rollback operations
2277 function rollback() {
2278 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2281 $result = $this->doRollback(
2282 $wgRequest->getVal( 'from' ),
2283 $wgRequest->getText( 'summary' ),
2284 $wgRequest->getVal( 'token' ),
2285 $wgRequest->getBool( 'bot' ),
2291 $wgOut->blockedPage();
2293 case self
::PERM_DENIED
:
2294 $wgOut->permissionRequired( 'rollback' );
2296 case self
::READONLY
:
2297 $wgOut->readOnlyPage( $this->getContent() );
2299 case self
::BAD_TOKEN
:
2300 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2301 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2303 case self
::BAD_TITLE
:
2304 $wgOut->addHtml( wfMsg( 'notanarticle' ) );
2306 case self
::ALREADY_ROLLED
:
2307 $current = $details['current'];
2308 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2309 $wgOut->addWikiText(
2310 wfMsg( 'alreadyrolled',
2311 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2312 htmlspecialchars( $wgRequest->getVal( 'from' ) ),
2313 htmlspecialchars( $current->getUserText() )
2316 if( $current->getComment() != '' ) {
2317 $wgOut->addHtml( wfMsg( 'editcomment',
2318 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2321 case self
::ONLY_AUTHOR
:
2322 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2323 $wgOut->addHtml( wfMsg( 'cantrollback' ) );
2326 $current = $details['current'];
2327 $target = $details['target'];
2328 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2329 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2330 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2331 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2332 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2333 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2334 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2335 $wgOut->returnToMain( false, $this->mTitle
);
2338 throw new MWException( __METHOD__
. ": Unknown return value `{$retval}`" );
2345 * Do standard deferred updates after page view
2348 function viewUpdates() {
2349 global $wgDeferredUpdateList;
2351 if ( 0 != $this->getID() ) {
2352 global $wgDisableCounters;
2353 if( !$wgDisableCounters ) {
2354 Article
::incViewCount( $this->getID() );
2355 $u = new SiteStatsUpdate( 1, 0, 0 );
2356 array_push( $wgDeferredUpdateList, $u );
2360 # Update newtalk / watchlist notification status
2362 $wgUser->clearNotification( $this->mTitle
);
2366 * Do standard deferred updates after page edit.
2367 * Update links tables, site stats, search index and message cache.
2368 * Every 1000th edit, prune the recent changes table.
2371 * @param $text New text of the article
2372 * @param $summary Edit summary
2373 * @param $minoredit Minor edit
2374 * @param $timestamp_of_pagechange Timestamp associated with the page change
2375 * @param $newid rev_id value of the new revision
2376 * @param $changed Whether or not the content actually changed
2378 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2379 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2381 wfProfileIn( __METHOD__
);
2384 $options = new ParserOptions
;
2385 $options->setTidy(true);
2386 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2388 # Save it to the parser cache
2389 $parserCache =& ParserCache
::singleton();
2390 $parserCache->save( $poutput, $this, $wgUser );
2392 # Update the links tables
2393 $u = new LinksUpdate( $this->mTitle
, $poutput );
2396 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2398 if ( 0 == mt_rand( 0, 99 ) ) {
2399 # Periodically flush old entries from the recentchanges table.
2402 $dbw = wfGetDB( DB_MASTER
);
2403 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2404 $recentchanges = $dbw->tableName( 'recentchanges' );
2405 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2406 $dbw->query( $sql );
2410 $id = $this->getID();
2411 $title = $this->mTitle
->getPrefixedDBkey();
2412 $shortTitle = $this->mTitle
->getDBkey();
2415 wfProfileOut( __METHOD__
);
2419 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2420 array_push( $wgDeferredUpdateList, $u );
2421 $u = new SearchUpdate( $id, $title, $text );
2422 array_push( $wgDeferredUpdateList, $u );
2424 # If this is another user's talk page, update newtalk
2425 # Don't do this if $changed = false otherwise some idiot can null-edit a
2426 # load of user talk pages and piss people off, nor if it's a minor edit
2427 # by a properly-flagged bot.
2428 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2429 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2430 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2431 $other = User
::newFromName( $shortTitle );
2432 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2433 // An anonymous user
2434 $other = new User();
2435 $other->setName( $shortTitle );
2438 $other->setNewtalk( true );
2443 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2444 $wgMessageCache->replace( $shortTitle, $text );
2447 wfProfileOut( __METHOD__
);
2451 * Perform article updates on a special page creation.
2453 * @param Revision $rev
2455 * @todo This is a shitty interface function. Kill it and replace the
2456 * other shitty functions like editUpdates and such so it's not needed
2459 function createUpdates( $rev ) {
2460 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2461 $this->mTotalAdjustment
= 1;
2462 $this->editUpdates( $rev->getText(), $rev->getComment(),
2463 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2467 * Generate the navigation links when browsing through an article revisions
2468 * It shows the information as:
2469 * Revision as of \<date\>; view current revision
2470 * \<- Previous version | Next Version -\>
2473 * @param string $oldid Revision ID of this article revision
2475 function setOldSubtitle( $oldid=0 ) {
2476 global $wgLang, $wgOut, $wgUser;
2478 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2482 $revision = Revision
::newFromId( $oldid );
2484 $current = ( $oldid == $this->mLatest
);
2485 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2486 $sk = $wgUser->getSkin();
2488 ?
wfMsg( 'currentrevisionlink' )
2489 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2492 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2493 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2495 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2496 : wfMsg( 'previousrevision' );
2498 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2500 $nextlink = $current
2501 ?
wfMsg( 'nextrevision' )
2502 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2503 $nextdiff = $current
2505 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2507 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2508 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2510 $m = wfMsg( 'revision-info-current' );
2511 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2512 ?
'revision-info-current'
2515 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2516 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2517 $wgOut->setSubtitle( $r );
2521 * This function is called right before saving the wikitext,
2522 * so we can do things like signatures and links-in-context.
2524 * @param string $text
2526 function preSaveTransform( $text ) {
2527 global $wgParser, $wgUser;
2528 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2531 /* Caching functions */
2534 * checkLastModified returns true if it has taken care of all
2535 * output to the client that is necessary for this request.
2536 * (that is, it has sent a cached version of the page)
2538 function tryFileCache() {
2539 static $called = false;
2541 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2545 if($this->isFileCacheable()) {
2546 $touched = $this->mTouched
;
2547 $cache = new HTMLFileCache( $this->mTitle
);
2548 if($cache->isFileCacheGood( $touched )) {
2549 wfDebug( "Article::tryFileCache(): about to load file\n" );
2550 $cache->loadFromFileCache();
2553 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2554 ob_start( array(&$cache, 'saveToFileCache' ) );
2557 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2562 * Check if the page can be cached
2565 function isFileCacheable() {
2566 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2567 $action = $wgRequest->getVal( 'action' );
2568 $oldid = $wgRequest->getVal( 'oldid' );
2569 $diff = $wgRequest->getVal( 'diff' );
2570 $redirect = $wgRequest->getVal( 'redirect' );
2571 $printable = $wgRequest->getVal( 'printable' );
2572 $page = $wgRequest->getVal( 'page' );
2574 //check for non-standard user language; this covers uselang,
2575 //and extensions for auto-detecting user language.
2576 $ulang = $wgLang->getCode();
2577 $clang = $wgContLang->getCode();
2579 $cacheable = $wgUseFileCache
2580 && (!$wgShowIPinHeader)
2581 && ($this->getID() != 0)
2582 && ($wgUser->isAnon())
2583 && (!$wgUser->getNewtalk())
2584 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2585 && (empty( $action ) ||
$action == 'view')
2588 && (!isset($redirect))
2589 && (!isset($printable))
2591 && (!$this->mRedirectedFrom
)
2592 && ($ulang === $clang);
2595 //extension may have reason to disable file caching on some pages.
2596 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2603 * Loads page_touched and returns a value indicating if it should be used
2606 function checkTouched() {
2607 if( !$this->mDataLoaded
) {
2608 $this->loadPageData();
2610 return !$this->mIsRedirect
;
2614 * Get the page_touched field
2616 function getTouched() {
2617 # Ensure that page data has been loaded
2618 if( !$this->mDataLoaded
) {
2619 $this->loadPageData();
2621 return $this->mTouched
;
2625 * Get the page_latest field
2627 function getLatest() {
2628 if ( !$this->mDataLoaded
) {
2629 $this->loadPageData();
2631 return $this->mLatest
;
2635 * Edit an article without doing all that other stuff
2636 * The article must already exist; link tables etc
2637 * are not updated, caches are not flushed.
2639 * @param string $text text submitted
2640 * @param string $comment comment submitted
2641 * @param bool $minor whereas it's a minor modification
2643 function quickEdit( $text, $comment = '', $minor = 0 ) {
2644 wfProfileIn( __METHOD__
);
2646 $dbw = wfGetDB( DB_MASTER
);
2648 $revision = new Revision( array(
2649 'page' => $this->getId(),
2651 'comment' => $comment,
2652 'minor_edit' => $minor ?
1 : 0,
2654 $revision->insertOn( $dbw );
2655 $this->updateRevisionOn( $dbw, $revision );
2658 wfProfileOut( __METHOD__
);
2662 * Used to increment the view counter
2665 * @param integer $id article id
2667 function incViewCount( $id ) {
2668 $id = intval( $id );
2669 global $wgHitcounterUpdateFreq, $wgDBtype;
2671 $dbw = wfGetDB( DB_MASTER
);
2672 $pageTable = $dbw->tableName( 'page' );
2673 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2674 $acchitsTable = $dbw->tableName( 'acchits' );
2676 if( $wgHitcounterUpdateFreq <= 1 ) {
2677 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2681 # Not important enough to warrant an error page in case of failure
2682 $oldignore = $dbw->ignoreErrors( true );
2684 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2686 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2687 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2688 # Most of the time (or on SQL errors), skip row count check
2689 $dbw->ignoreErrors( $oldignore );
2693 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2694 $row = $dbw->fetchObject( $res );
2695 $rown = intval( $row->n
);
2696 if( $rown >= $wgHitcounterUpdateFreq ){
2697 wfProfileIn( 'Article::incViewCount-collect' );
2698 $old_user_abort = ignore_user_abort( true );
2700 if ($wgDBtype == 'mysql')
2701 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2702 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2703 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2704 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2706 $dbw->query("DELETE FROM $hitcounterTable");
2707 if ($wgDBtype == 'mysql') {
2708 $dbw->query('UNLOCK TABLES');
2709 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2710 'WHERE page_id = hc_id');
2713 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2714 "FROM $acchitsTable WHERE page_id = hc_id");
2716 $dbw->query("DROP TABLE $acchitsTable");
2718 ignore_user_abort( $old_user_abort );
2719 wfProfileOut( 'Article::incViewCount-collect' );
2721 $dbw->ignoreErrors( $oldignore );
2725 * The onArticle*() functions are supposed to be a kind of hooks
2726 * which should be called whenever any of the specified actions
2729 * This is a good place to put code to clear caches, for instance.
2731 * This is called on page move and undelete, as well as edit
2733 * @param $title_obj a title object
2736 static function onArticleCreate($title) {
2737 # The talk page isn't in the regular link tables, so we need to update manually:
2738 if ( $title->isTalkPage() ) {
2739 $other = $title->getSubjectPage();
2741 $other = $title->getTalkPage();
2743 $other->invalidateCache();
2744 $other->purgeSquid();
2746 $title->touchLinks();
2747 $title->purgeSquid();
2750 static function onArticleDelete( $title ) {
2751 global $wgUseFileCache, $wgMessageCache;
2753 $title->touchLinks();
2754 $title->purgeSquid();
2757 if ( $wgUseFileCache ) {
2758 $cm = new HTMLFileCache( $title );
2759 @unlink
( $cm->fileCacheName() );
2762 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2763 $wgMessageCache->replace( $title->getDBkey(), false );
2768 * Purge caches on page update etc
2770 static function onArticleEdit( $title ) {
2771 global $wgDeferredUpdateList, $wgUseFileCache;
2773 // Invalidate caches of articles which include this page
2774 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2775 $wgDeferredUpdateList[] = $update;
2777 # Purge squid for this page only
2778 $title->purgeSquid();
2781 if ( $wgUseFileCache ) {
2782 $cm = new HTMLFileCache( $title );
2783 @unlink
( $cm->fileCacheName() );
2790 * Info about this page
2791 * Called for ?action=info when $wgAllowPageInfo is on.
2796 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2798 if ( !$wgAllowPageInfo ) {
2799 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2803 $page = $this->mTitle
->getSubjectPage();
2805 $wgOut->setPagetitle( $page->getPrefixedText() );
2806 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
2807 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
2809 if( !$this->mTitle
->exists() ) {
2810 $wgOut->addHtml( '<div class="noarticletext">' );
2811 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2812 // This doesn't quite make sense; the user is asking for
2813 // information about the _page_, not the message... -- RC
2814 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
2816 $msg = $wgUser->isLoggedIn()
2818 : 'noarticletextanon';
2819 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
2821 $wgOut->addHtml( '</div>' );
2823 $dbr = wfGetDB( DB_SLAVE
);
2825 'wl_title' => $page->getDBkey(),
2826 'wl_namespace' => $page->getNamespace() );
2827 $numwatchers = $dbr->selectField(
2832 $this->getSelectOptions() );
2834 $pageInfo = $this->pageCountInfo( $page );
2835 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2837 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2838 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2840 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2842 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2844 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2846 $wgOut->addHTML( '</ul>' );
2852 * Return the total number of edits and number of unique editors
2853 * on a given page. If page does not exist, returns false.
2855 * @param Title $title
2859 function pageCountInfo( $title ) {
2860 $id = $title->getArticleId();
2865 $dbr = wfGetDB( DB_SLAVE
);
2867 $rev_clause = array( 'rev_page' => $id );
2869 $edits = $dbr->selectField(
2874 $this->getSelectOptions() );
2876 $authors = $dbr->selectField(
2878 'COUNT(DISTINCT rev_user_text)',
2881 $this->getSelectOptions() );
2883 return array( 'edits' => $edits, 'authors' => $authors );
2887 * Return a list of templates used by this article.
2888 * Uses the templatelinks table
2890 * @return array Array of Title objects
2892 function getUsedTemplates() {
2894 $id = $this->mTitle
->getArticleID();
2899 $dbr = wfGetDB( DB_SLAVE
);
2900 $res = $dbr->select( array( 'templatelinks' ),
2901 array( 'tl_namespace', 'tl_title' ),
2902 array( 'tl_from' => $id ),
2903 'Article:getUsedTemplates' );
2904 if ( false !== $res ) {
2905 if ( $dbr->numRows( $res ) ) {
2906 while ( $row = $dbr->fetchObject( $res ) ) {
2907 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2911 $dbr->freeResult( $res );
2916 * Return an auto-generated summary if the text provided is a redirect.
2918 * @param string $text The wikitext to check
2919 * @return string '' or an appropriate summary
2921 public static function getRedirectAutosummary( $text ) {
2922 $rt = Title
::newFromRedirect( $text );
2923 if( is_object( $rt ) )
2924 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2930 * Return an auto-generated summary if the new text is much shorter than
2933 * @param string $oldtext The previous text of the page
2934 * @param string $text The submitted text of the page
2935 * @return string An appropriate autosummary, or an empty string.
2937 public static function getBlankingAutosummary( $oldtext, $text ) {
2938 if ($oldtext!='' && $text=='') {
2939 return wfMsgForContent('autosumm-blank');
2940 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2941 #Removing more than 90% of the article
2943 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2944 return wfMsgForContent('autosumm-replace', $truncatedtext);
2951 * Return an applicable autosummary if one exists for the given edit.
2952 * @param string $oldtext The previous text of the page.
2953 * @param string $newtext The submitted text of the page.
2954 * @param bitmask $flags A bitmask of flags submitted for the edit.
2955 * @return string An appropriate autosummary, or an empty string.
2957 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2959 # This code is UGLY UGLY UGLY.
2960 # Somebody PLEASE come up with a more elegant way to do it.
2962 #Redirect autosummaries
2963 $summary = self
::getRedirectAutosummary( $newtext );
2968 #Blanking autosummaries
2969 if (!($flags & EDIT_NEW
))
2970 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
2975 #New page autosummaries
2976 if ($flags & EDIT_NEW
&& strlen($newtext)) {
2977 #If they're making a new article, give its text, truncated, in the summary.
2979 $truncatedtext = $wgContLang->truncate(
2980 str_replace("\n", ' ', $newtext),
2981 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2983 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
2993 * Add the primary page-view wikitext to the output buffer
2994 * Saves the text into the parser cache if possible.
2995 * Updates templatelinks if it is out of date.
2997 * @param string $text
2998 * @param bool $cache
3000 public function outputWikiText( $text, $cache = true ) {
3001 global $wgParser, $wgUser, $wgOut;
3003 $popts = $wgOut->parserOptions();
3004 $popts->setTidy(true);
3005 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3006 $popts, true, true, $this->getRevIdFetched() );
3007 $popts->setTidy(false);
3008 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3009 $parserCache =& ParserCache
::singleton();
3010 $parserCache->save( $parserOutput, $this, $wgUser );
3013 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3014 // templatelinks table may have become out of sync,
3015 // especially if using variable-based transclusions.
3016 // For paranoia, check if things have changed and if
3017 // so apply updates to the database. This will ensure
3018 // that cascaded protections apply as soon as the changes
3021 # Get templates from templatelinks
3022 $id = $this->mTitle
->getArticleID();
3024 $tlTemplates = array();
3026 $dbr = wfGetDB( DB_SLAVE
);
3027 $res = $dbr->select( array( 'templatelinks' ),
3028 array( 'tl_namespace', 'tl_title' ),
3029 array( 'tl_from' => $id ),
3030 'Article:getUsedTemplates' );
3034 if ( false !== $res ) {
3035 if ( $dbr->numRows( $res ) ) {
3036 while ( $row = $dbr->fetchObject( $res ) ) {
3037 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3042 # Get templates from parser output.
3043 $poTemplates_allns = $parserOutput->getTemplates();
3045 $poTemplates = array ();
3046 foreach ( $poTemplates_allns as $ns_templates ) {
3047 $poTemplates = array_merge( $poTemplates, $ns_templates );
3051 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3053 if ( count( $templates_diff ) > 0 ) {
3054 # Whee, link updates time.
3055 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3057 $dbw = wfGetDb( DB_MASTER
);
3066 $wgOut->addParserOutput( $parserOutput );