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