Update the WikiPage object with the new ID when undeleting
[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 );
886 return $this->mRedirectTarget;
887 }
888
889 // This page doesn't have an entry in the redirect table
890 $this->mRedirectTarget = $this->insertRedirect();
891 return $this->mRedirectTarget;
892 }
893
894 /**
895 * Insert an entry for this page into the redirect table if the content is a redirect
896 *
897 * The database update will be deferred via DeferredUpdates
898 *
899 * Don't call this function directly unless you know what you're doing.
900 * @return Title|null Title object or null if not a redirect
901 */
902 public function insertRedirect() {
903 $content = $this->getContent();
904 $retval = $content ? $content->getUltimateRedirectTarget() : null;
905 if ( !$retval ) {
906 return null;
907 }
908
909 // Update the DB post-send if the page has not cached since now
910 $that = $this;
911 $latest = $this->getLatest();
912 DeferredUpdates::addCallableUpdate( function() use ( $that, $retval, $latest ) {
913 $that->insertRedirectEntry( $retval, $latest );
914 } );
915
916 return $retval;
917 }
918
919 /**
920 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
921 * @param Title $rt Redirect target
922 * @param int|null $oldLatest Prior page_latest for check and set
923 */
924 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
925 $dbw = wfGetDB( DB_MASTER );
926 $dbw->startAtomic( __METHOD__ );
927
928 if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
929 $dbw->replace( 'redirect',
930 array( 'rd_from' ),
931 array(
932 'rd_from' => $this->getId(),
933 'rd_namespace' => $rt->getNamespace(),
934 'rd_title' => $rt->getDBkey(),
935 'rd_fragment' => $rt->getFragment(),
936 'rd_interwiki' => $rt->getInterwiki(),
937 ),
938 __METHOD__
939 );
940 }
941
942 $dbw->endAtomic( __METHOD__ );
943 }
944
945 /**
946 * Get the Title object or URL this page redirects to
947 *
948 * @return bool|Title|string False, Title of in-wiki target, or string with URL
949 */
950 public function followRedirect() {
951 return $this->getRedirectURL( $this->getRedirectTarget() );
952 }
953
954 /**
955 * Get the Title object or URL to use for a redirect. We use Title
956 * objects for same-wiki, non-special redirects and URLs for everything
957 * else.
958 * @param Title $rt Redirect target
959 * @return bool|Title|string False, Title object of local target, or string with URL
960 */
961 public function getRedirectURL( $rt ) {
962 if ( !$rt ) {
963 return false;
964 }
965
966 if ( $rt->isExternal() ) {
967 if ( $rt->isLocal() ) {
968 // Offsite wikis need an HTTP redirect.
969 // This can be hard to reverse and may produce loops,
970 // so they may be disabled in the site configuration.
971 $source = $this->mTitle->getFullURL( 'redirect=no' );
972 return $rt->getFullURL( array( 'rdfrom' => $source ) );
973 } else {
974 // External pages without "local" bit set are not valid
975 // redirect targets
976 return false;
977 }
978 }
979
980 if ( $rt->isSpecialPage() ) {
981 // Gotta handle redirects to special pages differently:
982 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
983 // Some pages are not valid targets.
984 if ( $rt->isValidRedirectTarget() ) {
985 return $rt->getFullURL();
986 } else {
987 return false;
988 }
989 }
990
991 return $rt;
992 }
993
994 /**
995 * Get a list of users who have edited this article, not including the user who made
996 * the most recent revision, which you can get from $article->getUser() if you want it
997 * @return UserArrayFromResult
998 */
999 public function getContributors() {
1000 // @todo FIXME: This is expensive; cache this info somewhere.
1001
1002 $dbr = wfGetDB( DB_SLAVE );
1003
1004 if ( $dbr->implicitGroupby() ) {
1005 $realNameField = 'user_real_name';
1006 } else {
1007 $realNameField = 'MIN(user_real_name) AS user_real_name';
1008 }
1009
1010 $tables = array( 'revision', 'user' );
1011
1012 $fields = array(
1013 'user_id' => 'rev_user',
1014 'user_name' => 'rev_user_text',
1015 $realNameField,
1016 'timestamp' => 'MAX(rev_timestamp)',
1017 );
1018
1019 $conds = array( 'rev_page' => $this->getId() );
1020
1021 // The user who made the top revision gets credited as "this page was last edited by
1022 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1023 $user = $this->getUser();
1024 if ( $user ) {
1025 $conds[] = "rev_user != $user";
1026 } else {
1027 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1028 }
1029
1030 // Username hidden?
1031 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1032
1033 $jconds = array(
1034 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1035 );
1036
1037 $options = array(
1038 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1039 'ORDER BY' => 'timestamp DESC',
1040 );
1041
1042 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1043 return new UserArrayFromResult( $res );
1044 }
1045
1046 /**
1047 * Should the parser cache be used?
1048 *
1049 * @param ParserOptions $parserOptions ParserOptions to check
1050 * @param int $oldId
1051 * @return bool
1052 */
1053 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1054 return $parserOptions->getStubThreshold() == 0
1055 && $this->exists()
1056 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1057 && $this->getContentHandler()->isParserCacheSupported();
1058 }
1059
1060 /**
1061 * Get a ParserOutput for the given ParserOptions and revision ID.
1062 *
1063 * The parser cache will be used if possible. Cache misses that result
1064 * in parser runs are debounced with PoolCounter.
1065 *
1066 * @since 1.19
1067 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1068 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1069 * get the current revision (default value)
1070 *
1071 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1072 */
1073 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1074
1075 $useParserCache = $this->shouldCheckParserCache( $parserOptions, $oldid );
1076 wfDebug( __METHOD__ .
1077 ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1078 if ( $parserOptions->getStubThreshold() ) {
1079 wfIncrStats( 'pcache.miss.stub' );
1080 }
1081
1082 if ( $useParserCache ) {
1083 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1084 if ( $parserOutput !== false ) {
1085 return $parserOutput;
1086 }
1087 }
1088
1089 if ( $oldid === null || $oldid === 0 ) {
1090 $oldid = $this->getLatest();
1091 }
1092
1093 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1094 $pool->execute();
1095
1096 return $pool->getParserOutput();
1097 }
1098
1099 /**
1100 * Do standard deferred updates after page view (existing or missing page)
1101 * @param User $user The relevant user
1102 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1103 */
1104 public function doViewUpdates( User $user, $oldid = 0 ) {
1105 if ( wfReadOnly() ) {
1106 return;
1107 }
1108
1109 Hooks::run( 'PageViewUpdates', array( $this, $user ) );
1110 // Update newtalk / watchlist notification status
1111 try {
1112 $user->clearNotification( $this->mTitle, $oldid );
1113 } catch ( DBError $e ) {
1114 // Avoid outage if the master is not reachable
1115 MWExceptionHandler::logException( $e );
1116 }
1117 }
1118
1119 /**
1120 * Perform the actions of a page purging
1121 * @return bool
1122 */
1123 public function doPurge() {
1124 if ( !Hooks::run( 'ArticlePurge', array( &$this ) ) ) {
1125 return false;
1126 }
1127
1128 $title = $this->mTitle;
1129 wfGetDB( DB_MASTER )->onTransactionIdle( function() use ( $title ) {
1130 // Invalidate the cache in auto-commit mode
1131 $title->invalidateCache();
1132 } );
1133
1134 // Send purge after above page_touched update was committed
1135 DeferredUpdates::addUpdate(
1136 new CdnCacheUpdate( $title->getCdnUrls() ),
1137 DeferredUpdates::PRESEND
1138 );
1139
1140 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1141 // @todo move this logic to MessageCache
1142 if ( $this->exists() ) {
1143 // NOTE: use transclusion text for messages.
1144 // This is consistent with MessageCache::getMsgFromNamespace()
1145
1146 $content = $this->getContent();
1147 $text = $content === null ? null : $content->getWikitextForTransclusion();
1148
1149 if ( $text === null ) {
1150 $text = false;
1151 }
1152 } else {
1153 $text = false;
1154 }
1155
1156 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1157 }
1158
1159 return true;
1160 }
1161
1162 /**
1163 * Insert a new empty page record for this article.
1164 * This *must* be followed up by creating a revision
1165 * and running $this->updateRevisionOn( ... );
1166 * or else the record will be left in a funky state.
1167 * Best if all done inside a transaction.
1168 *
1169 * @param IDatabase $dbw
1170 * @param int|null $pageId Custom page ID that will be used for the insert statement
1171 *
1172 * @return bool|int The newly created page_id key; false if the title already existed
1173 */
1174 public function insertOn( $dbw, $pageId = null ) {
1175 $pageIdForInsert = $pageId ?: $dbw->nextSequenceValue( 'page_page_id_seq' );
1176 $dbw->insert(
1177 'page',
1178 array(
1179 'page_id' => $pageIdForInsert,
1180 'page_namespace' => $this->mTitle->getNamespace(),
1181 'page_title' => $this->mTitle->getDBkey(),
1182 'page_restrictions' => '',
1183 'page_is_redirect' => 0, // Will set this shortly...
1184 'page_is_new' => 1,
1185 'page_random' => wfRandom(),
1186 'page_touched' => $dbw->timestamp(),
1187 'page_latest' => 0, // Fill this in shortly...
1188 'page_len' => 0, // Fill this in shortly...
1189 ),
1190 __METHOD__,
1191 'IGNORE'
1192 );
1193
1194 if ( $dbw->affectedRows() > 0 ) {
1195 $newid = $pageId ?: $dbw->insertId();
1196 $this->mId = $newid;
1197 $this->mTitle->resetArticleID( $newid );
1198
1199 return $newid;
1200 } else {
1201 return false; // nothing changed
1202 }
1203 }
1204
1205 /**
1206 * Update the page record to point to a newly saved revision.
1207 *
1208 * @param IDatabase $dbw
1209 * @param Revision $revision For ID number, and text used to set
1210 * length and redirect status fields
1211 * @param int $lastRevision If given, will not overwrite the page field
1212 * when different from the currently set value.
1213 * Giving 0 indicates the new page flag should be set on.
1214 * @param bool $lastRevIsRedirect If given, will optimize adding and
1215 * removing rows in redirect table.
1216 * @return bool Success; false if the page row was missing or page_latest changed
1217 */
1218 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1219 $lastRevIsRedirect = null
1220 ) {
1221 global $wgContentHandlerUseDB;
1222
1223 // Assertion to try to catch T92046
1224 if ( (int)$revision->getId() === 0 ) {
1225 throw new InvalidArgumentException(
1226 __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1227 );
1228 }
1229
1230 $content = $revision->getContent();
1231 $len = $content ? $content->getSize() : 0;
1232 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1233
1234 $conditions = array( 'page_id' => $this->getId() );
1235
1236 if ( !is_null( $lastRevision ) ) {
1237 // An extra check against threads stepping on each other
1238 $conditions['page_latest'] = $lastRevision;
1239 }
1240
1241 $row = array( /* SET */
1242 'page_latest' => $revision->getId(),
1243 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1244 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1245 'page_is_redirect' => $rt !== null ? 1 : 0,
1246 'page_len' => $len,
1247 );
1248
1249 if ( $wgContentHandlerUseDB ) {
1250 $row['page_content_model'] = $revision->getContentModel();
1251 }
1252
1253 $dbw->update( 'page',
1254 $row,
1255 $conditions,
1256 __METHOD__ );
1257
1258 $result = $dbw->affectedRows() > 0;
1259 if ( $result ) {
1260 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1261 $this->setLastEdit( $revision );
1262 $this->mLatest = $revision->getId();
1263 $this->mIsRedirect = (bool)$rt;
1264 // Update the LinkCache.
1265 LinkCache::singleton()->addGoodLinkObj(
1266 $this->getId(),
1267 $this->mTitle,
1268 $len,
1269 $this->mIsRedirect,
1270 $this->mLatest,
1271 $revision->getContentModel()
1272 );
1273 }
1274
1275 return $result;
1276 }
1277
1278 /**
1279 * Add row to the redirect table if this is a redirect, remove otherwise.
1280 *
1281 * @param IDatabase $dbw
1282 * @param Title $redirectTitle Title object pointing to the redirect target,
1283 * or NULL if this is not a redirect
1284 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1285 * removing rows in redirect table.
1286 * @return bool True on success, false on failure
1287 * @private
1288 */
1289 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1290 // Always update redirects (target link might have changed)
1291 // Update/Insert if we don't know if the last revision was a redirect or not
1292 // Delete if changing from redirect to non-redirect
1293 $isRedirect = !is_null( $redirectTitle );
1294
1295 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1296 return true;
1297 }
1298
1299 if ( $isRedirect ) {
1300 $this->insertRedirectEntry( $redirectTitle );
1301 } else {
1302 // This is not a redirect, remove row from redirect table
1303 $where = array( 'rd_from' => $this->getId() );
1304 $dbw->delete( 'redirect', $where, __METHOD__ );
1305 }
1306
1307 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1308 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1309 }
1310
1311 return ( $dbw->affectedRows() != 0 );
1312 }
1313
1314 /**
1315 * If the given revision is newer than the currently set page_latest,
1316 * update the page record. Otherwise, do nothing.
1317 *
1318 * @deprecated since 1.24, use updateRevisionOn instead
1319 *
1320 * @param IDatabase $dbw
1321 * @param Revision $revision
1322 * @return bool
1323 */
1324 public function updateIfNewerOn( $dbw, $revision ) {
1325
1326 $row = $dbw->selectRow(
1327 array( 'revision', 'page' ),
1328 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1329 array(
1330 'page_id' => $this->getId(),
1331 'page_latest=rev_id' ),
1332 __METHOD__ );
1333
1334 if ( $row ) {
1335 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1336 return false;
1337 }
1338 $prev = $row->rev_id;
1339 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1340 } else {
1341 // No or missing previous revision; mark the page as new
1342 $prev = 0;
1343 $lastRevIsRedirect = null;
1344 }
1345
1346 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1347
1348 return $ret;
1349 }
1350
1351 /**
1352 * Get the content that needs to be saved in order to undo all revisions
1353 * between $undo and $undoafter. Revisions must belong to the same page,
1354 * must exist and must not be deleted
1355 * @param Revision $undo
1356 * @param Revision $undoafter Must be an earlier revision than $undo
1357 * @return Content|bool Content on success, false on failure
1358 * @since 1.21
1359 * Before we had the Content object, this was done in getUndoText
1360 */
1361 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1362 $handler = $undo->getContentHandler();
1363 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1364 }
1365
1366 /**
1367 * Get the text that needs to be saved in order to undo all revisions
1368 * between $undo and $undoafter. Revisions must belong to the same page,
1369 * must exist and must not be deleted
1370 * @param Revision $undo
1371 * @param Revision $undoafter Must be an earlier revision than $undo
1372 * @return string|bool String on success, false on failure
1373 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1374 */
1375 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1376 ContentHandler::deprecated( __METHOD__, '1.21' );
1377
1378 $this->loadLastEdit();
1379
1380 if ( $this->mLastRevision ) {
1381 if ( is_null( $undoafter ) ) {
1382 $undoafter = $undo->getPrevious();
1383 }
1384
1385 $handler = $this->getContentHandler();
1386 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1387
1388 if ( !$undone ) {
1389 return false;
1390 } else {
1391 return ContentHandler::getContentText( $undone );
1392 }
1393 }
1394
1395 return false;
1396 }
1397
1398 /**
1399 * @param string|number|null|bool $sectionId Section identifier as a number or string
1400 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1401 * or 'new' for a new section.
1402 * @param string $text New text of the section.
1403 * @param string $sectionTitle New section's subject, only if $section is "new".
1404 * @param string $edittime Revision timestamp or null to use the current revision.
1405 *
1406 * @throws MWException
1407 * @return string|null New complete article text, or null if error.
1408 *
1409 * @deprecated since 1.21, use replaceSectionAtRev() instead
1410 */
1411 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1412 $edittime = null
1413 ) {
1414 ContentHandler::deprecated( __METHOD__, '1.21' );
1415
1416 // NOTE: keep condition in sync with condition in replaceSectionContent!
1417 if ( strval( $sectionId ) === '' ) {
1418 // Whole-page edit; let the whole text through
1419 return $text;
1420 }
1421
1422 if ( !$this->supportsSections() ) {
1423 throw new MWException( "sections not supported for content model " .
1424 $this->getContentHandler()->getModelID() );
1425 }
1426
1427 // could even make section title, but that's not required.
1428 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() );
1429
1430 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1431 $edittime );
1432
1433 return ContentHandler::getContentText( $newContent );
1434 }
1435
1436 /**
1437 * Returns true if this page's content model supports sections.
1438 *
1439 * @return bool
1440 *
1441 * @todo The skin should check this and not offer section functionality if
1442 * sections are not supported.
1443 * @todo The EditPage should check this and not offer section functionality
1444 * if sections are not supported.
1445 */
1446 public function supportsSections() {
1447 return $this->getContentHandler()->supportsSections();
1448 }
1449
1450 /**
1451 * @param string|number|null|bool $sectionId Section identifier as a number or string
1452 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1453 * or 'new' for a new section.
1454 * @param Content $sectionContent New content of the section.
1455 * @param string $sectionTitle New section's subject, only if $section is "new".
1456 * @param string $edittime Revision timestamp or null to use the current revision.
1457 *
1458 * @throws MWException
1459 * @return Content|null New complete article content, or null if error.
1460 *
1461 * @since 1.21
1462 * @deprecated since 1.24, use replaceSectionAtRev instead
1463 */
1464 public function replaceSectionContent(
1465 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1466 ) {
1467
1468 $baseRevId = null;
1469 if ( $edittime && $sectionId !== 'new' ) {
1470 $dbr = wfGetDB( DB_SLAVE );
1471 $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1472 // Try the master if this thread may have just added it.
1473 // This could be abstracted into a Revision method, but we don't want
1474 // to encourage loading of revisions by timestamp.
1475 if ( !$rev
1476 && wfGetLB()->getServerCount() > 1
1477 && wfGetLB()->hasOrMadeRecentMasterChanges()
1478 ) {
1479 $dbw = wfGetDB( DB_MASTER );
1480 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1481 }
1482 if ( $rev ) {
1483 $baseRevId = $rev->getId();
1484 }
1485 }
1486
1487 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1488 }
1489
1490 /**
1491 * @param string|number|null|bool $sectionId Section identifier as a number or string
1492 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1493 * or 'new' for a new section.
1494 * @param Content $sectionContent New content of the section.
1495 * @param string $sectionTitle New section's subject, only if $section is "new".
1496 * @param int|null $baseRevId
1497 *
1498 * @throws MWException
1499 * @return Content|null New complete article content, or null if error.
1500 *
1501 * @since 1.24
1502 */
1503 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1504 $sectionTitle = '', $baseRevId = null
1505 ) {
1506
1507 if ( strval( $sectionId ) === '' ) {
1508 // Whole-page edit; let the whole text through
1509 $newContent = $sectionContent;
1510 } else {
1511 if ( !$this->supportsSections() ) {
1512 throw new MWException( "sections not supported for content model " .
1513 $this->getContentHandler()->getModelID() );
1514 }
1515
1516 // Bug 30711: always use current version when adding a new section
1517 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1518 $oldContent = $this->getContent();
1519 } else {
1520 $rev = Revision::newFromId( $baseRevId );
1521 if ( !$rev ) {
1522 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1523 $this->getId() . "; section: $sectionId)\n" );
1524 return null;
1525 }
1526
1527 $oldContent = $rev->getContent();
1528 }
1529
1530 if ( !$oldContent ) {
1531 wfDebug( __METHOD__ . ": no page text\n" );
1532 return null;
1533 }
1534
1535 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1536 }
1537
1538 return $newContent;
1539 }
1540
1541 /**
1542 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1543 * @param int $flags
1544 * @return int Updated $flags
1545 */
1546 public function checkFlags( $flags ) {
1547 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1548 if ( $this->exists() ) {
1549 $flags |= EDIT_UPDATE;
1550 } else {
1551 $flags |= EDIT_NEW;
1552 }
1553 }
1554
1555 return $flags;
1556 }
1557
1558 /**
1559 * Change an existing article or create a new article. Updates RC and all necessary caches,
1560 * optionally via the deferred update array.
1561 *
1562 * @param string $text New text
1563 * @param string $summary Edit summary
1564 * @param int $flags Bitfield:
1565 * EDIT_NEW
1566 * Article is known or assumed to be non-existent, create a new one
1567 * EDIT_UPDATE
1568 * Article is known or assumed to be pre-existing, update it
1569 * EDIT_MINOR
1570 * Mark this edit minor, if the user is allowed to do so
1571 * EDIT_SUPPRESS_RC
1572 * Do not log the change in recentchanges
1573 * EDIT_FORCE_BOT
1574 * Mark the edit a "bot" edit regardless of user rights
1575 * EDIT_AUTOSUMMARY
1576 * Fill in blank summaries with generated text where possible
1577 *
1578 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1579 * article will be detected. If EDIT_UPDATE is specified and the article
1580 * doesn't exist, the function will return an edit-gone-missing error. If
1581 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1582 * error will be returned. These two conditions are also possible with
1583 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1584 *
1585 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1586 * This is not the parent revision ID, rather the revision ID for older
1587 * content used as the source for a rollback, for example.
1588 * @param User $user The user doing the edit
1589 *
1590 * @throws MWException
1591 * @return Status Possible errors:
1592 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1593 * set the fatal flag of $status
1594 * edit-gone-missing: In update mode, but the article didn't exist.
1595 * edit-conflict: In update mode, the article changed unexpectedly.
1596 * edit-no-change: Warning that the text was the same as before.
1597 * edit-already-exists: In creation mode, but the article already exists.
1598 *
1599 * Extensions may define additional errors.
1600 *
1601 * $return->value will contain an associative array with members as follows:
1602 * new: Boolean indicating if the function attempted to create a new article.
1603 * revision: The revision object for the inserted revision, or null.
1604 *
1605 * Compatibility note: this function previously returned a boolean value
1606 * indicating success/failure
1607 *
1608 * @deprecated since 1.21: use doEditContent() instead.
1609 */
1610 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1611 ContentHandler::deprecated( __METHOD__, '1.21' );
1612
1613 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1614
1615 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1616 }
1617
1618 /**
1619 * Change an existing article or create a new article. Updates RC and all necessary caches,
1620 * optionally via the deferred update array.
1621 *
1622 * @param Content $content New content
1623 * @param string $summary Edit summary
1624 * @param int $flags Bitfield:
1625 * EDIT_NEW
1626 * Article is known or assumed to be non-existent, create a new one
1627 * EDIT_UPDATE
1628 * Article is known or assumed to be pre-existing, update it
1629 * EDIT_MINOR
1630 * Mark this edit minor, if the user is allowed to do so
1631 * EDIT_SUPPRESS_RC
1632 * Do not log the change in recentchanges
1633 * EDIT_FORCE_BOT
1634 * Mark the edit a "bot" edit regardless of user rights
1635 * EDIT_AUTOSUMMARY
1636 * Fill in blank summaries with generated text where possible
1637 *
1638 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1639 * article will be detected. If EDIT_UPDATE is specified and the article
1640 * doesn't exist, the function will return an edit-gone-missing error. If
1641 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1642 * error will be returned. These two conditions are also possible with
1643 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1644 *
1645 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1646 * This is not the parent revision ID, rather the revision ID for older
1647 * content used as the source for a rollback, for example.
1648 * @param User $user The user doing the edit
1649 * @param string $serialFormat Format for storing the content in the
1650 * database.
1651 *
1652 * @throws MWException
1653 * @return Status Possible errors:
1654 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1655 * set the fatal flag of $status.
1656 * edit-gone-missing: In update mode, but the article didn't exist.
1657 * edit-conflict: In update mode, the article changed unexpectedly.
1658 * edit-no-change: Warning that the text was the same as before.
1659 * edit-already-exists: In creation mode, but the article already exists.
1660 *
1661 * Extensions may define additional errors.
1662 *
1663 * $return->value will contain an associative array with members as follows:
1664 * new: Boolean indicating if the function attempted to create a new article.
1665 * revision: The revision object for the inserted revision, or null.
1666 *
1667 * @since 1.21
1668 * @throws MWException
1669 */
1670 public function doEditContent(
1671 Content $content, $summary, $flags = 0, $baseRevId = false,
1672 User $user = null, $serialFormat = null
1673 ) {
1674 global $wgUser, $wgUseAutomaticEditSummaries;
1675
1676 // Low-level sanity check
1677 if ( $this->mTitle->getText() === '' ) {
1678 throw new MWException( 'Something is trying to edit an article with an empty title' );
1679 }
1680 // Make sure the given content type is allowed for this page
1681 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1682 return Status::newFatal( 'content-not-allowed-here',
1683 ContentHandler::getLocalizedName( $content->getModel() ),
1684 $this->mTitle->getPrefixedText()
1685 );
1686 }
1687
1688 // Load the data from the master database if needed.
1689 // The caller may already loaded it from the master or even loaded it using
1690 // SELECT FOR UPDATE, so do not override that using clear().
1691 $this->loadPageData( 'fromdbmaster' );
1692
1693 $user = $user ?: $wgUser;
1694 $flags = $this->checkFlags( $flags );
1695
1696 // Trigger pre-save hook (using provided edit summary)
1697 $hookStatus = Status::newGood( array() );
1698 $hook_args = array( &$this, &$user, &$content, &$summary,
1699 $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus );
1700 // Check if the hook rejected the attempted save
1701 if ( !Hooks::run( 'PageContentSave', $hook_args )
1702 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args )
1703 ) {
1704 if ( $hookStatus->isOK() ) {
1705 // Hook returned false but didn't call fatal(); use generic message
1706 $hookStatus->fatal( 'edit-hook-aborted' );
1707 }
1708
1709 return $hookStatus;
1710 }
1711
1712 $old_revision = $this->getRevision(); // current revision
1713 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1714
1715 // Provide autosummaries if one is not provided and autosummaries are enabled
1716 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1717 $handler = $content->getContentHandler();
1718 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1719 }
1720
1721 // Get the pre-save transform content and final parser output
1722 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1723 $pstContent = $editInfo->pstContent; // Content object
1724 $meta = array(
1725 'bot' => ( $flags & EDIT_FORCE_BOT ),
1726 'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1727 'serialized' => $editInfo->pst,
1728 'serialFormat' => $serialFormat,
1729 'baseRevId' => $baseRevId,
1730 'oldRevision' => $old_revision,
1731 'oldContent' => $old_content,
1732 'oldId' => $this->getLatest(),
1733 'oldIsRedirect' => $this->isRedirect(),
1734 'oldCountable' => $this->isCountable()
1735 );
1736
1737 // Actually create the revision and create/update the page
1738 if ( $flags & EDIT_UPDATE ) {
1739 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1740 } else {
1741 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1742 }
1743
1744 // Promote user to any groups they meet the criteria for
1745 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1746 $user->addAutopromoteOnceGroups( 'onEdit' );
1747 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1748 } );
1749
1750 return $status;
1751 }
1752
1753 /**
1754 * @param Content $content Pre-save transform content
1755 * @param integer $flags
1756 * @param User $user
1757 * @param string $summary
1758 * @param array $meta
1759 * @return Status
1760 * @throws DBUnexpectedError
1761 * @throws Exception
1762 * @throws FatalError
1763 * @throws MWException
1764 */
1765 private function doModify(
1766 Content $content, $flags, User $user, $summary, array $meta
1767 ) {
1768 global $wgUseRCPatrol;
1769
1770 // Update article, but only if changed.
1771 $status = Status::newGood( array( 'new' => false, 'revision' => null ) );
1772
1773 // Convenience variables
1774 $now = wfTimestampNow();
1775 $oldid = $meta['oldId'];
1776 /** @var $oldContent Content|null */
1777 $oldContent = $meta['oldContent'];
1778 $newsize = $content->getSize();
1779
1780 if ( !$oldid ) {
1781 // Article gone missing
1782 $status->fatal( 'edit-gone-missing' );
1783
1784 return $status;
1785 } elseif ( !$oldContent ) {
1786 // Sanity check for bug 37225
1787 throw new MWException( "Could not find text for current revision {$oldid}." );
1788 }
1789
1790 // @TODO: pass content object?!
1791 $revision = new Revision( array(
1792 'page' => $this->getId(),
1793 'title' => $this->mTitle, // for determining the default content model
1794 'comment' => $summary,
1795 'minor_edit' => $meta['minor'],
1796 'text' => $meta['serialized'],
1797 'len' => $newsize,
1798 'parent_id' => $oldid,
1799 'user' => $user->getId(),
1800 'user_text' => $user->getName(),
1801 'timestamp' => $now,
1802 'content_model' => $content->getModel(),
1803 'content_format' => $meta['serialFormat'],
1804 ) );
1805
1806 $changed = !$content->equals( $oldContent );
1807
1808 if ( $changed ) {
1809 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1810 $status->merge( $prepStatus );
1811 if ( !$status->isOK() ) {
1812 return $status;
1813 }
1814
1815 $dbw = wfGetDB( DB_MASTER );
1816 $dbw->begin( __METHOD__ );
1817 // Get the latest page_latest value while locking it.
1818 // Do a CAS style check to see if it's the same as when this method
1819 // started. If it changed then bail out before touching the DB.
1820 $latestNow = $this->lockAndGetLatest();
1821 if ( $latestNow != $oldid ) {
1822 $dbw->commit( __METHOD__ );
1823 // Page updated or deleted in the mean time
1824 $status->fatal( 'edit-conflict' );
1825
1826 return $status;
1827 }
1828
1829 // At this point we are now comitted to returning an OK
1830 // status unless some DB query error or other exception comes up.
1831 // This way callers don't have to call rollback() if $status is bad
1832 // unless they actually try to catch exceptions (which is rare).
1833
1834 // Save the revision text
1835 $revisionId = $revision->insertOn( $dbw );
1836 // Update page_latest and friends to reflect the new revision
1837 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1838 $dbw->rollback( __METHOD__ );
1839 throw new MWException( "Failed to update page row to use new revision." );
1840 }
1841
1842 Hooks::run( 'NewRevisionFromEditComplete',
1843 array( $this, $revision, $meta['baseRevId'], $user ) );
1844
1845 // Update recentchanges
1846 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1847 // Mark as patrolled if the user can do so
1848 $patrolled = $wgUseRCPatrol && !count(
1849 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1850 // Add RC row to the DB
1851 RecentChange::notifyEdit(
1852 $now,
1853 $this->mTitle,
1854 $revision->isMinor(),
1855 $user,
1856 $summary,
1857 $oldid,
1858 $this->getTimestamp(),
1859 $meta['bot'],
1860 '',
1861 $oldContent ? $oldContent->getSize() : 0,
1862 $newsize,
1863 $revisionId,
1864 $patrolled
1865 );
1866 }
1867
1868 $user->incEditCount();
1869
1870 $dbw->commit( __METHOD__ );
1871 $this->mTimestamp = $now;
1872 } else {
1873 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1874 // related variables correctly
1875 $revision->setId( $this->getLatest() );
1876 }
1877
1878 // Update links tables, site stats, etc.
1879 $this->doEditUpdates(
1880 $revision,
1881 $user,
1882 array(
1883 'changed' => $changed,
1884 'oldcountable' => $meta['oldCountable'],
1885 'oldrevision' => $meta['oldRevision']
1886 )
1887 );
1888
1889 if ( $changed ) {
1890 // Return the new revision to the caller
1891 $status->value['revision'] = $revision;
1892 } else {
1893 $status->warning( 'edit-no-change' );
1894 // Update page_touched as updateRevisionOn() was not called.
1895 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1896 $this->mTitle->invalidateCache( $now );
1897 }
1898
1899 // Trigger post-save hook
1900 $hook_args = array( &$this, &$user, $content, $summary,
1901 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $meta['baseRevId'] );
1902 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1903 Hooks::run( 'PageContentSaveComplete', $hook_args );
1904
1905 return $status;
1906 }
1907
1908 /**
1909 * @param Content $content Pre-save transform content
1910 * @param integer $flags
1911 * @param User $user
1912 * @param string $summary
1913 * @param array $meta
1914 * @return Status
1915 * @throws DBUnexpectedError
1916 * @throws Exception
1917 * @throws FatalError
1918 * @throws MWException
1919 */
1920 private function doCreate(
1921 Content $content, $flags, User $user, $summary, array $meta
1922 ) {
1923 global $wgUseRCPatrol, $wgUseNPPatrol;
1924
1925 $status = Status::newGood( array( 'new' => true, 'revision' => null ) );
1926
1927 $now = wfTimestampNow();
1928 $newsize = $content->getSize();
1929 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1930 $status->merge( $prepStatus );
1931 if ( !$status->isOK() ) {
1932 return $status;
1933 }
1934
1935 $dbw = wfGetDB( DB_MASTER );
1936 $dbw->begin( __METHOD__ );
1937
1938 // Add the page record unless one already exists for the title
1939 $newid = $this->insertOn( $dbw );
1940 if ( $newid === false ) {
1941 $dbw->commit( __METHOD__ ); // nothing inserted
1942 $status->fatal( 'edit-already-exists' );
1943
1944 return $status; // nothing done
1945 }
1946
1947 // At this point we are now comitted to returning an OK
1948 // status unless some DB query error or other exception comes up.
1949 // This way callers don't have to call rollback() if $status is bad
1950 // unless they actually try to catch exceptions (which is rare).
1951
1952 // @TODO: pass content object?!
1953 $revision = new Revision( array(
1954 'page' => $newid,
1955 'title' => $this->mTitle, // for determining the default content model
1956 'comment' => $summary,
1957 'minor_edit' => $meta['minor'],
1958 'text' => $meta['serialized'],
1959 'len' => $newsize,
1960 'user' => $user->getId(),
1961 'user_text' => $user->getName(),
1962 'timestamp' => $now,
1963 'content_model' => $content->getModel(),
1964 'content_format' => $meta['serialFormat'],
1965 ) );
1966
1967 // Save the revision text...
1968 $revisionId = $revision->insertOn( $dbw );
1969 // Update the page record with revision data
1970 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1971 $dbw->rollback( __METHOD__ );
1972 throw new MWException( "Failed to update page row to use new revision." );
1973 }
1974
1975 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1976
1977 // Update recentchanges
1978 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1979 // Mark as patrolled if the user can do so
1980 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
1981 !count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1982 // Add RC row to the DB
1983 RecentChange::notifyNew(
1984 $now,
1985 $this->mTitle,
1986 $revision->isMinor(),
1987 $user,
1988 $summary,
1989 $meta['bot'],
1990 '',
1991 $newsize,
1992 $revisionId,
1993 $patrolled
1994 );
1995 }
1996
1997 $user->incEditCount();
1998
1999 $dbw->commit( __METHOD__ );
2000 $this->mTimestamp = $now;
2001
2002 // Update links, etc.
2003 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
2004
2005 $hook_args = array( &$this, &$user, $content, $summary,
2006 $flags & EDIT_MINOR, null, null, &$flags, $revision );
2007 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
2008 Hooks::run( 'PageContentInsertComplete', $hook_args );
2009
2010 // Return the new revision to the caller
2011 $status->value['revision'] = $revision;
2012
2013 // Trigger post-save hook
2014 $hook_args = array( &$this, &$user, $content, $summary,
2015 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $meta['baseRevId'] );
2016 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
2017 Hooks::run( 'PageContentSaveComplete', $hook_args );
2018
2019 return $status;
2020 }
2021
2022 /**
2023 * Get parser options suitable for rendering the primary article wikitext
2024 *
2025 * @see ContentHandler::makeParserOptions
2026 *
2027 * @param IContextSource|User|string $context One of the following:
2028 * - IContextSource: Use the User and the Language of the provided
2029 * context
2030 * - User: Use the provided User object and $wgLang for the language,
2031 * so use an IContextSource object if possible.
2032 * - 'canonical': Canonical options (anonymous user with default
2033 * preferences and content language).
2034 * @return ParserOptions
2035 */
2036 public function makeParserOptions( $context ) {
2037 $options = $this->getContentHandler()->makeParserOptions( $context );
2038
2039 if ( $this->getTitle()->isConversionTable() ) {
2040 // @todo ConversionTable should become a separate content model, so
2041 // we don't need special cases like this one.
2042 $options->disableContentConversion();
2043 }
2044
2045 return $options;
2046 }
2047
2048 /**
2049 * Prepare text which is about to be saved.
2050 * Returns a stdClass with source, pst and output members
2051 *
2052 * @param string $text
2053 * @param int|null $revid
2054 * @param User|null $user
2055 * @deprecated since 1.21: use prepareContentForEdit instead.
2056 * @return object
2057 */
2058 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2059 ContentHandler::deprecated( __METHOD__, '1.21' );
2060 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2061 return $this->prepareContentForEdit( $content, $revid, $user );
2062 }
2063
2064 /**
2065 * Prepare content which is about to be saved.
2066 * Returns a stdClass with source, pst and output members
2067 *
2068 * @param Content $content
2069 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2070 * revision ID is also accepted, but this is deprecated.
2071 * @param User|null $user
2072 * @param string|null $serialFormat
2073 * @param bool $useCache Check shared prepared edit cache
2074 *
2075 * @return object
2076 *
2077 * @since 1.21
2078 */
2079 public function prepareContentForEdit(
2080 Content $content, $revision = null, User $user = null,
2081 $serialFormat = null, $useCache = true
2082 ) {
2083 global $wgContLang, $wgUser, $wgAjaxEditStash;
2084
2085 if ( is_object( $revision ) ) {
2086 $revid = $revision->getId();
2087 } else {
2088 $revid = $revision;
2089 // This code path is deprecated, and nothing is known to
2090 // use it, so performance here shouldn't be a worry.
2091 if ( $revid !== null ) {
2092 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2093 } else {
2094 $revision = null;
2095 }
2096 }
2097
2098 $user = is_null( $user ) ? $wgUser : $user;
2099 // XXX: check $user->getId() here???
2100
2101 // Use a sane default for $serialFormat, see bug 57026
2102 if ( $serialFormat === null ) {
2103 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2104 }
2105
2106 if ( $this->mPreparedEdit
2107 && $this->mPreparedEdit->newContent
2108 && $this->mPreparedEdit->newContent->equals( $content )
2109 && $this->mPreparedEdit->revid == $revid
2110 && $this->mPreparedEdit->format == $serialFormat
2111 // XXX: also check $user here?
2112 ) {
2113 // Already prepared
2114 return $this->mPreparedEdit;
2115 }
2116
2117 // The edit may have already been prepared via api.php?action=stashedit
2118 $cachedEdit = $useCache && $wgAjaxEditStash
2119 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2120 : false;
2121
2122 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2123 Hooks::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2124
2125 $edit = (object)array();
2126 if ( $cachedEdit ) {
2127 $edit->timestamp = $cachedEdit->timestamp;
2128 } else {
2129 $edit->timestamp = wfTimestampNow();
2130 }
2131 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2132 $edit->revid = $revid;
2133
2134 if ( $cachedEdit ) {
2135 $edit->pstContent = $cachedEdit->pstContent;
2136 } else {
2137 $edit->pstContent = $content
2138 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2139 : null;
2140 }
2141
2142 $edit->format = $serialFormat;
2143 $edit->popts = $this->makeParserOptions( 'canonical' );
2144 if ( $cachedEdit ) {
2145 $edit->output = $cachedEdit->output;
2146 } else {
2147 if ( $revision ) {
2148 // We get here if vary-revision is set. This means that this page references
2149 // itself (such as via self-transclusion). In this case, we need to make sure
2150 // that any such self-references refer to the newly-saved revision, and not
2151 // to the previous one, which could otherwise happen due to slave lag.
2152 $oldCallback = $edit->popts->getCurrentRevisionCallback();
2153 $edit->popts->setCurrentRevisionCallback(
2154 function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2155 if ( $title->equals( $revision->getTitle() ) ) {
2156 return $revision;
2157 } else {
2158 return call_user_func( $oldCallback, $title, $parser );
2159 }
2160 }
2161 );
2162 }
2163 $edit->output = $edit->pstContent
2164 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2165 : null;
2166 }
2167
2168 $edit->newContent = $content;
2169 $edit->oldContent = $this->getContent( Revision::RAW );
2170
2171 // NOTE: B/C for hooks! don't use these fields!
2172 $edit->newText = $edit->newContent
2173 ? ContentHandler::getContentText( $edit->newContent )
2174 : '';
2175 $edit->oldText = $edit->oldContent
2176 ? ContentHandler::getContentText( $edit->oldContent )
2177 : '';
2178 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2179
2180 $this->mPreparedEdit = $edit;
2181 return $edit;
2182 }
2183
2184 /**
2185 * Do standard deferred updates after page edit.
2186 * Update links tables, site stats, search index and message cache.
2187 * Purges pages that include this page if the text was changed here.
2188 * Every 100th edit, prune the recent changes table.
2189 *
2190 * @param Revision $revision
2191 * @param User $user User object that did the revision
2192 * @param array $options Array of options, following indexes are used:
2193 * - changed: boolean, whether the revision changed the content (default true)
2194 * - created: boolean, whether the revision created the page (default false)
2195 * - moved: boolean, whether the page was moved (default false)
2196 * - restored: boolean, whether the page was undeleted (default false)
2197 * - oldrevision: Revision object for the pre-update revision (default null)
2198 * - oldcountable: boolean, null, or string 'no-change' (default null):
2199 * - boolean: whether the page was counted as an article before that
2200 * revision, only used in changed is true and created is false
2201 * - null: if created is false, don't update the article count; if created
2202 * is true, do update the article count
2203 * - 'no-change': don't update the article count, ever
2204 */
2205 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2206 global $wgRCWatchCategoryMembership;
2207
2208 $options += array(
2209 'changed' => true,
2210 'created' => false,
2211 'moved' => false,
2212 'restored' => false,
2213 'oldrevision' => null,
2214 'oldcountable' => null
2215 );
2216 $content = $revision->getContent();
2217
2218 // Parse the text
2219 // Be careful not to do pre-save transform twice: $text is usually
2220 // already pre-save transformed once.
2221 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2222 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2223 $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2224 } else {
2225 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2226 $editInfo = $this->mPreparedEdit;
2227 }
2228
2229 // Save it to the parser cache.
2230 // Make sure the cache time matches page_touched to avoid double parsing.
2231 ParserCache::singleton()->save(
2232 $editInfo->output, $this, $editInfo->popts,
2233 $revision->getTimestamp(), $editInfo->revid
2234 );
2235
2236 // Update the links tables and other secondary data
2237 if ( $content ) {
2238 $recursive = $options['changed']; // bug 50785
2239 $updates = $content->getSecondaryDataUpdates(
2240 $this->getTitle(), null, $recursive, $editInfo->output
2241 );
2242 foreach ( $updates as $update ) {
2243 if ( $update instanceof LinksUpdate ) {
2244 $update->setRevision( $revision );
2245 $update->setTriggeringUser( $user );
2246 }
2247 DeferredUpdates::addUpdate( $update );
2248 }
2249 if ( $wgRCWatchCategoryMembership
2250 && ( $options['changed'] || $options['created'] )
2251 && !$options['restored']
2252 ) {
2253 // Note: jobs are pushed after deferred updates, so the job should be able to see
2254 // the recent change entry (also done via deferred updates) and carry over any
2255 // bot/deletion/IP flags, ect.
2256 JobQueueGroup::singleton()->lazyPush( new CategoryMembershipChangeJob(
2257 $this->getTitle(),
2258 array(
2259 'pageId' => $this->getId(),
2260 'revTimestamp' => $revision->getTimestamp()
2261 )
2262 ) );
2263 }
2264 }
2265
2266 Hooks::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2267
2268 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2269 // Flush old entries from the `recentchanges` table
2270 if ( mt_rand( 0, 9 ) == 0 ) {
2271 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newPurgeJob() );
2272 }
2273 }
2274
2275 if ( !$this->exists() ) {
2276 return;
2277 }
2278
2279 $id = $this->getId();
2280 $title = $this->mTitle->getPrefixedDBkey();
2281 $shortTitle = $this->mTitle->getDBkey();
2282
2283 if ( $options['oldcountable'] === 'no-change' ||
2284 ( !$options['changed'] && !$options['moved'] )
2285 ) {
2286 $good = 0;
2287 } elseif ( $options['created'] ) {
2288 $good = (int)$this->isCountable( $editInfo );
2289 } elseif ( $options['oldcountable'] !== null ) {
2290 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2291 } else {
2292 $good = 0;
2293 }
2294 $edits = $options['changed'] ? 1 : 0;
2295 $total = $options['created'] ? 1 : 0;
2296
2297 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2298 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2299
2300 // If this is another user's talk page, update newtalk.
2301 // Don't do this if $options['changed'] = false (null-edits) nor if
2302 // it's a minor edit and the user doesn't want notifications for those.
2303 if ( $options['changed']
2304 && $this->mTitle->getNamespace() == NS_USER_TALK
2305 && $shortTitle != $user->getTitleKey()
2306 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2307 ) {
2308 $recipient = User::newFromName( $shortTitle, false );
2309 if ( !$recipient ) {
2310 wfDebug( __METHOD__ . ": invalid username\n" );
2311 } else {
2312 // Allow extensions to prevent user notification
2313 // when a new message is added to their talk page
2314 if ( Hooks::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2315 if ( User::isIP( $shortTitle ) ) {
2316 // An anonymous user
2317 $recipient->setNewtalk( true, $revision );
2318 } elseif ( $recipient->isLoggedIn() ) {
2319 $recipient->setNewtalk( true, $revision );
2320 } else {
2321 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2322 }
2323 }
2324 }
2325 }
2326
2327 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2328 // XXX: could skip pseudo-messages like js/css here, based on content model.
2329 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2330 if ( $msgtext === false || $msgtext === null ) {
2331 $msgtext = '';
2332 }
2333
2334 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2335 }
2336
2337 if ( $options['created'] ) {
2338 self::onArticleCreate( $this->mTitle );
2339 } elseif ( $options['changed'] ) { // bug 50785
2340 self::onArticleEdit( $this->mTitle, $revision );
2341 }
2342 }
2343
2344 /**
2345 * Edit an article without doing all that other stuff
2346 * The article must already exist; link tables etc
2347 * are not updated, caches are not flushed.
2348 *
2349 * @param Content $content Content submitted
2350 * @param User $user The relevant user
2351 * @param string $comment Comment submitted
2352 * @param bool $minor Whereas it's a minor modification
2353 * @param string $serialFormat Format for storing the content in the database
2354 */
2355 public function doQuickEditContent(
2356 Content $content, User $user, $comment = '', $minor = false, $serialFormat = null
2357 ) {
2358
2359 $serialized = $content->serialize( $serialFormat );
2360
2361 $dbw = wfGetDB( DB_MASTER );
2362 $revision = new Revision( array(
2363 'title' => $this->getTitle(), // for determining the default content model
2364 'page' => $this->getId(),
2365 'user_text' => $user->getName(),
2366 'user' => $user->getId(),
2367 'text' => $serialized,
2368 'length' => $content->getSize(),
2369 'comment' => $comment,
2370 'minor_edit' => $minor ? 1 : 0,
2371 ) ); // XXX: set the content object?
2372 $revision->insertOn( $dbw );
2373 $this->updateRevisionOn( $dbw, $revision );
2374
2375 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2376
2377 }
2378
2379 /**
2380 * Update the article's restriction field, and leave a log entry.
2381 * This works for protection both existing and non-existing pages.
2382 *
2383 * @param array $limit Set of restriction keys
2384 * @param array $expiry Per restriction type expiration
2385 * @param int &$cascade Set to false if cascading protection isn't allowed.
2386 * @param string $reason
2387 * @param User $user The user updating the restrictions
2388 * @return Status
2389 */
2390 public function doUpdateRestrictions( array $limit, array $expiry,
2391 &$cascade, $reason, User $user
2392 ) {
2393 global $wgCascadingRestrictionLevels, $wgContLang;
2394
2395 if ( wfReadOnly() ) {
2396 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2397 }
2398
2399 $this->loadPageData( 'fromdbmaster' );
2400 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2401 $id = $this->getId();
2402
2403 if ( !$cascade ) {
2404 $cascade = false;
2405 }
2406
2407 // Take this opportunity to purge out expired restrictions
2408 Title::purgeExpiredRestrictions();
2409
2410 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2411 // we expect a single selection, but the schema allows otherwise.
2412 $isProtected = false;
2413 $protect = false;
2414 $changed = false;
2415
2416 $dbw = wfGetDB( DB_MASTER );
2417
2418 foreach ( $restrictionTypes as $action ) {
2419 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2420 $expiry[$action] = 'infinity';
2421 }
2422 if ( !isset( $limit[$action] ) ) {
2423 $limit[$action] = '';
2424 } elseif ( $limit[$action] != '' ) {
2425 $protect = true;
2426 }
2427
2428 // Get current restrictions on $action
2429 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2430 if ( $current != '' ) {
2431 $isProtected = true;
2432 }
2433
2434 if ( $limit[$action] != $current ) {
2435 $changed = true;
2436 } elseif ( $limit[$action] != '' ) {
2437 // Only check expiry change if the action is actually being
2438 // protected, since expiry does nothing on an not-protected
2439 // action.
2440 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2441 $changed = true;
2442 }
2443 }
2444 }
2445
2446 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2447 $changed = true;
2448 }
2449
2450 // If nothing has changed, do nothing
2451 if ( !$changed ) {
2452 return Status::newGood();
2453 }
2454
2455 if ( !$protect ) { // No protection at all means unprotection
2456 $revCommentMsg = 'unprotectedarticle';
2457 $logAction = 'unprotect';
2458 } elseif ( $isProtected ) {
2459 $revCommentMsg = 'modifiedarticleprotection';
2460 $logAction = 'modify';
2461 } else {
2462 $revCommentMsg = 'protectedarticle';
2463 $logAction = 'protect';
2464 }
2465
2466 // Truncate for whole multibyte characters
2467 $reason = $wgContLang->truncate( $reason, 255 );
2468
2469 $logRelationsValues = array();
2470 $logRelationsField = null;
2471 $logParamsDetails = array();
2472
2473 if ( $id ) { // Protection of existing page
2474 if ( !Hooks::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2475 return Status::newGood();
2476 }
2477
2478 // Only certain restrictions can cascade...
2479 $editrestriction = isset( $limit['edit'] )
2480 ? array( $limit['edit'] )
2481 : $this->mTitle->getRestrictions( 'edit' );
2482 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2483 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2484 }
2485 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2486 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2487 }
2488
2489 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2490 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2491 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2492 }
2493 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2494 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2495 }
2496
2497 // The schema allows multiple restrictions
2498 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2499 $cascade = false;
2500 }
2501
2502 // insert null revision to identify the page protection change as edit summary
2503 $latest = $this->getLatest();
2504 $nullRevision = $this->insertProtectNullRevision(
2505 $revCommentMsg,
2506 $limit,
2507 $expiry,
2508 $cascade,
2509 $reason,
2510 $user
2511 );
2512
2513 if ( $nullRevision === null ) {
2514 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2515 }
2516
2517 $logRelationsField = 'pr_id';
2518
2519 // Update restrictions table
2520 foreach ( $limit as $action => $restrictions ) {
2521 $dbw->delete(
2522 'page_restrictions',
2523 array(
2524 'pr_page' => $id,
2525 'pr_type' => $action
2526 ),
2527 __METHOD__
2528 );
2529 if ( $restrictions != '' ) {
2530 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2531 $dbw->insert(
2532 'page_restrictions',
2533 array(
2534 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2535 'pr_page' => $id,
2536 'pr_type' => $action,
2537 'pr_level' => $restrictions,
2538 'pr_cascade' => $cascadeValue,
2539 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2540 ),
2541 __METHOD__
2542 );
2543 $logRelationsValues[] = $dbw->insertId();
2544 $logParamsDetails[] = array(
2545 'type' => $action,
2546 'level' => $restrictions,
2547 'expiry' => $expiry[$action],
2548 'cascade' => (bool)$cascadeValue,
2549 );
2550 }
2551 }
2552
2553 // Clear out legacy restriction fields
2554 $dbw->update(
2555 'page',
2556 array( 'page_restrictions' => '' ),
2557 array( 'page_id' => $id ),
2558 __METHOD__
2559 );
2560
2561 Hooks::run( 'NewRevisionFromEditComplete',
2562 array( $this, $nullRevision, $latest, $user ) );
2563 Hooks::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2564 } else { // Protection of non-existing page (also known as "title protection")
2565 // Cascade protection is meaningless in this case
2566 $cascade = false;
2567
2568 if ( $limit['create'] != '' ) {
2569 $dbw->replace( 'protected_titles',
2570 array( array( 'pt_namespace', 'pt_title' ) ),
2571 array(
2572 'pt_namespace' => $this->mTitle->getNamespace(),
2573 'pt_title' => $this->mTitle->getDBkey(),
2574 'pt_create_perm' => $limit['create'],
2575 'pt_timestamp' => $dbw->timestamp(),
2576 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2577 'pt_user' => $user->getId(),
2578 'pt_reason' => $reason,
2579 ), __METHOD__
2580 );
2581 $logParamsDetails[] = array(
2582 'type' => 'create',
2583 'level' => $limit['create'],
2584 'expiry' => $expiry['create'],
2585 );
2586 } else {
2587 $dbw->delete( 'protected_titles',
2588 array(
2589 'pt_namespace' => $this->mTitle->getNamespace(),
2590 'pt_title' => $this->mTitle->getDBkey()
2591 ), __METHOD__
2592 );
2593 }
2594 }
2595
2596 $this->mTitle->flushRestrictions();
2597 InfoAction::invalidateCache( $this->mTitle );
2598
2599 if ( $logAction == 'unprotect' ) {
2600 $params = array();
2601 } else {
2602 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2603 $params = array(
2604 '4::description' => $protectDescriptionLog, // parameter for IRC
2605 '5:bool:cascade' => $cascade,
2606 'details' => $logParamsDetails, // parameter for localize and api
2607 );
2608 }
2609
2610 // Update the protection log
2611 $logEntry = new ManualLogEntry( 'protect', $logAction );
2612 $logEntry->setTarget( $this->mTitle );
2613 $logEntry->setComment( $reason );
2614 $logEntry->setPerformer( $user );
2615 $logEntry->setParameters( $params );
2616 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2617 $logEntry->setRelations( array( $logRelationsField => $logRelationsValues ) );
2618 }
2619 $logId = $logEntry->insert();
2620 $logEntry->publish( $logId );
2621
2622 return Status::newGood();
2623 }
2624
2625 /**
2626 * Insert a new null revision for this page.
2627 *
2628 * @param string $revCommentMsg Comment message key for the revision
2629 * @param array $limit Set of restriction keys
2630 * @param array $expiry Per restriction type expiration
2631 * @param int $cascade Set to false if cascading protection isn't allowed.
2632 * @param string $reason
2633 * @param User|null $user
2634 * @return Revision|null Null on error
2635 */
2636 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2637 array $expiry, $cascade, $reason, $user = null
2638 ) {
2639 global $wgContLang;
2640 $dbw = wfGetDB( DB_MASTER );
2641
2642 // Prepare a null revision to be added to the history
2643 $editComment = $wgContLang->ucfirst(
2644 wfMessage(
2645 $revCommentMsg,
2646 $this->mTitle->getPrefixedText()
2647 )->inContentLanguage()->text()
2648 );
2649 if ( $reason ) {
2650 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2651 }
2652 $protectDescription = $this->protectDescription( $limit, $expiry );
2653 if ( $protectDescription ) {
2654 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2655 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2656 ->inContentLanguage()->text();
2657 }
2658 if ( $cascade ) {
2659 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2660 $editComment .= wfMessage( 'brackets' )->params(
2661 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2662 )->inContentLanguage()->text();
2663 }
2664
2665 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2666 if ( $nullRev ) {
2667 $nullRev->insertOn( $dbw );
2668
2669 // Update page record and touch page
2670 $oldLatest = $nullRev->getParentId();
2671 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2672 }
2673
2674 return $nullRev;
2675 }
2676
2677 /**
2678 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2679 * @return string
2680 */
2681 protected function formatExpiry( $expiry ) {
2682 global $wgContLang;
2683
2684 if ( $expiry != 'infinity' ) {
2685 return wfMessage(
2686 'protect-expiring',
2687 $wgContLang->timeanddate( $expiry, false, false ),
2688 $wgContLang->date( $expiry, false, false ),
2689 $wgContLang->time( $expiry, false, false )
2690 )->inContentLanguage()->text();
2691 } else {
2692 return wfMessage( 'protect-expiry-indefinite' )
2693 ->inContentLanguage()->text();
2694 }
2695 }
2696
2697 /**
2698 * Builds the description to serve as comment for the edit.
2699 *
2700 * @param array $limit Set of restriction keys
2701 * @param array $expiry Per restriction type expiration
2702 * @return string
2703 */
2704 public function protectDescription( array $limit, array $expiry ) {
2705 $protectDescription = '';
2706
2707 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2708 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2709 # All possible message keys are listed here for easier grepping:
2710 # * restriction-create
2711 # * restriction-edit
2712 # * restriction-move
2713 # * restriction-upload
2714 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2715 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2716 # with '' filtered out. All possible message keys are listed below:
2717 # * protect-level-autoconfirmed
2718 # * protect-level-sysop
2719 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2720 ->inContentLanguage()->text();
2721
2722 $expiryText = $this->formatExpiry( $expiry[$action] );
2723
2724 if ( $protectDescription !== '' ) {
2725 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2726 }
2727 $protectDescription .= wfMessage( 'protect-summary-desc' )
2728 ->params( $actionText, $restrictionsText, $expiryText )
2729 ->inContentLanguage()->text();
2730 }
2731
2732 return $protectDescription;
2733 }
2734
2735 /**
2736 * Builds the description to serve as comment for the log entry.
2737 *
2738 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2739 * protect description text. Keep them in old format to avoid breaking compatibility.
2740 * TODO: Fix protection log to store structured description and format it on-the-fly.
2741 *
2742 * @param array $limit Set of restriction keys
2743 * @param array $expiry Per restriction type expiration
2744 * @return string
2745 */
2746 public function protectDescriptionLog( array $limit, array $expiry ) {
2747 global $wgContLang;
2748
2749 $protectDescriptionLog = '';
2750
2751 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2752 $expiryText = $this->formatExpiry( $expiry[$action] );
2753 $protectDescriptionLog .= $wgContLang->getDirMark() .
2754 "[$action=$restrictions] ($expiryText)";
2755 }
2756
2757 return trim( $protectDescriptionLog );
2758 }
2759
2760 /**
2761 * Take an array of page restrictions and flatten it to a string
2762 * suitable for insertion into the page_restrictions field.
2763 *
2764 * @param string[] $limit
2765 *
2766 * @throws MWException
2767 * @return string
2768 */
2769 protected static function flattenRestrictions( $limit ) {
2770 if ( !is_array( $limit ) ) {
2771 throw new MWException( __METHOD__ . ' given non-array restriction set' );
2772 }
2773
2774 $bits = array();
2775 ksort( $limit );
2776
2777 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2778 $bits[] = "$action=$restrictions";
2779 }
2780
2781 return implode( ':', $bits );
2782 }
2783
2784 /**
2785 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2786 * backwards compatibility, if you care about error reporting you should use
2787 * doDeleteArticleReal() instead.
2788 *
2789 * Deletes the article with database consistency, writes logs, purges caches
2790 *
2791 * @param string $reason Delete reason for deletion log
2792 * @param bool $suppress Suppress all revisions and log the deletion in
2793 * the suppression log instead of the deletion log
2794 * @param int $u1 Unused
2795 * @param bool $u2 Unused
2796 * @param array|string &$error Array of errors to append to
2797 * @param User $user The deleting user
2798 * @return bool True if successful
2799 */
2800 public function doDeleteArticle(
2801 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2802 ) {
2803 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2804 return $status->isGood();
2805 }
2806
2807 /**
2808 * Back-end article deletion
2809 * Deletes the article with database consistency, writes logs, purges caches
2810 *
2811 * @since 1.19
2812 *
2813 * @param string $reason Delete reason for deletion log
2814 * @param bool $suppress Suppress all revisions and log the deletion in
2815 * the suppression log instead of the deletion log
2816 * @param int $u1 Unused
2817 * @param bool $u2 Unused
2818 * @param array|string &$error Array of errors to append to
2819 * @param User $user The deleting user
2820 * @return Status Status object; if successful, $status->value is the log_id of the
2821 * deletion log entry. If the page couldn't be deleted because it wasn't
2822 * found, $status is a non-fatal 'cannotdelete' error
2823 */
2824 public function doDeleteArticleReal(
2825 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2826 ) {
2827 global $wgUser, $wgContentHandlerUseDB;
2828
2829 wfDebug( __METHOD__ . "\n" );
2830
2831 $status = Status::newGood();
2832
2833 if ( $this->mTitle->getDBkey() === '' ) {
2834 $status->error( 'cannotdelete',
2835 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2836 return $status;
2837 }
2838
2839 $user = is_null( $user ) ? $wgUser : $user;
2840 if ( !Hooks::run( 'ArticleDelete',
2841 array( &$this, &$user, &$reason, &$error, &$status, $suppress )
2842 ) ) {
2843 if ( $status->isOK() ) {
2844 // Hook aborted but didn't set a fatal status
2845 $status->fatal( 'delete-hook-aborted' );
2846 }
2847 return $status;
2848 }
2849
2850 $dbw = wfGetDB( DB_MASTER );
2851 $dbw->startAtomic( __METHOD__ );
2852
2853 $this->loadPageData( self::READ_LATEST );
2854 $id = $this->getID();
2855 // T98706: lock the page from various other updates but avoid using
2856 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2857 // the revisions queries (which also JOIN on user). Only lock the page
2858 // row and CAS check on page_latest to see if the trx snapshot matches.
2859 $lockedLatest = $this->lockAndGetLatest();
2860 if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2861 $dbw->endAtomic( __METHOD__ );
2862 // Page not there or trx snapshot is stale
2863 $status->error( 'cannotdelete',
2864 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2865 return $status;
2866 }
2867
2868 // At this point we are now comitted to returning an OK
2869 // status unless some DB query error or other exception comes up.
2870 // This way callers don't have to call rollback() if $status is bad
2871 // unless they actually try to catch exceptions (which is rare).
2872
2873 // we need to remember the old content so we can use it to generate all deletion updates.
2874 $content = $this->getContent( Revision::RAW );
2875
2876 // Bitfields to further suppress the content
2877 if ( $suppress ) {
2878 $bitfield = 0;
2879 // This should be 15...
2880 $bitfield |= Revision::DELETED_TEXT;
2881 $bitfield |= Revision::DELETED_COMMENT;
2882 $bitfield |= Revision::DELETED_USER;
2883 $bitfield |= Revision::DELETED_RESTRICTED;
2884 } else {
2885 $bitfield = 'rev_deleted';
2886 }
2887
2888 /**
2889 * For now, shunt the revision data into the archive table.
2890 * Text is *not* removed from the text table; bulk storage
2891 * is left intact to avoid breaking block-compression or
2892 * immutable storage schemes.
2893 *
2894 * For backwards compatibility, note that some older archive
2895 * table entries will have ar_text and ar_flags fields still.
2896 *
2897 * In the future, we may keep revisions and mark them with
2898 * the rev_deleted field, which is reserved for this purpose.
2899 */
2900
2901 $row = array(
2902 'ar_namespace' => 'page_namespace',
2903 'ar_title' => 'page_title',
2904 'ar_comment' => 'rev_comment',
2905 'ar_user' => 'rev_user',
2906 'ar_user_text' => 'rev_user_text',
2907 'ar_timestamp' => 'rev_timestamp',
2908 'ar_minor_edit' => 'rev_minor_edit',
2909 'ar_rev_id' => 'rev_id',
2910 'ar_parent_id' => 'rev_parent_id',
2911 'ar_text_id' => 'rev_text_id',
2912 'ar_text' => '\'\'', // Be explicit to appease
2913 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2914 'ar_len' => 'rev_len',
2915 'ar_page_id' => 'page_id',
2916 'ar_deleted' => $bitfield,
2917 'ar_sha1' => 'rev_sha1',
2918 );
2919
2920 if ( $wgContentHandlerUseDB ) {
2921 $row['ar_content_model'] = 'rev_content_model';
2922 $row['ar_content_format'] = 'rev_content_format';
2923 }
2924
2925 // Copy all the page revisions into the archive table
2926 $dbw->insertSelect(
2927 'archive',
2928 array( 'page', 'revision' ),
2929 $row,
2930 array(
2931 'page_id' => $id,
2932 'page_id = rev_page'
2933 ),
2934 __METHOD__
2935 );
2936
2937 // Now that it's safely backed up, delete it
2938 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2939
2940 if ( !$dbw->cascadingDeletes() ) {
2941 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2942 }
2943
2944 // Clone the title, so we have the information we need when we log
2945 $logTitle = clone $this->mTitle;
2946
2947 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2948 $logtype = $suppress ? 'suppress' : 'delete';
2949
2950 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2951 $logEntry->setPerformer( $user );
2952 $logEntry->setTarget( $logTitle );
2953 $logEntry->setComment( $reason );
2954 $logid = $logEntry->insert();
2955
2956 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2957 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2958 $logEntry->publish( $logid );
2959 } );
2960
2961 $dbw->endAtomic( __METHOD__ );
2962
2963 $this->doDeleteUpdates( $id, $content );
2964
2965 Hooks::run( 'ArticleDeleteComplete',
2966 array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2967 $status->value = $logid;
2968
2969 // Show log excerpt on 404 pages rather than just a link
2970 $cache = ObjectCache::getMainStashInstance();
2971 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2972 $cache->set( $key, 1, $cache::TTL_DAY );
2973
2974 return $status;
2975 }
2976
2977 /**
2978 * Lock the page row for this title+id and return page_latest (or 0)
2979 *
2980 * @return integer Returns 0 if no row was found with this title+id
2981 * @since 1.27
2982 */
2983 public function lockAndGetLatest() {
2984 return (int)wfGetDB( DB_MASTER )->selectField(
2985 'page',
2986 'page_latest',
2987 array(
2988 'page_id' => $this->getId(),
2989 // Typically page_id is enough, but some code might try to do
2990 // updates assuming the title is the same, so verify that
2991 'page_namespace' => $this->getTitle()->getNamespace(),
2992 'page_title' => $this->getTitle()->getDBkey()
2993 ),
2994 __METHOD__,
2995 array( 'FOR UPDATE' )
2996 );
2997 }
2998
2999 /**
3000 * Do some database updates after deletion
3001 *
3002 * @param int $id The page_id value of the page being deleted
3003 * @param Content $content Optional page content to be used when determining
3004 * the required updates. This may be needed because $this->getContent()
3005 * may already return null when the page proper was deleted.
3006 */
3007 public function doDeleteUpdates( $id, Content $content = null ) {
3008 // Update site status
3009 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
3010
3011 // Delete pagelinks, update secondary indexes, etc
3012 $updates = $this->getDeletionUpdates( $content );
3013 foreach ( $updates as $update ) {
3014 DeferredUpdates::addUpdate( $update );
3015 }
3016
3017 // Reparse any pages transcluding this page
3018 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
3019
3020 // Reparse any pages including this image
3021 if ( $this->mTitle->getNamespace() == NS_FILE ) {
3022 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
3023 }
3024
3025 // Clear caches
3026 WikiPage::onArticleDelete( $this->mTitle );
3027
3028 // Reset this object and the Title object
3029 $this->loadFromRow( false, self::READ_LATEST );
3030
3031 // Search engine
3032 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
3033 }
3034
3035 /**
3036 * Roll back the most recent consecutive set of edits to a page
3037 * from the same user; fails if there are no eligible edits to
3038 * roll back to, e.g. user is the sole contributor. This function
3039 * performs permissions checks on $user, then calls commitRollback()
3040 * to do the dirty work
3041 *
3042 * @todo Separate the business/permission stuff out from backend code
3043 *
3044 * @param string $fromP Name of the user whose edits to rollback.
3045 * @param string $summary Custom summary. Set to default summary if empty.
3046 * @param string $token Rollback token.
3047 * @param bool $bot If true, mark all reverted edits as bot.
3048 *
3049 * @param array $resultDetails Array contains result-specific array of additional values
3050 * 'alreadyrolled' : 'current' (rev)
3051 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3052 *
3053 * @param User $user The user performing the rollback
3054 * @return array Array of errors, each error formatted as
3055 * array(messagekey, param1, param2, ...).
3056 * On success, the array is empty. This array can also be passed to
3057 * OutputPage::showPermissionsErrorPage().
3058 */
3059 public function doRollback(
3060 $fromP, $summary, $token, $bot, &$resultDetails, User $user
3061 ) {
3062 $resultDetails = null;
3063
3064 // Check permissions
3065 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3066 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3067 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3068
3069 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3070 $errors[] = array( 'sessionfailure' );
3071 }
3072
3073 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3074 $errors[] = array( 'actionthrottledtext' );
3075 }
3076
3077 // If there were errors, bail out now
3078 if ( !empty( $errors ) ) {
3079 return $errors;
3080 }
3081
3082 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
3083 }
3084
3085 /**
3086 * Backend implementation of doRollback(), please refer there for parameter
3087 * and return value documentation
3088 *
3089 * NOTE: This function does NOT check ANY permissions, it just commits the
3090 * rollback to the DB. Therefore, you should only call this function direct-
3091 * ly if you want to use custom permissions checks. If you don't, use
3092 * doRollback() instead.
3093 * @param string $fromP Name of the user whose edits to rollback.
3094 * @param string $summary Custom summary. Set to default summary if empty.
3095 * @param bool $bot If true, mark all reverted edits as bot.
3096 *
3097 * @param array $resultDetails Contains result-specific array of additional values
3098 * @param User $guser The user performing the rollback
3099 * @return array
3100 */
3101 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
3102 global $wgUseRCPatrol, $wgContLang;
3103
3104 $dbw = wfGetDB( DB_MASTER );
3105
3106 if ( wfReadOnly() ) {
3107 return array( array( 'readonlytext' ) );
3108 }
3109
3110 // Get the last editor
3111 $current = $this->getRevision();
3112 if ( is_null( $current ) ) {
3113 // Something wrong... no page?
3114 return array( array( 'notanarticle' ) );
3115 }
3116
3117 $from = str_replace( '_', ' ', $fromP );
3118 // User name given should match up with the top revision.
3119 // If the user was deleted then $from should be empty.
3120 if ( $from != $current->getUserText() ) {
3121 $resultDetails = array( 'current' => $current );
3122 return array( array( 'alreadyrolled',
3123 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3124 htmlspecialchars( $fromP ),
3125 htmlspecialchars( $current->getUserText() )
3126 ) );
3127 }
3128
3129 // Get the last edit not by this person...
3130 // Note: these may not be public values
3131 $user = intval( $current->getUser( Revision::RAW ) );
3132 $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3133 $s = $dbw->selectRow( 'revision',
3134 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3135 array( 'rev_page' => $current->getPage(),
3136 "rev_user != {$user} OR rev_user_text != {$user_text}"
3137 ), __METHOD__,
3138 array( 'USE INDEX' => 'page_timestamp',
3139 'ORDER BY' => 'rev_timestamp DESC' )
3140 );
3141 if ( $s === false ) {
3142 // No one else ever edited this page
3143 return array( array( 'cantrollback' ) );
3144 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3145 || $s->rev_deleted & Revision::DELETED_USER
3146 ) {
3147 // Only admins can see this text
3148 return array( array( 'notvisiblerev' ) );
3149 }
3150
3151 // Generate the edit summary if necessary
3152 $target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3153 if ( empty( $summary ) ) {
3154 if ( $from == '' ) { // no public user name
3155 $summary = wfMessage( 'revertpage-nouser' );
3156 } else {
3157 $summary = wfMessage( 'revertpage' );
3158 }
3159 }
3160
3161 // Allow the custom summary to use the same args as the default message
3162 $args = array(
3163 $target->getUserText(), $from, $s->rev_id,
3164 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3165 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3166 );
3167 if ( $summary instanceof Message ) {
3168 $summary = $summary->params( $args )->inContentLanguage()->text();
3169 } else {
3170 $summary = wfMsgReplaceArgs( $summary, $args );
3171 }
3172
3173 // Trim spaces on user supplied text
3174 $summary = trim( $summary );
3175
3176 // Truncate for whole multibyte characters.
3177 $summary = $wgContLang->truncate( $summary, 255 );
3178
3179 // Save
3180 $flags = EDIT_UPDATE;
3181
3182 if ( $guser->isAllowed( 'minoredit' ) ) {
3183 $flags |= EDIT_MINOR;
3184 }
3185
3186 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3187 $flags |= EDIT_FORCE_BOT;
3188 }
3189
3190 // Actually store the edit
3191 $status = $this->doEditContent(
3192 $target->getContent(),
3193 $summary,
3194 $flags,
3195 $target->getId(),
3196 $guser
3197 );
3198
3199 // Set patrolling and bot flag on the edits, which gets rollbacked.
3200 // This is done even on edit failure to have patrolling in that case (bug 62157).
3201 $set = array();
3202 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3203 // Mark all reverted edits as bot
3204 $set['rc_bot'] = 1;
3205 }
3206
3207 if ( $wgUseRCPatrol ) {
3208 // Mark all reverted edits as patrolled
3209 $set['rc_patrolled'] = 1;
3210 }
3211
3212 if ( count( $set ) ) {
3213 $dbw->update( 'recentchanges', $set,
3214 array( /* WHERE */
3215 'rc_cur_id' => $current->getPage(),
3216 'rc_user_text' => $current->getUserText(),
3217 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3218 ),
3219 __METHOD__
3220 );
3221 }
3222
3223 if ( !$status->isOK() ) {
3224 return $status->getErrorsArray();
3225 }
3226
3227 // raise error, when the edit is an edit without a new version
3228 $statusRev = isset( $status->value['revision'] )
3229 ? $status->value['revision']
3230 : null;
3231 if ( !( $statusRev instanceof Revision ) ) {
3232 $resultDetails = array( 'current' => $current );
3233 return array( array( 'alreadyrolled',
3234 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3235 htmlspecialchars( $fromP ),
3236 htmlspecialchars( $current->getUserText() )
3237 ) );
3238 }
3239
3240 $revId = $statusRev->getId();
3241
3242 Hooks::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3243
3244 $resultDetails = array(
3245 'summary' => $summary,
3246 'current' => $current,
3247 'target' => $target,
3248 'newid' => $revId
3249 );
3250
3251 return array();
3252 }
3253
3254 /**
3255 * The onArticle*() functions are supposed to be a kind of hooks
3256 * which should be called whenever any of the specified actions
3257 * are done.
3258 *
3259 * This is a good place to put code to clear caches, for instance.
3260 *
3261 * This is called on page move and undelete, as well as edit
3262 *
3263 * @param Title $title
3264 */
3265 public static function onArticleCreate( Title $title ) {
3266 // Update existence markers on article/talk tabs...
3267 $other = $title->getOtherPage();
3268
3269 $other->purgeSquid();
3270
3271 $title->touchLinks();
3272 $title->purgeSquid();
3273 $title->deleteTitleProtection();
3274 }
3275
3276 /**
3277 * Clears caches when article is deleted
3278 *
3279 * @param Title $title
3280 */
3281 public static function onArticleDelete( Title $title ) {
3282 // Update existence markers on article/talk tabs...
3283 $other = $title->getOtherPage();
3284
3285 $other->purgeSquid();
3286
3287 $title->touchLinks();
3288 $title->purgeSquid();
3289
3290 // File cache
3291 HTMLFileCache::clearFileCache( $title );
3292 InfoAction::invalidateCache( $title );
3293
3294 // Messages
3295 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3296 MessageCache::singleton()->replace( $title->getDBkey(), false );
3297 }
3298
3299 // Images
3300 if ( $title->getNamespace() == NS_FILE ) {
3301 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3302 }
3303
3304 // User talk pages
3305 if ( $title->getNamespace() == NS_USER_TALK ) {
3306 $user = User::newFromName( $title->getText(), false );
3307 if ( $user ) {
3308 $user->setNewtalk( false );
3309 }
3310 }
3311
3312 // Image redirects
3313 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3314 }
3315
3316 /**
3317 * Purge caches on page update etc
3318 *
3319 * @param Title $title
3320 * @param Revision|null $revision Revision that was just saved, may be null
3321 */
3322 public static function onArticleEdit( Title $title, Revision $revision = null ) {
3323 // Invalidate caches of articles which include this page
3324 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3325
3326 // Invalidate the caches of all pages which redirect here
3327 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3328
3329 // Purge CDN for this page only
3330 $title->purgeSquid();
3331 // Clear file cache for this page only
3332 HTMLFileCache::clearFileCache( $title );
3333
3334 $revid = $revision ? $revision->getId() : null;
3335 DeferredUpdates::addCallableUpdate( function() use ( $title, $revid ) {
3336 InfoAction::invalidateCache( $title, $revid );
3337 } );
3338 }
3339
3340 /**#@-*/
3341
3342 /**
3343 * Returns a list of categories this page is a member of.
3344 * Results will include hidden categories
3345 *
3346 * @return TitleArray
3347 */
3348 public function getCategories() {
3349 $id = $this->getId();
3350 if ( $id == 0 ) {
3351 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3352 }
3353
3354 $dbr = wfGetDB( DB_SLAVE );
3355 $res = $dbr->select( 'categorylinks',
3356 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3357 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3358 // as not being aliases, and NS_CATEGORY is numeric
3359 array( 'cl_from' => $id ),
3360 __METHOD__ );
3361
3362 return TitleArray::newFromResult( $res );
3363 }
3364
3365 /**
3366 * Returns a list of hidden categories this page is a member of.
3367 * Uses the page_props and categorylinks tables.
3368 *
3369 * @return array Array of Title objects
3370 */
3371 public function getHiddenCategories() {
3372 $result = array();
3373 $id = $this->getId();
3374
3375 if ( $id == 0 ) {
3376 return array();
3377 }
3378
3379 $dbr = wfGetDB( DB_SLAVE );
3380 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3381 array( 'cl_to' ),
3382 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3383 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3384 __METHOD__ );
3385
3386 if ( $res !== false ) {
3387 foreach ( $res as $row ) {
3388 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3389 }
3390 }
3391
3392 return $result;
3393 }
3394
3395 /**
3396 * Return an applicable autosummary if one exists for the given edit.
3397 * @param string|null $oldtext The previous text of the page.
3398 * @param string|null $newtext The submitted text of the page.
3399 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3400 * @return string An appropriate autosummary, or an empty string.
3401 *
3402 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3403 */
3404 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3405 // NOTE: stub for backwards-compatibility. assumes the given text is
3406 // wikitext. will break horribly if it isn't.
3407
3408 ContentHandler::deprecated( __METHOD__, '1.21' );
3409
3410 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3411 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3412 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3413
3414 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3415 }
3416
3417 /**
3418 * Auto-generates a deletion reason
3419 *
3420 * @param bool &$hasHistory Whether the page has a history
3421 * @return string|bool String containing deletion reason or empty string, or boolean false
3422 * if no revision occurred
3423 */
3424 public function getAutoDeleteReason( &$hasHistory ) {
3425 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3426 }
3427
3428 /**
3429 * Update all the appropriate counts in the category table, given that
3430 * we've added the categories $added and deleted the categories $deleted.
3431 *
3432 * @param array $added The names of categories that were added
3433 * @param array $deleted The names of categories that were deleted
3434 */
3435 public function updateCategoryCounts( array $added, array $deleted ) {
3436 $that = $this;
3437 $method = __METHOD__;
3438 $dbw = wfGetDB( DB_MASTER );
3439
3440 // Do this at the end of the commit to reduce lock wait timeouts
3441 $dbw->onTransactionPreCommitOrIdle(
3442 function () use ( $dbw, $that, $method, $added, $deleted ) {
3443 $ns = $that->getTitle()->getNamespace();
3444
3445 $addFields = array( 'cat_pages = cat_pages + 1' );
3446 $removeFields = array( 'cat_pages = cat_pages - 1' );
3447 if ( $ns == NS_CATEGORY ) {
3448 $addFields[] = 'cat_subcats = cat_subcats + 1';
3449 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3450 } elseif ( $ns == NS_FILE ) {
3451 $addFields[] = 'cat_files = cat_files + 1';
3452 $removeFields[] = 'cat_files = cat_files - 1';
3453 }
3454
3455 if ( count( $added ) ) {
3456 $existingAdded = $dbw->selectFieldValues(
3457 'category',
3458 'cat_title',
3459 array( 'cat_title' => $added ),
3460 __METHOD__
3461 );
3462
3463 // For category rows that already exist, do a plain
3464 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3465 // to avoid creating gaps in the cat_id sequence.
3466 if ( count( $existingAdded ) ) {
3467 $dbw->update(
3468 'category',
3469 $addFields,
3470 array( 'cat_title' => $existingAdded ),
3471 __METHOD__
3472 );
3473 }
3474
3475 $missingAdded = array_diff( $added, $existingAdded );
3476 if ( count( $missingAdded ) ) {
3477 $insertRows = array();
3478 foreach ( $missingAdded as $cat ) {
3479 $insertRows[] = array(
3480 'cat_title' => $cat,
3481 'cat_pages' => 1,
3482 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3483 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3484 );
3485 }
3486 $dbw->upsert(
3487 'category',
3488 $insertRows,
3489 array( 'cat_title' ),
3490 $addFields,
3491 $method
3492 );
3493 }
3494 }
3495
3496 if ( count( $deleted ) ) {
3497 $dbw->update(
3498 'category',
3499 $removeFields,
3500 array( 'cat_title' => $deleted ),
3501 $method
3502 );
3503 }
3504
3505 foreach ( $added as $catName ) {
3506 $cat = Category::newFromName( $catName );
3507 Hooks::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3508 }
3509
3510 foreach ( $deleted as $catName ) {
3511 $cat = Category::newFromName( $catName );
3512 Hooks::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3513 }
3514 }
3515 );
3516 }
3517
3518 /**
3519 * Opportunistically enqueue link update jobs given fresh parser output if useful
3520 *
3521 * @param ParserOutput $parserOutput Current version page output
3522 * @since 1.25
3523 */
3524 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
3525 if ( wfReadOnly() ) {
3526 return;
3527 }
3528
3529 if ( !Hooks::run( 'OpportunisticLinksUpdate',
3530 array( $this, $this->mTitle, $parserOutput )
3531 ) ) {
3532 return;
3533 }
3534
3535 $params = array(
3536 'isOpportunistic' => true,
3537 'rootJobTimestamp' => $parserOutput->getCacheTime()
3538 );
3539
3540 if ( $this->mTitle->areRestrictionsCascading() ) {
3541 // If the page is cascade protecting, the links should really be up-to-date
3542 JobQueueGroup::singleton()->lazyPush(
3543 RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3544 );
3545 } elseif ( $parserOutput->hasDynamicContent() ) {
3546 // Assume the output contains "dynamic" time/random based magic words.
3547 // Only update pages that expired due to dynamic content and NOT due to edits
3548 // to referenced templates/files. When the cache expires due to dynamic content,
3549 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3550 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3551 // template/file edit already triggered recursive RefreshLinksJob jobs.
3552 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3553 // If a page is uncacheable, do not keep spamming a job for it.
3554 // Although it would be de-duplicated, it would still waste I/O.
3555 $cache = ObjectCache::getLocalClusterInstance();
3556 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3557 if ( $cache->add( $key, time(), 60 ) ) {
3558 JobQueueGroup::singleton()->lazyPush(
3559 RefreshLinksJob::newDynamic( $this->mTitle, $params )
3560 );
3561 }
3562 }
3563 }
3564 }
3565
3566 /**
3567 * Returns a list of updates to be performed when this page is deleted. The
3568 * updates should remove any information about this page from secondary data
3569 * stores such as links tables.
3570 *
3571 * @param Content|null $content Optional Content object for determining the
3572 * necessary updates.
3573 * @return DataUpdate[]
3574 */
3575 public function getDeletionUpdates( Content $content = null ) {
3576 if ( !$content ) {
3577 // load content object, which may be used to determine the necessary updates.
3578 // XXX: the content may not be needed to determine the updates.
3579 $content = $this->getContent( Revision::RAW );
3580 }
3581
3582 if ( !$content ) {
3583 $updates = array();
3584 } else {
3585 $updates = $content->getDeletionUpdates( $this );
3586 }
3587
3588 Hooks::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3589 return $updates;
3590 }
3591 }