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