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