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