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