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