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