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
{
20 public $mTitle = null;
25 public $mCounter = -1; // !< Integer (-1 means "not loaded")
26 public $mDataLoaded = false; // !< Boolean
27 public $mIsRedirect = false; // !< Boolean
28 public $mLatest = false; // !< Boolean
29 public $mPreparedEdit = false; // !< Array
30 public $mRedirectTarget = null; // !< Title object
31 public $mLastRevision = null; // !< Revision object
32 public $mTimestamp = ''; // !< String
33 public $mTouched = '19700101000000'; // !< String
38 * @var ParserOptions: ParserOptions object for $wgUser articles
40 public $mParserOptions;
43 * Constructor and clear the article
44 * @param $title Title Reference to a Title object.
46 public function __construct( Title
$title ) {
47 $this->mTitle
= $title;
51 * Create a WikiPage object of the appropriate class for the given title.
54 * @return WikiPage object of the appropriate type
56 public static function factory( Title
$title ) {
57 $ns = $title->getNamespace();
59 if ( $ns == NS_MEDIA
) {
60 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
61 } elseif ( $ns < 0 ) {
62 throw new MWException( "Invalid or virtual namespace $ns given." );
67 $page = new WikiFilePage( $title );
70 $page = new WikiCategoryPage( $title );
73 $page = new WikiPage( $title );
80 * Constructor from a page id
82 * Always override this for all subclasses (until we use PHP with LSB)
84 * @param $id Int article ID to load
88 public static function newFromID( $id ) {
89 $t = Title
::newFromID( $id );
90 # @todo FIXME: Doesn't inherit right
91 return $t == null ?
null : new self( $t );
92 # return $t == null ? null : new static( $t ); // PHP 5.3
96 * Returns overrides for action handlers.
97 * Classes listed here will be used instead of the default one when
98 * (and only when) $wgActions[$action] === true. This allows subclasses
99 * to override the default behavior.
101 * @todo: move this UI stuff somewhere else
105 public function getActionOverrides() {
110 * If this page is a redirect, get its target
112 * The target will be fetched from the redirect table if possible.
113 * If this page doesn't have an entry there, call insertRedirect()
114 * @return Title|mixed object, or null if this page is not a redirect
116 public function getRedirectTarget() {
117 if ( !$this->mTitle
->isRedirect() ) {
121 if ( $this->mRedirectTarget
!== null ) {
122 return $this->mRedirectTarget
;
125 # Query the redirect table
126 $dbr = wfGetDB( DB_SLAVE
);
127 $row = $dbr->selectRow( 'redirect',
128 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
129 array( 'rd_from' => $this->getId() ),
133 // rd_fragment and rd_interwiki were added later, populate them if empty
134 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
135 return $this->mRedirectTarget
= Title
::makeTitle(
136 $row->rd_namespace
, $row->rd_title
,
137 $row->rd_fragment
, $row->rd_interwiki
);
140 # This page doesn't have an entry in the redirect table
141 return $this->mRedirectTarget
= $this->insertRedirect();
145 * Insert an entry for this page into the redirect table.
147 * Don't call this function directly unless you know what you're doing.
148 * @return Title object or null if not a redirect
150 public function insertRedirect() {
151 // recurse through to only get the final target
152 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
156 $this->insertRedirectEntry( $retval );
161 * Insert or update the redirect table entry for this page to indicate
162 * it redirects to $rt .
163 * @param $rt Title redirect target
165 public function insertRedirectEntry( $rt ) {
166 $dbw = wfGetDB( DB_MASTER
);
167 $dbw->replace( 'redirect', array( 'rd_from' ),
169 'rd_from' => $this->getId(),
170 'rd_namespace' => $rt->getNamespace(),
171 'rd_title' => $rt->getDBkey(),
172 'rd_fragment' => $rt->getFragment(),
173 'rd_interwiki' => $rt->getInterwiki(),
180 * Get the Title object or URL this page redirects to
182 * @return mixed false, Title of in-wiki target, or string with URL
184 public function followRedirect() {
185 return $this->getRedirectURL( $this->getRedirectTarget() );
189 * Get the Title object or URL to use for a redirect. We use Title
190 * objects for same-wiki, non-special redirects and URLs for everything
192 * @param $rt Title Redirect target
193 * @return mixed false, Title object of local target, or string with URL
195 public function getRedirectURL( $rt ) {
197 if ( $rt->getInterwiki() != '' ) {
198 if ( $rt->isLocal() ) {
199 // Offsite wikis need an HTTP redirect.
201 // This can be hard to reverse and may produce loops,
202 // so they may be disabled in the site configuration.
203 $source = $this->mTitle
->getFullURL( 'redirect=no' );
204 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
207 if ( $rt->getNamespace() == NS_SPECIAL
) {
208 // Gotta handle redirects to special pages differently:
209 // Fill the HTTP response "Location" header and ignore
210 // the rest of the page we're on.
212 // This can be hard to reverse, so they may be disabled.
213 if ( $rt->isSpecial( 'Userlogout' ) ) {
216 return $rt->getFullURL();
224 // No or invalid redirect
229 * Get the title object of the article
230 * @return Title object of this page
232 public function getTitle() {
233 return $this->mTitle
;
239 public function clear() {
240 $this->mDataLoaded
= false;
242 $this->mCounter
= -1; # Not loaded
243 $this->mRedirectTarget
= null; # Title object if set
244 $this->mLastRevision
= null; # Latest revision
245 $this->mTimestamp
= '';
246 $this->mTouched
= '19700101000000';
247 $this->mIsRedirect
= false;
248 $this->mLatest
= false;
249 $this->mPreparedEdit
= false;
253 * Get the text that needs to be saved in order to undo all revisions
254 * between $undo and $undoafter. Revisions must belong to the same page,
255 * must exist and must not be deleted
256 * @param $undo Revision
257 * @param $undoafter Revision Must be an earlier revision than $undo
258 * @return mixed string on success, false on failure
260 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
261 $cur_text = $this->getRawText();
262 if ( $cur_text === false ) {
263 return false; // no page
265 $undo_text = $undo->getText();
266 $undoafter_text = $undoafter->getText();
268 if ( $cur_text == $undo_text ) {
269 # No use doing a merge if it's just a straight revert.
270 return $undoafter_text;
275 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
283 * Return the list of revision fields that should be selected to create
288 public static function selectFields() {
305 * Fetch a page record with the given conditions
306 * @param $dbr DatabaseBase object
307 * @param $conditions Array
308 * @return mixed Database result resource, or false on failure
310 protected function pageData( $dbr, $conditions ) {
311 $fields = self
::selectFields();
313 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
315 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
);
317 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
323 * Fetch a page record matching the Title object's namespace and title
324 * using a sanitized title string
326 * @param $dbr DatabaseBase object
327 * @param $title Title object
328 * @return mixed Database result resource, or false on failure
330 public function pageDataFromTitle( $dbr, $title ) {
331 return $this->pageData( $dbr, array(
332 'page_namespace' => $title->getNamespace(),
333 'page_title' => $title->getDBkey() ) );
337 * Fetch a page record matching the requested ID
339 * @param $dbr DatabaseBase
341 * @return mixed Database result resource, or false on failure
343 public function pageDataFromId( $dbr, $id ) {
344 return $this->pageData( $dbr, array( 'page_id' => $id ) );
348 * Set the general counter, title etc data loaded from
351 * @param $data Object|String One of the following:
352 * A DB query result object or...
353 * "fromdb" to get from a slave DB or...
354 * "fromdbmaster" to get from the master DB
357 public function loadPageData( $data = 'fromdb' ) {
358 if ( $data === 'fromdbmaster' ) {
359 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
360 } elseif ( $data === 'fromdb' ) { // slave
361 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
362 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
363 # Note that DB also stores the master position in the session and checks it.
364 $touched = $this->getCachedLastEditTime();
365 if ( $touched ) { // key set
366 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
367 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
372 $lc = LinkCache
::singleton();
375 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
,
376 $data->page_len
, $data->page_is_redirect
, $data->page_latest
);
378 $this->mTitle
->loadFromRow( $data );
380 # Old-fashioned restrictions
381 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
383 $this->mCounter
= intval( $data->page_counter
);
384 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
385 $this->mIsRedirect
= intval( $data->page_is_redirect
);
386 $this->mLatest
= intval( $data->page_latest
);
388 $lc->addBadLinkObj( $this->mTitle
);
390 $this->mTitle
->loadFromRow( false );
393 $this->mDataLoaded
= true;
397 * @return int Page ID
399 public function getId() {
400 return $this->mTitle
->getArticleID();
404 * @return bool Whether or not the page exists in the database
406 public function exists() {
407 return $this->getId() > 0;
411 * Check if this page is something we're going to be showing
412 * some sort of sensible content for. If we return false, page
413 * views (plain action=view) will return an HTTP 404 response,
414 * so spiders and robots can know they're following a bad link.
418 public function hasViewableContent() {
419 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
423 * @return int The view count for the page
425 public function getCount() {
426 if ( -1 == $this->mCounter
) {
427 $id = $this->getId();
432 $dbr = wfGetDB( DB_SLAVE
);
433 $this->mCounter
= $dbr->selectField( 'page',
435 array( 'page_id' => $id ),
441 return $this->mCounter
;
445 * Determine whether a page would be suitable for being counted as an
446 * article in the site_stats table based on the title & its content
448 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
449 * if false, the current database state will be used
452 public function isCountable( $editInfo = false ) {
453 global $wgArticleCountMethod;
455 if ( !$this->mTitle
->isContentPage() ) {
459 $text = $editInfo ?
$editInfo->pst
: false;
461 if ( $this->isRedirect( $text ) ) {
465 switch ( $wgArticleCountMethod ) {
469 if ( $text === false ) {
470 $text = $this->getRawText();
472 return strpos( $text, ',' ) !== false;
475 // ParserOutput::getLinks() is a 2D array of page links, so
476 // to be really correct we would need to recurse in the array
477 // but the main array should only have items in it if there are
479 return (bool)count( $editInfo->output
->getLinks() );
481 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
482 array( 'pl_from' => $this->getId() ), __METHOD__
);
488 * Tests if the article text represents a redirect
490 * @param $text mixed string containing article contents, or boolean
493 public function isRedirect( $text = false ) {
494 if ( $text === false ) {
495 if ( !$this->mDataLoaded
) {
496 $this->loadPageData();
499 return (bool)$this->mIsRedirect
;
501 return Title
::newFromRedirect( $text ) !== null;
506 * Loads everything except the text
507 * This isn't necessary for all uses, so it's only done if needed.
509 protected function loadLastEdit() {
510 if ( $this->mLastRevision
!== null ) {
511 return; // already loaded
514 $latest = $this->getLatest();
516 return; // page doesn't exist or is missing page_latest info
519 $revision = Revision
::newFromPageId( $this->getId(), $latest );
520 if ( $revision ) { // sanity
521 $this->setLastEdit( $revision );
526 * Set the latest revision
528 protected function setLastEdit( Revision
$revision ) {
529 $this->mLastRevision
= $revision;
530 $this->mTimestamp
= $revision->getTimestamp();
534 * Get the latest revision
535 * @return Revision|null
537 public function getRevision() {
538 $this->loadLastEdit();
539 if ( $this->mLastRevision
) {
540 return $this->mLastRevision
;
546 * Get the text of the current revision. No side-effects...
548 * @param $audience Integer: one of:
549 * Revision::FOR_PUBLIC to be displayed to all users
550 * Revision::FOR_THIS_USER to be displayed to $wgUser
551 * Revision::RAW get the text regardless of permissions
552 * @return String|false The text of the current revision
554 public function getText( $audience = Revision
::FOR_PUBLIC
) {
555 $this->loadLastEdit();
556 if ( $this->mLastRevision
) {
557 return $this->mLastRevision
->getText( $audience );
563 * Get the text of the current revision. No side-effects...
565 * @return String|false The text of the current revision
567 public function getRawText() {
568 $this->loadLastEdit();
569 if ( $this->mLastRevision
) {
570 return $this->mLastRevision
->getRawText();
576 * @return string MW timestamp of last article revision
578 public function getTimestamp() {
579 // Check if the field has been filled by WikiPage::setTimestamp()
580 if ( !$this->mTimestamp
) {
581 $this->loadLastEdit();
583 return wfTimestamp( TS_MW
, $this->mTimestamp
);
587 * Set the page timestamp (use only to avoid DB queries)
588 * @param $ts string MW timestamp of last article revision
591 public function setTimestamp( $ts ) {
592 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
596 * @param $audience Integer: one of:
597 * Revision::FOR_PUBLIC to be displayed to all users
598 * Revision::FOR_THIS_USER to be displayed to $wgUser
599 * Revision::RAW get the text regardless of permissions
600 * @return int user ID for the user that made the last article revision
602 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
603 $this->loadLastEdit();
604 if ( $this->mLastRevision
) {
605 return $this->mLastRevision
->getUser( $audience );
612 * @param $audience Integer: one of:
613 * Revision::FOR_PUBLIC to be displayed to all users
614 * Revision::FOR_THIS_USER to be displayed to $wgUser
615 * Revision::RAW get the text regardless of permissions
616 * @return string username of the user that made the last article revision
618 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
619 $this->loadLastEdit();
620 if ( $this->mLastRevision
) {
621 return $this->mLastRevision
->getUserText( $audience );
628 * @param $audience Integer: one of:
629 * Revision::FOR_PUBLIC to be displayed to all users
630 * Revision::FOR_THIS_USER to be displayed to $wgUser
631 * Revision::RAW get the text regardless of permissions
632 * @return string Comment stored for the last article revision
634 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
635 $this->loadLastEdit();
636 if ( $this->mLastRevision
) {
637 return $this->mLastRevision
->getComment( $audience );
644 * Returns true if last revision was marked as "minor edit"
646 * @return boolean Minor edit indicator for the last article revision.
648 public function getMinorEdit() {
649 $this->loadLastEdit();
650 if ( $this->mLastRevision
) {
651 return $this->mLastRevision
->isMinor();
658 * Get a list of users who have edited this article, not including the user who made
659 * the most recent revision, which you can get from $article->getUser() if you want it
660 * @return UserArrayFromResult
662 public function getContributors() {
663 # @todo FIXME: This is expensive; cache this info somewhere.
665 $dbr = wfGetDB( DB_SLAVE
);
667 if ( $dbr->implicitGroupby() ) {
668 $realNameField = 'user_real_name';
670 $realNameField = 'FIRST(user_real_name) AS user_real_name';
673 $tables = array( 'revision', 'user' );
676 'rev_user as user_id',
677 'rev_user_text AS user_name',
679 'MAX(rev_timestamp) AS timestamp',
682 $conds = array( 'rev_page' => $this->getId() );
684 // The user who made the top revision gets credited as "this page was last edited by
685 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
686 $user = $this->getUser();
688 $conds[] = "rev_user != $user";
690 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
693 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
696 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
700 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
701 'ORDER BY' => 'timestamp DESC',
704 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
705 return new UserArrayFromResult( $res );
709 * Should the parser cache be used?
711 * @param $user User The relevant user
714 public function isParserCacheUsed( User
$user, $oldid ) {
715 global $wgEnableParserCache;
717 return $wgEnableParserCache
718 && $user->getStubThreshold() == 0
721 && $this->mTitle
->isWikitextPage();
725 * Perform the actions of a page purging
727 public function doPurge() {
730 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
734 // Invalidate the cache
735 $this->mTitle
->invalidateCache();
739 // Commit the transaction before the purge is sent
740 $dbw = wfGetDB( DB_MASTER
);
744 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
748 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
749 if ( $this->getId() == 0 ) {
752 $text = $this->getRawText();
755 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
760 * Insert a new empty page record for this article.
761 * This *must* be followed up by creating a revision
762 * and running $this->updateRevisionOn( ... );
763 * or else the record will be left in a funky state.
764 * Best if all done inside a transaction.
766 * @param $dbw DatabaseBase
767 * @return int The newly created page_id key, or false if the title already existed
770 public function insertOn( $dbw ) {
771 wfProfileIn( __METHOD__
);
773 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
774 $dbw->insert( 'page', array(
775 'page_id' => $page_id,
776 'page_namespace' => $this->mTitle
->getNamespace(),
777 'page_title' => $this->mTitle
->getDBkey(),
779 'page_restrictions' => '',
780 'page_is_redirect' => 0, # Will set this shortly...
782 'page_random' => wfRandom(),
783 'page_touched' => $dbw->timestamp(),
784 'page_latest' => 0, # Fill this in shortly...
785 'page_len' => 0, # Fill this in shortly...
786 ), __METHOD__
, 'IGNORE' );
788 $affected = $dbw->affectedRows();
791 $newid = $dbw->insertId();
792 $this->mTitle
->resetArticleID( $newid );
794 wfProfileOut( __METHOD__
);
796 return $affected ?
$newid : false;
800 * Update the page record to point to a newly saved revision.
802 * @param $dbw DatabaseBase: object
803 * @param $revision Revision: For ID number, and text used to set
804 * length and redirect status fields
805 * @param $lastRevision Integer: if given, will not overwrite the page field
806 * when different from the currently set value.
807 * Giving 0 indicates the new page flag should be set
809 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
810 * removing rows in redirect table.
811 * @return bool true on success, false on failure
814 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
815 wfProfileIn( __METHOD__
);
817 $text = $revision->getText();
818 $rt = Title
::newFromRedirectRecurse( $text );
820 $conditions = array( 'page_id' => $this->getId() );
822 if ( !is_null( $lastRevision ) ) {
823 # An extra check against threads stepping on each other
824 $conditions['page_latest'] = $lastRevision;
827 $now = wfTimestampNow();
828 $dbw->update( 'page',
830 'page_latest' => $revision->getId(),
831 'page_touched' => $dbw->timestamp( $now ),
832 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
833 'page_is_redirect' => $rt !== null ?
1 : 0,
834 'page_len' => strlen( $text ),
839 $result = $dbw->affectedRows() != 0;
841 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
842 $this->setCachedLastEditTime( $now );
845 wfProfileOut( __METHOD__
);
850 * Get the cached timestamp for the last time the page changed.
851 * This is only used to help handle slave lag by comparing to page_touched.
852 * @return string MW timestamp
854 protected function getCachedLastEditTime() {
856 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
857 return $wgMemc->get( $key );
861 * Set the cached timestamp for the last time the page changed.
862 * This is only used to help handle slave lag by comparing to page_touched.
863 * @param $timestamp string
866 public function setCachedLastEditTime( $timestamp ) {
868 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
869 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
873 * Add row to the redirect table if this is a redirect, remove otherwise.
875 * @param $dbw DatabaseBase
876 * @param $redirectTitle Title object pointing to the redirect target,
877 * or NULL if this is not a redirect
878 * @param $lastRevIsRedirect If given, will optimize adding and
879 * removing rows in redirect table.
880 * @return bool true on success, false on failure
883 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
884 // Always update redirects (target link might have changed)
885 // Update/Insert if we don't know if the last revision was a redirect or not
886 // Delete if changing from redirect to non-redirect
887 $isRedirect = !is_null( $redirectTitle );
889 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
893 wfProfileIn( __METHOD__
);
895 $this->insertRedirectEntry( $redirectTitle );
897 // This is not a redirect, remove row from redirect table
898 $where = array( 'rd_from' => $this->getId() );
899 $dbw->delete( 'redirect', $where, __METHOD__
);
902 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
903 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
905 wfProfileOut( __METHOD__
);
907 return ( $dbw->affectedRows() != 0 );
911 * If the given revision is newer than the currently set page_latest,
912 * update the page record. Otherwise, do nothing.
914 * @param $dbw Database object
915 * @param $revision Revision object
918 public function updateIfNewerOn( $dbw, $revision ) {
919 wfProfileIn( __METHOD__
);
921 $row = $dbw->selectRow(
922 array( 'revision', 'page' ),
923 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
925 'page_id' => $this->getId(),
926 'page_latest=rev_id' ),
930 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
931 wfProfileOut( __METHOD__
);
934 $prev = $row->rev_id
;
935 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
937 # No or missing previous revision; mark the page as new
939 $lastRevIsRedirect = null;
942 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
944 wfProfileOut( __METHOD__
);
949 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
950 * @param $text String: new text of the section
951 * @param $summary String: new section's subject, only if $section is 'new'
952 * @param $edittime String: revision timestamp or null to use the current revision
953 * @return string Complete article text, or null if error
955 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
956 wfProfileIn( __METHOD__
);
958 if ( strval( $section ) == '' ) {
959 // Whole-page edit; let the whole text through
961 if ( is_null( $edittime ) ) {
962 $rev = Revision
::newFromTitle( $this->mTitle
);
964 $dbw = wfGetDB( DB_MASTER
);
965 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
969 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
970 $this->getId() . "; section: $section; edittime: $edittime)\n" );
971 wfProfileOut( __METHOD__
);
975 $oldtext = $rev->getText();
977 if ( $section == 'new' ) {
978 # Inserting a new section
979 $subject = $summary ?
wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
980 $text = strlen( trim( $oldtext ) ) > 0
981 ?
"{$oldtext}\n\n{$subject}{$text}"
982 : "{$subject}{$text}";
984 # Replacing an existing section; roll out the big guns
987 $text = $wgParser->replaceSection( $oldtext, $section, $text );
991 wfProfileOut( __METHOD__
);
996 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
998 * @return Int updated $flags
1000 function checkFlags( $flags ) {
1001 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1002 if ( $this->mTitle
->getArticleID() ) {
1003 $flags |
= EDIT_UPDATE
;
1013 * Change an existing article or create a new article. Updates RC and all necessary caches,
1014 * optionally via the deferred update array.
1016 * @param $text String: new text
1017 * @param $summary String: edit summary
1018 * @param $flags Integer bitfield:
1020 * Article is known or assumed to be non-existent, create a new one
1022 * Article is known or assumed to be pre-existing, update it
1024 * Mark this edit minor, if the user is allowed to do so
1026 * Do not log the change in recentchanges
1028 * Mark the edit a "bot" edit regardless of user rights
1029 * EDIT_DEFER_UPDATES
1030 * Defer some of the updates until the end of index.php
1032 * Fill in blank summaries with generated text where possible
1034 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1035 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1036 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1037 * edit-already-exists error will be returned. These two conditions are also possible with
1038 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1040 * @param $baseRevId the revision ID this edit was based off, if any
1041 * @param $user User the user doing the edit
1043 * @return Status object. Possible errors:
1044 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1045 * edit-gone-missing: In update mode, but the article didn't exist
1046 * edit-conflict: In update mode, the article changed unexpectedly
1047 * edit-no-change: Warning that the text was the same as before
1048 * edit-already-exists: In creation mode, but the article already exists
1050 * Extensions may define additional errors.
1052 * $return->value will contain an associative array with members as follows:
1053 * new: Boolean indicating if the function attempted to create a new article
1054 * revision: The revision object for the inserted revision, or null
1056 * Compatibility note: this function previously returned a boolean value indicating success/failure
1058 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1059 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1061 # Low-level sanity check
1062 if ( $this->mTitle
->getText() === '' ) {
1063 throw new MWException( 'Something is trying to edit an article with an empty title' );
1066 wfProfileIn( __METHOD__
);
1068 $user = is_null( $user ) ?
$wgUser : $user;
1069 $status = Status
::newGood( array() );
1071 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1072 $this->loadPageData();
1074 $flags = $this->checkFlags( $flags );
1076 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1077 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1079 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1081 if ( $status->isOK() ) {
1082 $status->fatal( 'edit-hook-aborted' );
1085 wfProfileOut( __METHOD__
);
1089 # Silently ignore EDIT_MINOR if not allowed
1090 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1091 $bot = $flags & EDIT_FORCE_BOT
;
1093 $oldtext = $this->getRawText(); // current revision
1094 $oldsize = strlen( $oldtext );
1095 $oldcountable = $this->isCountable();
1097 # Provide autosummaries if one is not provided and autosummaries are enabled.
1098 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1099 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1102 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1103 $text = $editInfo->pst
;
1104 $newsize = strlen( $text );
1106 $dbw = wfGetDB( DB_MASTER
);
1107 $now = wfTimestampNow();
1108 $this->mTimestamp
= $now;
1110 if ( $flags & EDIT_UPDATE
) {
1111 # Update article, but only if changed.
1112 $status->value
['new'] = false;
1114 # Make sure the revision is either completely inserted or not inserted at all
1115 if ( !$wgDBtransactions ) {
1116 $userAbort = ignore_user_abort( true );
1119 $revision = new Revision( array(
1120 'page' => $this->getId(),
1121 'comment' => $summary,
1122 'minor_edit' => $isminor,
1124 'parent_id' => $this->mLatest
,
1125 'user' => $user->getId(),
1126 'user_text' => $user->getName(),
1130 $changed = ( strcmp( $text, $oldtext ) != 0 );
1133 if ( !$this->mLatest
) {
1134 # Article gone missing
1135 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1136 $status->fatal( 'edit-gone-missing' );
1138 wfProfileOut( __METHOD__
);
1143 $revisionId = $revision->insertOn( $dbw );
1147 # Note that we use $this->mLatest instead of fetching a value from the master DB
1148 # during the course of this function. This makes sure that EditPage can detect
1149 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1150 # before this function is called. A previous function used a separate query, this
1151 # creates a window where concurrent edits can cause an ignored edit conflict.
1152 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest
);
1155 /* Belated edit conflict! Run away!! */
1156 $status->fatal( 'edit-conflict' );
1158 # Delete the invalid revision if the DB is not transactional
1159 if ( !$wgDBtransactions ) {
1160 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1166 global $wgUseRCPatrol;
1167 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1168 # Update recentchanges
1169 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1170 # Mark as patrolled if the user can do so
1171 $patrolled = $wgUseRCPatrol && !count(
1172 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1173 # Add RC row to the DB
1174 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1175 $this->mLatest
, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1176 $revisionId, $patrolled
1179 # Log auto-patrolled edits
1181 PatrolLog
::record( $rc, true );
1184 $user->incEditCount();
1189 if ( !$wgDBtransactions ) {
1190 ignore_user_abort( $userAbort );
1193 // Now that ignore_user_abort is restored, we can respond to fatal errors
1194 if ( !$status->isOK() ) {
1195 wfProfileOut( __METHOD__
);
1199 # Update links tables, site stats, etc.
1200 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1201 'oldcountable' => $oldcountable ) );
1204 $status->warning( 'edit-no-change' );
1206 // Keep the same revision ID, but do some updates on it
1207 $revisionId = $this->getLatest();
1208 // Update page_touched, this is usually implicit in the page update
1209 // Other cache updates are done in onArticleEdit()
1210 $this->mTitle
->invalidateCache();
1213 # Create new article
1214 $status->value
['new'] = true;
1218 # Add the page record; stake our claim on this title!
1219 # This will return false if the article already exists
1220 $newid = $this->insertOn( $dbw );
1222 if ( $newid === false ) {
1224 $status->fatal( 'edit-already-exists' );
1226 wfProfileOut( __METHOD__
);
1230 # Save the revision text...
1231 $revision = new Revision( array(
1233 'comment' => $summary,
1234 'minor_edit' => $isminor,
1236 'user' => $user->getId(),
1237 'user_text' => $user->getName(),
1240 $revisionId = $revision->insertOn( $dbw );
1242 $this->mTitle
->resetArticleID( $newid );
1243 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
1245 LinkCache
::singleton()->addGoodLinkObj( $newid, $this->mTitle
, strlen( $text ), (bool)Title
::newFromRedirect( $text ), $revisionId );
1247 # Update the page record with revision data
1248 $this->updateRevisionOn( $dbw, $revision, 0 );
1250 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1252 # Update recentchanges
1253 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1254 global $wgUseRCPatrol, $wgUseNPPatrol;
1256 # Mark as patrolled if the user can do so
1257 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1258 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1259 # Add RC row to the DB
1260 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1261 '', strlen( $text ), $revisionId, $patrolled );
1263 # Log auto-patrolled edits
1265 PatrolLog
::record( $rc, true );
1268 $user->incEditCount();
1271 # Update links, etc.
1272 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1274 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1275 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1278 # Do updates right now unless deferral was requested
1279 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1280 DeferredUpdates
::doUpdates();
1283 // Return the new revision (or null) to the caller
1284 $status->value
['revision'] = $revision;
1286 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1287 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1289 # Promote user to any groups they meet the criteria for
1290 $user->addAutopromoteOnceGroups( 'onEdit' );
1292 wfProfileOut( __METHOD__
);
1297 * Update the article's restriction field, and leave a log entry.
1299 * @todo: seperate the business/permission stuff out from backend code
1301 * @param $limit Array: set of restriction keys
1302 * @param $reason String
1303 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1304 * @param $expiry Array: per restriction type expiration
1305 * @param $user User The user updating the restrictions
1306 * @return bool true on success
1308 public function updateRestrictions(
1309 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
1311 global $wgUser, $wgContLang;
1312 $user = is_null( $user ) ?
$wgUser : $user;
1314 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1316 $id = $this->mTitle
->getArticleID();
1319 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1323 if ( wfReadOnly() ) {
1324 wfDebug( "updateRestrictions failed: read-only\n" );
1328 if ( count( $this->mTitle
->getUserPermissionsErrors( 'protect', $user ) ) ) {
1329 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1337 // Take this opportunity to purge out expired restrictions
1338 Title
::purgeExpiredRestrictions();
1340 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1341 # we expect a single selection, but the schema allows otherwise.
1343 $updated = self
::flattenRestrictions( $limit );
1346 foreach ( $restrictionTypes as $action ) {
1347 if ( isset( $expiry[$action] ) ) {
1348 # Get current restrictions on $action
1349 $aLimits = $this->mTitle
->getRestrictions( $action );
1350 $current[$action] = implode( '', $aLimits );
1351 # Are any actual restrictions being dealt with here?
1352 $aRChanged = count( $aLimits ) ||
!empty( $limit[$action] );
1354 # If something changed, we need to log it. Checking $aRChanged
1355 # assures that "unprotecting" a page that is not protected does
1356 # not log just because the expiry was "changed".
1358 $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] )
1365 $current = self
::flattenRestrictions( $current );
1367 $changed = ( $changed ||
$current != $updated );
1368 $changed = $changed ||
( $updated && $this->mTitle
->areRestrictionsCascading() != $cascade );
1369 $protect = ( $updated != '' );
1371 # If nothing's changed, do nothing
1373 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1374 $dbw = wfGetDB( DB_MASTER
);
1376 # Prepare a null revision to be added to the history
1377 $modified = $current != '' && $protect;
1380 $comment_type = $modified ?
'modifiedarticleprotection' : 'protectedarticle';
1382 $comment_type = 'unprotectedarticle';
1385 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle
->getPrefixedText() ) );
1387 # Only restrictions with the 'protect' right can cascade...
1388 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1389 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1391 # The schema allows multiple restrictions
1392 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1396 $cascade_description = '';
1399 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1403 $comment .= ": $reason";
1406 $editComment = $comment;
1407 $encodedExpiry = array();
1408 $protect_description = '';
1409 foreach ( $limit as $action => $restrictions ) {
1410 if ( !isset( $expiry[$action] ) )
1411 $expiry[$action] = $dbw->getInfinity();
1413 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1414 if ( $restrictions != '' ) {
1415 $protect_description .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1416 if ( $encodedExpiry[$action] != 'infinity' ) {
1417 $protect_description .= wfMsgForContent( 'protect-expiring',
1418 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1419 $wgContLang->date( $expiry[$action], false, false ) ,
1420 $wgContLang->time( $expiry[$action], false, false ) );
1422 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1425 $protect_description .= ') ';
1428 $protect_description = trim( $protect_description );
1430 if ( $protect_description && $protect ) {
1431 $editComment .= " ($protect_description)";
1435 $editComment .= "$cascade_description";
1438 # Update restrictions table
1439 foreach ( $limit as $action => $restrictions ) {
1440 if ( $restrictions != '' ) {
1441 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1442 array( 'pr_page' => $id,
1443 'pr_type' => $action,
1444 'pr_level' => $restrictions,
1445 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1446 'pr_expiry' => $encodedExpiry[$action]
1451 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1452 'pr_type' => $action ), __METHOD__
);
1456 # Insert a null revision
1457 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
1458 $nullRevId = $nullRevision->insertOn( $dbw );
1460 $latest = $this->getLatest();
1461 # Update page record
1462 $dbw->update( 'page',
1464 'page_touched' => $dbw->timestamp(),
1465 'page_restrictions' => '',
1466 'page_latest' => $nullRevId
1467 ), array( /* WHERE */
1472 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1473 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1475 # Update the protection log
1476 $log = new LogPage( 'protect' );
1478 $params = array( $protect_description, $cascade ?
'cascade' : '' );
1479 $log->addEntry( $modified ?
'modify' : 'protect', $this->mTitle
, trim( $reason ), $params );
1481 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1484 } # End "changed" check
1490 * Take an array of page restrictions and flatten it to a string
1491 * suitable for insertion into the page_restrictions field.
1492 * @param $limit Array
1495 protected static function flattenRestrictions( $limit ) {
1496 if ( !is_array( $limit ) ) {
1497 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1503 foreach ( $limit as $action => $restrictions ) {
1504 if ( $restrictions != '' ) {
1505 $bits[] = "$action=$restrictions";
1509 return implode( ':', $bits );
1513 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1515 public function isBigDeletion() {
1516 global $wgDeleteRevisionsLimit;
1518 if ( $wgDeleteRevisionsLimit ) {
1519 $revCount = $this->estimateRevisionCount();
1521 return $revCount > $wgDeleteRevisionsLimit;
1528 * @return int approximate revision count
1530 public function estimateRevisionCount() {
1531 $dbr = wfGetDB( DB_SLAVE
);
1533 // For an exact count...
1534 // return $dbr->selectField( 'revision', 'COUNT(*)',
1535 // array( 'rev_page' => $this->getId() ), __METHOD__ );
1536 return $dbr->estimateRowCount( 'revision', '*',
1537 array( 'rev_page' => $this->getId() ), __METHOD__
);
1541 * Get the last N authors
1542 * @param $num Integer: number of revisions to get
1543 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1544 * @return array Array of authors, duplicates not removed
1546 public function getLastNAuthors( $num, $revLatest = 0 ) {
1547 wfProfileIn( __METHOD__
);
1548 // First try the slave
1549 // If that doesn't have the latest revision, try the master
1551 $db = wfGetDB( DB_SLAVE
);
1554 $res = $db->select( array( 'page', 'revision' ),
1555 array( 'rev_id', 'rev_user_text' ),
1557 'page_namespace' => $this->mTitle
->getNamespace(),
1558 'page_title' => $this->mTitle
->getDBkey(),
1559 'rev_page = page_id'
1562 'ORDER BY' => 'rev_timestamp DESC',
1568 wfProfileOut( __METHOD__
);
1572 $row = $db->fetchObject( $res );
1574 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1575 $db = wfGetDB( DB_MASTER
);
1580 } while ( $continue );
1582 $authors = array( $row->rev_user_text
);
1584 foreach ( $res as $row ) {
1585 $authors[] = $row->rev_user_text
;
1588 wfProfileOut( __METHOD__
);
1593 * Back-end article deletion
1594 * Deletes the article with database consistency, writes logs, purges caches
1596 * @param $reason string delete reason for deletion log
1597 * @param suppress bitfield
1598 * Revision::DELETED_TEXT
1599 * Revision::DELETED_COMMENT
1600 * Revision::DELETED_USER
1601 * Revision::DELETED_RESTRICTED
1602 * @param $id int article ID
1603 * @param $commit boolean defaults to true, triggers transaction end
1604 * @param &$errors Array of errors to append to
1605 * @param $user User The relevant user
1606 * @return boolean true if successful
1608 public function doDeleteArticle(
1609 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
1611 global $wgUseTrackbacks, $wgEnableInterwikiTemplatesTracking, $wgGlobalDatabase, $wgUser;
1612 $user = is_null( $user ) ?
$wgUser : $user;
1614 wfDebug( __METHOD__
. "\n" );
1616 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1619 $dbw = wfGetDB( DB_MASTER
);
1620 $t = $this->mTitle
->getDBkey();
1621 $id = $id ?
$id : $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1623 if ( $t === '' ||
$id == 0 ) {
1627 DeferredUpdates
::addUpdate(
1628 new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 )
1631 // Bitfields to further suppress the content
1634 // This should be 15...
1635 $bitfield |
= Revision
::DELETED_TEXT
;
1636 $bitfield |
= Revision
::DELETED_COMMENT
;
1637 $bitfield |
= Revision
::DELETED_USER
;
1638 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1640 $bitfield = 'rev_deleted';
1644 // For now, shunt the revision data into the archive table.
1645 // Text is *not* removed from the text table; bulk storage
1646 // is left intact to avoid breaking block-compression or
1647 // immutable storage schemes.
1649 // For backwards compatibility, note that some older archive
1650 // table entries will have ar_text and ar_flags fields still.
1652 // In the future, we may keep revisions and mark them with
1653 // the rev_deleted field, which is reserved for this purpose.
1654 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1656 'ar_namespace' => 'page_namespace',
1657 'ar_title' => 'page_title',
1658 'ar_comment' => 'rev_comment',
1659 'ar_user' => 'rev_user',
1660 'ar_user_text' => 'rev_user_text',
1661 'ar_timestamp' => 'rev_timestamp',
1662 'ar_minor_edit' => 'rev_minor_edit',
1663 'ar_rev_id' => 'rev_id',
1664 'ar_parent_id' => 'rev_parent_id',
1665 'ar_text_id' => 'rev_text_id',
1666 'ar_text' => '\'\'', // Be explicit to appease
1667 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1668 'ar_len' => 'rev_len',
1669 'ar_page_id' => 'page_id',
1670 'ar_deleted' => $bitfield
1673 'page_id = rev_page'
1677 # Delete restrictions for it
1678 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__
);
1680 # Now that it's safely backed up, delete it
1681 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1682 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1689 # Fix category table counts
1691 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__
);
1693 foreach ( $res as $row ) {
1694 $cats [] = $row->cl_to
;
1697 $this->updateCategoryCounts( array(), $cats );
1699 # If using cascading deletes, we can skip some explicit deletes
1700 if ( !$dbw->cascadingDeletes() ) {
1701 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1703 if ( $wgUseTrackbacks ) {
1704 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
1707 # Delete outgoing links
1708 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__
);
1709 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__
);
1710 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__
);
1711 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__
);
1712 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__
);
1713 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__
);
1714 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__
);
1715 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
1716 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__
);
1718 if ( $wgEnableInterwikiTemplatesTracking && $wgGlobalDatabase ) {
1719 $dbw2 = wfGetDB( DB_MASTER
, array(), $wgGlobalDatabase );
1720 $dbw2->delete( 'globaltemplatelinks',
1721 array( 'gtl_from_wiki' => wfGetID(),
1722 'gtl_from_page' => $id )
1727 # If using cleanup triggers, we can skip some manual deletes
1728 if ( !$dbw->cleanupTriggers() ) {
1729 # Clean up recentchanges entries...
1730 $dbw->delete( 'recentchanges',
1731 array( 'rc_type != ' . RC_LOG
,
1732 'rc_namespace' => $this->mTitle
->getNamespace(),
1733 'rc_title' => $this->mTitle
->getDBkey() ),
1735 $dbw->delete( 'recentchanges',
1736 array( 'rc_type != ' . RC_LOG
, 'rc_cur_id' => $id ),
1741 self
::onArticleDelete( $this->mTitle
);
1743 # Clear the cached article id so the interface doesn't act like we exist
1744 $this->mTitle
->resetArticleID( 0 );
1746 # Log the deletion, if the page was suppressed, log it at Oversight instead
1747 $logtype = $suppress ?
'suppress' : 'delete';
1749 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1750 $logEntry->setPerformer( $user );
1751 $logEntry->setTarget( $this->mTitle
);
1752 $logEntry->setComment( $reason );
1753 $logid = $logEntry->insert();
1754 $logEntry->publish( $logid );
1760 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1765 * Roll back the most recent consecutive set of edits to a page
1766 * from the same user; fails if there are no eligible edits to
1767 * roll back to, e.g. user is the sole contributor. This function
1768 * performs permissions checks on $user, then calls commitRollback()
1769 * to do the dirty work
1771 * @param $fromP String: Name of the user whose edits to rollback.
1772 * @param $summary String: Custom summary. Set to default summary if empty.
1773 * @param $token String: Rollback token.
1774 * @param $bot Boolean: If true, mark all reverted edits as bot.
1776 * @param $resultDetails Array: contains result-specific array of additional values
1777 * 'alreadyrolled' : 'current' (rev)
1778 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1780 * @param $user User The user performing the rollback
1781 * @return array of errors, each error formatted as
1782 * array(messagekey, param1, param2, ...).
1783 * On success, the array is empty. This array can also be passed to
1784 * OutputPage::showPermissionsErrorPage().
1786 public function doRollback(
1787 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
1789 $resultDetails = null;
1792 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
1793 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
1794 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1796 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
1797 $errors[] = array( 'sessionfailure' );
1800 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
1801 $errors[] = array( 'actionthrottledtext' );
1804 # If there were errors, bail out now
1805 if ( !empty( $errors ) ) {
1809 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
1813 * Backend implementation of doRollback(), please refer there for parameter
1814 * and return value documentation
1816 * NOTE: This function does NOT check ANY permissions, it just commits the
1817 * rollback to the DB. Therefore, you should only call this function direct-
1818 * ly if you want to use custom permissions checks. If you don't, use
1819 * doRollback() instead.
1820 * @param $fromP String: Name of the user whose edits to rollback.
1821 * @param $summary String: Custom summary. Set to default summary if empty.
1822 * @param $bot Boolean: If true, mark all reverted edits as bot.
1824 * @param $resultDetails Array: contains result-specific array of additional values
1825 * @param $guser User The user performing the rollback
1827 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
1828 global $wgUseRCPatrol, $wgContLang;
1830 $dbw = wfGetDB( DB_MASTER
);
1832 if ( wfReadOnly() ) {
1833 return array( array( 'readonlytext' ) );
1836 # Get the last editor
1837 $current = Revision
::newFromTitle( $this->mTitle
);
1838 if ( is_null( $current ) ) {
1839 # Something wrong... no page?
1840 return array( array( 'notanarticle' ) );
1843 $from = str_replace( '_', ' ', $fromP );
1844 # User name given should match up with the top revision.
1845 # If the user was deleted then $from should be empty.
1846 if ( $from != $current->getUserText() ) {
1847 $resultDetails = array( 'current' => $current );
1848 return array( array( 'alreadyrolled',
1849 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
1850 htmlspecialchars( $fromP ),
1851 htmlspecialchars( $current->getUserText() )
1855 # Get the last edit not by this guy...
1856 # Note: these may not be public values
1857 $user = intval( $current->getRawUser() );
1858 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1859 $s = $dbw->selectRow( 'revision',
1860 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1861 array( 'rev_page' => $current->getPage(),
1862 "rev_user != {$user} OR rev_user_text != {$user_text}"
1864 array( 'USE INDEX' => 'page_timestamp',
1865 'ORDER BY' => 'rev_timestamp DESC' )
1867 if ( $s === false ) {
1868 # No one else ever edited this page
1869 return array( array( 'cantrollback' ) );
1870 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
1871 # Only admins can see this text
1872 return array( array( 'notvisiblerev' ) );
1876 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1877 # Mark all reverted edits as bot
1881 if ( $wgUseRCPatrol ) {
1882 # Mark all reverted edits as patrolled
1883 $set['rc_patrolled'] = 1;
1886 if ( count( $set ) ) {
1887 $dbw->update( 'recentchanges', $set,
1889 'rc_cur_id' => $current->getPage(),
1890 'rc_user_text' => $current->getUserText(),
1891 "rc_timestamp > '{$s->rev_timestamp}'",
1896 # Generate the edit summary if necessary
1897 $target = Revision
::newFromId( $s->rev_id
);
1898 if ( empty( $summary ) ) {
1899 if ( $from == '' ) { // no public user name
1900 $summary = wfMsgForContent( 'revertpage-nouser' );
1902 $summary = wfMsgForContent( 'revertpage' );
1906 # Allow the custom summary to use the same args as the default message
1908 $target->getUserText(), $from, $s->rev_id
,
1909 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
1910 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1912 $summary = wfMsgReplaceArgs( $summary, $args );
1915 $flags = EDIT_UPDATE
;
1917 if ( $guser->isAllowed( 'minoredit' ) ) {
1918 $flags |
= EDIT_MINOR
;
1921 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1922 $flags |
= EDIT_FORCE_BOT
;
1925 # Actually store the edit
1926 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1927 if ( !empty( $status->value
['revision'] ) ) {
1928 $revId = $status->value
['revision']->getId();
1933 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1935 $resultDetails = array(
1936 'summary' => $summary,
1937 'current' => $current,
1938 'target' => $target,
1946 * Do standard deferred updates after page view
1947 * @param $user User The relevant user
1949 public function doViewUpdates( User
$user ) {
1950 global $wgDisableCounters;
1951 if ( wfReadOnly() ) {
1955 # Don't update page view counters on views from bot users (bug 14044)
1956 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getId() ) {
1957 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1958 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1961 # Update newtalk / watchlist notification status
1962 $user->clearNotification( $this->mTitle
);
1966 * Prepare text which is about to be saved.
1967 * Returns a stdclass with source, pst and output members
1969 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1970 global $wgParser, $wgUser;
1971 $user = is_null( $user ) ?
$wgUser : $user;
1972 // @TODO fixme: check $user->getId() here???
1973 if ( $this->mPreparedEdit
1974 && $this->mPreparedEdit
->newText
== $text
1975 && $this->mPreparedEdit
->revid
== $revid
1978 return $this->mPreparedEdit
;
1981 $popts = ParserOptions
::newFromUser( $user );
1982 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1984 $edit = (object)array();
1985 $edit->revid
= $revid;
1986 $edit->newText
= $text;
1987 $edit->pst
= $this->preSaveTransform( $text, $user, $popts );
1988 $edit->popts
= $this->getParserOptions( true );
1989 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1990 $edit->oldText
= $this->getRawText();
1992 $this->mPreparedEdit
= $edit;
1998 * Do standard deferred updates after page edit.
1999 * Update links tables, site stats, search index and message cache.
2000 * Purges pages that include this page if the text was changed here.
2001 * Every 100th edit, prune the recent changes table.
2004 * @param $revision Revision object
2005 * @param $user User object that did the revision
2006 * @param $options Array of options, following indexes are used:
2007 * - changed: boolean, whether the revision changed the content (default true)
2008 * - created: boolean, whether the revision created the page (default false)
2009 * - oldcountable: boolean or null (default null):
2010 * - boolean: whether the page was counted as an article before that
2011 * revision, only used in changed is true and created is false
2012 * - null: don't change the article count
2014 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2015 global $wgEnableParserCache;
2017 wfProfileIn( __METHOD__
);
2019 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2020 $text = $revision->getText();
2023 # Be careful not to double-PST: $text is usually already PST-ed once
2024 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2025 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2026 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
2028 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2029 $editInfo = $this->mPreparedEdit
;
2032 # Save it to the parser cache
2033 if ( $wgEnableParserCache ) {
2034 $parserCache = ParserCache
::singleton();
2035 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2038 # Update the links tables
2039 $u = new LinksUpdate( $this->mTitle
, $editInfo->output
);
2042 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2044 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2045 if ( 0 == mt_rand( 0, 99 ) ) {
2046 // Flush old entries from the `recentchanges` table; we do this on
2047 // random requests so as to avoid an increase in writes for no good reason
2050 $dbw = wfGetDB( DB_MASTER
);
2051 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2054 array( "rc_timestamp < '$cutoff'" ),
2060 $id = $this->getId();
2061 $title = $this->mTitle
->getPrefixedDBkey();
2062 $shortTitle = $this->mTitle
->getDBkey();
2065 wfProfileOut( __METHOD__
);
2069 if ( !$options['changed'] ) {
2072 } elseif ( $options['created'] ) {
2073 $good = (int)$this->isCountable( $editInfo );
2075 } elseif ( $options['oldcountable'] !== null ) {
2076 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2083 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2084 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
2086 # If this is another user's talk page, update newtalk.
2087 # Don't do this if $options['changed'] = false (null-edits) nor if
2088 # it's a minor edit and the user doesn't want notifications for those.
2089 if ( $options['changed']
2090 && $this->mTitle
->getNamespace() == NS_USER_TALK
2091 && $shortTitle != $user->getTitleKey()
2092 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2094 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2095 $other = User
::newFromName( $shortTitle, false );
2097 wfDebug( __METHOD__
. ": invalid username\n" );
2098 } elseif ( User
::isIP( $shortTitle ) ) {
2099 // An anonymous user
2100 $other->setNewtalk( true );
2101 } elseif ( $other->isLoggedIn() ) {
2102 $other->setNewtalk( true );
2104 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2109 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2110 MessageCache
::singleton()->replace( $shortTitle, $text );
2113 if( $options['created'] ) {
2114 self
::onArticleCreate( $this->mTitle
);
2116 self
::onArticleEdit( $this->mTitle
);
2119 wfProfileOut( __METHOD__
);
2123 * Perform article updates on a special page creation.
2125 * @param $rev Revision object
2127 * @todo This is a shitty interface function. Kill it and replace the
2128 * other shitty functions like doEditUpdates and such so it's not needed
2130 * @deprecated since 1.18, use doEditUpdates()
2132 public function createUpdates( $rev ) {
2134 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2138 * This function is called right before saving the wikitext,
2139 * so we can do things like signatures and links-in-context.
2141 * @param $text String article contents
2142 * @param $user User object: user doing the edit
2143 * @param $popts ParserOptions object: parser options, default options for
2144 * the user loaded if null given
2145 * @return string article contents with altered wikitext markup (signatures
2146 * converted, {{subst:}}, templates, etc.)
2148 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2149 global $wgParser, $wgUser;
2150 $user = is_null( $user ) ?
$wgUser : $user;
2152 if ( $popts === null ) {
2153 $popts = ParserOptions
::newFromUser( $user );
2156 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2160 * Loads page_touched and returns a value indicating if it should be used
2161 * @return boolean true if not a redirect
2163 public function checkTouched() {
2164 if ( !$this->mDataLoaded
) {
2165 $this->loadPageData();
2167 return !$this->mIsRedirect
;
2171 * Get the page_touched field
2172 * @return string containing GMT timestamp
2174 public function getTouched() {
2175 if ( !$this->mDataLoaded
) {
2176 $this->loadPageData();
2178 return $this->mTouched
;
2182 * Get the page_latest field
2183 * @return integer rev_id of current revision
2185 public function getLatest() {
2186 if ( !$this->mDataLoaded
) {
2187 $this->loadPageData();
2189 return (int)$this->mLatest
;
2193 * Edit an article without doing all that other stuff
2194 * The article must already exist; link tables etc
2195 * are not updated, caches are not flushed.
2197 * @param $text String: text submitted
2198 * @param $user User The relevant user
2199 * @param $comment String: comment submitted
2200 * @param $minor Boolean: whereas it's a minor modification
2202 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2203 wfProfileIn( __METHOD__
);
2205 $dbw = wfGetDB( DB_MASTER
);
2206 $revision = new Revision( array(
2207 'page' => $this->getId(),
2209 'comment' => $comment,
2210 'minor_edit' => $minor ?
1 : 0,
2212 $revision->insertOn( $dbw );
2213 $this->updateRevisionOn( $dbw, $revision );
2215 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2217 wfProfileOut( __METHOD__
);
2221 * The onArticle*() functions are supposed to be a kind of hooks
2222 * which should be called whenever any of the specified actions
2225 * This is a good place to put code to clear caches, for instance.
2227 * This is called on page move and undelete, as well as edit
2229 * @param $title Title object
2231 public static function onArticleCreate( $title ) {
2232 # Update existence markers on article/talk tabs...
2233 if ( $title->isTalkPage() ) {
2234 $other = $title->getSubjectPage();
2236 $other = $title->getTalkPage();
2239 $other->invalidateCache();
2240 $other->purgeSquid();
2242 $title->touchLinks();
2243 $title->purgeSquid();
2244 $title->deleteTitleProtection();
2246 # Invalidate caches of distant articles which transclude this page
2247 DeferredUpdates
::addHTMLCacheUpdate( $title, 'globaltemplatelinks' );
2251 * Clears caches when article is deleted
2253 * @param $title Title
2255 public static function onArticleDelete( $title ) {
2256 # Update existence markers on article/talk tabs...
2257 if ( $title->isTalkPage() ) {
2258 $other = $title->getSubjectPage();
2260 $other = $title->getTalkPage();
2263 $other->invalidateCache();
2264 $other->purgeSquid();
2266 $title->touchLinks();
2267 $title->purgeSquid();
2270 HTMLFileCache
::clearFileCache( $title );
2273 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2274 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2278 if ( $title->getNamespace() == NS_FILE
) {
2279 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2280 $update->doUpdate();
2284 if ( $title->getNamespace() == NS_USER_TALK
) {
2285 $user = User
::newFromName( $title->getText(), false );
2286 $user->setNewtalk( false );
2290 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2292 # Invalidate caches of distant articles which transclude this page
2293 DeferredUpdates
::addHTMLCacheUpdate( $title, 'globaltemplatelinks' );
2297 * Purge caches on page update etc
2299 * @param $title Title object
2300 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2302 public static function onArticleEdit( $title ) {
2303 // Invalidate caches of articles which include this page
2304 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2306 // Invalidate caches of distant articles which transclude this page
2307 DeferredUpdates
::addHTMLCacheUpdate( $title, 'globaltemplatelinks' );
2309 // Invalidate the caches of all pages which redirect here
2310 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2312 # Purge squid for this page only
2313 $title->purgeSquid();
2315 # Clear file cache for this page only
2316 HTMLFileCache
::clearFileCache( $title );
2322 * Return a list of templates used by this article.
2323 * Uses the templatelinks table
2325 * @return Array of Title objects
2327 public function getUsedTemplates() {
2329 $id = $this->mTitle
->getArticleID();
2335 $dbr = wfGetDB( DB_SLAVE
);
2336 $res = $dbr->select( array( 'templatelinks' ),
2337 array( 'tl_namespace', 'tl_title' ),
2338 array( 'tl_from' => $id ),
2341 if ( $res !== false ) {
2342 foreach ( $res as $row ) {
2343 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2351 * Return a list of distant templates used by this article.
2352 * Uses the globaltemplatelinks table
2354 * @return Array of Title objects
2356 public function getUsedDistantTemplates() {
2357 global $wgGlobalDatabase;
2361 if ( $wgGlobalDatabase ) {
2362 $id = $this->mTitle
->getArticleID();
2368 $dbr = wfGetDB( DB_SLAVE
, array(), $wgGlobalDatabase );
2369 $res = $dbr->select( 'globaltemplatelinks',
2370 array( 'gtl_to_prefix', 'gtl_to_namespace', 'gtl_to_title' ),
2371 array( 'gtl_from_wiki' => wfWikiID( ), 'gtl_from_page' => $id ),
2374 if ( $res !== false ) {
2375 foreach ( $res as $row ) {
2376 $result[] = Title
::makeTitle( $row->gtl_to_namespace
, $row->gtl_to_title
, null, $row->gtl_to_prefix
);
2385 * Returns a list of hidden categories this page is a member of.
2386 * Uses the page_props and categorylinks tables.
2388 * @return Array of Title objects
2390 public function getHiddenCategories() {
2392 $id = $this->mTitle
->getArticleID();
2398 $dbr = wfGetDB( DB_SLAVE
);
2399 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2401 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2402 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2405 if ( $res !== false ) {
2406 foreach ( $res as $row ) {
2407 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2415 * Return an applicable autosummary if one exists for the given edit.
2416 * @param $oldtext String: the previous text of the page.
2417 * @param $newtext String: The submitted text of the page.
2418 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2419 * @return string An appropriate autosummary, or an empty string.
2421 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2424 # Decide what kind of autosummary is needed.
2426 # Redirect autosummaries
2427 $ot = Title
::newFromRedirect( $oldtext );
2428 $rt = Title
::newFromRedirect( $newtext );
2430 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2431 $truncatedtext = $wgContLang->truncate(
2432 str_replace( "\n", ' ', $newtext ),
2434 - strlen( wfMsgForContent( 'autoredircomment' ) )
2435 - strlen( $rt->getFullText() )
2437 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2440 # New page autosummaries
2441 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2442 # If they're making a new article, give its text, truncated, in the summary.
2444 $truncatedtext = $wgContLang->truncate(
2445 str_replace( "\n", ' ', $newtext ),
2446 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2448 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2451 # Blanking autosummaries
2452 if ( $oldtext != '' && $newtext == '' ) {
2453 return wfMsgForContent( 'autosumm-blank' );
2454 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2455 # Removing more than 90% of the article
2457 $truncatedtext = $wgContLang->truncate(
2459 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2461 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2464 # If we reach this point, there's no applicable autosummary for our case, so our
2465 # autosummary is empty.
2470 * Auto-generates a deletion reason
2472 * @param &$hasHistory Boolean: whether the page has a history
2473 * @return mixed String containing deletion reason or empty string, or boolean false
2474 * if no revision occurred
2476 public function getAutoDeleteReason( &$hasHistory ) {
2479 $dbw = wfGetDB( DB_MASTER
);
2480 // Get the last revision
2481 $rev = Revision
::newFromTitle( $this->getTitle() );
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 // Find out if there was only one contributor
2503 // Only scan the last 20 revisions
2504 $res = $dbw->select( 'revision', 'rev_user_text',
2505 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2507 array( 'LIMIT' => 20 )
2510 if ( $res === false ) {
2511 // This page has no revisions, which is very weird
2515 $hasHistory = ( $res->numRows() > 1 );
2516 $row = $dbw->fetchObject( $res );
2518 if ( $row ) { // $row is false if the only contributor is hidden
2519 $onlyAuthor = $row->rev_user_text
;
2520 // Try to find a second contributor
2521 foreach ( $res as $row ) {
2522 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2523 $onlyAuthor = false;
2528 $onlyAuthor = false;
2531 // Generate the summary with a '$1' placeholder
2533 // The current revision is blank and the one before is also
2534 // blank. It's just not our lucky day
2535 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2537 if ( $onlyAuthor ) {
2538 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2540 $reason = wfMsgForContent( 'excontent', '$1' );
2544 if ( $reason == '-' ) {
2545 // Allow these UI messages to be blanked out cleanly
2549 // Replace newlines with spaces to prevent uglyness
2550 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2551 // Calculate the maximum amount of chars to get
2552 // Max content length = max comment length - length of the comment (excl. $1)
2553 $maxLength = 255 - ( strlen( $reason ) - 2 );
2554 $contents = $wgContLang->truncate( $contents, $maxLength );
2555 // Remove possible unfinished links
2556 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2557 // Now replace the '$1' placeholder
2558 $reason = str_replace( '$1', $contents, $reason );
2564 * Get parser options suitable for rendering the primary article wikitext
2565 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
2566 * @return mixed ParserOptions object or boolean false
2568 public function getParserOptions( $canonical = false ) {
2569 global $wgUser, $wgLanguageCode;
2571 if ( !$this->mParserOptions ||
$canonical ) {
2572 $user = !$canonical ?
$wgUser : new User
;
2573 $parserOptions = new ParserOptions( $user );
2574 $parserOptions->setTidy( true );
2575 $parserOptions->enableLimitReport();
2578 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
2579 return $parserOptions;
2581 $this->mParserOptions
= $parserOptions;
2583 // Clone to allow modifications of the return value without affecting cache
2584 return clone $this->mParserOptions
;
2588 * Get parser options suitable for rendering the primary article wikitext
2590 * @return ParserOptions
2592 public function makeParserOptions( User
$user ) {
2593 $options = ParserOptions
::newFromUser( $user );
2594 $options->enableLimitReport(); // show inclusion/loop reports
2595 $options->setTidy( true ); // fix bad HTML
2600 * Update all the appropriate counts in the category table, given that
2601 * we've added the categories $added and deleted the categories $deleted.
2603 * @param $added array The names of categories that were added
2604 * @param $deleted array The names of categories that were deleted
2606 public function updateCategoryCounts( $added, $deleted ) {
2607 $ns = $this->mTitle
->getNamespace();
2608 $dbw = wfGetDB( DB_MASTER
);
2610 # First make sure the rows exist. If one of the "deleted" ones didn't
2611 # exist, we might legitimately not create it, but it's simpler to just
2612 # create it and then give it a negative value, since the value is bogus
2615 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2616 $insertCats = array_merge( $added, $deleted );
2617 if ( !$insertCats ) {
2618 # Okay, nothing to do
2622 $insertRows = array();
2624 foreach ( $insertCats as $cat ) {
2625 $insertRows[] = array(
2626 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2630 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2632 $addFields = array( 'cat_pages = cat_pages + 1' );
2633 $removeFields = array( 'cat_pages = cat_pages - 1' );
2635 if ( $ns == NS_CATEGORY
) {
2636 $addFields[] = 'cat_subcats = cat_subcats + 1';
2637 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2638 } elseif ( $ns == NS_FILE
) {
2639 $addFields[] = 'cat_files = cat_files + 1';
2640 $removeFields[] = 'cat_files = cat_files - 1';
2647 array( 'cat_title' => $added ),
2656 array( 'cat_title' => $deleted ),
2663 * Updates cascading protections
2665 * @param $parserOutput ParserOutput object for the current version
2667 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2668 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2672 // templatelinks table may have become out of sync,
2673 // especially if using variable-based transclusions.
2674 // For paranoia, check if things have changed and if
2675 // so apply updates to the database. This will ensure
2676 // that cascaded protections apply as soon as the changes
2679 # Get templates from templatelinks
2680 $id = $this->mTitle
->getArticleID();
2682 $tlTemplates = array();
2684 $dbr = wfGetDB( DB_SLAVE
);
2685 $res = $dbr->select( array( 'templatelinks' ),
2686 array( 'tl_namespace', 'tl_title' ),
2687 array( 'tl_from' => $id ),
2691 foreach ( $res as $row ) {
2692 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2695 # Get templates from parser output.
2696 $poTemplates = array();
2697 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2698 foreach ( $templates as $dbk => $id ) {
2699 $poTemplates["$ns:$dbk"] = true;
2704 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2706 if ( count( $templates_diff ) > 0 ) {
2707 # Whee, link updates time.
2708 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2714 * @deprecated since 1.18
2716 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2718 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2722 * @deprecated since 1.18
2724 public function viewUpdates() {
2726 return $this->doViewUpdates( $wgUser );
2730 * @deprecated since 1.18
2732 public function useParserCache( $oldid ) {
2734 return $this->isParserCacheUsed( $wgUser, $oldid );