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