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