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