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