Add a 'revdelete-selected-file' message on Special:RevisionDelete
[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 (existing or missing page)
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 public 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 $logRelationsValues = array();
2359 $logRelationsField = null;
2360
2361 if ( $id ) { // Protection of existing page
2362 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2363 return Status::newGood();
2364 }
2365
2366 // Only certain restrictions can cascade...
2367 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2368 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2369 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2370 }
2371 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2372 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2373 }
2374
2375 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2376 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2377 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2378 }
2379 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2380 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2381 }
2382
2383 // The schema allows multiple restrictions
2384 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2385 $cascade = false;
2386 }
2387
2388 // insert null revision to identify the page protection change as edit summary
2389 $latest = $this->getLatest();
2390 $nullRevision = $this->insertProtectNullRevision( $revCommentMsg, $limit, $expiry, $cascade, $reason );
2391 if ( $nullRevision === null ) {
2392 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2393 }
2394
2395 $logRelationsField = 'pr_id';
2396
2397 // Update restrictions table
2398 foreach ( $limit as $action => $restrictions ) {
2399 $dbw->delete(
2400 'page_restrictions',
2401 array(
2402 'pr_page' => $id,
2403 'pr_type' => $action
2404 ),
2405 __METHOD__
2406 );
2407 if ( $restrictions != '' ) {
2408 $dbw->insert(
2409 'page_restrictions',
2410 array(
2411 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2412 'pr_page' => $id,
2413 'pr_type' => $action,
2414 'pr_level' => $restrictions,
2415 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2416 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2417 ),
2418 __METHOD__
2419 );
2420 $logRelationsValues[] = $dbw->insertId();
2421 }
2422 }
2423
2424 // Clear out legacy restriction fields
2425 $dbw->update(
2426 'page',
2427 array( 'page_restrictions' => '' ),
2428 array( 'page_id' => $id ),
2429 __METHOD__
2430 );
2431
2432 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2433 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2434 } else { // Protection of non-existing page (also known as "title protection")
2435 // Cascade protection is meaningless in this case
2436 $cascade = false;
2437
2438 if ( $limit['create'] != '' ) {
2439 $dbw->replace( 'protected_titles',
2440 array( array( 'pt_namespace', 'pt_title' ) ),
2441 array(
2442 'pt_namespace' => $this->mTitle->getNamespace(),
2443 'pt_title' => $this->mTitle->getDBkey(),
2444 'pt_create_perm' => $limit['create'],
2445 'pt_timestamp' => $dbw->timestamp(),
2446 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2447 'pt_user' => $user->getId(),
2448 'pt_reason' => $reason,
2449 ), __METHOD__
2450 );
2451 } else {
2452 $dbw->delete( 'protected_titles',
2453 array(
2454 'pt_namespace' => $this->mTitle->getNamespace(),
2455 'pt_title' => $this->mTitle->getDBkey()
2456 ), __METHOD__
2457 );
2458 }
2459 }
2460
2461 $this->mTitle->flushRestrictions();
2462 InfoAction::invalidateCache( $this->mTitle );
2463
2464 if ( $logAction == 'unprotect' ) {
2465 $params = array();
2466 } else {
2467 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2468 $params = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2469 }
2470
2471 // Update the protection log
2472 $log = new LogPage( 'protect' );
2473 $logId = $log->addEntry( $logAction, $this->mTitle, $reason, $params, $user );
2474 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2475 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2476 }
2477
2478 return Status::newGood();
2479 }
2480
2481 /**
2482 * Insert a new null revision for this page.
2483 *
2484 * @param string $revCommentMsg comment message key for the revision
2485 * @param array $limit set of restriction keys
2486 * @param array $expiry per restriction type expiration
2487 * @param int $cascade Set to false if cascading protection isn't allowed.
2488 * @param string $reason
2489 * @return Revision|null on error
2490 */
2491 public function insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason ) {
2492 global $wgContLang;
2493 $dbw = wfGetDB( DB_MASTER );
2494
2495 // Prepare a null revision to be added to the history
2496 $editComment = $wgContLang->ucfirst(
2497 wfMessage(
2498 $revCommentMsg,
2499 $this->mTitle->getPrefixedText()
2500 )->inContentLanguage()->text()
2501 );
2502 if ( $reason ) {
2503 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2504 }
2505 $protectDescription = $this->protectDescription( $limit, $expiry );
2506 if ( $protectDescription ) {
2507 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2508 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2509 }
2510 if ( $cascade ) {
2511 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2512 $editComment .= wfMessage( 'brackets' )->params(
2513 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2514 )->inContentLanguage()->text();
2515 }
2516
2517 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true );
2518 if ( $nullRev ) {
2519 $nullRev->insertOn( $dbw );
2520
2521 // Update page record and touch page
2522 $oldLatest = $nullRev->getParentId();
2523 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2524 }
2525
2526 return $nullRev;
2527 }
2528
2529 /**
2530 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2531 * @return string
2532 */
2533 protected function formatExpiry( $expiry ) {
2534 global $wgContLang;
2535 $dbr = wfGetDB( DB_SLAVE );
2536
2537 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2538 if ( $encodedExpiry != 'infinity' ) {
2539 return wfMessage(
2540 'protect-expiring',
2541 $wgContLang->timeanddate( $expiry, false, false ),
2542 $wgContLang->date( $expiry, false, false ),
2543 $wgContLang->time( $expiry, false, false )
2544 )->inContentLanguage()->text();
2545 } else {
2546 return wfMessage( 'protect-expiry-indefinite' )
2547 ->inContentLanguage()->text();
2548 }
2549 }
2550
2551 /**
2552 * Builds the description to serve as comment for the edit.
2553 *
2554 * @param array $limit set of restriction keys
2555 * @param array $expiry per restriction type expiration
2556 * @return string
2557 */
2558 public function protectDescription( array $limit, array $expiry ) {
2559 $protectDescription = '';
2560
2561 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2562 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2563 # All possible message keys are listed here for easier grepping:
2564 # * restriction-create
2565 # * restriction-edit
2566 # * restriction-move
2567 # * restriction-upload
2568 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2569 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2570 # with '' filtered out. All possible message keys are listed below:
2571 # * protect-level-autoconfirmed
2572 # * protect-level-sysop
2573 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2574
2575 $expiryText = $this->formatExpiry( $expiry[$action] );
2576
2577 if ( $protectDescription !== '' ) {
2578 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2579 }
2580 $protectDescription .= wfMessage( 'protect-summary-desc' )
2581 ->params( $actionText, $restrictionsText, $expiryText )
2582 ->inContentLanguage()->text();
2583 }
2584
2585 return $protectDescription;
2586 }
2587
2588 /**
2589 * Builds the description to serve as comment for the log entry.
2590 *
2591 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2592 * protect description text. Keep them in old format to avoid breaking compatibility.
2593 * TODO: Fix protection log to store structured description and format it on-the-fly.
2594 *
2595 * @param array $limit set of restriction keys
2596 * @param array $expiry per restriction type expiration
2597 * @return string
2598 */
2599 public function protectDescriptionLog( array $limit, array $expiry ) {
2600 global $wgContLang;
2601
2602 $protectDescriptionLog = '';
2603
2604 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2605 $expiryText = $this->formatExpiry( $expiry[$action] );
2606 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2607 }
2608
2609 return trim( $protectDescriptionLog );
2610 }
2611
2612 /**
2613 * Take an array of page restrictions and flatten it to a string
2614 * suitable for insertion into the page_restrictions field.
2615 * @param $limit Array
2616 * @throws MWException
2617 * @return String
2618 */
2619 protected static function flattenRestrictions( $limit ) {
2620 if ( !is_array( $limit ) ) {
2621 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2622 }
2623
2624 $bits = array();
2625 ksort( $limit );
2626
2627 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2628 $bits[] = "$action=$restrictions";
2629 }
2630
2631 return implode( ':', $bits );
2632 }
2633
2634 /**
2635 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2636 * backwards compatibility, if you care about error reporting you should use
2637 * doDeleteArticleReal() instead.
2638 *
2639 * Deletes the article with database consistency, writes logs, purges caches
2640 *
2641 * @param string $reason delete reason for deletion log
2642 * @param $suppress boolean suppress all revisions and log the deletion in
2643 * the suppression log instead of the deletion log
2644 * @param int $id article ID
2645 * @param $commit boolean defaults to true, triggers transaction end
2646 * @param &$error Array of errors to append to
2647 * @param $user User The deleting user
2648 * @return boolean true if successful
2649 */
2650 public function doDeleteArticle(
2651 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2652 ) {
2653 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2654 return $status->isGood();
2655 }
2656
2657 /**
2658 * Back-end article deletion
2659 * Deletes the article with database consistency, writes logs, purges caches
2660 *
2661 * @since 1.19
2662 *
2663 * @param string $reason delete reason for deletion log
2664 * @param $suppress boolean suppress all revisions and log the deletion in
2665 * the suppression log instead of the deletion log
2666 * @param int $id article ID
2667 * @param $commit boolean defaults to true, triggers transaction end
2668 * @param &$error Array of errors to append to
2669 * @param $user User The deleting user
2670 * @return Status: Status object; if successful, $status->value is the log_id of the
2671 * deletion log entry. If the page couldn't be deleted because it wasn't
2672 * found, $status is a non-fatal 'cannotdelete' error
2673 */
2674 public function doDeleteArticleReal(
2675 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2676 ) {
2677 global $wgUser, $wgContentHandlerUseDB;
2678
2679 wfDebug( __METHOD__ . "\n" );
2680
2681 $status = Status::newGood();
2682
2683 if ( $this->mTitle->getDBkey() === '' ) {
2684 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2685 return $status;
2686 }
2687
2688 $user = is_null( $user ) ? $wgUser : $user;
2689 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2690 if ( $status->isOK() ) {
2691 // Hook aborted but didn't set a fatal status
2692 $status->fatal( 'delete-hook-aborted' );
2693 }
2694 return $status;
2695 }
2696
2697 if ( $id == 0 ) {
2698 $this->loadPageData( 'forupdate' );
2699 $id = $this->getID();
2700 if ( $id == 0 ) {
2701 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2702 return $status;
2703 }
2704 }
2705
2706 // Bitfields to further suppress the content
2707 if ( $suppress ) {
2708 $bitfield = 0;
2709 // This should be 15...
2710 $bitfield |= Revision::DELETED_TEXT;
2711 $bitfield |= Revision::DELETED_COMMENT;
2712 $bitfield |= Revision::DELETED_USER;
2713 $bitfield |= Revision::DELETED_RESTRICTED;
2714 } else {
2715 $bitfield = 'rev_deleted';
2716 }
2717
2718 // we need to remember the old content so we can use it to generate all deletion updates.
2719 $content = $this->getContent( Revision::RAW );
2720
2721 $dbw = wfGetDB( DB_MASTER );
2722 $dbw->begin( __METHOD__ );
2723 // For now, shunt the revision data into the archive table.
2724 // Text is *not* removed from the text table; bulk storage
2725 // is left intact to avoid breaking block-compression or
2726 // immutable storage schemes.
2727 //
2728 // For backwards compatibility, note that some older archive
2729 // table entries will have ar_text and ar_flags fields still.
2730 //
2731 // In the future, we may keep revisions and mark them with
2732 // the rev_deleted field, which is reserved for this purpose.
2733
2734 $row = array(
2735 'ar_namespace' => 'page_namespace',
2736 'ar_title' => 'page_title',
2737 'ar_comment' => 'rev_comment',
2738 'ar_user' => 'rev_user',
2739 'ar_user_text' => 'rev_user_text',
2740 'ar_timestamp' => 'rev_timestamp',
2741 'ar_minor_edit' => 'rev_minor_edit',
2742 'ar_rev_id' => 'rev_id',
2743 'ar_parent_id' => 'rev_parent_id',
2744 'ar_text_id' => 'rev_text_id',
2745 'ar_text' => '\'\'', // Be explicit to appease
2746 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2747 'ar_len' => 'rev_len',
2748 'ar_page_id' => 'page_id',
2749 'ar_deleted' => $bitfield,
2750 'ar_sha1' => 'rev_sha1',
2751 );
2752
2753 if ( $wgContentHandlerUseDB ) {
2754 $row['ar_content_model'] = 'rev_content_model';
2755 $row['ar_content_format'] = 'rev_content_format';
2756 }
2757
2758 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2759 $row,
2760 array(
2761 'page_id' => $id,
2762 'page_id = rev_page'
2763 ), __METHOD__
2764 );
2765
2766 // Now that it's safely backed up, delete it
2767 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2768 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2769
2770 if ( !$ok ) {
2771 $dbw->rollback( __METHOD__ );
2772 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2773 return $status;
2774 }
2775
2776 if ( !$dbw->cascadingDeletes() ) {
2777 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2778 }
2779
2780 $this->doDeleteUpdates( $id, $content );
2781
2782 // Log the deletion, if the page was suppressed, log it at Oversight instead
2783 $logtype = $suppress ? 'suppress' : 'delete';
2784
2785 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2786 $logEntry->setPerformer( $user );
2787 $logEntry->setTarget( $this->mTitle );
2788 $logEntry->setComment( $reason );
2789 $logid = $logEntry->insert();
2790 $logEntry->publish( $logid );
2791
2792 if ( $commit ) {
2793 $dbw->commit( __METHOD__ );
2794 }
2795
2796 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2797 $status->value = $logid;
2798 return $status;
2799 }
2800
2801 /**
2802 * Do some database updates after deletion
2803 *
2804 * @param int $id page_id value of the page being deleted
2805 * @param $content Content: optional page content to be used when determining the required updates.
2806 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2807 */
2808 public function doDeleteUpdates( $id, Content $content = null ) {
2809 // update site status
2810 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2811
2812 // remove secondary indexes, etc
2813 $updates = $this->getDeletionUpdates( $content );
2814 DataUpdate::runUpdates( $updates );
2815
2816 // Reparse any pages transcluding this page
2817 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2818
2819 // Reparse any pages including this image
2820 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2821 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2822 }
2823
2824 // Clear caches
2825 WikiPage::onArticleDelete( $this->mTitle );
2826
2827 // Reset this object and the Title object
2828 $this->loadFromRow( false, self::READ_LATEST );
2829
2830 // Search engine
2831 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2832 }
2833
2834 /**
2835 * Roll back the most recent consecutive set of edits to a page
2836 * from the same user; fails if there are no eligible edits to
2837 * roll back to, e.g. user is the sole contributor. This function
2838 * performs permissions checks on $user, then calls commitRollback()
2839 * to do the dirty work
2840 *
2841 * @todo Separate the business/permission stuff out from backend code
2842 *
2843 * @param string $fromP Name of the user whose edits to rollback.
2844 * @param string $summary Custom summary. Set to default summary if empty.
2845 * @param string $token Rollback token.
2846 * @param $bot Boolean: If true, mark all reverted edits as bot.
2847 *
2848 * @param array $resultDetails contains result-specific array of additional values
2849 * 'alreadyrolled' : 'current' (rev)
2850 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2851 *
2852 * @param $user User The user performing the rollback
2853 * @return array of errors, each error formatted as
2854 * array(messagekey, param1, param2, ...).
2855 * On success, the array is empty. This array can also be passed to
2856 * OutputPage::showPermissionsErrorPage().
2857 */
2858 public function doRollback(
2859 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2860 ) {
2861 $resultDetails = null;
2862
2863 // Check permissions
2864 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2865 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2866 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2867
2868 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2869 $errors[] = array( 'sessionfailure' );
2870 }
2871
2872 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2873 $errors[] = array( 'actionthrottledtext' );
2874 }
2875
2876 // If there were errors, bail out now
2877 if ( !empty( $errors ) ) {
2878 return $errors;
2879 }
2880
2881 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2882 }
2883
2884 /**
2885 * Backend implementation of doRollback(), please refer there for parameter
2886 * and return value documentation
2887 *
2888 * NOTE: This function does NOT check ANY permissions, it just commits the
2889 * rollback to the DB. Therefore, you should only call this function direct-
2890 * ly if you want to use custom permissions checks. If you don't, use
2891 * doRollback() instead.
2892 * @param string $fromP Name of the user whose edits to rollback.
2893 * @param string $summary Custom summary. Set to default summary if empty.
2894 * @param $bot Boolean: If true, mark all reverted edits as bot.
2895 *
2896 * @param array $resultDetails contains result-specific array of additional values
2897 * @param $guser User The user performing the rollback
2898 * @return array
2899 */
2900 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2901 global $wgUseRCPatrol, $wgContLang;
2902
2903 $dbw = wfGetDB( DB_MASTER );
2904
2905 if ( wfReadOnly() ) {
2906 return array( array( 'readonlytext' ) );
2907 }
2908
2909 // Get the last editor
2910 $current = $this->getRevision();
2911 if ( is_null( $current ) ) {
2912 // Something wrong... no page?
2913 return array( array( 'notanarticle' ) );
2914 }
2915
2916 $from = str_replace( '_', ' ', $fromP );
2917 // User name given should match up with the top revision.
2918 // If the user was deleted then $from should be empty.
2919 if ( $from != $current->getUserText() ) {
2920 $resultDetails = array( 'current' => $current );
2921 return array( array( 'alreadyrolled',
2922 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2923 htmlspecialchars( $fromP ),
2924 htmlspecialchars( $current->getUserText() )
2925 ) );
2926 }
2927
2928 // Get the last edit not by this guy...
2929 // Note: these may not be public values
2930 $user = intval( $current->getRawUser() );
2931 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2932 $s = $dbw->selectRow( 'revision',
2933 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2934 array( 'rev_page' => $current->getPage(),
2935 "rev_user != {$user} OR rev_user_text != {$user_text}"
2936 ), __METHOD__,
2937 array( 'USE INDEX' => 'page_timestamp',
2938 'ORDER BY' => 'rev_timestamp DESC' )
2939 );
2940 if ( $s === false ) {
2941 // No one else ever edited this page
2942 return array( array( 'cantrollback' ) );
2943 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2944 // Only admins can see this text
2945 return array( array( 'notvisiblerev' ) );
2946 }
2947
2948 // Set patrolling and bot flag on the edits, which gets rollbacked.
2949 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
2950 $set = array();
2951 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2952 // Mark all reverted edits as bot
2953 $set['rc_bot'] = 1;
2954 }
2955
2956 if ( $wgUseRCPatrol ) {
2957 // Mark all reverted edits as patrolled
2958 $set['rc_patrolled'] = 1;
2959 }
2960
2961 if ( count( $set ) ) {
2962 $dbw->update( 'recentchanges', $set,
2963 array( /* WHERE */
2964 'rc_cur_id' => $current->getPage(),
2965 'rc_user_text' => $current->getUserText(),
2966 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
2967 ), __METHOD__
2968 );
2969 }
2970
2971 // Generate the edit summary if necessary
2972 $target = Revision::newFromId( $s->rev_id );
2973 if ( empty( $summary ) ) {
2974 if ( $from == '' ) { // no public user name
2975 $summary = wfMessage( 'revertpage-nouser' );
2976 } else {
2977 $summary = wfMessage( 'revertpage' );
2978 }
2979 }
2980
2981 // Allow the custom summary to use the same args as the default message
2982 $args = array(
2983 $target->getUserText(), $from, $s->rev_id,
2984 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2985 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2986 );
2987 if ( $summary instanceof Message ) {
2988 $summary = $summary->params( $args )->inContentLanguage()->text();
2989 } else {
2990 $summary = wfMsgReplaceArgs( $summary, $args );
2991 }
2992
2993 // Trim spaces on user supplied text
2994 $summary = trim( $summary );
2995
2996 // Truncate for whole multibyte characters.
2997 $summary = $wgContLang->truncate( $summary, 255 );
2998
2999 // Save
3000 $flags = EDIT_UPDATE;
3001
3002 if ( $guser->isAllowed( 'minoredit' ) ) {
3003 $flags |= EDIT_MINOR;
3004 }
3005
3006 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3007 $flags |= EDIT_FORCE_BOT;
3008 }
3009
3010 // Actually store the edit
3011 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
3012
3013 if ( !$status->isOK() ) {
3014 return $status->getErrorsArray();
3015 }
3016
3017 // raise error, when the edit is an edit without a new version
3018 if ( empty( $status->value['revision'] ) ) {
3019 $resultDetails = array( 'current' => $current );
3020 return array( array( 'alreadyrolled',
3021 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3022 htmlspecialchars( $fromP ),
3023 htmlspecialchars( $current->getUserText() )
3024 ) );
3025 }
3026
3027 $revId = $status->value['revision']->getId();
3028
3029 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3030
3031 $resultDetails = array(
3032 'summary' => $summary,
3033 'current' => $current,
3034 'target' => $target,
3035 'newid' => $revId
3036 );
3037
3038 return array();
3039 }
3040
3041 /**
3042 * The onArticle*() functions are supposed to be a kind of hooks
3043 * which should be called whenever any of the specified actions
3044 * are done.
3045 *
3046 * This is a good place to put code to clear caches, for instance.
3047 *
3048 * This is called on page move and undelete, as well as edit
3049 *
3050 * @param $title Title object
3051 */
3052 public static function onArticleCreate( $title ) {
3053 // Update existence markers on article/talk tabs...
3054 if ( $title->isTalkPage() ) {
3055 $other = $title->getSubjectPage();
3056 } else {
3057 $other = $title->getTalkPage();
3058 }
3059
3060 $other->invalidateCache();
3061 $other->purgeSquid();
3062
3063 $title->touchLinks();
3064 $title->purgeSquid();
3065 $title->deleteTitleProtection();
3066 }
3067
3068 /**
3069 * Clears caches when article is deleted
3070 *
3071 * @param $title Title
3072 */
3073 public static function onArticleDelete( $title ) {
3074 // Update existence markers on article/talk tabs...
3075 if ( $title->isTalkPage() ) {
3076 $other = $title->getSubjectPage();
3077 } else {
3078 $other = $title->getTalkPage();
3079 }
3080
3081 $other->invalidateCache();
3082 $other->purgeSquid();
3083
3084 $title->touchLinks();
3085 $title->purgeSquid();
3086
3087 // File cache
3088 HTMLFileCache::clearFileCache( $title );
3089 InfoAction::invalidateCache( $title );
3090
3091 // Messages
3092 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3093 MessageCache::singleton()->replace( $title->getDBkey(), false );
3094 }
3095
3096 // Images
3097 if ( $title->getNamespace() == NS_FILE ) {
3098 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3099 $update->doUpdate();
3100 }
3101
3102 // User talk pages
3103 if ( $title->getNamespace() == NS_USER_TALK ) {
3104 $user = User::newFromName( $title->getText(), false );
3105 if ( $user ) {
3106 $user->setNewtalk( false );
3107 }
3108 }
3109
3110 // Image redirects
3111 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3112 }
3113
3114 /**
3115 * Purge caches on page update etc
3116 *
3117 * @param $title Title object
3118 * @todo Verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3119 */
3120 public static function onArticleEdit( $title ) {
3121 // Invalidate caches of articles which include this page
3122 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
3123
3124 // Invalidate the caches of all pages which redirect here
3125 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
3126
3127 // Purge squid for this page only
3128 $title->purgeSquid();
3129
3130 // Clear file cache for this page only
3131 HTMLFileCache::clearFileCache( $title );
3132 InfoAction::invalidateCache( $title );
3133 }
3134
3135 /**#@-*/
3136
3137 /**
3138 * Returns a list of categories this page is a member of.
3139 * Results will include hidden categories
3140 *
3141 * @return TitleArray
3142 */
3143 public function getCategories() {
3144 $id = $this->getId();
3145 if ( $id == 0 ) {
3146 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3147 }
3148
3149 $dbr = wfGetDB( DB_SLAVE );
3150 $res = $dbr->select( 'categorylinks',
3151 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3152 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3153 // as not being aliases, and NS_CATEGORY is numeric
3154 array( 'cl_from' => $id ),
3155 __METHOD__ );
3156
3157 return TitleArray::newFromResult( $res );
3158 }
3159
3160 /**
3161 * Returns a list of hidden categories this page is a member of.
3162 * Uses the page_props and categorylinks tables.
3163 *
3164 * @return Array of Title objects
3165 */
3166 public function getHiddenCategories() {
3167 $result = array();
3168 $id = $this->getId();
3169
3170 if ( $id == 0 ) {
3171 return array();
3172 }
3173
3174 $dbr = wfGetDB( DB_SLAVE );
3175 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3176 array( 'cl_to' ),
3177 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3178 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3179 __METHOD__ );
3180
3181 if ( $res !== false ) {
3182 foreach ( $res as $row ) {
3183 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3184 }
3185 }
3186
3187 return $result;
3188 }
3189
3190 /**
3191 * Return an applicable autosummary if one exists for the given edit.
3192 * @param string|null $oldtext the previous text of the page.
3193 * @param string|null $newtext The submitted text of the page.
3194 * @param int $flags bitmask: a bitmask of flags submitted for the edit.
3195 * @return string An appropriate autosummary, or an empty string.
3196 *
3197 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3198 */
3199 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3200 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
3201
3202 ContentHandler::deprecated( __METHOD__, '1.21' );
3203
3204 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3205 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3206 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3207
3208 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3209 }
3210
3211 /**
3212 * Auto-generates a deletion reason
3213 *
3214 * @param &$hasHistory Boolean: whether the page has a history
3215 * @return mixed String containing deletion reason or empty string, or boolean false
3216 * if no revision occurred
3217 */
3218 public function getAutoDeleteReason( &$hasHistory ) {
3219 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3220 }
3221
3222 /**
3223 * Update all the appropriate counts in the category table, given that
3224 * we've added the categories $added and deleted the categories $deleted.
3225 *
3226 * @param array $added The names of categories that were added
3227 * @param array $deleted The names of categories that were deleted
3228 */
3229 public function updateCategoryCounts( array $added, array $deleted ) {
3230 $that = $this;
3231 $method = __METHOD__;
3232 $dbw = wfGetDB( DB_MASTER );
3233
3234 // Do this at the end of the commit to reduce lock wait timeouts
3235 $dbw->onTransactionPreCommitOrIdle(
3236 function() use ( $dbw, $that, $method, $added, $deleted ) {
3237 $ns = $that->getTitle()->getNamespace();
3238
3239 $addFields = array( 'cat_pages = cat_pages + 1' );
3240 $removeFields = array( 'cat_pages = cat_pages - 1' );
3241 if ( $ns == NS_CATEGORY ) {
3242 $addFields[] = 'cat_subcats = cat_subcats + 1';
3243 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3244 } elseif ( $ns == NS_FILE ) {
3245 $addFields[] = 'cat_files = cat_files + 1';
3246 $removeFields[] = 'cat_files = cat_files - 1';
3247 }
3248
3249 if ( count( $added ) ) {
3250 $insertRows = array();
3251 foreach ( $added as $cat ) {
3252 $insertRows[] = array(
3253 'cat_title' => $cat,
3254 'cat_pages' => 1,
3255 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3256 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3257 );
3258 }
3259 $dbw->upsert(
3260 'category',
3261 $insertRows,
3262 array( 'cat_title' ),
3263 $addFields,
3264 $method
3265 );
3266 }
3267
3268 if ( count( $deleted ) ) {
3269 $dbw->update(
3270 'category',
3271 $removeFields,
3272 array( 'cat_title' => $deleted ),
3273 $method
3274 );
3275 }
3276
3277 foreach ( $added as $catName ) {
3278 $cat = Category::newFromName( $catName );
3279 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3280 }
3281
3282 foreach ( $deleted as $catName ) {
3283 $cat = Category::newFromName( $catName );
3284 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3285 }
3286 }
3287 );
3288 }
3289
3290 /**
3291 * Updates cascading protections
3292 *
3293 * @param $parserOutput ParserOutput object for the current version
3294 */
3295 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3296 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3297 return;
3298 }
3299
3300 // templatelinks or imagelinks tables may have become out of sync,
3301 // especially if using variable-based transclusions.
3302 // For paranoia, check if things have changed and if
3303 // so apply updates to the database. This will ensure
3304 // that cascaded protections apply as soon as the changes
3305 // are visible.
3306
3307 // Get templates from templatelinks and images from imagelinks
3308 $id = $this->getId();
3309
3310 $dbLinks = array();
3311
3312 $dbr = wfGetDB( DB_SLAVE );
3313 $res = $dbr->select( array( 'templatelinks' ),
3314 array( 'tl_namespace', 'tl_title' ),
3315 array( 'tl_from' => $id ),
3316 __METHOD__
3317 );
3318
3319 foreach ( $res as $row ) {
3320 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3321 }
3322
3323 $dbr = wfGetDB( DB_SLAVE );
3324 $res = $dbr->select( array( 'imagelinks' ),
3325 array( 'il_to' ),
3326 array( 'il_from' => $id ),
3327 __METHOD__
3328 );
3329
3330 foreach ( $res as $row ) {
3331 $dbLinks[NS_FILE . ":{$row->il_to}"] = true;
3332 }
3333
3334 // Get templates and images from parser output.
3335 $poLinks = array();
3336 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3337 foreach ( $templates as $dbk => $id ) {
3338 $poLinks["$ns:$dbk"] = true;
3339 }
3340 }
3341 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3342 $poLinks[NS_FILE . ":$dbk"] = true;
3343 }
3344
3345 // Get the diff
3346 $links_diff = array_diff_key( $poLinks, $dbLinks );
3347
3348 if ( count( $links_diff ) > 0 ) {
3349 // Whee, link updates time.
3350 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3351 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3352 $u->doUpdate();
3353 }
3354 }
3355
3356 /**
3357 * Return a list of templates used by this article.
3358 * Uses the templatelinks table
3359 *
3360 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3361 * @return Array of Title objects
3362 */
3363 public function getUsedTemplates() {
3364 return $this->mTitle->getTemplateLinksFrom();
3365 }
3366
3367 /**
3368 * This function is called right before saving the wikitext,
3369 * so we can do things like signatures and links-in-context.
3370 *
3371 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3372 * @param string $text article contents
3373 * @param $user User object: user doing the edit
3374 * @param $popts ParserOptions object: parser options, default options for
3375 * the user loaded if null given
3376 * @return string article contents with altered wikitext markup (signatures
3377 * converted, {{subst:}}, templates, etc.)
3378 */
3379 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3380 global $wgParser, $wgUser;
3381
3382 wfDeprecated( __METHOD__, '1.19' );
3383
3384 $user = is_null( $user ) ? $wgUser : $user;
3385
3386 if ( $popts === null ) {
3387 $popts = ParserOptions::newFromUser( $user );
3388 }
3389
3390 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3391 }
3392
3393 /**
3394 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3395 *
3396 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3397 * @return bool
3398 */
3399 public function isBigDeletion() {
3400 wfDeprecated( __METHOD__, '1.19' );
3401 return $this->mTitle->isBigDeletion();
3402 }
3403
3404 /**
3405 * Get the approximate revision count of this page.
3406 *
3407 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3408 * @return int
3409 */
3410 public function estimateRevisionCount() {
3411 wfDeprecated( __METHOD__, '1.19' );
3412 return $this->mTitle->estimateRevisionCount();
3413 }
3414
3415 /**
3416 * Update the article's restriction field, and leave a log entry.
3417 *
3418 * @deprecated since 1.19
3419 * @param array $limit set of restriction keys
3420 * @param $reason String
3421 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3422 * @param array $expiry per restriction type expiration
3423 * @param $user User The user updating the restrictions
3424 * @return bool true on success
3425 */
3426 public function updateRestrictions(
3427 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3428 ) {
3429 global $wgUser;
3430
3431 $user = is_null( $user ) ? $wgUser : $user;
3432
3433 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3434 }
3435
3436 /**
3437 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3438 * about this page from secondary data stores such as links tables.
3439 *
3440 * @param Content|null $content optional Content object for determining the necessary updates
3441 * @return Array an array of DataUpdates objects
3442 */
3443 public function getDeletionUpdates( Content $content = null ) {
3444 if ( !$content ) {
3445 // load content object, which may be used to determine the necessary updates
3446 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3447 $content = $this->getContent( Revision::RAW );
3448 }
3449
3450 if ( !$content ) {
3451 $updates = array();
3452 } else {
3453 $updates = $content->getDeletionUpdates( $this );
3454 }
3455
3456 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3457 return $updates;
3458 }
3459
3460 }
3461
3462 class PoolWorkArticleView extends PoolCounterWork {
3463
3464 /**
3465 * @var Page
3466 */
3467 private $page;
3468
3469 /**
3470 * @var string
3471 */
3472 private $cacheKey;
3473
3474 /**
3475 * @var integer
3476 */
3477 private $revid;
3478
3479 /**
3480 * @var ParserOptions
3481 */
3482 private $parserOptions;
3483
3484 /**
3485 * @var Content|null
3486 */
3487 private $content = null;
3488
3489 /**
3490 * @var ParserOutput|bool
3491 */
3492 private $parserOutput = false;
3493
3494 /**
3495 * @var bool
3496 */
3497 private $isDirty = false;
3498
3499 /**
3500 * @var Status|bool
3501 */
3502 private $error = false;
3503
3504 /**
3505 * Constructor
3506 *
3507 * @param $page Page|WikiPage
3508 * @param $revid Integer: ID of the revision being parsed
3509 * @param $useParserCache Boolean: whether to use the parser cache
3510 * @param $parserOptions parserOptions to use for the parse operation
3511 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3512 */
3513 public function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $content = null ) {
3514 if ( is_string( $content ) ) { // BC: old style call
3515 $modelId = $page->getRevision()->getContentModel();
3516 $format = $page->getRevision()->getContentFormat();
3517 $content = ContentHandler::makeContent( $content, $page->getTitle(), $modelId, $format );
3518 }
3519
3520 $this->page = $page;
3521 $this->revid = $revid;
3522 $this->cacheable = $useParserCache;
3523 $this->parserOptions = $parserOptions;
3524 $this->content = $content;
3525 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
3526 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
3527 }
3528
3529 /**
3530 * Get the ParserOutput from this object, or false in case of failure
3531 *
3532 * @return ParserOutput
3533 */
3534 public function getParserOutput() {
3535 return $this->parserOutput;
3536 }
3537
3538 /**
3539 * Get whether the ParserOutput is a dirty one (i.e. expired)
3540 *
3541 * @return bool
3542 */
3543 public function getIsDirty() {
3544 return $this->isDirty;
3545 }
3546
3547 /**
3548 * Get a Status object in case of error or false otherwise
3549 *
3550 * @return Status|bool
3551 */
3552 public function getError() {
3553 return $this->error;
3554 }
3555
3556 /**
3557 * @return bool
3558 */
3559 public function doWork() {
3560 global $wgUseFileCache;
3561
3562 // @todo several of the methods called on $this->page are not declared in Page, but present
3563 // in WikiPage and delegated by Article.
3564
3565 $isCurrent = $this->revid === $this->page->getLatest();
3566
3567 if ( $this->content !== null ) {
3568 $content = $this->content;
3569 } elseif ( $isCurrent ) {
3570 // XXX: why use RAW audience here, and PUBLIC (default) below?
3571 $content = $this->page->getContent( Revision::RAW );
3572 } else {
3573 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
3574
3575 if ( $rev === null ) {
3576 $content = null;
3577 } else {
3578 // XXX: why use PUBLIC audience here (default), and RAW above?
3579 $content = $rev->getContent();
3580 }
3581 }
3582
3583 if ( $content === null ) {
3584 return false;
3585 }
3586
3587 // Reduce effects of race conditions for slow parses (bug 46014)
3588 $cacheTime = wfTimestampNow();
3589
3590 $time = - microtime( true );
3591 $this->parserOutput = $content->getParserOutput( $this->page->getTitle(), $this->revid, $this->parserOptions );
3592 $time += microtime( true );
3593
3594 // Timing hack
3595 if ( $time > 3 ) {
3596 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3597 $this->page->getTitle()->getPrefixedDBkey() ) );
3598 }
3599
3600 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
3601 ParserCache::singleton()->save(
3602 $this->parserOutput, $this->page, $this->parserOptions, $cacheTime );
3603 }
3604
3605 // Make sure file cache is not used on uncacheable content.
3606 // Output that has magic words in it can still use the parser cache
3607 // (if enabled), though it will generally expire sooner.
3608 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
3609 $wgUseFileCache = false;
3610 }
3611
3612 if ( $isCurrent ) {
3613 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
3614 }
3615
3616 return true;
3617 }
3618
3619 /**
3620 * @return bool
3621 */
3622 public function getCachedWork() {
3623 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
3624
3625 if ( $this->parserOutput === false ) {
3626 wfDebug( __METHOD__ . ": parser cache miss\n" );
3627 return false;
3628 } else {
3629 wfDebug( __METHOD__ . ": parser cache hit\n" );
3630 return true;
3631 }
3632 }
3633
3634 /**
3635 * @return bool
3636 */
3637 public function fallback() {
3638 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
3639
3640 if ( $this->parserOutput === false ) {
3641 wfDebugLog( 'dirty', 'dirty missing' );
3642 wfDebug( __METHOD__ . ": no dirty cache\n" );
3643 return false;
3644 } else {
3645 wfDebug( __METHOD__ . ": sending dirty output\n" );
3646 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}" );
3647 $this->isDirty = true;
3648 return true;
3649 }
3650 }
3651
3652 /**
3653 * @param $status Status
3654 * @return bool
3655 */
3656 public function error( $status ) {
3657 $this->error = $status;
3658 return false;
3659 }
3660 }