Remove old-fashioned $wgLinkCacheMemcached stuff
[mediawiki.git] / includes / Article.php
blob57e4887ef00cc8364690a596dcb2e17a85138280
1 <?php
2 /**
3 * File for articles
4 */
6 /**
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.
14 class Article {
15 /**@{{
16 * @private
18 var $mComment; //!<
19 var $mContent; //!<
20 var $mContentLoaded; //!<
21 var $mCounter; //!<
22 var $mForUpdate; //!<
23 var $mGoodAdjustment; //!<
24 var $mLatest; //!<
25 var $mMinorEdit; //!<
26 var $mOldId; //!<
27 var $mRedirectedFrom; //!<
28 var $mRedirectUrl; //!<
29 var $mRevIdFetched; //!<
30 var $mRevision; //!<
31 var $mTimestamp; //!<
32 var $mTitle; //!<
33 var $mTotalAdjustment; //!<
34 var $mTouched; //!<
35 var $mUser; //!<
36 var $mUserText; //!<
37 /**@}}*/
39 /**
40 * Constructor and clear the article
41 * @param $title Reference to a Title object.
42 * @param $oldId Integer revision ID, null to fetch from request, zero for current
44 function __construct( Title $title, $oldId = null ) {
45 $this->mTitle =& $title;
46 $this->mOldId = $oldId;
47 $this->clear();
50 /**
51 * Tell the page view functions that this view was redirected
52 * from another page on the wiki.
53 * @param $from Title object.
55 function setRedirectedFrom( $from ) {
56 $this->mRedirectedFrom = $from;
59 /**
60 * @return mixed false, Title of in-wiki target, or string with URL
62 function followRedirect() {
63 $text = $this->getContent();
64 $rt = Title::newFromRedirect( $text );
66 # process if title object is valid and not special:userlogout
67 if( $rt ) {
68 if( $rt->getInterwiki() != '' ) {
69 if( $rt->isLocal() ) {
70 // Offsite wikis need an HTTP redirect.
72 // This can be hard to reverse and may produce loops,
73 // so they may be disabled in the site configuration.
75 $source = $this->mTitle->getFullURL( 'redirect=no' );
76 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
78 } else {
79 if( $rt->getNamespace() == NS_SPECIAL ) {
80 // Gotta handle redirects to special pages differently:
81 // Fill the HTTP response "Location" header and ignore
82 // the rest of the page we're on.
84 // This can be hard to reverse, so they may be disabled.
86 if( $rt->isSpecial( 'Userlogout' ) ) {
87 // rolleyes
88 } else {
89 return $rt->getFullURL();
92 return $rt;
96 // No or invalid redirect
97 return false;
101 * get the title object of the article
103 function getTitle() {
104 return $this->mTitle;
108 * Clear the object
109 * @private
111 function clear() {
112 $this->mDataLoaded = false;
113 $this->mContentLoaded = false;
115 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
116 $this->mRedirectedFrom = null; # Title object if set
117 $this->mUserText =
118 $this->mTimestamp = $this->mComment = '';
119 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
120 $this->mTouched = '19700101000000';
121 $this->mForUpdate = false;
122 $this->mIsRedirect = false;
123 $this->mRevIdFetched = 0;
124 $this->mRedirectUrl = false;
125 $this->mLatest = false;
126 $this->mPreparedEdit = false;
130 * Note that getContent/loadContent do not follow redirects anymore.
131 * If you need to fetch redirectable content easily, try
132 * the shortcut in Article::followContent()
133 * FIXME
134 * @todo There are still side-effects in this!
135 * In general, you should use the Revision class, not Article,
136 * to fetch text for purposes other than page views.
138 * @return Return the text of this revision
140 function getContent() {
141 global $wgUser, $wgOut, $wgMessageCache;
143 wfProfileIn( __METHOD__ );
145 if ( 0 == $this->getID() ) {
146 wfProfileOut( __METHOD__ );
147 $wgOut->setRobotpolicy( 'noindex,nofollow' );
149 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
150 $wgMessageCache->loadAllMessages();
151 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
152 } else {
153 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
156 return "<div class='noarticletext'>\n$ret\n</div>";
157 } else {
158 $this->loadContent();
159 wfProfileOut( __METHOD__ );
160 return $this->mContent;
165 * This function returns the text of a section, specified by a number ($section).
166 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
167 * the first section before any such heading (section 0).
169 * If a section contains subsections, these are also returned.
171 * @param $text String: text to look in
172 * @param $section Integer: section number
173 * @return string text of the requested section
174 * @deprecated
176 function getSection($text,$section) {
177 global $wgParser;
178 return $wgParser->getSection( $text, $section );
182 * @return int The oldid of the article that is to be shown, 0 for the
183 * current revision
185 function getOldID() {
186 if ( is_null( $this->mOldId ) ) {
187 $this->mOldId = $this->getOldIDFromRequest();
189 return $this->mOldId;
193 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
195 * @return int The old id for the request
197 function getOldIDFromRequest() {
198 global $wgRequest;
199 $this->mRedirectUrl = false;
200 $oldid = $wgRequest->getVal( 'oldid' );
201 if ( isset( $oldid ) ) {
202 $oldid = intval( $oldid );
203 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
204 $nextid = $this->mTitle->getNextRevisionID( $oldid );
205 if ( $nextid ) {
206 $oldid = $nextid;
207 } else {
208 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
210 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
211 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
212 if ( $previd ) {
213 $oldid = $previd;
214 } else {
215 # TODO
218 # unused:
219 # $lastid = $oldid;
222 if ( !$oldid ) {
223 $oldid = 0;
225 return $oldid;
229 * Load the revision (including text) into this object
231 function loadContent() {
232 if ( $this->mContentLoaded ) return;
234 # Query variables :P
235 $oldid = $this->getOldID();
237 # Pre-fill content with error message so that if something
238 # fails we'll have something telling us what we intended.
239 $this->mOldId = $oldid;
240 $this->fetchContent( $oldid );
245 * Fetch a page record with the given conditions
246 * @param Database $dbr
247 * @param array $conditions
248 * @private
250 function pageData( $dbr, $conditions ) {
251 $fields = array(
252 'page_id',
253 'page_namespace',
254 'page_title',
255 'page_restrictions',
256 'page_counter',
257 'page_is_redirect',
258 'page_is_new',
259 'page_random',
260 'page_touched',
261 'page_latest',
262 'page_len',
264 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
265 $row = $dbr->selectRow(
266 'page',
267 $fields,
268 $conditions,
269 __METHOD__
271 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
272 return $row ;
276 * @param Database $dbr
277 * @param Title $title
279 function pageDataFromTitle( $dbr, $title ) {
280 return $this->pageData( $dbr, array(
281 'page_namespace' => $title->getNamespace(),
282 'page_title' => $title->getDBkey() ) );
286 * @param Database $dbr
287 * @param int $id
289 function pageDataFromId( $dbr, $id ) {
290 return $this->pageData( $dbr, array( 'page_id' => $id ) );
294 * Set the general counter, title etc data loaded from
295 * some source.
297 * @param object $data
298 * @private
300 function loadPageData( $data = 'fromdb' ) {
301 if ( $data === 'fromdb' ) {
302 $dbr = $this->getDB();
303 $data = $this->pageDataFromId( $dbr, $this->getId() );
306 $lc = LinkCache::singleton();
307 if ( $data ) {
308 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
310 $this->mTitle->mArticleID = $data->page_id;
312 # Old-fashioned restrictions.
313 $this->mTitle->loadRestrictions( $data->page_restrictions );
315 $this->mCounter = $data->page_counter;
316 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
317 $this->mIsRedirect = $data->page_is_redirect;
318 $this->mLatest = $data->page_latest;
319 } else {
320 if ( is_object( $this->mTitle ) ) {
321 $lc->addBadLinkObj( $this->mTitle );
323 $this->mTitle->mArticleID = 0;
326 $this->mDataLoaded = true;
330 * Get text of an article from database
331 * Does *NOT* follow redirects.
332 * @param int $oldid 0 for whatever the latest revision is
333 * @return string
335 function fetchContent( $oldid = 0 ) {
336 if ( $this->mContentLoaded ) {
337 return $this->mContent;
340 $dbr = $this->getDB();
342 # Pre-fill content with error message so that if something
343 # fails we'll have something telling us what we intended.
344 $t = $this->mTitle->getPrefixedText();
345 if( $oldid ) {
346 $t .= ',oldid='.$oldid;
348 $this->mContent = wfMsg( 'missingarticle', $t ) ;
350 if( $oldid ) {
351 $revision = Revision::newFromId( $oldid );
352 if( is_null( $revision ) ) {
353 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
354 return false;
356 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
357 if( !$data ) {
358 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
359 return false;
361 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
362 $this->loadPageData( $data );
363 } else {
364 if( !$this->mDataLoaded ) {
365 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
366 if( !$data ) {
367 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
368 return false;
370 $this->loadPageData( $data );
372 $revision = Revision::newFromId( $this->mLatest );
373 if( is_null( $revision ) ) {
374 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$data->page_latest}\n" );
375 return false;
379 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
380 // We should instead work with the Revision object when we need it...
381 $this->mContent = $revision->revText(); // Loads if user is allowed
383 $this->mUser = $revision->getUser();
384 $this->mUserText = $revision->getUserText();
385 $this->mComment = $revision->getComment();
386 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
388 $this->mRevIdFetched = $revision->getID();
389 $this->mContentLoaded = true;
390 $this->mRevision =& $revision;
392 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
394 return $this->mContent;
398 * Read/write accessor to select FOR UPDATE
400 * @param $x Mixed: FIXME
402 function forUpdate( $x = NULL ) {
403 return wfSetVar( $this->mForUpdate, $x );
407 * Get the database which should be used for reads
409 * @return Database
411 function getDB() {
412 return wfGetDB( DB_MASTER );
416 * Get options for all SELECT statements
418 * @param $options Array: an optional options array which'll be appended to
419 * the default
420 * @return Array: options
422 function getSelectOptions( $options = '' ) {
423 if ( $this->mForUpdate ) {
424 if ( is_array( $options ) ) {
425 $options[] = 'FOR UPDATE';
426 } else {
427 $options = 'FOR UPDATE';
430 return $options;
434 * @return int Page ID
436 function getID() {
437 if( $this->mTitle ) {
438 return $this->mTitle->getArticleID();
439 } else {
440 return 0;
445 * @return bool Whether or not the page exists in the database
447 function exists() {
448 return $this->getId() != 0;
452 * @return int The view count for the page
454 function getCount() {
455 if ( -1 == $this->mCounter ) {
456 $id = $this->getID();
457 if ( $id == 0 ) {
458 $this->mCounter = 0;
459 } else {
460 $dbr = wfGetDB( DB_SLAVE );
461 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
462 'Article::getCount', $this->getSelectOptions() );
465 return $this->mCounter;
469 * Determine whether a page would be suitable for being counted as an
470 * article in the site_stats table based on the title & its content
472 * @param $text String: text to analyze
473 * @return bool
475 function isCountable( $text ) {
476 global $wgUseCommaCount;
478 $token = $wgUseCommaCount ? ',' : '[[';
479 return
480 $this->mTitle->isContentPage()
481 && !$this->isRedirect( $text )
482 && in_string( $token, $text );
486 * Tests if the article text represents a redirect
488 * @param $text String: FIXME
489 * @return bool
491 function isRedirect( $text = false ) {
492 if ( $text === false ) {
493 $this->loadContent();
494 $titleObj = Title::newFromRedirect( $this->fetchContent() );
495 } else {
496 $titleObj = Title::newFromRedirect( $text );
498 return $titleObj !== NULL;
502 * Returns true if the currently-referenced revision is the current edit
503 * to this page (and it exists).
504 * @return bool
506 function isCurrent() {
507 # If no oldid, this is the current version.
508 if ($this->getOldID() == 0)
509 return true;
511 return $this->exists() &&
512 isset( $this->mRevision ) &&
513 $this->mRevision->isCurrent();
517 * Loads everything except the text
518 * This isn't necessary for all uses, so it's only done if needed.
519 * @private
521 function loadLastEdit() {
522 if ( -1 != $this->mUser )
523 return;
525 # New or non-existent articles have no user information
526 $id = $this->getID();
527 if ( 0 == $id ) return;
529 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
530 if( !is_null( $this->mLastRevision ) ) {
531 $this->mUser = $this->mLastRevision->getUser();
532 $this->mUserText = $this->mLastRevision->getUserText();
533 $this->mTimestamp = $this->mLastRevision->getTimestamp();
534 $this->mComment = $this->mLastRevision->getComment();
535 $this->mMinorEdit = $this->mLastRevision->isMinor();
536 $this->mRevIdFetched = $this->mLastRevision->getID();
540 function getTimestamp() {
541 // Check if the field has been filled by ParserCache::get()
542 if ( !$this->mTimestamp ) {
543 $this->loadLastEdit();
545 return wfTimestamp(TS_MW, $this->mTimestamp);
548 function getUser() {
549 $this->loadLastEdit();
550 return $this->mUser;
553 function getUserText() {
554 $this->loadLastEdit();
555 return $this->mUserText;
558 function getComment() {
559 $this->loadLastEdit();
560 return $this->mComment;
563 function getMinorEdit() {
564 $this->loadLastEdit();
565 return $this->mMinorEdit;
568 function getRevIdFetched() {
569 $this->loadLastEdit();
570 return $this->mRevIdFetched;
574 * @todo Document, fixme $offset never used.
575 * @param $limit Integer: default 0.
576 * @param $offset Integer: default 0.
578 function getContributors($limit = 0, $offset = 0) {
579 # XXX: this is expensive; cache this info somewhere.
581 $contribs = array();
582 $dbr = wfGetDB( DB_SLAVE );
583 $revTable = $dbr->tableName( 'revision' );
584 $userTable = $dbr->tableName( 'user' );
585 $user = $this->getUser();
586 $pageId = $this->getId();
588 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
589 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
590 WHERE rev_page = $pageId
591 AND rev_user != $user
592 GROUP BY rev_user, rev_user_text, user_real_name
593 ORDER BY timestamp DESC";
595 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
596 $sql .= ' '. $this->getSelectOptions();
598 $res = $dbr->query($sql, __METHOD__);
600 while ( $line = $dbr->fetchObject( $res ) ) {
601 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
604 $dbr->freeResult($res);
605 return $contribs;
609 * This is the default action of the script: just view the page of
610 * the given title.
612 function view() {
613 global $wgUser, $wgOut, $wgRequest, $wgContLang;
614 global $wgEnableParserCache, $wgStylePath, $wgParser;
615 global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
616 global $wgDefaultRobotPolicy;
617 $sk = $wgUser->getSkin();
619 wfProfileIn( __METHOD__ );
621 $parserCache = ParserCache::singleton();
622 $ns = $this->mTitle->getNamespace(); # shortcut
624 # Get variables from query string
625 $oldid = $this->getOldID();
627 # getOldID may want us to redirect somewhere else
628 if ( $this->mRedirectUrl ) {
629 $wgOut->redirect( $this->mRedirectUrl );
630 wfProfileOut( __METHOD__ );
631 return;
634 $diff = $wgRequest->getVal( 'diff' );
635 $rcid = $wgRequest->getVal( 'rcid' );
636 $rdfrom = $wgRequest->getVal( 'rdfrom' );
637 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
638 $purge = $wgRequest->getVal( 'action' ) == 'purge';
640 $wgOut->setArticleFlag( true );
642 # Discourage indexing of printable versions, but encourage following
643 if( $wgOut->isPrintable() ) {
644 $policy = 'noindex,follow';
645 } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
646 $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
647 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
648 # Honour customised robot policies for this namespace
649 $policy = $wgNamespaceRobotPolicies[$ns];
650 } else {
651 $policy = $wgDefaultRobotPolicy;
653 $wgOut->setRobotPolicy( $policy );
655 # If we got diff and oldid in the query, we want to see a
656 # diff page instead of the article.
658 if ( !is_null( $diff ) ) {
659 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
661 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge );
662 // DifferenceEngine directly fetched the revision:
663 $this->mRevIdFetched = $de->mNewid;
664 $de->showDiffPage( $diffOnly );
666 // Needed to get the page's current revision
667 $this->loadPageData();
668 if( $diff == 0 || $diff == $this->mLatest ) {
669 # Run view updates for current revision only
670 $this->viewUpdates();
672 wfProfileOut( __METHOD__ );
673 return;
676 if ( empty( $oldid ) && $this->checkTouched() ) {
677 $wgOut->setETag($parserCache->getETag($this, $wgUser));
679 if( $wgOut->checkLastModified( $this->mTouched ) ){
680 wfProfileOut( __METHOD__ );
681 return;
682 } else if ( $this->tryFileCache() ) {
683 # tell wgOut that output is taken care of
684 $wgOut->disable();
685 $this->viewUpdates();
686 wfProfileOut( __METHOD__ );
687 return;
691 # Should the parser cache be used?
692 $pcache = $wgEnableParserCache
693 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
694 && $this->exists()
695 && empty( $oldid )
696 && !$this->mTitle->isCssOrJsPage()
697 && !$this->mTitle->isCssJsSubpage();
698 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
699 if ( $wgUser->getOption( 'stubthreshold' ) ) {
700 wfIncrStats( 'pcache_miss_stub' );
703 $wasRedirected = false;
704 if ( isset( $this->mRedirectedFrom ) ) {
705 // This is an internally redirected page view.
706 // We'll need a backlink to the source page for navigation.
707 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
708 $sk = $wgUser->getSkin();
709 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
710 $s = wfMsg( 'redirectedfrom', $redir );
711 $wgOut->setSubtitle( $s );
713 // Set the fragment if one was specified in the redirect
714 if ( strval( $this->mTitle->getFragment() ) != '' ) {
715 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
716 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
718 $wasRedirected = true;
720 } elseif ( !empty( $rdfrom ) ) {
721 // This is an externally redirected view, from some other wiki.
722 // If it was reported from a trusted site, supply a backlink.
723 global $wgRedirectSources;
724 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
725 $sk = $wgUser->getSkin();
726 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
727 $s = wfMsg( 'redirectedfrom', $redir );
728 $wgOut->setSubtitle( $s );
729 $wasRedirected = true;
733 $outputDone = false;
734 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
735 if ( $pcache ) {
736 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
737 // Ensure that UI elements requiring revision ID have
738 // the correct version information.
739 $wgOut->setRevisionId( $this->mLatest );
740 $outputDone = true;
743 if ( !$outputDone ) {
744 $text = $this->getContent();
745 if ( $text === false ) {
746 # Failed to load, replace text with error message
747 $t = $this->mTitle->getPrefixedText();
748 if( $oldid ) {
749 $t .= ',oldid='.$oldid;
750 $text = wfMsg( 'missingarticle', $t );
751 } else {
752 $text = wfMsg( 'noarticletext', $t );
756 # Another whitelist check in case oldid is altering the title
757 if ( !$this->mTitle->userCanRead() ) {
758 $wgOut->loginToUse();
759 $wgOut->output();
760 exit;
763 # We're looking at an old revision
765 if ( !empty( $oldid ) ) {
766 $wgOut->setRobotpolicy( 'noindex,nofollow' );
767 if( is_null( $this->mRevision ) ) {
768 // FIXME: This would be a nice place to load the 'no such page' text.
769 } else {
770 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
771 if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
772 if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
773 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
774 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
775 return;
776 } else {
777 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
778 // and we are allowed to see...
785 if( !$outputDone ) {
786 $wgOut->setRevisionId( $this->getRevIdFetched() );
788 // Pages containing custom CSS or JavaScript get special treatment
789 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
790 $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
792 // Give hooks a chance to customise the output
793 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
794 // Wrap the whole lot in a <pre> and don't parse
795 $m = array();
796 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
797 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
798 $wgOut->addHtml( htmlspecialchars( $this->mContent ) );
799 $wgOut->addHtml( "\n</pre>\n" );
804 elseif ( $rt = Title::newFromRedirect( $text ) ) {
805 # Display redirect
806 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
807 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
808 # Don't overwrite the subtitle if this was an old revision
809 if( !$wasRedirected && $this->isCurrent() ) {
810 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
812 $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
814 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
815 '<span class="redirectText">'.$link.'</span>' );
817 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
818 $wgOut->addParserOutputNoText( $parseout );
819 } else if ( $pcache ) {
820 # Display content and save to parser cache
821 $this->outputWikiText( $text );
822 } else {
823 # Display content, don't attempt to save to parser cache
824 # Don't show section-edit links on old revisions... this way lies madness.
825 if( !$this->isCurrent() ) {
826 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
828 # Display content and don't save to parser cache
829 # With timing hack -- TS 2006-07-26
830 $time = -wfTime();
831 $this->outputWikiText( $text, false );
832 $time += wfTime();
834 # Timing hack
835 if ( $time > 3 ) {
836 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
837 $this->mTitle->getPrefixedDBkey()));
840 if( !$this->isCurrent() ) {
841 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
846 /* title may have been set from the cache */
847 $t = $wgOut->getPageTitle();
848 if( empty( $t ) ) {
849 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
852 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
853 if( $ns == NS_USER_TALK &&
854 User::isIP( $this->mTitle->getText() ) ) {
855 $wgOut->addWikiMsg('anontalkpagetext');
858 # If we have been passed an &rcid= parameter, we want to give the user a
859 # chance to mark this new article as patrolled.
860 if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle->exists() ) {
861 $wgOut->addHTML(
862 "<div class='patrollink'>" .
863 wfMsgHtml( 'markaspatrolledlink',
864 $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
865 "action=markpatrolled&rcid=$rcid" )
867 '</div>'
871 # Trackbacks
872 if ($wgUseTrackbacks)
873 $this->addTrackbacks();
875 $this->viewUpdates();
876 wfProfileOut( __METHOD__ );
879 function addTrackbacks() {
880 global $wgOut, $wgUser;
882 $dbr = wfGetDB(DB_SLAVE);
883 $tbs = $dbr->select(
884 /* FROM */ 'trackbacks',
885 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
886 /* WHERE */ array('tb_page' => $this->getID())
889 if (!$dbr->numrows($tbs))
890 return;
892 $tbtext = "";
893 while ($o = $dbr->fetchObject($tbs)) {
894 $rmvtxt = "";
895 if ($wgUser->isAllowed( 'trackback' )) {
896 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
897 . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
898 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
900 $tbtext .= "\n";
901 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
902 $o->tb_title,
903 $o->tb_url,
904 $o->tb_ex,
905 $o->tb_name,
906 $rmvtxt);
908 $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
911 function deletetrackback() {
912 global $wgUser, $wgRequest, $wgOut, $wgTitle;
914 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
915 $wgOut->addWikiMsg( 'sessionfailure' );
916 return;
919 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
921 if (count($permission_errors)>0)
923 $wgOut->showPermissionsErrorPage( $permission_errors );
924 return;
927 $db = wfGetDB(DB_MASTER);
928 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
929 $wgTitle->invalidateCache();
930 $wgOut->addWikiMsg('trackbackdeleteok');
933 function render() {
934 global $wgOut;
936 $wgOut->setArticleBodyOnly(true);
937 $this->view();
941 * Handle action=purge
943 function purge() {
944 global $wgUser, $wgRequest, $wgOut;
946 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
947 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
948 $this->doPurge();
950 } else {
951 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
952 $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
953 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
954 $msg = str_replace( '$1',
955 "<form method=\"post\" action=\"$action\">\n" .
956 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
957 "</form>\n", $msg );
959 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
960 $wgOut->setRobotpolicy( 'noindex,nofollow' );
961 $wgOut->addHTML( $msg );
966 * Perform the actions of a page purging
968 function doPurge() {
969 global $wgUseSquid;
970 // Invalidate the cache
971 $this->mTitle->invalidateCache();
973 if ( $wgUseSquid ) {
974 // Commit the transaction before the purge is sent
975 $dbw = wfGetDB( DB_MASTER );
976 $dbw->immediateCommit();
978 // Send purge
979 $update = SquidUpdate::newSimplePurge( $this->mTitle );
980 $update->doUpdate();
982 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
983 global $wgMessageCache;
984 if ( $this->getID() == 0 ) {
985 $text = false;
986 } else {
987 $text = $this->getContent();
989 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
991 $this->view();
995 * Insert a new empty page record for this article.
996 * This *must* be followed up by creating a revision
997 * and running $this->updateToLatest( $rev_id );
998 * or else the record will be left in a funky state.
999 * Best if all done inside a transaction.
1001 * @param Database $dbw
1002 * @return int The newly created page_id key
1003 * @private
1005 function insertOn( $dbw ) {
1006 wfProfileIn( __METHOD__ );
1008 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1009 $dbw->insert( 'page', array(
1010 'page_id' => $page_id,
1011 'page_namespace' => $this->mTitle->getNamespace(),
1012 'page_title' => $this->mTitle->getDBkey(),
1013 'page_counter' => 0,
1014 'page_restrictions' => '',
1015 'page_is_redirect' => 0, # Will set this shortly...
1016 'page_is_new' => 1,
1017 'page_random' => wfRandom(),
1018 'page_touched' => $dbw->timestamp(),
1019 'page_latest' => 0, # Fill this in shortly...
1020 'page_len' => 0, # Fill this in shortly...
1021 ), __METHOD__ );
1022 $newid = $dbw->insertId();
1024 $this->mTitle->resetArticleId( $newid );
1026 wfProfileOut( __METHOD__ );
1027 return $newid;
1031 * Update the page record to point to a newly saved revision.
1033 * @param Database $dbw
1034 * @param Revision $revision For ID number, and text used to set
1035 length and redirect status fields
1036 * @param int $lastRevision If given, will not overwrite the page field
1037 * when different from the currently set value.
1038 * Giving 0 indicates the new page flag should
1039 * be set on.
1040 * @param bool $lastRevIsRedirect If given, will optimize adding and
1041 * removing rows in redirect table.
1042 * @return bool true on success, false on failure
1043 * @private
1045 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1046 wfProfileIn( __METHOD__ );
1048 $text = $revision->getText();
1049 $rt = Title::newFromRedirect( $text );
1051 $conditions = array( 'page_id' => $this->getId() );
1052 if( !is_null( $lastRevision ) ) {
1053 # An extra check against threads stepping on each other
1054 $conditions['page_latest'] = $lastRevision;
1057 $dbw->update( 'page',
1058 array( /* SET */
1059 'page_latest' => $revision->getId(),
1060 'page_touched' => $dbw->timestamp(),
1061 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1062 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1063 'page_len' => strlen( $text ),
1065 $conditions,
1066 __METHOD__ );
1068 $result = $dbw->affectedRows() != 0;
1070 if ($result) {
1071 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1074 wfProfileOut( __METHOD__ );
1075 return $result;
1079 * Add row to the redirect table if this is a redirect, remove otherwise.
1081 * @param Database $dbw
1082 * @param $redirectTitle a title object pointing to the redirect target,
1083 * or NULL if this is not a redirect
1084 * @param bool $lastRevIsRedirect If given, will optimize adding and
1085 * removing rows in redirect table.
1086 * @return bool true on success, false on failure
1087 * @private
1089 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1091 // Always update redirects (target link might have changed)
1092 // Update/Insert if we don't know if the last revision was a redirect or not
1093 // Delete if changing from redirect to non-redirect
1094 $isRedirect = !is_null($redirectTitle);
1095 if ($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1097 wfProfileIn( __METHOD__ );
1099 if ($isRedirect) {
1101 // This title is a redirect, Add/Update row in the redirect table
1102 $set = array( /* SET */
1103 'rd_namespace' => $redirectTitle->getNamespace(),
1104 'rd_title' => $redirectTitle->getDBkey(),
1105 'rd_from' => $this->getId(),
1108 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1109 } else {
1110 // This is not a redirect, remove row from redirect table
1111 $where = array( 'rd_from' => $this->getId() );
1112 $dbw->delete( 'redirect', $where, __METHOD__);
1115 wfProfileOut( __METHOD__ );
1116 return ( $dbw->affectedRows() != 0 );
1119 return true;
1123 * If the given revision is newer than the currently set page_latest,
1124 * update the page record. Otherwise, do nothing.
1126 * @param Database $dbw
1127 * @param Revision $revision
1129 function updateIfNewerOn( &$dbw, $revision ) {
1130 wfProfileIn( __METHOD__ );
1132 $row = $dbw->selectRow(
1133 array( 'revision', 'page' ),
1134 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1135 array(
1136 'page_id' => $this->getId(),
1137 'page_latest=rev_id' ),
1138 __METHOD__ );
1139 if( $row ) {
1140 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1141 wfProfileOut( __METHOD__ );
1142 return false;
1144 $prev = $row->rev_id;
1145 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1146 } else {
1147 # No or missing previous revision; mark the page as new
1148 $prev = 0;
1149 $lastRevIsRedirect = null;
1152 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1153 wfProfileOut( __METHOD__ );
1154 return $ret;
1158 * @return string Complete article text, or null if error
1160 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1161 wfProfileIn( __METHOD__ );
1163 if( $section == '' ) {
1164 // Whole-page edit; let the text through unmolested.
1165 } else {
1166 if( is_null( $edittime ) ) {
1167 $rev = Revision::newFromTitle( $this->mTitle );
1168 } else {
1169 $dbw = wfGetDB( DB_MASTER );
1170 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1172 if( is_null( $rev ) ) {
1173 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1174 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1175 return null;
1177 $oldtext = $rev->getText();
1179 if( $section == 'new' ) {
1180 # Inserting a new section
1181 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1182 $text = strlen( trim( $oldtext ) ) > 0
1183 ? "{$oldtext}\n\n{$subject}{$text}"
1184 : "{$subject}{$text}";
1185 } else {
1186 # Replacing an existing section; roll out the big guns
1187 global $wgParser;
1188 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1193 wfProfileOut( __METHOD__ );
1194 return $text;
1198 * @deprecated use Article::doEdit()
1200 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1201 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1202 ( $isminor ? EDIT_MINOR : 0 ) |
1203 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1204 ( $bot ? EDIT_FORCE_BOT : 0 );
1206 # If this is a comment, add the summary as headline
1207 if ( $comment && $summary != "" ) {
1208 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1211 $this->doEdit( $text, $summary, $flags );
1213 $dbw = wfGetDB( DB_MASTER );
1214 if ($watchthis) {
1215 if (!$this->mTitle->userIsWatching()) {
1216 $dbw->begin();
1217 $this->doWatch();
1218 $dbw->commit();
1220 } else {
1221 if ( $this->mTitle->userIsWatching() ) {
1222 $dbw->begin();
1223 $this->doUnwatch();
1224 $dbw->commit();
1227 $this->doRedirect( $this->isRedirect( $text ) );
1231 * @deprecated use Article::doEdit()
1233 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1234 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1235 ( $minor ? EDIT_MINOR : 0 ) |
1236 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1238 $good = $this->doEdit( $text, $summary, $flags );
1239 if ( $good ) {
1240 $dbw = wfGetDB( DB_MASTER );
1241 if ($watchthis) {
1242 if (!$this->mTitle->userIsWatching()) {
1243 $dbw->begin();
1244 $this->doWatch();
1245 $dbw->commit();
1247 } else {
1248 if ( $this->mTitle->userIsWatching() ) {
1249 $dbw->begin();
1250 $this->doUnwatch();
1251 $dbw->commit();
1255 $extraq = ''; // Give extensions a chance to modify URL query on update
1256 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraq ) );
1258 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraq );
1260 return $good;
1264 * Article::doEdit()
1266 * Change an existing article or create a new article. Updates RC and all necessary caches,
1267 * optionally via the deferred update array.
1269 * $wgUser must be set before calling this function.
1271 * @param string $text New text
1272 * @param string $summary Edit summary
1273 * @param integer $flags bitfield:
1274 * EDIT_NEW
1275 * Article is known or assumed to be non-existent, create a new one
1276 * EDIT_UPDATE
1277 * Article is known or assumed to be pre-existing, update it
1278 * EDIT_MINOR
1279 * Mark this edit minor, if the user is allowed to do so
1280 * EDIT_SUPPRESS_RC
1281 * Do not log the change in recentchanges
1282 * EDIT_FORCE_BOT
1283 * Mark the edit a "bot" edit regardless of user rights
1284 * EDIT_DEFER_UPDATES
1285 * Defer some of the updates until the end of index.php
1286 * EDIT_AUTOSUMMARY
1287 * Fill in blank summaries with generated text where possible
1289 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1290 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1291 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1292 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1293 * to MediaWiki's performance-optimised locking strategy.
1295 * @return bool success
1297 function doEdit( $text, $summary, $flags = 0 ) {
1298 global $wgUser, $wgDBtransactions;
1300 wfProfileIn( __METHOD__ );
1301 $good = true;
1303 if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1304 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
1305 if ( $aid ) {
1306 $flags |= EDIT_UPDATE;
1307 } else {
1308 $flags |= EDIT_NEW;
1312 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1313 &$summary, $flags & EDIT_MINOR,
1314 null, null, &$flags ) ) )
1316 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1317 wfProfileOut( __METHOD__ );
1318 return false;
1321 # Silently ignore EDIT_MINOR if not allowed
1322 $isminor = ( $flags & EDIT_MINOR ) && $wgUser->isAllowed('minoredit');
1323 $bot = $flags & EDIT_FORCE_BOT;
1325 $oldtext = $this->getContent();
1326 $oldsize = strlen( $oldtext );
1328 # Provide autosummaries if one is not provided.
1329 if ($flags & EDIT_AUTOSUMMARY && $summary == '')
1330 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1332 $editInfo = $this->prepareTextForEdit( $text );
1333 $text = $editInfo->pst;
1334 $newsize = strlen( $text );
1336 $dbw = wfGetDB( DB_MASTER );
1337 $now = wfTimestampNow();
1339 if ( $flags & EDIT_UPDATE ) {
1340 # Update article, but only if changed.
1342 # Make sure the revision is either completely inserted or not inserted at all
1343 if( !$wgDBtransactions ) {
1344 $userAbort = ignore_user_abort( true );
1347 $lastRevision = 0;
1348 $revisionId = 0;
1350 $changed = ( strcmp( $text, $oldtext ) != 0 );
1352 if ( $changed ) {
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__ );
1364 return false;
1367 $revision = new Revision( array(
1368 'page' => $this->getId(),
1369 'comment' => $summary,
1370 'minor_edit' => $isminor,
1371 'text' => $text,
1372 'parent_id' => $lastRevision
1373 ) );
1375 $dbw->begin();
1376 $revisionId = $revision->insertOn( $dbw );
1378 # Update page
1379 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1381 if( !$ok ) {
1382 /* Belated edit conflict! Run away!! */
1383 $good = false;
1384 $dbw->rollback();
1385 } else {
1386 # Update recentchanges
1387 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1388 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1389 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1390 $revisionId );
1392 # Mark as patrolled if the user can do so
1393 if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
1394 RecentChange::markPatrolled( $rcid );
1395 PatrolLog::record( $rcid, true );
1398 $wgUser->incEditCount();
1399 $dbw->commit();
1401 } else {
1402 $revision = null;
1403 // Keep the same revision ID, but do some updates on it
1404 $revisionId = $this->getRevIdFetched();
1405 // Update page_touched, this is usually implicit in the page update
1406 // Other cache updates are done in onArticleEdit()
1407 $this->mTitle->invalidateCache();
1410 if( !$wgDBtransactions ) {
1411 ignore_user_abort( $userAbort );
1414 if ( $good ) {
1415 # Invalidate cache of this article and all pages using this article
1416 # as a template. Partly deferred.
1417 Article::onArticleEdit( $this->mTitle );
1419 # Update links tables, site stats, etc.
1420 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1422 } else {
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;
1431 $dbw->begin();
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(
1439 'page' => $newid,
1440 'comment' => $summary,
1441 'minor_edit' => $isminor,
1442 'text' => $text
1443 ) );
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();
1461 $dbw->commit();
1463 # Update links, etc.
1464 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1466 # Clear caches
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 ) ) {
1474 wfDoUpdates();
1477 if ( $good ) {
1478 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text, $summary,
1479 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1482 wfProfileOut( __METHOD__ );
1483 return $good;
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 "#"
1499 * @param string $extraq, extra query params
1501 function doRedirect( $noRedir = false, $sectionAnchor = '', $extraq = '' ) {
1502 global $wgOut;
1503 if ( $noRedir ) {
1504 $query = 'redirect=no';
1505 if( $extraq )
1506 $query .= "&$query";
1507 } else {
1508 $query = $extraq;
1510 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
1514 * Mark this particular edit/page as patrolled
1516 function markpatrolled() {
1517 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
1518 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1520 # Check patrol config options
1522 if ( !($wgUseNPPatrol || $wgUseRCPatrol)) {
1523 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1524 return;
1527 # If we haven't been given an rc_id value, we can't do anything
1528 $rcid = (int) $wgRequest->getVal('rcid');
1529 $rc = $rcid ? RecentChange::newFromId($rcid) : null;
1530 if ( is_null ( $rc ) )
1532 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1533 return;
1536 if ( !$wgUseRCPatrol && $rc->getAttribute( 'rc_type' ) != RC_NEW) {
1537 // Only new pages can be patrolled if the general patrolling is off....???
1538 // @fixme -- is this necessary? Shouldn't we only bother controlling the
1539 // front end here?
1540 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1541 return;
1544 # Check permissions
1545 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'patrol', $wgUser );
1547 if (count($permission_errors)>0)
1549 $wgOut->showPermissionsErrorPage( $permission_errors );
1550 return;
1553 # Handle the 'MarkPatrolled' hook
1554 if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
1555 return;
1558 #It would be nice to see where the user had actually come from, but for now just guess
1559 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
1560 $return = Title::makeTitle( NS_SPECIAL, $returnto );
1562 # If it's left up to us, check that the user is allowed to patrol this edit
1563 # If the user has the "autopatrol" right, then we'll assume there are no
1564 # other conditions stopping them doing so
1565 if( !$wgUser->isAllowed( 'autopatrol' ) ) {
1566 $rc = RecentChange::newFromId( $rcid );
1567 # Graceful error handling, as we've done before here...
1568 # (If the recent change doesn't exist, then it doesn't matter whether
1569 # the user is allowed to patrol it or not; nothing is going to happen
1570 if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
1571 # The user made this edit, and can't patrol it
1572 # Tell them so, and then back off
1573 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
1574 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
1575 $wgOut->returnToMain( false, $return );
1576 return;
1580 # Check that the revision isn't patrolled already
1581 # Prevents duplicate log entries
1582 if( !$rc->getAttribute( 'rc_patrolled' ) ) {
1583 # Mark the edit as patrolled
1584 RecentChange::markPatrolled( $rcid );
1585 PatrolLog::record( $rcid );
1586 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1589 # Inform the user
1590 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
1591 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
1592 $wgOut->returnToMain( false, $return );
1596 * User-interface handler for the "watch" action
1599 function watch() {
1601 global $wgUser, $wgOut;
1603 if ( $wgUser->isAnon() ) {
1604 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1605 return;
1607 if ( wfReadOnly() ) {
1608 $wgOut->readOnlyPage();
1609 return;
1612 if( $this->doWatch() ) {
1613 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1614 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1616 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
1619 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1623 * Add this page to $wgUser's watchlist
1624 * @return bool true on successful watch operation
1626 function doWatch() {
1627 global $wgUser;
1628 if( $wgUser->isAnon() ) {
1629 return false;
1632 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1633 $wgUser->addWatch( $this->mTitle );
1635 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1638 return false;
1642 * User interface handler for the "unwatch" action.
1644 function unwatch() {
1646 global $wgUser, $wgOut;
1648 if ( $wgUser->isAnon() ) {
1649 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1650 return;
1652 if ( wfReadOnly() ) {
1653 $wgOut->readOnlyPage();
1654 return;
1657 if( $this->doUnwatch() ) {
1658 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1659 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1661 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
1664 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1668 * Stop watching a page
1669 * @return bool true on successful unwatch
1671 function doUnwatch() {
1672 global $wgUser;
1673 if( $wgUser->isAnon() ) {
1674 return false;
1677 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1678 $wgUser->removeWatch( $this->mTitle );
1680 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1683 return false;
1687 * action=protect handler
1689 function protect() {
1690 $form = new ProtectionForm( $this );
1691 $form->execute();
1695 * action=unprotect handler (alias)
1697 function unprotect() {
1698 $this->protect();
1702 * Update the article's restriction field, and leave a log entry.
1704 * @param array $limit set of restriction keys
1705 * @param string $reason
1706 * @return bool true on success
1708 function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
1709 global $wgUser, $wgRestrictionTypes, $wgContLang;
1711 $id = $this->mTitle->getArticleID();
1712 if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
1713 return false;
1716 if (!$cascade) {
1717 $cascade = false;
1720 // Take this opportunity to purge out expired restrictions
1721 Title::purgeExpiredRestrictions();
1723 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1724 # we expect a single selection, but the schema allows otherwise.
1725 $current = array();
1726 foreach( $wgRestrictionTypes as $action )
1727 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1729 $current = Article::flattenRestrictions( $current );
1730 $updated = Article::flattenRestrictions( $limit );
1732 $changed = ( $current != $updated );
1733 $changed = $changed || ($this->mTitle->areRestrictionsCascading() != $cascade);
1734 $changed = $changed || ($this->mTitle->mRestrictionsExpiry != $expiry);
1735 $protect = ( $updated != '' );
1737 # If nothing's changed, do nothing
1738 if( $changed ) {
1739 global $wgGroupPermissions;
1740 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1742 $dbw = wfGetDB( DB_MASTER );
1744 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1746 $expiry_description = '';
1747 if ( $encodedExpiry != 'infinity' ) {
1748 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry, false, false ) ).')';
1751 # Prepare a null revision to be added to the history
1752 $modified = $current != '' && $protect;
1753 if ( $protect ) {
1754 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1755 } else {
1756 $comment_type = 'unprotectedarticle';
1758 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1760 foreach( $limit as $action => $restrictions ) {
1761 # Check if the group level required to edit also can protect pages
1762 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1763 $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) &&
1764 $wgGroupPermissions[$restrictions]['protect'] );
1767 $cascade_description = '';
1768 if ($cascade) {
1769 $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
1772 if( $reason )
1773 $comment .= ": $reason";
1774 if( $protect )
1775 $comment .= " [$updated]";
1776 if ( $expiry_description && $protect )
1777 $comment .= "$expiry_description";
1778 if ( $cascade )
1779 $comment .= "$cascade_description";
1781 # Update restrictions table
1782 foreach( $limit as $action => $restrictions ) {
1783 if ($restrictions != '' ) {
1784 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
1785 array( 'pr_page' => $id, 'pr_type' => $action
1786 , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
1787 , 'pr_expiry' => $encodedExpiry ), __METHOD__ );
1788 } else {
1789 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1790 'pr_type' => $action ), __METHOD__ );
1794 # Insert a null revision
1795 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1796 $nullRevId = $nullRevision->insertOn( $dbw );
1798 # Update page record
1799 $dbw->update( 'page',
1800 array( /* SET */
1801 'page_touched' => $dbw->timestamp(),
1802 'page_restrictions' => '',
1803 'page_latest' => $nullRevId
1804 ), array( /* WHERE */
1805 'page_id' => $id
1806 ), 'Article::protect'
1808 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1810 # Update the protection log
1811 $log = new LogPage( 'protect' );
1815 if( $protect ) {
1816 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
1817 } else {
1818 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1821 } # End hook
1822 } # End "changed" check
1824 return true;
1828 * Take an array of page restrictions and flatten it to a string
1829 * suitable for insertion into the page_restrictions field.
1830 * @param array $limit
1831 * @return string
1832 * @private
1834 function flattenRestrictions( $limit ) {
1835 if( !is_array( $limit ) ) {
1836 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1838 $bits = array();
1839 ksort( $limit );
1840 foreach( $limit as $action => $restrictions ) {
1841 if( $restrictions != '' ) {
1842 $bits[] = "$action=$restrictions";
1845 return implode( ':', $bits );
1849 * Auto-generates a deletion reason
1850 * @param bool &$hasHistory Whether the page has a history
1852 public function generateReason(&$hasHistory)
1854 global $wgContLang;
1855 $dbw = wfGetDB(DB_MASTER);
1856 // Get the last revision
1857 $rev = Revision::newFromTitle($this->mTitle);
1858 if(is_null($rev))
1859 return false;
1860 // Get the article's contents
1861 $contents = $rev->getText();
1862 $blank = false;
1863 // If the page is blank, use the text from the previous revision,
1864 // which can only be blank if there's a move/import/protect dummy revision involved
1865 if($contents == '')
1867 $prev = $rev->getPrevious();
1868 if($prev)
1870 $contents = $prev->getText();
1871 $blank = true;
1875 // Find out if there was only one contributor
1876 // Only scan the last 20 revisions
1877 $limit = 20;
1878 $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__,
1879 array('LIMIT' => $limit));
1880 if($res === false)
1881 // This page has no revisions, which is very weird
1882 return false;
1883 if($res->numRows() > 1)
1884 $hasHistory = true;
1885 else
1886 $hasHistory = false;
1887 $row = $dbw->fetchObject($res);
1888 $onlyAuthor = $row->rev_user_text;
1889 // Try to find a second contributor
1890 while( $row = $dbw->fetchObject($res) ) {
1891 if($row->rev_user_text != $onlyAuthor) {
1892 $onlyAuthor = false;
1893 break;
1896 $dbw->freeResult($res);
1898 // Generate the summary with a '$1' placeholder
1899 if($blank) {
1900 // The current revision is blank and the one before is also
1901 // blank. It's just not our lucky day
1902 $reason = wfMsgForContent('exbeforeblank', '$1');
1903 } else {
1904 if($onlyAuthor)
1905 $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
1906 else
1907 $reason = wfMsgForContent('excontent', '$1');
1910 // Replace newlines with spaces to prevent uglyness
1911 $contents = preg_replace("/[\n\r]/", ' ', $contents);
1912 // Calculate the maximum amount of chars to get
1913 // Max content length = max comment length - length of the comment (excl. $1) - '...'
1914 $maxLength = 255 - (strlen($reason) - 2) - 3;
1915 $contents = $wgContLang->truncate($contents, $maxLength, '...');
1916 // Remove possible unfinished links
1917 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
1918 // Now replace the '$1' placeholder
1919 $reason = str_replace( '$1', $contents, $reason );
1920 return $reason;
1925 * UI entry point for page deletion
1927 function delete() {
1928 global $wgUser, $wgOut, $wgRequest;
1930 $confirm = $wgRequest->wasPosted() &&
1931 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1933 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1934 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
1936 $reason = $this->DeleteReasonList;
1938 if ( $reason != 'other' && $this->DeleteReason != '') {
1939 // Entry from drop down menu + additional comment
1940 $reason .= ': ' . $this->DeleteReason;
1941 } elseif ( $reason == 'other' ) {
1942 $reason = $this->DeleteReason;
1944 # Flag to hide all contents of the archived revisions
1945 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('deleterevision');
1947 # This code desperately needs to be totally rewritten
1949 # Read-only check...
1950 if ( wfReadOnly() ) {
1951 $wgOut->readOnlyPage();
1952 return;
1955 # Check permissions
1956 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1958 if (count($permission_errors)>0) {
1959 $wgOut->showPermissionsErrorPage( $permission_errors );
1960 return;
1963 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
1965 # Better double-check that it hasn't been deleted yet!
1966 $dbw = wfGetDB( DB_MASTER );
1967 $conds = $this->mTitle->pageCond();
1968 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1969 if ( $latest === false ) {
1970 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1971 return;
1974 # Hack for big sites
1975 $bigHistory = $this->isBigDeletion();
1976 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
1977 global $wgLang, $wgDeleteRevisionsLimit;
1978 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
1979 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
1980 return;
1983 if( $confirm ) {
1984 $this->doDelete( $reason, $suppress );
1985 if( $wgRequest->getCheck( 'wpWatch' ) ) {
1986 $this->doWatch();
1987 } elseif( $this->mTitle->userIsWatching() ) {
1988 $this->doUnwatch();
1990 return;
1993 // Generate deletion reason
1994 $hasHistory = false;
1995 if ( !$reason ) $reason = $this->generateReason($hasHistory);
1997 // If the page has a history, insert a warning
1998 if( $hasHistory && !$confirm ) {
1999 $skin=$wgUser->getSkin();
2000 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
2001 if( $bigHistory ) {
2002 global $wgLang, $wgDeleteRevisionsLimit;
2003 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2004 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2008 return $this->confirmDelete( '', $reason );
2012 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2014 function isBigDeletion() {
2015 global $wgDeleteRevisionsLimit;
2016 if( $wgDeleteRevisionsLimit ) {
2017 $revCount = $this->estimateRevisionCount();
2018 return $revCount > $wgDeleteRevisionsLimit;
2020 return false;
2024 * @return int approximate revision count
2026 function estimateRevisionCount() {
2027 $dbr = wfGetDB();
2028 // For an exact count...
2029 //return $dbr->selectField( 'revision', 'COUNT(*)',
2030 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2031 return $dbr->estimateRowCount( 'revision', '*',
2032 array( 'rev_page' => $this->getId() ), __METHOD__ );
2036 * Get the last N authors
2037 * @param int $num Number of revisions to get
2038 * @param string $revLatest The latest rev_id, selected from the master (optional)
2039 * @return array Array of authors, duplicates not removed
2041 function getLastNAuthors( $num, $revLatest = 0 ) {
2042 wfProfileIn( __METHOD__ );
2044 // First try the slave
2045 // If that doesn't have the latest revision, try the master
2046 $continue = 2;
2047 $db = wfGetDB( DB_SLAVE );
2048 do {
2049 $res = $db->select( array( 'page', 'revision' ),
2050 array( 'rev_id', 'rev_user_text' ),
2051 array(
2052 'page_namespace' => $this->mTitle->getNamespace(),
2053 'page_title' => $this->mTitle->getDBkey(),
2054 'rev_page = page_id'
2055 ), __METHOD__, $this->getSelectOptions( array(
2056 'ORDER BY' => 'rev_timestamp DESC',
2057 'LIMIT' => $num
2060 if ( !$res ) {
2061 wfProfileOut( __METHOD__ );
2062 return array();
2064 $row = $db->fetchObject( $res );
2065 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2066 $db = wfGetDB( DB_MASTER );
2067 $continue--;
2068 } else {
2069 $continue = 0;
2071 } while ( $continue );
2073 $authors = array( $row->rev_user_text );
2074 while ( $row = $db->fetchObject( $res ) ) {
2075 $authors[] = $row->rev_user_text;
2077 wfProfileOut( __METHOD__ );
2078 return $authors;
2082 * Output deletion confirmation dialog
2083 * @param $par string FIXME: do we need this parameter? One Call from Article::delete with '' only.
2084 * @param $reason string Prefilled reason
2086 function confirmDelete( $par, $reason ) {
2087 global $wgOut, $wgUser, $wgContLang;
2088 $align = $wgContLang->isRtl() ? 'left' : 'right';
2090 wfDebug( "Article::confirmDelete\n" );
2092 $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
2093 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2094 $wgOut->addWikiMsg( 'confirmdeletetext' );
2096 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2097 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
2098 $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
2099 $suppress .= "</td></tr>";
2100 } else {
2101 $suppress = '';
2104 $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' . $par ), 'id' => 'deleteconfirm' ) ) .
2105 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2106 Xml::element( 'legend', null, wfMsg( 'delete-legend' ) ) .
2107 Xml::openElement( 'table' ) .
2108 "<tr id=\"wpDeleteReasonListRow\">
2109 <td align='$align'>" .
2110 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2111 "</td>
2112 <td>" .
2113 Xml::listDropDown( 'wpDeleteReasonList',
2114 wfMsgForContent( 'deletereason-dropdown' ),
2115 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2116 "</td>
2117 </tr>
2118 <tr id=\"wpDeleteReasonRow\">
2119 <td align='$align'>" .
2120 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2121 "</td>
2122 <td>" .
2123 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2124 "</td>
2125 </tr>
2126 <tr>
2127 <td></td>
2128 <td>" .
2129 Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '3' ) ) .
2130 "</td>
2131 </tr>
2132 $suppress
2133 <tr>
2134 <td></td>
2135 <td>" .
2136 Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
2137 "</td>
2138 </tr>" .
2139 Xml::closeElement( 'table' ) .
2140 Xml::closeElement( 'fieldset' ) .
2141 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2142 Xml::closeElement( 'form' );
2144 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2145 $skin = $wgUser->getSkin();
2146 $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
2147 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2150 $wgOut->addHTML( $form );
2151 $this->showLogExtract( $wgOut );
2156 * Show relevant lines from the deletion log
2158 function showLogExtract( $out ) {
2159 $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2160 LogEventsList::showLogExtract( $out, 'delete', $this->mTitle->getPrefixedText() );
2165 * Perform a deletion and output success or failure messages
2167 function doDelete( $reason, $suppress = false ) {
2168 global $wgOut, $wgUser;
2169 wfDebug( __METHOD__."\n" );
2171 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2172 if ( $this->doDeleteArticle( $reason, $suppress ) ) {
2173 $deleted = $this->mTitle->getPrefixedText();
2175 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2176 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2178 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2180 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2181 $wgOut->returnToMain( false );
2182 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2183 } else {
2184 $wgOut->showFatalError( wfMsg( 'cannotdelete' ).'<br/>'.wfMsg('cannotdelete-merge') );
2190 * Back-end article deletion
2191 * Deletes the article with database consistency, writes logs, purges caches
2192 * Returns success
2194 function doDeleteArticle( $reason, $suppress = false ) {
2195 global $wgUseSquid, $wgDeferredUpdateList;
2196 global $wgUseTrackbacks;
2198 wfDebug( __METHOD__."\n" );
2200 $dbw = wfGetDB( DB_MASTER );
2201 $ns = $this->mTitle->getNamespace();
2202 $t = $this->mTitle->getDBkey();
2203 $id = $this->mTitle->getArticleID();
2205 if ( $t == '' || $id == 0 ) {
2206 return false;
2209 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2210 array_push( $wgDeferredUpdateList, $u );
2212 // Bitfields to further suppress the content
2213 if ( $suppress ) {
2214 $bitfield = 0;
2215 // This should be 15...
2216 $bitfield |= Revision::DELETED_TEXT;
2217 $bitfield |= Revision::DELETED_COMMENT;
2218 $bitfield |= Revision::DELETED_USER;
2219 $bitfield |= Revision::DELETED_RESTRICTED;
2220 } else {
2221 $bitfield = 'rev_deleted';
2224 // For now, shunt the revision data into the archive table.
2225 // Text is *not* removed from the text table; bulk storage
2226 // is left intact to avoid breaking block-compression or
2227 // immutable storage schemes.
2229 // For backwards compatibility, note that some older archive
2230 // table entries will have ar_text and ar_flags fields still.
2232 // In the future, we may keep revisions and mark them with
2233 // the rev_deleted field, which is reserved for this purpose.
2234 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2235 array(
2236 'ar_namespace' => 'page_namespace',
2237 'ar_title' => 'page_title',
2238 'ar_comment' => 'rev_comment',
2239 'ar_user' => 'rev_user',
2240 'ar_user_text' => 'rev_user_text',
2241 'ar_timestamp' => 'rev_timestamp',
2242 'ar_minor_edit' => 'rev_minor_edit',
2243 'ar_rev_id' => 'rev_id',
2244 'ar_text_id' => 'rev_text_id',
2245 'ar_text' => '\'\'', // Be explicit to appease
2246 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2247 'ar_len' => 'rev_len',
2248 'ar_page_id' => 'page_id',
2249 'ar_deleted' => $bitfield
2250 ), array(
2251 'page_id' => $id,
2252 'page_id = rev_page'
2253 ), __METHOD__
2256 # Delete restrictions for it
2257 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2259 # Fix category table counts
2260 $cats = array();
2261 $res = $dbw->select( 'categorylinks', 'cl_to',
2262 array( 'cl_from' => $id ), __METHOD__ );
2263 foreach( $res as $row ) {
2264 $cats []= $row->cl_to;
2266 $this->updateCategoryCounts( array(), $cats );
2268 # Now that it's safely backed up, delete it
2269 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2271 # If using cascading deletes, we can skip some explicit deletes
2272 if ( !$dbw->cascadingDeletes() ) {
2273 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2275 if ($wgUseTrackbacks)
2276 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2278 # Delete outgoing links
2279 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2280 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2281 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2282 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2283 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2284 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2285 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2288 # If using cleanup triggers, we can skip some manual deletes
2289 if ( !$dbw->cleanupTriggers() ) {
2291 # Clean up recentchanges entries...
2292 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__ );
2295 # Clear caches
2296 Article::onArticleDelete( $this->mTitle );
2298 # Log the deletion, if the page was suppressed, log it at Oversight instead
2299 $logtype = $suppress ? 'suppress' : 'delete';
2300 $log = new LogPage( $logtype );
2301 $log->addEntry( 'delete', $this->mTitle, $reason );
2303 # Clear the cached article id so the interface doesn't act like we exist
2304 $this->mTitle->resetArticleID( 0 );
2305 $this->mTitle->mArticleID = 0;
2306 return true;
2310 * Roll back the most recent consecutive set of edits to a page
2311 * from the same user; fails if there are no eligible edits to
2312 * roll back to, e.g. user is the sole contributor. This function
2313 * performs permissions checks on $wgUser, then calls commitRollback()
2314 * to do the dirty work
2316 * @param string $fromP - Name of the user whose edits to rollback.
2317 * @param string $summary - Custom summary. Set to default summary if empty.
2318 * @param string $token - Rollback token.
2319 * @param bool $bot - If true, mark all reverted edits as bot.
2321 * @param array $resultDetails contains result-specific array of additional values
2322 * 'alreadyrolled' : 'current' (rev)
2323 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2325 * @return array of errors, each error formatted as
2326 * array(messagekey, param1, param2, ...).
2327 * On success, the array is empty. This array can also be passed to
2328 * OutputPage::showPermissionsErrorPage().
2330 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2331 global $wgUser;
2332 $resultDetails = null;
2334 # Check permissions
2335 $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
2336 $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
2337 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2338 $errors[] = array( 'sessionfailure' );
2340 if ( $wgUser->pingLimiter('rollback') || $wgUser->pingLimiter() ) {
2341 $errors[] = array( 'actionthrottledtext' );
2343 # If there were errors, bail out now
2344 if(!empty($errors))
2345 return $errors;
2347 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2351 * Backend implementation of doRollback(), please refer there for parameter
2352 * and return value documentation
2354 * NOTE: This function does NOT check ANY permissions, it just commits the
2355 * rollback to the DB Therefore, you should only call this function direct-
2356 * ly if you want to use custom permissions checks. If you don't, use
2357 * doRollback() instead.
2359 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2360 global $wgUseRCPatrol, $wgUser;
2361 $dbw = wfGetDB( DB_MASTER );
2363 if( wfReadOnly() ) {
2364 return array( array( 'readonlytext' ) );
2367 # Get the last editor
2368 $current = Revision::newFromTitle( $this->mTitle );
2369 if( is_null( $current ) ) {
2370 # Something wrong... no page?
2371 return array(array('notanarticle'));
2374 $from = str_replace( '_', ' ', $fromP );
2375 if( $from != $current->getUserText() ) {
2376 $resultDetails = array( 'current' => $current );
2377 return array(array('alreadyrolled',
2378 htmlspecialchars($this->mTitle->getPrefixedText()),
2379 htmlspecialchars($fromP),
2380 htmlspecialchars($current->getUserText())
2384 # Get the last edit not by this guy
2385 $user = intval( $current->getUser() );
2386 $user_text = $dbw->addQuotes( $current->getUserText() );
2387 $s = $dbw->selectRow( 'revision',
2388 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2389 array( 'rev_page' => $current->getPage(),
2390 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2391 ), __METHOD__,
2392 array( 'USE INDEX' => 'page_timestamp',
2393 'ORDER BY' => 'rev_timestamp DESC' )
2395 if( $s === false ) {
2396 # No one else ever edited this page
2397 return array(array('cantrollback'));
2398 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2399 # Only admins can see this text
2400 return array(array('notvisiblerev'));
2403 $set = array();
2404 if ( $bot && $wgUser->isAllowed('markbotedits') ) {
2405 # Mark all reverted edits as bot
2406 $set['rc_bot'] = 1;
2408 if ( $wgUseRCPatrol ) {
2409 # Mark all reverted edits as patrolled
2410 $set['rc_patrolled'] = 1;
2413 if ( $set ) {
2414 $dbw->update( 'recentchanges', $set,
2415 array( /* WHERE */
2416 'rc_cur_id' => $current->getPage(),
2417 'rc_user_text' => $current->getUserText(),
2418 "rc_timestamp > '{$s->rev_timestamp}'",
2419 ), __METHOD__
2423 # Generate the edit summary if necessary
2424 $target = Revision::newFromId( $s->rev_id );
2425 if( empty( $summary ) )
2427 global $wgLang;
2428 $summary = wfMsgForContent( 'revertpage',
2429 $target->getUserText(), $from,
2430 $s->rev_id, $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2431 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2435 # Save
2436 $flags = EDIT_UPDATE;
2438 if ($wgUser->isAllowed('minoredit'))
2439 $flags |= EDIT_MINOR;
2441 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2442 $flags |= EDIT_FORCE_BOT;
2443 $this->doEdit( $target->getText(), $summary, $flags );
2445 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
2447 $resultDetails = array(
2448 'summary' => $summary,
2449 'current' => $current,
2450 'target' => $target,
2452 return array();
2456 * User interface for rollback operations
2458 function rollback() {
2459 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2460 $details = null;
2462 $result = $this->doRollback(
2463 $wgRequest->getVal( 'from' ),
2464 $wgRequest->getText( 'summary' ),
2465 $wgRequest->getVal( 'token' ),
2466 $wgRequest->getBool( 'bot' ),
2467 $details
2470 if( in_array( array( 'blocked' ), $result ) ) {
2471 $wgOut->blockedPage();
2472 return;
2474 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
2475 $wgOut->rateLimited();
2476 return;
2478 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ){
2479 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2480 $errArray = $result[0];
2481 $errMsg = array_shift( $errArray );
2482 $wgOut->addWikiMsgArray( $errMsg, $errArray );
2483 if( isset( $details['current'] ) ){
2484 $current = $details['current'];
2485 if( $current->getComment() != '' ) {
2486 $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
2489 return;
2491 # Display permissions errors before read-only message -- there's no
2492 # point in misleading the user into thinking the inability to rollback
2493 # is only temporary.
2494 if( !empty($result) && $result !== array( array('readonlytext') ) ) {
2495 # array_diff is completely broken for arrays of arrays, sigh. Re-
2496 # move any 'readonlytext' error manually.
2497 $out = array();
2498 foreach( $result as $error ) {
2499 if( $error != array( 'readonlytext' ) ) {
2500 $out []= $error;
2503 $wgOut->showPermissionsErrorPage( $out );
2504 return;
2506 if( $result == array( array('readonlytext') ) ) {
2507 $wgOut->readOnlyPage();
2508 return;
2511 $current = $details['current'];
2512 $target = $details['target'];
2513 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
2514 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2515 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
2516 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
2517 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
2518 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
2519 $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
2520 $wgOut->returnToMain( false, $this->mTitle );
2525 * Do standard deferred updates after page view
2526 * @private
2528 function viewUpdates() {
2529 global $wgDeferredUpdateList;
2531 if ( 0 != $this->getID() ) {
2532 global $wgDisableCounters;
2533 if( !$wgDisableCounters ) {
2534 Article::incViewCount( $this->getID() );
2535 $u = new SiteStatsUpdate( 1, 0, 0 );
2536 array_push( $wgDeferredUpdateList, $u );
2540 # Update newtalk / watchlist notification status
2541 global $wgUser;
2542 $wgUser->clearNotification( $this->mTitle );
2546 * Prepare text which is about to be saved.
2547 * Returns a stdclass with source, pst and output members
2549 function prepareTextForEdit( $text, $revid=null ) {
2550 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
2551 // Already prepared
2552 return $this->mPreparedEdit;
2554 global $wgParser;
2555 $edit = (object)array();
2556 $edit->revid = $revid;
2557 $edit->newText = $text;
2558 $edit->pst = $this->preSaveTransform( $text );
2559 $options = new ParserOptions;
2560 $options->setTidy( true );
2561 $options->enableLimitReport();
2562 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
2563 $edit->oldText = $this->getContent();
2564 $this->mPreparedEdit = $edit;
2565 return $edit;
2569 * Do standard deferred updates after page edit.
2570 * Update links tables, site stats, search index and message cache.
2571 * Every 100th edit, prune the recent changes table.
2573 * @private
2574 * @param $text New text of the article
2575 * @param $summary Edit summary
2576 * @param $minoredit Minor edit
2577 * @param $timestamp_of_pagechange Timestamp associated with the page change
2578 * @param $newid rev_id value of the new revision
2579 * @param $changed Whether or not the content actually changed
2581 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2582 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
2584 wfProfileIn( __METHOD__ );
2586 # Parse the text
2587 # Be careful not to double-PST: $text is usually already PST-ed once
2588 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2589 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2590 $editInfo = $this->prepareTextForEdit( $text, $newid );
2591 } else {
2592 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2593 $editInfo = $this->mPreparedEdit;
2596 # Save it to the parser cache
2597 if ( $wgEnableParserCache ) {
2598 $parserCache = ParserCache::singleton();
2599 $parserCache->save( $editInfo->output, $this, $wgUser );
2602 # Update the links tables
2603 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2604 $u->doUpdate();
2606 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2607 if ( 0 == mt_rand( 0, 99 ) ) {
2608 // Flush old entries from the `recentchanges` table; we do this on
2609 // random requests so as to avoid an increase in writes for no good reason
2610 global $wgRCMaxAge;
2611 $dbw = wfGetDB( DB_MASTER );
2612 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2613 $recentchanges = $dbw->tableName( 'recentchanges' );
2614 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2615 $dbw->query( $sql );
2619 $id = $this->getID();
2620 $title = $this->mTitle->getPrefixedDBkey();
2621 $shortTitle = $this->mTitle->getDBkey();
2623 if ( 0 == $id ) {
2624 wfProfileOut( __METHOD__ );
2625 return;
2628 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2629 array_push( $wgDeferredUpdateList, $u );
2630 $u = new SearchUpdate( $id, $title, $text );
2631 array_push( $wgDeferredUpdateList, $u );
2633 # If this is another user's talk page, update newtalk
2634 # Don't do this if $changed = false otherwise some idiot can null-edit a
2635 # load of user talk pages and piss people off, nor if it's a minor edit
2636 # by a properly-flagged bot.
2637 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
2638 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2639 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2640 $other = User::newFromName( $shortTitle );
2641 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2642 // An anonymous user
2643 $other = new User();
2644 $other->setName( $shortTitle );
2646 if( $other ) {
2647 $other->setNewtalk( true );
2652 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2653 $wgMessageCache->replace( $shortTitle, $text );
2656 wfProfileOut( __METHOD__ );
2660 * Perform article updates on a special page creation.
2662 * @param Revision $rev
2664 * @todo This is a shitty interface function. Kill it and replace the
2665 * other shitty functions like editUpdates and such so it's not needed
2666 * anymore.
2668 function createUpdates( $rev ) {
2669 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
2670 $this->mTotalAdjustment = 1;
2671 $this->editUpdates( $rev->getText(), $rev->getComment(),
2672 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2676 * Generate the navigation links when browsing through an article revisions
2677 * It shows the information as:
2678 * Revision as of \<date\>; view current revision
2679 * \<- Previous version | Next Version -\>
2681 * @private
2682 * @param string $oldid Revision ID of this article revision
2684 function setOldSubtitle( $oldid=0 ) {
2685 global $wgLang, $wgOut, $wgUser;
2687 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2688 return;
2691 $revision = Revision::newFromId( $oldid );
2693 $current = ( $oldid == $this->mLatest );
2694 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2695 $sk = $wgUser->getSkin();
2696 $lnk = $current
2697 ? wfMsg( 'currentrevisionlink' )
2698 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2699 $curdiff = $current
2700 ? wfMsg( 'diff' )
2701 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2702 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2703 $prevlink = $prev
2704 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2705 : wfMsg( 'previousrevision' );
2706 $prevdiff = $prev
2707 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2708 : wfMsg( 'diff' );
2709 $nextlink = $current
2710 ? wfMsg( 'nextrevision' )
2711 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2712 $nextdiff = $current
2713 ? wfMsg( 'diff' )
2714 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2716 $cdel='';
2717 if( $wgUser->isAllowed( 'deleterevision' ) ) {
2718 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
2719 if( $revision->isCurrent() ) {
2720 // We don't handle top deleted edits too well
2721 $cdel = wfMsgHtml('rev-delundel');
2722 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
2723 // If revision was hidden from sysops
2724 $cdel = wfMsgHtml('rev-delundel');
2725 } else {
2726 $cdel = $sk->makeKnownLinkObj( $revdel,
2727 wfMsgHtml('rev-delundel'),
2728 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
2729 '&oldid=' . urlencode( $oldid ) );
2730 // Bolden oversighted content
2731 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
2732 $cdel = "<strong>$cdel</strong>";
2734 $cdel = "(<small>$cdel</small>) ";
2736 # Show user links if allowed to see them. Normally they
2737 # are hidden regardless, but since we can already see the text here...
2738 $userlinks = $sk->revUserTools( $revision, false );
2740 $m = wfMsg( 'revision-info-current' );
2741 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
2742 ? 'revision-info-current'
2743 : 'revision-info';
2745 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
2747 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
2748 $wgOut->setSubtitle( $r );
2752 * This function is called right before saving the wikitext,
2753 * so we can do things like signatures and links-in-context.
2755 * @param string $text
2757 function preSaveTransform( $text ) {
2758 global $wgParser, $wgUser;
2759 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2762 /* Caching functions */
2765 * checkLastModified returns true if it has taken care of all
2766 * output to the client that is necessary for this request.
2767 * (that is, it has sent a cached version of the page)
2769 function tryFileCache() {
2770 static $called = false;
2771 if( $called ) {
2772 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2773 return;
2775 $called = true;
2776 if($this->isFileCacheable()) {
2777 $touched = $this->mTouched;
2778 $cache = new HTMLFileCache( $this->mTitle );
2779 if($cache->isFileCacheGood( $touched )) {
2780 wfDebug( "Article::tryFileCache(): about to load file\n" );
2781 $cache->loadFromFileCache();
2782 return true;
2783 } else {
2784 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2785 ob_start( array(&$cache, 'saveToFileCache' ) );
2787 } else {
2788 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2793 * Check if the page can be cached
2794 * @return bool
2796 function isFileCacheable() {
2797 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
2798 $action = $wgRequest->getVal( 'action' );
2799 $oldid = $wgRequest->getVal( 'oldid' );
2800 $diff = $wgRequest->getVal( 'diff' );
2801 $redirect = $wgRequest->getVal( 'redirect' );
2802 $printable = $wgRequest->getVal( 'printable' );
2803 $page = $wgRequest->getVal( 'page' );
2805 //check for non-standard user language; this covers uselang,
2806 //and extensions for auto-detecting user language.
2807 $ulang = $wgLang->getCode();
2808 $clang = $wgContLang->getCode();
2810 $cacheable = $wgUseFileCache
2811 && (!$wgShowIPinHeader)
2812 && ($this->getID() != 0)
2813 && ($wgUser->isAnon())
2814 && (!$wgUser->getNewtalk())
2815 && ($this->mTitle->getNamespace() != NS_SPECIAL )
2816 && (empty( $action ) || $action == 'view')
2817 && (!isset($oldid))
2818 && (!isset($diff))
2819 && (!isset($redirect))
2820 && (!isset($printable))
2821 && !isset($page)
2822 && (!$this->mRedirectedFrom)
2823 && ($ulang === $clang);
2825 if ( $cacheable ) {
2826 //extension may have reason to disable file caching on some pages.
2827 $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
2830 return $cacheable;
2834 * Loads page_touched and returns a value indicating if it should be used
2837 function checkTouched() {
2838 if( !$this->mDataLoaded ) {
2839 $this->loadPageData();
2841 return !$this->mIsRedirect;
2845 * Get the page_touched field
2847 function getTouched() {
2848 # Ensure that page data has been loaded
2849 if( !$this->mDataLoaded ) {
2850 $this->loadPageData();
2852 return $this->mTouched;
2856 * Get the page_latest field
2858 function getLatest() {
2859 if ( !$this->mDataLoaded ) {
2860 $this->loadPageData();
2862 return $this->mLatest;
2866 * Edit an article without doing all that other stuff
2867 * The article must already exist; link tables etc
2868 * are not updated, caches are not flushed.
2870 * @param string $text text submitted
2871 * @param string $comment comment submitted
2872 * @param bool $minor whereas it's a minor modification
2874 function quickEdit( $text, $comment = '', $minor = 0 ) {
2875 wfProfileIn( __METHOD__ );
2877 $dbw = wfGetDB( DB_MASTER );
2878 $dbw->begin();
2879 $revision = new Revision( array(
2880 'page' => $this->getId(),
2881 'text' => $text,
2882 'comment' => $comment,
2883 'minor_edit' => $minor ? 1 : 0,
2884 ) );
2885 $revision->insertOn( $dbw );
2886 $this->updateRevisionOn( $dbw, $revision );
2887 $dbw->commit();
2889 wfProfileOut( __METHOD__ );
2893 * Used to increment the view counter
2895 * @static
2896 * @param integer $id article id
2898 function incViewCount( $id ) {
2899 $id = intval( $id );
2900 global $wgHitcounterUpdateFreq, $wgDBtype;
2902 $dbw = wfGetDB( DB_MASTER );
2903 $pageTable = $dbw->tableName( 'page' );
2904 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2905 $acchitsTable = $dbw->tableName( 'acchits' );
2907 if( $wgHitcounterUpdateFreq <= 1 ) {
2908 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2909 return;
2912 # Not important enough to warrant an error page in case of failure
2913 $oldignore = $dbw->ignoreErrors( true );
2915 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2917 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2918 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2919 # Most of the time (or on SQL errors), skip row count check
2920 $dbw->ignoreErrors( $oldignore );
2921 return;
2924 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2925 $row = $dbw->fetchObject( $res );
2926 $rown = intval( $row->n );
2927 if( $rown >= $wgHitcounterUpdateFreq ){
2928 wfProfileIn( 'Article::incViewCount-collect' );
2929 $old_user_abort = ignore_user_abort( true );
2931 if ($wgDBtype == 'mysql')
2932 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2933 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2934 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
2935 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2936 'GROUP BY hc_id');
2937 $dbw->query("DELETE FROM $hitcounterTable");
2938 if ($wgDBtype == 'mysql') {
2939 $dbw->query('UNLOCK TABLES');
2940 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2941 'WHERE page_id = hc_id');
2943 else {
2944 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
2945 "FROM $acchitsTable WHERE page_id = hc_id");
2947 $dbw->query("DROP TABLE $acchitsTable");
2949 ignore_user_abort( $old_user_abort );
2950 wfProfileOut( 'Article::incViewCount-collect' );
2952 $dbw->ignoreErrors( $oldignore );
2955 /**#@+
2956 * The onArticle*() functions are supposed to be a kind of hooks
2957 * which should be called whenever any of the specified actions
2958 * are done.
2960 * This is a good place to put code to clear caches, for instance.
2962 * This is called on page move and undelete, as well as edit
2963 * @static
2964 * @param $title_obj a title object
2967 static function onArticleCreate($title) {
2968 # The talk page isn't in the regular link tables, so we need to update manually:
2969 if ( $title->isTalkPage() ) {
2970 $other = $title->getSubjectPage();
2971 } else {
2972 $other = $title->getTalkPage();
2974 $other->invalidateCache();
2975 $other->purgeSquid();
2977 $title->touchLinks();
2978 $title->purgeSquid();
2979 $title->deleteTitleProtection();
2982 static function onArticleDelete( $title ) {
2983 global $wgUseFileCache, $wgMessageCache;
2985 // Update existence markers on article/talk tabs...
2986 if( $title->isTalkPage() ) {
2987 $other = $title->getSubjectPage();
2988 } else {
2989 $other = $title->getTalkPage();
2991 $other->invalidateCache();
2992 $other->purgeSquid();
2994 $title->touchLinks();
2995 $title->purgeSquid();
2997 # File cache
2998 if ( $wgUseFileCache ) {
2999 $cm = new HTMLFileCache( $title );
3000 @unlink( $cm->fileCacheName() );
3003 if( $title->getNamespace() == NS_MEDIAWIKI) {
3004 $wgMessageCache->replace( $title->getDBkey(), false );
3006 if( $title->getNamespace() == NS_IMAGE ) {
3007 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3008 $update->doUpdate();
3013 * Purge caches on page update etc
3015 static function onArticleEdit( $title ) {
3016 global $wgDeferredUpdateList, $wgUseFileCache;
3018 // Invalidate caches of articles which include this page
3019 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3021 // Invalidate the caches of all pages which redirect here
3022 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3024 # Purge squid for this page only
3025 $title->purgeSquid();
3027 # Clear file cache
3028 if ( $wgUseFileCache ) {
3029 $cm = new HTMLFileCache( $title );
3030 @unlink( $cm->fileCacheName() );
3034 /**#@-*/
3037 * Overriden by ImagePage class, only present here to avoid a fatal error
3038 * Called for ?action=revert
3040 public function revert(){
3041 global $wgOut;
3042 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3046 * Info about this page
3047 * Called for ?action=info when $wgAllowPageInfo is on.
3049 * @public
3051 function info() {
3052 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3054 if ( !$wgAllowPageInfo ) {
3055 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3056 return;
3059 $page = $this->mTitle->getSubjectPage();
3061 $wgOut->setPagetitle( $page->getPrefixedText() );
3062 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3063 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
3065 if( !$this->mTitle->exists() ) {
3066 $wgOut->addHtml( '<div class="noarticletext">' );
3067 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3068 // This doesn't quite make sense; the user is asking for
3069 // information about the _page_, not the message... -- RC
3070 $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3071 } else {
3072 $msg = $wgUser->isLoggedIn()
3073 ? 'noarticletext'
3074 : 'noarticletextanon';
3075 $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
3077 $wgOut->addHtml( '</div>' );
3078 } else {
3079 $dbr = wfGetDB( DB_SLAVE );
3080 $wl_clause = array(
3081 'wl_title' => $page->getDBkey(),
3082 'wl_namespace' => $page->getNamespace() );
3083 $numwatchers = $dbr->selectField(
3084 'watchlist',
3085 'COUNT(*)',
3086 $wl_clause,
3087 __METHOD__,
3088 $this->getSelectOptions() );
3090 $pageInfo = $this->pageCountInfo( $page );
3091 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3093 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3094 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3095 if( $talkInfo ) {
3096 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3098 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3099 if( $talkInfo ) {
3100 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3102 $wgOut->addHTML( '</ul>' );
3108 * Return the total number of edits and number of unique editors
3109 * on a given page. If page does not exist, returns false.
3111 * @param Title $title
3112 * @return array
3113 * @private
3115 function pageCountInfo( $title ) {
3116 $id = $title->getArticleId();
3117 if( $id == 0 ) {
3118 return false;
3121 $dbr = wfGetDB( DB_SLAVE );
3123 $rev_clause = array( 'rev_page' => $id );
3125 $edits = $dbr->selectField(
3126 'revision',
3127 'COUNT(rev_page)',
3128 $rev_clause,
3129 __METHOD__,
3130 $this->getSelectOptions() );
3132 $authors = $dbr->selectField(
3133 'revision',
3134 'COUNT(DISTINCT rev_user_text)',
3135 $rev_clause,
3136 __METHOD__,
3137 $this->getSelectOptions() );
3139 return array( 'edits' => $edits, 'authors' => $authors );
3143 * Return a list of templates used by this article.
3144 * Uses the templatelinks table
3146 * @return array Array of Title objects
3148 function getUsedTemplates() {
3149 $result = array();
3150 $id = $this->mTitle->getArticleID();
3151 if( $id == 0 ) {
3152 return array();
3155 $dbr = wfGetDB( DB_SLAVE );
3156 $res = $dbr->select( array( 'templatelinks' ),
3157 array( 'tl_namespace', 'tl_title' ),
3158 array( 'tl_from' => $id ),
3159 'Article:getUsedTemplates' );
3160 if ( false !== $res ) {
3161 if ( $dbr->numRows( $res ) ) {
3162 while ( $row = $dbr->fetchObject( $res ) ) {
3163 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3167 $dbr->freeResult( $res );
3168 return $result;
3172 * Returns a list of hidden categories this page is a member of.
3173 * Uses the page_props and categorylinks tables.
3175 * @return array Array of Title objects
3177 function getHiddenCategories() {
3178 $result = array();
3179 $id = $this->mTitle->getArticleID();
3180 if( $id == 0 ) {
3181 return array();
3184 $dbr = wfGetDB( DB_SLAVE );
3185 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3186 array( 'cl_to' ),
3187 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3188 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3189 'Article:getHiddenCategories' );
3190 if ( false !== $res ) {
3191 if ( $dbr->numRows( $res ) ) {
3192 while ( $row = $dbr->fetchObject( $res ) ) {
3193 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3197 $dbr->freeResult( $res );
3198 return $result;
3202 * Return an auto-generated summary if the text provided is a redirect.
3204 * @param string $text The wikitext to check
3205 * @return string '' or an appropriate summary
3207 public static function getRedirectAutosummary( $text ) {
3208 $rt = Title::newFromRedirect( $text );
3209 if( is_object( $rt ) )
3210 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3211 else
3212 return '';
3216 * Return an auto-generated summary if the new text is much shorter than
3217 * the old text.
3219 * @param string $oldtext The previous text of the page
3220 * @param string $text The submitted text of the page
3221 * @return string An appropriate autosummary, or an empty string.
3223 public static function getBlankingAutosummary( $oldtext, $text ) {
3224 if ($oldtext!='' && $text=='') {
3225 return wfMsgForContent('autosumm-blank');
3226 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
3227 #Removing more than 90% of the article
3228 global $wgContLang;
3229 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
3230 return wfMsgForContent('autosumm-replace', $truncatedtext);
3231 } else {
3232 return '';
3237 * Return an applicable autosummary if one exists for the given edit.
3238 * @param string $oldtext The previous text of the page.
3239 * @param string $newtext The submitted text of the page.
3240 * @param bitmask $flags A bitmask of flags submitted for the edit.
3241 * @return string An appropriate autosummary, or an empty string.
3243 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3245 # This code is UGLY UGLY UGLY.
3246 # Somebody PLEASE come up with a more elegant way to do it.
3248 #Redirect autosummaries
3249 $summary = self::getRedirectAutosummary( $newtext );
3251 if ($summary)
3252 return $summary;
3254 #Blanking autosummaries
3255 if (!($flags & EDIT_NEW))
3256 $summary = self::getBlankingAutosummary( $oldtext, $newtext );
3258 if ($summary)
3259 return $summary;
3261 #New page autosummaries
3262 if ($flags & EDIT_NEW && strlen($newtext)) {
3263 #If they're making a new article, give its text, truncated, in the summary.
3264 global $wgContLang;
3265 $truncatedtext = $wgContLang->truncate(
3266 str_replace("\n", ' ', $newtext),
3267 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
3268 '...' );
3269 $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
3272 if ($summary)
3273 return $summary;
3275 return $summary;
3279 * Add the primary page-view wikitext to the output buffer
3280 * Saves the text into the parser cache if possible.
3281 * Updates templatelinks if it is out of date.
3283 * @param string $text
3284 * @param bool $cache
3286 public function outputWikiText( $text, $cache = true ) {
3287 global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
3289 $popts = $wgOut->parserOptions();
3290 $popts->setTidy(true);
3291 $popts->enableLimitReport();
3292 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3293 $popts, true, true, $this->getRevIdFetched() );
3294 $popts->setTidy(false);
3295 $popts->enableLimitReport( false );
3296 if ( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3297 $parserCache = ParserCache::singleton();
3298 $parserCache->save( $parserOutput, $this, $wgUser );
3301 if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
3302 // templatelinks table may have become out of sync,
3303 // especially if using variable-based transclusions.
3304 // For paranoia, check if things have changed and if
3305 // so apply updates to the database. This will ensure
3306 // that cascaded protections apply as soon as the changes
3307 // are visible.
3309 # Get templates from templatelinks
3310 $id = $this->mTitle->getArticleID();
3312 $tlTemplates = array();
3314 $dbr = wfGetDB( DB_SLAVE );
3315 $res = $dbr->select( array( 'templatelinks' ),
3316 array( 'tl_namespace', 'tl_title' ),
3317 array( 'tl_from' => $id ),
3318 'Article:getUsedTemplates' );
3320 global $wgContLang;
3322 if ( false !== $res ) {
3323 if ( $dbr->numRows( $res ) ) {
3324 while ( $row = $dbr->fetchObject( $res ) ) {
3325 $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
3330 # Get templates from parser output.
3331 $poTemplates_allns = $parserOutput->getTemplates();
3333 $poTemplates = array ();
3334 foreach ( $poTemplates_allns as $ns_templates ) {
3335 $poTemplates = array_merge( $poTemplates, $ns_templates );
3338 # Get the diff
3339 $templates_diff = array_diff( $poTemplates, $tlTemplates );
3341 if ( count( $templates_diff ) > 0 ) {
3342 # Whee, link updates time.
3343 $u = new LinksUpdate( $this->mTitle, $parserOutput );
3345 $dbw = wfGetDb( DB_MASTER );
3346 $dbw->begin();
3348 $u->doUpdate();
3350 $dbw->commit();
3354 $wgOut->addParserOutput( $parserOutput );
3358 * Update all the appropriate counts in the category table, given that
3359 * we've added the categories $added and deleted the categories $deleted.
3361 * @param $added array The names of categories that were added
3362 * @param $deleted array The names of categories that were deleted
3363 * @return null
3365 public function updateCategoryCounts( $added, $deleted ) {
3366 $ns = $this->mTitle->getNamespace();
3367 $dbw = wfGetDB( DB_MASTER );
3369 # First make sure the rows exist. If one of the "deleted" ones didn't
3370 # exist, we might legitimately not create it, but it's simpler to just
3371 # create it and then give it a negative value, since the value is bogus
3372 # anyway.
3374 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3375 $insertCats = array_merge( $added, $deleted );
3376 if( !$insertCats ) {
3377 # Okay, nothing to do
3378 return;
3380 $insertRows = array();
3381 foreach( $insertCats as $cat ) {
3382 $insertRows[] = array( 'cat_title' => $cat );
3384 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3386 $addFields = array( 'cat_pages = cat_pages + 1' );
3387 $removeFields = array( 'cat_pages = cat_pages - 1' );
3388 if( $ns == NS_CATEGORY ) {
3389 $addFields[] = 'cat_subcats = cat_subcats + 1';
3390 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3391 } elseif( $ns == NS_IMAGE ) {
3392 $addFields[] = 'cat_files = cat_files + 1';
3393 $removeFields[] = 'cat_files = cat_files - 1';
3396 if ( $added ) {
3397 $dbw->update(
3398 'category',
3399 $addFields,
3400 array( 'cat_title' => $added ),
3401 __METHOD__
3404 if ( $deleted ) {
3405 $dbw->update(
3406 'category',
3407 $removeFields,
3408 array( 'cat_title' => $deleted ),
3409 __METHOD__