Merge "Doc: Document problem sorting inserted data"
[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 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
312
313 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
314
315 wfRunHooks( '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 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 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 ( !wfRunHooks( '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 $serialisation_format 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, $serialisation_format = 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 ( !wfRunHooks( '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, $serialisation_format );
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' => $serialisation_format,
1829 ) ); // XXX: pass content object?!
1830
1831 $changed = !$content->equals( $old_content );
1832
1833 if ( $changed ) {
1834 if ( !$content->isValid() ) {
1835 wfProfileOut( __METHOD__ );
1836 throw new MWException( "New content failed validity check!" );
1837 }
1838
1839 $dbw->begin( __METHOD__ );
1840 try {
1841
1842 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1843 $status->merge( $prepStatus );
1844
1845 if ( !$status->isOK() ) {
1846 $dbw->rollback( __METHOD__ );
1847
1848 wfProfileOut( __METHOD__ );
1849 return $status;
1850 }
1851 $revisionId = $revision->insertOn( $dbw );
1852
1853 // Update page
1854 //
1855 // We check for conflicts by comparing $oldid with the current latest revision ID.
1856 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1857
1858 if ( !$ok ) {
1859 // Belated edit conflict! Run away!!
1860 $status->fatal( 'edit-conflict' );
1861
1862 $dbw->rollback( __METHOD__ );
1863
1864 wfProfileOut( __METHOD__ );
1865 return $status;
1866 }
1867
1868 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1869 // Update recentchanges
1870 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1871 // Mark as patrolled if the user can do so
1872 $patrolled = $wgUseRCPatrol && !count(
1873 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1874 // Add RC row to the DB
1875 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1876 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1877 $revisionId, $patrolled
1878 );
1879
1880 // Log auto-patrolled edits
1881 if ( $patrolled ) {
1882 PatrolLog::record( $rc, true, $user );
1883 }
1884 }
1885 $user->incEditCount();
1886 } catch ( MWException $e ) {
1887 $dbw->rollback( __METHOD__ );
1888 // Question: Would it perhaps be better if this method turned all
1889 // exceptions into $status's?
1890 throw $e;
1891 }
1892 $dbw->commit( __METHOD__ );
1893 } else {
1894 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1895 // related variables correctly
1896 $revision->setId( $this->getLatest() );
1897 }
1898
1899 // Update links tables, site stats, etc.
1900 $this->doEditUpdates(
1901 $revision,
1902 $user,
1903 array(
1904 'changed' => $changed,
1905 'oldcountable' => $oldcountable
1906 )
1907 );
1908
1909 if ( !$changed ) {
1910 $status->warning( 'edit-no-change' );
1911 $revision = null;
1912 // Update page_touched, this is usually implicit in the page update
1913 // Other cache updates are done in onArticleEdit()
1914 $this->mTitle->invalidateCache();
1915 }
1916 } else {
1917 // Create new article
1918 $status->value['new'] = true;
1919
1920 $dbw->begin( __METHOD__ );
1921 try {
1922
1923 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1924 $status->merge( $prepStatus );
1925
1926 if ( !$status->isOK() ) {
1927 $dbw->rollback( __METHOD__ );
1928
1929 wfProfileOut( __METHOD__ );
1930 return $status;
1931 }
1932
1933 $status->merge( $prepStatus );
1934
1935 // Add the page record; stake our claim on this title!
1936 // This will return false if the article already exists
1937 $newid = $this->insertOn( $dbw );
1938
1939 if ( $newid === false ) {
1940 $dbw->rollback( __METHOD__ );
1941 $status->fatal( 'edit-already-exists' );
1942
1943 wfProfileOut( __METHOD__ );
1944 return $status;
1945 }
1946
1947 // Save the revision text...
1948 $revision = new Revision( array(
1949 'page' => $newid,
1950 'title' => $this->getTitle(), // for determining the default content model
1951 'comment' => $summary,
1952 'minor_edit' => $isminor,
1953 'text' => $serialized,
1954 'len' => $newsize,
1955 'user' => $user->getId(),
1956 'user_text' => $user->getName(),
1957 'timestamp' => $now,
1958 'content_model' => $content->getModel(),
1959 'content_format' => $serialisation_format,
1960 ) );
1961 $revisionId = $revision->insertOn( $dbw );
1962
1963 // Bug 37225: use accessor to get the text as Revision may trim it
1964 $content = $revision->getContent(); // sanity; get normalized version
1965
1966 if ( $content ) {
1967 $newsize = $content->getSize();
1968 }
1969
1970 // Update the page record with revision data
1971 $this->updateRevisionOn( $dbw, $revision, 0 );
1972
1973 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1974
1975 // Update recentchanges
1976 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1977 // Mark as patrolled if the user can do so
1978 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1979 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1980 // Add RC row to the DB
1981 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1982 '', $newsize, $revisionId, $patrolled );
1983
1984 // Log auto-patrolled edits
1985 if ( $patrolled ) {
1986 PatrolLog::record( $rc, true, $user );
1987 }
1988 }
1989 $user->incEditCount();
1990
1991 } catch ( MWException $e ) {
1992 $dbw->rollback( __METHOD__ );
1993 throw $e;
1994 }
1995 $dbw->commit( __METHOD__ );
1996
1997 // Update links, etc.
1998 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1999
2000 $hook_args = array( &$this, &$user, $content, $summary,
2001 $flags & EDIT_MINOR, null, null, &$flags, $revision );
2002
2003 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
2004 wfRunHooks( 'PageContentInsertComplete', $hook_args );
2005 }
2006
2007 // Do updates right now unless deferral was requested
2008 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2009 DeferredUpdates::doUpdates();
2010 }
2011
2012 // Return the new revision (or null) to the caller
2013 $status->value['revision'] = $revision;
2014
2015 $hook_args = array( &$this, &$user, $content, $summary,
2016 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId );
2017
2018 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
2019 wfRunHooks( 'PageContentSaveComplete', $hook_args );
2020
2021 // Promote user to any groups they meet the criteria for
2022 $dbw->onTransactionIdle( function () use ( $user ) {
2023 $user->addAutopromoteOnceGroups( 'onEdit' );
2024 } );
2025
2026 wfProfileOut( __METHOD__ );
2027 return $status;
2028 }
2029
2030 /**
2031 * Get parser options suitable for rendering the primary article wikitext
2032 *
2033 * @see ContentHandler::makeParserOptions
2034 *
2035 * @param IContextSource|User|string $context One of the following:
2036 * - IContextSource: Use the User and the Language of the provided
2037 * context
2038 * - User: Use the provided User object and $wgLang for the language,
2039 * so use an IContextSource object if possible.
2040 * - 'canonical': Canonical options (anonymous user with default
2041 * preferences and content language).
2042 * @return ParserOptions
2043 */
2044 public function makeParserOptions( $context ) {
2045 $options = $this->getContentHandler()->makeParserOptions( $context );
2046
2047 if ( $this->getTitle()->isConversionTable() ) {
2048 // @todo ConversionTable should become a separate content model, so
2049 // we don't need special cases like this one.
2050 $options->disableContentConversion();
2051 }
2052
2053 return $options;
2054 }
2055
2056 /**
2057 * Prepare text which is about to be saved.
2058 * Returns a stdclass with source, pst and output members
2059 *
2060 * @deprecated since 1.21: use prepareContentForEdit instead.
2061 * @return object
2062 */
2063 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2064 ContentHandler::deprecated( __METHOD__, '1.21' );
2065 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2066 return $this->prepareContentForEdit( $content, $revid, $user );
2067 }
2068
2069 /**
2070 * Prepare content which is about to be saved.
2071 * Returns a stdclass with source, pst and output members
2072 *
2073 * @param Content $content
2074 * @param int|null $revid
2075 * @param User|null $user
2076 * @param string|null $serialization_format
2077 *
2078 * @return bool|object
2079 *
2080 * @since 1.21
2081 */
2082 public function prepareContentForEdit( Content $content, $revid = null, User $user = null,
2083 $serialization_format = null
2084 ) {
2085 global $wgContLang, $wgUser;
2086 $user = is_null( $user ) ? $wgUser : $user;
2087 //XXX: check $user->getId() here???
2088
2089 // Use a sane default for $serialization_format, see bug 57026
2090 if ( $serialization_format === null ) {
2091 $serialization_format = $content->getContentHandler()->getDefaultFormat();
2092 }
2093
2094 if ( $this->mPreparedEdit
2095 && $this->mPreparedEdit->newContent
2096 && $this->mPreparedEdit->newContent->equals( $content )
2097 && $this->mPreparedEdit->revid == $revid
2098 && $this->mPreparedEdit->format == $serialization_format
2099 // XXX: also check $user here?
2100 ) {
2101 // Already prepared
2102 return $this->mPreparedEdit;
2103 }
2104
2105 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2106 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2107
2108 $edit = (object)array();
2109 $edit->revid = $revid;
2110 $edit->timestamp = wfTimestampNow();
2111
2112 $edit->pstContent = $content ? $content->preSaveTransform( $this->mTitle, $user, $popts ) : null;
2113
2114 $edit->format = $serialization_format;
2115 $edit->popts = $this->makeParserOptions( 'canonical' );
2116 $edit->output = $edit->pstContent
2117 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2118 : null;
2119
2120 $edit->newContent = $content;
2121 $edit->oldContent = $this->getContent( Revision::RAW );
2122
2123 // NOTE: B/C for hooks! don't use these fields!
2124 $edit->newText = $edit->newContent ? ContentHandler::getContentText( $edit->newContent ) : '';
2125 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : '';
2126 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialization_format ) : '';
2127
2128 $this->mPreparedEdit = $edit;
2129 return $edit;
2130 }
2131
2132 /**
2133 * Do standard deferred updates after page edit.
2134 * Update links tables, site stats, search index and message cache.
2135 * Purges pages that include this page if the text was changed here.
2136 * Every 100th edit, prune the recent changes table.
2137 *
2138 * @param Revision $revision
2139 * @param User $user User object that did the revision
2140 * @param array $options Array of options, following indexes are used:
2141 * - changed: boolean, whether the revision changed the content (default true)
2142 * - created: boolean, whether the revision created the page (default false)
2143 * - moved: boolean, whether the page was moved (default false)
2144 * - oldcountable: boolean or null (default null):
2145 * - boolean: whether the page was counted as an article before that
2146 * revision, only used in changed is true and created is false
2147 * - null: don't change the article count
2148 */
2149 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2150 global $wgEnableParserCache;
2151
2152 wfProfileIn( __METHOD__ );
2153
2154 $options += array(
2155 'changed' => true,
2156 'created' => false,
2157 'moved' => false,
2158 'oldcountable' => null
2159 );
2160 $content = $revision->getContent();
2161
2162 // Parse the text
2163 // Be careful not to do pre-save transform twice: $text is usually
2164 // already pre-save transformed once.
2165 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2166 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2167 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2168 } else {
2169 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2170 $editInfo = $this->mPreparedEdit;
2171 }
2172
2173 // Save it to the parser cache
2174 if ( $wgEnableParserCache ) {
2175 $parserCache = ParserCache::singleton();
2176 $parserCache->save(
2177 $editInfo->output, $this, $editInfo->popts, $editInfo->timestamp, $editInfo->revid
2178 );
2179 }
2180
2181 // Update the links tables and other secondary data
2182 if ( $content ) {
2183 $recursive = $options['changed']; // bug 50785
2184 $updates = $content->getSecondaryDataUpdates(
2185 $this->getTitle(), null, $recursive, $editInfo->output );
2186 DataUpdate::runUpdates( $updates );
2187 }
2188
2189 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2190
2191 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2192 if ( 0 == mt_rand( 0, 99 ) ) {
2193 // Flush old entries from the `recentchanges` table; we do this on
2194 // random requests so as to avoid an increase in writes for no good reason
2195 RecentChange::purgeExpiredChanges();
2196 }
2197 }
2198
2199 if ( !$this->exists() ) {
2200 wfProfileOut( __METHOD__ );
2201 return;
2202 }
2203
2204 $id = $this->getId();
2205 $title = $this->mTitle->getPrefixedDBkey();
2206 $shortTitle = $this->mTitle->getDBkey();
2207
2208 if ( !$options['changed'] && !$options['moved'] ) {
2209 $good = 0;
2210 } elseif ( $options['created'] ) {
2211 $good = (int)$this->isCountable( $editInfo );
2212 } elseif ( $options['oldcountable'] !== null ) {
2213 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2214 } else {
2215 $good = 0;
2216 }
2217 $edits = $options['changed'] ? 1 : 0;
2218 $total = $options['created'] ? 1 : 0;
2219
2220 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2221 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2222
2223 // If this is another user's talk page, update newtalk.
2224 // Don't do this if $options['changed'] = false (null-edits) nor if
2225 // it's a minor edit and the user doesn't want notifications for those.
2226 if ( $options['changed']
2227 && $this->mTitle->getNamespace() == NS_USER_TALK
2228 && $shortTitle != $user->getTitleKey()
2229 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2230 ) {
2231 $recipient = User::newFromName( $shortTitle, false );
2232 if ( !$recipient ) {
2233 wfDebug( __METHOD__ . ": invalid username\n" );
2234 } else {
2235 // Allow extensions to prevent user notification when a new message is added to their talk page
2236 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2237 if ( User::isIP( $shortTitle ) ) {
2238 // An anonymous user
2239 $recipient->setNewtalk( true, $revision );
2240 } elseif ( $recipient->isLoggedIn() ) {
2241 $recipient->setNewtalk( true, $revision );
2242 } else {
2243 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2244 }
2245 }
2246 }
2247 }
2248
2249 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2250 // XXX: could skip pseudo-messages like js/css here, based on content model.
2251 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2252 if ( $msgtext === false || $msgtext === null ) {
2253 $msgtext = '';
2254 }
2255
2256 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2257 }
2258
2259 if ( $options['created'] ) {
2260 self::onArticleCreate( $this->mTitle );
2261 } elseif ( $options['changed'] ) { // bug 50785
2262 self::onArticleEdit( $this->mTitle );
2263 }
2264
2265 wfProfileOut( __METHOD__ );
2266 }
2267
2268 /**
2269 * Edit an article without doing all that other stuff
2270 * The article must already exist; link tables etc
2271 * are not updated, caches are not flushed.
2272 *
2273 * @param string $text Text submitted
2274 * @param User $user The relevant user
2275 * @param string $comment Comment submitted
2276 * @param bool $minor Whereas it's a minor modification
2277 *
2278 * @deprecated since 1.21, use doEditContent() instead.
2279 */
2280 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2281 ContentHandler::deprecated( __METHOD__, "1.21" );
2282
2283 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2284 $this->doQuickEditContent( $content, $user, $comment, $minor );
2285 }
2286
2287 /**
2288 * Edit an article without doing all that other stuff
2289 * The article must already exist; link tables etc
2290 * are not updated, caches are not flushed.
2291 *
2292 * @param Content $content Content submitted
2293 * @param User $user The relevant user
2294 * @param string $comment Comment submitted
2295 * @param bool $minor Whereas it's a minor modification
2296 * @param string $serialisation_format Format for storing the content in the database
2297 */
2298 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = false,
2299 $serialisation_format = null
2300 ) {
2301 wfProfileIn( __METHOD__ );
2302
2303 $serialized = $content->serialize( $serialisation_format );
2304
2305 $dbw = wfGetDB( DB_MASTER );
2306 $revision = new Revision( array(
2307 'title' => $this->getTitle(), // for determining the default content model
2308 'page' => $this->getId(),
2309 'user_text' => $user->getName(),
2310 'user' => $user->getId(),
2311 'text' => $serialized,
2312 'length' => $content->getSize(),
2313 'comment' => $comment,
2314 'minor_edit' => $minor ? 1 : 0,
2315 ) ); // XXX: set the content object?
2316 $revision->insertOn( $dbw );
2317 $this->updateRevisionOn( $dbw, $revision );
2318
2319 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2320
2321 wfProfileOut( __METHOD__ );
2322 }
2323
2324 /**
2325 * Update the article's restriction field, and leave a log entry.
2326 * This works for protection both existing and non-existing pages.
2327 *
2328 * @param array $limit Set of restriction keys
2329 * @param array $expiry Per restriction type expiration
2330 * @param int &$cascade Set to false if cascading protection isn't allowed.
2331 * @param string $reason
2332 * @param User $user The user updating the restrictions
2333 * @return Status
2334 */
2335 public function doUpdateRestrictions( array $limit, array $expiry,
2336 &$cascade, $reason, User $user
2337 ) {
2338 global $wgCascadingRestrictionLevels, $wgContLang;
2339
2340 if ( wfReadOnly() ) {
2341 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2342 }
2343
2344 $this->loadPageData( 'fromdbmaster' );
2345 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2346 $id = $this->getId();
2347
2348 if ( !$cascade ) {
2349 $cascade = false;
2350 }
2351
2352 // Take this opportunity to purge out expired restrictions
2353 Title::purgeExpiredRestrictions();
2354
2355 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2356 // we expect a single selection, but the schema allows otherwise.
2357 $isProtected = false;
2358 $protect = false;
2359 $changed = false;
2360
2361 $dbw = wfGetDB( DB_MASTER );
2362
2363 foreach ( $restrictionTypes as $action ) {
2364 if ( !isset( $expiry[$action] ) ) {
2365 $expiry[$action] = $dbw->getInfinity();
2366 }
2367 if ( !isset( $limit[$action] ) ) {
2368 $limit[$action] = '';
2369 } elseif ( $limit[$action] != '' ) {
2370 $protect = true;
2371 }
2372
2373 // Get current restrictions on $action
2374 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2375 if ( $current != '' ) {
2376 $isProtected = true;
2377 }
2378
2379 if ( $limit[$action] != $current ) {
2380 $changed = true;
2381 } elseif ( $limit[$action] != '' ) {
2382 // Only check expiry change if the action is actually being
2383 // protected, since expiry does nothing on an not-protected
2384 // action.
2385 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2386 $changed = true;
2387 }
2388 }
2389 }
2390
2391 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2392 $changed = true;
2393 }
2394
2395 // If nothing has changed, do nothing
2396 if ( !$changed ) {
2397 return Status::newGood();
2398 }
2399
2400 if ( !$protect ) { // No protection at all means unprotection
2401 $revCommentMsg = 'unprotectedarticle';
2402 $logAction = 'unprotect';
2403 } elseif ( $isProtected ) {
2404 $revCommentMsg = 'modifiedarticleprotection';
2405 $logAction = 'modify';
2406 } else {
2407 $revCommentMsg = 'protectedarticle';
2408 $logAction = 'protect';
2409 }
2410
2411 // Truncate for whole multibyte characters
2412 $reason = $wgContLang->truncate( $reason, 255 );
2413
2414 $logRelationsValues = array();
2415 $logRelationsField = null;
2416
2417 if ( $id ) { // Protection of existing page
2418 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2419 return Status::newGood();
2420 }
2421
2422 // Only certain restrictions can cascade...
2423 $editrestriction = isset( $limit['edit'] )
2424 ? array( $limit['edit'] )
2425 : $this->mTitle->getRestrictions( 'edit' );
2426 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2427 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2428 }
2429 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2430 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2431 }
2432
2433 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2434 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2435 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2436 }
2437 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2438 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2439 }
2440
2441 // The schema allows multiple restrictions
2442 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2443 $cascade = false;
2444 }
2445
2446 // insert null revision to identify the page protection change as edit summary
2447 $latest = $this->getLatest();
2448 $nullRevision = $this->insertProtectNullRevision(
2449 $revCommentMsg,
2450 $limit,
2451 $expiry,
2452 $cascade,
2453 $reason,
2454 $user
2455 );
2456
2457 if ( $nullRevision === null ) {
2458 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2459 }
2460
2461 $logRelationsField = 'pr_id';
2462
2463 // Update restrictions table
2464 foreach ( $limit as $action => $restrictions ) {
2465 $dbw->delete(
2466 'page_restrictions',
2467 array(
2468 'pr_page' => $id,
2469 'pr_type' => $action
2470 ),
2471 __METHOD__
2472 );
2473 if ( $restrictions != '' ) {
2474 $dbw->insert(
2475 'page_restrictions',
2476 array(
2477 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2478 'pr_page' => $id,
2479 'pr_type' => $action,
2480 'pr_level' => $restrictions,
2481 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2482 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2483 ),
2484 __METHOD__
2485 );
2486 $logRelationsValues[] = $dbw->insertId();
2487 }
2488 }
2489
2490 // Clear out legacy restriction fields
2491 $dbw->update(
2492 'page',
2493 array( 'page_restrictions' => '' ),
2494 array( 'page_id' => $id ),
2495 __METHOD__
2496 );
2497
2498 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2499 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2500 } else { // Protection of non-existing page (also known as "title protection")
2501 // Cascade protection is meaningless in this case
2502 $cascade = false;
2503
2504 if ( $limit['create'] != '' ) {
2505 $dbw->replace( 'protected_titles',
2506 array( array( 'pt_namespace', 'pt_title' ) ),
2507 array(
2508 'pt_namespace' => $this->mTitle->getNamespace(),
2509 'pt_title' => $this->mTitle->getDBkey(),
2510 'pt_create_perm' => $limit['create'],
2511 'pt_timestamp' => $dbw->timestamp(),
2512 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2513 'pt_user' => $user->getId(),
2514 'pt_reason' => $reason,
2515 ), __METHOD__
2516 );
2517 } else {
2518 $dbw->delete( 'protected_titles',
2519 array(
2520 'pt_namespace' => $this->mTitle->getNamespace(),
2521 'pt_title' => $this->mTitle->getDBkey()
2522 ), __METHOD__
2523 );
2524 }
2525 }
2526
2527 $this->mTitle->flushRestrictions();
2528 InfoAction::invalidateCache( $this->mTitle );
2529
2530 if ( $logAction == 'unprotect' ) {
2531 $params = array();
2532 } else {
2533 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2534 $params = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2535 }
2536
2537 // Update the protection log
2538 $log = new LogPage( 'protect' );
2539 $logId = $log->addEntry( $logAction, $this->mTitle, $reason, $params, $user );
2540 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2541 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2542 }
2543
2544 return Status::newGood();
2545 }
2546
2547 /**
2548 * Insert a new null revision for this page.
2549 *
2550 * @param string $revCommentMsg Comment message key for the revision
2551 * @param array $limit Set of restriction keys
2552 * @param array $expiry Per restriction type expiration
2553 * @param int $cascade Set to false if cascading protection isn't allowed.
2554 * @param string $reason
2555 * @param User|null $user
2556 * @return Revision|null Null on error
2557 */
2558 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2559 array $expiry, $cascade, $reason, $user = null
2560 ) {
2561 global $wgContLang;
2562 $dbw = wfGetDB( DB_MASTER );
2563
2564 // Prepare a null revision to be added to the history
2565 $editComment = $wgContLang->ucfirst(
2566 wfMessage(
2567 $revCommentMsg,
2568 $this->mTitle->getPrefixedText()
2569 )->inContentLanguage()->text()
2570 );
2571 if ( $reason ) {
2572 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2573 }
2574 $protectDescription = $this->protectDescription( $limit, $expiry );
2575 if ( $protectDescription ) {
2576 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2577 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2578 ->inContentLanguage()->text();
2579 }
2580 if ( $cascade ) {
2581 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2582 $editComment .= wfMessage( 'brackets' )->params(
2583 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2584 )->inContentLanguage()->text();
2585 }
2586
2587 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2588 if ( $nullRev ) {
2589 $nullRev->insertOn( $dbw );
2590
2591 // Update page record and touch page
2592 $oldLatest = $nullRev->getParentId();
2593 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2594 }
2595
2596 return $nullRev;
2597 }
2598
2599 /**
2600 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2601 * @return string
2602 */
2603 protected function formatExpiry( $expiry ) {
2604 global $wgContLang;
2605 $dbr = wfGetDB( DB_SLAVE );
2606
2607 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2608 if ( $encodedExpiry != 'infinity' ) {
2609 return wfMessage(
2610 'protect-expiring',
2611 $wgContLang->timeanddate( $expiry, false, false ),
2612 $wgContLang->date( $expiry, false, false ),
2613 $wgContLang->time( $expiry, false, false )
2614 )->inContentLanguage()->text();
2615 } else {
2616 return wfMessage( 'protect-expiry-indefinite' )
2617 ->inContentLanguage()->text();
2618 }
2619 }
2620
2621 /**
2622 * Builds the description to serve as comment for the edit.
2623 *
2624 * @param array $limit Set of restriction keys
2625 * @param array $expiry Per restriction type expiration
2626 * @return string
2627 */
2628 public function protectDescription( array $limit, array $expiry ) {
2629 $protectDescription = '';
2630
2631 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2632 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2633 # All possible message keys are listed here for easier grepping:
2634 # * restriction-create
2635 # * restriction-edit
2636 # * restriction-move
2637 # * restriction-upload
2638 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2639 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2640 # with '' filtered out. All possible message keys are listed below:
2641 # * protect-level-autoconfirmed
2642 # * protect-level-sysop
2643 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2644
2645 $expiryText = $this->formatExpiry( $expiry[$action] );
2646
2647 if ( $protectDescription !== '' ) {
2648 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2649 }
2650 $protectDescription .= wfMessage( 'protect-summary-desc' )
2651 ->params( $actionText, $restrictionsText, $expiryText )
2652 ->inContentLanguage()->text();
2653 }
2654
2655 return $protectDescription;
2656 }
2657
2658 /**
2659 * Builds the description to serve as comment for the log entry.
2660 *
2661 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2662 * protect description text. Keep them in old format to avoid breaking compatibility.
2663 * TODO: Fix protection log to store structured description and format it on-the-fly.
2664 *
2665 * @param array $limit Set of restriction keys
2666 * @param array $expiry Per restriction type expiration
2667 * @return string
2668 */
2669 public function protectDescriptionLog( array $limit, array $expiry ) {
2670 global $wgContLang;
2671
2672 $protectDescriptionLog = '';
2673
2674 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2675 $expiryText = $this->formatExpiry( $expiry[$action] );
2676 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2677 }
2678
2679 return trim( $protectDescriptionLog );
2680 }
2681
2682 /**
2683 * Take an array of page restrictions and flatten it to a string
2684 * suitable for insertion into the page_restrictions field.
2685 *
2686 * @param string[] $limit
2687 *
2688 * @throws MWException
2689 * @return string
2690 */
2691 protected static function flattenRestrictions( $limit ) {
2692 if ( !is_array( $limit ) ) {
2693 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2694 }
2695
2696 $bits = array();
2697 ksort( $limit );
2698
2699 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2700 $bits[] = "$action=$restrictions";
2701 }
2702
2703 return implode( ':', $bits );
2704 }
2705
2706 /**
2707 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2708 * backwards compatibility, if you care about error reporting you should use
2709 * doDeleteArticleReal() instead.
2710 *
2711 * Deletes the article with database consistency, writes logs, purges caches
2712 *
2713 * @param string $reason Delete reason for deletion log
2714 * @param bool $suppress Suppress all revisions and log the deletion in
2715 * the suppression log instead of the deletion log
2716 * @param int $id Article ID
2717 * @param bool $commit Defaults to true, triggers transaction end
2718 * @param array &$error Array of errors to append to
2719 * @param User $user The deleting user
2720 * @return bool True if successful
2721 */
2722 public function doDeleteArticle(
2723 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2724 ) {
2725 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2726 return $status->isGood();
2727 }
2728
2729 /**
2730 * Back-end article deletion
2731 * Deletes the article with database consistency, writes logs, purges caches
2732 *
2733 * @since 1.19
2734 *
2735 * @param string $reason Delete reason for deletion log
2736 * @param bool $suppress Suppress all revisions and log the deletion in
2737 * the suppression log instead of the deletion log
2738 * @param int $id Article ID
2739 * @param bool $commit Defaults to true, triggers transaction end
2740 * @param array &$error Array of errors to append to
2741 * @param User $user The deleting user
2742 * @return Status Status object; if successful, $status->value is the log_id of the
2743 * deletion log entry. If the page couldn't be deleted because it wasn't
2744 * found, $status is a non-fatal 'cannotdelete' error
2745 */
2746 public function doDeleteArticleReal(
2747 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2748 ) {
2749 global $wgUser, $wgContentHandlerUseDB;
2750
2751 wfDebug( __METHOD__ . "\n" );
2752
2753 $status = Status::newGood();
2754
2755 if ( $this->mTitle->getDBkey() === '' ) {
2756 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2757 return $status;
2758 }
2759
2760 $user = is_null( $user ) ? $wgUser : $user;
2761 if ( !wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2762 if ( $status->isOK() ) {
2763 // Hook aborted but didn't set a fatal status
2764 $status->fatal( 'delete-hook-aborted' );
2765 }
2766 return $status;
2767 }
2768
2769 $dbw = wfGetDB( DB_MASTER );
2770 $dbw->begin( __METHOD__ );
2771
2772 if ( $id == 0 ) {
2773 $this->loadPageData( 'forupdate' );
2774 $id = $this->getID();
2775 if ( $id == 0 ) {
2776 $dbw->rollback( __METHOD__ );
2777 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2778 return $status;
2779 }
2780 }
2781
2782 // we need to remember the old content so we can use it to generate all deletion updates.
2783 $content = $this->getContent( Revision::RAW );
2784
2785 // Bitfields to further suppress the content
2786 if ( $suppress ) {
2787 $bitfield = 0;
2788 // This should be 15...
2789 $bitfield |= Revision::DELETED_TEXT;
2790 $bitfield |= Revision::DELETED_COMMENT;
2791 $bitfield |= Revision::DELETED_USER;
2792 $bitfield |= Revision::DELETED_RESTRICTED;
2793 } else {
2794 $bitfield = 'rev_deleted';
2795 }
2796
2797 // For now, shunt the revision data into the archive table.
2798 // Text is *not* removed from the text table; bulk storage
2799 // is left intact to avoid breaking block-compression or
2800 // immutable storage schemes.
2801 //
2802 // For backwards compatibility, note that some older archive
2803 // table entries will have ar_text and ar_flags fields still.
2804 //
2805 // In the future, we may keep revisions and mark them with
2806 // the rev_deleted field, which is reserved for this purpose.
2807
2808 $row = array(
2809 'ar_namespace' => 'page_namespace',
2810 'ar_title' => 'page_title',
2811 'ar_comment' => 'rev_comment',
2812 'ar_user' => 'rev_user',
2813 'ar_user_text' => 'rev_user_text',
2814 'ar_timestamp' => 'rev_timestamp',
2815 'ar_minor_edit' => 'rev_minor_edit',
2816 'ar_rev_id' => 'rev_id',
2817 'ar_parent_id' => 'rev_parent_id',
2818 'ar_text_id' => 'rev_text_id',
2819 'ar_text' => '\'\'', // Be explicit to appease
2820 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2821 'ar_len' => 'rev_len',
2822 'ar_page_id' => 'page_id',
2823 'ar_deleted' => $bitfield,
2824 'ar_sha1' => 'rev_sha1',
2825 );
2826
2827 if ( $wgContentHandlerUseDB ) {
2828 $row['ar_content_model'] = 'rev_content_model';
2829 $row['ar_content_format'] = 'rev_content_format';
2830 }
2831
2832 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2833 $row,
2834 array(
2835 'page_id' => $id,
2836 'page_id = rev_page'
2837 ), __METHOD__
2838 );
2839
2840 // Now that it's safely backed up, delete it
2841 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2842 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2843
2844 if ( !$ok ) {
2845 $dbw->rollback( __METHOD__ );
2846 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2847 return $status;
2848 }
2849
2850 if ( !$dbw->cascadingDeletes() ) {
2851 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2852 }
2853
2854 // Clone the title, so we have the information we need when we log
2855 $logTitle = clone $this->mTitle;
2856
2857 // Log the deletion, if the page was suppressed, log it at Oversight instead
2858 $logtype = $suppress ? 'suppress' : 'delete';
2859
2860 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2861 $logEntry->setPerformer( $user );
2862 $logEntry->setTarget( $logTitle );
2863 $logEntry->setComment( $reason );
2864 $logid = $logEntry->insert();
2865
2866 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2867 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2868 $logEntry->publish( $logid );
2869 } );
2870
2871 if ( $commit ) {
2872 $dbw->commit( __METHOD__ );
2873 }
2874
2875 $this->doDeleteUpdates( $id, $content );
2876
2877 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2878 $status->value = $logid;
2879 return $status;
2880 }
2881
2882 /**
2883 * Do some database updates after deletion
2884 *
2885 * @param int $id The page_id value of the page being deleted
2886 * @param Content $content Optional page content to be used when determining
2887 * the required updates. This may be needed because $this->getContent()
2888 * may already return null when the page proper was deleted.
2889 */
2890 public function doDeleteUpdates( $id, Content $content = null ) {
2891 // update site status
2892 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2893
2894 // remove secondary indexes, etc
2895 $updates = $this->getDeletionUpdates( $content );
2896 DataUpdate::runUpdates( $updates );
2897
2898 // Reparse any pages transcluding this page
2899 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2900
2901 // Reparse any pages including this image
2902 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2903 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2904 }
2905
2906 // Clear caches
2907 WikiPage::onArticleDelete( $this->mTitle );
2908
2909 // Reset this object and the Title object
2910 $this->loadFromRow( false, self::READ_LATEST );
2911
2912 // Search engine
2913 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2914 }
2915
2916 /**
2917 * Roll back the most recent consecutive set of edits to a page
2918 * from the same user; fails if there are no eligible edits to
2919 * roll back to, e.g. user is the sole contributor. This function
2920 * performs permissions checks on $user, then calls commitRollback()
2921 * to do the dirty work
2922 *
2923 * @todo Separate the business/permission stuff out from backend code
2924 *
2925 * @param string $fromP Name of the user whose edits to rollback.
2926 * @param string $summary Custom summary. Set to default summary if empty.
2927 * @param string $token Rollback token.
2928 * @param bool $bot If true, mark all reverted edits as bot.
2929 *
2930 * @param array $resultDetails Array contains result-specific array of additional values
2931 * 'alreadyrolled' : 'current' (rev)
2932 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2933 *
2934 * @param User $user The user performing the rollback
2935 * @return array Array of errors, each error formatted as
2936 * array(messagekey, param1, param2, ...).
2937 * On success, the array is empty. This array can also be passed to
2938 * OutputPage::showPermissionsErrorPage().
2939 */
2940 public function doRollback(
2941 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2942 ) {
2943 $resultDetails = null;
2944
2945 // Check permissions
2946 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2947 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2948 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2949
2950 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2951 $errors[] = array( 'sessionfailure' );
2952 }
2953
2954 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2955 $errors[] = array( 'actionthrottledtext' );
2956 }
2957
2958 // If there were errors, bail out now
2959 if ( !empty( $errors ) ) {
2960 return $errors;
2961 }
2962
2963 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2964 }
2965
2966 /**
2967 * Backend implementation of doRollback(), please refer there for parameter
2968 * and return value documentation
2969 *
2970 * NOTE: This function does NOT check ANY permissions, it just commits the
2971 * rollback to the DB. Therefore, you should only call this function direct-
2972 * ly if you want to use custom permissions checks. If you don't, use
2973 * doRollback() instead.
2974 * @param string $fromP Name of the user whose edits to rollback.
2975 * @param string $summary Custom summary. Set to default summary if empty.
2976 * @param bool $bot If true, mark all reverted edits as bot.
2977 *
2978 * @param array $resultDetails Contains result-specific array of additional values
2979 * @param User $guser The user performing the rollback
2980 * @return array
2981 */
2982 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2983 global $wgUseRCPatrol, $wgContLang;
2984
2985 $dbw = wfGetDB( DB_MASTER );
2986
2987 if ( wfReadOnly() ) {
2988 return array( array( 'readonlytext' ) );
2989 }
2990
2991 // Get the last editor
2992 $current = $this->getRevision();
2993 if ( is_null( $current ) ) {
2994 // Something wrong... no page?
2995 return array( array( 'notanarticle' ) );
2996 }
2997
2998 $from = str_replace( '_', ' ', $fromP );
2999 // User name given should match up with the top revision.
3000 // If the user was deleted then $from should be empty.
3001 if ( $from != $current->getUserText() ) {
3002 $resultDetails = array( 'current' => $current );
3003 return array( array( 'alreadyrolled',
3004 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3005 htmlspecialchars( $fromP ),
3006 htmlspecialchars( $current->getUserText() )
3007 ) );
3008 }
3009
3010 // Get the last edit not by this guy...
3011 // Note: these may not be public values
3012 $user = intval( $current->getRawUser() );
3013 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3014 $s = $dbw->selectRow( 'revision',
3015 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3016 array( 'rev_page' => $current->getPage(),
3017 "rev_user != {$user} OR rev_user_text != {$user_text}"
3018 ), __METHOD__,
3019 array( 'USE INDEX' => 'page_timestamp',
3020 'ORDER BY' => 'rev_timestamp DESC' )
3021 );
3022 if ( $s === false ) {
3023 // No one else ever edited this page
3024 return array( array( 'cantrollback' ) );
3025 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3026 || $s->rev_deleted & Revision::DELETED_USER
3027 ) {
3028 // Only admins can see this text
3029 return array( array( 'notvisiblerev' ) );
3030 }
3031
3032 // Set patrolling and bot flag on the edits, which gets rollbacked.
3033 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3034 $set = array();
3035 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3036 // Mark all reverted edits as bot
3037 $set['rc_bot'] = 1;
3038 }
3039
3040 if ( $wgUseRCPatrol ) {
3041 // Mark all reverted edits as patrolled
3042 $set['rc_patrolled'] = 1;
3043 }
3044
3045 if ( count( $set ) ) {
3046 $dbw->update( 'recentchanges', $set,
3047 array( /* WHERE */
3048 'rc_cur_id' => $current->getPage(),
3049 'rc_user_text' => $current->getUserText(),
3050 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3051 ), __METHOD__
3052 );
3053 }
3054
3055 // Generate the edit summary if necessary
3056 $target = Revision::newFromId( $s->rev_id );
3057 if ( empty( $summary ) ) {
3058 if ( $from == '' ) { // no public user name
3059 $summary = wfMessage( 'revertpage-nouser' );
3060 } else {
3061 $summary = wfMessage( 'revertpage' );
3062 }
3063 }
3064
3065 // Allow the custom summary to use the same args as the default message
3066 $args = array(
3067 $target->getUserText(), $from, $s->rev_id,
3068 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3069 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3070 );
3071 if ( $summary instanceof Message ) {
3072 $summary = $summary->params( $args )->inContentLanguage()->text();
3073 } else {
3074 $summary = wfMsgReplaceArgs( $summary, $args );
3075 }
3076
3077 // Trim spaces on user supplied text
3078 $summary = trim( $summary );
3079
3080 // Truncate for whole multibyte characters.
3081 $summary = $wgContLang->truncate( $summary, 255 );
3082
3083 // Save
3084 $flags = EDIT_UPDATE;
3085
3086 if ( $guser->isAllowed( 'minoredit' ) ) {
3087 $flags |= EDIT_MINOR;
3088 }
3089
3090 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3091 $flags |= EDIT_FORCE_BOT;
3092 }
3093
3094 // Actually store the edit
3095 $status = $this->doEditContent(
3096 $target->getContent(),
3097 $summary,
3098 $flags,
3099 $target->getId(),
3100 $guser
3101 );
3102
3103 if ( !$status->isOK() ) {
3104 return $status->getErrorsArray();
3105 }
3106
3107 // raise error, when the edit is an edit without a new version
3108 if ( empty( $status->value['revision'] ) ) {
3109 $resultDetails = array( 'current' => $current );
3110 return array( array( 'alreadyrolled',
3111 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3112 htmlspecialchars( $fromP ),
3113 htmlspecialchars( $current->getUserText() )
3114 ) );
3115 }
3116
3117 $revId = $status->value['revision']->getId();
3118
3119 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3120
3121 $resultDetails = array(
3122 'summary' => $summary,
3123 'current' => $current,
3124 'target' => $target,
3125 'newid' => $revId
3126 );
3127
3128 return array();
3129 }
3130
3131 /**
3132 * The onArticle*() functions are supposed to be a kind of hooks
3133 * which should be called whenever any of the specified actions
3134 * are done.
3135 *
3136 * This is a good place to put code to clear caches, for instance.
3137 *
3138 * This is called on page move and undelete, as well as edit
3139 *
3140 * @param Title $title
3141 */
3142 public static function onArticleCreate( $title ) {
3143 // Update existence markers on article/talk tabs...
3144 if ( $title->isTalkPage() ) {
3145 $other = $title->getSubjectPage();
3146 } else {
3147 $other = $title->getTalkPage();
3148 }
3149
3150 $other->invalidateCache();
3151 $other->purgeSquid();
3152
3153 $title->touchLinks();
3154 $title->purgeSquid();
3155 $title->deleteTitleProtection();
3156 }
3157
3158 /**
3159 * Clears caches when article is deleted
3160 *
3161 * @param Title $title
3162 */
3163 public static function onArticleDelete( $title ) {
3164 // Update existence markers on article/talk tabs...
3165 if ( $title->isTalkPage() ) {
3166 $other = $title->getSubjectPage();
3167 } else {
3168 $other = $title->getTalkPage();
3169 }
3170
3171 $other->invalidateCache();
3172 $other->purgeSquid();
3173
3174 $title->touchLinks();
3175 $title->purgeSquid();
3176
3177 // File cache
3178 HTMLFileCache::clearFileCache( $title );
3179 InfoAction::invalidateCache( $title );
3180
3181 // Messages
3182 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3183 MessageCache::singleton()->replace( $title->getDBkey(), false );
3184 }
3185
3186 // Images
3187 if ( $title->getNamespace() == NS_FILE ) {
3188 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3189 $update->doUpdate();
3190 }
3191
3192 // User talk pages
3193 if ( $title->getNamespace() == NS_USER_TALK ) {
3194 $user = User::newFromName( $title->getText(), false );
3195 if ( $user ) {
3196 $user->setNewtalk( false );
3197 }
3198 }
3199
3200 // Image redirects
3201 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3202 }
3203
3204 /**
3205 * Purge caches on page update etc
3206 *
3207 * @param Title $title
3208 * @todo Verify that $title is always a Title object (and never false or
3209 * null), add Title hint to parameter $title.
3210 */
3211 public static function onArticleEdit( $title ) {
3212 // Invalidate caches of articles which include this page
3213 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
3214
3215 // Invalidate the caches of all pages which redirect here
3216 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
3217
3218 // Purge squid for this page only
3219 $title->purgeSquid();
3220
3221 // Clear file cache for this page only
3222 HTMLFileCache::clearFileCache( $title );
3223 InfoAction::invalidateCache( $title );
3224 }
3225
3226 /**#@-*/
3227
3228 /**
3229 * Returns a list of categories this page is a member of.
3230 * Results will include hidden categories
3231 *
3232 * @return TitleArray
3233 */
3234 public function getCategories() {
3235 $id = $this->getId();
3236 if ( $id == 0 ) {
3237 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3238 }
3239
3240 $dbr = wfGetDB( DB_SLAVE );
3241 $res = $dbr->select( 'categorylinks',
3242 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3243 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3244 // as not being aliases, and NS_CATEGORY is numeric
3245 array( 'cl_from' => $id ),
3246 __METHOD__ );
3247
3248 return TitleArray::newFromResult( $res );
3249 }
3250
3251 /**
3252 * Returns a list of hidden categories this page is a member of.
3253 * Uses the page_props and categorylinks tables.
3254 *
3255 * @return array Array of Title objects
3256 */
3257 public function getHiddenCategories() {
3258 $result = array();
3259 $id = $this->getId();
3260
3261 if ( $id == 0 ) {
3262 return array();
3263 }
3264
3265 $dbr = wfGetDB( DB_SLAVE );
3266 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3267 array( 'cl_to' ),
3268 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3269 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3270 __METHOD__ );
3271
3272 if ( $res !== false ) {
3273 foreach ( $res as $row ) {
3274 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3275 }
3276 }
3277
3278 return $result;
3279 }
3280
3281 /**
3282 * Return an applicable autosummary if one exists for the given edit.
3283 * @param string|null $oldtext The previous text of the page.
3284 * @param string|null $newtext The submitted text of the page.
3285 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3286 * @return string An appropriate autosummary, or an empty string.
3287 *
3288 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3289 */
3290 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3291 // NOTE: stub for backwards-compatibility. assumes the given text is
3292 // wikitext. will break horribly if it isn't.
3293
3294 ContentHandler::deprecated( __METHOD__, '1.21' );
3295
3296 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3297 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3298 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3299
3300 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3301 }
3302
3303 /**
3304 * Auto-generates a deletion reason
3305 *
3306 * @param bool &$hasHistory Whether the page has a history
3307 * @return string|bool String containing deletion reason or empty string, or boolean false
3308 * if no revision occurred
3309 */
3310 public function getAutoDeleteReason( &$hasHistory ) {
3311 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3312 }
3313
3314 /**
3315 * Update all the appropriate counts in the category table, given that
3316 * we've added the categories $added and deleted the categories $deleted.
3317 *
3318 * @param array $added The names of categories that were added
3319 * @param array $deleted The names of categories that were deleted
3320 */
3321 public function updateCategoryCounts( array $added, array $deleted ) {
3322 $that = $this;
3323 $method = __METHOD__;
3324 $dbw = wfGetDB( DB_MASTER );
3325
3326 // Do this at the end of the commit to reduce lock wait timeouts
3327 $dbw->onTransactionPreCommitOrIdle(
3328 function () use ( $dbw, $that, $method, $added, $deleted ) {
3329 $ns = $that->getTitle()->getNamespace();
3330
3331 $addFields = array( 'cat_pages = cat_pages + 1' );
3332 $removeFields = array( 'cat_pages = cat_pages - 1' );
3333 if ( $ns == NS_CATEGORY ) {
3334 $addFields[] = 'cat_subcats = cat_subcats + 1';
3335 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3336 } elseif ( $ns == NS_FILE ) {
3337 $addFields[] = 'cat_files = cat_files + 1';
3338 $removeFields[] = 'cat_files = cat_files - 1';
3339 }
3340
3341 if ( count( $added ) ) {
3342 $insertRows = array();
3343 foreach ( $added as $cat ) {
3344 $insertRows[] = array(
3345 'cat_title' => $cat,
3346 'cat_pages' => 1,
3347 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3348 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3349 );
3350 }
3351 $dbw->upsert(
3352 'category',
3353 $insertRows,
3354 array( 'cat_title' ),
3355 $addFields,
3356 $method
3357 );
3358 }
3359
3360 if ( count( $deleted ) ) {
3361 $dbw->update(
3362 'category',
3363 $removeFields,
3364 array( 'cat_title' => $deleted ),
3365 $method
3366 );
3367 }
3368
3369 foreach ( $added as $catName ) {
3370 $cat = Category::newFromName( $catName );
3371 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3372 }
3373
3374 foreach ( $deleted as $catName ) {
3375 $cat = Category::newFromName( $catName );
3376 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3377 }
3378 }
3379 );
3380 }
3381
3382 /**
3383 * Updates cascading protections
3384 *
3385 * @param ParserOutput $parserOutput ParserOutput object for the current version
3386 */
3387 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3388 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3389 return;
3390 }
3391
3392 // templatelinks or imagelinks tables may have become out of sync,
3393 // especially if using variable-based transclusions.
3394 // For paranoia, check if things have changed and if
3395 // so apply updates to the database. This will ensure
3396 // that cascaded protections apply as soon as the changes
3397 // are visible.
3398
3399 // Get templates from templatelinks and images from imagelinks
3400 $id = $this->getId();
3401
3402 $dbLinks = array();
3403
3404 $dbr = wfGetDB( DB_SLAVE );
3405 $res = $dbr->select( array( 'templatelinks' ),
3406 array( 'tl_namespace', 'tl_title' ),
3407 array( 'tl_from' => $id ),
3408 __METHOD__
3409 );
3410
3411 foreach ( $res as $row ) {
3412 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3413 }
3414
3415 $dbr = wfGetDB( DB_SLAVE );
3416 $res = $dbr->select( array( 'imagelinks' ),
3417 array( 'il_to' ),
3418 array( 'il_from' => $id ),
3419 __METHOD__
3420 );
3421
3422 foreach ( $res as $row ) {
3423 $dbLinks[NS_FILE . ":{$row->il_to}"] = true;
3424 }
3425
3426 // Get templates and images from parser output.
3427 $poLinks = array();
3428 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3429 foreach ( $templates as $dbk => $id ) {
3430 $poLinks["$ns:$dbk"] = true;
3431 }
3432 }
3433 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3434 $poLinks[NS_FILE . ":$dbk"] = true;
3435 }
3436
3437 // Get the diff
3438 $links_diff = array_diff_key( $poLinks, $dbLinks );
3439
3440 if ( count( $links_diff ) > 0 ) {
3441 // Whee, link updates time.
3442 // Note: we are only interested in links here. We don't need to get
3443 // other DataUpdate items from the parser output.
3444 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3445 $u->doUpdate();
3446 }
3447 }
3448
3449 /**
3450 * Return a list of templates used by this article.
3451 * Uses the templatelinks table
3452 *
3453 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3454 * @return array Array of Title objects
3455 */
3456 public function getUsedTemplates() {
3457 return $this->mTitle->getTemplateLinksFrom();
3458 }
3459
3460 /**
3461 * This function is called right before saving the wikitext,
3462 * so we can do things like signatures and links-in-context.
3463 *
3464 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3465 * @param string $text Article contents
3466 * @param User $user User doing the edit
3467 * @param ParserOptions $popts Parser options, default options for
3468 * the user loaded if null given
3469 * @return string Article contents with altered wikitext markup (signatures
3470 * converted, {{subst:}}, templates, etc.)
3471 */
3472 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3473 global $wgParser, $wgUser;
3474
3475 wfDeprecated( __METHOD__, '1.19' );
3476
3477 $user = is_null( $user ) ? $wgUser : $user;
3478
3479 if ( $popts === null ) {
3480 $popts = ParserOptions::newFromUser( $user );
3481 }
3482
3483 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3484 }
3485
3486 /**
3487 * Update the article's restriction field, and leave a log entry.
3488 *
3489 * @deprecated since 1.19
3490 * @param array $limit Set of restriction keys
3491 * @param string $reason
3492 * @param int &$cascade Set to false if cascading protection isn't allowed.
3493 * @param array $expiry Per restriction type expiration
3494 * @param User $user The user updating the restrictions
3495 * @return bool True on success
3496 */
3497 public function updateRestrictions(
3498 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3499 ) {
3500 global $wgUser;
3501
3502 $user = is_null( $user ) ? $wgUser : $user;
3503
3504 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3505 }
3506
3507 /**
3508 * Returns a list of updates to be performed when this page is deleted. The
3509 * updates should remove any information about this page from secondary data
3510 * stores such as links tables.
3511 *
3512 * @param Content|null $content Optional Content object for determining the
3513 * necessary updates.
3514 * @return array An array of DataUpdates objects
3515 */
3516 public function getDeletionUpdates( Content $content = null ) {
3517 if ( !$content ) {
3518 // load content object, which may be used to determine the necessary updates
3519 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3520 $content = $this->getContent( Revision::RAW );
3521 }
3522
3523 if ( !$content ) {
3524 $updates = array();
3525 } else {
3526 $updates = $content->getDeletionUpdates( $this );
3527 }
3528
3529 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3530 return $updates;
3531 }
3532 }