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