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