Move category membership RC updates to CategoryMembershipChangeJob
[lhc/web/wiklou.git] / includes / page / WikiPage.php
1 <?php
2 /**
3 * Base representation for a MediaWiki page.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
25 */
26 interface Page {
27 }
28
29 /**
30 * Class representing a MediaWiki article and history.
31 *
32 * Some fields are public only for backwards-compatibility. Use accessors.
33 * In the past, this class was part of Article.php and everything was public.
34 */
35 class WikiPage implements Page, IDBAccessObject {
36 // Constants for $mDataLoadedFrom and related
37
38 /**
39 * @var Title
40 */
41 public $mTitle = null;
42
43 /**@{{
44 * @protected
45 */
46 public $mDataLoaded = false; // !< Boolean
47 public $mIsRedirect = false; // !< Boolean
48 public $mLatest = false; // !< Integer (false means "not loaded")
49 /**@}}*/
50
51 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
52 public $mPreparedEdit = false;
53
54 /**
55 * @var int
56 */
57 protected $mId = null;
58
59 /**
60 * @var int One of the READ_* constants
61 */
62 protected $mDataLoadedFrom = self::READ_NONE;
63
64 /**
65 * @var Title
66 */
67 protected $mRedirectTarget = null;
68
69 /**
70 * @var Revision
71 */
72 protected $mLastRevision = null;
73
74 /**
75 * @var string Timestamp of the current revision or empty string if not loaded
76 */
77 protected $mTimestamp = '';
78
79 /**
80 * @var string
81 */
82 protected $mTouched = '19700101000000';
83
84 /**
85 * @var string
86 */
87 protected $mLinksUpdated = '19700101000000';
88
89 /**
90 * Constructor and clear the article
91 * @param Title $title Reference to a Title object.
92 */
93 public function __construct( Title $title ) {
94 $this->mTitle = $title;
95 }
96
97 /**
98 * Create a WikiPage object of the appropriate class for the given title.
99 *
100 * @param Title $title
101 *
102 * @throws MWException
103 * @return WikiPage Object of the appropriate type
104 */
105 public static function factory( Title $title ) {
106 $ns = $title->getNamespace();
107
108 if ( $ns == NS_MEDIA ) {
109 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
110 } elseif ( $ns < 0 ) {
111 throw new MWException( "Invalid or virtual namespace $ns given." );
112 }
113
114 switch ( $ns ) {
115 case NS_FILE:
116 $page = new WikiFilePage( $title );
117 break;
118 case NS_CATEGORY:
119 $page = new WikiCategoryPage( $title );
120 break;
121 default:
122 $page = new WikiPage( $title );
123 }
124
125 return $page;
126 }
127
128 /**
129 * Constructor from a page id
130 *
131 * @param int $id Article ID to load
132 * @param string|int $from One of the following values:
133 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
134 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
135 *
136 * @return WikiPage|null
137 */
138 public static function newFromID( $id, $from = 'fromdb' ) {
139 // page id's are never 0 or negative, see bug 61166
140 if ( $id < 1 ) {
141 return null;
142 }
143
144 $from = self::convertSelectType( $from );
145 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
146 $row = $db->selectRow(
147 'page', self::selectFields(), array( 'page_id' => $id ), __METHOD__ );
148 if ( !$row ) {
149 return null;
150 }
151 return self::newFromRow( $row, $from );
152 }
153
154 /**
155 * Constructor from a database row
156 *
157 * @since 1.20
158 * @param object $row Database row containing at least fields returned by selectFields().
159 * @param string|int $from Source of $data:
160 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
161 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
162 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
163 * @return WikiPage
164 */
165 public static function newFromRow( $row, $from = 'fromdb' ) {
166 $page = self::factory( Title::newFromRow( $row ) );
167 $page->loadFromRow( $row, $from );
168 return $page;
169 }
170
171 /**
172 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
173 *
174 * @param object|string|int $type
175 * @return mixed
176 */
177 private static function convertSelectType( $type ) {
178 switch ( $type ) {
179 case 'fromdb':
180 return self::READ_NORMAL;
181 case 'fromdbmaster':
182 return self::READ_LATEST;
183 case 'forupdate':
184 return self::READ_LOCKING;
185 default:
186 // It may already be an integer or whatever else
187 return $type;
188 }
189 }
190
191 /**
192 * Returns overrides for action handlers.
193 * Classes listed here will be used instead of the default one when
194 * (and only when) $wgActions[$action] === true. This allows subclasses
195 * to override the default behavior.
196 *
197 * @todo Move this UI stuff somewhere else
198 *
199 * @return array
200 */
201 public function getActionOverrides() {
202 $content_handler = $this->getContentHandler();
203 return $content_handler->getActionOverrides();
204 }
205
206 /**
207 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
208 *
209 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
210 *
211 * @return ContentHandler
212 *
213 * @since 1.21
214 */
215 public function getContentHandler() {
216 return ContentHandler::getForModelID( $this->getContentModel() );
217 }
218
219 /**
220 * Get the title object of the article
221 * @return Title Title object of this page
222 */
223 public function getTitle() {
224 return $this->mTitle;
225 }
226
227 /**
228 * Clear the object
229 * @return void
230 */
231 public function clear() {
232 $this->mDataLoaded = false;
233 $this->mDataLoadedFrom = self::READ_NONE;
234
235 $this->clearCacheFields();
236 }
237
238 /**
239 * Clear the object cache fields
240 * @return void
241 */
242 protected function clearCacheFields() {
243 $this->mId = null;
244 $this->mRedirectTarget = null; // Title object if set
245 $this->mLastRevision = null; // Latest revision
246 $this->mTouched = '19700101000000';
247 $this->mLinksUpdated = '19700101000000';
248 $this->mTimestamp = '';
249 $this->mIsRedirect = false;
250 $this->mLatest = false;
251 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
252 // the requested rev ID and content against the cached one for equality. For most
253 // content types, the output should not change during the lifetime of this cache.
254 // Clearing it can cause extra parses on edit for no reason.
255 }
256
257 /**
258 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
259 * @return void
260 * @since 1.23
261 */
262 public function clearPreparedEdit() {
263 $this->mPreparedEdit = false;
264 }
265
266 /**
267 * Return the list of revision fields that should be selected to create
268 * a new page.
269 *
270 * @return array
271 */
272 public static function selectFields() {
273 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
274
275 $fields = array(
276 'page_id',
277 'page_namespace',
278 'page_title',
279 'page_restrictions',
280 'page_is_redirect',
281 'page_is_new',
282 'page_random',
283 'page_touched',
284 'page_links_updated',
285 'page_latest',
286 'page_len',
287 );
288
289 if ( $wgContentHandlerUseDB ) {
290 $fields[] = 'page_content_model';
291 }
292
293 if ( $wgPageLanguageUseDB ) {
294 $fields[] = 'page_lang';
295 }
296
297 return $fields;
298 }
299
300 /**
301 * Fetch a page record with the given conditions
302 * @param IDatabase $dbr
303 * @param array $conditions
304 * @param array $options
305 * @return object|bool Database result resource, or false on failure
306 */
307 protected function pageData( $dbr, $conditions, $options = array() ) {
308 $fields = self::selectFields();
309
310 Hooks::run( 'ArticlePageDataBefore', array( &$this, &$fields ) );
311
312 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
313
314 Hooks::run( 'ArticlePageDataAfter', array( &$this, &$row ) );
315
316 return $row;
317 }
318
319 /**
320 * Fetch a page record matching the Title object's namespace and title
321 * using a sanitized title string
322 *
323 * @param IDatabase $dbr
324 * @param Title $title
325 * @param array $options
326 * @return object|bool Database result resource, or false on failure
327 */
328 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
329 return $this->pageData( $dbr, array(
330 'page_namespace' => $title->getNamespace(),
331 'page_title' => $title->getDBkey() ), $options );
332 }
333
334 /**
335 * Fetch a page record matching the requested ID
336 *
337 * @param IDatabase $dbr
338 * @param int $id
339 * @param array $options
340 * @return object|bool Database result resource, or false on failure
341 */
342 public function pageDataFromId( $dbr, $id, $options = array() ) {
343 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
344 }
345
346 /**
347 * Load the object from a given source by title
348 *
349 * @param object|string|int $from One of the following:
350 * - A DB query result object.
351 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
352 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
353 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
354 * using SELECT FOR UPDATE.
355 *
356 * @return void
357 */
358 public function loadPageData( $from = 'fromdb' ) {
359 $from = self::convertSelectType( $from );
360 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
361 // We already have the data from the correct location, no need to load it twice.
362 return;
363 }
364
365 if ( is_int( $from ) ) {
366 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
367 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
368
369 if ( !$data
370 && $index == DB_SLAVE
371 && wfGetLB()->getServerCount() > 1
372 && wfGetLB()->hasOrMadeRecentMasterChanges()
373 ) {
374 $from = self::READ_LATEST;
375 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
376 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
377 }
378 } else {
379 // No idea from where the caller got this data, assume slave database.
380 $data = $from;
381 $from = self::READ_NORMAL;
382 }
383
384 $this->loadFromRow( $data, $from );
385 }
386
387 /**
388 * Load the object from a database row
389 *
390 * @since 1.20
391 * @param object|bool $data DB row containing fields returned by selectFields() or false
392 * @param string|int $from One of the following:
393 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
394 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
395 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
396 * the master DB using SELECT FOR UPDATE
397 */
398 public function loadFromRow( $data, $from ) {
399 $lc = LinkCache::singleton();
400 $lc->clearLink( $this->mTitle );
401
402 if ( $data ) {
403 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
404
405 $this->mTitle->loadFromRow( $data );
406
407 // Old-fashioned restrictions
408 $this->mTitle->loadRestrictions( $data->page_restrictions );
409
410 $this->mId = intval( $data->page_id );
411 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
412 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
413 $this->mIsRedirect = intval( $data->page_is_redirect );
414 $this->mLatest = intval( $data->page_latest );
415 // Bug 37225: $latest may no longer match the cached latest Revision object.
416 // Double-check the ID of any cached latest Revision object for consistency.
417 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
418 $this->mLastRevision = null;
419 $this->mTimestamp = '';
420 }
421 } else {
422 $lc->addBadLinkObj( $this->mTitle );
423
424 $this->mTitle->loadFromRow( false );
425
426 $this->clearCacheFields();
427
428 $this->mId = 0;
429 }
430
431 $this->mDataLoaded = true;
432 $this->mDataLoadedFrom = self::convertSelectType( $from );
433 }
434
435 /**
436 * @return int Page ID
437 */
438 public function getId() {
439 if ( !$this->mDataLoaded ) {
440 $this->loadPageData();
441 }
442 return $this->mId;
443 }
444
445 /**
446 * @return bool Whether or not the page exists in the database
447 */
448 public function exists() {
449 if ( !$this->mDataLoaded ) {
450 $this->loadPageData();
451 }
452 return $this->mId > 0;
453 }
454
455 /**
456 * Check if this page is something we're going to be showing
457 * some sort of sensible content for. If we return false, page
458 * views (plain action=view) will return an HTTP 404 response,
459 * so spiders and robots can know they're following a bad link.
460 *
461 * @return bool
462 */
463 public function hasViewableContent() {
464 return $this->exists() || $this->mTitle->isAlwaysKnown();
465 }
466
467 /**
468 * Tests if the article content represents a redirect
469 *
470 * @return bool
471 */
472 public function isRedirect() {
473 if ( !$this->mDataLoaded ) {
474 $this->loadPageData();
475 }
476
477 return (bool)$this->mIsRedirect;
478 }
479
480 /**
481 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
482 *
483 * Will use the revisions actual content model if the page exists,
484 * and the page's default if the page doesn't exist yet.
485 *
486 * @return string
487 *
488 * @since 1.21
489 */
490 public function getContentModel() {
491 if ( $this->exists() ) {
492 // look at the revision's actual content model
493 $rev = $this->getRevision();
494
495 if ( $rev !== null ) {
496 return $rev->getContentModel();
497 } else {
498 $title = $this->mTitle->getPrefixedDBkey();
499 wfWarn( "Page $title exists but has no (visible) revisions!" );
500 }
501 }
502
503 // use the default model for this page
504 return $this->mTitle->getContentModel();
505 }
506
507 /**
508 * Loads page_touched and returns a value indicating if it should be used
509 * @return bool True if not a redirect
510 */
511 public function checkTouched() {
512 if ( !$this->mDataLoaded ) {
513 $this->loadPageData();
514 }
515 return !$this->mIsRedirect;
516 }
517
518 /**
519 * Get the page_touched field
520 * @return string Containing GMT timestamp
521 */
522 public function getTouched() {
523 if ( !$this->mDataLoaded ) {
524 $this->loadPageData();
525 }
526 return $this->mTouched;
527 }
528
529 /**
530 * Get the page_links_updated field
531 * @return string|null Containing GMT timestamp
532 */
533 public function getLinksTimestamp() {
534 if ( !$this->mDataLoaded ) {
535 $this->loadPageData();
536 }
537 return $this->mLinksUpdated;
538 }
539
540 /**
541 * Get the page_latest field
542 * @return int The rev_id of current revision
543 */
544 public function getLatest() {
545 if ( !$this->mDataLoaded ) {
546 $this->loadPageData();
547 }
548 return (int)$this->mLatest;
549 }
550
551 /**
552 * Get the Revision object of the oldest revision
553 * @return Revision|null
554 */
555 public function getOldestRevision() {
556
557 // Try using the slave database first, then try the master
558 $continue = 2;
559 $db = wfGetDB( DB_SLAVE );
560 $revSelectFields = Revision::selectFields();
561
562 $row = null;
563 while ( $continue ) {
564 $row = $db->selectRow(
565 array( 'page', 'revision' ),
566 $revSelectFields,
567 array(
568 'page_namespace' => $this->mTitle->getNamespace(),
569 'page_title' => $this->mTitle->getDBkey(),
570 'rev_page = page_id'
571 ),
572 __METHOD__,
573 array(
574 'ORDER BY' => 'rev_timestamp ASC'
575 )
576 );
577
578 if ( $row ) {
579 $continue = 0;
580 } else {
581 $db = wfGetDB( DB_MASTER );
582 $continue--;
583 }
584 }
585
586 return $row ? Revision::newFromRow( $row ) : null;
587 }
588
589 /**
590 * Loads everything except the text
591 * This isn't necessary for all uses, so it's only done if needed.
592 */
593 protected function loadLastEdit() {
594 if ( $this->mLastRevision !== null ) {
595 return; // already loaded
596 }
597
598 $latest = $this->getLatest();
599 if ( !$latest ) {
600 return; // page doesn't exist or is missing page_latest info
601 }
602
603 if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
604 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
605 // includes the latest changes committed. This is true even within REPEATABLE-READ
606 // transactions, where S1 normally only sees changes committed before the first S1
607 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
608 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
609 // happened after the first S1 SELECT.
610 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
611 $flags = Revision::READ_LOCKING;
612 } elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
613 // Bug T93976: if page_latest was loaded from the master, fetch the
614 // revision from there as well, as it may not exist yet on a slave DB.
615 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
616 $flags = Revision::READ_LATEST;
617 } else {
618 $flags = 0;
619 }
620 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
621 if ( $revision ) { // sanity
622 $this->setLastEdit( $revision );
623 }
624 }
625
626 /**
627 * Set the latest revision
628 * @param Revision $revision
629 */
630 protected function setLastEdit( Revision $revision ) {
631 $this->mLastRevision = $revision;
632 $this->mTimestamp = $revision->getTimestamp();
633 }
634
635 /**
636 * Get the latest revision
637 * @return Revision|null
638 */
639 public function getRevision() {
640 $this->loadLastEdit();
641 if ( $this->mLastRevision ) {
642 return $this->mLastRevision;
643 }
644 return null;
645 }
646
647 /**
648 * Get the content of the current revision. No side-effects...
649 *
650 * @param int $audience One of:
651 * Revision::FOR_PUBLIC to be displayed to all users
652 * Revision::FOR_THIS_USER to be displayed to $wgUser
653 * Revision::RAW get the text regardless of permissions
654 * @param User $user User object to check for, only if FOR_THIS_USER is passed
655 * to the $audience parameter
656 * @return Content|null The content of the current revision
657 *
658 * @since 1.21
659 */
660 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
661 $this->loadLastEdit();
662 if ( $this->mLastRevision ) {
663 return $this->mLastRevision->getContent( $audience, $user );
664 }
665 return null;
666 }
667
668 /**
669 * Get the text of the current revision. No side-effects...
670 *
671 * @param int $audience One of:
672 * Revision::FOR_PUBLIC to be displayed to all users
673 * Revision::FOR_THIS_USER to be displayed to the given user
674 * Revision::RAW get the text regardless of permissions
675 * @param User $user User object to check for, only if FOR_THIS_USER is passed
676 * to the $audience parameter
677 * @return string|bool The text of the current revision
678 * @deprecated since 1.21, getContent() should be used instead.
679 */
680 public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
681 ContentHandler::deprecated( __METHOD__, '1.21' );
682
683 $this->loadLastEdit();
684 if ( $this->mLastRevision ) {
685 return $this->mLastRevision->getText( $audience, $user );
686 }
687 return false;
688 }
689
690 /**
691 * Get the text of the current revision. No side-effects...
692 *
693 * @return string|bool The text of the current revision. False on failure
694 * @deprecated since 1.21, getContent() should be used instead.
695 */
696 public function getRawText() {
697 ContentHandler::deprecated( __METHOD__, '1.21' );
698
699 return $this->getText( Revision::RAW );
700 }
701
702 /**
703 * @return string MW timestamp of last article revision
704 */
705 public function getTimestamp() {
706 // Check if the field has been filled by WikiPage::setTimestamp()
707 if ( !$this->mTimestamp ) {
708 $this->loadLastEdit();
709 }
710
711 return wfTimestamp( TS_MW, $this->mTimestamp );
712 }
713
714 /**
715 * Set the page timestamp (use only to avoid DB queries)
716 * @param string $ts MW timestamp of last article revision
717 * @return void
718 */
719 public function setTimestamp( $ts ) {
720 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
721 }
722
723 /**
724 * @param int $audience One of:
725 * Revision::FOR_PUBLIC to be displayed to all users
726 * Revision::FOR_THIS_USER to be displayed to the given user
727 * Revision::RAW get the text regardless of permissions
728 * @param User $user User object to check for, only if FOR_THIS_USER is passed
729 * to the $audience parameter
730 * @return int User ID for the user that made the last article revision
731 */
732 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
733 $this->loadLastEdit();
734 if ( $this->mLastRevision ) {
735 return $this->mLastRevision->getUser( $audience, $user );
736 } else {
737 return -1;
738 }
739 }
740
741 /**
742 * Get the User object of the user who created the page
743 * @param int $audience One of:
744 * Revision::FOR_PUBLIC to be displayed to all users
745 * Revision::FOR_THIS_USER to be displayed to the given user
746 * Revision::RAW get the text regardless of permissions
747 * @param User $user User object to check for, only if FOR_THIS_USER is passed
748 * to the $audience parameter
749 * @return User|null
750 */
751 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
752 $revision = $this->getOldestRevision();
753 if ( $revision ) {
754 $userName = $revision->getUserText( $audience, $user );
755 return User::newFromName( $userName, false );
756 } else {
757 return null;
758 }
759 }
760
761 /**
762 * @param int $audience One of:
763 * Revision::FOR_PUBLIC to be displayed to all users
764 * Revision::FOR_THIS_USER to be displayed to the given user
765 * Revision::RAW get the text regardless of permissions
766 * @param User $user User object to check for, only if FOR_THIS_USER is passed
767 * to the $audience parameter
768 * @return string Username of the user that made the last article revision
769 */
770 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
771 $this->loadLastEdit();
772 if ( $this->mLastRevision ) {
773 return $this->mLastRevision->getUserText( $audience, $user );
774 } else {
775 return '';
776 }
777 }
778
779 /**
780 * @param int $audience One of:
781 * Revision::FOR_PUBLIC to be displayed to all users
782 * Revision::FOR_THIS_USER to be displayed to the given user
783 * Revision::RAW get the text regardless of permissions
784 * @param User $user User object to check for, only if FOR_THIS_USER is passed
785 * to the $audience parameter
786 * @return string Comment stored for the last article revision
787 */
788 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
789 $this->loadLastEdit();
790 if ( $this->mLastRevision ) {
791 return $this->mLastRevision->getComment( $audience, $user );
792 } else {
793 return '';
794 }
795 }
796
797 /**
798 * Returns true if last revision was marked as "minor edit"
799 *
800 * @return bool Minor edit indicator for the last article revision.
801 */
802 public function getMinorEdit() {
803 $this->loadLastEdit();
804 if ( $this->mLastRevision ) {
805 return $this->mLastRevision->isMinor();
806 } else {
807 return false;
808 }
809 }
810
811 /**
812 * Determine whether a page would be suitable for being counted as an
813 * article in the site_stats table based on the title & its content
814 *
815 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
816 * if false, the current database state will be used
817 * @return bool
818 */
819 public function isCountable( $editInfo = false ) {
820 global $wgArticleCountMethod;
821
822 if ( !$this->mTitle->isContentPage() ) {
823 return false;
824 }
825
826 if ( $editInfo ) {
827 $content = $editInfo->pstContent;
828 } else {
829 $content = $this->getContent();
830 }
831
832 if ( !$content || $content->isRedirect() ) {
833 return false;
834 }
835
836 $hasLinks = null;
837
838 if ( $wgArticleCountMethod === 'link' ) {
839 // nasty special case to avoid re-parsing to detect links
840
841 if ( $editInfo ) {
842 // ParserOutput::getLinks() is a 2D array of page links, so
843 // to be really correct we would need to recurse in the array
844 // but the main array should only have items in it if there are
845 // links.
846 $hasLinks = (bool)count( $editInfo->output->getLinks() );
847 } else {
848 $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
849 array( 'pl_from' => $this->getId() ), __METHOD__ );
850 }
851 }
852
853 return $content->isCountable( $hasLinks );
854 }
855
856 /**
857 * If this page is a redirect, get its target
858 *
859 * The target will be fetched from the redirect table if possible.
860 * If this page doesn't have an entry there, call insertRedirect()
861 * @return Title|null Title object, or null if this page is not a redirect
862 */
863 public function getRedirectTarget() {
864 if ( !$this->mTitle->isRedirect() ) {
865 return null;
866 }
867
868 if ( $this->mRedirectTarget !== null ) {
869 return $this->mRedirectTarget;
870 }
871
872 // Query the redirect table
873 $dbr = wfGetDB( DB_SLAVE );
874 $row = $dbr->selectRow( 'redirect',
875 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
876 array( 'rd_from' => $this->getId() ),
877 __METHOD__
878 );
879
880 // rd_fragment and rd_interwiki were added later, populate them if empty
881 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
882 $this->mRedirectTarget = Title::makeTitle(
883 $row->rd_namespace, $row->rd_title,
884 $row->rd_fragment, $row->rd_interwiki );
885 return $this->mRedirectTarget;
886 }
887
888 // This page doesn't have an entry in the redirect table
889 $this->mRedirectTarget = $this->insertRedirect();
890 return $this->mRedirectTarget;
891 }
892
893 /**
894 * Insert an entry for this page into the redirect table.
895 *
896 * Don't call this function directly unless you know what you're doing.
897 * @return Title|null Title object or null if not a redirect
898 */
899 public function insertRedirect() {
900 // recurse through to only get the final target
901 $content = $this->getContent();
902 $retval = $content ? $content->getUltimateRedirectTarget() : null;
903 if ( !$retval ) {
904 return null;
905 }
906 $this->insertRedirectEntry( $retval );
907 return $retval;
908 }
909
910 /**
911 * Insert or update the redirect table entry for this page to indicate
912 * it redirects to $rt .
913 * @param Title $rt Redirect target
914 */
915 public function insertRedirectEntry( $rt ) {
916 $dbw = wfGetDB( DB_MASTER );
917 $dbw->replace( 'redirect', array( 'rd_from' ),
918 array(
919 'rd_from' => $this->getId(),
920 'rd_namespace' => $rt->getNamespace(),
921 'rd_title' => $rt->getDBkey(),
922 'rd_fragment' => $rt->getFragment(),
923 'rd_interwiki' => $rt->getInterwiki(),
924 ),
925 __METHOD__
926 );
927 }
928
929 /**
930 * Get the Title object or URL this page redirects to
931 *
932 * @return bool|Title|string False, Title of in-wiki target, or string with URL
933 */
934 public function followRedirect() {
935 return $this->getRedirectURL( $this->getRedirectTarget() );
936 }
937
938 /**
939 * Get the Title object or URL to use for a redirect. We use Title
940 * objects for same-wiki, non-special redirects and URLs for everything
941 * else.
942 * @param Title $rt Redirect target
943 * @return bool|Title|string False, Title object of local target, or string with URL
944 */
945 public function getRedirectURL( $rt ) {
946 if ( !$rt ) {
947 return false;
948 }
949
950 if ( $rt->isExternal() ) {
951 if ( $rt->isLocal() ) {
952 // Offsite wikis need an HTTP redirect.
953 // This can be hard to reverse and may produce loops,
954 // so they may be disabled in the site configuration.
955 $source = $this->mTitle->getFullURL( 'redirect=no' );
956 return $rt->getFullURL( array( 'rdfrom' => $source ) );
957 } else {
958 // External pages without "local" bit set are not valid
959 // redirect targets
960 return false;
961 }
962 }
963
964 if ( $rt->isSpecialPage() ) {
965 // Gotta handle redirects to special pages differently:
966 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
967 // Some pages are not valid targets.
968 if ( $rt->isValidRedirectTarget() ) {
969 return $rt->getFullURL();
970 } else {
971 return false;
972 }
973 }
974
975 return $rt;
976 }
977
978 /**
979 * Get a list of users who have edited this article, not including the user who made
980 * the most recent revision, which you can get from $article->getUser() if you want it
981 * @return UserArrayFromResult
982 */
983 public function getContributors() {
984 // @todo FIXME: This is expensive; cache this info somewhere.
985
986 $dbr = wfGetDB( DB_SLAVE );
987
988 if ( $dbr->implicitGroupby() ) {
989 $realNameField = 'user_real_name';
990 } else {
991 $realNameField = 'MIN(user_real_name) AS user_real_name';
992 }
993
994 $tables = array( 'revision', 'user' );
995
996 $fields = array(
997 'user_id' => 'rev_user',
998 'user_name' => 'rev_user_text',
999 $realNameField,
1000 'timestamp' => 'MAX(rev_timestamp)',
1001 );
1002
1003 $conds = array( 'rev_page' => $this->getId() );
1004
1005 // The user who made the top revision gets credited as "this page was last edited by
1006 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1007 $user = $this->getUser();
1008 if ( $user ) {
1009 $conds[] = "rev_user != $user";
1010 } else {
1011 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1012 }
1013
1014 // Username hidden?
1015 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1016
1017 $jconds = array(
1018 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1019 );
1020
1021 $options = array(
1022 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1023 'ORDER BY' => 'timestamp DESC',
1024 );
1025
1026 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1027 return new UserArrayFromResult( $res );
1028 }
1029
1030 /**
1031 * Get the last N authors
1032 * @param int $num Number of revisions to get
1033 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1034 * @return array Array of authors, duplicates not removed
1035 */
1036 public function getLastNAuthors( $num, $revLatest = 0 ) {
1037 // First try the slave
1038 // If that doesn't have the latest revision, try the master
1039 $continue = 2;
1040 $db = wfGetDB( DB_SLAVE );
1041
1042 do {
1043 $res = $db->select( array( 'page', 'revision' ),
1044 array( 'rev_id', 'rev_user_text' ),
1045 array(
1046 'page_namespace' => $this->mTitle->getNamespace(),
1047 'page_title' => $this->mTitle->getDBkey(),
1048 'rev_page = page_id'
1049 ), __METHOD__,
1050 array(
1051 'ORDER BY' => 'rev_timestamp DESC',
1052 'LIMIT' => $num
1053 )
1054 );
1055
1056 if ( !$res ) {
1057 return array();
1058 }
1059
1060 $row = $db->fetchObject( $res );
1061
1062 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1063 $db = wfGetDB( DB_MASTER );
1064 $continue--;
1065 } else {
1066 $continue = 0;
1067 }
1068 } while ( $continue );
1069
1070 $authors = array( $row->rev_user_text );
1071
1072 foreach ( $res as $row ) {
1073 $authors[] = $row->rev_user_text;
1074 }
1075
1076 return $authors;
1077 }
1078
1079 /**
1080 * Should the parser cache be used?
1081 *
1082 * @param ParserOptions $parserOptions ParserOptions to check
1083 * @param int $oldId
1084 * @return bool
1085 */
1086 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1087 return $parserOptions->getStubThreshold() == 0
1088 && $this->exists()
1089 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1090 && $this->getContentHandler()->isParserCacheSupported();
1091 }
1092
1093 /**
1094 * Get a ParserOutput for the given ParserOptions and revision ID.
1095 *
1096 * The parser cache will be used if possible. Cache misses that result
1097 * in parser runs are debounced with PoolCounter.
1098 *
1099 * @since 1.19
1100 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1101 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1102 * get the current revision (default value)
1103 *
1104 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1105 */
1106 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1107
1108 $useParserCache = $this->shouldCheckParserCache( $parserOptions, $oldid );
1109 wfDebug( __METHOD__ .
1110 ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1111 if ( $parserOptions->getStubThreshold() ) {
1112 wfIncrStats( 'pcache.miss.stub' );
1113 }
1114
1115 if ( $useParserCache ) {
1116 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1117 if ( $parserOutput !== false ) {
1118 return $parserOutput;
1119 }
1120 }
1121
1122 if ( $oldid === null || $oldid === 0 ) {
1123 $oldid = $this->getLatest();
1124 }
1125
1126 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1127 $pool->execute();
1128
1129 return $pool->getParserOutput();
1130 }
1131
1132 /**
1133 * Do standard deferred updates after page view (existing or missing page)
1134 * @param User $user The relevant user
1135 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1136 */
1137 public function doViewUpdates( User $user, $oldid = 0 ) {
1138 if ( wfReadOnly() ) {
1139 return;
1140 }
1141
1142 Hooks::run( 'PageViewUpdates', array( $this, $user ) );
1143 // Update newtalk / watchlist notification status
1144 try {
1145 $user->clearNotification( $this->mTitle, $oldid );
1146 } catch ( DBError $e ) {
1147 // Avoid outage if the master is not reachable
1148 MWExceptionHandler::logException( $e );
1149 }
1150 }
1151
1152 /**
1153 * Perform the actions of a page purging
1154 * @return bool
1155 */
1156 public function doPurge() {
1157 if ( !Hooks::run( 'ArticlePurge', array( &$this ) ) ) {
1158 return false;
1159 }
1160
1161 $title = $this->mTitle;
1162 wfGetDB( DB_MASTER )->onTransactionIdle( function() use ( $title ) {
1163 global $wgUseSquid;
1164 // Invalidate the cache in auto-commit mode
1165 $title->invalidateCache();
1166 if ( $wgUseSquid ) {
1167 // Send purge now that page_touched update was committed above
1168 $update = new SquidUpdate( $title->getSquidURLs() );
1169 $update->doUpdate();
1170 }
1171 } );
1172
1173 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1174 // @todo move this logic to MessageCache
1175 if ( $this->exists() ) {
1176 // NOTE: use transclusion text for messages.
1177 // This is consistent with MessageCache::getMsgFromNamespace()
1178
1179 $content = $this->getContent();
1180 $text = $content === null ? null : $content->getWikitextForTransclusion();
1181
1182 if ( $text === null ) {
1183 $text = false;
1184 }
1185 } else {
1186 $text = false;
1187 }
1188
1189 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1190 }
1191
1192 return true;
1193 }
1194 /**
1195 * Insert a new empty page record for this article.
1196 * This *must* be followed up by creating a revision
1197 * and running $this->updateRevisionOn( ... );
1198 * or else the record will be left in a funky state.
1199 * Best if all done inside a transaction.
1200 *
1201 * @param IDatabase $dbw
1202 * @return int|bool The newly created page_id key; false if the title already existed
1203 */
1204 public function insertOn( $dbw ) {
1205 $dbw->insert(
1206 'page',
1207 array(
1208 'page_id' => $dbw->nextSequenceValue( 'page_page_id_seq' ),
1209 'page_namespace' => $this->mTitle->getNamespace(),
1210 'page_title' => $this->mTitle->getDBkey(),
1211 'page_restrictions' => '',
1212 'page_is_redirect' => 0, // Will set this shortly...
1213 'page_is_new' => 1,
1214 'page_random' => wfRandom(),
1215 'page_touched' => $dbw->timestamp(),
1216 'page_latest' => 0, // Fill this in shortly...
1217 'page_len' => 0, // Fill this in shortly...
1218 ),
1219 __METHOD__,
1220 'IGNORE'
1221 );
1222
1223 if ( $dbw->affectedRows() > 0 ) {
1224 $newid = $dbw->insertId();
1225 $this->mId = $newid;
1226 $this->mTitle->resetArticleID( $newid );
1227
1228 return $newid;
1229 } else {
1230 return false; // nothing changed
1231 }
1232 }
1233
1234 /**
1235 * Update the page record to point to a newly saved revision.
1236 *
1237 * @param IDatabase $dbw
1238 * @param Revision $revision For ID number, and text used to set
1239 * length and redirect status fields
1240 * @param int $lastRevision If given, will not overwrite the page field
1241 * when different from the currently set value.
1242 * Giving 0 indicates the new page flag should be set on.
1243 * @param bool $lastRevIsRedirect If given, will optimize adding and
1244 * removing rows in redirect table.
1245 * @return bool Success; false if the page row was missing or page_latest changed
1246 */
1247 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1248 $lastRevIsRedirect = null
1249 ) {
1250 global $wgContentHandlerUseDB;
1251
1252 // Assertion to try to catch T92046
1253 if ( (int)$revision->getId() === 0 ) {
1254 throw new InvalidArgumentException(
1255 __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1256 );
1257 }
1258
1259 $content = $revision->getContent();
1260 $len = $content ? $content->getSize() : 0;
1261 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1262
1263 $conditions = array( 'page_id' => $this->getId() );
1264
1265 if ( !is_null( $lastRevision ) ) {
1266 // An extra check against threads stepping on each other
1267 $conditions['page_latest'] = $lastRevision;
1268 }
1269
1270 $row = array( /* SET */
1271 'page_latest' => $revision->getId(),
1272 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1273 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1274 'page_is_redirect' => $rt !== null ? 1 : 0,
1275 'page_len' => $len,
1276 );
1277
1278 if ( $wgContentHandlerUseDB ) {
1279 $row['page_content_model'] = $revision->getContentModel();
1280 }
1281
1282 $dbw->update( 'page',
1283 $row,
1284 $conditions,
1285 __METHOD__ );
1286
1287 $result = $dbw->affectedRows() > 0;
1288 if ( $result ) {
1289 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1290 $this->setLastEdit( $revision );
1291 $this->mLatest = $revision->getId();
1292 $this->mIsRedirect = (bool)$rt;
1293 // Update the LinkCache.
1294 LinkCache::singleton()->addGoodLinkObj(
1295 $this->getId(),
1296 $this->mTitle,
1297 $len,
1298 $this->mIsRedirect,
1299 $this->mLatest,
1300 $revision->getContentModel()
1301 );
1302 }
1303
1304 return $result;
1305 }
1306
1307 /**
1308 * Add row to the redirect table if this is a redirect, remove otherwise.
1309 *
1310 * @param IDatabase $dbw
1311 * @param Title $redirectTitle Title object pointing to the redirect target,
1312 * or NULL if this is not a redirect
1313 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1314 * removing rows in redirect table.
1315 * @return bool True on success, false on failure
1316 * @private
1317 */
1318 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1319 // Always update redirects (target link might have changed)
1320 // Update/Insert if we don't know if the last revision was a redirect or not
1321 // Delete if changing from redirect to non-redirect
1322 $isRedirect = !is_null( $redirectTitle );
1323
1324 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1325 return true;
1326 }
1327
1328 if ( $isRedirect ) {
1329 $this->insertRedirectEntry( $redirectTitle );
1330 } else {
1331 // This is not a redirect, remove row from redirect table
1332 $where = array( 'rd_from' => $this->getId() );
1333 $dbw->delete( 'redirect', $where, __METHOD__ );
1334 }
1335
1336 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1337 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1338 }
1339
1340 return ( $dbw->affectedRows() != 0 );
1341 }
1342
1343 /**
1344 * If the given revision is newer than the currently set page_latest,
1345 * update the page record. Otherwise, do nothing.
1346 *
1347 * @deprecated since 1.24, use updateRevisionOn instead
1348 *
1349 * @param IDatabase $dbw
1350 * @param Revision $revision
1351 * @return bool
1352 */
1353 public function updateIfNewerOn( $dbw, $revision ) {
1354
1355 $row = $dbw->selectRow(
1356 array( 'revision', 'page' ),
1357 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1358 array(
1359 'page_id' => $this->getId(),
1360 'page_latest=rev_id' ),
1361 __METHOD__ );
1362
1363 if ( $row ) {
1364 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1365 return false;
1366 }
1367 $prev = $row->rev_id;
1368 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1369 } else {
1370 // No or missing previous revision; mark the page as new
1371 $prev = 0;
1372 $lastRevIsRedirect = null;
1373 }
1374
1375 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1376
1377 return $ret;
1378 }
1379
1380 /**
1381 * Get the content that needs to be saved in order to undo all revisions
1382 * between $undo and $undoafter. Revisions must belong to the same page,
1383 * must exist and must not be deleted
1384 * @param Revision $undo
1385 * @param Revision $undoafter Must be an earlier revision than $undo
1386 * @return Content|bool Content on success, false on failure
1387 * @since 1.21
1388 * Before we had the Content object, this was done in getUndoText
1389 */
1390 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1391 $handler = $undo->getContentHandler();
1392 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1393 }
1394
1395 /**
1396 * Get the text that needs to be saved in order to undo all revisions
1397 * between $undo and $undoafter. Revisions must belong to the same page,
1398 * must exist and must not be deleted
1399 * @param Revision $undo
1400 * @param Revision $undoafter Must be an earlier revision than $undo
1401 * @return string|bool String on success, false on failure
1402 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1403 */
1404 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1405 ContentHandler::deprecated( __METHOD__, '1.21' );
1406
1407 $this->loadLastEdit();
1408
1409 if ( $this->mLastRevision ) {
1410 if ( is_null( $undoafter ) ) {
1411 $undoafter = $undo->getPrevious();
1412 }
1413
1414 $handler = $this->getContentHandler();
1415 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1416
1417 if ( !$undone ) {
1418 return false;
1419 } else {
1420 return ContentHandler::getContentText( $undone );
1421 }
1422 }
1423
1424 return false;
1425 }
1426
1427 /**
1428 * @param string|number|null|bool $sectionId Section identifier as a number or string
1429 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1430 * or 'new' for a new section.
1431 * @param string $text New text of the section.
1432 * @param string $sectionTitle New section's subject, only if $section is "new".
1433 * @param string $edittime Revision timestamp or null to use the current revision.
1434 *
1435 * @throws MWException
1436 * @return string|null New complete article text, or null if error.
1437 *
1438 * @deprecated since 1.21, use replaceSectionAtRev() instead
1439 */
1440 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1441 $edittime = null
1442 ) {
1443 ContentHandler::deprecated( __METHOD__, '1.21' );
1444
1445 // NOTE: keep condition in sync with condition in replaceSectionContent!
1446 if ( strval( $sectionId ) === '' ) {
1447 // Whole-page edit; let the whole text through
1448 return $text;
1449 }
1450
1451 if ( !$this->supportsSections() ) {
1452 throw new MWException( "sections not supported for content model " .
1453 $this->getContentHandler()->getModelID() );
1454 }
1455
1456 // could even make section title, but that's not required.
1457 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() );
1458
1459 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1460 $edittime );
1461
1462 return ContentHandler::getContentText( $newContent );
1463 }
1464
1465 /**
1466 * Returns true if this page's content model supports sections.
1467 *
1468 * @return bool
1469 *
1470 * @todo The skin should check this and not offer section functionality if
1471 * sections are not supported.
1472 * @todo The EditPage should check this and not offer section functionality
1473 * if sections are not supported.
1474 */
1475 public function supportsSections() {
1476 return $this->getContentHandler()->supportsSections();
1477 }
1478
1479 /**
1480 * @param string|number|null|bool $sectionId Section identifier as a number or string
1481 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1482 * or 'new' for a new section.
1483 * @param Content $sectionContent New content of the section.
1484 * @param string $sectionTitle New section's subject, only if $section is "new".
1485 * @param string $edittime Revision timestamp or null to use the current revision.
1486 *
1487 * @throws MWException
1488 * @return Content|null New complete article content, or null if error.
1489 *
1490 * @since 1.21
1491 * @deprecated since 1.24, use replaceSectionAtRev instead
1492 */
1493 public function replaceSectionContent(
1494 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1495 ) {
1496
1497 $baseRevId = null;
1498 if ( $edittime && $sectionId !== 'new' ) {
1499 $dbr = wfGetDB( DB_SLAVE );
1500 $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1501 // Try the master if this thread may have just added it.
1502 // This could be abstracted into a Revision method, but we don't want
1503 // to encourage loading of revisions by timestamp.
1504 if ( !$rev
1505 && wfGetLB()->getServerCount() > 1
1506 && wfGetLB()->hasOrMadeRecentMasterChanges()
1507 ) {
1508 $dbw = wfGetDB( DB_MASTER );
1509 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1510 }
1511 if ( $rev ) {
1512 $baseRevId = $rev->getId();
1513 }
1514 }
1515
1516 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1517 }
1518
1519 /**
1520 * @param string|number|null|bool $sectionId Section identifier as a number or string
1521 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1522 * or 'new' for a new section.
1523 * @param Content $sectionContent New content of the section.
1524 * @param string $sectionTitle New section's subject, only if $section is "new".
1525 * @param int|null $baseRevId
1526 *
1527 * @throws MWException
1528 * @return Content|null New complete article content, or null if error.
1529 *
1530 * @since 1.24
1531 */
1532 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1533 $sectionTitle = '', $baseRevId = null
1534 ) {
1535
1536 if ( strval( $sectionId ) === '' ) {
1537 // Whole-page edit; let the whole text through
1538 $newContent = $sectionContent;
1539 } else {
1540 if ( !$this->supportsSections() ) {
1541 throw new MWException( "sections not supported for content model " .
1542 $this->getContentHandler()->getModelID() );
1543 }
1544
1545 // Bug 30711: always use current version when adding a new section
1546 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1547 $oldContent = $this->getContent();
1548 } else {
1549 $rev = Revision::newFromId( $baseRevId );
1550 if ( !$rev ) {
1551 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1552 $this->getId() . "; section: $sectionId)\n" );
1553 return null;
1554 }
1555
1556 $oldContent = $rev->getContent();
1557 }
1558
1559 if ( !$oldContent ) {
1560 wfDebug( __METHOD__ . ": no page text\n" );
1561 return null;
1562 }
1563
1564 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1565 }
1566
1567 return $newContent;
1568 }
1569
1570 /**
1571 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1572 * @param int $flags
1573 * @return int Updated $flags
1574 */
1575 public function checkFlags( $flags ) {
1576 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1577 if ( $this->exists() ) {
1578 $flags |= EDIT_UPDATE;
1579 } else {
1580 $flags |= EDIT_NEW;
1581 }
1582 }
1583
1584 return $flags;
1585 }
1586
1587 /**
1588 * Change an existing article or create a new article. Updates RC and all necessary caches,
1589 * optionally via the deferred update array.
1590 *
1591 * @param string $text New text
1592 * @param string $summary Edit summary
1593 * @param int $flags Bitfield:
1594 * EDIT_NEW
1595 * Article is known or assumed to be non-existent, create a new one
1596 * EDIT_UPDATE
1597 * Article is known or assumed to be pre-existing, update it
1598 * EDIT_MINOR
1599 * Mark this edit minor, if the user is allowed to do so
1600 * EDIT_SUPPRESS_RC
1601 * Do not log the change in recentchanges
1602 * EDIT_FORCE_BOT
1603 * Mark the edit a "bot" edit regardless of user rights
1604 * EDIT_AUTOSUMMARY
1605 * Fill in blank summaries with generated text where possible
1606 *
1607 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1608 * article will be detected. If EDIT_UPDATE is specified and the article
1609 * doesn't exist, the function will return an edit-gone-missing error. If
1610 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1611 * error will be returned. These two conditions are also possible with
1612 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1613 *
1614 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1615 * This is not the parent revision ID, rather the revision ID for older
1616 * content used as the source for a rollback, for example.
1617 * @param User $user The user doing the edit
1618 *
1619 * @throws MWException
1620 * @return Status Possible errors:
1621 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1622 * set the fatal flag of $status
1623 * edit-gone-missing: In update mode, but the article didn't exist.
1624 * edit-conflict: In update mode, the article changed unexpectedly.
1625 * edit-no-change: Warning that the text was the same as before.
1626 * edit-already-exists: In creation mode, but the article already exists.
1627 *
1628 * Extensions may define additional errors.
1629 *
1630 * $return->value will contain an associative array with members as follows:
1631 * new: Boolean indicating if the function attempted to create a new article.
1632 * revision: The revision object for the inserted revision, or null.
1633 *
1634 * Compatibility note: this function previously returned a boolean value
1635 * indicating success/failure
1636 *
1637 * @deprecated since 1.21: use doEditContent() instead.
1638 */
1639 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1640 ContentHandler::deprecated( __METHOD__, '1.21' );
1641
1642 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1643
1644 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1645 }
1646
1647 /**
1648 * Change an existing article or create a new article. Updates RC and all necessary caches,
1649 * optionally via the deferred update array.
1650 *
1651 * @param Content $content New content
1652 * @param string $summary Edit summary
1653 * @param int $flags Bitfield:
1654 * EDIT_NEW
1655 * Article is known or assumed to be non-existent, create a new one
1656 * EDIT_UPDATE
1657 * Article is known or assumed to be pre-existing, update it
1658 * EDIT_MINOR
1659 * Mark this edit minor, if the user is allowed to do so
1660 * EDIT_SUPPRESS_RC
1661 * Do not log the change in recentchanges
1662 * EDIT_FORCE_BOT
1663 * Mark the edit a "bot" edit regardless of user rights
1664 * EDIT_AUTOSUMMARY
1665 * Fill in blank summaries with generated text where possible
1666 *
1667 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1668 * article will be detected. If EDIT_UPDATE is specified and the article
1669 * doesn't exist, the function will return an edit-gone-missing error. If
1670 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1671 * error will be returned. These two conditions are also possible with
1672 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1673 *
1674 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1675 * This is not the parent revision ID, rather the revision ID for older
1676 * content used as the source for a rollback, for example.
1677 * @param User $user The user doing the edit
1678 * @param string $serialFormat Format for storing the content in the
1679 * database.
1680 *
1681 * @throws MWException
1682 * @return Status Possible errors:
1683 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1684 * set the fatal flag of $status.
1685 * edit-gone-missing: In update mode, but the article didn't exist.
1686 * edit-conflict: In update mode, the article changed unexpectedly.
1687 * edit-no-change: Warning that the text was the same as before.
1688 * edit-already-exists: In creation mode, but the article already exists.
1689 *
1690 * Extensions may define additional errors.
1691 *
1692 * $return->value will contain an associative array with members as follows:
1693 * new: Boolean indicating if the function attempted to create a new article.
1694 * revision: The revision object for the inserted revision, or null.
1695 *
1696 * @since 1.21
1697 * @throws MWException
1698 */
1699 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
1700 User $user = null, $serialFormat = null
1701 ) {
1702 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1703
1704 // Low-level sanity check
1705 if ( $this->mTitle->getText() === '' ) {
1706 throw new MWException( 'Something is trying to edit an article with an empty title' );
1707 }
1708
1709 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1710 return Status::newFatal( 'content-not-allowed-here',
1711 ContentHandler::getLocalizedName( $content->getModel() ),
1712 $this->getTitle()->getPrefixedText() );
1713 }
1714
1715 $user = is_null( $user ) ? $wgUser : $user;
1716 $status = Status::newGood( array() );
1717
1718 // Load the data from the master database if needed.
1719 // The caller may already loaded it from the master or even loaded it using
1720 // SELECT FOR UPDATE, so do not override that using clear().
1721 $this->loadPageData( 'fromdbmaster' );
1722
1723 $flags = $this->checkFlags( $flags );
1724
1725 // handle hook
1726 $hook_args = array( &$this, &$user, &$content, &$summary,
1727 $flags & EDIT_MINOR, null, null, &$flags, &$status );
1728
1729 if ( !Hooks::run( 'PageContentSave', $hook_args )
1730 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1731
1732 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1733
1734 if ( $status->isOK() ) {
1735 $status->fatal( 'edit-hook-aborted' );
1736 }
1737
1738 return $status;
1739 }
1740
1741 // Silently ignore EDIT_MINOR if not allowed
1742 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1743 $bot = $flags & EDIT_FORCE_BOT;
1744
1745 $old_revision = $this->getRevision(); // current revision
1746 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1747
1748 $oldsize = $old_content ? $old_content->getSize() : 0;
1749 $oldid = $this->getLatest();
1750 $oldIsRedirect = $this->isRedirect();
1751 $oldcountable = $this->isCountable();
1752
1753 $handler = $content->getContentHandler();
1754
1755 // Provide autosummaries if one is not provided and autosummaries are enabled.
1756 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1757 if ( !$old_content ) {
1758 $old_content = null;
1759 }
1760 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1761 }
1762
1763 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1764 $serialized = $editInfo->pst;
1765
1766 /**
1767 * @var Content $content
1768 */
1769 $content = $editInfo->pstContent;
1770 $newsize = $content->getSize();
1771
1772 $dbw = wfGetDB( DB_MASTER );
1773 $now = wfTimestampNow();
1774
1775 if ( $flags & EDIT_UPDATE ) {
1776 // Update article, but only if changed.
1777 $status->value['new'] = false;
1778
1779 if ( !$oldid ) {
1780 // Article gone missing
1781 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1782 $status->fatal( 'edit-gone-missing' );
1783
1784 return $status;
1785 } elseif ( !$old_content ) {
1786 // Sanity check for bug 37225
1787 throw new MWException( "Could not find text for current revision {$oldid}." );
1788 }
1789
1790 $revision = new Revision( array(
1791 'page' => $this->getId(),
1792 'title' => $this->getTitle(), // for determining the default content model
1793 'comment' => $summary,
1794 'minor_edit' => $isminor,
1795 'text' => $serialized,
1796 'len' => $newsize,
1797 'parent_id' => $oldid,
1798 'user' => $user->getId(),
1799 'user_text' => $user->getName(),
1800 'timestamp' => $now,
1801 'content_model' => $content->getModel(),
1802 'content_format' => $serialFormat,
1803 ) ); // XXX: pass content object?!
1804
1805 $changed = !$content->equals( $old_content );
1806
1807 if ( $changed ) {
1808 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1809 $status->merge( $prepStatus );
1810
1811 if ( !$status->isOK() ) {
1812 return $status;
1813 }
1814
1815 $dbw->begin( __METHOD__ );
1816 // Get the latest page_latest value while locking it.
1817 // Do a CAS style check to see if it's the same as when this method
1818 // started. If it changed then bail out before touching the DB.
1819 $latestNow = $this->lockAndGetLatest();
1820 if ( $latestNow != $oldid ) {
1821 $dbw->commit( __METHOD__ );
1822 // Page updated or deleted in the mean time
1823 $status->fatal( 'edit-conflict' );
1824
1825 return $status;
1826 }
1827
1828 // At this point we are now comitted to returning an OK
1829 // status unless some DB query error or other exception comes up.
1830 // This way callers don't have to call rollback() if $status is bad
1831 // unless they actually try to catch exceptions (which is rare).
1832
1833 $revisionId = $revision->insertOn( $dbw );
1834
1835 // Update page_latest and friends to reflect the new revision
1836 if ( !$this->updateRevisionOn( $dbw, $revision, null, $oldIsRedirect ) ) {
1837 $dbw->rollback( __METHOD__ );
1838 throw new MWException( "Failed to update page row to use new revision." );
1839 }
1840
1841 Hooks::run( 'NewRevisionFromEditComplete',
1842 array( $this, $revision, $baseRevId, $user ) );
1843
1844 // Update recentchanges
1845 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1846 // Mark as patrolled if the user can do so
1847 $patrolled = $wgUseRCPatrol && !count(
1848 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1849 // Add RC row to the DB
1850 RecentChange::notifyEdit(
1851 $now, $this->mTitle, $isminor, $user, $summary,
1852 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1853 $revisionId, $patrolled
1854 );
1855 }
1856
1857 $user->incEditCount();
1858
1859 $dbw->commit( __METHOD__ );
1860 $this->mTimestamp = $now;
1861 } else {
1862 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1863 // related variables correctly
1864 $revision->setId( $this->getLatest() );
1865 }
1866
1867 // Update links tables, site stats, etc.
1868 $this->doEditUpdates(
1869 $revision,
1870 $user,
1871 array(
1872 'changed' => $changed,
1873 'oldcountable' => $oldcountable,
1874 'oldrevision' => $old_revision
1875 )
1876 );
1877
1878 if ( !$changed ) {
1879 $status->warning( 'edit-no-change' );
1880 $revision = null;
1881 // Update page_touched, this is usually implicit in the page update
1882 // Other cache updates are done in onArticleEdit()
1883 $this->mTitle->invalidateCache( $now );
1884 }
1885 } else {
1886 // Create new article
1887 $status->value['new'] = true;
1888
1889 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1890 $status->merge( $prepStatus );
1891 if ( !$status->isOK() ) {
1892 return $status;
1893 }
1894
1895 $dbw->begin( __METHOD__ );
1896
1897 // Add the page record unless one already exists for the title
1898 $newid = $this->insertOn( $dbw );
1899 if ( $newid === false ) {
1900 $dbw->commit( __METHOD__ ); // nothing inserted
1901 $status->fatal( 'edit-already-exists' );
1902
1903 return $status; // nothing done
1904 }
1905
1906 // At this point we are now comitted to returning an OK
1907 // status unless some DB query error or other exception comes up.
1908 // This way callers don't have to call rollback() if $status is bad
1909 // unless they actually try to catch exceptions (which is rare).
1910
1911 // Save the revision text...
1912 $revision = new Revision( array(
1913 'page' => $newid,
1914 'title' => $this->getTitle(), // for determining the default content model
1915 'comment' => $summary,
1916 'minor_edit' => $isminor,
1917 'text' => $serialized,
1918 'len' => $newsize,
1919 'user' => $user->getId(),
1920 'user_text' => $user->getName(),
1921 'timestamp' => $now,
1922 'content_model' => $content->getModel(),
1923 'content_format' => $serialFormat,
1924 ) );
1925 $revisionId = $revision->insertOn( $dbw );
1926
1927 // Bug 37225: use accessor to get the text as Revision may trim it
1928 $content = $revision->getContent(); // sanity; get normalized version
1929
1930 if ( $content ) {
1931 $newsize = $content->getSize();
1932 }
1933
1934 // Update the page record with revision data
1935 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1936 $dbw->rollback( __METHOD__ );
1937 throw new MWException( "Failed to update page row to use new revision." );
1938 }
1939
1940 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1941
1942 // Update recentchanges
1943 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1944 // Mark as patrolled if the user can do so
1945 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1946 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1947 // Add RC row to the DB
1948 RecentChange::notifyNew(
1949 $now, $this->mTitle, $isminor, $user, $summary, $bot,
1950 '', $newsize, $revisionId, $patrolled
1951 );
1952 }
1953
1954 $user->incEditCount();
1955
1956 $dbw->commit( __METHOD__ );
1957 $this->mTimestamp = $now;
1958
1959 // Update links, etc.
1960 $this->doEditUpdates(
1961 $revision,
1962 $user,
1963 array( 'created' => true, 'oldrevision' => $old_revision )
1964 );
1965
1966 $hook_args = array( &$this, &$user, $content, $summary,
1967 $flags & EDIT_MINOR, null, null, &$flags, $revision );
1968
1969 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1970 Hooks::run( 'PageContentInsertComplete', $hook_args );
1971 }
1972
1973 // Return the new revision (or null) to the caller
1974 $status->value['revision'] = $revision;
1975
1976 $hook_args = array( &$this, &$user, $content, $summary,
1977 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId );
1978
1979 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1980 Hooks::run( 'PageContentSaveComplete', $hook_args );
1981
1982 // Promote user to any groups they meet the criteria for
1983 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1984 $user->addAutopromoteOnceGroups( 'onEdit' );
1985 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1986 } );
1987
1988 return $status;
1989 }
1990
1991 /**
1992 * Get parser options suitable for rendering the primary article wikitext
1993 *
1994 * @see ContentHandler::makeParserOptions
1995 *
1996 * @param IContextSource|User|string $context One of the following:
1997 * - IContextSource: Use the User and the Language of the provided
1998 * context
1999 * - User: Use the provided User object and $wgLang for the language,
2000 * so use an IContextSource object if possible.
2001 * - 'canonical': Canonical options (anonymous user with default
2002 * preferences and content language).
2003 * @return ParserOptions
2004 */
2005 public function makeParserOptions( $context ) {
2006 $options = $this->getContentHandler()->makeParserOptions( $context );
2007
2008 if ( $this->getTitle()->isConversionTable() ) {
2009 // @todo ConversionTable should become a separate content model, so
2010 // we don't need special cases like this one.
2011 $options->disableContentConversion();
2012 }
2013
2014 return $options;
2015 }
2016
2017 /**
2018 * Prepare text which is about to be saved.
2019 * Returns a stdClass with source, pst and output members
2020 *
2021 * @param string $text
2022 * @param int|null $revid
2023 * @param User|null $user
2024 * @deprecated since 1.21: use prepareContentForEdit instead.
2025 * @return object
2026 */
2027 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2028 ContentHandler::deprecated( __METHOD__, '1.21' );
2029 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2030 return $this->prepareContentForEdit( $content, $revid, $user );
2031 }
2032
2033 /**
2034 * Prepare content which is about to be saved.
2035 * Returns a stdClass with source, pst and output members
2036 *
2037 * @param Content $content
2038 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2039 * revision ID is also accepted, but this is deprecated.
2040 * @param User|null $user
2041 * @param string|null $serialFormat
2042 * @param bool $useCache Check shared prepared edit cache
2043 *
2044 * @return object
2045 *
2046 * @since 1.21
2047 */
2048 public function prepareContentForEdit(
2049 Content $content, $revision = null, User $user = null,
2050 $serialFormat = null, $useCache = true
2051 ) {
2052 global $wgContLang, $wgUser, $wgAjaxEditStash;
2053
2054 if ( is_object( $revision ) ) {
2055 $revid = $revision->getId();
2056 } else {
2057 $revid = $revision;
2058 // This code path is deprecated, and nothing is known to
2059 // use it, so performance here shouldn't be a worry.
2060 if ( $revid !== null ) {
2061 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2062 } else {
2063 $revision = null;
2064 }
2065 }
2066
2067 $user = is_null( $user ) ? $wgUser : $user;
2068 // XXX: check $user->getId() here???
2069
2070 // Use a sane default for $serialFormat, see bug 57026
2071 if ( $serialFormat === null ) {
2072 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2073 }
2074
2075 if ( $this->mPreparedEdit
2076 && $this->mPreparedEdit->newContent
2077 && $this->mPreparedEdit->newContent->equals( $content )
2078 && $this->mPreparedEdit->revid == $revid
2079 && $this->mPreparedEdit->format == $serialFormat
2080 // XXX: also check $user here?
2081 ) {
2082 // Already prepared
2083 return $this->mPreparedEdit;
2084 }
2085
2086 // The edit may have already been prepared via api.php?action=stashedit
2087 $cachedEdit = $useCache && $wgAjaxEditStash
2088 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2089 : false;
2090
2091 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2092 Hooks::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2093
2094 $edit = (object)array();
2095 if ( $cachedEdit ) {
2096 $edit->timestamp = $cachedEdit->timestamp;
2097 } else {
2098 $edit->timestamp = wfTimestampNow();
2099 }
2100 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2101 $edit->revid = $revid;
2102
2103 if ( $cachedEdit ) {
2104 $edit->pstContent = $cachedEdit->pstContent;
2105 } else {
2106 $edit->pstContent = $content
2107 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2108 : null;
2109 }
2110
2111 $edit->format = $serialFormat;
2112 $edit->popts = $this->makeParserOptions( 'canonical' );
2113 if ( $cachedEdit ) {
2114 $edit->output = $cachedEdit->output;
2115 } else {
2116 if ( $revision ) {
2117 // We get here if vary-revision is set. This means that this page references
2118 // itself (such as via self-transclusion). In this case, we need to make sure
2119 // that any such self-references refer to the newly-saved revision, and not
2120 // to the previous one, which could otherwise happen due to slave lag.
2121 $oldCallback = $edit->popts->getCurrentRevisionCallback();
2122 $edit->popts->setCurrentRevisionCallback(
2123 function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2124 if ( $title->equals( $revision->getTitle() ) ) {
2125 return $revision;
2126 } else {
2127 return call_user_func( $oldCallback, $title, $parser );
2128 }
2129 }
2130 );
2131 }
2132 $edit->output = $edit->pstContent
2133 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2134 : null;
2135 }
2136
2137 $edit->newContent = $content;
2138 $edit->oldContent = $this->getContent( Revision::RAW );
2139
2140 // NOTE: B/C for hooks! don't use these fields!
2141 $edit->newText = $edit->newContent
2142 ? ContentHandler::getContentText( $edit->newContent )
2143 : '';
2144 $edit->oldText = $edit->oldContent
2145 ? ContentHandler::getContentText( $edit->oldContent )
2146 : '';
2147 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2148
2149 $this->mPreparedEdit = $edit;
2150 return $edit;
2151 }
2152
2153 /**
2154 * Do standard deferred updates after page edit.
2155 * Update links tables, site stats, search index and message cache.
2156 * Purges pages that include this page if the text was changed here.
2157 * Every 100th edit, prune the recent changes table.
2158 *
2159 * @param Revision $revision
2160 * @param User $user User object that did the revision
2161 * @param array $options Array of options, following indexes are used:
2162 * - changed: boolean, whether the revision changed the content (default true)
2163 * - created: boolean, whether the revision created the page (default false)
2164 * - moved: boolean, whether the page was moved (default false)
2165 * - restored: boolean, whether the page was undeleted (default false)
2166 * - oldrevision: Revision object for the pre-update revision (default null)
2167 * - oldcountable: boolean, null, or string 'no-change' (default null):
2168 * - boolean: whether the page was counted as an article before that
2169 * revision, only used in changed is true and created is false
2170 * - null: if created is false, don't update the article count; if created
2171 * is true, do update the article count
2172 * - 'no-change': don't update the article count, ever
2173 */
2174 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2175 global $wgRCWatchCategoryMembership;
2176
2177 $options += array(
2178 'changed' => true,
2179 'created' => false,
2180 'moved' => false,
2181 'restored' => false,
2182 'oldrevision' => null,
2183 'oldcountable' => null
2184 );
2185 $content = $revision->getContent();
2186
2187 // Parse the text
2188 // Be careful not to do pre-save transform twice: $text is usually
2189 // already pre-save transformed once.
2190 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2191 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2192 $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2193 } else {
2194 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2195 $editInfo = $this->mPreparedEdit;
2196 }
2197
2198 // Save it to the parser cache.
2199 // Make sure the cache time matches page_touched to avoid double parsing.
2200 ParserCache::singleton()->save(
2201 $editInfo->output, $this, $editInfo->popts,
2202 $revision->getTimestamp(), $editInfo->revid
2203 );
2204
2205 // Update the links tables and other secondary data
2206 if ( $content ) {
2207 $recursive = $options['changed']; // bug 50785
2208 $updates = $content->getSecondaryDataUpdates(
2209 $this->getTitle(), null, $recursive, $editInfo->output
2210 );
2211 foreach ( $updates as $update ) {
2212 if ( $update instanceof LinksUpdate ) {
2213 $update->setRevision( $revision );
2214 $update->setTriggeringUser( $user );
2215 }
2216 DeferredUpdates::addUpdate( $update );
2217 }
2218 if ( $wgRCWatchCategoryMembership
2219 && ( $options['changed'] || $options['created'] )
2220 && !$options['restored']
2221 ) {
2222 // Note: jobs are pushed after deferred updates, so the job should be able to see
2223 // the recent change entry (also done via deferred updates) and carry over any
2224 // bot/deletion/IP flags, ect.
2225 JobQueueGroup::singleton()->lazyPush( new CategoryMembershipChangeJob(
2226 $this->getTitle(),
2227 array(
2228 'pageId' => $this->getId(),
2229 'revTimestamp' => $revision->getTimestamp()
2230 )
2231 ) );
2232 }
2233 }
2234
2235 Hooks::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2236
2237 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2238 // Flush old entries from the `recentchanges` table
2239 if ( mt_rand( 0, 9 ) == 0 ) {
2240 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newPurgeJob() );
2241 }
2242 }
2243
2244 if ( !$this->exists() ) {
2245 return;
2246 }
2247
2248 $id = $this->getId();
2249 $title = $this->mTitle->getPrefixedDBkey();
2250 $shortTitle = $this->mTitle->getDBkey();
2251
2252 if ( $options['oldcountable'] === 'no-change' ||
2253 ( !$options['changed'] && !$options['moved'] )
2254 ) {
2255 $good = 0;
2256 } elseif ( $options['created'] ) {
2257 $good = (int)$this->isCountable( $editInfo );
2258 } elseif ( $options['oldcountable'] !== null ) {
2259 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2260 } else {
2261 $good = 0;
2262 }
2263 $edits = $options['changed'] ? 1 : 0;
2264 $total = $options['created'] ? 1 : 0;
2265
2266 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2267 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2268
2269 // If this is another user's talk page, update newtalk.
2270 // Don't do this if $options['changed'] = false (null-edits) nor if
2271 // it's a minor edit and the user doesn't want notifications for those.
2272 if ( $options['changed']
2273 && $this->mTitle->getNamespace() == NS_USER_TALK
2274 && $shortTitle != $user->getTitleKey()
2275 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2276 ) {
2277 $recipient = User::newFromName( $shortTitle, false );
2278 if ( !$recipient ) {
2279 wfDebug( __METHOD__ . ": invalid username\n" );
2280 } else {
2281 // Allow extensions to prevent user notification
2282 // when a new message is added to their talk page
2283 if ( Hooks::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2284 if ( User::isIP( $shortTitle ) ) {
2285 // An anonymous user
2286 $recipient->setNewtalk( true, $revision );
2287 } elseif ( $recipient->isLoggedIn() ) {
2288 $recipient->setNewtalk( true, $revision );
2289 } else {
2290 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2291 }
2292 }
2293 }
2294 }
2295
2296 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2297 // XXX: could skip pseudo-messages like js/css here, based on content model.
2298 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2299 if ( $msgtext === false || $msgtext === null ) {
2300 $msgtext = '';
2301 }
2302
2303 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2304 }
2305
2306 if ( $options['created'] ) {
2307 self::onArticleCreate( $this->mTitle );
2308 } elseif ( $options['changed'] ) { // bug 50785
2309 self::onArticleEdit( $this->mTitle, $revision );
2310 }
2311 }
2312
2313 /**
2314 * Edit an article without doing all that other stuff
2315 * The article must already exist; link tables etc
2316 * are not updated, caches are not flushed.
2317 *
2318 * @param Content $content Content submitted
2319 * @param User $user The relevant user
2320 * @param string $comment Comment submitted
2321 * @param bool $minor Whereas it's a minor modification
2322 * @param string $serialFormat Format for storing the content in the database
2323 */
2324 public function doQuickEditContent(
2325 Content $content, User $user, $comment = '', $minor = false, $serialFormat = null
2326 ) {
2327
2328 $serialized = $content->serialize( $serialFormat );
2329
2330 $dbw = wfGetDB( DB_MASTER );
2331 $revision = new Revision( array(
2332 'title' => $this->getTitle(), // for determining the default content model
2333 'page' => $this->getId(),
2334 'user_text' => $user->getName(),
2335 'user' => $user->getId(),
2336 'text' => $serialized,
2337 'length' => $content->getSize(),
2338 'comment' => $comment,
2339 'minor_edit' => $minor ? 1 : 0,
2340 ) ); // XXX: set the content object?
2341 $revision->insertOn( $dbw );
2342 $this->updateRevisionOn( $dbw, $revision );
2343
2344 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2345
2346 }
2347
2348 /**
2349 * Update the article's restriction field, and leave a log entry.
2350 * This works for protection both existing and non-existing pages.
2351 *
2352 * @param array $limit Set of restriction keys
2353 * @param array $expiry Per restriction type expiration
2354 * @param int &$cascade Set to false if cascading protection isn't allowed.
2355 * @param string $reason
2356 * @param User $user The user updating the restrictions
2357 * @return Status
2358 */
2359 public function doUpdateRestrictions( array $limit, array $expiry,
2360 &$cascade, $reason, User $user
2361 ) {
2362 global $wgCascadingRestrictionLevels, $wgContLang;
2363
2364 if ( wfReadOnly() ) {
2365 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2366 }
2367
2368 $this->loadPageData( 'fromdbmaster' );
2369 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2370 $id = $this->getId();
2371
2372 if ( !$cascade ) {
2373 $cascade = false;
2374 }
2375
2376 // Take this opportunity to purge out expired restrictions
2377 Title::purgeExpiredRestrictions();
2378
2379 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2380 // we expect a single selection, but the schema allows otherwise.
2381 $isProtected = false;
2382 $protect = false;
2383 $changed = false;
2384
2385 $dbw = wfGetDB( DB_MASTER );
2386
2387 foreach ( $restrictionTypes as $action ) {
2388 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2389 $expiry[$action] = 'infinity';
2390 }
2391 if ( !isset( $limit[$action] ) ) {
2392 $limit[$action] = '';
2393 } elseif ( $limit[$action] != '' ) {
2394 $protect = true;
2395 }
2396
2397 // Get current restrictions on $action
2398 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2399 if ( $current != '' ) {
2400 $isProtected = true;
2401 }
2402
2403 if ( $limit[$action] != $current ) {
2404 $changed = true;
2405 } elseif ( $limit[$action] != '' ) {
2406 // Only check expiry change if the action is actually being
2407 // protected, since expiry does nothing on an not-protected
2408 // action.
2409 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2410 $changed = true;
2411 }
2412 }
2413 }
2414
2415 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2416 $changed = true;
2417 }
2418
2419 // If nothing has changed, do nothing
2420 if ( !$changed ) {
2421 return Status::newGood();
2422 }
2423
2424 if ( !$protect ) { // No protection at all means unprotection
2425 $revCommentMsg = 'unprotectedarticle';
2426 $logAction = 'unprotect';
2427 } elseif ( $isProtected ) {
2428 $revCommentMsg = 'modifiedarticleprotection';
2429 $logAction = 'modify';
2430 } else {
2431 $revCommentMsg = 'protectedarticle';
2432 $logAction = 'protect';
2433 }
2434
2435 // Truncate for whole multibyte characters
2436 $reason = $wgContLang->truncate( $reason, 255 );
2437
2438 $logRelationsValues = array();
2439 $logRelationsField = null;
2440 $logParamsDetails = array();
2441
2442 if ( $id ) { // Protection of existing page
2443 if ( !Hooks::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2444 return Status::newGood();
2445 }
2446
2447 // Only certain restrictions can cascade...
2448 $editrestriction = isset( $limit['edit'] )
2449 ? array( $limit['edit'] )
2450 : $this->mTitle->getRestrictions( 'edit' );
2451 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2452 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2453 }
2454 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2455 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2456 }
2457
2458 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2459 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2460 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2461 }
2462 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2463 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2464 }
2465
2466 // The schema allows multiple restrictions
2467 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2468 $cascade = false;
2469 }
2470
2471 // insert null revision to identify the page protection change as edit summary
2472 $latest = $this->getLatest();
2473 $nullRevision = $this->insertProtectNullRevision(
2474 $revCommentMsg,
2475 $limit,
2476 $expiry,
2477 $cascade,
2478 $reason,
2479 $user
2480 );
2481
2482 if ( $nullRevision === null ) {
2483 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2484 }
2485
2486 $logRelationsField = 'pr_id';
2487
2488 // Update restrictions table
2489 foreach ( $limit as $action => $restrictions ) {
2490 $dbw->delete(
2491 'page_restrictions',
2492 array(
2493 'pr_page' => $id,
2494 'pr_type' => $action
2495 ),
2496 __METHOD__
2497 );
2498 if ( $restrictions != '' ) {
2499 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2500 $dbw->insert(
2501 'page_restrictions',
2502 array(
2503 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2504 'pr_page' => $id,
2505 'pr_type' => $action,
2506 'pr_level' => $restrictions,
2507 'pr_cascade' => $cascadeValue,
2508 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2509 ),
2510 __METHOD__
2511 );
2512 $logRelationsValues[] = $dbw->insertId();
2513 $logParamsDetails[] = array(
2514 'type' => $action,
2515 'level' => $restrictions,
2516 'expiry' => $expiry[$action],
2517 'cascade' => (bool)$cascadeValue,
2518 );
2519 }
2520 }
2521
2522 // Clear out legacy restriction fields
2523 $dbw->update(
2524 'page',
2525 array( 'page_restrictions' => '' ),
2526 array( 'page_id' => $id ),
2527 __METHOD__
2528 );
2529
2530 Hooks::run( 'NewRevisionFromEditComplete',
2531 array( $this, $nullRevision, $latest, $user ) );
2532 Hooks::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2533 } else { // Protection of non-existing page (also known as "title protection")
2534 // Cascade protection is meaningless in this case
2535 $cascade = false;
2536
2537 if ( $limit['create'] != '' ) {
2538 $dbw->replace( 'protected_titles',
2539 array( array( 'pt_namespace', 'pt_title' ) ),
2540 array(
2541 'pt_namespace' => $this->mTitle->getNamespace(),
2542 'pt_title' => $this->mTitle->getDBkey(),
2543 'pt_create_perm' => $limit['create'],
2544 'pt_timestamp' => $dbw->timestamp(),
2545 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2546 'pt_user' => $user->getId(),
2547 'pt_reason' => $reason,
2548 ), __METHOD__
2549 );
2550 $logParamsDetails[] = array(
2551 'type' => 'create',
2552 'level' => $limit['create'],
2553 'expiry' => $expiry['create'],
2554 );
2555 } else {
2556 $dbw->delete( 'protected_titles',
2557 array(
2558 'pt_namespace' => $this->mTitle->getNamespace(),
2559 'pt_title' => $this->mTitle->getDBkey()
2560 ), __METHOD__
2561 );
2562 }
2563 }
2564
2565 $this->mTitle->flushRestrictions();
2566 InfoAction::invalidateCache( $this->mTitle );
2567
2568 if ( $logAction == 'unprotect' ) {
2569 $params = array();
2570 } else {
2571 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2572 $params = array(
2573 '4::description' => $protectDescriptionLog, // parameter for IRC
2574 '5:bool:cascade' => $cascade,
2575 'details' => $logParamsDetails, // parameter for localize and api
2576 );
2577 }
2578
2579 // Update the protection log
2580 $logEntry = new ManualLogEntry( 'protect', $logAction );
2581 $logEntry->setTarget( $this->mTitle );
2582 $logEntry->setComment( $reason );
2583 $logEntry->setPerformer( $user );
2584 $logEntry->setParameters( $params );
2585 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2586 $logEntry->setRelations( array( $logRelationsField => $logRelationsValues ) );
2587 }
2588 $logId = $logEntry->insert();
2589 $logEntry->publish( $logId );
2590
2591 return Status::newGood();
2592 }
2593
2594 /**
2595 * Insert a new null revision for this page.
2596 *
2597 * @param string $revCommentMsg Comment message key for the revision
2598 * @param array $limit Set of restriction keys
2599 * @param array $expiry Per restriction type expiration
2600 * @param int $cascade Set to false if cascading protection isn't allowed.
2601 * @param string $reason
2602 * @param User|null $user
2603 * @return Revision|null Null on error
2604 */
2605 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2606 array $expiry, $cascade, $reason, $user = null
2607 ) {
2608 global $wgContLang;
2609 $dbw = wfGetDB( DB_MASTER );
2610
2611 // Prepare a null revision to be added to the history
2612 $editComment = $wgContLang->ucfirst(
2613 wfMessage(
2614 $revCommentMsg,
2615 $this->mTitle->getPrefixedText()
2616 )->inContentLanguage()->text()
2617 );
2618 if ( $reason ) {
2619 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2620 }
2621 $protectDescription = $this->protectDescription( $limit, $expiry );
2622 if ( $protectDescription ) {
2623 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2624 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2625 ->inContentLanguage()->text();
2626 }
2627 if ( $cascade ) {
2628 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2629 $editComment .= wfMessage( 'brackets' )->params(
2630 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2631 )->inContentLanguage()->text();
2632 }
2633
2634 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2635 if ( $nullRev ) {
2636 $nullRev->insertOn( $dbw );
2637
2638 // Update page record and touch page
2639 $oldLatest = $nullRev->getParentId();
2640 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2641 }
2642
2643 return $nullRev;
2644 }
2645
2646 /**
2647 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2648 * @return string
2649 */
2650 protected function formatExpiry( $expiry ) {
2651 global $wgContLang;
2652
2653 if ( $expiry != 'infinity' ) {
2654 return wfMessage(
2655 'protect-expiring',
2656 $wgContLang->timeanddate( $expiry, false, false ),
2657 $wgContLang->date( $expiry, false, false ),
2658 $wgContLang->time( $expiry, false, false )
2659 )->inContentLanguage()->text();
2660 } else {
2661 return wfMessage( 'protect-expiry-indefinite' )
2662 ->inContentLanguage()->text();
2663 }
2664 }
2665
2666 /**
2667 * Builds the description to serve as comment for the edit.
2668 *
2669 * @param array $limit Set of restriction keys
2670 * @param array $expiry Per restriction type expiration
2671 * @return string
2672 */
2673 public function protectDescription( array $limit, array $expiry ) {
2674 $protectDescription = '';
2675
2676 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2677 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2678 # All possible message keys are listed here for easier grepping:
2679 # * restriction-create
2680 # * restriction-edit
2681 # * restriction-move
2682 # * restriction-upload
2683 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2684 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2685 # with '' filtered out. All possible message keys are listed below:
2686 # * protect-level-autoconfirmed
2687 # * protect-level-sysop
2688 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2689 ->inContentLanguage()->text();
2690
2691 $expiryText = $this->formatExpiry( $expiry[$action] );
2692
2693 if ( $protectDescription !== '' ) {
2694 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2695 }
2696 $protectDescription .= wfMessage( 'protect-summary-desc' )
2697 ->params( $actionText, $restrictionsText, $expiryText )
2698 ->inContentLanguage()->text();
2699 }
2700
2701 return $protectDescription;
2702 }
2703
2704 /**
2705 * Builds the description to serve as comment for the log entry.
2706 *
2707 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2708 * protect description text. Keep them in old format to avoid breaking compatibility.
2709 * TODO: Fix protection log to store structured description and format it on-the-fly.
2710 *
2711 * @param array $limit Set of restriction keys
2712 * @param array $expiry Per restriction type expiration
2713 * @return string
2714 */
2715 public function protectDescriptionLog( array $limit, array $expiry ) {
2716 global $wgContLang;
2717
2718 $protectDescriptionLog = '';
2719
2720 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2721 $expiryText = $this->formatExpiry( $expiry[$action] );
2722 $protectDescriptionLog .= $wgContLang->getDirMark() .
2723 "[$action=$restrictions] ($expiryText)";
2724 }
2725
2726 return trim( $protectDescriptionLog );
2727 }
2728
2729 /**
2730 * Take an array of page restrictions and flatten it to a string
2731 * suitable for insertion into the page_restrictions field.
2732 *
2733 * @param string[] $limit
2734 *
2735 * @throws MWException
2736 * @return string
2737 */
2738 protected static function flattenRestrictions( $limit ) {
2739 if ( !is_array( $limit ) ) {
2740 throw new MWException( __METHOD__ . ' given non-array restriction set' );
2741 }
2742
2743 $bits = array();
2744 ksort( $limit );
2745
2746 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2747 $bits[] = "$action=$restrictions";
2748 }
2749
2750 return implode( ':', $bits );
2751 }
2752
2753 /**
2754 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2755 * backwards compatibility, if you care about error reporting you should use
2756 * doDeleteArticleReal() instead.
2757 *
2758 * Deletes the article with database consistency, writes logs, purges caches
2759 *
2760 * @param string $reason Delete reason for deletion log
2761 * @param bool $suppress Suppress all revisions and log the deletion in
2762 * the suppression log instead of the deletion log
2763 * @param int $u1 Unused
2764 * @param bool $u2 Unused
2765 * @param array|string &$error Array of errors to append to
2766 * @param User $user The deleting user
2767 * @return bool True if successful
2768 */
2769 public function doDeleteArticle(
2770 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2771 ) {
2772 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2773 return $status->isGood();
2774 }
2775
2776 /**
2777 * Back-end article deletion
2778 * Deletes the article with database consistency, writes logs, purges caches
2779 *
2780 * @since 1.19
2781 *
2782 * @param string $reason Delete reason for deletion log
2783 * @param bool $suppress Suppress all revisions and log the deletion in
2784 * the suppression log instead of the deletion log
2785 * @param int $u1 Unused
2786 * @param bool $u2 Unused
2787 * @param array|string &$error Array of errors to append to
2788 * @param User $user The deleting user
2789 * @return Status Status object; if successful, $status->value is the log_id of the
2790 * deletion log entry. If the page couldn't be deleted because it wasn't
2791 * found, $status is a non-fatal 'cannotdelete' error
2792 */
2793 public function doDeleteArticleReal(
2794 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2795 ) {
2796 global $wgUser, $wgContentHandlerUseDB;
2797
2798 wfDebug( __METHOD__ . "\n" );
2799
2800 $status = Status::newGood();
2801
2802 if ( $this->mTitle->getDBkey() === '' ) {
2803 $status->error( 'cannotdelete',
2804 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2805 return $status;
2806 }
2807
2808 $user = is_null( $user ) ? $wgUser : $user;
2809 if ( !Hooks::run( 'ArticleDelete',
2810 array( &$this, &$user, &$reason, &$error, &$status, $suppress )
2811 ) ) {
2812 if ( $status->isOK() ) {
2813 // Hook aborted but didn't set a fatal status
2814 $status->fatal( 'delete-hook-aborted' );
2815 }
2816 return $status;
2817 }
2818
2819 $dbw = wfGetDB( DB_MASTER );
2820 $dbw->startAtomic( __METHOD__ );
2821
2822 $this->loadPageData( self::READ_LATEST );
2823 $id = $this->getID();
2824 // T98706: lock the page from various other updates but avoid using
2825 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2826 // the revisions queries (which also JOIN on user). Only lock the page
2827 // row and CAS check on page_latest to see if the trx snapshot matches.
2828 $lockedLatest = $this->lockAndGetLatest();
2829 if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2830 $dbw->endAtomic( __METHOD__ );
2831 // Page not there or trx snapshot is stale
2832 $status->error( 'cannotdelete',
2833 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2834 return $status;
2835 }
2836
2837 // At this point we are now comitted to returning an OK
2838 // status unless some DB query error or other exception comes up.
2839 // This way callers don't have to call rollback() if $status is bad
2840 // unless they actually try to catch exceptions (which is rare).
2841
2842 // we need to remember the old content so we can use it to generate all deletion updates.
2843 $content = $this->getContent( Revision::RAW );
2844
2845 // Bitfields to further suppress the content
2846 if ( $suppress ) {
2847 $bitfield = 0;
2848 // This should be 15...
2849 $bitfield |= Revision::DELETED_TEXT;
2850 $bitfield |= Revision::DELETED_COMMENT;
2851 $bitfield |= Revision::DELETED_USER;
2852 $bitfield |= Revision::DELETED_RESTRICTED;
2853 } else {
2854 $bitfield = 'rev_deleted';
2855 }
2856
2857 /**
2858 * For now, shunt the revision data into the archive table.
2859 * Text is *not* removed from the text table; bulk storage
2860 * is left intact to avoid breaking block-compression or
2861 * immutable storage schemes.
2862 *
2863 * For backwards compatibility, note that some older archive
2864 * table entries will have ar_text and ar_flags fields still.
2865 *
2866 * In the future, we may keep revisions and mark them with
2867 * the rev_deleted field, which is reserved for this purpose.
2868 */
2869
2870 $row = array(
2871 'ar_namespace' => 'page_namespace',
2872 'ar_title' => 'page_title',
2873 'ar_comment' => 'rev_comment',
2874 'ar_user' => 'rev_user',
2875 'ar_user_text' => 'rev_user_text',
2876 'ar_timestamp' => 'rev_timestamp',
2877 'ar_minor_edit' => 'rev_minor_edit',
2878 'ar_rev_id' => 'rev_id',
2879 'ar_parent_id' => 'rev_parent_id',
2880 'ar_text_id' => 'rev_text_id',
2881 'ar_text' => '\'\'', // Be explicit to appease
2882 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2883 'ar_len' => 'rev_len',
2884 'ar_page_id' => 'page_id',
2885 'ar_deleted' => $bitfield,
2886 'ar_sha1' => 'rev_sha1',
2887 );
2888
2889 if ( $wgContentHandlerUseDB ) {
2890 $row['ar_content_model'] = 'rev_content_model';
2891 $row['ar_content_format'] = 'rev_content_format';
2892 }
2893
2894 // Copy all the page revisions into the archive table
2895 $dbw->insertSelect(
2896 'archive',
2897 array( 'page', 'revision' ),
2898 $row,
2899 array(
2900 'page_id' => $id,
2901 'page_id = rev_page'
2902 ),
2903 __METHOD__
2904 );
2905
2906 // Now that it's safely backed up, delete it
2907 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2908
2909 if ( !$dbw->cascadingDeletes() ) {
2910 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2911 }
2912
2913 // Clone the title, so we have the information we need when we log
2914 $logTitle = clone $this->mTitle;
2915
2916 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2917 $logtype = $suppress ? 'suppress' : 'delete';
2918
2919 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2920 $logEntry->setPerformer( $user );
2921 $logEntry->setTarget( $logTitle );
2922 $logEntry->setComment( $reason );
2923 $logid = $logEntry->insert();
2924
2925 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2926 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2927 $logEntry->publish( $logid );
2928 } );
2929
2930 $dbw->endAtomic( __METHOD__ );
2931
2932 $this->doDeleteUpdates( $id, $content );
2933
2934 Hooks::run( 'ArticleDeleteComplete',
2935 array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2936 $status->value = $logid;
2937
2938 // Show log excerpt on 404 pages rather than just a link
2939 $cache = ObjectCache::getMainStashInstance();
2940 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2941 $cache->set( $key, 1, $cache::TTL_DAY );
2942
2943 return $status;
2944 }
2945
2946 /**
2947 * Lock the page row for this title+id and return page_latest (or 0)
2948 *
2949 * @return integer Returns 0 if no row was found with this title+id
2950 * @since 1.27
2951 */
2952 public function lockAndGetLatest() {
2953 return (int)wfGetDB( DB_MASTER )->selectField(
2954 'page',
2955 'page_latest',
2956 array(
2957 'page_id' => $this->getId(),
2958 // Typically page_id is enough, but some code might try to do
2959 // updates assuming the title is the same, so verify that
2960 'page_namespace' => $this->getTitle()->getNamespace(),
2961 'page_title' => $this->getTitle()->getDBkey()
2962 ),
2963 __METHOD__,
2964 array( 'FOR UPDATE' )
2965 );
2966 }
2967
2968 /**
2969 * Do some database updates after deletion
2970 *
2971 * @param int $id The page_id value of the page being deleted
2972 * @param Content $content Optional page content to be used when determining
2973 * the required updates. This may be needed because $this->getContent()
2974 * may already return null when the page proper was deleted.
2975 */
2976 public function doDeleteUpdates( $id, Content $content = null ) {
2977 // Update site status
2978 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2979
2980 // Delete pagelinks, update secondary indexes, etc
2981 $updates = $this->getDeletionUpdates( $content );
2982 foreach ( $updates as $update ) {
2983 DeferredUpdates::addUpdate( $update );
2984 }
2985
2986 // Reparse any pages transcluding this page
2987 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2988
2989 // Reparse any pages including this image
2990 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2991 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2992 }
2993
2994 // Clear caches
2995 WikiPage::onArticleDelete( $this->mTitle );
2996
2997 // Reset this object and the Title object
2998 $this->loadFromRow( false, self::READ_LATEST );
2999
3000 // Search engine
3001 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
3002 }
3003
3004 /**
3005 * Roll back the most recent consecutive set of edits to a page
3006 * from the same user; fails if there are no eligible edits to
3007 * roll back to, e.g. user is the sole contributor. This function
3008 * performs permissions checks on $user, then calls commitRollback()
3009 * to do the dirty work
3010 *
3011 * @todo Separate the business/permission stuff out from backend code
3012 *
3013 * @param string $fromP Name of the user whose edits to rollback.
3014 * @param string $summary Custom summary. Set to default summary if empty.
3015 * @param string $token Rollback token.
3016 * @param bool $bot If true, mark all reverted edits as bot.
3017 *
3018 * @param array $resultDetails Array contains result-specific array of additional values
3019 * 'alreadyrolled' : 'current' (rev)
3020 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3021 *
3022 * @param User $user The user performing the rollback
3023 * @return array Array of errors, each error formatted as
3024 * array(messagekey, param1, param2, ...).
3025 * On success, the array is empty. This array can also be passed to
3026 * OutputPage::showPermissionsErrorPage().
3027 */
3028 public function doRollback(
3029 $fromP, $summary, $token, $bot, &$resultDetails, User $user
3030 ) {
3031 $resultDetails = null;
3032
3033 // Check permissions
3034 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3035 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3036 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3037
3038 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3039 $errors[] = array( 'sessionfailure' );
3040 }
3041
3042 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3043 $errors[] = array( 'actionthrottledtext' );
3044 }
3045
3046 // If there were errors, bail out now
3047 if ( !empty( $errors ) ) {
3048 return $errors;
3049 }
3050
3051 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
3052 }
3053
3054 /**
3055 * Backend implementation of doRollback(), please refer there for parameter
3056 * and return value documentation
3057 *
3058 * NOTE: This function does NOT check ANY permissions, it just commits the
3059 * rollback to the DB. Therefore, you should only call this function direct-
3060 * ly if you want to use custom permissions checks. If you don't, use
3061 * doRollback() instead.
3062 * @param string $fromP Name of the user whose edits to rollback.
3063 * @param string $summary Custom summary. Set to default summary if empty.
3064 * @param bool $bot If true, mark all reverted edits as bot.
3065 *
3066 * @param array $resultDetails Contains result-specific array of additional values
3067 * @param User $guser The user performing the rollback
3068 * @return array
3069 */
3070 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
3071 global $wgUseRCPatrol, $wgContLang;
3072
3073 $dbw = wfGetDB( DB_MASTER );
3074
3075 if ( wfReadOnly() ) {
3076 return array( array( 'readonlytext' ) );
3077 }
3078
3079 // Get the last editor
3080 $current = $this->getRevision();
3081 if ( is_null( $current ) ) {
3082 // Something wrong... no page?
3083 return array( array( 'notanarticle' ) );
3084 }
3085
3086 $from = str_replace( '_', ' ', $fromP );
3087 // User name given should match up with the top revision.
3088 // If the user was deleted then $from should be empty.
3089 if ( $from != $current->getUserText() ) {
3090 $resultDetails = array( 'current' => $current );
3091 return array( array( 'alreadyrolled',
3092 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3093 htmlspecialchars( $fromP ),
3094 htmlspecialchars( $current->getUserText() )
3095 ) );
3096 }
3097
3098 // Get the last edit not by this person...
3099 // Note: these may not be public values
3100 $user = intval( $current->getUser( Revision::RAW ) );
3101 $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3102 $s = $dbw->selectRow( 'revision',
3103 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3104 array( 'rev_page' => $current->getPage(),
3105 "rev_user != {$user} OR rev_user_text != {$user_text}"
3106 ), __METHOD__,
3107 array( 'USE INDEX' => 'page_timestamp',
3108 'ORDER BY' => 'rev_timestamp DESC' )
3109 );
3110 if ( $s === false ) {
3111 // No one else ever edited this page
3112 return array( array( 'cantrollback' ) );
3113 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3114 || $s->rev_deleted & Revision::DELETED_USER
3115 ) {
3116 // Only admins can see this text
3117 return array( array( 'notvisiblerev' ) );
3118 }
3119
3120 // Generate the edit summary if necessary
3121 $target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3122 if ( empty( $summary ) ) {
3123 if ( $from == '' ) { // no public user name
3124 $summary = wfMessage( 'revertpage-nouser' );
3125 } else {
3126 $summary = wfMessage( 'revertpage' );
3127 }
3128 }
3129
3130 // Allow the custom summary to use the same args as the default message
3131 $args = array(
3132 $target->getUserText(), $from, $s->rev_id,
3133 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3134 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3135 );
3136 if ( $summary instanceof Message ) {
3137 $summary = $summary->params( $args )->inContentLanguage()->text();
3138 } else {
3139 $summary = wfMsgReplaceArgs( $summary, $args );
3140 }
3141
3142 // Trim spaces on user supplied text
3143 $summary = trim( $summary );
3144
3145 // Truncate for whole multibyte characters.
3146 $summary = $wgContLang->truncate( $summary, 255 );
3147
3148 // Save
3149 $flags = EDIT_UPDATE;
3150
3151 if ( $guser->isAllowed( 'minoredit' ) ) {
3152 $flags |= EDIT_MINOR;
3153 }
3154
3155 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3156 $flags |= EDIT_FORCE_BOT;
3157 }
3158
3159 // Actually store the edit
3160 $status = $this->doEditContent(
3161 $target->getContent(),
3162 $summary,
3163 $flags,
3164 $target->getId(),
3165 $guser
3166 );
3167
3168 // Set patrolling and bot flag on the edits, which gets rollbacked.
3169 // This is done even on edit failure to have patrolling in that case (bug 62157).
3170 $set = array();
3171 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3172 // Mark all reverted edits as bot
3173 $set['rc_bot'] = 1;
3174 }
3175
3176 if ( $wgUseRCPatrol ) {
3177 // Mark all reverted edits as patrolled
3178 $set['rc_patrolled'] = 1;
3179 }
3180
3181 if ( count( $set ) ) {
3182 $dbw->update( 'recentchanges', $set,
3183 array( /* WHERE */
3184 'rc_cur_id' => $current->getPage(),
3185 'rc_user_text' => $current->getUserText(),
3186 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3187 ),
3188 __METHOD__
3189 );
3190 }
3191
3192 if ( !$status->isOK() ) {
3193 return $status->getErrorsArray();
3194 }
3195
3196 // raise error, when the edit is an edit without a new version
3197 $statusRev = isset( $status->value['revision'] )
3198 ? $status->value['revision']
3199 : null;
3200 if ( !( $statusRev instanceof Revision ) ) {
3201 $resultDetails = array( 'current' => $current );
3202 return array( array( 'alreadyrolled',
3203 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3204 htmlspecialchars( $fromP ),
3205 htmlspecialchars( $current->getUserText() )
3206 ) );
3207 }
3208
3209 $revId = $statusRev->getId();
3210
3211 Hooks::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3212
3213 $resultDetails = array(
3214 'summary' => $summary,
3215 'current' => $current,
3216 'target' => $target,
3217 'newid' => $revId
3218 );
3219
3220 return array();
3221 }
3222
3223 /**
3224 * The onArticle*() functions are supposed to be a kind of hooks
3225 * which should be called whenever any of the specified actions
3226 * are done.
3227 *
3228 * This is a good place to put code to clear caches, for instance.
3229 *
3230 * This is called on page move and undelete, as well as edit
3231 *
3232 * @param Title $title
3233 */
3234 public static function onArticleCreate( Title $title ) {
3235 // Update existence markers on article/talk tabs...
3236 $other = $title->getOtherPage();
3237
3238 $other->purgeSquid();
3239
3240 $title->touchLinks();
3241 $title->purgeSquid();
3242 $title->deleteTitleProtection();
3243 }
3244
3245 /**
3246 * Clears caches when article is deleted
3247 *
3248 * @param Title $title
3249 */
3250 public static function onArticleDelete( Title $title ) {
3251 // Update existence markers on article/talk tabs...
3252 $other = $title->getOtherPage();
3253
3254 $other->purgeSquid();
3255
3256 $title->touchLinks();
3257 $title->purgeSquid();
3258
3259 // File cache
3260 HTMLFileCache::clearFileCache( $title );
3261 InfoAction::invalidateCache( $title );
3262
3263 // Messages
3264 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3265 MessageCache::singleton()->replace( $title->getDBkey(), false );
3266 }
3267
3268 // Images
3269 if ( $title->getNamespace() == NS_FILE ) {
3270 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3271 }
3272
3273 // User talk pages
3274 if ( $title->getNamespace() == NS_USER_TALK ) {
3275 $user = User::newFromName( $title->getText(), false );
3276 if ( $user ) {
3277 $user->setNewtalk( false );
3278 }
3279 }
3280
3281 // Image redirects
3282 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3283 }
3284
3285 /**
3286 * Purge caches on page update etc
3287 *
3288 * @param Title $title
3289 * @param Revision|null $revision Revision that was just saved, may be null
3290 */
3291 public static function onArticleEdit( Title $title, Revision $revision = null ) {
3292 // Invalidate caches of articles which include this page
3293 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3294
3295 // Invalidate the caches of all pages which redirect here
3296 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3297
3298 // Purge squid for this page only
3299 $title->purgeSquid();
3300 // Clear file cache for this page only
3301 HTMLFileCache::clearFileCache( $title );
3302
3303 $revid = $revision ? $revision->getId() : null;
3304 DeferredUpdates::addCallableUpdate( function() use ( $title, $revid ) {
3305 InfoAction::invalidateCache( $title, $revid );
3306 } );
3307 }
3308
3309 /**#@-*/
3310
3311 /**
3312 * Returns a list of categories this page is a member of.
3313 * Results will include hidden categories
3314 *
3315 * @return TitleArray
3316 */
3317 public function getCategories() {
3318 $id = $this->getId();
3319 if ( $id == 0 ) {
3320 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3321 }
3322
3323 $dbr = wfGetDB( DB_SLAVE );
3324 $res = $dbr->select( 'categorylinks',
3325 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3326 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3327 // as not being aliases, and NS_CATEGORY is numeric
3328 array( 'cl_from' => $id ),
3329 __METHOD__ );
3330
3331 return TitleArray::newFromResult( $res );
3332 }
3333
3334 /**
3335 * Returns a list of hidden categories this page is a member of.
3336 * Uses the page_props and categorylinks tables.
3337 *
3338 * @return array Array of Title objects
3339 */
3340 public function getHiddenCategories() {
3341 $result = array();
3342 $id = $this->getId();
3343
3344 if ( $id == 0 ) {
3345 return array();
3346 }
3347
3348 $dbr = wfGetDB( DB_SLAVE );
3349 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3350 array( 'cl_to' ),
3351 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3352 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3353 __METHOD__ );
3354
3355 if ( $res !== false ) {
3356 foreach ( $res as $row ) {
3357 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3358 }
3359 }
3360
3361 return $result;
3362 }
3363
3364 /**
3365 * Return an applicable autosummary if one exists for the given edit.
3366 * @param string|null $oldtext The previous text of the page.
3367 * @param string|null $newtext The submitted text of the page.
3368 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3369 * @return string An appropriate autosummary, or an empty string.
3370 *
3371 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3372 */
3373 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3374 // NOTE: stub for backwards-compatibility. assumes the given text is
3375 // wikitext. will break horribly if it isn't.
3376
3377 ContentHandler::deprecated( __METHOD__, '1.21' );
3378
3379 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3380 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3381 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3382
3383 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3384 }
3385
3386 /**
3387 * Auto-generates a deletion reason
3388 *
3389 * @param bool &$hasHistory Whether the page has a history
3390 * @return string|bool String containing deletion reason or empty string, or boolean false
3391 * if no revision occurred
3392 */
3393 public function getAutoDeleteReason( &$hasHistory ) {
3394 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3395 }
3396
3397 /**
3398 * Update all the appropriate counts in the category table, given that
3399 * we've added the categories $added and deleted the categories $deleted.
3400 *
3401 * @param array $added The names of categories that were added
3402 * @param array $deleted The names of categories that were deleted
3403 */
3404 public function updateCategoryCounts( array $added, array $deleted ) {
3405 $that = $this;
3406 $method = __METHOD__;
3407 $dbw = wfGetDB( DB_MASTER );
3408
3409 // Do this at the end of the commit to reduce lock wait timeouts
3410 $dbw->onTransactionPreCommitOrIdle(
3411 function () use ( $dbw, $that, $method, $added, $deleted ) {
3412 $ns = $that->getTitle()->getNamespace();
3413
3414 $addFields = array( 'cat_pages = cat_pages + 1' );
3415 $removeFields = array( 'cat_pages = cat_pages - 1' );
3416 if ( $ns == NS_CATEGORY ) {
3417 $addFields[] = 'cat_subcats = cat_subcats + 1';
3418 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3419 } elseif ( $ns == NS_FILE ) {
3420 $addFields[] = 'cat_files = cat_files + 1';
3421 $removeFields[] = 'cat_files = cat_files - 1';
3422 }
3423
3424 if ( count( $added ) ) {
3425 $existingAdded = $dbw->selectFieldValues(
3426 'category',
3427 'cat_title',
3428 array( 'cat_title' => $added ),
3429 __METHOD__
3430 );
3431
3432 // For category rows that already exist, do a plain
3433 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3434 // to avoid creating gaps in the cat_id sequence.
3435 if ( count( $existingAdded ) ) {
3436 $dbw->update(
3437 'category',
3438 $addFields,
3439 array( 'cat_title' => $existingAdded ),
3440 __METHOD__
3441 );
3442 }
3443
3444 $missingAdded = array_diff( $added, $existingAdded );
3445 if ( count( $missingAdded ) ) {
3446 $insertRows = array();
3447 foreach ( $missingAdded as $cat ) {
3448 $insertRows[] = array(
3449 'cat_title' => $cat,
3450 'cat_pages' => 1,
3451 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3452 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3453 );
3454 }
3455 $dbw->upsert(
3456 'category',
3457 $insertRows,
3458 array( 'cat_title' ),
3459 $addFields,
3460 $method
3461 );
3462 }
3463 }
3464
3465 if ( count( $deleted ) ) {
3466 $dbw->update(
3467 'category',
3468 $removeFields,
3469 array( 'cat_title' => $deleted ),
3470 $method
3471 );
3472 }
3473
3474 foreach ( $added as $catName ) {
3475 $cat = Category::newFromName( $catName );
3476 Hooks::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3477 }
3478
3479 foreach ( $deleted as $catName ) {
3480 $cat = Category::newFromName( $catName );
3481 Hooks::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3482 }
3483 }
3484 );
3485 }
3486
3487 /**
3488 * Opportunistically enqueue link update jobs given fresh parser output if useful
3489 *
3490 * @param ParserOutput $parserOutput Current version page output
3491 * @since 1.25
3492 */
3493 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
3494 if ( wfReadOnly() ) {
3495 return;
3496 }
3497
3498 if ( !Hooks::run( 'OpportunisticLinksUpdate',
3499 array( $this, $this->mTitle, $parserOutput )
3500 ) ) {
3501 return;
3502 }
3503
3504 $params = array(
3505 'isOpportunistic' => true,
3506 'rootJobTimestamp' => $parserOutput->getCacheTime()
3507 );
3508
3509 if ( $this->mTitle->areRestrictionsCascading() ) {
3510 // If the page is cascade protecting, the links should really be up-to-date
3511 JobQueueGroup::singleton()->lazyPush(
3512 RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3513 );
3514 } elseif ( $parserOutput->hasDynamicContent() ) {
3515 // Assume the output contains "dynamic" time/random based magic words.
3516 // Only update pages that expired due to dynamic content and NOT due to edits
3517 // to referenced templates/files. When the cache expires due to dynamic content,
3518 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3519 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3520 // template/file edit already triggered recursive RefreshLinksJob jobs.
3521 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3522 // If a page is uncacheable, do not keep spamming a job for it.
3523 // Although it would be de-duplicated, it would still waste I/O.
3524 $cache = ObjectCache::getLocalClusterInstance();
3525 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3526 if ( $cache->add( $key, time(), 60 ) ) {
3527 JobQueueGroup::singleton()->lazyPush(
3528 RefreshLinksJob::newDynamic( $this->mTitle, $params )
3529 );
3530 }
3531 }
3532 }
3533 }
3534
3535 /**
3536 * Return a list of templates used by this article.
3537 * Uses the templatelinks table
3538 *
3539 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3540 * @return array Array of Title objects
3541 */
3542 public function getUsedTemplates() {
3543 return $this->mTitle->getTemplateLinksFrom();
3544 }
3545
3546 /**
3547 * This function is called right before saving the wikitext,
3548 * so we can do things like signatures and links-in-context.
3549 *
3550 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3551 * @param string $text Article contents
3552 * @param User $user User doing the edit
3553 * @param ParserOptions $popts Parser options, default options for
3554 * the user loaded if null given
3555 * @return string Article contents with altered wikitext markup (signatures
3556 * converted, {{subst:}}, templates, etc.)
3557 */
3558 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3559 global $wgParser, $wgUser;
3560
3561 wfDeprecated( __METHOD__, '1.19' );
3562
3563 $user = is_null( $user ) ? $wgUser : $user;
3564
3565 if ( $popts === null ) {
3566 $popts = ParserOptions::newFromUser( $user );
3567 }
3568
3569 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3570 }
3571
3572 /**
3573 * Update the article's restriction field, and leave a log entry.
3574 *
3575 * @deprecated since 1.19
3576 * @param array $limit Set of restriction keys
3577 * @param string $reason
3578 * @param int &$cascade Set to false if cascading protection isn't allowed.
3579 * @param array $expiry Per restriction type expiration
3580 * @param User $user The user updating the restrictions
3581 * @return bool True on success
3582 */
3583 public function updateRestrictions(
3584 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3585 ) {
3586 global $wgUser;
3587
3588 $user = is_null( $user ) ? $wgUser : $user;
3589
3590 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3591 }
3592
3593 /**
3594 * Returns a list of updates to be performed when this page is deleted. The
3595 * updates should remove any information about this page from secondary data
3596 * stores such as links tables.
3597 *
3598 * @param Content|null $content Optional Content object for determining the
3599 * necessary updates.
3600 * @return DataUpdate[]
3601 */
3602 public function getDeletionUpdates( Content $content = null ) {
3603 if ( !$content ) {
3604 // load content object, which may be used to determine the necessary updates.
3605 // XXX: the content may not be needed to determine the updates.
3606 $content = $this->getContent( Revision::RAW );
3607 }
3608
3609 if ( !$content ) {
3610 $updates = array();
3611 } else {
3612 $updates = $content->getDeletionUpdates( $this );
3613 }
3614
3615 Hooks::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3616 return $updates;
3617 }
3618 }