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