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 ) {
274 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
275 $row = $dbr->selectRow(
281 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
286 * @param Database $dbr
287 * @param Title $title
289 function pageDataFromTitle( $dbr, $title ) {
290 return $this->pageData( $dbr, array(
291 'page_namespace' => $title->getNamespace(),
292 'page_title' => $title->getDBkey() ) );
296 * @param Database $dbr
299 function pageDataFromId( $dbr, $id ) {
300 return $this->pageData( $dbr, array( 'page_id' => $id ) );
304 * Set the general counter, title etc data loaded from
307 * @param object $data
310 function loadPageData( $data = 'fromdb' ) {
311 if ( $data === 'fromdb' ) {
312 $dbr = $this->getDB();
313 $data = $this->pageDataFromId( $dbr, $this->getId() );
316 $lc =& LinkCache
::singleton();
318 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
320 $this->mTitle
->mArticleID
= $data->page_id
;
322 # Old-fashioned restrictions.
323 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
325 $this->mCounter
= $data->page_counter
;
326 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
327 $this->mIsRedirect
= $data->page_is_redirect
;
328 $this->mLatest
= $data->page_latest
;
330 if ( is_object( $this->mTitle
) ) {
331 $lc->addBadLinkObj( $this->mTitle
);
333 $this->mTitle
->mArticleID
= 0;
336 $this->mDataLoaded
= true;
340 * Get text of an article from database
341 * Does *NOT* follow redirects.
342 * @param int $oldid 0 for whatever the latest revision is
345 function fetchContent( $oldid = 0 ) {
346 if ( $this->mContentLoaded
) {
347 return $this->mContent
;
350 $dbr = $this->getDB();
352 # Pre-fill content with error message so that if something
353 # fails we'll have something telling us what we intended.
354 $t = $this->mTitle
->getPrefixedText();
356 $t .= ',oldid='.$oldid;
358 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
361 $revision = Revision
::newFromId( $oldid );
362 if( is_null( $revision ) ) {
363 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
366 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
368 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
371 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
372 $this->loadPageData( $data );
374 if( !$this->mDataLoaded
) {
375 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
377 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
380 $this->loadPageData( $data );
382 $revision = Revision
::newFromId( $this->mLatest
);
383 if( is_null( $revision ) ) {
384 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
389 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
390 // We should instead work with the Revision object when we need it...
391 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
392 //$this->mContent = $revision->getText();
394 $this->mUser
= $revision->getUser();
395 $this->mUserText
= $revision->getUserText();
396 $this->mComment
= $revision->getComment();
397 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
399 $this->mRevIdFetched
= $revision->getID();
400 $this->mContentLoaded
= true;
401 $this->mRevision
=& $revision;
403 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
405 return $this->mContent
;
409 * Read/write accessor to select FOR UPDATE
411 * @param $x Mixed: FIXME
413 function forUpdate( $x = NULL ) {
414 return wfSetVar( $this->mForUpdate
, $x );
418 * Get the database which should be used for reads
423 return wfGetDB( DB_MASTER
);
427 * Get options for all SELECT statements
429 * @param $options Array: an optional options array which'll be appended to
431 * @return Array: options
433 function getSelectOptions( $options = '' ) {
434 if ( $this->mForUpdate
) {
435 if ( is_array( $options ) ) {
436 $options[] = 'FOR UPDATE';
438 $options = 'FOR UPDATE';
445 * @return int Page ID
448 if( $this->mTitle
) {
449 return $this->mTitle
->getArticleID();
456 * @return bool Whether or not the page exists in the database
459 return $this->getId() != 0;
463 * @return int The view count for the page
465 function getCount() {
466 if ( -1 == $this->mCounter
) {
467 $id = $this->getID();
471 $dbr = wfGetDB( DB_SLAVE
);
472 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
473 'Article::getCount', $this->getSelectOptions() );
476 return $this->mCounter
;
480 * Determine whether a page would be suitable for being counted as an
481 * article in the site_stats table based on the title & its content
483 * @param $text String: text to analyze
486 function isCountable( $text ) {
487 global $wgUseCommaCount;
489 $token = $wgUseCommaCount ?
',' : '[[';
491 $this->mTitle
->isContentPage()
492 && !$this->isRedirect( $text )
493 && in_string( $token, $text );
497 * Tests if the article text represents a redirect
499 * @param $text String: FIXME
502 function isRedirect( $text = false ) {
503 if ( $text === false ) {
504 $this->loadContent();
505 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
507 $titleObj = Title
::newFromRedirect( $text );
509 return $titleObj !== NULL;
513 * Returns true if the currently-referenced revision is the current edit
514 * to this page (and it exists).
517 function isCurrent() {
518 # If no oldid, this is the current version.
519 if ($this->getOldID() == 0)
522 return $this->exists() &&
523 isset( $this->mRevision
) &&
524 $this->mRevision
->isCurrent();
528 * Loads everything except the text
529 * This isn't necessary for all uses, so it's only done if needed.
532 function loadLastEdit() {
533 if ( -1 != $this->mUser
)
536 # New or non-existent articles have no user information
537 $id = $this->getID();
538 if ( 0 == $id ) return;
540 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
541 if( !is_null( $this->mLastRevision
) ) {
542 $this->mUser
= $this->mLastRevision
->getUser();
543 $this->mUserText
= $this->mLastRevision
->getUserText();
544 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
545 $this->mComment
= $this->mLastRevision
->getComment();
546 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
547 $this->mRevIdFetched
= $this->mLastRevision
->getID();
551 function getTimestamp() {
552 // Check if the field has been filled by ParserCache::get()
553 if ( !$this->mTimestamp
) {
554 $this->loadLastEdit();
556 return wfTimestamp(TS_MW
, $this->mTimestamp
);
560 $this->loadLastEdit();
564 function getUserText() {
565 $this->loadLastEdit();
566 return $this->mUserText
;
569 function getComment() {
570 $this->loadLastEdit();
571 return $this->mComment
;
574 function getMinorEdit() {
575 $this->loadLastEdit();
576 return $this->mMinorEdit
;
579 function getRevIdFetched() {
580 $this->loadLastEdit();
581 return $this->mRevIdFetched
;
585 * @todo Document, fixme $offset never used.
586 * @param $limit Integer: default 0.
587 * @param $offset Integer: default 0.
589 function getContributors($limit = 0, $offset = 0) {
590 # XXX: this is expensive; cache this info somewhere.
593 $dbr = wfGetDB( DB_SLAVE
);
594 $revTable = $dbr->tableName( 'revision' );
595 $userTable = $dbr->tableName( 'user' );
596 $user = $this->getUser();
597 $pageId = $this->getId();
599 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
600 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
601 WHERE rev_page = $pageId
602 AND rev_user != $user
603 GROUP BY rev_user, rev_user_text, user_real_name
604 ORDER BY timestamp DESC";
606 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
607 $sql .= ' '. $this->getSelectOptions();
609 $res = $dbr->query($sql, __METHOD__
);
611 while ( $line = $dbr->fetchObject( $res ) ) {
612 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
615 $dbr->freeResult($res);
620 * This is the default action of the script: just view the page of
624 global $wgUser, $wgOut, $wgRequest, $wgContLang;
625 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
626 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
627 $sk = $wgUser->getSkin();
629 wfProfileIn( __METHOD__
);
631 $parserCache =& ParserCache
::singleton();
632 $ns = $this->mTitle
->getNamespace(); # shortcut
634 # Get variables from query string
635 $oldid = $this->getOldID();
637 # getOldID may want us to redirect somewhere else
638 if ( $this->mRedirectUrl
) {
639 $wgOut->redirect( $this->mRedirectUrl
);
640 wfProfileOut( __METHOD__
);
644 $diff = $wgRequest->getVal( 'diff' );
645 $rcid = $wgRequest->getVal( 'rcid' );
646 $rdfrom = $wgRequest->getVal( 'rdfrom' );
647 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
649 $wgOut->setArticleFlag( true );
651 # Discourage indexing of printable versions, but encourage following
652 if( $wgOut->isPrintable() ) {
653 $policy = 'noindex,follow';
654 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
655 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
656 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
657 # Honour customised robot policies for this namespace
658 $policy = $wgNamespaceRobotPolicies[$ns];
660 # Default to encourage indexing and following links
661 $policy = 'index,follow';
663 $wgOut->setRobotPolicy( $policy );
665 # If we got diff and oldid in the query, we want to see a
666 # diff page instead of the article.
668 if ( !is_null( $diff ) ) {
669 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
671 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
672 // DifferenceEngine directly fetched the revision:
673 $this->mRevIdFetched
= $de->mNewid
;
674 $de->showDiffPage( $diffOnly );
676 // Needed to get the page's current revision
677 $this->loadPageData();
678 if( $diff == 0 ||
$diff == $this->mLatest
) {
679 # Run view updates for current revision only
680 $this->viewUpdates();
682 wfProfileOut( __METHOD__
);
686 if ( empty( $oldid ) && $this->checkTouched() ) {
687 $wgOut->setETag($parserCache->getETag($this, $wgUser));
689 if( $wgOut->checkLastModified( $this->mTouched
) ){
690 wfProfileOut( __METHOD__
);
692 } else if ( $this->tryFileCache() ) {
693 # tell wgOut that output is taken care of
695 $this->viewUpdates();
696 wfProfileOut( __METHOD__
);
701 # Should the parser cache be used?
702 $pcache = $wgEnableParserCache
703 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
706 && !$this->mTitle
->isCssOrJsPage()
707 && !$this->mTitle
->isCssJsSubpage();
708 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
709 if ( $wgUser->getOption( 'stubthreshold' ) ) {
710 wfIncrStats( 'pcache_miss_stub' );
713 $wasRedirected = false;
714 if ( isset( $this->mRedirectedFrom
) ) {
715 // This is an internally redirected page view.
716 // We'll need a backlink to the source page for navigation.
717 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
718 $sk = $wgUser->getSkin();
719 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
720 $s = wfMsg( 'redirectedfrom', $redir );
721 $wgOut->setSubtitle( $s );
723 // Set the fragment if one was specified in the redirect
724 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
725 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
726 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
728 $wasRedirected = true;
730 } elseif ( !empty( $rdfrom ) ) {
731 // This is an externally redirected view, from some other wiki.
732 // If it was reported from a trusted site, supply a backlink.
733 global $wgRedirectSources;
734 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
735 $sk = $wgUser->getSkin();
736 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
737 $s = wfMsg( 'redirectedfrom', $redir );
738 $wgOut->setSubtitle( $s );
739 $wasRedirected = true;
744 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
746 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
747 // Ensure that UI elements requiring revision ID have
748 // the correct version information.
749 $wgOut->setRevisionId( $this->mLatest
);
753 if ( !$outputDone ) {
754 $text = $this->getContent();
755 if ( $text === false ) {
756 # Failed to load, replace text with error message
757 $t = $this->mTitle
->getPrefixedText();
759 $t .= ',oldid='.$oldid;
760 $text = wfMsg( 'missingarticle', $t );
762 $text = wfMsg( 'noarticletext', $t );
766 # Another whitelist check in case oldid is altering the title
767 if ( !$this->mTitle
->userCanRead() ) {
768 $wgOut->loginToUse();
773 # We're looking at an old revision
775 if ( !empty( $oldid ) ) {
776 $wgOut->setRobotpolicy( 'noindex,nofollow' );
777 if( is_null( $this->mRevision
) ) {
778 // FIXME: This would be a nice place to load the 'no such page' text.
780 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
781 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
782 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
783 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
784 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
787 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
788 // and we are allowed to see...
796 $wgOut->setRevisionId( $this->getRevIdFetched() );
798 // Pages containing custom CSS or JavaScript get special treatment
799 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
800 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
802 // Give hooks a chance to customise the output
803 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
804 // Wrap the whole lot in a <pre> and don't parse
805 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
806 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
807 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
808 $wgOut->addHtml( "\n</pre>\n" );
813 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
815 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
816 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
817 # Don't overwrite the subtitle if this was an old revision
818 if( !$wasRedirected && $this->isCurrent() ) {
819 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
821 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
823 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
824 '<span class="redirectText">'.$link.'</span>' );
826 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
827 $wgOut->addParserOutputNoText( $parseout );
828 } else if ( $pcache ) {
829 # Display content and save to parser cache
830 $this->outputWikiText( $text );
832 # Display content, don't attempt to save to parser cache
833 # Don't show section-edit links on old revisions... this way lies madness.
834 if( !$this->isCurrent() ) {
835 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
837 # Display content and don't save to parser cache
838 # With timing hack -- TS 2006-07-26
840 $this->outputWikiText( $text, false );
845 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
846 $this->mTitle
->getPrefixedDBkey()));
849 if( !$this->isCurrent() ) {
850 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
855 /* title may have been set from the cache */
856 $t = $wgOut->getPageTitle();
858 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
861 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
862 if( $ns == NS_USER_TALK
&&
863 User
::isIP( $this->mTitle
->getText() ) ) {
864 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
867 # If we have been passed an &rcid= parameter, we want to give the user a
868 # chance to mark this new article as patrolled.
869 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
871 "<div class='patrollink'>" .
872 wfMsgHtml( 'markaspatrolledlink',
873 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
874 "action=markpatrolled&rcid=$rcid" )
881 if ($wgUseTrackbacks)
882 $this->addTrackbacks();
884 $this->viewUpdates();
885 wfProfileOut( __METHOD__
);
888 function addTrackbacks() {
889 global $wgOut, $wgUser;
891 $dbr = wfGetDB(DB_SLAVE
);
893 /* FROM */ 'trackbacks',
894 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
895 /* WHERE */ array('tb_page' => $this->getID())
898 if (!$dbr->numrows($tbs))
902 while ($o = $dbr->fetchObject($tbs)) {
904 if ($wgUser->isAllowed( 'trackback' )) {
905 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
906 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
907 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
909 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
916 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
919 function deletetrackback() {
920 global $wgUser, $wgRequest, $wgOut, $wgTitle;
922 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
923 $wgOut->addWikitext(wfMsg('sessionfailure'));
927 if ((!$wgUser->isAllowed('delete'))) {
928 $wgOut->permissionRequired( 'delete' );
933 $wgOut->readOnlyPage();
937 $db = wfGetDB(DB_MASTER
);
938 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
939 $wgTitle->invalidateCache();
940 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
946 $wgOut->setArticleBodyOnly(true);
951 * Handle action=purge
954 global $wgUser, $wgRequest, $wgOut;
956 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
957 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
961 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
962 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
963 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
964 $msg = str_replace( '$1',
965 "<form method=\"post\" action=\"$action\">\n" .
966 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
969 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
970 $wgOut->setRobotpolicy( 'noindex,nofollow' );
971 $wgOut->addHTML( $msg );
976 * Perform the actions of a page purging
980 // Invalidate the cache
981 $this->mTitle
->invalidateCache();
984 // Commit the transaction before the purge is sent
985 $dbw = wfGetDB( DB_MASTER
);
986 $dbw->immediateCommit();
989 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
996 * Insert a new empty page record for this article.
997 * This *must* be followed up by creating a revision
998 * and running $this->updateToLatest( $rev_id );
999 * or else the record will be left in a funky state.
1000 * Best if all done inside a transaction.
1002 * @param Database $dbw
1003 * @return int The newly created page_id key
1006 function insertOn( $dbw ) {
1007 wfProfileIn( __METHOD__
);
1009 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1010 $dbw->insert( 'page', array(
1011 'page_id' => $page_id,
1012 'page_namespace' => $this->mTitle
->getNamespace(),
1013 'page_title' => $this->mTitle
->getDBkey(),
1014 'page_counter' => 0,
1015 'page_restrictions' => '',
1016 'page_is_redirect' => 0, # Will set this shortly...
1018 'page_random' => wfRandom(),
1019 'page_touched' => $dbw->timestamp(),
1020 'page_latest' => 0, # Fill this in shortly...
1021 'page_len' => 0, # Fill this in shortly...
1023 $newid = $dbw->insertId();
1025 $this->mTitle
->resetArticleId( $newid );
1027 wfProfileOut( __METHOD__
);
1032 * Update the page record to point to a newly saved revision.
1034 * @param Database $dbw
1035 * @param Revision $revision For ID number, and text used to set
1036 length and redirect status fields
1037 * @param int $lastRevision If given, will not overwrite the page field
1038 * when different from the currently set value.
1039 * Giving 0 indicates the new page flag should
1041 * @param bool $lastRevIsRedirect If given, will optimize adding and
1042 * removing rows in redirect table.
1043 * @return bool true on success, false on failure
1046 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1047 wfProfileIn( __METHOD__
);
1049 $text = $revision->getText();
1050 $rt = Title
::newFromRedirect( $text );
1052 $conditions = array( 'page_id' => $this->getId() );
1053 if( !is_null( $lastRevision ) ) {
1054 # An extra check against threads stepping on each other
1055 $conditions['page_latest'] = $lastRevision;
1058 $dbw->update( 'page',
1060 'page_latest' => $revision->getId(),
1061 'page_touched' => $dbw->timestamp(),
1062 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1063 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1064 'page_len' => strlen( $text ),
1069 $result = $dbw->affectedRows() != 0;
1072 // FIXME: Should the result from updateRedirectOn() be returned instead?
1073 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1076 wfProfileOut( __METHOD__
);
1081 * Add row to the redirect table if this is a redirect, remove otherwise.
1083 * @param Database $dbw
1084 * @param $redirectTitle a title object pointing to the redirect target,
1085 * or NULL if this is not a redirect
1086 * @param bool $lastRevIsRedirect If given, will optimize adding and
1087 * removing rows in redirect table.
1088 * @return bool true on success, false on failure
1091 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1093 // Always update redirects (target link might have changed)
1094 // Update/Insert if we don't know if the last revision was a redirect or not
1095 // Delete if changing from redirect to non-redirect
1096 $isRedirect = !is_null($redirectTitle);
1097 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1099 wfProfileIn( __METHOD__
);
1103 // This title is a redirect, Add/Update row in the redirect table
1104 $set = array( /* SET */
1105 'rd_namespace' => $redirectTitle->getNamespace(),
1106 'rd_title' => $redirectTitle->getDBkey(),
1107 'rd_from' => $this->getId(),
1110 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1112 // This is not a redirect, remove row from redirect table
1113 $where = array( 'rd_from' => $this->getId() );
1114 $dbw->delete( 'redirect', $where, __METHOD__
);
1117 wfProfileOut( __METHOD__
);
1118 return ( $dbw->affectedRows() != 0 );
1125 * If the given revision is newer than the currently set page_latest,
1126 * update the page record. Otherwise, do nothing.
1128 * @param Database $dbw
1129 * @param Revision $revision
1131 function updateIfNewerOn( &$dbw, $revision ) {
1132 wfProfileIn( __METHOD__
);
1134 $row = $dbw->selectRow(
1135 array( 'revision', 'page' ),
1136 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1138 'page_id' => $this->getId(),
1139 'page_latest=rev_id' ),
1142 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1143 wfProfileOut( __METHOD__
);
1146 $prev = $row->rev_id
;
1147 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1149 # No or missing previous revision; mark the page as new
1151 $lastRevIsRedirect = null;
1154 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1155 wfProfileOut( __METHOD__
);
1160 * @return string Complete article text, or null if error
1162 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1163 wfProfileIn( __METHOD__
);
1165 if( $section == '' ) {
1166 // Whole-page edit; let the text through unmolested.
1168 if( is_null( $edittime ) ) {
1169 $rev = Revision
::newFromTitle( $this->mTitle
);
1171 $dbw = wfGetDB( DB_MASTER
);
1172 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1174 if( is_null( $rev ) ) {
1175 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1176 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1179 $oldtext = $rev->getText();
1181 if( $section == 'new' ) {
1182 # Inserting a new section
1183 $subject = $summary ?
"== {$summary} ==\n\n" : '';
1184 $text = strlen( trim( $oldtext ) ) > 0
1185 ?
"{$oldtext}\n\n{$subject}{$text}"
1186 : "{$subject}{$text}";
1188 # Replacing an existing section; roll out the big guns
1190 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1195 wfProfileOut( __METHOD__
);
1200 * @deprecated use Article::doEdit()
1202 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1203 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1204 ( $isminor ? EDIT_MINOR
: 0 ) |
1205 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1207 # If this is a comment, add the summary as headline
1208 if ( $comment && $summary != "" ) {
1209 $text = "== {$summary} ==\n\n".$text;
1212 $this->doEdit( $text, $summary, $flags );
1214 $dbw = wfGetDB( DB_MASTER
);
1216 if (!$this->mTitle
->userIsWatching()) {
1222 if ( $this->mTitle
->userIsWatching() ) {
1228 $this->doRedirect( $this->isRedirect( $text ) );
1232 * @deprecated use Article::doEdit()
1234 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1235 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1236 ( $minor ? EDIT_MINOR
: 0 ) |
1237 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1239 $good = $this->doEdit( $text, $summary, $flags );
1241 $dbw = wfGetDB( DB_MASTER
);
1243 if (!$this->mTitle
->userIsWatching()) {
1249 if ( $this->mTitle
->userIsWatching() ) {
1256 $extraq = ''; // Give extensions a chance to modify URL query on update
1257 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1259 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1267 * Change an existing article or create a new article. Updates RC and all necessary caches,
1268 * optionally via the deferred update array.
1270 * $wgUser must be set before calling this function.
1272 * @param string $text New text
1273 * @param string $summary Edit summary
1274 * @param integer $flags bitfield:
1276 * Article is known or assumed to be non-existent, create a new one
1278 * Article is known or assumed to be pre-existing, update it
1280 * Mark this edit minor, if the user is allowed to do so
1282 * Do not log the change in recentchanges
1284 * Mark the edit a "bot" edit regardless of user rights
1285 * EDIT_DEFER_UPDATES
1286 * Defer some of the updates until the end of index.php
1288 * Fill in blank summaries with generated text where possible
1290 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1291 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1292 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1293 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1294 * to MediaWiki's performance-optimised locking strategy.
1296 * @return bool success
1298 function doEdit( $text, $summary, $flags = 0 ) {
1299 global $wgUser, $wgDBtransactions;
1301 wfProfileIn( __METHOD__
);
1304 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1305 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1307 $flags |
= EDIT_UPDATE
;
1313 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1314 &$summary, $flags & EDIT_MINOR
,
1315 null, null, &$flags ) ) )
1317 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1318 wfProfileOut( __METHOD__
);
1322 # Silently ignore EDIT_MINOR if not allowed
1323 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1324 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1326 $oldtext = $this->getContent();
1327 $oldsize = strlen( $oldtext );
1329 # Provide autosummaries if one is not provided.
1330 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1331 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1333 $text = $this->preSaveTransform( $text );
1334 $newsize = strlen( $text );
1336 $dbw = wfGetDB( DB_MASTER
);
1337 $now = wfTimestampNow();
1339 if ( $flags & EDIT_UPDATE
) {
1340 # Update article, but only if changed.
1342 # Make sure the revision is either completely inserted or not inserted at all
1343 if( !$wgDBtransactions ) {
1344 $userAbort = ignore_user_abort( true );
1350 if ( 0 != strcmp( $text, $oldtext ) ) {
1351 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1352 - (int)$this->isCountable( $oldtext );
1353 $this->mTotalAdjustment
= 0;
1355 $lastRevision = $dbw->selectField(
1356 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1358 if ( !$lastRevision ) {
1359 # Article gone missing
1360 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1361 wfProfileOut( __METHOD__
);
1365 $revision = new Revision( array(
1366 'page' => $this->getId(),
1367 'comment' => $summary,
1368 'minor_edit' => $isminor,
1373 $revisionId = $revision->insertOn( $dbw );
1376 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1379 /* Belated edit conflict! Run away!! */
1383 # Update recentchanges
1384 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1385 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1386 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1389 # Mark as patrolled if the user can do so
1390 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1391 RecentChange
::markPatrolled( $rcid );
1392 PatrolLog
::record( $rcid, true );
1395 $wgUser->incEditCount();
1399 // Keep the same revision ID, but do some updates on it
1400 $revisionId = $this->getRevIdFetched();
1401 // Update page_touched, this is usually implicit in the page update
1402 // Other cache updates are done in onArticleEdit()
1403 $this->mTitle
->invalidateCache();
1406 if( !$wgDBtransactions ) {
1407 ignore_user_abort( $userAbort );
1411 # Invalidate cache of this article and all pages using this article
1412 # as a template. Partly deferred.
1413 Article
::onArticleEdit( $this->mTitle
);
1415 # Update links tables, site stats, etc.
1416 $changed = ( strcmp( $oldtext, $text ) != 0 );
1417 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1420 # Create new article
1422 # Set statistics members
1423 # We work out if it's countable after PST to avoid counter drift
1424 # when articles are created with {{subst:}}
1425 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1426 $this->mTotalAdjustment
= 1;
1430 # Add the page record; stake our claim on this title!
1431 # This will fail with a database query exception if the article already exists
1432 $newid = $this->insertOn( $dbw );
1434 # Save the revision text...
1435 $revision = new Revision( array(
1437 'comment' => $summary,
1438 'minor_edit' => $isminor,
1441 $revisionId = $revision->insertOn( $dbw );
1443 $this->mTitle
->resetArticleID( $newid );
1445 # Update the page record with revision data
1446 $this->updateRevisionOn( $dbw, $revision, 0 );
1448 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1449 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1450 '', strlen( $text ), $revisionId );
1451 # Mark as patrolled if the user can
1452 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1453 RecentChange
::markPatrolled( $rcid );
1454 PatrolLog
::record( $rcid, true );
1457 $wgUser->incEditCount();
1460 # Update links, etc.
1461 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1464 Article
::onArticleCreate( $this->mTitle
);
1466 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1467 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1470 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1474 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1475 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1477 wfProfileOut( __METHOD__
);
1482 * @deprecated wrapper for doRedirect
1484 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1485 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1489 * Output a redirect back to the article.
1490 * This is typically used after an edit.
1492 * @param boolean $noRedir Add redirect=no
1493 * @param string $sectionAnchor section to redirect to, including "#"
1495 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1498 $query = 'redirect=no';
1500 $query .= "&$query";
1504 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1508 * Mark this particular edit as patrolled
1510 function markpatrolled() {
1511 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1512 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1514 # Check RC patrol config. option
1515 if( !$wgUseRCPatrol ) {
1516 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1521 if( !$wgUser->isAllowed( 'patrol' ) ) {
1522 $wgOut->permissionRequired( 'patrol' );
1526 # If we haven't been given an rc_id value, we can't do anything
1527 $rcid = $wgRequest->getVal( 'rcid' );
1529 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1533 # Handle the 'MarkPatrolled' hook
1534 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1538 $return = SpecialPage
::getTitleFor( 'Recentchanges' );
1539 # If it's left up to us, check that the user is allowed to patrol this edit
1540 # If the user has the "autopatrol" right, then we'll assume there are no
1541 # other conditions stopping them doing so
1542 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1543 $rc = RecentChange
::newFromId( $rcid );
1544 # Graceful error handling, as we've done before here...
1545 # (If the recent change doesn't exist, then it doesn't matter whether
1546 # the user is allowed to patrol it or not; nothing is going to happen
1547 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1548 # The user made this edit, and can't patrol it
1549 # Tell them so, and then back off
1550 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1551 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1552 $wgOut->returnToMain( false, $return );
1557 # Mark the edit as patrolled
1558 RecentChange
::markPatrolled( $rcid );
1559 PatrolLog
::record( $rcid );
1560 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1563 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1564 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1565 $wgOut->returnToMain( false, $return );
1569 * User-interface handler for the "watch" action
1574 global $wgUser, $wgOut;
1576 if ( $wgUser->isAnon() ) {
1577 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1580 if ( wfReadOnly() ) {
1581 $wgOut->readOnlyPage();
1585 if( $this->doWatch() ) {
1586 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1587 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1589 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1590 $text = wfMsg( 'addedwatchtext', $link );
1591 $wgOut->addWikiText( $text );
1594 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1598 * Add this page to $wgUser's watchlist
1599 * @return bool true on successful watch operation
1601 function doWatch() {
1603 if( $wgUser->isAnon() ) {
1607 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1608 $wgUser->addWatch( $this->mTitle
);
1610 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1617 * User interface handler for the "unwatch" action.
1619 function unwatch() {
1621 global $wgUser, $wgOut;
1623 if ( $wgUser->isAnon() ) {
1624 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1627 if ( wfReadOnly() ) {
1628 $wgOut->readOnlyPage();
1632 if( $this->doUnwatch() ) {
1633 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1634 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1636 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1637 $text = wfMsg( 'removedwatchtext', $link );
1638 $wgOut->addWikiText( $text );
1641 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1645 * Stop watching a page
1646 * @return bool true on successful unwatch
1648 function doUnwatch() {
1650 if( $wgUser->isAnon() ) {
1654 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1655 $wgUser->removeWatch( $this->mTitle
);
1657 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1664 * action=protect handler
1666 function protect() {
1667 $form = new ProtectionForm( $this );
1672 * action=unprotect handler (alias)
1674 function unprotect() {
1679 * Update the article's restriction field, and leave a log entry.
1681 * @param array $limit set of restriction keys
1682 * @param string $reason
1683 * @return bool true on success
1685 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1686 global $wgUser, $wgRestrictionTypes, $wgContLang;
1688 $id = $this->mTitle
->getArticleID();
1689 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1697 // Take this opportunity to purge out expired restrictions
1698 Title
::purgeExpiredRestrictions();
1700 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1701 # we expect a single selection, but the schema allows otherwise.
1703 foreach( $wgRestrictionTypes as $action )
1704 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1706 $current = Article
::flattenRestrictions( $current );
1707 $updated = Article
::flattenRestrictions( $limit );
1709 $changed = ( $current != $updated );
1710 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1711 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1712 $protect = ( $updated != '' );
1714 # If nothing's changed, do nothing
1716 global $wgGroupPermissions;
1717 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1719 $dbw = wfGetDB( DB_MASTER
);
1721 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1723 $expiry_description = '';
1724 if ( $encodedExpiry != 'infinity' ) {
1725 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1728 # Prepare a null revision to be added to the history
1729 $modified = $current != '' && $protect;
1731 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1733 $comment_type = 'unprotectedarticle';
1735 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1737 foreach( $limit as $action => $restrictions ) {
1738 # Check if the group level required to edit also can protect pages
1739 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1740 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1743 $cascade_description = '';
1745 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1749 $comment .= ": $reason";
1751 $comment .= " [$updated]";
1752 if ( $expiry_description && $protect )
1753 $comment .= "$expiry_description";
1755 $comment .= "$cascade_description";
1757 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1758 $nullRevId = $nullRevision->insertOn( $dbw );
1760 # Update restrictions table
1761 foreach( $limit as $action => $restrictions ) {
1762 if ($restrictions != '' ) {
1763 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1764 array( 'pr_page' => $id, 'pr_type' => $action
1765 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1766 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1768 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1769 'pr_type' => $action ), __METHOD__
);
1773 # Update page record
1774 $dbw->update( 'page',
1776 'page_touched' => $dbw->timestamp(),
1777 'page_restrictions' => '',
1778 'page_latest' => $nullRevId
1779 ), array( /* WHERE */
1781 ), 'Article::protect'
1783 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1785 # Update the protection log
1786 $log = new LogPage( 'protect' );
1789 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1791 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1795 } # End "changed" check
1801 * Take an array of page restrictions and flatten it to a string
1802 * suitable for insertion into the page_restrictions field.
1803 * @param array $limit
1807 function flattenRestrictions( $limit ) {
1808 if( !is_array( $limit ) ) {
1809 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1813 foreach( $limit as $action => $restrictions ) {
1814 if( $restrictions != '' ) {
1815 $bits[] = "$action=$restrictions";
1818 return implode( ':', $bits );
1822 * UI entry point for page deletion
1825 global $wgUser, $wgOut, $wgRequest;
1826 $confirm = $wgRequest->wasPosted() &&
1827 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1828 $reason = $wgRequest->getText( 'wpReason' );
1830 # This code desperately needs to be totally rewritten
1833 if( $wgUser->isAllowed( 'delete' ) ) {
1834 if( $wgUser->isBlocked( !$confirm ) ) {
1835 $wgOut->blockedPage();
1839 $wgOut->permissionRequired( 'delete' );
1843 if( wfReadOnly() ) {
1844 $wgOut->readOnlyPage();
1848 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1850 # Better double-check that it hasn't been deleted yet!
1851 $dbw = wfGetDB( DB_MASTER
);
1852 $conds = $this->mTitle
->pageCond();
1853 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1854 if ( $latest === false ) {
1855 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1860 $this->doDelete( $reason );
1861 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1863 } elseif( $this->mTitle
->userIsWatching() ) {
1869 # determine whether this page has earlier revisions
1870 # and insert a warning if it does
1872 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1874 if( count( $authors ) > 1 && !$confirm ) {
1875 $skin=$wgUser->getSkin();
1876 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1879 # If a single user is responsible for all revisions, find out who they are
1880 if ( count( $authors ) == $maxRevisions ) {
1881 // Query bailed out, too many revisions to find out if they're all the same
1882 $authorOfAll = false;
1884 $authorOfAll = reset( $authors );
1885 foreach ( $authors as $author ) {
1886 if ( $authorOfAll != $author ) {
1887 $authorOfAll = false;
1892 # Fetch article text
1893 $rev = Revision
::newFromTitle( $this->mTitle
);
1895 if( !is_null( $rev ) ) {
1896 # if this is a mini-text, we can paste part of it into the deletion reason
1897 $text = $rev->getText();
1899 #if this is empty, an earlier revision may contain "useful" text
1902 $prev = $rev->getPrevious();
1904 $text = $prev->getText();
1909 $length = strlen( $text );
1911 # this should not happen, since it is not possible to store an empty, new
1912 # page. Let's insert a standard text in case it does, though
1913 if( $length == 0 && $reason === '' ) {
1914 $reason = wfMsgForContent( 'exblank' );
1917 if( $reason === '' ) {
1918 # comment field=255, let's grep the first 150 to have some user
1921 $text = $wgContLang->truncate( $text, 150, '...' );
1923 # let's strip out newlines
1924 $text = preg_replace( "/[\n\r]/", '', $text );
1927 if( $authorOfAll === false ) {
1928 $reason = wfMsgForContent( 'excontent', $text );
1930 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1933 $reason = wfMsgForContent( 'exbeforeblank', $text );
1938 return $this->confirmDelete( '', $reason );
1942 * Get the last N authors
1943 * @param int $num Number of revisions to get
1944 * @param string $revLatest The latest rev_id, selected from the master (optional)
1945 * @return array Array of authors, duplicates not removed
1947 function getLastNAuthors( $num, $revLatest = 0 ) {
1948 wfProfileIn( __METHOD__
);
1950 // First try the slave
1951 // If that doesn't have the latest revision, try the master
1953 $db = wfGetDB( DB_SLAVE
);
1955 $res = $db->select( array( 'page', 'revision' ),
1956 array( 'rev_id', 'rev_user_text' ),
1958 'page_namespace' => $this->mTitle
->getNamespace(),
1959 'page_title' => $this->mTitle
->getDBkey(),
1960 'rev_page = page_id'
1961 ), __METHOD__
, $this->getSelectOptions( array(
1962 'ORDER BY' => 'rev_timestamp DESC',
1967 wfProfileOut( __METHOD__
);
1970 $row = $db->fetchObject( $res );
1971 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1972 $db = wfGetDB( DB_MASTER
);
1977 } while ( $continue );
1979 $authors = array( $row->rev_user_text
);
1980 while ( $row = $db->fetchObject( $res ) ) {
1981 $authors[] = $row->rev_user_text
;
1983 wfProfileOut( __METHOD__
);
1988 * Output deletion confirmation dialog
1990 function confirmDelete( $par, $reason ) {
1991 global $wgOut, $wgUser;
1993 wfDebug( "Article::confirmDelete\n" );
1995 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1996 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1997 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1998 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
2000 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
2002 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
2003 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
2004 $token = htmlspecialchars( $wgUser->editToken() );
2005 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
2008 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
2012 <label for='wpReason'>{$delcom}:</label>
2015 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
2025 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2029 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2032 $wgOut->returnToMain( false );
2034 $this->showLogExtract( $wgOut );
2039 * Show relevant lines from the deletion log
2041 function showLogExtract( $out ) {
2042 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2043 $logViewer = new LogViewer(
2046 array( 'page' => $this->mTitle
->getPrefixedText(),
2047 'type' => 'delete' ) ) ) );
2048 $logViewer->showList( $out );
2053 * Perform a deletion and output success or failure messages
2055 function doDelete( $reason ) {
2056 global $wgOut, $wgUser;
2057 wfDebug( __METHOD__
."\n" );
2059 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2060 if ( $this->doDeleteArticle( $reason ) ) {
2061 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2063 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2064 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2066 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2067 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2069 $wgOut->addWikiText( $text );
2070 $wgOut->returnToMain( false );
2071 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2073 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2079 * Back-end article deletion
2080 * Deletes the article with database consistency, writes logs, purges caches
2083 function doDeleteArticle( $reason ) {
2084 global $wgUseSquid, $wgDeferredUpdateList;
2085 global $wgUseTrackbacks;
2087 wfDebug( __METHOD__
."\n" );
2089 $dbw = wfGetDB( DB_MASTER
);
2090 $ns = $this->mTitle
->getNamespace();
2091 $t = $this->mTitle
->getDBkey();
2092 $id = $this->mTitle
->getArticleID();
2094 if ( $t == '' ||
$id == 0 ) {
2098 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2099 array_push( $wgDeferredUpdateList, $u );
2101 // For now, shunt the revision data into the archive table.
2102 // Text is *not* removed from the text table; bulk storage
2103 // is left intact to avoid breaking block-compression or
2104 // immutable storage schemes.
2106 // For backwards compatibility, note that some older archive
2107 // table entries will have ar_text and ar_flags fields still.
2109 // In the future, we may keep revisions and mark them with
2110 // the rev_deleted field, which is reserved for this purpose.
2111 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2113 'ar_namespace' => 'page_namespace',
2114 'ar_title' => 'page_title',
2115 'ar_comment' => 'rev_comment',
2116 'ar_user' => 'rev_user',
2117 'ar_user_text' => 'rev_user_text',
2118 'ar_timestamp' => 'rev_timestamp',
2119 'ar_minor_edit' => 'rev_minor_edit',
2120 'ar_rev_id' => 'rev_id',
2121 'ar_text_id' => 'rev_text_id',
2122 'ar_text' => '\'\'', // Be explicit to appease
2123 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2124 'ar_len' => 'rev_len',
2125 'ar_page_id' => 'page_id',
2128 'page_id = rev_page'
2132 # Delete restrictions for it
2133 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2135 # Now that it's safely backed up, delete it
2136 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2138 # If using cascading deletes, we can skip some explicit deletes
2139 if ( !$dbw->cascadingDeletes() ) {
2141 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2143 if ($wgUseTrackbacks)
2144 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2146 # Delete outgoing links
2147 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2148 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2149 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2150 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2151 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2152 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2153 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2156 # If using cleanup triggers, we can skip some manual deletes
2157 if ( !$dbw->cleanupTriggers() ) {
2159 # Clean up recentchanges entries...
2160 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2164 Article
::onArticleDelete( $this->mTitle
);
2167 $log = new LogPage( 'delete' );
2168 $log->addEntry( 'delete', $this->mTitle
, $reason );
2170 # Clear the cached article id so the interface doesn't act like we exist
2171 $this->mTitle
->resetArticleID( 0 );
2172 $this->mTitle
->mArticleID
= 0;
2177 * Roll back the most recent consecutive set of edits to a page
2178 * from the same user; fails if there are no eligible edits to
2179 * roll back to, e.g. user is the sole contributor
2181 * @param string $fromP - Name of the user whose edits to rollback.
2182 * @param string $summary - Custom summary. Set to default summary if empty.
2183 * @param string $token - Rollback token.
2184 * @param bool $bot - If true, mark all reverted edits as bot.
2186 * @param array $resultDetails contains result-specific dict of additional values
2187 * ALREADY_ROLLED : 'current' (rev)
2188 * SUCCESS : 'summary' (str), 'current' (rev), 'target' (rev)
2190 * @return self::SUCCESS on succes, self::* on failure
2192 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2193 global $wgUser, $wgUseRCPatrol;
2194 $resultDetails = null;
2196 if( $wgUser->isAllowed( 'rollback' ) ) {
2197 if( $wgUser->isBlocked() ) {
2198 return self
::BLOCKED
;
2201 return self
::PERM_DENIED
;
2204 if ( wfReadOnly() ) {
2205 return self
::READONLY
;
2207 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2208 return self
::BAD_TOKEN
;
2210 $dbw = wfGetDB( DB_MASTER
);
2212 # Get the last editor
2213 $current = Revision
::newFromTitle( $this->mTitle
);
2214 if( is_null( $current ) ) {
2215 # Something wrong... no page?
2216 return self
::BAD_TITLE
;
2219 $from = str_replace( '_', ' ', $fromP );
2220 if( $from != $current->getUserText() ) {
2221 $resultDetails = array( 'current' => $current );
2222 return self
::ALREADY_ROLLED
;
2225 # Get the last edit not by this guy
2226 $user = intval( $current->getUser() );
2227 $user_text = $dbw->addQuotes( $current->getUserText() );
2228 $s = $dbw->selectRow( 'revision',
2229 array( 'rev_id', 'rev_timestamp' ),
2231 'rev_page' => $current->getPage(),
2232 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2235 'USE INDEX' => 'page_timestamp',
2236 'ORDER BY' => 'rev_timestamp DESC' )
2238 if( $s === false ) {
2240 return self
::ONLY_AUTHOR
;
2245 # Mark all reverted edits as bot
2248 if ( $wgUseRCPatrol ) {
2249 # Mark all reverted edits as patrolled
2250 $set['rc_patrolled'] = 1;
2254 $dbw->update( 'recentchanges', $set,
2256 'rc_cur_id' => $current->getPage(),
2257 'rc_user_text' => $current->getUserText(),
2258 "rc_timestamp > '{$s->rev_timestamp}'",
2263 # Get the edit summary
2264 $target = Revision
::newFromId( $s->rev_id
);
2265 if( empty( $summary ) )
2266 $summary = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2269 $flags = EDIT_UPDATE | EDIT_MINOR
;
2271 $flags |
= EDIT_FORCE_BOT
;
2272 $this->doEdit( $target->getText(), $summary, $flags );
2274 $resultDetails = array(
2275 'summary' => $summary,
2276 'current' => $current,
2277 'target' => $target,
2279 return self
::SUCCESS
;
2283 * User interface for rollback operations
2285 function rollback() {
2286 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2289 $result = $this->doRollback(
2290 $wgRequest->getVal( 'from' ),
2291 $wgRequest->getText( 'summary' ),
2292 $wgRequest->getVal( 'token' ),
2293 $wgRequest->getBool( 'bot' ),
2299 $wgOut->blockedPage();
2301 case self
::PERM_DENIED
:
2302 $wgOut->permissionRequired( 'rollback' );
2304 case self
::READONLY
:
2305 $wgOut->readOnlyPage( $this->getContent() );
2307 case self
::BAD_TOKEN
:
2308 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2309 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2311 case self
::BAD_TITLE
:
2312 $wgOut->addHtml( wfMsg( 'notanarticle' ) );
2314 case self
::ALREADY_ROLLED
:
2315 $current = $details['current'];
2316 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2317 $wgOut->addWikiText(
2318 wfMsg( 'alreadyrolled',
2319 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2320 htmlspecialchars( $wgRequest->getVal( 'from' ) ),
2321 htmlspecialchars( $current->getUserText() )
2324 if( $current->getComment() != '' ) {
2325 $wgOut->addHtml( wfMsg( 'editcomment',
2326 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2329 case self
::ONLY_AUTHOR
:
2330 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2331 $wgOut->addHtml( wfMsg( 'cantrollback' ) );
2334 $current = $details['current'];
2335 $target = $details['target'];
2336 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2337 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2338 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2339 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2340 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2341 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2342 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2343 $wgOut->returnToMain( false, $this->mTitle
);
2346 throw new MWException( __METHOD__
. ": Unknown return value `{$retval}`" );
2353 * Do standard deferred updates after page view
2356 function viewUpdates() {
2357 global $wgDeferredUpdateList;
2359 if ( 0 != $this->getID() ) {
2360 global $wgDisableCounters;
2361 if( !$wgDisableCounters ) {
2362 Article
::incViewCount( $this->getID() );
2363 $u = new SiteStatsUpdate( 1, 0, 0 );
2364 array_push( $wgDeferredUpdateList, $u );
2368 # Update newtalk / watchlist notification status
2370 $wgUser->clearNotification( $this->mTitle
);
2374 * Do standard deferred updates after page edit.
2375 * Update links tables, site stats, search index and message cache.
2376 * Every 1000th edit, prune the recent changes table.
2379 * @param $text New text of the article
2380 * @param $summary Edit summary
2381 * @param $minoredit Minor edit
2382 * @param $timestamp_of_pagechange Timestamp associated with the page change
2383 * @param $newid rev_id value of the new revision
2384 * @param $changed Whether or not the content actually changed
2386 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2387 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2389 wfProfileIn( __METHOD__
);
2392 $options = new ParserOptions
;
2393 $options->setTidy(true);
2394 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2396 # Save it to the parser cache
2397 $parserCache =& ParserCache
::singleton();
2398 $parserCache->save( $poutput, $this, $wgUser );
2400 # Update the links tables
2401 $u = new LinksUpdate( $this->mTitle
, $poutput );
2404 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2406 if ( 0 == mt_rand( 0, 99 ) ) {
2407 # Periodically flush old entries from the recentchanges table.
2410 $dbw = wfGetDB( DB_MASTER
);
2411 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2412 $recentchanges = $dbw->tableName( 'recentchanges' );
2413 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2414 $dbw->query( $sql );
2418 $id = $this->getID();
2419 $title = $this->mTitle
->getPrefixedDBkey();
2420 $shortTitle = $this->mTitle
->getDBkey();
2423 wfProfileOut( __METHOD__
);
2427 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2428 array_push( $wgDeferredUpdateList, $u );
2429 $u = new SearchUpdate( $id, $title, $text );
2430 array_push( $wgDeferredUpdateList, $u );
2432 # If this is another user's talk page, update newtalk
2433 # Don't do this if $changed = false otherwise some idiot can null-edit a
2434 # load of user talk pages and piss people off, nor if it's a minor edit
2435 # by a properly-flagged bot.
2436 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2437 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2438 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2439 $other = User
::newFromName( $shortTitle );
2440 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2441 // An anonymous user
2442 $other = new User();
2443 $other->setName( $shortTitle );
2446 $other->setNewtalk( true );
2451 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2452 $wgMessageCache->replace( $shortTitle, $text );
2455 wfProfileOut( __METHOD__
);
2459 * Perform article updates on a special page creation.
2461 * @param Revision $rev
2463 * @todo This is a shitty interface function. Kill it and replace the
2464 * other shitty functions like editUpdates and such so it's not needed
2467 function createUpdates( $rev ) {
2468 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2469 $this->mTotalAdjustment
= 1;
2470 $this->editUpdates( $rev->getText(), $rev->getComment(),
2471 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2475 * Generate the navigation links when browsing through an article revisions
2476 * It shows the information as:
2477 * Revision as of \<date\>; view current revision
2478 * \<- Previous version | Next Version -\>
2481 * @param string $oldid Revision ID of this article revision
2483 function setOldSubtitle( $oldid=0 ) {
2484 global $wgLang, $wgOut, $wgUser;
2486 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2490 $revision = Revision
::newFromId( $oldid );
2492 $current = ( $oldid == $this->mLatest
);
2493 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2494 $sk = $wgUser->getSkin();
2496 ?
wfMsg( 'currentrevisionlink' )
2497 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2500 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2501 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2503 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2504 : wfMsg( 'previousrevision' );
2506 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2508 $nextlink = $current
2509 ?
wfMsg( 'nextrevision' )
2510 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2511 $nextdiff = $current
2513 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2515 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2516 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2518 $m = wfMsg( 'revision-info-current' );
2519 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2520 ?
'revision-info-current'
2523 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2524 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2525 $wgOut->setSubtitle( $r );
2529 * This function is called right before saving the wikitext,
2530 * so we can do things like signatures and links-in-context.
2532 * @param string $text
2534 function preSaveTransform( $text ) {
2535 global $wgParser, $wgUser;
2536 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2539 /* Caching functions */
2542 * checkLastModified returns true if it has taken care of all
2543 * output to the client that is necessary for this request.
2544 * (that is, it has sent a cached version of the page)
2546 function tryFileCache() {
2547 static $called = false;
2549 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2553 if($this->isFileCacheable()) {
2554 $touched = $this->mTouched
;
2555 $cache = new HTMLFileCache( $this->mTitle
);
2556 if($cache->isFileCacheGood( $touched )) {
2557 wfDebug( "Article::tryFileCache(): about to load file\n" );
2558 $cache->loadFromFileCache();
2561 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2562 ob_start( array(&$cache, 'saveToFileCache' ) );
2565 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2570 * Check if the page can be cached
2573 function isFileCacheable() {
2574 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2575 $action = $wgRequest->getVal( 'action' );
2576 $oldid = $wgRequest->getVal( 'oldid' );
2577 $diff = $wgRequest->getVal( 'diff' );
2578 $redirect = $wgRequest->getVal( 'redirect' );
2579 $printable = $wgRequest->getVal( 'printable' );
2580 $page = $wgRequest->getVal( 'page' );
2582 //check for non-standard user language; this covers uselang,
2583 //and extensions for auto-detecting user language.
2584 $ulang = $wgLang->getCode();
2585 $clang = $wgContLang->getCode();
2587 $cacheable = $wgUseFileCache
2588 && (!$wgShowIPinHeader)
2589 && ($this->getID() != 0)
2590 && ($wgUser->isAnon())
2591 && (!$wgUser->getNewtalk())
2592 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2593 && (empty( $action ) ||
$action == 'view')
2596 && (!isset($redirect))
2597 && (!isset($printable))
2599 && (!$this->mRedirectedFrom
)
2600 && ($ulang === $clang);
2603 //extension may have reason to disable file caching on some pages.
2604 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2611 * Loads page_touched and returns a value indicating if it should be used
2614 function checkTouched() {
2615 if( !$this->mDataLoaded
) {
2616 $this->loadPageData();
2618 return !$this->mIsRedirect
;
2622 * Get the page_touched field
2624 function getTouched() {
2625 # Ensure that page data has been loaded
2626 if( !$this->mDataLoaded
) {
2627 $this->loadPageData();
2629 return $this->mTouched
;
2633 * Get the page_latest field
2635 function getLatest() {
2636 if ( !$this->mDataLoaded
) {
2637 $this->loadPageData();
2639 return $this->mLatest
;
2643 * Edit an article without doing all that other stuff
2644 * The article must already exist; link tables etc
2645 * are not updated, caches are not flushed.
2647 * @param string $text text submitted
2648 * @param string $comment comment submitted
2649 * @param bool $minor whereas it's a minor modification
2651 function quickEdit( $text, $comment = '', $minor = 0 ) {
2652 wfProfileIn( __METHOD__
);
2654 $dbw = wfGetDB( DB_MASTER
);
2656 $revision = new Revision( array(
2657 'page' => $this->getId(),
2659 'comment' => $comment,
2660 'minor_edit' => $minor ?
1 : 0,
2662 $revision->insertOn( $dbw );
2663 $this->updateRevisionOn( $dbw, $revision );
2666 wfProfileOut( __METHOD__
);
2670 * Used to increment the view counter
2673 * @param integer $id article id
2675 function incViewCount( $id ) {
2676 $id = intval( $id );
2677 global $wgHitcounterUpdateFreq, $wgDBtype;
2679 $dbw = wfGetDB( DB_MASTER
);
2680 $pageTable = $dbw->tableName( 'page' );
2681 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2682 $acchitsTable = $dbw->tableName( 'acchits' );
2684 if( $wgHitcounterUpdateFreq <= 1 ) {
2685 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2689 # Not important enough to warrant an error page in case of failure
2690 $oldignore = $dbw->ignoreErrors( true );
2692 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2694 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2695 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2696 # Most of the time (or on SQL errors), skip row count check
2697 $dbw->ignoreErrors( $oldignore );
2701 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2702 $row = $dbw->fetchObject( $res );
2703 $rown = intval( $row->n
);
2704 if( $rown >= $wgHitcounterUpdateFreq ){
2705 wfProfileIn( 'Article::incViewCount-collect' );
2706 $old_user_abort = ignore_user_abort( true );
2708 if ($wgDBtype == 'mysql')
2709 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2710 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2711 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2712 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2714 $dbw->query("DELETE FROM $hitcounterTable");
2715 if ($wgDBtype == 'mysql') {
2716 $dbw->query('UNLOCK TABLES');
2717 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2718 'WHERE page_id = hc_id');
2721 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2722 "FROM $acchitsTable WHERE page_id = hc_id");
2724 $dbw->query("DROP TABLE $acchitsTable");
2726 ignore_user_abort( $old_user_abort );
2727 wfProfileOut( 'Article::incViewCount-collect' );
2729 $dbw->ignoreErrors( $oldignore );
2733 * The onArticle*() functions are supposed to be a kind of hooks
2734 * which should be called whenever any of the specified actions
2737 * This is a good place to put code to clear caches, for instance.
2739 * This is called on page move and undelete, as well as edit
2741 * @param $title_obj a title object
2744 static function onArticleCreate($title) {
2745 # The talk page isn't in the regular link tables, so we need to update manually:
2746 if ( $title->isTalkPage() ) {
2747 $other = $title->getSubjectPage();
2749 $other = $title->getTalkPage();
2751 $other->invalidateCache();
2752 $other->purgeSquid();
2754 $title->touchLinks();
2755 $title->purgeSquid();
2758 static function onArticleDelete( $title ) {
2759 global $wgUseFileCache, $wgMessageCache;
2761 $title->touchLinks();
2762 $title->purgeSquid();
2765 if ( $wgUseFileCache ) {
2766 $cm = new HTMLFileCache( $title );
2767 @unlink
( $cm->fileCacheName() );
2770 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2771 $wgMessageCache->replace( $title->getDBkey(), false );
2776 * Purge caches on page update etc
2778 static function onArticleEdit( $title ) {
2779 global $wgDeferredUpdateList, $wgUseFileCache;
2781 // Invalidate caches of articles which include this page
2782 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2783 $wgDeferredUpdateList[] = $update;
2785 # Purge squid for this page only
2786 $title->purgeSquid();
2789 if ( $wgUseFileCache ) {
2790 $cm = new HTMLFileCache( $title );
2791 @unlink
( $cm->fileCacheName() );
2798 * Info about this page
2799 * Called for ?action=info when $wgAllowPageInfo is on.
2804 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2806 if ( !$wgAllowPageInfo ) {
2807 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2811 $page = $this->mTitle
->getSubjectPage();
2813 $wgOut->setPagetitle( $page->getPrefixedText() );
2814 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
2815 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
2817 if( !$this->mTitle
->exists() ) {
2818 $wgOut->addHtml( '<div class="noarticletext">' );
2819 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2820 // This doesn't quite make sense; the user is asking for
2821 // information about the _page_, not the message... -- RC
2822 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
2824 $msg = $wgUser->isLoggedIn()
2826 : 'noarticletextanon';
2827 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
2829 $wgOut->addHtml( '</div>' );
2831 $dbr = wfGetDB( DB_SLAVE
);
2833 'wl_title' => $page->getDBkey(),
2834 'wl_namespace' => $page->getNamespace() );
2835 $numwatchers = $dbr->selectField(
2840 $this->getSelectOptions() );
2842 $pageInfo = $this->pageCountInfo( $page );
2843 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2845 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2846 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2848 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2850 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2852 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2854 $wgOut->addHTML( '</ul>' );
2860 * Return the total number of edits and number of unique editors
2861 * on a given page. If page does not exist, returns false.
2863 * @param Title $title
2867 function pageCountInfo( $title ) {
2868 $id = $title->getArticleId();
2873 $dbr = wfGetDB( DB_SLAVE
);
2875 $rev_clause = array( 'rev_page' => $id );
2877 $edits = $dbr->selectField(
2882 $this->getSelectOptions() );
2884 $authors = $dbr->selectField(
2886 'COUNT(DISTINCT rev_user_text)',
2889 $this->getSelectOptions() );
2891 return array( 'edits' => $edits, 'authors' => $authors );
2895 * Return a list of templates used by this article.
2896 * Uses the templatelinks table
2898 * @return array Array of Title objects
2900 function getUsedTemplates() {
2902 $id = $this->mTitle
->getArticleID();
2907 $dbr = wfGetDB( DB_SLAVE
);
2908 $res = $dbr->select( array( 'templatelinks' ),
2909 array( 'tl_namespace', 'tl_title' ),
2910 array( 'tl_from' => $id ),
2911 'Article:getUsedTemplates' );
2912 if ( false !== $res ) {
2913 if ( $dbr->numRows( $res ) ) {
2914 while ( $row = $dbr->fetchObject( $res ) ) {
2915 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2919 $dbr->freeResult( $res );
2924 * Return an auto-generated summary if the text provided is a redirect.
2926 * @param string $text The wikitext to check
2927 * @return string '' or an appropriate summary
2929 public static function getRedirectAutosummary( $text ) {
2930 $rt = Title
::newFromRedirect( $text );
2931 if( is_object( $rt ) )
2932 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2938 * Return an auto-generated summary if the new text is much shorter than
2941 * @param string $oldtext The previous text of the page
2942 * @param string $text The submitted text of the page
2943 * @return string An appropriate autosummary, or an empty string.
2945 public static function getBlankingAutosummary( $oldtext, $text ) {
2946 if ($oldtext!='' && $text=='') {
2947 return wfMsgForContent('autosumm-blank');
2948 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
2949 #Removing more than 90% of the article
2951 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
2952 return wfMsgForContent('autosumm-replace', $truncatedtext);
2959 * Return an applicable autosummary if one exists for the given edit.
2960 * @param string $oldtext The previous text of the page.
2961 * @param string $newtext The submitted text of the page.
2962 * @param bitmask $flags A bitmask of flags submitted for the edit.
2963 * @return string An appropriate autosummary, or an empty string.
2965 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2967 # This code is UGLY UGLY UGLY.
2968 # Somebody PLEASE come up with a more elegant way to do it.
2970 #Redirect autosummaries
2971 $summary = self
::getRedirectAutosummary( $newtext );
2976 #Blanking autosummaries
2977 if (!($flags & EDIT_NEW
))
2978 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
2983 #New page autosummaries
2984 if ($flags & EDIT_NEW
&& strlen($newtext)) {
2985 #If they're making a new article, give its text, truncated, in the summary.
2987 $truncatedtext = $wgContLang->truncate(
2988 str_replace("\n", ' ', $newtext),
2989 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
2991 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3001 * Add the primary page-view wikitext to the output buffer
3002 * Saves the text into the parser cache if possible.
3003 * Updates templatelinks if it is out of date.
3005 * @param string $text
3006 * @param bool $cache
3008 public function outputWikiText( $text, $cache = true ) {
3009 global $wgParser, $wgUser, $wgOut;
3011 $popts = $wgOut->parserOptions();
3012 $popts->setTidy(true);
3013 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3014 $popts, true, true, $this->getRevIdFetched() );
3015 $popts->setTidy(false);
3016 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3017 $parserCache =& ParserCache
::singleton();
3018 $parserCache->save( $parserOutput, $this, $wgUser );
3021 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3022 // templatelinks table may have become out of sync,
3023 // especially if using variable-based transclusions.
3024 // For paranoia, check if things have changed and if
3025 // so apply updates to the database. This will ensure
3026 // that cascaded protections apply as soon as the changes
3029 # Get templates from templatelinks
3030 $id = $this->mTitle
->getArticleID();
3032 $tlTemplates = array();
3034 $dbr = wfGetDB( DB_SLAVE
);
3035 $res = $dbr->select( array( 'templatelinks' ),
3036 array( 'tl_namespace', 'tl_title' ),
3037 array( 'tl_from' => $id ),
3038 'Article:getUsedTemplates' );
3042 if ( false !== $res ) {
3043 if ( $dbr->numRows( $res ) ) {
3044 while ( $row = $dbr->fetchObject( $res ) ) {
3045 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3050 # Get templates from parser output.
3051 $poTemplates_allns = $parserOutput->getTemplates();
3053 $poTemplates = array ();
3054 foreach ( $poTemplates_allns as $ns_templates ) {
3055 $poTemplates = array_merge( $poTemplates, $ns_templates );
3059 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3061 if ( count( $templates_diff ) > 0 ) {
3062 # Whee, link updates time.
3063 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3065 $dbw = wfGetDb( DB_MASTER
);
3074 $wgOut->addParserOutput( $parserOutput );