7 * Class representing a MediaWiki article and history.
9 * See design.txt for an overview.
10 * Note: edit user interface and cache support functions have been
11 * moved to separate EditPage and HTMLFileCache classes.
20 var $mContentLoaded; //!<
23 var $mGoodAdjustment; //!<
27 var $mRedirectedFrom; //!<
28 var $mRedirectUrl; //!<
29 var $mRevIdFetched; //!<
33 var $mTotalAdjustment; //!<
40 * Constants used by internal components to get rollback results
42 const SUCCESS
= 0; // Operation successful
43 const PERM_DENIED
= 1; // Permission denied
44 const BLOCKED
= 2; // User has been blocked
45 const READONLY
= 3; // Wiki is in read-only mode
46 const BAD_TOKEN
= 4; // Invalid token specified
47 const BAD_TITLE
= 5; // $this is not a valid Article
48 const ALREADY_ROLLED
= 6; // Someone else already rolled this back. $from and $summary will be set
49 const ONLY_AUTHOR
= 7; // User is the only author of the page
52 * Constructor and clear the article
53 * @param $title Reference to a Title object.
54 * @param $oldId Integer revision ID, null to fetch from request, zero for current
56 function __construct( &$title, $oldId = null ) {
57 $this->mTitle
=& $title;
58 $this->mOldId
= $oldId;
63 * Tell the page view functions that this view was redirected
64 * from another page on the wiki.
65 * @param $from Title object.
67 function setRedirectedFrom( $from ) {
68 $this->mRedirectedFrom
= $from;
72 * @return mixed false, Title of in-wiki target, or string with URL
74 function followRedirect() {
75 $text = $this->getContent();
76 $rt = Title
::newFromRedirect( $text );
78 # process if title object is valid and not special:userlogout
80 if( $rt->getInterwiki() != '' ) {
81 if( $rt->isLocal() ) {
82 // Offsite wikis need an HTTP redirect.
84 // This can be hard to reverse and may produce loops,
85 // so they may be disabled in the site configuration.
87 $source = $this->mTitle
->getFullURL( 'redirect=no' );
88 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
91 if( $rt->getNamespace() == NS_SPECIAL
) {
92 // Gotta handle redirects to special pages differently:
93 // Fill the HTTP response "Location" header and ignore
94 // the rest of the page we're on.
96 // This can be hard to reverse, so they may be disabled.
98 if( $rt->isSpecial( 'Userlogout' ) ) {
101 return $rt->getFullURL();
108 // No or invalid redirect
113 * get the title object of the article
115 function getTitle() {
116 return $this->mTitle
;
124 $this->mDataLoaded
= false;
125 $this->mContentLoaded
= false;
127 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
128 $this->mRedirectedFrom
= null; # Title object if set
130 $this->mTimestamp
= $this->mComment
= '';
131 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
132 $this->mTouched
= '19700101000000';
133 $this->mForUpdate
= false;
134 $this->mIsRedirect
= false;
135 $this->mRevIdFetched
= 0;
136 $this->mRedirectUrl
= false;
137 $this->mLatest
= false;
138 $this->mPreparedEdit
= false;
142 * Note that getContent/loadContent do not follow redirects anymore.
143 * If you need to fetch redirectable content easily, try
144 * the shortcut in Article::followContent()
146 * @todo There are still side-effects in this!
147 * In general, you should use the Revision class, not Article,
148 * to fetch text for purposes other than page views.
150 * @return Return the text of this revision
152 function getContent() {
153 global $wgUser, $wgOut;
155 wfProfileIn( __METHOD__
);
157 if ( 0 == $this->getID() ) {
158 wfProfileOut( __METHOD__
);
159 $wgOut->setRobotpolicy( 'noindex,nofollow' );
161 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
162 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
164 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
167 return "<div class='noarticletext'>$ret</div>";
169 $this->loadContent();
170 wfProfileOut( __METHOD__
);
171 return $this->mContent
;
176 * This function returns the text of a section, specified by a number ($section).
177 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
178 * the first section before any such heading (section 0).
180 * If a section contains subsections, these are also returned.
182 * @param $text String: text to look in
183 * @param $section Integer: section number
184 * @return string text of the requested section
187 function getSection($text,$section) {
189 return $wgParser->getSection( $text, $section );
193 * @return int The oldid of the article that is to be shown, 0 for the
196 function getOldID() {
197 if ( is_null( $this->mOldId
) ) {
198 $this->mOldId
= $this->getOldIDFromRequest();
200 return $this->mOldId
;
204 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
206 * @return int The old id for the request
208 function getOldIDFromRequest() {
210 $this->mRedirectUrl
= false;
211 $oldid = $wgRequest->getVal( 'oldid' );
212 if ( isset( $oldid ) ) {
213 $oldid = intval( $oldid );
214 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
215 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
219 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
221 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
222 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
240 * Load the revision (including text) into this object
242 function loadContent() {
243 if ( $this->mContentLoaded
) return;
246 $oldid = $this->getOldID();
248 # Pre-fill content with error message so that if something
249 # fails we'll have something telling us what we intended.
250 $this->mOldId
= $oldid;
251 $this->fetchContent( $oldid );
256 * Fetch a page record with the given conditions
257 * @param Database $dbr
258 * @param array $conditions
261 function pageData( $dbr, $conditions ) {
275 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
276 $row = $dbr->selectRow(
282 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
287 * @param Database $dbr
288 * @param Title $title
290 function pageDataFromTitle( $dbr, $title ) {
291 return $this->pageData( $dbr, array(
292 'page_namespace' => $title->getNamespace(),
293 'page_title' => $title->getDBkey() ) );
297 * @param Database $dbr
300 function pageDataFromId( $dbr, $id ) {
301 return $this->pageData( $dbr, array( 'page_id' => $id ) );
305 * Set the general counter, title etc data loaded from
308 * @param object $data
311 function loadPageData( $data = 'fromdb' ) {
312 if ( $data === 'fromdb' ) {
313 $dbr = $this->getDB();
314 $data = $this->pageDataFromId( $dbr, $this->getId() );
317 $lc =& LinkCache
::singleton();
319 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
321 $this->mTitle
->mArticleID
= $data->page_id
;
323 # Old-fashioned restrictions.
324 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
326 $this->mCounter
= $data->page_counter
;
327 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
328 $this->mIsRedirect
= $data->page_is_redirect
;
329 $this->mLatest
= $data->page_latest
;
331 if ( is_object( $this->mTitle
) ) {
332 $lc->addBadLinkObj( $this->mTitle
);
334 $this->mTitle
->mArticleID
= 0;
337 $this->mDataLoaded
= true;
341 * Get text of an article from database
342 * Does *NOT* follow redirects.
343 * @param int $oldid 0 for whatever the latest revision is
346 function fetchContent( $oldid = 0 ) {
347 if ( $this->mContentLoaded
) {
348 return $this->mContent
;
351 $dbr = $this->getDB();
353 # Pre-fill content with error message so that if something
354 # fails we'll have something telling us what we intended.
355 $t = $this->mTitle
->getPrefixedText();
357 $t .= ',oldid='.$oldid;
359 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
362 $revision = Revision
::newFromId( $oldid );
363 if( is_null( $revision ) ) {
364 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
367 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
369 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
372 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
373 $this->loadPageData( $data );
375 if( !$this->mDataLoaded
) {
376 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
378 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
381 $this->loadPageData( $data );
383 $revision = Revision
::newFromId( $this->mLatest
);
384 if( is_null( $revision ) ) {
385 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
390 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
391 // We should instead work with the Revision object when we need it...
392 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
393 //$this->mContent = $revision->getText();
395 $this->mUser
= $revision->getUser();
396 $this->mUserText
= $revision->getUserText();
397 $this->mComment
= $revision->getComment();
398 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
400 $this->mRevIdFetched
= $revision->getID();
401 $this->mContentLoaded
= true;
402 $this->mRevision
=& $revision;
404 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
406 return $this->mContent
;
410 * Read/write accessor to select FOR UPDATE
412 * @param $x Mixed: FIXME
414 function forUpdate( $x = NULL ) {
415 return wfSetVar( $this->mForUpdate
, $x );
419 * Get the database which should be used for reads
424 return wfGetDB( DB_MASTER
);
428 * Get options for all SELECT statements
430 * @param $options Array: an optional options array which'll be appended to
432 * @return Array: options
434 function getSelectOptions( $options = '' ) {
435 if ( $this->mForUpdate
) {
436 if ( is_array( $options ) ) {
437 $options[] = 'FOR UPDATE';
439 $options = 'FOR UPDATE';
446 * @return int Page ID
449 if( $this->mTitle
) {
450 return $this->mTitle
->getArticleID();
457 * @return bool Whether or not the page exists in the database
460 return $this->getId() != 0;
464 * @return int The view count for the page
466 function getCount() {
467 if ( -1 == $this->mCounter
) {
468 $id = $this->getID();
472 $dbr = wfGetDB( DB_SLAVE
);
473 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
474 'Article::getCount', $this->getSelectOptions() );
477 return $this->mCounter
;
481 * Determine whether a page would be suitable for being counted as an
482 * article in the site_stats table based on the title & its content
484 * @param $text String: text to analyze
487 function isCountable( $text ) {
488 global $wgUseCommaCount;
490 $token = $wgUseCommaCount ?
',' : '[[';
492 $this->mTitle
->isContentPage()
493 && !$this->isRedirect( $text )
494 && in_string( $token, $text );
498 * Tests if the article text represents a redirect
500 * @param $text String: FIXME
503 function isRedirect( $text = false ) {
504 if ( $text === false ) {
505 $this->loadContent();
506 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
508 $titleObj = Title
::newFromRedirect( $text );
510 return $titleObj !== NULL;
514 * Returns true if the currently-referenced revision is the current edit
515 * to this page (and it exists).
518 function isCurrent() {
519 # If no oldid, this is the current version.
520 if ($this->getOldID() == 0)
523 return $this->exists() &&
524 isset( $this->mRevision
) &&
525 $this->mRevision
->isCurrent();
529 * Loads everything except the text
530 * This isn't necessary for all uses, so it's only done if needed.
533 function loadLastEdit() {
534 if ( -1 != $this->mUser
)
537 # New or non-existent articles have no user information
538 $id = $this->getID();
539 if ( 0 == $id ) return;
541 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
542 if( !is_null( $this->mLastRevision
) ) {
543 $this->mUser
= $this->mLastRevision
->getUser();
544 $this->mUserText
= $this->mLastRevision
->getUserText();
545 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
546 $this->mComment
= $this->mLastRevision
->getComment();
547 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
548 $this->mRevIdFetched
= $this->mLastRevision
->getID();
552 function getTimestamp() {
553 // Check if the field has been filled by ParserCache::get()
554 if ( !$this->mTimestamp
) {
555 $this->loadLastEdit();
557 return wfTimestamp(TS_MW
, $this->mTimestamp
);
561 $this->loadLastEdit();
565 function getUserText() {
566 $this->loadLastEdit();
567 return $this->mUserText
;
570 function getComment() {
571 $this->loadLastEdit();
572 return $this->mComment
;
575 function getMinorEdit() {
576 $this->loadLastEdit();
577 return $this->mMinorEdit
;
580 function getRevIdFetched() {
581 $this->loadLastEdit();
582 return $this->mRevIdFetched
;
586 * @todo Document, fixme $offset never used.
587 * @param $limit Integer: default 0.
588 * @param $offset Integer: default 0.
590 function getContributors($limit = 0, $offset = 0) {
591 # XXX: this is expensive; cache this info somewhere.
594 $dbr = wfGetDB( DB_SLAVE
);
595 $revTable = $dbr->tableName( 'revision' );
596 $userTable = $dbr->tableName( 'user' );
597 $user = $this->getUser();
598 $pageId = $this->getId();
600 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
601 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
602 WHERE rev_page = $pageId
603 AND rev_user != $user
604 GROUP BY rev_user, rev_user_text, user_real_name
605 ORDER BY timestamp DESC";
607 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
608 $sql .= ' '. $this->getSelectOptions();
610 $res = $dbr->query($sql, __METHOD__
);
612 while ( $line = $dbr->fetchObject( $res ) ) {
613 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
616 $dbr->freeResult($res);
621 * This is the default action of the script: just view the page of
625 global $wgUser, $wgOut, $wgRequest, $wgContLang;
626 global $wgEnableParserCache, $wgStylePath, $wgParser;
627 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
628 $sk = $wgUser->getSkin();
630 wfProfileIn( __METHOD__
);
632 $parserCache =& ParserCache
::singleton();
633 $ns = $this->mTitle
->getNamespace(); # shortcut
635 # Get variables from query string
636 $oldid = $this->getOldID();
638 # getOldID may want us to redirect somewhere else
639 if ( $this->mRedirectUrl
) {
640 $wgOut->redirect( $this->mRedirectUrl
);
641 wfProfileOut( __METHOD__
);
645 $diff = $wgRequest->getVal( 'diff' );
646 $rcid = $wgRequest->getVal( 'rcid' );
647 $rdfrom = $wgRequest->getVal( 'rdfrom' );
648 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
649 $purge = $wgRequest->getVal( 'action' ) == 'purge';
651 $wgOut->setArticleFlag( true );
653 # Discourage indexing of printable versions, but encourage following
654 if( $wgOut->isPrintable() ) {
655 $policy = 'noindex,follow';
656 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()] ) ) {
657 $policy = $wgArticleRobotPolicies[$this->mTitle
->getPrefixedText()];
658 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
659 # Honour customised robot policies for this namespace
660 $policy = $wgNamespaceRobotPolicies[$ns];
662 # Default to encourage indexing and following links
663 $policy = 'index,follow';
665 $wgOut->setRobotPolicy( $policy );
667 # If we got diff and oldid in the query, we want to see a
668 # diff page instead of the article.
670 if ( !is_null( $diff ) ) {
671 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
673 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid, $purge );
674 // DifferenceEngine directly fetched the revision:
675 $this->mRevIdFetched
= $de->mNewid
;
676 $de->showDiffPage( $diffOnly );
678 // Needed to get the page's current revision
679 $this->loadPageData();
680 if( $diff == 0 ||
$diff == $this->mLatest
) {
681 # Run view updates for current revision only
682 $this->viewUpdates();
684 wfProfileOut( __METHOD__
);
688 if ( empty( $oldid ) && $this->checkTouched() ) {
689 $wgOut->setETag($parserCache->getETag($this, $wgUser));
691 if( $wgOut->checkLastModified( $this->mTouched
) ){
692 wfProfileOut( __METHOD__
);
694 } else if ( $this->tryFileCache() ) {
695 # tell wgOut that output is taken care of
697 $this->viewUpdates();
698 wfProfileOut( __METHOD__
);
703 # Should the parser cache be used?
704 $pcache = $wgEnableParserCache
705 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
708 && !$this->mTitle
->isCssOrJsPage()
709 && !$this->mTitle
->isCssJsSubpage();
710 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
711 if ( $wgUser->getOption( 'stubthreshold' ) ) {
712 wfIncrStats( 'pcache_miss_stub' );
715 $wasRedirected = false;
716 if ( isset( $this->mRedirectedFrom
) ) {
717 // This is an internally redirected page view.
718 // We'll need a backlink to the source page for navigation.
719 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
720 $sk = $wgUser->getSkin();
721 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
722 $s = wfMsg( 'redirectedfrom', $redir );
723 $wgOut->setSubtitle( $s );
725 // Set the fragment if one was specified in the redirect
726 if ( strval( $this->mTitle
->getFragment() ) != '' ) {
727 $fragment = Xml
::escapeJsString( $this->mTitle
->getFragmentForURL() );
728 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
730 $wasRedirected = true;
732 } elseif ( !empty( $rdfrom ) ) {
733 // This is an externally redirected view, from some other wiki.
734 // If it was reported from a trusted site, supply a backlink.
735 global $wgRedirectSources;
736 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
737 $sk = $wgUser->getSkin();
738 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
739 $s = wfMsg( 'redirectedfrom', $redir );
740 $wgOut->setSubtitle( $s );
741 $wasRedirected = true;
746 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
748 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
749 // Ensure that UI elements requiring revision ID have
750 // the correct version information.
751 $wgOut->setRevisionId( $this->mLatest
);
755 if ( !$outputDone ) {
756 $text = $this->getContent();
757 if ( $text === false ) {
758 # Failed to load, replace text with error message
759 $t = $this->mTitle
->getPrefixedText();
761 $t .= ',oldid='.$oldid;
762 $text = wfMsg( 'missingarticle', $t );
764 $text = wfMsg( 'noarticletext', $t );
768 # Another whitelist check in case oldid is altering the title
769 if ( !$this->mTitle
->userCanRead() ) {
770 $wgOut->loginToUse();
775 # We're looking at an old revision
777 if ( !empty( $oldid ) ) {
778 $wgOut->setRobotpolicy( 'noindex,nofollow' );
779 if( is_null( $this->mRevision
) ) {
780 // FIXME: This would be a nice place to load the 'no such page' text.
782 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
783 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
784 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
785 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
786 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
789 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
790 // and we are allowed to see...
798 $wgOut->setRevisionId( $this->getRevIdFetched() );
800 // Pages containing custom CSS or JavaScript get special treatment
801 if( $this->mTitle
->isCssOrJsPage() ||
$this->mTitle
->isCssJsSubpage() ) {
802 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
804 // Give hooks a chance to customise the output
805 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent
, $this->mTitle
, $wgOut ) ) ) {
806 // Wrap the whole lot in a <pre> and don't parse
808 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
809 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
810 $wgOut->addHtml( htmlspecialchars( $this->mContent
) );
811 $wgOut->addHtml( "\n</pre>\n" );
816 elseif ( $rt = Title
::newFromRedirect( $text ) ) {
818 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
819 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
820 # Don't overwrite the subtitle if this was an old revision
821 if( !$wasRedirected && $this->isCurrent() ) {
822 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
824 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
826 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
827 '<span class="redirectText">'.$link.'</span>' );
829 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
830 $wgOut->addParserOutputNoText( $parseout );
831 } else if ( $pcache ) {
832 # Display content and save to parser cache
833 $this->outputWikiText( $text );
835 # Display content, don't attempt to save to parser cache
836 # Don't show section-edit links on old revisions... this way lies madness.
837 if( !$this->isCurrent() ) {
838 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
840 # Display content and don't save to parser cache
841 # With timing hack -- TS 2006-07-26
843 $this->outputWikiText( $text, false );
848 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
849 $this->mTitle
->getPrefixedDBkey()));
852 if( !$this->isCurrent() ) {
853 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
858 /* title may have been set from the cache */
859 $t = $wgOut->getPageTitle();
861 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
864 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
865 if( $ns == NS_USER_TALK
&&
866 User
::isIP( $this->mTitle
->getText() ) ) {
867 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
870 # If we have been passed an &rcid= parameter, we want to give the user a
871 # chance to mark this new article as patrolled.
872 if (!is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
874 "<div class='patrollink'>" .
875 wfMsgHtml( 'markaspatrolledlink',
876 $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml('markaspatrolledtext'),
877 "action=markpatrolled&rcid=$rcid" )
884 if ($wgUseTrackbacks)
885 $this->addTrackbacks();
887 $this->viewUpdates();
888 wfProfileOut( __METHOD__
);
891 function addTrackbacks() {
892 global $wgOut, $wgUser;
894 $dbr = wfGetDB(DB_SLAVE
);
896 /* FROM */ 'trackbacks',
897 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
898 /* WHERE */ array('tb_page' => $this->getID())
901 if (!$dbr->numrows($tbs))
905 while ($o = $dbr->fetchObject($tbs)) {
907 if ($wgUser->isAllowed( 'trackback' )) {
908 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
909 . $o->tb_id
. "&token=" . urlencode( $wgUser->editToken() ) );
910 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
912 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
919 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
922 function deletetrackback() {
923 global $wgUser, $wgRequest, $wgOut, $wgTitle;
925 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
926 $wgOut->addWikitext(wfMsg('sessionfailure'));
930 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
932 if (count($permission_errors)>0)
934 $wgOut->showPermissionsErrorPage( $permission_errors );
938 $db = wfGetDB(DB_MASTER
);
939 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
940 $wgTitle->invalidateCache();
941 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
947 $wgOut->setArticleBodyOnly(true);
952 * Handle action=purge
955 global $wgUser, $wgRequest, $wgOut;
957 if ( $wgUser->isAllowed( 'purge' ) ||
$wgRequest->wasPosted() ) {
958 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
962 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
963 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
964 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
965 $msg = str_replace( '$1',
966 "<form method=\"post\" action=\"$action\">\n" .
967 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
970 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
971 $wgOut->setRobotpolicy( 'noindex,nofollow' );
972 $wgOut->addHTML( $msg );
977 * Perform the actions of a page purging
981 // Invalidate the cache
982 $this->mTitle
->invalidateCache();
985 // Commit the transaction before the purge is sent
986 $dbw = wfGetDB( DB_MASTER
);
987 $dbw->immediateCommit();
990 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
997 * Insert a new empty page record for this article.
998 * This *must* be followed up by creating a revision
999 * and running $this->updateToLatest( $rev_id );
1000 * or else the record will be left in a funky state.
1001 * Best if all done inside a transaction.
1003 * @param Database $dbw
1004 * @return int The newly created page_id key
1007 function insertOn( $dbw ) {
1008 wfProfileIn( __METHOD__
);
1010 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1011 $dbw->insert( 'page', array(
1012 'page_id' => $page_id,
1013 'page_namespace' => $this->mTitle
->getNamespace(),
1014 'page_title' => $this->mTitle
->getDBkey(),
1015 'page_counter' => 0,
1016 'page_restrictions' => '',
1017 'page_is_redirect' => 0, # Will set this shortly...
1019 'page_random' => wfRandom(),
1020 'page_touched' => $dbw->timestamp(),
1021 'page_latest' => 0, # Fill this in shortly...
1022 'page_len' => 0, # Fill this in shortly...
1024 $newid = $dbw->insertId();
1026 $this->mTitle
->resetArticleId( $newid );
1028 wfProfileOut( __METHOD__
);
1033 * Update the page record to point to a newly saved revision.
1035 * @param Database $dbw
1036 * @param Revision $revision For ID number, and text used to set
1037 length and redirect status fields
1038 * @param int $lastRevision If given, will not overwrite the page field
1039 * when different from the currently set value.
1040 * Giving 0 indicates the new page flag should
1042 * @param bool $lastRevIsRedirect If given, will optimize adding and
1043 * removing rows in redirect table.
1044 * @return bool true on success, false on failure
1047 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1048 wfProfileIn( __METHOD__
);
1050 $text = $revision->getText();
1051 $rt = Title
::newFromRedirect( $text );
1053 $conditions = array( 'page_id' => $this->getId() );
1054 if( !is_null( $lastRevision ) ) {
1055 # An extra check against threads stepping on each other
1056 $conditions['page_latest'] = $lastRevision;
1059 $dbw->update( 'page',
1061 'page_latest' => $revision->getId(),
1062 'page_touched' => $dbw->timestamp(),
1063 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1064 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1065 'page_len' => strlen( $text ),
1070 $result = $dbw->affectedRows() != 0;
1073 // FIXME: Should the result from updateRedirectOn() be returned instead?
1074 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1077 wfProfileOut( __METHOD__
);
1082 * Add row to the redirect table if this is a redirect, remove otherwise.
1084 * @param Database $dbw
1085 * @param $redirectTitle a title object pointing to the redirect target,
1086 * or NULL if this is not a redirect
1087 * @param bool $lastRevIsRedirect If given, will optimize adding and
1088 * removing rows in redirect table.
1089 * @return bool true on success, false on failure
1092 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1094 // Always update redirects (target link might have changed)
1095 // Update/Insert if we don't know if the last revision was a redirect or not
1096 // Delete if changing from redirect to non-redirect
1097 $isRedirect = !is_null($redirectTitle);
1098 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1100 wfProfileIn( __METHOD__
);
1104 // This title is a redirect, Add/Update row in the redirect table
1105 $set = array( /* SET */
1106 'rd_namespace' => $redirectTitle->getNamespace(),
1107 'rd_title' => $redirectTitle->getDBkey(),
1108 'rd_from' => $this->getId(),
1111 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1113 // This is not a redirect, remove row from redirect table
1114 $where = array( 'rd_from' => $this->getId() );
1115 $dbw->delete( 'redirect', $where, __METHOD__
);
1118 wfProfileOut( __METHOD__
);
1119 return ( $dbw->affectedRows() != 0 );
1126 * If the given revision is newer than the currently set page_latest,
1127 * update the page record. Otherwise, do nothing.
1129 * @param Database $dbw
1130 * @param Revision $revision
1132 function updateIfNewerOn( &$dbw, $revision ) {
1133 wfProfileIn( __METHOD__
);
1135 $row = $dbw->selectRow(
1136 array( 'revision', 'page' ),
1137 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1139 'page_id' => $this->getId(),
1140 'page_latest=rev_id' ),
1143 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1144 wfProfileOut( __METHOD__
);
1147 $prev = $row->rev_id
;
1148 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1150 # No or missing previous revision; mark the page as new
1152 $lastRevIsRedirect = null;
1155 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1156 wfProfileOut( __METHOD__
);
1161 * @return string Complete article text, or null if error
1163 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1164 wfProfileIn( __METHOD__
);
1166 if( $section == '' ) {
1167 // Whole-page edit; let the text through unmolested.
1169 if( is_null( $edittime ) ) {
1170 $rev = Revision
::newFromTitle( $this->mTitle
);
1172 $dbw = wfGetDB( DB_MASTER
);
1173 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1175 if( is_null( $rev ) ) {
1176 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1177 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1180 $oldtext = $rev->getText();
1182 if( $section == 'new' ) {
1183 # Inserting a new section
1184 $subject = $summary ?
wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1185 $text = strlen( trim( $oldtext ) ) > 0
1186 ?
"{$oldtext}\n\n{$subject}{$text}"
1187 : "{$subject}{$text}";
1189 # Replacing an existing section; roll out the big guns
1191 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1196 wfProfileOut( __METHOD__
);
1201 * @deprecated use Article::doEdit()
1203 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1204 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1205 ( $isminor ? EDIT_MINOR
: 0 ) |
1206 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1208 # If this is a comment, add the summary as headline
1209 if ( $comment && $summary != "" ) {
1210 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1213 $this->doEdit( $text, $summary, $flags );
1215 $dbw = wfGetDB( DB_MASTER
);
1217 if (!$this->mTitle
->userIsWatching()) {
1223 if ( $this->mTitle
->userIsWatching() ) {
1229 $this->doRedirect( $this->isRedirect( $text ) );
1233 * @deprecated use Article::doEdit()
1235 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1236 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1237 ( $minor ? EDIT_MINOR
: 0 ) |
1238 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1240 $good = $this->doEdit( $text, $summary, $flags );
1242 $dbw = wfGetDB( DB_MASTER
);
1244 if (!$this->mTitle
->userIsWatching()) {
1250 if ( $this->mTitle
->userIsWatching() ) {
1257 $extraq = ''; // Give extensions a chance to modify URL query on update
1258 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1260 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1268 * Change an existing article or create a new article. Updates RC and all necessary caches,
1269 * optionally via the deferred update array.
1271 * $wgUser must be set before calling this function.
1273 * @param string $text New text
1274 * @param string $summary Edit summary
1275 * @param integer $flags bitfield:
1277 * Article is known or assumed to be non-existent, create a new one
1279 * Article is known or assumed to be pre-existing, update it
1281 * Mark this edit minor, if the user is allowed to do so
1283 * Do not log the change in recentchanges
1285 * Mark the edit a "bot" edit regardless of user rights
1286 * EDIT_DEFER_UPDATES
1287 * Defer some of the updates until the end of index.php
1289 * Fill in blank summaries with generated text where possible
1291 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1292 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1293 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1294 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1295 * to MediaWiki's performance-optimised locking strategy.
1297 * @return bool success
1299 function doEdit( $text, $summary, $flags = 0 ) {
1300 global $wgUser, $wgDBtransactions;
1302 wfProfileIn( __METHOD__
);
1305 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1306 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1308 $flags |
= EDIT_UPDATE
;
1314 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1315 &$summary, $flags & EDIT_MINOR
,
1316 null, null, &$flags ) ) )
1318 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1319 wfProfileOut( __METHOD__
);
1323 # Silently ignore EDIT_MINOR if not allowed
1324 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1325 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1327 $oldtext = $this->getContent();
1328 $oldsize = strlen( $oldtext );
1330 # Provide autosummaries if one is not provided.
1331 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '')
1332 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1334 $editInfo = $this->prepareTextForEdit( $text );
1335 $text = $editInfo->pst
;
1336 $newsize = strlen( $text );
1338 $dbw = wfGetDB( DB_MASTER
);
1339 $now = wfTimestampNow();
1341 if ( $flags & EDIT_UPDATE
) {
1342 # Update article, but only if changed.
1344 # Make sure the revision is either completely inserted or not inserted at all
1345 if( !$wgDBtransactions ) {
1346 $userAbort = ignore_user_abort( true );
1352 if ( 0 != strcmp( $text, $oldtext ) ) {
1353 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1354 - (int)$this->isCountable( $oldtext );
1355 $this->mTotalAdjustment
= 0;
1357 $lastRevision = $dbw->selectField(
1358 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1360 if ( !$lastRevision ) {
1361 # Article gone missing
1362 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1363 wfProfileOut( __METHOD__
);
1367 $revision = new Revision( array(
1368 'page' => $this->getId(),
1369 'comment' => $summary,
1370 'minor_edit' => $isminor,
1375 $revisionId = $revision->insertOn( $dbw );
1378 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1381 /* Belated edit conflict! Run away!! */
1385 # Update recentchanges
1386 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1387 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1388 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1391 # Mark as patrolled if the user can do so
1392 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1393 RecentChange
::markPatrolled( $rcid );
1394 PatrolLog
::record( $rcid, true );
1397 $wgUser->incEditCount();
1402 // Keep the same revision ID, but do some updates on it
1403 $revisionId = $this->getRevIdFetched();
1404 // Update page_touched, this is usually implicit in the page update
1405 // Other cache updates are done in onArticleEdit()
1406 $this->mTitle
->invalidateCache();
1409 if( !$wgDBtransactions ) {
1410 ignore_user_abort( $userAbort );
1414 # Invalidate cache of this article and all pages using this article
1415 # as a template. Partly deferred.
1416 Article
::onArticleEdit( $this->mTitle
);
1418 # Update links tables, site stats, etc.
1419 $changed = ( strcmp( $oldtext, $text ) != 0 );
1420 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1423 # Create new article
1425 # Set statistics members
1426 # We work out if it's countable after PST to avoid counter drift
1427 # when articles are created with {{subst:}}
1428 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1429 $this->mTotalAdjustment
= 1;
1433 # Add the page record; stake our claim on this title!
1434 # This will fail with a database query exception if the article already exists
1435 $newid = $this->insertOn( $dbw );
1437 # Save the revision text...
1438 $revision = new Revision( array(
1440 'comment' => $summary,
1441 'minor_edit' => $isminor,
1444 $revisionId = $revision->insertOn( $dbw );
1446 $this->mTitle
->resetArticleID( $newid );
1448 # Update the page record with revision data
1449 $this->updateRevisionOn( $dbw, $revision, 0 );
1451 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1452 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1453 '', strlen( $text ), $revisionId );
1454 # Mark as patrolled if the user can
1455 if( ($GLOBALS['wgUseRCPatrol'] ||
$GLOBALS['wgUseNPPatrol']) && $wgUser->isAllowed( 'autopatrol' ) ) {
1456 RecentChange
::markPatrolled( $rcid );
1457 PatrolLog
::record( $rcid, true );
1460 $wgUser->incEditCount();
1463 # Update links, etc.
1464 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1467 Article
::onArticleCreate( $this->mTitle
);
1469 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text, $summary,
1470 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1473 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1478 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1479 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1482 wfProfileOut( __METHOD__
);
1487 * @deprecated wrapper for doRedirect
1489 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1490 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1494 * Output a redirect back to the article.
1495 * This is typically used after an edit.
1497 * @param boolean $noRedir Add redirect=no
1498 * @param string $sectionAnchor section to redirect to, including "#"
1500 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1503 $query = 'redirect=no';
1505 $query .= "&$query";
1509 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1513 * Mark this particular edit/page as patrolled
1515 function markpatrolled() {
1516 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1517 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1519 # Check patrol config options
1521 if ( !($wgUseNPPatrol ||
$wgUseRCPatrol)) {
1522 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1526 # If we haven't been given an rc_id value, we can't do anything
1527 $rcid = (int) $wgRequest->getVal('rcid');
1528 $rc = $rcid ? RecentChange
::newFromId($rcid) : null;
1529 if ( is_null ( $rc ) )
1531 $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1535 if ( !$wgUseRCPatrol && $rc->mAttribs
['rc_type'] != RC_NEW
) {
1536 // Only new pages can be patrolled if the general patrolling is off....???
1537 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1539 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1544 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'patrol', $wgUser );
1546 if (count($permission_errors)>0)
1548 $wgOut->showPermissionsErrorPage( $permission_errors );
1552 # Handle the 'MarkPatrolled' hook
1553 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1557 #It would be nice to see where the user had actually come from, but for now just guess
1558 $returnto = $rc->mAttribs
['rc_type'] == RC_NEW ?
'Newpages' : 'Recentchanges';
1559 $return = Title
::makeTitle( NS_SPECIAL
, $returnto );
1561 # If it's left up to us, check that the user is allowed to patrol this edit
1562 # If the user has the "autopatrol" right, then we'll assume there are no
1563 # other conditions stopping them doing so
1564 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1565 $rc = RecentChange
::newFromId( $rcid );
1566 # Graceful error handling, as we've done before here...
1567 # (If the recent change doesn't exist, then it doesn't matter whether
1568 # the user is allowed to patrol it or not; nothing is going to happen
1569 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1570 # The user made this edit, and can't patrol it
1571 # Tell them so, and then back off
1572 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1573 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
1574 $wgOut->returnToMain( false, $return );
1579 # Mark the edit as patrolled
1580 RecentChange
::markPatrolled( $rcid );
1581 PatrolLog
::record( $rcid );
1582 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1585 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1586 $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
1587 $wgOut->returnToMain( false, $return );
1591 * User-interface handler for the "watch" action
1596 global $wgUser, $wgOut;
1598 if ( $wgUser->isAnon() ) {
1599 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1602 if ( wfReadOnly() ) {
1603 $wgOut->readOnlyPage();
1607 if( $this->doWatch() ) {
1608 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1609 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1611 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1612 $text = wfMsg( 'addedwatchtext', $link );
1613 $wgOut->addWikiText( $text );
1616 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1620 * Add this page to $wgUser's watchlist
1621 * @return bool true on successful watch operation
1623 function doWatch() {
1625 if( $wgUser->isAnon() ) {
1629 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1630 $wgUser->addWatch( $this->mTitle
);
1632 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1639 * User interface handler for the "unwatch" action.
1641 function unwatch() {
1643 global $wgUser, $wgOut;
1645 if ( $wgUser->isAnon() ) {
1646 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1649 if ( wfReadOnly() ) {
1650 $wgOut->readOnlyPage();
1654 if( $this->doUnwatch() ) {
1655 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1656 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1658 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1659 $text = wfMsg( 'removedwatchtext', $link );
1660 $wgOut->addWikiText( $text );
1663 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1667 * Stop watching a page
1668 * @return bool true on successful unwatch
1670 function doUnwatch() {
1672 if( $wgUser->isAnon() ) {
1676 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1677 $wgUser->removeWatch( $this->mTitle
);
1679 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1686 * action=protect handler
1688 function protect() {
1689 $form = new ProtectionForm( $this );
1694 * action=unprotect handler (alias)
1696 function unprotect() {
1701 * Update the article's restriction field, and leave a log entry.
1703 * @param array $limit set of restriction keys
1704 * @param string $reason
1705 * @return bool true on success
1707 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1708 global $wgUser, $wgRestrictionTypes, $wgContLang;
1710 $id = $this->mTitle
->getArticleID();
1711 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1719 // Take this opportunity to purge out expired restrictions
1720 Title
::purgeExpiredRestrictions();
1722 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1723 # we expect a single selection, but the schema allows otherwise.
1725 foreach( $wgRestrictionTypes as $action )
1726 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1728 $current = Article
::flattenRestrictions( $current );
1729 $updated = Article
::flattenRestrictions( $limit );
1731 $changed = ( $current != $updated );
1732 $changed = $changed ||
($this->mTitle
->areRestrictionsCascading() != $cascade);
1733 $changed = $changed ||
($this->mTitle
->mRestrictionsExpiry
!= $expiry);
1734 $protect = ( $updated != '' );
1736 # If nothing's changed, do nothing
1738 global $wgGroupPermissions;
1739 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1741 $dbw = wfGetDB( DB_MASTER
);
1743 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1745 $expiry_description = '';
1746 if ( $encodedExpiry != 'infinity' ) {
1747 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1750 # Prepare a null revision to be added to the history
1751 $modified = $current != '' && $protect;
1753 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1755 $comment_type = 'unprotectedarticle';
1757 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1759 foreach( $limit as $action => $restrictions ) {
1760 # Check if the group level required to edit also can protect pages
1761 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1762 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );
1765 $cascade_description = '';
1767 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1771 $comment .= ": $reason";
1773 $comment .= " [$updated]";
1774 if ( $expiry_description && $protect )
1775 $comment .= "$expiry_description";
1777 $comment .= "$cascade_description";
1779 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1780 $nullRevId = $nullRevision->insertOn( $dbw );
1782 # Update restrictions table
1783 foreach( $limit as $action => $restrictions ) {
1784 if ($restrictions != '' ) {
1785 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1786 array( 'pr_page' => $id, 'pr_type' => $action
1787 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ?
1 : 0
1788 , 'pr_expiry' => $encodedExpiry ), __METHOD__
);
1790 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1791 'pr_type' => $action ), __METHOD__
);
1795 # Update page record
1796 $dbw->update( 'page',
1798 'page_touched' => $dbw->timestamp(),
1799 'page_restrictions' => '',
1800 'page_latest' => $nullRevId
1801 ), array( /* WHERE */
1803 ), 'Article::protect'
1805 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1807 # Update the protection log
1808 $log = new LogPage( 'protect' );
1811 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1813 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1817 } # End "changed" check
1823 * Take an array of page restrictions and flatten it to a string
1824 * suitable for insertion into the page_restrictions field.
1825 * @param array $limit
1829 function flattenRestrictions( $limit ) {
1830 if( !is_array( $limit ) ) {
1831 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1835 foreach( $limit as $action => $restrictions ) {
1836 if( $restrictions != '' ) {
1837 $bits[] = "$action=$restrictions";
1840 return implode( ':', $bits );
1844 * Auto-generates a deletion reason
1845 * @param bool &$hashistory Whether the page has a history
1847 public function generateReason(&$hashistory)
1850 $dbw = wfGetDB(DB_MASTER
);
1851 // Get the last revision
1852 $rev = Revision
::newFromTitle($this->mTitle
);
1855 // Get the article's contents
1856 $contents = $rev->getText();
1858 // If the page is blank, use the text from the previous revision,
1859 // which can only be blank if there's a move/import/protect dummy revision involved
1862 $prev = $rev->getPrevious();
1865 $contents = $prev->getText();
1870 // Find out if there was only one contributor
1871 // Only scan the last 20 revisions
1873 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__
,
1874 array('LIMIT' => $limit));
1876 // This page has no revisions, which is very weird
1878 if($res->numRows() > 1)
1881 $hasHistory = false;
1882 $row = $dbw->fetchObject($res);
1883 $onlyAuthor = $row->rev_user_text
;
1884 // Try to find a second contributor
1885 while(($row = $dbw->fetchObject($res)))
1886 if($row->rev_user_text
!= $onlyAuthor)
1888 $onlyAuthor = false;
1891 $dbw->freeResult($res);
1893 // Generate the summary with a '$1' placeholder
1895 // The current revision is blank and the one before is also
1896 // blank. It's just not our lucky day
1897 $reason = wfMsgForContent('exbeforeblank', '$1');
1901 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1903 $reason = wfMsgForContent('excontent', '$1');
1906 // Replace newlines with spaces to prevent uglyness
1907 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1908 // Calculate the maximum amount of chars to get
1909 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1910 $maxLength = 255 - (strlen($reason) - 2) - 3;
1911 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1912 // Remove possible unfinished links
1913 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1914 // Now replace the '$1' placeholder
1915 $reason = str_replace( '$1', $contents, $reason );
1921 * UI entry point for page deletion
1924 global $wgUser, $wgOut, $wgRequest;
1925 $confirm = $wgRequest->wasPosted() &&
1926 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1927 $reason = $wgRequest->getText( 'wpReason' );
1929 # This code desperately needs to be totally rewritten
1932 $permission_errors = $this->mTitle
->getUserPermissionsErrors( 'delete', $wgUser );
1934 if (count($permission_errors)>0)
1936 $wgOut->showPermissionsErrorPage( $permission_errors );
1940 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1942 # Better double-check that it hasn't been deleted yet!
1943 $dbw = wfGetDB( DB_MASTER
);
1944 $conds = $this->mTitle
->pageCond();
1945 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1946 if ( $latest === false ) {
1947 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1952 $this->doDelete( $reason );
1953 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1955 } elseif( $this->mTitle
->userIsWatching() ) {
1961 // Generate deletion reason
1962 $hasHistory = false;
1963 $reason = $this->generateReason($hasHistory);
1965 // If the page has a history, insert a warning
1966 if( $hasHistory && !$confirm ) {
1967 $skin=$wgUser->getSkin();
1968 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1971 return $this->confirmDelete( '', $reason );
1975 * Get the last N authors
1976 * @param int $num Number of revisions to get
1977 * @param string $revLatest The latest rev_id, selected from the master (optional)
1978 * @return array Array of authors, duplicates not removed
1980 function getLastNAuthors( $num, $revLatest = 0 ) {
1981 wfProfileIn( __METHOD__
);
1983 // First try the slave
1984 // If that doesn't have the latest revision, try the master
1986 $db = wfGetDB( DB_SLAVE
);
1988 $res = $db->select( array( 'page', 'revision' ),
1989 array( 'rev_id', 'rev_user_text' ),
1991 'page_namespace' => $this->mTitle
->getNamespace(),
1992 'page_title' => $this->mTitle
->getDBkey(),
1993 'rev_page = page_id'
1994 ), __METHOD__
, $this->getSelectOptions( array(
1995 'ORDER BY' => 'rev_timestamp DESC',
2000 wfProfileOut( __METHOD__
);
2003 $row = $db->fetchObject( $res );
2004 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
2005 $db = wfGetDB( DB_MASTER
);
2010 } while ( $continue );
2012 $authors = array( $row->rev_user_text
);
2013 while ( $row = $db->fetchObject( $res ) ) {
2014 $authors[] = $row->rev_user_text
;
2016 wfProfileOut( __METHOD__
);
2021 * Output deletion confirmation dialog
2023 function confirmDelete( $par, $reason ) {
2024 global $wgOut, $wgUser;
2026 wfDebug( "Article::confirmDelete\n" );
2028 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
2029 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
2030 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2031 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
2033 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
2035 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
2036 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
2037 $token = htmlspecialchars( $wgUser->editToken() );
2038 $watch = Xml
::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) ||
$this->mTitle
->userIsWatching(), array( 'tabindex' => '2' ) );
2041 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
2045 <label for='wpReason'>{$delcom}:</label>
2048 <input type='text' maxlength='255' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
2058 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
2062 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
2065 $wgOut->returnToMain( false, $this->mTitle
);
2067 $this->showLogExtract( $wgOut );
2072 * Show relevant lines from the deletion log
2074 function showLogExtract( $out ) {
2075 $out->addHtml( '<h2>' . htmlspecialchars( LogPage
::logName( 'delete' ) ) . '</h2>' );
2076 $logViewer = new LogViewer(
2079 array( 'page' => $this->mTitle
->getPrefixedText(),
2080 'type' => 'delete' ) ) ) );
2081 $logViewer->showList( $out );
2086 * Perform a deletion and output success or failure messages
2088 function doDelete( $reason ) {
2089 global $wgOut, $wgUser;
2090 wfDebug( __METHOD__
."\n" );
2092 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2093 if ( $this->doDeleteArticle( $reason ) ) {
2094 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2096 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2097 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2099 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2100 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2102 $wgOut->addWikiText( $text );
2103 $wgOut->returnToMain( false );
2104 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2106 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
2112 * Back-end article deletion
2113 * Deletes the article with database consistency, writes logs, purges caches
2116 function doDeleteArticle( $reason ) {
2117 global $wgUseSquid, $wgDeferredUpdateList;
2118 global $wgUseTrackbacks;
2120 wfDebug( __METHOD__
."\n" );
2122 $dbw = wfGetDB( DB_MASTER
);
2123 $ns = $this->mTitle
->getNamespace();
2124 $t = $this->mTitle
->getDBkey();
2125 $id = $this->mTitle
->getArticleID();
2127 if ( $t == '' ||
$id == 0 ) {
2131 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2132 array_push( $wgDeferredUpdateList, $u );
2134 // For now, shunt the revision data into the archive table.
2135 // Text is *not* removed from the text table; bulk storage
2136 // is left intact to avoid breaking block-compression or
2137 // immutable storage schemes.
2139 // For backwards compatibility, note that some older archive
2140 // table entries will have ar_text and ar_flags fields still.
2142 // In the future, we may keep revisions and mark them with
2143 // the rev_deleted field, which is reserved for this purpose.
2144 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2146 'ar_namespace' => 'page_namespace',
2147 'ar_title' => 'page_title',
2148 'ar_comment' => 'rev_comment',
2149 'ar_user' => 'rev_user',
2150 'ar_user_text' => 'rev_user_text',
2151 'ar_timestamp' => 'rev_timestamp',
2152 'ar_minor_edit' => 'rev_minor_edit',
2153 'ar_rev_id' => 'rev_id',
2154 'ar_text_id' => 'rev_text_id',
2155 'ar_text' => '\'\'', // Be explicit to appease
2156 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2157 'ar_len' => 'rev_len',
2158 'ar_page_id' => 'page_id',
2161 'page_id = rev_page'
2165 # Delete restrictions for it
2166 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2168 # Now that it's safely backed up, delete it
2169 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2171 # If using cascading deletes, we can skip some explicit deletes
2172 if ( !$dbw->cascadingDeletes() ) {
2174 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2176 if ($wgUseTrackbacks)
2177 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
2179 # Delete outgoing links
2180 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2181 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2182 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2183 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2184 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2185 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2186 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2189 # If using cleanup triggers, we can skip some manual deletes
2190 if ( !$dbw->cleanupTriggers() ) {
2192 # Clean up recentchanges entries...
2193 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2197 Article
::onArticleDelete( $this->mTitle
);
2200 $log = new LogPage( 'delete' );
2201 $log->addEntry( 'delete', $this->mTitle
, $reason );
2203 # Clear the cached article id so the interface doesn't act like we exist
2204 $this->mTitle
->resetArticleID( 0 );
2205 $this->mTitle
->mArticleID
= 0;
2210 * Roll back the most recent consecutive set of edits to a page
2211 * from the same user; fails if there are no eligible edits to
2212 * roll back to, e.g. user is the sole contributor
2214 * @param string $fromP - Name of the user whose edits to rollback.
2215 * @param string $summary - Custom summary. Set to default summary if empty.
2216 * @param string $token - Rollback token.
2217 * @param bool $bot - If true, mark all reverted edits as bot.
2219 * @param array $resultDetails contains result-specific dict of additional values
2220 * ALREADY_ROLLED : 'current' (rev)
2221 * SUCCESS : 'summary' (str), 'current' (rev), 'target' (rev)
2223 * @return self::SUCCESS on succes, self::* on failure
2225 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2226 global $wgUser, $wgUseRCPatrol;
2227 $resultDetails = null;
2229 # Just in case it's being called from elsewhere
2231 if( $wgUser->isAllowed( 'rollback' ) && $this->mTitle
->userCan( 'edit' ) ) {
2232 if( $wgUser->isBlocked() ) {
2233 return self
::BLOCKED
;
2236 return self
::PERM_DENIED
;
2239 if ( wfReadOnly() ) {
2240 return self
::READONLY
;
2243 if( !$wgUser->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) )
2244 return self
::BAD_TOKEN
;
2246 $dbw = wfGetDB( DB_MASTER
);
2248 # Get the last editor
2249 $current = Revision
::newFromTitle( $this->mTitle
);
2250 if( is_null( $current ) ) {
2251 # Something wrong... no page?
2252 return self
::BAD_TITLE
;
2255 $from = str_replace( '_', ' ', $fromP );
2256 if( $from != $current->getUserText() ) {
2257 $resultDetails = array( 'current' => $current );
2258 return self
::ALREADY_ROLLED
;
2261 # Get the last edit not by this guy
2262 $user = intval( $current->getUser() );
2263 $user_text = $dbw->addQuotes( $current->getUserText() );
2264 $s = $dbw->selectRow( 'revision',
2265 array( 'rev_id', 'rev_timestamp' ),
2267 'rev_page' => $current->getPage(),
2268 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2271 'USE INDEX' => 'page_timestamp',
2272 'ORDER BY' => 'rev_timestamp DESC' )
2274 if( $s === false ) {
2276 return self
::ONLY_AUTHOR
;
2281 # Mark all reverted edits as bot
2284 if ( $wgUseRCPatrol ) {
2285 # Mark all reverted edits as patrolled
2286 $set['rc_patrolled'] = 1;
2290 $dbw->update( 'recentchanges', $set,
2292 'rc_cur_id' => $current->getPage(),
2293 'rc_user_text' => $current->getUserText(),
2294 "rc_timestamp > '{$s->rev_timestamp}'",
2299 # Get the edit summary
2300 $target = Revision
::newFromId( $s->rev_id
);
2301 if( empty( $summary ) )
2302 $summary = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2305 $flags = EDIT_UPDATE | EDIT_MINOR
;
2307 $flags |
= EDIT_FORCE_BOT
;
2308 $this->doEdit( $target->getText(), $summary, $flags );
2310 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2312 $resultDetails = array(
2313 'summary' => $summary,
2314 'current' => $current,
2315 'target' => $target,
2317 return self
::SUCCESS
;
2321 * User interface for rollback operations
2323 function rollback() {
2324 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2328 # Skip the permissions-checking in doRollback() itself, by checking permissions here.
2330 $perm_errors = array_merge( $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser ),
2331 $this->mTitle
->getUserPermissionsErrors( 'rollback', $wgUser ) );
2333 if (count($perm_errors)) {
2334 $wgOut->showPermissionsErrorPage( $perm_errors );
2338 $result = $this->doRollback(
2339 $wgRequest->getVal( 'from' ),
2340 $wgRequest->getText( 'summary' ),
2341 $wgRequest->getVal( 'token' ),
2342 $wgRequest->getBool( 'bot' ),
2348 $wgOut->blockedPage();
2350 case self
::PERM_DENIED
:
2351 $wgOut->permissionRequired( 'rollback' );
2353 case self
::READONLY
:
2354 $wgOut->readOnlyPage( $this->getContent() );
2356 case self
::BAD_TOKEN
:
2357 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2358 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2360 case self
::BAD_TITLE
:
2361 $wgOut->addHtml( wfMsg( 'notanarticle' ) );
2363 case self
::ALREADY_ROLLED
:
2364 $current = $details['current'];
2365 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2366 $wgOut->addWikiText(
2367 wfMsg( 'alreadyrolled',
2368 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2369 htmlspecialchars( $wgRequest->getVal( 'from' ) ),
2370 htmlspecialchars( $current->getUserText() )
2373 if( $current->getComment() != '' ) {
2374 $wgOut->addHtml( wfMsg( 'editcomment',
2375 $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
2378 case self
::ONLY_AUTHOR
:
2379 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2380 $wgOut->addHtml( wfMsg( 'cantrollback' ) );
2383 $current = $details['current'];
2384 $target = $details['target'];
2385 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2386 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2387 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2388 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2389 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2390 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2391 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2392 $wgOut->returnToMain( false, $this->mTitle
);
2395 throw new MWException( __METHOD__
. ": Unknown return value `{$result}`" );
2402 * Do standard deferred updates after page view
2405 function viewUpdates() {
2406 global $wgDeferredUpdateList;
2408 if ( 0 != $this->getID() ) {
2409 global $wgDisableCounters;
2410 if( !$wgDisableCounters ) {
2411 Article
::incViewCount( $this->getID() );
2412 $u = new SiteStatsUpdate( 1, 0, 0 );
2413 array_push( $wgDeferredUpdateList, $u );
2417 # Update newtalk / watchlist notification status
2419 $wgUser->clearNotification( $this->mTitle
);
2423 * Prepare text which is about to be saved.
2424 * Returns a stdclass with source, pst and output members
2426 function prepareTextForEdit( $text, $revid=null ) {
2427 if ( $this->mPreparedEdit
&& $this->mPreparedEdit
->newText
== $text && $this->mPreparedEdit
->revid
== $revid) {
2429 return $this->mPreparedEdit
;
2432 $edit = (object)array();
2433 $edit->revid
= $revid;
2434 $edit->newText
= $text;
2435 $edit->pst
= $this->preSaveTransform( $text );
2436 $options = new ParserOptions
;
2437 $options->setTidy( true );
2438 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $options, true, true, $revid );
2439 $edit->oldText
= $this->getContent();
2440 $this->mPreparedEdit
= $edit;
2445 * Do standard deferred updates after page edit.
2446 * Update links tables, site stats, search index and message cache.
2447 * Every 100th edit, prune the recent changes table.
2450 * @param $text New text of the article
2451 * @param $summary Edit summary
2452 * @param $minoredit Minor edit
2453 * @param $timestamp_of_pagechange Timestamp associated with the page change
2454 * @param $newid rev_id value of the new revision
2455 * @param $changed Whether or not the content actually changed
2457 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2458 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2460 wfProfileIn( __METHOD__
);
2463 # Be careful not to double-PST: $text is usually already PST-ed once
2464 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2465 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2466 $editInfo = $this->prepareTextForEdit( $text, $newid );
2468 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2469 $editInfo = $this->mPreparedEdit
;
2472 # Save it to the parser cache
2473 $parserCache =& ParserCache
::singleton();
2474 $parserCache->save( $editInfo->output
, $this, $wgUser );
2476 # Update the links tables
2477 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2480 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2481 if ( 0 == mt_rand( 0, 99 ) ) {
2482 // Flush old entries from the `recentchanges` table; we do this on
2483 // random requests so as to avoid an increase in writes for no good reason
2485 $dbw = wfGetDB( DB_MASTER
);
2486 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2487 $recentchanges = $dbw->tableName( 'recentchanges' );
2488 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2489 $dbw->query( $sql );
2493 $id = $this->getID();
2494 $title = $this->mTitle
->getPrefixedDBkey();
2495 $shortTitle = $this->mTitle
->getDBkey();
2498 wfProfileOut( __METHOD__
);
2502 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2503 array_push( $wgDeferredUpdateList, $u );
2504 $u = new SearchUpdate( $id, $title, $text );
2505 array_push( $wgDeferredUpdateList, $u );
2507 # If this is another user's talk page, update newtalk
2508 # Don't do this if $changed = false otherwise some idiot can null-edit a
2509 # load of user talk pages and piss people off, nor if it's a minor edit
2510 # by a properly-flagged bot.
2511 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2512 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2513 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2514 $other = User
::newFromName( $shortTitle );
2515 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2516 // An anonymous user
2517 $other = new User();
2518 $other->setName( $shortTitle );
2521 $other->setNewtalk( true );
2526 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2527 $wgMessageCache->replace( $shortTitle, $text );
2530 wfProfileOut( __METHOD__
);
2534 * Perform article updates on a special page creation.
2536 * @param Revision $rev
2538 * @todo This is a shitty interface function. Kill it and replace the
2539 * other shitty functions like editUpdates and such so it's not needed
2542 function createUpdates( $rev ) {
2543 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2544 $this->mTotalAdjustment
= 1;
2545 $this->editUpdates( $rev->getText(), $rev->getComment(),
2546 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2550 * Generate the navigation links when browsing through an article revisions
2551 * It shows the information as:
2552 * Revision as of \<date\>; view current revision
2553 * \<- Previous version | Next Version -\>
2556 * @param string $oldid Revision ID of this article revision
2558 function setOldSubtitle( $oldid=0 ) {
2559 global $wgLang, $wgOut, $wgUser;
2561 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2565 $revision = Revision
::newFromId( $oldid );
2567 $current = ( $oldid == $this->mLatest
);
2568 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2569 $sk = $wgUser->getSkin();
2571 ?
wfMsg( 'currentrevisionlink' )
2572 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2575 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2576 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2578 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2579 : wfMsg( 'previousrevision' );
2581 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2583 $nextlink = $current
2584 ?
wfMsg( 'nextrevision' )
2585 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2586 $nextdiff = $current
2588 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2590 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2591 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2593 $m = wfMsg( 'revision-info-current' );
2594 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2595 ?
'revision-info-current'
2598 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2599 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2600 $wgOut->setSubtitle( $r );
2604 * This function is called right before saving the wikitext,
2605 * so we can do things like signatures and links-in-context.
2607 * @param string $text
2609 function preSaveTransform( $text ) {
2610 global $wgParser, $wgUser;
2611 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2614 /* Caching functions */
2617 * checkLastModified returns true if it has taken care of all
2618 * output to the client that is necessary for this request.
2619 * (that is, it has sent a cached version of the page)
2621 function tryFileCache() {
2622 static $called = false;
2624 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2628 if($this->isFileCacheable()) {
2629 $touched = $this->mTouched
;
2630 $cache = new HTMLFileCache( $this->mTitle
);
2631 if($cache->isFileCacheGood( $touched )) {
2632 wfDebug( "Article::tryFileCache(): about to load file\n" );
2633 $cache->loadFromFileCache();
2636 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2637 ob_start( array(&$cache, 'saveToFileCache' ) );
2640 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2645 * Check if the page can be cached
2648 function isFileCacheable() {
2649 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2650 $action = $wgRequest->getVal( 'action' );
2651 $oldid = $wgRequest->getVal( 'oldid' );
2652 $diff = $wgRequest->getVal( 'diff' );
2653 $redirect = $wgRequest->getVal( 'redirect' );
2654 $printable = $wgRequest->getVal( 'printable' );
2655 $page = $wgRequest->getVal( 'page' );
2657 //check for non-standard user language; this covers uselang,
2658 //and extensions for auto-detecting user language.
2659 $ulang = $wgLang->getCode();
2660 $clang = $wgContLang->getCode();
2662 $cacheable = $wgUseFileCache
2663 && (!$wgShowIPinHeader)
2664 && ($this->getID() != 0)
2665 && ($wgUser->isAnon())
2666 && (!$wgUser->getNewtalk())
2667 && ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2668 && (empty( $action ) ||
$action == 'view')
2671 && (!isset($redirect))
2672 && (!isset($printable))
2674 && (!$this->mRedirectedFrom
)
2675 && ($ulang === $clang);
2678 //extension may have reason to disable file caching on some pages.
2679 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2686 * Loads page_touched and returns a value indicating if it should be used
2689 function checkTouched() {
2690 if( !$this->mDataLoaded
) {
2691 $this->loadPageData();
2693 return !$this->mIsRedirect
;
2697 * Get the page_touched field
2699 function getTouched() {
2700 # Ensure that page data has been loaded
2701 if( !$this->mDataLoaded
) {
2702 $this->loadPageData();
2704 return $this->mTouched
;
2708 * Get the page_latest field
2710 function getLatest() {
2711 if ( !$this->mDataLoaded
) {
2712 $this->loadPageData();
2714 return $this->mLatest
;
2718 * Edit an article without doing all that other stuff
2719 * The article must already exist; link tables etc
2720 * are not updated, caches are not flushed.
2722 * @param string $text text submitted
2723 * @param string $comment comment submitted
2724 * @param bool $minor whereas it's a minor modification
2726 function quickEdit( $text, $comment = '', $minor = 0 ) {
2727 wfProfileIn( __METHOD__
);
2729 $dbw = wfGetDB( DB_MASTER
);
2731 $revision = new Revision( array(
2732 'page' => $this->getId(),
2734 'comment' => $comment,
2735 'minor_edit' => $minor ?
1 : 0,
2737 $revision->insertOn( $dbw );
2738 $this->updateRevisionOn( $dbw, $revision );
2741 wfProfileOut( __METHOD__
);
2745 * Used to increment the view counter
2748 * @param integer $id article id
2750 function incViewCount( $id ) {
2751 $id = intval( $id );
2752 global $wgHitcounterUpdateFreq, $wgDBtype;
2754 $dbw = wfGetDB( DB_MASTER
);
2755 $pageTable = $dbw->tableName( 'page' );
2756 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2757 $acchitsTable = $dbw->tableName( 'acchits' );
2759 if( $wgHitcounterUpdateFreq <= 1 ) {
2760 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2764 # Not important enough to warrant an error page in case of failure
2765 $oldignore = $dbw->ignoreErrors( true );
2767 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2769 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2770 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2771 # Most of the time (or on SQL errors), skip row count check
2772 $dbw->ignoreErrors( $oldignore );
2776 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2777 $row = $dbw->fetchObject( $res );
2778 $rown = intval( $row->n
);
2779 if( $rown >= $wgHitcounterUpdateFreq ){
2780 wfProfileIn( 'Article::incViewCount-collect' );
2781 $old_user_abort = ignore_user_abort( true );
2783 if ($wgDBtype == 'mysql')
2784 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2785 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2786 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2787 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2789 $dbw->query("DELETE FROM $hitcounterTable");
2790 if ($wgDBtype == 'mysql') {
2791 $dbw->query('UNLOCK TABLES');
2792 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2793 'WHERE page_id = hc_id');
2796 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2797 "FROM $acchitsTable WHERE page_id = hc_id");
2799 $dbw->query("DROP TABLE $acchitsTable");
2801 ignore_user_abort( $old_user_abort );
2802 wfProfileOut( 'Article::incViewCount-collect' );
2804 $dbw->ignoreErrors( $oldignore );
2808 * The onArticle*() functions are supposed to be a kind of hooks
2809 * which should be called whenever any of the specified actions
2812 * This is a good place to put code to clear caches, for instance.
2814 * This is called on page move and undelete, as well as edit
2816 * @param $title_obj a title object
2819 static function onArticleCreate($title) {
2820 # The talk page isn't in the regular link tables, so we need to update manually:
2821 if ( $title->isTalkPage() ) {
2822 $other = $title->getSubjectPage();
2824 $other = $title->getTalkPage();
2826 $other->invalidateCache();
2827 $other->purgeSquid();
2829 $title->touchLinks();
2830 $title->purgeSquid();
2833 static function onArticleDelete( $title ) {
2834 global $wgUseFileCache, $wgMessageCache;
2836 $title->touchLinks();
2837 $title->purgeSquid();
2840 if ( $wgUseFileCache ) {
2841 $cm = new HTMLFileCache( $title );
2842 @unlink
( $cm->fileCacheName() );
2845 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2846 $wgMessageCache->replace( $title->getDBkey(), false );
2851 * Purge caches on page update etc
2853 static function onArticleEdit( $title ) {
2854 global $wgDeferredUpdateList, $wgUseFileCache;
2856 // Invalidate caches of articles which include this page
2857 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2858 $wgDeferredUpdateList[] = $update;
2860 # Purge squid for this page only
2861 $title->purgeSquid();
2864 if ( $wgUseFileCache ) {
2865 $cm = new HTMLFileCache( $title );
2866 @unlink
( $cm->fileCacheName() );
2873 * Info about this page
2874 * Called for ?action=info when $wgAllowPageInfo is on.
2879 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2881 if ( !$wgAllowPageInfo ) {
2882 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2886 $page = $this->mTitle
->getSubjectPage();
2888 $wgOut->setPagetitle( $page->getPrefixedText() );
2889 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
2890 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
2892 if( !$this->mTitle
->exists() ) {
2893 $wgOut->addHtml( '<div class="noarticletext">' );
2894 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2895 // This doesn't quite make sense; the user is asking for
2896 // information about the _page_, not the message... -- RC
2897 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle
->getText() ) ) );
2899 $msg = $wgUser->isLoggedIn()
2901 : 'noarticletextanon';
2902 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
2904 $wgOut->addHtml( '</div>' );
2906 $dbr = wfGetDB( DB_SLAVE
);
2908 'wl_title' => $page->getDBkey(),
2909 'wl_namespace' => $page->getNamespace() );
2910 $numwatchers = $dbr->selectField(
2915 $this->getSelectOptions() );
2917 $pageInfo = $this->pageCountInfo( $page );
2918 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2920 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2921 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2923 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2925 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2927 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2929 $wgOut->addHTML( '</ul>' );
2935 * Return the total number of edits and number of unique editors
2936 * on a given page. If page does not exist, returns false.
2938 * @param Title $title
2942 function pageCountInfo( $title ) {
2943 $id = $title->getArticleId();
2948 $dbr = wfGetDB( DB_SLAVE
);
2950 $rev_clause = array( 'rev_page' => $id );
2952 $edits = $dbr->selectField(
2957 $this->getSelectOptions() );
2959 $authors = $dbr->selectField(
2961 'COUNT(DISTINCT rev_user_text)',
2964 $this->getSelectOptions() );
2966 return array( 'edits' => $edits, 'authors' => $authors );
2970 * Return a list of templates used by this article.
2971 * Uses the templatelinks table
2973 * @return array Array of Title objects
2975 function getUsedTemplates() {
2977 $id = $this->mTitle
->getArticleID();
2982 $dbr = wfGetDB( DB_SLAVE
);
2983 $res = $dbr->select( array( 'templatelinks' ),
2984 array( 'tl_namespace', 'tl_title' ),
2985 array( 'tl_from' => $id ),
2986 'Article:getUsedTemplates' );
2987 if ( false !== $res ) {
2988 if ( $dbr->numRows( $res ) ) {
2989 while ( $row = $dbr->fetchObject( $res ) ) {
2990 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2994 $dbr->freeResult( $res );
2999 * Return an auto-generated summary if the text provided is a redirect.
3001 * @param string $text The wikitext to check
3002 * @return string '' or an appropriate summary
3004 public static function getRedirectAutosummary( $text ) {
3005 $rt = Title
::newFromRedirect( $text );
3006 if( is_object( $rt ) )
3007 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3013 * Return an auto-generated summary if the new text is much shorter than
3016 * @param string $oldtext The previous text of the page
3017 * @param string $text The submitted text of the page
3018 * @return string An appropriate autosummary, or an empty string.
3020 public static function getBlankingAutosummary( $oldtext, $text ) {
3021 if ($oldtext!='' && $text=='') {
3022 return wfMsgForContent('autosumm-blank');
3023 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3024 #Removing more than 90% of the article
3026 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3027 return wfMsgForContent('autosumm-replace', $truncatedtext);
3034 * Return an applicable autosummary if one exists for the given edit.
3035 * @param string $oldtext The previous text of the page.
3036 * @param string $newtext The submitted text of the page.
3037 * @param bitmask $flags A bitmask of flags submitted for the edit.
3038 * @return string An appropriate autosummary, or an empty string.
3040 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3042 # This code is UGLY UGLY UGLY.
3043 # Somebody PLEASE come up with a more elegant way to do it.
3045 #Redirect autosummaries
3046 $summary = self
::getRedirectAutosummary( $newtext );
3051 #Blanking autosummaries
3052 if (!($flags & EDIT_NEW
))
3053 $summary = self
::getBlankingAutosummary( $oldtext, $newtext );
3058 #New page autosummaries
3059 if ($flags & EDIT_NEW
&& strlen($newtext)) {
3060 #If they're making a new article, give its text, truncated, in the summary.
3062 $truncatedtext = $wgContLang->truncate(
3063 str_replace("\n", ' ', $newtext),
3064 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3066 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3076 * Add the primary page-view wikitext to the output buffer
3077 * Saves the text into the parser cache if possible.
3078 * Updates templatelinks if it is out of date.
3080 * @param string $text
3081 * @param bool $cache
3083 public function outputWikiText( $text, $cache = true ) {
3084 global $wgParser, $wgUser, $wgOut;
3086 $popts = $wgOut->parserOptions();
3087 $popts->setTidy(true);
3088 $parserOutput = $wgParser->parse( $text, $this->mTitle
,
3089 $popts, true, true, $this->getRevIdFetched() );
3090 $popts->setTidy(false);
3091 if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3092 $parserCache =& ParserCache
::singleton();
3093 $parserCache->save( $parserOutput, $this, $wgUser );
3096 if ( !wfReadOnly() && $this->mTitle
->areRestrictionsCascading() ) {
3097 // templatelinks table may have become out of sync,
3098 // especially if using variable-based transclusions.
3099 // For paranoia, check if things have changed and if
3100 // so apply updates to the database. This will ensure
3101 // that cascaded protections apply as soon as the changes
3104 # Get templates from templatelinks
3105 $id = $this->mTitle
->getArticleID();
3107 $tlTemplates = array();
3109 $dbr = wfGetDB( DB_SLAVE
);
3110 $res = $dbr->select( array( 'templatelinks' ),
3111 array( 'tl_namespace', 'tl_title' ),
3112 array( 'tl_from' => $id ),
3113 'Article:getUsedTemplates' );
3117 if ( false !== $res ) {
3118 if ( $dbr->numRows( $res ) ) {
3119 while ( $row = $dbr->fetchObject( $res ) ) {
3120 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace
) . ':' . $row->tl_title
;
3125 # Get templates from parser output.
3126 $poTemplates_allns = $parserOutput->getTemplates();
3128 $poTemplates = array ();
3129 foreach ( $poTemplates_allns as $ns_templates ) {
3130 $poTemplates = array_merge( $poTemplates, $ns_templates );
3134 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3136 if ( count( $templates_diff ) > 0 ) {
3137 # Whee, link updates time.
3138 $u = new LinksUpdate( $this->mTitle
, $parserOutput );
3140 $dbw = wfGetDb( DB_MASTER
);
3149 $wgOut->addParserOutput( $parserOutput );