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