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
50 const RATE_LIMITED
= 8;
53 * Constructor and clear the article
54 * @param $title Reference to a Title object.
55 * @param $oldId Integer revision ID, null to fetch from request, zero for current
57 function __construct( &$title, $oldId = null ) {
58 $this->mTitle
=& $title;
59 $this->mOldId
= $oldId;
64 * Tell the page view functions that this view was redirected
65 * from another page on the wiki.
66 * @param $from Title object.
68 function setRedirectedFrom( $from ) {
69 $this->mRedirectedFrom
= $from;
73 * @return mixed false, Title of in-wiki target, or string with URL
75 function followRedirect() {
76 $text = $this->getContent();
77 $rt = Title
::newFromRedirect( $text );
79 # process if title object is valid and not special:userlogout
81 if( $rt->getInterwiki() != '' ) {
82 if( $rt->isLocal() ) {
83 // Offsite wikis need an HTTP redirect.
85 // This can be hard to reverse and may produce loops,
86 // so they may be disabled in the site configuration.
88 $source = $this->mTitle
->getFullURL( 'redirect=no' );
89 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
92 if( $rt->getNamespace() == NS_SPECIAL
) {
93 // Gotta handle redirects to special pages differently:
94 // Fill the HTTP response "Location" header and ignore
95 // the rest of the page we're on.
97 // This can be hard to reverse, so they may be disabled.
99 if( $rt->isSpecial( 'Userlogout' ) ) {
102 return $rt->getFullURL();
109 // No or invalid redirect
114 * get the title object of the article
116 function getTitle() {
117 return $this->mTitle
;
125 $this->mDataLoaded
= false;
126 $this->mContentLoaded
= false;
128 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
129 $this->mRedirectedFrom
= null; # Title object if set
131 $this->mTimestamp
= $this->mComment
= '';
132 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
133 $this->mTouched
= '19700101000000';
134 $this->mForUpdate
= false;
135 $this->mIsRedirect
= false;
136 $this->mRevIdFetched
= 0;
137 $this->mRedirectUrl
= false;
138 $this->mLatest
= false;
139 $this->mPreparedEdit
= false;
143 * Note that getContent/loadContent do not follow redirects anymore.
144 * If you need to fetch redirectable content easily, try
145 * the shortcut in Article::followContent()
147 * @todo There are still side-effects in this!
148 * In general, you should use the Revision class, not Article,
149 * to fetch text for purposes other than page views.
151 * @return Return the text of this revision
153 function getContent() {
154 global $wgUser, $wgOut;
156 wfProfileIn( __METHOD__
);
158 if ( 0 == $this->getID() ) {
159 wfProfileOut( __METHOD__
);
160 $wgOut->setRobotpolicy( 'noindex,nofollow' );
162 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
163 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
165 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
168 return "<div class='noarticletext'>$ret</div>";
170 $this->loadContent();
171 wfProfileOut( __METHOD__
);
172 return $this->mContent
;
177 * This function returns the text of a section, specified by a number ($section).
178 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
179 * the first section before any such heading (section 0).
181 * If a section contains subsections, these are also returned.
183 * @param $text String: text to look in
184 * @param $section Integer: section number
185 * @return string text of the requested section
188 function getSection($text,$section) {
190 return $wgParser->getSection( $text, $section );
194 * @return int The oldid of the article that is to be shown, 0 for the
197 function getOldID() {
198 if ( is_null( $this->mOldId
) ) {
199 $this->mOldId
= $this->getOldIDFromRequest();
201 return $this->mOldId
;
205 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
207 * @return int The old id for the request
209 function getOldIDFromRequest() {
211 $this->mRedirectUrl
= false;
212 $oldid = $wgRequest->getVal( 'oldid' );
213 if ( isset( $oldid ) ) {
214 $oldid = intval( $oldid );
215 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
216 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
220 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
222 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
223 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
241 * Load the revision (including text) into this object
243 function loadContent() {
244 if ( $this->mContentLoaded
) return;
247 $oldid = $this->getOldID();
249 # Pre-fill content with error message so that if something
250 # fails we'll have something telling us what we intended.
251 $this->mOldId
= $oldid;
252 $this->fetchContent( $oldid );
257 * Fetch a page record with the given conditions
258 * @param Database $dbr
259 * @param array $conditions
262 function pageData( $dbr, $conditions ) {
276 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
277 $row = $dbr->selectRow(
283 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
288 * @param Database $dbr
289 * @param Title $title
291 function pageDataFromTitle( $dbr, $title ) {
292 return $this->pageData( $dbr, array(
293 'page_namespace' => $title->getNamespace(),
294 'page_title' => $title->getDBkey() ) );
298 * @param Database $dbr
301 function pageDataFromId( $dbr, $id ) {
302 return $this->pageData( $dbr, array( 'page_id' => $id ) );
306 * Set the general counter, title etc data loaded from
309 * @param object $data
312 function loadPageData( $data = 'fromdb' ) {
313 if ( $data === 'fromdb' ) {
314 $dbr = $this->getDB();
315 $data = $this->pageDataFromId( $dbr, $this->getId() );
318 $lc =& LinkCache
::singleton();
320 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
322 $this->mTitle
->mArticleID
= $data->page_id
;
324 # Old-fashioned restrictions.
325 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
327 $this->mCounter
= $data->page_counter
;
328 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
329 $this->mIsRedirect
= $data->page_is_redirect
;
330 $this->mLatest
= $data->page_latest
;
332 if ( is_object( $this->mTitle
) ) {
333 $lc->addBadLinkObj( $this->mTitle
);
335 $this->mTitle
->mArticleID
= 0;
338 $this->mDataLoaded
= true;
342 * Get text of an article from database
343 * Does *NOT* follow redirects.
344 * @param int $oldid 0 for whatever the latest revision is
347 function fetchContent( $oldid = 0 ) {
348 if ( $this->mContentLoaded
) {
349 return $this->mContent
;
352 $dbr = $this->getDB();
354 # Pre-fill content with error message so that if something
355 # fails we'll have something telling us what we intended.
356 $t = $this->mTitle
->getPrefixedText();
358 $t .= ',oldid='.$oldid;
360 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
363 $revision = Revision
::newFromId( $oldid );
364 if( is_null( $revision ) ) {
365 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
368 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
370 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
373 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
374 $this->loadPageData( $data );
376 if( !$this->mDataLoaded
) {
377 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
379 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
382 $this->loadPageData( $data );
384 $revision = Revision
::newFromId( $this->mLatest
);
385 if( is_null( $revision ) ) {
386 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
391 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
392 // We should instead work with the Revision object when we need it...
393 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
394 //$this->mContent = $revision->getText();
396 $this->mUser
= $revision->getUser();
397 $this->mUserText
= $revision->getUserText();
398 $this->mComment
= $revision->getComment();
399 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
401 $this->mRevIdFetched
= $revision->getID();
402 $this->mContentLoaded
= true;
403 $this->mRevision
=& $revision;
405 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
407 return $this->mContent
;
411 * Read/write accessor to select FOR UPDATE
413 * @param $x Mixed: FIXME
415 function forUpdate( $x = NULL ) {
416 return wfSetVar( $this->mForUpdate
, $x );
420 * Get the database which should be used for reads
425 return wfGetDB( DB_MASTER
);
429 * Get options for all SELECT statements
431 * @param $options Array: an optional options array which'll be appended to
433 * @return Array: options
435 function getSelectOptions( $options = '' ) {
436 if ( $this->mForUpdate
) {
437 if ( is_array( $options ) ) {
438 $options[] = 'FOR UPDATE';
440 $options = 'FOR UPDATE';
447 * @return int Page ID
450 if( $this->mTitle
) {
451 return $this->mTitle
->getArticleID();
458 * @return bool Whether or not the page exists in the database
461 return $this->getId() != 0;
465 * @return int The view count for the page
467 function getCount() {
468 if ( -1 == $this->mCounter
) {
469 $id = $this->getID();
473 $dbr = wfGetDB( DB_SLAVE
);
474 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
475 'Article::getCount', $this->getSelectOptions() );
478 return $this->mCounter
;
482 * Determine whether a page would be suitable for being counted as an
483 * article in the site_stats table based on the title & its content
485 * @param $text String: text to analyze
488 function isCountable( $text ) {
489 global $wgUseCommaCount;
491 $token = $wgUseCommaCount ?
',' : '[[';
493 $this->mTitle
->isContentPage()
494 && !$this->isRedirect( $text )
495 && in_string( $token, $text );
499 * Tests if the article text represents a redirect
501 * @param $text String: FIXME
504 function isRedirect( $text = false ) {
505 if ( $text === false ) {
506 $this->loadContent();
507 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
509 $titleObj = Title
::newFromRedirect( $text );
511 return $titleObj !== NULL;
515 * Returns true if the currently-referenced revision is the current edit
516 * to this page (and it exists).
519 function isCurrent() {
520 # If no oldid, this is the current version.
521 if ($this->getOldID() == 0)
524 return $this->exists() &&
525 isset( $this->mRevision
) &&
526 $this->mRevision
->isCurrent();
530 * Loads everything except the text
531 * This isn't necessary for all uses, so it's only done if needed.
534 function loadLastEdit() {
535 if ( -1 != $this->mUser
)
538 # New or non-existent articles have no user information
539 $id = $this->getID();
540 if ( 0 == $id ) return;
542 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
543 if( !is_null( $this->mLastRevision
) ) {
544 $this->mUser
= $this->mLastRevision
->getUser();
545 $this->mUserText
= $this->mLastRevision
->getUserText();
546 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
547 $this->mComment
= $this->mLastRevision
->getComment();
548 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
549 $this->mRevIdFetched
= $this->mLastRevision
->getID();
553 function getTimestamp() {
554 // Check if the field has been filled by ParserCache::get()
555 if ( !$this->mTimestamp
) {
556 $this->loadLastEdit();
558 return wfTimestamp(TS_MW
, $this->mTimestamp
);
562 $this->loadLastEdit();
566 function getUserText() {
567 $this->loadLastEdit();
568 return $this->mUserText
;
571 function getComment() {
572 $this->loadLastEdit();
573 return $this->mComment
;
576 function getMinorEdit() {
577 $this->loadLastEdit();
578 return $this->mMinorEdit
;
581 function getRevIdFetched() {
582 $this->loadLastEdit();
583 return $this->mRevIdFetched
;
587 * @todo Document, fixme $offset never used.
588 * @param $limit Integer: default 0.
589 * @param $offset Integer: default 0.
591 function getContributors($limit = 0, $offset = 0) {
592 # XXX: this is expensive; cache this info somewhere.
595 $dbr = wfGetDB( DB_SLAVE
);
596 $revTable = $dbr->tableName( 'revision' );
597 $userTable = $dbr->tableName( 'user' );
598 $user = $this->getUser();
599 $pageId = $this->getId();
601 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
602 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
603 WHERE rev_page = $pageId
604 AND rev_user != $user
605 GROUP BY rev_user, rev_user_text, user_real_name
606 ORDER BY timestamp DESC";
608 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
609 $sql .= ' '. $this->getSelectOptions();
611 $res = $dbr->query($sql, __METHOD__
);
613 while ( $line = $dbr->fetchObject( $res ) ) {
614 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
617 $dbr->freeResult($res);
622 * This is the default action of the script: just view the page of
626 global $wgUser, $wgOut, $wgRequest, $wgContLang;
627 global $wgEnableParserCache, $wgStylePath, $wgParser;
628 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
629 $sk = $wgUser->getSkin();
631 wfProfileIn( __METHOD__
);
633 $parserCache =& ParserCache
::singleton();
634 $ns = $this->mTitle
->getNamespace(); # shortcut
636 # Get variables from query string
637 $oldid = $this->getOldID();
639 # getOldID may want us to redirect somewhere else
640 if ( $this->mRedirectUrl
) {
641 $wgOut->redirect( $this->mRedirectUrl
);
642 wfProfileOut( __METHOD__
);
646 $diff = $wgRequest->getVal( 'diff' );
647 $rcid = $wgRequest->getVal( 'rcid' );
648 $rdfrom = $wgRequest->getVal( 'rdfrom' );
649 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
650 $purge = $wgRequest->getVal( 'action' ) == 'purge';
652 $wgOut->setArticleFlag( true );
654 # Discourage indexing of printable versions, but encourage following
655 if( $wgOut->isPrintable() ) {
656 $policy = 'noindex,follow';
657 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
658 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
659 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
660 # Honour customised robot policies for this namespace
661 $policy = $wgNamespaceRobotPolicies[$ns];
663 # Default to encourage indexing and following links
664 $policy = 'index,follow';
666 $wgOut->setRobotPolicy( $policy );
668 # If we got diff and oldid in the query, we want to see a
669 # diff page instead of the article.
671 if ( !is_null( $diff ) ) {
672 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
674 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
675 // DifferenceEngine directly fetched the revision:
676 $this->mRevIdFetched
= $de->mNewid
;
677 $de->showDiffPage( $diffOnly );
679 // Needed to get the page's current revision
680 $this->loadPageData();
681 if( $diff == 0 ||
$diff == $this->mLatest
) {
682 # Run view updates for current revision only
683 $this->viewUpdates();
685 wfProfileOut( __METHOD__
);
689 if ( empty( $oldid ) && $this->checkTouched() ) {
690 $wgOut->setETag($parserCache->getETag($this, $wgUser));
692 if( $wgOut->checkLastModified( $this->mTouched
) ){
693 wfProfileOut( __METHOD__
);
695 } else if ( $this->tryFileCache() ) {
696 # tell wgOut that output is taken care of
698 $this->viewUpdates();
699 wfProfileOut( __METHOD__
);
704 # Should the parser cache be used?
705 $pcache = $wgEnableParserCache
706 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
709 && !$this->mTitle
->isCssOrJsPage()
710 && !$this->mTitle
->isCssJsSubpage();
711 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
712 if ( $wgUser->getOption( 'stubthreshold' ) ) {
713 wfIncrStats( 'pcache_miss_stub' );
716 $wasRedirected = false;
717 if ( isset( $this->mRedirectedFrom
) ) {
718 // This is an internally redirected page view.
719 // We'll need a backlink to the source page for navigation.
720 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
721 $sk = $wgUser->getSkin();
722 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
723 $s = wfMsg( 'redirectedfrom', $redir );
724 $wgOut->setSubtitle( $s );
726 // Set the fragment if one was specified in the redirect
727 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
728 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
729 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
731 $wasRedirected = true;
733 } elseif ( !empty( $rdfrom ) ) {
734 // This is an externally redirected view, from some other wiki.
735 // If it was reported from a trusted site, supply a backlink.
736 global $wgRedirectSources;
737 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
738 $sk = $wgUser->getSkin();
739 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
740 $s = wfMsg( 'redirectedfrom', $redir );
741 $wgOut->setSubtitle( $s );
742 $wasRedirected = true;
747 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
749 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
750 // Ensure that UI elements requiring revision ID have
751 // the correct version information.
752 $wgOut->setRevisionId( $this->mLatest
);
756 if ( !$outputDone ) {
757 $text = $this->getContent();
758 if ( $text === false ) {
759 # Failed to load, replace text with error message
760 $t = $this->mTitle
->getPrefixedText();
762 $t .= ',oldid='.$oldid;
763 $text = wfMsg( 'missingarticle', $t );
765 $text = wfMsg( 'noarticletext', $t );
769 # Another whitelist check in case oldid is altering the title
770 if ( !$this->mTitle
->userCanRead() ) {
771 $wgOut->loginToUse();
776 # We're looking at an old revision
778 if ( !empty( $oldid ) ) {
779 $wgOut->setRobotpolicy( 'noindex,nofollow' );
780 if( is_null( $this->mRevision
) ) {
781 // FIXME: This would be a nice place to load the 'no such page' text.
783 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
784 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
785 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
786 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
787 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
790 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
791 // and we are allowed to see...
799 $wgOut->setRevisionId( $this->getRevIdFetched() );
801 // Pages containing custom CSS or JavaScript get special treatment
802 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
803 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
805 // Give hooks a chance to customise the output
806 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
807 // Wrap the whole lot in a <pre> and don't parse
809 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
810 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
811 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
812 $wgOut->addHtml( "\n</pre>\n" );
817 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
819 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
820 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
821 # Don't overwrite the subtitle if this was an old revision
822 if( !$wasRedirected && $this->isCurrent() ) {
823 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
825 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
827 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
828 '<span class="redirectText">'.$link.'</span>' );
830 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
831 $wgOut->addParserOutputNoText( $parseout );
832 } else if ( $pcache ) {
833 # Display content and save to parser cache
834 $this->outputWikiText( $text );
836 # Display content, don't attempt to save to parser cache
837 # Don't show section-edit links on old revisions... this way lies madness.
838 if( !$this->isCurrent() ) {
839 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
841 # Display content and don't save to parser cache
842 # With timing hack -- TS 2006-07-26
844 $this->outputWikiText( $text, false );
849 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
850 $this->mTitle
->getPrefixedDBkey()));
853 if( !$this->isCurrent() ) {
854 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
859 /* title may have been set from the cache */
860 $t = $wgOut->getPageTitle();
862 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
865 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
866 if( $ns == NS_USER_TALK
&&
867 User
::isIP( $this->mTitle
->getText() ) ) {
868 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
871 # If we have been passed an &rcid= parameter, we want to give the user a
872 # chance to mark this new article as patrolled.
873 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle
->exists() ) {
875 "<div class='patrollink'>" .
876 wfMsgHtml( 'markaspatrolledlink',
877 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
878 "action=markpatrolled&rcid=$rcid" )
885 if ($wgUseTrackbacks)
886 $this->addTrackbacks();
888 $this->viewUpdates();
889 wfProfileOut( __METHOD__
);
892 function addTrackbacks() {
893 global $wgOut, $wgUser;
895 $dbr = wfGetDB(DB_SLAVE
);
897 /* FROM */ 'trackbacks',
898 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
899 /* WHERE */ array('tb_page' => $this->getID())
902 if (!$dbr->numrows($tbs))
906 while ($o = $dbr->fetchObject($tbs)) {
908 if ($wgUser->isAllowed( 'trackback' )) {
909 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
910 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
911 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
913 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
920 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
923 function deletetrackback() {
924 global $wgUser, $wgRequest, $wgOut, $wgTitle;
926 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
927 $wgOut->addWikitext(wfMsg('sessionfailure'));
931 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
933 if (count($permission_errors)>0)
935 $wgOut->showPermissionsErrorPage( $permission_errors );
939 $db = wfGetDB(DB_MASTER
);
940 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
941 $wgTitle->invalidateCache();
942 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
948 $wgOut->setArticleBodyOnly(true);
953 * Handle action=purge
956 global $wgUser, $wgRequest, $wgOut;
958 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
959 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
963 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
964 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
965 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
966 $msg = str_replace( '$1',
967 "<form method=\"post\" action=\"$action\">\n" .
968 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
971 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
972 $wgOut->setRobotpolicy( 'noindex,nofollow' );
973 $wgOut->addHTML( $msg );
978 * Perform the actions of a page purging
982 // Invalidate the cache
983 $this->mTitle
->invalidateCache();
986 // Commit the transaction before the purge is sent
987 $dbw = wfGetDB( DB_MASTER
);
988 $dbw->immediateCommit();
991 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
998 * Insert a new empty page record for this article.
999 * This *must* be followed up by creating a revision
1000 * and running $this->updateToLatest( $rev_id );
1001 * or else the record will be left in a funky state.
1002 * Best if all done inside a transaction.
1004 * @param Database $dbw
1005 * @return int The newly created page_id key
1008 function insertOn( $dbw ) {
1009 wfProfileIn( __METHOD__
);
1011 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1012 $dbw->insert( 'page', array(
1013 'page_id' => $page_id,
1014 'page_namespace' => $this->mTitle
->getNamespace(),
1015 'page_title' => $this->mTitle
->getDBkey(),
1016 'page_counter' => 0,
1017 'page_restrictions' => '',
1018 'page_is_redirect' => 0, # Will set this shortly...
1020 'page_random' => wfRandom(),
1021 'page_touched' => $dbw->timestamp(),
1022 'page_latest' => 0, # Fill this in shortly...
1023 'page_len' => 0, # Fill this in shortly...
1025 $newid = $dbw->insertId();
1027 $this->mTitle
->resetArticleId( $newid );
1029 wfProfileOut( __METHOD__
);
1034 * Update the page record to point to a newly saved revision.
1036 * @param Database $dbw
1037 * @param Revision $revision For ID number, and text used to set
1038 length and redirect status fields
1039 * @param int $lastRevision If given, will not overwrite the page field
1040 * when different from the currently set value.
1041 * Giving 0 indicates the new page flag should
1043 * @param bool $lastRevIsRedirect If given, will optimize adding and
1044 * removing rows in redirect table.
1045 * @return bool true on success, false on failure
1048 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1049 wfProfileIn( __METHOD__
);
1051 $text = $revision->getText();
1052 $rt = Title
::newFromRedirect( $text );
1054 $conditions = array( 'page_id' => $this->getId() );
1055 if( !is_null( $lastRevision ) ) {
1056 # An extra check against threads stepping on each other
1057 $conditions['page_latest'] = $lastRevision;
1060 $dbw->update( 'page',
1062 'page_latest' => $revision->getId(),
1063 'page_touched' => $dbw->timestamp(),
1064 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1065 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1066 'page_len' => strlen( $text ),
1071 $result = $dbw->affectedRows() != 0;
1074 // FIXME: Should the result from updateRedirectOn() be returned instead?
1075 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1078 wfProfileOut( __METHOD__
);
1083 * Add row to the redirect table if this is a redirect, remove otherwise.
1085 * @param Database $dbw
1086 * @param $redirectTitle a title object pointing to the redirect target,
1087 * or NULL if this is not a redirect
1088 * @param bool $lastRevIsRedirect If given, will optimize adding and
1089 * removing rows in redirect table.
1090 * @return bool true on success, false on failure
1093 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1095 // Always update redirects (target link might have changed)
1096 // Update/Insert if we don't know if the last revision was a redirect or not
1097 // Delete if changing from redirect to non-redirect
1098 $isRedirect = !is_null($redirectTitle);
1099 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1101 $imageResult = true; //Result of imageredirects handling
1102 file_put_contents( "C:\\err.txt", strval( $this->mTitle
->getNamespace() == NS_IMAGE
) );
1103 if( $this->mTitle
->getNamespace() == NS_IMAGE
) {
1104 wfProfileIn( __METHOD__
. "-img" );
1106 $exists = $redirectTitle ? RepoGroup
::singleton()->findFile( $redirectTitle->getDBkey() ) !== false : false;
1107 if( $isRedirect && $redirectTitle->getNamespace() == NS_IMAGE
&& $exists ) {
1109 'ir_from' => $this->mTitle
->getDBkey(),
1110 'ir_to' => $redirectTitle->getDBkey(),
1112 $dbw->replace( 'imageredirects', array( 'ir_from' ), $set, __METHOD__
);
1113 $imageResult = $dbw->affectedRows() != 0;
1115 // Non-redirect or redirect to non-image
1116 $where = array( 'ir_from' => $this->mTitle
->getDBkey() );
1117 $dbw->delete( 'imageredirects', $where, __METHOD__
);
1120 wfProfileOut( __METHOD__
. "-img" );
1123 wfProfileIn( __METHOD__
);
1127 // This title is a redirect, Add/Update row in the redirect table
1128 $set = array( /* SET */
1129 'rd_namespace' => $redirectTitle->getNamespace(),
1130 'rd_title' => $redirectTitle->getDBkey(),
1131 'rd_from' => $this->getId(),
1134 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1136 // This is not a redirect, remove row from redirect table
1137 $where = array( 'rd_from' => $this->getId() );
1138 $dbw->delete( 'redirect', $where, __METHOD__
);
1141 wfProfileOut( __METHOD__
);
1142 return ( $dbw->affectedRows() != 0 ) && $imageResult;
1149 * If the given revision is newer than the currently set page_latest,
1150 * update the page record. Otherwise, do nothing.
1152 * @param Database $dbw
1153 * @param Revision $revision
1155 function updateIfNewerOn( &$dbw, $revision ) {
1156 wfProfileIn( __METHOD__
);
1158 $row = $dbw->selectRow(
1159 array( 'revision', 'page' ),
1160 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1162 'page_id' => $this->getId(),
1163 'page_latest=rev_id' ),
1166 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1167 wfProfileOut( __METHOD__
);
1170 $prev = $row->rev_id
;
1171 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1173 # No or missing previous revision; mark the page as new
1175 $lastRevIsRedirect = null;
1178 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1179 wfProfileOut( __METHOD__
);
1184 * @return string Complete article text, or null if error
1186 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1187 wfProfileIn( __METHOD__
);
1189 if( $section == '' ) {
1190 // Whole-page edit; let the text through unmolested.
1192 if( is_null( $edittime ) ) {
1193 $rev = Revision
::newFromTitle( $this->mTitle
);
1195 $dbw = wfGetDB( DB_MASTER
);
1196 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1198 if( is_null( $rev ) ) {
1199 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1200 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1203 $oldtext = $rev->getText();
1205 if( $section == 'new' ) {
1206 # Inserting a new section
1207 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1208 $text = strlen( trim( $oldtext ) ) > 0
1209 ?
"{$oldtext}\n\n{$subject}{$text}"
1210 : "{$subject}{$text}";
1212 # Replacing an existing section; roll out the big guns
1214 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1219 wfProfileOut( __METHOD__
);
1224 * @deprecated use Article::doEdit()
1226 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1227 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1228 ( $isminor ? EDIT_MINOR
: 0 ) |
1229 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1231 # If this is a comment, add the summary as headline
1232 if ( $comment && $summary != "" ) {
1233 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1236 $this->doEdit( $text, $summary, $flags );
1238 $dbw = wfGetDB( DB_MASTER
);
1240 if (!$this->mTitle
->userIsWatching()) {
1246 if ( $this->mTitle
->userIsWatching() ) {
1252 $this->doRedirect( $this->isRedirect( $text ) );
1256 * @deprecated use Article::doEdit()
1258 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1259 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1260 ( $minor ? EDIT_MINOR
: 0 ) |
1261 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1263 $good = $this->doEdit( $text, $summary, $flags );
1265 $dbw = wfGetDB( DB_MASTER
);
1267 if (!$this->mTitle
->userIsWatching()) {
1273 if ( $this->mTitle
->userIsWatching() ) {
1280 $extraq = ''; // Give extensions a chance to modify URL query on update
1281 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1283 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1291 * Change an existing article or create a new article. Updates RC and all necessary caches,
1292 * optionally via the deferred update array.
1294 * $wgUser must be set before calling this function.
1296 * @param string $text New text
1297 * @param string $summary Edit summary
1298 * @param integer $flags bitfield:
1300 * Article is known or assumed to be non-existent, create a new one
1302 * Article is known or assumed to be pre-existing, update it
1304 * Mark this edit minor, if the user is allowed to do so
1306 * Do not log the change in recentchanges
1308 * Mark the edit a "bot" edit regardless of user rights
1309 * EDIT_DEFER_UPDATES
1310 * Defer some of the updates until the end of index.php
1312 * Fill in blank summaries with generated text where possible
1314 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1315 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1316 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1317 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1318 * to MediaWiki's performance-optimised locking strategy.
1320 * @return bool success
1322 function doEdit( $text, $summary, $flags = 0 ) {
1323 global $wgUser, $wgDBtransactions;
1325 wfProfileIn( __METHOD__
);
1328 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1329 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1331 $flags |
= EDIT_UPDATE
;
1337 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1338 &$summary, $flags & EDIT_MINOR
,
1339 null, null, &$flags ) ) )
1341 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1342 wfProfileOut( __METHOD__
);
1346 # Silently ignore EDIT_MINOR if not allowed
1347 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1348 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1350 $oldtext = $this->getContent();
1351 $oldsize = strlen( $oldtext );
1353 # Provide autosummaries if one is not provided.
1354 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1355 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1357 $editInfo = $this->prepareTextForEdit( $text );
1358 $text = $editInfo->pst
;
1359 $newsize = strlen( $text );
1361 $dbw = wfGetDB( DB_MASTER
);
1362 $now = wfTimestampNow();
1364 if ( $flags & EDIT_UPDATE
) {
1365 # Update article, but only if changed.
1367 # Make sure the revision is either completely inserted or not inserted at all
1368 if( !$wgDBtransactions ) {
1369 $userAbort = ignore_user_abort( true );
1375 if ( 0 != strcmp( $text, $oldtext ) ) {
1376 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1377 - (int)$this->isCountable( $oldtext );
1378 $this->mTotalAdjustment
= 0;
1380 $lastRevision = $dbw->selectField(
1381 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1383 if ( !$lastRevision ) {
1384 # Article gone missing
1385 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1386 wfProfileOut( __METHOD__
);
1390 $revision = new Revision( array(
1391 'page' => $this->getId(),
1392 'comment' => $summary,
1393 'minor_edit' => $isminor,
1398 $revisionId = $revision->insertOn( $dbw );
1401 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1404 /* Belated edit conflict! Run away!! */
1408 # Update recentchanges
1409 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1410 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1411 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1414 # Mark as patrolled if the user can do so
1415 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1416 RecentChange
::markPatrolled( $rcid );
1417 PatrolLog
::record( $rcid, true );
1420 $wgUser->incEditCount();
1425 // Keep the same revision ID, but do some updates on it
1426 $revisionId = $this->getRevIdFetched();
1427 // Update page_touched, this is usually implicit in the page update
1428 // Other cache updates are done in onArticleEdit()
1429 $this->mTitle
->invalidateCache();
1432 if( !$wgDBtransactions ) {
1433 ignore_user_abort( $userAbort );
1437 # Invalidate cache of this article and all pages using this article
1438 # as a template. Partly deferred.
1439 Article
::onArticleEdit( $this->mTitle
);
1441 # Update links tables, site stats, etc.
1442 $changed = ( strcmp( $oldtext, $text ) != 0 );
1443 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1446 # Create new article
1448 # Set statistics members
1449 # We work out if it's countable after PST to avoid counter drift
1450 # when articles are created with {{subst:}}
1451 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1452 $this->mTotalAdjustment
= 1;
1456 # Add the page record; stake our claim on this title!
1457 # This will fail with a database query exception if the article already exists
1458 $newid = $this->insertOn( $dbw );
1460 # Save the revision text...
1461 $revision = new Revision( array(
1463 'comment' => $summary,
1464 'minor_edit' => $isminor,
1467 $revisionId = $revision->insertOn( $dbw );
1469 $this->mTitle
->resetArticleID( $newid );
1471 # Update the page record with revision data
1472 $this->updateRevisionOn( $dbw, $revision, 0 );
1474 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1475 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1476 '', strlen( $text ), $revisionId );
1477 # Mark as patrolled if the user can
1478 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1479 RecentChange
::markPatrolled( $rcid );
1480 PatrolLog
::record( $rcid, true );
1483 $wgUser->incEditCount();
1486 # Update links, etc.
1487 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1490 Article
::onArticleCreate( $this->mTitle
);
1492 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1493 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1496 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1501 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1502 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1505 wfProfileOut( __METHOD__
);
1510 * @deprecated wrapper for doRedirect
1512 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1513 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1517 * Output a redirect back to the article.
1518 * This is typically used after an edit.
1520 * @param boolean $noRedir Add redirect=no
1521 * @param string $sectionAnchor section to redirect to, including "#"
1523 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1526 $query = 'redirect=no';
1528 $query .= "&$query";
1532 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1536 * Mark this particular edit/page as patrolled
1538 function markpatrolled() {
1539 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1540 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1542 # Check patrol config options
1544 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1545 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1549 # If we haven't been given an rc_id value, we can't do anything
1550 $rcid = (int) $wgRequest->getVal('rcid');
1551 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1552 if ( is_null ( $rc ) )
1554 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1558 if ( !$wgUseRCPatrol && $rc->mAttribs
['rc_type'] != RC_NEW
) {
1559 // Only new pages can be patrolled if the general patrolling is off....???
1560 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1562 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1567 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1569 if (count($permission_errors)>0)
1571 $wgOut->showPermissionsErrorPage( $permission_errors );
1575 # Handle the 'MarkPatrolled' hook
1576 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1580 #It would be nice to see where the user had actually come from, but for now just guess
1581 $returnto = $rc->mAttribs
['rc_type'] == RC_NEW ?
'Newpages' : 'Recentchanges';
1582 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1584 # If it's left up to us, check that the user is allowed to patrol this edit
1585 # If the user has the "autopatrol" right, then we'll assume there are no
1586 # other conditions stopping them doing so
1587 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1588 $rc = RecentChange
::newFromId( $rcid );
1589 # Graceful error handling, as we've done before here...
1590 # (If the recent change doesn't exist, then it doesn't matter whether
1591 # the user is allowed to patrol it or not; nothing is going to happen
1592 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1593 # The user made this edit, and can't patrol it
1594 # Tell them so, and then back off
1595 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1596 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1597 $wgOut->returnToMain( false, $return );
1602 # Mark the edit as patrolled
1603 RecentChange
::markPatrolled( $rcid );
1604 PatrolLog
::record( $rcid );
1605 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1608 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1609 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1610 $wgOut->returnToMain( false, $return );
1614 * User-interface handler for the "watch" action
1619 global $wgUser, $wgOut;
1621 if ( $wgUser->isAnon() ) {
1622 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1625 if ( wfReadOnly() ) {
1626 $wgOut->readOnlyPage();
1630 if( $this->doWatch() ) {
1631 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1632 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1634 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1635 $text = wfMsg( 'addedwatchtext', $link );
1636 $wgOut->addWikiText( $text );
1639 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1643 * Add this page to $wgUser's watchlist
1644 * @return bool true on successful watch operation
1646 function doWatch() {
1648 if( $wgUser->isAnon() ) {
1652 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1653 $wgUser->addWatch( $this->mTitle
);
1655 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1662 * User interface handler for the "unwatch" action.
1664 function unwatch() {
1666 global $wgUser, $wgOut;
1668 if ( $wgUser->isAnon() ) {
1669 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1672 if ( wfReadOnly() ) {
1673 $wgOut->readOnlyPage();
1677 if( $this->doUnwatch() ) {
1678 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1679 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1681 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1682 $text = wfMsg( 'removedwatchtext', $link );
1683 $wgOut->addWikiText( $text );
1686 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1690 * Stop watching a page
1691 * @return bool true on successful unwatch
1693 function doUnwatch() {
1695 if( $wgUser->isAnon() ) {
1699 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1700 $wgUser->removeWatch( $this->mTitle
);
1702 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1709 * action=protect handler
1711 function protect() {
1712 $form = new ProtectionForm( $this );
1717 * action=unprotect handler (alias)
1719 function unprotect() {
1724 * Update the article's restriction field, and leave a log entry.
1726 * @param array $limit set of restriction keys
1727 * @param string $reason
1728 * @return bool true on success
1730 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1731 global $wgUser, $wgRestrictionTypes, $wgContLang;
1733 $id = $this->mTitle
->getArticleID();
1734 if( array() != $this->mTitle
->getUserPermissionsErrors( 'protect', $wgUser ) ||
wfReadOnly() ||
$id == 0 ) {
1742 // Take this opportunity to purge out expired restrictions
1743 Title
::purgeExpiredRestrictions();
1745 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1746 # we expect a single selection, but the schema allows otherwise.
1748 foreach( $wgRestrictionTypes as $action )
1749 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1751 $current = Article
::flattenRestrictions( $current );
1752 $updated = Article
::flattenRestrictions( $limit );
1754 $changed = ( $current != $updated );
1755 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1756 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1757 $protect = ( $updated != '' );
1759 # If nothing's changed, do nothing
1761 global $wgGroupPermissions;
1762 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1764 $dbw = wfGetDB( DB_MASTER
);
1766 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1768 $expiry_description = '';
1769 if ( $encodedExpiry != 'infinity' ) {
1770 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1773 # Prepare a null revision to be added to the history
1774 $modified = $current != '' && $protect;
1776 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1778 $comment_type = 'unprotectedarticle';
1780 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1782 foreach( $limit as $action => $restrictions ) {
1783 # Check if the group level required to edit also can protect pages
1784 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1785 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1788 $cascade_description = '';
1790 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1794 $comment .= ": $reason";
1796 $comment .= " [$updated]";
1797 if ( $expiry_description && $protect )
1798 $comment .= "$expiry_description";
1800 $comment .= "$cascade_description";
1802 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1803 $nullRevId = $nullRevision->insertOn( $dbw );
1805 # Update restrictions table
1806 foreach( $limit as $action => $restrictions ) {
1807 if ($restrictions != '' ) {
1808 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1809 array( 'pr_page' => $id, 'pr_type' => $action
1810 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1811 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1813 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1814 'pr_type' => $action ), __METHOD__
);
1818 # Update page record
1819 $dbw->update( 'page',
1821 'page_touched' => $dbw->timestamp(),
1822 'page_restrictions' => '',
1823 'page_latest' => $nullRevId
1824 ), array( /* WHERE */
1826 ), 'Article::protect'
1828 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1830 # Update the protection log
1831 $log = new LogPage( 'protect' );
1834 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1836 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1840 } # End "changed" check
1846 * Take an array of page restrictions and flatten it to a string
1847 * suitable for insertion into the page_restrictions field.
1848 * @param array $limit
1852 function flattenRestrictions( $limit ) {
1853 if( !is_array( $limit ) ) {
1854 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1858 foreach( $limit as $action => $restrictions ) {
1859 if( $restrictions != '' ) {
1860 $bits[] = "$action=$restrictions";
1863 return implode( ':', $bits );
1867 * Auto-generates a deletion reason
1868 * @param bool &$hasHistory Whether the page has a history
1870 public function generateReason(&$hasHistory)
1873 $dbw = wfGetDB(DB_MASTER
);
1874 // Get the last revision
1875 $rev = Revision
::newFromTitle($this->mTitle
);
1878 // Get the article's contents
1879 $contents = $rev->getText();
1881 // If the page is blank, use the text from the previous revision,
1882 // which can only be blank if there's a move/import/protect dummy revision involved
1885 $prev = $rev->getPrevious();
1888 $contents = $prev->getText();
1893 // Find out if there was only one contributor
1894 // Only scan the last 20 revisions
1896 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1897 array('LIMIT' => $limit));
1899 // This page has no revisions, which is very weird
1901 if($res->numRows() > 1)
1904 $hasHistory = false;
1905 $row = $dbw->fetchObject($res);
1906 $onlyAuthor = $row->rev_user_text
;
1907 // Try to find a second contributor
1908 while(($row = $dbw->fetchObject($res)))
1909 if($row->rev_user_text
!= $onlyAuthor)
1911 $onlyAuthor = false;
1914 $dbw->freeResult($res);
1916 // Generate the summary with a '$1' placeholder
1918 // The current revision is blank and the one before is also
1919 // blank. It's just not our lucky day
1920 $reason = wfMsgForContent('exbeforeblank', '$1');
1924 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1926 $reason = wfMsgForContent('excontent', '$1');
1929 // Replace newlines with spaces to prevent uglyness
1930 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1931 // Calculate the maximum amount of chars to get
1932 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1933 $maxLength = 255 - (strlen($reason) - 2) - 3;
1934 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1935 // Remove possible unfinished links
1936 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1937 // Now replace the '$1' placeholder
1938 $reason = str_replace( '$1', $contents, $reason );
1944 * UI entry point for page deletion
1947 global $wgUser, $wgOut, $wgRequest;
1949 $confirm = $wgRequest->wasPosted() &&
1950 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1952 $this->DeleteReasonList
= $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1953 $this->DeleteReason
= $wgRequest->getText( 'wpReason' );
1955 $reason = $this->DeleteReasonList
;
1957 if ( $reason != 'other' && $this->DeleteReason
!= '') {
1958 // Entry from drop down menu + additional comment
1959 $reason .= ': ' . $this->DeleteReason
;
1960 } elseif ( $reason == 'other' ) {
1961 $reason = $this->DeleteReason
;
1964 # This code desperately needs to be totally rewritten
1967 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1969 if (count($permission_errors)>0)
1971 $wgOut->showPermissionsErrorPage( $permission_errors );
1975 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1977 # Better double-check that it hasn't been deleted yet!
1978 $dbw = wfGetDB( DB_MASTER
);
1979 $conds = $this->mTitle
->pageCond();
1980 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1981 if ( $latest === false ) {
1982 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1987 $this->doDelete( $reason );
1988 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1990 } elseif( $this->mTitle
->userIsWatching() ) {
1996 // Generate deletion reason
1997 $hasHistory = false;
1998 if ( !$reason ) $reason = $this->generateReason($hasHistory);
2000 // If the page has a history, insert a warning
2001 if( $hasHistory && !$confirm ) {
2002 $skin=$wgUser->getSkin();
2003 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2006 return $this->confirmDelete( '', $reason );
2010 * Get the last N authors
2011 * @param int $num Number of revisions to get
2012 * @param string $revLatest The latest rev_id, selected from the master (optional)
2013 * @return array Array of authors, duplicates not removed
2015 function getLastNAuthors( $num, $revLatest = 0 ) {
2016 wfProfileIn( __METHOD__
);
2018 // First try the slave
2019 // If that doesn't have the latest revision, try the master
2021 $db = wfGetDB( DB_SLAVE
);
2023 $res = $db->select( array( 'page', 'revision' ),
2024 array( 'rev_id', 'rev_user_text' ),
2026 'page_namespace' => $this->mTitle
->getNamespace(),
2027 'page_title' => $this->mTitle
->getDBkey(),
2028 'rev_page = page_id'
2029 ), __METHOD__
, $this->getSelectOptions( array(
2030 'ORDER BY' => 'rev_timestamp DESC',
2035 wfProfileOut( __METHOD__
);
2038 $row = $db->fetchObject( $res );
2039 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2040 $db = wfGetDB( DB_MASTER
);
2045 } while ( $continue );
2047 $authors = array( $row->rev_user_text
);
2048 while ( $row = $db->fetchObject( $res ) ) {
2049 $authors[] = $row->rev_user_text
;
2051 wfProfileOut( __METHOD__
);
2056 * Output deletion confirmation dialog
2058 function confirmDelete( $par, $reason ) {
2059 global $wgOut, $wgUser;
2061 wfDebug( "Article::confirmDelete\n" );
2063 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
2064 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
2065 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2066 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
2068 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
2070 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
2071 $delcom = Xml
::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' );
2072 $token = htmlspecialchars( $wgUser->editToken() );
2073 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
2075 $mDeletereasonother = Xml
::label( wfMsg( 'deleteotherreason' ), 'wpReason' );
2076 $mDeletereasonotherlist = wfMsgHtml( 'deletereasonotherlist' );
2077 $scDeleteReasonList = wfMsgForContent( 'deletereason-dropdown' );
2079 $deleteReasonList = '';
2080 if ( $scDeleteReasonList != '' && $scDeleteReasonList != '-' ) {
2081 $deleteReasonList = "<option value=\"other\">$mDeletereasonotherlist</option>";
2083 foreach ( explode( "\n", $scDeleteReasonList ) as $option) {
2084 $value = trim( htmlspecialchars($option) );
2085 if ( $value == '' ) {
2087 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
2088 // A new group is starting ...
2089 $value = trim( substr( $value, 1 ) );
2090 $deleteReasonList .= "$optgroup<optgroup label=\"$value\">";
2091 $optgroup = "</optgroup>";
2092 } elseif ( substr( $value, 0, 2) == '**' ) {
2095 $value = trim( substr( $value, 2 ) );
2096 if ( $this->DeleteReasonList
=== $value)
2097 $selected = ' selected="selected"';
2098 $deleteReasonList .= "<option value=\"$value\"$selected>$value</option>";
2100 // groupless delete reason
2102 if ( $this->DeleteReasonList
=== $value)
2103 $selected = ' selected="selected"';
2104 $deleteReasonList .= "$optgroup<option value=\"$value\"$selected>$value</option>";
2108 $deleteReasonList .= $optgroup;
2111 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
2113 <tr id=\"wpDeleteReasonListRow\" name=\"wpDeleteReasonListRow\">
2118 <select tabindex='1' id='wpDeleteReasonList' name=\"wpDeleteReasonList\">
2123 <tr id=\"wpDeleteReasonRow\" name=\"wpDeleteReasonRow\">
2128 <input type='text' maxlength='255' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"2\" />
2138 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2142 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2145 $wgOut->returnToMain( false, $this->mTitle
);
2147 $this->showLogExtract( $wgOut );
2152 * Show relevant lines from the deletion log
2154 function showLogExtract( $out ) {
2155 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2156 $logViewer = new LogViewer(
2159 array( 'page' => $this->mTitle
->getPrefixedText(),
2160 'type' => 'delete' ) ) ) );
2161 $logViewer->showList( $out );
2166 * Perform a deletion and output success or failure messages
2168 function doDelete( $reason ) {
2169 global $wgOut, $wgUser;
2170 wfDebug( __METHOD__
."\n" );
2172 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2173 if ( $this->doDeleteArticle( $reason ) ) {
2174 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2176 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2177 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2179 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2180 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2182 $wgOut->addWikiText( $text );
2183 $wgOut->returnToMain( false );
2184 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2186 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2192 * Back-end article deletion
2193 * Deletes the article with database consistency, writes logs, purges caches
2196 function doDeleteArticle( $reason ) {
2197 global $wgUseSquid, $wgDeferredUpdateList;
2198 global $wgUseTrackbacks;
2200 wfDebug( __METHOD__
."\n" );
2202 $dbw = wfGetDB( DB_MASTER
);
2203 $ns = $this->mTitle
->getNamespace();
2204 $t = $this->mTitle
->getDBkey();
2205 $id = $this->mTitle
->getArticleID();
2207 if ( $t == '' ||
$id == 0 ) {
2211 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2212 array_push( $wgDeferredUpdateList, $u );
2214 // For now, shunt the revision data into the archive table.
2215 // Text is *not* removed from the text table; bulk storage
2216 // is left intact to avoid breaking block-compression or
2217 // immutable storage schemes.
2219 // For backwards compatibility, note that some older archive
2220 // table entries will have ar_text and ar_flags fields still.
2222 // In the future, we may keep revisions and mark them with
2223 // the rev_deleted field, which is reserved for this purpose.
2224 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2226 'ar_namespace' => 'page_namespace',
2227 'ar_title' => 'page_title',
2228 'ar_comment' => 'rev_comment',
2229 'ar_user' => 'rev_user',
2230 'ar_user_text' => 'rev_user_text',
2231 'ar_timestamp' => 'rev_timestamp',
2232 'ar_minor_edit' => 'rev_minor_edit',
2233 'ar_rev_id' => 'rev_id',
2234 'ar_text_id' => 'rev_text_id',
2235 'ar_text' => '\'\'', // Be explicit to appease
2236 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2237 'ar_len' => 'rev_len',
2238 'ar_page_id' => 'page_id',
2241 'page_id = rev_page'
2245 # Delete restrictions for it
2246 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2248 # Now that it's safely backed up, delete it
2249 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2251 # If using cascading deletes, we can skip some explicit deletes
2252 if ( !$dbw->cascadingDeletes() ) {
2254 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2256 if ($wgUseTrackbacks)
2257 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2259 # Delete outgoing links
2260 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2261 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2262 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2263 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2264 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2265 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2266 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2269 # If using cleanup triggers, we can skip some manual deletes
2270 if ( !$dbw->cleanupTriggers() ) {
2272 # Clean up recentchanges entries...
2273 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2277 Article
::onArticleDelete( $this->mTitle
);
2280 $log = new LogPage( 'delete' );
2281 $log->addEntry( 'delete', $this->mTitle
, $reason );
2283 # Clear the cached article id so the interface doesn't act like we exist
2284 $this->mTitle
->resetArticleID( 0 );
2285 $this->mTitle
->mArticleID
= 0;
2290 * Roll back the most recent consecutive set of edits to a page
2291 * from the same user; fails if there are no eligible edits to
2292 * roll back to, e.g. user is the sole contributor
2294 * @param string $fromP - Name of the user whose edits to rollback.
2295 * @param string $summary - Custom summary. Set to default summary if empty.
2296 * @param string $token - Rollback token.
2297 * @param bool $bot - If true, mark all reverted edits as bot.
2299 * @param array $resultDetails contains result-specific dict of additional values
2300 * ALREADY_ROLLED : 'current' (rev)
2301 * SUCCESS : 'summary' (str), 'current' (rev), 'target' (rev)
2303 * @return self::SUCCESS on succes, self::* on failure
2305 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2306 global $wgUser, $wgUseRCPatrol;
2307 $resultDetails = null;
2309 # Just in case it's being called from elsewhere
2311 if( $wgUser->isAllowed( 'rollback' ) && $this->mTitle
->userCan( 'edit' ) ) {
2312 if( $wgUser->isBlocked() ) {
2313 return self
::BLOCKED
;
2316 return self
::PERM_DENIED
;
2319 if ( wfReadOnly() ) {
2320 return self
::READONLY
;
2323 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2324 return self
::BAD_TOKEN
;
2326 if ( $wgUser->pingLimiter('rollback') ||
$wgUser->pingLimiter() ) {
2327 return self
::RATE_LIMITED
;
2330 $dbw = wfGetDB( DB_MASTER
);
2332 # Get the last editor
2333 $current = Revision
::newFromTitle( $this->mTitle
);
2334 if( is_null( $current ) ) {
2335 # Something wrong... no page?
2336 return self
::BAD_TITLE
;
2339 $from = str_replace( '_', ' ', $fromP );
2340 if( $from != $current->getUserText() ) {
2341 $resultDetails = array( 'current' => $current );
2342 return self
::ALREADY_ROLLED
;
2345 # Get the last edit not by this guy
2346 $user = intval( $current->getUser() );
2347 $user_text = $dbw->addQuotes( $current->getUserText() );
2348 $s = $dbw->selectRow( 'revision',
2349 array( 'rev_id', 'rev_timestamp' ),
2351 'rev_page' => $current->getPage(),
2352 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2355 'USE INDEX' => 'page_timestamp',
2356 'ORDER BY' => 'rev_timestamp DESC' )
2358 if( $s === false ) {
2360 return self
::ONLY_AUTHOR
;
2364 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2365 # Mark all reverted edits as bot
2368 if ( $wgUseRCPatrol ) {
2369 # Mark all reverted edits as patrolled
2370 $set['rc_patrolled'] = 1;
2374 $dbw->update( 'recentchanges', $set,
2376 'rc_cur_id' => $current->getPage(),
2377 'rc_user_text' => $current->getUserText(),
2378 "rc_timestamp > '{$s->rev_timestamp}'",
2383 # Get the edit summary
2384 $target = Revision
::newFromId( $s->rev_id
);
2385 if( empty( $summary ) )
2386 $summary = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2389 $flags = EDIT_UPDATE
;
2391 if ($wgUser->isAllowed('minoredit'))
2392 $flags |
= EDIT_MINOR
;
2395 $flags |
= EDIT_FORCE_BOT
;
2396 $this->doEdit( $target->getText(), $summary, $flags );
2398 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2400 $resultDetails = array(
2401 'summary' => $summary,
2402 'current' => $current,
2403 'target' => $target,
2405 return self
::SUCCESS
;
2409 * User interface for rollback operations
2411 function rollback() {
2412 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2416 # Skip the permissions-checking in doRollback() itself, by checking permissions here.
2418 $perm_errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2419 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2421 if (count($perm_errors)) {
2422 $wgOut->showPermissionsErrorPage( $perm_errors );
2426 $result = $this->doRollback(
2427 $wgRequest->getVal( 'from' ),
2428 $wgRequest->getText( 'summary' ),
2429 $wgRequest->getVal( 'token' ),
2430 $wgRequest->getBool( 'bot' ),
2436 $wgOut->blockedPage();
2438 case self
::PERM_DENIED
:
2439 $wgOut->permissionRequired( 'rollback' );
2441 case self
::READONLY
:
2442 $wgOut->readOnlyPage( $this->getContent() );
2444 case self
::BAD_TOKEN
:
2445 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2446 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2448 case self
::BAD_TITLE
:
2449 $wgOut->addHtml( wfMsg( 'notanarticle' ) );
2451 case self
::ALREADY_ROLLED
:
2452 $current = $details['current'];
2453 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2454 $wgOut->addWikiText(
2455 wfMsg( 'alreadyrolled',
2456 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2457 htmlspecialchars( $wgRequest->getVal( 'from' ) ),
2458 htmlspecialchars( $current->getUserText() )
2461 if( $current->getComment() != '' ) {
2462 $wgOut->addHtml( wfMsg( 'editcomment',
2463 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2466 case self
::ONLY_AUTHOR
:
2467 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2468 $wgOut->addHtml( wfMsg( 'cantrollback' ) );
2470 case self
::RATE_LIMITED
:
2471 $wgOut->rateLimited();
2474 $current = $details['current'];
2475 $target = $details['target'];
2476 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2477 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2478 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2479 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2480 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2481 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2482 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2483 $wgOut->returnToMain( false, $this->mTitle
);
2486 throw new MWException( __METHOD__
. ": Unknown return value `{$result}`" );
2493 * Do standard deferred updates after page view
2496 function viewUpdates() {
2497 global $wgDeferredUpdateList;
2499 if ( 0 != $this->getID() ) {
2500 global $wgDisableCounters;
2501 if( !$wgDisableCounters ) {
2502 Article
::incViewCount( $this->getID() );
2503 $u = new SiteStatsUpdate( 1, 0, 0 );
2504 array_push( $wgDeferredUpdateList, $u );
2508 # Update newtalk / watchlist notification status
2510 $wgUser->clearNotification( $this->mTitle
);
2514 * Prepare text which is about to be saved.
2515 * Returns a stdclass with source, pst and output members
2517 function prepareTextForEdit( $text, $revid=null ) {
2518 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2520 return $this->mPreparedEdit
;
2523 $edit = (object)array();
2524 $edit->revid
= $revid;
2525 $edit->newText
= $text;
2526 $edit->pst
= $this->preSaveTransform( $text );
2527 $options = new ParserOptions
;
2528 $options->setTidy( true );
2529 $options->enableLimitReport();
2530 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2531 $edit->oldText
= $this->getContent();
2532 $this->mPreparedEdit
= $edit;
2537 * Do standard deferred updates after page edit.
2538 * Update links tables, site stats, search index and message cache.
2539 * Every 100th edit, prune the recent changes table.
2542 * @param $text New text of the article
2543 * @param $summary Edit summary
2544 * @param $minoredit Minor edit
2545 * @param $timestamp_of_pagechange Timestamp associated with the page change
2546 * @param $newid rev_id value of the new revision
2547 * @param $changed Whether or not the content actually changed
2549 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2550 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2552 wfProfileIn( __METHOD__
);
2555 # Be careful not to double-PST: $text is usually already PST-ed once
2556 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2557 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2558 $editInfo = $this->prepareTextForEdit( $text, $newid );
2560 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2561 $editInfo = $this->mPreparedEdit
;
2564 # Save it to the parser cache
2565 $parserCache =& ParserCache
::singleton();
2566 $parserCache->save( $editInfo->output
, $this, $wgUser );
2568 # Update the links tables
2569 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2572 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2573 if ( 0 == mt_rand( 0, 99 ) ) {
2574 // Flush old entries from the `recentchanges` table; we do this on
2575 // random requests so as to avoid an increase in writes for no good reason
2577 $dbw = wfGetDB( DB_MASTER
);
2578 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2579 $recentchanges = $dbw->tableName( 'recentchanges' );
2580 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2581 $dbw->query( $sql );
2585 $id = $this->getID();
2586 $title = $this->mTitle
->getPrefixedDBkey();
2587 $shortTitle = $this->mTitle
->getDBkey();
2590 wfProfileOut( __METHOD__
);
2594 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2595 array_push( $wgDeferredUpdateList, $u );
2596 $u = new SearchUpdate( $id, $title, $text );
2597 array_push( $wgDeferredUpdateList, $u );
2599 # If this is another user's talk page, update newtalk
2600 # Don't do this if $changed = false otherwise some idiot can null-edit a
2601 # load of user talk pages and piss people off, nor if it's a minor edit
2602 # by a properly-flagged bot.
2603 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2604 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2605 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2606 $other = User
::newFromName( $shortTitle );
2607 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2608 // An anonymous user
2609 $other = new User();
2610 $other->setName( $shortTitle );
2613 $other->setNewtalk( true );
2618 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2619 $wgMessageCache->replace( $shortTitle, $text );
2622 wfProfileOut( __METHOD__
);
2626 * Perform article updates on a special page creation.
2628 * @param Revision $rev
2630 * @todo This is a shitty interface function. Kill it and replace the
2631 * other shitty functions like editUpdates and such so it's not needed
2634 function createUpdates( $rev ) {
2635 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2636 $this->mTotalAdjustment
= 1;
2637 $this->editUpdates( $rev->getText(), $rev->getComment(),
2638 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2642 * Generate the navigation links when browsing through an article revisions
2643 * It shows the information as:
2644 * Revision as of \<date\>; view current revision
2645 * \<- Previous version | Next Version -\>
2648 * @param string $oldid Revision ID of this article revision
2650 function setOldSubtitle( $oldid=0 ) {
2651 global $wgLang, $wgOut, $wgUser;
2653 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2657 $revision = Revision
::newFromId( $oldid );
2659 $current = ( $oldid == $this->mLatest
);
2660 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2661 $sk = $wgUser->getSkin();
2663 ?
wfMsg( 'currentrevisionlink' )
2664 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2667 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2668 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2670 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2671 : wfMsg( 'previousrevision' );
2673 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2675 $nextlink = $current
2676 ?
wfMsg( 'nextrevision' )
2677 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2678 $nextdiff = $current
2680 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2682 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2683 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2685 $m = wfMsg( 'revision-info-current' );
2686 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2687 ?
'revision-info-current'
2690 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2691 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2692 $wgOut->setSubtitle( $r );
2696 * This function is called right before saving the wikitext,
2697 * so we can do things like signatures and links-in-context.
2699 * @param string $text
2701 function preSaveTransform( $text ) {
2702 global $wgParser, $wgUser;
2703 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2706 /* Caching functions */
2709 * checkLastModified returns true if it has taken care of all
2710 * output to the client that is necessary for this request.
2711 * (that is, it has sent a cached version of the page)
2713 function tryFileCache() {
2714 static $called = false;
2716 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2720 if($this->isFileCacheable()) {
2721 $touched = $this->mTouched
;
2722 $cache = new HTMLFileCache( $this->mTitle
);
2723 if($cache->isFileCacheGood( $touched )) {
2724 wfDebug( "Article::tryFileCache(): about to load file\n" );
2725 $cache->loadFromFileCache();
2728 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2729 ob_start( array(&$cache, 'saveToFileCache' ) );
2732 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2737 * Check if the page can be cached
2740 function isFileCacheable() {
2741 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2742 $action = $wgRequest->getVal( 'action' );
2743 $oldid = $wgRequest->getVal( 'oldid' );
2744 $diff = $wgRequest->getVal( 'diff' );
2745 $redirect = $wgRequest->getVal( 'redirect' );
2746 $printable = $wgRequest->getVal( 'printable' );
2747 $page = $wgRequest->getVal( 'page' );
2749 //check for non-standard user language; this covers uselang,
2750 //and extensions for auto-detecting user language.
2751 $ulang = $wgLang->getCode();
2752 $clang = $wgContLang->getCode();
2754 $cacheable = $wgUseFileCache
2755 && (!$wgShowIPinHeader)
2756 && ($this->getID() != 0)
2757 && ($wgUser->isAnon())
2758 && (!$wgUser->getNewtalk())
2759 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2760 && (empty( $action ) ||
$action == 'view')
2763 && (!isset($redirect))
2764 && (!isset($printable))
2766 && (!$this->mRedirectedFrom
)
2767 && ($ulang === $clang);
2770 //extension may have reason to disable file caching on some pages.
2771 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2778 * Loads page_touched and returns a value indicating if it should be used
2781 function checkTouched() {
2782 if( !$this->mDataLoaded
) {
2783 $this->loadPageData();
2785 return !$this->mIsRedirect
;
2789 * Get the page_touched field
2791 function getTouched() {
2792 # Ensure that page data has been loaded
2793 if( !$this->mDataLoaded
) {
2794 $this->loadPageData();
2796 return $this->mTouched
;
2800 * Get the page_latest field
2802 function getLatest() {
2803 if ( !$this->mDataLoaded
) {
2804 $this->loadPageData();
2806 return $this->mLatest
;
2810 * Edit an article without doing all that other stuff
2811 * The article must already exist; link tables etc
2812 * are not updated, caches are not flushed.
2814 * @param string $text text submitted
2815 * @param string $comment comment submitted
2816 * @param bool $minor whereas it's a minor modification
2818 function quickEdit( $text, $comment = '', $minor = 0 ) {
2819 wfProfileIn( __METHOD__
);
2821 $dbw = wfGetDB( DB_MASTER
);
2823 $revision = new Revision( array(
2824 'page' => $this->getId(),
2826 'comment' => $comment,
2827 'minor_edit' => $minor ?
1 : 0,
2829 $revision->insertOn( $dbw );
2830 $this->updateRevisionOn( $dbw, $revision );
2833 wfProfileOut( __METHOD__
);
2837 * Used to increment the view counter
2840 * @param integer $id article id
2842 function incViewCount( $id ) {
2843 $id = intval( $id );
2844 global $wgHitcounterUpdateFreq, $wgDBtype;
2846 $dbw = wfGetDB( DB_MASTER
);
2847 $pageTable = $dbw->tableName( 'page' );
2848 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2849 $acchitsTable = $dbw->tableName( 'acchits' );
2851 if( $wgHitcounterUpdateFreq <= 1 ) {
2852 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2856 # Not important enough to warrant an error page in case of failure
2857 $oldignore = $dbw->ignoreErrors( true );
2859 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2861 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2862 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2863 # Most of the time (or on SQL errors), skip row count check
2864 $dbw->ignoreErrors( $oldignore );
2868 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2869 $row = $dbw->fetchObject( $res );
2870 $rown = intval( $row->n
);
2871 if( $rown >= $wgHitcounterUpdateFreq ){
2872 wfProfileIn( 'Article::incViewCount-collect' );
2873 $old_user_abort = ignore_user_abort( true );
2875 if ($wgDBtype == 'mysql')
2876 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2877 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2878 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2879 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2881 $dbw->query("DELETE FROM $hitcounterTable");
2882 if ($wgDBtype == 'mysql') {
2883 $dbw->query('UNLOCK TABLES');
2884 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2885 'WHERE page_id = hc_id');
2888 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2889 "FROM $acchitsTable WHERE page_id = hc_id");
2891 $dbw->query("DROP TABLE $acchitsTable");
2893 ignore_user_abort( $old_user_abort );
2894 wfProfileOut( 'Article::incViewCount-collect' );
2896 $dbw->ignoreErrors( $oldignore );
2900 * The onArticle*() functions are supposed to be a kind of hooks
2901 * which should be called whenever any of the specified actions
2904 * This is a good place to put code to clear caches, for instance.
2906 * This is called on page move and undelete, as well as edit
2908 * @param $title_obj a title object
2911 static function onArticleCreate($title) {
2912 # The talk page isn't in the regular link tables, so we need to update manually:
2913 if ( $title->isTalkPage() ) {
2914 $other = $title->getSubjectPage();
2916 $other = $title->getTalkPage();
2918 $other->invalidateCache();
2919 $other->purgeSquid();
2921 $title->touchLinks();
2922 $title->purgeSquid();
2923 $title->deleteTitleProtection();
2926 static function onArticleDelete( $title ) {
2927 global $wgUseFileCache, $wgMessageCache;
2929 $title->touchLinks();
2930 $title->purgeSquid();
2933 if ( $wgUseFileCache ) {
2934 $cm = new HTMLFileCache( $title );
2935 @unlink
( $cm->fileCacheName() );
2938 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2939 $wgMessageCache->replace( $title->getDBkey(), false );
2944 * Purge caches on page update etc
2946 static function onArticleEdit( $title ) {
2947 global $wgDeferredUpdateList, $wgUseFileCache;
2949 // Invalidate caches of articles which include this page
2950 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2951 $wgDeferredUpdateList[] = $update;
2953 # Purge squid for this page only
2954 $title->purgeSquid();
2957 if ( $wgUseFileCache ) {
2958 $cm = new HTMLFileCache( $title );
2959 @unlink
( $cm->fileCacheName() );
2966 * Info about this page
2967 * Called for ?action=info when $wgAllowPageInfo is on.
2972 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2974 if ( !$wgAllowPageInfo ) {
2975 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2979 $page = $this->mTitle
->getSubjectPage();
2981 $wgOut->setPagetitle( $page->getPrefixedText() );
2982 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
2983 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
2985 if( !$this->mTitle
->exists() ) {
2986 $wgOut->addHtml( '<div class="noarticletext">' );
2987 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2988 // This doesn't quite make sense; the user is asking for
2989 // information about the _page_, not the message... -- RC
2990 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
2992 $msg = $wgUser->isLoggedIn()
2994 : 'noarticletextanon';
2995 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
2997 $wgOut->addHtml( '</div>' );
2999 $dbr = wfGetDB( DB_SLAVE
);
3001 'wl_title' => $page->getDBkey(),
3002 'wl_namespace' => $page->getNamespace() );
3003 $numwatchers = $dbr->selectField(
3008 $this->getSelectOptions() );
3010 $pageInfo = $this->pageCountInfo( $page );
3011 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3013 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3014 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3016 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3018 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3020 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3022 $wgOut->addHTML( '</ul>' );
3028 * Return the total number of edits and number of unique editors
3029 * on a given page. If page does not exist, returns false.
3031 * @param Title $title
3035 function pageCountInfo( $title ) {
3036 $id = $title->getArticleId();
3041 $dbr = wfGetDB( DB_SLAVE
);
3043 $rev_clause = array( 'rev_page' => $id );
3045 $edits = $dbr->selectField(
3050 $this->getSelectOptions() );
3052 $authors = $dbr->selectField(
3054 'COUNT(DISTINCT rev_user_text)',
3057 $this->getSelectOptions() );
3059 return array( 'edits' => $edits, 'authors' => $authors );
3063 * Return a list of templates used by this article.
3064 * Uses the templatelinks table
3066 * @return array Array of Title objects
3068 function getUsedTemplates() {
3070 $id = $this->mTitle
->getArticleID();
3075 $dbr = wfGetDB( DB_SLAVE
);
3076 $res = $dbr->select( array( 'templatelinks' ),
3077 array( 'tl_namespace', 'tl_title' ),
3078 array( 'tl_from' => $id ),
3079 'Article:getUsedTemplates' );
3080 if ( false !== $res ) {
3081 if ( $dbr->numRows( $res ) ) {
3082 while ( $row = $dbr->fetchObject( $res ) ) {
3083 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
3087 $dbr->freeResult( $res );
3092 * Return an auto-generated summary if the text provided is a redirect.
3094 * @param string $text The wikitext to check
3095 * @return string '' or an appropriate summary
3097 public static function getRedirectAutosummary( $text ) {
3098 $rt = Title
::newFromRedirect( $text );
3099 if( is_object( $rt ) )
3100 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3106 * Return an auto-generated summary if the new text is much shorter than
3109 * @param string $oldtext The previous text of the page
3110 * @param string $text The submitted text of the page
3111 * @return string An appropriate autosummary, or an empty string.
3113 public static function getBlankingAutosummary( $oldtext, $text ) {
3114 if ($oldtext!='' && $text=='') {
3115 return wfMsgForContent('autosumm-blank');
3116 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3117 #Removing more than 90% of the article
3119 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3120 return wfMsgForContent('autosumm-replace', $truncatedtext);
3127 * Return an applicable autosummary if one exists for the given edit.
3128 * @param string $oldtext The previous text of the page.
3129 * @param string $newtext The submitted text of the page.
3130 * @param bitmask $flags A bitmask of flags submitted for the edit.
3131 * @return string An appropriate autosummary, or an empty string.
3133 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3135 # This code is UGLY UGLY UGLY.
3136 # Somebody PLEASE come up with a more elegant way to do it.
3138 #Redirect autosummaries
3139 $summary = self
::getRedirectAutosummary( $newtext );
3144 #Blanking autosummaries
3145 if (!($flags & EDIT_NEW
))
3146 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3151 #New page autosummaries
3152 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3153 #If they're making a new article, give its text, truncated, in the summary.
3155 $truncatedtext = $wgContLang->truncate(
3156 str_replace("\n", ' ', $newtext),
3157 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3159 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3169 * Add the primary page-view wikitext to the output buffer
3170 * Saves the text into the parser cache if possible.
3171 * Updates templatelinks if it is out of date.
3173 * @param string $text
3174 * @param bool $cache
3176 public function outputWikiText( $text, $cache = true ) {
3177 global $wgParser, $wgUser, $wgOut;
3179 $popts = $wgOut->parserOptions();
3180 $popts->setTidy(true);
3181 $popts->enableLimitReport();
3182 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3183 $popts, true, true, $this->getRevIdFetched() );
3184 $popts->setTidy(false);
3185 $popts->enableLimitReport( false );
3186 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3187 $parserCache =& ParserCache
::singleton();
3188 $parserCache->save( $parserOutput, $this, $wgUser );
3191 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3192 // templatelinks table may have become out of sync,
3193 // especially if using variable-based transclusions.
3194 // For paranoia, check if things have changed and if
3195 // so apply updates to the database. This will ensure
3196 // that cascaded protections apply as soon as the changes
3199 # Get templates from templatelinks
3200 $id = $this->mTitle
->getArticleID();
3202 $tlTemplates = array();
3204 $dbr = wfGetDB( DB_SLAVE
);
3205 $res = $dbr->select( array( 'templatelinks' ),
3206 array( 'tl_namespace', 'tl_title' ),
3207 array( 'tl_from' => $id ),
3208 'Article:getUsedTemplates' );
3212 if ( false !== $res ) {
3213 if ( $dbr->numRows( $res ) ) {
3214 while ( $row = $dbr->fetchObject( $res ) ) {
3215 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3220 # Get templates from parser output.
3221 $poTemplates_allns = $parserOutput->getTemplates();
3223 $poTemplates = array ();
3224 foreach ( $poTemplates_allns as $ns_templates ) {
3225 $poTemplates = array_merge( $poTemplates, $ns_templates );
3229 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3231 if ( count( $templates_diff ) > 0 ) {
3232 # Whee, link updates time.
3233 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3235 $dbw = wfGetDb( DB_MASTER
);
3244 $wgOut->addParserOutput( $parserOutput );