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