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