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