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