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