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