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