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