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