3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
8 * Class representing a MediaWiki article and history.
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
13 * @internal documentation reviewed 15 Mar 2010
15 class WikiPage
extends Page
{
16 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
17 // values greater than zero indicate that there were problems not resulting in page
21 * Delete operation aborted by hook
23 const DELETE_HOOK_ABORTED
= -1;
28 const DELETE_SUCCESS
= 0;
33 const DELETE_NO_PAGE
= 1;
36 * No revisions found to delete
38 const DELETE_NO_REVISIONS
= 2;
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 public $mPreparedEdit = false; // !< Array
57 protected $mRedirectTarget = null;
62 protected $mLastRevision = null;
65 * @var string; timestamp of the current revision or empty string if not loaded
67 protected $mTimestamp = '';
72 protected $mTouched = '19700101000000';
77 protected $mCounter = null;
80 * Constructor and clear the article
81 * @param $title Title Reference to a Title object.
83 public function __construct( Title
$title ) {
84 $this->mTitle
= $title;
88 * Create a WikiPage object of the appropriate class for the given title.
91 * @return WikiPage object of the appropriate type
93 public static function factory( Title
$title ) {
94 $ns = $title->getNamespace();
96 if ( $ns == NS_MEDIA
) {
97 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
98 } elseif ( $ns < 0 ) {
99 throw new MWException( "Invalid or virtual namespace $ns given." );
104 $page = new WikiFilePage( $title );
107 $page = new WikiCategoryPage( $title );
110 $page = new WikiPage( $title );
117 * Constructor from a page id
119 * @param $id Int article ID to load
121 * @return WikiPage|null
123 public static function newFromID( $id ) {
124 $t = Title
::newFromID( $id );
126 return self
::factory( $t );
132 * Returns overrides for action handlers.
133 * Classes listed here will be used instead of the default one when
134 * (and only when) $wgActions[$action] === true. This allows subclasses
135 * to override the default behavior.
137 * @todo: move this UI stuff somewhere else
141 public function getActionOverrides() {
142 $content_handler = $this->getContentHandler();
143 return $content_handler->getActionOverrides();
147 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
149 * Shorthand for ContentHandler::getForModelName( $this->getContentModelName() );
151 * @return ContentHandler
153 public function getContentHandler() {
154 return ContentHandler
::getForModelName( $this->getContentModelName() );
158 * Get the title object of the article
159 * @return Title object of this page
161 public function getTitle() {
162 return $this->mTitle
;
168 public function clear() {
169 $this->mDataLoaded
= false;
171 $this->mCounter
= null;
172 $this->mRedirectTarget
= null; # Title object if set
173 $this->mLastRevision
= null; # Latest revision
174 $this->mTouched
= '19700101000000';
175 $this->mTimestamp
= '';
176 $this->mIsRedirect
= false;
177 $this->mLatest
= false;
178 $this->mPreparedEdit
= false;
182 * Return the list of revision fields that should be selected to create
187 public static function selectFields() {
200 'page_content_model',
205 * Fetch a page record with the given conditions
206 * @param $dbr DatabaseBase object
207 * @param $conditions Array
208 * @return mixed Database result resource, or false on failure
210 protected function pageData( $dbr, $conditions ) {
211 $fields = self
::selectFields();
213 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
215 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
217 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
223 * Fetch a page record matching the Title object's namespace and title
224 * using a sanitized title string
226 * @param $dbr DatabaseBase object
227 * @param $title Title object
228 * @return mixed Database result resource, or false on failure
230 public function pageDataFromTitle( $dbr, $title ) {
231 return $this->pageData( $dbr, array(
232 'page_namespace' => $title->getNamespace(),
233 'page_title' => $title->getDBkey() ) );
237 * Fetch a page record matching the requested ID
239 * @param $dbr DatabaseBase
241 * @return mixed Database result resource, or false on failure
243 public function pageDataFromId( $dbr, $id ) {
244 return $this->pageData( $dbr, array( 'page_id' => $id ) );
248 * Set the general counter, title etc data loaded from
251 * @param $data Object|String One of the following:
252 * A DB query result object or...
253 * "fromdb" to get from a slave DB or...
254 * "fromdbmaster" to get from the master DB
257 public function loadPageData( $data = 'fromdb' ) {
258 if ( $data === 'fromdbmaster' ) {
259 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
260 } elseif ( $data === 'fromdb' ) { // slave
261 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
262 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
263 # Note that DB also stores the master position in the session and checks it.
264 $touched = $this->getCachedLastEditTime();
265 if ( $touched ) { // key set
266 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
267 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
272 $lc = LinkCache
::singleton();
275 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
277 $this->mTitle
->loadFromRow( $data );
279 # Old-fashioned restrictions
280 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
282 $this->mCounter
= intval( $data->page_counter
);
283 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
284 $this->mIsRedirect
= intval( $data->page_is_redirect
);
285 $this->mLatest
= intval( $data->page_latest
);
287 $lc->addBadLinkObj( $this->mTitle
);
289 $this->mTitle
->loadFromRow( false );
292 $this->mDataLoaded
= true;
296 * @return int Page ID
298 public function getId() {
299 return $this->mTitle
->getArticleID();
303 * @return bool Whether or not the page exists in the database
305 public function exists() {
306 return $this->mTitle
->exists();
310 * Check if this page is something we're going to be showing
311 * some sort of sensible content for. If we return false, page
312 * views (plain action=view) will return an HTTP 404 response,
313 * so spiders and robots can know they're following a bad link.
317 public function hasViewableContent() {
318 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
322 * @return int The view count for the page
324 public function getCount() {
325 if ( !$this->mDataLoaded
) {
326 $this->loadPageData();
329 return $this->mCounter
;
333 * Tests if the article text represents a redirect
335 * @param $text mixed string containing article contents, or boolean
338 public function isRedirect( $text = false ) {
339 if ( $text === false ) $content = $this->getContent();
340 else $content = ContentHandler
::makeContent( $text, $this->mTitle
); # TODO: allow model and format to be provided; or better, expect a Content object
343 if ( empty( $content ) ) return false;
344 else return $content->isRedirect();
348 * Returns the page's content model name. Will use the revisions actual content model if the page exists,
349 * and the page's default if the page doesn't exist yet.
353 public function getContentModelName() {
354 if ( $this->exists() ) {
355 # look at the revision's actual content model
356 $content = $this->getContent();
357 return $content->getModelName();
359 # use the default model for this page
360 return $this->mTitle
->getContentModelName();
365 * Loads page_touched and returns a value indicating if it should be used
366 * @return boolean true if not a redirect
368 public function checkTouched() {
369 if ( !$this->mDataLoaded
) {
370 $this->loadPageData();
372 return !$this->mIsRedirect
;
376 * Get the page_touched field
377 * @return string containing GMT timestamp
379 public function getTouched() {
380 if ( !$this->mDataLoaded
) {
381 $this->loadPageData();
383 return $this->mTouched
;
387 * Get the page_latest field
388 * @return integer rev_id of current revision
390 public function getLatest() {
391 if ( !$this->mDataLoaded
) {
392 $this->loadPageData();
394 return (int)$this->mLatest
;
398 * Loads everything except the text
399 * This isn't necessary for all uses, so it's only done if needed.
401 protected function loadLastEdit() {
402 if ( $this->mLastRevision
!== null ) {
403 return; // already loaded
406 $latest = $this->getLatest();
408 return; // page doesn't exist or is missing page_latest info
411 $revision = Revision
::newFromPageId( $this->getId(), $latest );
412 if ( $revision ) { // sanity
413 $this->setLastEdit( $revision );
418 * Set the latest revision
420 protected function setLastEdit( Revision
$revision ) {
421 $this->mLastRevision
= $revision;
422 $this->mTimestamp
= $revision->getTimestamp();
426 * Get the latest revision
427 * @return Revision|null
429 public function getRevision() {
430 $this->loadLastEdit();
431 if ( $this->mLastRevision
) {
432 return $this->mLastRevision
;
438 * Get the content of the current revision. No side-effects...
440 * @param $audience Integer: one of:
441 * Revision::FOR_PUBLIC to be displayed to all users
442 * Revision::FOR_THIS_USER to be displayed to $wgUser
443 * Revision::RAW get the text regardless of permissions
444 * @return Content|null The content of the current revision
446 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
447 $this->loadLastEdit();
448 if ( $this->mLastRevision
) {
449 return $this->mLastRevision
->getContent( $audience );
455 * Get the text of the current revision. No side-effects...
457 * @param $audience Integer: one of:
458 * Revision::FOR_PUBLIC to be displayed to all users
459 * Revision::FOR_THIS_USER to be displayed to $wgUser
460 * Revision::RAW get the text regardless of permissions
461 * @return String|false The text of the current revision
462 * @deprecated as of 1.20, getContent() should be used instead.
464 public function getText( $audience = Revision
::FOR_PUBLIC
) { #FIXME: deprecated, replace usage!
465 wfDeprecated( __METHOD__
, '1.20' );
466 $this->loadLastEdit();
467 if ( $this->mLastRevision
) {
468 return $this->mLastRevision
->getText( $audience );
474 * Get the text of the current revision. No side-effects...
476 * @return String|bool The text of the current revision. False on failure
478 public function getRawText() { #FIXME: deprecated, replace usage!
479 return $this->getText( Revision
::RAW
);
483 * Get the content of the current revision. No side-effects...
485 * @return Contet|false The text of the current revision
487 protected function getNativeData() { #FIXME: examine all uses carefully! caller must be aware of content model!
488 $content = $this->getContent( Revision
::RAW
);
489 if ( !$content ) return null;
491 return $content->getNativeData();
495 * @return string MW timestamp of last article revision
497 public function getTimestamp() {
498 // Check if the field has been filled by WikiPage::setTimestamp()
499 if ( !$this->mTimestamp
) {
500 $this->loadLastEdit();
503 return wfTimestamp( TS_MW
, $this->mTimestamp
);
507 * Set the page timestamp (use only to avoid DB queries)
508 * @param $ts string MW timestamp of last article revision
511 public function setTimestamp( $ts ) {
512 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
516 * @param $audience Integer: one of:
517 * Revision::FOR_PUBLIC to be displayed to all users
518 * Revision::FOR_THIS_USER to be displayed to $wgUser
519 * Revision::RAW get the text regardless of permissions
520 * @return int user ID for the user that made the last article revision
522 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
523 $this->loadLastEdit();
524 if ( $this->mLastRevision
) {
525 return $this->mLastRevision
->getUser( $audience );
532 * @param $audience Integer: one of:
533 * Revision::FOR_PUBLIC to be displayed to all users
534 * Revision::FOR_THIS_USER to be displayed to $wgUser
535 * Revision::RAW get the text regardless of permissions
536 * @return string username of the user that made the last article revision
538 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
539 $this->loadLastEdit();
540 if ( $this->mLastRevision
) {
541 return $this->mLastRevision
->getUserText( $audience );
548 * @param $audience Integer: one of:
549 * Revision::FOR_PUBLIC to be displayed to all users
550 * Revision::FOR_THIS_USER to be displayed to $wgUser
551 * Revision::RAW get the text regardless of permissions
552 * @return string Comment stored for the last article revision
554 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
555 $this->loadLastEdit();
556 if ( $this->mLastRevision
) {
557 return $this->mLastRevision
->getComment( $audience );
564 * Returns true if last revision was marked as "minor edit"
566 * @return boolean Minor edit indicator for the last article revision.
568 public function getMinorEdit() {
569 $this->loadLastEdit();
570 if ( $this->mLastRevision
) {
571 return $this->mLastRevision
->isMinor();
578 * Get the cached timestamp for the last time the page changed.
579 * This is only used to help handle slave lag by comparing to page_touched.
580 * @return string MW timestamp
582 protected function getCachedLastEditTime() {
584 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
585 return $wgMemc->get( $key );
589 * Set the cached timestamp for the last time the page changed.
590 * This is only used to help handle slave lag by comparing to page_touched.
591 * @param $timestamp string
594 public function setCachedLastEditTime( $timestamp ) {
596 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
597 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
601 * Determine whether a page would be suitable for being counted as an
602 * article in the site_stats table based on the title & its content
604 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
605 * if false, the current database state will be used
608 public function isCountable( $editInfo = false ) {
609 global $wgArticleCountMethod;
611 if ( !$this->mTitle
->isContentPage() ) {
616 $content = ContentHandler
::makeContent( $editInfo->pst
, $this->mTitle
);
617 # TODO: take model and format from edit info!
619 $content = $this->getContent();
622 if ( !$content ||
$content->isRedirect( ) ) {
628 if ( $wgArticleCountMethod === 'link' ) {
629 # nasty special case to avoid re-parsing to detect links
632 // ParserOutput::getLinks() is a 2D array of page links, so
633 // to be really correct we would need to recurse in the array
634 // but the main array should only have items in it if there are
636 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
638 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
639 array( 'pl_from' => $this->getId() ), __METHOD__
);
643 return $content->isCountable( $hasLinks );
647 * If this page is a redirect, get its target
649 * The target will be fetched from the redirect table if possible.
650 * If this page doesn't have an entry there, call insertRedirect()
651 * @return Title|mixed object, or null if this page is not a redirect
653 public function getRedirectTarget() {
654 if ( !$this->mTitle
->isRedirect() ) {
658 if ( $this->mRedirectTarget
!== null ) {
659 return $this->mRedirectTarget
;
662 # Query the redirect table
663 $dbr = wfGetDB( DB_SLAVE
);
664 $row = $dbr->selectRow( 'redirect',
665 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
666 array( 'rd_from' => $this->getId() ),
670 // rd_fragment and rd_interwiki were added later, populate them if empty
671 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
672 return $this->mRedirectTarget
= Title
::makeTitle(
673 $row->rd_namespace
, $row->rd_title
,
674 $row->rd_fragment
, $row->rd_interwiki
);
677 # This page doesn't have an entry in the redirect table
678 return $this->mRedirectTarget
= $this->insertRedirect();
682 * Insert an entry for this page into the redirect table.
684 * Don't call this function directly unless you know what you're doing.
685 * @return Title object or null if not a redirect
687 public function insertRedirect() {
688 // recurse through to only get the final target
689 $content = $this->getContent();
690 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
694 $this->insertRedirectEntry( $retval );
699 * Insert or update the redirect table entry for this page to indicate
700 * it redirects to $rt .
701 * @param $rt Title redirect target
703 public function insertRedirectEntry( $rt ) {
704 $dbw = wfGetDB( DB_MASTER
);
705 $dbw->replace( 'redirect', array( 'rd_from' ),
707 'rd_from' => $this->getId(),
708 'rd_namespace' => $rt->getNamespace(),
709 'rd_title' => $rt->getDBkey(),
710 'rd_fragment' => $rt->getFragment(),
711 'rd_interwiki' => $rt->getInterwiki(),
718 * Get the Title object or URL this page redirects to
720 * @return mixed false, Title of in-wiki target, or string with URL
722 public function followRedirect() {
723 return $this->getRedirectURL( $this->getRedirectTarget() );
727 * Get the Title object or URL to use for a redirect. We use Title
728 * objects for same-wiki, non-special redirects and URLs for everything
730 * @param $rt Title Redirect target
731 * @return mixed false, Title object of local target, or string with URL
733 public function getRedirectURL( $rt ) {
738 if ( $rt->isExternal() ) {
739 if ( $rt->isLocal() ) {
740 // Offsite wikis need an HTTP redirect.
742 // This can be hard to reverse and may produce loops,
743 // so they may be disabled in the site configuration.
744 $source = $this->mTitle
->getFullURL( 'redirect=no' );
745 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
747 // External pages pages without "local" bit set are not valid
753 if ( $rt->isSpecialPage() ) {
754 // Gotta handle redirects to special pages differently:
755 // Fill the HTTP response "Location" header and ignore
756 // the rest of the page we're on.
758 // Some pages are not valid targets
759 if ( $rt->isValidRedirectTarget() ) {
760 return $rt->getFullURL();
770 * Get a list of users who have edited this article, not including the user who made
771 * the most recent revision, which you can get from $article->getUser() if you want it
772 * @return UserArrayFromResult
774 public function getContributors() {
775 # @todo FIXME: This is expensive; cache this info somewhere.
777 $dbr = wfGetDB( DB_SLAVE
);
779 if ( $dbr->implicitGroupby() ) {
780 $realNameField = 'user_real_name';
782 $realNameField = 'MIN(user_real_name) AS user_real_name';
785 $tables = array( 'revision', 'user' );
788 'rev_user as user_id',
789 'rev_user_text AS user_name',
791 'MAX(rev_timestamp) AS timestamp',
794 $conds = array( 'rev_page' => $this->getId() );
796 // The user who made the top revision gets credited as "this page was last edited by
797 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
798 $user = $this->getUser();
800 $conds[] = "rev_user != $user";
802 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
805 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
808 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
812 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
813 'ORDER BY' => 'timestamp DESC',
816 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
817 return new UserArrayFromResult( $res );
821 * Get the last N authors
822 * @param $num Integer: number of revisions to get
823 * @param $revLatest String: the latest rev_id, selected from the master (optional)
824 * @return array Array of authors, duplicates not removed
826 public function getLastNAuthors( $num, $revLatest = 0 ) {
827 wfProfileIn( __METHOD__
);
828 // First try the slave
829 // If that doesn't have the latest revision, try the master
831 $db = wfGetDB( DB_SLAVE
);
834 $res = $db->select( array( 'page', 'revision' ),
835 array( 'rev_id', 'rev_user_text' ),
837 'page_namespace' => $this->mTitle
->getNamespace(),
838 'page_title' => $this->mTitle
->getDBkey(),
842 'ORDER BY' => 'rev_timestamp DESC',
848 wfProfileOut( __METHOD__
);
852 $row = $db->fetchObject( $res );
854 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
855 $db = wfGetDB( DB_MASTER
);
860 } while ( $continue );
862 $authors = array( $row->rev_user_text
);
864 foreach ( $res as $row ) {
865 $authors[] = $row->rev_user_text
;
868 wfProfileOut( __METHOD__
);
873 * Should the parser cache be used?
875 * @param $parserOptions ParserOptions to check
879 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
880 global $wgEnableParserCache;
882 return $wgEnableParserCache
883 && $parserOptions->getStubThreshold() == 0
884 && $this->mTitle
->exists()
885 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
886 && $this->mTitle
->isWikitextPage(); #FIXME: ask ContentHandler if cachable!
890 * Get a ParserOutput for the given ParserOptions and revision ID.
891 * The parser cache will be used if possible.
894 * @param $parserOptions ParserOptions to use for the parse operation
895 * @param $oldid Revision ID to get the text from, passing null or 0 will
896 * get the current revision (default value)
897 * @return ParserOutput or false if the revision was not found
899 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
900 wfProfileIn( __METHOD__
);
902 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
903 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
904 if ( $parserOptions->getStubThreshold() ) {
905 wfIncrStats( 'pcache_miss_stub' );
908 if ( $useParserCache ) {
909 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
910 if ( $parserOutput !== false ) {
911 wfProfileOut( __METHOD__
);
912 return $parserOutput;
916 if ( $oldid === null ||
$oldid === 0 ) {
917 $oldid = $this->getLatest();
920 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
923 wfProfileOut( __METHOD__
);
925 return $pool->getParserOutput();
929 * Do standard deferred updates after page view
930 * @param $user User The relevant user
932 public function doViewUpdates( User
$user ) {
933 global $wgDisableCounters;
934 if ( wfReadOnly() ) {
938 # Don't update page view counters on views from bot users (bug 14044)
939 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
940 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
941 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
944 # Update newtalk / watchlist notification status
945 $user->clearNotification( $this->mTitle
);
949 * Perform the actions of a page purging
952 public function doPurge() {
955 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
959 // Invalidate the cache
960 $this->mTitle
->invalidateCache();
964 // Commit the transaction before the purge is sent
965 $dbw = wfGetDB( DB_MASTER
);
966 $dbw->commit( __METHOD__
);
969 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
973 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
974 if ( $this->mTitle
->exists() ) {
975 $text = $this->getNativeData(); #FIXME: may not be a string. check Content model!
980 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
986 * Insert a new empty page record for this article.
987 * This *must* be followed up by creating a revision
988 * and running $this->updateRevisionOn( ... );
989 * or else the record will be left in a funky state.
990 * Best if all done inside a transaction.
992 * @param $dbw DatabaseBase
993 * @return int The newly created page_id key, or false if the title already existed
995 public function insertOn( $dbw ) {
996 wfProfileIn( __METHOD__
);
998 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
999 $dbw->insert( 'page', array(
1000 'page_id' => $page_id,
1001 'page_namespace' => $this->mTitle
->getNamespace(),
1002 'page_title' => $this->mTitle
->getDBkey(),
1003 'page_counter' => 0,
1004 'page_restrictions' => '',
1005 'page_is_redirect' => 0, # Will set this shortly...
1007 'page_random' => wfRandom(),
1008 'page_touched' => $dbw->timestamp(),
1009 'page_latest' => 0, # Fill this in shortly...
1010 'page_len' => 0, # Fill this in shortly...
1011 ), __METHOD__
, 'IGNORE' );
1013 $affected = $dbw->affectedRows();
1016 $newid = $dbw->insertId();
1017 $this->mTitle
->resetArticleID( $newid );
1019 wfProfileOut( __METHOD__
);
1021 return $affected ?
$newid : false;
1025 * Update the page record to point to a newly saved revision.
1027 * @param $dbw DatabaseBase: object
1028 * @param $revision Revision: For ID number, and text used to set
1029 * length and redirect status fields
1030 * @param $lastRevision Integer: if given, will not overwrite the page field
1031 * when different from the currently set value.
1032 * Giving 0 indicates the new page flag should be set
1034 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1035 * removing rows in redirect table.
1036 * @return bool true on success, false on failure
1039 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1040 wfProfileIn( __METHOD__
);
1042 $content = $revision->getContent();
1043 $len = $content->getSize();
1044 $rt = $content->getUltimateRedirectTarget();
1046 $conditions = array( 'page_id' => $this->getId() );
1048 if ( !is_null( $lastRevision ) ) {
1049 # An extra check against threads stepping on each other
1050 $conditions['page_latest'] = $lastRevision;
1053 $now = wfTimestampNow();
1054 $dbw->update( 'page',
1056 'page_latest' => $revision->getId(),
1057 'page_touched' => $dbw->timestamp( $now ),
1058 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1059 'page_is_redirect' => $rt !== null ?
1 : 0,
1065 $result = $dbw->affectedRows() != 0;
1067 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1068 $this->setLastEdit( $revision );
1069 $this->setCachedLastEditTime( $now );
1070 $this->mLatest
= $revision->getId();
1071 $this->mIsRedirect
= (bool)$rt;
1072 # Update the LinkCache.
1073 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1076 wfProfileOut( __METHOD__
);
1081 * Add row to the redirect table if this is a redirect, remove otherwise.
1083 * @param $dbw DatabaseBase
1084 * @param $redirectTitle Title object pointing to the redirect target,
1085 * or NULL if this is not a redirect
1086 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1087 * removing rows in redirect table.
1088 * @return bool true on success, false on failure
1091 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1092 // Always update redirects (target link might have changed)
1093 // Update/Insert if we don't know if the last revision was a redirect or not
1094 // Delete if changing from redirect to non-redirect
1095 $isRedirect = !is_null( $redirectTitle );
1097 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1101 wfProfileIn( __METHOD__
);
1102 if ( $isRedirect ) {
1103 $this->insertRedirectEntry( $redirectTitle );
1105 // This is not a redirect, remove row from redirect table
1106 $where = array( 'rd_from' => $this->getId() );
1107 $dbw->delete( 'redirect', $where, __METHOD__
);
1110 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1111 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1113 wfProfileOut( __METHOD__
);
1115 return ( $dbw->affectedRows() != 0 );
1119 * If the given revision is newer than the currently set page_latest,
1120 * update the page record. Otherwise, do nothing.
1122 * @param $dbw DatabaseBase object
1123 * @param $revision Revision object
1126 public function updateIfNewerOn( $dbw, $revision ) {
1127 wfProfileIn( __METHOD__
);
1129 $row = $dbw->selectRow(
1130 array( 'revision', 'page' ),
1131 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1133 'page_id' => $this->getId(),
1134 'page_latest=rev_id' ),
1138 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1139 wfProfileOut( __METHOD__
);
1142 $prev = $row->rev_id
;
1143 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1145 # No or missing previous revision; mark the page as new
1147 $lastRevIsRedirect = null;
1150 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1152 wfProfileOut( __METHOD__
);
1157 * Get the text that needs to be saved in order to undo all revisions
1158 * between $undo and $undoafter. Revisions must belong to the same page,
1159 * must exist and must not be deleted
1160 * @param $undo Revision
1161 * @param $undoafter Revision Must be an earlier revision than $undo
1162 * @return mixed string on success, false on failure
1163 * @deprecated since 1.20: use ContentHandler::getUndoContent() instead.
1165 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) { #FIXME: replace usages.
1166 $this->loadLastEdit();
1168 if ( $this->mLastRevision
) {
1169 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1170 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1175 return ContentHandler
::getContentText( $undone );
1183 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1184 * @param $text String: new text of the section
1185 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1186 * @param $edittime String: revision timestamp or null to use the current revision
1187 * @return Content new complete article content, or null if error
1188 * @deprected since 1.20, use replaceSectionContent() instead
1190 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) { #FIXME: use replaceSectionContent() instead!
1192 //wfDeprecated( __METHOD__, '1.20' );
1194 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1196 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1198 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1201 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1202 wfProfileIn( __METHOD__
);
1204 if ( strval( $section ) == '' ) {
1205 // Whole-page edit; let the whole text through
1206 $newContent = $sectionContent;
1208 // Bug 30711: always use current version when adding a new section
1209 if ( is_null( $edittime ) ||
$section == 'new' ) {
1210 $oldContent = $this->getContent();
1211 if ( ! $oldContent ) {
1212 wfDebug( __METHOD__
. ": no page text\n" );
1213 wfProfileOut( __METHOD__
);
1217 $dbw = wfGetDB( DB_MASTER
);
1218 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1221 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1222 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1223 wfProfileOut( __METHOD__
);
1227 $oldContent = $rev->getContent();
1230 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1233 wfProfileOut( __METHOD__
);
1238 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1240 * @return Int updated $flags
1242 function checkFlags( $flags ) {
1243 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1244 if ( $this->mTitle
->getArticleID() ) {
1245 $flags |
= EDIT_UPDATE
;
1255 * Change an existing article or create a new article. Updates RC and all necessary caches,
1256 * optionally via the deferred update array.
1258 * @param $text String: new text
1259 * @param $summary String: edit summary
1260 * @param $flags Integer bitfield:
1262 * Article is known or assumed to be non-existent, create a new one
1264 * Article is known or assumed to be pre-existing, update it
1266 * Mark this edit minor, if the user is allowed to do so
1268 * Do not log the change in recentchanges
1270 * Mark the edit a "bot" edit regardless of user rights
1271 * EDIT_DEFER_UPDATES
1272 * Defer some of the updates until the end of index.php
1274 * Fill in blank summaries with generated text where possible
1276 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1277 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1278 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1279 * edit-already-exists error will be returned. These two conditions are also possible with
1280 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1282 * @param $baseRevId int the revision ID this edit was based off, if any
1283 * @param $user User the user doing the edit
1285 * @return Status object. Possible errors:
1286 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1287 * edit-gone-missing: In update mode, but the article didn't exist
1288 * edit-conflict: In update mode, the article changed unexpectedly
1289 * edit-no-change: Warning that the text was the same as before
1290 * edit-already-exists: In creation mode, but the article already exists
1292 * Extensions may define additional errors.
1294 * $return->value will contain an associative array with members as follows:
1295 * new: Boolean indicating if the function attempted to create a new article
1296 * revision: The revision object for the inserted revision, or null
1298 * Compatibility note: this function previously returned a boolean value indicating success/failure
1299 * @deprecated since 1.20: use doEditContent() instead.
1301 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #FIXME: use doEditContent() instead
1302 #TODO: log use of deprecated function
1303 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1305 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1309 * Change an existing article or create a new article. Updates RC and all necessary caches,
1310 * optionally via the deferred update array.
1312 * @param $content Content: new content
1313 * @param $summary String: edit summary
1314 * @param $flags Integer bitfield:
1316 * Article is known or assumed to be non-existent, create a new one
1318 * Article is known or assumed to be pre-existing, update it
1320 * Mark this edit minor, if the user is allowed to do so
1322 * Do not log the change in recentchanges
1324 * Mark the edit a "bot" edit regardless of user rights
1325 * EDIT_DEFER_UPDATES
1326 * Defer some of the updates until the end of index.php
1328 * Fill in blank summaries with generated text where possible
1330 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1331 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1332 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1333 * edit-already-exists error will be returned. These two conditions are also possible with
1334 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1336 * @param $baseRevId the revision ID this edit was based off, if any
1337 * @param $user User the user doing the edit
1338 * @param $serialisation_format String: format for storing the content in the database
1340 * @return Status object. Possible errors:
1341 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1342 * edit-gone-missing: In update mode, but the article didn't exist
1343 * edit-conflict: In update mode, the article changed unexpectedly
1344 * edit-no-change: Warning that the text was the same as before
1345 * edit-already-exists: In creation mode, but the article already exists
1347 * Extensions may define additional errors.
1349 * $return->value will contain an associative array with members as follows:
1350 * new: Boolean indicating if the function attempted to create a new article
1351 * revision: The revision object for the inserted revision, or null
1353 * Compatibility note: this function previously returned a boolean value indicating success/failure
1355 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1356 User
$user = null, $serialisation_format = null ) { #FIXME: use this
1357 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1359 # Low-level sanity check
1360 if ( $this->mTitle
->getText() === '' ) {
1361 throw new MWException( 'Something is trying to edit an article with an empty title' );
1364 wfProfileIn( __METHOD__
);
1366 $user = is_null( $user ) ?
$wgUser : $user;
1367 $status = Status
::newGood( array() );
1369 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1370 $this->loadPageData( 'fromdbmaster' );
1372 $flags = $this->checkFlags( $flags );
1375 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary, #FIXME: document new hook!
1376 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1378 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1379 $content_text = $content->serialize();
1380 $txt = $content_text; # clone
1382 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary, #FIXME: deprecate legacy hook!
1383 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1385 if ( $txt !== $content_text ) {
1386 # if the text changed, unserialize the new version to create an updated Content object.
1387 $content = $content->getContentHandler()->unserialize( $txt );
1392 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1394 if ( $status->isOK() ) {
1395 $status->fatal( 'edit-hook-aborted' );
1398 wfProfileOut( __METHOD__
);
1402 # Silently ignore EDIT_MINOR if not allowed
1403 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1404 $bot = $flags & EDIT_FORCE_BOT
;
1406 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1408 $oldsize = $old_content ?
$old_content->getSize() : 0;
1409 $oldid = $this->getLatest();
1410 $oldIsRedirect = $this->isRedirect();
1411 $oldcountable = $this->isCountable();
1413 $handler = $content->getContentHandler();
1415 # Provide autosummaries if one is not provided and autosummaries are enabled.
1416 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1417 if ( !$old_content ) $old_content = null;
1418 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1421 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1422 $serialized = $editInfo->pst
;
1423 $content = $editInfo->pstContent
;
1424 $newsize = $content->getSize();
1426 $dbw = wfGetDB( DB_MASTER
);
1427 $now = wfTimestampNow();
1428 $this->mTimestamp
= $now;
1430 if ( $flags & EDIT_UPDATE
) {
1431 # Update article, but only if changed.
1432 $status->value
['new'] = false;
1435 # Article gone missing
1436 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1437 $status->fatal( 'edit-gone-missing' );
1439 wfProfileOut( __METHOD__
);
1443 # Make sure the revision is either completely inserted or not inserted at all
1444 if ( !$wgDBtransactions ) {
1445 $userAbort = ignore_user_abort( true );
1448 $revision = new Revision( array(
1449 'page' => $this->getId(),
1450 'comment' => $summary,
1451 'minor_edit' => $isminor,
1452 'text' => $serialized,
1454 'parent_id' => $oldid,
1455 'user' => $user->getId(),
1456 'user_text' => $user->getName(),
1457 'timestamp' => $now,
1458 'content_model' => $content->getModelName(),
1459 'content_format' => $serialisation_format,
1462 $changed = !$content->equals( $old_content );
1465 $dbw->begin( __METHOD__
);
1466 $revisionId = $revision->insertOn( $dbw );
1470 # Note that we use $this->mLatest instead of fetching a value from the master DB
1471 # during the course of this function. This makes sure that EditPage can detect
1472 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1473 # before this function is called. A previous function used a separate query, this
1474 # creates a window where concurrent edits can cause an ignored edit conflict.
1475 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1478 /* Belated edit conflict! Run away!! */
1479 $status->fatal( 'edit-conflict' );
1481 # Delete the invalid revision if the DB is not transactional
1482 if ( !$wgDBtransactions ) {
1483 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1487 $dbw->rollback( __METHOD__
);
1489 global $wgUseRCPatrol;
1490 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1491 # Update recentchanges
1492 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1493 # Mark as patrolled if the user can do so
1494 $patrolled = $wgUseRCPatrol && !count(
1495 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1496 # Add RC row to the DB
1497 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1498 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1499 $revisionId, $patrolled
1502 # Log auto-patrolled edits
1504 PatrolLog
::record( $rc, true, $user );
1507 $user->incEditCount();
1508 $dbw->commit( __METHOD__
);
1511 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1512 // related variables correctly
1513 $revision->setId( $this->getLatest() );
1516 if ( !$wgDBtransactions ) {
1517 ignore_user_abort( $userAbort );
1520 // Now that ignore_user_abort is restored, we can respond to fatal errors
1521 if ( !$status->isOK() ) {
1522 wfProfileOut( __METHOD__
);
1526 # Update links tables, site stats, etc.
1527 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1528 'oldcountable' => $oldcountable ) );
1531 $status->warning( 'edit-no-change' );
1533 // Update page_touched, this is usually implicit in the page update
1534 // Other cache updates are done in onArticleEdit()
1535 $this->mTitle
->invalidateCache();
1538 # Create new article
1539 $status->value
['new'] = true;
1541 $dbw->begin( __METHOD__
);
1543 # Add the page record; stake our claim on this title!
1544 # This will return false if the article already exists
1545 $newid = $this->insertOn( $dbw );
1547 if ( $newid === false ) {
1548 $dbw->rollback( __METHOD__
);
1549 $status->fatal( 'edit-already-exists' );
1551 wfProfileOut( __METHOD__
);
1555 # Save the revision text...
1556 $revision = new Revision( array(
1558 'comment' => $summary,
1559 'minor_edit' => $isminor,
1560 'text' => $serialized,
1562 'user' => $user->getId(),
1563 'user_text' => $user->getName(),
1564 'timestamp' => $now,
1565 'content_model' => $content->getModelName(),
1566 'content_format' => $serialisation_format,
1568 $revisionId = $revision->insertOn( $dbw );
1570 # Update the page record with revision data
1571 $this->updateRevisionOn( $dbw, $revision, 0 );
1573 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1575 # Update recentchanges
1576 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1577 global $wgUseRCPatrol, $wgUseNPPatrol;
1579 # Mark as patrolled if the user can do so
1580 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1581 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1582 # Add RC row to the DB
1583 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1584 '', $content->getSize(), $revisionId, $patrolled );
1586 # Log auto-patrolled edits
1588 PatrolLog
::record( $rc, true, $user );
1591 $user->incEditCount();
1592 $dbw->commit( __METHOD__
);
1594 # Update links, etc.
1595 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1597 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1598 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1600 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1601 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1604 # Do updates right now unless deferral was requested
1605 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1606 DeferredUpdates
::doUpdates();
1609 // Return the new revision (or null) to the caller
1610 $status->value
['revision'] = $revision;
1612 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1613 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1615 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1616 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1618 # Promote user to any groups they meet the criteria for
1619 $user->addAutopromoteOnceGroups( 'onEdit' );
1621 wfProfileOut( __METHOD__
);
1626 * Get parser options suitable for rendering the primary article wikitext
1627 * @param User|string $user User object or 'canonical'
1628 * @return ParserOptions
1630 public function makeParserOptions( $user ) {
1632 if ( $user instanceof User
) { // settings per user (even anons)
1633 $options = ParserOptions
::newFromUser( $user );
1634 } else { // canonical settings
1635 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1637 $options->enableLimitReport(); // show inclusion/loop reports
1638 $options->setTidy( true ); // fix bad HTML
1643 * Prepare text which is about to be saved.
1644 * Returns a stdclass with source, pst and output members
1645 * @deprecated in 1.20: use prepareContentForEdit instead.
1647 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1648 #TODO: log use of deprecated function
1649 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1650 return $this->prepareContentForEdit( $content, $revid , $user );
1654 * Prepare content which is about to be saved.
1655 * Returns a stdclass with source, pst and output members
1657 * @param \Content $content
1658 * @param null $revid
1659 * @param null|\User $user
1660 * @param null $serialization_format
1661 * @return bool|object
1663 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1664 global $wgParser, $wgContLang, $wgUser;
1665 $user = is_null( $user ) ?
$wgUser : $user;
1666 // @TODO fixme: check $user->getId() here???
1668 if ( $this->mPreparedEdit
1669 && $this->mPreparedEdit
->newContent
1670 && $this->mPreparedEdit
->newContent
->equals( $content )
1671 && $this->mPreparedEdit
->revid
== $revid
1672 && $this->mPreparedEdit
->format
== $serialization_format
1673 #XXX: also check $user here?
1676 return $this->mPreparedEdit
;
1679 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1680 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1682 $edit = (object)array();
1683 $edit->revid
= $revid;
1685 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1686 $edit->pst
= $edit->pstContent
->serialize( $serialization_format );
1687 $edit->format
= $serialization_format;
1689 $edit->popts
= $this->makeParserOptions( 'canonical' );
1690 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1692 $edit->newContent
= $content;
1693 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1695 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1696 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1698 $this->mPreparedEdit
= $edit;
1704 * Do standard deferred updates after page edit.
1705 * Update links tables, site stats, search index and message cache.
1706 * Purges pages that include this page if the text was changed here.
1707 * Every 100th edit, prune the recent changes table.
1710 * @param $revision Revision object
1711 * @param $user User object that did the revision
1712 * @param $options Array of options, following indexes are used:
1713 * - changed: boolean, whether the revision changed the content (default true)
1714 * - created: boolean, whether the revision created the page (default false)
1715 * - oldcountable: boolean or null (default null):
1716 * - boolean: whether the page was counted as an article before that
1717 * revision, only used in changed is true and created is false
1718 * - null: don't change the article count
1720 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1721 global $wgEnableParserCache;
1723 wfProfileIn( __METHOD__
);
1725 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1726 $content = $revision->getContent();
1729 # Be careful not to double-PST: $text is usually already PST-ed once
1730 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1731 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1732 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1734 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1735 $editInfo = $this->mPreparedEdit
;
1738 # Save it to the parser cache
1739 if ( $wgEnableParserCache ) {
1740 $parserCache = ParserCache
::singleton();
1741 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1744 # Update the links tables and other secondary data
1745 $updates = $editInfo->output
->getLinksUpdateAndOtherUpdates( $this->mTitle
);
1746 SecondaryDataUpdate
::runUpdates( $updates );
1748 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1750 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1751 if ( 0 == mt_rand( 0, 99 ) ) {
1752 // Flush old entries from the `recentchanges` table; we do this on
1753 // random requests so as to avoid an increase in writes for no good reason
1756 $dbw = wfGetDB( DB_MASTER
);
1757 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1760 array( "rc_timestamp < '$cutoff'" ),
1766 if ( !$this->mTitle
->exists() ) {
1767 wfProfileOut( __METHOD__
);
1771 $id = $this->getId();
1772 $title = $this->mTitle
->getPrefixedDBkey();
1773 $shortTitle = $this->mTitle
->getDBkey();
1775 if ( !$options['changed'] ) {
1778 } elseif ( $options['created'] ) {
1779 $good = (int)$this->isCountable( $editInfo );
1781 } elseif ( $options['oldcountable'] !== null ) {
1782 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1789 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1790 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1792 # If this is another user's talk page, update newtalk.
1793 # Don't do this if $options['changed'] = false (null-edits) nor if
1794 # it's a minor edit and the user doesn't want notifications for those.
1795 if ( $options['changed']
1796 && $this->mTitle
->getNamespace() == NS_USER_TALK
1797 && $shortTitle != $user->getTitleKey()
1798 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1800 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1801 $other = User
::newFromName( $shortTitle, false );
1803 wfDebug( __METHOD__
. ": invalid username\n" );
1804 } elseif ( User
::isIP( $shortTitle ) ) {
1805 // An anonymous user
1806 $other->setNewtalk( true );
1807 } elseif ( $other->isLoggedIn() ) {
1808 $other->setNewtalk( true );
1810 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1815 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1816 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1817 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
1819 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
1822 if( $options['created'] ) {
1823 self
::onArticleCreate( $this->mTitle
);
1825 self
::onArticleEdit( $this->mTitle
);
1828 wfProfileOut( __METHOD__
);
1832 * Edit an article without doing all that other stuff
1833 * The article must already exist; link tables etc
1834 * are not updated, caches are not flushed.
1836 * @param $text String: text submitted
1837 * @param $user User The relevant user
1838 * @param $comment String: comment submitted
1839 * @param $minor Boolean: whereas it's a minor modification
1841 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1842 #TODO: log use of deprecated function
1843 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1844 return $this->doQuickEdit( $content, $user, $comment , $minor );
1848 * Edit an article without doing all that other stuff
1849 * The article must already exist; link tables etc
1850 * are not updated, caches are not flushed.
1852 * @param $content Content: content submitted
1853 * @param $user User The relevant user
1854 * @param $comment String: comment submitted
1855 * @param $serialisation_format String: format for storing the content in the database
1856 * @param $minor Boolean: whereas it's a minor modification
1858 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
1859 wfProfileIn( __METHOD__
);
1861 $serialized = $content->serialize( $serialisation_format );
1863 $dbw = wfGetDB( DB_MASTER
);
1864 $revision = new Revision( array(
1865 'page' => $this->getId(),
1866 'text' => $serialized,
1867 'length' => $content->getSize(),
1868 'comment' => $comment,
1869 'minor_edit' => $minor ?
1 : 0,
1871 $revision->insertOn( $dbw );
1872 $this->updateRevisionOn( $dbw, $revision );
1874 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1876 wfProfileOut( __METHOD__
);
1880 * Update the article's restriction field, and leave a log entry.
1881 * This works for protection both existing and non-existing pages.
1883 * @param $limit Array: set of restriction keys
1884 * @param $reason String
1885 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1886 * @param $expiry Array: per restriction type expiration
1887 * @param $user User The user updating the restrictions
1888 * @return bool true on success
1890 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1893 if ( wfReadOnly() ) {
1894 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1897 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1899 $id = $this->mTitle
->getArticleID();
1905 // Take this opportunity to purge out expired restrictions
1906 Title
::purgeExpiredRestrictions();
1908 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1909 # we expect a single selection, but the schema allows otherwise.
1910 $isProtected = false;
1914 $dbw = wfGetDB( DB_MASTER
);
1916 foreach ( $restrictionTypes as $action ) {
1917 if ( !isset( $expiry[$action] ) ) {
1918 $expiry[$action] = $dbw->getInfinity();
1920 if ( !isset( $limit[$action] ) ) {
1921 $limit[$action] = '';
1922 } elseif ( $limit[$action] != '' ) {
1926 # Get current restrictions on $action
1927 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1928 if ( $current != '' ) {
1929 $isProtected = true;
1932 if ( $limit[$action] != $current ) {
1934 } elseif ( $limit[$action] != '' ) {
1935 # Only check expiry change if the action is actually being
1936 # protected, since expiry does nothing on an not-protected
1938 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1944 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1948 # If nothing's changed, do nothing
1950 return Status
::newGood();
1953 if ( !$protect ) { # No protection at all means unprotection
1954 $revCommentMsg = 'unprotectedarticle';
1955 $logAction = 'unprotect';
1956 } elseif ( $isProtected ) {
1957 $revCommentMsg = 'modifiedarticleprotection';
1958 $logAction = 'modify';
1960 $revCommentMsg = 'protectedarticle';
1961 $logAction = 'protect';
1964 $encodedExpiry = array();
1965 $protectDescription = '';
1966 foreach ( $limit as $action => $restrictions ) {
1967 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1968 if ( $restrictions != '' ) {
1969 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1970 if ( $encodedExpiry[$action] != 'infinity' ) {
1971 $protectDescription .= wfMsgForContent( 'protect-expiring',
1972 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1973 $wgContLang->date( $expiry[$action], false, false ) ,
1974 $wgContLang->time( $expiry[$action], false, false ) );
1976 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1979 $protectDescription .= ') ';
1982 $protectDescription = trim( $protectDescription );
1984 if ( $id ) { # Protection of existing page
1985 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1986 return Status
::newGood();
1989 # Only restrictions with the 'protect' right can cascade...
1990 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1991 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1993 # The schema allows multiple restrictions
1994 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1998 # Update restrictions table
1999 foreach ( $limit as $action => $restrictions ) {
2000 if ( $restrictions != '' ) {
2001 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2002 array( 'pr_page' => $id,
2003 'pr_type' => $action,
2004 'pr_level' => $restrictions,
2005 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2006 'pr_expiry' => $encodedExpiry[$action]
2011 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2012 'pr_type' => $action ), __METHOD__
);
2016 # Prepare a null revision to be added to the history
2017 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2019 $editComment .= ": $reason";
2021 if ( $protectDescription ) {
2022 $editComment .= " ($protectDescription)";
2025 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2028 # Insert a null revision
2029 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2030 $nullRevId = $nullRevision->insertOn( $dbw );
2032 $latest = $this->getLatest();
2033 # Update page record
2034 $dbw->update( 'page',
2036 'page_touched' => $dbw->timestamp(),
2037 'page_restrictions' => '',
2038 'page_latest' => $nullRevId
2039 ), array( /* WHERE */
2044 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2045 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2046 } else { # Protection of non-existing page (also known as "title protection")
2047 # Cascade protection is meaningless in this case
2050 if ( $limit['create'] != '' ) {
2051 $dbw->replace( 'protected_titles',
2052 array( array( 'pt_namespace', 'pt_title' ) ),
2054 'pt_namespace' => $this->mTitle
->getNamespace(),
2055 'pt_title' => $this->mTitle
->getDBkey(),
2056 'pt_create_perm' => $limit['create'],
2057 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2058 'pt_expiry' => $encodedExpiry['create'],
2059 'pt_user' => $user->getId(),
2060 'pt_reason' => $reason,
2064 $dbw->delete( 'protected_titles',
2066 'pt_namespace' => $this->mTitle
->getNamespace(),
2067 'pt_title' => $this->mTitle
->getDBkey()
2073 $this->mTitle
->flushRestrictions();
2075 if ( $logAction == 'unprotect' ) {
2076 $logParams = array();
2078 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2081 # Update the protection log
2082 $log = new LogPage( 'protect' );
2083 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2085 return Status
::newGood();
2089 * Take an array of page restrictions and flatten it to a string
2090 * suitable for insertion into the page_restrictions field.
2091 * @param $limit Array
2094 protected static function flattenRestrictions( $limit ) {
2095 if ( !is_array( $limit ) ) {
2096 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2102 foreach ( $limit as $action => $restrictions ) {
2103 if ( $restrictions != '' ) {
2104 $bits[] = "$action=$restrictions";
2108 return implode( ':', $bits );
2112 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2113 * Deletes the article with database consistency, writes logs, purges caches
2115 * @param $reason string delete reason for deletion log
2116 * @param $suppress int bitfield
2117 * Revision::DELETED_TEXT
2118 * Revision::DELETED_COMMENT
2119 * Revision::DELETED_USER
2120 * Revision::DELETED_RESTRICTED
2121 * @param $id int article ID
2122 * @param $commit boolean defaults to true, triggers transaction end
2123 * @param &$error Array of errors to append to
2124 * @param $user User The deleting user
2125 * @return boolean true if successful
2127 public function doDeleteArticle(
2128 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2130 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2131 == WikiPage
::DELETE_SUCCESS
;
2135 * Back-end article deletion
2136 * Deletes the article with database consistency, writes logs, purges caches
2138 * @param $reason string delete reason for deletion log
2139 * @param $suppress int bitfield
2140 * Revision::DELETED_TEXT
2141 * Revision::DELETED_COMMENT
2142 * Revision::DELETED_USER
2143 * Revision::DELETED_RESTRICTED
2144 * @param $id int article ID
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 int: One of WikiPage::DELETE_* constants
2150 public function doDeleteArticleReal(
2151 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2154 $user = is_null( $user ) ?
$wgUser : $user;
2156 wfDebug( __METHOD__
. "\n" );
2158 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2159 return WikiPage
::DELETE_HOOK_ABORTED
;
2161 $dbw = wfGetDB( DB_MASTER
);
2162 $t = $this->mTitle
->getDBkey();
2163 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
2165 if ( $t === '' ||
$id == 0 ) {
2166 return WikiPage
::DELETE_NO_PAGE
;
2169 // Bitfields to further suppress the content
2172 // This should be 15...
2173 $bitfield |
= Revision
::DELETED_TEXT
;
2174 $bitfield |
= Revision
::DELETED_COMMENT
;
2175 $bitfield |
= Revision
::DELETED_USER
;
2176 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2178 $bitfield = 'rev_deleted';
2181 $dbw->begin( __METHOD__
);
2182 // For now, shunt the revision data into the archive table.
2183 // Text is *not* removed from the text table; bulk storage
2184 // is left intact to avoid breaking block-compression or
2185 // immutable storage schemes.
2187 // For backwards compatibility, note that some older archive
2188 // table entries will have ar_text and ar_flags fields still.
2190 // In the future, we may keep revisions and mark them with
2191 // the rev_deleted field, which is reserved for this purpose.
2192 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2194 'ar_namespace' => 'page_namespace',
2195 'ar_title' => 'page_title',
2196 'ar_comment' => 'rev_comment',
2197 'ar_user' => 'rev_user',
2198 'ar_user_text' => 'rev_user_text',
2199 'ar_timestamp' => 'rev_timestamp',
2200 'ar_minor_edit' => 'rev_minor_edit',
2201 'ar_rev_id' => 'rev_id',
2202 'ar_parent_id' => 'rev_parent_id',
2203 'ar_text_id' => 'rev_text_id',
2204 'ar_text' => '\'\'', // Be explicit to appease
2205 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2206 'ar_len' => 'rev_len',
2207 'ar_page_id' => 'page_id',
2208 'ar_deleted' => $bitfield,
2209 'ar_sha1' => 'rev_content_model',
2210 'ar_content_format' => 'rev_content_format',
2211 'ar_content_format' => 'rev_sha1'
2214 'page_id = rev_page'
2218 # Now that it's safely backed up, delete it
2219 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2220 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2223 $dbw->rollback( __METHOD__
);
2224 return WikiPage
::DELETE_NO_REVISIONS
;
2227 $this->doDeleteUpdates( $id );
2229 # Log the deletion, if the page was suppressed, log it at Oversight instead
2230 $logtype = $suppress ?
'suppress' : 'delete';
2232 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2233 $logEntry->setPerformer( $user );
2234 $logEntry->setTarget( $this->mTitle
);
2235 $logEntry->setComment( $reason );
2236 $logid = $logEntry->insert();
2237 $logEntry->publish( $logid );
2240 $dbw->commit( __METHOD__
);
2243 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2244 return WikiPage
::DELETE_SUCCESS
;
2248 * Do some database updates after deletion
2250 * @param $id Int: page_id value of the page being deleted
2252 public function doDeleteUpdates( $id ) {
2253 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2255 $dbw = wfGetDB( DB_MASTER
);
2257 # Delete restrictions for it
2258 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2260 # Fix category table counts
2262 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2264 foreach ( $res as $row ) {
2265 $cats [] = $row->cl_to
;
2268 $this->updateCategoryCounts( array(), $cats );
2270 # If using cascading deletes, we can skip some explicit deletes
2271 if ( !$dbw->cascadingDeletes() ) {
2272 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2274 # Delete outgoing links
2275 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2276 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2277 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2278 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2279 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2280 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2281 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2282 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2283 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2286 # If using cleanup triggers, we can skip some manual deletes
2287 if ( !$dbw->cleanupTriggers() ) {
2288 # Clean up recentchanges entries...
2289 $dbw->delete( 'recentchanges',
2290 array( 'rc_type != ' . RC_LOG
,
2291 'rc_namespace' => $this->mTitle
->getNamespace(),
2292 'rc_title' => $this->mTitle
->getDBkey() ),
2294 $dbw->delete( 'recentchanges',
2295 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2300 self
::onArticleDelete( $this->mTitle
);
2305 # Clear the cached article id so the interface doesn't act like we exist
2306 $this->mTitle
->resetArticleID( 0 );
2310 * Roll back the most recent consecutive set of edits to a page
2311 * from the same user; fails if there are no eligible edits to
2312 * roll back to, e.g. user is the sole contributor. This function
2313 * performs permissions checks on $user, then calls commitRollback()
2314 * to do the dirty work
2316 * @todo: seperate the business/permission stuff out from backend code
2318 * @param $fromP String: Name of the user whose edits to rollback.
2319 * @param $summary String: Custom summary. Set to default summary if empty.
2320 * @param $token String: Rollback token.
2321 * @param $bot Boolean: If true, mark all reverted edits as bot.
2323 * @param $resultDetails Array: contains result-specific array of additional values
2324 * 'alreadyrolled' : 'current' (rev)
2325 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2327 * @param $user User The user performing the rollback
2328 * @return array of errors, each error formatted as
2329 * array(messagekey, param1, param2, ...).
2330 * On success, the array is empty. This array can also be passed to
2331 * OutputPage::showPermissionsErrorPage().
2333 public function doRollback(
2334 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2336 $resultDetails = null;
2339 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2340 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2341 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2343 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2344 $errors[] = array( 'sessionfailure' );
2347 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2348 $errors[] = array( 'actionthrottledtext' );
2351 # If there were errors, bail out now
2352 if ( !empty( $errors ) ) {
2356 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2360 * Backend implementation of doRollback(), please refer there for parameter
2361 * and return value documentation
2363 * NOTE: This function does NOT check ANY permissions, it just commits the
2364 * rollback to the DB. Therefore, you should only call this function direct-
2365 * ly if you want to use custom permissions checks. If you don't, use
2366 * doRollback() instead.
2367 * @param $fromP String: Name of the user whose edits to rollback.
2368 * @param $summary String: Custom summary. Set to default summary if empty.
2369 * @param $bot Boolean: If true, mark all reverted edits as bot.
2371 * @param $resultDetails Array: contains result-specific array of additional values
2372 * @param $guser User The user performing the rollback
2375 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2376 global $wgUseRCPatrol, $wgContLang;
2378 $dbw = wfGetDB( DB_MASTER
);
2380 if ( wfReadOnly() ) {
2381 return array( array( 'readonlytext' ) );
2384 # Get the last editor
2385 $current = $this->getRevision();
2386 if ( is_null( $current ) ) {
2387 # Something wrong... no page?
2388 return array( array( 'notanarticle' ) );
2391 $from = str_replace( '_', ' ', $fromP );
2392 # User name given should match up with the top revision.
2393 # If the user was deleted then $from should be empty.
2394 if ( $from != $current->getUserText() ) {
2395 $resultDetails = array( 'current' => $current );
2396 return array( array( 'alreadyrolled',
2397 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2398 htmlspecialchars( $fromP ),
2399 htmlspecialchars( $current->getUserText() )
2403 # Get the last edit not by this guy...
2404 # Note: these may not be public values
2405 $user = intval( $current->getRawUser() );
2406 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2407 $s = $dbw->selectRow( 'revision',
2408 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2409 array( 'rev_page' => $current->getPage(),
2410 "rev_user != {$user} OR rev_user_text != {$user_text}"
2412 array( 'USE INDEX' => 'page_timestamp',
2413 'ORDER BY' => 'rev_timestamp DESC' )
2415 if ( $s === false ) {
2416 # No one else ever edited this page
2417 return array( array( 'cantrollback' ) );
2418 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2419 # Only admins can see this text
2420 return array( array( 'notvisiblerev' ) );
2424 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2425 # Mark all reverted edits as bot
2429 if ( $wgUseRCPatrol ) {
2430 # Mark all reverted edits as patrolled
2431 $set['rc_patrolled'] = 1;
2434 if ( count( $set ) ) {
2435 $dbw->update( 'recentchanges', $set,
2437 'rc_cur_id' => $current->getPage(),
2438 'rc_user_text' => $current->getUserText(),
2439 "rc_timestamp > '{$s->rev_timestamp}'",
2444 # Generate the edit summary if necessary
2445 $target = Revision
::newFromId( $s->rev_id
);
2446 if ( empty( $summary ) ) {
2447 if ( $from == '' ) { // no public user name
2448 $summary = wfMsgForContent( 'revertpage-nouser' );
2450 $summary = wfMsgForContent( 'revertpage' );
2454 # Allow the custom summary to use the same args as the default message
2456 $target->getUserText(), $from, $s->rev_id
,
2457 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2458 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2460 $summary = wfMsgReplaceArgs( $summary, $args );
2463 $flags = EDIT_UPDATE
;
2465 if ( $guser->isAllowed( 'minoredit' ) ) {
2466 $flags |
= EDIT_MINOR
;
2469 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2470 $flags |
= EDIT_FORCE_BOT
;
2473 # Actually store the edit
2474 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2475 if ( !empty( $status->value
['revision'] ) ) {
2476 $revId = $status->value
['revision']->getId();
2481 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2483 $resultDetails = array(
2484 'summary' => $summary,
2485 'current' => $current,
2486 'target' => $target,
2494 * The onArticle*() functions are supposed to be a kind of hooks
2495 * which should be called whenever any of the specified actions
2498 * This is a good place to put code to clear caches, for instance.
2500 * This is called on page move and undelete, as well as edit
2502 * @param $title Title object
2504 public static function onArticleCreate( $title ) {
2505 # Update existence markers on article/talk tabs...
2506 if ( $title->isTalkPage() ) {
2507 $other = $title->getSubjectPage();
2509 $other = $title->getTalkPage();
2512 $other->invalidateCache();
2513 $other->purgeSquid();
2515 $title->touchLinks();
2516 $title->purgeSquid();
2517 $title->deleteTitleProtection();
2521 * Clears caches when article is deleted
2523 * @param $title Title
2525 public static function onArticleDelete( $title ) {
2526 # Update existence markers on article/talk tabs...
2527 if ( $title->isTalkPage() ) {
2528 $other = $title->getSubjectPage();
2530 $other = $title->getTalkPage();
2533 $other->invalidateCache();
2534 $other->purgeSquid();
2536 $title->touchLinks();
2537 $title->purgeSquid();
2540 HTMLFileCache
::clearFileCache( $title );
2543 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2544 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2548 if ( $title->getNamespace() == NS_FILE
) {
2549 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2550 $update->doUpdate();
2554 if ( $title->getNamespace() == NS_USER_TALK
) {
2555 $user = User
::newFromName( $title->getText(), false );
2557 $user->setNewtalk( false );
2562 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2566 * Purge caches on page update etc
2568 * @param $title Title object
2569 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2571 public static function onArticleEdit( $title ) {
2572 // Invalidate caches of articles which include this page
2573 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2576 // Invalidate the caches of all pages which redirect here
2577 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2579 # Purge squid for this page only
2580 $title->purgeSquid();
2582 # Clear file cache for this page only
2583 HTMLFileCache
::clearFileCache( $title );
2589 * Returns a list of hidden categories this page is a member of.
2590 * Uses the page_props and categorylinks tables.
2592 * @return Array of Title objects
2594 public function getHiddenCategories() {
2596 $id = $this->mTitle
->getArticleID();
2602 $dbr = wfGetDB( DB_SLAVE
);
2603 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2605 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2606 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2609 if ( $res !== false ) {
2610 foreach ( $res as $row ) {
2611 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2619 * Return an applicable autosummary if one exists for the given edit.
2620 * @param $oldtext String: the previous text of the page.
2621 * @param $newtext String: The submitted text of the page.
2622 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2623 * @return string An appropriate autosummary, or an empty string.
2624 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
2626 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2627 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2629 $handler = ContentHandler
::getForModelName( CONTENT_MODEL_WIKITEXT
);
2630 $oldContent = $oldtext ?
$handler->unserialize( $oldtext ) : null;
2631 $newContent = $newtext ?
$handler->unserialize( $newtext ) : null;
2633 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2637 * Auto-generates a deletion reason
2639 * @param &$hasHistory Boolean: whether the page has a history
2640 * @return mixed String containing deletion reason or empty string, or boolean false
2641 * if no revision occurred
2642 * @deprecated since 1.20, use ContentHandler::getAutoDeleteReason() instead
2644 public function getAutoDeleteReason( &$hasHistory ) {
2645 #NOTE: stub for backwards-compatibility.
2647 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2648 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2651 // Get the last revision
2652 $rev = $this->getRevision();
2654 if ( is_null( $rev ) ) {
2658 // Get the article's contents
2659 $contents = $rev->getText();
2662 // If the page is blank, use the text from the previous revision,
2663 // which can only be blank if there's a move/import/protect dummy revision involved
2664 if ( $contents == '' ) {
2665 $prev = $rev->getPrevious();
2668 $contents = $prev->getText();
2673 $dbw = wfGetDB( DB_MASTER
);
2675 // Find out if there was only one contributor
2676 // Only scan the last 20 revisions
2677 $res = $dbw->select( 'revision', 'rev_user_text',
2678 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2680 array( 'LIMIT' => 20 )
2683 if ( $res === false ) {
2684 // This page has no revisions, which is very weird
2688 $hasHistory = ( $res->numRows() > 1 );
2689 $row = $dbw->fetchObject( $res );
2691 if ( $row ) { // $row is false if the only contributor is hidden
2692 $onlyAuthor = $row->rev_user_text
;
2693 // Try to find a second contributor
2694 foreach ( $res as $row ) {
2695 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2696 $onlyAuthor = false;
2701 $onlyAuthor = false;
2704 // Generate the summary with a '$1' placeholder
2706 // The current revision is blank and the one before is also
2707 // blank. It's just not our lucky day
2708 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2710 if ( $onlyAuthor ) {
2711 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2713 $reason = wfMsgForContent( 'excontent', '$1' );
2717 if ( $reason == '-' ) {
2718 // Allow these UI messages to be blanked out cleanly
2722 // Replace newlines with spaces to prevent uglyness
2723 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2724 // Calculate the maximum amount of chars to get
2725 // Max content length = max comment length - length of the comment (excl. $1)
2726 $maxLength = 255 - ( strlen( $reason ) - 2 );
2727 $contents = $wgContLang->truncate( $contents, $maxLength );
2728 // Remove possible unfinished links
2729 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2730 // Now replace the '$1' placeholder
2731 $reason = str_replace( '$1', $contents, $reason );
2737 * Update all the appropriate counts in the category table, given that
2738 * we've added the categories $added and deleted the categories $deleted.
2740 * @param $added array The names of categories that were added
2741 * @param $deleted array The names of categories that were deleted
2743 public function updateCategoryCounts( $added, $deleted ) {
2744 $ns = $this->mTitle
->getNamespace();
2745 $dbw = wfGetDB( DB_MASTER
);
2747 # First make sure the rows exist. If one of the "deleted" ones didn't
2748 # exist, we might legitimately not create it, but it's simpler to just
2749 # create it and then give it a negative value, since the value is bogus
2752 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2753 $insertCats = array_merge( $added, $deleted );
2754 if ( !$insertCats ) {
2755 # Okay, nothing to do
2759 $insertRows = array();
2761 foreach ( $insertCats as $cat ) {
2762 $insertRows[] = array(
2763 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2767 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2769 $addFields = array( 'cat_pages = cat_pages + 1' );
2770 $removeFields = array( 'cat_pages = cat_pages - 1' );
2772 if ( $ns == NS_CATEGORY
) {
2773 $addFields[] = 'cat_subcats = cat_subcats + 1';
2774 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2775 } elseif ( $ns == NS_FILE
) {
2776 $addFields[] = 'cat_files = cat_files + 1';
2777 $removeFields[] = 'cat_files = cat_files - 1';
2784 array( 'cat_title' => $added ),
2793 array( 'cat_title' => $deleted ),
2800 * Updates cascading protections
2802 * @param $parserOutput ParserOutput object for the current version
2804 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2805 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2809 // templatelinks table may have become out of sync,
2810 // especially if using variable-based transclusions.
2811 // For paranoia, check if things have changed and if
2812 // so apply updates to the database. This will ensure
2813 // that cascaded protections apply as soon as the changes
2816 # Get templates from templatelinks
2817 $id = $this->mTitle
->getArticleID();
2819 $tlTemplates = array();
2821 $dbr = wfGetDB( DB_SLAVE
);
2822 $res = $dbr->select( array( 'templatelinks' ),
2823 array( 'tl_namespace', 'tl_title' ),
2824 array( 'tl_from' => $id ),
2828 foreach ( $res as $row ) {
2829 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2832 # Get templates from parser output.
2833 $poTemplates = array();
2834 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2835 foreach ( $templates as $dbk => $id ) {
2836 $poTemplates["$ns:$dbk"] = true;
2841 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2843 if ( count( $templates_diff ) > 0 ) {
2844 # Whee, link updates time.
2845 # Note: we are only interested in links here. We don't need to get other SecondaryDataUpdate items from the parser output.
2846 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2852 * Return a list of templates used by this article.
2853 * Uses the templatelinks table
2855 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2856 * @return Array of Title objects
2858 public function getUsedTemplates() {
2859 return $this->mTitle
->getTemplateLinksFrom();
2863 * Perform article updates on a special page creation.
2865 * @param $rev Revision object
2867 * @todo This is a shitty interface function. Kill it and replace the
2868 * other shitty functions like doEditUpdates and such so it's not needed
2870 * @deprecated since 1.18, use doEditUpdates()
2872 public function createUpdates( $rev ) {
2873 wfDeprecated( __METHOD__
, '1.18' );
2875 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2879 * This function is called right before saving the wikitext,
2880 * so we can do things like signatures and links-in-context.
2882 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2883 * @param $text String article contents
2884 * @param $user User object: user doing the edit
2885 * @param $popts ParserOptions object: parser options, default options for
2886 * the user loaded if null given
2887 * @return string article contents with altered wikitext markup (signatures
2888 * converted, {{subst:}}, templates, etc.)
2890 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2891 global $wgParser, $wgUser;
2893 wfDeprecated( __METHOD__
, '1.19' );
2895 $user = is_null( $user ) ?
$wgUser : $user;
2897 if ( $popts === null ) {
2898 $popts = ParserOptions
::newFromUser( $user );
2901 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2905 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2907 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2910 public function isBigDeletion() {
2911 wfDeprecated( __METHOD__
, '1.19' );
2912 return $this->mTitle
->isBigDeletion();
2916 * Get the approximate revision count of this page.
2918 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2921 public function estimateRevisionCount() {
2922 wfDeprecated( __METHOD__
, '1.19' );
2923 return $this->mTitle
->estimateRevisionCount();
2927 * Update the article's restriction field, and leave a log entry.
2929 * @deprecated since 1.19
2930 * @param $limit Array: set of restriction keys
2931 * @param $reason String
2932 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2933 * @param $expiry Array: per restriction type expiration
2934 * @param $user User The user updating the restrictions
2935 * @return bool true on success
2937 public function updateRestrictions(
2938 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2942 $user = is_null( $user ) ?
$wgUser : $user;
2944 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2948 * @deprecated since 1.18
2950 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2951 wfDeprecated( __METHOD__
, '1.18' );
2953 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2957 * @deprecated since 1.18
2959 public function viewUpdates() {
2960 wfDeprecated( __METHOD__
, '1.18' );
2962 return $this->doViewUpdates( $wgUser );
2966 * @deprecated since 1.18
2969 public function useParserCache( $oldid ) {
2970 wfDeprecated( __METHOD__
, '1.18' );
2972 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2976 class PoolWorkArticleView
extends PoolCounterWork
{
2994 * @var ParserOptions
2996 private $parserOptions;
3004 * @var ParserOutput|bool
3006 private $parserOutput = false;
3011 private $isDirty = false;
3016 private $error = false;
3022 * @param $revid Integer: ID of the revision being parsed
3023 * @param $useParserCache Boolean: whether to use the parser cache
3024 * @param $parserOptions parserOptions to use for the parse operation
3025 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3027 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3028 if ( is_string($content) ) { #BC: old style call
3029 $modelName = $page->getRevision()->getContentModelName();
3030 $format = $page->getRevision()->getContentFormat();
3031 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelName, $format );
3034 $this->page
= $page;
3035 $this->revid
= $revid;
3036 $this->cacheable
= $useParserCache;
3037 $this->parserOptions
= $parserOptions;
3038 $this->content
= $content;
3039 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3040 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3044 * Get the ParserOutput from this object, or false in case of failure
3046 * @return ParserOutput
3048 public function getParserOutput() {
3049 return $this->parserOutput
;
3053 * Get whether the ParserOutput is a dirty one (i.e. expired)
3057 public function getIsDirty() {
3058 return $this->isDirty
;
3062 * Get a Status object in case of error or false otherwise
3064 * @return Status|bool
3066 public function getError() {
3067 return $this->error
;
3074 global $wgParser, $wgUseFileCache;
3076 $isCurrent = $this->revid
=== $this->page
->getLatest();
3078 if ( $this->content
!== null ) {
3079 $content = $this->content
;
3080 } elseif ( $isCurrent ) {
3081 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
3083 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3084 if ( $rev === null ) {
3087 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3090 $time = - microtime( true );
3091 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3092 $time +
= microtime( true );
3096 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3097 $this->page
->getTitle()->getPrefixedDBkey() ) );
3100 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3101 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3104 // Make sure file cache is not used on uncacheable content.
3105 // Output that has magic words in it can still use the parser cache
3106 // (if enabled), though it will generally expire sooner.
3107 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3108 $wgUseFileCache = false;
3112 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3121 function getCachedWork() {
3122 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3124 if ( $this->parserOutput
=== false ) {
3125 wfDebug( __METHOD__
. ": parser cache miss\n" );
3128 wfDebug( __METHOD__
. ": parser cache hit\n" );
3136 function fallback() {
3137 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3139 if ( $this->parserOutput
=== false ) {
3140 wfDebugLog( 'dirty', "dirty missing\n" );
3141 wfDebug( __METHOD__
. ": no dirty cache\n" );
3144 wfDebug( __METHOD__
. ": sending dirty output\n" );
3145 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3146 $this->isDirty
= true;
3152 * @param $status Status
3155 function error( $status ) {
3156 $this->error
= $status;