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