7 * Class representing a MediaWiki article and history.
9 * See design.txt for an overview.
10 * Note: edit user interface and cache support functions have been
11 * moved to separate EditPage and HTMLFileCache classes.
20 var $mContentLoaded; //!<
23 var $mGoodAdjustment; //!<
27 var $mRedirectedFrom; //!<
28 var $mRedirectUrl; //!<
29 var $mRevIdFetched; //!<
33 var $mTotalAdjustment; //!<
40 * Constructor and clear the article
41 * @param $title Reference to a Title object.
42 * @param $oldId Integer revision ID, null to fetch from request, zero for current
44 function __construct( &$title, $oldId = null ) {
45 $this->mTitle
=& $title;
46 $this->mOldId
= $oldId;
51 * Tell the page view functions that this view was redirected
52 * from another page on the wiki.
53 * @param $from Title object.
55 function setRedirectedFrom( $from ) {
56 $this->mRedirectedFrom
= $from;
60 * @return mixed false, Title of in-wiki target, or string with URL
62 function followRedirect() {
63 $text = $this->getContent();
64 $rt = Title
::newFromRedirect( $text );
66 # process if title object is valid and not special:userlogout
68 if( $rt->getInterwiki() != '' ) {
69 if( $rt->isLocal() ) {
70 // Offsite wikis need an HTTP redirect.
72 // This can be hard to reverse and may produce loops,
73 // so they may be disabled in the site configuration.
75 $source = $this->mTitle
->getFullURL( 'redirect=no' );
76 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
79 if( $rt->getNamespace() == NS_SPECIAL
) {
80 // Gotta handle redirects to special pages differently:
81 // Fill the HTTP response "Location" header and ignore
82 // the rest of the page we're on.
84 // This can be hard to reverse, so they may be disabled.
86 if( $rt->isSpecial( 'Userlogout' ) ) {
89 return $rt->getFullURL();
96 // No or invalid redirect
101 * get the title object of the article
103 function getTitle() {
104 return $this->mTitle
;
112 $this->mDataLoaded
= false;
113 $this->mContentLoaded
= false;
115 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
116 $this->mRedirectedFrom
= null; # Title object if set
118 $this->mTimestamp
= $this->mComment
= '';
119 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
120 $this->mTouched
= '19700101000000';
121 $this->mForUpdate
= false;
122 $this->mIsRedirect
= false;
123 $this->mRevIdFetched
= 0;
124 $this->mRedirectUrl
= false;
125 $this->mLatest
= false;
126 $this->mPreparedEdit
= false;
130 * Note that getContent/loadContent do not follow redirects anymore.
131 * If you need to fetch redirectable content easily, try
132 * the shortcut in Article::followContent()
134 * @todo There are still side-effects in this!
135 * In general, you should use the Revision class, not Article,
136 * to fetch text for purposes other than page views.
138 * @return Return the text of this revision
140 function getContent() {
141 global $wgUser, $wgOut;
143 wfProfileIn( __METHOD__
);
145 if ( 0 == $this->getID() ) {
146 wfProfileOut( __METHOD__
);
147 $wgOut->setRobotpolicy( 'noindex,nofollow' );
149 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
150 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
152 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
155 return "<div class='noarticletext'>$ret</div>";
157 $this->loadContent();
158 wfProfileOut( __METHOD__
);
159 return $this->mContent
;
164 * This function returns the text of a section, specified by a number ($section).
165 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
166 * the first section before any such heading (section 0).
168 * If a section contains subsections, these are also returned.
170 * @param $text String: text to look in
171 * @param $section Integer: section number
172 * @return string text of the requested section
175 function getSection($text,$section) {
177 return $wgParser->getSection( $text, $section );
181 * @return int The oldid of the article that is to be shown, 0 for the
184 function getOldID() {
185 if ( is_null( $this->mOldId
) ) {
186 $this->mOldId
= $this->getOldIDFromRequest();
188 return $this->mOldId
;
192 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
194 * @return int The old id for the request
196 function getOldIDFromRequest() {
198 $this->mRedirectUrl
= false;
199 $oldid = $wgRequest->getVal( 'oldid' );
200 if ( isset( $oldid ) ) {
201 $oldid = intval( $oldid );
202 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
203 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
207 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
209 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
210 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
228 * Load the revision (including text) into this object
230 function loadContent() {
231 if ( $this->mContentLoaded
) return;
234 $oldid = $this->getOldID();
236 # Pre-fill content with error message so that if something
237 # fails we'll have something telling us what we intended.
238 $this->mOldId
= $oldid;
239 $this->fetchContent( $oldid );
244 * Fetch a page record with the given conditions
245 * @param Database $dbr
246 * @param array $conditions
249 function pageData( $dbr, $conditions ) {
263 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
264 $row = $dbr->selectRow(
270 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
275 * @param Database $dbr
276 * @param Title $title
278 function pageDataFromTitle( $dbr, $title ) {
279 return $this->pageData( $dbr, array(
280 'page_namespace' => $title->getNamespace(),
281 'page_title' => $title->getDBkey() ) );
285 * @param Database $dbr
288 function pageDataFromId( $dbr, $id ) {
289 return $this->pageData( $dbr, array( 'page_id' => $id ) );
293 * Set the general counter, title etc data loaded from
296 * @param object $data
299 function loadPageData( $data = 'fromdb' ) {
300 if ( $data === 'fromdb' ) {
301 $dbr = $this->getDB();
302 $data = $this->pageDataFromId( $dbr, $this->getId() );
305 $lc =& LinkCache
::singleton();
307 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
309 $this->mTitle
->mArticleID
= $data->page_id
;
311 # Old-fashioned restrictions.
312 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
314 $this->mCounter
= $data->page_counter
;
315 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
316 $this->mIsRedirect
= $data->page_is_redirect
;
317 $this->mLatest
= $data->page_latest
;
319 if ( is_object( $this->mTitle
) ) {
320 $lc->addBadLinkObj( $this->mTitle
);
322 $this->mTitle
->mArticleID
= 0;
325 $this->mDataLoaded
= true;
329 * Get text of an article from database
330 * Does *NOT* follow redirects.
331 * @param int $oldid 0 for whatever the latest revision is
334 function fetchContent( $oldid = 0 ) {
335 if ( $this->mContentLoaded
) {
336 return $this->mContent
;
339 $dbr = $this->getDB();
341 # Pre-fill content with error message so that if something
342 # fails we'll have something telling us what we intended.
343 $t = $this->mTitle
->getPrefixedText();
345 $t .= ',oldid='.$oldid;
347 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
350 $revision = Revision
::newFromId( $oldid );
351 if( is_null( $revision ) ) {
352 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
355 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
357 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
360 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
361 $this->loadPageData( $data );
363 if( !$this->mDataLoaded
) {
364 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
366 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
369 $this->loadPageData( $data );
371 $revision = Revision
::newFromId( $this->mLatest
);
372 if( is_null( $revision ) ) {
373 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
378 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
379 // We should instead work with the Revision object when we need it...
380 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
381 //$this->mContent = $revision->getText();
383 $this->mUser
= $revision->getUser();
384 $this->mUserText
= $revision->getUserText();
385 $this->mComment
= $revision->getComment();
386 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
388 $this->mRevIdFetched
= $revision->getID();
389 $this->mContentLoaded
= true;
390 $this->mRevision
=& $revision;
392 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
394 return $this->mContent
;
398 * Read/write accessor to select FOR UPDATE
400 * @param $x Mixed: FIXME
402 function forUpdate( $x = NULL ) {
403 return wfSetVar( $this->mForUpdate
, $x );
407 * Get the database which should be used for reads
412 return wfGetDB( DB_MASTER
);
416 * Get options for all SELECT statements
418 * @param $options Array: an optional options array which'll be appended to
420 * @return Array: options
422 function getSelectOptions( $options = '' ) {
423 if ( $this->mForUpdate
) {
424 if ( is_array( $options ) ) {
425 $options[] = 'FOR UPDATE';
427 $options = 'FOR UPDATE';
434 * @return int Page ID
437 if( $this->mTitle
) {
438 return $this->mTitle
->getArticleID();
445 * @return bool Whether or not the page exists in the database
448 return $this->getId() != 0;
452 * @return int The view count for the page
454 function getCount() {
455 if ( -1 == $this->mCounter
) {
456 $id = $this->getID();
460 $dbr = wfGetDB( DB_SLAVE
);
461 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
462 'Article::getCount', $this->getSelectOptions() );
465 return $this->mCounter
;
469 * Determine whether a page would be suitable for being counted as an
470 * article in the site_stats table based on the title & its content
472 * @param $text String: text to analyze
475 function isCountable( $text ) {
476 global $wgUseCommaCount;
478 $token = $wgUseCommaCount ?
',' : '[[';
480 $this->mTitle
->isContentPage()
481 && !$this->isRedirect( $text )
482 && in_string( $token, $text );
486 * Tests if the article text represents a redirect
488 * @param $text String: FIXME
491 function isRedirect( $text = false ) {
492 if ( $text === false ) {
493 $this->loadContent();
494 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
496 $titleObj = Title
::newFromRedirect( $text );
498 return $titleObj !== NULL;
502 * Returns true if the currently-referenced revision is the current edit
503 * to this page (and it exists).
506 function isCurrent() {
507 # If no oldid, this is the current version.
508 if ($this->getOldID() == 0)
511 return $this->exists() &&
512 isset( $this->mRevision
) &&
513 $this->mRevision
->isCurrent();
517 * Loads everything except the text
518 * This isn't necessary for all uses, so it's only done if needed.
521 function loadLastEdit() {
522 if ( -1 != $this->mUser
)
525 # New or non-existent articles have no user information
526 $id = $this->getID();
527 if ( 0 == $id ) return;
529 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
530 if( !is_null( $this->mLastRevision
) ) {
531 $this->mUser
= $this->mLastRevision
->getUser();
532 $this->mUserText
= $this->mLastRevision
->getUserText();
533 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
534 $this->mComment
= $this->mLastRevision
->getComment();
535 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
536 $this->mRevIdFetched
= $this->mLastRevision
->getID();
540 function getTimestamp() {
541 // Check if the field has been filled by ParserCache::get()
542 if ( !$this->mTimestamp
) {
543 $this->loadLastEdit();
545 return wfTimestamp(TS_MW
, $this->mTimestamp
);
549 $this->loadLastEdit();
553 function getUserText() {
554 $this->loadLastEdit();
555 return $this->mUserText
;
558 function getComment() {
559 $this->loadLastEdit();
560 return $this->mComment
;
563 function getMinorEdit() {
564 $this->loadLastEdit();
565 return $this->mMinorEdit
;
568 function getRevIdFetched() {
569 $this->loadLastEdit();
570 return $this->mRevIdFetched
;
574 * @todo Document, fixme $offset never used.
575 * @param $limit Integer: default 0.
576 * @param $offset Integer: default 0.
578 function getContributors($limit = 0, $offset = 0) {
579 # XXX: this is expensive; cache this info somewhere.
582 $dbr = wfGetDB( DB_SLAVE
);
583 $revTable = $dbr->tableName( 'revision' );
584 $userTable = $dbr->tableName( 'user' );
585 $user = $this->getUser();
586 $pageId = $this->getId();
588 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
589 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
590 WHERE rev_page = $pageId
591 AND rev_user != $user
592 GROUP BY rev_user, rev_user_text, user_real_name
593 ORDER BY timestamp DESC";
595 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
596 $sql .= ' '. $this->getSelectOptions();
598 $res = $dbr->query($sql, __METHOD__
);
600 while ( $line = $dbr->fetchObject( $res ) ) {
601 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
604 $dbr->freeResult($res);
609 * This is the default action of the script: just view the page of
613 global $wgUser, $wgOut, $wgRequest, $wgContLang;
614 global $wgEnableParserCache, $wgStylePath, $wgParser;
615 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
616 $sk = $wgUser->getSkin();
618 wfProfileIn( __METHOD__
);
620 $parserCache =& ParserCache
::singleton();
621 $ns = $this->mTitle
->getNamespace(); # shortcut
623 # Get variables from query string
624 $oldid = $this->getOldID();
626 # getOldID may want us to redirect somewhere else
627 if ( $this->mRedirectUrl
) {
628 $wgOut->redirect( $this->mRedirectUrl
);
629 wfProfileOut( __METHOD__
);
633 $diff = $wgRequest->getVal( 'diff' );
634 $rcid = $wgRequest->getVal( 'rcid' );
635 $rdfrom = $wgRequest->getVal( 'rdfrom' );
636 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
637 $purge = $wgRequest->getVal( 'action' ) == 'purge';
639 $wgOut->setArticleFlag( true );
641 # Discourage indexing of printable versions, but encourage following
642 if( $wgOut->isPrintable() ) {
643 $policy = 'noindex,follow';
644 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
645 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
646 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
647 # Honour customised robot policies for this namespace
648 $policy = $wgNamespaceRobotPolicies[$ns];
650 # Default to encourage indexing and following links
651 $policy = 'index,follow';
653 $wgOut->setRobotPolicy( $policy );
655 # If we got diff and oldid in the query, we want to see a
656 # diff page instead of the article.
658 if ( !is_null( $diff ) ) {
659 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
661 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
662 // DifferenceEngine directly fetched the revision:
663 $this->mRevIdFetched
= $de->mNewid
;
664 $de->showDiffPage( $diffOnly );
666 // Needed to get the page's current revision
667 $this->loadPageData();
668 if( $diff == 0 ||
$diff == $this->mLatest
) {
669 # Run view updates for current revision only
670 $this->viewUpdates();
672 wfProfileOut( __METHOD__
);
676 if ( empty( $oldid ) && $this->checkTouched() ) {
677 $wgOut->setETag($parserCache->getETag($this, $wgUser));
679 if( $wgOut->checkLastModified( $this->mTouched
) ){
680 wfProfileOut( __METHOD__
);
682 } else if ( $this->tryFileCache() ) {
683 # tell wgOut that output is taken care of
685 $this->viewUpdates();
686 wfProfileOut( __METHOD__
);
691 # Should the parser cache be used?
692 $pcache = $wgEnableParserCache
693 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
696 && !$this->mTitle
->isCssOrJsPage()
697 && !$this->mTitle
->isCssJsSubpage();
698 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
699 if ( $wgUser->getOption( 'stubthreshold' ) ) {
700 wfIncrStats( 'pcache_miss_stub' );
703 $wasRedirected = false;
704 if ( isset( $this->mRedirectedFrom
) ) {
705 // This is an internally redirected page view.
706 // We'll need a backlink to the source page for navigation.
707 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
708 $sk = $wgUser->getSkin();
709 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
710 $s = wfMsg( 'redirectedfrom', $redir );
711 $wgOut->setSubtitle( $s );
713 // Set the fragment if one was specified in the redirect
714 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
715 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
716 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
718 $wasRedirected = true;
720 } elseif ( !empty( $rdfrom ) ) {
721 // This is an externally redirected view, from some other wiki.
722 // If it was reported from a trusted site, supply a backlink.
723 global $wgRedirectSources;
724 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
725 $sk = $wgUser->getSkin();
726 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
727 $s = wfMsg( 'redirectedfrom', $redir );
728 $wgOut->setSubtitle( $s );
729 $wasRedirected = true;
734 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
736 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
737 // Ensure that UI elements requiring revision ID have
738 // the correct version information.
739 $wgOut->setRevisionId( $this->mLatest
);
743 if ( !$outputDone ) {
744 $text = $this->getContent();
745 if ( $text === false ) {
746 # Failed to load, replace text with error message
747 $t = $this->mTitle
->getPrefixedText();
749 $t .= ',oldid='.$oldid;
750 $text = wfMsg( 'missingarticle', $t );
752 $text = wfMsg( 'noarticletext', $t );
756 # Another whitelist check in case oldid is altering the title
757 if ( !$this->mTitle
->userCanRead() ) {
758 $wgOut->loginToUse();
763 # We're looking at an old revision
765 if ( !empty( $oldid ) ) {
766 $wgOut->setRobotpolicy( 'noindex,nofollow' );
767 if( is_null( $this->mRevision
) ) {
768 // FIXME: This would be a nice place to load the 'no such page' text.
770 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
771 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
772 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
773 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
774 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
777 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
778 // and we are allowed to see...
786 $wgOut->setRevisionId( $this->getRevIdFetched() );
788 // Pages containing custom CSS or JavaScript get special treatment
789 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
790 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
792 // Give hooks a chance to customise the output
793 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
794 // Wrap the whole lot in a <pre> and don't parse
796 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
797 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
798 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
799 $wgOut->addHtml( "\n</pre>\n" );
804 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
806 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
807 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
808 # Don't overwrite the subtitle if this was an old revision
809 if( !$wasRedirected && $this->isCurrent() ) {
810 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
812 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
814 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
815 '<span class="redirectText">'.$link.'</span>' );
817 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
818 $wgOut->addParserOutputNoText( $parseout );
819 } else if ( $pcache ) {
820 # Display content and save to parser cache
821 $this->outputWikiText( $text );
823 # Display content, don't attempt to save to parser cache
824 # Don't show section-edit links on old revisions... this way lies madness.
825 if( !$this->isCurrent() ) {
826 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
828 # Display content and don't save to parser cache
829 # With timing hack -- TS 2006-07-26
831 $this->outputWikiText( $text, false );
836 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
837 $this->mTitle
->getPrefixedDBkey()));
840 if( !$this->isCurrent() ) {
841 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
846 /* title may have been set from the cache */
847 $t = $wgOut->getPageTitle();
849 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
852 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
853 if( $ns == NS_USER_TALK
&&
854 User
::isIP( $this->mTitle
->getText() ) ) {
855 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
858 # If we have been passed an &rcid= parameter, we want to give the user a
859 # chance to mark this new article as patrolled.
860 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
862 "<div class='patrollink'>" .
863 wfMsgHtml( 'markaspatrolledlink',
864 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
865 "action=markpatrolled&rcid=$rcid" )
872 if ($wgUseTrackbacks)
873 $this->addTrackbacks();
875 $this->viewUpdates();
876 wfProfileOut( __METHOD__
);
879 function addTrackbacks() {
880 global $wgOut, $wgUser;
882 $dbr = wfGetDB(DB_SLAVE
);
884 /* FROM */ 'trackbacks',
885 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
886 /* WHERE */ array('tb_page' => $this->getID())
889 if (!$dbr->numrows($tbs))
893 while ($o = $dbr->fetchObject($tbs)) {
895 if ($wgUser->isAllowed( 'trackback' )) {
896 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
897 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
898 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
900 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
907 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
910 function deletetrackback() {
911 global $wgUser, $wgRequest, $wgOut, $wgTitle;
913 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
914 $wgOut->addWikitext(wfMsg('sessionfailure'));
918 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
920 if (count($permission_errors)>0)
922 $wgOut->showPermissionsErrorPage( $permission_errors );
926 $db = wfGetDB(DB_MASTER
);
927 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
928 $wgTitle->invalidateCache();
929 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
935 $wgOut->setArticleBodyOnly(true);
940 * Handle action=purge
943 global $wgUser, $wgRequest, $wgOut;
945 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
946 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
950 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
951 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
952 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
953 $msg = str_replace( '$1',
954 "<form method=\"post\" action=\"$action\">\n" .
955 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
958 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
959 $wgOut->setRobotpolicy( 'noindex,nofollow' );
960 $wgOut->addHTML( $msg );
965 * Perform the actions of a page purging
969 // Invalidate the cache
970 $this->mTitle
->invalidateCache();
973 // Commit the transaction before the purge is sent
974 $dbw = wfGetDB( DB_MASTER
);
975 $dbw->immediateCommit();
978 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
985 * Insert a new empty page record for this article.
986 * This *must* be followed up by creating a revision
987 * and running $this->updateToLatest( $rev_id );
988 * or else the record will be left in a funky state.
989 * Best if all done inside a transaction.
991 * @param Database $dbw
992 * @return int The newly created page_id key
995 function insertOn( $dbw ) {
996 wfProfileIn( __METHOD__
);
998 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
999 $dbw->insert( 'page', array(
1000 'page_id' => $page_id,
1001 'page_namespace' => $this->mTitle
->getNamespace(),
1002 'page_title' => $this->mTitle
->getDBkey(),
1003 'page_counter' => 0,
1004 'page_restrictions' => '',
1005 'page_is_redirect' => 0, # Will set this shortly...
1007 'page_random' => wfRandom(),
1008 'page_touched' => $dbw->timestamp(),
1009 'page_latest' => 0, # Fill this in shortly...
1010 'page_len' => 0, # Fill this in shortly...
1012 $newid = $dbw->insertId();
1014 $this->mTitle
->resetArticleId( $newid );
1016 wfProfileOut( __METHOD__
);
1021 * Update the page record to point to a newly saved revision.
1023 * @param Database $dbw
1024 * @param Revision $revision For ID number, and text used to set
1025 length and redirect status fields
1026 * @param int $lastRevision If given, will not overwrite the page field
1027 * when different from the currently set value.
1028 * Giving 0 indicates the new page flag should
1030 * @param bool $lastRevIsRedirect If given, will optimize adding and
1031 * removing rows in redirect table.
1032 * @return bool true on success, false on failure
1035 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1036 wfProfileIn( __METHOD__
);
1038 $text = $revision->getText();
1039 $rt = Title
::newFromRedirect( $text );
1041 $conditions = array( 'page_id' => $this->getId() );
1042 if( !is_null( $lastRevision ) ) {
1043 # An extra check against threads stepping on each other
1044 $conditions['page_latest'] = $lastRevision;
1047 $dbw->update( 'page',
1049 'page_latest' => $revision->getId(),
1050 'page_touched' => $dbw->timestamp(),
1051 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1052 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1053 'page_len' => strlen( $text ),
1058 $result = $dbw->affectedRows() != 0;
1061 // FIXME: Should the result from updateRedirectOn() be returned instead?
1062 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1065 wfProfileOut( __METHOD__
);
1070 * Add row to the redirect table if this is a redirect, remove otherwise.
1072 * @param Database $dbw
1073 * @param $redirectTitle a title object pointing to the redirect target,
1074 * or NULL if this is not a redirect
1075 * @param bool $lastRevIsRedirect If given, will optimize adding and
1076 * removing rows in redirect table.
1077 * @return bool true on success, false on failure
1080 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1082 // Always update redirects (target link might have changed)
1083 // Update/Insert if we don't know if the last revision was a redirect or not
1084 // Delete if changing from redirect to non-redirect
1085 $isRedirect = !is_null($redirectTitle);
1086 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1088 wfProfileIn( __METHOD__
);
1092 // This title is a redirect, Add/Update row in the redirect table
1093 $set = array( /* SET */
1094 'rd_namespace' => $redirectTitle->getNamespace(),
1095 'rd_title' => $redirectTitle->getDBkey(),
1096 'rd_from' => $this->getId(),
1099 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1101 // This is not a redirect, remove row from redirect table
1102 $where = array( 'rd_from' => $this->getId() );
1103 $dbw->delete( 'redirect', $where, __METHOD__
);
1106 wfProfileOut( __METHOD__
);
1107 return ( $dbw->affectedRows() != 0 );
1114 * If the given revision is newer than the currently set page_latest,
1115 * update the page record. Otherwise, do nothing.
1117 * @param Database $dbw
1118 * @param Revision $revision
1120 function updateIfNewerOn( &$dbw, $revision ) {
1121 wfProfileIn( __METHOD__
);
1123 $row = $dbw->selectRow(
1124 array( 'revision', 'page' ),
1125 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1127 'page_id' => $this->getId(),
1128 'page_latest=rev_id' ),
1131 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1132 wfProfileOut( __METHOD__
);
1135 $prev = $row->rev_id
;
1136 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1138 # No or missing previous revision; mark the page as new
1140 $lastRevIsRedirect = null;
1143 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1144 wfProfileOut( __METHOD__
);
1149 * @return string Complete article text, or null if error
1151 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1152 wfProfileIn( __METHOD__
);
1154 if( $section == '' ) {
1155 // Whole-page edit; let the text through unmolested.
1157 if( is_null( $edittime ) ) {
1158 $rev = Revision
::newFromTitle( $this->mTitle
);
1160 $dbw = wfGetDB( DB_MASTER
);
1161 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1163 if( is_null( $rev ) ) {
1164 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1165 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1168 $oldtext = $rev->getText();
1170 if( $section == 'new' ) {
1171 # Inserting a new section
1172 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1173 $text = strlen( trim( $oldtext ) ) > 0
1174 ?
"{$oldtext}\n\n{$subject}{$text}"
1175 : "{$subject}{$text}";
1177 # Replacing an existing section; roll out the big guns
1179 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1184 wfProfileOut( __METHOD__
);
1189 * @deprecated use Article::doEdit()
1191 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1192 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1193 ( $isminor ? EDIT_MINOR
: 0 ) |
1194 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 ) |
1195 ( $bot ? EDIT_FORCE_BOT
: 0 );
1197 # If this is a comment, add the summary as headline
1198 if ( $comment && $summary != "" ) {
1199 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1202 $this->doEdit( $text, $summary, $flags );
1204 $dbw = wfGetDB( DB_MASTER
);
1206 if (!$this->mTitle
->userIsWatching()) {
1212 if ( $this->mTitle
->userIsWatching() ) {
1218 $this->doRedirect( $this->isRedirect( $text ) );
1222 * @deprecated use Article::doEdit()
1224 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1225 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1226 ( $minor ? EDIT_MINOR
: 0 ) |
1227 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1229 $good = $this->doEdit( $text, $summary, $flags );
1231 $dbw = wfGetDB( DB_MASTER
);
1233 if (!$this->mTitle
->userIsWatching()) {
1239 if ( $this->mTitle
->userIsWatching() ) {
1246 $extraq = ''; // Give extensions a chance to modify URL query on update
1247 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1249 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1257 * Change an existing article or create a new article. Updates RC and all necessary caches,
1258 * optionally via the deferred update array.
1260 * $wgUser must be set before calling this function.
1262 * @param string $text New text
1263 * @param string $summary Edit summary
1264 * @param integer $flags bitfield:
1266 * Article is known or assumed to be non-existent, create a new one
1268 * Article is known or assumed to be pre-existing, update it
1270 * Mark this edit minor, if the user is allowed to do so
1272 * Do not log the change in recentchanges
1274 * Mark the edit a "bot" edit regardless of user rights
1275 * EDIT_DEFER_UPDATES
1276 * Defer some of the updates until the end of index.php
1278 * Fill in blank summaries with generated text where possible
1280 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1281 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1282 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1283 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1284 * to MediaWiki's performance-optimised locking strategy.
1286 * @return bool success
1288 function doEdit( $text, $summary, $flags = 0 ) {
1289 global $wgUser, $wgDBtransactions;
1291 wfProfileIn( __METHOD__
);
1294 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1295 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1297 $flags |
= EDIT_UPDATE
;
1303 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1304 &$summary, $flags & EDIT_MINOR
,
1305 null, null, &$flags ) ) )
1307 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1308 wfProfileOut( __METHOD__
);
1312 # Silently ignore EDIT_MINOR if not allowed
1313 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1314 $bot = $flags & EDIT_FORCE_BOT
;
1316 $oldtext = $this->getContent();
1317 $oldsize = strlen( $oldtext );
1319 # Provide autosummaries if one is not provided.
1320 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1321 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1323 $editInfo = $this->prepareTextForEdit( $text );
1324 $text = $editInfo->pst
;
1325 $newsize = strlen( $text );
1327 $dbw = wfGetDB( DB_MASTER
);
1328 $now = wfTimestampNow();
1330 if ( $flags & EDIT_UPDATE
) {
1331 # Update article, but only if changed.
1333 # Make sure the revision is either completely inserted or not inserted at all
1334 if( !$wgDBtransactions ) {
1335 $userAbort = ignore_user_abort( true );
1341 $changed = ( strcmp( $text, $oldtext ) != 0 );
1344 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1345 - (int)$this->isCountable( $oldtext );
1346 $this->mTotalAdjustment
= 0;
1348 $lastRevision = $dbw->selectField(
1349 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1351 if ( !$lastRevision ) {
1352 # Article gone missing
1353 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1354 wfProfileOut( __METHOD__
);
1358 $revision = new Revision( array(
1359 'page' => $this->getId(),
1360 'comment' => $summary,
1361 'minor_edit' => $isminor,
1366 $revisionId = $revision->insertOn( $dbw );
1369 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1372 /* Belated edit conflict! Run away!! */
1376 # Update recentchanges
1377 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1378 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1379 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1382 # Mark as patrolled if the user can do so
1383 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1384 RecentChange
::markPatrolled( $rcid );
1385 PatrolLog
::record( $rcid, true );
1388 $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 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1413 # Create new article
1415 # Set statistics members
1416 # We work out if it's countable after PST to avoid counter drift
1417 # when articles are created with {{subst:}}
1418 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1419 $this->mTotalAdjustment
= 1;
1423 # Add the page record; stake our claim on this title!
1424 # This will fail with a database query exception if the article already exists
1425 $newid = $this->insertOn( $dbw );
1427 # Save the revision text...
1428 $revision = new Revision( array(
1430 'comment' => $summary,
1431 'minor_edit' => $isminor,
1434 $revisionId = $revision->insertOn( $dbw );
1436 $this->mTitle
->resetArticleID( $newid );
1438 # Update the page record with revision data
1439 $this->updateRevisionOn( $dbw, $revision, 0 );
1441 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1442 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1443 '', strlen( $text ), $revisionId );
1444 # Mark as patrolled if the user can
1445 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1446 RecentChange
::markPatrolled( $rcid );
1447 PatrolLog
::record( $rcid, true );
1450 $wgUser->incEditCount();
1453 # Update links, etc.
1454 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1457 Article
::onArticleCreate( $this->mTitle
);
1459 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1460 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1463 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1468 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1469 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1472 wfProfileOut( __METHOD__
);
1477 * @deprecated wrapper for doRedirect
1479 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1480 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1484 * Output a redirect back to the article.
1485 * This is typically used after an edit.
1487 * @param boolean $noRedir Add redirect=no
1488 * @param string $sectionAnchor section to redirect to, including "#"
1490 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1493 $query = 'redirect=no';
1495 $query .= "&$query";
1499 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1503 * Mark this particular edit/page as patrolled
1505 function markpatrolled() {
1506 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1507 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1509 # Check patrol config options
1511 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1512 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1516 # If we haven't been given an rc_id value, we can't do anything
1517 $rcid = (int) $wgRequest->getVal('rcid');
1518 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1519 if ( is_null ( $rc ) )
1521 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1525 if ( !$wgUseRCPatrol && $rc->mAttribs
['rc_type'] != RC_NEW
) {
1526 // Only new pages can be patrolled if the general patrolling is off....???
1527 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1529 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1534 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1536 if (count($permission_errors)>0)
1538 $wgOut->showPermissionsErrorPage( $permission_errors );
1542 # Handle the 'MarkPatrolled' hook
1543 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1547 #It would be nice to see where the user had actually come from, but for now just guess
1548 $returnto = $rc->mAttribs
['rc_type'] == RC_NEW ?
'Newpages' : 'Recentchanges';
1549 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1551 # If it's left up to us, check that the user is allowed to patrol this edit
1552 # If the user has the "autopatrol" right, then we'll assume there are no
1553 # other conditions stopping them doing so
1554 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1555 $rc = RecentChange
::newFromId( $rcid );
1556 # Graceful error handling, as we've done before here...
1557 # (If the recent change doesn't exist, then it doesn't matter whether
1558 # the user is allowed to patrol it or not; nothing is going to happen
1559 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1560 # The user made this edit, and can't patrol it
1561 # Tell them so, and then back off
1562 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1563 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1564 $wgOut->returnToMain( false, $return );
1569 # Mark the edit as patrolled
1570 RecentChange
::markPatrolled( $rcid );
1571 PatrolLog
::record( $rcid );
1572 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1575 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1576 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1577 $wgOut->returnToMain( false, $return );
1581 * User-interface handler for the "watch" action
1586 global $wgUser, $wgOut;
1588 if ( $wgUser->isAnon() ) {
1589 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1592 if ( wfReadOnly() ) {
1593 $wgOut->readOnlyPage();
1597 if( $this->doWatch() ) {
1598 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1599 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1601 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1602 $text = wfMsg( 'addedwatchtext', $link );
1603 $wgOut->addWikiText( $text );
1606 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1610 * Add this page to $wgUser's watchlist
1611 * @return bool true on successful watch operation
1613 function doWatch() {
1615 if( $wgUser->isAnon() ) {
1619 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1620 $wgUser->addWatch( $this->mTitle
);
1622 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1629 * User interface handler for the "unwatch" action.
1631 function unwatch() {
1633 global $wgUser, $wgOut;
1635 if ( $wgUser->isAnon() ) {
1636 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1639 if ( wfReadOnly() ) {
1640 $wgOut->readOnlyPage();
1644 if( $this->doUnwatch() ) {
1645 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1646 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1648 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1649 $text = wfMsg( 'removedwatchtext', $link );
1650 $wgOut->addWikiText( $text );
1653 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1657 * Stop watching a page
1658 * @return bool true on successful unwatch
1660 function doUnwatch() {
1662 if( $wgUser->isAnon() ) {
1666 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1667 $wgUser->removeWatch( $this->mTitle
);
1669 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1676 * action=protect handler
1678 function protect() {
1679 $form = new ProtectionForm( $this );
1684 * action=unprotect handler (alias)
1686 function unprotect() {
1691 * Update the article's restriction field, and leave a log entry.
1693 * @param array $limit set of restriction keys
1694 * @param string $reason
1695 * @return bool true on success
1697 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1698 global $wgUser, $wgRestrictionTypes, $wgContLang;
1700 $id = $this->mTitle
->getArticleID();
1701 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1709 // Take this opportunity to purge out expired restrictions
1710 Title
::purgeExpiredRestrictions();
1712 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1713 # we expect a single selection, but the schema allows otherwise.
1715 foreach( $wgRestrictionTypes as $action )
1716 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1718 $current = Article
::flattenRestrictions( $current );
1719 $updated = Article
::flattenRestrictions( $limit );
1721 $changed = ( $current != $updated );
1722 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1723 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1724 $protect = ( $updated != '' );
1726 # If nothing's changed, do nothing
1728 global $wgGroupPermissions;
1729 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1731 $dbw = wfGetDB( DB_MASTER
);
1733 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1735 $expiry_description = '';
1736 if ( $encodedExpiry != 'infinity' ) {
1737 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1740 # Prepare a null revision to be added to the history
1741 $modified = $current != '' && $protect;
1743 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1745 $comment_type = 'unprotectedarticle';
1747 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1749 foreach( $limit as $action => $restrictions ) {
1750 # Check if the group level required to edit also can protect pages
1751 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1752 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1755 $cascade_description = '';
1757 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1761 $comment .= ": $reason";
1763 $comment .= " [$updated]";
1764 if ( $expiry_description && $protect )
1765 $comment .= "$expiry_description";
1767 $comment .= "$cascade_description";
1769 # Update restrictions table
1770 foreach( $limit as $action => $restrictions ) {
1771 if ($restrictions != '' ) {
1772 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1773 array( 'pr_page' => $id, 'pr_type' => $action
1774 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1775 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1777 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1778 'pr_type' => $action ), __METHOD__
);
1781 if($dbw->affectedRows() == 0)
1785 # Insert a null revision
1786 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1787 $nullRevId = $nullRevision->insertOn( $dbw );
1789 # Update page record
1790 $dbw->update( 'page',
1792 'page_touched' => $dbw->timestamp(),
1793 'page_restrictions' => '',
1794 'page_latest' => $nullRevId
1795 ), array( /* WHERE */
1797 ), 'Article::protect'
1799 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1801 # Update the protection log
1802 $log = new LogPage( 'protect' );
1805 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1807 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1811 } # End "changed" check
1817 * Take an array of page restrictions and flatten it to a string
1818 * suitable for insertion into the page_restrictions field.
1819 * @param array $limit
1823 function flattenRestrictions( $limit ) {
1824 if( !is_array( $limit ) ) {
1825 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1829 foreach( $limit as $action => $restrictions ) {
1830 if( $restrictions != '' ) {
1831 $bits[] = "$action=$restrictions";
1834 return implode( ':', $bits );
1838 * Auto-generates a deletion reason
1839 * @param bool &$hasHistory Whether the page has a history
1841 public function generateReason(&$hasHistory)
1844 $dbw = wfGetDB(DB_MASTER
);
1845 // Get the last revision
1846 $rev = Revision
::newFromTitle($this->mTitle
);
1849 // Get the article's contents
1850 $contents = $rev->getText();
1852 // If the page is blank, use the text from the previous revision,
1853 // which can only be blank if there's a move/import/protect dummy revision involved
1856 $prev = $rev->getPrevious();
1859 $contents = $prev->getText();
1864 // Find out if there was only one contributor
1865 // Only scan the last 20 revisions
1867 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1868 array('LIMIT' => $limit));
1870 // This page has no revisions, which is very weird
1872 if($res->numRows() > 1)
1875 $hasHistory = false;
1876 $row = $dbw->fetchObject($res);
1877 $onlyAuthor = $row->rev_user_text
;
1878 // Try to find a second contributor
1879 while( $row = $dbw->fetchObject($res) ) {
1880 if($row->rev_user_text
!= $onlyAuthor) {
1881 $onlyAuthor = false;
1885 $dbw->freeResult($res);
1887 // Generate the summary with a '$1' placeholder
1889 // The current revision is blank and the one before is also
1890 // blank. It's just not our lucky day
1891 $reason = wfMsgForContent('exbeforeblank', '$1');
1894 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1896 $reason = wfMsgForContent('excontent', '$1');
1899 // Replace newlines with spaces to prevent uglyness
1900 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1901 // Calculate the maximum amount of chars to get
1902 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1903 $maxLength = 255 - (strlen($reason) - 2) - 3;
1904 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1905 // Remove possible unfinished links
1906 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1907 // Now replace the '$1' placeholder
1908 $reason = str_replace( '$1', $contents, $reason );
1914 * UI entry point for page deletion
1917 global $wgUser, $wgOut, $wgRequest;
1919 $confirm = $wgRequest->wasPosted() &&
1920 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1922 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1923 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1925 $reason = $this->DeleteReasonList
;
1927 if ( $reason != 'other' && $this->DeleteReason
!= '') {
1928 // Entry from drop down menu + additional comment
1929 $reason .= ': ' . $this->DeleteReason
;
1930 } elseif ( $reason == 'other' ) {
1931 $reason = $this->DeleteReason
;
1934 # This code desperately needs to be totally rewritten
1936 # Read-only check...
1937 if ( wfReadOnly() ) {
1938 $wgOut->readOnlyPage();
1943 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1945 if (count($permission_errors)>0) {
1946 $wgOut->showPermissionsErrorPage( $permission_errors );
1950 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1952 # Better double-check that it hasn't been deleted yet!
1953 $dbw = wfGetDB( DB_MASTER
);
1954 $conds = $this->mTitle
->pageCond();
1955 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1956 if ( $latest === false ) {
1957 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1961 # Hack for big sites
1962 $bigHistory = $this->isBigDeletion();
1963 if( $bigHistory && !$this->mTitle
->userCan( 'bigdelete' ) ) {
1964 global $wgLang, $wgDeleteRevisionsLimit;
1965 $wgOut->addWikiText( "<div class='error'>\n" .
1966 wfMsg( 'delete-toobig',
1967 $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) .
1973 $this->doDelete( $reason );
1974 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1976 } elseif( $this->mTitle
->userIsWatching() ) {
1982 // Generate deletion reason
1983 $hasHistory = false;
1984 if ( !$reason ) $reason = $this->generateReason($hasHistory);
1986 // If the page has a history, insert a warning
1987 if( $hasHistory && !$confirm ) {
1988 $skin=$wgUser->getSkin();
1989 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1991 global $wgLang, $wgDeleteRevisionsLimit;
1992 $wgOut->addWikiText( "<div class='error'>\n" .
1993 wfMsg( 'delete-warning-toobig',
1994 $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) .
1999 return $this->confirmDelete( '', $reason );
2003 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2005 function isBigDeletion() {
2006 global $wgDeleteRevisionsLimit;
2007 if( $wgDeleteRevisionsLimit ) {
2008 $revCount = $this->estimateRevisionCount();
2009 return $revCount > $wgDeleteRevisionsLimit;
2015 * @return int approximate revision count
2017 function estimateRevisionCount() {
2019 // For an exact count...
2020 //return $dbr->selectField( 'revision', 'COUNT(*)',
2021 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2022 return $dbr->estimateRowCount( 'revision', '*',
2023 array( 'rev_page' => $this->getId() ), __METHOD__
);
2027 * Get the last N authors
2028 * @param int $num Number of revisions to get
2029 * @param string $revLatest The latest rev_id, selected from the master (optional)
2030 * @return array Array of authors, duplicates not removed
2032 function getLastNAuthors( $num, $revLatest = 0 ) {
2033 wfProfileIn( __METHOD__
);
2035 // First try the slave
2036 // If that doesn't have the latest revision, try the master
2038 $db = wfGetDB( DB_SLAVE
);
2040 $res = $db->select( array( 'page', 'revision' ),
2041 array( 'rev_id', 'rev_user_text' ),
2043 'page_namespace' => $this->mTitle
->getNamespace(),
2044 'page_title' => $this->mTitle
->getDBkey(),
2045 'rev_page = page_id'
2046 ), __METHOD__
, $this->getSelectOptions( array(
2047 'ORDER BY' => 'rev_timestamp DESC',
2052 wfProfileOut( __METHOD__
);
2055 $row = $db->fetchObject( $res );
2056 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2057 $db = wfGetDB( DB_MASTER
);
2062 } while ( $continue );
2064 $authors = array( $row->rev_user_text
);
2065 while ( $row = $db->fetchObject( $res ) ) {
2066 $authors[] = $row->rev_user_text
;
2068 wfProfileOut( __METHOD__
);
2073 * Output deletion confirmation dialog
2075 function confirmDelete( $par, $reason ) {
2076 global $wgOut, $wgUser;
2078 wfDebug( "Article::confirmDelete\n" );
2080 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
2081 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
2082 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2083 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
2085 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
2087 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
2088 $delcom = Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' );
2089 $token = htmlspecialchars( $wgUser->editToken() );
2090 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
2092 $mDeletereasonother = Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' );
2093 $mDeletereasonotherlist = wfMsgHtml( 'deletereasonotherlist' );
2094 $scDeleteReasonList = wfMsgForContent( 'deletereason-dropdown' );
2096 $deleteReasonList = '';
2097 if ( $scDeleteReasonList != '' && $scDeleteReasonList != '-' ) {
2098 $deleteReasonList = "<option value=\"other\">$mDeletereasonotherlist</option>";
2100 foreach ( explode( "\n", $scDeleteReasonList ) as $option) {
2101 $value = trim( htmlspecialchars($option) );
2102 if ( $value == '' ) {
2104 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
2105 // A new group is starting ...
2106 $value = trim( substr( $value, 1 ) );
2107 $deleteReasonList .= "$optgroup<optgroup label=\"$value\">";
2108 $optgroup = "</optgroup>";
2109 } elseif ( substr( $value, 0, 2) == '**' ) {
2112 $value = trim( substr( $value, 2 ) );
2113 if ( $this->DeleteReasonList
=== $value)
2114 $selected = ' selected="selected"';
2115 $deleteReasonList .= "<option value=\"$value\"$selected>$value</option>";
2117 // groupless delete reason
2119 if ( $this->DeleteReasonList
=== $value)
2120 $selected = ' selected="selected"';
2121 $deleteReasonList .= "$optgroup<option value=\"$value\"$selected>$value</option>";
2125 $deleteReasonList .= $optgroup;
2128 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
2130 <tr id=\"wpDeleteReasonListRow\" name=\"wpDeleteReasonListRow\">
2135 <select tabindex='1' id='wpDeleteReasonList' name=\"wpDeleteReasonList\">
2140 <tr id=\"wpDeleteReasonRow\" name=\"wpDeleteReasonRow\">
2145 <input type='text' maxlength='255' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"2\" />
2155 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2159 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2162 $wgOut->returnToMain( false, $this->mTitle
);
2164 $this->showLogExtract( $wgOut );
2169 * Show relevant lines from the deletion log
2171 function showLogExtract( $out ) {
2172 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2173 $logViewer = new LogViewer(
2176 array( 'page' => $this->mTitle
->getPrefixedText(),
2177 'type' => 'delete' ) ) ) );
2178 $logViewer->showList( $out );
2183 * Perform a deletion and output success or failure messages
2185 function doDelete( $reason ) {
2186 global $wgOut, $wgUser;
2187 wfDebug( __METHOD__
."\n" );
2189 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2190 if ( $this->doDeleteArticle( $reason ) ) {
2191 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2193 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2194 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2196 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2197 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2199 $wgOut->addWikiText( $text );
2200 $wgOut->returnToMain( false );
2201 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2203 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2209 * Back-end article deletion
2210 * Deletes the article with database consistency, writes logs, purges caches
2213 function doDeleteArticle( $reason ) {
2214 global $wgUseSquid, $wgDeferredUpdateList;
2215 global $wgUseTrackbacks;
2217 wfDebug( __METHOD__
."\n" );
2219 $dbw = wfGetDB( DB_MASTER
);
2220 $ns = $this->mTitle
->getNamespace();
2221 $t = $this->mTitle
->getDBkey();
2222 $id = $this->mTitle
->getArticleID();
2224 if ( $t == '' ||
$id == 0 ) {
2228 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2229 array_push( $wgDeferredUpdateList, $u );
2231 // For now, shunt the revision data into the archive table.
2232 // Text is *not* removed from the text table; bulk storage
2233 // is left intact to avoid breaking block-compression or
2234 // immutable storage schemes.
2236 // For backwards compatibility, note that some older archive
2237 // table entries will have ar_text and ar_flags fields still.
2239 // In the future, we may keep revisions and mark them with
2240 // the rev_deleted field, which is reserved for this purpose.
2241 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2243 'ar_namespace' => 'page_namespace',
2244 'ar_title' => 'page_title',
2245 'ar_comment' => 'rev_comment',
2246 'ar_user' => 'rev_user',
2247 'ar_user_text' => 'rev_user_text',
2248 'ar_timestamp' => 'rev_timestamp',
2249 'ar_minor_edit' => 'rev_minor_edit',
2250 'ar_rev_id' => 'rev_id',
2251 'ar_text_id' => 'rev_text_id',
2252 'ar_text' => '\'\'', // Be explicit to appease
2253 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2254 'ar_len' => 'rev_len',
2255 'ar_page_id' => 'page_id',
2258 'page_id = rev_page'
2262 # Delete restrictions for it
2263 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2265 # Now that it's safely backed up, delete it
2266 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2268 # If using cascading deletes, we can skip some explicit deletes
2269 if ( !$dbw->cascadingDeletes() ) {
2271 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2273 if ($wgUseTrackbacks)
2274 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2276 # Delete outgoing links
2277 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2278 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2279 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2280 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2281 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2282 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2283 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2286 # If using cleanup triggers, we can skip some manual deletes
2287 if ( !$dbw->cleanupTriggers() ) {
2289 # Clean up recentchanges entries...
2290 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2294 Article
::onArticleDelete( $this->mTitle
);
2297 $log = new LogPage( 'delete' );
2298 $log->addEntry( 'delete', $this->mTitle
, $reason );
2300 # Clear the cached article id so the interface doesn't act like we exist
2301 $this->mTitle
->resetArticleID( 0 );
2302 $this->mTitle
->mArticleID
= 0;
2307 * Roll back the most recent consecutive set of edits to a page
2308 * from the same user; fails if there are no eligible edits to
2309 * roll back to, e.g. user is the sole contributor. This function
2310 * performs permissions checks on $wgUser, then calls commitRollback()
2311 * to do the dirty work
2313 * @param string $fromP - Name of the user whose edits to rollback.
2314 * @param string $summary - Custom summary. Set to default summary if empty.
2315 * @param string $token - Rollback token.
2316 * @param bool $bot - If true, mark all reverted edits as bot.
2318 * @param array $resultDetails contains result-specific array of additional values
2319 * 'alreadyrolled' : 'current' (rev)
2320 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2322 * @return array of errors, each error formatted as
2323 * array(messagekey, param1, param2, ...).
2324 * On success, the array is empty. This array can also be passed to
2325 * OutputPage::showPermissionsErrorPage().
2327 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2329 $resultDetails = null;
2332 $errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2333 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2334 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2335 $errors[] = array( 'sessionfailure' );
2337 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2338 $errors[] = array( 'actionthrottledtext' );
2340 # If there were errors, bail out now
2344 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2348 * Backend implementation of doRollback(), please refer there for parameter
2349 * and return value documentation
2351 * NOTE: This function does NOT check ANY permissions, it just commits the
2352 * rollback to the DB Therefore, you should only call this function direct-
2353 * ly if you want to use custom permissions checks. If you don't, use
2354 * doRollback() instead.
2356 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2357 global $wgUseRCPatrol, $wgUser;
2358 $dbw = wfGetDB( DB_MASTER
);
2360 if( wfReadOnly() ) {
2361 return array( array( 'readonlytext' ) );
2364 # Get the last editor
2365 $current = Revision
::newFromTitle( $this->mTitle
);
2366 if( is_null( $current ) ) {
2367 # Something wrong... no page?
2368 return array(array('notanarticle'));
2371 $from = str_replace( '_', ' ', $fromP );
2372 if( $from != $current->getUserText() ) {
2373 $resultDetails = array( 'current' => $current );
2374 return array(array('alreadyrolled',
2375 htmlspecialchars($this->mTitle
->getPrefixedText()),
2376 htmlspecialchars($fromP),
2377 htmlspecialchars($current->getUserText())
2381 # Get the last edit not by this guy
2382 $user = intval( $current->getUser() );
2383 $user_text = $dbw->addQuotes( $current->getUserText() );
2384 $s = $dbw->selectRow( 'revision',
2385 array( 'rev_id', 'rev_timestamp' ),
2386 array( 'rev_page' => $current->getPage(),
2387 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2389 array( 'USE INDEX' => 'page_timestamp',
2390 'ORDER BY' => 'rev_timestamp DESC' )
2392 if( $s === false ) {
2393 # No one else ever edited this page
2394 return array(array('cantrollback'));
2398 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2399 # Mark all reverted edits as bot
2402 if ( $wgUseRCPatrol ) {
2403 # Mark all reverted edits as patrolled
2404 $set['rc_patrolled'] = 1;
2408 $dbw->update( 'recentchanges', $set,
2410 'rc_cur_id' => $current->getPage(),
2411 'rc_user_text' => $current->getUserText(),
2412 "rc_timestamp > '{$s->rev_timestamp}'",
2417 # Generate the edit summary if necessary
2418 $target = Revision
::newFromId( $s->rev_id
);
2419 if( empty( $summary ) )
2422 $summary = wfMsgForContent( 'revertpage',
2423 $target->getUserText(), $from,
2424 $s->rev_id
, $wgLang->timeanddate(wfTimestamp(TS_MW
, $s->rev_timestamp
), true),
2425 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2430 $flags = EDIT_UPDATE
;
2432 if ($wgUser->isAllowed('minoredit'))
2433 $flags |
= EDIT_MINOR
;
2435 if( $bot && ($wgUser->isAllowed('markbotedits') ||
$wgUser->isAllowed('bot')) )
2436 $flags |
= EDIT_FORCE_BOT
;
2437 $this->doEdit( $target->getText(), $summary, $flags );
2439 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2441 $resultDetails = array(
2442 'summary' => $summary,
2443 'current' => $current,
2444 'target' => $target,
2450 * User interface for rollback operations
2452 function rollback() {
2453 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2456 $result = $this->doRollback(
2457 $wgRequest->getVal( 'from' ),
2458 $wgRequest->getText( 'summary' ),
2459 $wgRequest->getVal( 'token' ),
2460 $wgRequest->getBool( 'bot' ),
2464 if( in_array( array( 'blocked' ), $result ) ) {
2465 $wgOut->blockedPage();
2468 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2469 $wgOut->rateLimited();
2472 # Display permissions errors before read-only message -- there's no
2473 # point in misleading the user into thinking the inability to rollback
2474 # is only temporary.
2475 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2476 # array_diff is completely broken for arrays of arrays, sigh. Re-
2477 # move any 'readonlytext' error manually.
2479 foreach( $result as $error ) {
2480 if( $error != array( 'readonlytext' ) ) {
2484 $wgOut->showPermissionsErrorPage( $out );
2487 if( $result == array( array('readonlytext') ) ) {
2488 $wgOut->readOnlyPage();
2492 $current = $details['current'];
2493 $target = $details['target'];
2494 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2495 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2496 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2497 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2498 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2499 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2500 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2501 $wgOut->returnToMain( false, $this->mTitle
);
2506 * Do standard deferred updates after page view
2509 function viewUpdates() {
2510 global $wgDeferredUpdateList;
2512 if ( 0 != $this->getID() ) {
2513 global $wgDisableCounters;
2514 if( !$wgDisableCounters ) {
2515 Article
::incViewCount( $this->getID() );
2516 $u = new SiteStatsUpdate( 1, 0, 0 );
2517 array_push( $wgDeferredUpdateList, $u );
2521 # Update newtalk / watchlist notification status
2523 $wgUser->clearNotification( $this->mTitle
);
2527 * Prepare text which is about to be saved.
2528 * Returns a stdclass with source, pst and output members
2530 function prepareTextForEdit( $text, $revid=null ) {
2531 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2533 return $this->mPreparedEdit
;
2536 $edit = (object)array();
2537 $edit->revid
= $revid;
2538 $edit->newText
= $text;
2539 $edit->pst
= $this->preSaveTransform( $text );
2540 $options = new ParserOptions
;
2541 $options->setTidy( true );
2542 $options->enableLimitReport();
2543 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2544 $edit->oldText
= $this->getContent();
2545 $this->mPreparedEdit
= $edit;
2550 * Do standard deferred updates after page edit.
2551 * Update links tables, site stats, search index and message cache.
2552 * Every 100th edit, prune the recent changes table.
2555 * @param $text New text of the article
2556 * @param $summary Edit summary
2557 * @param $minoredit Minor edit
2558 * @param $timestamp_of_pagechange Timestamp associated with the page change
2559 * @param $newid rev_id value of the new revision
2560 * @param $changed Whether or not the content actually changed
2562 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2563 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2565 wfProfileIn( __METHOD__
);
2568 # Be careful not to double-PST: $text is usually already PST-ed once
2569 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2570 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2571 $editInfo = $this->prepareTextForEdit( $text, $newid );
2573 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2574 $editInfo = $this->mPreparedEdit
;
2577 # Save it to the parser cache
2578 if ( $wgEnableParserCache ) {
2579 $parserCache =& ParserCache
::singleton();
2580 $parserCache->save( $editInfo->output
, $this, $wgUser );
2583 # Update the links tables
2584 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2587 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2588 if ( 0 == mt_rand( 0, 99 ) ) {
2589 // Flush old entries from the `recentchanges` table; we do this on
2590 // random requests so as to avoid an increase in writes for no good reason
2592 $dbw = wfGetDB( DB_MASTER
);
2593 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2594 $recentchanges = $dbw->tableName( 'recentchanges' );
2595 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2596 $dbw->query( $sql );
2600 $id = $this->getID();
2601 $title = $this->mTitle
->getPrefixedDBkey();
2602 $shortTitle = $this->mTitle
->getDBkey();
2605 wfProfileOut( __METHOD__
);
2609 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2610 array_push( $wgDeferredUpdateList, $u );
2611 $u = new SearchUpdate( $id, $title, $text );
2612 array_push( $wgDeferredUpdateList, $u );
2614 # If this is another user's talk page, update newtalk
2615 # Don't do this if $changed = false otherwise some idiot can null-edit a
2616 # load of user talk pages and piss people off, nor if it's a minor edit
2617 # by a properly-flagged bot.
2618 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2619 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2620 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2621 $other = User
::newFromName( $shortTitle );
2622 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2623 // An anonymous user
2624 $other = new User();
2625 $other->setName( $shortTitle );
2628 $other->setNewtalk( true );
2633 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2634 $wgMessageCache->replace( $shortTitle, $text );
2637 wfProfileOut( __METHOD__
);
2641 * Perform article updates on a special page creation.
2643 * @param Revision $rev
2645 * @todo This is a shitty interface function. Kill it and replace the
2646 * other shitty functions like editUpdates and such so it's not needed
2649 function createUpdates( $rev ) {
2650 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2651 $this->mTotalAdjustment
= 1;
2652 $this->editUpdates( $rev->getText(), $rev->getComment(),
2653 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2657 * Generate the navigation links when browsing through an article revisions
2658 * It shows the information as:
2659 * Revision as of \<date\>; view current revision
2660 * \<- Previous version | Next Version -\>
2663 * @param string $oldid Revision ID of this article revision
2665 function setOldSubtitle( $oldid=0 ) {
2666 global $wgLang, $wgOut, $wgUser;
2668 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2672 $revision = Revision
::newFromId( $oldid );
2674 $current = ( $oldid == $this->mLatest
);
2675 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2676 $sk = $wgUser->getSkin();
2678 ?
wfMsg( 'currentrevisionlink' )
2679 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2682 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2683 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2685 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2686 : wfMsg( 'previousrevision' );
2688 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2690 $nextlink = $current
2691 ?
wfMsg( 'nextrevision' )
2692 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2693 $nextdiff = $current
2695 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2697 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2698 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2700 $m = wfMsg( 'revision-info-current' );
2701 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2702 ?
'revision-info-current'
2705 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2706 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2707 $wgOut->setSubtitle( $r );
2711 * This function is called right before saving the wikitext,
2712 * so we can do things like signatures and links-in-context.
2714 * @param string $text
2716 function preSaveTransform( $text ) {
2717 global $wgParser, $wgUser;
2718 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2721 /* Caching functions */
2724 * checkLastModified returns true if it has taken care of all
2725 * output to the client that is necessary for this request.
2726 * (that is, it has sent a cached version of the page)
2728 function tryFileCache() {
2729 static $called = false;
2731 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2735 if($this->isFileCacheable()) {
2736 $touched = $this->mTouched
;
2737 $cache = new HTMLFileCache( $this->mTitle
);
2738 if($cache->isFileCacheGood( $touched )) {
2739 wfDebug( "Article::tryFileCache(): about to load file\n" );
2740 $cache->loadFromFileCache();
2743 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2744 ob_start( array(&$cache, 'saveToFileCache' ) );
2747 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2752 * Check if the page can be cached
2755 function isFileCacheable() {
2756 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2757 $action = $wgRequest->getVal( 'action' );
2758 $oldid = $wgRequest->getVal( 'oldid' );
2759 $diff = $wgRequest->getVal( 'diff' );
2760 $redirect = $wgRequest->getVal( 'redirect' );
2761 $printable = $wgRequest->getVal( 'printable' );
2762 $page = $wgRequest->getVal( 'page' );
2764 //check for non-standard user language; this covers uselang,
2765 //and extensions for auto-detecting user language.
2766 $ulang = $wgLang->getCode();
2767 $clang = $wgContLang->getCode();
2769 $cacheable = $wgUseFileCache
2770 && (!$wgShowIPinHeader)
2771 && ($this->getID() != 0)
2772 && ($wgUser->isAnon())
2773 && (!$wgUser->getNewtalk())
2774 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2775 && (empty( $action ) ||
$action == 'view')
2778 && (!isset($redirect))
2779 && (!isset($printable))
2781 && (!$this->mRedirectedFrom
)
2782 && ($ulang === $clang);
2785 //extension may have reason to disable file caching on some pages.
2786 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2793 * Loads page_touched and returns a value indicating if it should be used
2796 function checkTouched() {
2797 if( !$this->mDataLoaded
) {
2798 $this->loadPageData();
2800 return !$this->mIsRedirect
;
2804 * Get the page_touched field
2806 function getTouched() {
2807 # Ensure that page data has been loaded
2808 if( !$this->mDataLoaded
) {
2809 $this->loadPageData();
2811 return $this->mTouched
;
2815 * Get the page_latest field
2817 function getLatest() {
2818 if ( !$this->mDataLoaded
) {
2819 $this->loadPageData();
2821 return $this->mLatest
;
2825 * Edit an article without doing all that other stuff
2826 * The article must already exist; link tables etc
2827 * are not updated, caches are not flushed.
2829 * @param string $text text submitted
2830 * @param string $comment comment submitted
2831 * @param bool $minor whereas it's a minor modification
2833 function quickEdit( $text, $comment = '', $minor = 0 ) {
2834 wfProfileIn( __METHOD__
);
2836 $dbw = wfGetDB( DB_MASTER
);
2838 $revision = new Revision( array(
2839 'page' => $this->getId(),
2841 'comment' => $comment,
2842 'minor_edit' => $minor ?
1 : 0,
2844 $revision->insertOn( $dbw );
2845 $this->updateRevisionOn( $dbw, $revision );
2848 wfProfileOut( __METHOD__
);
2852 * Used to increment the view counter
2855 * @param integer $id article id
2857 function incViewCount( $id ) {
2858 $id = intval( $id );
2859 global $wgHitcounterUpdateFreq, $wgDBtype;
2861 $dbw = wfGetDB( DB_MASTER
);
2862 $pageTable = $dbw->tableName( 'page' );
2863 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2864 $acchitsTable = $dbw->tableName( 'acchits' );
2866 if( $wgHitcounterUpdateFreq <= 1 ) {
2867 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2871 # Not important enough to warrant an error page in case of failure
2872 $oldignore = $dbw->ignoreErrors( true );
2874 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2876 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2877 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2878 # Most of the time (or on SQL errors), skip row count check
2879 $dbw->ignoreErrors( $oldignore );
2883 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2884 $row = $dbw->fetchObject( $res );
2885 $rown = intval( $row->n
);
2886 if( $rown >= $wgHitcounterUpdateFreq ){
2887 wfProfileIn( 'Article::incViewCount-collect' );
2888 $old_user_abort = ignore_user_abort( true );
2890 if ($wgDBtype == 'mysql')
2891 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2892 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2893 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2894 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2896 $dbw->query("DELETE FROM $hitcounterTable");
2897 if ($wgDBtype == 'mysql') {
2898 $dbw->query('UNLOCK TABLES');
2899 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2900 'WHERE page_id = hc_id');
2903 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2904 "FROM $acchitsTable WHERE page_id = hc_id");
2906 $dbw->query("DROP TABLE $acchitsTable");
2908 ignore_user_abort( $old_user_abort );
2909 wfProfileOut( 'Article::incViewCount-collect' );
2911 $dbw->ignoreErrors( $oldignore );
2915 * The onArticle*() functions are supposed to be a kind of hooks
2916 * which should be called whenever any of the specified actions
2919 * This is a good place to put code to clear caches, for instance.
2921 * This is called on page move and undelete, as well as edit
2923 * @param $title_obj a title object
2926 static function onArticleCreate($title) {
2927 # The talk page isn't in the regular link tables, so we need to update manually:
2928 if ( $title->isTalkPage() ) {
2929 $other = $title->getSubjectPage();
2931 $other = $title->getTalkPage();
2933 $other->invalidateCache();
2934 $other->purgeSquid();
2936 $title->touchLinks();
2937 $title->purgeSquid();
2938 $title->deleteTitleProtection();
2941 static function onArticleDelete( $title ) {
2942 global $wgUseFileCache, $wgMessageCache;
2944 $title->touchLinks();
2945 $title->purgeSquid();
2948 if ( $wgUseFileCache ) {
2949 $cm = new HTMLFileCache( $title );
2950 @unlink
( $cm->fileCacheName() );
2953 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2954 $wgMessageCache->replace( $title->getDBkey(), false );
2959 * Purge caches on page update etc
2961 static function onArticleEdit( $title ) {
2962 global $wgDeferredUpdateList, $wgUseFileCache;
2964 // Invalidate caches of articles which include this page
2965 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
2967 // Invalidate the caches of all pages which redirect here
2968 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
2970 # Purge squid for this page only
2971 $title->purgeSquid();
2974 if ( $wgUseFileCache ) {
2975 $cm = new HTMLFileCache( $title );
2976 @unlink
( $cm->fileCacheName() );
2983 * Info about this page
2984 * Called for ?action=info when $wgAllowPageInfo is on.
2989 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2991 if ( !$wgAllowPageInfo ) {
2992 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2996 $page = $this->mTitle
->getSubjectPage();
2998 $wgOut->setPagetitle( $page->getPrefixedText() );
2999 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3000 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3002 if( !$this->mTitle
->exists() ) {
3003 $wgOut->addHtml( '<div class="noarticletext">' );
3004 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
3005 // This doesn't quite make sense; the user is asking for
3006 // information about the _page_, not the message... -- RC
3007 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
3009 $msg = $wgUser->isLoggedIn()
3011 : 'noarticletextanon';
3012 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3014 $wgOut->addHtml( '</div>' );
3016 $dbr = wfGetDB( DB_SLAVE
);
3018 'wl_title' => $page->getDBkey(),
3019 'wl_namespace' => $page->getNamespace() );
3020 $numwatchers = $dbr->selectField(
3025 $this->getSelectOptions() );
3027 $pageInfo = $this->pageCountInfo( $page );
3028 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3030 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3031 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3033 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3035 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3037 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3039 $wgOut->addHTML( '</ul>' );
3045 * Return the total number of edits and number of unique editors
3046 * on a given page. If page does not exist, returns false.
3048 * @param Title $title
3052 function pageCountInfo( $title ) {
3053 $id = $title->getArticleId();
3058 $dbr = wfGetDB( DB_SLAVE
);
3060 $rev_clause = array( 'rev_page' => $id );
3062 $edits = $dbr->selectField(
3067 $this->getSelectOptions() );
3069 $authors = $dbr->selectField(
3071 'COUNT(DISTINCT rev_user_text)',
3074 $this->getSelectOptions() );
3076 return array( 'edits' => $edits, 'authors' => $authors );
3080 * Return a list of templates used by this article.
3081 * Uses the templatelinks table
3083 * @return array Array of Title objects
3085 function getUsedTemplates() {
3087 $id = $this->mTitle
->getArticleID();
3092 $dbr = wfGetDB( DB_SLAVE
);
3093 $res = $dbr->select( array( 'templatelinks' ),
3094 array( 'tl_namespace', 'tl_title' ),
3095 array( 'tl_from' => $id ),
3096 'Article:getUsedTemplates' );
3097 if ( false !== $res ) {
3098 if ( $dbr->numRows( $res ) ) {
3099 while ( $row = $dbr->fetchObject( $res ) ) {
3100 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3104 $dbr->freeResult( $res );
3109 * Return an auto-generated summary if the text provided is a redirect.
3111 * @param string $text The wikitext to check
3112 * @return string '' or an appropriate summary
3114 public static function getRedirectAutosummary( $text ) {
3115 $rt = Title
::newFromRedirect( $text );
3116 if( is_object( $rt ) )
3117 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3123 * Return an auto-generated summary if the new text is much shorter than
3126 * @param string $oldtext The previous text of the page
3127 * @param string $text The submitted text of the page
3128 * @return string An appropriate autosummary, or an empty string.
3130 public static function getBlankingAutosummary( $oldtext, $text ) {
3131 if ($oldtext!='' && $text=='') {
3132 return wfMsgForContent('autosumm-blank');
3133 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3134 #Removing more than 90% of the article
3136 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3137 return wfMsgForContent('autosumm-replace', $truncatedtext);
3144 * Return an applicable autosummary if one exists for the given edit.
3145 * @param string $oldtext The previous text of the page.
3146 * @param string $newtext The submitted text of the page.
3147 * @param bitmask $flags A bitmask of flags submitted for the edit.
3148 * @return string An appropriate autosummary, or an empty string.
3150 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3152 # This code is UGLY UGLY UGLY.
3153 # Somebody PLEASE come up with a more elegant way to do it.
3155 #Redirect autosummaries
3156 $summary = self
::getRedirectAutosummary( $newtext );
3161 #Blanking autosummaries
3162 if (!($flags & EDIT_NEW
))
3163 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3168 #New page autosummaries
3169 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3170 #If they're making a new article, give its text, truncated, in the summary.
3172 $truncatedtext = $wgContLang->truncate(
3173 str_replace("\n", ' ', $newtext),
3174 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3176 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3186 * Add the primary page-view wikitext to the output buffer
3187 * Saves the text into the parser cache if possible.
3188 * Updates templatelinks if it is out of date.
3190 * @param string $text
3191 * @param bool $cache
3193 public function outputWikiText( $text, $cache = true ) {
3194 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3196 $popts = $wgOut->parserOptions();
3197 $popts->setTidy(true);
3198 $popts->enableLimitReport();
3199 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3200 $popts, true, true, $this->getRevIdFetched() );
3201 $popts->setTidy(false);
3202 $popts->enableLimitReport( false );
3203 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3204 $parserCache =& ParserCache
::singleton();
3205 $parserCache->save( $parserOutput, $this, $wgUser );
3208 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3209 // templatelinks table may have become out of sync,
3210 // especially if using variable-based transclusions.
3211 // For paranoia, check if things have changed and if
3212 // so apply updates to the database. This will ensure
3213 // that cascaded protections apply as soon as the changes
3216 # Get templates from templatelinks
3217 $id = $this->mTitle
->getArticleID();
3219 $tlTemplates = array();
3221 $dbr = wfGetDB( DB_SLAVE
);
3222 $res = $dbr->select( array( 'templatelinks' ),
3223 array( 'tl_namespace', 'tl_title' ),
3224 array( 'tl_from' => $id ),
3225 'Article:getUsedTemplates' );
3229 if ( false !== $res ) {
3230 if ( $dbr->numRows( $res ) ) {
3231 while ( $row = $dbr->fetchObject( $res ) ) {
3232 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3237 # Get templates from parser output.
3238 $poTemplates_allns = $parserOutput->getTemplates();
3240 $poTemplates = array ();
3241 foreach ( $poTemplates_allns as $ns_templates ) {
3242 $poTemplates = array_merge( $poTemplates, $ns_templates );
3246 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3248 if ( count( $templates_diff ) > 0 ) {
3249 # Whee, link updates time.
3250 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3252 $dbw = wfGetDb( DB_MASTER
);
3261 $wgOut->addParserOutput( $parserOutput );