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