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