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