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