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