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