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