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