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