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