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