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