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