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