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