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