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