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