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