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