merged latest master
[lhc/web/wiklou.git] / includes / WikiPage.php
1 <?php
2 /**
3 * Base representation for a MediaWiki page.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
25 */
26 abstract class Page {}
27
28 /**
29 * Class representing a MediaWiki article and history.
30 *
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
33 *
34 * @internal documentation reviewed 15 Mar 2010
35 */
36 class WikiPage extends Page {
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 ) {
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 * @param $context IContextSource context for parsing
1097 *
1098 * @return ParserOutput or false if the revision was not found
1099 */
1100 public function getParserOutput( ParserOptions $parserOptions, $oldid = null, IContextSource $context = null ) {
1101 wfProfileIn( __METHOD__ );
1102
1103 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1104 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1105 if ( $parserOptions->getStubThreshold() ) {
1106 wfIncrStats( 'pcache_miss_stub' );
1107 }
1108
1109 if ( $useParserCache ) {
1110 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1111 if ( $parserOutput !== false ) {
1112 wfProfileOut( __METHOD__ );
1113 return $parserOutput;
1114 }
1115 }
1116
1117 if ( $oldid === null || $oldid === 0 ) {
1118 $oldid = $this->getLatest();
1119 }
1120
1121 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache, null, $context );
1122 $pool->execute();
1123
1124 wfProfileOut( __METHOD__ );
1125
1126 return $pool->getParserOutput();
1127 }
1128
1129 /**
1130 * Do standard deferred updates after page view
1131 * @param $user User The relevant user
1132 */
1133 public function doViewUpdates( User $user ) {
1134 global $wgDisableCounters;
1135 if ( wfReadOnly() ) {
1136 return;
1137 }
1138
1139 # Don't update page view counters on views from bot users (bug 14044)
1140 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle->exists() ) {
1141 DeferredUpdates::addUpdate( new ViewCountUpdate( $this->getId() ) );
1142 DeferredUpdates::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1143 }
1144
1145 # Update newtalk / watchlist notification status
1146 $user->clearNotification( $this->mTitle );
1147 }
1148
1149 /**
1150 * Perform the actions of a page purging
1151 * @return bool
1152 */
1153 public function doPurge() {
1154 global $wgUseSquid;
1155
1156 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1157 return false;
1158 }
1159
1160 // Invalidate the cache
1161 $this->mTitle->invalidateCache();
1162 $this->clear();
1163
1164 if ( $wgUseSquid ) {
1165 // Commit the transaction before the purge is sent
1166 $dbw = wfGetDB( DB_MASTER );
1167 $dbw->commit( __METHOD__ );
1168
1169 // Send purge
1170 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1171 $update->doUpdate();
1172 }
1173
1174 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1175 if ( $this->mTitle->exists() ) {
1176 $text = ContentHandler::getContentText( $this->getContent() );
1177 } else {
1178 $text = false;
1179 }
1180
1181 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1182 }
1183 return true;
1184 }
1185
1186 /**
1187 * Insert a new empty page record for this article.
1188 * This *must* be followed up by creating a revision
1189 * and running $this->updateRevisionOn( ... );
1190 * or else the record will be left in a funky state.
1191 * Best if all done inside a transaction.
1192 *
1193 * @param $dbw DatabaseBase
1194 * @return int The newly created page_id key, or false if the title already existed
1195 */
1196 public function insertOn( $dbw ) {
1197 wfProfileIn( __METHOD__ );
1198
1199 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1200 $dbw->insert( 'page', array(
1201 'page_id' => $page_id,
1202 'page_namespace' => $this->mTitle->getNamespace(),
1203 'page_title' => $this->mTitle->getDBkey(),
1204 'page_counter' => 0,
1205 'page_restrictions' => '',
1206 'page_is_redirect' => 0, # Will set this shortly...
1207 'page_is_new' => 1,
1208 'page_random' => wfRandom(),
1209 'page_touched' => $dbw->timestamp(),
1210 'page_latest' => 0, # Fill this in shortly...
1211 'page_len' => 0, # Fill this in shortly...
1212 ), __METHOD__, 'IGNORE' );
1213
1214 $affected = $dbw->affectedRows();
1215
1216 if ( $affected ) {
1217 $newid = $dbw->insertId();
1218 $this->mTitle->resetArticleID( $newid );
1219 }
1220 wfProfileOut( __METHOD__ );
1221
1222 return $affected ? $newid : false;
1223 }
1224
1225 /**
1226 * Update the page record to point to a newly saved revision.
1227 *
1228 * @param $dbw DatabaseBase: object
1229 * @param $revision Revision: For ID number, and text used to set
1230 * length and redirect status fields
1231 * @param $lastRevision Integer: if given, will not overwrite the page field
1232 * when different from the currently set value.
1233 * Giving 0 indicates the new page flag should be set
1234 * on.
1235 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1236 * removing rows in redirect table.
1237 * @return bool true on success, false on failure
1238 * @private
1239 */
1240 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1241 global $wgContentHandlerUseDB;
1242
1243 wfProfileIn( __METHOD__ );
1244
1245 $content = $revision->getContent();
1246 $len = $content->getSize();
1247 $rt = $content->getUltimateRedirectTarget();
1248
1249 $conditions = array( 'page_id' => $this->getId() );
1250
1251 if ( !is_null( $lastRevision ) ) {
1252 # An extra check against threads stepping on each other
1253 $conditions['page_latest'] = $lastRevision;
1254 }
1255
1256 $now = wfTimestampNow();
1257 $row = array( /* SET */
1258 'page_latest' => $revision->getId(),
1259 'page_touched' => $dbw->timestamp( $now ),
1260 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1261 'page_is_redirect' => $rt !== null ? 1 : 0,
1262 'page_len' => $len,
1263 );
1264
1265 if ( $wgContentHandlerUseDB ) {
1266 $row[ 'page_content_model' ] = $revision->getContentModel();
1267 }
1268
1269 $dbw->update( 'page',
1270 $row,
1271 $conditions,
1272 __METHOD__ );
1273
1274 $result = $dbw->affectedRows() != 0;
1275 if ( $result ) {
1276 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1277 $this->setLastEdit( $revision );
1278 $this->setCachedLastEditTime( $now );
1279 $this->mLatest = $revision->getId();
1280 $this->mIsRedirect = (bool)$rt;
1281 # Update the LinkCache.
1282 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect, $this->mLatest );
1283 }
1284
1285 wfProfileOut( __METHOD__ );
1286 return $result;
1287 }
1288
1289 /**
1290 * Add row to the redirect table if this is a redirect, remove otherwise.
1291 *
1292 * @param $dbw DatabaseBase
1293 * @param $redirectTitle Title object pointing to the redirect target,
1294 * or NULL if this is not a redirect
1295 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1296 * removing rows in redirect table.
1297 * @return bool true on success, false on failure
1298 * @private
1299 */
1300 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1301 // Always update redirects (target link might have changed)
1302 // Update/Insert if we don't know if the last revision was a redirect or not
1303 // Delete if changing from redirect to non-redirect
1304 $isRedirect = !is_null( $redirectTitle );
1305
1306 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1307 return true;
1308 }
1309
1310 wfProfileIn( __METHOD__ );
1311 if ( $isRedirect ) {
1312 $this->insertRedirectEntry( $redirectTitle );
1313 } else {
1314 // This is not a redirect, remove row from redirect table
1315 $where = array( 'rd_from' => $this->getId() );
1316 $dbw->delete( 'redirect', $where, __METHOD__ );
1317 }
1318
1319 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1320 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1321 }
1322 wfProfileOut( __METHOD__ );
1323
1324 return ( $dbw->affectedRows() != 0 );
1325 }
1326
1327 /**
1328 * If the given revision is newer than the currently set page_latest,
1329 * update the page record. Otherwise, do nothing.
1330 *
1331 * @param $dbw DatabaseBase object
1332 * @param $revision Revision object
1333 * @return mixed
1334 */
1335 public function updateIfNewerOn( $dbw, $revision ) {
1336 wfProfileIn( __METHOD__ );
1337
1338 $row = $dbw->selectRow(
1339 array( 'revision', 'page' ),
1340 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1341 array(
1342 'page_id' => $this->getId(),
1343 'page_latest=rev_id' ),
1344 __METHOD__ );
1345
1346 if ( $row ) {
1347 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1348 wfProfileOut( __METHOD__ );
1349 return false;
1350 }
1351 $prev = $row->rev_id;
1352 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1353 } else {
1354 # No or missing previous revision; mark the page as new
1355 $prev = 0;
1356 $lastRevIsRedirect = null;
1357 }
1358
1359 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1360
1361 wfProfileOut( __METHOD__ );
1362 return $ret;
1363 }
1364
1365 /**
1366 * Get the text that needs to be saved in order to undo all revisions
1367 * between $undo and $undoafter. Revisions must belong to the same page,
1368 * must exist and must not be deleted
1369 * @param $undo Revision
1370 * @param $undoafter Revision Must be an earlier revision than $undo
1371 * @return mixed string on success, false on failure
1372 * @deprecated since 1.WD: use ContentHandler::getUndoContent() instead.
1373 */
1374 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1375 wfDeprecated( __METHOD__, '1.WD' );
1376
1377 $this->loadLastEdit();
1378
1379 if ( $this->mLastRevision ) {
1380 if ( is_null( $undoafter ) ) {
1381 $undoafter = $undo->getPrevious();
1382 }
1383
1384 $handler = $this->getContentHandler();
1385 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1386
1387 if ( !$undone ) {
1388 return false;
1389 } else {
1390 return ContentHandler::getContentText( $undone );
1391 }
1392 }
1393
1394 return false;
1395 }
1396
1397 /**
1398 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1399 * @param $text String: new text of the section
1400 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1401 * @param $edittime String: revision timestamp or null to use the current revision
1402 * @return String new complete article text, or null if error
1403 *
1404 * @deprecated since 1.WD, use replaceSectionContent() instead
1405 */
1406 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1407 wfDeprecated( __METHOD__, '1.WD' );
1408
1409 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1410
1411 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1412
1413 return ContentHandler::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1414 }
1415
1416 /**
1417 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1418 * @param $content Content: new content of the section
1419 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1420 * @param $edittime String: revision timestamp or null to use the current revision
1421 *
1422 * @return Content new complete article content, or null if error
1423 *
1424 * @since 1.WD
1425 */
1426 public function replaceSectionContent( $section, Content $sectionContent, $sectionTitle = '', $edittime = null ) {
1427 wfProfileIn( __METHOD__ );
1428
1429 if ( strval( $section ) == '' ) {
1430 // Whole-page edit; let the whole text through
1431 $newContent = $sectionContent;
1432 } else {
1433 // Bug 30711: always use current version when adding a new section
1434 if ( is_null( $edittime ) || $section == 'new' ) {
1435 $oldContent = $this->getContent();
1436 if ( ! $oldContent ) {
1437 wfDebug( __METHOD__ . ": no page text\n" );
1438 wfProfileOut( __METHOD__ );
1439 return null;
1440 }
1441 } else {
1442 $dbw = wfGetDB( DB_MASTER );
1443 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1444
1445 if ( !$rev ) {
1446 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1447 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1448 wfProfileOut( __METHOD__ );
1449 return null;
1450 }
1451
1452 $oldContent = $rev->getContent();
1453 }
1454
1455 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1456 }
1457
1458 wfProfileOut( __METHOD__ );
1459 return $newContent;
1460 }
1461
1462 /**
1463 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1464 * @param $flags Int
1465 * @return Int updated $flags
1466 */
1467 function checkFlags( $flags ) {
1468 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1469 if ( $this->mTitle->getArticleID() ) {
1470 $flags |= EDIT_UPDATE;
1471 } else {
1472 $flags |= EDIT_NEW;
1473 }
1474 }
1475
1476 return $flags;
1477 }
1478
1479 /**
1480 * Change an existing article or create a new article. Updates RC and all necessary caches,
1481 * optionally via the deferred update array.
1482 *
1483 * @param $text String: new text
1484 * @param $summary String: edit summary
1485 * @param $flags Integer bitfield:
1486 * EDIT_NEW
1487 * Article is known or assumed to be non-existent, create a new one
1488 * EDIT_UPDATE
1489 * Article is known or assumed to be pre-existing, update it
1490 * EDIT_MINOR
1491 * Mark this edit minor, if the user is allowed to do so
1492 * EDIT_SUPPRESS_RC
1493 * Do not log the change in recentchanges
1494 * EDIT_FORCE_BOT
1495 * Mark the edit a "bot" edit regardless of user rights
1496 * EDIT_DEFER_UPDATES
1497 * Defer some of the updates until the end of index.php
1498 * EDIT_AUTOSUMMARY
1499 * Fill in blank summaries with generated text where possible
1500 *
1501 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1502 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1503 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1504 * edit-already-exists error will be returned. These two conditions are also possible with
1505 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1506 *
1507 * @param $baseRevId int the revision ID this edit was based off, if any
1508 * @param $user User the user doing the edit
1509 *
1510 * @return Status object. Possible errors:
1511 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1512 * edit-gone-missing: In update mode, but the article didn't exist
1513 * edit-conflict: In update mode, the article changed unexpectedly
1514 * edit-no-change: Warning that the text was the same as before
1515 * edit-already-exists: In creation mode, but the article already exists
1516 *
1517 * Extensions may define additional errors.
1518 *
1519 * $return->value will contain an associative array with members as follows:
1520 * new: Boolean indicating if the function attempted to create a new article
1521 * revision: The revision object for the inserted revision, or null
1522 *
1523 * Compatibility note: this function previously returned a boolean value indicating success/failure
1524 *
1525 * @deprecated since 1.WD: use doEditContent() instead.
1526 */
1527 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #@todo: use doEditContent() instead
1528 wfDeprecated( __METHOD__, '1.WD' );
1529
1530 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1531
1532 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1533 }
1534
1535 /**
1536 * Change an existing article or create a new article. Updates RC and all necessary caches,
1537 * optionally via the deferred update array.
1538 *
1539 * @param $content Content: new content
1540 * @param $summary String: edit summary
1541 * @param $flags Integer bitfield:
1542 * EDIT_NEW
1543 * Article is known or assumed to be non-existent, create a new one
1544 * EDIT_UPDATE
1545 * Article is known or assumed to be pre-existing, update it
1546 * EDIT_MINOR
1547 * Mark this edit minor, if the user is allowed to do so
1548 * EDIT_SUPPRESS_RC
1549 * Do not log the change in recentchanges
1550 * EDIT_FORCE_BOT
1551 * Mark the edit a "bot" edit regardless of user rights
1552 * EDIT_DEFER_UPDATES
1553 * Defer some of the updates until the end of index.php
1554 * EDIT_AUTOSUMMARY
1555 * Fill in blank summaries with generated text where possible
1556 *
1557 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1558 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1559 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1560 * edit-already-exists error will be returned. These two conditions are also possible with
1561 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1562 *
1563 * @param $baseRevId the revision ID this edit was based off, if any
1564 * @param $user User the user doing the edit
1565 * @param $serialisation_format String: format for storing the content in the database
1566 *
1567 * @return Status object. Possible errors:
1568 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1569 * edit-gone-missing: In update mode, but the article didn't exist
1570 * edit-conflict: In update mode, the article changed unexpectedly
1571 * edit-no-change: Warning that the text was the same as before
1572 * edit-already-exists: In creation mode, but the article already exists
1573 *
1574 * Extensions may define additional errors.
1575 *
1576 * $return->value will contain an associative array with members as follows:
1577 * new: Boolean indicating if the function attempted to create a new article
1578 * revision: The revision object for the inserted revision, or null
1579 *
1580 * @since 1.WD
1581 */
1582 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
1583 User $user = null, $serialisation_format = null ) {
1584 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1585
1586 # Low-level sanity check
1587 if ( $this->mTitle->getText() === '' ) {
1588 throw new MWException( 'Something is trying to edit an article with an empty title' );
1589 }
1590
1591 wfProfileIn( __METHOD__ );
1592
1593 $user = is_null( $user ) ? $wgUser : $user;
1594 $status = Status::newGood( array() );
1595
1596 // Load the data from the master database if needed.
1597 // The caller may already loaded it from the master or even loaded it using
1598 // SELECT FOR UPDATE, so do not override that using clear().
1599 $this->loadPageData( 'fromdbmaster' );
1600
1601 $flags = $this->checkFlags( $flags );
1602
1603 # call legacy hook
1604 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary,
1605 $flags & EDIT_MINOR, null, null, &$flags, &$status ) );
1606
1607 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { # avoid serialization overhead if the hook isn't present
1608 $content_text = $content->serialize();
1609 $txt = $content_text; # clone
1610
1611 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary,
1612 $flags & EDIT_MINOR, null, null, &$flags, &$status ) );
1613
1614 if ( $txt !== $content_text ) {
1615 # if the text changed, unserialize the new version to create an updated Content object.
1616 $content = $content->getContentHandler()->unserializeContent( $txt );
1617 }
1618 }
1619
1620 if ( !$hook_ok ) {
1621 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1622
1623 if ( $status->isOK() ) {
1624 $status->fatal( 'edit-hook-aborted' );
1625 }
1626
1627 wfProfileOut( __METHOD__ );
1628 return $status;
1629 }
1630
1631 # Silently ignore EDIT_MINOR if not allowed
1632 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1633 $bot = $flags & EDIT_FORCE_BOT;
1634
1635 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1636
1637 $oldsize = $old_content ? $old_content->getSize() : 0;
1638 $oldid = $this->getLatest();
1639 $oldIsRedirect = $this->isRedirect();
1640 $oldcountable = $this->isCountable();
1641
1642 $handler = $content->getContentHandler();
1643
1644 # Provide autosummaries if one is not provided and autosummaries are enabled.
1645 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1646 if ( !$old_content ) $old_content = null;
1647 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1648 }
1649
1650 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1651 $serialized = $editInfo->pst;
1652 $content = $editInfo->pstContent;
1653 $newsize = $content->getSize();
1654
1655 $dbw = wfGetDB( DB_MASTER );
1656 $now = wfTimestampNow();
1657 $this->mTimestamp = $now;
1658
1659 if ( $flags & EDIT_UPDATE ) {
1660 # Update article, but only if changed.
1661 $status->value['new'] = false;
1662
1663 if ( !$oldid ) {
1664 # Article gone missing
1665 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1666 $status->fatal( 'edit-gone-missing' );
1667
1668 wfProfileOut( __METHOD__ );
1669 return $status;
1670 }
1671
1672 # Make sure the revision is either completely inserted or not inserted at all
1673 if ( !$wgDBtransactions ) {
1674 $userAbort = ignore_user_abort( true );
1675 }
1676
1677 $revision = new Revision( array(
1678 'page' => $this->getId(),
1679 'comment' => $summary,
1680 'minor_edit' => $isminor,
1681 'text' => $serialized,
1682 'len' => $newsize,
1683 'parent_id' => $oldid,
1684 'user' => $user->getId(),
1685 'user_text' => $user->getName(),
1686 'timestamp' => $now,
1687 'content_model' => $content->getModel(),
1688 'content_format' => $serialisation_format,
1689 ) );
1690
1691 $changed = !$content->equals( $old_content );
1692
1693 if ( $changed ) {
1694 $dbw->begin( __METHOD__ );
1695 $revisionId = $revision->insertOn( $dbw );
1696
1697 # Update page
1698 #
1699 # Note that we use $this->mLatest instead of fetching a value from the master DB
1700 # during the course of this function. This makes sure that EditPage can detect
1701 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1702 # before this function is called. A previous function used a separate query, this
1703 # creates a window where concurrent edits can cause an ignored edit conflict.
1704 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1705
1706 if ( !$ok ) {
1707 /* Belated edit conflict! Run away!! */
1708 $status->fatal( 'edit-conflict' );
1709
1710 # Delete the invalid revision if the DB is not transactional
1711 if ( !$wgDBtransactions ) {
1712 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1713 }
1714
1715 $revisionId = 0;
1716 $dbw->rollback( __METHOD__ );
1717 } else {
1718 global $wgUseRCPatrol;
1719 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1720 # Update recentchanges
1721 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1722 # Mark as patrolled if the user can do so
1723 $patrolled = $wgUseRCPatrol && !count(
1724 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1725 # Add RC row to the DB
1726 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1727 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1728 $revisionId, $patrolled
1729 );
1730
1731 # Log auto-patrolled edits
1732 if ( $patrolled ) {
1733 PatrolLog::record( $rc, true, $user );
1734 }
1735 }
1736 $user->incEditCount();
1737 $dbw->commit( __METHOD__ );
1738 }
1739 } else {
1740 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1741 // related variables correctly
1742 $revision->setId( $this->getLatest() );
1743 }
1744
1745 if ( !$wgDBtransactions ) {
1746 ignore_user_abort( $userAbort );
1747 }
1748
1749 // Now that ignore_user_abort is restored, we can respond to fatal errors
1750 if ( !$status->isOK() ) {
1751 wfProfileOut( __METHOD__ );
1752 return $status;
1753 }
1754
1755 # Update links tables, site stats, etc.
1756 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1757 'oldcountable' => $oldcountable ) );
1758
1759 if ( !$changed ) {
1760 $status->warning( 'edit-no-change' );
1761 $revision = null;
1762 // Update page_touched, this is usually implicit in the page update
1763 // Other cache updates are done in onArticleEdit()
1764 $this->mTitle->invalidateCache();
1765 }
1766 } else {
1767 # Create new article
1768 $status->value['new'] = true;
1769
1770 $dbw->begin( __METHOD__ );
1771
1772 # Add the page record; stake our claim on this title!
1773 # This will return false if the article already exists
1774 $newid = $this->insertOn( $dbw );
1775
1776 if ( $newid === false ) {
1777 $dbw->rollback( __METHOD__ );
1778 $status->fatal( 'edit-already-exists' );
1779
1780 wfProfileOut( __METHOD__ );
1781 return $status;
1782 }
1783
1784 # Save the revision text...
1785 $revision = new Revision( array(
1786 'page' => $newid,
1787 'comment' => $summary,
1788 'minor_edit' => $isminor,
1789 'text' => $serialized,
1790 'len' => $newsize,
1791 'user' => $user->getId(),
1792 'user_text' => $user->getName(),
1793 'timestamp' => $now,
1794 'content_model' => $content->getModel(),
1795 'content_format' => $serialisation_format,
1796 ) );
1797 $revisionId = $revision->insertOn( $dbw );
1798
1799 # Update the page record with revision data
1800 $this->updateRevisionOn( $dbw, $revision, 0 );
1801
1802 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1803
1804 # Update recentchanges
1805 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1806 global $wgUseRCPatrol, $wgUseNPPatrol;
1807
1808 # Mark as patrolled if the user can do so
1809 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1810 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1811 # Add RC row to the DB
1812 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1813 '', $content->getSize(), $revisionId, $patrolled );
1814
1815 # Log auto-patrolled edits
1816 if ( $patrolled ) {
1817 PatrolLog::record( $rc, true, $user );
1818 }
1819 }
1820 $user->incEditCount();
1821 $dbw->commit( __METHOD__ );
1822
1823 # Update links, etc.
1824 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1825
1826 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary,
1827 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1828
1829 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary,
1830 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1831 }
1832
1833 # Do updates right now unless deferral was requested
1834 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1835 DeferredUpdates::doUpdates();
1836 }
1837
1838 // Return the new revision (or null) to the caller
1839 $status->value['revision'] = $revision;
1840
1841 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary,
1842 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1843
1844 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary,
1845 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1846
1847 # Promote user to any groups they meet the criteria for
1848 $user->addAutopromoteOnceGroups( 'onEdit' );
1849
1850 wfProfileOut( __METHOD__ );
1851 return $status;
1852 }
1853
1854 /**
1855 * Get parser options suitable for rendering the primary article wikitext
1856 * @param User|string $user User object or 'canonical'
1857 * @return ParserOptions
1858 */
1859 public function makeParserOptions( $user ) {
1860 global $wgContLang;
1861 if ( $user instanceof User ) { // settings per user (even anons)
1862 $options = ParserOptions::newFromUser( $user );
1863 } else { // canonical settings
1864 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
1865 }
1866 $options->enableLimitReport(); // show inclusion/loop reports
1867 $options->setTidy( true ); // fix bad HTML
1868 return $options;
1869 }
1870
1871 /**
1872 * Prepare text which is about to be saved.
1873 * Returns a stdclass with source, pst and output members
1874 *
1875 * @deprecated in 1.WD: use prepareContentForEdit instead.
1876 */
1877 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1878 wfDeprecated( __METHOD__, '1.WD' );
1879 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1880 return $this->prepareContentForEdit( $content, $revid , $user );
1881 }
1882
1883 /**
1884 * Prepare content which is about to be saved.
1885 * Returns a stdclass with source, pst and output members
1886 *
1887 * @param \Content $content
1888 * @param null $revid
1889 * @param null|\User $user
1890 * @param null $serialization_format
1891 *
1892 * @return bool|object
1893 *
1894 * @since 1.WD
1895 */
1896 public function prepareContentForEdit( Content $content, $revid = null, User $user = null, $serialization_format = null ) {
1897 global $wgParser, $wgContLang, $wgUser;
1898 $user = is_null( $user ) ? $wgUser : $user;
1899 // @TODO fixme: check $user->getId() here???
1900
1901 if ( $this->mPreparedEdit
1902 && $this->mPreparedEdit->newContent
1903 && $this->mPreparedEdit->newContent->equals( $content )
1904 && $this->mPreparedEdit->revid == $revid
1905 && $this->mPreparedEdit->format == $serialization_format
1906 #XXX: also check $user here?
1907 ) {
1908 // Already prepared
1909 return $this->mPreparedEdit;
1910 }
1911
1912 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
1913 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1914
1915 $edit = (object)array();
1916 $edit->revid = $revid;
1917
1918 $edit->pstContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
1919 $edit->pst = $edit->pstContent->serialize( $serialization_format );
1920 $edit->format = $serialization_format;
1921
1922 $edit->popts = $this->makeParserOptions( 'canonical' );
1923
1924 // TODO: is there no better way to obtain a context here?
1925 $context = RequestContext::getMain();
1926 $context->setTitle( $this->mTitle );
1927 $edit->output = $edit->pstContent->getParserOutput( $context, $revid, $edit->popts );
1928
1929 $edit->newContent = $content;
1930 $edit->oldContent = $this->getContent( Revision::RAW );
1931
1932 $edit->newText = ContentHandler::getContentText( $edit->newContent ); #FIXME: B/C only! don't use this field!
1933 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : ''; #FIXME: B/C only! don't use this field!
1934
1935 $this->mPreparedEdit = $edit;
1936
1937 return $edit;
1938 }
1939
1940 /**
1941 * Do standard deferred updates after page edit.
1942 * Update links tables, site stats, search index and message cache.
1943 * Purges pages that include this page if the text was changed here.
1944 * Every 100th edit, prune the recent changes table.
1945 *
1946 * @param $revision Revision object
1947 * @param $user User object that did the revision
1948 * @param $options Array of options, following indexes are used:
1949 * - changed: boolean, whether the revision changed the content (default true)
1950 * - created: boolean, whether the revision created the page (default false)
1951 * - oldcountable: boolean or null (default null):
1952 * - boolean: whether the page was counted as an article before that
1953 * revision, only used in changed is true and created is false
1954 * - null: don't change the article count
1955 */
1956 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
1957 global $wgEnableParserCache;
1958
1959 wfProfileIn( __METHOD__ );
1960
1961 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1962 $content = $revision->getContent();
1963
1964 # Parse the text
1965 # Be careful not to double-PST: $text is usually already PST-ed once
1966 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
1967 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
1968 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1969 } else {
1970 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
1971 $editInfo = $this->mPreparedEdit;
1972 }
1973
1974 # Save it to the parser cache
1975 if ( $wgEnableParserCache ) {
1976 $parserCache = ParserCache::singleton();
1977 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
1978 }
1979
1980 # Update the links tables and other secondary data
1981 $updates = $editInfo->output->getSecondaryDataUpdates( $this->mTitle );
1982 SecondaryDataUpdate::runUpdates( $updates );
1983
1984 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1985
1986 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1987 if ( 0 == mt_rand( 0, 99 ) ) {
1988 // Flush old entries from the `recentchanges` table; we do this on
1989 // random requests so as to avoid an increase in writes for no good reason
1990 global $wgRCMaxAge;
1991
1992 $dbw = wfGetDB( DB_MASTER );
1993 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1994 $dbw->delete(
1995 'recentchanges',
1996 array( "rc_timestamp < '$cutoff'" ),
1997 __METHOD__
1998 );
1999 }
2000 }
2001
2002 if ( !$this->mTitle->exists() ) {
2003 wfProfileOut( __METHOD__ );
2004 return;
2005 }
2006
2007 $id = $this->getId();
2008 $title = $this->mTitle->getPrefixedDBkey();
2009 $shortTitle = $this->mTitle->getDBkey();
2010
2011 if ( !$options['changed'] ) {
2012 $good = 0;
2013 $total = 0;
2014 } elseif ( $options['created'] ) {
2015 $good = (int)$this->isCountable( $editInfo );
2016 $total = 1;
2017 } elseif ( $options['oldcountable'] !== null ) {
2018 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2019 $total = 0;
2020 } else {
2021 $good = 0;
2022 $total = 0;
2023 }
2024
2025 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2026 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
2027
2028 # If this is another user's talk page, update newtalk.
2029 # Don't do this if $options['changed'] = false (null-edits) nor if
2030 # it's a minor edit and the user doesn't want notifications for those.
2031 if ( $options['changed']
2032 && $this->mTitle->getNamespace() == NS_USER_TALK
2033 && $shortTitle != $user->getTitleKey()
2034 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2035 ) {
2036 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2037 $other = User::newFromName( $shortTitle, false );
2038 if ( !$other ) {
2039 wfDebug( __METHOD__ . ": invalid username\n" );
2040 } elseif ( User::isIP( $shortTitle ) ) {
2041 // An anonymous user
2042 $other->setNewtalk( true );
2043 } elseif ( $other->isLoggedIn() ) {
2044 $other->setNewtalk( true );
2045 } else {
2046 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2047 }
2048 }
2049 }
2050
2051 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2052 $msgtext = ContentHandler::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
2053 if ( $msgtext === false || $msgtext === null ) $msgtext = '';
2054
2055 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2056 }
2057
2058 if( $options['created'] ) {
2059 self::onArticleCreate( $this->mTitle );
2060 } else {
2061 self::onArticleEdit( $this->mTitle );
2062 }
2063
2064 wfProfileOut( __METHOD__ );
2065 }
2066
2067 /**
2068 * Edit an article without doing all that other stuff
2069 * The article must already exist; link tables etc
2070 * are not updated, caches are not flushed.
2071 *
2072 * @param $text String: text submitted
2073 * @param $user User The relevant user
2074 * @param $comment String: comment submitted
2075 * @param $minor Boolean: whereas it's a minor modification
2076 *
2077 * @deprecated since 1.WD, use doEditContent() instead.
2078 */
2079 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2080 wfDeprecated( __METHOD__, "1.WD" );
2081
2082 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2083 return $this->doQuickEditContent( $content, $user, $comment , $minor );
2084 }
2085
2086 /**
2087 * Edit an article without doing all that other stuff
2088 * The article must already exist; link tables etc
2089 * are not updated, caches are not flushed.
2090 *
2091 * @param $content Content: content submitted
2092 * @param $user User The relevant user
2093 * @param $comment String: comment submitted
2094 * @param $serialisation_format String: format for storing the content in the database
2095 * @param $minor Boolean: whereas it's a minor modification
2096 */
2097 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = 0, $serialisation_format = null ) {
2098 wfProfileIn( __METHOD__ );
2099
2100 $serialized = $content->serialize( $serialisation_format );
2101
2102 $dbw = wfGetDB( DB_MASTER );
2103 $revision = new Revision( array(
2104 'page' => $this->getId(),
2105 'text' => $serialized,
2106 'length' => $content->getSize(),
2107 'comment' => $comment,
2108 'minor_edit' => $minor ? 1 : 0,
2109 ) );
2110 $revision->insertOn( $dbw );
2111 $this->updateRevisionOn( $dbw, $revision );
2112
2113 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2114
2115 wfProfileOut( __METHOD__ );
2116 }
2117
2118 /**
2119 * Update the article's restriction field, and leave a log entry.
2120 * This works for protection both existing and non-existing pages.
2121 *
2122 * @param $limit Array: set of restriction keys
2123 * @param $reason String
2124 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2125 * @param $expiry Array: per restriction type expiration
2126 * @param $user User The user updating the restrictions
2127 * @return Status
2128 */
2129 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
2130 global $wgContLang;
2131
2132 if ( wfReadOnly() ) {
2133 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2134 }
2135
2136 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2137
2138 $id = $this->mTitle->getArticleID();
2139
2140 if ( !$cascade ) {
2141 $cascade = false;
2142 }
2143
2144 // Take this opportunity to purge out expired restrictions
2145 Title::purgeExpiredRestrictions();
2146
2147 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2148 # we expect a single selection, but the schema allows otherwise.
2149 $isProtected = false;
2150 $protect = false;
2151 $changed = false;
2152
2153 $dbw = wfGetDB( DB_MASTER );
2154
2155 foreach ( $restrictionTypes as $action ) {
2156 if ( !isset( $expiry[$action] ) ) {
2157 $expiry[$action] = $dbw->getInfinity();
2158 }
2159 if ( !isset( $limit[$action] ) ) {
2160 $limit[$action] = '';
2161 } elseif ( $limit[$action] != '' ) {
2162 $protect = true;
2163 }
2164
2165 # Get current restrictions on $action
2166 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2167 if ( $current != '' ) {
2168 $isProtected = true;
2169 }
2170
2171 if ( $limit[$action] != $current ) {
2172 $changed = true;
2173 } elseif ( $limit[$action] != '' ) {
2174 # Only check expiry change if the action is actually being
2175 # protected, since expiry does nothing on an not-protected
2176 # action.
2177 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2178 $changed = true;
2179 }
2180 }
2181 }
2182
2183 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2184 $changed = true;
2185 }
2186
2187 # If nothing's changed, do nothing
2188 if ( !$changed ) {
2189 return Status::newGood();
2190 }
2191
2192 if ( !$protect ) { # No protection at all means unprotection
2193 $revCommentMsg = 'unprotectedarticle';
2194 $logAction = 'unprotect';
2195 } elseif ( $isProtected ) {
2196 $revCommentMsg = 'modifiedarticleprotection';
2197 $logAction = 'modify';
2198 } else {
2199 $revCommentMsg = 'protectedarticle';
2200 $logAction = 'protect';
2201 }
2202
2203 $encodedExpiry = array();
2204 $protectDescription = '';
2205 foreach ( $limit as $action => $restrictions ) {
2206 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2207 if ( $restrictions != '' ) {
2208 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2209 if ( $encodedExpiry[$action] != 'infinity' ) {
2210 $protectDescription .= wfMsgForContent( 'protect-expiring',
2211 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2212 $wgContLang->date( $expiry[$action], false, false ) ,
2213 $wgContLang->time( $expiry[$action], false, false ) );
2214 } else {
2215 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
2216 }
2217
2218 $protectDescription .= ') ';
2219 }
2220 }
2221 $protectDescription = trim( $protectDescription );
2222
2223 if ( $id ) { # Protection of existing page
2224 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2225 return Status::newGood();
2226 }
2227
2228 # Only restrictions with the 'protect' right can cascade...
2229 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2230 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2231
2232 # The schema allows multiple restrictions
2233 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2234 $cascade = false;
2235 }
2236
2237 # Update restrictions table
2238 foreach ( $limit as $action => $restrictions ) {
2239 if ( $restrictions != '' ) {
2240 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2241 array( 'pr_page' => $id,
2242 'pr_type' => $action,
2243 'pr_level' => $restrictions,
2244 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2245 'pr_expiry' => $encodedExpiry[$action]
2246 ),
2247 __METHOD__
2248 );
2249 } else {
2250 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2251 'pr_type' => $action ), __METHOD__ );
2252 }
2253 }
2254
2255 # Prepare a null revision to be added to the history
2256 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle->getPrefixedText() ) );
2257 if ( $reason ) {
2258 $editComment .= ": $reason";
2259 }
2260 if ( $protectDescription ) {
2261 $editComment .= " ($protectDescription)";
2262 }
2263 if ( $cascade ) {
2264 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2265 }
2266
2267 # Insert a null revision
2268 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2269 $nullRevId = $nullRevision->insertOn( $dbw );
2270
2271 $latest = $this->getLatest();
2272 # Update page record
2273 $dbw->update( 'page',
2274 array( /* SET */
2275 'page_touched' => $dbw->timestamp(),
2276 'page_restrictions' => '',
2277 'page_latest' => $nullRevId
2278 ), array( /* WHERE */
2279 'page_id' => $id
2280 ), __METHOD__
2281 );
2282
2283 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2284 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2285 } else { # Protection of non-existing page (also known as "title protection")
2286 # Cascade protection is meaningless in this case
2287 $cascade = false;
2288
2289 if ( $limit['create'] != '' ) {
2290 $dbw->replace( 'protected_titles',
2291 array( array( 'pt_namespace', 'pt_title' ) ),
2292 array(
2293 'pt_namespace' => $this->mTitle->getNamespace(),
2294 'pt_title' => $this->mTitle->getDBkey(),
2295 'pt_create_perm' => $limit['create'],
2296 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2297 'pt_expiry' => $encodedExpiry['create'],
2298 'pt_user' => $user->getId(),
2299 'pt_reason' => $reason,
2300 ), __METHOD__
2301 );
2302 } else {
2303 $dbw->delete( 'protected_titles',
2304 array(
2305 'pt_namespace' => $this->mTitle->getNamespace(),
2306 'pt_title' => $this->mTitle->getDBkey()
2307 ), __METHOD__
2308 );
2309 }
2310 }
2311
2312 $this->mTitle->flushRestrictions();
2313
2314 if ( $logAction == 'unprotect' ) {
2315 $logParams = array();
2316 } else {
2317 $logParams = array( $protectDescription, $cascade ? 'cascade' : '' );
2318 }
2319
2320 # Update the protection log
2321 $log = new LogPage( 'protect' );
2322 $log->addEntry( $logAction, $this->mTitle, trim( $reason ), $logParams, $user );
2323
2324 return Status::newGood();
2325 }
2326
2327 /**
2328 * Take an array of page restrictions and flatten it to a string
2329 * suitable for insertion into the page_restrictions field.
2330 * @param $limit Array
2331 * @return String
2332 */
2333 protected static function flattenRestrictions( $limit ) {
2334 if ( !is_array( $limit ) ) {
2335 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2336 }
2337
2338 $bits = array();
2339 ksort( $limit );
2340
2341 foreach ( $limit as $action => $restrictions ) {
2342 if ( $restrictions != '' ) {
2343 $bits[] = "$action=$restrictions";
2344 }
2345 }
2346
2347 return implode( ':', $bits );
2348 }
2349
2350 /**
2351 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2352 * Deletes the article with database consistency, writes logs, purges caches
2353 *
2354 * @param $reason string delete reason for deletion log
2355 * @param $suppress int bitfield
2356 * Revision::DELETED_TEXT
2357 * Revision::DELETED_COMMENT
2358 * Revision::DELETED_USER
2359 * Revision::DELETED_RESTRICTED
2360 * @param $id int article ID
2361 * @param $commit boolean defaults to true, triggers transaction end
2362 * @param &$error Array of errors to append to
2363 * @param $user User The deleting user
2364 * @return boolean true if successful
2365 */
2366 public function doDeleteArticle(
2367 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2368 ) {
2369 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2370 == WikiPage::DELETE_SUCCESS;
2371 }
2372
2373 /**
2374 * Back-end article deletion
2375 * Deletes the article with database consistency, writes logs, purges caches
2376 *
2377 * @param $reason string delete reason for deletion log
2378 * @param $suppress int bitfield
2379 * Revision::DELETED_TEXT
2380 * Revision::DELETED_COMMENT
2381 * Revision::DELETED_USER
2382 * Revision::DELETED_RESTRICTED
2383 * @param $id int article ID
2384 * @param $commit boolean defaults to true, triggers transaction end
2385 * @param &$error Array of errors to append to
2386 * @param $user User The deleting user
2387 * @return int: One of WikiPage::DELETE_* constants
2388 */
2389 public function doDeleteArticleReal(
2390 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2391 ) {
2392 global $wgUser, $wgContentHandlerUseDB;
2393
2394 wfDebug( __METHOD__ . "\n" );
2395
2396 if ( $this->mTitle->getDBkey() === '' ) {
2397 return WikiPage::DELETE_NO_PAGE;
2398 }
2399
2400 $user = is_null( $user ) ? $wgUser : $user;
2401 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2402 return WikiPage::DELETE_HOOK_ABORTED;
2403 }
2404
2405 if ( $id == 0 ) {
2406 $this->loadPageData( 'forupdate' );
2407 $id = $this->getID();
2408 if ( $id == 0 ) {
2409 return WikiPage::DELETE_NO_PAGE;
2410 }
2411 }
2412
2413 // Bitfields to further suppress the content
2414 if ( $suppress ) {
2415 $bitfield = 0;
2416 // This should be 15...
2417 $bitfield |= Revision::DELETED_TEXT;
2418 $bitfield |= Revision::DELETED_COMMENT;
2419 $bitfield |= Revision::DELETED_USER;
2420 $bitfield |= Revision::DELETED_RESTRICTED;
2421 } else {
2422 $bitfield = 'rev_deleted';
2423 }
2424
2425 $dbw = wfGetDB( DB_MASTER );
2426 $dbw->begin( __METHOD__ );
2427 // For now, shunt the revision data into the archive table.
2428 // Text is *not* removed from the text table; bulk storage
2429 // is left intact to avoid breaking block-compression or
2430 // immutable storage schemes.
2431 //
2432 // For backwards compatibility, note that some older archive
2433 // table entries will have ar_text and ar_flags fields still.
2434 //
2435 // In the future, we may keep revisions and mark them with
2436 // the rev_deleted field, which is reserved for this purpose.
2437
2438 $row = array(
2439 'ar_namespace' => 'page_namespace',
2440 'ar_title' => 'page_title',
2441 'ar_comment' => 'rev_comment',
2442 'ar_user' => 'rev_user',
2443 'ar_user_text' => 'rev_user_text',
2444 'ar_timestamp' => 'rev_timestamp',
2445 'ar_minor_edit' => 'rev_minor_edit',
2446 'ar_rev_id' => 'rev_id',
2447 'ar_parent_id' => 'rev_parent_id',
2448 'ar_text_id' => 'rev_text_id',
2449 'ar_text' => '\'\'', // Be explicit to appease
2450 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2451 'ar_len' => 'rev_len',
2452 'ar_page_id' => 'page_id',
2453 'ar_deleted' => $bitfield,
2454 'ar_sha1' => 'rev_sha1',
2455 );
2456
2457 if ( $wgContentHandlerUseDB ) {
2458 $row[ 'ar_content_model' ] = 'rev_content_model';
2459 $row[ 'ar_content_format' ] = 'rev_content_format';
2460 }
2461
2462 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2463 $row,
2464 array(
2465 'page_id' => $id,
2466 'page_id = rev_page'
2467 ), __METHOD__
2468 );
2469
2470 # Now that it's safely backed up, delete it
2471 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2472 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2473
2474 if ( !$ok ) {
2475 $dbw->rollback( __METHOD__ );
2476 return WikiPage::DELETE_NO_REVISIONS;
2477 }
2478
2479 # update site status
2480 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2481
2482 # remove secondary indexes, etc
2483 $handler = $this->getContentHandler();
2484 $updates = $handler->getDeletionUpdates( $this );
2485 SecondaryDataUpdate::runUpdates( $updates );
2486
2487 # Clear caches
2488 WikiPage::onArticleDelete( $this->mTitle );
2489
2490 # Reset this object
2491 $this->clear();
2492
2493 # Clear the cached article id so the interface doesn't act like we exist
2494 $this->mTitle->resetArticleID( 0 );
2495
2496 # Log the deletion, if the page was suppressed, log it at Oversight instead
2497 $logtype = $suppress ? 'suppress' : 'delete';
2498
2499 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2500 $logEntry->setPerformer( $user );
2501 $logEntry->setTarget( $this->mTitle );
2502 $logEntry->setComment( $reason );
2503 $logid = $logEntry->insert();
2504 $logEntry->publish( $logid );
2505
2506 if ( $commit ) {
2507 $dbw->commit( __METHOD__ );
2508 }
2509
2510 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2511 return WikiPage::DELETE_SUCCESS;
2512 }
2513
2514 /**
2515 * Roll back the most recent consecutive set of edits to a page
2516 * from the same user; fails if there are no eligible edits to
2517 * roll back to, e.g. user is the sole contributor. This function
2518 * performs permissions checks on $user, then calls commitRollback()
2519 * to do the dirty work
2520 *
2521 * @todo: seperate the business/permission stuff out from backend code
2522 *
2523 * @param $fromP String: Name of the user whose edits to rollback.
2524 * @param $summary String: Custom summary. Set to default summary if empty.
2525 * @param $token String: Rollback token.
2526 * @param $bot Boolean: If true, mark all reverted edits as bot.
2527 *
2528 * @param $resultDetails Array: contains result-specific array of additional values
2529 * 'alreadyrolled' : 'current' (rev)
2530 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2531 *
2532 * @param $user User The user performing the rollback
2533 * @return array of errors, each error formatted as
2534 * array(messagekey, param1, param2, ...).
2535 * On success, the array is empty. This array can also be passed to
2536 * OutputPage::showPermissionsErrorPage().
2537 */
2538 public function doRollback(
2539 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2540 ) {
2541 $resultDetails = null;
2542
2543 # Check permissions
2544 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2545 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2546 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2547
2548 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2549 $errors[] = array( 'sessionfailure' );
2550 }
2551
2552 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2553 $errors[] = array( 'actionthrottledtext' );
2554 }
2555
2556 # If there were errors, bail out now
2557 if ( !empty( $errors ) ) {
2558 return $errors;
2559 }
2560
2561 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2562 }
2563
2564 /**
2565 * Backend implementation of doRollback(), please refer there for parameter
2566 * and return value documentation
2567 *
2568 * NOTE: This function does NOT check ANY permissions, it just commits the
2569 * rollback to the DB. Therefore, you should only call this function direct-
2570 * ly if you want to use custom permissions checks. If you don't, use
2571 * doRollback() instead.
2572 * @param $fromP String: Name of the user whose edits to rollback.
2573 * @param $summary String: Custom summary. Set to default summary if empty.
2574 * @param $bot Boolean: If true, mark all reverted edits as bot.
2575 *
2576 * @param $resultDetails Array: contains result-specific array of additional values
2577 * @param $guser User The user performing the rollback
2578 * @return array
2579 */
2580 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2581 global $wgUseRCPatrol, $wgContLang;
2582
2583 $dbw = wfGetDB( DB_MASTER );
2584
2585 if ( wfReadOnly() ) {
2586 return array( array( 'readonlytext' ) );
2587 }
2588
2589 # Get the last editor
2590 $current = $this->getRevision();
2591 if ( is_null( $current ) ) {
2592 # Something wrong... no page?
2593 return array( array( 'notanarticle' ) );
2594 }
2595
2596 $from = str_replace( '_', ' ', $fromP );
2597 # User name given should match up with the top revision.
2598 # If the user was deleted then $from should be empty.
2599 if ( $from != $current->getUserText() ) {
2600 $resultDetails = array( 'current' => $current );
2601 return array( array( 'alreadyrolled',
2602 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2603 htmlspecialchars( $fromP ),
2604 htmlspecialchars( $current->getUserText() )
2605 ) );
2606 }
2607
2608 # Get the last edit not by this guy...
2609 # Note: these may not be public values
2610 $user = intval( $current->getRawUser() );
2611 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2612 $s = $dbw->selectRow( 'revision',
2613 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2614 array( 'rev_page' => $current->getPage(),
2615 "rev_user != {$user} OR rev_user_text != {$user_text}"
2616 ), __METHOD__,
2617 array( 'USE INDEX' => 'page_timestamp',
2618 'ORDER BY' => 'rev_timestamp DESC' )
2619 );
2620 if ( $s === false ) {
2621 # No one else ever edited this page
2622 return array( array( 'cantrollback' ) );
2623 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2624 # Only admins can see this text
2625 return array( array( 'notvisiblerev' ) );
2626 }
2627
2628 $set = array();
2629 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2630 # Mark all reverted edits as bot
2631 $set['rc_bot'] = 1;
2632 }
2633
2634 if ( $wgUseRCPatrol ) {
2635 # Mark all reverted edits as patrolled
2636 $set['rc_patrolled'] = 1;
2637 }
2638
2639 if ( count( $set ) ) {
2640 $dbw->update( 'recentchanges', $set,
2641 array( /* WHERE */
2642 'rc_cur_id' => $current->getPage(),
2643 'rc_user_text' => $current->getUserText(),
2644 "rc_timestamp > '{$s->rev_timestamp}'",
2645 ), __METHOD__
2646 );
2647 }
2648
2649 # Generate the edit summary if necessary
2650 $target = Revision::newFromId( $s->rev_id );
2651 if ( empty( $summary ) ) {
2652 if ( $from == '' ) { // no public user name
2653 $summary = wfMsgForContent( 'revertpage-nouser' );
2654 } else {
2655 $summary = wfMsgForContent( 'revertpage' );
2656 }
2657 }
2658
2659 # Allow the custom summary to use the same args as the default message
2660 $args = array(
2661 $target->getUserText(), $from, $s->rev_id,
2662 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2663 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2664 );
2665 $summary = wfMsgReplaceArgs( $summary, $args );
2666
2667 # Save
2668 $flags = EDIT_UPDATE;
2669
2670 if ( $guser->isAllowed( 'minoredit' ) ) {
2671 $flags |= EDIT_MINOR;
2672 }
2673
2674 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2675 $flags |= EDIT_FORCE_BOT;
2676 }
2677
2678 # Actually store the edit
2679 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2680 if ( !empty( $status->value['revision'] ) ) {
2681 $revId = $status->value['revision']->getId();
2682 } else {
2683 $revId = false;
2684 }
2685
2686 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2687
2688 $resultDetails = array(
2689 'summary' => $summary,
2690 'current' => $current,
2691 'target' => $target,
2692 'newid' => $revId
2693 );
2694
2695 return array();
2696 }
2697
2698 /**
2699 * The onArticle*() functions are supposed to be a kind of hooks
2700 * which should be called whenever any of the specified actions
2701 * are done.
2702 *
2703 * This is a good place to put code to clear caches, for instance.
2704 *
2705 * This is called on page move and undelete, as well as edit
2706 *
2707 * @param $title Title object
2708 */
2709 public static function onArticleCreate( $title ) {
2710 # Update existence markers on article/talk tabs...
2711 if ( $title->isTalkPage() ) {
2712 $other = $title->getSubjectPage();
2713 } else {
2714 $other = $title->getTalkPage();
2715 }
2716
2717 $other->invalidateCache();
2718 $other->purgeSquid();
2719
2720 $title->touchLinks();
2721 $title->purgeSquid();
2722 $title->deleteTitleProtection();
2723 }
2724
2725 /**
2726 * Clears caches when article is deleted
2727 *
2728 * @param $title Title
2729 */
2730 public static function onArticleDelete( $title ) {
2731 # Update existence markers on article/talk tabs...
2732 if ( $title->isTalkPage() ) {
2733 $other = $title->getSubjectPage();
2734 } else {
2735 $other = $title->getTalkPage();
2736 }
2737
2738 $other->invalidateCache();
2739 $other->purgeSquid();
2740
2741 $title->touchLinks();
2742 $title->purgeSquid();
2743
2744 # File cache
2745 HTMLFileCache::clearFileCache( $title );
2746
2747 # Messages
2748 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2749 MessageCache::singleton()->replace( $title->getDBkey(), false );
2750 }
2751
2752 # Images
2753 if ( $title->getNamespace() == NS_FILE ) {
2754 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2755 $update->doUpdate();
2756 }
2757
2758 # User talk pages
2759 if ( $title->getNamespace() == NS_USER_TALK ) {
2760 $user = User::newFromName( $title->getText(), false );
2761 if ( $user ) {
2762 $user->setNewtalk( false );
2763 }
2764 }
2765
2766 # Image redirects
2767 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2768 }
2769
2770 /**
2771 * Purge caches on page update etc
2772 *
2773 * @param $title Title object
2774 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2775 */
2776 public static function onArticleEdit( $title ) {
2777 // Invalidate caches of articles which include this page
2778 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2779
2780
2781 // Invalidate the caches of all pages which redirect here
2782 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2783
2784 # Purge squid for this page only
2785 $title->purgeSquid();
2786
2787 # Clear file cache for this page only
2788 HTMLFileCache::clearFileCache( $title );
2789 }
2790
2791 /**#@-*/
2792
2793 /**
2794 * Returns a list of hidden categories this page is a member of.
2795 * Uses the page_props and categorylinks tables.
2796 *
2797 * @return Array of Title objects
2798 */
2799 public function getHiddenCategories() {
2800 $result = array();
2801 $id = $this->mTitle->getArticleID();
2802
2803 if ( $id == 0 ) {
2804 return array();
2805 }
2806
2807 $dbr = wfGetDB( DB_SLAVE );
2808 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2809 array( 'cl_to' ),
2810 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2811 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2812 __METHOD__ );
2813
2814 if ( $res !== false ) {
2815 foreach ( $res as $row ) {
2816 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2817 }
2818 }
2819
2820 return $result;
2821 }
2822
2823 /**
2824 * Return an applicable autosummary if one exists for the given edit.
2825 * @param $oldtext String|null: the previous text of the page.
2826 * @param $newtext String|null: The submitted text of the page.
2827 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2828 * @return string An appropriate autosummary, or an empty string.
2829 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2830 */
2831 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2832 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2833
2834 wfDeprecated( __METHOD__, '1.WD' );
2835
2836 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
2837 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
2838 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
2839
2840 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2841 }
2842
2843 /**
2844 * Auto-generates a deletion reason
2845 *
2846 * @param &$hasHistory Boolean: whether the page has a history
2847 * @return mixed String containing deletion reason or empty string, or boolean false
2848 * if no revision occurred
2849 * @deprecated since 1.WD, use ContentHandler::getAutoDeleteReason() instead
2850 */
2851 public function getAutoDeleteReason( &$hasHistory ) {
2852 #NOTE: stub for backwards-compatibility.
2853
2854 wfDeprecated( __METHOD__, '1.WD' );
2855
2856 $handler = ContentHandler::getForTitle( $this->getTitle() );
2857 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2858 global $wgContLang;
2859
2860 // Get the last revision
2861 $rev = $this->getRevision();
2862
2863 if ( is_null( $rev ) ) {
2864 return false;
2865 }
2866
2867 // Get the article's contents
2868 $contents = $rev->getText();
2869 $blank = false;
2870
2871 // If the page is blank, use the text from the previous revision,
2872 // which can only be blank if there's a move/import/protect dummy revision involved
2873 if ( $contents == '' ) {
2874 $prev = $rev->getPrevious();
2875
2876 if ( $prev ) {
2877 $contents = $prev->getText();
2878 $blank = true;
2879 }
2880 }
2881
2882 $dbw = wfGetDB( DB_MASTER );
2883
2884 // Find out if there was only one contributor
2885 // Only scan the last 20 revisions
2886 $res = $dbw->select( 'revision', 'rev_user_text',
2887 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2888 __METHOD__,
2889 array( 'LIMIT' => 20 )
2890 );
2891
2892 if ( $res === false ) {
2893 // This page has no revisions, which is very weird
2894 return false;
2895 }
2896
2897 $hasHistory = ( $res->numRows() > 1 );
2898 $row = $dbw->fetchObject( $res );
2899
2900 if ( $row ) { // $row is false if the only contributor is hidden
2901 $onlyAuthor = $row->rev_user_text;
2902 // Try to find a second contributor
2903 foreach ( $res as $row ) {
2904 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2905 $onlyAuthor = false;
2906 break;
2907 }
2908 }
2909 } else {
2910 $onlyAuthor = false;
2911 }
2912
2913 // Generate the summary with a '$1' placeholder
2914 if ( $blank ) {
2915 // The current revision is blank and the one before is also
2916 // blank. It's just not our lucky day
2917 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2918 } else {
2919 if ( $onlyAuthor ) {
2920 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2921 } else {
2922 $reason = wfMsgForContent( 'excontent', '$1' );
2923 }
2924 }
2925
2926 if ( $reason == '-' ) {
2927 // Allow these UI messages to be blanked out cleanly
2928 return '';
2929 }
2930
2931 // Replace newlines with spaces to prevent uglyness
2932 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2933 // Calculate the maximum amount of chars to get
2934 // Max content length = max comment length - length of the comment (excl. $1)
2935 $maxLength = 255 - ( strlen( $reason ) - 2 );
2936 $contents = $wgContLang->truncate( $contents, $maxLength );
2937 // Remove possible unfinished links
2938 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2939 // Now replace the '$1' placeholder
2940 $reason = str_replace( '$1', $contents, $reason );
2941
2942 return $reason;
2943 }
2944
2945 /**
2946 * Update all the appropriate counts in the category table, given that
2947 * we've added the categories $added and deleted the categories $deleted.
2948 *
2949 * @param $added array The names of categories that were added
2950 * @param $deleted array The names of categories that were deleted
2951 */
2952 public function updateCategoryCounts( $added, $deleted ) {
2953 $ns = $this->mTitle->getNamespace();
2954 $dbw = wfGetDB( DB_MASTER );
2955
2956 # First make sure the rows exist. If one of the "deleted" ones didn't
2957 # exist, we might legitimately not create it, but it's simpler to just
2958 # create it and then give it a negative value, since the value is bogus
2959 # anyway.
2960 #
2961 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2962 $insertCats = array_merge( $added, $deleted );
2963 if ( !$insertCats ) {
2964 # Okay, nothing to do
2965 return;
2966 }
2967
2968 $insertRows = array();
2969
2970 foreach ( $insertCats as $cat ) {
2971 $insertRows[] = array(
2972 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2973 'cat_title' => $cat
2974 );
2975 }
2976 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2977
2978 $addFields = array( 'cat_pages = cat_pages + 1' );
2979 $removeFields = array( 'cat_pages = cat_pages - 1' );
2980
2981 if ( $ns == NS_CATEGORY ) {
2982 $addFields[] = 'cat_subcats = cat_subcats + 1';
2983 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2984 } elseif ( $ns == NS_FILE ) {
2985 $addFields[] = 'cat_files = cat_files + 1';
2986 $removeFields[] = 'cat_files = cat_files - 1';
2987 }
2988
2989 if ( $added ) {
2990 $dbw->update(
2991 'category',
2992 $addFields,
2993 array( 'cat_title' => $added ),
2994 __METHOD__
2995 );
2996 }
2997
2998 if ( $deleted ) {
2999 $dbw->update(
3000 'category',
3001 $removeFields,
3002 array( 'cat_title' => $deleted ),
3003 __METHOD__
3004 );
3005 }
3006 }
3007
3008 /**
3009 * Updates cascading protections
3010 *
3011 * @param $parserOutput ParserOutput object for the current version
3012 */
3013 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3014 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3015 return;
3016 }
3017
3018 // templatelinks table may have become out of sync,
3019 // especially if using variable-based transclusions.
3020 // For paranoia, check if things have changed and if
3021 // so apply updates to the database. This will ensure
3022 // that cascaded protections apply as soon as the changes
3023 // are visible.
3024
3025 # Get templates from templatelinks
3026 $id = $this->mTitle->getArticleID();
3027
3028 $tlTemplates = array();
3029
3030 $dbr = wfGetDB( DB_SLAVE );
3031 $res = $dbr->select( array( 'templatelinks' ),
3032 array( 'tl_namespace', 'tl_title' ),
3033 array( 'tl_from' => $id ),
3034 __METHOD__
3035 );
3036
3037 foreach ( $res as $row ) {
3038 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3039 }
3040
3041 # Get templates from parser output.
3042 $poTemplates = array();
3043 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3044 foreach ( $templates as $dbk => $id ) {
3045 $poTemplates["$ns:$dbk"] = true;
3046 }
3047 }
3048
3049 # Get the diff
3050 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3051
3052 if ( count( $templates_diff ) > 0 ) {
3053 # Whee, link updates time.
3054 # Note: we are only interested in links here. We don't need to get other SecondaryDataUpdate items from the parser output.
3055 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3056 $u->doUpdate();
3057 }
3058 }
3059
3060 /**
3061 * Return a list of templates used by this article.
3062 * Uses the templatelinks table
3063 *
3064 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3065 * @return Array of Title objects
3066 */
3067 public function getUsedTemplates() {
3068 return $this->mTitle->getTemplateLinksFrom();
3069 }
3070
3071 /**
3072 * Perform article updates on a special page creation.
3073 *
3074 * @param $rev Revision object
3075 *
3076 * @todo This is a shitty interface function. Kill it and replace the
3077 * other shitty functions like doEditUpdates and such so it's not needed
3078 * anymore.
3079 * @deprecated since 1.18, use doEditUpdates()
3080 */
3081 public function createUpdates( $rev ) {
3082 wfDeprecated( __METHOD__, '1.18' );
3083 global $wgUser;
3084 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3085 }
3086
3087 /**
3088 * This function is called right before saving the wikitext,
3089 * so we can do things like signatures and links-in-context.
3090 *
3091 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3092 * @param $text String article contents
3093 * @param $user User object: user doing the edit
3094 * @param $popts ParserOptions object: parser options, default options for
3095 * the user loaded if null given
3096 * @return string article contents with altered wikitext markup (signatures
3097 * converted, {{subst:}}, templates, etc.)
3098 */
3099 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3100 global $wgParser, $wgUser;
3101
3102 wfDeprecated( __METHOD__, '1.19' );
3103
3104 $user = is_null( $user ) ? $wgUser : $user;
3105
3106 if ( $popts === null ) {
3107 $popts = ParserOptions::newFromUser( $user );
3108 }
3109
3110 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3111 }
3112
3113 /**
3114 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3115 *
3116 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3117 * @return bool
3118 */
3119 public function isBigDeletion() {
3120 wfDeprecated( __METHOD__, '1.19' );
3121 return $this->mTitle->isBigDeletion();
3122 }
3123
3124 /**
3125 * Get the approximate revision count of this page.
3126 *
3127 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3128 * @return int
3129 */
3130 public function estimateRevisionCount() {
3131 wfDeprecated( __METHOD__, '1.19' );
3132 return $this->mTitle->estimateRevisionCount();
3133 }
3134
3135 /**
3136 * Update the article's restriction field, and leave a log entry.
3137 *
3138 * @deprecated since 1.19
3139 * @param $limit Array: set of restriction keys
3140 * @param $reason String
3141 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3142 * @param $expiry Array: per restriction type expiration
3143 * @param $user User The user updating the restrictions
3144 * @return bool true on success
3145 */
3146 public function updateRestrictions(
3147 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3148 ) {
3149 global $wgUser;
3150
3151 $user = is_null( $user ) ? $wgUser : $user;
3152
3153 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3154 }
3155
3156 /**
3157 * @deprecated since 1.18
3158 */
3159 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3160 wfDeprecated( __METHOD__, '1.18' );
3161 global $wgUser;
3162 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3163 }
3164
3165 /**
3166 * @deprecated since 1.18
3167 */
3168 public function viewUpdates() {
3169 wfDeprecated( __METHOD__, '1.18' );
3170 global $wgUser;
3171 return $this->doViewUpdates( $wgUser );
3172 }
3173
3174 /**
3175 * @deprecated since 1.18
3176 * @return bool
3177 */
3178 public function useParserCache( $oldid ) {
3179 wfDeprecated( __METHOD__, '1.18' );
3180 global $wgUser;
3181 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
3182 }
3183 }
3184
3185 class PoolWorkArticleView extends PoolCounterWork {
3186
3187 /**
3188 * @var Page
3189 */
3190 private $page;
3191
3192 /**
3193 * @var string
3194 */
3195 private $cacheKey;
3196
3197 /**
3198 * @var integer
3199 */
3200 private $revid;
3201
3202 /**
3203 * @var ParserOptions
3204 */
3205 private $parserOptions;
3206
3207 /**
3208 * @var string|null
3209 */
3210 private $text;
3211
3212 /**
3213 * @var ParserOutput|bool
3214 */
3215 private $parserOutput = false;
3216
3217 /**
3218 * @var bool
3219 */
3220 private $isDirty = false;
3221
3222 /**
3223 * @var Status|bool
3224 */
3225 private $error = false;
3226
3227 /**
3228 * Constructor
3229 *
3230 * @param $page Page
3231 * @param $revid Integer: ID of the revision being parsed
3232 * @param $useParserCache Boolean: whether to use the parser cache
3233 * @param $parserOptions parserOptions to use for the parse operation
3234 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3235 * @param $context IContextSource context for parsing
3236 */
3237 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $content = null, IContextSource $context = null ) {
3238 if ( is_string($content) ) { #BC: old style call
3239 $modelId = $page->getRevision()->getContentModel();
3240 $format = $page->getRevision()->getContentFormat();
3241 $content = ContentHandler::makeContent( $content, $page->getTitle(), $modelId, $format );
3242 }
3243
3244 if ( is_null( $context ) ) {
3245 $context = RequestContext::getMain();
3246 #XXX: clone and then set title?
3247 }
3248
3249 $this->page = $page;
3250 $this->revid = $revid;
3251 $this->context = $context;
3252 $this->cacheable = $useParserCache;
3253 $this->parserOptions = $parserOptions;
3254 $this->content = $content;
3255 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
3256 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
3257 }
3258
3259 /**
3260 * Get the ParserOutput from this object, or false in case of failure
3261 *
3262 * @return ParserOutput
3263 */
3264 public function getParserOutput() {
3265 return $this->parserOutput;
3266 }
3267
3268 /**
3269 * Get whether the ParserOutput is a dirty one (i.e. expired)
3270 *
3271 * @return bool
3272 */
3273 public function getIsDirty() {
3274 return $this->isDirty;
3275 }
3276
3277 /**
3278 * Get a Status object in case of error or false otherwise
3279 *
3280 * @return Status|bool
3281 */
3282 public function getError() {
3283 return $this->error;
3284 }
3285
3286 /**
3287 * @return bool
3288 */
3289 function doWork() {
3290 global $wgUseFileCache;
3291
3292 // @todo: several of the methods called on $this->page are not declared in Page, but present in WikiPage and delegated by Article.
3293
3294 $isCurrent = $this->revid === $this->page->getLatest();
3295
3296 if ( $this->content !== null ) {
3297 $content = $this->content;
3298 } elseif ( $isCurrent ) {
3299 $content = $this->page->getContent( Revision::RAW ); #XXX: why use RAW audience here, and PUBLIC (default) below?
3300 } else {
3301 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
3302 if ( $rev === null ) {
3303 return false;
3304 }
3305 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3306 }
3307
3308 $time = - microtime( true );
3309 // TODO: page might not have this method? Hard to tell what page is supposed to be here...
3310 $this->parserOutput = $content->getParserOutput( $this->context, $this->revid, $this->parserOptions );
3311 $time += microtime( true );
3312
3313 # Timing hack
3314 if ( $time > 3 ) {
3315 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3316 $this->page->getTitle()->getPrefixedDBkey() ) );
3317 }
3318
3319 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
3320 ParserCache::singleton()->save( $this->parserOutput, $this->page, $this->parserOptions );
3321 }
3322
3323 // Make sure file cache is not used on uncacheable content.
3324 // Output that has magic words in it can still use the parser cache
3325 // (if enabled), though it will generally expire sooner.
3326 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
3327 $wgUseFileCache = false;
3328 }
3329
3330 if ( $isCurrent ) {
3331 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
3332 }
3333
3334 return true;
3335 }
3336
3337 /**
3338 * @return bool
3339 */
3340 function getCachedWork() {
3341 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
3342
3343 if ( $this->parserOutput === false ) {
3344 wfDebug( __METHOD__ . ": parser cache miss\n" );
3345 return false;
3346 } else {
3347 wfDebug( __METHOD__ . ": parser cache hit\n" );
3348 return true;
3349 }
3350 }
3351
3352 /**
3353 * @return bool
3354 */
3355 function fallback() {
3356 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
3357
3358 if ( $this->parserOutput === false ) {
3359 wfDebugLog( 'dirty', "dirty missing\n" );
3360 wfDebug( __METHOD__ . ": no dirty cache\n" );
3361 return false;
3362 } else {
3363 wfDebug( __METHOD__ . ": sending dirty output\n" );
3364 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3365 $this->isDirty = true;
3366 return true;
3367 }
3368 }
3369
3370 /**
3371 * @param $status Status
3372 * @return bool
3373 */
3374 function error( $status ) {
3375 $this->error = $status;
3376 return false;
3377 }
3378 }
3379