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
{
19 public $mTitle = null;
24 public $mDataLoaded = false; // !< Boolean
25 public $mIsRedirect = false; // !< Boolean
26 public $mLatest = false; // !< Integer (false means "not loaded")
27 public $mPreparedEdit = false; // !< Array
33 protected $mRedirectTarget = null;
38 protected $mLastRevision = null;
41 * @var string; timestamp of the current revision or empty string if not loaded
43 protected $mTimestamp = '';
48 protected $mTouched = '19700101000000';
53 protected $mCounter = null;
56 * Constructor and clear the article
57 * @param $title Title Reference to a Title object.
59 public function __construct( Title
$title ) {
60 $this->mTitle
= $title;
64 * Create a WikiPage object of the appropriate class for the given title.
67 * @return WikiPage object of the appropriate type
69 public static function factory( Title
$title ) {
70 $ns = $title->getNamespace();
72 if ( $ns == NS_MEDIA
) {
73 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
74 } elseif ( $ns < 0 ) {
75 throw new MWException( "Invalid or virtual namespace $ns given." );
80 $page = new WikiFilePage( $title );
83 $page = new WikiCategoryPage( $title );
86 $page = new WikiPage( $title );
93 * Constructor from a page id
95 * @param $id Int article ID to load
99 public static function newFromID( $id ) {
100 $t = Title
::newFromID( $id );
102 return self
::factory( $t );
108 * Returns overrides for action handlers.
109 * Classes listed here will be used instead of the default one when
110 * (and only when) $wgActions[$action] === true. This allows subclasses
111 * to override the default behavior.
113 * @todo: move this UI stuff somewhere else
117 public function getActionOverrides() {
122 * If this page is a redirect, get its target
124 * The target will be fetched from the redirect table if possible.
125 * If this page doesn't have an entry there, call insertRedirect()
126 * @return Title|mixed object, or null if this page is not a redirect
128 public function getRedirectTarget() {
129 if ( !$this->mTitle
->isRedirect() ) {
133 if ( $this->mRedirectTarget
!== null ) {
134 return $this->mRedirectTarget
;
137 # Query the redirect table
138 $dbr = wfGetDB( DB_SLAVE
);
139 $row = $dbr->selectRow( 'redirect',
140 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
141 array( 'rd_from' => $this->getId() ),
145 // rd_fragment and rd_interwiki were added later, populate them if empty
146 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
147 return $this->mRedirectTarget
= Title
::makeTitle(
148 $row->rd_namespace
, $row->rd_title
,
149 $row->rd_fragment
, $row->rd_interwiki
);
152 # This page doesn't have an entry in the redirect table
153 return $this->mRedirectTarget
= $this->insertRedirect();
157 * Insert an entry for this page into the redirect table.
159 * Don't call this function directly unless you know what you're doing.
160 * @return Title object or null if not a redirect
162 public function insertRedirect() {
163 // recurse through to only get the final target
164 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
168 $this->insertRedirectEntry( $retval );
173 * Insert or update the redirect table entry for this page to indicate
174 * it redirects to $rt .
175 * @param $rt Title redirect target
177 public function insertRedirectEntry( $rt ) {
178 $dbw = wfGetDB( DB_MASTER
);
179 $dbw->replace( 'redirect', array( 'rd_from' ),
181 'rd_from' => $this->getId(),
182 'rd_namespace' => $rt->getNamespace(),
183 'rd_title' => $rt->getDBkey(),
184 'rd_fragment' => $rt->getFragment(),
185 'rd_interwiki' => $rt->getInterwiki(),
192 * Get the Title object or URL this page redirects to
194 * @return mixed false, Title of in-wiki target, or string with URL
196 public function followRedirect() {
197 return $this->getRedirectURL( $this->getRedirectTarget() );
201 * Get the Title object or URL to use for a redirect. We use Title
202 * objects for same-wiki, non-special redirects and URLs for everything
204 * @param $rt Title Redirect target
205 * @return mixed false, Title object of local target, or string with URL
207 public function getRedirectURL( $rt ) {
212 if ( $rt->isExternal() ) {
213 if ( $rt->isLocal() ) {
214 // Offsite wikis need an HTTP redirect.
216 // This can be hard to reverse and may produce loops,
217 // so they may be disabled in the site configuration.
218 $source = $this->mTitle
->getFullURL( 'redirect=no' );
219 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
221 // External pages pages without "local" bit set are not valid
227 if ( $rt->isSpecialPage() ) {
228 // Gotta handle redirects to special pages differently:
229 // Fill the HTTP response "Location" header and ignore
230 // the rest of the page we're on.
232 // Some pages are not valid targets
233 if ( $rt->isValidRedirectTarget() ) {
234 return $rt->getFullURL();
244 * Get the title object of the article
245 * @return Title object of this page
247 public function getTitle() {
248 return $this->mTitle
;
254 public function clear() {
255 $this->mDataLoaded
= false;
257 $this->mCounter
= null;
258 $this->mRedirectTarget
= null; # Title object if set
259 $this->mLastRevision
= null; # Latest revision
260 $this->mTouched
= '19700101000000';
261 $this->mTimestamp
= '';
262 $this->mIsRedirect
= false;
263 $this->mLatest
= false;
264 $this->mPreparedEdit
= false;
268 * Get the text that needs to be saved in order to undo all revisions
269 * between $undo and $undoafter. Revisions must belong to the same page,
270 * must exist and must not be deleted
271 * @param $undo Revision
272 * @param $undoafter Revision Must be an earlier revision than $undo
273 * @return mixed string on success, false on failure
275 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
276 $cur_text = $this->getRawText();
277 if ( $cur_text === false ) {
278 return false; // no page
280 $undo_text = $undo->getText();
281 $undoafter_text = $undoafter->getText();
283 if ( $cur_text == $undo_text ) {
284 # No use doing a merge if it's just a straight revert.
285 return $undoafter_text;
290 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
298 * Return the list of revision fields that should be selected to create
303 public static function selectFields() {
320 * Fetch a page record with the given conditions
321 * @param $dbr DatabaseBase object
322 * @param $conditions Array
323 * @return mixed Database result resource, or false on failure
325 protected function pageData( $dbr, $conditions ) {
326 $fields = self
::selectFields();
328 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
330 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
332 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
338 * Fetch a page record matching the Title object's namespace and title
339 * using a sanitized title string
341 * @param $dbr DatabaseBase object
342 * @param $title Title object
343 * @return mixed Database result resource, or false on failure
345 public function pageDataFromTitle( $dbr, $title ) {
346 return $this->pageData( $dbr, array(
347 'page_namespace' => $title->getNamespace(),
348 'page_title' => $title->getDBkey() ) );
352 * Fetch a page record matching the requested ID
354 * @param $dbr DatabaseBase
356 * @return mixed Database result resource, or false on failure
358 public function pageDataFromId( $dbr, $id ) {
359 return $this->pageData( $dbr, array( 'page_id' => $id ) );
363 * Set the general counter, title etc data loaded from
366 * @param $data Object|String One of the following:
367 * A DB query result object or...
368 * "fromdb" to get from a slave DB or...
369 * "fromdbmaster" to get from the master DB
371 public function loadPageData( $data = 'fromdb' ) {
372 if ( $data === 'fromdbmaster' ) {
373 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
374 } elseif ( $data === 'fromdb' ) { // slave
375 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
376 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
377 # Note that DB also stores the master position in the session and checks it.
378 $touched = $this->getCachedLastEditTime();
379 if ( $touched ) { // key set
380 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
381 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
386 $lc = LinkCache
::singleton();
389 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
391 $this->mTitle
->loadFromRow( $data );
393 # Old-fashioned restrictions
394 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
396 $this->mCounter
= intval( $data->page_counter
);
397 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
398 $this->mIsRedirect
= intval( $data->page_is_redirect
);
399 $this->mLatest
= intval( $data->page_latest
);
401 $lc->addBadLinkObj( $this->mTitle
);
403 $this->mTitle
->loadFromRow( false );
406 $this->mDataLoaded
= true;
410 * @return int Page ID
412 public function getId() {
413 return $this->mTitle
->getArticleID();
417 * @return bool Whether or not the page exists in the database
419 public function exists() {
420 return $this->mTitle
->exists();
424 * Check if this page is something we're going to be showing
425 * some sort of sensible content for. If we return false, page
426 * views (plain action=view) will return an HTTP 404 response,
427 * so spiders and robots can know they're following a bad link.
431 public function hasViewableContent() {
432 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
436 * @return int The view count for the page
438 public function getCount() {
439 if ( !$this->mDataLoaded
) {
440 $this->loadPageData();
443 return $this->mCounter
;
447 * Determine whether a page would be suitable for being counted as an
448 * article in the site_stats table based on the title & its content
450 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
451 * if false, the current database state will be used
454 public function isCountable( $editInfo = false ) {
455 global $wgArticleCountMethod;
457 if ( !$this->mTitle
->isContentPage() ) {
461 $text = $editInfo ?
$editInfo->pst
: false;
463 if ( $this->isRedirect( $text ) ) {
467 switch ( $wgArticleCountMethod ) {
471 if ( $text === false ) {
472 $text = $this->getRawText();
474 return strpos( $text, ',' ) !== false;
477 // ParserOutput::getLinks() is a 2D array of page links, so
478 // to be really correct we would need to recurse in the array
479 // but the main array should only have items in it if there are
481 return (bool)count( $editInfo->output
->getLinks() );
483 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
484 array( 'pl_from' => $this->getId() ), __METHOD__
);
490 * Tests if the article text represents a redirect
492 * @param $text mixed string containing article contents, or boolean
495 public function isRedirect( $text = false ) {
496 if ( $text === false ) {
497 if ( !$this->mDataLoaded
) {
498 $this->loadPageData();
501 return (bool)$this->mIsRedirect
;
503 return Title
::newFromRedirect( $text ) !== null;
508 * Loads page_touched and returns a value indicating if it should be used
509 * @return boolean true if not a redirect
511 public function checkTouched() {
512 if ( !$this->mDataLoaded
) {
513 $this->loadPageData();
515 return !$this->mIsRedirect
;
519 * Get the page_touched field
520 * @return string containing GMT timestamp
522 public function getTouched() {
523 if ( !$this->mDataLoaded
) {
524 $this->loadPageData();
526 return $this->mTouched
;
530 * Get the page_latest field
531 * @return integer rev_id of current revision
533 public function getLatest() {
534 if ( !$this->mDataLoaded
) {
535 $this->loadPageData();
537 return (int)$this->mLatest
;
541 * Loads everything except the text
542 * This isn't necessary for all uses, so it's only done if needed.
544 protected function loadLastEdit() {
545 if ( $this->mLastRevision
!== null ) {
546 return; // already loaded
549 $latest = $this->getLatest();
551 return; // page doesn't exist or is missing page_latest info
554 $revision = Revision
::newFromPageId( $this->getId(), $latest );
555 if ( $revision ) { // sanity
556 $this->setLastEdit( $revision );
561 * Set the latest revision
563 protected function setLastEdit( Revision
$revision ) {
564 $this->mLastRevision
= $revision;
565 $this->mTimestamp
= $revision->getTimestamp();
569 * Get the latest revision
570 * @return Revision|null
572 public function getRevision() {
573 $this->loadLastEdit();
574 if ( $this->mLastRevision
) {
575 return $this->mLastRevision
;
581 * Get the text of the current revision. No side-effects...
583 * @param $audience Integer: one of:
584 * Revision::FOR_PUBLIC to be displayed to all users
585 * Revision::FOR_THIS_USER to be displayed to $wgUser
586 * Revision::RAW get the text regardless of permissions
587 * @return String|false The text of the current revision
589 public function getText( $audience = Revision
::FOR_PUBLIC
) {
590 $this->loadLastEdit();
591 if ( $this->mLastRevision
) {
592 return $this->mLastRevision
->getText( $audience );
598 * Get the text of the current revision. No side-effects...
600 * @return String|false The text of the current revision
602 public function getRawText() {
603 $this->loadLastEdit();
604 if ( $this->mLastRevision
) {
605 return $this->mLastRevision
->getRawText();
611 * @return string MW timestamp of last article revision
613 public function getTimestamp() {
614 // Check if the field has been filled by WikiPage::setTimestamp()
615 if ( !$this->mTimestamp
) {
616 $this->loadLastEdit();
618 return wfTimestamp( TS_MW
, $this->mTimestamp
);
622 * Set the page timestamp (use only to avoid DB queries)
623 * @param $ts string MW timestamp of last article revision
625 public function setTimestamp( $ts ) {
626 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
630 * @param $audience Integer: one of:
631 * Revision::FOR_PUBLIC to be displayed to all users
632 * Revision::FOR_THIS_USER to be displayed to $wgUser
633 * Revision::RAW get the text regardless of permissions
634 * @return int user ID for the user that made the last article revision
636 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
637 $this->loadLastEdit();
638 if ( $this->mLastRevision
) {
639 return $this->mLastRevision
->getUser( $audience );
646 * @param $audience Integer: one of:
647 * Revision::FOR_PUBLIC to be displayed to all users
648 * Revision::FOR_THIS_USER to be displayed to $wgUser
649 * Revision::RAW get the text regardless of permissions
650 * @return string username of the user that made the last article revision
652 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
653 $this->loadLastEdit();
654 if ( $this->mLastRevision
) {
655 return $this->mLastRevision
->getUserText( $audience );
662 * @param $audience Integer: one of:
663 * Revision::FOR_PUBLIC to be displayed to all users
664 * Revision::FOR_THIS_USER to be displayed to $wgUser
665 * Revision::RAW get the text regardless of permissions
666 * @return string Comment stored for the last article revision
668 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
669 $this->loadLastEdit();
670 if ( $this->mLastRevision
) {
671 return $this->mLastRevision
->getComment( $audience );
678 * Returns true if last revision was marked as "minor edit"
680 * @return boolean Minor edit indicator for the last article revision.
682 public function getMinorEdit() {
683 $this->loadLastEdit();
684 if ( $this->mLastRevision
) {
685 return $this->mLastRevision
->isMinor();
692 * Get the cached timestamp for the last time the page changed.
693 * This is only used to help handle slave lag by comparing to page_touched.
694 * @return string MW timestamp
696 protected function getCachedLastEditTime() {
698 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
699 return $wgMemc->get( $key );
703 * Set the cached timestamp for the last time the page changed.
704 * This is only used to help handle slave lag by comparing to page_touched.
705 * @param $timestamp string
707 public function setCachedLastEditTime( $timestamp ) {
709 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
710 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
714 * Get a list of users who have edited this article, not including the user who made
715 * the most recent revision, which you can get from $article->getUser() if you want it
716 * @return UserArrayFromResult
718 public function getContributors() {
719 # @todo FIXME: This is expensive; cache this info somewhere.
721 $dbr = wfGetDB( DB_SLAVE
);
723 if ( $dbr->implicitGroupby() ) {
724 $realNameField = 'user_real_name';
726 $realNameField = 'MIN(user_real_name) AS user_real_name';
729 $tables = array( 'revision', 'user' );
732 'rev_user as user_id',
733 'rev_user_text AS user_name',
735 'MAX(rev_timestamp) AS timestamp',
738 $conds = array( 'rev_page' => $this->getId() );
740 // The user who made the top revision gets credited as "this page was last edited by
741 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
742 $user = $this->getUser();
744 $conds[] = "rev_user != $user";
746 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
749 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
752 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
756 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
757 'ORDER BY' => 'timestamp DESC',
760 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
761 return new UserArrayFromResult( $res );
765 * Get the last N authors
766 * @param $num Integer: number of revisions to get
767 * @param $revLatest String: the latest rev_id, selected from the master (optional)
768 * @return array Array of authors, duplicates not removed
770 public function getLastNAuthors( $num, $revLatest = 0 ) {
771 wfProfileIn( __METHOD__
);
772 // First try the slave
773 // If that doesn't have the latest revision, try the master
775 $db = wfGetDB( DB_SLAVE
);
778 $res = $db->select( array( 'page', 'revision' ),
779 array( 'rev_id', 'rev_user_text' ),
781 'page_namespace' => $this->mTitle
->getNamespace(),
782 'page_title' => $this->mTitle
->getDBkey(),
786 'ORDER BY' => 'rev_timestamp DESC',
792 wfProfileOut( __METHOD__
);
796 $row = $db->fetchObject( $res );
798 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
799 $db = wfGetDB( DB_MASTER
);
804 } while ( $continue );
806 $authors = array( $row->rev_user_text
);
808 foreach ( $res as $row ) {
809 $authors[] = $row->rev_user_text
;
812 wfProfileOut( __METHOD__
);
817 * Should the parser cache be used?
819 * @param $parserOptions ParserOptions to check
823 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
824 global $wgEnableParserCache;
826 return $wgEnableParserCache
827 && $parserOptions->getStubThreshold() == 0
828 && $this->mTitle
->exists()
829 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
830 && $this->mTitle
->isWikitextPage();
834 * Get a ParserOutput for the given ParserOptions and revision ID.
835 * The parser cache will be used if possible.
838 * @param $parserOptions ParserOptions to use for the parse operation
839 * @param $oldid Revision ID to get the text from, passing null or 0 will
840 * get the current revision (default value)
841 * @return ParserOutput or false if the revision was not found
843 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
844 wfProfileIn( __METHOD__
);
846 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
847 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
848 if ( $parserOptions->getStubThreshold() ) {
849 wfIncrStats( 'pcache_miss_stub' );
852 if ( $useParserCache ) {
853 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
854 if ( $parserOutput !== false ) {
855 wfProfileOut( __METHOD__
);
856 return $parserOutput;
860 if ( $oldid === null ||
$oldid === 0 ) {
861 $oldid = $this->getLatest();
864 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
867 wfProfileOut( __METHOD__
);
869 return $pool->getParserOutput();
873 * Do standard deferred updates after page view
874 * @param $user User The relevant user
876 public function doViewUpdates( User
$user ) {
877 global $wgDisableCounters;
878 if ( wfReadOnly() ) {
882 # Don't update page view counters on views from bot users (bug 14044)
883 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
884 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
885 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
888 # Update newtalk / watchlist notification status
889 $user->clearNotification( $this->mTitle
);
893 * Perform the actions of a page purging
895 public function doPurge() {
898 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
902 // Invalidate the cache
903 $this->mTitle
->invalidateCache();
907 // Commit the transaction before the purge is sent
908 $dbw = wfGetDB( DB_MASTER
);
912 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
916 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
917 if ( $this->mTitle
->exists() ) {
918 $text = $this->getRawText();
923 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
929 * Insert a new empty page record for this article.
930 * This *must* be followed up by creating a revision
931 * and running $this->updateRevisionOn( ... );
932 * or else the record will be left in a funky state.
933 * Best if all done inside a transaction.
935 * @param $dbw DatabaseBase
936 * @return int The newly created page_id key, or false if the title already existed
938 public function insertOn( $dbw ) {
939 wfProfileIn( __METHOD__
);
941 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
942 $dbw->insert( 'page', array(
943 'page_id' => $page_id,
944 'page_namespace' => $this->mTitle
->getNamespace(),
945 'page_title' => $this->mTitle
->getDBkey(),
947 'page_restrictions' => '',
948 'page_is_redirect' => 0, # Will set this shortly...
950 'page_random' => wfRandom(),
951 'page_touched' => $dbw->timestamp(),
952 'page_latest' => 0, # Fill this in shortly...
953 'page_len' => 0, # Fill this in shortly...
954 ), __METHOD__
, 'IGNORE' );
956 $affected = $dbw->affectedRows();
959 $newid = $dbw->insertId();
960 $this->mTitle
->resetArticleID( $newid );
962 wfProfileOut( __METHOD__
);
964 return $affected ?
$newid : false;
968 * Update the page record to point to a newly saved revision.
970 * @param $dbw DatabaseBase: object
971 * @param $revision Revision: For ID number, and text used to set
972 * length and redirect status fields
973 * @param $lastRevision Integer: if given, will not overwrite the page field
974 * when different from the currently set value.
975 * Giving 0 indicates the new page flag should be set
977 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
978 * removing rows in redirect table.
979 * @return bool true on success, false on failure
982 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
983 wfProfileIn( __METHOD__
);
985 $text = $revision->getText();
986 $len = strlen( $text );
987 $rt = Title
::newFromRedirectRecurse( $text );
989 $conditions = array( 'page_id' => $this->getId() );
991 if ( !is_null( $lastRevision ) ) {
992 # An extra check against threads stepping on each other
993 $conditions['page_latest'] = $lastRevision;
996 $now = wfTimestampNow();
997 $dbw->update( 'page',
999 'page_latest' => $revision->getId(),
1000 'page_touched' => $dbw->timestamp( $now ),
1001 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1002 'page_is_redirect' => $rt !== null ?
1 : 0,
1008 $result = $dbw->affectedRows() != 0;
1010 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1011 $this->setLastEdit( $revision );
1012 $this->setCachedLastEditTime( $now );
1013 $this->mLatest
= $revision->getId();
1014 $this->mIsRedirect
= (bool)$rt;
1015 # Update the LinkCache.
1016 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1019 wfProfileOut( __METHOD__
);
1024 * Add row to the redirect table if this is a redirect, remove otherwise.
1026 * @param $dbw DatabaseBase
1027 * @param $redirectTitle Title object pointing to the redirect target,
1028 * or NULL if this is not a redirect
1029 * @param $lastRevIsRedirect If given, will optimize adding and
1030 * removing rows in redirect table.
1031 * @return bool true on success, false on failure
1034 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1035 // Always update redirects (target link might have changed)
1036 // Update/Insert if we don't know if the last revision was a redirect or not
1037 // Delete if changing from redirect to non-redirect
1038 $isRedirect = !is_null( $redirectTitle );
1040 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1044 wfProfileIn( __METHOD__
);
1045 if ( $isRedirect ) {
1046 $this->insertRedirectEntry( $redirectTitle );
1048 // This is not a redirect, remove row from redirect table
1049 $where = array( 'rd_from' => $this->getId() );
1050 $dbw->delete( 'redirect', $where, __METHOD__
);
1053 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1054 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1056 wfProfileOut( __METHOD__
);
1058 return ( $dbw->affectedRows() != 0 );
1062 * If the given revision is newer than the currently set page_latest,
1063 * update the page record. Otherwise, do nothing.
1065 * @param $dbw Database object
1066 * @param $revision Revision object
1069 public function updateIfNewerOn( $dbw, $revision ) {
1070 wfProfileIn( __METHOD__
);
1072 $row = $dbw->selectRow(
1073 array( 'revision', 'page' ),
1074 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1076 'page_id' => $this->getId(),
1077 'page_latest=rev_id' ),
1081 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1082 wfProfileOut( __METHOD__
);
1085 $prev = $row->rev_id
;
1086 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1088 # No or missing previous revision; mark the page as new
1090 $lastRevIsRedirect = null;
1093 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1095 wfProfileOut( __METHOD__
);
1100 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1101 * @param $text String: new text of the section
1102 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1103 * @param $edittime String: revision timestamp or null to use the current revision
1104 * @return string Complete article text, or null if error
1106 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1107 wfProfileIn( __METHOD__
);
1109 if ( strval( $section ) == '' ) {
1110 // Whole-page edit; let the whole text through
1112 // Bug 30711: always use current version when adding a new section
1113 if ( is_null( $edittime ) ||
$section == 'new' ) {
1114 $oldtext = $this->getRawText();
1115 if ( $oldtext === false ) {
1116 wfDebug( __METHOD__
. ": no page text\n" );
1117 wfProfileOut( __METHOD__
);
1121 $dbw = wfGetDB( DB_MASTER
);
1122 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1125 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1126 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1127 wfProfileOut( __METHOD__
);
1131 $oldtext = $rev->getText();
1134 if ( $section == 'new' ) {
1135 # Inserting a new section
1136 $subject = $sectionTitle ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1137 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1138 $text = strlen( trim( $oldtext ) ) > 0
1139 ?
"{$oldtext}\n\n{$subject}{$text}"
1140 : "{$subject}{$text}";
1143 # Replacing an existing section; roll out the big guns
1146 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1150 wfProfileOut( __METHOD__
);
1155 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1157 * @return Int updated $flags
1159 function checkFlags( $flags ) {
1160 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1161 if ( $this->mTitle
->getArticleID() ) {
1162 $flags |
= EDIT_UPDATE
;
1172 * Change an existing article or create a new article. Updates RC and all necessary caches,
1173 * optionally via the deferred update array.
1175 * @param $text String: new text
1176 * @param $summary String: edit summary
1177 * @param $flags Integer bitfield:
1179 * Article is known or assumed to be non-existent, create a new one
1181 * Article is known or assumed to be pre-existing, update it
1183 * Mark this edit minor, if the user is allowed to do so
1185 * Do not log the change in recentchanges
1187 * Mark the edit a "bot" edit regardless of user rights
1188 * EDIT_DEFER_UPDATES
1189 * Defer some of the updates until the end of index.php
1191 * Fill in blank summaries with generated text where possible
1193 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1194 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1195 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1196 * edit-already-exists error will be returned. These two conditions are also possible with
1197 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1199 * @param $baseRevId the revision ID this edit was based off, if any
1200 * @param $user User the user doing the edit
1202 * @return Status object. Possible errors:
1203 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1204 * edit-gone-missing: In update mode, but the article didn't exist
1205 * edit-conflict: In update mode, the article changed unexpectedly
1206 * edit-no-change: Warning that the text was the same as before
1207 * edit-already-exists: In creation mode, but the article already exists
1209 * Extensions may define additional errors.
1211 * $return->value will contain an associative array with members as follows:
1212 * new: Boolean indicating if the function attempted to create a new article
1213 * revision: The revision object for the inserted revision, or null
1215 * Compatibility note: this function previously returned a boolean value indicating success/failure
1217 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1218 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1220 # Low-level sanity check
1221 if ( $this->mTitle
->getText() === '' ) {
1222 throw new MWException( 'Something is trying to edit an article with an empty title' );
1225 wfProfileIn( __METHOD__
);
1227 $user = is_null( $user ) ?
$wgUser : $user;
1228 $status = Status
::newGood( array() );
1230 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1231 $this->loadPageData( 'fromdbmaster' );
1233 $flags = $this->checkFlags( $flags );
1235 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1236 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1238 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1240 if ( $status->isOK() ) {
1241 $status->fatal( 'edit-hook-aborted' );
1244 wfProfileOut( __METHOD__
);
1248 # Silently ignore EDIT_MINOR if not allowed
1249 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1250 $bot = $flags & EDIT_FORCE_BOT
;
1252 $oldtext = $this->getRawText(); // current revision
1253 $oldsize = strlen( $oldtext );
1254 $oldid = $this->getLatest();
1255 $oldIsRedirect = $this->isRedirect();
1256 $oldcountable = $this->isCountable();
1258 # Provide autosummaries if one is not provided and autosummaries are enabled.
1259 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1260 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1263 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1264 $text = $editInfo->pst
;
1265 $newsize = strlen( $text );
1267 $dbw = wfGetDB( DB_MASTER
);
1268 $now = wfTimestampNow();
1269 $this->mTimestamp
= $now;
1271 if ( $flags & EDIT_UPDATE
) {
1272 # Update article, but only if changed.
1273 $status->value
['new'] = false;
1275 # Make sure the revision is either completely inserted or not inserted at all
1276 if ( !$wgDBtransactions ) {
1277 $userAbort = ignore_user_abort( true );
1280 $revision = new Revision( array(
1281 'page' => $this->getId(),
1282 'comment' => $summary,
1283 'minor_edit' => $isminor,
1285 'parent_id' => $oldid,
1286 'user' => $user->getId(),
1287 'user_text' => $user->getName(),
1291 $changed = ( strcmp( $text, $oldtext ) != 0 );
1294 if ( !$this->mLatest
) {
1295 # Article gone missing
1296 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1297 $status->fatal( 'edit-gone-missing' );
1299 wfProfileOut( __METHOD__
);
1304 $revisionId = $revision->insertOn( $dbw );
1308 # Note that we use $this->mLatest instead of fetching a value from the master DB
1309 # during the course of this function. This makes sure that EditPage can detect
1310 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1311 # before this function is called. A previous function used a separate query, this
1312 # creates a window where concurrent edits can cause an ignored edit conflict.
1313 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1316 /* Belated edit conflict! Run away!! */
1317 $status->fatal( 'edit-conflict' );
1319 # Delete the invalid revision if the DB is not transactional
1320 if ( !$wgDBtransactions ) {
1321 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1327 global $wgUseRCPatrol;
1328 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1329 # Update recentchanges
1330 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1331 # Mark as patrolled if the user can do so
1332 $patrolled = $wgUseRCPatrol && !count(
1333 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1334 # Add RC row to the DB
1335 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1336 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1337 $revisionId, $patrolled
1340 # Log auto-patrolled edits
1342 PatrolLog
::record( $rc, true );
1345 $user->incEditCount();
1350 if ( !$wgDBtransactions ) {
1351 ignore_user_abort( $userAbort );
1354 // Now that ignore_user_abort is restored, we can respond to fatal errors
1355 if ( !$status->isOK() ) {
1356 wfProfileOut( __METHOD__
);
1360 # Update links tables, site stats, etc.
1361 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1362 'oldcountable' => $oldcountable ) );
1365 $status->warning( 'edit-no-change' );
1367 // Keep the same revision ID, but do some updates on it
1368 $revisionId = $this->getLatest();
1369 // Update page_touched, this is usually implicit in the page update
1370 // Other cache updates are done in onArticleEdit()
1371 $this->mTitle
->invalidateCache();
1374 # Create new article
1375 $status->value
['new'] = true;
1379 # Add the page record; stake our claim on this title!
1380 # This will return false if the article already exists
1381 $newid = $this->insertOn( $dbw );
1383 if ( $newid === false ) {
1385 $status->fatal( 'edit-already-exists' );
1387 wfProfileOut( __METHOD__
);
1391 # Save the revision text...
1392 $revision = new Revision( array(
1394 'comment' => $summary,
1395 'minor_edit' => $isminor,
1397 'user' => $user->getId(),
1398 'user_text' => $user->getName(),
1401 $revisionId = $revision->insertOn( $dbw );
1403 # Update the page record with revision data
1404 $this->updateRevisionOn( $dbw, $revision, 0 );
1406 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1408 # Update recentchanges
1409 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1410 global $wgUseRCPatrol, $wgUseNPPatrol;
1412 # Mark as patrolled if the user can do so
1413 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1414 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1415 # Add RC row to the DB
1416 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1417 '', strlen( $text ), $revisionId, $patrolled );
1419 # Log auto-patrolled edits
1421 PatrolLog
::record( $rc, true );
1424 $user->incEditCount();
1427 # Update links, etc.
1428 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1430 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1431 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1434 # Do updates right now unless deferral was requested
1435 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1436 DeferredUpdates
::doUpdates();
1439 // Return the new revision (or null) to the caller
1440 $status->value
['revision'] = $revision;
1442 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1443 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1445 # Promote user to any groups they meet the criteria for
1446 $user->addAutopromoteOnceGroups( 'onEdit' );
1448 wfProfileOut( __METHOD__
);
1453 * Get parser options suitable for rendering the primary article wikitext
1454 * @param User|string $user User object or 'canonical'
1455 * @return ParserOptions
1457 public function makeParserOptions( $user ) {
1459 if ( $user instanceof User
) { // settings per user (even anons)
1460 $options = ParserOptions
::newFromUser( $user );
1461 } else { // canonical settings
1462 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1464 $options->enableLimitReport(); // show inclusion/loop reports
1465 $options->setTidy( true ); // fix bad HTML
1470 * Prepare text which is about to be saved.
1471 * Returns a stdclass with source, pst and output members
1473 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1474 global $wgParser, $wgContLang, $wgUser;
1475 $user = is_null( $user ) ?
$wgUser : $user;
1476 // @TODO fixme: check $user->getId() here???
1477 if ( $this->mPreparedEdit
1478 && $this->mPreparedEdit
->newText
== $text
1479 && $this->mPreparedEdit
->revid
== $revid
1482 return $this->mPreparedEdit
;
1485 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1486 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1488 $edit = (object)array();
1489 $edit->revid
= $revid;
1490 $edit->newText
= $text;
1491 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1492 $edit->popts
= $this->makeParserOptions( 'canonical' );
1493 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1494 $edit->oldText
= $this->getRawText();
1496 $this->mPreparedEdit
= $edit;
1502 * Do standard deferred updates after page edit.
1503 * Update links tables, site stats, search index and message cache.
1504 * Purges pages that include this page if the text was changed here.
1505 * Every 100th edit, prune the recent changes table.
1508 * @param $revision Revision object
1509 * @param $user User object that did the revision
1510 * @param $options Array of options, following indexes are used:
1511 * - changed: boolean, whether the revision changed the content (default true)
1512 * - created: boolean, whether the revision created the page (default false)
1513 * - oldcountable: boolean or null (default null):
1514 * - boolean: whether the page was counted as an article before that
1515 * revision, only used in changed is true and created is false
1516 * - null: don't change the article count
1518 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1519 global $wgEnableParserCache;
1521 wfProfileIn( __METHOD__
);
1523 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1524 $text = $revision->getText();
1527 # Be careful not to double-PST: $text is usually already PST-ed once
1528 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1529 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1530 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1532 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1533 $editInfo = $this->mPreparedEdit
;
1536 # Save it to the parser cache
1537 if ( $wgEnableParserCache ) {
1538 $parserCache = ParserCache
::singleton();
1539 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1542 # Update the links tables
1543 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
1546 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1548 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1549 if ( 0 == mt_rand( 0, 99 ) ) {
1550 // Flush old entries from the `recentchanges` table; we do this on
1551 // random requests so as to avoid an increase in writes for no good reason
1554 $dbw = wfGetDB( DB_MASTER
);
1555 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1558 array( "rc_timestamp < '$cutoff'" ),
1564 if ( !$this->mTitle
->exists() ) {
1565 wfProfileOut( __METHOD__
);
1569 $id = $this->getId();
1570 $title = $this->mTitle
->getPrefixedDBkey();
1571 $shortTitle = $this->mTitle
->getDBkey();
1573 if ( !$options['changed'] ) {
1576 } elseif ( $options['created'] ) {
1577 $good = (int)$this->isCountable( $editInfo );
1579 } elseif ( $options['oldcountable'] !== null ) {
1580 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1587 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1588 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1590 # If this is another user's talk page, update newtalk.
1591 # Don't do this if $options['changed'] = false (null-edits) nor if
1592 # it's a minor edit and the user doesn't want notifications for those.
1593 if ( $options['changed']
1594 && $this->mTitle
->getNamespace() == NS_USER_TALK
1595 && $shortTitle != $user->getTitleKey()
1596 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1598 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1599 $other = User
::newFromName( $shortTitle, false );
1601 wfDebug( __METHOD__
. ": invalid username\n" );
1602 } elseif ( User
::isIP( $shortTitle ) ) {
1603 // An anonymous user
1604 $other->setNewtalk( true );
1605 } elseif ( $other->isLoggedIn() ) {
1606 $other->setNewtalk( true );
1608 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1613 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1614 MessageCache
::singleton()->replace( $shortTitle, $text );
1617 if( $options['created'] ) {
1618 self
::onArticleCreate( $this->mTitle
);
1620 self
::onArticleEdit( $this->mTitle
);
1623 wfProfileOut( __METHOD__
);
1627 * Edit an article without doing all that other stuff
1628 * The article must already exist; link tables etc
1629 * are not updated, caches are not flushed.
1631 * @param $text String: text submitted
1632 * @param $user User The relevant user
1633 * @param $comment String: comment submitted
1634 * @param $minor Boolean: whereas it's a minor modification
1636 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1637 wfProfileIn( __METHOD__
);
1639 $dbw = wfGetDB( DB_MASTER
);
1640 $revision = new Revision( array(
1641 'page' => $this->getId(),
1643 'comment' => $comment,
1644 'minor_edit' => $minor ?
1 : 0,
1646 $revision->insertOn( $dbw );
1647 $this->updateRevisionOn( $dbw, $revision );
1649 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1651 wfProfileOut( __METHOD__
);
1655 * Update the article's restriction field, and leave a log entry.
1656 * This works for protection both existing and non-existing pages.
1658 * @param $limit Array: set of restriction keys
1659 * @param $reason String
1660 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1661 * @param $expiry Array: per restriction type expiration
1662 * @param $user User The user updating the restrictions
1663 * @return bool true on success
1665 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1668 if ( wfReadOnly() ) {
1669 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1672 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1674 $id = $this->mTitle
->getArticleID();
1680 // Take this opportunity to purge out expired restrictions
1681 Title
::purgeExpiredRestrictions();
1683 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1684 # we expect a single selection, but the schema allows otherwise.
1685 $isProtected = false;
1689 $dbw = wfGetDB( DB_MASTER
);
1691 foreach ( $restrictionTypes as $action ) {
1692 if ( !isset( $expiry[$action] ) ) {
1693 $expiry[$action] = $dbw->getInfinity();
1695 if ( !isset( $limit[$action] ) ) {
1696 $limit[$action] = '';
1697 } elseif ( $limit[$action] != '' ) {
1701 # Get current restrictions on $action
1702 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1703 if ( $current != '' ) {
1704 $isProtected = true;
1707 if ( $limit[$action] != $current ) {
1709 } elseif ( $limit[$action] != '' ) {
1710 # Only check expiry change if the action is actually being
1711 # protected, since expiry does nothing on an not-protected
1713 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1719 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1723 # If nothing's changed, do nothing
1725 return Status
::newGood();
1728 if ( !$protect ) { # No protection at all means unprotection
1729 $revCommentMsg = 'unprotectedarticle';
1730 $logAction = 'unprotect';
1731 } elseif ( $isProtected ) {
1732 $revCommentMsg = 'modifiedarticleprotection';
1733 $logAction = 'modify';
1735 $revCommentMsg = 'protectedarticle';
1736 $logAction = 'protect';
1739 $encodedExpiry = array();
1740 $protectDescription = '';
1741 foreach ( $limit as $action => $restrictions ) {
1742 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1743 if ( $restrictions != '' ) {
1744 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1745 if ( $encodedExpiry[$action] != 'infinity' ) {
1746 $protectDescription .= wfMsgForContent( 'protect-expiring',
1747 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1748 $wgContLang->date( $expiry[$action], false, false ) ,
1749 $wgContLang->time( $expiry[$action], false, false ) );
1751 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1754 $protectDescription .= ') ';
1757 $protectDescription = trim( $protectDescription );
1759 if ( $id ) { # Protection of existing page
1760 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1761 return Status
::newGood();
1764 # Only restrictions with the 'protect' right can cascade...
1765 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1766 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1768 # The schema allows multiple restrictions
1769 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1773 # Update restrictions table
1774 foreach ( $limit as $action => $restrictions ) {
1775 if ( $restrictions != '' ) {
1776 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1777 array( 'pr_page' => $id,
1778 'pr_type' => $action,
1779 'pr_level' => $restrictions,
1780 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1781 'pr_expiry' => $encodedExpiry[$action]
1786 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1787 'pr_type' => $action ), __METHOD__
);
1791 # Prepare a null revision to be added to the history
1792 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
1794 $editComment .= ": $reason";
1796 if ( $protectDescription ) {
1797 $editComment .= " ($protectDescription)";
1800 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1803 # Insert a null revision
1804 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1805 $nullRevId = $nullRevision->insertOn( $dbw );
1807 $latest = $this->getLatest();
1808 # Update page record
1809 $dbw->update( 'page',
1811 'page_touched' => $dbw->timestamp(),
1812 'page_restrictions' => '',
1813 'page_latest' => $nullRevId
1814 ), array( /* WHERE */
1819 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1820 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1821 } else { # Protection of non-existing page (also known as "title protection")
1822 # Cascade protection is meaningless in this case
1825 if ( $limit['create'] != '' ) {
1826 $dbw->replace( 'protected_titles',
1827 array( array( 'pt_namespace', 'pt_title' ) ),
1829 'pt_namespace' => $this->mTitle
->getNamespace(),
1830 'pt_title' => $this->mTitle
->getDBkey(),
1831 'pt_create_perm' => $limit['create'],
1832 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1833 'pt_expiry' => $encodedExpiry['create'],
1834 'pt_user' => $user->getId(),
1835 'pt_reason' => $reason,
1839 $dbw->delete( 'protected_titles',
1841 'pt_namespace' => $this->mTitle
->getNamespace(),
1842 'pt_title' => $this->mTitle
->getDBkey()
1848 $this->mTitle
->flushRestrictions();
1850 if ( $logAction == 'unprotect' ) {
1851 $logParams = array();
1853 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
1856 # Update the protection log
1857 $log = new LogPage( 'protect' );
1858 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
1860 return Status
::newGood();
1864 * Take an array of page restrictions and flatten it to a string
1865 * suitable for insertion into the page_restrictions field.
1866 * @param $limit Array
1869 protected static function flattenRestrictions( $limit ) {
1870 if ( !is_array( $limit ) ) {
1871 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1877 foreach ( $limit as $action => $restrictions ) {
1878 if ( $restrictions != '' ) {
1879 $bits[] = "$action=$restrictions";
1883 return implode( ':', $bits );
1887 * Back-end article deletion
1888 * Deletes the article with database consistency, writes logs, purges caches
1890 * @param $reason string delete reason for deletion log
1891 * @param $suppress bitfield
1892 * Revision::DELETED_TEXT
1893 * Revision::DELETED_COMMENT
1894 * Revision::DELETED_USER
1895 * Revision::DELETED_RESTRICTED
1896 * @param $id int article ID
1897 * @param $commit boolean defaults to true, triggers transaction end
1898 * @param &$errors Array of errors to append to
1899 * @param $user User The relevant user
1900 * @return boolean true if successful
1902 public function doDeleteArticle(
1903 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1906 $user = is_null( $user ) ?
$wgUser : $user;
1908 wfDebug( __METHOD__
. "\n" );
1910 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1913 $dbw = wfGetDB( DB_MASTER
);
1914 $t = $this->mTitle
->getDBkey();
1915 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1917 if ( $t === '' ||
$id == 0 ) {
1921 // Bitfields to further suppress the content
1924 // This should be 15...
1925 $bitfield |
= Revision
::DELETED_TEXT
;
1926 $bitfield |
= Revision
::DELETED_COMMENT
;
1927 $bitfield |
= Revision
::DELETED_USER
;
1928 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1930 $bitfield = 'rev_deleted';
1934 // For now, shunt the revision data into the archive table.
1935 // Text is *not* removed from the text table; bulk storage
1936 // is left intact to avoid breaking block-compression or
1937 // immutable storage schemes.
1939 // For backwards compatibility, note that some older archive
1940 // table entries will have ar_text and ar_flags fields still.
1942 // In the future, we may keep revisions and mark them with
1943 // the rev_deleted field, which is reserved for this purpose.
1944 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1946 'ar_namespace' => 'page_namespace',
1947 'ar_title' => 'page_title',
1948 'ar_comment' => 'rev_comment',
1949 'ar_user' => 'rev_user',
1950 'ar_user_text' => 'rev_user_text',
1951 'ar_timestamp' => 'rev_timestamp',
1952 'ar_minor_edit' => 'rev_minor_edit',
1953 'ar_rev_id' => 'rev_id',
1954 'ar_parent_id' => 'rev_parent_id',
1955 'ar_text_id' => 'rev_text_id',
1956 'ar_text' => '\'\'', // Be explicit to appease
1957 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1958 'ar_len' => 'rev_len',
1959 'ar_page_id' => 'page_id',
1960 'ar_deleted' => $bitfield,
1961 'ar_sha1' => 'rev_sha1'
1964 'page_id = rev_page'
1968 # Now that it's safely backed up, delete it
1969 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1970 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1977 $this->doDeleteUpdates( $id );
1979 # Log the deletion, if the page was suppressed, log it at Oversight instead
1980 $logtype = $suppress ?
'suppress' : 'delete';
1982 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1983 $logEntry->setPerformer( $user );
1984 $logEntry->setTarget( $this->mTitle
);
1985 $logEntry->setComment( $reason );
1986 $logid = $logEntry->insert();
1987 $logEntry->publish( $logid );
1993 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1998 * Do some database updates after deletion
2000 * @param $id Int: page_id value of the page being deleted
2002 public function doDeleteUpdates( $id ) {
2003 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2005 $dbw = wfGetDB( DB_MASTER
);
2007 # Delete restrictions for it
2008 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
2010 # Fix category table counts
2012 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
2014 foreach ( $res as $row ) {
2015 $cats [] = $row->cl_to
;
2018 $this->updateCategoryCounts( array(), $cats );
2020 # If using cascading deletes, we can skip some explicit deletes
2021 if ( !$dbw->cascadingDeletes() ) {
2022 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2024 # Delete outgoing links
2025 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
2026 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
2027 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
2028 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
2029 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
2030 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
2031 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
2032 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
2033 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
2036 # If using cleanup triggers, we can skip some manual deletes
2037 if ( !$dbw->cleanupTriggers() ) {
2038 # Clean up recentchanges entries...
2039 $dbw->delete( 'recentchanges',
2040 array( 'rc_type != ' . RC_LOG
,
2041 'rc_namespace' => $this->mTitle
->getNamespace(),
2042 'rc_title' => $this->mTitle
->getDBkey() ),
2044 $dbw->delete( 'recentchanges',
2045 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
2050 self
::onArticleDelete( $this->mTitle
);
2052 # Clear the cached article id so the interface doesn't act like we exist
2053 $this->mTitle
->resetArticleID( 0 );
2057 * Roll back the most recent consecutive set of edits to a page
2058 * from the same user; fails if there are no eligible edits to
2059 * roll back to, e.g. user is the sole contributor. This function
2060 * performs permissions checks on $user, then calls commitRollback()
2061 * to do the dirty work
2063 * @todo: seperate the business/permission stuff out from backend code
2065 * @param $fromP String: Name of the user whose edits to rollback.
2066 * @param $summary String: Custom summary. Set to default summary if empty.
2067 * @param $token String: Rollback token.
2068 * @param $bot Boolean: If true, mark all reverted edits as bot.
2070 * @param $resultDetails Array: contains result-specific array of additional values
2071 * 'alreadyrolled' : 'current' (rev)
2072 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2074 * @param $user User The user performing the rollback
2075 * @return array of errors, each error formatted as
2076 * array(messagekey, param1, param2, ...).
2077 * On success, the array is empty. This array can also be passed to
2078 * OutputPage::showPermissionsErrorPage().
2080 public function doRollback(
2081 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2083 $resultDetails = null;
2086 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2087 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2088 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2090 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2091 $errors[] = array( 'sessionfailure' );
2094 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2095 $errors[] = array( 'actionthrottledtext' );
2098 # If there were errors, bail out now
2099 if ( !empty( $errors ) ) {
2103 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2107 * Backend implementation of doRollback(), please refer there for parameter
2108 * and return value documentation
2110 * NOTE: This function does NOT check ANY permissions, it just commits the
2111 * rollback to the DB. Therefore, you should only call this function direct-
2112 * ly if you want to use custom permissions checks. If you don't, use
2113 * doRollback() instead.
2114 * @param $fromP String: Name of the user whose edits to rollback.
2115 * @param $summary String: Custom summary. Set to default summary if empty.
2116 * @param $bot Boolean: If true, mark all reverted edits as bot.
2118 * @param $resultDetails Array: contains result-specific array of additional values
2119 * @param $guser User The user performing the rollback
2121 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2122 global $wgUseRCPatrol, $wgContLang;
2124 $dbw = wfGetDB( DB_MASTER
);
2126 if ( wfReadOnly() ) {
2127 return array( array( 'readonlytext' ) );
2130 # Get the last editor
2131 $current = Revision
::newFromTitle( $this->mTitle
);
2132 if ( is_null( $current ) ) {
2133 # Something wrong... no page?
2134 return array( array( 'notanarticle' ) );
2137 $from = str_replace( '_', ' ', $fromP );
2138 # User name given should match up with the top revision.
2139 # If the user was deleted then $from should be empty.
2140 if ( $from != $current->getUserText() ) {
2141 $resultDetails = array( 'current' => $current );
2142 return array( array( 'alreadyrolled',
2143 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2144 htmlspecialchars( $fromP ),
2145 htmlspecialchars( $current->getUserText() )
2149 # Get the last edit not by this guy...
2150 # Note: these may not be public values
2151 $user = intval( $current->getRawUser() );
2152 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2153 $s = $dbw->selectRow( 'revision',
2154 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2155 array( 'rev_page' => $current->getPage(),
2156 "rev_user != {$user} OR rev_user_text != {$user_text}"
2158 array( 'USE INDEX' => 'page_timestamp',
2159 'ORDER BY' => 'rev_timestamp DESC' )
2161 if ( $s === false ) {
2162 # No one else ever edited this page
2163 return array( array( 'cantrollback' ) );
2164 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2165 # Only admins can see this text
2166 return array( array( 'notvisiblerev' ) );
2170 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2171 # Mark all reverted edits as bot
2175 if ( $wgUseRCPatrol ) {
2176 # Mark all reverted edits as patrolled
2177 $set['rc_patrolled'] = 1;
2180 if ( count( $set ) ) {
2181 $dbw->update( 'recentchanges', $set,
2183 'rc_cur_id' => $current->getPage(),
2184 'rc_user_text' => $current->getUserText(),
2185 "rc_timestamp > '{$s->rev_timestamp}'",
2190 # Generate the edit summary if necessary
2191 $target = Revision
::newFromId( $s->rev_id
);
2192 if ( empty( $summary ) ) {
2193 if ( $from == '' ) { // no public user name
2194 $summary = wfMsgForContent( 'revertpage-nouser' );
2196 $summary = wfMsgForContent( 'revertpage' );
2200 # Allow the custom summary to use the same args as the default message
2202 $target->getUserText(), $from, $s->rev_id
,
2203 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2204 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2206 $summary = wfMsgReplaceArgs( $summary, $args );
2209 $flags = EDIT_UPDATE
;
2211 if ( $guser->isAllowed( 'minoredit' ) ) {
2212 $flags |
= EDIT_MINOR
;
2215 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2216 $flags |
= EDIT_FORCE_BOT
;
2219 # Actually store the edit
2220 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2221 if ( !empty( $status->value
['revision'] ) ) {
2222 $revId = $status->value
['revision']->getId();
2227 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2229 $resultDetails = array(
2230 'summary' => $summary,
2231 'current' => $current,
2232 'target' => $target,
2240 * The onArticle*() functions are supposed to be a kind of hooks
2241 * which should be called whenever any of the specified actions
2244 * This is a good place to put code to clear caches, for instance.
2246 * This is called on page move and undelete, as well as edit
2248 * @param $title Title object
2250 public static function onArticleCreate( $title ) {
2251 # Update existence markers on article/talk tabs...
2252 if ( $title->isTalkPage() ) {
2253 $other = $title->getSubjectPage();
2255 $other = $title->getTalkPage();
2258 $other->invalidateCache();
2259 $other->purgeSquid();
2261 $title->touchLinks();
2262 $title->purgeSquid();
2263 $title->deleteTitleProtection();
2267 * Clears caches when article is deleted
2269 * @param $title Title
2271 public static function onArticleDelete( $title ) {
2272 # Update existence markers on article/talk tabs...
2273 if ( $title->isTalkPage() ) {
2274 $other = $title->getSubjectPage();
2276 $other = $title->getTalkPage();
2279 $other->invalidateCache();
2280 $other->purgeSquid();
2282 $title->touchLinks();
2283 $title->purgeSquid();
2286 HTMLFileCache
::clearFileCache( $title );
2289 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2290 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2294 if ( $title->getNamespace() == NS_FILE
) {
2295 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2296 $update->doUpdate();
2300 if ( $title->getNamespace() == NS_USER_TALK
) {
2301 $user = User
::newFromName( $title->getText(), false );
2303 $user->setNewtalk( false );
2308 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2312 * Purge caches on page update etc
2314 * @param $title Title object
2315 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2317 public static function onArticleEdit( $title ) {
2318 // Invalidate caches of articles which include this page
2319 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2322 // Invalidate the caches of all pages which redirect here
2323 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2325 # Purge squid for this page only
2326 $title->purgeSquid();
2328 # Clear file cache for this page only
2329 HTMLFileCache
::clearFileCache( $title );
2335 * Returns a list of hidden categories this page is a member of.
2336 * Uses the page_props and categorylinks tables.
2338 * @return Array of Title objects
2340 public function getHiddenCategories() {
2342 $id = $this->mTitle
->getArticleID();
2348 $dbr = wfGetDB( DB_SLAVE
);
2349 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2351 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2352 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2355 if ( $res !== false ) {
2356 foreach ( $res as $row ) {
2357 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2365 * Return an applicable autosummary if one exists for the given edit.
2366 * @param $oldtext String: the previous text of the page.
2367 * @param $newtext String: The submitted text of the page.
2368 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2369 * @return string An appropriate autosummary, or an empty string.
2371 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2374 # Decide what kind of autosummary is needed.
2376 # Redirect autosummaries
2377 $ot = Title
::newFromRedirect( $oldtext );
2378 $rt = Title
::newFromRedirect( $newtext );
2380 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2381 $truncatedtext = $wgContLang->truncate(
2382 str_replace( "\n", ' ', $newtext ),
2384 - strlen( wfMsgForContent( 'autoredircomment' ) )
2385 - strlen( $rt->getFullText() )
2387 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2390 # New page autosummaries
2391 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2392 # If they're making a new article, give its text, truncated, in the summary.
2394 $truncatedtext = $wgContLang->truncate(
2395 str_replace( "\n", ' ', $newtext ),
2396 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2398 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2401 # Blanking autosummaries
2402 if ( $oldtext != '' && $newtext == '' ) {
2403 return wfMsgForContent( 'autosumm-blank' );
2404 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2405 # Removing more than 90% of the article
2407 $truncatedtext = $wgContLang->truncate(
2409 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2411 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2414 # If we reach this point, there's no applicable autosummary for our case, so our
2415 # autosummary is empty.
2420 * Auto-generates a deletion reason
2422 * @param &$hasHistory Boolean: whether the page has a history
2423 * @return mixed String containing deletion reason or empty string, or boolean false
2424 * if no revision occurred
2426 public function getAutoDeleteReason( &$hasHistory ) {
2429 $dbw = wfGetDB( DB_MASTER
);
2430 // Get the last revision
2431 $rev = Revision
::newFromTitle( $this->getTitle() );
2433 if ( is_null( $rev ) ) {
2437 // Get the article's contents
2438 $contents = $rev->getText();
2441 // If the page is blank, use the text from the previous revision,
2442 // which can only be blank if there's a move/import/protect dummy revision involved
2443 if ( $contents == '' ) {
2444 $prev = $rev->getPrevious();
2447 $contents = $prev->getText();
2452 // Find out if there was only one contributor
2453 // Only scan the last 20 revisions
2454 $res = $dbw->select( 'revision', 'rev_user_text',
2455 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2457 array( 'LIMIT' => 20 )
2460 if ( $res === false ) {
2461 // This page has no revisions, which is very weird
2465 $hasHistory = ( $res->numRows() > 1 );
2466 $row = $dbw->fetchObject( $res );
2468 if ( $row ) { // $row is false if the only contributor is hidden
2469 $onlyAuthor = $row->rev_user_text
;
2470 // Try to find a second contributor
2471 foreach ( $res as $row ) {
2472 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2473 $onlyAuthor = false;
2478 $onlyAuthor = false;
2481 // Generate the summary with a '$1' placeholder
2483 // The current revision is blank and the one before is also
2484 // blank. It's just not our lucky day
2485 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2487 if ( $onlyAuthor ) {
2488 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2490 $reason = wfMsgForContent( 'excontent', '$1' );
2494 if ( $reason == '-' ) {
2495 // Allow these UI messages to be blanked out cleanly
2499 // Replace newlines with spaces to prevent uglyness
2500 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2501 // Calculate the maximum amount of chars to get
2502 // Max content length = max comment length - length of the comment (excl. $1)
2503 $maxLength = 255 - ( strlen( $reason ) - 2 );
2504 $contents = $wgContLang->truncate( $contents, $maxLength );
2505 // Remove possible unfinished links
2506 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2507 // Now replace the '$1' placeholder
2508 $reason = str_replace( '$1', $contents, $reason );
2514 * Update all the appropriate counts in the category table, given that
2515 * we've added the categories $added and deleted the categories $deleted.
2517 * @param $added array The names of categories that were added
2518 * @param $deleted array The names of categories that were deleted
2520 public function updateCategoryCounts( $added, $deleted ) {
2521 $ns = $this->mTitle
->getNamespace();
2522 $dbw = wfGetDB( DB_MASTER
);
2524 # First make sure the rows exist. If one of the "deleted" ones didn't
2525 # exist, we might legitimately not create it, but it's simpler to just
2526 # create it and then give it a negative value, since the value is bogus
2529 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2530 $insertCats = array_merge( $added, $deleted );
2531 if ( !$insertCats ) {
2532 # Okay, nothing to do
2536 $insertRows = array();
2538 foreach ( $insertCats as $cat ) {
2539 $insertRows[] = array(
2540 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2544 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2546 $addFields = array( 'cat_pages = cat_pages + 1' );
2547 $removeFields = array( 'cat_pages = cat_pages - 1' );
2549 if ( $ns == NS_CATEGORY
) {
2550 $addFields[] = 'cat_subcats = cat_subcats + 1';
2551 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2552 } elseif ( $ns == NS_FILE
) {
2553 $addFields[] = 'cat_files = cat_files + 1';
2554 $removeFields[] = 'cat_files = cat_files - 1';
2561 array( 'cat_title' => $added ),
2570 array( 'cat_title' => $deleted ),
2577 * Updates cascading protections
2579 * @param $parserOutput ParserOutput object for the current version
2581 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2582 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2586 // templatelinks table may have become out of sync,
2587 // especially if using variable-based transclusions.
2588 // For paranoia, check if things have changed and if
2589 // so apply updates to the database. This will ensure
2590 // that cascaded protections apply as soon as the changes
2593 # Get templates from templatelinks
2594 $id = $this->mTitle
->getArticleID();
2596 $tlTemplates = array();
2598 $dbr = wfGetDB( DB_SLAVE
);
2599 $res = $dbr->select( array( 'templatelinks' ),
2600 array( 'tl_namespace', 'tl_title' ),
2601 array( 'tl_from' => $id ),
2605 foreach ( $res as $row ) {
2606 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2609 # Get templates from parser output.
2610 $poTemplates = array();
2611 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2612 foreach ( $templates as $dbk => $id ) {
2613 $poTemplates["$ns:$dbk"] = true;
2618 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2620 if ( count( $templates_diff ) > 0 ) {
2621 # Whee, link updates time.
2622 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2628 * Return a list of templates used by this article.
2629 * Uses the templatelinks table
2631 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2632 * @return Array of Title objects
2634 public function getUsedTemplates() {
2635 return $this->mTitle
->getTemplateLinksFrom();
2639 * Perform article updates on a special page creation.
2641 * @param $rev Revision object
2643 * @todo This is a shitty interface function. Kill it and replace the
2644 * other shitty functions like doEditUpdates and such so it's not needed
2646 * @deprecated since 1.18, use doEditUpdates()
2648 public function createUpdates( $rev ) {
2649 wfDeprecated( __METHOD__
, '1.18' );
2651 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2655 * This function is called right before saving the wikitext,
2656 * so we can do things like signatures and links-in-context.
2658 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2659 * @param $text String article contents
2660 * @param $user User object: user doing the edit
2661 * @param $popts ParserOptions object: parser options, default options for
2662 * the user loaded if null given
2663 * @return string article contents with altered wikitext markup (signatures
2664 * converted, {{subst:}}, templates, etc.)
2666 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2667 global $wgParser, $wgUser;
2669 wfDeprecated( __METHOD__
, '1.19' );
2671 $user = is_null( $user ) ?
$wgUser : $user;
2673 if ( $popts === null ) {
2674 $popts = ParserOptions
::newFromUser( $user );
2677 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2681 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2683 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2686 public function isBigDeletion() {
2687 wfDeprecated( __METHOD__
, '1.19' );
2688 return $this->mTitle
->isBigDeletion();
2692 * Get the approximate revision count of this page.
2694 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2697 public function estimateRevisionCount() {
2698 wfDeprecated( __METHOD__
, '1.19' );
2699 return $this->mTitle
->estimateRevisionCount();
2703 * Update the article's restriction field, and leave a log entry.
2705 * @deprecated since 1.19
2706 * @param $limit Array: set of restriction keys
2707 * @param $reason String
2708 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2709 * @param $expiry Array: per restriction type expiration
2710 * @param $user User The user updating the restrictions
2711 * @return bool true on success
2713 public function updateRestrictions(
2714 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2718 $user = is_null( $user ) ?
$wgUser : $user;
2720 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2724 * @deprecated since 1.18
2726 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2727 wfDeprecated( __METHOD__
, '1.18' );
2729 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2733 * @deprecated since 1.18
2735 public function viewUpdates() {
2736 wfDeprecated( __METHOD__
, '1.18' );
2738 return $this->doViewUpdates( $wgUser );
2742 * @deprecated since 1.18
2744 public function useParserCache( $oldid ) {
2745 wfDeprecated( __METHOD__
, '1.18' );
2747 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2751 class PoolWorkArticleView
extends PoolCounterWork
{
2769 * @var ParserOptions
2771 private $parserOptions;
2779 * @var ParserOutput|false
2781 private $parserOutput = false;
2786 private $isDirty = false;
2791 private $error = false;
2797 * @param $revid Integer: ID of the revision being parsed
2798 * @param $useParserCache Boolean: whether to use the parser cache
2799 * @param $parserOptions parserOptions to use for the parse operation
2800 * @param $text String: text to parse or null to load it
2802 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
2803 $this->page
= $page;
2804 $this->revid
= $revid;
2805 $this->cacheable
= $useParserCache;
2806 $this->parserOptions
= $parserOptions;
2807 $this->text
= $text;
2808 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
2809 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
2813 * Get the ParserOutput from this object, or false in case of failure
2815 * @return ParserOutput
2817 public function getParserOutput() {
2818 return $this->parserOutput
;
2822 * Get whether the ParserOutput is a dirty one (i.e. expired)
2826 public function getIsDirty() {
2827 return $this->isDirty
;
2831 * Get a Status object in case of error or false otherwise
2833 * @return Status|false
2835 public function getError() {
2836 return $this->error
;
2843 global $wgParser, $wgUseFileCache;
2845 $isCurrent = $this->revid
=== $this->page
->getLatest();
2847 if ( $this->text
!== null ) {
2848 $text = $this->text
;
2849 } elseif ( $isCurrent ) {
2850 $text = $this->page
->getRawText();
2852 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
2853 if ( $rev === null ) {
2856 $text = $rev->getText();
2860 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
2861 $this->parserOptions
, true, true, $this->revid
);
2866 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2867 $this->page
->getTitle()->getPrefixedDBkey() ) );
2870 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
2871 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
2874 // Make sure file cache is not used on uncacheable content.
2875 // Output that has magic words in it can still use the parser cache
2876 // (if enabled), though it will generally expire sooner.
2877 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
2878 $wgUseFileCache = false;
2882 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
2891 function getCachedWork() {
2892 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
2894 if ( $this->parserOutput
=== false ) {
2895 wfDebug( __METHOD__
. ": parser cache miss\n" );
2898 wfDebug( __METHOD__
. ": parser cache hit\n" );
2906 function fallback() {
2907 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
2909 if ( $this->parserOutput
=== false ) {
2910 wfDebugLog( 'dirty', "dirty missing\n" );
2911 wfDebug( __METHOD__
. ": no dirty cache\n" );
2914 wfDebug( __METHOD__
. ": sending dirty output\n" );
2915 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2916 $this->isDirty
= true;
2922 * @param $status Status
2924 function error( $status ) {
2925 $this->error
= $status;