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