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