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