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