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