Merge "Separate language generation from outputPage"
[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 $recipient = User::newFromName( $shortTitle, false );
2125 if ( !$recipient ) {
2126 wfDebug( __METHOD__ . ": invalid username\n" );
2127 } else {
2128 // Allow extensions to prevent user notification when a new message is added to their talk page
2129 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2130 if ( User::isIP( $shortTitle ) ) {
2131 // An anonymous user
2132 $recipient->setNewtalk( true, $revision );
2133 } elseif ( $recipient->isLoggedIn() ) {
2134 $recipient->setNewtalk( true, $revision );
2135 } else {
2136 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2137 }
2138 }
2139 }
2140 }
2141
2142 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2143 // XXX: could skip pseudo-messages like js/css here, based on content model.
2144 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2145 if ( $msgtext === false || $msgtext === null ) $msgtext = '';
2146
2147 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2148 }
2149
2150 if( $options['created'] ) {
2151 self::onArticleCreate( $this->mTitle );
2152 } else {
2153 self::onArticleEdit( $this->mTitle );
2154 }
2155
2156 wfProfileOut( __METHOD__ );
2157 }
2158
2159 /**
2160 * Edit an article without doing all that other stuff
2161 * The article must already exist; link tables etc
2162 * are not updated, caches are not flushed.
2163 *
2164 * @param string $text text submitted
2165 * @param $user User The relevant user
2166 * @param string $comment comment submitted
2167 * @param $minor Boolean: whereas it's a minor modification
2168 *
2169 * @deprecated since 1.21, use doEditContent() instead.
2170 */
2171 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2172 ContentHandler::deprecated( __METHOD__, "1.21" );
2173
2174 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2175 return $this->doQuickEditContent( $content, $user, $comment, $minor );
2176 }
2177
2178 /**
2179 * Edit an article without doing all that other stuff
2180 * The article must already exist; link tables etc
2181 * are not updated, caches are not flushed.
2182 *
2183 * @param $content Content: content submitted
2184 * @param $user User The relevant user
2185 * @param string $comment comment submitted
2186 * @param $serialisation_format String: format for storing the content in the database
2187 * @param $minor Boolean: whereas it's a minor modification
2188 */
2189 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = 0, $serialisation_format = null ) {
2190 wfProfileIn( __METHOD__ );
2191
2192 $serialized = $content->serialize( $serialisation_format );
2193
2194 $dbw = wfGetDB( DB_MASTER );
2195 $revision = new Revision( array(
2196 'title' => $this->getTitle(), // for determining the default content model
2197 'page' => $this->getId(),
2198 'text' => $serialized,
2199 'length' => $content->getSize(),
2200 'comment' => $comment,
2201 'minor_edit' => $minor ? 1 : 0,
2202 ) ); // XXX: set the content object?
2203 $revision->insertOn( $dbw );
2204 $this->updateRevisionOn( $dbw, $revision );
2205
2206 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2207
2208 wfProfileOut( __METHOD__ );
2209 }
2210
2211 /**
2212 * Update the article's restriction field, and leave a log entry.
2213 * This works for protection both existing and non-existing pages.
2214 *
2215 * @param array $limit set of restriction keys
2216 * @param $reason String
2217 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2218 * @param array $expiry per restriction type expiration
2219 * @param $user User The user updating the restrictions
2220 * @return Status
2221 */
2222 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
2223 global $wgContLang;
2224
2225 if ( wfReadOnly() ) {
2226 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2227 }
2228
2229 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2230
2231 $id = $this->getId();
2232
2233 if ( !$cascade ) {
2234 $cascade = false;
2235 }
2236
2237 // Take this opportunity to purge out expired restrictions
2238 Title::purgeExpiredRestrictions();
2239
2240 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2241 // we expect a single selection, but the schema allows otherwise.
2242 $isProtected = false;
2243 $protect = false;
2244 $changed = false;
2245
2246 $dbw = wfGetDB( DB_MASTER );
2247
2248 foreach ( $restrictionTypes as $action ) {
2249 if ( !isset( $expiry[$action] ) ) {
2250 $expiry[$action] = $dbw->getInfinity();
2251 }
2252 if ( !isset( $limit[$action] ) ) {
2253 $limit[$action] = '';
2254 } elseif ( $limit[$action] != '' ) {
2255 $protect = true;
2256 }
2257
2258 // Get current restrictions on $action
2259 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2260 if ( $current != '' ) {
2261 $isProtected = true;
2262 }
2263
2264 if ( $limit[$action] != $current ) {
2265 $changed = true;
2266 } elseif ( $limit[$action] != '' ) {
2267 // Only check expiry change if the action is actually being
2268 // protected, since expiry does nothing on an not-protected
2269 // action.
2270 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2271 $changed = true;
2272 }
2273 }
2274 }
2275
2276 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2277 $changed = true;
2278 }
2279
2280 // If nothing has changed, do nothing
2281 if ( !$changed ) {
2282 return Status::newGood();
2283 }
2284
2285 if ( !$protect ) { // No protection at all means unprotection
2286 $revCommentMsg = 'unprotectedarticle';
2287 $logAction = 'unprotect';
2288 } elseif ( $isProtected ) {
2289 $revCommentMsg = 'modifiedarticleprotection';
2290 $logAction = 'modify';
2291 } else {
2292 $revCommentMsg = 'protectedarticle';
2293 $logAction = 'protect';
2294 }
2295
2296 $encodedExpiry = array();
2297 $protectDescription = '';
2298 # Some bots may parse IRC lines, which are generated from log entries which contain plain
2299 # protect description text. Keep them in old format to avoid breaking compatibility.
2300 # TODO: Fix protection log to store structured description and format it on-the-fly.
2301 $protectDescriptionLog = '';
2302 foreach ( $limit as $action => $restrictions ) {
2303 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2304 if ( $restrictions != '' ) {
2305 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2306 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2307 # All possible message keys are listed here for easier grepping:
2308 # * restriction-create
2309 # * restriction-edit
2310 # * restriction-move
2311 # * restriction-upload
2312 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2313 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2314 # with '' filtered out. All possible message keys are listed below:
2315 # * protect-level-autoconfirmed
2316 # * protect-level-sysop
2317 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2318 if ( $encodedExpiry[$action] != 'infinity' ) {
2319 $expiryText = wfMessage(
2320 'protect-expiring',
2321 $wgContLang->timeanddate( $expiry[$action], false, false ),
2322 $wgContLang->date( $expiry[$action], false, false ),
2323 $wgContLang->time( $expiry[$action], false, false )
2324 )->inContentLanguage()->text();
2325 } else {
2326 $expiryText = wfMessage( 'protect-expiry-indefinite' )
2327 ->inContentLanguage()->text();
2328 }
2329
2330 if ( $protectDescription !== '' ) {
2331 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2332 }
2333 $protectDescription .= wfMessage( 'protect-summary-desc' )
2334 ->params( $actionText, $restrictionsText, $expiryText )
2335 ->inContentLanguage()->text();
2336 $protectDescriptionLog .= $expiryText . ') ';
2337 }
2338 }
2339 $protectDescriptionLog = trim( $protectDescriptionLog );
2340
2341 if ( $id ) { // Protection of existing page
2342 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2343 return Status::newGood();
2344 }
2345
2346 // Only restrictions with the 'protect' right can cascade...
2347 // Otherwise, people who cannot normally protect can "protect" pages via transclusion
2348 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2349
2350 // The schema allows multiple restrictions
2351 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2352 $cascade = false;
2353 }
2354
2355 // Update restrictions table
2356 foreach ( $limit as $action => $restrictions ) {
2357 if ( $restrictions != '' ) {
2358 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2359 array( 'pr_page' => $id,
2360 'pr_type' => $action,
2361 'pr_level' => $restrictions,
2362 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2363 'pr_expiry' => $encodedExpiry[$action]
2364 ),
2365 __METHOD__
2366 );
2367 } else {
2368 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2369 'pr_type' => $action ), __METHOD__ );
2370 }
2371 }
2372
2373 // Prepare a null revision to be added to the history
2374 $editComment = $wgContLang->ucfirst(
2375 wfMessage(
2376 $revCommentMsg,
2377 $this->mTitle->getPrefixedText()
2378 )->inContentLanguage()->text()
2379 );
2380 if ( $reason ) {
2381 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2382 }
2383 if ( $protectDescription ) {
2384 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2385 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2386 }
2387 if ( $cascade ) {
2388 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2389 $editComment .= wfMessage( 'brackets' )->params(
2390 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2391 )->inContentLanguage()->text();
2392 }
2393
2394 // Insert a null revision
2395 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2396 $nullRevId = $nullRevision->insertOn( $dbw );
2397
2398 $latest = $this->getLatest();
2399 // Update page record
2400 $dbw->update( 'page',
2401 array( /* SET */
2402 'page_touched' => $dbw->timestamp(),
2403 'page_restrictions' => '',
2404 'page_latest' => $nullRevId
2405 ), array( /* WHERE */
2406 'page_id' => $id
2407 ), __METHOD__
2408 );
2409
2410 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2411 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2412 } else { // Protection of non-existing page (also known as "title protection")
2413 // Cascade protection is meaningless in this case
2414 $cascade = false;
2415
2416 if ( $limit['create'] != '' ) {
2417 $dbw->replace( 'protected_titles',
2418 array( array( 'pt_namespace', 'pt_title' ) ),
2419 array(
2420 'pt_namespace' => $this->mTitle->getNamespace(),
2421 'pt_title' => $this->mTitle->getDBkey(),
2422 'pt_create_perm' => $limit['create'],
2423 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2424 'pt_expiry' => $encodedExpiry['create'],
2425 'pt_user' => $user->getId(),
2426 'pt_reason' => $reason,
2427 ), __METHOD__
2428 );
2429 } else {
2430 $dbw->delete( 'protected_titles',
2431 array(
2432 'pt_namespace' => $this->mTitle->getNamespace(),
2433 'pt_title' => $this->mTitle->getDBkey()
2434 ), __METHOD__
2435 );
2436 }
2437 }
2438
2439 $this->mTitle->flushRestrictions();
2440
2441 if ( $logAction == 'unprotect' ) {
2442 $logParams = array();
2443 } else {
2444 $logParams = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2445 }
2446
2447 // Update the protection log
2448 $log = new LogPage( 'protect' );
2449 $log->addEntry( $logAction, $this->mTitle, trim( $reason ), $logParams, $user );
2450
2451 return Status::newGood();
2452 }
2453
2454 /**
2455 * Take an array of page restrictions and flatten it to a string
2456 * suitable for insertion into the page_restrictions field.
2457 * @param $limit Array
2458 * @throws MWException
2459 * @return String
2460 */
2461 protected static function flattenRestrictions( $limit ) {
2462 if ( !is_array( $limit ) ) {
2463 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2464 }
2465
2466 $bits = array();
2467 ksort( $limit );
2468
2469 foreach ( $limit as $action => $restrictions ) {
2470 if ( $restrictions != '' ) {
2471 $bits[] = "$action=$restrictions";
2472 }
2473 }
2474
2475 return implode( ':', $bits );
2476 }
2477
2478 /**
2479 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2480 * backwards compatibility, if you care about error reporting you should use
2481 * doDeleteArticleReal() instead.
2482 *
2483 * Deletes the article with database consistency, writes logs, purges caches
2484 *
2485 * @param string $reason delete reason for deletion log
2486 * @param $suppress boolean suppress all revisions and log the deletion in
2487 * the suppression log instead of the deletion log
2488 * @param int $id article ID
2489 * @param $commit boolean defaults to true, triggers transaction end
2490 * @param &$error Array of errors to append to
2491 * @param $user User The deleting user
2492 * @return boolean true if successful
2493 */
2494 public function doDeleteArticle(
2495 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2496 ) {
2497 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2498 return $status->isGood();
2499 }
2500
2501 /**
2502 * Back-end article deletion
2503 * Deletes the article with database consistency, writes logs, purges caches
2504 *
2505 * @since 1.19
2506 *
2507 * @param string $reason delete reason for deletion log
2508 * @param $suppress boolean suppress all revisions and log the deletion in
2509 * the suppression log instead of the deletion log
2510 * @param int $id article ID
2511 * @param $commit boolean defaults to true, triggers transaction end
2512 * @param &$error Array of errors to append to
2513 * @param $user User The deleting user
2514 * @return Status: Status object; if successful, $status->value is the log_id of the
2515 * deletion log entry. If the page couldn't be deleted because it wasn't
2516 * found, $status is a non-fatal 'cannotdelete' error
2517 */
2518 public function doDeleteArticleReal(
2519 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2520 ) {
2521 global $wgUser, $wgContentHandlerUseDB;
2522
2523 wfDebug( __METHOD__ . "\n" );
2524
2525 $status = Status::newGood();
2526
2527 if ( $this->mTitle->getDBkey() === '' ) {
2528 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2529 return $status;
2530 }
2531
2532 $user = is_null( $user ) ? $wgUser : $user;
2533 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2534 if ( $status->isOK() ) {
2535 // Hook aborted but didn't set a fatal status
2536 $status->fatal( 'delete-hook-aborted' );
2537 }
2538 return $status;
2539 }
2540
2541 if ( $id == 0 ) {
2542 $this->loadPageData( 'forupdate' );
2543 $id = $this->getID();
2544 if ( $id == 0 ) {
2545 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2546 return $status;
2547 }
2548 }
2549
2550 // Bitfields to further suppress the content
2551 if ( $suppress ) {
2552 $bitfield = 0;
2553 // This should be 15...
2554 $bitfield |= Revision::DELETED_TEXT;
2555 $bitfield |= Revision::DELETED_COMMENT;
2556 $bitfield |= Revision::DELETED_USER;
2557 $bitfield |= Revision::DELETED_RESTRICTED;
2558 } else {
2559 $bitfield = 'rev_deleted';
2560 }
2561
2562 // we need to remember the old content so we can use it to generate all deletion updates.
2563 $content = $this->getContent( Revision::RAW );
2564
2565 $dbw = wfGetDB( DB_MASTER );
2566 $dbw->begin( __METHOD__ );
2567 // For now, shunt the revision data into the archive table.
2568 // Text is *not* removed from the text table; bulk storage
2569 // is left intact to avoid breaking block-compression or
2570 // immutable storage schemes.
2571 //
2572 // For backwards compatibility, note that some older archive
2573 // table entries will have ar_text and ar_flags fields still.
2574 //
2575 // In the future, we may keep revisions and mark them with
2576 // the rev_deleted field, which is reserved for this purpose.
2577
2578 $row = array(
2579 'ar_namespace' => 'page_namespace',
2580 'ar_title' => 'page_title',
2581 'ar_comment' => 'rev_comment',
2582 'ar_user' => 'rev_user',
2583 'ar_user_text' => 'rev_user_text',
2584 'ar_timestamp' => 'rev_timestamp',
2585 'ar_minor_edit' => 'rev_minor_edit',
2586 'ar_rev_id' => 'rev_id',
2587 'ar_parent_id' => 'rev_parent_id',
2588 'ar_text_id' => 'rev_text_id',
2589 'ar_text' => '\'\'', // Be explicit to appease
2590 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2591 'ar_len' => 'rev_len',
2592 'ar_page_id' => 'page_id',
2593 'ar_deleted' => $bitfield,
2594 'ar_sha1' => 'rev_sha1',
2595 );
2596
2597 if ( $wgContentHandlerUseDB ) {
2598 $row['ar_content_model'] = 'rev_content_model';
2599 $row['ar_content_format'] = 'rev_content_format';
2600 }
2601
2602 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2603 $row,
2604 array(
2605 'page_id' => $id,
2606 'page_id = rev_page'
2607 ), __METHOD__
2608 );
2609
2610 // Now that it's safely backed up, delete it
2611 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2612 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2613
2614 if ( !$ok ) {
2615 $dbw->rollback( __METHOD__ );
2616 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2617 return $status;
2618 }
2619
2620 $this->doDeleteUpdates( $id, $content );
2621
2622 // Log the deletion, if the page was suppressed, log it at Oversight instead
2623 $logtype = $suppress ? 'suppress' : 'delete';
2624
2625 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2626 $logEntry->setPerformer( $user );
2627 $logEntry->setTarget( $this->mTitle );
2628 $logEntry->setComment( $reason );
2629 $logid = $logEntry->insert();
2630 $logEntry->publish( $logid );
2631
2632 if ( $commit ) {
2633 $dbw->commit( __METHOD__ );
2634 }
2635
2636 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2637 $status->value = $logid;
2638 return $status;
2639 }
2640
2641 /**
2642 * Do some database updates after deletion
2643 *
2644 * @param int $id page_id value of the page being deleted (B/C, currently unused)
2645 * @param $content Content: optional page content to be used when determining the required updates.
2646 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2647 */
2648 public function doDeleteUpdates( $id, Content $content = null ) {
2649 // update site status
2650 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2651
2652 // remove secondary indexes, etc
2653 $updates = $this->getDeletionUpdates( $content );
2654 DataUpdate::runUpdates( $updates );
2655
2656 // Clear caches
2657 WikiPage::onArticleDelete( $this->mTitle );
2658
2659 // Reset this object and the Title object
2660 $this->loadFromRow( false, self::READ_LATEST );
2661 }
2662
2663 /**
2664 * Roll back the most recent consecutive set of edits to a page
2665 * from the same user; fails if there are no eligible edits to
2666 * roll back to, e.g. user is the sole contributor. This function
2667 * performs permissions checks on $user, then calls commitRollback()
2668 * to do the dirty work
2669 *
2670 * @todo: separate the business/permission stuff out from backend code
2671 *
2672 * @param string $fromP Name of the user whose edits to rollback.
2673 * @param string $summary Custom summary. Set to default summary if empty.
2674 * @param string $token Rollback token.
2675 * @param $bot Boolean: If true, mark all reverted edits as bot.
2676 *
2677 * @param array $resultDetails contains result-specific array of additional values
2678 * 'alreadyrolled' : 'current' (rev)
2679 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2680 *
2681 * @param $user User The user performing the rollback
2682 * @return array of errors, each error formatted as
2683 * array(messagekey, param1, param2, ...).
2684 * On success, the array is empty. This array can also be passed to
2685 * OutputPage::showPermissionsErrorPage().
2686 */
2687 public function doRollback(
2688 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2689 ) {
2690 $resultDetails = null;
2691
2692 // Check permissions
2693 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2694 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2695 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2696
2697 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2698 $errors[] = array( 'sessionfailure' );
2699 }
2700
2701 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2702 $errors[] = array( 'actionthrottledtext' );
2703 }
2704
2705 // If there were errors, bail out now
2706 if ( !empty( $errors ) ) {
2707 return $errors;
2708 }
2709
2710 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2711 }
2712
2713 /**
2714 * Backend implementation of doRollback(), please refer there for parameter
2715 * and return value documentation
2716 *
2717 * NOTE: This function does NOT check ANY permissions, it just commits the
2718 * rollback to the DB. Therefore, you should only call this function direct-
2719 * ly if you want to use custom permissions checks. If you don't, use
2720 * doRollback() instead.
2721 * @param string $fromP Name of the user whose edits to rollback.
2722 * @param string $summary Custom summary. Set to default summary if empty.
2723 * @param $bot Boolean: If true, mark all reverted edits as bot.
2724 *
2725 * @param array $resultDetails contains result-specific array of additional values
2726 * @param $guser User The user performing the rollback
2727 * @return array
2728 */
2729 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2730 global $wgUseRCPatrol, $wgContLang;
2731
2732 $dbw = wfGetDB( DB_MASTER );
2733
2734 if ( wfReadOnly() ) {
2735 return array( array( 'readonlytext' ) );
2736 }
2737
2738 // Get the last editor
2739 $current = $this->getRevision();
2740 if ( is_null( $current ) ) {
2741 // Something wrong... no page?
2742 return array( array( 'notanarticle' ) );
2743 }
2744
2745 $from = str_replace( '_', ' ', $fromP );
2746 // User name given should match up with the top revision.
2747 // If the user was deleted then $from should be empty.
2748 if ( $from != $current->getUserText() ) {
2749 $resultDetails = array( 'current' => $current );
2750 return array( array( 'alreadyrolled',
2751 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2752 htmlspecialchars( $fromP ),
2753 htmlspecialchars( $current->getUserText() )
2754 ) );
2755 }
2756
2757 // Get the last edit not by this guy...
2758 // Note: these may not be public values
2759 $user = intval( $current->getRawUser() );
2760 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2761 $s = $dbw->selectRow( 'revision',
2762 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2763 array( 'rev_page' => $current->getPage(),
2764 "rev_user != {$user} OR rev_user_text != {$user_text}"
2765 ), __METHOD__,
2766 array( 'USE INDEX' => 'page_timestamp',
2767 'ORDER BY' => 'rev_timestamp DESC' )
2768 );
2769 if ( $s === false ) {
2770 // No one else ever edited this page
2771 return array( array( 'cantrollback' ) );
2772 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2773 // Only admins can see this text
2774 return array( array( 'notvisiblerev' ) );
2775 }
2776
2777 $set = array();
2778 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2779 // Mark all reverted edits as bot
2780 $set['rc_bot'] = 1;
2781 }
2782
2783 if ( $wgUseRCPatrol ) {
2784 // Mark all reverted edits as patrolled
2785 $set['rc_patrolled'] = 1;
2786 }
2787
2788 if ( count( $set ) ) {
2789 $dbw->update( 'recentchanges', $set,
2790 array( /* WHERE */
2791 'rc_cur_id' => $current->getPage(),
2792 'rc_user_text' => $current->getUserText(),
2793 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
2794 ), __METHOD__
2795 );
2796 }
2797
2798 // Generate the edit summary if necessary
2799 $target = Revision::newFromId( $s->rev_id );
2800 if ( empty( $summary ) ) {
2801 if ( $from == '' ) { // no public user name
2802 $summary = wfMessage( 'revertpage-nouser' );
2803 } else {
2804 $summary = wfMessage( 'revertpage' );
2805 }
2806 }
2807
2808 // Allow the custom summary to use the same args as the default message
2809 $args = array(
2810 $target->getUserText(), $from, $s->rev_id,
2811 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2812 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2813 );
2814 if( $summary instanceof Message ) {
2815 $summary = $summary->params( $args )->inContentLanguage()->text();
2816 } else {
2817 $summary = wfMsgReplaceArgs( $summary, $args );
2818 }
2819
2820 // Trim spaces on user supplied text
2821 $summary = trim( $summary );
2822
2823 // Truncate for whole multibyte characters.
2824 $summary = $wgContLang->truncate( $summary, 255 );
2825
2826 // Save
2827 $flags = EDIT_UPDATE;
2828
2829 if ( $guser->isAllowed( 'minoredit' ) ) {
2830 $flags |= EDIT_MINOR;
2831 }
2832
2833 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2834 $flags |= EDIT_FORCE_BOT;
2835 }
2836
2837 // Actually store the edit
2838 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2839
2840 if ( !$status->isOK() ) {
2841 return $status->getErrorsArray();
2842 }
2843
2844 if ( !empty( $status->value['revision'] ) ) {
2845 $revId = $status->value['revision']->getId();
2846 } else {
2847 $revId = false;
2848 }
2849
2850 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2851
2852 $resultDetails = array(
2853 'summary' => $summary,
2854 'current' => $current,
2855 'target' => $target,
2856 'newid' => $revId
2857 );
2858
2859 return array();
2860 }
2861
2862 /**
2863 * The onArticle*() functions are supposed to be a kind of hooks
2864 * which should be called whenever any of the specified actions
2865 * are done.
2866 *
2867 * This is a good place to put code to clear caches, for instance.
2868 *
2869 * This is called on page move and undelete, as well as edit
2870 *
2871 * @param $title Title object
2872 */
2873 public static function onArticleCreate( $title ) {
2874 // Update existence markers on article/talk tabs...
2875 if ( $title->isTalkPage() ) {
2876 $other = $title->getSubjectPage();
2877 } else {
2878 $other = $title->getTalkPage();
2879 }
2880
2881 $other->invalidateCache();
2882 $other->purgeSquid();
2883
2884 $title->touchLinks();
2885 $title->purgeSquid();
2886 $title->deleteTitleProtection();
2887 }
2888
2889 /**
2890 * Clears caches when article is deleted
2891 *
2892 * @param $title Title
2893 */
2894 public static function onArticleDelete( $title ) {
2895 // Update existence markers on article/talk tabs...
2896 if ( $title->isTalkPage() ) {
2897 $other = $title->getSubjectPage();
2898 } else {
2899 $other = $title->getTalkPage();
2900 }
2901
2902 $other->invalidateCache();
2903 $other->purgeSquid();
2904
2905 $title->touchLinks();
2906 $title->purgeSquid();
2907
2908 // File cache
2909 HTMLFileCache::clearFileCache( $title );
2910
2911 // Messages
2912 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2913 MessageCache::singleton()->replace( $title->getDBkey(), false );
2914 }
2915
2916 // Images
2917 if ( $title->getNamespace() == NS_FILE ) {
2918 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2919 $update->doUpdate();
2920 }
2921
2922 // User talk pages
2923 if ( $title->getNamespace() == NS_USER_TALK ) {
2924 $user = User::newFromName( $title->getText(), false );
2925 if ( $user ) {
2926 $user->setNewtalk( false );
2927 }
2928 }
2929
2930 // Image redirects
2931 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2932 }
2933
2934 /**
2935 * Purge caches on page update etc
2936 *
2937 * @param $title Title object
2938 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2939 */
2940 public static function onArticleEdit( $title ) {
2941 // Invalidate caches of articles which include this page
2942 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2943
2944 // Invalidate the caches of all pages which redirect here
2945 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2946
2947 // Purge squid for this page only
2948 $title->purgeSquid();
2949
2950 // Clear file cache for this page only
2951 HTMLFileCache::clearFileCache( $title );
2952 }
2953
2954 /**#@-*/
2955
2956 /**
2957 * Returns a list of hidden categories this page is a member of.
2958 * Uses the page_props and categorylinks tables.
2959 *
2960 * @return Array of Title objects
2961 */
2962 public function getHiddenCategories() {
2963 $result = array();
2964 $id = $this->getId();
2965
2966 if ( $id == 0 ) {
2967 return array();
2968 }
2969
2970 $dbr = wfGetDB( DB_SLAVE );
2971 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2972 array( 'cl_to' ),
2973 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2974 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2975 __METHOD__ );
2976
2977 if ( $res !== false ) {
2978 foreach ( $res as $row ) {
2979 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2980 }
2981 }
2982
2983 return $result;
2984 }
2985
2986 /**
2987 * Return an applicable autosummary if one exists for the given edit.
2988 * @param string|null $oldtext the previous text of the page.
2989 * @param string|null $newtext The submitted text of the page.
2990 * @param int $flags bitmask: a bitmask of flags submitted for the edit.
2991 * @return string An appropriate autosummary, or an empty string.
2992 *
2993 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
2994 */
2995 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2996 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2997
2998 ContentHandler::deprecated( __METHOD__, '1.21' );
2999
3000 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3001 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3002 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3003
3004 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3005 }
3006
3007 /**
3008 * Auto-generates a deletion reason
3009 *
3010 * @param &$hasHistory Boolean: whether the page has a history
3011 * @return mixed String containing deletion reason or empty string, or boolean false
3012 * if no revision occurred
3013 */
3014 public function getAutoDeleteReason( &$hasHistory ) {
3015 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3016 }
3017
3018 /**
3019 * Update all the appropriate counts in the category table, given that
3020 * we've added the categories $added and deleted the categories $deleted.
3021 *
3022 * @param array $added The names of categories that were added
3023 * @param array $deleted The names of categories that were deleted
3024 */
3025 public function updateCategoryCounts( array $added, array $deleted ) {
3026 $that = $this;
3027 $method = __METHOD__;
3028 $dbw = wfGetDB( DB_MASTER );
3029
3030 // Do this at the end of the commit to reduce lock wait timeouts
3031 $dbw->onTransactionPreCommitOrIdle(
3032 function() use ( $dbw, $that, $method, $added, $deleted ) {
3033 $ns = $that->getTitle()->getNamespace();
3034
3035 // First make sure the rows exist. If one of the "deleted" ones didn't
3036 // exist, we might legitimately not create it, but it's simpler to just
3037 // create it and then give it a negative value, since the value is bogus
3038 // anyway.
3039 //
3040 // Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3041 $insertCats = array_merge( $added, $deleted );
3042 if ( !$insertCats ) {
3043 // Okay, nothing to do
3044 return;
3045 }
3046
3047 $insertRows = array();
3048 foreach ( $insertCats as $cat ) {
3049 $insertRows[] = array(
3050 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
3051 'cat_title' => $cat
3052 );
3053 }
3054 $dbw->insert( 'category', $insertRows, $method, 'IGNORE' );
3055
3056 $addFields = array( 'cat_pages = cat_pages + 1' );
3057 $removeFields = array( 'cat_pages = cat_pages - 1' );
3058
3059 if ( $ns == NS_CATEGORY ) {
3060 $addFields[] = 'cat_subcats = cat_subcats + 1';
3061 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3062 } elseif ( $ns == NS_FILE ) {
3063 $addFields[] = 'cat_files = cat_files + 1';
3064 $removeFields[] = 'cat_files = cat_files - 1';
3065 }
3066
3067 if ( $added ) {
3068 $dbw->update(
3069 'category',
3070 $addFields,
3071 array( 'cat_title' => $added ),
3072 $method
3073 );
3074 }
3075
3076 if ( $deleted ) {
3077 $dbw->update(
3078 'category',
3079 $removeFields,
3080 array( 'cat_title' => $deleted ),
3081 $method
3082 );
3083 }
3084
3085 foreach( $added as $catName ) {
3086 $cat = Category::newFromName( $catName );
3087 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3088 }
3089 foreach( $deleted as $catName ) {
3090 $cat = Category::newFromName( $catName );
3091 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3092 }
3093 }
3094 );
3095 }
3096
3097 /**
3098 * Updates cascading protections
3099 *
3100 * @param $parserOutput ParserOutput object for the current version
3101 */
3102 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3103 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3104 return;
3105 }
3106
3107 // templatelinks table may have become out of sync,
3108 // especially if using variable-based transclusions.
3109 // For paranoia, check if things have changed and if
3110 // so apply updates to the database. This will ensure
3111 // that cascaded protections apply as soon as the changes
3112 // are visible.
3113
3114 // Get templates from templatelinks
3115 $id = $this->getId();
3116
3117 $tlTemplates = array();
3118
3119 $dbr = wfGetDB( DB_SLAVE );
3120 $res = $dbr->select( array( 'templatelinks' ),
3121 array( 'tl_namespace', 'tl_title' ),
3122 array( 'tl_from' => $id ),
3123 __METHOD__
3124 );
3125
3126 foreach ( $res as $row ) {
3127 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3128 }
3129
3130 // Get templates from parser output.
3131 $poTemplates = array();
3132 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3133 foreach ( $templates as $dbk => $id ) {
3134 $poTemplates["$ns:$dbk"] = true;
3135 }
3136 }
3137
3138 // Get the diff
3139 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3140
3141 if ( count( $templates_diff ) > 0 ) {
3142 // Whee, link updates time.
3143 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3144 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3145 $u->doUpdate();
3146 }
3147 }
3148
3149 /**
3150 * Return a list of templates used by this article.
3151 * Uses the templatelinks table
3152 *
3153 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3154 * @return Array of Title objects
3155 */
3156 public function getUsedTemplates() {
3157 return $this->mTitle->getTemplateLinksFrom();
3158 }
3159
3160 /**
3161 * Perform article updates on a special page creation.
3162 *
3163 * @param $rev Revision object
3164 *
3165 * @todo This is a shitty interface function. Kill it and replace the
3166 * other shitty functions like doEditUpdates and such so it's not needed
3167 * anymore.
3168 * @deprecated since 1.18, use doEditUpdates()
3169 */
3170 public function createUpdates( $rev ) {
3171 wfDeprecated( __METHOD__, '1.18' );
3172 global $wgUser;
3173 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3174 }
3175
3176 /**
3177 * This function is called right before saving the wikitext,
3178 * so we can do things like signatures and links-in-context.
3179 *
3180 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3181 * @param string $text article contents
3182 * @param $user User object: user doing the edit
3183 * @param $popts ParserOptions object: parser options, default options for
3184 * the user loaded if null given
3185 * @return string article contents with altered wikitext markup (signatures
3186 * converted, {{subst:}}, templates, etc.)
3187 */
3188 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3189 global $wgParser, $wgUser;
3190
3191 wfDeprecated( __METHOD__, '1.19' );
3192
3193 $user = is_null( $user ) ? $wgUser : $user;
3194
3195 if ( $popts === null ) {
3196 $popts = ParserOptions::newFromUser( $user );
3197 }
3198
3199 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3200 }
3201
3202 /**
3203 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3204 *
3205 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3206 * @return bool
3207 */
3208 public function isBigDeletion() {
3209 wfDeprecated( __METHOD__, '1.19' );
3210 return $this->mTitle->isBigDeletion();
3211 }
3212
3213 /**
3214 * Get the approximate revision count of this page.
3215 *
3216 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3217 * @return int
3218 */
3219 public function estimateRevisionCount() {
3220 wfDeprecated( __METHOD__, '1.19' );
3221 return $this->mTitle->estimateRevisionCount();
3222 }
3223
3224 /**
3225 * Update the article's restriction field, and leave a log entry.
3226 *
3227 * @deprecated since 1.19
3228 * @param array $limit set of restriction keys
3229 * @param $reason String
3230 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3231 * @param array $expiry per restriction type expiration
3232 * @param $user User The user updating the restrictions
3233 * @return bool true on success
3234 */
3235 public function updateRestrictions(
3236 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3237 ) {
3238 global $wgUser;
3239
3240 $user = is_null( $user ) ? $wgUser : $user;
3241
3242 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3243 }
3244
3245 /**
3246 * @deprecated since 1.18
3247 */
3248 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3249 wfDeprecated( __METHOD__, '1.18' );
3250 global $wgUser;
3251 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3252 }
3253
3254 /**
3255 * @deprecated since 1.18
3256 */
3257 public function viewUpdates() {
3258 wfDeprecated( __METHOD__, '1.18' );
3259 global $wgUser;
3260 return $this->doViewUpdates( $wgUser );
3261 }
3262
3263 /**
3264 * @deprecated since 1.18
3265 * @param $oldid int
3266 * @return bool
3267 */
3268 public function useParserCache( $oldid ) {
3269 wfDeprecated( __METHOD__, '1.18' );
3270 global $wgUser;
3271 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
3272 }
3273
3274 /**
3275 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3276 * about this page from secondary data stores such as links tables.
3277 *
3278 * @param Content|null $content optional Content object for determining the necessary updates
3279 * @return Array an array of DataUpdates objects
3280 */
3281 public function getDeletionUpdates( Content $content = null ) {
3282 if ( !$content ) {
3283 // load content object, which may be used to determine the necessary updates
3284 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3285 $content = $this->getContent( Revision::RAW );
3286 }
3287
3288 if ( !$content ) {
3289 $updates = array();
3290 } else {
3291 $updates = $content->getDeletionUpdates( $this );
3292 }
3293
3294 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3295 return $updates;
3296 }
3297
3298 }
3299
3300 class PoolWorkArticleView extends PoolCounterWork {
3301
3302 /**
3303 * @var Page
3304 */
3305 private $page;
3306
3307 /**
3308 * @var string
3309 */
3310 private $cacheKey;
3311
3312 /**
3313 * @var integer
3314 */
3315 private $revid;
3316
3317 /**
3318 * @var ParserOptions
3319 */
3320 private $parserOptions;
3321
3322 /**
3323 * @var Content|null
3324 */
3325 private $content = null;
3326
3327 /**
3328 * @var ParserOutput|bool
3329 */
3330 private $parserOutput = false;
3331
3332 /**
3333 * @var bool
3334 */
3335 private $isDirty = false;
3336
3337 /**
3338 * @var Status|bool
3339 */
3340 private $error = false;
3341
3342 /**
3343 * Constructor
3344 *
3345 * @param $page Page
3346 * @param $revid Integer: ID of the revision being parsed
3347 * @param $useParserCache Boolean: whether to use the parser cache
3348 * @param $parserOptions parserOptions to use for the parse operation
3349 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3350 */
3351 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $content = null ) {
3352 if ( is_string( $content ) ) { // BC: old style call
3353 $modelId = $page->getRevision()->getContentModel();
3354 $format = $page->getRevision()->getContentFormat();
3355 $content = ContentHandler::makeContent( $content, $page->getTitle(), $modelId, $format );
3356 }
3357
3358 $this->page = $page;
3359 $this->revid = $revid;
3360 $this->cacheable = $useParserCache;
3361 $this->parserOptions = $parserOptions;
3362 $this->content = $content;
3363 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
3364 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
3365 }
3366
3367 /**
3368 * Get the ParserOutput from this object, or false in case of failure
3369 *
3370 * @return ParserOutput
3371 */
3372 public function getParserOutput() {
3373 return $this->parserOutput;
3374 }
3375
3376 /**
3377 * Get whether the ParserOutput is a dirty one (i.e. expired)
3378 *
3379 * @return bool
3380 */
3381 public function getIsDirty() {
3382 return $this->isDirty;
3383 }
3384
3385 /**
3386 * Get a Status object in case of error or false otherwise
3387 *
3388 * @return Status|bool
3389 */
3390 public function getError() {
3391 return $this->error;
3392 }
3393
3394 /**
3395 * @return bool
3396 */
3397 function doWork() {
3398 global $wgUseFileCache;
3399
3400 // @todo: several of the methods called on $this->page are not declared in Page, but present
3401 // in WikiPage and delegated by Article.
3402
3403 $isCurrent = $this->revid === $this->page->getLatest();
3404
3405 if ( $this->content !== null ) {
3406 $content = $this->content;
3407 } elseif ( $isCurrent ) {
3408 // XXX: why use RAW audience here, and PUBLIC (default) below?
3409 $content = $this->page->getContent( Revision::RAW );
3410 } else {
3411 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
3412
3413 if ( $rev === null ) {
3414 $content = null;
3415 } else {
3416 // XXX: why use PUBLIC audience here (default), and RAW above?
3417 $content = $rev->getContent();
3418 }
3419 }
3420
3421 if ( $content === null ) {
3422 return false;
3423 }
3424
3425 $time = - microtime( true );
3426 $this->parserOutput = $content->getParserOutput( $this->page->getTitle(), $this->revid, $this->parserOptions );
3427 $time += microtime( true );
3428
3429 // Timing hack
3430 if ( $time > 3 ) {
3431 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3432 $this->page->getTitle()->getPrefixedDBkey() ) );
3433 }
3434
3435 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
3436 ParserCache::singleton()->save( $this->parserOutput, $this->page, $this->parserOptions );
3437 }
3438
3439 // Make sure file cache is not used on uncacheable content.
3440 // Output that has magic words in it can still use the parser cache
3441 // (if enabled), though it will generally expire sooner.
3442 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
3443 $wgUseFileCache = false;
3444 }
3445
3446 if ( $isCurrent ) {
3447 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
3448 }
3449
3450 return true;
3451 }
3452
3453 /**
3454 * @return bool
3455 */
3456 function getCachedWork() {
3457 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
3458
3459 if ( $this->parserOutput === false ) {
3460 wfDebug( __METHOD__ . ": parser cache miss\n" );
3461 return false;
3462 } else {
3463 wfDebug( __METHOD__ . ": parser cache hit\n" );
3464 return true;
3465 }
3466 }
3467
3468 /**
3469 * @return bool
3470 */
3471 function fallback() {
3472 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
3473
3474 if ( $this->parserOutput === false ) {
3475 wfDebugLog( 'dirty', "dirty missing\n" );
3476 wfDebug( __METHOD__ . ": no dirty cache\n" );
3477 return false;
3478 } else {
3479 wfDebug( __METHOD__ . ": sending dirty output\n" );
3480 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3481 $this->isDirty = true;
3482 return true;
3483 }
3484 }
3485
3486 /**
3487 * @param $status Status
3488 * @return bool
3489 */
3490 function error( $status ) {
3491 $this->error = $status;
3492 return false;
3493 }
3494 }