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