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