Bug 23733 - Add IDs to messages used on CSS/JS pages
[mediawiki.git] / includes / Article.php
blob39cfc152c28657656df3ff8121057eb23601e052
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
7 /**
8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
14 * @internal documentation reviewed 15 Mar 2010
16 class Article {
17 /**@{{
18 * @private
20 var $mComment = ''; // !<
21 var $mContent; // !<
22 var $mContentLoaded = false; // !<
23 var $mCounter = -1; // !< Not loaded
24 var $mCurID = -1; // !< Not loaded
25 var $mDataLoaded = false; // !<
26 var $mForUpdate = false; // !<
27 var $mGoodAdjustment = 0; // !<
28 var $mIsRedirect = false; // !<
29 var $mLatest = false; // !<
30 var $mMinorEdit; // !<
31 var $mOldId; // !<
32 var $mPreparedEdit = false; // !< Title object if set
33 var $mRedirectedFrom = null; // !< Title object if set
34 var $mRedirectTarget = null; // !< Title object if set
35 var $mRedirectUrl = false; // !<
36 var $mRevIdFetched = 0; // !<
37 var $mRevision; // !< Revision object if set
38 var $mTimestamp = ''; // !<
39 var $mTitle; // !< Title object
40 var $mTotalAdjustment = 0; // !<
41 var $mTouched = '19700101000000'; // !<
42 var $mUser = -1; // !< Not loaded
43 var $mUserText = ''; // !< username from Revision if set
44 var $mParserOptions; // !< ParserOptions object
45 var $mParserOutput; // !< ParserCache object if set
46 /**@}}*/
48 /**
49 * Constructor and clear the article
50 * @param $title Reference to a Title object.
51 * @param $oldId Integer revision ID, null to fetch from request, zero for current
53 public function __construct( Title $title, $oldId = null ) {
54 $this->mTitle =& $title;
55 $this->mOldId = $oldId;
58 /**
59 * Constructor from an article article
60 * @param $id The article ID to load
62 public static function newFromID( $id ) {
63 $t = Title::newFromID( $id );
64 # FIXME: doesn't inherit right
65 return $t == null ? null : new self( $t );
66 # return $t == null ? null : new static( $t ); // PHP 5.3
69 /**
70 * Tell the page view functions that this view was redirected
71 * from another page on the wiki.
72 * @param $from Title object.
74 public function setRedirectedFrom( Title $from ) {
75 $this->mRedirectedFrom = $from;
78 /**
79 * If this page is a redirect, get its target
81 * The target will be fetched from the redirect table if possible.
82 * If this page doesn't have an entry there, call insertRedirect()
83 * @return mixed Title object, or null if this page is not a redirect
85 public function getRedirectTarget() {
86 if ( !$this->mTitle || !$this->mTitle->isRedirect() ) {
87 return null;
90 if ( !is_null( $this->mRedirectTarget ) ) {
91 return $this->mRedirectTarget;
94 # Query the redirect table
95 $dbr = wfGetDB( DB_SLAVE );
96 $row = $dbr->selectRow( 'redirect',
97 array( 'rd_namespace', 'rd_title' ),
98 array( 'rd_from' => $this->getID() ),
99 __METHOD__
102 if ( $row ) {
103 return $this->mRedirectTarget = Title::makeTitle( $row->rd_namespace, $row->rd_title );
106 # This page doesn't have an entry in the redirect table
107 return $this->mRedirectTarget = $this->insertRedirect();
111 * Insert an entry for this page into the redirect table.
113 * Don't call this function directly unless you know what you're doing.
114 * @return Title object
116 public function insertRedirect() {
117 $retval = Title::newFromRedirect( $this->getContent() );
119 if ( !$retval ) {
120 return null;
123 $dbw = wfGetDB( DB_MASTER );
124 $dbw->replace( 'redirect', array( 'rd_from' ),
125 array(
126 'rd_from' => $this->getID(),
127 'rd_namespace' => $retval->getNamespace(),
128 'rd_title' => $retval->getDBkey()
130 __METHOD__
133 return $retval;
137 * Get the Title object this page redirects to
139 * @return mixed false, Title of in-wiki target, or string with URL
141 public function followRedirect() {
142 $text = $this->getContent();
144 return $this->followRedirectText( $text );
148 * Get the Title object this text redirects to
150 * @param $text string article content containing redirect info
151 * @return mixed false, Title of in-wiki target, or string with URL
153 public function followRedirectText( $text ) {
154 $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
155 # process if title object is valid and not special:userlogout
157 if ( $rt ) {
158 if ( $rt->getInterwiki() != '' ) {
159 if ( $rt->isLocal() ) {
160 // Offsite wikis need an HTTP redirect.
162 // This can be hard to reverse and may produce loops,
163 // so they may be disabled in the site configuration.
164 $source = $this->mTitle->getFullURL( 'redirect=no' );
165 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
167 } else {
168 if ( $rt->getNamespace() == NS_SPECIAL ) {
169 // Gotta handle redirects to special pages differently:
170 // Fill the HTTP response "Location" header and ignore
171 // the rest of the page we're on.
173 // This can be hard to reverse, so they may be disabled.
174 if ( $rt->isSpecial( 'Userlogout' ) ) {
175 // rolleyes
176 } else {
177 return $rt->getFullURL();
181 return $rt;
185 // No or invalid redirect
186 return false;
190 * get the title object of the article
191 * @return Title object of current title
193 public function getTitle() {
194 return $this->mTitle;
198 * Clear the object
199 * @private
201 public function clear() {
202 $this->mDataLoaded = false;
203 $this->mContentLoaded = false;
205 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
206 $this->mRedirectedFrom = null; # Title object if set
207 $this->mRedirectTarget = null; # Title object if set
208 $this->mUserText =
209 $this->mTimestamp = $this->mComment = '';
210 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
211 $this->mTouched = '19700101000000';
212 $this->mForUpdate = false;
213 $this->mIsRedirect = false;
214 $this->mRevIdFetched = 0;
215 $this->mRedirectUrl = false;
216 $this->mLatest = false;
217 $this->mPreparedEdit = false;
221 * Note that getContent/loadContent do not follow redirects anymore.
222 * If you need to fetch redirectable content easily, try
223 * the shortcut in Article::followRedirect()
225 * @return Return the text of this revision
227 public function getContent() {
228 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
230 wfProfileIn( __METHOD__ );
232 if ( $this->getID() === 0 ) {
233 # If this is a MediaWiki:x message, then load the messages
234 # and return the message value for x.
235 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
236 # If this is a system message, get the default text.
237 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
238 $wgMessageCache->loadAllMessages( $lang );
239 $text = wfMsgGetKey( $message, false, $lang, false );
241 if ( wfEmptyMsg( $message, $text ) )
242 $text = '';
243 } else {
244 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
246 wfProfileOut( __METHOD__ );
248 return $text;
249 } else {
250 $this->loadContent();
251 wfProfileOut( __METHOD__ );
253 return $this->mContent;
258 * Get the text of the current revision. No side-effects...
260 * @return Return the text of the current revision
262 public function getRawText() {
263 // Check process cache for current revision
264 if ( $this->mContentLoaded && $this->mOldId == 0 ) {
265 return $this->mContent;
268 $rev = Revision::newFromTitle( $this->mTitle );
269 $text = $rev ? $rev->getRawText() : false;
271 return $text;
275 * This function returns the text of a section, specified by a number ($section).
276 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
277 * the first section before any such heading (section 0).
279 * If a section contains subsections, these are also returned.
281 * @param $text String: text to look in
282 * @param $section Integer: section number
283 * @return string text of the requested section
284 * @deprecated
286 public function getSection( $text, $section ) {
287 global $wgParser;
289 return $wgParser->getSection( $text, $section );
293 * Get the text that needs to be saved in order to undo all revisions
294 * between $undo and $undoafter. Revisions must belong to the same page,
295 * must exist and must not be deleted
296 * @param $undo Revision
297 * @param $undoafter Revision Must be an earlier revision than $undo
298 * @return mixed string on success, false on failure
300 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
301 $undo_text = $undo->getText();
302 $undoafter_text = $undoafter->getText();
303 $cur_text = $this->getContent();
305 if ( $cur_text == $undo_text ) {
306 # No use doing a merge if it's just a straight revert.
307 return $undoafter_text;
310 $undone_text = '';
312 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
313 return false;
316 return $undone_text;
320 * @return int The oldid of the article that is to be shown, 0 for the
321 * current revision
323 public function getOldID() {
324 if ( is_null( $this->mOldId ) ) {
325 $this->mOldId = $this->getOldIDFromRequest();
328 return $this->mOldId;
332 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
334 * @return int The old id for the request
336 public function getOldIDFromRequest() {
337 global $wgRequest;
339 $this->mRedirectUrl = false;
341 $oldid = $wgRequest->getVal( 'oldid' );
343 if ( isset( $oldid ) ) {
344 $oldid = intval( $oldid );
345 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
346 $nextid = $this->mTitle->getNextRevisionID( $oldid );
347 if ( $nextid ) {
348 $oldid = $nextid;
349 } else {
350 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
352 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
353 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
354 if ( $previd ) {
355 $oldid = $previd;
360 if ( !$oldid ) {
361 $oldid = 0;
364 return $oldid;
368 * Load the revision (including text) into this object
370 function loadContent() {
371 if ( $this->mContentLoaded ) {
372 return;
375 wfProfileIn( __METHOD__ );
377 # Query variables :P
378 $oldid = $this->getOldID();
379 # Pre-fill content with error message so that if something
380 # fails we'll have something telling us what we intended.
381 $this->mOldId = $oldid;
382 $this->fetchContent( $oldid );
384 wfProfileOut( __METHOD__ );
388 * Fetch a page record with the given conditions
389 * @param $dbr Database object
390 * @param $conditions Array
391 * @return mixed Database result resource, or false on failure
393 protected function pageData( $dbr, $conditions ) {
394 $fields = array(
395 'page_id',
396 'page_namespace',
397 'page_title',
398 'page_restrictions',
399 'page_counter',
400 'page_is_redirect',
401 'page_is_new',
402 'page_random',
403 'page_touched',
404 'page_latest',
405 'page_len',
408 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
410 $row = $dbr->selectRow(
411 'page',
412 $fields,
413 $conditions,
414 __METHOD__
417 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
419 return $row ;
423 * Fetch a page record matching the Title object's namespace and title
424 * using a sanitized title string
426 * @param $dbr Database object
427 * @param $title Title object
428 * @return mixed Database result resource, or false on failure
430 public function pageDataFromTitle( $dbr, $title ) {
431 return $this->pageData( $dbr, array(
432 'page_namespace' => $title->getNamespace(),
433 'page_title' => $title->getDBkey() ) );
437 * Fetch a page record matching the requested ID
439 * @param $dbr Database
440 * @param $id Integer
442 protected function pageDataFromId( $dbr, $id ) {
443 return $this->pageData( $dbr, array( 'page_id' => $id ) );
447 * Set the general counter, title etc data loaded from
448 * some source.
450 * @param $data Database row object or "fromdb"
452 public function loadPageData( $data = 'fromdb' ) {
453 if ( $data === 'fromdb' ) {
454 $dbr = wfGetDB( DB_MASTER );
455 $data = $this->pageDataFromId( $dbr, $this->getId() );
458 $lc = LinkCache::singleton();
460 if ( $data ) {
461 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
463 $this->mTitle->mArticleID = intval( $data->page_id );
465 # Old-fashioned restrictions
466 $this->mTitle->loadRestrictions( $data->page_restrictions );
468 $this->mCounter = intval( $data->page_counter );
469 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
470 $this->mIsRedirect = intval( $data->page_is_redirect );
471 $this->mLatest = intval( $data->page_latest );
472 } else {
473 if ( is_object( $this->mTitle ) ) {
474 $lc->addBadLinkObj( $this->mTitle );
476 $this->mTitle->mArticleID = 0;
479 $this->mDataLoaded = true;
483 * Get text of an article from database
484 * Does *NOT* follow redirects.
486 * @param $oldid Int: 0 for whatever the latest revision is
487 * @return mixed string containing article contents, or false if null
489 function fetchContent( $oldid = 0 ) {
490 if ( $this->mContentLoaded ) {
491 return $this->mContent;
494 $dbr = wfGetDB( DB_MASTER );
496 # Pre-fill content with error message so that if something
497 # fails we'll have something telling us what we intended.
498 $t = $this->mTitle->getPrefixedText();
499 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
500 $this->mContent = wfMsgNoTrans( 'missing-article', $t, $d ) ;
502 if ( $oldid ) {
503 $revision = Revision::newFromId( $oldid );
504 if ( is_null( $revision ) ) {
505 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
506 return false;
509 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
511 if ( !$data ) {
512 wfDebug( __METHOD__ . " failed to get page data linked to revision id $oldid\n" );
513 return false;
516 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
517 $this->loadPageData( $data );
518 } else {
519 if ( !$this->mDataLoaded ) {
520 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
522 if ( !$data ) {
523 wfDebug( __METHOD__ . " failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
524 return false;
527 $this->loadPageData( $data );
529 $revision = Revision::newFromId( $this->mLatest );
530 if ( is_null( $revision ) ) {
531 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id {$this->mLatest}\n" );
532 return false;
536 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
537 // We should instead work with the Revision object when we need it...
538 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
540 $this->mUser = $revision->getUser();
541 $this->mUserText = $revision->getUserText();
542 $this->mComment = $revision->getComment();
543 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
545 $this->mRevIdFetched = $revision->getId();
546 $this->mContentLoaded = true;
547 $this->mRevision =& $revision;
549 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
551 return $this->mContent;
555 * Read/write accessor to select FOR UPDATE
557 * @param $x Mixed: FIXME
558 * @return mixed value of $x, or value stored in Article::mForUpdate
560 public function forUpdate( $x = null ) {
561 return wfSetVar( $this->mForUpdate, $x );
565 * Get the database which should be used for reads
567 * @return Database
568 * @deprecated - just call wfGetDB( DB_MASTER ) instead
570 function getDB() {
571 wfDeprecated( __METHOD__ );
572 return wfGetDB( DB_MASTER );
576 * Get options for all SELECT statements
578 * @param $options Array: an optional options array which'll be appended to
579 * the default
580 * @return Array: options
582 protected function getSelectOptions( $options = '' ) {
583 if ( $this->mForUpdate ) {
584 if ( is_array( $options ) ) {
585 $options[] = 'FOR UPDATE';
586 } else {
587 $options = 'FOR UPDATE';
591 return $options;
595 * @return int Page ID
597 public function getID() {
598 if ( $this->mTitle ) {
599 return $this->mTitle->getArticleID();
600 } else {
601 return 0;
606 * @return bool Whether or not the page exists in the database
608 public function exists() {
609 return $this->getId() > 0;
613 * Check if this page is something we're going to be showing
614 * some sort of sensible content for. If we return false, page
615 * views (plain action=view) will return an HTTP 404 response,
616 * so spiders and robots can know they're following a bad link.
618 * @return bool
620 public function hasViewableContent() {
621 return $this->exists() || $this->mTitle->isAlwaysKnown();
625 * @return int The view count for the page
627 public function getCount() {
628 if ( -1 == $this->mCounter ) {
629 $id = $this->getID();
631 if ( $id == 0 ) {
632 $this->mCounter = 0;
633 } else {
634 $dbr = wfGetDB( DB_SLAVE );
635 $this->mCounter = $dbr->selectField( 'page',
636 'page_counter',
637 array( 'page_id' => $id ),
638 __METHOD__,
639 $this->getSelectOptions()
644 return $this->mCounter;
648 * Determine whether a page would be suitable for being counted as an
649 * article in the site_stats table based on the title & its content
651 * @param $text String: text to analyze
652 * @return bool
654 public function isCountable( $text ) {
655 global $wgUseCommaCount;
657 $token = $wgUseCommaCount ? ',' : '[[';
659 return $this->mTitle->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
663 * Tests if the article text represents a redirect
665 * @param $text mixed string containing article contents, or boolean
666 * @return bool
668 public function isRedirect( $text = false ) {
669 if ( $text === false ) {
670 if ( $this->mDataLoaded ) {
671 return $this->mIsRedirect;
674 // Apparently loadPageData was never called
675 $this->loadContent();
676 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
677 } else {
678 $titleObj = Title::newFromRedirect( $text );
681 return $titleObj !== null;
685 * Returns true if the currently-referenced revision is the current edit
686 * to this page (and it exists).
687 * @return bool
689 public function isCurrent() {
690 # If no oldid, this is the current version.
691 if ( $this->getOldID() == 0 ) {
692 return true;
695 return $this->exists() && isset( $this->mRevision ) && $this->mRevision->isCurrent();
699 * Loads everything except the text
700 * This isn't necessary for all uses, so it's only done if needed.
702 protected function loadLastEdit() {
703 if ( -1 != $this->mUser ) {
704 return;
707 # New or non-existent articles have no user information
708 $id = $this->getID();
709 if ( 0 == $id ) {
710 return;
713 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
714 if ( !is_null( $this->mLastRevision ) ) {
715 $this->mUser = $this->mLastRevision->getUser();
716 $this->mUserText = $this->mLastRevision->getUserText();
717 $this->mTimestamp = $this->mLastRevision->getTimestamp();
718 $this->mComment = $this->mLastRevision->getComment();
719 $this->mMinorEdit = $this->mLastRevision->isMinor();
720 $this->mRevIdFetched = $this->mLastRevision->getId();
725 * @return string GMT timestamp of last article revision
728 public function getTimestamp() {
729 // Check if the field has been filled by ParserCache::get()
730 if ( !$this->mTimestamp ) {
731 $this->loadLastEdit();
734 return wfTimestamp( TS_MW, $this->mTimestamp );
738 * @return int user ID for the user that made the last article revision
740 public function getUser() {
741 $this->loadLastEdit();
743 return $this->mUser;
747 * @return string username of the user that made the last article revision
749 public function getUserText() {
750 $this->loadLastEdit();
752 return $this->mUserText;
756 * @return string Comment stored for the last article revision
758 public function getComment() {
759 $this->loadLastEdit();
761 return $this->mComment;
765 * Returns true if last revision was marked as "minor edit"
767 * @return boolean Minor edit indicator for the last article revision.
769 public function getMinorEdit() {
770 $this->loadLastEdit();
772 return $this->mMinorEdit;
776 * Use this to fetch the rev ID used on page views
778 * @return int revision ID of last article revision
780 public function getRevIdFetched() {
781 $this->loadLastEdit();
783 return $this->mRevIdFetched;
787 * @param $limit Integer: default 0.
788 * @param $offset Integer: default 0.
789 * @return UserArrayFromResult object with User objects of article contributors for requested range
791 public function getContributors( $limit = 0, $offset = 0 ) {
792 # FIXME: this is expensive; cache this info somewhere.
794 $dbr = wfGetDB( DB_SLAVE );
795 $revTable = $dbr->tableName( 'revision' );
796 $userTable = $dbr->tableName( 'user' );
798 $pageId = $this->getId();
800 $user = $this->getUser();
802 if ( $user ) {
803 $excludeCond = "AND rev_user != $user";
804 } else {
805 $userText = $dbr->addQuotes( $this->getUserText() );
806 $excludeCond = "AND rev_user_text != $userText";
809 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ); // username hidden?
811 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
812 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
813 WHERE rev_page = $pageId
814 $excludeCond
815 AND $deletedBit = 0
816 GROUP BY rev_user, rev_user_text
817 ORDER BY timestamp DESC";
819 if ( $limit > 0 ) {
820 $sql = $dbr->limitResult( $sql, $limit, $offset );
823 $sql .= ' ' . $this->getSelectOptions();
824 $res = $dbr->query( $sql, __METHOD__ );
826 return new UserArrayFromResult( $res );
830 * This is the default action of the index.php entry point: just view the
831 * page of the given title.
833 public function view() {
834 global $wgUser, $wgOut, $wgRequest, $wgContLang;
835 global $wgEnableParserCache, $wgStylePath, $wgParser;
836 global $wgUseTrackbacks, $wgUseFileCache;
838 wfProfileIn( __METHOD__ );
840 # Get variables from query string
841 $oldid = $this->getOldID();
842 $parserCache = ParserCache::singleton();
844 $parserOptions = clone $this->getParserOptions();
845 # Render printable version, use printable version cache
846 if ( $wgOut->isPrintable() ) {
847 $parserOptions->setIsPrintable( true );
850 # Try client and file cache
851 if ( $oldid === 0 && $this->checkTouched() ) {
852 global $wgUseETag;
854 if ( $wgUseETag ) {
855 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
858 # Is is client cached?
859 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
860 wfDebug( __METHOD__ . ": done 304\n" );
861 wfProfileOut( __METHOD__ );
863 return;
864 # Try file cache
865 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
866 wfDebug( __METHOD__ . ": done file cache\n" );
867 # tell wgOut that output is taken care of
868 $wgOut->disable();
869 $this->viewUpdates();
870 wfProfileOut( __METHOD__ );
872 return;
876 # getOldID may want us to redirect somewhere else
877 if ( $this->mRedirectUrl ) {
878 $wgOut->redirect( $this->mRedirectUrl );
879 wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
880 wfProfileOut( __METHOD__ );
882 return;
885 $wgOut->setArticleFlag( true );
886 # Set page title (may be overridden by DISPLAYTITLE)
887 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
889 # If we got diff in the query, we want to see a diff page instead of the article.
890 if ( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
891 wfDebug( __METHOD__ . ": showing diff page\n" );
892 $this->showDiffPage();
893 wfProfileOut( __METHOD__ );
895 return;
898 # Should the parser cache be used?
899 $useParserCache = $this->useParserCache( $oldid );
900 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
901 if ( $wgUser->getOption( 'stubthreshold' ) ) {
902 wfIncrStats( 'pcache_miss_stub' );
905 $wasRedirected = $this->showRedirectedFromHeader();
906 $this->showNamespaceHeader();
908 # Iterate through the possible ways of constructing the output text.
909 # Keep going until $outputDone is set, or we run out of things to do.
910 $pass = 0;
911 $outputDone = false;
912 $this->mParserOutput = false;
914 while ( !$outputDone && ++$pass ) {
915 switch( $pass ) {
916 case 1:
917 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
918 break;
919 case 2:
920 # Try the parser cache
921 if ( $useParserCache ) {
922 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
924 if ( $this->mParserOutput !== false ) {
925 wfDebug( __METHOD__ . ": showing parser cache contents\n" );
926 $wgOut->addParserOutput( $this->mParserOutput );
927 # Ensure that UI elements requiring revision ID have
928 # the correct version information.
929 $wgOut->setRevisionId( $this->mLatest );
930 $outputDone = true;
933 break;
934 case 3:
935 $text = $this->getContent();
936 if ( $text === false || $this->getID() == 0 ) {
937 wfDebug( __METHOD__ . ": showing missing article\n" );
938 $this->showMissingArticle();
939 wfProfileOut( __METHOD__ );
940 return;
943 # Another whitelist check in case oldid is altering the title
944 if ( !$this->mTitle->userCanRead() ) {
945 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
946 $wgOut->loginToUse();
947 $wgOut->output();
948 $wgOut->disable();
949 wfProfileOut( __METHOD__ );
950 return;
953 # Are we looking at an old revision
954 if ( $oldid && !is_null( $this->mRevision ) ) {
955 $this->setOldSubtitle( $oldid );
957 if ( !$this->showDeletedRevisionHeader() ) {
958 wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
959 wfProfileOut( __METHOD__ );
960 return;
963 # If this "old" version is the current, then try the parser cache...
964 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
965 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
966 if ( $this->mParserOutput ) {
967 wfDebug( __METHOD__ . ": showing parser cache for current rev permalink\n" );
968 $wgOut->addParserOutput( $this->mParserOutput );
969 $wgOut->setRevisionId( $this->mLatest );
970 $this->showViewFooter();
971 $this->viewUpdates();
972 wfProfileOut( __METHOD__ );
973 return;
978 # Ensure that UI elements requiring revision ID have
979 # the correct version information.
980 $wgOut->setRevisionId( $this->getRevIdFetched() );
982 # Pages containing custom CSS or JavaScript get special treatment
983 if ( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
984 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
985 $this->showCssOrJsPage();
986 $outputDone = true;
987 } else if ( $rt = Title::newFromRedirectArray( $text ) ) {
988 wfDebug( __METHOD__ . ": showing redirect=no page\n" );
989 # Viewing a redirect page (e.g. with parameter redirect=no)
990 # Don't append the subtitle if this was an old revision
991 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
992 # Parse just to get categories, displaytitle, etc.
993 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
994 $wgOut->addParserOutputNoText( $this->mParserOutput );
995 $outputDone = true;
997 break;
998 case 4:
999 # Run the parse, protected by a pool counter
1000 wfDebug( __METHOD__ . ": doing uncached parse\n" );
1001 $key = $parserCache->getKey( $this, $parserOptions );
1002 $poolCounter = PoolCounter::factory( 'Article::view', $key );
1003 $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
1004 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
1006 if ( !$status->isOK() ) {
1007 # Connection or timeout error
1008 $this->showPoolError( $status );
1009 wfProfileOut( __METHOD__ );
1010 return;
1011 } else {
1012 $outputDone = true;
1014 break;
1015 # Should be unreachable, but just in case...
1016 default:
1017 break 2;
1021 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
1022 if ( $this->mParserOutput ) {
1023 $titleText = $this->mParserOutput->getTitleText();
1025 if ( strval( $titleText ) !== '' ) {
1026 $wgOut->setPageTitle( $titleText );
1030 # For the main page, overwrite the <title> element with the con-
1031 # tents of 'pagetitle-view-mainpage' instead of the default (if
1032 # that's not empty).
1033 if ( $this->mTitle->equals( Title::newMainPage() )
1034 && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
1036 $wgOut->setHTMLTitle( $m );
1039 # Now that we've filled $this->mParserOutput, we know whether
1040 # there are any __NOINDEX__ tags on the page
1041 $policy = $this->getRobotPolicy( 'view' );
1042 $wgOut->setIndexPolicy( $policy['index'] );
1043 $wgOut->setFollowPolicy( $policy['follow'] );
1045 $this->showViewFooter();
1046 $this->viewUpdates();
1047 wfProfileOut( __METHOD__ );
1051 * Show a diff page according to current request variables. For use within
1052 * Article::view() only, other callers should use the DifferenceEngine class.
1054 public function showDiffPage() {
1055 global $wgOut, $wgRequest, $wgUser;
1057 $diff = $wgRequest->getVal( 'diff' );
1058 $rcid = $wgRequest->getVal( 'rcid' );
1059 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
1060 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1061 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1062 $oldid = $this->getOldID();
1064 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $unhide );
1065 // DifferenceEngine directly fetched the revision:
1066 $this->mRevIdFetched = $de->mNewid;
1067 $de->showDiffPage( $diffOnly );
1069 // Needed to get the page's current revision
1070 $this->loadPageData();
1071 if ( $diff == 0 || $diff == $this->mLatest ) {
1072 # Run view updates for current revision only
1073 $this->viewUpdates();
1078 * Show a page view for a page formatted as CSS or JavaScript. To be called by
1079 * Article::view() only.
1081 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
1082 * page views.
1084 public function showCssOrJsPage() {
1085 global $wgOut;
1087 $wgOut->wrapWikiMsg( "<div class='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
1089 // Give hooks a chance to customise the output
1090 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
1091 // Wrap the whole lot in a <pre> and don't parse
1092 $m = array();
1093 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
1094 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
1095 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
1096 $wgOut->addHTML( "\n</pre>\n" );
1101 * Get the robot policy to be used for the current action=view request.
1102 * @return String the policy that should be set
1103 * @deprecated use getRobotPolicy() instead, which returns an associative
1104 * array
1106 public function getRobotPolicyForView() {
1107 wfDeprecated( __METHOD__ );
1108 $policy = $this->getRobotPolicy( 'view' );
1110 return $policy['index'] . ',' . $policy['follow'];
1114 * Get the robot policy to be used for the current view
1115 * @param $action String the action= GET parameter
1116 * @return Array the policy that should be set
1117 * TODO: actions other than 'view'
1119 public function getRobotPolicy( $action ) {
1120 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1121 global $wgDefaultRobotPolicy, $wgRequest;
1123 $ns = $this->mTitle->getNamespace();
1125 if ( $ns == NS_USER || $ns == NS_USER_TALK ) {
1126 # Don't index user and user talk pages for blocked users (bug 11443)
1127 if ( !$this->mTitle->isSubpage() ) {
1128 $block = new Block();
1129 if ( $block->load( $this->mTitle->getText() ) ) {
1130 return array(
1131 'index' => 'noindex',
1132 'follow' => 'nofollow'
1138 if ( $this->getID() === 0 || $this->getOldID() ) {
1139 # Non-articles (special pages etc), and old revisions
1140 return array(
1141 'index' => 'noindex',
1142 'follow' => 'nofollow'
1144 } elseif ( $wgOut->isPrintable() ) {
1145 # Discourage indexing of printable versions, but encourage following
1146 return array(
1147 'index' => 'noindex',
1148 'follow' => 'follow'
1150 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1151 # For ?curid=x urls, disallow indexing
1152 return array(
1153 'index' => 'noindex',
1154 'follow' => 'follow'
1158 # Otherwise, construct the policy based on the various config variables.
1159 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
1161 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1162 # Honour customised robot policies for this namespace
1163 $policy = array_merge(
1164 $policy,
1165 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
1168 if ( $this->mTitle->canUseNoindex() && is_object( $this->mParserOutput ) && $this->mParserOutput->getIndexPolicy() ) {
1169 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1170 # a final sanity check that we have really got the parser output.
1171 $policy = array_merge(
1172 $policy,
1173 array( 'index' => $this->mParserOutput->getIndexPolicy() )
1177 if ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
1178 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1179 $policy = array_merge(
1180 $policy,
1181 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] )
1185 return $policy;
1189 * Converts a String robot policy into an associative array, to allow
1190 * merging of several policies using array_merge().
1191 * @param $policy Mixed, returns empty array on null/false/'', transparent
1192 * to already-converted arrays, converts String.
1193 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1195 public static function formatRobotPolicy( $policy ) {
1196 if ( is_array( $policy ) ) {
1197 return $policy;
1198 } elseif ( !$policy ) {
1199 return array();
1202 $policy = explode( ',', $policy );
1203 $policy = array_map( 'trim', $policy );
1205 $arr = array();
1206 foreach ( $policy as $var ) {
1207 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1208 $arr['index'] = $var;
1209 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1210 $arr['follow'] = $var;
1214 return $arr;
1218 * If this request is a redirect view, send "redirected from" subtitle to
1219 * $wgOut. Returns true if the header was needed, false if this is not a
1220 * redirect view. Handles both local and remote redirects.
1222 * @return boolean
1224 public function showRedirectedFromHeader() {
1225 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1227 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1228 $sk = $wgUser->getSkin();
1230 if ( isset( $this->mRedirectedFrom ) ) {
1231 // This is an internally redirected page view.
1232 // We'll need a backlink to the source page for navigation.
1233 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1234 $redir = $sk->link(
1235 $this->mRedirectedFrom,
1236 null,
1237 array(),
1238 array( 'redirect' => 'no' ),
1239 array( 'known', 'noclasses' )
1242 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1243 $wgOut->setSubtitle( $s );
1245 // Set the fragment if one was specified in the redirect
1246 if ( strval( $this->mTitle->getFragment() ) != '' ) {
1247 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1248 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1251 // Add a <link rel="canonical"> tag
1252 $wgOut->addLink( array( 'rel' => 'canonical',
1253 'href' => $this->mTitle->getLocalURL() )
1256 return true;
1258 } elseif ( $rdfrom ) {
1259 // This is an externally redirected view, from some other wiki.
1260 // If it was reported from a trusted site, supply a backlink.
1261 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1262 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1263 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1264 $wgOut->setSubtitle( $s );
1266 return true;
1270 return false;
1274 * Show a header specific to the namespace currently being viewed, like
1275 * [[MediaWiki:Talkpagetext]]. For Article::view().
1277 public function showNamespaceHeader() {
1278 global $wgOut;
1280 if ( $this->mTitle->isTalkPage() ) {
1281 $msg = wfMsgNoTrans( 'talkpageheader' );
1282 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1283 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
1289 * Show the footer section of an ordinary page view
1291 public function showViewFooter() {
1292 global $wgOut, $wgUseTrackbacks, $wgRequest;
1294 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1295 if ( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1296 $wgOut->addWikiMsg( 'anontalkpagetext' );
1299 # If we have been passed an &rcid= parameter, we want to give the user a
1300 # chance to mark this new article as patrolled.
1301 $this->showPatrolFooter();
1303 # Trackbacks
1304 if ( $wgUseTrackbacks ) {
1305 $this->addTrackbacks();
1310 * If patrol is possible, output a patrol UI box. This is called from the
1311 * footer section of ordinary page views. If patrol is not possible or not
1312 * desired, does nothing.
1314 public function showPatrolFooter() {
1315 global $wgOut, $wgRequest, $wgUser;
1317 $rcid = $wgRequest->getVal( 'rcid' );
1319 if ( !$rcid || !$this->mTitle->exists() || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1320 return;
1323 $sk = $wgUser->getSkin();
1325 $wgOut->addHTML(
1326 "<div class='patrollink'>" .
1327 wfMsgHtml(
1328 'markaspatrolledlink',
1329 $sk->link(
1330 $this->mTitle,
1331 wfMsgHtml( 'markaspatrolledtext' ),
1332 array(),
1333 array(
1334 'action' => 'markpatrolled',
1335 'rcid' => $rcid
1337 array( 'known', 'noclasses' )
1340 '</div>'
1345 * Show the error text for a missing article. For articles in the MediaWiki
1346 * namespace, show the default message text. To be called from Article::view().
1348 public function showMissingArticle() {
1349 global $wgOut, $wgRequest, $wgUser;
1351 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1352 if ( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
1353 $parts = explode( '/', $this->mTitle->getText() );
1354 $rootPart = $parts[0];
1355 $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1356 $ip = User::isIP( $rootPart );
1358 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1359 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1360 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1361 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1362 LogEventsList::showLogExtract(
1363 $wgOut,
1364 'block',
1365 $user->getUserPage()->getPrefixedText(),
1367 array(
1368 'lim' => 1,
1369 'showIfEmpty' => false,
1370 'msgKey' => array(
1371 'blocked-notice-logextract',
1372 $user->getName() # Support GENDER in notice
1379 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1381 # Show delete and move logs
1382 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle->getPrefixedText(), '',
1383 array( 'lim' => 10,
1384 'conds' => array( "log_action != 'revision'" ),
1385 'showIfEmpty' => false,
1386 'msgKey' => array( 'moveddeleted-notice' ) )
1389 # Show error message
1390 $oldid = $this->getOldID();
1391 if ( $oldid ) {
1392 $text = wfMsgNoTrans( 'missing-article',
1393 $this->mTitle->getPrefixedText(),
1394 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1395 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1396 // Use the default message text
1397 $text = $this->getContent();
1398 } else {
1399 $createErrors = $this->mTitle->getUserPermissionsErrors( 'create', $wgUser );
1400 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
1401 $errors = array_merge( $createErrors, $editErrors );
1403 if ( !count( $errors ) ) {
1404 $text = wfMsgNoTrans( 'noarticletext' );
1405 } else {
1406 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1409 $text = "<div class='noarticletext'>\n$text\n</div>";
1411 if ( !$this->hasViewableContent() ) {
1412 // If there's no backing content, send a 404 Not Found
1413 // for better machine handling of broken links.
1414 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1417 $wgOut->addWikiText( $text );
1421 * If the revision requested for view is deleted, check permissions.
1422 * Send either an error message or a warning header to $wgOut.
1424 * @return boolean true if the view is allowed, false if not.
1426 public function showDeletedRevisionHeader() {
1427 global $wgOut, $wgRequest;
1429 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1430 // Not deleted
1431 return true;
1434 // If the user is not allowed to see it...
1435 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1436 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1437 'rev-deleted-text-permission' );
1439 return false;
1440 // If the user needs to confirm that they want to see it...
1441 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1442 # Give explanation and add a link to view the revision...
1443 $oldid = intval( $this->getOldID() );
1444 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1445 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1446 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1447 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1448 array( $msg, $link ) );
1450 return false;
1451 // We are allowed to see...
1452 } else {
1453 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1454 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1455 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1457 return true;
1462 * Should the parser cache be used?
1464 * @return boolean
1466 public function useParserCache( $oldid ) {
1467 global $wgUser, $wgEnableParserCache;
1469 return $wgEnableParserCache
1470 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1471 && $this->exists()
1472 && empty( $oldid )
1473 && !$this->mTitle->isCssOrJsPage()
1474 && !$this->mTitle->isCssJsSubpage();
1478 * Execute the uncached parse for action=view
1480 public function doViewParse() {
1481 global $wgOut;
1483 $oldid = $this->getOldID();
1484 $useParserCache = $this->useParserCache( $oldid );
1485 $parserOptions = clone $this->getParserOptions();
1487 # Render printable version, use printable version cache
1488 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1490 # Don't show section-edit links on old revisions... this way lies madness.
1491 $parserOptions->setEditSection( $this->isCurrent() );
1492 $useParserCache = $this->useParserCache( $oldid );
1493 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1497 * Try to fetch an expired entry from the parser cache. If it is present,
1498 * output it and return true. If it is not present, output nothing and
1499 * return false. This is used as a callback function for
1500 * PoolCounter::executeProtected().
1502 * @return boolean
1504 public function tryDirtyCache() {
1506 global $wgOut;
1507 $parserCache = ParserCache::singleton();
1508 $options = $this->getParserOptions();
1509 $options->setIsPrintable( $wgOut->isPrintable() );
1510 $output = $parserCache->getDirty( $this, $options );
1512 if ( $output ) {
1513 wfDebug( __METHOD__ . ": sending dirty output\n" );
1514 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1515 $wgOut->setSquidMaxage( 0 );
1516 $this->mParserOutput = $output;
1517 $wgOut->addParserOutput( $output );
1518 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1520 return true;
1521 } else {
1522 wfDebugLog( 'dirty', "dirty missing\n" );
1523 wfDebug( __METHOD__ . ": no dirty cache\n" );
1525 return false;
1530 * Show an error page for an error from the pool counter.
1531 * @param $status Status
1533 public function showPoolError( $status ) {
1534 global $wgOut;
1536 $wgOut->clearHTML(); // for release() errors
1537 $wgOut->enableClientCache( false );
1538 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1539 $wgOut->addWikiText(
1540 '<div class="errorbox">' .
1541 $status->getWikiText( false, 'view-pool-error' ) .
1542 '</div>'
1547 * View redirect
1549 * @param $target Title object or Array of destination(s) to redirect
1550 * @param $appendSubtitle Boolean [optional]
1551 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1552 * @return string containing HMTL with redirect link
1554 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1555 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1557 # Display redirect
1558 if ( !is_array( $target ) ) {
1559 $target = array( $target );
1562 $imageDir = $wgContLang->getDir();
1563 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1564 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1565 $alt2 = $wgContLang->isRTL() ? '←' : '→'; // should -> and <- be used instead of Unicode?
1567 if ( $appendSubtitle ) {
1568 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1571 $sk = $wgUser->getSkin();
1572 // the loop prepends the arrow image before the link, so the first case needs to be outside
1573 $title = array_shift( $target );
1575 if ( $forceKnown ) {
1576 $link = $sk->link(
1577 $title,
1578 htmlspecialchars( $title->getFullText() ),
1579 array(),
1580 array(),
1581 array( 'known', 'noclasses' )
1583 } else {
1584 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1587 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1588 foreach ( $target as $rt ) {
1589 if ( $forceKnown ) {
1590 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1591 . $sk->link(
1592 $rt,
1593 htmlspecialchars( $rt->getFullText() ),
1594 array(),
1595 array(),
1596 array( 'known', 'noclasses' )
1598 } else {
1599 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1600 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1604 return '<img src="' . $imageUrl . '" alt="#REDIRECT " />' .
1605 '<span class="redirectText">' . $link . '</span>';
1609 * Builds trackback links for article display if $wgUseTrackbacks is set to true
1611 public function addTrackbacks() {
1612 global $wgOut, $wgUser;
1614 $dbr = wfGetDB( DB_SLAVE );
1615 $tbs = $dbr->select( 'trackbacks',
1616 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1617 array( 'tb_page' => $this->getID() )
1620 if ( !$dbr->numRows( $tbs ) ) {
1621 return;
1624 $tbtext = "";
1625 while ( $o = $dbr->fetchObject( $tbs ) ) {
1626 $rmvtxt = "";
1628 if ( $wgUser->isAllowed( 'trackback' ) ) {
1629 $delurl = $this->mTitle->getFullURL( "action=deletetrackback&tbid=" .
1630 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1631 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1634 $tbtext .= "\n";
1635 $tbtext .= wfMsg( strlen( $o->tb_ex ) ? 'trackbackexcerpt' : 'trackback',
1636 $o->tb_title,
1637 $o->tb_url,
1638 $o->tb_ex,
1639 $o->tb_name,
1640 $rmvtxt );
1643 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>\n$1\n</div>\n", array( 'trackbackbox', $tbtext ) );
1647 * Removes trackback record for current article from trackbacks table
1649 public function deletetrackback() {
1650 global $wgUser, $wgRequest, $wgOut;
1652 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1653 $wgOut->addWikiMsg( 'sessionfailure' );
1655 return;
1658 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1660 if ( count( $permission_errors ) ) {
1661 $wgOut->showPermissionsErrorPage( $permission_errors );
1663 return;
1666 $db = wfGetDB( DB_MASTER );
1667 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1669 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1670 $this->mTitle->invalidateCache();
1674 * Handle action=render
1677 public function render() {
1678 global $wgOut;
1680 $wgOut->setArticleBodyOnly( true );
1681 $this->view();
1685 * Handle action=purge
1687 public function purge() {
1688 global $wgUser, $wgRequest, $wgOut;
1690 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1691 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1692 $this->doPurge();
1693 $this->view();
1695 } else {
1696 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1697 $button = wfMsgExt( 'confirm_purge_button', array( 'escapenoentities' ) );
1698 $form = "<form method=\"post\" action=\"$action\">\n" .
1699 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1700 "</form>\n";
1701 $top = wfMsgExt( 'confirm-purge-top', array( 'parse' ) );
1702 $bottom = wfMsgExt( 'confirm-purge-bottom', array( 'parse' ) );
1703 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1704 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1705 $wgOut->addHTML( $top . $form . $bottom );
1710 * Perform the actions of a page purging
1712 public function doPurge() {
1713 global $wgUseSquid;
1715 // Invalidate the cache
1716 $this->mTitle->invalidateCache();
1718 if ( $wgUseSquid ) {
1719 // Commit the transaction before the purge is sent
1720 $dbw = wfGetDB( DB_MASTER );
1721 $dbw->commit();
1723 // Send purge
1724 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1725 $update->doUpdate();
1728 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1729 global $wgMessageCache;
1731 if ( $this->getID() == 0 ) {
1732 $text = false;
1733 } else {
1734 $text = $this->getRawText();
1737 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1742 * Insert a new empty page record for this article.
1743 * This *must* be followed up by creating a revision
1744 * and running $this->updateRevisionOn( ... );
1745 * or else the record will be left in a funky state.
1746 * Best if all done inside a transaction.
1748 * @param $dbw Database
1749 * @return int The newly created page_id key, or false if the title already existed
1750 * @private
1752 public function insertOn( $dbw ) {
1753 wfProfileIn( __METHOD__ );
1755 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1756 $dbw->insert( 'page', array(
1757 'page_id' => $page_id,
1758 'page_namespace' => $this->mTitle->getNamespace(),
1759 'page_title' => $this->mTitle->getDBkey(),
1760 'page_counter' => 0,
1761 'page_restrictions' => '',
1762 'page_is_redirect' => 0, # Will set this shortly...
1763 'page_is_new' => 1,
1764 'page_random' => wfRandom(),
1765 'page_touched' => $dbw->timestamp(),
1766 'page_latest' => 0, # Fill this in shortly...
1767 'page_len' => 0, # Fill this in shortly...
1768 ), __METHOD__, 'IGNORE' );
1770 $affected = $dbw->affectedRows();
1772 if ( $affected ) {
1773 $newid = $dbw->insertId();
1774 $this->mTitle->resetArticleId( $newid );
1776 wfProfileOut( __METHOD__ );
1778 return $affected ? $newid : false;
1782 * Update the page record to point to a newly saved revision.
1784 * @param $dbw Database object
1785 * @param $revision Revision: For ID number, and text used to set
1786 length and redirect status fields
1787 * @param $lastRevision Integer: if given, will not overwrite the page field
1788 * when different from the currently set value.
1789 * Giving 0 indicates the new page flag should be set
1790 * on.
1791 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1792 * removing rows in redirect table.
1793 * @param $setNewFlag Boolean: Set to true if a page flag should be set
1794 * Needed when $lastRevision has to be set to sth. !=0
1795 * @return bool true on success, false on failure
1796 * @private
1798 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null, $setNewFlag = false ) {
1799 wfProfileIn( __METHOD__ );
1801 $text = $revision->getText();
1802 $rt = Title::newFromRedirect( $text );
1804 $conditions = array( 'page_id' => $this->getId() );
1806 if ( !is_null( $lastRevision ) ) {
1807 # An extra check against threads stepping on each other
1808 $conditions['page_latest'] = $lastRevision;
1811 if ( !$setNewFlag ) {
1812 $setNewFlag = ( $lastRevision === 0 );
1815 $dbw->update( 'page',
1816 array( /* SET */
1817 'page_latest' => $revision->getId(),
1818 'page_touched' => $dbw->timestamp(),
1819 'page_is_new' => $setNewFlag,
1820 'page_is_redirect' => $rt !== null ? 1 : 0,
1821 'page_len' => strlen( $text ),
1823 $conditions,
1824 __METHOD__ );
1826 $result = $dbw->affectedRows() != 0;
1827 if ( $result ) {
1828 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1831 wfProfileOut( __METHOD__ );
1832 return $result;
1836 * Add row to the redirect table if this is a redirect, remove otherwise.
1838 * @param $dbw Database
1839 * @param $redirectTitle a title object pointing to the redirect target,
1840 * or NULL if this is not a redirect
1841 * @param $lastRevIsRedirect If given, will optimize adding and
1842 * removing rows in redirect table.
1843 * @return bool true on success, false on failure
1844 * @private
1846 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1847 // Always update redirects (target link might have changed)
1848 // Update/Insert if we don't know if the last revision was a redirect or not
1849 // Delete if changing from redirect to non-redirect
1850 $isRedirect = !is_null( $redirectTitle );
1852 if ( $isRedirect || is_null( $lastRevIsRedirect ) || $lastRevIsRedirect !== $isRedirect ) {
1853 wfProfileIn( __METHOD__ );
1854 if ( $isRedirect ) {
1855 // This title is a redirect, Add/Update row in the redirect table
1856 $set = array( /* SET */
1857 'rd_namespace' => $redirectTitle->getNamespace(),
1858 'rd_title' => $redirectTitle->getDBkey(),
1859 'rd_from' => $this->getId(),
1861 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1862 } else {
1863 // This is not a redirect, remove row from redirect table
1864 $where = array( 'rd_from' => $this->getId() );
1865 $dbw->delete( 'redirect', $where, __METHOD__ );
1868 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1869 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1871 wfProfileOut( __METHOD__ );
1873 return ( $dbw->affectedRows() != 0 );
1876 return true;
1880 * If the given revision is newer than the currently set page_latest,
1881 * update the page record. Otherwise, do nothing.
1883 * @param $dbw Database object
1884 * @param $revision Revision object
1885 * @return mixed
1887 public function updateIfNewerOn( &$dbw, $revision ) {
1888 wfProfileIn( __METHOD__ );
1890 $row = $dbw->selectRow(
1891 array( 'revision', 'page' ),
1892 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1893 array(
1894 'page_id' => $this->getId(),
1895 'page_latest=rev_id' ),
1896 __METHOD__ );
1898 if ( $row ) {
1899 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1900 wfProfileOut( __METHOD__ );
1901 return false;
1903 $prev = $row->rev_id;
1904 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1905 } else {
1906 # No or missing previous revision; mark the page as new
1907 $prev = 0;
1908 $lastRevIsRedirect = null;
1911 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1913 wfProfileOut( __METHOD__ );
1914 return $ret;
1918 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1919 * @param $text String: new text of the section
1920 * @param $summary String: new section's subject, only if $section is 'new'
1921 * @param $edittime String: revision timestamp or null to use the current revision
1922 * @return string Complete article text, or null if error
1924 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1925 wfProfileIn( __METHOD__ );
1927 if ( strval( $section ) == '' ) {
1928 // Whole-page edit; let the whole text through
1929 } else {
1930 if ( is_null( $edittime ) ) {
1931 $rev = Revision::newFromTitle( $this->mTitle );
1932 } else {
1933 $dbw = wfGetDB( DB_MASTER );
1934 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1937 if ( !$rev ) {
1938 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1939 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1940 return null;
1943 $oldtext = $rev->getText();
1945 if ( $section == 'new' ) {
1946 # Inserting a new section
1947 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1948 $text = strlen( trim( $oldtext ) ) > 0
1949 ? "{$oldtext}\n\n{$subject}{$text}"
1950 : "{$subject}{$text}";
1951 } else {
1952 # Replacing an existing section; roll out the big guns
1953 global $wgParser;
1955 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1959 wfProfileOut( __METHOD__ );
1960 return $text;
1964 * This function is not deprecated until somebody fixes the core not to use
1965 * it. Nevertheless, use Article::doEdit() instead.
1967 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1968 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1969 ( $isminor ? EDIT_MINOR : 0 ) |
1970 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1971 ( $bot ? EDIT_FORCE_BOT : 0 );
1973 $this->doEdit( $text, $summary, $flags, false, null, $watchthis, $comment, '', true );
1977 * @deprecated use Article::doEdit()
1979 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1980 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1981 ( $minor ? EDIT_MINOR : 0 ) |
1982 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1984 $status = $this->doEdit( $text, $summary, $flags, false, null, $watchthis, false, $sectionanchor, true );
1986 if ( !$status->isOK() ) {
1987 return false;
1990 return true;
1994 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1995 * @param $flags Int
1996 * @return Int updated $flags
1998 function checkFlags( $flags ) {
1999 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
2000 if ( $this->mTitle->getArticleID() ) {
2001 $flags |= EDIT_UPDATE;
2002 } else {
2003 $flags |= EDIT_NEW;
2007 return $flags;
2011 * Article::doEdit()
2013 * Change an existing article or create a new article. Updates RC and all necessary caches,
2014 * optionally via the deferred update array.
2016 * $wgUser must be set before calling this function.
2018 * @param $text String: new text
2019 * @param $summary String: edit summary
2020 * @param $flags Integer bitfield:
2021 * EDIT_NEW
2022 * Article is known or assumed to be non-existent, create a new one
2023 * EDIT_UPDATE
2024 * Article is known or assumed to be pre-existing, update it
2025 * EDIT_MINOR
2026 * Mark this edit minor, if the user is allowed to do so
2027 * EDIT_SUPPRESS_RC
2028 * Do not log the change in recentchanges
2029 * EDIT_FORCE_BOT
2030 * Mark the edit a "bot" edit regardless of user rights
2031 * EDIT_DEFER_UPDATES
2032 * Defer some of the updates until the end of index.php
2033 * EDIT_AUTOSUMMARY
2034 * Fill in blank summaries with generated text where possible
2036 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
2037 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
2038 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
2039 * edit-already-exists error will be returned. These two conditions are also possible with
2040 * auto-detection due to MediaWiki's performance-optimised locking strategy.
2042 * @param $baseRevId the revision ID this edit was based off, if any
2043 * @param $user Optional user object, $wgUser will be used if not passed
2044 * @param $watchthis Watch the page if true, unwatch the page if false, do nothing if null
2045 * @param $sectionanchor The section anchor for the page; used for redirecting the user back to the page
2046 * after the edit is successfully committed
2047 * @param $redirect If true, redirect the user back to the page after the edit is successfully committed
2049 * @return Status object. Possible errors:
2050 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
2051 * edit-gone-missing: In update mode, but the article didn't exist
2052 * edit-conflict: In update mode, the article changed unexpectedly
2053 * edit-no-change: Warning that the text was the same as before
2054 * edit-already-exists: In creation mode, but the article already exists
2056 * Extensions may define additional errors.
2058 * $return->value will contain an associative array with members as follows:
2059 * new: Boolean indicating if the function attempted to create a new article
2060 * revision: The revision object for the inserted revision, or null
2062 * Compatibility note: this function previously returned a boolean value indicating success/failure
2064 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null , $watchthis = null,
2065 $comment = false, $sectionanchor = '', $redirect = false) {
2066 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
2068 # Low-level sanity check
2069 if ( $this->mTitle->getText() == '' ) {
2070 throw new MWException( 'Something is trying to edit an article with an empty title' );
2073 wfProfileIn( __METHOD__ );
2075 $user = is_null( $user ) ? $wgUser : $user;
2076 $status = Status::newGood( array() );
2078 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
2079 $this->loadPageData();
2081 $flags = $this->checkFlags( $flags );
2083 # If this is a comment, add the summary as headline
2084 if ( $comment && $summary != "" ) {
2085 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
2088 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
2089 $flags & EDIT_MINOR, &$watchthis, null, &$flags, &$status) ) )
2091 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
2092 wfProfileOut( __METHOD__ );
2094 if ( $status->isOK() ) {
2095 $status->fatal( 'edit-hook-aborted' );
2098 return $status;
2101 # Silently ignore EDIT_MINOR if not allowed
2102 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
2103 $bot = $flags & EDIT_FORCE_BOT;
2105 $oldtext = $this->getRawText(); // current revision
2106 $oldsize = strlen( $oldtext );
2108 # Provide autosummaries if one is not provided and autosummaries are enabled.
2109 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
2110 $summary = $this->getAutosummary( $oldtext, $text, $flags );
2113 $editInfo = $this->prepareTextForEdit( $text );
2114 $text = $editInfo->pst;
2115 $newsize = strlen( $text );
2117 $dbw = wfGetDB( DB_MASTER );
2118 $now = wfTimestampNow();
2119 $this->mTimestamp = $now;
2121 if ( $flags & EDIT_UPDATE ) {
2122 # Update article, but only if changed.
2123 $status->value['new'] = false;
2125 # Make sure the revision is either completely inserted or not inserted at all
2126 if ( !$wgDBtransactions ) {
2127 $userAbort = ignore_user_abort( true );
2130 $revisionId = 0;
2132 $changed = ( strcmp( $text, $oldtext ) != 0 );
2134 if ( $changed ) {
2135 $this->mGoodAdjustment = (int)$this->isCountable( $text )
2136 - (int)$this->isCountable( $oldtext );
2137 $this->mTotalAdjustment = 0;
2139 if ( !$this->mLatest ) {
2140 # Article gone missing
2141 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
2142 $status->fatal( 'edit-gone-missing' );
2144 wfProfileOut( __METHOD__ );
2145 return $status;
2148 $revision = new Revision( array(
2149 'page' => $this->getId(),
2150 'comment' => $summary,
2151 'minor_edit' => $isminor,
2152 'text' => $text,
2153 'parent_id' => $this->mLatest,
2154 'user' => $user->getId(),
2155 'user_text' => $user->getName(),
2156 ) );
2158 $dbw->begin();
2159 $revisionId = $revision->insertOn( $dbw );
2161 # Update page
2163 # Note that we use $this->mLatest instead of fetching a value from the master DB
2164 # during the course of this function. This makes sure that EditPage can detect
2165 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
2166 # before this function is called. A previous function used a separate query, this
2167 # creates a window where concurrent edits can cause an ignored edit conflict.
2168 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
2170 if ( !$ok ) {
2171 /* Belated edit conflict! Run away!! */
2172 $status->fatal( 'edit-conflict' );
2174 # Delete the invalid revision if the DB is not transactional
2175 if ( !$wgDBtransactions ) {
2176 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
2179 $revisionId = 0;
2180 $dbw->rollback();
2181 } else {
2182 global $wgUseRCPatrol;
2183 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
2184 # Update recentchanges
2185 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2186 # Mark as patrolled if the user can do so
2187 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan( 'autopatrol' );
2188 # Add RC row to the DB
2189 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
2190 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
2191 $revisionId, $patrolled
2194 # Log auto-patrolled edits
2195 if ( $patrolled ) {
2196 PatrolLog::record( $rc, true );
2199 $user->incEditCount();
2200 $dbw->commit();
2202 } else {
2203 $status->warning( 'edit-no-change' );
2204 $revision = null;
2205 // Keep the same revision ID, but do some updates on it
2206 $revisionId = $this->getRevIdFetched();
2207 // Update page_touched, this is usually implicit in the page update
2208 // Other cache updates are done in onArticleEdit()
2209 $this->mTitle->invalidateCache();
2212 if ( !$wgDBtransactions ) {
2213 ignore_user_abort( $userAbort );
2216 // Now that ignore_user_abort is restored, we can respond to fatal errors
2217 if ( !$status->isOK() ) {
2218 wfProfileOut( __METHOD__ );
2219 return $status;
2222 # Invalidate cache of this article and all pages using this article
2223 # as a template. Partly deferred.
2224 Article::onArticleEdit( $this->mTitle );
2225 # Update links tables, site stats, etc.
2226 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2227 } else {
2228 # Create new article
2229 $status->value['new'] = true;
2231 # Set statistics members
2232 # We work out if it's countable after PST to avoid counter drift
2233 # when articles are created with {{subst:}}
2234 $this->mGoodAdjustment = (int)$this->isCountable( $text );
2235 $this->mTotalAdjustment = 1;
2237 $dbw->begin();
2239 # Add the page record; stake our claim on this title!
2240 # This will return false if the article already exists
2241 $newid = $this->insertOn( $dbw );
2243 if ( $newid === false ) {
2244 $dbw->rollback();
2245 $status->fatal( 'edit-already-exists' );
2247 wfProfileOut( __METHOD__ );
2248 return $status;
2251 # Save the revision text...
2252 $revision = new Revision( array(
2253 'page' => $newid,
2254 'comment' => $summary,
2255 'minor_edit' => $isminor,
2256 'text' => $text,
2257 'user' => $user->getId(),
2258 'user_text' => $user->getName(),
2259 ) );
2260 $revisionId = $revision->insertOn( $dbw );
2262 $this->mTitle->resetArticleID( $newid );
2264 # Update the page record with revision data
2265 $this->updateRevisionOn( $dbw, $revision, 0 );
2267 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2269 # Update recentchanges
2270 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2271 global $wgUseRCPatrol, $wgUseNPPatrol;
2273 # Mark as patrolled if the user can do so
2274 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && $this->mTitle->userCan( 'autopatrol' );
2275 # Add RC row to the DB
2276 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2277 '', strlen( $text ), $revisionId, $patrolled );
2279 # Log auto-patrolled edits
2280 if ( $patrolled ) {
2281 PatrolLog::record( $rc, true );
2284 $user->incEditCount();
2285 $dbw->commit();
2287 # Update links, etc.
2288 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2290 # Clear caches
2291 Article::onArticleCreate( $this->mTitle );
2293 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2294 $flags & EDIT_MINOR, &$watchthis, null, &$flags, $revision ) );
2297 # Do updates right now unless deferral was requested
2298 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2299 wfDoUpdates();
2302 // Return the new revision (or null) to the caller
2303 $status->value['revision'] = $revision;
2305 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2306 $flags & EDIT_MINOR, &$watchthis, null, &$flags, $revision, &$status, $baseRevId,
2307 &$redirect) );
2309 # Watch or unwatch the page
2310 if ( $watchthis === true ) {
2311 if ( !$this->mTitle->userIsWatching() ) {
2312 $dbw->begin();
2313 $this->doWatch();
2314 $dbw->commit();
2316 } elseif ( $watchthis === false ) {
2317 if ( $this->mTitle->userIsWatching() ) {
2318 $dbw->begin();
2319 $this->doUnwatch();
2320 $dbw->commit();
2324 # Give extensions a chance to modify URL query on update
2325 $extraQuery = '';
2327 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
2329 if ( $redirect ) {
2330 if ( $sectionanchor || $extraQuery ) {
2331 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
2332 } else {
2333 $this->doRedirect( $this->isRedirect( $text ) );
2337 wfProfileOut( __METHOD__ );
2339 return $status;
2343 * @deprecated wrapper for doRedirect
2345 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2346 wfDeprecated( __METHOD__ );
2347 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2351 * Output a redirect back to the article.
2352 * This is typically used after an edit.
2354 * @param $noRedir Boolean: add redirect=no
2355 * @param $sectionAnchor String: section to redirect to, including "#"
2356 * @param $extraQuery String: extra query params
2358 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2359 global $wgOut;
2361 if ( $noRedir ) {
2362 $query = 'redirect=no';
2363 if ( $extraQuery )
2364 $query .= "&$extraQuery";
2365 } else {
2366 $query = $extraQuery;
2369 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2373 * Mark this particular edit/page as patrolled
2375 public function markpatrolled() {
2376 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2378 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2380 # If we haven't been given an rc_id value, we can't do anything
2381 $rcid = (int) $wgRequest->getVal( 'rcid' );
2382 $rc = RecentChange::newFromId( $rcid );
2384 if ( is_null( $rc ) ) {
2385 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2386 return;
2389 # It would be nice to see where the user had actually come from, but for now just guess
2390 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2391 $return = SpecialPage::getTitleFor( $returnto );
2393 $dbw = wfGetDB( DB_MASTER );
2394 $errors = $rc->doMarkPatrolled();
2396 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2397 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2399 return;
2402 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2403 // The hook itself has handled any output
2404 return;
2407 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2408 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2409 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2410 $wgOut->returnToMain( false, $return );
2412 return;
2415 if ( !empty( $errors ) ) {
2416 $wgOut->showPermissionsErrorPage( $errors );
2418 return;
2421 # Inform the user
2422 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2423 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2424 $wgOut->returnToMain( false, $return );
2428 * User-interface handler for the "watch" action
2430 public function watch() {
2431 global $wgUser, $wgOut;
2433 if ( $wgUser->isAnon() ) {
2434 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2435 return;
2438 if ( wfReadOnly() ) {
2439 $wgOut->readOnlyPage();
2440 return;
2443 if ( $this->doWatch() ) {
2444 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2445 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2446 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2449 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2453 * Add this page to $wgUser's watchlist
2454 * @return bool true on successful watch operation
2456 public function doWatch() {
2457 global $wgUser;
2459 if ( $wgUser->isAnon() ) {
2460 return false;
2463 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2464 $wgUser->addWatch( $this->mTitle );
2465 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2468 return false;
2472 * User interface handler for the "unwatch" action.
2474 public function unwatch() {
2475 global $wgUser, $wgOut;
2477 if ( $wgUser->isAnon() ) {
2478 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2479 return;
2482 if ( wfReadOnly() ) {
2483 $wgOut->readOnlyPage();
2484 return;
2487 if ( $this->doUnwatch() ) {
2488 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2489 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2490 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2493 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2497 * Stop watching a page
2498 * @return bool true on successful unwatch
2500 public function doUnwatch() {
2501 global $wgUser;
2503 if ( $wgUser->isAnon() ) {
2504 return false;
2507 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2508 $wgUser->removeWatch( $this->mTitle );
2509 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2512 return false;
2516 * action=protect handler
2518 public function protect() {
2519 $form = new ProtectionForm( $this );
2520 $form->execute();
2524 * action=unprotect handler (alias)
2526 public function unprotect() {
2527 $this->protect();
2531 * Update the article's restriction field, and leave a log entry.
2533 * @param $limit Array: set of restriction keys
2534 * @param $reason String
2535 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2536 * @param $expiry Array: per restriction type expiration
2537 * @return bool true on success
2539 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2540 global $wgUser, $wgContLang;
2542 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2544 $id = $this->mTitle->getArticleID();
2546 if ( $id <= 0 ) {
2547 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2548 return false;
2551 if ( wfReadOnly() ) {
2552 wfDebug( "updateRestrictions failed: read-only\n" );
2553 return false;
2556 if ( !$this->mTitle->userCan( 'protect' ) ) {
2557 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2558 return false;
2561 if ( !$cascade ) {
2562 $cascade = false;
2565 // Take this opportunity to purge out expired restrictions
2566 Title::purgeExpiredRestrictions();
2568 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2569 # we expect a single selection, but the schema allows otherwise.
2570 $current = array();
2571 $updated = Article::flattenRestrictions( $limit );
2572 $changed = false;
2574 foreach ( $restrictionTypes as $action ) {
2575 if ( isset( $expiry[$action] ) ) {
2576 # Get current restrictions on $action
2577 $aLimits = $this->mTitle->getRestrictions( $action );
2578 $current[$action] = implode( '', $aLimits );
2579 # Are any actual restrictions being dealt with here?
2580 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
2582 # If something changed, we need to log it. Checking $aRChanged
2583 # assures that "unprotecting" a page that is not protected does
2584 # not log just because the expiry was "changed".
2585 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2586 $changed = true;
2591 $current = Article::flattenRestrictions( $current );
2593 $changed = ( $changed || $current != $updated );
2594 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
2595 $protect = ( $updated != '' );
2597 # If nothing's changed, do nothing
2598 if ( $changed ) {
2599 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2600 $dbw = wfGetDB( DB_MASTER );
2602 # Prepare a null revision to be added to the history
2603 $modified = $current != '' && $protect;
2605 if ( $protect ) {
2606 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2607 } else {
2608 $comment_type = 'unprotectedarticle';
2611 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2613 # Only restrictions with the 'protect' right can cascade...
2614 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2615 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2617 # The schema allows multiple restrictions
2618 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2619 $cascade = false;
2622 $cascade_description = '';
2624 if ( $cascade ) {
2625 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2628 if ( $reason ) {
2629 $comment .= ": $reason";
2632 $editComment = $comment;
2633 $encodedExpiry = array();
2634 $protect_description = '';
2635 foreach ( $limit as $action => $restrictions ) {
2636 if ( !isset( $expiry[$action] ) )
2637 $expiry[$action] = 'infinite';
2639 $encodedExpiry[$action] = Block::encodeExpiry( $expiry[$action], $dbw );
2640 if ( $restrictions != '' ) {
2641 $protect_description .= "[$action=$restrictions] (";
2642 if ( $encodedExpiry[$action] != 'infinity' ) {
2643 $protect_description .= wfMsgForContent( 'protect-expiring',
2644 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2645 $wgContLang->date( $expiry[$action], false, false ) ,
2646 $wgContLang->time( $expiry[$action], false, false ) );
2647 } else {
2648 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2651 $protect_description .= ') ';
2654 $protect_description = trim( $protect_description );
2656 if ( $protect_description && $protect ) {
2657 $editComment .= " ($protect_description)";
2660 if ( $cascade ) {
2661 $editComment .= "$cascade_description";
2664 # Update restrictions table
2665 foreach ( $limit as $action => $restrictions ) {
2666 if ( $restrictions != '' ) {
2667 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2668 array( 'pr_page' => $id,
2669 'pr_type' => $action,
2670 'pr_level' => $restrictions,
2671 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2672 'pr_expiry' => $encodedExpiry[$action]
2674 __METHOD__
2676 } else {
2677 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2678 'pr_type' => $action ), __METHOD__ );
2682 # Insert a null revision
2683 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2684 $nullRevId = $nullRevision->insertOn( $dbw );
2686 $latest = $this->getLatest();
2687 # Update page record
2688 $dbw->update( 'page',
2689 array( /* SET */
2690 'page_touched' => $dbw->timestamp(),
2691 'page_restrictions' => '',
2692 'page_latest' => $nullRevId
2693 ), array( /* WHERE */
2694 'page_id' => $id
2695 ), 'Article::protect'
2698 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2699 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2701 # Update the protection log
2702 $log = new LogPage( 'protect' );
2703 if ( $protect ) {
2704 $params = array( $protect_description, $cascade ? 'cascade' : '' );
2705 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
2706 } else {
2707 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2709 } # End hook
2710 } # End "changed" check
2712 return true;
2716 * Take an array of page restrictions and flatten it to a string
2717 * suitable for insertion into the page_restrictions field.
2718 * @param $limit Array
2719 * @return String
2721 protected static function flattenRestrictions( $limit ) {
2722 if ( !is_array( $limit ) ) {
2723 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2726 $bits = array();
2727 ksort( $limit );
2729 foreach ( $limit as $action => $restrictions ) {
2730 if ( $restrictions != '' ) {
2731 $bits[] = "$action=$restrictions";
2735 return implode( ':', $bits );
2739 * Auto-generates a deletion reason
2741 * @param &$hasHistory Boolean: whether the page has a history
2742 * @return mixed String containing deletion reason or empty string, or boolean false
2743 * if no revision occurred
2745 public function generateReason( &$hasHistory ) {
2746 global $wgContLang;
2748 $dbw = wfGetDB( DB_MASTER );
2749 // Get the last revision
2750 $rev = Revision::newFromTitle( $this->mTitle );
2752 if ( is_null( $rev ) ) {
2753 return false;
2756 // Get the article's contents
2757 $contents = $rev->getText();
2758 $blank = false;
2760 // If the page is blank, use the text from the previous revision,
2761 // which can only be blank if there's a move/import/protect dummy revision involved
2762 if ( $contents == '' ) {
2763 $prev = $rev->getPrevious();
2765 if ( $prev ) {
2766 $contents = $prev->getText();
2767 $blank = true;
2771 // Find out if there was only one contributor
2772 // Only scan the last 20 revisions
2773 $res = $dbw->select( 'revision', 'rev_user_text',
2774 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2775 __METHOD__,
2776 array( 'LIMIT' => 20 )
2779 if ( $res === false ) {
2780 // This page has no revisions, which is very weird
2781 return false;
2784 $hasHistory = ( $res->numRows() > 1 );
2785 $row = $dbw->fetchObject( $res );
2787 if ( $row ) { // $row is false if the only contributor is hidden
2788 $onlyAuthor = $row->rev_user_text;
2789 // Try to find a second contributor
2790 foreach ( $res as $row ) {
2791 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2792 $onlyAuthor = false;
2793 break;
2796 } else {
2797 $onlyAuthor = false;
2800 $dbw->freeResult( $res );
2802 // Generate the summary with a '$1' placeholder
2803 if ( $blank ) {
2804 // The current revision is blank and the one before is also
2805 // blank. It's just not our lucky day
2806 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2807 } else {
2808 if ( $onlyAuthor ) {
2809 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2810 } else {
2811 $reason = wfMsgForContent( 'excontent', '$1' );
2815 if ( $reason == '-' ) {
2816 // Allow these UI messages to be blanked out cleanly
2817 return '';
2820 // Replace newlines with spaces to prevent uglyness
2821 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2822 // Calculate the maximum amount of chars to get
2823 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2824 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2825 $contents = $wgContLang->truncate( $contents, $maxLength );
2826 // Remove possible unfinished links
2827 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2828 // Now replace the '$1' placeholder
2829 $reason = str_replace( '$1', $contents, $reason );
2831 return $reason;
2836 * UI entry point for page deletion
2838 public function delete() {
2839 global $wgUser, $wgOut, $wgRequest;
2841 $confirm = $wgRequest->wasPosted() &&
2842 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2844 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2845 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2847 $reason = $this->DeleteReasonList;
2849 if ( $reason != 'other' && $this->DeleteReason != '' ) {
2850 // Entry from drop down menu + additional comment
2851 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2852 } elseif ( $reason == 'other' ) {
2853 $reason = $this->DeleteReason;
2856 # Flag to hide all contents of the archived revisions
2857 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2859 # This code desperately needs to be totally rewritten
2861 # Read-only check...
2862 if ( wfReadOnly() ) {
2863 $wgOut->readOnlyPage();
2865 return;
2868 # Check permissions
2869 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2871 if ( count( $permission_errors ) > 0 ) {
2872 $wgOut->showPermissionsErrorPage( $permission_errors );
2874 return;
2877 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2879 # Better double-check that it hasn't been deleted yet!
2880 $dbw = wfGetDB( DB_MASTER );
2881 $conds = $this->mTitle->pageCond();
2882 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2883 if ( $latest === false ) {
2884 $wgOut->showFatalError(
2885 Html::rawElement(
2886 'div',
2887 array( 'class' => 'error mw-error-cannotdelete' ),
2888 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2891 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2892 LogEventsList::showLogExtract(
2893 $wgOut,
2894 'delete',
2895 $this->mTitle->getPrefixedText()
2898 return;
2901 # Hack for big sites
2902 $bigHistory = $this->isBigDeletion();
2903 if ( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2904 global $wgLang, $wgDeleteRevisionsLimit;
2906 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2907 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2909 return;
2912 if ( $confirm ) {
2913 $this->doDelete( $reason, $suppress );
2915 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2916 $this->doWatch();
2917 } elseif ( $this->mTitle->userIsWatching() ) {
2918 $this->doUnwatch();
2921 return;
2924 // Generate deletion reason
2925 $hasHistory = false;
2926 if ( !$reason ) {
2927 $reason = $this->generateReason( $hasHistory );
2930 // If the page has a history, insert a warning
2931 if ( $hasHistory && !$confirm ) {
2932 global $wgLang;
2934 $skin = $wgUser->getSkin();
2935 $revisions = $this->estimateRevisionCount();
2936 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2937 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2938 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2939 '</strong>'
2942 if ( $bigHistory ) {
2943 global $wgDeleteRevisionsLimit;
2945 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
2946 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2950 return $this->confirmDelete( $reason );
2954 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2956 public function isBigDeletion() {
2957 global $wgDeleteRevisionsLimit;
2959 if ( $wgDeleteRevisionsLimit ) {
2960 $revCount = $this->estimateRevisionCount();
2962 return $revCount > $wgDeleteRevisionsLimit;
2965 return false;
2969 * @return int approximate revision count
2971 public function estimateRevisionCount() {
2972 $dbr = wfGetDB( DB_SLAVE );
2974 // For an exact count...
2975 // return $dbr->selectField( 'revision', 'COUNT(*)',
2976 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2977 return $dbr->estimateRowCount( 'revision', '*',
2978 array( 'rev_page' => $this->getId() ), __METHOD__ );
2982 * Get the last N authors
2983 * @param $num Integer: number of revisions to get
2984 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2985 * @return array Array of authors, duplicates not removed
2987 public function getLastNAuthors( $num, $revLatest = 0 ) {
2988 wfProfileIn( __METHOD__ );
2989 // First try the slave
2990 // If that doesn't have the latest revision, try the master
2991 $continue = 2;
2992 $db = wfGetDB( DB_SLAVE );
2994 do {
2995 $res = $db->select( array( 'page', 'revision' ),
2996 array( 'rev_id', 'rev_user_text' ),
2997 array(
2998 'page_namespace' => $this->mTitle->getNamespace(),
2999 'page_title' => $this->mTitle->getDBkey(),
3000 'rev_page = page_id'
3001 ), __METHOD__, $this->getSelectOptions( array(
3002 'ORDER BY' => 'rev_timestamp DESC',
3003 'LIMIT' => $num
3007 if ( !$res ) {
3008 wfProfileOut( __METHOD__ );
3009 return array();
3012 $row = $db->fetchObject( $res );
3014 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
3015 $db = wfGetDB( DB_MASTER );
3016 $continue--;
3017 } else {
3018 $continue = 0;
3020 } while ( $continue );
3022 $authors = array( $row->rev_user_text );
3024 while ( $row = $db->fetchObject( $res ) ) {
3025 $authors[] = $row->rev_user_text;
3028 wfProfileOut( __METHOD__ );
3029 return $authors;
3033 * Output deletion confirmation dialog
3034 * @param $reason String: prefilled reason
3036 public function confirmDelete( $reason ) {
3037 global $wgOut, $wgUser;
3039 wfDebug( "Article::confirmDelete\n" );
3041 $deleteBackLink = $wgUser->getSkin()->link(
3042 $this->mTitle,
3043 null,
3044 array(),
3045 array(),
3046 array( 'known', 'noclasses' )
3048 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
3049 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3050 $wgOut->addWikiMsg( 'confirmdeletetext' );
3052 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
3054 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
3055 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
3056 <td></td>
3057 <td class='mw-input'><strong>" .
3058 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
3059 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
3060 "</strong></td>
3061 </tr>";
3062 } else {
3063 $suppress = '';
3065 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
3067 $form = Xml::openElement( 'form', array( 'method' => 'post',
3068 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
3069 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
3070 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
3071 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
3072 "<tr id=\"wpDeleteReasonListRow\">
3073 <td class='mw-label'>" .
3074 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
3075 "</td>
3076 <td class='mw-input'>" .
3077 Xml::listDropDown( 'wpDeleteReasonList',
3078 wfMsgForContent( 'deletereason-dropdown' ),
3079 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
3080 "</td>
3081 </tr>
3082 <tr id=\"wpDeleteReasonRow\">
3083 <td class='mw-label'>" .
3084 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
3085 "</td>
3086 <td class='mw-input'>" .
3087 Html::input( 'wpReason', $reason, 'text', array(
3088 'size' => '60',
3089 'maxlength' => '255',
3090 'tabindex' => '2',
3091 'id' => 'wpReason',
3092 'autofocus'
3093 ) ) .
3094 "</td>
3095 </tr>";
3097 # Disallow watching if user is not logged in
3098 if ( $wgUser->isLoggedIn() ) {
3099 $form .= "
3100 <tr>
3101 <td></td>
3102 <td class='mw-input'>" .
3103 Xml::checkLabel( wfMsg( 'watchthis' ),
3104 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
3105 "</td>
3106 </tr>";
3109 $form .= "
3110 $suppress
3111 <tr>
3112 <td></td>
3113 <td class='mw-submit'>" .
3114 Xml::submitButton( wfMsg( 'deletepage' ),
3115 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
3116 "</td>
3117 </tr>" .
3118 Xml::closeElement( 'table' ) .
3119 Xml::closeElement( 'fieldset' ) .
3120 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
3121 Xml::closeElement( 'form' );
3123 if ( $wgUser->isAllowed( 'editinterface' ) ) {
3124 $skin = $wgUser->getSkin();
3125 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
3126 $link = $skin->link(
3127 $title,
3128 wfMsgHtml( 'delete-edit-reasonlist' ),
3129 array(),
3130 array( 'action' => 'edit' )
3132 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
3135 $wgOut->addHTML( $form );
3136 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3137 LogEventsList::showLogExtract(
3138 $wgOut,
3139 'delete',
3140 $this->mTitle->getPrefixedText()
3145 * Perform a deletion and output success or failure messages
3147 public function doDelete( $reason, $suppress = false ) {
3148 global $wgOut, $wgUser;
3150 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
3152 $error = '';
3153 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
3154 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
3155 $deleted = $this->mTitle->getPrefixedText();
3157 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
3158 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3160 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
3162 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
3163 $wgOut->returnToMain( false );
3164 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
3166 } else {
3167 if ( $error == '' ) {
3168 $wgOut->showFatalError(
3169 Html::rawElement(
3170 'div',
3171 array( 'class' => 'error mw-error-cannotdelete' ),
3172 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
3176 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
3178 LogEventsList::showLogExtract(
3179 $wgOut,
3180 'delete',
3181 $this->mTitle->getPrefixedText()
3183 } else {
3184 $wgOut->showFatalError( $error );
3190 * Back-end article deletion
3191 * Deletes the article with database consistency, writes logs, purges caches
3193 * @param $reason string delete reason for deletion log
3194 * @param suppress bitfield
3195 * Revision::DELETED_TEXT
3196 * Revision::DELETED_COMMENT
3197 * Revision::DELETED_USER
3198 * Revision::DELETED_RESTRICTED
3199 * @param $id int article ID
3200 * @param $commit boolean defaults to true, triggers transaction end
3201 * @return boolean true if successful
3203 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
3204 global $wgUseSquid, $wgDeferredUpdateList;
3205 global $wgUseTrackbacks;
3207 wfDebug( __METHOD__ . "\n" );
3209 $dbw = wfGetDB( DB_MASTER );
3210 $ns = $this->mTitle->getNamespace();
3211 $t = $this->mTitle->getDBkey();
3212 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
3214 if ( $t == '' || $id == 0 ) {
3215 return false;
3218 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
3219 array_push( $wgDeferredUpdateList, $u );
3221 // Bitfields to further suppress the content
3222 if ( $suppress ) {
3223 $bitfield = 0;
3224 // This should be 15...
3225 $bitfield |= Revision::DELETED_TEXT;
3226 $bitfield |= Revision::DELETED_COMMENT;
3227 $bitfield |= Revision::DELETED_USER;
3228 $bitfield |= Revision::DELETED_RESTRICTED;
3229 } else {
3230 $bitfield = 'rev_deleted';
3233 $dbw->begin();
3234 // For now, shunt the revision data into the archive table.
3235 // Text is *not* removed from the text table; bulk storage
3236 // is left intact to avoid breaking block-compression or
3237 // immutable storage schemes.
3239 // For backwards compatibility, note that some older archive
3240 // table entries will have ar_text and ar_flags fields still.
3242 // In the future, we may keep revisions and mark them with
3243 // the rev_deleted field, which is reserved for this purpose.
3244 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
3245 array(
3246 'ar_namespace' => 'page_namespace',
3247 'ar_title' => 'page_title',
3248 'ar_comment' => 'rev_comment',
3249 'ar_user' => 'rev_user',
3250 'ar_user_text' => 'rev_user_text',
3251 'ar_timestamp' => 'rev_timestamp',
3252 'ar_minor_edit' => 'rev_minor_edit',
3253 'ar_rev_id' => 'rev_id',
3254 'ar_text_id' => 'rev_text_id',
3255 'ar_text' => '\'\'', // Be explicit to appease
3256 'ar_flags' => '\'\'', // MySQL's "strict mode"...
3257 'ar_len' => 'rev_len',
3258 'ar_page_id' => 'page_id',
3259 'ar_deleted' => $bitfield
3260 ), array(
3261 'page_id' => $id,
3262 'page_id = rev_page'
3263 ), __METHOD__
3266 # Delete restrictions for it
3267 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
3269 # Now that it's safely backed up, delete it
3270 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
3271 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
3273 if ( !$ok ) {
3274 $dbw->rollback();
3275 return false;
3278 # Fix category table counts
3279 $cats = array();
3280 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
3282 foreach ( $res as $row ) {
3283 $cats [] = $row->cl_to;
3286 $this->updateCategoryCounts( array(), $cats );
3288 # If using cascading deletes, we can skip some explicit deletes
3289 if ( !$dbw->cascadingDeletes() ) {
3290 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
3292 if ( $wgUseTrackbacks )
3293 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
3295 # Delete outgoing links
3296 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
3297 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
3298 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
3299 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
3300 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
3301 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
3302 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
3305 # If using cleanup triggers, we can skip some manual deletes
3306 if ( !$dbw->cleanupTriggers() ) {
3307 # Clean up recentchanges entries...
3308 $dbw->delete( 'recentchanges',
3309 array( 'rc_type != ' . RC_LOG,
3310 'rc_namespace' => $this->mTitle->getNamespace(),
3311 'rc_title' => $this->mTitle->getDBkey() ),
3312 __METHOD__ );
3313 $dbw->delete( 'recentchanges',
3314 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
3315 __METHOD__ );
3318 # Clear caches
3319 Article::onArticleDelete( $this->mTitle );
3321 # Clear the cached article id so the interface doesn't act like we exist
3322 $this->mTitle->resetArticleID( 0 );
3324 # Log the deletion, if the page was suppressed, log it at Oversight instead
3325 $logtype = $suppress ? 'suppress' : 'delete';
3326 $log = new LogPage( $logtype );
3328 # Make sure logging got through
3329 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
3331 if ( $commit ) {
3332 $dbw->commit();
3335 return true;
3339 * Roll back the most recent consecutive set of edits to a page
3340 * from the same user; fails if there are no eligible edits to
3341 * roll back to, e.g. user is the sole contributor. This function
3342 * performs permissions checks on $wgUser, then calls commitRollback()
3343 * to do the dirty work
3345 * @param $fromP String: Name of the user whose edits to rollback.
3346 * @param $summary String: Custom summary. Set to default summary if empty.
3347 * @param $token String: Rollback token.
3348 * @param $bot Boolean: If true, mark all reverted edits as bot.
3350 * @param $resultDetails Array: contains result-specific array of additional values
3351 * 'alreadyrolled' : 'current' (rev)
3352 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3354 * @return array of errors, each error formatted as
3355 * array(messagekey, param1, param2, ...).
3356 * On success, the array is empty. This array can also be passed to
3357 * OutputPage::showPermissionsErrorPage().
3359 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3360 global $wgUser;
3362 $resultDetails = null;
3364 # Check permissions
3365 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
3366 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
3367 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3369 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3370 $errors[] = array( 'sessionfailure' );
3373 if ( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
3374 $errors[] = array( 'actionthrottledtext' );
3377 # If there were errors, bail out now
3378 if ( !empty( $errors ) ) {
3379 return $errors;
3382 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3386 * Backend implementation of doRollback(), please refer there for parameter
3387 * and return value documentation
3389 * NOTE: This function does NOT check ANY permissions, it just commits the
3390 * rollback to the DB Therefore, you should only call this function direct-
3391 * ly if you want to use custom permissions checks. If you don't, use
3392 * doRollback() instead.
3394 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3395 global $wgUseRCPatrol, $wgUser, $wgLang;
3397 $dbw = wfGetDB( DB_MASTER );
3399 if ( wfReadOnly() ) {
3400 return array( array( 'readonlytext' ) );
3403 # Get the last editor
3404 $current = Revision::newFromTitle( $this->mTitle );
3405 if ( is_null( $current ) ) {
3406 # Something wrong... no page?
3407 return array( array( 'notanarticle' ) );
3410 $from = str_replace( '_', ' ', $fromP );
3411 # User name given should match up with the top revision.
3412 # If the user was deleted then $from should be empty.
3413 if ( $from != $current->getUserText() ) {
3414 $resultDetails = array( 'current' => $current );
3415 return array( array( 'alreadyrolled',
3416 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3417 htmlspecialchars( $fromP ),
3418 htmlspecialchars( $current->getUserText() )
3419 ) );
3422 # Get the last edit not by this guy...
3423 # Note: these may not be public values
3424 $user = intval( $current->getRawUser() );
3425 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3426 $s = $dbw->selectRow( 'revision',
3427 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3428 array( 'rev_page' => $current->getPage(),
3429 "rev_user != {$user} OR rev_user_text != {$user_text}"
3430 ), __METHOD__,
3431 array( 'USE INDEX' => 'page_timestamp',
3432 'ORDER BY' => 'rev_timestamp DESC' )
3434 if ( $s === false ) {
3435 # No one else ever edited this page
3436 return array( array( 'cantrollback' ) );
3437 } else if ( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
3438 # Only admins can see this text
3439 return array( array( 'notvisiblerev' ) );
3442 $set = array();
3443 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3444 # Mark all reverted edits as bot
3445 $set['rc_bot'] = 1;
3448 if ( $wgUseRCPatrol ) {
3449 # Mark all reverted edits as patrolled
3450 $set['rc_patrolled'] = 1;
3453 if ( count( $set ) ) {
3454 $dbw->update( 'recentchanges', $set,
3455 array( /* WHERE */
3456 'rc_cur_id' => $current->getPage(),
3457 'rc_user_text' => $current->getUserText(),
3458 "rc_timestamp > '{$s->rev_timestamp}'",
3459 ), __METHOD__
3463 # Generate the edit summary if necessary
3464 $target = Revision::newFromId( $s->rev_id );
3465 if ( empty( $summary ) ) {
3466 if ( $from == '' ) { // no public user name
3467 $summary = wfMsgForContent( 'revertpage-nouser' );
3468 } else {
3469 $summary = wfMsgForContent( 'revertpage' );
3473 # Allow the custom summary to use the same args as the default message
3474 $args = array(
3475 $target->getUserText(), $from, $s->rev_id,
3476 $wgLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ), true ),
3477 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3479 $summary = wfMsgReplaceArgs( $summary, $args );
3481 # Save
3482 $flags = EDIT_UPDATE;
3484 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3485 $flags |= EDIT_MINOR;
3488 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) || $wgUser->isAllowed( 'bot' ) ) ) {
3489 $flags |= EDIT_FORCE_BOT;
3492 # Actually store the edit
3493 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3494 if ( !empty( $status->value['revision'] ) ) {
3495 $revId = $status->value['revision']->getId();
3496 } else {
3497 $revId = false;
3500 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3502 $resultDetails = array(
3503 'summary' => $summary,
3504 'current' => $current,
3505 'target' => $target,
3506 'newid' => $revId
3509 return array();
3513 * User interface for rollback operations
3515 public function rollback() {
3516 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3518 $details = null;
3520 $result = $this->doRollback(
3521 $wgRequest->getVal( 'from' ),
3522 $wgRequest->getText( 'summary' ),
3523 $wgRequest->getVal( 'token' ),
3524 $wgRequest->getBool( 'bot' ),
3525 $details
3528 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3529 $wgOut->rateLimited();
3530 return;
3533 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3534 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3535 $errArray = $result[0];
3536 $errMsg = array_shift( $errArray );
3537 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3539 if ( isset( $details['current'] ) ) {
3540 $current = $details['current'];
3542 if ( $current->getComment() != '' ) {
3543 $wgOut->addWikiMsgArray( 'editcomment', array(
3544 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3548 return;
3551 # Display permissions errors before read-only message -- there's no
3552 # point in misleading the user into thinking the inability to rollback
3553 # is only temporary.
3554 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3555 # array_diff is completely broken for arrays of arrays, sigh.
3556 # Remove any 'readonlytext' error manually.
3557 $out = array();
3558 foreach ( $result as $error ) {
3559 if ( $error != array( 'readonlytext' ) ) {
3560 $out [] = $error;
3563 $wgOut->showPermissionsErrorPage( $out );
3565 return;
3568 if ( $result == array( array( 'readonlytext' ) ) ) {
3569 $wgOut->readOnlyPage();
3571 return;
3574 $current = $details['current'];
3575 $target = $details['target'];
3576 $newId = $details['newid'];
3577 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3578 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3580 if ( $current->getUserText() === '' ) {
3581 $old = wfMsg( 'rev-deleted-user' );
3582 } else {
3583 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3584 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3587 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3588 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3589 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3590 $wgOut->returnToMain( false, $this->mTitle );
3592 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3593 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3594 $de->showDiff( '', '' );
3599 * Do standard deferred updates after page view
3601 public function viewUpdates() {
3602 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3603 if ( wfReadOnly() ) {
3604 return;
3607 # Don't update page view counters on views from bot users (bug 14044)
3608 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3609 Article::incViewCount( $this->getID() );
3610 $u = new SiteStatsUpdate( 1, 0, 0 );
3611 array_push( $wgDeferredUpdateList, $u );
3614 # Update newtalk / watchlist notification status
3615 $wgUser->clearNotification( $this->mTitle );
3619 * Prepare text which is about to be saved.
3620 * Returns a stdclass with source, pst and output members
3622 public function prepareTextForEdit( $text, $revid = null ) {
3623 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
3624 // Already prepared
3625 return $this->mPreparedEdit;
3628 global $wgParser;
3630 $edit = (object)array();
3631 $edit->revid = $revid;
3632 $edit->newText = $text;
3633 $edit->pst = $this->preSaveTransform( $text );
3634 $options = $this->getParserOptions();
3635 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3636 $edit->oldText = $this->getContent();
3638 $this->mPreparedEdit = $edit;
3640 return $edit;
3644 * Do standard deferred updates after page edit.
3645 * Update links tables, site stats, search index and message cache.
3646 * Purges pages that include this page if the text was changed here.
3647 * Every 100th edit, prune the recent changes table.
3649 * @private
3650 * @param $text New text of the article
3651 * @param $summary Edit summary
3652 * @param $minoredit Minor edit
3653 * @param $timestamp_of_pagechange Timestamp associated with the page change
3654 * @param $newid rev_id value of the new revision
3655 * @param $changed Whether or not the content actually changed
3657 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3658 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3660 wfProfileIn( __METHOD__ );
3662 # Parse the text
3663 # Be careful not to double-PST: $text is usually already PST-ed once
3664 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3665 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3666 $editInfo = $this->prepareTextForEdit( $text, $newid );
3667 } else {
3668 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3669 $editInfo = $this->mPreparedEdit;
3672 # Save it to the parser cache
3673 if ( $wgEnableParserCache ) {
3674 $popts = $this->getParserOptions();
3675 $parserCache = ParserCache::singleton();
3676 $parserCache->save( $editInfo->output, $this, $popts );
3679 # Update the links tables
3680 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3681 $u->doUpdate();
3683 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3685 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3686 if ( 0 == mt_rand( 0, 99 ) ) {
3687 // Flush old entries from the `recentchanges` table; we do this on
3688 // random requests so as to avoid an increase in writes for no good reason
3689 global $wgRCMaxAge;
3691 $dbw = wfGetDB( DB_MASTER );
3692 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3693 $recentchanges = $dbw->tableName( 'recentchanges' );
3694 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3696 $dbw->query( $sql );
3700 $id = $this->getID();
3701 $title = $this->mTitle->getPrefixedDBkey();
3702 $shortTitle = $this->mTitle->getDBkey();
3704 if ( 0 == $id ) {
3705 wfProfileOut( __METHOD__ );
3706 return;
3709 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3710 array_push( $wgDeferredUpdateList, $u );
3711 $u = new SearchUpdate( $id, $title, $text );
3712 array_push( $wgDeferredUpdateList, $u );
3714 # If this is another user's talk page, update newtalk
3715 # Don't do this if $changed = false otherwise some idiot can null-edit a
3716 # load of user talk pages and piss people off, nor if it's a minor edit
3717 # by a properly-flagged bot.
3718 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3719 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) )
3721 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3722 $other = User::newFromName( $shortTitle, false );
3723 if ( !$other ) {
3724 wfDebug( __METHOD__ . ": invalid username\n" );
3725 } elseif ( User::isIP( $shortTitle ) ) {
3726 // An anonymous user
3727 $other->setNewtalk( true );
3728 } elseif ( $other->isLoggedIn() ) {
3729 $other->setNewtalk( true );
3730 } else {
3731 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
3736 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3737 $wgMessageCache->replace( $shortTitle, $text );
3740 wfProfileOut( __METHOD__ );
3744 * Perform article updates on a special page creation.
3746 * @param $rev Revision object
3748 * @todo This is a shitty interface function. Kill it and replace the
3749 * other shitty functions like editUpdates and such so it's not needed
3750 * anymore.
3752 public function createUpdates( $rev ) {
3753 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3754 $this->mTotalAdjustment = 1;
3755 $this->editUpdates( $rev->getText(), $rev->getComment(),
3756 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3760 * Generate the navigation links when browsing through an article revisions
3761 * It shows the information as:
3762 * Revision as of \<date\>; view current revision
3763 * \<- Previous version | Next Version -\>
3765 * @param $oldid String: revision ID of this article revision
3767 public function setOldSubtitle( $oldid = 0 ) {
3768 global $wgLang, $wgOut, $wgUser, $wgRequest;
3770 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3771 return;
3774 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
3776 # Cascade unhide param in links for easy deletion browsing
3777 $extraParams = array();
3778 if ( $wgRequest->getVal( 'unhide' ) ) {
3779 $extraParams['unhide'] = 1;
3782 $revision = Revision::newFromId( $oldid );
3784 $current = ( $oldid == $this->mLatest );
3785 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3786 $tddate = $wgLang->date( $this->mTimestamp, true );
3787 $tdtime = $wgLang->time( $this->mTimestamp, true );
3788 $sk = $wgUser->getSkin();
3789 $lnk = $current
3790 ? wfMsgHtml( 'currentrevisionlink' )
3791 : $sk->link(
3792 $this->mTitle,
3793 wfMsgHtml( 'currentrevisionlink' ),
3794 array(),
3795 $extraParams,
3796 array( 'known', 'noclasses' )
3798 $curdiff = $current
3799 ? wfMsgHtml( 'diff' )
3800 : $sk->link(
3801 $this->mTitle,
3802 wfMsgHtml( 'diff' ),
3803 array(),
3804 array(
3805 'diff' => 'cur',
3806 'oldid' => $oldid
3807 ) + $extraParams,
3808 array( 'known', 'noclasses' )
3810 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3811 $prevlink = $prev
3812 ? $sk->link(
3813 $this->mTitle,
3814 wfMsgHtml( 'previousrevision' ),
3815 array(),
3816 array(
3817 'direction' => 'prev',
3818 'oldid' => $oldid
3819 ) + $extraParams,
3820 array( 'known', 'noclasses' )
3822 : wfMsgHtml( 'previousrevision' );
3823 $prevdiff = $prev
3824 ? $sk->link(
3825 $this->mTitle,
3826 wfMsgHtml( 'diff' ),
3827 array(),
3828 array(
3829 'diff' => 'prev',
3830 'oldid' => $oldid
3831 ) + $extraParams,
3832 array( 'known', 'noclasses' )
3834 : wfMsgHtml( 'diff' );
3835 $nextlink = $current
3836 ? wfMsgHtml( 'nextrevision' )
3837 : $sk->link(
3838 $this->mTitle,
3839 wfMsgHtml( 'nextrevision' ),
3840 array(),
3841 array(
3842 'direction' => 'next',
3843 'oldid' => $oldid
3844 ) + $extraParams,
3845 array( 'known', 'noclasses' )
3847 $nextdiff = $current
3848 ? wfMsgHtml( 'diff' )
3849 : $sk->link(
3850 $this->mTitle,
3851 wfMsgHtml( 'diff' ),
3852 array(),
3853 array(
3854 'diff' => 'next',
3855 'oldid' => $oldid
3856 ) + $extraParams,
3857 array( 'known', 'noclasses' )
3860 $cdel = '';
3862 // User can delete revisions or view deleted revisions...
3863 $canHide = $wgUser->isAllowed( 'deleterevision' );
3864 if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3865 if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3866 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3867 } else {
3868 $query = array(
3869 'type' => 'revision',
3870 'target' => $this->mTitle->getPrefixedDbkey(),
3871 'ids' => $oldid
3873 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
3875 $cdel .= ' ';
3878 # Show user links if allowed to see them. If hidden, then show them only if requested...
3879 $userlinks = $sk->revUserTools( $revision, !$unhide );
3881 $m = wfMsg( 'revision-info-current' );
3882 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3883 ? 'revision-info-current'
3884 : 'revision-info';
3886 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3887 wfMsgExt(
3888 $infomsg,
3889 array( 'parseinline', 'replaceafter' ),
3890 $td,
3891 $userlinks,
3892 $revision->getID(),
3893 $tddate,
3894 $tdtime,
3895 $revision->getUser()
3897 "</div>\n" .
3898 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3899 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3901 $wgOut->setSubtitle( $r );
3905 * This function is called right before saving the wikitext,
3906 * so we can do things like signatures and links-in-context.
3908 * @param $text String article contents
3909 * @return string article contents with altered wikitext markup (signatures
3910 * converted, {{subst:}}, templates, etc.)
3912 public function preSaveTransform( $text ) {
3913 global $wgParser, $wgUser;
3915 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3918 /* Caching functions */
3921 * checkLastModified returns true if it has taken care of all
3922 * output to the client that is necessary for this request.
3923 * (that is, it has sent a cached version of the page)
3925 * @return boolean true if cached version send, false otherwise
3927 protected function tryFileCache() {
3928 static $called = false;
3930 if ( $called ) {
3931 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3932 return false;
3935 $called = true;
3936 if ( $this->isFileCacheable() ) {
3937 $cache = new HTMLFileCache( $this->mTitle );
3938 if ( $cache->isFileCacheGood( $this->mTouched ) ) {
3939 wfDebug( "Article::tryFileCache(): about to load file\n" );
3940 $cache->loadFromFileCache();
3941 return true;
3942 } else {
3943 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3944 ob_start( array( &$cache, 'saveToFileCache' ) );
3946 } else {
3947 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3950 return false;
3954 * Check if the page can be cached
3955 * @return bool
3957 public function isFileCacheable() {
3958 $cacheable = false;
3960 if ( HTMLFileCache::useFileCache() ) {
3961 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3962 // Extension may have reason to disable file caching on some pages.
3963 if ( $cacheable ) {
3964 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3968 return $cacheable;
3972 * Loads page_touched and returns a value indicating if it should be used
3973 * @return boolean true if not a redirect
3975 public function checkTouched() {
3976 if ( !$this->mDataLoaded ) {
3977 $this->loadPageData();
3980 return !$this->mIsRedirect;
3984 * Get the page_touched field
3985 * @return string containing GMT timestamp
3987 public function getTouched() {
3988 # Ensure that page data has been loaded
3989 if ( !$this->mDataLoaded ) {
3990 $this->loadPageData();
3993 return $this->mTouched;
3997 * Get the page_latest field
3998 * @return integer rev_id of current revision
4000 public function getLatest() {
4001 if ( !$this->mDataLoaded ) {
4002 $this->loadPageData();
4005 return (int)$this->mLatest;
4009 * Edit an article without doing all that other stuff
4010 * The article must already exist; link tables etc
4011 * are not updated, caches are not flushed.
4013 * @param $text String: text submitted
4014 * @param $comment String: comment submitted
4015 * @param $minor Boolean: whereas it's a minor modification
4017 public function quickEdit( $text, $comment = '', $minor = 0 ) {
4018 wfProfileIn( __METHOD__ );
4020 $dbw = wfGetDB( DB_MASTER );
4021 $revision = new Revision( array(
4022 'page' => $this->getId(),
4023 'text' => $text,
4024 'comment' => $comment,
4025 'minor_edit' => $minor ? 1 : 0,
4026 ) );
4027 $revision->insertOn( $dbw );
4028 $this->updateRevisionOn( $dbw, $revision );
4030 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
4032 wfProfileOut( __METHOD__ );
4036 * Used to increment the view counter
4038 * @param $id Integer: article id
4040 public static function incViewCount( $id ) {
4041 $id = intval( $id );
4043 global $wgHitcounterUpdateFreq;
4045 $dbw = wfGetDB( DB_MASTER );
4046 $pageTable = $dbw->tableName( 'page' );
4047 $hitcounterTable = $dbw->tableName( 'hitcounter' );
4048 $acchitsTable = $dbw->tableName( 'acchits' );
4050 if ( $wgHitcounterUpdateFreq <= 1 ) {
4051 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
4053 return;
4056 # Not important enough to warrant an error page in case of failure
4057 $oldignore = $dbw->ignoreErrors( true );
4059 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
4061 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 + 1 );
4062 if ( ( rand() % $checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
4063 # Most of the time (or on SQL errors), skip row count check
4064 $dbw->ignoreErrors( $oldignore );
4066 return;
4069 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
4070 $row = $dbw->fetchObject( $res );
4071 $rown = intval( $row->n );
4073 if ( $rown >= $wgHitcounterUpdateFreq ) {
4074 wfProfileIn( 'Article::incViewCount-collect' );
4075 $old_user_abort = ignore_user_abort( true );
4077 $dbType = $dbw->getType();
4078 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__, false );
4079 $tabletype = $dbType == 'mysql' ? "ENGINE=HEAP " : '';
4080 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
4081 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
4082 'GROUP BY hc_id', __METHOD__ );
4083 $dbw->delete( 'hitcounter', '*', __METHOD__ );
4084 $dbw->unlockTables( __METHOD__ );
4086 if ( $dbType == 'mysql' ) {
4087 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
4088 'WHERE page_id = hc_id', __METHOD__ );
4089 } else {
4090 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
4091 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__ );
4093 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__ );
4095 ignore_user_abort( $old_user_abort );
4096 wfProfileOut( 'Article::incViewCount-collect' );
4099 $dbw->ignoreErrors( $oldignore );
4102 /**#@+
4103 * The onArticle*() functions are supposed to be a kind of hooks
4104 * which should be called whenever any of the specified actions
4105 * are done.
4107 * This is a good place to put code to clear caches, for instance.
4109 * This is called on page move and undelete, as well as edit
4111 * @param $title a title object
4113 public static function onArticleCreate( $title ) {
4114 # Update existence markers on article/talk tabs...
4115 if ( $title->isTalkPage() ) {
4116 $other = $title->getSubjectPage();
4117 } else {
4118 $other = $title->getTalkPage();
4121 $other->invalidateCache();
4122 $other->purgeSquid();
4124 $title->touchLinks();
4125 $title->purgeSquid();
4126 $title->deleteTitleProtection();
4130 * Clears caches when article is deleted
4132 public static function onArticleDelete( $title ) {
4133 global $wgMessageCache;
4135 # Update existence markers on article/talk tabs...
4136 if ( $title->isTalkPage() ) {
4137 $other = $title->getSubjectPage();
4138 } else {
4139 $other = $title->getTalkPage();
4142 $other->invalidateCache();
4143 $other->purgeSquid();
4145 $title->touchLinks();
4146 $title->purgeSquid();
4148 # File cache
4149 HTMLFileCache::clearFileCache( $title );
4151 # Messages
4152 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
4153 $wgMessageCache->replace( $title->getDBkey(), false );
4156 # Images
4157 if ( $title->getNamespace() == NS_FILE ) {
4158 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
4159 $update->doUpdate();
4162 # User talk pages
4163 if ( $title->getNamespace() == NS_USER_TALK ) {
4164 $user = User::newFromName( $title->getText(), false );
4165 $user->setNewtalk( false );
4168 # Image redirects
4169 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
4173 * Purge caches on page update etc
4175 * @param $title Title object
4176 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
4178 public static function onArticleEdit( $title ) {
4179 global $wgDeferredUpdateList;
4181 // Invalidate caches of articles which include this page
4182 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
4184 // Invalidate the caches of all pages which redirect here
4185 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
4187 # Purge squid for this page only
4188 $title->purgeSquid();
4190 # Clear file cache for this page only
4191 HTMLFileCache::clearFileCache( $title );
4194 /**#@-*/
4197 * Overriden by ImagePage class, only present here to avoid a fatal error
4198 * Called for ?action=revert
4200 public function revert() {
4201 global $wgOut;
4203 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4207 * Info about this page
4208 * Called for ?action=info when $wgAllowPageInfo is on.
4210 public function info() {
4211 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
4213 if ( !$wgAllowPageInfo ) {
4214 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
4215 return;
4218 $page = $this->mTitle->getSubjectPage();
4220 $wgOut->setPagetitle( $page->getPrefixedText() );
4221 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
4222 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
4224 if ( !$this->mTitle->exists() ) {
4225 $wgOut->addHTML( '<div class="noarticletext">' );
4226 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
4227 // This doesn't quite make sense; the user is asking for
4228 // information about the _page_, not the message... -- RC
4229 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
4230 } else {
4231 $msg = $wgUser->isLoggedIn()
4232 ? 'noarticletext'
4233 : 'noarticletextanon';
4234 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
4237 $wgOut->addHTML( '</div>' );
4238 } else {
4239 $dbr = wfGetDB( DB_SLAVE );
4240 $wl_clause = array(
4241 'wl_title' => $page->getDBkey(),
4242 'wl_namespace' => $page->getNamespace() );
4243 $numwatchers = $dbr->selectField(
4244 'watchlist',
4245 'COUNT(*)',
4246 $wl_clause,
4247 __METHOD__,
4248 $this->getSelectOptions() );
4250 $pageInfo = $this->pageCountInfo( $page );
4251 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
4253 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
4254 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
4256 if ( $talkInfo ) {
4257 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
4260 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
4262 if ( $talkInfo ) {
4263 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
4266 $wgOut->addHTML( '</ul>' );
4271 * Return the total number of edits and number of unique editors
4272 * on a given page. If page does not exist, returns false.
4274 * @param $title Title object
4275 * @return mixed array or boolean false
4277 public function pageCountInfo( $title ) {
4278 $id = $title->getArticleId();
4280 if ( $id == 0 ) {
4281 return false;
4284 $dbr = wfGetDB( DB_SLAVE );
4285 $rev_clause = array( 'rev_page' => $id );
4286 $edits = $dbr->selectField(
4287 'revision',
4288 'COUNT(rev_page)',
4289 $rev_clause,
4290 __METHOD__,
4291 $this->getSelectOptions()
4293 $authors = $dbr->selectField(
4294 'revision',
4295 'COUNT(DISTINCT rev_user_text)',
4296 $rev_clause,
4297 __METHOD__,
4298 $this->getSelectOptions()
4301 return array( 'edits' => $edits, 'authors' => $authors );
4305 * Return a list of templates used by this article.
4306 * Uses the templatelinks table
4308 * @return Array of Title objects
4310 public function getUsedTemplates() {
4311 $result = array();
4312 $id = $this->mTitle->getArticleID();
4314 if ( $id == 0 ) {
4315 return array();
4318 $dbr = wfGetDB( DB_SLAVE );
4319 $res = $dbr->select( array( 'templatelinks' ),
4320 array( 'tl_namespace', 'tl_title' ),
4321 array( 'tl_from' => $id ),
4322 __METHOD__ );
4324 if ( $res !== false ) {
4325 foreach ( $res as $row ) {
4326 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
4330 $dbr->freeResult( $res );
4332 return $result;
4336 * Returns a list of hidden categories this page is a member of.
4337 * Uses the page_props and categorylinks tables.
4339 * @return Array of Title objects
4341 public function getHiddenCategories() {
4342 $result = array();
4343 $id = $this->mTitle->getArticleID();
4345 if ( $id == 0 ) {
4346 return array();
4349 $dbr = wfGetDB( DB_SLAVE );
4350 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
4351 array( 'cl_to' ),
4352 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
4353 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
4354 __METHOD__ );
4356 if ( $res !== false ) {
4357 foreach ( $res as $row ) {
4358 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
4362 $dbr->freeResult( $res );
4364 return $result;
4368 * Return an applicable autosummary if one exists for the given edit.
4369 * @param $oldtext String: the previous text of the page.
4370 * @param $newtext String: The submitted text of the page.
4371 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
4372 * @return string An appropriate autosummary, or an empty string.
4374 public static function getAutosummary( $oldtext, $newtext, $flags ) {
4375 # Decide what kind of autosummary is needed.
4377 # Redirect autosummaries
4378 $ot = Title::newFromRedirect( $oldtext );
4379 $rt = Title::newFromRedirect( $newtext );
4381 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
4382 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
4385 # New page autosummaries
4386 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
4387 # If they're making a new article, give its text, truncated, in the summary.
4388 global $wgContLang;
4390 $truncatedtext = $wgContLang->truncate(
4391 str_replace( "\n", ' ', $newtext ),
4392 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
4394 return wfMsgForContent( 'autosumm-new', $truncatedtext );
4397 # Blanking autosummaries
4398 if ( $oldtext != '' && $newtext == '' ) {
4399 return wfMsgForContent( 'autosumm-blank' );
4400 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
4401 # Removing more than 90% of the article
4402 global $wgContLang;
4404 $truncatedtext = $wgContLang->truncate(
4405 $newtext,
4406 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
4408 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
4411 # If we reach this point, there's no applicable autosummary for our case, so our
4412 # autosummary is empty.
4413 return '';
4417 * Add the primary page-view wikitext to the output buffer
4418 * Saves the text into the parser cache if possible.
4419 * Updates templatelinks if it is out of date.
4421 * @param $text String
4422 * @param $cache Boolean
4423 * @param $parserOptions mixed ParserOptions object, or boolean false
4425 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4426 global $wgOut;
4428 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4429 $wgOut->addParserOutput( $this->mParserOutput );
4433 * This does all the heavy lifting for outputWikitext, except it returns the parser
4434 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4435 * say, embedding thread pages within a discussion system (LiquidThreads)
4437 * @param $text string
4438 * @param $cache boolean
4439 * @param $parserOptions parsing options, defaults to false
4440 * @return string containing parsed output
4442 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4443 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
4445 if ( !$parserOptions ) {
4446 $parserOptions = $this->getParserOptions();
4449 $time = - wfTime();
4450 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
4451 $parserOptions, true, true, $this->getRevIdFetched() );
4452 $time += wfTime();
4454 # Timing hack
4455 if ( $time > 3 ) {
4456 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4457 $this->mTitle->getPrefixedDBkey() ) );
4460 if ( $wgEnableParserCache && $cache && $this && !$this->mParserOutput->isCacheable() ) {
4461 $parserCache = ParserCache::singleton();
4462 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
4465 // Make sure file cache is not used on uncacheable content.
4466 // Output that has magic words in it can still use the parser cache
4467 // (if enabled), though it will generally expire sooner.
4468 if ( !$this->mParserOutput->isCacheable() || $this->mParserOutput->containsOldMagic() ) {
4469 $wgUseFileCache = false;
4472 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4474 return $this->mParserOutput;
4478 * Get parser options suitable for rendering the primary article wikitext
4479 * @return mixed ParserOptions object or boolean false
4481 public function getParserOptions() {
4482 global $wgUser;
4484 if ( !$this->mParserOptions ) {
4485 $this->mParserOptions = new ParserOptions( $wgUser );
4486 $this->mParserOptions->setTidy( true );
4487 $this->mParserOptions->enableLimitReport();
4490 return $this->mParserOptions;
4494 * Updates cascading protections
4496 * @param $parserOutput mixed ParserOptions object, or boolean false
4499 protected function doCascadeProtectionUpdates( $parserOutput ) {
4500 if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4501 return;
4504 // templatelinks table may have become out of sync,
4505 // especially if using variable-based transclusions.
4506 // For paranoia, check if things have changed and if
4507 // so apply updates to the database. This will ensure
4508 // that cascaded protections apply as soon as the changes
4509 // are visible.
4511 # Get templates from templatelinks
4512 $id = $this->mTitle->getArticleID();
4514 $tlTemplates = array();
4516 $dbr = wfGetDB( DB_SLAVE );
4517 $res = $dbr->select( array( 'templatelinks' ),
4518 array( 'tl_namespace', 'tl_title' ),
4519 array( 'tl_from' => $id ),
4520 __METHOD__
4523 global $wgContLang;
4525 foreach ( $res as $row ) {
4526 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4529 # Get templates from parser output.
4530 $poTemplates = array();
4531 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4532 foreach ( $templates as $dbk => $id ) {
4533 $poTemplates["$ns:$dbk"] = true;
4537 # Get the diff
4538 # Note that we simulate array_diff_key in PHP <5.0.x
4539 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4541 if ( count( $templates_diff ) > 0 ) {
4542 # Whee, link updates time.
4543 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4544 $u->doUpdate();
4549 * Update all the appropriate counts in the category table, given that
4550 * we've added the categories $added and deleted the categories $deleted.
4552 * @param $added array The names of categories that were added
4553 * @param $deleted array The names of categories that were deleted
4555 public function updateCategoryCounts( $added, $deleted ) {
4556 $ns = $this->mTitle->getNamespace();
4557 $dbw = wfGetDB( DB_MASTER );
4559 # First make sure the rows exist. If one of the "deleted" ones didn't
4560 # exist, we might legitimately not create it, but it's simpler to just
4561 # create it and then give it a negative value, since the value is bogus
4562 # anyway.
4564 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4565 $insertCats = array_merge( $added, $deleted );
4566 if ( !$insertCats ) {
4567 # Okay, nothing to do
4568 return;
4571 $insertRows = array();
4573 foreach ( $insertCats as $cat ) {
4574 $insertRows[] = array(
4575 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4576 'cat_title' => $cat
4579 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4581 $addFields = array( 'cat_pages = cat_pages + 1' );
4582 $removeFields = array( 'cat_pages = cat_pages - 1' );
4584 if ( $ns == NS_CATEGORY ) {
4585 $addFields[] = 'cat_subcats = cat_subcats + 1';
4586 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4587 } elseif ( $ns == NS_FILE ) {
4588 $addFields[] = 'cat_files = cat_files + 1';
4589 $removeFields[] = 'cat_files = cat_files - 1';
4592 if ( $added ) {
4593 $dbw->update(
4594 'category',
4595 $addFields,
4596 array( 'cat_title' => $added ),
4597 __METHOD__
4601 if ( $deleted ) {
4602 $dbw->update(
4603 'category',
4604 $removeFields,
4605 array( 'cat_title' => $deleted ),
4606 __METHOD__
4612 * Lightweight method to get the parser output for a page, checking the parser cache
4613 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4614 * consider, so it's not appropriate to use there.
4616 * @param $oldid mixed integer Revision ID or null
4618 public function getParserOutput( $oldid = null ) {
4619 global $wgEnableParserCache, $wgUser, $wgOut;
4621 // Should the parser cache be used?
4622 $useParserCache = $wgEnableParserCache &&
4623 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4624 $this->exists() &&
4625 $oldid === null;
4627 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4629 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4630 wfIncrStats( 'pcache_miss_stub' );
4633 $parserOutput = false;
4634 if ( $useParserCache ) {
4635 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4638 if ( $parserOutput === false ) {
4639 // Cache miss; parse and output it.
4640 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4642 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4643 } else {
4644 return $parserOutput;