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