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