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