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