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