Merge branch 'Wikidata' of ssh://gerrit.wikimedia.org:29418/mediawiki/core into Wikidata
[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 ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1442 // Whole-page edit; let the whole text through
1443 return $text;
1444 }
1445
1446 if ( !$this->supportsSections() ) {
1447 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1448 }
1449
1450 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() ); # could even make section title, but that's not required.
1451
1452 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1453
1454 return ContentHandler::getContentText( $newContent );
1455 }
1456
1457 /**
1458 * Returns true iff this page's content model supports sections.
1459 *
1460 * @return boolean whether sections are supported.
1461 *
1462 * @todo: the skin should check this and not offer section functionality if sections are not supported.
1463 * @todo: the EditPage should check this and not offer section functionality if sections are not supported.
1464 */
1465 public function supportsSections() {
1466 return $this->getContentHandler()->supportsSections();
1467 }
1468
1469 /**
1470 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1471 * @param $content Content: new content of the section
1472 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1473 * @param $edittime String: revision timestamp or null to use the current revision
1474 *
1475 * @return Content new complete article content, or null if error
1476 *
1477 * @since 1.WD
1478 */
1479 public function replaceSectionContent( $section, Content $sectionContent, $sectionTitle = '', $edittime = null ) {
1480 wfProfileIn( __METHOD__ );
1481
1482 if ( strval( $section ) == '' ) {
1483 // Whole-page edit; let the whole text through
1484 $newContent = $sectionContent;
1485 } else {
1486 if ( !$this->supportsSections() ) {
1487 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1488 }
1489
1490 // Bug 30711: always use current version when adding a new section
1491 if ( is_null( $edittime ) || $section == 'new' ) {
1492 $oldContent = $this->getContent();
1493 if ( ! $oldContent ) {
1494 wfDebug( __METHOD__ . ": no page text\n" );
1495 wfProfileOut( __METHOD__ );
1496 return null;
1497 }
1498 } else {
1499 $dbw = wfGetDB( DB_MASTER );
1500 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1501
1502 if ( !$rev ) {
1503 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1504 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1505 wfProfileOut( __METHOD__ );
1506 return null;
1507 }
1508
1509 $oldContent = $rev->getContent();
1510 }
1511
1512 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1513 }
1514
1515 wfProfileOut( __METHOD__ );
1516 return $newContent;
1517 }
1518
1519 /**
1520 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1521 * @param $flags Int
1522 * @return Int updated $flags
1523 */
1524 function checkFlags( $flags ) {
1525 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1526 if ( $this->mTitle->getArticleID() ) {
1527 $flags |= EDIT_UPDATE;
1528 } else {
1529 $flags |= EDIT_NEW;
1530 }
1531 }
1532
1533 return $flags;
1534 }
1535
1536 /**
1537 * Change an existing article or create a new article. Updates RC and all necessary caches,
1538 * optionally via the deferred update array.
1539 *
1540 * @param $text String: new text
1541 * @param $summary String: edit summary
1542 * @param $flags Integer bitfield:
1543 * EDIT_NEW
1544 * Article is known or assumed to be non-existent, create a new one
1545 * EDIT_UPDATE
1546 * Article is known or assumed to be pre-existing, update it
1547 * EDIT_MINOR
1548 * Mark this edit minor, if the user is allowed to do so
1549 * EDIT_SUPPRESS_RC
1550 * Do not log the change in recentchanges
1551 * EDIT_FORCE_BOT
1552 * Mark the edit a "bot" edit regardless of user rights
1553 * EDIT_DEFER_UPDATES
1554 * Defer some of the updates until the end of index.php
1555 * EDIT_AUTOSUMMARY
1556 * Fill in blank summaries with generated text where possible
1557 *
1558 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1559 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1560 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1561 * edit-already-exists error will be returned. These two conditions are also possible with
1562 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1563 *
1564 * @param $baseRevId int the revision ID this edit was based off, if any
1565 * @param $user User the user doing the edit
1566 *
1567 * @return Status object. Possible errors:
1568 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1569 * edit-gone-missing: In update mode, but the article didn't exist
1570 * edit-conflict: In update mode, the article changed unexpectedly
1571 * edit-no-change: Warning that the text was the same as before
1572 * edit-already-exists: In creation mode, but the article already exists
1573 *
1574 * Extensions may define additional errors.
1575 *
1576 * $return->value will contain an associative array with members as follows:
1577 * new: Boolean indicating if the function attempted to create a new article
1578 * revision: The revision object for the inserted revision, or null
1579 *
1580 * Compatibility note: this function previously returned a boolean value indicating success/failure
1581 *
1582 * @deprecated since 1.WD: use doEditContent() instead.
1583 */
1584 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #@todo: use doEditContent() instead
1585 wfDeprecated( __METHOD__, '1.WD' );
1586
1587 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1588
1589 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1590 }
1591
1592 /**
1593 * Change an existing article or create a new article. Updates RC and all necessary caches,
1594 * optionally via the deferred update array.
1595 *
1596 * @param $content Content: new content
1597 * @param $summary String: edit summary
1598 * @param $flags Integer bitfield:
1599 * EDIT_NEW
1600 * Article is known or assumed to be non-existent, create a new one
1601 * EDIT_UPDATE
1602 * Article is known or assumed to be pre-existing, update it
1603 * EDIT_MINOR
1604 * Mark this edit minor, if the user is allowed to do so
1605 * EDIT_SUPPRESS_RC
1606 * Do not log the change in recentchanges
1607 * EDIT_FORCE_BOT
1608 * Mark the edit a "bot" edit regardless of user rights
1609 * EDIT_DEFER_UPDATES
1610 * Defer some of the updates until the end of index.php
1611 * EDIT_AUTOSUMMARY
1612 * Fill in blank summaries with generated text where possible
1613 *
1614 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1615 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1616 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1617 * edit-already-exists error will be returned. These two conditions are also possible with
1618 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1619 *
1620 * @param $baseRevId the revision ID this edit was based off, if any
1621 * @param $user User the user doing the edit
1622 * @param $serialisation_format String: format for storing the content in the database
1623 *
1624 * @return Status object. Possible errors:
1625 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1626 * edit-gone-missing: In update mode, but the article didn't exist
1627 * edit-conflict: In update mode, the article changed unexpectedly
1628 * edit-no-change: Warning that the text was the same as before
1629 * edit-already-exists: In creation mode, but the article already exists
1630 *
1631 * Extensions may define additional errors.
1632 *
1633 * $return->value will contain an associative array with members as follows:
1634 * new: Boolean indicating if the function attempted to create a new article
1635 * revision: The revision object for the inserted revision, or null
1636 *
1637 * @since 1.WD
1638 */
1639 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
1640 User $user = null, $serialisation_format = null ) {
1641 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1642
1643 # Low-level sanity check
1644 if ( $this->mTitle->getText() === '' ) {
1645 throw new MWException( 'Something is trying to edit an article with an empty title' );
1646 }
1647
1648 wfProfileIn( __METHOD__ );
1649
1650 $user = is_null( $user ) ? $wgUser : $user;
1651 $status = Status::newGood( array() );
1652
1653 // Load the data from the master database if needed.
1654 // The caller may already loaded it from the master or even loaded it using
1655 // SELECT FOR UPDATE, so do not override that using clear().
1656 $this->loadPageData( 'fromdbmaster' );
1657
1658 $flags = $this->checkFlags( $flags );
1659
1660 # call legacy hook
1661 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary,
1662 $flags & EDIT_MINOR, null, null, &$flags, &$status ) );
1663
1664 if ( $hook_ok && Hooks::isRegistered( 'ArticleSave' ) ) { # avoid serialization overhead if the hook isn't present
1665 $content_text = $content->serialize();
1666 $txt = $content_text; # clone
1667
1668 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary,
1669 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ); #TODO: survey extensions using this hook
1670
1671 if ( $txt !== $content_text ) {
1672 # if the text changed, unserialize the new version to create an updated Content object.
1673 $content = $content->getContentHandler()->unserializeContent( $txt );
1674 }
1675 }
1676
1677 if ( !$hook_ok ) {
1678 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1679
1680 if ( $status->isOK() ) {
1681 $status->fatal( 'edit-hook-aborted' );
1682 }
1683
1684 wfProfileOut( __METHOD__ );
1685 return $status;
1686 }
1687
1688 # Silently ignore EDIT_MINOR if not allowed
1689 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1690 $bot = $flags & EDIT_FORCE_BOT;
1691
1692 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1693
1694 $oldsize = $old_content ? $old_content->getSize() : 0;
1695 $oldid = $this->getLatest();
1696 $oldIsRedirect = $this->isRedirect();
1697 $oldcountable = $this->isCountable();
1698
1699 $handler = $content->getContentHandler();
1700
1701 # Provide autosummaries if one is not provided and autosummaries are enabled.
1702 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1703 if ( !$old_content ) $old_content = null;
1704 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1705 }
1706
1707 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1708 $serialized = $editInfo->pst;
1709 $content = $editInfo->pstContent;
1710 $newsize = $content->getSize();
1711
1712 $dbw = wfGetDB( DB_MASTER );
1713 $now = wfTimestampNow();
1714 $this->mTimestamp = $now;
1715
1716 if ( $flags & EDIT_UPDATE ) {
1717 # Update article, but only if changed.
1718 $status->value['new'] = false;
1719
1720 if ( !$oldid ) {
1721 # Article gone missing
1722 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1723 $status->fatal( 'edit-gone-missing' );
1724
1725 wfProfileOut( __METHOD__ );
1726 return $status;
1727 }
1728
1729 $revision = new Revision( array(
1730 'page' => $this->getId(),
1731 'comment' => $summary,
1732 'minor_edit' => $isminor,
1733 'text' => $serialized,
1734 'len' => $newsize,
1735 'parent_id' => $oldid,
1736 'user' => $user->getId(),
1737 'user_text' => $user->getName(),
1738 'timestamp' => $now,
1739 'content_model' => $content->getModel(),
1740 'content_format' => $serialisation_format,
1741 ) ); #XXX: pass content object?!
1742
1743 $changed = !$content->equals( $old_content );
1744
1745 if ( $changed ) {
1746 if ( !$content->isValid() ) {
1747 throw new MWException( "New content failed validity check!" );
1748 }
1749
1750 $dbw->begin( __METHOD__ );
1751
1752 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1753 $status->merge( $prepStatus );
1754
1755 if ( !$status->isOK() ) {
1756 $dbw->rollback();
1757
1758 wfProfileOut( __METHOD__ );
1759 return $status;
1760 }
1761
1762 $revisionId = $revision->insertOn( $dbw );
1763
1764 # Update page
1765 #
1766 # Note that we use $this->mLatest instead of fetching a value from the master DB
1767 # during the course of this function. This makes sure that EditPage can detect
1768 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1769 # before this function is called. A previous function used a separate query, this
1770 # creates a window where concurrent edits can cause an ignored edit conflict.
1771 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1772
1773 if ( !$ok ) {
1774 /* Belated edit conflict! Run away!! */
1775 $status->fatal( 'edit-conflict' );
1776
1777 $revisionId = 0;
1778 $dbw->rollback( __METHOD__ );
1779 } else {
1780 global $wgUseRCPatrol;
1781 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1782 # Update recentchanges
1783 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1784 # Mark as patrolled if the user can do so
1785 $patrolled = $wgUseRCPatrol && !count(
1786 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1787 # Add RC row to the DB
1788 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1789 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1790 $revisionId, $patrolled
1791 );
1792
1793 # Log auto-patrolled edits
1794 if ( $patrolled ) {
1795 PatrolLog::record( $rc, true, $user );
1796 }
1797 }
1798 $user->incEditCount();
1799 $dbw->commit( __METHOD__ );
1800 }
1801 } else {
1802 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1803 // related variables correctly
1804 $revision->setId( $this->getLatest() );
1805 }
1806
1807 // Now that ignore_user_abort is restored, we can respond to fatal errors
1808 if ( !$status->isOK() ) {
1809 wfProfileOut( __METHOD__ );
1810 return $status;
1811 }
1812
1813 # Update links tables, site stats, etc.
1814 $this->doEditUpdates(
1815 $revision,
1816 $user,
1817 array(
1818 'changed' => $changed,
1819 'oldcountable' => $oldcountable
1820 )
1821 );
1822
1823 if ( !$changed ) {
1824 $status->warning( 'edit-no-change' );
1825 $revision = null;
1826 // Update page_touched, this is usually implicit in the page update
1827 // Other cache updates are done in onArticleEdit()
1828 $this->mTitle->invalidateCache();
1829 }
1830 } else {
1831 # Create new article
1832 $status->value['new'] = true;
1833
1834 $dbw->begin( __METHOD__ );
1835
1836 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1837 $status->merge( $prepStatus );
1838
1839 if ( !$status->isOK() ) {
1840 $dbw->rollback();
1841
1842 wfProfileOut( __METHOD__ );
1843 return $status;
1844 }
1845
1846 $status->merge( $prepStatus );
1847
1848 # Add the page record; stake our claim on this title!
1849 # This will return false if the article already exists
1850 $newid = $this->insertOn( $dbw );
1851
1852 if ( $newid === false ) {
1853 $dbw->rollback( __METHOD__ );
1854 $status->fatal( 'edit-already-exists' );
1855
1856 wfProfileOut( __METHOD__ );
1857 return $status;
1858 }
1859
1860 # Save the revision text...
1861 $revision = new Revision( array(
1862 'page' => $newid,
1863 'comment' => $summary,
1864 'minor_edit' => $isminor,
1865 'text' => $serialized,
1866 'len' => $newsize,
1867 'user' => $user->getId(),
1868 'user_text' => $user->getName(),
1869 'timestamp' => $now,
1870 'content_model' => $content->getModel(),
1871 'content_format' => $serialisation_format,
1872 ) );
1873 $revisionId = $revision->insertOn( $dbw );
1874
1875 # Update the page record with revision data
1876 $this->updateRevisionOn( $dbw, $revision, 0 );
1877
1878 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1879
1880 # Update recentchanges
1881 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1882 global $wgUseRCPatrol, $wgUseNPPatrol;
1883
1884 # Mark as patrolled if the user can do so
1885 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1886 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1887 # Add RC row to the DB
1888 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1889 '', $content->getSize(), $revisionId, $patrolled );
1890
1891 # Log auto-patrolled edits
1892 if ( $patrolled ) {
1893 PatrolLog::record( $rc, true, $user );
1894 }
1895 }
1896 $user->incEditCount();
1897 $dbw->commit( __METHOD__ );
1898
1899 # Update links, etc.
1900 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1901
1902 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary,
1903 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1904
1905 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary,
1906 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1907 }
1908
1909 # Do updates right now unless deferral was requested
1910 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1911 DeferredUpdates::doUpdates();
1912 }
1913
1914 // Return the new revision (or null) to the caller
1915 $status->value['revision'] = $revision;
1916
1917 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary,
1918 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1919
1920 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary,
1921 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1922
1923 # Promote user to any groups they meet the criteria for
1924 $user->addAutopromoteOnceGroups( 'onEdit' );
1925
1926 wfProfileOut( __METHOD__ );
1927 return $status;
1928 }
1929
1930 /**
1931 * Get parser options suitable for rendering the primary article wikitext
1932 * @param User|string $user User object or 'canonical'
1933 * @return ParserOptions
1934 */
1935 public function makeParserOptions( $user ) {
1936 global $wgContLang;
1937 if ( $user instanceof User ) { // settings per user (even anons)
1938 $options = ParserOptions::newFromUser( $user );
1939 } else { // canonical settings
1940 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
1941 }
1942 $options->enableLimitReport(); // show inclusion/loop reports
1943 $options->setTidy( true ); // fix bad HTML
1944 return $options;
1945 }
1946
1947 /**
1948 * Prepare text which is about to be saved.
1949 * Returns a stdclass with source, pst and output members
1950 *
1951 * @deprecated in 1.WD: use prepareContentForEdit instead.
1952 */
1953 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1954 wfDeprecated( __METHOD__, '1.WD' );
1955 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1956 return $this->prepareContentForEdit( $content, $revid , $user );
1957 }
1958
1959 /**
1960 * Prepare content which is about to be saved.
1961 * Returns a stdclass with source, pst and output members
1962 *
1963 * @param \Content $content
1964 * @param null $revid
1965 * @param null|\User $user
1966 * @param null $serialization_format
1967 *
1968 * @return bool|object
1969 *
1970 * @since 1.WD
1971 */
1972 public function prepareContentForEdit( Content $content, $revid = null, User $user = null, $serialization_format = null ) {
1973 global $wgParser, $wgContLang, $wgUser;
1974 $user = is_null( $user ) ? $wgUser : $user;
1975 // @TODO fixme: check $user->getId() here???
1976
1977 if ( $this->mPreparedEdit
1978 && $this->mPreparedEdit->newContent
1979 && $this->mPreparedEdit->newContent->equals( $content )
1980 && $this->mPreparedEdit->revid == $revid
1981 && $this->mPreparedEdit->format == $serialization_format
1982 #XXX: also check $user here?
1983 ) {
1984 // Already prepared
1985 return $this->mPreparedEdit;
1986 }
1987
1988 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
1989 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1990
1991 $edit = (object)array();
1992 $edit->revid = $revid;
1993
1994 $edit->pstContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
1995 $edit->pst = $edit->pstContent->serialize( $serialization_format ); #XXX: do we need this??
1996 $edit->format = $serialization_format;
1997
1998 $edit->popts = $this->makeParserOptions( 'canonical' );
1999
2000 $edit->output = $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts );
2001
2002 $edit->newContent = $content;
2003 $edit->oldContent = $this->getContent( Revision::RAW );
2004
2005 #NOTE: B/C for hooks! don't use these fields!
2006 $edit->newText = ContentHandler::getContentText( $edit->newContent );
2007 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : '';
2008
2009 $this->mPreparedEdit = $edit;
2010
2011 return $edit;
2012 }
2013
2014 /**
2015 * Do standard deferred updates after page edit.
2016 * Update links tables, site stats, search index and message cache.
2017 * Purges pages that include this page if the text was changed here.
2018 * Every 100th edit, prune the recent changes table.
2019 *
2020 * @param $revision Revision object
2021 * @param $user User object that did the revision
2022 * @param $options Array of options, following indexes are used:
2023 * - changed: boolean, whether the revision changed the content (default true)
2024 * - created: boolean, whether the revision created the page (default false)
2025 * - oldcountable: boolean or null (default null):
2026 * - boolean: whether the page was counted as an article before that
2027 * revision, only used in changed is true and created is false
2028 * - null: don't change the article count
2029 */
2030 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2031 global $wgEnableParserCache;
2032
2033 wfProfileIn( __METHOD__ );
2034
2035 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2036 $content = $revision->getContent();
2037
2038 # Parse the text
2039 # Be careful not to double-PST: $text is usually already PST-ed once
2040 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2041 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2042 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2043 } else {
2044 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2045 $editInfo = $this->mPreparedEdit;
2046 }
2047
2048 # Save it to the parser cache
2049 if ( $wgEnableParserCache ) {
2050 $parserCache = ParserCache::singleton();
2051 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
2052 }
2053
2054 # Update the links tables and other secondary data
2055 $contentHandler = $revision->getContentHandler();
2056 $updates = $contentHandler->getSecondaryDataUpdates( $content, $this->getTitle(), null, true, $editInfo->output );
2057 DataUpdate::runUpdates( $updates );
2058
2059 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2060
2061 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2062 if ( 0 == mt_rand( 0, 99 ) ) {
2063 // Flush old entries from the `recentchanges` table; we do this on
2064 // random requests so as to avoid an increase in writes for no good reason
2065 global $wgRCMaxAge;
2066
2067 $dbw = wfGetDB( DB_MASTER );
2068 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2069 $dbw->delete(
2070 'recentchanges',
2071 array( "rc_timestamp < '$cutoff'" ),
2072 __METHOD__
2073 );
2074 }
2075 }
2076
2077 if ( !$this->mTitle->exists() ) {
2078 wfProfileOut( __METHOD__ );
2079 return;
2080 }
2081
2082 $id = $this->getId();
2083 $title = $this->mTitle->getPrefixedDBkey();
2084 $shortTitle = $this->mTitle->getDBkey();
2085
2086 if ( !$options['changed'] ) {
2087 $good = 0;
2088 $total = 0;
2089 } elseif ( $options['created'] ) {
2090 $good = (int)$this->isCountable( $editInfo );
2091 $total = 1;
2092 } elseif ( $options['oldcountable'] !== null ) {
2093 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2094 $total = 0;
2095 } else {
2096 $good = 0;
2097 $total = 0;
2098 }
2099
2100 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2101 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) ); #TODO: let the search engine decide what to do with the content object
2102
2103 # If this is another user's talk page, update newtalk.
2104 # Don't do this if $options['changed'] = false (null-edits) nor if
2105 # it's a minor edit and the user doesn't want notifications for those.
2106 if ( $options['changed']
2107 && $this->mTitle->getNamespace() == NS_USER_TALK
2108 && $shortTitle != $user->getTitleKey()
2109 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2110 ) {
2111 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2112 $other = User::newFromName( $shortTitle, false );
2113 if ( !$other ) {
2114 wfDebug( __METHOD__ . ": invalid username\n" );
2115 } elseif ( User::isIP( $shortTitle ) ) {
2116 // An anonymous user
2117 $other->setNewtalk( true );
2118 } elseif ( $other->isLoggedIn() ) {
2119 $other->setNewtalk( true );
2120 } else {
2121 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2122 }
2123 }
2124 }
2125
2126 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2127 $msgtext = $content->getWikitextForTransclusion(); #XXX: could skip pseudo-messages like js/css here, based on content model.
2128 if ( $msgtext === false || $msgtext === null ) $msgtext = '';
2129
2130 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2131 }
2132
2133 if( $options['created'] ) {
2134 self::onArticleCreate( $this->mTitle );
2135 } else {
2136 self::onArticleEdit( $this->mTitle );
2137 }
2138
2139 wfProfileOut( __METHOD__ );
2140 }
2141
2142 /**
2143 * Edit an article without doing all that other stuff
2144 * The article must already exist; link tables etc
2145 * are not updated, caches are not flushed.
2146 *
2147 * @param $text String: text submitted
2148 * @param $user User The relevant user
2149 * @param $comment String: comment submitted
2150 * @param $minor Boolean: whereas it's a minor modification
2151 *
2152 * @deprecated since 1.WD, use doEditContent() instead.
2153 */
2154 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2155 wfDeprecated( __METHOD__, "1.WD" );
2156
2157 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2158 return $this->doQuickEditContent( $content, $user, $comment , $minor );
2159 }
2160
2161 /**
2162 * Edit an article without doing all that other stuff
2163 * The article must already exist; link tables etc
2164 * are not updated, caches are not flushed.
2165 *
2166 * @param $content Content: content submitted
2167 * @param $user User The relevant user
2168 * @param $comment String: comment submitted
2169 * @param $serialisation_format String: format for storing the content in the database
2170 * @param $minor Boolean: whereas it's a minor modification
2171 */
2172 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = 0, $serialisation_format = null ) {
2173 wfProfileIn( __METHOD__ );
2174
2175 $serialized = $content->serialize( $serialisation_format );
2176
2177 $dbw = wfGetDB( DB_MASTER );
2178 $revision = new Revision( array(
2179 'page' => $this->getId(),
2180 'text' => $serialized,
2181 'length' => $content->getSize(),
2182 'comment' => $comment,
2183 'minor_edit' => $minor ? 1 : 0,
2184 ) ); #XXX: set the content object?
2185 $revision->insertOn( $dbw );
2186 $this->updateRevisionOn( $dbw, $revision );
2187
2188 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2189
2190 wfProfileOut( __METHOD__ );
2191 }
2192
2193 /**
2194 * Update the article's restriction field, and leave a log entry.
2195 * This works for protection both existing and non-existing pages.
2196 *
2197 * @param $limit Array: set of restriction keys
2198 * @param $reason String
2199 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2200 * @param $expiry Array: per restriction type expiration
2201 * @param $user User The user updating the restrictions
2202 * @return Status
2203 */
2204 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
2205 global $wgContLang;
2206
2207 if ( wfReadOnly() ) {
2208 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2209 }
2210
2211 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2212
2213 $id = $this->mTitle->getArticleID();
2214
2215 if ( !$cascade ) {
2216 $cascade = false;
2217 }
2218
2219 // Take this opportunity to purge out expired restrictions
2220 Title::purgeExpiredRestrictions();
2221
2222 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2223 # we expect a single selection, but the schema allows otherwise.
2224 $isProtected = false;
2225 $protect = false;
2226 $changed = false;
2227
2228 $dbw = wfGetDB( DB_MASTER );
2229
2230 foreach ( $restrictionTypes as $action ) {
2231 if ( !isset( $expiry[$action] ) ) {
2232 $expiry[$action] = $dbw->getInfinity();
2233 }
2234 if ( !isset( $limit[$action] ) ) {
2235 $limit[$action] = '';
2236 } elseif ( $limit[$action] != '' ) {
2237 $protect = true;
2238 }
2239
2240 # Get current restrictions on $action
2241 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2242 if ( $current != '' ) {
2243 $isProtected = true;
2244 }
2245
2246 if ( $limit[$action] != $current ) {
2247 $changed = true;
2248 } elseif ( $limit[$action] != '' ) {
2249 # Only check expiry change if the action is actually being
2250 # protected, since expiry does nothing on an not-protected
2251 # action.
2252 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2253 $changed = true;
2254 }
2255 }
2256 }
2257
2258 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2259 $changed = true;
2260 }
2261
2262 # If nothing's changed, do nothing
2263 if ( !$changed ) {
2264 return Status::newGood();
2265 }
2266
2267 if ( !$protect ) { # No protection at all means unprotection
2268 $revCommentMsg = 'unprotectedarticle';
2269 $logAction = 'unprotect';
2270 } elseif ( $isProtected ) {
2271 $revCommentMsg = 'modifiedarticleprotection';
2272 $logAction = 'modify';
2273 } else {
2274 $revCommentMsg = 'protectedarticle';
2275 $logAction = 'protect';
2276 }
2277
2278 $encodedExpiry = array();
2279 $protectDescription = '';
2280 foreach ( $limit as $action => $restrictions ) {
2281 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2282 if ( $restrictions != '' ) {
2283 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2284 if ( $encodedExpiry[$action] != 'infinity' ) {
2285 $protectDescription .= wfMsgForContent( 'protect-expiring',
2286 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2287 $wgContLang->date( $expiry[$action], false, false ) ,
2288 $wgContLang->time( $expiry[$action], false, false ) );
2289 } else {
2290 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
2291 }
2292
2293 $protectDescription .= ') ';
2294 }
2295 }
2296 $protectDescription = trim( $protectDescription );
2297
2298 if ( $id ) { # Protection of existing page
2299 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2300 return Status::newGood();
2301 }
2302
2303 # Only restrictions with the 'protect' right can cascade...
2304 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2305 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2306
2307 # The schema allows multiple restrictions
2308 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2309 $cascade = false;
2310 }
2311
2312 # Update restrictions table
2313 foreach ( $limit as $action => $restrictions ) {
2314 if ( $restrictions != '' ) {
2315 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2316 array( 'pr_page' => $id,
2317 'pr_type' => $action,
2318 'pr_level' => $restrictions,
2319 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2320 'pr_expiry' => $encodedExpiry[$action]
2321 ),
2322 __METHOD__
2323 );
2324 } else {
2325 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2326 'pr_type' => $action ), __METHOD__ );
2327 }
2328 }
2329
2330 # Prepare a null revision to be added to the history
2331 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle->getPrefixedText() ) );
2332 if ( $reason ) {
2333 $editComment .= ": $reason";
2334 }
2335 if ( $protectDescription ) {
2336 $editComment .= " ($protectDescription)";
2337 }
2338 if ( $cascade ) {
2339 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2340 }
2341
2342 # Insert a null revision
2343 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2344 $nullRevId = $nullRevision->insertOn( $dbw );
2345
2346 $latest = $this->getLatest();
2347 # Update page record
2348 $dbw->update( 'page',
2349 array( /* SET */
2350 'page_touched' => $dbw->timestamp(),
2351 'page_restrictions' => '',
2352 'page_latest' => $nullRevId
2353 ), array( /* WHERE */
2354 'page_id' => $id
2355 ), __METHOD__
2356 );
2357
2358 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2359 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2360 } else { # Protection of non-existing page (also known as "title protection")
2361 # Cascade protection is meaningless in this case
2362 $cascade = false;
2363
2364 if ( $limit['create'] != '' ) {
2365 $dbw->replace( 'protected_titles',
2366 array( array( 'pt_namespace', 'pt_title' ) ),
2367 array(
2368 'pt_namespace' => $this->mTitle->getNamespace(),
2369 'pt_title' => $this->mTitle->getDBkey(),
2370 'pt_create_perm' => $limit['create'],
2371 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2372 'pt_expiry' => $encodedExpiry['create'],
2373 'pt_user' => $user->getId(),
2374 'pt_reason' => $reason,
2375 ), __METHOD__
2376 );
2377 } else {
2378 $dbw->delete( 'protected_titles',
2379 array(
2380 'pt_namespace' => $this->mTitle->getNamespace(),
2381 'pt_title' => $this->mTitle->getDBkey()
2382 ), __METHOD__
2383 );
2384 }
2385 }
2386
2387 $this->mTitle->flushRestrictions();
2388
2389 if ( $logAction == 'unprotect' ) {
2390 $logParams = array();
2391 } else {
2392 $logParams = array( $protectDescription, $cascade ? 'cascade' : '' );
2393 }
2394
2395 # Update the protection log
2396 $log = new LogPage( 'protect' );
2397 $log->addEntry( $logAction, $this->mTitle, trim( $reason ), $logParams, $user );
2398
2399 return Status::newGood();
2400 }
2401
2402 /**
2403 * Take an array of page restrictions and flatten it to a string
2404 * suitable for insertion into the page_restrictions field.
2405 * @param $limit Array
2406 * @return String
2407 */
2408 protected static function flattenRestrictions( $limit ) {
2409 if ( !is_array( $limit ) ) {
2410 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2411 }
2412
2413 $bits = array();
2414 ksort( $limit );
2415
2416 foreach ( $limit as $action => $restrictions ) {
2417 if ( $restrictions != '' ) {
2418 $bits[] = "$action=$restrictions";
2419 }
2420 }
2421
2422 return implode( ':', $bits );
2423 }
2424
2425 /**
2426 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2427 * Deletes the article with database consistency, writes logs, purges caches
2428 *
2429 * @param $reason string delete reason for deletion log
2430 * @param $suppress int bitfield
2431 * Revision::DELETED_TEXT
2432 * Revision::DELETED_COMMENT
2433 * Revision::DELETED_USER
2434 * Revision::DELETED_RESTRICTED
2435 * @param $id int article ID
2436 * @param $commit boolean defaults to true, triggers transaction end
2437 * @param &$error Array of errors to append to
2438 * @param $user User The deleting user
2439 * @return boolean true if successful
2440 */
2441 public function doDeleteArticle(
2442 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2443 ) {
2444 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2445 == WikiPage::DELETE_SUCCESS;
2446 }
2447
2448 /**
2449 * Back-end article deletion
2450 * Deletes the article with database consistency, writes logs, purges caches
2451 *
2452 * @param $reason string delete reason for deletion log
2453 * @param $suppress int bitfield
2454 * Revision::DELETED_TEXT
2455 * Revision::DELETED_COMMENT
2456 * Revision::DELETED_USER
2457 * Revision::DELETED_RESTRICTED
2458 * @param $id int article ID
2459 * @param $commit boolean defaults to true, triggers transaction end
2460 * @param &$error Array of errors to append to
2461 * @param $user User The deleting user
2462 * @return int: One of WikiPage::DELETE_* constants
2463 */
2464 public function doDeleteArticleReal(
2465 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2466 ) {
2467 global $wgUser, $wgContentHandlerUseDB;
2468
2469 wfDebug( __METHOD__ . "\n" );
2470
2471 if ( $this->mTitle->getDBkey() === '' ) {
2472 return WikiPage::DELETE_NO_PAGE;
2473 }
2474
2475 $user = is_null( $user ) ? $wgUser : $user;
2476 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2477 return WikiPage::DELETE_HOOK_ABORTED;
2478 }
2479
2480 if ( $id == 0 ) {
2481 $this->loadPageData( 'forupdate' );
2482 $id = $this->getID();
2483 if ( $id == 0 ) {
2484 return WikiPage::DELETE_NO_PAGE;
2485 }
2486 }
2487
2488 // Bitfields to further suppress the content
2489 if ( $suppress ) {
2490 $bitfield = 0;
2491 // This should be 15...
2492 $bitfield |= Revision::DELETED_TEXT;
2493 $bitfield |= Revision::DELETED_COMMENT;
2494 $bitfield |= Revision::DELETED_USER;
2495 $bitfield |= Revision::DELETED_RESTRICTED;
2496 } else {
2497 $bitfield = 'rev_deleted';
2498 }
2499
2500 // we need to remember the old content so we can use it to generate all deletion updates.
2501 $content = $this->getContent( Revision::RAW );
2502
2503 $dbw = wfGetDB( DB_MASTER );
2504 $dbw->begin( __METHOD__ );
2505 // For now, shunt the revision data into the archive table.
2506 // Text is *not* removed from the text table; bulk storage
2507 // is left intact to avoid breaking block-compression or
2508 // immutable storage schemes.
2509 //
2510 // For backwards compatibility, note that some older archive
2511 // table entries will have ar_text and ar_flags fields still.
2512 //
2513 // In the future, we may keep revisions and mark them with
2514 // the rev_deleted field, which is reserved for this purpose.
2515
2516 $row = array(
2517 'ar_namespace' => 'page_namespace',
2518 'ar_title' => 'page_title',
2519 'ar_comment' => 'rev_comment',
2520 'ar_user' => 'rev_user',
2521 'ar_user_text' => 'rev_user_text',
2522 'ar_timestamp' => 'rev_timestamp',
2523 'ar_minor_edit' => 'rev_minor_edit',
2524 'ar_rev_id' => 'rev_id',
2525 'ar_parent_id' => 'rev_parent_id',
2526 'ar_text_id' => 'rev_text_id',
2527 'ar_text' => '\'\'', // Be explicit to appease
2528 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2529 'ar_len' => 'rev_len',
2530 'ar_page_id' => 'page_id',
2531 'ar_deleted' => $bitfield,
2532 'ar_sha1' => 'rev_sha1',
2533 );
2534
2535 if ( $wgContentHandlerUseDB ) {
2536 $row[ 'ar_content_model' ] = 'rev_content_model';
2537 $row[ 'ar_content_format' ] = 'rev_content_format';
2538 }
2539
2540 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2541 $row,
2542 array(
2543 'page_id' => $id,
2544 'page_id = rev_page'
2545 ), __METHOD__
2546 );
2547
2548 # Now that it's safely backed up, delete it
2549 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2550 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2551
2552 if ( !$ok ) {
2553 $dbw->rollback( __METHOD__ );
2554 return WikiPage::DELETE_NO_REVISIONS;
2555 }
2556
2557 $this->doDeleteUpdates( $id, $content );
2558
2559 # Log the deletion, if the page was suppressed, log it at Oversight instead
2560 $logtype = $suppress ? 'suppress' : 'delete';
2561
2562 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2563 $logEntry->setPerformer( $user );
2564 $logEntry->setTarget( $this->mTitle );
2565 $logEntry->setComment( $reason );
2566 $logid = $logEntry->insert();
2567 $logEntry->publish( $logid );
2568
2569 if ( $commit ) {
2570 $dbw->commit( __METHOD__ );
2571 }
2572
2573 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2574 return WikiPage::DELETE_SUCCESS;
2575 }
2576
2577 /**
2578 * Do some database updates after deletion
2579 *
2580 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2581 * @param $content Content: optional page content to be used when determining the required updates.
2582 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2583 */
2584 public function doDeleteUpdates( $id, Content $content = null ) {
2585 # update site status
2586 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2587
2588 # remove secondary indexes, etc
2589 $updates = $this->getDeletionUpdates( $content );
2590 DataUpdate::runUpdates( $updates );
2591
2592 # Clear caches
2593 WikiPage::onArticleDelete( $this->mTitle );
2594
2595 # Reset this object
2596 $this->clear();
2597
2598 # Clear the cached article id so the interface doesn't act like we exist
2599 $this->mTitle->resetArticleID( 0 );
2600 }
2601
2602 /**
2603 * Roll back the most recent consecutive set of edits to a page
2604 * from the same user; fails if there are no eligible edits to
2605 * roll back to, e.g. user is the sole contributor. This function
2606 * performs permissions checks on $user, then calls commitRollback()
2607 * to do the dirty work
2608 *
2609 * @todo: seperate the business/permission stuff out from backend code
2610 *
2611 * @param $fromP String: Name of the user whose edits to rollback.
2612 * @param $summary String: Custom summary. Set to default summary if empty.
2613 * @param $token String: Rollback token.
2614 * @param $bot Boolean: If true, mark all reverted edits as bot.
2615 *
2616 * @param $resultDetails Array: contains result-specific array of additional values
2617 * 'alreadyrolled' : 'current' (rev)
2618 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2619 *
2620 * @param $user User The user performing the rollback
2621 * @return array of errors, each error formatted as
2622 * array(messagekey, param1, param2, ...).
2623 * On success, the array is empty. This array can also be passed to
2624 * OutputPage::showPermissionsErrorPage().
2625 */
2626 public function doRollback(
2627 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2628 ) {
2629 $resultDetails = null;
2630
2631 # Check permissions
2632 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2633 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2634 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2635
2636 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2637 $errors[] = array( 'sessionfailure' );
2638 }
2639
2640 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2641 $errors[] = array( 'actionthrottledtext' );
2642 }
2643
2644 # If there were errors, bail out now
2645 if ( !empty( $errors ) ) {
2646 return $errors;
2647 }
2648
2649 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2650 }
2651
2652 /**
2653 * Backend implementation of doRollback(), please refer there for parameter
2654 * and return value documentation
2655 *
2656 * NOTE: This function does NOT check ANY permissions, it just commits the
2657 * rollback to the DB. Therefore, you should only call this function direct-
2658 * ly if you want to use custom permissions checks. If you don't, use
2659 * doRollback() instead.
2660 * @param $fromP String: Name of the user whose edits to rollback.
2661 * @param $summary String: Custom summary. Set to default summary if empty.
2662 * @param $bot Boolean: If true, mark all reverted edits as bot.
2663 *
2664 * @param $resultDetails Array: contains result-specific array of additional values
2665 * @param $guser User The user performing the rollback
2666 * @return array
2667 */
2668 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2669 global $wgUseRCPatrol, $wgContLang;
2670
2671 $dbw = wfGetDB( DB_MASTER );
2672
2673 if ( wfReadOnly() ) {
2674 return array( array( 'readonlytext' ) );
2675 }
2676
2677 # Get the last editor
2678 $current = $this->getRevision();
2679 if ( is_null( $current ) ) {
2680 # Something wrong... no page?
2681 return array( array( 'notanarticle' ) );
2682 }
2683
2684 $from = str_replace( '_', ' ', $fromP );
2685 # User name given should match up with the top revision.
2686 # If the user was deleted then $from should be empty.
2687 if ( $from != $current->getUserText() ) {
2688 $resultDetails = array( 'current' => $current );
2689 return array( array( 'alreadyrolled',
2690 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2691 htmlspecialchars( $fromP ),
2692 htmlspecialchars( $current->getUserText() )
2693 ) );
2694 }
2695
2696 # Get the last edit not by this guy...
2697 # Note: these may not be public values
2698 $user = intval( $current->getRawUser() );
2699 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2700 $s = $dbw->selectRow( 'revision',
2701 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2702 array( 'rev_page' => $current->getPage(),
2703 "rev_user != {$user} OR rev_user_text != {$user_text}"
2704 ), __METHOD__,
2705 array( 'USE INDEX' => 'page_timestamp',
2706 'ORDER BY' => 'rev_timestamp DESC' )
2707 );
2708 if ( $s === false ) {
2709 # No one else ever edited this page
2710 return array( array( 'cantrollback' ) );
2711 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2712 # Only admins can see this text
2713 return array( array( 'notvisiblerev' ) );
2714 }
2715
2716 $set = array();
2717 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2718 # Mark all reverted edits as bot
2719 $set['rc_bot'] = 1;
2720 }
2721
2722 if ( $wgUseRCPatrol ) {
2723 # Mark all reverted edits as patrolled
2724 $set['rc_patrolled'] = 1;
2725 }
2726
2727 if ( count( $set ) ) {
2728 $dbw->update( 'recentchanges', $set,
2729 array( /* WHERE */
2730 'rc_cur_id' => $current->getPage(),
2731 'rc_user_text' => $current->getUserText(),
2732 "rc_timestamp > '{$s->rev_timestamp}'",
2733 ), __METHOD__
2734 );
2735 }
2736
2737 # Generate the edit summary if necessary
2738 $target = Revision::newFromId( $s->rev_id );
2739 if ( empty( $summary ) ) {
2740 if ( $from == '' ) { // no public user name
2741 $summary = wfMsgForContent( 'revertpage-nouser' );
2742 } else {
2743 $summary = wfMsgForContent( 'revertpage' );
2744 }
2745 }
2746
2747 # Allow the custom summary to use the same args as the default message
2748 $args = array(
2749 $target->getUserText(), $from, $s->rev_id,
2750 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2751 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2752 );
2753 $summary = wfMsgReplaceArgs( $summary, $args );
2754
2755 # Save
2756 $flags = EDIT_UPDATE;
2757
2758 if ( $guser->isAllowed( 'minoredit' ) ) {
2759 $flags |= EDIT_MINOR;
2760 }
2761
2762 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2763 $flags |= EDIT_FORCE_BOT;
2764 }
2765
2766 # Actually store the edit
2767 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2768 if ( !empty( $status->value['revision'] ) ) {
2769 $revId = $status->value['revision']->getId();
2770 } else {
2771 $revId = false;
2772 }
2773
2774 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2775
2776 $resultDetails = array(
2777 'summary' => $summary,
2778 'current' => $current,
2779 'target' => $target,
2780 'newid' => $revId
2781 );
2782
2783 return array();
2784 }
2785
2786 /**
2787 * The onArticle*() functions are supposed to be a kind of hooks
2788 * which should be called whenever any of the specified actions
2789 * are done.
2790 *
2791 * This is a good place to put code to clear caches, for instance.
2792 *
2793 * This is called on page move and undelete, as well as edit
2794 *
2795 * @param $title Title object
2796 */
2797 public static function onArticleCreate( $title ) {
2798 # Update existence markers on article/talk tabs...
2799 if ( $title->isTalkPage() ) {
2800 $other = $title->getSubjectPage();
2801 } else {
2802 $other = $title->getTalkPage();
2803 }
2804
2805 $other->invalidateCache();
2806 $other->purgeSquid();
2807
2808 $title->touchLinks();
2809 $title->purgeSquid();
2810 $title->deleteTitleProtection();
2811 }
2812
2813 /**
2814 * Clears caches when article is deleted
2815 *
2816 * @param $title Title
2817 */
2818 public static function onArticleDelete( $title ) {
2819 # Update existence markers on article/talk tabs...
2820 if ( $title->isTalkPage() ) {
2821 $other = $title->getSubjectPage();
2822 } else {
2823 $other = $title->getTalkPage();
2824 }
2825
2826 $other->invalidateCache();
2827 $other->purgeSquid();
2828
2829 $title->touchLinks();
2830 $title->purgeSquid();
2831
2832 # File cache
2833 HTMLFileCache::clearFileCache( $title );
2834
2835 # Messages
2836 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2837 MessageCache::singleton()->replace( $title->getDBkey(), false );
2838 }
2839
2840 # Images
2841 if ( $title->getNamespace() == NS_FILE ) {
2842 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2843 $update->doUpdate();
2844 }
2845
2846 # User talk pages
2847 if ( $title->getNamespace() == NS_USER_TALK ) {
2848 $user = User::newFromName( $title->getText(), false );
2849 if ( $user ) {
2850 $user->setNewtalk( false );
2851 }
2852 }
2853
2854 # Image redirects
2855 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2856 }
2857
2858 /**
2859 * Purge caches on page update etc
2860 *
2861 * @param $title Title object
2862 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2863 */
2864 public static function onArticleEdit( $title ) {
2865 // Invalidate caches of articles which include this page
2866 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2867
2868
2869 // Invalidate the caches of all pages which redirect here
2870 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2871
2872 # Purge squid for this page only
2873 $title->purgeSquid();
2874
2875 # Clear file cache for this page only
2876 HTMLFileCache::clearFileCache( $title );
2877 }
2878
2879 /**#@-*/
2880
2881 /**
2882 * Returns a list of hidden categories this page is a member of.
2883 * Uses the page_props and categorylinks tables.
2884 *
2885 * @return Array of Title objects
2886 */
2887 public function getHiddenCategories() {
2888 $result = array();
2889 $id = $this->mTitle->getArticleID();
2890
2891 if ( $id == 0 ) {
2892 return array();
2893 }
2894
2895 $dbr = wfGetDB( DB_SLAVE );
2896 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2897 array( 'cl_to' ),
2898 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2899 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2900 __METHOD__ );
2901
2902 if ( $res !== false ) {
2903 foreach ( $res as $row ) {
2904 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2905 }
2906 }
2907
2908 return $result;
2909 }
2910
2911 /**
2912 * Return an applicable autosummary if one exists for the given edit.
2913 * @param $oldtext String|null: the previous text of the page.
2914 * @param $newtext String|null: The submitted text of the page.
2915 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2916 * @return string An appropriate autosummary, or an empty string.
2917 *
2918 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2919 */
2920 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2921 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2922
2923 wfDeprecated( __METHOD__, '1.WD' );
2924
2925 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
2926 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
2927 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
2928
2929 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2930 }
2931
2932 /**
2933 * Auto-generates a deletion reason
2934 *
2935 * @param &$hasHistory Boolean: whether the page has a history
2936 * @return mixed String containing deletion reason or empty string, or boolean false
2937 * if no revision occurred
2938 */
2939 public function getAutoDeleteReason( &$hasHistory ) {
2940 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2941 }
2942
2943 /**
2944 * Update all the appropriate counts in the category table, given that
2945 * we've added the categories $added and deleted the categories $deleted.
2946 *
2947 * @param $added array The names of categories that were added
2948 * @param $deleted array The names of categories that were deleted
2949 */
2950 public function updateCategoryCounts( $added, $deleted ) {
2951 $ns = $this->mTitle->getNamespace();
2952 $dbw = wfGetDB( DB_MASTER );
2953
2954 # First make sure the rows exist. If one of the "deleted" ones didn't
2955 # exist, we might legitimately not create it, but it's simpler to just
2956 # create it and then give it a negative value, since the value is bogus
2957 # anyway.
2958 #
2959 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2960 $insertCats = array_merge( $added, $deleted );
2961 if ( !$insertCats ) {
2962 # Okay, nothing to do
2963 return;
2964 }
2965
2966 $insertRows = array();
2967
2968 foreach ( $insertCats as $cat ) {
2969 $insertRows[] = array(
2970 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2971 'cat_title' => $cat
2972 );
2973 }
2974 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2975
2976 $addFields = array( 'cat_pages = cat_pages + 1' );
2977 $removeFields = array( 'cat_pages = cat_pages - 1' );
2978
2979 if ( $ns == NS_CATEGORY ) {
2980 $addFields[] = 'cat_subcats = cat_subcats + 1';
2981 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2982 } elseif ( $ns == NS_FILE ) {
2983 $addFields[] = 'cat_files = cat_files + 1';
2984 $removeFields[] = 'cat_files = cat_files - 1';
2985 }
2986
2987 if ( $added ) {
2988 $dbw->update(
2989 'category',
2990 $addFields,
2991 array( 'cat_title' => $added ),
2992 __METHOD__
2993 );
2994 }
2995
2996 if ( $deleted ) {
2997 $dbw->update(
2998 'category',
2999 $removeFields,
3000 array( 'cat_title' => $deleted ),
3001 __METHOD__
3002 );
3003 }
3004 }
3005
3006 /**
3007 * Updates cascading protections
3008 *
3009 * @param $parserOutput ParserOutput object for the current version
3010 */
3011 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3012 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3013 return;
3014 }
3015
3016 // templatelinks table may have become out of sync,
3017 // especially if using variable-based transclusions.
3018 // For paranoia, check if things have changed and if
3019 // so apply updates to the database. This will ensure
3020 // that cascaded protections apply as soon as the changes
3021 // are visible.
3022
3023 # Get templates from templatelinks
3024 $id = $this->mTitle->getArticleID();
3025
3026 $tlTemplates = array();
3027
3028 $dbr = wfGetDB( DB_SLAVE );
3029 $res = $dbr->select( array( 'templatelinks' ),
3030 array( 'tl_namespace', 'tl_title' ),
3031 array( 'tl_from' => $id ),
3032 __METHOD__
3033 );
3034
3035 foreach ( $res as $row ) {
3036 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3037 }
3038
3039 # Get templates from parser output.
3040 $poTemplates = array();
3041 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3042 foreach ( $templates as $dbk => $id ) {
3043 $poTemplates["$ns:$dbk"] = true;
3044 }
3045 }
3046
3047 # Get the diff
3048 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3049
3050 if ( count( $templates_diff ) > 0 ) {
3051 # Whee, link updates time.
3052 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3053 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3054 $u->doUpdate();
3055 }
3056 }
3057
3058 /**
3059 * Return a list of templates used by this article.
3060 * Uses the templatelinks table
3061 *
3062 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3063 * @return Array of Title objects
3064 */
3065 public function getUsedTemplates() {
3066 return $this->mTitle->getTemplateLinksFrom();
3067 }
3068
3069 /**
3070 * Perform article updates on a special page creation.
3071 *
3072 * @param $rev Revision object
3073 *
3074 * @todo This is a shitty interface function. Kill it and replace the
3075 * other shitty functions like doEditUpdates and such so it's not needed
3076 * anymore.
3077 * @deprecated since 1.18, use doEditUpdates()
3078 */
3079 public function createUpdates( $rev ) {
3080 wfDeprecated( __METHOD__, '1.18' );
3081 global $wgUser;
3082 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3083 }
3084
3085 /**
3086 * This function is called right before saving the wikitext,
3087 * so we can do things like signatures and links-in-context.
3088 *
3089 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3090 * @param $text String article contents
3091 * @param $user User object: user doing the edit
3092 * @param $popts ParserOptions object: parser options, default options for
3093 * the user loaded if null given
3094 * @return string article contents with altered wikitext markup (signatures
3095 * converted, {{subst:}}, templates, etc.)
3096 */
3097 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3098 global $wgParser, $wgUser;
3099
3100 wfDeprecated( __METHOD__, '1.19' );
3101
3102 $user = is_null( $user ) ? $wgUser : $user;
3103
3104 if ( $popts === null ) {
3105 $popts = ParserOptions::newFromUser( $user );
3106 }
3107
3108 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3109 }
3110
3111 /**
3112 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3113 *
3114 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3115 * @return bool
3116 */
3117 public function isBigDeletion() {
3118 wfDeprecated( __METHOD__, '1.19' );
3119 return $this->mTitle->isBigDeletion();
3120 }
3121
3122 /**
3123 * Get the approximate revision count of this page.
3124 *
3125 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3126 * @return int
3127 */
3128 public function estimateRevisionCount() {
3129 wfDeprecated( __METHOD__, '1.19' );
3130 return $this->mTitle->estimateRevisionCount();
3131 }
3132
3133 /**
3134 * Update the article's restriction field, and leave a log entry.
3135 *
3136 * @deprecated since 1.19
3137 * @param $limit Array: set of restriction keys
3138 * @param $reason String
3139 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3140 * @param $expiry Array: per restriction type expiration
3141 * @param $user User The user updating the restrictions
3142 * @return bool true on success
3143 */
3144 public function updateRestrictions(
3145 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3146 ) {
3147 global $wgUser;
3148
3149 $user = is_null( $user ) ? $wgUser : $user;
3150
3151 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3152 }
3153
3154 /**
3155 * @deprecated since 1.18
3156 */
3157 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3158 wfDeprecated( __METHOD__, '1.18' );
3159 global $wgUser;
3160 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3161 }
3162
3163 /**
3164 * @deprecated since 1.18
3165 */
3166 public function viewUpdates() {
3167 wfDeprecated( __METHOD__, '1.18' );
3168 global $wgUser;
3169 return $this->doViewUpdates( $wgUser );
3170 }
3171
3172 /**
3173 * @deprecated since 1.18
3174 * @return bool
3175 */
3176 public function useParserCache( $oldid ) {
3177 wfDeprecated( __METHOD__, '1.18' );
3178 global $wgUser;
3179 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
3180 }
3181
3182 /**
3183 * Returns a list of updates to be performed when this page is deleted. The updates should remove any infomration
3184 * about this page from secondary data stores such as links tables.
3185 *
3186 * @param Content|null $content optional Content object for determining the necessary updates
3187 * @return Array an array of DataUpdates objects
3188 */
3189 public function getDeletionUpdates( Content $content = null ) {
3190 if ( !$content ) {
3191 // load content object, which may be used to determine the necessary updates
3192 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3193 $content = $this->getContent( Revision::RAW );
3194 }
3195
3196 $updates = $this->getContentHandler()->getDeletionUpdates( $content, $this->mTitle );
3197
3198 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, &$updates ) );
3199 return $updates;
3200 }
3201
3202 }
3203
3204 class PoolWorkArticleView extends PoolCounterWork {
3205
3206 /**
3207 * @var Page
3208 */
3209 private $page;
3210
3211 /**
3212 * @var string
3213 */
3214 private $cacheKey;
3215
3216 /**
3217 * @var integer
3218 */
3219 private $revid;
3220
3221 /**
3222 * @var ParserOptions
3223 */
3224 private $parserOptions;
3225
3226 /**
3227 * @var Content|null
3228 */
3229 private $content = null;
3230
3231 /**
3232 * @var ParserOutput|bool
3233 */
3234 private $parserOutput = false;
3235
3236 /**
3237 * @var bool
3238 */
3239 private $isDirty = false;
3240
3241 /**
3242 * @var Status|bool
3243 */
3244 private $error = false;
3245
3246 /**
3247 * Constructor
3248 *
3249 * @param $page Page
3250 * @param $revid Integer: ID of the revision being parsed
3251 * @param $useParserCache Boolean: whether to use the parser cache
3252 * @param $parserOptions parserOptions to use for the parse operation
3253 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3254 */
3255 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $content = null ) {
3256 if ( is_string($content) ) { #BC: old style call
3257 $modelId = $page->getRevision()->getContentModel();
3258 $format = $page->getRevision()->getContentFormat();
3259 $content = ContentHandler::makeContent( $content, $page->getTitle(), $modelId, $format );
3260 }
3261
3262 $this->page = $page;
3263 $this->revid = $revid;
3264 $this->cacheable = $useParserCache;
3265 $this->parserOptions = $parserOptions;
3266 $this->content = $content;
3267 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
3268 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
3269 }
3270
3271 /**
3272 * Get the ParserOutput from this object, or false in case of failure
3273 *
3274 * @return ParserOutput
3275 */
3276 public function getParserOutput() {
3277 return $this->parserOutput;
3278 }
3279
3280 /**
3281 * Get whether the ParserOutput is a dirty one (i.e. expired)
3282 *
3283 * @return bool
3284 */
3285 public function getIsDirty() {
3286 return $this->isDirty;
3287 }
3288
3289 /**
3290 * Get a Status object in case of error or false otherwise
3291 *
3292 * @return Status|bool
3293 */
3294 public function getError() {
3295 return $this->error;
3296 }
3297
3298 /**
3299 * @return bool
3300 */
3301 function doWork() {
3302 global $wgUseFileCache;
3303
3304 // @todo: several of the methods called on $this->page are not declared in Page, but present in WikiPage and delegated by Article.
3305
3306 $isCurrent = $this->revid === $this->page->getLatest();
3307
3308 if ( $this->content !== null ) {
3309 $content = $this->content;
3310 } elseif ( $isCurrent ) {
3311 $content = $this->page->getContent( Revision::RAW ); #XXX: why use RAW audience here, and PUBLIC (default) below?
3312 } else {
3313 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
3314 if ( $rev === null ) {
3315 return false;
3316 }
3317 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3318 }
3319
3320 $time = - microtime( true );
3321 $this->parserOutput = $content->getParserOutput( $this->page->getTitle(), $this->revid, $this->parserOptions );
3322 $time += microtime( true );
3323
3324 # Timing hack
3325 if ( $time > 3 ) {
3326 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3327 $this->page->getTitle()->getPrefixedDBkey() ) );
3328 }
3329
3330 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
3331 ParserCache::singleton()->save( $this->parserOutput, $this->page, $this->parserOptions );
3332 }
3333
3334 // Make sure file cache is not used on uncacheable content.
3335 // Output that has magic words in it can still use the parser cache
3336 // (if enabled), though it will generally expire sooner.
3337 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
3338 $wgUseFileCache = false;
3339 }
3340
3341 if ( $isCurrent ) {
3342 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
3343 }
3344
3345 return true;
3346 }
3347
3348 /**
3349 * @return bool
3350 */
3351 function getCachedWork() {
3352 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
3353
3354 if ( $this->parserOutput === false ) {
3355 wfDebug( __METHOD__ . ": parser cache miss\n" );
3356 return false;
3357 } else {
3358 wfDebug( __METHOD__ . ": parser cache hit\n" );
3359 return true;
3360 }
3361 }
3362
3363 /**
3364 * @return bool
3365 */
3366 function fallback() {
3367 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
3368
3369 if ( $this->parserOutput === false ) {
3370 wfDebugLog( 'dirty', "dirty missing\n" );
3371 wfDebug( __METHOD__ . ": no dirty cache\n" );
3372 return false;
3373 } else {
3374 wfDebug( __METHOD__ . ": sending dirty output\n" );
3375 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3376 $this->isDirty = true;
3377 return true;
3378 }
3379 }
3380
3381 /**
3382 * @param $status Status
3383 * @return bool
3384 */
3385 function error( $status ) {
3386 $this->error = $status;
3387 return false;
3388 }
3389 }
3390