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