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