3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
6 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
7 // values greater than zero indicate that there were non-fatal problems.
10 * Delete operation aborted by hook
12 const DELETE_HOOK_ABORTED
= -1;
17 const DELETE_SUCCESS
= 0;
22 const DELETE_NO_PAGE
= 1;
25 * No revisions found to delete
27 const DELETE_NO_REVISIONS
= 2;
31 * Class representing a MediaWiki article and history.
33 * Some fields are public only for backwards-compatibility. Use accessors.
34 * In the past, this class was part of Article.php and everything was public.
36 * @internal documentation reviewed 15 Mar 2010
38 class WikiPage
extends Page
{
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
56 protected $mRedirectTarget = null;
61 protected $mLastRevision = null;
64 * @var string; timestamp of the current revision or empty string if not loaded
66 protected $mTimestamp = '';
71 protected $mTouched = '19700101000000';
76 protected $mCounter = null;
79 * Constructor and clear the article
80 * @param $title Title Reference to a Title object.
82 public function __construct( Title
$title ) {
83 $this->mTitle
= $title;
87 * Create a WikiPage object of the appropriate class for the given title.
90 * @return WikiPage object of the appropriate type
92 public static function factory( Title
$title ) {
93 $ns = $title->getNamespace();
95 if ( $ns == NS_MEDIA
) {
96 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
97 } elseif ( $ns < 0 ) {
98 throw new MWException( "Invalid or virtual namespace $ns given." );
103 $page = new WikiFilePage( $title );
106 $page = new WikiCategoryPage( $title );
109 $page = new WikiPage( $title );
116 * Constructor from a page id
118 * @param $id Int article ID to load
122 public static function newFromID( $id ) {
123 $t = Title
::newFromID( $id );
125 return self
::factory( $t );
131 * Returns overrides for action handlers.
132 * Classes listed here will be used instead of the default one when
133 * (and only when) $wgActions[$action] === true. This allows subclasses
134 * to override the default behavior.
136 * @todo: move this UI stuff somewhere else
140 public function getActionOverrides() {
145 * Get the title object of the article
146 * @return Title object of this page
148 public function getTitle() {
149 return $this->mTitle
;
155 public function clear() {
156 $this->mDataLoaded
= false;
158 $this->mCounter
= null;
159 $this->mRedirectTarget
= null; # Title object if set
160 $this->mLastRevision
= null; # Latest revision
161 $this->mTouched
= '19700101000000';
162 $this->mTimestamp
= '';
163 $this->mIsRedirect
= false;
164 $this->mLatest
= false;
165 $this->mPreparedEdit
= false;
169 * Return the list of revision fields that should be selected to create
174 public static function selectFields() {
191 * Fetch a page record with the given conditions
192 * @param $dbr DatabaseBase object
193 * @param $conditions Array
194 * @return mixed Database result resource, or false on failure
196 protected function pageData( $dbr, $conditions ) {
197 $fields = self
::selectFields();
199 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
201 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
203 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
209 * Fetch a page record matching the Title object's namespace and title
210 * using a sanitized title string
212 * @param $dbr DatabaseBase object
213 * @param $title Title object
214 * @return mixed Database result resource, or false on failure
216 public function pageDataFromTitle( $dbr, $title ) {
217 return $this->pageData( $dbr, array(
218 'page_namespace' => $title->getNamespace(),
219 'page_title' => $title->getDBkey() ) );
223 * Fetch a page record matching the requested ID
225 * @param $dbr DatabaseBase
227 * @return mixed Database result resource, or false on failure
229 public function pageDataFromId( $dbr, $id ) {
230 return $this->pageData( $dbr, array( 'page_id' => $id ) );
234 * Set the general counter, title etc data loaded from
237 * @param $data Object|String One of the following:
238 * A DB query result object or...
239 * "fromdb" to get from a slave DB or...
240 * "fromdbmaster" to get from the master DB
243 public function loadPageData( $data = 'fromdb' ) {
244 if ( $data === 'fromdbmaster' ) {
245 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
246 } elseif ( $data === 'fromdb' ) { // slave
247 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
248 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
249 # Note that DB also stores the master position in the session and checks it.
250 $touched = $this->getCachedLastEditTime();
251 if ( $touched ) { // key set
252 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
253 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
258 $lc = LinkCache
::singleton();
261 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
263 $this->mTitle
->loadFromRow( $data );
265 # Old-fashioned restrictions
266 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
268 $this->mCounter
= intval( $data->page_counter
);
269 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
270 $this->mIsRedirect
= intval( $data->page_is_redirect
);
271 $this->mLatest
= intval( $data->page_latest
);
273 $lc->addBadLinkObj( $this->mTitle
);
275 $this->mTitle
->loadFromRow( false );
278 $this->mDataLoaded
= true;
282 * @return int Page ID
284 public function getId() {
285 return $this->mTitle
->getArticleID();
289 * @return bool Whether or not the page exists in the database
291 public function exists() {
292 return $this->mTitle
->exists();
296 * Check if this page is something we're going to be showing
297 * some sort of sensible content for. If we return false, page
298 * views (plain action=view) will return an HTTP 404 response,
299 * so spiders and robots can know they're following a bad link.
303 public function hasViewableContent() {
304 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
308 * @return int The view count for the page
310 public function getCount() {
311 if ( !$this->mDataLoaded
) {
312 $this->loadPageData();
315 return $this->mCounter
;
319 * Tests if the article text represents a redirect
321 * @param $text mixed string containing article contents, or boolean
324 public function isRedirect( $text = false ) {
325 if ( $text === false ) {
326 if ( !$this->mDataLoaded
) {
327 $this->loadPageData();
330 return (bool)$this->mIsRedirect
;
332 return Title
::newFromRedirect( $text ) !== null;
337 * Loads page_touched and returns a value indicating if it should be used
338 * @return boolean true if not a redirect
340 public function checkTouched() {
341 if ( !$this->mDataLoaded
) {
342 $this->loadPageData();
344 return !$this->mIsRedirect
;
348 * Get the page_touched field
349 * @return string containing GMT timestamp
351 public function getTouched() {
352 if ( !$this->mDataLoaded
) {
353 $this->loadPageData();
355 return $this->mTouched
;
359 * Get the page_latest field
360 * @return integer rev_id of current revision
362 public function getLatest() {
363 if ( !$this->mDataLoaded
) {
364 $this->loadPageData();
366 return (int)$this->mLatest
;
370 * Loads everything except the text
371 * This isn't necessary for all uses, so it's only done if needed.
373 protected function loadLastEdit() {
374 if ( $this->mLastRevision
!== null ) {
375 return; // already loaded
378 $latest = $this->getLatest();
380 return; // page doesn't exist or is missing page_latest info
383 $revision = Revision
::newFromPageId( $this->getId(), $latest );
384 if ( $revision ) { // sanity
385 $this->setLastEdit( $revision );
390 * Set the latest revision
392 protected function setLastEdit( Revision
$revision ) {
393 $this->mLastRevision
= $revision;
394 $this->mTimestamp
= $revision->getTimestamp();
398 * Get the latest revision
399 * @return Revision|null
401 public function getRevision() {
402 $this->loadLastEdit();
403 if ( $this->mLastRevision
) {
404 return $this->mLastRevision
;
410 * Get the text of the current revision. No side-effects...
412 * @param $audience Integer: one of:
413 * Revision::FOR_PUBLIC to be displayed to all users
414 * Revision::FOR_THIS_USER to be displayed to $wgUser
415 * Revision::RAW get the text regardless of permissions
416 * @return String|false The text of the current revision
418 public function getText( $audience = Revision
::FOR_PUBLIC
) {
419 $this->loadLastEdit();
420 if ( $this->mLastRevision
) {
421 return $this->mLastRevision
->getText( $audience );
427 * Get the text of the current revision. No side-effects...
429 * @return String|false The text of the current revision
431 public function getRawText() {
432 $this->loadLastEdit();
433 if ( $this->mLastRevision
) {
434 return $this->mLastRevision
->getRawText();
440 * @return string MW timestamp of last article revision
442 public function getTimestamp() {
443 // Check if the field has been filled by WikiPage::setTimestamp()
444 if ( !$this->mTimestamp
) {
445 $this->loadLastEdit();
447 return wfTimestamp( TS_MW
, $this->mTimestamp
);
451 * Set the page timestamp (use only to avoid DB queries)
452 * @param $ts string MW timestamp of last article revision
455 public function setTimestamp( $ts ) {
456 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
460 * @param $audience Integer: one of:
461 * Revision::FOR_PUBLIC to be displayed to all users
462 * Revision::FOR_THIS_USER to be displayed to $wgUser
463 * Revision::RAW get the text regardless of permissions
464 * @return int user ID for the user that made the last article revision
466 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
467 $this->loadLastEdit();
468 if ( $this->mLastRevision
) {
469 return $this->mLastRevision
->getUser( $audience );
476 * @param $audience Integer: one of:
477 * Revision::FOR_PUBLIC to be displayed to all users
478 * Revision::FOR_THIS_USER to be displayed to $wgUser
479 * Revision::RAW get the text regardless of permissions
480 * @return string username of the user that made the last article revision
482 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
483 $this->loadLastEdit();
484 if ( $this->mLastRevision
) {
485 return $this->mLastRevision
->getUserText( $audience );
492 * @param $audience Integer: one of:
493 * Revision::FOR_PUBLIC to be displayed to all users
494 * Revision::FOR_THIS_USER to be displayed to $wgUser
495 * Revision::RAW get the text regardless of permissions
496 * @return string Comment stored for the last article revision
498 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
499 $this->loadLastEdit();
500 if ( $this->mLastRevision
) {
501 return $this->mLastRevision
->getComment( $audience );
508 * Returns true if last revision was marked as "minor edit"
510 * @return boolean Minor edit indicator for the last article revision.
512 public function getMinorEdit() {
513 $this->loadLastEdit();
514 if ( $this->mLastRevision
) {
515 return $this->mLastRevision
->isMinor();
522 * Get the cached timestamp for the last time the page changed.
523 * This is only used to help handle slave lag by comparing to page_touched.
524 * @return string MW timestamp
526 protected function getCachedLastEditTime() {
528 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
529 return $wgMemc->get( $key );
533 * Set the cached timestamp for the last time the page changed.
534 * This is only used to help handle slave lag by comparing to page_touched.
535 * @param $timestamp string
538 public function setCachedLastEditTime( $timestamp ) {
540 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
541 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
545 * Determine whether a page would be suitable for being counted as an
546 * article in the site_stats table based on the title & its content
548 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
549 * if false, the current database state will be used
552 public function isCountable( $editInfo = false ) {
553 global $wgArticleCountMethod;
555 if ( !$this->mTitle
->isContentPage() ) {
559 $text = $editInfo ?
$editInfo->pst
: false;
561 if ( $this->isRedirect( $text ) ) {
565 switch ( $wgArticleCountMethod ) {
569 if ( $text === false ) {
570 $text = $this->getRawText();
572 return strpos( $text, ',' ) !== false;
575 // ParserOutput::getLinks() is a 2D array of page links, so
576 // to be really correct we would need to recurse in the array
577 // but the main array should only have items in it if there are
579 return (bool)count( $editInfo->output
->getLinks() );
581 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
582 array( 'pl_from' => $this->getId() ), __METHOD__
);
588 * If this page is a redirect, get its target
590 * The target will be fetched from the redirect table if possible.
591 * If this page doesn't have an entry there, call insertRedirect()
592 * @return Title|mixed object, or null if this page is not a redirect
594 public function getRedirectTarget() {
595 if ( !$this->mTitle
->isRedirect() ) {
599 if ( $this->mRedirectTarget
!== null ) {
600 return $this->mRedirectTarget
;
603 # Query the redirect table
604 $dbr = wfGetDB( DB_SLAVE
);
605 $row = $dbr->selectRow( 'redirect',
606 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
607 array( 'rd_from' => $this->getId() ),
611 // rd_fragment and rd_interwiki were added later, populate them if empty
612 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
613 return $this->mRedirectTarget
= Title
::makeTitle(
614 $row->rd_namespace
, $row->rd_title
,
615 $row->rd_fragment
, $row->rd_interwiki
);
618 # This page doesn't have an entry in the redirect table
619 return $this->mRedirectTarget
= $this->insertRedirect();
623 * Insert an entry for this page into the redirect table.
625 * Don't call this function directly unless you know what you're doing.
626 * @return Title object or null if not a redirect
628 public function insertRedirect() {
629 // recurse through to only get the final target
630 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
634 $this->insertRedirectEntry( $retval );
639 * Insert or update the redirect table entry for this page to indicate
640 * it redirects to $rt .
641 * @param $rt Title redirect target
643 public function insertRedirectEntry( $rt ) {
644 $dbw = wfGetDB( DB_MASTER
);
645 $dbw->replace( 'redirect', array( 'rd_from' ),
647 'rd_from' => $this->getId(),
648 'rd_namespace' => $rt->getNamespace(),
649 'rd_title' => $rt->getDBkey(),
650 'rd_fragment' => $rt->getFragment(),
651 'rd_interwiki' => $rt->getInterwiki(),
658 * Get the Title object or URL this page redirects to
660 * @return mixed false, Title of in-wiki target, or string with URL
662 public function followRedirect() {
663 return $this->getRedirectURL( $this->getRedirectTarget() );
667 * Get the Title object or URL to use for a redirect. We use Title
668 * objects for same-wiki, non-special redirects and URLs for everything
670 * @param $rt Title Redirect target
671 * @return mixed false, Title object of local target, or string with URL
673 public function getRedirectURL( $rt ) {
678 if ( $rt->isExternal() ) {
679 if ( $rt->isLocal() ) {
680 // Offsite wikis need an HTTP redirect.
682 // This can be hard to reverse and may produce loops,
683 // so they may be disabled in the site configuration.
684 $source = $this->mTitle
->getFullURL( 'redirect=no' );
685 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
687 // External pages pages without "local" bit set are not valid
693 if ( $rt->isSpecialPage() ) {
694 // Gotta handle redirects to special pages differently:
695 // Fill the HTTP response "Location" header and ignore
696 // the rest of the page we're on.
698 // Some pages are not valid targets
699 if ( $rt->isValidRedirectTarget() ) {
700 return $rt->getFullURL();
710 * Get a list of users who have edited this article, not including the user who made
711 * the most recent revision, which you can get from $article->getUser() if you want it
712 * @return UserArrayFromResult
714 public function getContributors() {
715 # @todo FIXME: This is expensive; cache this info somewhere.
717 $dbr = wfGetDB( DB_SLAVE
);
719 if ( $dbr->implicitGroupby() ) {
720 $realNameField = 'user_real_name';
722 $realNameField = 'MIN(user_real_name) AS user_real_name';
725 $tables = array( 'revision', 'user' );
728 'rev_user as user_id',
729 'rev_user_text AS user_name',
731 'MAX(rev_timestamp) AS timestamp',
734 $conds = array( 'rev_page' => $this->getId() );
736 // The user who made the top revision gets credited as "this page was last edited by
737 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
738 $user = $this->getUser();
740 $conds[] = "rev_user != $user";
742 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
745 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
748 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
752 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
753 'ORDER BY' => 'timestamp DESC',
756 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
757 return new UserArrayFromResult( $res );
761 * Get the last N authors
762 * @param $num Integer: number of revisions to get
763 * @param $revLatest String: the latest rev_id, selected from the master (optional)
764 * @return array Array of authors, duplicates not removed
766 public function getLastNAuthors( $num, $revLatest = 0 ) {
767 wfProfileIn( __METHOD__
);
768 // First try the slave
769 // If that doesn't have the latest revision, try the master
771 $db = wfGetDB( DB_SLAVE
);
774 $res = $db->select( array( 'page', 'revision' ),
775 array( 'rev_id', 'rev_user_text' ),
777 'page_namespace' => $this->mTitle
->getNamespace(),
778 'page_title' => $this->mTitle
->getDBkey(),
782 'ORDER BY' => 'rev_timestamp DESC',
788 wfProfileOut( __METHOD__
);
792 $row = $db->fetchObject( $res );
794 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
795 $db = wfGetDB( DB_MASTER
);
800 } while ( $continue );
802 $authors = array( $row->rev_user_text
);
804 foreach ( $res as $row ) {
805 $authors[] = $row->rev_user_text
;
808 wfProfileOut( __METHOD__
);
813 * Should the parser cache be used?
815 * @param $parserOptions ParserOptions to check
819 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
820 global $wgEnableParserCache;
822 return $wgEnableParserCache
823 && $parserOptions->getStubThreshold() == 0
824 && $this->mTitle
->exists()
825 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
826 && $this->mTitle
->isWikitextPage();
830 * Get a ParserOutput for the given ParserOptions and revision ID.
831 * The parser cache will be used if possible.
834 * @param $parserOptions ParserOptions to use for the parse operation
835 * @param $oldid Revision ID to get the text from, passing null or 0 will
836 * get the current revision (default value)
837 * @return ParserOutput or false if the revision was not found
839 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
840 wfProfileIn( __METHOD__
);
842 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
843 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
844 if ( $parserOptions->getStubThreshold() ) {
845 wfIncrStats( 'pcache_miss_stub' );
848 if ( $useParserCache ) {
849 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
850 if ( $parserOutput !== false ) {
851 wfProfileOut( __METHOD__
);
852 return $parserOutput;
856 if ( $oldid === null ||
$oldid === 0 ) {
857 $oldid = $this->getLatest();
860 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
863 wfProfileOut( __METHOD__
);
865 return $pool->getParserOutput();
869 * Do standard deferred updates after page view
870 * @param $user User The relevant user
872 public function doViewUpdates( User
$user ) {
873 global $wgDisableCounters;
874 if ( wfReadOnly() ) {
878 # Don't update page view counters on views from bot users (bug 14044)
879 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
880 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
881 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
884 # Update newtalk / watchlist notification status
885 $user->clearNotification( $this->mTitle
);
889 * Perform the actions of a page purging
891 public function doPurge() {
894 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
898 // Invalidate the cache
899 $this->mTitle
->invalidateCache();
903 // Commit the transaction before the purge is sent
904 $dbw = wfGetDB( DB_MASTER
);
908 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
912 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
913 if ( $this->mTitle
->exists() ) {
914 $text = $this->getRawText();
919 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
925 * Insert a new empty page record for this article.
926 * This *must* be followed up by creating a revision
927 * and running $this->updateRevisionOn( ... );
928 * or else the record will be left in a funky state.
929 * Best if all done inside a transaction.
931 * @param $dbw DatabaseBase
932 * @return int The newly created page_id key, or false if the title already existed
934 public function insertOn( $dbw ) {
935 wfProfileIn( __METHOD__
);
937 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
938 $dbw->insert( 'page', array(
939 'page_id' => $page_id,
940 'page_namespace' => $this->mTitle
->getNamespace(),
941 'page_title' => $this->mTitle
->getDBkey(),
943 'page_restrictions' => '',
944 'page_is_redirect' => 0, # Will set this shortly...
946 'page_random' => wfRandom(),
947 'page_touched' => $dbw->timestamp(),
948 'page_latest' => 0, # Fill this in shortly...
949 'page_len' => 0, # Fill this in shortly...
950 ), __METHOD__
, 'IGNORE' );
952 $affected = $dbw->affectedRows();
955 $newid = $dbw->insertId();
956 $this->mTitle
->resetArticleID( $newid );
958 wfProfileOut( __METHOD__
);
960 return $affected ?
$newid : false;
964 * Update the page record to point to a newly saved revision.
966 * @param $dbw DatabaseBase: object
967 * @param $revision Revision: For ID number, and text used to set
968 * length and redirect status fields
969 * @param $lastRevision Integer: if given, will not overwrite the page field
970 * when different from the currently set value.
971 * Giving 0 indicates the new page flag should be set
973 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
974 * removing rows in redirect table.
975 * @return bool true on success, false on failure
978 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
979 wfProfileIn( __METHOD__
);
981 $text = $revision->getText();
982 $len = strlen( $text );
983 $rt = Title
::newFromRedirectRecurse( $text );
985 $conditions = array( 'page_id' => $this->getId() );
987 if ( !is_null( $lastRevision ) ) {
988 # An extra check against threads stepping on each other
989 $conditions['page_latest'] = $lastRevision;
992 $now = wfTimestampNow();
993 $dbw->update( 'page',
995 'page_latest' => $revision->getId(),
996 'page_touched' => $dbw->timestamp( $now ),
997 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
998 'page_is_redirect' => $rt !== null ?
1 : 0,
1004 $result = $dbw->affectedRows() != 0;
1006 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1007 $this->setLastEdit( $revision );
1008 $this->setCachedLastEditTime( $now );
1009 $this->mLatest
= $revision->getId();
1010 $this->mIsRedirect
= (bool)$rt;
1011 # Update the LinkCache.
1012 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1015 wfProfileOut( __METHOD__
);
1020 * Add row to the redirect table if this is a redirect, remove otherwise.
1022 * @param $dbw DatabaseBase
1023 * @param $redirectTitle Title object pointing to the redirect target,
1024 * or NULL if this is not a redirect
1025 * @param $lastRevIsRedirect If given, will optimize adding and
1026 * removing rows in redirect table.
1027 * @return bool true on success, false on failure
1030 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1031 // Always update redirects (target link might have changed)
1032 // Update/Insert if we don't know if the last revision was a redirect or not
1033 // Delete if changing from redirect to non-redirect
1034 $isRedirect = !is_null( $redirectTitle );
1036 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1040 wfProfileIn( __METHOD__
);
1041 if ( $isRedirect ) {
1042 $this->insertRedirectEntry( $redirectTitle );
1044 // This is not a redirect, remove row from redirect table
1045 $where = array( 'rd_from' => $this->getId() );
1046 $dbw->delete( 'redirect', $where, __METHOD__
);
1049 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1050 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1052 wfProfileOut( __METHOD__
);
1054 return ( $dbw->affectedRows() != 0 );
1058 * If the given revision is newer than the currently set page_latest,
1059 * update the page record. Otherwise, do nothing.
1061 * @param $dbw Database object
1062 * @param $revision Revision object
1065 public function updateIfNewerOn( $dbw, $revision ) {
1066 wfProfileIn( __METHOD__
);
1068 $row = $dbw->selectRow(
1069 array( 'revision', 'page' ),
1070 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1072 'page_id' => $this->getId(),
1073 'page_latest=rev_id' ),
1077 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1078 wfProfileOut( __METHOD__
);
1081 $prev = $row->rev_id
;
1082 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1084 # No or missing previous revision; mark the page as new
1086 $lastRevIsRedirect = null;
1089 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1091 wfProfileOut( __METHOD__
);
1096 * Get the text that needs to be saved in order to undo all revisions
1097 * between $undo and $undoafter. Revisions must belong to the same page,
1098 * must exist and must not be deleted
1099 * @param $undo Revision
1100 * @param $undoafter Revision Must be an earlier revision than $undo
1101 * @return mixed string on success, false on failure
1103 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1104 $cur_text = $this->getRawText();
1105 if ( $cur_text === false ) {
1106 return false; // no page
1108 $undo_text = $undo->getText();
1109 $undoafter_text = $undoafter->getText();
1111 if ( $cur_text == $undo_text ) {
1112 # No use doing a merge if it's just a straight revert.
1113 return $undoafter_text;
1118 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1122 return $undone_text;
1126 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1127 * @param $text String: new text of the section
1128 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1129 * @param $edittime String: revision timestamp or null to use the current revision
1130 * @return string Complete article text, or null if error
1132 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1133 wfProfileIn( __METHOD__
);
1135 if ( strval( $section ) == '' ) {
1136 // Whole-page edit; let the whole text through
1138 // Bug 30711: always use current version when adding a new section
1139 if ( is_null( $edittime ) ||
$section == 'new' ) {
1140 $oldtext = $this->getRawText();
1141 if ( $oldtext === false ) {
1142 wfDebug( __METHOD__
. ": no page text\n" );
1143 wfProfileOut( __METHOD__
);
1147 $dbw = wfGetDB( DB_MASTER
);
1148 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1151 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1152 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1153 wfProfileOut( __METHOD__
);
1157 $oldtext = $rev->getText();
1160 if ( $section == 'new' ) {
1161 # Inserting a new section
1162 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1163 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1164 $text = strlen( trim( $oldtext ) ) > 0
1165 ?
"{$oldtext}\n\n{$subject}{$text}"
1166 : "{$subject}{$text}";
1169 # Replacing an existing section; roll out the big guns
1172 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1176 wfProfileOut( __METHOD__
);
1181 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1183 * @return Int updated $flags
1185 function checkFlags( $flags ) {
1186 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1187 if ( $this->mTitle
->getArticleID() ) {
1188 $flags |
= EDIT_UPDATE
;
1198 * Change an existing article or create a new article. Updates RC and all necessary caches,
1199 * optionally via the deferred update array.
1201 * @param $text String: new text
1202 * @param $summary String: edit summary
1203 * @param $flags Integer bitfield:
1205 * Article is known or assumed to be non-existent, create a new one
1207 * Article is known or assumed to be pre-existing, update it
1209 * Mark this edit minor, if the user is allowed to do so
1211 * Do not log the change in recentchanges
1213 * Mark the edit a "bot" edit regardless of user rights
1214 * EDIT_DEFER_UPDATES
1215 * Defer some of the updates until the end of index.php
1217 * Fill in blank summaries with generated text where possible
1219 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1220 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1221 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1222 * edit-already-exists error will be returned. These two conditions are also possible with
1223 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1225 * @param $baseRevId the revision ID this edit was based off, if any
1226 * @param $user User the user doing the edit
1228 * @return Status object. Possible errors:
1229 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1230 * edit-gone-missing: In update mode, but the article didn't exist
1231 * edit-conflict: In update mode, the article changed unexpectedly
1232 * edit-no-change: Warning that the text was the same as before
1233 * edit-already-exists: In creation mode, but the article already exists
1235 * Extensions may define additional errors.
1237 * $return->value will contain an associative array with members as follows:
1238 * new: Boolean indicating if the function attempted to create a new article
1239 * revision: The revision object for the inserted revision, or null
1241 * Compatibility note: this function previously returned a boolean value indicating success/failure
1243 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1244 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1246 # Low-level sanity check
1247 if ( $this->mTitle
->getText() === '' ) {
1248 throw new MWException( 'Something is trying to edit an article with an empty title' );
1251 wfProfileIn( __METHOD__
);
1253 $user = is_null( $user ) ?
$wgUser : $user;
1254 $status = Status
::newGood( array() );
1256 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1257 $this->loadPageData( 'fromdbmaster' );
1259 $flags = $this->checkFlags( $flags );
1261 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1262 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1264 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1266 if ( $status->isOK() ) {
1267 $status->fatal( 'edit-hook-aborted' );
1270 wfProfileOut( __METHOD__
);
1274 # Silently ignore EDIT_MINOR if not allowed
1275 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1276 $bot = $flags & EDIT_FORCE_BOT
;
1278 $oldtext = $this->getRawText(); // current revision
1279 $oldsize = strlen( $oldtext );
1280 $oldid = $this->getLatest();
1281 $oldIsRedirect = $this->isRedirect();
1282 $oldcountable = $this->isCountable();
1284 # Provide autosummaries if one is not provided and autosummaries are enabled.
1285 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1286 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1289 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1290 $text = $editInfo->pst
;
1291 $newsize = strlen( $text );
1293 $dbw = wfGetDB( DB_MASTER
);
1294 $now = wfTimestampNow();
1295 $this->mTimestamp
= $now;
1297 if ( $flags & EDIT_UPDATE
) {
1298 # Update article, but only if changed.
1299 $status->value
['new'] = false;
1302 # Article gone missing
1303 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1304 $status->fatal( 'edit-gone-missing' );
1306 wfProfileOut( __METHOD__
);
1310 # Make sure the revision is either completely inserted or not inserted at all
1311 if ( !$wgDBtransactions ) {
1312 $userAbort = ignore_user_abort( true );
1315 $revision = new Revision( array(
1316 'page' => $this->getId(),
1317 'comment' => $summary,
1318 'minor_edit' => $isminor,
1320 'parent_id' => $oldid,
1321 'user' => $user->getId(),
1322 'user_text' => $user->getName(),
1326 $changed = ( strcmp( $text, $oldtext ) != 0 );
1330 $revisionId = $revision->insertOn( $dbw );
1334 # Note that we use $this->mLatest instead of fetching a value from the master DB
1335 # during the course of this function. This makes sure that EditPage can detect
1336 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1337 # before this function is called. A previous function used a separate query, this
1338 # creates a window where concurrent edits can cause an ignored edit conflict.
1339 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1342 /* Belated edit conflict! Run away!! */
1343 $status->fatal( 'edit-conflict' );
1345 # Delete the invalid revision if the DB is not transactional
1346 if ( !$wgDBtransactions ) {
1347 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1353 global $wgUseRCPatrol;
1354 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1355 # Update recentchanges
1356 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1357 # Mark as patrolled if the user can do so
1358 $patrolled = $wgUseRCPatrol && !count(
1359 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1360 # Add RC row to the DB
1361 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1362 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1363 $revisionId, $patrolled
1366 # Log auto-patrolled edits
1368 PatrolLog
::record( $rc, true );
1371 $user->incEditCount();
1375 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1376 // related variables correctly
1377 $revision->setId( $this->getLatest() );
1380 if ( !$wgDBtransactions ) {
1381 ignore_user_abort( $userAbort );
1384 // Now that ignore_user_abort is restored, we can respond to fatal errors
1385 if ( !$status->isOK() ) {
1386 wfProfileOut( __METHOD__
);
1390 # Update links tables, site stats, etc.
1391 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1392 'oldcountable' => $oldcountable ) );
1395 $status->warning( 'edit-no-change' );
1397 // Update page_touched, this is usually implicit in the page update
1398 // Other cache updates are done in onArticleEdit()
1399 $this->mTitle
->invalidateCache();
1402 # Create new article
1403 $status->value
['new'] = true;
1407 # Add the page record; stake our claim on this title!
1408 # This will return false if the article already exists
1409 $newid = $this->insertOn( $dbw );
1411 if ( $newid === false ) {
1413 $status->fatal( 'edit-already-exists' );
1415 wfProfileOut( __METHOD__
);
1419 # Save the revision text...
1420 $revision = new Revision( array(
1422 'comment' => $summary,
1423 'minor_edit' => $isminor,
1425 'user' => $user->getId(),
1426 'user_text' => $user->getName(),
1429 $revisionId = $revision->insertOn( $dbw );
1431 # Update the page record with revision data
1432 $this->updateRevisionOn( $dbw, $revision, 0 );
1434 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1436 # Update recentchanges
1437 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1438 global $wgUseRCPatrol, $wgUseNPPatrol;
1440 # Mark as patrolled if the user can do so
1441 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1442 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1443 # Add RC row to the DB
1444 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1445 '', strlen( $text ), $revisionId, $patrolled );
1447 # Log auto-patrolled edits
1449 PatrolLog
::record( $rc, true );
1452 $user->incEditCount();
1455 # Update links, etc.
1456 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1458 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1459 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1462 # Do updates right now unless deferral was requested
1463 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1464 DeferredUpdates
::doUpdates();
1467 // Return the new revision (or null) to the caller
1468 $status->value
['revision'] = $revision;
1470 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1471 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1473 # Promote user to any groups they meet the criteria for
1474 $user->addAutopromoteOnceGroups( 'onEdit' );
1476 wfProfileOut( __METHOD__
);
1481 * Get parser options suitable for rendering the primary article wikitext
1482 * @param User|string $user User object or 'canonical'
1483 * @return ParserOptions
1485 public function makeParserOptions( $user ) {
1487 if ( $user instanceof User
) { // settings per user (even anons)
1488 $options = ParserOptions
::newFromUser( $user );
1489 } else { // canonical settings
1490 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1492 $options->enableLimitReport(); // show inclusion/loop reports
1493 $options->setTidy( true ); // fix bad HTML
1498 * Prepare text which is about to be saved.
1499 * Returns a stdclass with source, pst and output members
1501 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1502 global $wgParser, $wgContLang, $wgUser;
1503 $user = is_null( $user ) ?
$wgUser : $user;
1504 // @TODO fixme: check $user->getId() here???
1505 if ( $this->mPreparedEdit
1506 && $this->mPreparedEdit
->newText
== $text
1507 && $this->mPreparedEdit
->revid
== $revid
1510 return $this->mPreparedEdit
;
1513 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1514 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1516 $edit = (object)array();
1517 $edit->revid
= $revid;
1518 $edit->newText
= $text;
1519 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1520 $edit->popts
= $this->makeParserOptions( 'canonical' );
1521 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1522 $edit->oldText
= $this->getRawText();
1524 $this->mPreparedEdit
= $edit;
1530 * Do standard deferred updates after page edit.
1531 * Update links tables, site stats, search index and message cache.
1532 * Purges pages that include this page if the text was changed here.
1533 * Every 100th edit, prune the recent changes table.
1536 * @param $revision Revision object
1537 * @param $user User object that did the revision
1538 * @param $options Array of options, following indexes are used:
1539 * - changed: boolean, whether the revision changed the content (default true)
1540 * - created: boolean, whether the revision created the page (default false)
1541 * - oldcountable: boolean or null (default null):
1542 * - boolean: whether the page was counted as an article before that
1543 * revision, only used in changed is true and created is false
1544 * - null: don't change the article count
1546 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1547 global $wgEnableParserCache;
1549 wfProfileIn( __METHOD__
);
1551 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1552 $text = $revision->getText();
1555 # Be careful not to double-PST: $text is usually already PST-ed once
1556 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1557 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1558 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1560 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1561 $editInfo = $this->mPreparedEdit
;
1564 # Save it to the parser cache
1565 if ( $wgEnableParserCache ) {
1566 $parserCache = ParserCache
::singleton();
1567 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1570 # Update the links tables
1571 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1574 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1576 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1577 if ( 0 == mt_rand( 0, 99 ) ) {
1578 // Flush old entries from the `recentchanges` table; we do this on
1579 // random requests so as to avoid an increase in writes for no good reason
1582 $dbw = wfGetDB( DB_MASTER
);
1583 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1586 array( "rc_timestamp < '$cutoff'" ),
1592 if ( !$this->mTitle
->exists() ) {
1593 wfProfileOut( __METHOD__
);
1597 $id = $this->getId();
1598 $title = $this->mTitle
->getPrefixedDBkey();
1599 $shortTitle = $this->mTitle
->getDBkey();
1601 if ( !$options['changed'] ) {
1604 } elseif ( $options['created'] ) {
1605 $good = (int)$this->isCountable( $editInfo );
1607 } elseif ( $options['oldcountable'] !== null ) {
1608 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1615 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1616 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1618 # If this is another user's talk page, update newtalk.
1619 # Don't do this if $options['changed'] = false (null-edits) nor if
1620 # it's a minor edit and the user doesn't want notifications for those.
1621 if ( $options['changed']
1622 && $this->mTitle
->getNamespace() == NS_USER_TALK
1623 && $shortTitle != $user->getTitleKey()
1624 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1626 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1627 $other = User
::newFromName( $shortTitle, false );
1629 wfDebug( __METHOD__
. ": invalid username\n" );
1630 } elseif ( User
::isIP( $shortTitle ) ) {
1631 // An anonymous user
1632 $other->setNewtalk( true );
1633 } elseif ( $other->isLoggedIn() ) {
1634 $other->setNewtalk( true );
1636 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1641 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1642 MessageCache
::singleton()->replace( $shortTitle, $text );
1645 if( $options['created'] ) {
1646 self
::onArticleCreate( $this->mTitle
);
1648 self
::onArticleEdit( $this->mTitle
);
1651 wfProfileOut( __METHOD__
);
1655 * Edit an article without doing all that other stuff
1656 * The article must already exist; link tables etc
1657 * are not updated, caches are not flushed.
1659 * @param $text String: text submitted
1660 * @param $user User The relevant user
1661 * @param $comment String: comment submitted
1662 * @param $minor Boolean: whereas it's a minor modification
1664 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1665 wfProfileIn( __METHOD__
);
1667 $dbw = wfGetDB( DB_MASTER
);
1668 $revision = new Revision( array(
1669 'page' => $this->getId(),
1671 'comment' => $comment,
1672 'minor_edit' => $minor ?
1 : 0,
1674 $revision->insertOn( $dbw );
1675 $this->updateRevisionOn( $dbw, $revision );
1677 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1679 wfProfileOut( __METHOD__
);
1683 * Update the article's restriction field, and leave a log entry.
1684 * This works for protection both existing and non-existing pages.
1686 * @param $limit Array: set of restriction keys
1687 * @param $reason String
1688 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1689 * @param $expiry Array: per restriction type expiration
1690 * @param $user User The user updating the restrictions
1691 * @return bool true on success
1693 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1696 if ( wfReadOnly() ) {
1697 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1700 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1702 $id = $this->mTitle
->getArticleID();
1708 // Take this opportunity to purge out expired restrictions
1709 Title
::purgeExpiredRestrictions();
1711 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1712 # we expect a single selection, but the schema allows otherwise.
1713 $isProtected = false;
1717 $dbw = wfGetDB( DB_MASTER
);
1719 foreach ( $restrictionTypes as $action ) {
1720 if ( !isset( $expiry[$action] ) ) {
1721 $expiry[$action] = $dbw->getInfinity();
1723 if ( !isset( $limit[$action] ) ) {
1724 $limit[$action] = '';
1725 } elseif ( $limit[$action] != '' ) {
1729 # Get current restrictions on $action
1730 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1731 if ( $current != '' ) {
1732 $isProtected = true;
1735 if ( $limit[$action] != $current ) {
1737 } elseif ( $limit[$action] != '' ) {
1738 # Only check expiry change if the action is actually being
1739 # protected, since expiry does nothing on an not-protected
1741 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1747 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1751 # If nothing's changed, do nothing
1753 return Status
::newGood();
1756 if ( !$protect ) { # No protection at all means unprotection
1757 $revCommentMsg = 'unprotectedarticle';
1758 $logAction = 'unprotect';
1759 } elseif ( $isProtected ) {
1760 $revCommentMsg = 'modifiedarticleprotection';
1761 $logAction = 'modify';
1763 $revCommentMsg = 'protectedarticle';
1764 $logAction = 'protect';
1767 $encodedExpiry = array();
1768 $protectDescription = '';
1769 foreach ( $limit as $action => $restrictions ) {
1770 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1771 if ( $restrictions != '' ) {
1772 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1773 if ( $encodedExpiry[$action] != 'infinity' ) {
1774 $protectDescription .= wfMsgForContent( 'protect-expiring',
1775 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1776 $wgContLang->date( $expiry[$action], false, false ) ,
1777 $wgContLang->time( $expiry[$action], false, false ) );
1779 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1782 $protectDescription .= ') ';
1785 $protectDescription = trim( $protectDescription );
1787 if ( $id ) { # Protection of existing page
1788 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1789 return Status
::newGood();
1792 # Only restrictions with the 'protect' right can cascade...
1793 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1794 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1796 # The schema allows multiple restrictions
1797 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1801 # Update restrictions table
1802 foreach ( $limit as $action => $restrictions ) {
1803 if ( $restrictions != '' ) {
1804 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1805 array( 'pr_page' => $id,
1806 'pr_type' => $action,
1807 'pr_level' => $restrictions,
1808 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1809 'pr_expiry' => $encodedExpiry[$action]
1814 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1815 'pr_type' => $action ), __METHOD__
);
1819 # Prepare a null revision to be added to the history
1820 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1822 $editComment .= ": $reason";
1824 if ( $protectDescription ) {
1825 $editComment .= " ($protectDescription)";
1828 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1831 # Insert a null revision
1832 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1833 $nullRevId = $nullRevision->insertOn( $dbw );
1835 $latest = $this->getLatest();
1836 # Update page record
1837 $dbw->update( 'page',
1839 'page_touched' => $dbw->timestamp(),
1840 'page_restrictions' => '',
1841 'page_latest' => $nullRevId
1842 ), array( /* WHERE */
1847 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1848 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1849 } else { # Protection of non-existing page (also known as "title protection")
1850 # Cascade protection is meaningless in this case
1853 if ( $limit['create'] != '' ) {
1854 $dbw->replace( 'protected_titles',
1855 array( array( 'pt_namespace', 'pt_title' ) ),
1857 'pt_namespace' => $this->mTitle
->getNamespace(),
1858 'pt_title' => $this->mTitle
->getDBkey(),
1859 'pt_create_perm' => $limit['create'],
1860 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1861 'pt_expiry' => $encodedExpiry['create'],
1862 'pt_user' => $user->getId(),
1863 'pt_reason' => $reason,
1867 $dbw->delete( 'protected_titles',
1869 'pt_namespace' => $this->mTitle
->getNamespace(),
1870 'pt_title' => $this->mTitle
->getDBkey()
1876 $this->mTitle
->flushRestrictions();
1878 if ( $logAction == 'unprotect' ) {
1879 $logParams = array();
1881 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1884 # Update the protection log
1885 $log = new LogPage( 'protect' );
1886 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1888 return Status
::newGood();
1892 * Take an array of page restrictions and flatten it to a string
1893 * suitable for insertion into the page_restrictions field.
1894 * @param $limit Array
1897 protected static function flattenRestrictions( $limit ) {
1898 if ( !is_array( $limit ) ) {
1899 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1905 foreach ( $limit as $action => $restrictions ) {
1906 if ( $restrictions != '' ) {
1907 $bits[] = "$action=$restrictions";
1911 return implode( ':', $bits );
1915 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
1916 * Deletes the article with database consistency, writes logs, purges caches
1918 * @param $reason string delete reason for deletion log
1919 * @param $suppress bitfield
1920 * Revision::DELETED_TEXT
1921 * Revision::DELETED_COMMENT
1922 * Revision::DELETED_USER
1923 * Revision::DELETED_RESTRICTED
1924 * @param $id int article ID
1925 * @param $commit boolean defaults to true, triggers transaction end
1926 * @param &$error Array of errors to append to
1927 * @param $user User The deleting user
1928 * @return boolean true if successful
1930 public function doDeleteArticle(
1931 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1933 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
1934 != Page
::DELETE_SUCCESS
;
1938 * Back-end article deletion
1939 * Deletes the article with database consistency, writes logs, purges caches
1941 * @param $reason string delete reason for deletion log
1942 * @param $suppress bitfield
1943 * Revision::DELETED_TEXT
1944 * Revision::DELETED_COMMENT
1945 * Revision::DELETED_USER
1946 * Revision::DELETED_RESTRICTED
1947 * @param $id int article ID
1948 * @param $commit boolean defaults to true, triggers transaction end
1949 * @param &$error Array of errors to append to
1950 * @param $user User The deleting user
1951 * @return int: One of Page::DELETE_* constants
1953 public function doDeleteArticleReal(
1954 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1957 $user = is_null( $user ) ?
$wgUser : $user;
1959 wfDebug( __METHOD__
. "\n" );
1961 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1962 return Page
::DELETE_HOOK_ABORTED
;
1964 $dbw = wfGetDB( DB_MASTER
);
1965 $t = $this->mTitle
->getDBkey();
1966 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1968 if ( $t === '' ||
$id == 0 ) {
1969 return Page
::DELETE_NO_PAGE
;
1972 // Bitfields to further suppress the content
1975 // This should be 15...
1976 $bitfield |
= Revision
::DELETED_TEXT
;
1977 $bitfield |
= Revision
::DELETED_COMMENT
;
1978 $bitfield |
= Revision
::DELETED_USER
;
1979 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1981 $bitfield = 'rev_deleted';
1985 // For now, shunt the revision data into the archive table.
1986 // Text is *not* removed from the text table; bulk storage
1987 // is left intact to avoid breaking block-compression or
1988 // immutable storage schemes.
1990 // For backwards compatibility, note that some older archive
1991 // table entries will have ar_text and ar_flags fields still.
1993 // In the future, we may keep revisions and mark them with
1994 // the rev_deleted field, which is reserved for this purpose.
1995 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1997 'ar_namespace' => 'page_namespace',
1998 'ar_title' => 'page_title',
1999 'ar_comment' => 'rev_comment',
2000 'ar_user' => 'rev_user',
2001 'ar_user_text' => 'rev_user_text',
2002 'ar_timestamp' => 'rev_timestamp',
2003 'ar_minor_edit' => 'rev_minor_edit',
2004 'ar_rev_id' => 'rev_id',
2005 'ar_parent_id' => 'rev_parent_id',
2006 'ar_text_id' => 'rev_text_id',
2007 'ar_text' => '\'\'', // Be explicit to appease
2008 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2009 'ar_len' => 'rev_len',
2010 'ar_page_id' => 'page_id',
2011 'ar_deleted' => $bitfield,
2012 'ar_sha1' => 'rev_sha1'
2015 'page_id = rev_page'
2019 # Now that it's safely backed up, delete it
2020 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2021 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2025 return Page
::DELETE_NO_REVISIONS
;
2028 $this->doDeleteUpdates( $id );
2030 # Log the deletion, if the page was suppressed, log it at Oversight instead
2031 $logtype = $suppress ?
'suppress' : 'delete';
2033 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2034 $logEntry->setPerformer( $user );
2035 $logEntry->setTarget( $this->mTitle
);
2036 $logEntry->setComment( $reason );
2037 $logid = $logEntry->insert();
2038 $logEntry->publish( $logid );
2044 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2045 return Page
::DELETE_SUCCESS
;
2049 * Do some database updates after deletion
2051 * @param $id Int: page_id value of the page being deleted
2053 public function doDeleteUpdates( $id ) {
2054 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2056 $dbw = wfGetDB( DB_MASTER
);
2058 # Delete restrictions for it
2059 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2061 # Fix category table counts
2063 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2065 foreach ( $res as $row ) {
2066 $cats [] = $row->cl_to
;
2069 $this->updateCategoryCounts( array(), $cats );
2071 # If using cascading deletes, we can skip some explicit deletes
2072 if ( !$dbw->cascadingDeletes() ) {
2073 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2075 # Delete outgoing links
2076 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2077 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2078 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2079 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2080 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2081 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2082 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2083 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2084 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2087 # If using cleanup triggers, we can skip some manual deletes
2088 if ( !$dbw->cleanupTriggers() ) {
2089 # Clean up recentchanges entries...
2090 $dbw->delete( 'recentchanges',
2091 array( 'rc_type != ' . RC_LOG
,
2092 'rc_namespace' => $this->mTitle
->getNamespace(),
2093 'rc_title' => $this->mTitle
->getDBkey() ),
2095 $dbw->delete( 'recentchanges',
2096 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2101 self
::onArticleDelete( $this->mTitle
);
2103 # Clear the cached article id so the interface doesn't act like we exist
2104 $this->mTitle
->resetArticleID( 0 );
2108 * Roll back the most recent consecutive set of edits to a page
2109 * from the same user; fails if there are no eligible edits to
2110 * roll back to, e.g. user is the sole contributor. This function
2111 * performs permissions checks on $user, then calls commitRollback()
2112 * to do the dirty work
2114 * @todo: seperate the business/permission stuff out from backend code
2116 * @param $fromP String: Name of the user whose edits to rollback.
2117 * @param $summary String: Custom summary. Set to default summary if empty.
2118 * @param $token String: Rollback token.
2119 * @param $bot Boolean: If true, mark all reverted edits as bot.
2121 * @param $resultDetails Array: contains result-specific array of additional values
2122 * 'alreadyrolled' : 'current' (rev)
2123 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2125 * @param $user User The user performing the rollback
2126 * @return array of errors, each error formatted as
2127 * array(messagekey, param1, param2, ...).
2128 * On success, the array is empty. This array can also be passed to
2129 * OutputPage::showPermissionsErrorPage().
2131 public function doRollback(
2132 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2134 $resultDetails = null;
2137 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2138 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2139 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2141 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2142 $errors[] = array( 'sessionfailure' );
2145 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2146 $errors[] = array( 'actionthrottledtext' );
2149 # If there were errors, bail out now
2150 if ( !empty( $errors ) ) {
2154 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2158 * Backend implementation of doRollback(), please refer there for parameter
2159 * and return value documentation
2161 * NOTE: This function does NOT check ANY permissions, it just commits the
2162 * rollback to the DB. Therefore, you should only call this function direct-
2163 * ly if you want to use custom permissions checks. If you don't, use
2164 * doRollback() instead.
2165 * @param $fromP String: Name of the user whose edits to rollback.
2166 * @param $summary String: Custom summary. Set to default summary if empty.
2167 * @param $bot Boolean: If true, mark all reverted edits as bot.
2169 * @param $resultDetails Array: contains result-specific array of additional values
2170 * @param $guser User The user performing the rollback
2172 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2173 global $wgUseRCPatrol, $wgContLang;
2175 $dbw = wfGetDB( DB_MASTER
);
2177 if ( wfReadOnly() ) {
2178 return array( array( 'readonlytext' ) );
2181 # Get the last editor
2182 $current = $this->getRevision();
2183 if ( is_null( $current ) ) {
2184 # Something wrong... no page?
2185 return array( array( 'notanarticle' ) );
2188 $from = str_replace( '_', ' ', $fromP );
2189 # User name given should match up with the top revision.
2190 # If the user was deleted then $from should be empty.
2191 if ( $from != $current->getUserText() ) {
2192 $resultDetails = array( 'current' => $current );
2193 return array( array( 'alreadyrolled',
2194 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2195 htmlspecialchars( $fromP ),
2196 htmlspecialchars( $current->getUserText() )
2200 # Get the last edit not by this guy...
2201 # Note: these may not be public values
2202 $user = intval( $current->getRawUser() );
2203 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2204 $s = $dbw->selectRow( 'revision',
2205 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2206 array( 'rev_page' => $current->getPage(),
2207 "rev_user != {$user} OR rev_user_text != {$user_text}"
2209 array( 'USE INDEX' => 'page_timestamp',
2210 'ORDER BY' => 'rev_timestamp DESC' )
2212 if ( $s === false ) {
2213 # No one else ever edited this page
2214 return array( array( 'cantrollback' ) );
2215 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2216 # Only admins can see this text
2217 return array( array( 'notvisiblerev' ) );
2221 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2222 # Mark all reverted edits as bot
2226 if ( $wgUseRCPatrol ) {
2227 # Mark all reverted edits as patrolled
2228 $set['rc_patrolled'] = 1;
2231 if ( count( $set ) ) {
2232 $dbw->update( 'recentchanges', $set,
2234 'rc_cur_id' => $current->getPage(),
2235 'rc_user_text' => $current->getUserText(),
2236 "rc_timestamp > '{$s->rev_timestamp}'",
2241 # Generate the edit summary if necessary
2242 $target = Revision
::newFromId( $s->rev_id
);
2243 if ( empty( $summary ) ) {
2244 if ( $from == '' ) { // no public user name
2245 $summary = wfMsgForContent( 'revertpage-nouser' );
2247 $summary = wfMsgForContent( 'revertpage' );
2251 # Allow the custom summary to use the same args as the default message
2253 $target->getUserText(), $from, $s->rev_id
,
2254 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2255 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2257 $summary = wfMsgReplaceArgs( $summary, $args );
2260 $flags = EDIT_UPDATE
;
2262 if ( $guser->isAllowed( 'minoredit' ) ) {
2263 $flags |
= EDIT_MINOR
;
2266 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2267 $flags |
= EDIT_FORCE_BOT
;
2270 # Actually store the edit
2271 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2272 if ( !empty( $status->value
['revision'] ) ) {
2273 $revId = $status->value
['revision']->getId();
2278 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2280 $resultDetails = array(
2281 'summary' => $summary,
2282 'current' => $current,
2283 'target' => $target,
2291 * The onArticle*() functions are supposed to be a kind of hooks
2292 * which should be called whenever any of the specified actions
2295 * This is a good place to put code to clear caches, for instance.
2297 * This is called on page move and undelete, as well as edit
2299 * @param $title Title object
2301 public static function onArticleCreate( $title ) {
2302 # Update existence markers on article/talk tabs...
2303 if ( $title->isTalkPage() ) {
2304 $other = $title->getSubjectPage();
2306 $other = $title->getTalkPage();
2309 $other->invalidateCache();
2310 $other->purgeSquid();
2312 $title->touchLinks();
2313 $title->purgeSquid();
2314 $title->deleteTitleProtection();
2318 * Clears caches when article is deleted
2320 * @param $title Title
2322 public static function onArticleDelete( $title ) {
2323 # Update existence markers on article/talk tabs...
2324 if ( $title->isTalkPage() ) {
2325 $other = $title->getSubjectPage();
2327 $other = $title->getTalkPage();
2330 $other->invalidateCache();
2331 $other->purgeSquid();
2333 $title->touchLinks();
2334 $title->purgeSquid();
2337 HTMLFileCache
::clearFileCache( $title );
2340 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2341 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2345 if ( $title->getNamespace() == NS_FILE
) {
2346 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2347 $update->doUpdate();
2351 if ( $title->getNamespace() == NS_USER_TALK
) {
2352 $user = User
::newFromName( $title->getText(), false );
2354 $user->setNewtalk( false );
2359 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2363 * Purge caches on page update etc
2365 * @param $title Title object
2366 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2368 public static function onArticleEdit( $title ) {
2369 // Invalidate caches of articles which include this page
2370 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2373 // Invalidate the caches of all pages which redirect here
2374 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2376 # Purge squid for this page only
2377 $title->purgeSquid();
2379 # Clear file cache for this page only
2380 HTMLFileCache
::clearFileCache( $title );
2386 * Returns a list of hidden categories this page is a member of.
2387 * Uses the page_props and categorylinks tables.
2389 * @return Array of Title objects
2391 public function getHiddenCategories() {
2393 $id = $this->mTitle
->getArticleID();
2399 $dbr = wfGetDB( DB_SLAVE
);
2400 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2402 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2403 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2406 if ( $res !== false ) {
2407 foreach ( $res as $row ) {
2408 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2416 * Return an applicable autosummary if one exists for the given edit.
2417 * @param $oldtext String: the previous text of the page.
2418 * @param $newtext String: The submitted text of the page.
2419 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2420 * @return string An appropriate autosummary, or an empty string.
2422 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2425 # Decide what kind of autosummary is needed.
2427 # Redirect autosummaries
2428 $ot = Title
::newFromRedirect( $oldtext );
2429 $rt = Title
::newFromRedirect( $newtext );
2431 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2432 $truncatedtext = $wgContLang->truncate(
2433 str_replace( "\n", ' ', $newtext ),
2435 - strlen( wfMsgForContent( 'autoredircomment' ) )
2436 - strlen( $rt->getFullText() )
2438 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2441 # New page autosummaries
2442 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2443 # If they're making a new article, give its text, truncated, in the summary.
2445 $truncatedtext = $wgContLang->truncate(
2446 str_replace( "\n", ' ', $newtext ),
2447 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2449 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2452 # Blanking autosummaries
2453 if ( $oldtext != '' && $newtext == '' ) {
2454 return wfMsgForContent( 'autosumm-blank' );
2455 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2456 # Removing more than 90% of the article
2458 $truncatedtext = $wgContLang->truncate(
2460 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2462 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2465 # If we reach this point, there's no applicable autosummary for our case, so our
2466 # autosummary is empty.
2471 * Auto-generates a deletion reason
2473 * @param &$hasHistory Boolean: whether the page has a history
2474 * @return mixed String containing deletion reason or empty string, or boolean false
2475 * if no revision occurred
2477 public function getAutoDeleteReason( &$hasHistory ) {
2480 // Get the last revision
2481 $rev = $this->getRevision();
2483 if ( is_null( $rev ) ) {
2487 // Get the article's contents
2488 $contents = $rev->getText();
2491 // If the page is blank, use the text from the previous revision,
2492 // which can only be blank if there's a move/import/protect dummy revision involved
2493 if ( $contents == '' ) {
2494 $prev = $rev->getPrevious();
2497 $contents = $prev->getText();
2502 $dbw = wfGetDB( DB_MASTER
);
2504 // Find out if there was only one contributor
2505 // Only scan the last 20 revisions
2506 $res = $dbw->select( 'revision', 'rev_user_text',
2507 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2509 array( 'LIMIT' => 20 )
2512 if ( $res === false ) {
2513 // This page has no revisions, which is very weird
2517 $hasHistory = ( $res->numRows() > 1 );
2518 $row = $dbw->fetchObject( $res );
2520 if ( $row ) { // $row is false if the only contributor is hidden
2521 $onlyAuthor = $row->rev_user_text
;
2522 // Try to find a second contributor
2523 foreach ( $res as $row ) {
2524 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2525 $onlyAuthor = false;
2530 $onlyAuthor = false;
2533 // Generate the summary with a '$1' placeholder
2535 // The current revision is blank and the one before is also
2536 // blank. It's just not our lucky day
2537 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2539 if ( $onlyAuthor ) {
2540 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2542 $reason = wfMsgForContent( 'excontent', '$1' );
2546 if ( $reason == '-' ) {
2547 // Allow these UI messages to be blanked out cleanly
2551 // Replace newlines with spaces to prevent uglyness
2552 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2553 // Calculate the maximum amount of chars to get
2554 // Max content length = max comment length - length of the comment (excl. $1)
2555 $maxLength = 255 - ( strlen( $reason ) - 2 );
2556 $contents = $wgContLang->truncate( $contents, $maxLength );
2557 // Remove possible unfinished links
2558 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2559 // Now replace the '$1' placeholder
2560 $reason = str_replace( '$1', $contents, $reason );
2566 * Update all the appropriate counts in the category table, given that
2567 * we've added the categories $added and deleted the categories $deleted.
2569 * @param $added array The names of categories that were added
2570 * @param $deleted array The names of categories that were deleted
2572 public function updateCategoryCounts( $added, $deleted ) {
2573 $ns = $this->mTitle
->getNamespace();
2574 $dbw = wfGetDB( DB_MASTER
);
2576 # First make sure the rows exist. If one of the "deleted" ones didn't
2577 # exist, we might legitimately not create it, but it's simpler to just
2578 # create it and then give it a negative value, since the value is bogus
2581 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2582 $insertCats = array_merge( $added, $deleted );
2583 if ( !$insertCats ) {
2584 # Okay, nothing to do
2588 $insertRows = array();
2590 foreach ( $insertCats as $cat ) {
2591 $insertRows[] = array(
2592 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2596 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2598 $addFields = array( 'cat_pages = cat_pages + 1' );
2599 $removeFields = array( 'cat_pages = cat_pages - 1' );
2601 if ( $ns == NS_CATEGORY
) {
2602 $addFields[] = 'cat_subcats = cat_subcats + 1';
2603 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2604 } elseif ( $ns == NS_FILE
) {
2605 $addFields[] = 'cat_files = cat_files + 1';
2606 $removeFields[] = 'cat_files = cat_files - 1';
2613 array( 'cat_title' => $added ),
2622 array( 'cat_title' => $deleted ),
2629 * Updates cascading protections
2631 * @param $parserOutput ParserOutput object for the current version
2633 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2634 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2638 // templatelinks table may have become out of sync,
2639 // especially if using variable-based transclusions.
2640 // For paranoia, check if things have changed and if
2641 // so apply updates to the database. This will ensure
2642 // that cascaded protections apply as soon as the changes
2645 # Get templates from templatelinks
2646 $id = $this->mTitle
->getArticleID();
2648 $tlTemplates = array();
2650 $dbr = wfGetDB( DB_SLAVE
);
2651 $res = $dbr->select( array( 'templatelinks' ),
2652 array( 'tl_namespace', 'tl_title' ),
2653 array( 'tl_from' => $id ),
2657 foreach ( $res as $row ) {
2658 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2661 # Get templates from parser output.
2662 $poTemplates = array();
2663 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2664 foreach ( $templates as $dbk => $id ) {
2665 $poTemplates["$ns:$dbk"] = true;
2670 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2672 if ( count( $templates_diff ) > 0 ) {
2673 # Whee, link updates time.
2674 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2680 * Return a list of templates used by this article.
2681 * Uses the templatelinks table
2683 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2684 * @return Array of Title objects
2686 public function getUsedTemplates() {
2687 return $this->mTitle
->getTemplateLinksFrom();
2691 * Perform article updates on a special page creation.
2693 * @param $rev Revision object
2695 * @todo This is a shitty interface function. Kill it and replace the
2696 * other shitty functions like doEditUpdates and such so it's not needed
2698 * @deprecated since 1.18, use doEditUpdates()
2700 public function createUpdates( $rev ) {
2701 wfDeprecated( __METHOD__
, '1.18' );
2703 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2707 * This function is called right before saving the wikitext,
2708 * so we can do things like signatures and links-in-context.
2710 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2711 * @param $text String article contents
2712 * @param $user User object: user doing the edit
2713 * @param $popts ParserOptions object: parser options, default options for
2714 * the user loaded if null given
2715 * @return string article contents with altered wikitext markup (signatures
2716 * converted, {{subst:}}, templates, etc.)
2718 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2719 global $wgParser, $wgUser;
2721 wfDeprecated( __METHOD__
, '1.19' );
2723 $user = is_null( $user ) ?
$wgUser : $user;
2725 if ( $popts === null ) {
2726 $popts = ParserOptions
::newFromUser( $user );
2729 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2733 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2735 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2738 public function isBigDeletion() {
2739 wfDeprecated( __METHOD__
, '1.19' );
2740 return $this->mTitle
->isBigDeletion();
2744 * Get the approximate revision count of this page.
2746 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2749 public function estimateRevisionCount() {
2750 wfDeprecated( __METHOD__
, '1.19' );
2751 return $this->mTitle
->estimateRevisionCount();
2755 * Update the article's restriction field, and leave a log entry.
2757 * @deprecated since 1.19
2758 * @param $limit Array: set of restriction keys
2759 * @param $reason String
2760 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2761 * @param $expiry Array: per restriction type expiration
2762 * @param $user User The user updating the restrictions
2763 * @return bool true on success
2765 public function updateRestrictions(
2766 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2770 $user = is_null( $user ) ?
$wgUser : $user;
2772 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2776 * @deprecated since 1.18
2778 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2779 wfDeprecated( __METHOD__
, '1.18' );
2781 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2785 * @deprecated since 1.18
2787 public function viewUpdates() {
2788 wfDeprecated( __METHOD__
, '1.18' );
2790 return $this->doViewUpdates( $wgUser );
2794 * @deprecated since 1.18
2796 public function useParserCache( $oldid ) {
2797 wfDeprecated( __METHOD__
, '1.18' );
2799 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2803 class PoolWorkArticleView
extends PoolCounterWork
{
2821 * @var ParserOptions
2823 private $parserOptions;
2831 * @var ParserOutput|false
2833 private $parserOutput = false;
2838 private $isDirty = false;
2843 private $error = false;
2849 * @param $revid Integer: ID of the revision being parsed
2850 * @param $useParserCache Boolean: whether to use the parser cache
2851 * @param $parserOptions parserOptions to use for the parse operation
2852 * @param $text String: text to parse or null to load it
2854 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2855 $this->page
= $page;
2856 $this->revid
= $revid;
2857 $this->cacheable
= $useParserCache;
2858 $this->parserOptions
= $parserOptions;
2859 $this->text
= $text;
2860 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2861 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2865 * Get the ParserOutput from this object, or false in case of failure
2867 * @return ParserOutput
2869 public function getParserOutput() {
2870 return $this->parserOutput
;
2874 * Get whether the ParserOutput is a dirty one (i.e. expired)
2878 public function getIsDirty() {
2879 return $this->isDirty
;
2883 * Get a Status object in case of error or false otherwise
2885 * @return Status|false
2887 public function getError() {
2888 return $this->error
;
2895 global $wgParser, $wgUseFileCache;
2897 $isCurrent = $this->revid
=== $this->page
->getLatest();
2899 if ( $this->text
!== null ) {
2900 $text = $this->text
;
2901 } elseif ( $isCurrent ) {
2902 $text = $this->page
->getRawText();
2904 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2905 if ( $rev === null ) {
2908 $text = $rev->getText();
2911 $time = - microtime( true );
2912 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2913 $this->parserOptions
, true, true, $this->revid
);
2914 $time +
= microtime( true );
2918 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2919 $this->page
->getTitle()->getPrefixedDBkey() ) );
2922 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2923 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2926 // Make sure file cache is not used on uncacheable content.
2927 // Output that has magic words in it can still use the parser cache
2928 // (if enabled), though it will generally expire sooner.
2929 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2930 $wgUseFileCache = false;
2934 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2943 function getCachedWork() {
2944 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2946 if ( $this->parserOutput
=== false ) {
2947 wfDebug( __METHOD__
. ": parser cache miss\n" );
2950 wfDebug( __METHOD__
. ": parser cache hit\n" );
2958 function fallback() {
2959 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2961 if ( $this->parserOutput
=== false ) {
2962 wfDebugLog( 'dirty', "dirty missing\n" );
2963 wfDebug( __METHOD__
. ": no dirty cache\n" );
2966 wfDebug( __METHOD__
. ": sending dirty output\n" );
2967 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2968 $this->isDirty
= true;
2974 * @param $status Status
2976 function error( $status ) {
2977 $this->error
= $status;