Merge "Wrap changes lists in <div class="mw-changeslist" />"
[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 ) {
1665 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1666
1667 // Low-level sanity check
1668 if ( $this->mTitle->getText() === '' ) {
1669 throw new MWException( 'Something is trying to edit an article with an empty title' );
1670 }
1671
1672 wfProfileIn( __METHOD__ );
1673
1674 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1675 wfProfileOut( __METHOD__ );
1676 return Status::newFatal( 'content-not-allowed-here',
1677 ContentHandler::getLocalizedName( $content->getModel() ),
1678 $this->getTitle()->getPrefixedText() );
1679 }
1680
1681 $user = is_null( $user ) ? $wgUser : $user;
1682 $status = Status::newGood( array() );
1683
1684 // Load the data from the master database if needed.
1685 // The caller may already loaded it from the master or even loaded it using
1686 // SELECT FOR UPDATE, so do not override that using clear().
1687 $this->loadPageData( 'fromdbmaster' );
1688
1689 $flags = $this->checkFlags( $flags );
1690
1691 // handle hook
1692 $hook_args = array( &$this, &$user, &$content, &$summary,
1693 $flags & EDIT_MINOR, null, null, &$flags, &$status );
1694
1695 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1696 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1697
1698 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1699
1700 if ( $status->isOK() ) {
1701 $status->fatal( 'edit-hook-aborted' );
1702 }
1703
1704 wfProfileOut( __METHOD__ );
1705 return $status;
1706 }
1707
1708 // Silently ignore EDIT_MINOR if not allowed
1709 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1710 $bot = $flags & EDIT_FORCE_BOT;
1711
1712 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1713
1714 $oldsize = $old_content ? $old_content->getSize() : 0;
1715 $oldid = $this->getLatest();
1716 $oldIsRedirect = $this->isRedirect();
1717 $oldcountable = $this->isCountable();
1718
1719 $handler = $content->getContentHandler();
1720
1721 // Provide autosummaries if one is not provided and autosummaries are enabled.
1722 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1723 if ( !$old_content ) {
1724 $old_content = null;
1725 }
1726 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1727 }
1728
1729 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1730 $serialized = $editInfo->pst;
1731
1732 /**
1733 * @var Content $content
1734 */
1735 $content = $editInfo->pstContent;
1736 $newsize = $content->getSize();
1737
1738 $dbw = wfGetDB( DB_MASTER );
1739 $now = wfTimestampNow();
1740 $this->mTimestamp = $now;
1741
1742 if ( $flags & EDIT_UPDATE ) {
1743 // Update article, but only if changed.
1744 $status->value['new'] = false;
1745
1746 if ( !$oldid ) {
1747 // Article gone missing
1748 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1749 $status->fatal( 'edit-gone-missing' );
1750
1751 wfProfileOut( __METHOD__ );
1752 return $status;
1753 } elseif ( !$old_content ) {
1754 // Sanity check for bug 37225
1755 wfProfileOut( __METHOD__ );
1756 throw new MWException( "Could not find text for current revision {$oldid}." );
1757 }
1758
1759 $revision = new Revision( array(
1760 'page' => $this->getId(),
1761 'title' => $this->getTitle(), // for determining the default content model
1762 'comment' => $summary,
1763 'minor_edit' => $isminor,
1764 'text' => $serialized,
1765 'len' => $newsize,
1766 'parent_id' => $oldid,
1767 'user' => $user->getId(),
1768 'user_text' => $user->getName(),
1769 'timestamp' => $now,
1770 'content_model' => $content->getModel(),
1771 'content_format' => $serialisation_format,
1772 ) ); // XXX: pass content object?!
1773
1774 $changed = !$content->equals( $old_content );
1775
1776 if ( $changed ) {
1777 if ( !$content->isValid() ) {
1778 wfProfileOut( __METHOD__ );
1779 throw new MWException( "New content failed validity check!" );
1780 }
1781
1782 $dbw->begin( __METHOD__ );
1783
1784 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1785 $status->merge( $prepStatus );
1786
1787 if ( !$status->isOK() ) {
1788 $dbw->rollback( __METHOD__ );
1789
1790 wfProfileOut( __METHOD__ );
1791 return $status;
1792 }
1793
1794 $revisionId = $revision->insertOn( $dbw );
1795
1796 // Update page
1797 //
1798 // Note that we use $this->mLatest instead of fetching a value from the master DB
1799 // during the course of this function. This makes sure that EditPage can detect
1800 // edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1801 // before this function is called. A previous function used a separate query, this
1802 // creates a window where concurrent edits can cause an ignored edit conflict.
1803 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1804
1805 if ( !$ok ) {
1806 // Belated edit conflict! Run away!!
1807 $status->fatal( 'edit-conflict' );
1808
1809 $dbw->rollback( __METHOD__ );
1810
1811 wfProfileOut( __METHOD__ );
1812 return $status;
1813 }
1814
1815 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1816 // Update recentchanges
1817 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1818 // Mark as patrolled if the user can do so
1819 $patrolled = $wgUseRCPatrol && !count(
1820 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1821 // Add RC row to the DB
1822 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1823 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1824 $revisionId, $patrolled
1825 );
1826
1827 // Log auto-patrolled edits
1828 if ( $patrolled ) {
1829 PatrolLog::record( $rc, true, $user );
1830 }
1831 }
1832 $user->incEditCount();
1833 $dbw->commit( __METHOD__ );
1834 } else {
1835 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1836 // related variables correctly
1837 $revision->setId( $this->getLatest() );
1838 }
1839
1840 // Update links tables, site stats, etc.
1841 $this->doEditUpdates(
1842 $revision,
1843 $user,
1844 array(
1845 'changed' => $changed,
1846 'oldcountable' => $oldcountable
1847 )
1848 );
1849
1850 if ( !$changed ) {
1851 $status->warning( 'edit-no-change' );
1852 $revision = null;
1853 // Update page_touched, this is usually implicit in the page update
1854 // Other cache updates are done in onArticleEdit()
1855 $this->mTitle->invalidateCache();
1856 }
1857 } else {
1858 // Create new article
1859 $status->value['new'] = true;
1860
1861 $dbw->begin( __METHOD__ );
1862
1863 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1864 $status->merge( $prepStatus );
1865
1866 if ( !$status->isOK() ) {
1867 $dbw->rollback( __METHOD__ );
1868
1869 wfProfileOut( __METHOD__ );
1870 return $status;
1871 }
1872
1873 $status->merge( $prepStatus );
1874
1875 // Add the page record; stake our claim on this title!
1876 // This will return false if the article already exists
1877 $newid = $this->insertOn( $dbw );
1878
1879 if ( $newid === false ) {
1880 $dbw->rollback( __METHOD__ );
1881 $status->fatal( 'edit-already-exists' );
1882
1883 wfProfileOut( __METHOD__ );
1884 return $status;
1885 }
1886
1887 // Save the revision text...
1888 $revision = new Revision( array(
1889 'page' => $newid,
1890 'title' => $this->getTitle(), // for determining the default content model
1891 'comment' => $summary,
1892 'minor_edit' => $isminor,
1893 'text' => $serialized,
1894 'len' => $newsize,
1895 'user' => $user->getId(),
1896 'user_text' => $user->getName(),
1897 'timestamp' => $now,
1898 'content_model' => $content->getModel(),
1899 'content_format' => $serialisation_format,
1900 ) );
1901 $revisionId = $revision->insertOn( $dbw );
1902
1903 // Bug 37225: use accessor to get the text as Revision may trim it
1904 $content = $revision->getContent(); // sanity; get normalized version
1905
1906 if ( $content ) {
1907 $newsize = $content->getSize();
1908 }
1909
1910 // Update the page record with revision data
1911 $this->updateRevisionOn( $dbw, $revision, 0 );
1912
1913 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1914
1915 // Update recentchanges
1916 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1917 // Mark as patrolled if the user can do so
1918 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1919 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1920 // Add RC row to the DB
1921 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1922 '', $newsize, $revisionId, $patrolled );
1923
1924 // Log auto-patrolled edits
1925 if ( $patrolled ) {
1926 PatrolLog::record( $rc, true, $user );
1927 }
1928 }
1929 $user->incEditCount();
1930 $dbw->commit( __METHOD__ );
1931
1932 // Update links, etc.
1933 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1934
1935 $hook_args = array( &$this, &$user, $content, $summary,
1936 $flags & EDIT_MINOR, null, null, &$flags, $revision );
1937
1938 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1939 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1940 }
1941
1942 // Do updates right now unless deferral was requested
1943 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1944 DeferredUpdates::doUpdates();
1945 }
1946
1947 // Return the new revision (or null) to the caller
1948 $status->value['revision'] = $revision;
1949
1950 $hook_args = array( &$this, &$user, $content, $summary,
1951 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId );
1952
1953 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1954 wfRunHooks( 'PageContentSaveComplete', $hook_args );
1955
1956 // Promote user to any groups they meet the criteria for
1957 $user->addAutopromoteOnceGroups( 'onEdit' );
1958
1959 wfProfileOut( __METHOD__ );
1960 return $status;
1961 }
1962
1963 /**
1964 * Get parser options suitable for rendering the primary article wikitext
1965 *
1966 * @see ContentHandler::makeParserOptions
1967 *
1968 * @param IContextSource|User|string $context One of the following:
1969 * - IContextSource: Use the User and the Language of the provided
1970 * context
1971 * - User: Use the provided User object and $wgLang for the language,
1972 * so use an IContextSource object if possible.
1973 * - 'canonical': Canonical options (anonymous user with default
1974 * preferences and content language).
1975 * @return ParserOptions
1976 */
1977 public function makeParserOptions( $context ) {
1978 $options = $this->getContentHandler()->makeParserOptions( $context );
1979
1980 if ( $this->getTitle()->isConversionTable() ) {
1981 // @todo ConversionTable should become a separate content model, so we don't need special cases like this one.
1982 $options->disableContentConversion();
1983 }
1984
1985 return $options;
1986 }
1987
1988 /**
1989 * Prepare text which is about to be saved.
1990 * Returns a stdclass with source, pst and output members
1991 *
1992 * @deprecated in 1.21: use prepareContentForEdit instead.
1993 */
1994 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1995 ContentHandler::deprecated( __METHOD__, '1.21' );
1996 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1997 return $this->prepareContentForEdit( $content, $revid, $user );
1998 }
1999
2000 /**
2001 * Prepare content which is about to be saved.
2002 * Returns a stdclass with source, pst and output members
2003 *
2004 * @param Content $content
2005 * @param int|null $revid
2006 * @param User|null $user
2007 * @param string|null $serialization_format
2008 *
2009 * @return bool|object
2010 *
2011 * @since 1.21
2012 */
2013 public function prepareContentForEdit( Content $content, $revid = null, User $user = null,
2014 $serialization_format = null
2015 ) {
2016 global $wgContLang, $wgUser;
2017 $user = is_null( $user ) ? $wgUser : $user;
2018 //XXX: check $user->getId() here???
2019
2020 if ( $this->mPreparedEdit
2021 && $this->mPreparedEdit->newContent
2022 && $this->mPreparedEdit->newContent->equals( $content )
2023 && $this->mPreparedEdit->revid == $revid
2024 && $this->mPreparedEdit->format == $serialization_format
2025 // XXX: also check $user here?
2026 ) {
2027 // Already prepared
2028 return $this->mPreparedEdit;
2029 }
2030
2031 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2032 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2033
2034 $edit = (object)array();
2035 $edit->revid = $revid;
2036
2037 $edit->pstContent = $content ? $content->preSaveTransform( $this->mTitle, $user, $popts ) : null;
2038
2039 $edit->format = $serialization_format;
2040 $edit->popts = $this->makeParserOptions( 'canonical' );
2041 $edit->output = $edit->pstContent ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts ) : null;
2042
2043 $edit->newContent = $content;
2044 $edit->oldContent = $this->getContent( Revision::RAW );
2045
2046 // NOTE: B/C for hooks! don't use these fields!
2047 $edit->newText = $edit->newContent ? ContentHandler::getContentText( $edit->newContent ) : '';
2048 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : '';
2049 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialization_format ) : '';
2050
2051 $this->mPreparedEdit = $edit;
2052 return $edit;
2053 }
2054
2055 /**
2056 * Do standard deferred updates after page edit.
2057 * Update links tables, site stats, search index and message cache.
2058 * Purges pages that include this page if the text was changed here.
2059 * Every 100th edit, prune the recent changes table.
2060 *
2061 * @param $revision Revision object
2062 * @param $user User object that did the revision
2063 * @param array $options of options, following indexes are used:
2064 * - changed: boolean, whether the revision changed the content (default true)
2065 * - created: boolean, whether the revision created the page (default false)
2066 * - oldcountable: boolean or null (default null):
2067 * - boolean: whether the page was counted as an article before that
2068 * revision, only used in changed is true and created is false
2069 * - null: don't change the article count
2070 */
2071 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2072 global $wgEnableParserCache;
2073
2074 wfProfileIn( __METHOD__ );
2075
2076 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2077 $content = $revision->getContent();
2078
2079 // Parse the text
2080 // Be careful not to do pre-save transform twice: $text is usually
2081 // already pre-save transformed once.
2082 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2083 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2084 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2085 } else {
2086 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2087 $editInfo = $this->mPreparedEdit;
2088 }
2089
2090 // Save it to the parser cache
2091 if ( $wgEnableParserCache ) {
2092 $parserCache = ParserCache::singleton();
2093 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
2094 }
2095
2096 // Update the links tables and other secondary data
2097 if ( $content ) {
2098 $recursive = $options['changed']; // bug 50785
2099 $updates = $content->getSecondaryDataUpdates(
2100 $this->getTitle(), null, $recursive, $editInfo->output );
2101 DataUpdate::runUpdates( $updates );
2102 }
2103
2104 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2105
2106 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2107 if ( 0 == mt_rand( 0, 99 ) ) {
2108 // Flush old entries from the `recentchanges` table; we do this on
2109 // random requests so as to avoid an increase in writes for no good reason
2110 RecentChange::purgeExpiredChanges();
2111 }
2112 }
2113
2114 if ( !$this->exists() ) {
2115 wfProfileOut( __METHOD__ );
2116 return;
2117 }
2118
2119 $id = $this->getId();
2120 $title = $this->mTitle->getPrefixedDBkey();
2121 $shortTitle = $this->mTitle->getDBkey();
2122
2123 if ( !$options['changed'] ) {
2124 $good = 0;
2125 $total = 0;
2126 } elseif ( $options['created'] ) {
2127 $good = (int)$this->isCountable( $editInfo );
2128 $total = 1;
2129 } elseif ( $options['oldcountable'] !== null ) {
2130 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2131 $total = 0;
2132 } else {
2133 $good = 0;
2134 $total = 0;
2135 }
2136
2137 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2138 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2139
2140 // If this is another user's talk page, update newtalk.
2141 // Don't do this if $options['changed'] = false (null-edits) nor if
2142 // it's a minor edit and the user doesn't want notifications for those.
2143 if ( $options['changed']
2144 && $this->mTitle->getNamespace() == NS_USER_TALK
2145 && $shortTitle != $user->getTitleKey()
2146 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2147 ) {
2148 $recipient = User::newFromName( $shortTitle, false );
2149 if ( !$recipient ) {
2150 wfDebug( __METHOD__ . ": invalid username\n" );
2151 } else {
2152 // Allow extensions to prevent user notification when a new message is added to their talk page
2153 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2154 if ( User::isIP( $shortTitle ) ) {
2155 // An anonymous user
2156 $recipient->setNewtalk( true, $revision );
2157 } elseif ( $recipient->isLoggedIn() ) {
2158 $recipient->setNewtalk( true, $revision );
2159 } else {
2160 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2161 }
2162 }
2163 }
2164 }
2165
2166 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2167 // XXX: could skip pseudo-messages like js/css here, based on content model.
2168 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2169 if ( $msgtext === false || $msgtext === null ) {
2170 $msgtext = '';
2171 }
2172
2173 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2174 }
2175
2176 if ( $options['created'] ) {
2177 self::onArticleCreate( $this->mTitle );
2178 } else {
2179 self::onArticleEdit( $this->mTitle );
2180 }
2181
2182 wfProfileOut( __METHOD__ );
2183 }
2184
2185 /**
2186 * Edit an article without doing all that other stuff
2187 * The article must already exist; link tables etc
2188 * are not updated, caches are not flushed.
2189 *
2190 * @param string $text text submitted
2191 * @param $user User The relevant user
2192 * @param string $comment comment submitted
2193 * @param $minor Boolean: whereas it's a minor modification
2194 *
2195 * @deprecated since 1.21, use doEditContent() instead.
2196 */
2197 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2198 ContentHandler::deprecated( __METHOD__, "1.21" );
2199
2200 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2201 $this->doQuickEditContent( $content, $user, $comment, $minor );
2202 }
2203
2204 /**
2205 * Edit an article without doing all that other stuff
2206 * The article must already exist; link tables etc
2207 * are not updated, caches are not flushed.
2208 *
2209 * @param Content $content Content submitted
2210 * @param User $user The relevant user
2211 * @param string $comment comment submitted
2212 * @param string $serialisation_format Format for storing the content in the database
2213 * @param bool $minor Whereas it's a minor modification
2214 */
2215 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = false,
2216 $serialisation_format = null
2217 ) {
2218 wfProfileIn( __METHOD__ );
2219
2220 $serialized = $content->serialize( $serialisation_format );
2221
2222 $dbw = wfGetDB( DB_MASTER );
2223 $revision = new Revision( array(
2224 'title' => $this->getTitle(), // for determining the default content model
2225 'page' => $this->getId(),
2226 'text' => $serialized,
2227 'length' => $content->getSize(),
2228 'comment' => $comment,
2229 'minor_edit' => $minor ? 1 : 0,
2230 ) ); // XXX: set the content object?
2231 $revision->insertOn( $dbw );
2232 $this->updateRevisionOn( $dbw, $revision );
2233
2234 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2235
2236 wfProfileOut( __METHOD__ );
2237 }
2238
2239 /**
2240 * Update the article's restriction field, and leave a log entry.
2241 * This works for protection both existing and non-existing pages.
2242 *
2243 * @param array $limit set of restriction keys
2244 * @param array $expiry per restriction type expiration
2245 * @param int &$cascade Set to false if cascading protection isn't allowed.
2246 * @param string $reason
2247 * @param User $user The user updating the restrictions
2248 * @return Status
2249 */
2250 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
2251 global $wgCascadingRestrictionLevels, $wgContLang;
2252
2253 if ( wfReadOnly() ) {
2254 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2255 }
2256
2257 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2258
2259 $id = $this->getId();
2260
2261 if ( !$cascade ) {
2262 $cascade = false;
2263 }
2264
2265 // Take this opportunity to purge out expired restrictions
2266 Title::purgeExpiredRestrictions();
2267
2268 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2269 // we expect a single selection, but the schema allows otherwise.
2270 $isProtected = false;
2271 $protect = false;
2272 $changed = false;
2273
2274 $dbw = wfGetDB( DB_MASTER );
2275
2276 foreach ( $restrictionTypes as $action ) {
2277 if ( !isset( $expiry[$action] ) ) {
2278 $expiry[$action] = $dbw->getInfinity();
2279 }
2280 if ( !isset( $limit[$action] ) ) {
2281 $limit[$action] = '';
2282 } elseif ( $limit[$action] != '' ) {
2283 $protect = true;
2284 }
2285
2286 // Get current restrictions on $action
2287 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2288 if ( $current != '' ) {
2289 $isProtected = true;
2290 }
2291
2292 if ( $limit[$action] != $current ) {
2293 $changed = true;
2294 } elseif ( $limit[$action] != '' ) {
2295 // Only check expiry change if the action is actually being
2296 // protected, since expiry does nothing on an not-protected
2297 // action.
2298 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2299 $changed = true;
2300 }
2301 }
2302 }
2303
2304 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2305 $changed = true;
2306 }
2307
2308 // If nothing has changed, do nothing
2309 if ( !$changed ) {
2310 return Status::newGood();
2311 }
2312
2313 if ( !$protect ) { // No protection at all means unprotection
2314 $revCommentMsg = 'unprotectedarticle';
2315 $logAction = 'unprotect';
2316 } elseif ( $isProtected ) {
2317 $revCommentMsg = 'modifiedarticleprotection';
2318 $logAction = 'modify';
2319 } else {
2320 $revCommentMsg = 'protectedarticle';
2321 $logAction = 'protect';
2322 }
2323
2324 // Truncate for whole multibyte characters
2325 $reason = $wgContLang->truncate( $reason, 255 );
2326
2327 if ( $id ) { // Protection of existing page
2328 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2329 return Status::newGood();
2330 }
2331
2332 // Only certain restrictions can cascade...
2333 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2334 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2335 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2336 }
2337 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2338 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2339 }
2340
2341 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2342 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2343 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2344 }
2345 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2346 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2347 }
2348
2349 // The schema allows multiple restrictions
2350 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2351 $cascade = false;
2352 }
2353
2354 // insert null revision to identify the page protection change as edit summary
2355 $latest = $this->getLatest();
2356 $nullRevision = $this->insertProtectNullRevision( $revCommentMsg, $limit, $expiry, $cascade, $reason );
2357 if ( $nullRevision === null ) {
2358 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2359 }
2360
2361 // Update restrictions table
2362 foreach ( $limit as $action => $restrictions ) {
2363 if ( $restrictions != '' ) {
2364 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2365 array( 'pr_page' => $id,
2366 'pr_type' => $action,
2367 'pr_level' => $restrictions,
2368 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2369 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2370 ),
2371 __METHOD__
2372 );
2373 } else {
2374 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2375 'pr_type' => $action ), __METHOD__ );
2376 }
2377 }
2378
2379 // Clear out legacy restriction fields
2380 $dbw->update(
2381 'page',
2382 array( 'page_restrictions' => '' ),
2383 array( 'page_id' => $id ),
2384 __METHOD__
2385 );
2386
2387 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2388 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2389 } else { // Protection of non-existing page (also known as "title protection")
2390 // Cascade protection is meaningless in this case
2391 $cascade = false;
2392
2393 if ( $limit['create'] != '' ) {
2394 $dbw->replace( 'protected_titles',
2395 array( array( 'pt_namespace', 'pt_title' ) ),
2396 array(
2397 'pt_namespace' => $this->mTitle->getNamespace(),
2398 'pt_title' => $this->mTitle->getDBkey(),
2399 'pt_create_perm' => $limit['create'],
2400 'pt_timestamp' => $dbw->timestamp(),
2401 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2402 'pt_user' => $user->getId(),
2403 'pt_reason' => $reason,
2404 ), __METHOD__
2405 );
2406 } else {
2407 $dbw->delete( 'protected_titles',
2408 array(
2409 'pt_namespace' => $this->mTitle->getNamespace(),
2410 'pt_title' => $this->mTitle->getDBkey()
2411 ), __METHOD__
2412 );
2413 }
2414 }
2415
2416 $this->mTitle->flushRestrictions();
2417 InfoAction::invalidateCache( $this->mTitle );
2418
2419 if ( $logAction == 'unprotect' ) {
2420 $params = array();
2421 } else {
2422 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2423 $params = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2424 }
2425
2426 // Update the protection log
2427 $log = new LogPage( 'protect' );
2428 $log->addEntry( $logAction, $this->mTitle, $reason, $params, $user );
2429
2430 return Status::newGood();
2431 }
2432
2433 /**
2434 * Insert a new null revision for this page.
2435 *
2436 * @param string $revCommentMsg comment message key for the revision
2437 * @param array $limit set of restriction keys
2438 * @param array $expiry per restriction type expiration
2439 * @param int $cascade Set to false if cascading protection isn't allowed.
2440 * @param string $reason
2441 * @return Revision|null on error
2442 */
2443 public function insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason ) {
2444 global $wgContLang;
2445 $dbw = wfGetDB( DB_MASTER );
2446
2447 // Prepare a null revision to be added to the history
2448 $editComment = $wgContLang->ucfirst(
2449 wfMessage(
2450 $revCommentMsg,
2451 $this->mTitle->getPrefixedText()
2452 )->inContentLanguage()->text()
2453 );
2454 if ( $reason ) {
2455 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2456 }
2457 $protectDescription = $this->protectDescription( $limit, $expiry );
2458 if ( $protectDescription ) {
2459 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2460 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2461 }
2462 if ( $cascade ) {
2463 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2464 $editComment .= wfMessage( 'brackets' )->params(
2465 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2466 )->inContentLanguage()->text();
2467 }
2468
2469 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true );
2470 if ( $nullRev ) {
2471 $nullRev->insertOn( $dbw );
2472
2473 // Update page record and touch page
2474 $oldLatest = $nullRev->getParentId();
2475 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2476 }
2477
2478 return $nullRev;
2479 }
2480
2481 /**
2482 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2483 * @return string
2484 */
2485 protected function formatExpiry( $expiry ) {
2486 global $wgContLang;
2487 $dbr = wfGetDB( DB_SLAVE );
2488
2489 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2490 if ( $encodedExpiry != 'infinity' ) {
2491 return wfMessage(
2492 'protect-expiring',
2493 $wgContLang->timeanddate( $expiry, false, false ),
2494 $wgContLang->date( $expiry, false, false ),
2495 $wgContLang->time( $expiry, false, false )
2496 )->inContentLanguage()->text();
2497 } else {
2498 return wfMessage( 'protect-expiry-indefinite' )
2499 ->inContentLanguage()->text();
2500 }
2501 }
2502
2503 /**
2504 * Builds the description to serve as comment for the edit.
2505 *
2506 * @param array $limit set of restriction keys
2507 * @param array $expiry per restriction type expiration
2508 * @return string
2509 */
2510 public function protectDescription( array $limit, array $expiry ) {
2511 $protectDescription = '';
2512
2513 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2514 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2515 # All possible message keys are listed here for easier grepping:
2516 # * restriction-create
2517 # * restriction-edit
2518 # * restriction-move
2519 # * restriction-upload
2520 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2521 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2522 # with '' filtered out. All possible message keys are listed below:
2523 # * protect-level-autoconfirmed
2524 # * protect-level-sysop
2525 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2526
2527 $expiryText = $this->formatExpiry( $expiry[$action] );
2528
2529 if ( $protectDescription !== '' ) {
2530 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2531 }
2532 $protectDescription .= wfMessage( 'protect-summary-desc' )
2533 ->params( $actionText, $restrictionsText, $expiryText )
2534 ->inContentLanguage()->text();
2535 }
2536
2537 return $protectDescription;
2538 }
2539
2540 /**
2541 * Builds the description to serve as comment for the log entry.
2542 *
2543 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2544 * protect description text. Keep them in old format to avoid breaking compatibility.
2545 * TODO: Fix protection log to store structured description and format it on-the-fly.
2546 *
2547 * @param array $limit set of restriction keys
2548 * @param array $expiry per restriction type expiration
2549 * @return string
2550 */
2551 public function protectDescriptionLog( array $limit, array $expiry ) {
2552 global $wgContLang;
2553
2554 $protectDescriptionLog = '';
2555
2556 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2557 $expiryText = $this->formatExpiry( $expiry[$action] );
2558 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2559 }
2560
2561 return trim( $protectDescriptionLog );
2562 }
2563
2564 /**
2565 * Take an array of page restrictions and flatten it to a string
2566 * suitable for insertion into the page_restrictions field.
2567 * @param $limit Array
2568 * @throws MWException
2569 * @return String
2570 */
2571 protected static function flattenRestrictions( $limit ) {
2572 if ( !is_array( $limit ) ) {
2573 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2574 }
2575
2576 $bits = array();
2577 ksort( $limit );
2578
2579 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2580 $bits[] = "$action=$restrictions";
2581 }
2582
2583 return implode( ':', $bits );
2584 }
2585
2586 /**
2587 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2588 * backwards compatibility, if you care about error reporting you should use
2589 * doDeleteArticleReal() instead.
2590 *
2591 * Deletes the article with database consistency, writes logs, purges caches
2592 *
2593 * @param string $reason delete reason for deletion log
2594 * @param $suppress boolean suppress all revisions and log the deletion in
2595 * the suppression log instead of the deletion log
2596 * @param int $id article ID
2597 * @param $commit boolean defaults to true, triggers transaction end
2598 * @param &$error Array of errors to append to
2599 * @param $user User The deleting user
2600 * @return boolean true if successful
2601 */
2602 public function doDeleteArticle(
2603 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2604 ) {
2605 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2606 return $status->isGood();
2607 }
2608
2609 /**
2610 * Back-end article deletion
2611 * Deletes the article with database consistency, writes logs, purges caches
2612 *
2613 * @since 1.19
2614 *
2615 * @param string $reason delete reason for deletion log
2616 * @param $suppress boolean suppress all revisions and log the deletion in
2617 * the suppression log instead of the deletion log
2618 * @param int $id article ID
2619 * @param $commit boolean defaults to true, triggers transaction end
2620 * @param &$error Array of errors to append to
2621 * @param $user User The deleting user
2622 * @return Status: Status object; if successful, $status->value is the log_id of the
2623 * deletion log entry. If the page couldn't be deleted because it wasn't
2624 * found, $status is a non-fatal 'cannotdelete' error
2625 */
2626 public function doDeleteArticleReal(
2627 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2628 ) {
2629 global $wgUser, $wgContentHandlerUseDB;
2630
2631 wfDebug( __METHOD__ . "\n" );
2632
2633 $status = Status::newGood();
2634
2635 if ( $this->mTitle->getDBkey() === '' ) {
2636 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2637 return $status;
2638 }
2639
2640 $user = is_null( $user ) ? $wgUser : $user;
2641 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2642 if ( $status->isOK() ) {
2643 // Hook aborted but didn't set a fatal status
2644 $status->fatal( 'delete-hook-aborted' );
2645 }
2646 return $status;
2647 }
2648
2649 if ( $id == 0 ) {
2650 $this->loadPageData( 'forupdate' );
2651 $id = $this->getID();
2652 if ( $id == 0 ) {
2653 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2654 return $status;
2655 }
2656 }
2657
2658 // Bitfields to further suppress the content
2659 if ( $suppress ) {
2660 $bitfield = 0;
2661 // This should be 15...
2662 $bitfield |= Revision::DELETED_TEXT;
2663 $bitfield |= Revision::DELETED_COMMENT;
2664 $bitfield |= Revision::DELETED_USER;
2665 $bitfield |= Revision::DELETED_RESTRICTED;
2666 } else {
2667 $bitfield = 'rev_deleted';
2668 }
2669
2670 // we need to remember the old content so we can use it to generate all deletion updates.
2671 $content = $this->getContent( Revision::RAW );
2672
2673 $dbw = wfGetDB( DB_MASTER );
2674 $dbw->begin( __METHOD__ );
2675 // For now, shunt the revision data into the archive table.
2676 // Text is *not* removed from the text table; bulk storage
2677 // is left intact to avoid breaking block-compression or
2678 // immutable storage schemes.
2679 //
2680 // For backwards compatibility, note that some older archive
2681 // table entries will have ar_text and ar_flags fields still.
2682 //
2683 // In the future, we may keep revisions and mark them with
2684 // the rev_deleted field, which is reserved for this purpose.
2685
2686 $row = array(
2687 'ar_namespace' => 'page_namespace',
2688 'ar_title' => 'page_title',
2689 'ar_comment' => 'rev_comment',
2690 'ar_user' => 'rev_user',
2691 'ar_user_text' => 'rev_user_text',
2692 'ar_timestamp' => 'rev_timestamp',
2693 'ar_minor_edit' => 'rev_minor_edit',
2694 'ar_rev_id' => 'rev_id',
2695 'ar_parent_id' => 'rev_parent_id',
2696 'ar_text_id' => 'rev_text_id',
2697 'ar_text' => '\'\'', // Be explicit to appease
2698 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2699 'ar_len' => 'rev_len',
2700 'ar_page_id' => 'page_id',
2701 'ar_deleted' => $bitfield,
2702 'ar_sha1' => 'rev_sha1',
2703 );
2704
2705 if ( $wgContentHandlerUseDB ) {
2706 $row['ar_content_model'] = 'rev_content_model';
2707 $row['ar_content_format'] = 'rev_content_format';
2708 }
2709
2710 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2711 $row,
2712 array(
2713 'page_id' => $id,
2714 'page_id = rev_page'
2715 ), __METHOD__
2716 );
2717
2718 // Now that it's safely backed up, delete it
2719 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2720 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2721
2722 if ( !$ok ) {
2723 $dbw->rollback( __METHOD__ );
2724 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2725 return $status;
2726 }
2727
2728 if ( !$dbw->cascadingDeletes() ) {
2729 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2730 }
2731
2732 $this->doDeleteUpdates( $id, $content );
2733
2734 // Log the deletion, if the page was suppressed, log it at Oversight instead
2735 $logtype = $suppress ? 'suppress' : 'delete';
2736
2737 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2738 $logEntry->setPerformer( $user );
2739 $logEntry->setTarget( $this->mTitle );
2740 $logEntry->setComment( $reason );
2741 $logid = $logEntry->insert();
2742 $logEntry->publish( $logid );
2743
2744 if ( $commit ) {
2745 $dbw->commit( __METHOD__ );
2746 }
2747
2748 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2749 $status->value = $logid;
2750 return $status;
2751 }
2752
2753 /**
2754 * Do some database updates after deletion
2755 *
2756 * @param int $id page_id value of the page being deleted
2757 * @param $content Content: optional page content to be used when determining the required updates.
2758 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2759 */
2760 public function doDeleteUpdates( $id, Content $content = null ) {
2761 // update site status
2762 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2763
2764 // remove secondary indexes, etc
2765 $updates = $this->getDeletionUpdates( $content );
2766 DataUpdate::runUpdates( $updates );
2767
2768 // Reparse any pages transcluding this page
2769 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2770
2771 // Clear caches
2772 WikiPage::onArticleDelete( $this->mTitle );
2773
2774 // Reset this object and the Title object
2775 $this->loadFromRow( false, self::READ_LATEST );
2776
2777 // Search engine
2778 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2779 }
2780
2781 /**
2782 * Roll back the most recent consecutive set of edits to a page
2783 * from the same user; fails if there are no eligible edits to
2784 * roll back to, e.g. user is the sole contributor. This function
2785 * performs permissions checks on $user, then calls commitRollback()
2786 * to do the dirty work
2787 *
2788 * @todo Separate the business/permission stuff out from backend code
2789 *
2790 * @param string $fromP Name of the user whose edits to rollback.
2791 * @param string $summary Custom summary. Set to default summary if empty.
2792 * @param string $token Rollback token.
2793 * @param $bot Boolean: If true, mark all reverted edits as bot.
2794 *
2795 * @param array $resultDetails contains result-specific array of additional values
2796 * 'alreadyrolled' : 'current' (rev)
2797 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2798 *
2799 * @param $user User The user performing the rollback
2800 * @return array of errors, each error formatted as
2801 * array(messagekey, param1, param2, ...).
2802 * On success, the array is empty. This array can also be passed to
2803 * OutputPage::showPermissionsErrorPage().
2804 */
2805 public function doRollback(
2806 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2807 ) {
2808 $resultDetails = null;
2809
2810 // Check permissions
2811 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2812 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2813 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2814
2815 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2816 $errors[] = array( 'sessionfailure' );
2817 }
2818
2819 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2820 $errors[] = array( 'actionthrottledtext' );
2821 }
2822
2823 // If there were errors, bail out now
2824 if ( !empty( $errors ) ) {
2825 return $errors;
2826 }
2827
2828 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2829 }
2830
2831 /**
2832 * Backend implementation of doRollback(), please refer there for parameter
2833 * and return value documentation
2834 *
2835 * NOTE: This function does NOT check ANY permissions, it just commits the
2836 * rollback to the DB. Therefore, you should only call this function direct-
2837 * ly if you want to use custom permissions checks. If you don't, use
2838 * doRollback() instead.
2839 * @param string $fromP Name of the user whose edits to rollback.
2840 * @param string $summary Custom summary. Set to default summary if empty.
2841 * @param $bot Boolean: If true, mark all reverted edits as bot.
2842 *
2843 * @param array $resultDetails contains result-specific array of additional values
2844 * @param $guser User The user performing the rollback
2845 * @return array
2846 */
2847 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2848 global $wgUseRCPatrol, $wgContLang;
2849
2850 $dbw = wfGetDB( DB_MASTER );
2851
2852 if ( wfReadOnly() ) {
2853 return array( array( 'readonlytext' ) );
2854 }
2855
2856 // Get the last editor
2857 $current = $this->getRevision();
2858 if ( is_null( $current ) ) {
2859 // Something wrong... no page?
2860 return array( array( 'notanarticle' ) );
2861 }
2862
2863 $from = str_replace( '_', ' ', $fromP );
2864 // User name given should match up with the top revision.
2865 // If the user was deleted then $from should be empty.
2866 if ( $from != $current->getUserText() ) {
2867 $resultDetails = array( 'current' => $current );
2868 return array( array( 'alreadyrolled',
2869 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2870 htmlspecialchars( $fromP ),
2871 htmlspecialchars( $current->getUserText() )
2872 ) );
2873 }
2874
2875 // Get the last edit not by this guy...
2876 // Note: these may not be public values
2877 $user = intval( $current->getRawUser() );
2878 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2879 $s = $dbw->selectRow( 'revision',
2880 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2881 array( 'rev_page' => $current->getPage(),
2882 "rev_user != {$user} OR rev_user_text != {$user_text}"
2883 ), __METHOD__,
2884 array( 'USE INDEX' => 'page_timestamp',
2885 'ORDER BY' => 'rev_timestamp DESC' )
2886 );
2887 if ( $s === false ) {
2888 // No one else ever edited this page
2889 return array( array( 'cantrollback' ) );
2890 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2891 // Only admins can see this text
2892 return array( array( 'notvisiblerev' ) );
2893 }
2894
2895 $set = array();
2896 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2897 // Mark all reverted edits as bot
2898 $set['rc_bot'] = 1;
2899 }
2900
2901 if ( $wgUseRCPatrol ) {
2902 // Mark all reverted edits as patrolled
2903 $set['rc_patrolled'] = 1;
2904 }
2905
2906 if ( count( $set ) ) {
2907 $dbw->update( 'recentchanges', $set,
2908 array( /* WHERE */
2909 'rc_cur_id' => $current->getPage(),
2910 'rc_user_text' => $current->getUserText(),
2911 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
2912 ), __METHOD__
2913 );
2914 }
2915
2916 // Generate the edit summary if necessary
2917 $target = Revision::newFromId( $s->rev_id );
2918 if ( empty( $summary ) ) {
2919 if ( $from == '' ) { // no public user name
2920 $summary = wfMessage( 'revertpage-nouser' );
2921 } else {
2922 $summary = wfMessage( 'revertpage' );
2923 }
2924 }
2925
2926 // Allow the custom summary to use the same args as the default message
2927 $args = array(
2928 $target->getUserText(), $from, $s->rev_id,
2929 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2930 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2931 );
2932 if ( $summary instanceof Message ) {
2933 $summary = $summary->params( $args )->inContentLanguage()->text();
2934 } else {
2935 $summary = wfMsgReplaceArgs( $summary, $args );
2936 }
2937
2938 // Trim spaces on user supplied text
2939 $summary = trim( $summary );
2940
2941 // Truncate for whole multibyte characters.
2942 $summary = $wgContLang->truncate( $summary, 255 );
2943
2944 // Save
2945 $flags = EDIT_UPDATE;
2946
2947 if ( $guser->isAllowed( 'minoredit' ) ) {
2948 $flags |= EDIT_MINOR;
2949 }
2950
2951 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2952 $flags |= EDIT_FORCE_BOT;
2953 }
2954
2955 // Actually store the edit
2956 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2957
2958 if ( !$status->isOK() ) {
2959 return $status->getErrorsArray();
2960 }
2961
2962 if ( !empty( $status->value['revision'] ) ) {
2963 $revId = $status->value['revision']->getId();
2964 } else {
2965 $revId = false;
2966 }
2967
2968 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2969
2970 $resultDetails = array(
2971 'summary' => $summary,
2972 'current' => $current,
2973 'target' => $target,
2974 'newid' => $revId
2975 );
2976
2977 return array();
2978 }
2979
2980 /**
2981 * The onArticle*() functions are supposed to be a kind of hooks
2982 * which should be called whenever any of the specified actions
2983 * are done.
2984 *
2985 * This is a good place to put code to clear caches, for instance.
2986 *
2987 * This is called on page move and undelete, as well as edit
2988 *
2989 * @param $title Title object
2990 */
2991 public static function onArticleCreate( $title ) {
2992 // Update existence markers on article/talk tabs...
2993 if ( $title->isTalkPage() ) {
2994 $other = $title->getSubjectPage();
2995 } else {
2996 $other = $title->getTalkPage();
2997 }
2998
2999 $other->invalidateCache();
3000 $other->purgeSquid();
3001
3002 $title->touchLinks();
3003 $title->purgeSquid();
3004 $title->deleteTitleProtection();
3005 }
3006
3007 /**
3008 * Clears caches when article is deleted
3009 *
3010 * @param $title Title
3011 */
3012 public static function onArticleDelete( $title ) {
3013 // Update existence markers on article/talk tabs...
3014 if ( $title->isTalkPage() ) {
3015 $other = $title->getSubjectPage();
3016 } else {
3017 $other = $title->getTalkPage();
3018 }
3019
3020 $other->invalidateCache();
3021 $other->purgeSquid();
3022
3023 $title->touchLinks();
3024 $title->purgeSquid();
3025
3026 // File cache
3027 HTMLFileCache::clearFileCache( $title );
3028 InfoAction::invalidateCache( $title );
3029
3030 // Messages
3031 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3032 MessageCache::singleton()->replace( $title->getDBkey(), false );
3033 }
3034
3035 // Images
3036 if ( $title->getNamespace() == NS_FILE ) {
3037 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3038 $update->doUpdate();
3039 }
3040
3041 // User talk pages
3042 if ( $title->getNamespace() == NS_USER_TALK ) {
3043 $user = User::newFromName( $title->getText(), false );
3044 if ( $user ) {
3045 $user->setNewtalk( false );
3046 }
3047 }
3048
3049 // Image redirects
3050 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3051 }
3052
3053 /**
3054 * Purge caches on page update etc
3055 *
3056 * @param $title Title object
3057 * @todo Verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3058 */
3059 public static function onArticleEdit( $title ) {
3060 // Invalidate caches of articles which include this page
3061 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
3062
3063 // Invalidate the caches of all pages which redirect here
3064 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
3065
3066 // Purge squid for this page only
3067 $title->purgeSquid();
3068
3069 // Clear file cache for this page only
3070 HTMLFileCache::clearFileCache( $title );
3071 InfoAction::invalidateCache( $title );
3072 }
3073
3074 /**#@-*/
3075
3076 /**
3077 * Returns a list of categories this page is a member of.
3078 * Results will include hidden categories
3079 *
3080 * @return TitleArray
3081 */
3082 public function getCategories() {
3083 $id = $this->getId();
3084 if ( $id == 0 ) {
3085 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3086 }
3087
3088 $dbr = wfGetDB( DB_SLAVE );
3089 $res = $dbr->select( 'categorylinks',
3090 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3091 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3092 // as not being aliases, and NS_CATEGORY is numeric
3093 array( 'cl_from' => $id ),
3094 __METHOD__ );
3095
3096 return TitleArray::newFromResult( $res );
3097 }
3098
3099 /**
3100 * Returns a list of hidden categories this page is a member of.
3101 * Uses the page_props and categorylinks tables.
3102 *
3103 * @return Array of Title objects
3104 */
3105 public function getHiddenCategories() {
3106 $result = array();
3107 $id = $this->getId();
3108
3109 if ( $id == 0 ) {
3110 return array();
3111 }
3112
3113 $dbr = wfGetDB( DB_SLAVE );
3114 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3115 array( 'cl_to' ),
3116 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3117 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3118 __METHOD__ );
3119
3120 if ( $res !== false ) {
3121 foreach ( $res as $row ) {
3122 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3123 }
3124 }
3125
3126 return $result;
3127 }
3128
3129 /**
3130 * Return an applicable autosummary if one exists for the given edit.
3131 * @param string|null $oldtext the previous text of the page.
3132 * @param string|null $newtext The submitted text of the page.
3133 * @param int $flags bitmask: a bitmask of flags submitted for the edit.
3134 * @return string An appropriate autosummary, or an empty string.
3135 *
3136 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3137 */
3138 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3139 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
3140
3141 ContentHandler::deprecated( __METHOD__, '1.21' );
3142
3143 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3144 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3145 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3146
3147 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3148 }
3149
3150 /**
3151 * Auto-generates a deletion reason
3152 *
3153 * @param &$hasHistory Boolean: whether the page has a history
3154 * @return mixed String containing deletion reason or empty string, or boolean false
3155 * if no revision occurred
3156 */
3157 public function getAutoDeleteReason( &$hasHistory ) {
3158 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3159 }
3160
3161 /**
3162 * Update all the appropriate counts in the category table, given that
3163 * we've added the categories $added and deleted the categories $deleted.
3164 *
3165 * @param array $added The names of categories that were added
3166 * @param array $deleted The names of categories that were deleted
3167 */
3168 public function updateCategoryCounts( array $added, array $deleted ) {
3169 $that = $this;
3170 $method = __METHOD__;
3171 $dbw = wfGetDB( DB_MASTER );
3172
3173 // Do this at the end of the commit to reduce lock wait timeouts
3174 $dbw->onTransactionPreCommitOrIdle(
3175 function() use ( $dbw, $that, $method, $added, $deleted ) {
3176 $ns = $that->getTitle()->getNamespace();
3177
3178 $addFields = array( 'cat_pages = cat_pages + 1' );
3179 $removeFields = array( 'cat_pages = cat_pages - 1' );
3180 if ( $ns == NS_CATEGORY ) {
3181 $addFields[] = 'cat_subcats = cat_subcats + 1';
3182 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3183 } elseif ( $ns == NS_FILE ) {
3184 $addFields[] = 'cat_files = cat_files + 1';
3185 $removeFields[] = 'cat_files = cat_files - 1';
3186 }
3187
3188 if ( count( $added ) ) {
3189 $insertRows = array();
3190 foreach ( $added as $cat ) {
3191 $insertRows[] = array(
3192 'cat_title' => $cat,
3193 'cat_pages' => 1,
3194 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3195 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3196 );
3197 }
3198 $dbw->upsert(
3199 'category',
3200 $insertRows,
3201 array( 'cat_title' ),
3202 $addFields,
3203 $method
3204 );
3205 }
3206
3207 if ( count( $deleted ) ) {
3208 $dbw->update(
3209 'category',
3210 $removeFields,
3211 array( 'cat_title' => $deleted ),
3212 $method
3213 );
3214 }
3215
3216 foreach ( $added as $catName ) {
3217 $cat = Category::newFromName( $catName );
3218 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3219 }
3220
3221 foreach ( $deleted as $catName ) {
3222 $cat = Category::newFromName( $catName );
3223 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3224 }
3225 }
3226 );
3227 }
3228
3229 /**
3230 * Updates cascading protections
3231 *
3232 * @param $parserOutput ParserOutput object for the current version
3233 */
3234 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3235 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3236 return;
3237 }
3238
3239 // templatelinks table may have become out of sync,
3240 // especially if using variable-based transclusions.
3241 // For paranoia, check if things have changed and if
3242 // so apply updates to the database. This will ensure
3243 // that cascaded protections apply as soon as the changes
3244 // are visible.
3245
3246 // Get templates from templatelinks
3247 $id = $this->getId();
3248
3249 $tlTemplates = array();
3250
3251 $dbr = wfGetDB( DB_SLAVE );
3252 $res = $dbr->select( array( 'templatelinks' ),
3253 array( 'tl_namespace', 'tl_title' ),
3254 array( 'tl_from' => $id ),
3255 __METHOD__
3256 );
3257
3258 foreach ( $res as $row ) {
3259 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3260 }
3261
3262 // Get templates from parser output.
3263 $poTemplates = array();
3264 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3265 foreach ( $templates as $dbk => $id ) {
3266 $poTemplates["$ns:$dbk"] = true;
3267 }
3268 }
3269
3270 // Get the diff
3271 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3272
3273 if ( count( $templates_diff ) > 0 ) {
3274 // Whee, link updates time.
3275 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3276 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3277 $u->doUpdate();
3278 }
3279 }
3280
3281 /**
3282 * Return a list of templates used by this article.
3283 * Uses the templatelinks table
3284 *
3285 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3286 * @return Array of Title objects
3287 */
3288 public function getUsedTemplates() {
3289 return $this->mTitle->getTemplateLinksFrom();
3290 }
3291
3292 /**
3293 * Perform article updates on a special page creation.
3294 *
3295 * @param $rev Revision object
3296 *
3297 * @todo This is a shitty interface function. Kill it and replace the
3298 * other shitty functions like doEditUpdates and such so it's not needed
3299 * anymore.
3300 * @deprecated since 1.18, use doEditUpdates()
3301 */
3302 public function createUpdates( $rev ) {
3303 wfDeprecated( __METHOD__, '1.18' );
3304 global $wgUser;
3305 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3306 }
3307
3308 /**
3309 * This function is called right before saving the wikitext,
3310 * so we can do things like signatures and links-in-context.
3311 *
3312 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3313 * @param string $text article contents
3314 * @param $user User object: user doing the edit
3315 * @param $popts ParserOptions object: parser options, default options for
3316 * the user loaded if null given
3317 * @return string article contents with altered wikitext markup (signatures
3318 * converted, {{subst:}}, templates, etc.)
3319 */
3320 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3321 global $wgParser, $wgUser;
3322
3323 wfDeprecated( __METHOD__, '1.19' );
3324
3325 $user = is_null( $user ) ? $wgUser : $user;
3326
3327 if ( $popts === null ) {
3328 $popts = ParserOptions::newFromUser( $user );
3329 }
3330
3331 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3332 }
3333
3334 /**
3335 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3336 *
3337 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3338 * @return bool
3339 */
3340 public function isBigDeletion() {
3341 wfDeprecated( __METHOD__, '1.19' );
3342 return $this->mTitle->isBigDeletion();
3343 }
3344
3345 /**
3346 * Get the approximate revision count of this page.
3347 *
3348 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3349 * @return int
3350 */
3351 public function estimateRevisionCount() {
3352 wfDeprecated( __METHOD__, '1.19' );
3353 return $this->mTitle->estimateRevisionCount();
3354 }
3355
3356 /**
3357 * Update the article's restriction field, and leave a log entry.
3358 *
3359 * @deprecated since 1.19
3360 * @param array $limit set of restriction keys
3361 * @param $reason String
3362 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3363 * @param array $expiry per restriction type expiration
3364 * @param $user User The user updating the restrictions
3365 * @return bool true on success
3366 */
3367 public function updateRestrictions(
3368 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3369 ) {
3370 global $wgUser;
3371
3372 $user = is_null( $user ) ? $wgUser : $user;
3373
3374 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3375 }
3376
3377 /**
3378 * @deprecated since 1.18
3379 */
3380 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3381 wfDeprecated( __METHOD__, '1.18' );
3382 global $wgUser;
3383 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3384 }
3385
3386 /**
3387 * @deprecated since 1.18
3388 */
3389 public function viewUpdates() {
3390 wfDeprecated( __METHOD__, '1.18' );
3391 global $wgUser;
3392 $this->doViewUpdates( $wgUser );
3393 }
3394
3395 /**
3396 * @deprecated since 1.18
3397 * @param $oldid int
3398 * @return bool
3399 */
3400 public function useParserCache( $oldid ) {
3401 wfDeprecated( __METHOD__, '1.18' );
3402 global $wgUser;
3403 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
3404 }
3405
3406 /**
3407 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3408 * about this page from secondary data stores such as links tables.
3409 *
3410 * @param Content|null $content optional Content object for determining the necessary updates
3411 * @return Array an array of DataUpdates objects
3412 */
3413 public function getDeletionUpdates( Content $content = null ) {
3414 if ( !$content ) {
3415 // load content object, which may be used to determine the necessary updates
3416 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3417 $content = $this->getContent( Revision::RAW );
3418 }
3419
3420 if ( !$content ) {
3421 $updates = array();
3422 } else {
3423 $updates = $content->getDeletionUpdates( $this );
3424 }
3425
3426 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3427 return $updates;
3428 }
3429
3430 }
3431
3432 class PoolWorkArticleView extends PoolCounterWork {
3433
3434 /**
3435 * @var Page
3436 */
3437 private $page;
3438
3439 /**
3440 * @var string
3441 */
3442 private $cacheKey;
3443
3444 /**
3445 * @var integer
3446 */
3447 private $revid;
3448
3449 /**
3450 * @var ParserOptions
3451 */
3452 private $parserOptions;
3453
3454 /**
3455 * @var Content|null
3456 */
3457 private $content = null;
3458
3459 /**
3460 * @var ParserOutput|bool
3461 */
3462 private $parserOutput = false;
3463
3464 /**
3465 * @var bool
3466 */
3467 private $isDirty = false;
3468
3469 /**
3470 * @var Status|bool
3471 */
3472 private $error = false;
3473
3474 /**
3475 * Constructor
3476 *
3477 * @param $page Page|WikiPage
3478 * @param $revid Integer: ID of the revision being parsed
3479 * @param $useParserCache Boolean: whether to use the parser cache
3480 * @param $parserOptions parserOptions to use for the parse operation
3481 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3482 */
3483 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $content = null ) {
3484 if ( is_string( $content ) ) { // BC: old style call
3485 $modelId = $page->getRevision()->getContentModel();
3486 $format = $page->getRevision()->getContentFormat();
3487 $content = ContentHandler::makeContent( $content, $page->getTitle(), $modelId, $format );
3488 }
3489
3490 $this->page = $page;
3491 $this->revid = $revid;
3492 $this->cacheable = $useParserCache;
3493 $this->parserOptions = $parserOptions;
3494 $this->content = $content;
3495 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
3496 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
3497 }
3498
3499 /**
3500 * Get the ParserOutput from this object, or false in case of failure
3501 *
3502 * @return ParserOutput
3503 */
3504 public function getParserOutput() {
3505 return $this->parserOutput;
3506 }
3507
3508 /**
3509 * Get whether the ParserOutput is a dirty one (i.e. expired)
3510 *
3511 * @return bool
3512 */
3513 public function getIsDirty() {
3514 return $this->isDirty;
3515 }
3516
3517 /**
3518 * Get a Status object in case of error or false otherwise
3519 *
3520 * @return Status|bool
3521 */
3522 public function getError() {
3523 return $this->error;
3524 }
3525
3526 /**
3527 * @return bool
3528 */
3529 function doWork() {
3530 global $wgUseFileCache;
3531
3532 // @todo several of the methods called on $this->page are not declared in Page, but present
3533 // in WikiPage and delegated by Article.
3534
3535 $isCurrent = $this->revid === $this->page->getLatest();
3536
3537 if ( $this->content !== null ) {
3538 $content = $this->content;
3539 } elseif ( $isCurrent ) {
3540 // XXX: why use RAW audience here, and PUBLIC (default) below?
3541 $content = $this->page->getContent( Revision::RAW );
3542 } else {
3543 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
3544
3545 if ( $rev === null ) {
3546 $content = null;
3547 } else {
3548 // XXX: why use PUBLIC audience here (default), and RAW above?
3549 $content = $rev->getContent();
3550 }
3551 }
3552
3553 if ( $content === null ) {
3554 return false;
3555 }
3556
3557 // Reduce effects of race conditions for slow parses (bug 46014)
3558 $cacheTime = wfTimestampNow();
3559
3560 $time = - microtime( true );
3561 $this->parserOutput = $content->getParserOutput( $this->page->getTitle(), $this->revid, $this->parserOptions );
3562 $time += microtime( true );
3563
3564 // Timing hack
3565 if ( $time > 3 ) {
3566 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3567 $this->page->getTitle()->getPrefixedDBkey() ) );
3568 }
3569
3570 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
3571 ParserCache::singleton()->save(
3572 $this->parserOutput, $this->page, $this->parserOptions, $cacheTime );
3573 }
3574
3575 // Make sure file cache is not used on uncacheable content.
3576 // Output that has magic words in it can still use the parser cache
3577 // (if enabled), though it will generally expire sooner.
3578 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
3579 $wgUseFileCache = false;
3580 }
3581
3582 if ( $isCurrent ) {
3583 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
3584 }
3585
3586 return true;
3587 }
3588
3589 /**
3590 * @return bool
3591 */
3592 function getCachedWork() {
3593 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
3594
3595 if ( $this->parserOutput === false ) {
3596 wfDebug( __METHOD__ . ": parser cache miss\n" );
3597 return false;
3598 } else {
3599 wfDebug( __METHOD__ . ": parser cache hit\n" );
3600 return true;
3601 }
3602 }
3603
3604 /**
3605 * @return bool
3606 */
3607 function fallback() {
3608 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
3609
3610 if ( $this->parserOutput === false ) {
3611 wfDebugLog( 'dirty', "dirty missing\n" );
3612 wfDebug( __METHOD__ . ": no dirty cache\n" );
3613 return false;
3614 } else {
3615 wfDebug( __METHOD__ . ": sending dirty output\n" );
3616 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3617 $this->isDirty = true;
3618 return true;
3619 }
3620 }
3621
3622 /**
3623 * @param $status Status
3624 * @return bool
3625 */
3626 function error( $status ) {
3627 $this->error = $status;
3628 return false;
3629 }
3630 }