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