3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 abstract class Page
{}
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 * @internal documentation reviewed 15 Mar 2010
36 class WikiPage
extends Page
implements IDBAccessObject
{
37 // Constants for $mDataLoadedFrom and related
42 public $mTitle = null;
47 public $mDataLoaded = false; // !< Boolean
48 public $mIsRedirect = false; // !< Boolean
49 public $mLatest = false; // !< Integer (false means "not loaded")
50 public $mPreparedEdit = false; // !< Array
54 * @var int; one of the READ_* constants
56 protected $mDataLoadedFrom = self
::READ_NONE
;
61 protected $mRedirectTarget = null;
66 protected $mLastRevision = null;
69 * @var string; timestamp of the current revision or empty string if not loaded
71 protected $mTimestamp = '';
76 protected $mTouched = '19700101000000';
81 protected $mCounter = null;
84 * Constructor and clear the article
85 * @param $title Title Reference to a Title object.
87 public function __construct( Title
$title ) {
88 $this->mTitle
= $title;
92 * Create a WikiPage object of the appropriate class for the given title.
96 * @return WikiPage object of the appropriate type
98 public static function factory( Title
$title ) {
99 $ns = $title->getNamespace();
101 if ( $ns == NS_MEDIA
) {
102 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
103 } elseif ( $ns < 0 ) {
104 throw new MWException( "Invalid or virtual namespace $ns given." );
109 $page = new WikiFilePage( $title );
112 $page = new WikiCategoryPage( $title );
115 $page = new WikiPage( $title );
122 * Constructor from a page id
124 * @param $id Int article ID to load
125 * @param $from string|int one of the following values:
126 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
127 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
129 * @return WikiPage|null
131 public static function newFromID( $id, $from = 'fromdb' ) {
132 $from = self
::convertSelectType( $from );
133 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
134 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
138 return self
::newFromRow( $row, $from );
142 * Constructor from a database row
145 * @param $row object: database row containing at least fields returned
147 * @param $from string|int: source of $data:
148 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
149 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
150 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
153 public static function newFromRow( $row, $from = 'fromdb' ) {
154 $page = self
::factory( Title
::newFromRow( $row ) );
155 $page->loadFromRow( $row, $from );
160 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
162 * @param $type object|string|int
165 private static function convertSelectType( $type ) {
168 return self
::READ_NORMAL
;
170 return self
::READ_LATEST
;
172 return self
::READ_LOCKING
;
174 // It may already be an integer or whatever else
180 * Returns overrides for action handlers.
181 * Classes listed here will be used instead of the default one when
182 * (and only when) $wgActions[$action] === true. This allows subclasses
183 * to override the default behavior.
185 * @todo: move this UI stuff somewhere else
189 public function getActionOverrides() {
194 * Get the title object of the article
195 * @return Title object of this page
197 public function getTitle() {
198 return $this->mTitle
;
205 public function clear() {
206 $this->mDataLoaded
= false;
207 $this->mDataLoadedFrom
= self
::READ_NONE
;
209 $this->clearCacheFields();
213 * Clear the object cache fields
216 protected function clearCacheFields() {
217 $this->mCounter
= null;
218 $this->mRedirectTarget
= null; # Title object if set
219 $this->mLastRevision
= null; # Latest revision
220 $this->mTouched
= '19700101000000';
221 $this->mTimestamp
= '';
222 $this->mIsRedirect
= false;
223 $this->mLatest
= false;
224 $this->mPreparedEdit
= false;
228 * Return the list of revision fields that should be selected to create
233 public static function selectFields() {
250 * Fetch a page record with the given conditions
251 * @param $dbr DatabaseBase object
252 * @param $conditions Array
253 * @param $options Array
254 * @return mixed Database result resource, or false on failure
256 protected function pageData( $dbr, $conditions, $options = array() ) {
257 $fields = self
::selectFields();
259 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
261 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
263 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
269 * Fetch a page record matching the Title object's namespace and title
270 * using a sanitized title string
272 * @param $dbr DatabaseBase object
273 * @param $title Title object
274 * @param $options Array
275 * @return mixed Database result resource, or false on failure
277 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
278 return $this->pageData( $dbr, array(
279 'page_namespace' => $title->getNamespace(),
280 'page_title' => $title->getDBkey() ), $options );
284 * Fetch a page record matching the requested ID
286 * @param $dbr DatabaseBase
288 * @param $options Array
289 * @return mixed Database result resource, or false on failure
291 public function pageDataFromId( $dbr, $id, $options = array() ) {
292 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
296 * Set the general counter, title etc data loaded from
299 * @param $from object|string|int One of the following:
300 * - A DB query result object
301 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
302 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
303 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
307 public function loadPageData( $from = 'fromdb' ) {
308 $from = self
::convertSelectType( $from );
309 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
310 // We already have the data from the correct location, no need to load it twice.
314 if ( $from === self
::READ_LOCKING
) {
315 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
316 } elseif ( $from === self
::READ_LATEST
) {
317 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
318 } elseif ( $from === self
::READ_NORMAL
) {
319 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
320 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
321 # Note that DB also stores the master position in the session and checks it.
322 $touched = $this->getCachedLastEditTime();
323 if ( $touched ) { // key set
324 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
325 $from = self
::READ_LATEST
;
326 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
330 // No idea from where the caller got this data, assume slave database.
332 $from = self
::READ_NORMAL
;
335 $this->loadFromRow( $data, $from );
339 * Load the object from a database row
342 * @param $data object: database row containing at least fields returned
344 * @param $from string|int One of the following:
345 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
346 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
347 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
348 * the master DB using SELECT FOR UPDATE
350 public function loadFromRow( $data, $from ) {
351 $lc = LinkCache
::singleton();
354 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
356 $this->mTitle
->loadFromRow( $data );
358 # Old-fashioned restrictions
359 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
361 $this->mCounter
= intval( $data->page_counter
);
362 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
363 $this->mIsRedirect
= intval( $data->page_is_redirect
);
364 $this->mLatest
= intval( $data->page_latest
);
365 // Bug 37225: $latest may no longer match the cached latest Revision object.
366 // Double-check the ID of any cached latest Revision object for consistency.
367 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
368 $this->mLastRevision
= null;
369 $this->mTimestamp
= '';
372 $lc->addBadLinkObj( $this->mTitle
);
374 $this->mTitle
->loadFromRow( false );
376 $this->clearCacheFields();
379 $this->mDataLoaded
= true;
380 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
384 * @return int Page ID
386 public function getId() {
387 return $this->mTitle
->getArticleID();
391 * @return bool Whether or not the page exists in the database
393 public function exists() {
394 return $this->mTitle
->exists();
398 * Check if this page is something we're going to be showing
399 * some sort of sensible content for. If we return false, page
400 * views (plain action=view) will return an HTTP 404 response,
401 * so spiders and robots can know they're following a bad link.
405 public function hasViewableContent() {
406 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
410 * @return int The view count for the page
412 public function getCount() {
413 if ( !$this->mDataLoaded
) {
414 $this->loadPageData();
417 return $this->mCounter
;
421 * Tests if the article text represents a redirect
423 * @param $text mixed string containing article contents, or boolean
426 public function isRedirect( $text = false ) {
427 if ( $text === false ) {
428 if ( !$this->mDataLoaded
) {
429 $this->loadPageData();
432 return (bool)$this->mIsRedirect
;
434 return Title
::newFromRedirect( $text ) !== null;
439 * Loads page_touched and returns a value indicating if it should be used
440 * @return boolean true if not a redirect
442 public function checkTouched() {
443 if ( !$this->mDataLoaded
) {
444 $this->loadPageData();
446 return !$this->mIsRedirect
;
450 * Get the page_touched field
451 * @return string containing GMT timestamp
453 public function getTouched() {
454 if ( !$this->mDataLoaded
) {
455 $this->loadPageData();
457 return $this->mTouched
;
461 * Get the page_latest field
462 * @return integer rev_id of current revision
464 public function getLatest() {
465 if ( !$this->mDataLoaded
) {
466 $this->loadPageData();
468 return (int)$this->mLatest
;
472 * Get the Revision object of the oldest revision
473 * @return Revision|null
475 public function getOldestRevision() {
476 wfProfileIn( __METHOD__
);
478 // Try using the slave database first, then try the master
480 $db = wfGetDB( DB_SLAVE
);
481 $revSelectFields = Revision
::selectFields();
483 while ( $continue ) {
484 $row = $db->selectRow(
485 array( 'page', 'revision' ),
488 'page_namespace' => $this->mTitle
->getNamespace(),
489 'page_title' => $this->mTitle
->getDBkey(),
494 'ORDER BY' => 'rev_timestamp ASC'
501 $db = wfGetDB( DB_MASTER
);
506 wfProfileOut( __METHOD__
);
507 return $row ? Revision
::newFromRow( $row ) : null;
511 * Loads everything except the text
512 * This isn't necessary for all uses, so it's only done if needed.
514 protected function loadLastEdit() {
515 if ( $this->mLastRevision
!== null ) {
516 return; // already loaded
519 $latest = $this->getLatest();
521 return; // page doesn't exist or is missing page_latest info
524 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
525 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
526 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
527 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
528 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
529 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
530 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
531 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
532 if ( $revision ) { // sanity
533 $this->setLastEdit( $revision );
538 * Set the latest revision
540 protected function setLastEdit( Revision
$revision ) {
541 $this->mLastRevision
= $revision;
542 $this->mTimestamp
= $revision->getTimestamp();
546 * Get the latest revision
547 * @return Revision|null
549 public function getRevision() {
550 $this->loadLastEdit();
551 if ( $this->mLastRevision
) {
552 return $this->mLastRevision
;
558 * Get the text of the current revision. No side-effects...
560 * @param $audience Integer: one of:
561 * Revision::FOR_PUBLIC to be displayed to all users
562 * Revision::FOR_THIS_USER to be displayed to the given user
563 * Revision::RAW get the text regardless of permissions
564 * @param $user User object to check for, only if FOR_THIS_USER is passed
565 * to the $audience parameter
566 * @return String|bool The text of the current revision. False on failure
568 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
569 $this->loadLastEdit();
570 if ( $this->mLastRevision
) {
571 return $this->mLastRevision
->getText( $audience, $user );
577 * Get the text of the current revision. No side-effects...
579 * @return String|bool The text of the current revision. False on failure
581 public function getRawText() {
582 $this->loadLastEdit();
583 if ( $this->mLastRevision
) {
584 return $this->mLastRevision
->getRawText();
590 * @return string MW timestamp of last article revision
592 public function getTimestamp() {
593 // Check if the field has been filled by WikiPage::setTimestamp()
594 if ( !$this->mTimestamp
) {
595 $this->loadLastEdit();
598 return wfTimestamp( TS_MW
, $this->mTimestamp
);
602 * Set the page timestamp (use only to avoid DB queries)
603 * @param $ts string MW timestamp of last article revision
606 public function setTimestamp( $ts ) {
607 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
611 * @param $audience Integer: one of:
612 * Revision::FOR_PUBLIC to be displayed to all users
613 * Revision::FOR_THIS_USER to be displayed to the given user
614 * Revision::RAW get the text regardless of permissions
615 * @param $user User object to check for, only if FOR_THIS_USER is passed
616 * to the $audience parameter
617 * @return int user ID for the user that made the last article revision
619 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
620 $this->loadLastEdit();
621 if ( $this->mLastRevision
) {
622 return $this->mLastRevision
->getUser( $audience, $user );
629 * Get the User object of the user who created the page
630 * @param $audience Integer: one of:
631 * Revision::FOR_PUBLIC to be displayed to all users
632 * Revision::FOR_THIS_USER to be displayed to the given user
633 * Revision::RAW get the text regardless of permissions
634 * @param $user User object to check for, only if FOR_THIS_USER is passed
635 * to the $audience parameter
638 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
639 $revision = $this->getOldestRevision();
641 $userName = $revision->getUserText( $audience, $user );
642 return User
::newFromName( $userName, false );
649 * @param $audience Integer: one of:
650 * Revision::FOR_PUBLIC to be displayed to all users
651 * Revision::FOR_THIS_USER to be displayed to the given user
652 * Revision::RAW get the text regardless of permissions
653 * @param $user User object to check for, only if FOR_THIS_USER is passed
654 * to the $audience parameter
655 * @return string username of the user that made the last article revision
657 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
658 $this->loadLastEdit();
659 if ( $this->mLastRevision
) {
660 return $this->mLastRevision
->getUserText( $audience, $user );
667 * @param $audience Integer: one of:
668 * Revision::FOR_PUBLIC to be displayed to all users
669 * Revision::FOR_THIS_USER to be displayed to the given user
670 * Revision::RAW get the text regardless of permissions
671 * @param $user User object to check for, only if FOR_THIS_USER is passed
672 * to the $audience parameter
673 * @return string Comment stored for the last article revision
675 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
676 $this->loadLastEdit();
677 if ( $this->mLastRevision
) {
678 return $this->mLastRevision
->getComment( $audience, $user );
685 * Returns true if last revision was marked as "minor edit"
687 * @return boolean Minor edit indicator for the last article revision.
689 public function getMinorEdit() {
690 $this->loadLastEdit();
691 if ( $this->mLastRevision
) {
692 return $this->mLastRevision
->isMinor();
699 * Get the cached timestamp for the last time the page changed.
700 * This is only used to help handle slave lag by comparing to page_touched.
701 * @return string MW timestamp
703 protected function getCachedLastEditTime() {
705 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
706 return $wgMemc->get( $key );
710 * Set the cached timestamp for the last time the page changed.
711 * This is only used to help handle slave lag by comparing to page_touched.
712 * @param $timestamp string
715 public function setCachedLastEditTime( $timestamp ) {
717 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
718 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
722 * Determine whether a page would be suitable for being counted as an
723 * article in the site_stats table based on the title & its content
725 * @param $editInfo Object|bool (false): object returned by prepareTextForEdit(),
726 * if false, the current database state will be used
729 public function isCountable( $editInfo = false ) {
730 global $wgArticleCountMethod;
732 if ( !$this->mTitle
->isContentPage() ) {
736 $text = $editInfo ?
$editInfo->pst
: false;
738 if ( $this->isRedirect( $text ) ) {
742 switch ( $wgArticleCountMethod ) {
746 if ( $text === false ) {
747 $text = $this->getRawText();
749 return strpos( $text, ',' ) !== false;
752 // ParserOutput::getLinks() is a 2D array of page links, so
753 // to be really correct we would need to recurse in the array
754 // but the main array should only have items in it if there are
756 return (bool)count( $editInfo->output
->getLinks() );
758 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
759 array( 'pl_from' => $this->getId() ), __METHOD__
);
765 * If this page is a redirect, get its target
767 * The target will be fetched from the redirect table if possible.
768 * If this page doesn't have an entry there, call insertRedirect()
769 * @return Title|mixed object, or null if this page is not a redirect
771 public function getRedirectTarget() {
772 if ( !$this->mTitle
->isRedirect() ) {
776 if ( $this->mRedirectTarget
!== null ) {
777 return $this->mRedirectTarget
;
780 # Query the redirect table
781 $dbr = wfGetDB( DB_SLAVE
);
782 $row = $dbr->selectRow( 'redirect',
783 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
784 array( 'rd_from' => $this->getId() ),
788 // rd_fragment and rd_interwiki were added later, populate them if empty
789 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
790 return $this->mRedirectTarget
= Title
::makeTitle(
791 $row->rd_namespace
, $row->rd_title
,
792 $row->rd_fragment
, $row->rd_interwiki
);
795 # This page doesn't have an entry in the redirect table
796 return $this->mRedirectTarget
= $this->insertRedirect();
800 * Insert an entry for this page into the redirect table.
802 * Don't call this function directly unless you know what you're doing.
803 * @return Title object or null if not a redirect
805 public function insertRedirect() {
806 // recurse through to only get the final target
807 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
811 $this->insertRedirectEntry( $retval );
816 * Insert or update the redirect table entry for this page to indicate
817 * it redirects to $rt .
818 * @param $rt Title redirect target
820 public function insertRedirectEntry( $rt ) {
821 $dbw = wfGetDB( DB_MASTER
);
822 $dbw->replace( 'redirect', array( 'rd_from' ),
824 'rd_from' => $this->getId(),
825 'rd_namespace' => $rt->getNamespace(),
826 'rd_title' => $rt->getDBkey(),
827 'rd_fragment' => $rt->getFragment(),
828 'rd_interwiki' => $rt->getInterwiki(),
835 * Get the Title object or URL this page redirects to
837 * @return mixed false, Title of in-wiki target, or string with URL
839 public function followRedirect() {
840 return $this->getRedirectURL( $this->getRedirectTarget() );
844 * Get the Title object or URL to use for a redirect. We use Title
845 * objects for same-wiki, non-special redirects and URLs for everything
847 * @param $rt Title Redirect target
848 * @return mixed false, Title object of local target, or string with URL
850 public function getRedirectURL( $rt ) {
855 if ( $rt->isExternal() ) {
856 if ( $rt->isLocal() ) {
857 // Offsite wikis need an HTTP redirect.
859 // This can be hard to reverse and may produce loops,
860 // so they may be disabled in the site configuration.
861 $source = $this->mTitle
->getFullURL( 'redirect=no' );
862 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
864 // External pages pages without "local" bit set are not valid
870 if ( $rt->isSpecialPage() ) {
871 // Gotta handle redirects to special pages differently:
872 // Fill the HTTP response "Location" header and ignore
873 // the rest of the page we're on.
875 // Some pages are not valid targets
876 if ( $rt->isValidRedirectTarget() ) {
877 return $rt->getFullURL();
887 * Get a list of users who have edited this article, not including the user who made
888 * the most recent revision, which you can get from $article->getUser() if you want it
889 * @return UserArrayFromResult
891 public function getContributors() {
892 # @todo FIXME: This is expensive; cache this info somewhere.
894 $dbr = wfGetDB( DB_SLAVE
);
896 if ( $dbr->implicitGroupby() ) {
897 $realNameField = 'user_real_name';
899 $realNameField = 'MIN(user_real_name) AS user_real_name';
902 $tables = array( 'revision', 'user' );
905 'user_id' => 'rev_user',
906 'user_name' => 'rev_user_text',
908 'timestamp' => 'MAX(rev_timestamp)',
911 $conds = array( 'rev_page' => $this->getId() );
913 // The user who made the top revision gets credited as "this page was last edited by
914 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
915 $user = $this->getUser();
917 $conds[] = "rev_user != $user";
919 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
922 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
925 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
929 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
930 'ORDER BY' => 'timestamp DESC',
933 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
934 return new UserArrayFromResult( $res );
938 * Get the last N authors
939 * @param $num Integer: number of revisions to get
940 * @param $revLatest String: the latest rev_id, selected from the master (optional)
941 * @return array Array of authors, duplicates not removed
943 public function getLastNAuthors( $num, $revLatest = 0 ) {
944 wfProfileIn( __METHOD__
);
945 // First try the slave
946 // If that doesn't have the latest revision, try the master
948 $db = wfGetDB( DB_SLAVE
);
951 $res = $db->select( array( 'page', 'revision' ),
952 array( 'rev_id', 'rev_user_text' ),
954 'page_namespace' => $this->mTitle
->getNamespace(),
955 'page_title' => $this->mTitle
->getDBkey(),
959 'ORDER BY' => 'rev_timestamp DESC',
965 wfProfileOut( __METHOD__
);
969 $row = $db->fetchObject( $res );
971 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
972 $db = wfGetDB( DB_MASTER
);
977 } while ( $continue );
979 $authors = array( $row->rev_user_text
);
981 foreach ( $res as $row ) {
982 $authors[] = $row->rev_user_text
;
985 wfProfileOut( __METHOD__
);
990 * Should the parser cache be used?
992 * @param $parserOptions ParserOptions to check
996 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
997 global $wgEnableParserCache;
999 return $wgEnableParserCache
1000 && $parserOptions->getStubThreshold() == 0
1001 && $this->mTitle
->exists()
1002 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1003 && $this->mTitle
->isWikitextPage();
1007 * Get a ParserOutput for the given ParserOptions and revision ID.
1008 * The parser cache will be used if possible.
1011 * @param $parserOptions ParserOptions to use for the parse operation
1012 * @param $oldid Revision ID to get the text from, passing null or 0 will
1013 * get the current revision (default value)
1014 * @return ParserOutput or false if the revision was not found
1016 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1017 wfProfileIn( __METHOD__
);
1019 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1020 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1021 if ( $parserOptions->getStubThreshold() ) {
1022 wfIncrStats( 'pcache_miss_stub' );
1025 if ( $useParserCache ) {
1026 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1027 if ( $parserOutput !== false ) {
1028 wfProfileOut( __METHOD__
);
1029 return $parserOutput;
1033 if ( $oldid === null ||
$oldid === 0 ) {
1034 $oldid = $this->getLatest();
1037 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1040 wfProfileOut( __METHOD__
);
1042 return $pool->getParserOutput();
1046 * Do standard deferred updates after page view
1047 * @param $user User The relevant user
1049 public function doViewUpdates( User
$user ) {
1050 global $wgDisableCounters;
1051 if ( wfReadOnly() ) {
1055 # Don't update page view counters on views from bot users (bug 14044)
1056 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1057 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1058 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1061 # Update newtalk / watchlist notification status
1062 $user->clearNotification( $this->mTitle
);
1066 * Perform the actions of a page purging
1069 public function doPurge() {
1072 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1076 // Invalidate the cache
1077 $this->mTitle
->invalidateCache();
1080 if ( $wgUseSquid ) {
1081 // Commit the transaction before the purge is sent
1082 $dbw = wfGetDB( DB_MASTER
);
1083 $dbw->commit( __METHOD__
);
1086 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1087 $update->doUpdate();
1090 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1091 if ( $this->mTitle
->exists() ) {
1092 $text = $this->getRawText();
1097 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1103 * Insert a new empty page record for this article.
1104 * This *must* be followed up by creating a revision
1105 * and running $this->updateRevisionOn( ... );
1106 * or else the record will be left in a funky state.
1107 * Best if all done inside a transaction.
1109 * @param $dbw DatabaseBase
1110 * @return int The newly created page_id key, or false if the title already existed
1112 public function insertOn( $dbw ) {
1113 wfProfileIn( __METHOD__
);
1115 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1116 $dbw->insert( 'page', array(
1117 'page_id' => $page_id,
1118 'page_namespace' => $this->mTitle
->getNamespace(),
1119 'page_title' => $this->mTitle
->getDBkey(),
1120 'page_counter' => 0,
1121 'page_restrictions' => '',
1122 'page_is_redirect' => 0, # Will set this shortly...
1124 'page_random' => wfRandom(),
1125 'page_touched' => $dbw->timestamp(),
1126 'page_latest' => 0, # Fill this in shortly...
1127 'page_len' => 0, # Fill this in shortly...
1128 ), __METHOD__
, 'IGNORE' );
1130 $affected = $dbw->affectedRows();
1133 $newid = $dbw->insertId();
1134 $this->mTitle
->resetArticleID( $newid );
1136 wfProfileOut( __METHOD__
);
1138 return $affected ?
$newid : false;
1142 * Update the page record to point to a newly saved revision.
1144 * @param $dbw DatabaseBase: object
1145 * @param $revision Revision: For ID number, and text used to set
1146 * length and redirect status fields
1147 * @param $lastRevision Integer: if given, will not overwrite the page field
1148 * when different from the currently set value.
1149 * Giving 0 indicates the new page flag should be set
1151 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1152 * removing rows in redirect table.
1153 * @return bool true on success, false on failure
1156 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1157 wfProfileIn( __METHOD__
);
1159 $text = $revision->getText();
1160 $len = strlen( $text );
1161 $rt = Title
::newFromRedirectRecurse( $text );
1163 $conditions = array( 'page_id' => $this->getId() );
1165 if ( !is_null( $lastRevision ) ) {
1166 # An extra check against threads stepping on each other
1167 $conditions['page_latest'] = $lastRevision;
1170 $now = wfTimestampNow();
1171 $dbw->update( 'page',
1173 'page_latest' => $revision->getId(),
1174 'page_touched' => $dbw->timestamp( $now ),
1175 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1176 'page_is_redirect' => $rt !== null ?
1 : 0,
1182 $result = $dbw->affectedRows() > 0;
1184 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1185 $this->setLastEdit( $revision );
1186 $this->setCachedLastEditTime( $now );
1187 $this->mLatest
= $revision->getId();
1188 $this->mIsRedirect
= (bool)$rt;
1189 # Update the LinkCache.
1190 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1193 wfProfileOut( __METHOD__
);
1198 * Add row to the redirect table if this is a redirect, remove otherwise.
1200 * @param $dbw DatabaseBase
1201 * @param $redirectTitle Title object pointing to the redirect target,
1202 * or NULL if this is not a redirect
1203 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1204 * removing rows in redirect table.
1205 * @return bool true on success, false on failure
1208 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1209 // Always update redirects (target link might have changed)
1210 // Update/Insert if we don't know if the last revision was a redirect or not
1211 // Delete if changing from redirect to non-redirect
1212 $isRedirect = !is_null( $redirectTitle );
1214 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1218 wfProfileIn( __METHOD__
);
1219 if ( $isRedirect ) {
1220 $this->insertRedirectEntry( $redirectTitle );
1222 // This is not a redirect, remove row from redirect table
1223 $where = array( 'rd_from' => $this->getId() );
1224 $dbw->delete( 'redirect', $where, __METHOD__
);
1227 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1228 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1230 wfProfileOut( __METHOD__
);
1232 return ( $dbw->affectedRows() != 0 );
1236 * If the given revision is newer than the currently set page_latest,
1237 * update the page record. Otherwise, do nothing.
1239 * @param $dbw DatabaseBase object
1240 * @param $revision Revision object
1243 public function updateIfNewerOn( $dbw, $revision ) {
1244 wfProfileIn( __METHOD__
);
1246 $row = $dbw->selectRow(
1247 array( 'revision', 'page' ),
1248 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1250 'page_id' => $this->getId(),
1251 'page_latest=rev_id' ),
1255 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1256 wfProfileOut( __METHOD__
);
1259 $prev = $row->rev_id
;
1260 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1262 # No or missing previous revision; mark the page as new
1264 $lastRevIsRedirect = null;
1267 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1269 wfProfileOut( __METHOD__
);
1274 * Get the text that needs to be saved in order to undo all revisions
1275 * between $undo and $undoafter. Revisions must belong to the same page,
1276 * must exist and must not be deleted
1277 * @param $undo Revision
1278 * @param $undoafter Revision Must be an earlier revision than $undo
1279 * @return mixed string on success, false on failure
1281 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1282 $cur_text = $this->getRawText();
1283 if ( $cur_text === false ) {
1284 return false; // no page
1286 $undo_text = $undo->getText();
1287 $undoafter_text = $undoafter->getText();
1289 if ( $cur_text == $undo_text ) {
1290 # No use doing a merge if it's just a straight revert.
1291 return $undoafter_text;
1296 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1300 return $undone_text;
1304 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1305 * @param $text String: new text of the section
1306 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1307 * @param $edittime String: revision timestamp or null to use the current revision
1308 * @return string Complete article text, or null if error
1310 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1311 wfProfileIn( __METHOD__
);
1313 if ( strval( $section ) == '' ) {
1314 // Whole-page edit; let the whole text through
1316 // Bug 30711: always use current version when adding a new section
1317 if ( is_null( $edittime ) ||
$section == 'new' ) {
1318 $oldtext = $this->getRawText();
1319 if ( $oldtext === false ) {
1320 wfDebug( __METHOD__
. ": no page text\n" );
1321 wfProfileOut( __METHOD__
);
1325 $dbw = wfGetDB( DB_MASTER
);
1326 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1329 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1330 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1331 wfProfileOut( __METHOD__
);
1335 $oldtext = $rev->getText();
1338 if ( $section == 'new' ) {
1339 # Inserting a new section
1340 $subject = $sectionTitle ?
wfMessage( 'newsectionheaderdefaultlevel' )
1341 ->rawParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
1342 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1343 $text = strlen( trim( $oldtext ) ) > 0
1344 ?
"{$oldtext}\n\n{$subject}{$text}"
1345 : "{$subject}{$text}";
1348 # Replacing an existing section; roll out the big guns
1351 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1355 wfProfileOut( __METHOD__
);
1360 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1362 * @return Int updated $flags
1364 function checkFlags( $flags ) {
1365 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1366 if ( $this->mTitle
->getArticleID() ) {
1367 $flags |
= EDIT_UPDATE
;
1377 * Change an existing article or create a new article. Updates RC and all necessary caches,
1378 * optionally via the deferred update array.
1380 * @param $text String: new text
1381 * @param $summary String: edit summary
1382 * @param $flags Integer bitfield:
1384 * Article is known or assumed to be non-existent, create a new one
1386 * Article is known or assumed to be pre-existing, update it
1388 * Mark this edit minor, if the user is allowed to do so
1390 * Do not log the change in recentchanges
1392 * Mark the edit a "bot" edit regardless of user rights
1393 * EDIT_DEFER_UPDATES
1394 * Defer some of the updates until the end of index.php
1396 * Fill in blank summaries with generated text where possible
1398 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1399 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1400 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1401 * edit-already-exists error will be returned. These two conditions are also possible with
1402 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1404 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1405 * @param $user User the user doing the edit
1407 * @throws MWException
1408 * @return Status object. Possible errors:
1409 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1410 * edit-gone-missing: In update mode, but the article didn't exist
1411 * edit-conflict: In update mode, the article changed unexpectedly
1412 * edit-no-change: Warning that the text was the same as before
1413 * edit-already-exists: In creation mode, but the article already exists
1415 * Extensions may define additional errors.
1417 * $return->value will contain an associative array with members as follows:
1418 * new: Boolean indicating if the function attempted to create a new article
1419 * revision: The revision object for the inserted revision, or null
1421 * Compatibility note: this function previously returned a boolean value indicating success/failure
1423 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1424 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1426 # Low-level sanity check
1427 if ( $this->mTitle
->getText() === '' ) {
1428 throw new MWException( 'Something is trying to edit an article with an empty title' );
1431 wfProfileIn( __METHOD__
);
1433 $user = is_null( $user ) ?
$wgUser : $user;
1434 $status = Status
::newGood( array() );
1436 // Load the data from the master database if needed.
1437 // The caller may already loaded it from the master or even loaded it using
1438 // SELECT FOR UPDATE, so do not override that using clear().
1439 $this->loadPageData( 'fromdbmaster' );
1441 $flags = $this->checkFlags( $flags );
1443 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1444 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1446 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1448 if ( $status->isOK() ) {
1449 $status->fatal( 'edit-hook-aborted' );
1452 wfProfileOut( __METHOD__
);
1456 # Silently ignore EDIT_MINOR if not allowed
1457 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1458 $bot = $flags & EDIT_FORCE_BOT
;
1460 $oldtext = $this->getRawText(); // current revision
1461 $oldsize = strlen( $oldtext );
1462 $oldid = $this->getLatest();
1463 $oldIsRedirect = $this->isRedirect();
1464 $oldcountable = $this->isCountable();
1466 # Provide autosummaries if one is not provided and autosummaries are enabled.
1467 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1468 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1471 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1472 $text = $editInfo->pst
;
1473 $newsize = strlen( $text );
1475 $dbw = wfGetDB( DB_MASTER
);
1476 $now = wfTimestampNow();
1477 $this->mTimestamp
= $now;
1479 if ( $flags & EDIT_UPDATE
) {
1480 # Update article, but only if changed.
1481 $status->value
['new'] = false;
1484 # Article gone missing
1485 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1486 $status->fatal( 'edit-gone-missing' );
1488 wfProfileOut( __METHOD__
);
1490 } elseif ( $oldtext === false ) {
1491 # Sanity check for bug 37225
1492 wfProfileOut( __METHOD__
);
1493 throw new MWException( "Could not find text for current revision {$oldid}." );
1496 $revision = new Revision( array(
1497 'page' => $this->getId(),
1498 'comment' => $summary,
1499 'minor_edit' => $isminor,
1501 'parent_id' => $oldid,
1502 'user' => $user->getId(),
1503 'user_text' => $user->getName(),
1506 # Bug 37225: use accessor to get the text as Revision may trim it.
1507 # After trimming, the text may be a duplicate of the current text.
1508 $text = $revision->getText(); // sanity; EditPage should trim already
1510 $changed = ( strcmp( $text, $oldtext ) != 0 );
1513 $dbw->begin( __METHOD__
);
1514 $revisionId = $revision->insertOn( $dbw );
1518 # Note that we use $this->mLatest instead of fetching a value from the master DB
1519 # during the course of this function. This makes sure that EditPage can detect
1520 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1521 # before this function is called. A previous function used a separate query, this
1522 # creates a window where concurrent edits can cause an ignored edit conflict.
1523 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1526 # Belated edit conflict! Run away!!
1527 $status->fatal( 'edit-conflict' );
1529 $dbw->rollback( __METHOD__
);
1531 wfProfileOut( __METHOD__
);
1535 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1536 # Update recentchanges
1537 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1538 # Mark as patrolled if the user can do so
1539 $patrolled = $wgUseRCPatrol && !count(
1540 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1541 # Add RC row to the DB
1542 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1543 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1544 $revisionId, $patrolled
1547 # Log auto-patrolled edits
1549 PatrolLog
::record( $rc, true, $user );
1552 $user->incEditCount();
1553 $dbw->commit( __METHOD__
);
1555 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1556 // related variables correctly
1557 $revision->setId( $this->getLatest() );
1560 # Update links tables, site stats, etc.
1561 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1562 'oldcountable' => $oldcountable ) );
1565 $status->warning( 'edit-no-change' );
1567 // Update page_touched, this is usually implicit in the page update
1568 // Other cache updates are done in onArticleEdit()
1569 $this->mTitle
->invalidateCache();
1572 # Create new article
1573 $status->value
['new'] = true;
1575 $dbw->begin( __METHOD__
);
1577 # Add the page record; stake our claim on this title!
1578 # This will return false if the article already exists
1579 $newid = $this->insertOn( $dbw );
1581 if ( $newid === false ) {
1582 $dbw->rollback( __METHOD__
);
1583 $status->fatal( 'edit-already-exists' );
1585 wfProfileOut( __METHOD__
);
1589 # Save the revision text...
1590 $revision = new Revision( array(
1592 'comment' => $summary,
1593 'minor_edit' => $isminor,
1595 'user' => $user->getId(),
1596 'user_text' => $user->getName(),
1599 $revisionId = $revision->insertOn( $dbw );
1601 # Bug 37225: use accessor to get the text as Revision may trim it
1602 $text = $revision->getText(); // sanity; EditPage should trim already
1604 # Update the page record with revision data
1605 $this->updateRevisionOn( $dbw, $revision, 0 );
1607 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1609 # Update recentchanges
1610 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1611 # Mark as patrolled if the user can do so
1612 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1613 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1614 # Add RC row to the DB
1615 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1616 '', strlen( $text ), $revisionId, $patrolled );
1618 # Log auto-patrolled edits
1620 PatrolLog
::record( $rc, true, $user );
1623 $user->incEditCount();
1624 $dbw->commit( __METHOD__
);
1626 # Update links, etc.
1627 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1629 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1630 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1633 # Do updates right now unless deferral was requested
1634 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1635 DeferredUpdates
::doUpdates();
1638 // Return the new revision (or null) to the caller
1639 $status->value
['revision'] = $revision;
1641 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1642 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1644 # Promote user to any groups they meet the criteria for
1645 $user->addAutopromoteOnceGroups( 'onEdit' );
1647 wfProfileOut( __METHOD__
);
1652 * Get parser options suitable for rendering the primary article wikitext
1654 * @param IContextSource|User|string $context One of the following:
1655 * - IContextSource: Use the User and the Language of the provided
1657 * - User: Use the provided User object and $wgLang for the language,
1658 * so use an IContextSource object if possible.
1659 * - 'canonical': Canonical options (anonymous user with default
1660 * preferences and content language).
1661 * @return ParserOptions
1663 public function makeParserOptions( $context ) {
1666 if ( $context instanceof IContextSource
) {
1667 $options = ParserOptions
::newFromContext( $context );
1668 } elseif ( $context instanceof User
) { // settings per user (even anons)
1669 $options = ParserOptions
::newFromUser( $context );
1670 } else { // canonical settings
1671 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1674 if ( $this->getTitle()->isConversionTable() ) {
1675 $options->disableContentConversion();
1678 $options->enableLimitReport(); // show inclusion/loop reports
1679 $options->setTidy( true ); // fix bad HTML
1685 * Prepare text which is about to be saved.
1686 * Returns a stdclass with source, pst and output members
1687 * @return bool|object
1689 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1690 global $wgParser, $wgContLang, $wgUser;
1691 $user = is_null( $user ) ?
$wgUser : $user;
1692 // @TODO fixme: check $user->getId() here???
1693 if ( $this->mPreparedEdit
1694 && $this->mPreparedEdit
->newText
== $text
1695 && $this->mPreparedEdit
->revid
== $revid
1698 return $this->mPreparedEdit
;
1701 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1702 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1704 $edit = (object)array();
1705 $edit->revid
= $revid;
1706 $edit->newText
= $text;
1707 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1708 $edit->popts
= $this->makeParserOptions( 'canonical' );
1709 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1710 $edit->oldText
= $this->getRawText();
1712 $this->mPreparedEdit
= $edit;
1718 * Do standard deferred updates after page edit.
1719 * Update links tables, site stats, search index and message cache.
1720 * Purges pages that include this page if the text was changed here.
1721 * Every 100th edit, prune the recent changes table.
1724 * @param $revision Revision object
1725 * @param $user User object that did the revision
1726 * @param $options Array of options, following indexes are used:
1727 * - changed: boolean, whether the revision changed the content (default true)
1728 * - created: boolean, whether the revision created the page (default false)
1729 * - oldcountable: boolean or null (default null):
1730 * - boolean: whether the page was counted as an article before that
1731 * revision, only used in changed is true and created is false
1732 * - null: don't change the article count
1734 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1735 global $wgEnableParserCache;
1737 wfProfileIn( __METHOD__
);
1739 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1740 $text = $revision->getText();
1743 # Be careful not to double-PST: $text is usually already PST-ed once
1744 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1745 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1746 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1748 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1749 $editInfo = $this->mPreparedEdit
;
1752 # Save it to the parser cache
1753 if ( $wgEnableParserCache ) {
1754 $parserCache = ParserCache
::singleton();
1755 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1758 # Update the links tables and other secondary data
1759 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->mTitle
);
1760 DataUpdate
::runUpdates( $updates );
1762 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1764 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1765 if ( 0 == mt_rand( 0, 99 ) ) {
1766 // Flush old entries from the `recentchanges` table; we do this on
1767 // random requests so as to avoid an increase in writes for no good reason
1770 $dbw = wfGetDB( DB_MASTER
);
1771 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1774 array( "rc_timestamp < '$cutoff'" ),
1780 if ( !$this->mTitle
->exists() ) {
1781 wfProfileOut( __METHOD__
);
1785 $id = $this->getId();
1786 $title = $this->mTitle
->getPrefixedDBkey();
1787 $shortTitle = $this->mTitle
->getDBkey();
1789 if ( !$options['changed'] ) {
1792 } elseif ( $options['created'] ) {
1793 $good = (int)$this->isCountable( $editInfo );
1795 } elseif ( $options['oldcountable'] !== null ) {
1796 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1803 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1804 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1806 # If this is another user's talk page, update newtalk.
1807 # Don't do this if $options['changed'] = false (null-edits) nor if
1808 # it's a minor edit and the user doesn't want notifications for those.
1809 if ( $options['changed']
1810 && $this->mTitle
->getNamespace() == NS_USER_TALK
1811 && $shortTitle != $user->getTitleKey()
1812 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1814 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1815 $other = User
::newFromName( $shortTitle, false );
1817 wfDebug( __METHOD__
. ": invalid username\n" );
1818 } elseif ( User
::isIP( $shortTitle ) ) {
1819 // An anonymous user
1820 $other->setNewtalk( true, $revision );
1821 } elseif ( $other->isLoggedIn() ) {
1822 $other->setNewtalk( true, $revision );
1824 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1829 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1830 MessageCache
::singleton()->replace( $shortTitle, $text );
1833 if( $options['created'] ) {
1834 self
::onArticleCreate( $this->mTitle
);
1836 self
::onArticleEdit( $this->mTitle
);
1839 wfProfileOut( __METHOD__
);
1843 * Edit an article without doing all that other stuff
1844 * The article must already exist; link tables etc
1845 * are not updated, caches are not flushed.
1847 * @param $text String: text submitted
1848 * @param $user User The relevant user
1849 * @param $comment String: comment submitted
1850 * @param $minor Boolean: whereas it's a minor modification
1852 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1853 wfProfileIn( __METHOD__
);
1855 $dbw = wfGetDB( DB_MASTER
);
1856 $revision = new Revision( array(
1857 'page' => $this->getId(),
1859 'comment' => $comment,
1860 'minor_edit' => $minor ?
1 : 0,
1862 $revision->insertOn( $dbw );
1863 $this->updateRevisionOn( $dbw, $revision );
1865 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1867 wfProfileOut( __METHOD__
);
1871 * Update the article's restriction field, and leave a log entry.
1872 * This works for protection both existing and non-existing pages.
1874 * @param $limit Array: set of restriction keys
1875 * @param $reason String
1876 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1877 * @param $expiry Array: per restriction type expiration
1878 * @param $user User The user updating the restrictions
1881 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1884 if ( wfReadOnly() ) {
1885 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1888 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1890 $id = $this->mTitle
->getArticleID();
1896 // Take this opportunity to purge out expired restrictions
1897 Title
::purgeExpiredRestrictions();
1899 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1900 # we expect a single selection, but the schema allows otherwise.
1901 $isProtected = false;
1905 $dbw = wfGetDB( DB_MASTER
);
1907 foreach ( $restrictionTypes as $action ) {
1908 if ( !isset( $expiry[$action] ) ) {
1909 $expiry[$action] = $dbw->getInfinity();
1911 if ( !isset( $limit[$action] ) ) {
1912 $limit[$action] = '';
1913 } elseif ( $limit[$action] != '' ) {
1917 # Get current restrictions on $action
1918 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1919 if ( $current != '' ) {
1920 $isProtected = true;
1923 if ( $limit[$action] != $current ) {
1925 } elseif ( $limit[$action] != '' ) {
1926 # Only check expiry change if the action is actually being
1927 # protected, since expiry does nothing on an not-protected
1929 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1935 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1939 # If nothing's changed, do nothing
1941 return Status
::newGood();
1944 if ( !$protect ) { # No protection at all means unprotection
1945 $revCommentMsg = 'unprotectedarticle';
1946 $logAction = 'unprotect';
1947 } elseif ( $isProtected ) {
1948 $revCommentMsg = 'modifiedarticleprotection';
1949 $logAction = 'modify';
1951 $revCommentMsg = 'protectedarticle';
1952 $logAction = 'protect';
1955 $encodedExpiry = array();
1956 $protectDescription = '';
1957 foreach ( $limit as $action => $restrictions ) {
1958 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1959 if ( $restrictions != '' ) {
1960 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1961 if ( $encodedExpiry[$action] != 'infinity' ) {
1962 $protectDescription .= wfMessage(
1964 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1965 $wgContLang->date( $expiry[$action], false, false ) ,
1966 $wgContLang->time( $expiry[$action], false, false )
1967 )->inContentLanguage()->text();
1969 $protectDescription .= wfMessage( 'protect-expiry-indefinite' )
1970 ->inContentLanguage()->text();
1973 $protectDescription .= ') ';
1976 $protectDescription = trim( $protectDescription );
1978 if ( $id ) { # Protection of existing page
1979 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1980 return Status
::newGood();
1983 # Only restrictions with the 'protect' right can cascade...
1984 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1985 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1987 # The schema allows multiple restrictions
1988 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1992 # Update restrictions table
1993 foreach ( $limit as $action => $restrictions ) {
1994 if ( $restrictions != '' ) {
1995 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1996 array( 'pr_page' => $id,
1997 'pr_type' => $action,
1998 'pr_level' => $restrictions,
1999 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2000 'pr_expiry' => $encodedExpiry[$action]
2005 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2006 'pr_type' => $action ), __METHOD__
);
2010 # Prepare a null revision to be added to the history
2011 $editComment = $wgContLang->ucfirst(
2014 $this->mTitle
->getPrefixedText()
2015 )->inContentLanguage()->text()
2018 $editComment .= ": $reason";
2020 if ( $protectDescription ) {
2021 $editComment .= " ($protectDescription)";
2024 // FIXME: Should use 'brackets' message.
2025 $editComment .= ' [' . wfMessage( 'protect-summary-cascade' )
2026 ->inContentLanguage()->text() . ']';
2029 # Insert a null revision
2030 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2031 $nullRevId = $nullRevision->insertOn( $dbw );
2033 $latest = $this->getLatest();
2034 # Update page record
2035 $dbw->update( 'page',
2037 'page_touched' => $dbw->timestamp(),
2038 'page_restrictions' => '',
2039 'page_latest' => $nullRevId
2040 ), array( /* WHERE */
2045 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2046 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2047 } else { # Protection of non-existing page (also known as "title protection")
2048 # Cascade protection is meaningless in this case
2051 if ( $limit['create'] != '' ) {
2052 $dbw->replace( 'protected_titles',
2053 array( array( 'pt_namespace', 'pt_title' ) ),
2055 'pt_namespace' => $this->mTitle
->getNamespace(),
2056 'pt_title' => $this->mTitle
->getDBkey(),
2057 'pt_create_perm' => $limit['create'],
2058 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2059 'pt_expiry' => $encodedExpiry['create'],
2060 'pt_user' => $user->getId(),
2061 'pt_reason' => $reason,
2065 $dbw->delete( 'protected_titles',
2067 'pt_namespace' => $this->mTitle
->getNamespace(),
2068 'pt_title' => $this->mTitle
->getDBkey()
2074 $this->mTitle
->flushRestrictions();
2076 if ( $logAction == 'unprotect' ) {
2077 $logParams = array();
2079 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2082 # Update the protection log
2083 $log = new LogPage( 'protect' );
2084 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2086 return Status
::newGood();
2090 * Take an array of page restrictions and flatten it to a string
2091 * suitable for insertion into the page_restrictions field.
2092 * @param $limit Array
2093 * @throws MWException
2096 protected static function flattenRestrictions( $limit ) {
2097 if ( !is_array( $limit ) ) {
2098 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2104 foreach ( $limit as $action => $restrictions ) {
2105 if ( $restrictions != '' ) {
2106 $bits[] = "$action=$restrictions";
2110 return implode( ':', $bits );
2114 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2115 * backwards compatibility, if you care about error reporting you should use
2116 * doDeleteArticleReal() instead.
2118 * Deletes the article with database consistency, writes logs, purges caches
2120 * @param $reason string delete reason for deletion log
2121 * @param $suppress boolean suppress all revisions and log the deletion in
2122 * the suppression log instead of the deletion log
2123 * @param $id int article ID
2124 * @param $commit boolean defaults to true, triggers transaction end
2125 * @param &$error Array of errors to append to
2126 * @param $user User The deleting user
2127 * @return boolean true if successful
2129 public function doDeleteArticle(
2130 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2132 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2133 return $status->isGood();
2137 * Back-end article deletion
2138 * Deletes the article with database consistency, writes logs, purges caches
2142 * @param $reason string delete reason for deletion log
2143 * @param $suppress boolean suppress all revisions and log the deletion in
2144 * the suppression log instead of the deletion log
2145 * @param $commit boolean defaults to true, triggers transaction end
2146 * @param &$error Array of errors to append to
2147 * @param $user User The deleting user
2148 * @return Status: Status object; if successful, $status->value is the log_id of the
2149 * deletion log entry. If the page couldn't be deleted because it wasn't
2150 * found, $status is a non-fatal 'cannotdelete' error
2152 public function doDeleteArticleReal(
2153 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2157 wfDebug( __METHOD__
. "\n" );
2159 $status = Status
::newGood();
2161 if ( $this->mTitle
->getDBkey() === '' ) {
2162 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2166 $user = is_null( $user ) ?
$wgUser : $user;
2167 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2168 if ( $status->isOK() ) {
2169 // Hook aborted but didn't set a fatal status
2170 $status->fatal( 'delete-hook-aborted' );
2176 $this->loadPageData( 'forupdate' );
2177 $id = $this->getID();
2179 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2184 // Bitfields to further suppress the content
2187 // This should be 15...
2188 $bitfield |
= Revision
::DELETED_TEXT
;
2189 $bitfield |
= Revision
::DELETED_COMMENT
;
2190 $bitfield |
= Revision
::DELETED_USER
;
2191 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2193 $bitfield = 'rev_deleted';
2196 $dbw = wfGetDB( DB_MASTER
);
2197 $dbw->begin( __METHOD__
);
2198 // For now, shunt the revision data into the archive table.
2199 // Text is *not* removed from the text table; bulk storage
2200 // is left intact to avoid breaking block-compression or
2201 // immutable storage schemes.
2203 // For backwards compatibility, note that some older archive
2204 // table entries will have ar_text and ar_flags fields still.
2206 // In the future, we may keep revisions and mark them with
2207 // the rev_deleted field, which is reserved for this purpose.
2208 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2210 'ar_namespace' => 'page_namespace',
2211 'ar_title' => 'page_title',
2212 'ar_comment' => 'rev_comment',
2213 'ar_user' => 'rev_user',
2214 'ar_user_text' => 'rev_user_text',
2215 'ar_timestamp' => 'rev_timestamp',
2216 'ar_minor_edit' => 'rev_minor_edit',
2217 'ar_rev_id' => 'rev_id',
2218 'ar_parent_id' => 'rev_parent_id',
2219 'ar_text_id' => 'rev_text_id',
2220 'ar_text' => '\'\'', // Be explicit to appease
2221 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2222 'ar_len' => 'rev_len',
2223 'ar_page_id' => 'page_id',
2224 'ar_deleted' => $bitfield,
2225 'ar_sha1' => 'rev_sha1'
2228 'page_id = rev_page'
2232 # Now that it's safely backed up, delete it
2233 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2234 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2237 $dbw->rollback( __METHOD__
);
2238 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2242 $this->doDeleteUpdates( $id );
2244 # Log the deletion, if the page was suppressed, log it at Oversight instead
2245 $logtype = $suppress ?
'suppress' : 'delete';
2247 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2248 $logEntry->setPerformer( $user );
2249 $logEntry->setTarget( $this->mTitle
);
2250 $logEntry->setComment( $reason );
2251 $logid = $logEntry->insert();
2252 $logEntry->publish( $logid );
2255 $dbw->commit( __METHOD__
);
2258 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2259 $status->value
= $logid;
2264 * Do some database updates after deletion
2266 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2268 public function doDeleteUpdates( $id ) {
2269 # update site status
2270 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2272 # remove secondary indexes, etc
2273 $updates = $this->getDeletionUpdates( );
2274 DataUpdate
::runUpdates( $updates );
2277 WikiPage
::onArticleDelete( $this->mTitle
);
2282 # Clear the cached article id so the interface doesn't act like we exist
2283 $this->mTitle
->resetArticleID( 0 );
2286 public function getDeletionUpdates() {
2288 new LinksDeletionUpdate( $this ),
2291 //@todo: make a hook to add update objects
2292 //NOTE: deletion updates will be determined by the ContentHandler in the future
2297 * Roll back the most recent consecutive set of edits to a page
2298 * from the same user; fails if there are no eligible edits to
2299 * roll back to, e.g. user is the sole contributor. This function
2300 * performs permissions checks on $user, then calls commitRollback()
2301 * to do the dirty work
2303 * @todo: seperate the business/permission stuff out from backend code
2305 * @param $fromP String: Name of the user whose edits to rollback.
2306 * @param $summary String: Custom summary. Set to default summary if empty.
2307 * @param $token String: Rollback token.
2308 * @param $bot Boolean: If true, mark all reverted edits as bot.
2310 * @param $resultDetails Array: contains result-specific array of additional values
2311 * 'alreadyrolled' : 'current' (rev)
2312 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2314 * @param $user User The user performing the rollback
2315 * @return array of errors, each error formatted as
2316 * array(messagekey, param1, param2, ...).
2317 * On success, the array is empty. This array can also be passed to
2318 * OutputPage::showPermissionsErrorPage().
2320 public function doRollback(
2321 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2323 $resultDetails = null;
2326 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2327 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2328 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2330 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2331 $errors[] = array( 'sessionfailure' );
2334 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2335 $errors[] = array( 'actionthrottledtext' );
2338 # If there were errors, bail out now
2339 if ( !empty( $errors ) ) {
2343 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2347 * Backend implementation of doRollback(), please refer there for parameter
2348 * and return value documentation
2350 * NOTE: This function does NOT check ANY permissions, it just commits the
2351 * rollback to the DB. Therefore, you should only call this function direct-
2352 * ly if you want to use custom permissions checks. If you don't, use
2353 * doRollback() instead.
2354 * @param $fromP String: Name of the user whose edits to rollback.
2355 * @param $summary String: Custom summary. Set to default summary if empty.
2356 * @param $bot Boolean: If true, mark all reverted edits as bot.
2358 * @param $resultDetails Array: contains result-specific array of additional values
2359 * @param $guser User The user performing the rollback
2362 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2363 global $wgUseRCPatrol, $wgContLang;
2365 $dbw = wfGetDB( DB_MASTER
);
2367 if ( wfReadOnly() ) {
2368 return array( array( 'readonlytext' ) );
2371 # Get the last editor
2372 $current = $this->getRevision();
2373 if ( is_null( $current ) ) {
2374 # Something wrong... no page?
2375 return array( array( 'notanarticle' ) );
2378 $from = str_replace( '_', ' ', $fromP );
2379 # User name given should match up with the top revision.
2380 # If the user was deleted then $from should be empty.
2381 if ( $from != $current->getUserText() ) {
2382 $resultDetails = array( 'current' => $current );
2383 return array( array( 'alreadyrolled',
2384 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2385 htmlspecialchars( $fromP ),
2386 htmlspecialchars( $current->getUserText() )
2390 # Get the last edit not by this guy...
2391 # Note: these may not be public values
2392 $user = intval( $current->getRawUser() );
2393 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2394 $s = $dbw->selectRow( 'revision',
2395 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2396 array( 'rev_page' => $current->getPage(),
2397 "rev_user != {$user} OR rev_user_text != {$user_text}"
2399 array( 'USE INDEX' => 'page_timestamp',
2400 'ORDER BY' => 'rev_timestamp DESC' )
2402 if ( $s === false ) {
2403 # No one else ever edited this page
2404 return array( array( 'cantrollback' ) );
2405 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2406 # Only admins can see this text
2407 return array( array( 'notvisiblerev' ) );
2411 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2412 # Mark all reverted edits as bot
2416 if ( $wgUseRCPatrol ) {
2417 # Mark all reverted edits as patrolled
2418 $set['rc_patrolled'] = 1;
2421 if ( count( $set ) ) {
2422 $dbw->update( 'recentchanges', $set,
2424 'rc_cur_id' => $current->getPage(),
2425 'rc_user_text' => $current->getUserText(),
2426 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2431 # Generate the edit summary if necessary
2432 $target = Revision
::newFromId( $s->rev_id
);
2433 if ( empty( $summary ) ) {
2434 if ( $from == '' ) { // no public user name
2435 $summary = wfMessage( 'revertpage-nouser' );
2437 $summary = wfMessage( 'revertpage' );
2441 # Allow the custom summary to use the same args as the default message
2443 $target->getUserText(), $from, $s->rev_id
,
2444 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2445 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2447 if( $summary instanceof Message
) {
2448 $summary = $summary->params( $args )->inContentLanguage()->text();
2450 $summary = wfMsgReplaceArgs( $summary, $args );
2453 # Truncate for whole multibyte characters.
2454 $summary = $wgContLang->truncate( $summary, 255 );
2457 $flags = EDIT_UPDATE
;
2459 if ( $guser->isAllowed( 'minoredit' ) ) {
2460 $flags |
= EDIT_MINOR
;
2463 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2464 $flags |
= EDIT_FORCE_BOT
;
2467 # Actually store the edit
2468 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2469 if ( !empty( $status->value
['revision'] ) ) {
2470 $revId = $status->value
['revision']->getId();
2475 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2477 $resultDetails = array(
2478 'summary' => $summary,
2479 'current' => $current,
2480 'target' => $target,
2488 * The onArticle*() functions are supposed to be a kind of hooks
2489 * which should be called whenever any of the specified actions
2492 * This is a good place to put code to clear caches, for instance.
2494 * This is called on page move and undelete, as well as edit
2496 * @param $title Title object
2498 public static function onArticleCreate( $title ) {
2499 # Update existence markers on article/talk tabs...
2500 if ( $title->isTalkPage() ) {
2501 $other = $title->getSubjectPage();
2503 $other = $title->getTalkPage();
2506 $other->invalidateCache();
2507 $other->purgeSquid();
2509 $title->touchLinks();
2510 $title->purgeSquid();
2511 $title->deleteTitleProtection();
2515 * Clears caches when article is deleted
2517 * @param $title Title
2519 public static function onArticleDelete( $title ) {
2520 # Update existence markers on article/talk tabs...
2521 if ( $title->isTalkPage() ) {
2522 $other = $title->getSubjectPage();
2524 $other = $title->getTalkPage();
2527 $other->invalidateCache();
2528 $other->purgeSquid();
2530 $title->touchLinks();
2531 $title->purgeSquid();
2534 HTMLFileCache
::clearFileCache( $title );
2537 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2538 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2542 if ( $title->getNamespace() == NS_FILE
) {
2543 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2544 $update->doUpdate();
2548 if ( $title->getNamespace() == NS_USER_TALK
) {
2549 $user = User
::newFromName( $title->getText(), false );
2551 $user->setNewtalk( false );
2556 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2560 * Purge caches on page update etc
2562 * @param $title Title object
2563 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2565 public static function onArticleEdit( $title ) {
2566 // Invalidate caches of articles which include this page
2567 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2570 // Invalidate the caches of all pages which redirect here
2571 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2573 # Purge squid for this page only
2574 $title->purgeSquid();
2576 # Clear file cache for this page only
2577 HTMLFileCache
::clearFileCache( $title );
2583 * Returns a list of hidden categories this page is a member of.
2584 * Uses the page_props and categorylinks tables.
2586 * @return Array of Title objects
2588 public function getHiddenCategories() {
2590 $id = $this->mTitle
->getArticleID();
2596 $dbr = wfGetDB( DB_SLAVE
);
2597 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2599 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2600 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2603 if ( $res !== false ) {
2604 foreach ( $res as $row ) {
2605 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2613 * Return an applicable autosummary if one exists for the given edit.
2614 * @param $oldtext String: the previous text of the page.
2615 * @param $newtext String: The submitted text of the page.
2616 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2617 * @return string An appropriate autosummary, or an empty string.
2619 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2622 # Decide what kind of autosummary is needed.
2624 # Redirect autosummaries
2625 $ot = Title
::newFromRedirect( $oldtext );
2626 $rt = Title
::newFromRedirect( $newtext );
2628 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2629 $truncatedtext = $wgContLang->truncate(
2630 str_replace( "\n", ' ', $newtext ),
2632 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
2633 - strlen( $rt->getFullText() )
2635 return wfMessage( 'autoredircomment', $rt->getFullText() )
2636 ->rawParams( $truncatedtext )->inContentLanguage()->text();
2639 # New page autosummaries
2640 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2641 # If they're making a new article, give its text, truncated, in the summary.
2643 $truncatedtext = $wgContLang->truncate(
2644 str_replace( "\n", ' ', $newtext ),
2645 max( 0, 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) ) );
2647 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
2648 ->inContentLanguage()->text();
2651 # Blanking autosummaries
2652 if ( $oldtext != '' && $newtext == '' ) {
2653 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
2654 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2655 # Removing more than 90% of the article
2657 $truncatedtext = $wgContLang->truncate(
2659 max( 0, 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) ) );
2661 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
2662 ->inContentLanguage()->text();
2665 # If we reach this point, there's no applicable autosummary for our case, so our
2666 # autosummary is empty.
2671 * Auto-generates a deletion reason
2673 * @param &$hasHistory Boolean: whether the page has a history
2674 * @return mixed String containing deletion reason or empty string, or boolean false
2675 * if no revision occurred
2677 public function getAutoDeleteReason( &$hasHistory ) {
2680 // Get the last revision
2681 $rev = $this->getRevision();
2683 if ( is_null( $rev ) ) {
2687 // Get the article's contents
2688 $contents = $rev->getText();
2691 // If the page is blank, use the text from the previous revision,
2692 // which can only be blank if there's a move/import/protect dummy revision involved
2693 if ( $contents == '' ) {
2694 $prev = $rev->getPrevious();
2697 $contents = $prev->getText();
2702 $dbw = wfGetDB( DB_MASTER
);
2704 // Find out if there was only one contributor
2705 // Only scan the last 20 revisions
2706 $res = $dbw->select( 'revision', 'rev_user_text',
2707 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2709 array( 'LIMIT' => 20 )
2712 if ( $res === false ) {
2713 // This page has no revisions, which is very weird
2717 $hasHistory = ( $res->numRows() > 1 );
2718 $row = $dbw->fetchObject( $res );
2720 if ( $row ) { // $row is false if the only contributor is hidden
2721 $onlyAuthor = $row->rev_user_text
;
2722 // Try to find a second contributor
2723 foreach ( $res as $row ) {
2724 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2725 $onlyAuthor = false;
2730 $onlyAuthor = false;
2733 // Generate the summary with a '$1' placeholder
2735 // The current revision is blank and the one before is also
2736 // blank. It's just not our lucky day
2737 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
2739 if ( $onlyAuthor ) {
2740 $reason = wfMessage(
2744 )->inContentLanguage()->text();
2746 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
2750 if ( $reason == '-' ) {
2751 // Allow these UI messages to be blanked out cleanly
2755 // Replace newlines with spaces to prevent uglyness
2756 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2757 // Calculate the maximum amount of chars to get
2758 // Max content length = max comment length - length of the comment (excl. $1)
2759 $maxLength = 255 - ( strlen( $reason ) - 2 );
2760 $contents = $wgContLang->truncate( $contents, $maxLength );
2761 // Remove possible unfinished links
2762 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2763 // Now replace the '$1' placeholder
2764 $reason = str_replace( '$1', $contents, $reason );
2770 * Update all the appropriate counts in the category table, given that
2771 * we've added the categories $added and deleted the categories $deleted.
2773 * @param $added array The names of categories that were added
2774 * @param $deleted array The names of categories that were deleted
2776 public function updateCategoryCounts( $added, $deleted ) {
2777 $ns = $this->mTitle
->getNamespace();
2778 $dbw = wfGetDB( DB_MASTER
);
2780 # First make sure the rows exist. If one of the "deleted" ones didn't
2781 # exist, we might legitimately not create it, but it's simpler to just
2782 # create it and then give it a negative value, since the value is bogus
2785 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2786 $insertCats = array_merge( $added, $deleted );
2787 if ( !$insertCats ) {
2788 # Okay, nothing to do
2792 $insertRows = array();
2794 foreach ( $insertCats as $cat ) {
2795 $insertRows[] = array(
2796 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2800 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2802 $addFields = array( 'cat_pages = cat_pages + 1' );
2803 $removeFields = array( 'cat_pages = cat_pages - 1' );
2805 if ( $ns == NS_CATEGORY
) {
2806 $addFields[] = 'cat_subcats = cat_subcats + 1';
2807 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2808 } elseif ( $ns == NS_FILE
) {
2809 $addFields[] = 'cat_files = cat_files + 1';
2810 $removeFields[] = 'cat_files = cat_files - 1';
2817 array( 'cat_title' => $added ),
2826 array( 'cat_title' => $deleted ),
2833 * Updates cascading protections
2835 * @param $parserOutput ParserOutput object for the current version
2837 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2838 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2842 // templatelinks table may have become out of sync,
2843 // especially if using variable-based transclusions.
2844 // For paranoia, check if things have changed and if
2845 // so apply updates to the database. This will ensure
2846 // that cascaded protections apply as soon as the changes
2849 # Get templates from templatelinks
2850 $id = $this->mTitle
->getArticleID();
2852 $tlTemplates = array();
2854 $dbr = wfGetDB( DB_SLAVE
);
2855 $res = $dbr->select( array( 'templatelinks' ),
2856 array( 'tl_namespace', 'tl_title' ),
2857 array( 'tl_from' => $id ),
2861 foreach ( $res as $row ) {
2862 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2865 # Get templates from parser output.
2866 $poTemplates = array();
2867 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2868 foreach ( $templates as $dbk => $id ) {
2869 $poTemplates["$ns:$dbk"] = true;
2874 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2876 if ( count( $templates_diff ) > 0 ) {
2877 # Whee, link updates time.
2878 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
2879 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2885 * Return a list of templates used by this article.
2886 * Uses the templatelinks table
2888 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2889 * @return Array of Title objects
2891 public function getUsedTemplates() {
2892 return $this->mTitle
->getTemplateLinksFrom();
2896 * Perform article updates on a special page creation.
2898 * @param $rev Revision object
2900 * @todo This is a shitty interface function. Kill it and replace the
2901 * other shitty functions like doEditUpdates and such so it's not needed
2903 * @deprecated since 1.18, use doEditUpdates()
2905 public function createUpdates( $rev ) {
2906 wfDeprecated( __METHOD__
, '1.18' );
2908 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2912 * This function is called right before saving the wikitext,
2913 * so we can do things like signatures and links-in-context.
2915 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2916 * @param $text String article contents
2917 * @param $user User object: user doing the edit
2918 * @param $popts ParserOptions object: parser options, default options for
2919 * the user loaded if null given
2920 * @return string article contents with altered wikitext markup (signatures
2921 * converted, {{subst:}}, templates, etc.)
2923 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2924 global $wgParser, $wgUser;
2926 wfDeprecated( __METHOD__
, '1.19' );
2928 $user = is_null( $user ) ?
$wgUser : $user;
2930 if ( $popts === null ) {
2931 $popts = ParserOptions
::newFromUser( $user );
2934 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2938 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2940 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2943 public function isBigDeletion() {
2944 wfDeprecated( __METHOD__
, '1.19' );
2945 return $this->mTitle
->isBigDeletion();
2949 * Get the approximate revision count of this page.
2951 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2954 public function estimateRevisionCount() {
2955 wfDeprecated( __METHOD__
, '1.19' );
2956 return $this->mTitle
->estimateRevisionCount();
2960 * Update the article's restriction field, and leave a log entry.
2962 * @deprecated since 1.19
2963 * @param $limit Array: set of restriction keys
2964 * @param $reason String
2965 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2966 * @param $expiry Array: per restriction type expiration
2967 * @param $user User The user updating the restrictions
2968 * @return bool true on success
2970 public function updateRestrictions(
2971 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2975 $user = is_null( $user ) ?
$wgUser : $user;
2977 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2981 * @deprecated since 1.18
2983 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2984 wfDeprecated( __METHOD__
, '1.18' );
2986 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2990 * @deprecated since 1.18
2992 public function viewUpdates() {
2993 wfDeprecated( __METHOD__
, '1.18' );
2995 return $this->doViewUpdates( $wgUser );
2999 * @deprecated since 1.18
3003 public function useParserCache( $oldid ) {
3004 wfDeprecated( __METHOD__
, '1.18' );
3006 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3010 class PoolWorkArticleView
extends PoolCounterWork
{
3028 * @var ParserOptions
3030 private $parserOptions;
3038 * @var ParserOutput|bool
3040 private $parserOutput = false;
3045 private $isDirty = false;
3050 private $error = false;
3056 * @param $revid Integer: ID of the revision being parsed
3057 * @param $useParserCache Boolean: whether to use the parser cache
3058 * @param $parserOptions parserOptions to use for the parse operation
3059 * @param $text String: text to parse or null to load it
3061 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
3062 $this->page
= $page;
3063 $this->revid
= $revid;
3064 $this->cacheable
= $useParserCache;
3065 $this->parserOptions
= $parserOptions;
3066 $this->text
= $text;
3067 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3068 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3072 * Get the ParserOutput from this object, or false in case of failure
3074 * @return ParserOutput
3076 public function getParserOutput() {
3077 return $this->parserOutput
;
3081 * Get whether the ParserOutput is a dirty one (i.e. expired)
3085 public function getIsDirty() {
3086 return $this->isDirty
;
3090 * Get a Status object in case of error or false otherwise
3092 * @return Status|bool
3094 public function getError() {
3095 return $this->error
;
3102 global $wgParser, $wgUseFileCache;
3104 $isCurrent = $this->revid
=== $this->page
->getLatest();
3106 if ( $this->text
!== null ) {
3107 $text = $this->text
;
3108 } elseif ( $isCurrent ) {
3109 $text = $this->page
->getRawText();
3111 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3112 if ( $rev === null ) {
3115 $text = $rev->getText();
3118 $time = - microtime( true );
3119 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
3120 $this->parserOptions
, true, true, $this->revid
);
3121 $time +
= microtime( true );
3125 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3126 $this->page
->getTitle()->getPrefixedDBkey() ) );
3129 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3130 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3133 // Make sure file cache is not used on uncacheable content.
3134 // Output that has magic words in it can still use the parser cache
3135 // (if enabled), though it will generally expire sooner.
3136 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3137 $wgUseFileCache = false;
3141 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3150 function getCachedWork() {
3151 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3153 if ( $this->parserOutput
=== false ) {
3154 wfDebug( __METHOD__
. ": parser cache miss\n" );
3157 wfDebug( __METHOD__
. ": parser cache hit\n" );
3165 function fallback() {
3166 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3168 if ( $this->parserOutput
=== false ) {
3169 wfDebugLog( 'dirty', "dirty missing\n" );
3170 wfDebug( __METHOD__
. ": no dirty cache\n" );
3173 wfDebug( __METHOD__
. ": sending dirty output\n" );
3174 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3175 $this->isDirty
= true;
3181 * @param $status Status
3184 function error( $status ) {
3185 $this->error
= $status;