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