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