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