939eee61807f8967f82f295c823b1c313eea6ad3
[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 $mCounter = -1; // !< Integer (-1 means "not loaded")
25 public $mDataLoaded = false; // !< Boolean
26 public $mIsRedirect = false; // !< Boolean
27 public $mLatest = false; // !< Integer (false means "not loaded")
28 public $mPreparedEdit = false; // !< Array
29
30 /**
31 * @var Title
32 */
33 protected $mRedirectTarget = null;
34
35 /**
36 * @var Revision
37 */
38 protected $mLastRevision = null;
39
40 protected $mTimestamp = ''; // !< String
41 protected $mTouched = '19700101000000'; // !< String
42 /**@}}*/
43
44 /**
45 * Constructor and clear the article
46 * @param $title Title Reference to a Title object.
47 */
48 public function __construct( Title $title ) {
49 $this->mTitle = $title;
50 }
51
52 /**
53 * Create a WikiPage object of the appropriate class for the given title.
54 *
55 * @param $title Title
56 * @return WikiPage object of the appropriate type
57 */
58 public static function factory( Title $title ) {
59 $ns = $title->getNamespace();
60
61 if ( $ns == NS_MEDIA ) {
62 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
63 } elseif ( $ns < 0 ) {
64 throw new MWException( "Invalid or virtual namespace $ns given." );
65 }
66
67 switch ( $ns ) {
68 case NS_FILE:
69 $page = new WikiFilePage( $title );
70 break;
71 case NS_CATEGORY:
72 $page = new WikiCategoryPage( $title );
73 break;
74 default:
75 $page = new WikiPage( $title );
76 }
77
78 return $page;
79 }
80
81 /**
82 * Constructor from a page id
83 *
84 * @param $id Int article ID to load
85 *
86 * @return WikiPage
87 */
88 public static function newFromID( $id ) {
89 $t = Title::newFromID( $id );
90 if ( $t ) {
91 return self::factory( $t );
92 }
93 return null;
94 }
95
96 /**
97 * Returns overrides for action handlers.
98 * Classes listed here will be used instead of the default one when
99 * (and only when) $wgActions[$action] === true. This allows subclasses
100 * to override the default behavior.
101 *
102 * @todo: move this UI stuff somewhere else
103 *
104 * @return Array
105 */
106 public function getActionOverrides() {
107 return array();
108 }
109
110 /**
111 * If this page is a redirect, get its target
112 *
113 * The target will be fetched from the redirect table if possible.
114 * If this page doesn't have an entry there, call insertRedirect()
115 * @return Title|mixed object, or null if this page is not a redirect
116 */
117 public function getRedirectTarget() {
118 if ( !$this->mTitle->isRedirect() ) {
119 return null;
120 }
121
122 if ( $this->mRedirectTarget !== null ) {
123 return $this->mRedirectTarget;
124 }
125
126 # Query the redirect table
127 $dbr = wfGetDB( DB_SLAVE );
128 $row = $dbr->selectRow( 'redirect',
129 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
130 array( 'rd_from' => $this->getId() ),
131 __METHOD__
132 );
133
134 // rd_fragment and rd_interwiki were added later, populate them if empty
135 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
136 return $this->mRedirectTarget = Title::makeTitle(
137 $row->rd_namespace, $row->rd_title,
138 $row->rd_fragment, $row->rd_interwiki );
139 }
140
141 # This page doesn't have an entry in the redirect table
142 return $this->mRedirectTarget = $this->insertRedirect();
143 }
144
145 /**
146 * Insert an entry for this page into the redirect table.
147 *
148 * Don't call this function directly unless you know what you're doing.
149 * @return Title object or null if not a redirect
150 */
151 public function insertRedirect() {
152 // recurse through to only get the final target
153 $retval = Title::newFromRedirectRecurse( $this->getRawText() );
154 if ( !$retval ) {
155 return null;
156 }
157 $this->insertRedirectEntry( $retval );
158 return $retval;
159 }
160
161 /**
162 * Insert or update the redirect table entry for this page to indicate
163 * it redirects to $rt .
164 * @param $rt Title redirect target
165 */
166 public function insertRedirectEntry( $rt ) {
167 $dbw = wfGetDB( DB_MASTER );
168 $dbw->replace( 'redirect', array( 'rd_from' ),
169 array(
170 'rd_from' => $this->getId(),
171 'rd_namespace' => $rt->getNamespace(),
172 'rd_title' => $rt->getDBkey(),
173 'rd_fragment' => $rt->getFragment(),
174 'rd_interwiki' => $rt->getInterwiki(),
175 ),
176 __METHOD__
177 );
178 }
179
180 /**
181 * Get the Title object or URL this page redirects to
182 *
183 * @return mixed false, Title of in-wiki target, or string with URL
184 */
185 public function followRedirect() {
186 return $this->getRedirectURL( $this->getRedirectTarget() );
187 }
188
189 /**
190 * Get the Title object or URL to use for a redirect. We use Title
191 * objects for same-wiki, non-special redirects and URLs for everything
192 * else.
193 * @param $rt Title Redirect target
194 * @return mixed false, Title object of local target, or string with URL
195 */
196 public function getRedirectURL( $rt ) {
197 if ( $rt ) {
198 if ( $rt->getInterwiki() != '' ) {
199 if ( $rt->isLocal() ) {
200 // Offsite wikis need an HTTP redirect.
201 //
202 // This can be hard to reverse and may produce loops,
203 // so they may be disabled in the site configuration.
204 $source = $this->mTitle->getFullURL( 'redirect=no' );
205 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
206 }
207 } else {
208 if ( $rt->isSpecialPage() ) {
209 // Gotta handle redirects to special pages differently:
210 // Fill the HTTP response "Location" header and ignore
211 // the rest of the page we're on.
212 //
213 // This can be hard to reverse, so they may be disabled.
214 if ( $rt->isSpecial( 'Userlogout' ) ) {
215 // rolleyes
216 } else {
217 return $rt->getFullURL();
218 }
219 }
220
221 return $rt;
222 }
223 }
224
225 // No or invalid redirect
226 return false;
227 }
228
229 /**
230 * Get the title object of the article
231 * @return Title object of this page
232 */
233 public function getTitle() {
234 return $this->mTitle;
235 }
236
237 /**
238 * Clear the object
239 */
240 public function clear() {
241 $this->mDataLoaded = false;
242
243 $this->mCounter = -1; # Not loaded
244 $this->mRedirectTarget = null; # Title object if set
245 $this->mLastRevision = null; # Latest revision
246 $this->mTimestamp = '';
247 $this->mTouched = '19700101000000';
248 $this->mIsRedirect = false;
249 $this->mLatest = false;
250 $this->mPreparedEdit = false;
251 }
252
253 /**
254 * Get the text that needs to be saved in order to undo all revisions
255 * between $undo and $undoafter. Revisions must belong to the same page,
256 * must exist and must not be deleted
257 * @param $undo Revision
258 * @param $undoafter Revision Must be an earlier revision than $undo
259 * @return mixed string on success, false on failure
260 */
261 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
262 $cur_text = $this->getRawText();
263 if ( $cur_text === false ) {
264 return false; // no page
265 }
266 $undo_text = $undo->getText();
267 $undoafter_text = $undoafter->getText();
268
269 if ( $cur_text == $undo_text ) {
270 # No use doing a merge if it's just a straight revert.
271 return $undoafter_text;
272 }
273
274 $undone_text = '';
275
276 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
277 return false;
278 }
279
280 return $undone_text;
281 }
282
283 /**
284 * Return the list of revision fields that should be selected to create
285 * a new page.
286 *
287 * @return array
288 */
289 public static function selectFields() {
290 return array(
291 'page_id',
292 'page_namespace',
293 'page_title',
294 'page_restrictions',
295 'page_counter',
296 'page_is_redirect',
297 'page_is_new',
298 'page_random',
299 'page_touched',
300 'page_latest',
301 'page_len',
302 );
303 }
304
305 /**
306 * Fetch a page record with the given conditions
307 * @param $dbr DatabaseBase object
308 * @param $conditions Array
309 * @return mixed Database result resource, or false on failure
310 */
311 protected function pageData( $dbr, $conditions ) {
312 $fields = self::selectFields();
313
314 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
315
316 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__ );
317
318 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
319
320 return $row;
321 }
322
323 /**
324 * Fetch a page record matching the Title object's namespace and title
325 * using a sanitized title string
326 *
327 * @param $dbr DatabaseBase object
328 * @param $title Title object
329 * @return mixed Database result resource, or false on failure
330 */
331 public function pageDataFromTitle( $dbr, $title ) {
332 return $this->pageData( $dbr, array(
333 'page_namespace' => $title->getNamespace(),
334 'page_title' => $title->getDBkey() ) );
335 }
336
337 /**
338 * Fetch a page record matching the requested ID
339 *
340 * @param $dbr DatabaseBase
341 * @param $id Integer
342 * @return mixed Database result resource, or false on failure
343 */
344 public function pageDataFromId( $dbr, $id ) {
345 return $this->pageData( $dbr, array( 'page_id' => $id ) );
346 }
347
348 /**
349 * Set the general counter, title etc data loaded from
350 * some source.
351 *
352 * @param $data Object|String One of the following:
353 * A DB query result object or...
354 * "fromdb" to get from a slave DB or...
355 * "fromdbmaster" to get from the master DB
356 * @return void
357 */
358 public function loadPageData( $data = 'fromdb' ) {
359 if ( $data === 'fromdbmaster' ) {
360 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
361 } elseif ( $data === 'fromdb' ) { // slave
362 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE ), $this->mTitle );
363 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
364 # Note that DB also stores the master position in the session and checks it.
365 $touched = $this->getCachedLastEditTime();
366 if ( $touched ) { // key set
367 if ( !$data || $touched > wfTimestamp( TS_MW, $data->page_touched ) ) {
368 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
369 }
370 }
371 }
372
373 $lc = LinkCache::singleton();
374
375 if ( $data ) {
376 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
377
378 $this->mTitle->loadFromRow( $data );
379
380 # Old-fashioned restrictions
381 $this->mTitle->loadRestrictions( $data->page_restrictions );
382
383 $this->mCounter = intval( $data->page_counter );
384 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
385 $this->mIsRedirect = intval( $data->page_is_redirect );
386 $this->mLatest = intval( $data->page_latest );
387 } else {
388 $lc->addBadLinkObj( $this->mTitle );
389
390 $this->mTitle->loadFromRow( false );
391 }
392
393 $this->mDataLoaded = true;
394 }
395
396 /**
397 * @return int Page ID
398 */
399 public function getId() {
400 return $this->mTitle->getArticleID();
401 }
402
403 /**
404 * @return bool Whether or not the page exists in the database
405 */
406 public function exists() {
407 return $this->getId() > 0;
408 }
409
410 /**
411 * Check if this page is something we're going to be showing
412 * some sort of sensible content for. If we return false, page
413 * views (plain action=view) will return an HTTP 404 response,
414 * so spiders and robots can know they're following a bad link.
415 *
416 * @return bool
417 */
418 public function hasViewableContent() {
419 return $this->exists() || $this->mTitle->isAlwaysKnown();
420 }
421
422 /**
423 * @return int The view count for the page
424 */
425 public function getCount() {
426 if ( -1 == $this->mCounter ) {
427 $id = $this->getId();
428
429 if ( $id == 0 ) {
430 $this->mCounter = 0;
431 } else {
432 $dbr = wfGetDB( DB_SLAVE );
433 $this->mCounter = $dbr->selectField( 'page',
434 'page_counter',
435 array( 'page_id' => $id ),
436 __METHOD__
437 );
438 }
439 }
440
441 return $this->mCounter;
442 }
443
444 /**
445 * Determine whether a page would be suitable for being counted as an
446 * article in the site_stats table based on the title & its content
447 *
448 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
449 * if false, the current database state will be used
450 * @return Boolean
451 */
452 public function isCountable( $editInfo = false ) {
453 global $wgArticleCountMethod;
454
455 if ( !$this->mTitle->isContentPage() ) {
456 return false;
457 }
458
459 $text = $editInfo ? $editInfo->pst : false;
460
461 if ( $this->isRedirect( $text ) ) {
462 return false;
463 }
464
465 switch ( $wgArticleCountMethod ) {
466 case 'any':
467 return true;
468 case 'comma':
469 if ( $text === false ) {
470 $text = $this->getRawText();
471 }
472 return strpos( $text, ',' ) !== false;
473 case 'link':
474 if ( $editInfo ) {
475 // ParserOutput::getLinks() is a 2D array of page links, so
476 // to be really correct we would need to recurse in the array
477 // but the main array should only have items in it if there are
478 // links.
479 return (bool)count( $editInfo->output->getLinks() );
480 } else {
481 return (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
482 array( 'pl_from' => $this->getId() ), __METHOD__ );
483 }
484 }
485 }
486
487 /**
488 * Tests if the article text represents a redirect
489 *
490 * @param $text mixed string containing article contents, or boolean
491 * @return bool
492 */
493 public function isRedirect( $text = false ) {
494 if ( $text === false ) {
495 if ( !$this->mDataLoaded ) {
496 $this->loadPageData();
497 }
498
499 return (bool)$this->mIsRedirect;
500 } else {
501 return Title::newFromRedirect( $text ) !== null;
502 }
503 }
504
505 /**
506 * Loads everything except the text
507 * This isn't necessary for all uses, so it's only done if needed.
508 */
509 protected function loadLastEdit() {
510 if ( $this->mLastRevision !== null ) {
511 return; // already loaded
512 }
513
514 $latest = $this->getLatest();
515 if ( !$latest ) {
516 return; // page doesn't exist or is missing page_latest info
517 }
518
519 $revision = Revision::newFromPageId( $this->getId(), $latest );
520 if ( $revision ) { // sanity
521 $this->setLastEdit( $revision );
522 }
523 }
524
525 /**
526 * Set the latest revision
527 */
528 protected function setLastEdit( Revision $revision ) {
529 $this->mLastRevision = $revision;
530 $this->mTimestamp = $revision->getTimestamp();
531 }
532
533 /**
534 * Get the latest revision
535 * @return Revision|null
536 */
537 public function getRevision() {
538 $this->loadLastEdit();
539 if ( $this->mLastRevision ) {
540 return $this->mLastRevision;
541 }
542 return null;
543 }
544
545 /**
546 * Get the text of the current revision. No side-effects...
547 *
548 * @param $audience Integer: one of:
549 * Revision::FOR_PUBLIC to be displayed to all users
550 * Revision::FOR_THIS_USER to be displayed to $wgUser
551 * Revision::RAW get the text regardless of permissions
552 * @return String|false The text of the current revision
553 */
554 public function getText( $audience = Revision::FOR_PUBLIC ) {
555 $this->loadLastEdit();
556 if ( $this->mLastRevision ) {
557 return $this->mLastRevision->getText( $audience );
558 }
559 return false;
560 }
561
562 /**
563 * Get the text of the current revision. No side-effects...
564 *
565 * @return String|false The text of the current revision
566 */
567 public function getRawText() {
568 $this->loadLastEdit();
569 if ( $this->mLastRevision ) {
570 return $this->mLastRevision->getRawText();
571 }
572 return false;
573 }
574
575 /**
576 * @return string MW timestamp of last article revision
577 */
578 public function getTimestamp() {
579 // Check if the field has been filled by WikiPage::setTimestamp()
580 if ( !$this->mTimestamp ) {
581 $this->loadLastEdit();
582 }
583 return wfTimestamp( TS_MW, $this->mTimestamp );
584 }
585
586 /**
587 * Set the page timestamp (use only to avoid DB queries)
588 * @param $ts string MW timestamp of last article revision
589 * @return void
590 */
591 public function setTimestamp( $ts ) {
592 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
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 int user ID for the user that made the last article revision
601 */
602 public function getUser( $audience = Revision::FOR_PUBLIC ) {
603 $this->loadLastEdit();
604 if ( $this->mLastRevision ) {
605 return $this->mLastRevision->getUser( $audience );
606 } else {
607 return -1;
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 username of the user that made the last article revision
617 */
618 public function getUserText( $audience = Revision::FOR_PUBLIC ) {
619 $this->loadLastEdit();
620 if ( $this->mLastRevision ) {
621 return $this->mLastRevision->getUserText( $audience );
622 } else {
623 return '';
624 }
625 }
626
627 /**
628 * @param $audience Integer: one of:
629 * Revision::FOR_PUBLIC to be displayed to all users
630 * Revision::FOR_THIS_USER to be displayed to $wgUser
631 * Revision::RAW get the text regardless of permissions
632 * @return string Comment stored for the last article revision
633 */
634 public function getComment( $audience = Revision::FOR_PUBLIC ) {
635 $this->loadLastEdit();
636 if ( $this->mLastRevision ) {
637 return $this->mLastRevision->getComment( $audience );
638 } else {
639 return '';
640 }
641 }
642
643 /**
644 * Returns true if last revision was marked as "minor edit"
645 *
646 * @return boolean Minor edit indicator for the last article revision.
647 */
648 public function getMinorEdit() {
649 $this->loadLastEdit();
650 if ( $this->mLastRevision ) {
651 return $this->mLastRevision->isMinor();
652 } else {
653 return false;
654 }
655 }
656
657 /**
658 * Get a list of users who have edited this article, not including the user who made
659 * the most recent revision, which you can get from $article->getUser() if you want it
660 * @return UserArrayFromResult
661 */
662 public function getContributors() {
663 # @todo FIXME: This is expensive; cache this info somewhere.
664
665 $dbr = wfGetDB( DB_SLAVE );
666
667 if ( $dbr->implicitGroupby() ) {
668 $realNameField = 'user_real_name';
669 } else {
670 $realNameField = 'MIN(user_real_name) AS user_real_name';
671 }
672
673 $tables = array( 'revision', 'user' );
674
675 $fields = array(
676 'rev_user as user_id',
677 'rev_user_text AS user_name',
678 $realNameField,
679 'MAX(rev_timestamp) AS timestamp',
680 );
681
682 $conds = array( 'rev_page' => $this->getId() );
683
684 // The user who made the top revision gets credited as "this page was last edited by
685 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
686 $user = $this->getUser();
687 if ( $user ) {
688 $conds[] = "rev_user != $user";
689 } else {
690 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
691 }
692
693 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
694
695 $jconds = array(
696 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
697 );
698
699 $options = array(
700 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
701 'ORDER BY' => 'timestamp DESC',
702 );
703
704 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
705 return new UserArrayFromResult( $res );
706 }
707
708 /**
709 * Should the parser cache be used?
710 *
711 * @param $parserOptions ParserOptions to check
712 * @param $oldid int
713 * @return boolean
714 */
715 public function isParserCacheUsed( ParserOptions $parserOptions, $oldid ) {
716 global $wgEnableParserCache;
717
718 return $wgEnableParserCache
719 && $parserOptions->getStubThreshold() == 0
720 && $this->exists()
721 && ( $oldid === null || $oldid === 0 || $oldid === $this->getLatest() )
722 && $this->mTitle->isWikitextPage();
723 }
724
725 /**
726 * Get a ParserOutput for the given ParserOptions and revision ID.
727 * The parser cache will be used if possible.
728 *
729 * @since 1.19
730 * @param $parserOptions ParserOptions to use for the parse operation
731 * @param $oldid Revision ID to get the text from, passing null or 0 will
732 * get the current revision (default value)
733 * @return ParserOutput or false if the revision was not found
734 */
735 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
736 wfProfileIn( __METHOD__ );
737
738 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
739 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
740 if ( $parserOptions->getStubThreshold() ) {
741 wfIncrStats( 'pcache_miss_stub' );
742 }
743
744 if ( $useParserCache ) {
745 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
746 if ( $parserOutput !== false ) {
747 wfProfileOut( __METHOD__ );
748 return $parserOutput;
749 }
750 }
751
752 if ( $oldid === null || $oldid === 0 ) {
753 $oldid = $this->getLatest();
754 }
755
756 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
757 $pool->execute();
758
759 wfProfileOut( __METHOD__ );
760
761 return $pool->getParserOutput();
762 }
763
764 /**
765 * Perform the actions of a page purging
766 */
767 public function doPurge() {
768 global $wgUseSquid;
769
770 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
771 return false;
772 }
773
774 // Invalidate the cache
775 $this->mTitle->invalidateCache();
776 $this->clear();
777
778 if ( $wgUseSquid ) {
779 // Commit the transaction before the purge is sent
780 $dbw = wfGetDB( DB_MASTER );
781 $dbw->commit();
782
783 // Send purge
784 $update = SquidUpdate::newSimplePurge( $this->mTitle );
785 $update->doUpdate();
786 }
787
788 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
789 if ( $this->getId() == 0 ) {
790 $text = false;
791 } else {
792 $text = $this->getRawText();
793 }
794
795 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
796 }
797 return true;
798 }
799
800 /**
801 * Insert a new empty page record for this article.
802 * This *must* be followed up by creating a revision
803 * and running $this->updateRevisionOn( ... );
804 * or else the record will be left in a funky state.
805 * Best if all done inside a transaction.
806 *
807 * @param $dbw DatabaseBase
808 * @return int The newly created page_id key, or false if the title already existed
809 */
810 public function insertOn( $dbw ) {
811 wfProfileIn( __METHOD__ );
812
813 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
814 $dbw->insert( 'page', array(
815 'page_id' => $page_id,
816 'page_namespace' => $this->mTitle->getNamespace(),
817 'page_title' => $this->mTitle->getDBkey(),
818 'page_counter' => 0,
819 'page_restrictions' => '',
820 'page_is_redirect' => 0, # Will set this shortly...
821 'page_is_new' => 1,
822 'page_random' => wfRandom(),
823 'page_touched' => $dbw->timestamp(),
824 'page_latest' => 0, # Fill this in shortly...
825 'page_len' => 0, # Fill this in shortly...
826 ), __METHOD__, 'IGNORE' );
827
828 $affected = $dbw->affectedRows();
829
830 if ( $affected ) {
831 $newid = $dbw->insertId();
832 $this->mTitle->resetArticleID( $newid );
833 }
834 wfProfileOut( __METHOD__ );
835
836 return $affected ? $newid : false;
837 }
838
839 /**
840 * Update the page record to point to a newly saved revision.
841 *
842 * @param $dbw DatabaseBase: object
843 * @param $revision Revision: For ID number, and text used to set
844 * length and redirect status fields
845 * @param $lastRevision Integer: if given, will not overwrite the page field
846 * when different from the currently set value.
847 * Giving 0 indicates the new page flag should be set
848 * on.
849 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
850 * removing rows in redirect table.
851 * @return bool true on success, false on failure
852 * @private
853 */
854 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
855 wfProfileIn( __METHOD__ );
856
857 $text = $revision->getText();
858 $len = strlen( $text );
859 $rt = Title::newFromRedirectRecurse( $text );
860
861 $conditions = array( 'page_id' => $this->getId() );
862
863 if ( !is_null( $lastRevision ) ) {
864 # An extra check against threads stepping on each other
865 $conditions['page_latest'] = $lastRevision;
866 }
867
868 $now = wfTimestampNow();
869 $dbw->update( 'page',
870 array( /* SET */
871 'page_latest' => $revision->getId(),
872 'page_touched' => $dbw->timestamp( $now ),
873 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
874 'page_is_redirect' => $rt !== null ? 1 : 0,
875 'page_len' => $len,
876 ),
877 $conditions,
878 __METHOD__ );
879
880 $result = $dbw->affectedRows() != 0;
881 if ( $result ) {
882 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
883 $this->setLastEdit( $revision );
884 $this->setCachedLastEditTime( $now );
885 $this->mLatest = $revision->getId();
886 $this->mIsRedirect = (bool)$rt;
887 # Update the LinkCache.
888 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect, $this->mLatest );
889 }
890
891 wfProfileOut( __METHOD__ );
892 return $result;
893 }
894
895 /**
896 * Get the cached timestamp for the last time the page changed.
897 * This is only used to help handle slave lag by comparing to page_touched.
898 * @return string MW timestamp
899 */
900 protected function getCachedLastEditTime() {
901 global $wgMemc;
902 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
903 return $wgMemc->get( $key );
904 }
905
906 /**
907 * Set the cached timestamp for the last time the page changed.
908 * This is only used to help handle slave lag by comparing to page_touched.
909 * @param $timestamp string
910 * @return void
911 */
912 public function setCachedLastEditTime( $timestamp ) {
913 global $wgMemc;
914 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
915 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60*15 );
916 }
917
918 /**
919 * Add row to the redirect table if this is a redirect, remove otherwise.
920 *
921 * @param $dbw DatabaseBase
922 * @param $redirectTitle Title object pointing to the redirect target,
923 * or NULL if this is not a redirect
924 * @param $lastRevIsRedirect If given, will optimize adding and
925 * removing rows in redirect table.
926 * @return bool true on success, false on failure
927 * @private
928 */
929 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
930 // Always update redirects (target link might have changed)
931 // Update/Insert if we don't know if the last revision was a redirect or not
932 // Delete if changing from redirect to non-redirect
933 $isRedirect = !is_null( $redirectTitle );
934
935 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
936 return true;
937 }
938
939 wfProfileIn( __METHOD__ );
940 if ( $isRedirect ) {
941 $this->insertRedirectEntry( $redirectTitle );
942 } else {
943 // This is not a redirect, remove row from redirect table
944 $where = array( 'rd_from' => $this->getId() );
945 $dbw->delete( 'redirect', $where, __METHOD__ );
946 }
947
948 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
949 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
950 }
951 wfProfileOut( __METHOD__ );
952
953 return ( $dbw->affectedRows() != 0 );
954 }
955
956 /**
957 * If the given revision is newer than the currently set page_latest,
958 * update the page record. Otherwise, do nothing.
959 *
960 * @param $dbw Database object
961 * @param $revision Revision object
962 * @return mixed
963 */
964 public function updateIfNewerOn( $dbw, $revision ) {
965 wfProfileIn( __METHOD__ );
966
967 $row = $dbw->selectRow(
968 array( 'revision', 'page' ),
969 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
970 array(
971 'page_id' => $this->getId(),
972 'page_latest=rev_id' ),
973 __METHOD__ );
974
975 if ( $row ) {
976 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
977 wfProfileOut( __METHOD__ );
978 return false;
979 }
980 $prev = $row->rev_id;
981 $lastRevIsRedirect = (bool)$row->page_is_redirect;
982 } else {
983 # No or missing previous revision; mark the page as new
984 $prev = 0;
985 $lastRevIsRedirect = null;
986 }
987
988 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
989
990 wfProfileOut( __METHOD__ );
991 return $ret;
992 }
993
994 /**
995 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
996 * @param $text String: new text of the section
997 * @param $summary String: new section's subject, only if $section is 'new'
998 * @param $edittime String: revision timestamp or null to use the current revision
999 * @return string Complete article text, or null if error
1000 */
1001 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1002 wfProfileIn( __METHOD__ );
1003
1004 if ( strval( $section ) == '' ) {
1005 // Whole-page edit; let the whole text through
1006 } else {
1007 if ( is_null( $edittime ) ) {
1008 $rev = Revision::newFromTitle( $this->mTitle );
1009 } else {
1010 $dbw = wfGetDB( DB_MASTER );
1011 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1012 }
1013
1014 if ( !$rev ) {
1015 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1016 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1017 wfProfileOut( __METHOD__ );
1018 return null;
1019 }
1020
1021 $oldtext = $rev->getText();
1022
1023 if ( $section == 'new' ) {
1024 # Inserting a new section
1025 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1026 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1027 $text = strlen( trim( $oldtext ) ) > 0
1028 ? "{$oldtext}\n\n{$subject}{$text}"
1029 : "{$subject}{$text}";
1030 }
1031 } else {
1032 # Replacing an existing section; roll out the big guns
1033 global $wgParser;
1034
1035 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1036 }
1037 }
1038
1039 wfProfileOut( __METHOD__ );
1040 return $text;
1041 }
1042
1043 /**
1044 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1045 * @param $flags Int
1046 * @return Int updated $flags
1047 */
1048 function checkFlags( $flags ) {
1049 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1050 if ( $this->mTitle->getArticleID() ) {
1051 $flags |= EDIT_UPDATE;
1052 } else {
1053 $flags |= EDIT_NEW;
1054 }
1055 }
1056
1057 return $flags;
1058 }
1059
1060 /**
1061 * Change an existing article or create a new article. Updates RC and all necessary caches,
1062 * optionally via the deferred update array.
1063 *
1064 * @param $text String: new text
1065 * @param $summary String: edit summary
1066 * @param $flags Integer bitfield:
1067 * EDIT_NEW
1068 * Article is known or assumed to be non-existent, create a new one
1069 * EDIT_UPDATE
1070 * Article is known or assumed to be pre-existing, update it
1071 * EDIT_MINOR
1072 * Mark this edit minor, if the user is allowed to do so
1073 * EDIT_SUPPRESS_RC
1074 * Do not log the change in recentchanges
1075 * EDIT_FORCE_BOT
1076 * Mark the edit a "bot" edit regardless of user rights
1077 * EDIT_DEFER_UPDATES
1078 * Defer some of the updates until the end of index.php
1079 * EDIT_AUTOSUMMARY
1080 * Fill in blank summaries with generated text where possible
1081 *
1082 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1083 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1084 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1085 * edit-already-exists error will be returned. These two conditions are also possible with
1086 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1087 *
1088 * @param $baseRevId the revision ID this edit was based off, if any
1089 * @param $user User the user doing the edit
1090 *
1091 * @return Status object. Possible errors:
1092 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1093 * edit-gone-missing: In update mode, but the article didn't exist
1094 * edit-conflict: In update mode, the article changed unexpectedly
1095 * edit-no-change: Warning that the text was the same as before
1096 * edit-already-exists: In creation mode, but the article already exists
1097 *
1098 * Extensions may define additional errors.
1099 *
1100 * $return->value will contain an associative array with members as follows:
1101 * new: Boolean indicating if the function attempted to create a new article
1102 * revision: The revision object for the inserted revision, or null
1103 *
1104 * Compatibility note: this function previously returned a boolean value indicating success/failure
1105 */
1106 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1107 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1108
1109 # Low-level sanity check
1110 if ( $this->mTitle->getText() === '' ) {
1111 throw new MWException( 'Something is trying to edit an article with an empty title' );
1112 }
1113
1114 wfProfileIn( __METHOD__ );
1115
1116 $user = is_null( $user ) ? $wgUser : $user;
1117 $status = Status::newGood( array() );
1118
1119 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1120 $this->loadPageData( 'fromdbmaster' );
1121
1122 $flags = $this->checkFlags( $flags );
1123
1124 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1125 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1126 {
1127 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1128
1129 if ( $status->isOK() ) {
1130 $status->fatal( 'edit-hook-aborted' );
1131 }
1132
1133 wfProfileOut( __METHOD__ );
1134 return $status;
1135 }
1136
1137 # Silently ignore EDIT_MINOR if not allowed
1138 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1139 $bot = $flags & EDIT_FORCE_BOT;
1140
1141 $oldtext = $this->getRawText(); // current revision
1142 $oldsize = strlen( $oldtext );
1143 $oldid = $this->getLatest();
1144 $oldIsRedirect = $this->isRedirect();
1145 $oldcountable = $this->isCountable();
1146
1147 # Provide autosummaries if one is not provided and autosummaries are enabled.
1148 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1149 $summary = self::getAutosummary( $oldtext, $text, $flags );
1150 }
1151
1152 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1153 $text = $editInfo->pst;
1154 $newsize = strlen( $text );
1155
1156 $dbw = wfGetDB( DB_MASTER );
1157 $now = wfTimestampNow();
1158 $this->mTimestamp = $now;
1159
1160 if ( $flags & EDIT_UPDATE ) {
1161 # Update article, but only if changed.
1162 $status->value['new'] = false;
1163
1164 # Make sure the revision is either completely inserted or not inserted at all
1165 if ( !$wgDBtransactions ) {
1166 $userAbort = ignore_user_abort( true );
1167 }
1168
1169 $revision = new Revision( array(
1170 'page' => $this->getId(),
1171 'comment' => $summary,
1172 'minor_edit' => $isminor,
1173 'text' => $text,
1174 'parent_id' => $oldid,
1175 'user' => $user->getId(),
1176 'user_text' => $user->getName(),
1177 'timestamp' => $now
1178 ) );
1179
1180 $changed = ( strcmp( $text, $oldtext ) != 0 );
1181
1182 if ( $changed ) {
1183 if ( !$this->mLatest ) {
1184 # Article gone missing
1185 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1186 $status->fatal( 'edit-gone-missing' );
1187
1188 wfProfileOut( __METHOD__ );
1189 return $status;
1190 }
1191
1192 $dbw->begin();
1193 $revisionId = $revision->insertOn( $dbw );
1194
1195 # Update page
1196 #
1197 # Note that we use $this->mLatest instead of fetching a value from the master DB
1198 # during the course of this function. This makes sure that EditPage can detect
1199 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1200 # before this function is called. A previous function used a separate query, this
1201 # creates a window where concurrent edits can cause an ignored edit conflict.
1202 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1203
1204 if ( !$ok ) {
1205 /* Belated edit conflict! Run away!! */
1206 $status->fatal( 'edit-conflict' );
1207
1208 # Delete the invalid revision if the DB is not transactional
1209 if ( !$wgDBtransactions ) {
1210 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1211 }
1212
1213 $revisionId = 0;
1214 $dbw->rollback();
1215 } else {
1216 global $wgUseRCPatrol;
1217 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1218 # Update recentchanges
1219 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1220 # Mark as patrolled if the user can do so
1221 $patrolled = $wgUseRCPatrol && !count(
1222 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1223 # Add RC row to the DB
1224 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1225 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1226 $revisionId, $patrolled
1227 );
1228
1229 # Log auto-patrolled edits
1230 if ( $patrolled ) {
1231 PatrolLog::record( $rc, true );
1232 }
1233 }
1234 $user->incEditCount();
1235 $dbw->commit();
1236 }
1237 }
1238
1239 if ( !$wgDBtransactions ) {
1240 ignore_user_abort( $userAbort );
1241 }
1242
1243 // Now that ignore_user_abort is restored, we can respond to fatal errors
1244 if ( !$status->isOK() ) {
1245 wfProfileOut( __METHOD__ );
1246 return $status;
1247 }
1248
1249 # Update links tables, site stats, etc.
1250 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1251 'oldcountable' => $oldcountable ) );
1252
1253 if ( !$changed ) {
1254 $status->warning( 'edit-no-change' );
1255 $revision = null;
1256 // Keep the same revision ID, but do some updates on it
1257 $revisionId = $this->getLatest();
1258 // Update page_touched, this is usually implicit in the page update
1259 // Other cache updates are done in onArticleEdit()
1260 $this->mTitle->invalidateCache();
1261 }
1262 } else {
1263 # Create new article
1264 $status->value['new'] = true;
1265
1266 $dbw->begin();
1267
1268 # Add the page record; stake our claim on this title!
1269 # This will return false if the article already exists
1270 $newid = $this->insertOn( $dbw );
1271
1272 if ( $newid === false ) {
1273 $dbw->rollback();
1274 $status->fatal( 'edit-already-exists' );
1275
1276 wfProfileOut( __METHOD__ );
1277 return $status;
1278 }
1279
1280 # Save the revision text...
1281 $revision = new Revision( array(
1282 'page' => $newid,
1283 'comment' => $summary,
1284 'minor_edit' => $isminor,
1285 'text' => $text,
1286 'user' => $user->getId(),
1287 'user_text' => $user->getName(),
1288 'timestamp' => $now
1289 ) );
1290 $revisionId = $revision->insertOn( $dbw );
1291
1292 # Update the page record with revision data
1293 $this->updateRevisionOn( $dbw, $revision, 0 );
1294
1295 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1296
1297 # Update recentchanges
1298 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1299 global $wgUseRCPatrol, $wgUseNPPatrol;
1300
1301 # Mark as patrolled if the user can do so
1302 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1303 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1304 # Add RC row to the DB
1305 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1306 '', strlen( $text ), $revisionId, $patrolled );
1307
1308 # Log auto-patrolled edits
1309 if ( $patrolled ) {
1310 PatrolLog::record( $rc, true );
1311 }
1312 }
1313 $user->incEditCount();
1314 $dbw->commit();
1315
1316 # Update links, etc.
1317 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1318
1319 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1320 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1321 }
1322
1323 # Do updates right now unless deferral was requested
1324 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1325 DeferredUpdates::doUpdates();
1326 }
1327
1328 // Return the new revision (or null) to the caller
1329 $status->value['revision'] = $revision;
1330
1331 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1332 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1333
1334 # Promote user to any groups they meet the criteria for
1335 $user->addAutopromoteOnceGroups( 'onEdit' );
1336
1337 wfProfileOut( __METHOD__ );
1338 return $status;
1339 }
1340
1341 /**
1342 * Update the article's restriction field, and leave a log entry.
1343 *
1344 * @todo: seperate the business/permission stuff out from backend code
1345 *
1346 * @param $limit Array: set of restriction keys
1347 * @param $reason String
1348 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1349 * @param $expiry Array: per restriction type expiration
1350 * @param $user User The user updating the restrictions
1351 * @return bool true on success
1352 */
1353 public function updateRestrictions(
1354 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
1355 ) {
1356 global $wgUser, $wgContLang;
1357 $user = is_null( $user ) ? $wgUser : $user;
1358
1359 $restrictionTypes = $this->mTitle->getRestrictionTypes();
1360
1361 $id = $this->mTitle->getArticleID();
1362
1363 if ( $id <= 0 ) {
1364 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1365 return false;
1366 }
1367
1368 if ( wfReadOnly() ) {
1369 wfDebug( "updateRestrictions failed: read-only\n" );
1370 return false;
1371 }
1372
1373 if ( count( $this->mTitle->getUserPermissionsErrors( 'protect', $user ) ) ) {
1374 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1375 return false;
1376 }
1377
1378 if ( !$cascade ) {
1379 $cascade = false;
1380 }
1381
1382 // Take this opportunity to purge out expired restrictions
1383 Title::purgeExpiredRestrictions();
1384
1385 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1386 # we expect a single selection, but the schema allows otherwise.
1387 $current = array();
1388 $updated = self::flattenRestrictions( $limit );
1389 $changed = false;
1390
1391 foreach ( $restrictionTypes as $action ) {
1392 if ( isset( $expiry[$action] ) ) {
1393 # Get current restrictions on $action
1394 $aLimits = $this->mTitle->getRestrictions( $action );
1395 $current[$action] = implode( '', $aLimits );
1396 # Are any actual restrictions being dealt with here?
1397 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
1398
1399 # If something changed, we need to log it. Checking $aRChanged
1400 # assures that "unprotecting" a page that is not protected does
1401 # not log just because the expiry was "changed".
1402 if ( $aRChanged &&
1403 $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] )
1404 {
1405 $changed = true;
1406 }
1407 }
1408 }
1409
1410 $current = self::flattenRestrictions( $current );
1411
1412 $changed = ( $changed || $current != $updated );
1413 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
1414 $protect = ( $updated != '' );
1415
1416 # If nothing's changed, do nothing
1417 if ( $changed ) {
1418 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1419 $dbw = wfGetDB( DB_MASTER );
1420
1421 # Prepare a null revision to be added to the history
1422 $modified = $current != '' && $protect;
1423
1424 if ( $protect ) {
1425 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1426 } else {
1427 $comment_type = 'unprotectedarticle';
1428 }
1429
1430 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1431
1432 # Only restrictions with the 'protect' right can cascade...
1433 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1434 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1435
1436 # The schema allows multiple restrictions
1437 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1438 $cascade = false;
1439 }
1440
1441 $cascade_description = '';
1442
1443 if ( $cascade ) {
1444 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1445 }
1446
1447 if ( $reason ) {
1448 $comment .= ": $reason";
1449 }
1450
1451 $editComment = $comment;
1452 $encodedExpiry = array();
1453 $protect_description = '';
1454 foreach ( $limit as $action => $restrictions ) {
1455 if ( !isset( $expiry[$action] ) )
1456 $expiry[$action] = $dbw->getInfinity();
1457
1458 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1459 if ( $restrictions != '' ) {
1460 $protect_description .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1461 if ( $encodedExpiry[$action] != 'infinity' ) {
1462 $protect_description .= wfMsgForContent( 'protect-expiring',
1463 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1464 $wgContLang->date( $expiry[$action], false, false ) ,
1465 $wgContLang->time( $expiry[$action], false, false ) );
1466 } else {
1467 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1468 }
1469
1470 $protect_description .= ') ';
1471 }
1472 }
1473 $protect_description = trim( $protect_description );
1474
1475 if ( $protect_description && $protect ) {
1476 $editComment .= " ($protect_description)";
1477 }
1478
1479 if ( $cascade ) {
1480 $editComment .= "$cascade_description";
1481 }
1482
1483 # Update restrictions table
1484 foreach ( $limit as $action => $restrictions ) {
1485 if ( $restrictions != '' ) {
1486 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1487 array( 'pr_page' => $id,
1488 'pr_type' => $action,
1489 'pr_level' => $restrictions,
1490 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
1491 'pr_expiry' => $encodedExpiry[$action]
1492 ),
1493 __METHOD__
1494 );
1495 } else {
1496 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1497 'pr_type' => $action ), __METHOD__ );
1498 }
1499 }
1500
1501 # Insert a null revision
1502 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1503 $nullRevId = $nullRevision->insertOn( $dbw );
1504
1505 $latest = $this->getLatest();
1506 # Update page record
1507 $dbw->update( 'page',
1508 array( /* SET */
1509 'page_touched' => $dbw->timestamp(),
1510 'page_restrictions' => '',
1511 'page_latest' => $nullRevId
1512 ), array( /* WHERE */
1513 'page_id' => $id
1514 ), __METHOD__
1515 );
1516
1517 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1518 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1519
1520 # Update the protection log
1521 $log = new LogPage( 'protect' );
1522 if ( $protect ) {
1523 $params = array( $protect_description, $cascade ? 'cascade' : '' );
1524 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
1525 } else {
1526 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1527 }
1528 } # End hook
1529 } # End "changed" check
1530
1531 return true;
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->getId() ) {
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 $id = $this->getId();
2104 $title = $this->mTitle->getPrefixedDBkey();
2105 $shortTitle = $this->mTitle->getDBkey();
2106
2107 if ( 0 == $id ) {
2108 wfProfileOut( __METHOD__ );
2109 return;
2110 }
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 global $wgUser;
2177 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2178 }
2179
2180 /**
2181 * This function is called right before saving the wikitext,
2182 * so we can do things like signatures and links-in-context.
2183 *
2184 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2185 * @param $text String article contents
2186 * @param $user User object: user doing the edit
2187 * @param $popts ParserOptions object: parser options, default options for
2188 * the user loaded if null given
2189 * @return string article contents with altered wikitext markup (signatures
2190 * converted, {{subst:}}, templates, etc.)
2191 */
2192 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
2193 global $wgParser, $wgUser;
2194
2195 wfDeprecated( __METHOD__ );
2196
2197 $user = is_null( $user ) ? $wgUser : $user;
2198
2199 if ( $popts === null ) {
2200 $popts = ParserOptions::newFromUser( $user );
2201 }
2202
2203 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2204 }
2205
2206 /**
2207 * Loads page_touched and returns a value indicating if it should be used
2208 * @return boolean true if not a redirect
2209 */
2210 public function checkTouched() {
2211 if ( !$this->mDataLoaded ) {
2212 $this->loadPageData();
2213 }
2214 return !$this->mIsRedirect;
2215 }
2216
2217 /**
2218 * Get the page_touched field
2219 * @return string containing GMT timestamp
2220 */
2221 public function getTouched() {
2222 if ( !$this->mDataLoaded ) {
2223 $this->loadPageData();
2224 }
2225 return $this->mTouched;
2226 }
2227
2228 /**
2229 * Get the page_latest field
2230 * @return integer rev_id of current revision
2231 */
2232 public function getLatest() {
2233 if ( !$this->mDataLoaded ) {
2234 $this->loadPageData();
2235 }
2236 return (int)$this->mLatest;
2237 }
2238
2239 /**
2240 * Edit an article without doing all that other stuff
2241 * The article must already exist; link tables etc
2242 * are not updated, caches are not flushed.
2243 *
2244 * @param $text String: text submitted
2245 * @param $user User The relevant user
2246 * @param $comment String: comment submitted
2247 * @param $minor Boolean: whereas it's a minor modification
2248 */
2249 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2250 wfProfileIn( __METHOD__ );
2251
2252 $dbw = wfGetDB( DB_MASTER );
2253 $revision = new Revision( array(
2254 'page' => $this->getId(),
2255 'text' => $text,
2256 'comment' => $comment,
2257 'minor_edit' => $minor ? 1 : 0,
2258 ) );
2259 $revision->insertOn( $dbw );
2260 $this->updateRevisionOn( $dbw, $revision );
2261
2262 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2263
2264 wfProfileOut( __METHOD__ );
2265 }
2266
2267 /**
2268 * The onArticle*() functions are supposed to be a kind of hooks
2269 * which should be called whenever any of the specified actions
2270 * are done.
2271 *
2272 * This is a good place to put code to clear caches, for instance.
2273 *
2274 * This is called on page move and undelete, as well as edit
2275 *
2276 * @param $title Title object
2277 */
2278 public static function onArticleCreate( $title ) {
2279 # Update existence markers on article/talk tabs...
2280 if ( $title->isTalkPage() ) {
2281 $other = $title->getSubjectPage();
2282 } else {
2283 $other = $title->getTalkPage();
2284 }
2285
2286 $other->invalidateCache();
2287 $other->purgeSquid();
2288
2289 $title->touchLinks();
2290 $title->purgeSquid();
2291 $title->deleteTitleProtection();
2292 }
2293
2294 /**
2295 * Clears caches when article is deleted
2296 *
2297 * @param $title Title
2298 */
2299 public static function onArticleDelete( $title ) {
2300 # Update existence markers on article/talk tabs...
2301 if ( $title->isTalkPage() ) {
2302 $other = $title->getSubjectPage();
2303 } else {
2304 $other = $title->getTalkPage();
2305 }
2306
2307 $other->invalidateCache();
2308 $other->purgeSquid();
2309
2310 $title->touchLinks();
2311 $title->purgeSquid();
2312
2313 # File cache
2314 HTMLFileCache::clearFileCache( $title );
2315
2316 # Messages
2317 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2318 MessageCache::singleton()->replace( $title->getDBkey(), false );
2319 }
2320
2321 # Images
2322 if ( $title->getNamespace() == NS_FILE ) {
2323 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2324 $update->doUpdate();
2325 }
2326
2327 # User talk pages
2328 if ( $title->getNamespace() == NS_USER_TALK ) {
2329 $user = User::newFromName( $title->getText(), false );
2330 if ( $user ) {
2331 $user->setNewtalk( false );
2332 }
2333 }
2334
2335 # Image redirects
2336 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2337 }
2338
2339 /**
2340 * Purge caches on page update etc
2341 *
2342 * @param $title Title object
2343 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2344 */
2345 public static function onArticleEdit( $title ) {
2346 // Invalidate caches of articles which include this page
2347 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2348
2349
2350 // Invalidate the caches of all pages which redirect here
2351 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2352
2353 # Purge squid for this page only
2354 $title->purgeSquid();
2355
2356 # Clear file cache for this page only
2357 HTMLFileCache::clearFileCache( $title );
2358 }
2359
2360 /**#@-*/
2361
2362 /**
2363 * Return a list of templates used by this article.
2364 * Uses the templatelinks table
2365 *
2366 * @return Array of Title objects
2367 */
2368 public function getUsedTemplates() {
2369 $result = array();
2370 $id = $this->mTitle->getArticleID();
2371
2372 if ( $id == 0 ) {
2373 return array();
2374 }
2375
2376 $dbr = wfGetDB( DB_SLAVE );
2377 $res = $dbr->select( array( 'templatelinks' ),
2378 array( 'tl_namespace', 'tl_title' ),
2379 array( 'tl_from' => $id ),
2380 __METHOD__ );
2381
2382 if ( $res !== false ) {
2383 foreach ( $res as $row ) {
2384 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2385 }
2386 }
2387
2388 return $result;
2389 }
2390
2391 /**
2392 * Returns a list of hidden categories this page is a member of.
2393 * Uses the page_props and categorylinks tables.
2394 *
2395 * @return Array of Title objects
2396 */
2397 public function getHiddenCategories() {
2398 $result = array();
2399 $id = $this->mTitle->getArticleID();
2400
2401 if ( $id == 0 ) {
2402 return array();
2403 }
2404
2405 $dbr = wfGetDB( DB_SLAVE );
2406 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2407 array( 'cl_to' ),
2408 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2409 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2410 __METHOD__ );
2411
2412 if ( $res !== false ) {
2413 foreach ( $res as $row ) {
2414 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2415 }
2416 }
2417
2418 return $result;
2419 }
2420
2421 /**
2422 * Return an applicable autosummary if one exists for the given edit.
2423 * @param $oldtext String: the previous text of the page.
2424 * @param $newtext String: The submitted text of the page.
2425 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2426 * @return string An appropriate autosummary, or an empty string.
2427 */
2428 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2429 global $wgContLang;
2430
2431 # Decide what kind of autosummary is needed.
2432
2433 # Redirect autosummaries
2434 $ot = Title::newFromRedirect( $oldtext );
2435 $rt = Title::newFromRedirect( $newtext );
2436
2437 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
2438 $truncatedtext = $wgContLang->truncate(
2439 str_replace( "\n", ' ', $newtext ),
2440 max( 0, 250
2441 - strlen( wfMsgForContent( 'autoredircomment' ) )
2442 - strlen( $rt->getFullText() )
2443 ) );
2444 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2445 }
2446
2447 # New page autosummaries
2448 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
2449 # If they're making a new article, give its text, truncated, in the summary.
2450
2451 $truncatedtext = $wgContLang->truncate(
2452 str_replace( "\n", ' ', $newtext ),
2453 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2454
2455 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2456 }
2457
2458 # Blanking autosummaries
2459 if ( $oldtext != '' && $newtext == '' ) {
2460 return wfMsgForContent( 'autosumm-blank' );
2461 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2462 # Removing more than 90% of the article
2463
2464 $truncatedtext = $wgContLang->truncate(
2465 $newtext,
2466 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2467
2468 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2469 }
2470
2471 # If we reach this point, there's no applicable autosummary for our case, so our
2472 # autosummary is empty.
2473 return '';
2474 }
2475
2476 /**
2477 * Auto-generates a deletion reason
2478 *
2479 * @param &$hasHistory Boolean: whether the page has a history
2480 * @return mixed String containing deletion reason or empty string, or boolean false
2481 * if no revision occurred
2482 */
2483 public function getAutoDeleteReason( &$hasHistory ) {
2484 global $wgContLang;
2485
2486 $dbw = wfGetDB( DB_MASTER );
2487 // Get the last revision
2488 $rev = Revision::newFromTitle( $this->getTitle() );
2489
2490 if ( is_null( $rev ) ) {
2491 return false;
2492 }
2493
2494 // Get the article's contents
2495 $contents = $rev->getText();
2496 $blank = false;
2497
2498 // If the page is blank, use the text from the previous revision,
2499 // which can only be blank if there's a move/import/protect dummy revision involved
2500 if ( $contents == '' ) {
2501 $prev = $rev->getPrevious();
2502
2503 if ( $prev ) {
2504 $contents = $prev->getText();
2505 $blank = true;
2506 }
2507 }
2508
2509 // Find out if there was only one contributor
2510 // Only scan the last 20 revisions
2511 $res = $dbw->select( 'revision', 'rev_user_text',
2512 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2513 __METHOD__,
2514 array( 'LIMIT' => 20 )
2515 );
2516
2517 if ( $res === false ) {
2518 // This page has no revisions, which is very weird
2519 return false;
2520 }
2521
2522 $hasHistory = ( $res->numRows() > 1 );
2523 $row = $dbw->fetchObject( $res );
2524
2525 if ( $row ) { // $row is false if the only contributor is hidden
2526 $onlyAuthor = $row->rev_user_text;
2527 // Try to find a second contributor
2528 foreach ( $res as $row ) {
2529 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2530 $onlyAuthor = false;
2531 break;
2532 }
2533 }
2534 } else {
2535 $onlyAuthor = false;
2536 }
2537
2538 // Generate the summary with a '$1' placeholder
2539 if ( $blank ) {
2540 // The current revision is blank and the one before is also
2541 // blank. It's just not our lucky day
2542 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2543 } else {
2544 if ( $onlyAuthor ) {
2545 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2546 } else {
2547 $reason = wfMsgForContent( 'excontent', '$1' );
2548 }
2549 }
2550
2551 if ( $reason == '-' ) {
2552 // Allow these UI messages to be blanked out cleanly
2553 return '';
2554 }
2555
2556 // Replace newlines with spaces to prevent uglyness
2557 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2558 // Calculate the maximum amount of chars to get
2559 // Max content length = max comment length - length of the comment (excl. $1)
2560 $maxLength = 255 - ( strlen( $reason ) - 2 );
2561 $contents = $wgContLang->truncate( $contents, $maxLength );
2562 // Remove possible unfinished links
2563 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2564 // Now replace the '$1' placeholder
2565 $reason = str_replace( '$1', $contents, $reason );
2566
2567 return $reason;
2568 }
2569
2570 /**
2571 * Get parser options suitable for rendering the primary article wikitext
2572 * @param User|string $user User object or 'canonical'
2573 * @return ParserOptions
2574 */
2575 public function makeParserOptions( $user ) {
2576 global $wgContLang;
2577 if ( $user instanceof User ) { // settings per user (even anons)
2578 $options = ParserOptions::newFromUser( $user );
2579 } else { // canonical settings
2580 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
2581 }
2582 $options->enableLimitReport(); // show inclusion/loop reports
2583 $options->setTidy( true ); // fix bad HTML
2584 return $options;
2585 }
2586
2587 /**
2588 * Update all the appropriate counts in the category table, given that
2589 * we've added the categories $added and deleted the categories $deleted.
2590 *
2591 * @param $added array The names of categories that were added
2592 * @param $deleted array The names of categories that were deleted
2593 */
2594 public function updateCategoryCounts( $added, $deleted ) {
2595 $ns = $this->mTitle->getNamespace();
2596 $dbw = wfGetDB( DB_MASTER );
2597
2598 # First make sure the rows exist. If one of the "deleted" ones didn't
2599 # exist, we might legitimately not create it, but it's simpler to just
2600 # create it and then give it a negative value, since the value is bogus
2601 # anyway.
2602 #
2603 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2604 $insertCats = array_merge( $added, $deleted );
2605 if ( !$insertCats ) {
2606 # Okay, nothing to do
2607 return;
2608 }
2609
2610 $insertRows = array();
2611
2612 foreach ( $insertCats as $cat ) {
2613 $insertRows[] = array(
2614 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2615 'cat_title' => $cat
2616 );
2617 }
2618 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2619
2620 $addFields = array( 'cat_pages = cat_pages + 1' );
2621 $removeFields = array( 'cat_pages = cat_pages - 1' );
2622
2623 if ( $ns == NS_CATEGORY ) {
2624 $addFields[] = 'cat_subcats = cat_subcats + 1';
2625 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2626 } elseif ( $ns == NS_FILE ) {
2627 $addFields[] = 'cat_files = cat_files + 1';
2628 $removeFields[] = 'cat_files = cat_files - 1';
2629 }
2630
2631 if ( $added ) {
2632 $dbw->update(
2633 'category',
2634 $addFields,
2635 array( 'cat_title' => $added ),
2636 __METHOD__
2637 );
2638 }
2639
2640 if ( $deleted ) {
2641 $dbw->update(
2642 'category',
2643 $removeFields,
2644 array( 'cat_title' => $deleted ),
2645 __METHOD__
2646 );
2647 }
2648 }
2649
2650 /**
2651 * Updates cascading protections
2652 *
2653 * @param $parserOutput ParserOutput object for the current version
2654 */
2655 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
2656 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
2657 return;
2658 }
2659
2660 // templatelinks table may have become out of sync,
2661 // especially if using variable-based transclusions.
2662 // For paranoia, check if things have changed and if
2663 // so apply updates to the database. This will ensure
2664 // that cascaded protections apply as soon as the changes
2665 // are visible.
2666
2667 # Get templates from templatelinks
2668 $id = $this->mTitle->getArticleID();
2669
2670 $tlTemplates = array();
2671
2672 $dbr = wfGetDB( DB_SLAVE );
2673 $res = $dbr->select( array( 'templatelinks' ),
2674 array( 'tl_namespace', 'tl_title' ),
2675 array( 'tl_from' => $id ),
2676 __METHOD__
2677 );
2678
2679 foreach ( $res as $row ) {
2680 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2681 }
2682
2683 # Get templates from parser output.
2684 $poTemplates = array();
2685 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2686 foreach ( $templates as $dbk => $id ) {
2687 $poTemplates["$ns:$dbk"] = true;
2688 }
2689 }
2690
2691 # Get the diff
2692 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2693
2694 if ( count( $templates_diff ) > 0 ) {
2695 # Whee, link updates time.
2696 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
2697 $u->doUpdate();
2698 }
2699 }
2700
2701 /**
2702 * @deprecated since 1.18
2703 */
2704 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2705 global $wgUser;
2706 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2707 }
2708
2709 /**
2710 * @deprecated since 1.18
2711 */
2712 public function viewUpdates() {
2713 global $wgUser;
2714 return $this->doViewUpdates( $wgUser );
2715 }
2716
2717 /**
2718 * @deprecated since 1.18
2719 */
2720 public function useParserCache( $oldid ) {
2721 global $wgUser;
2722 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
2723 }
2724 }
2725
2726 class PoolWorkArticleView extends PoolCounterWork {
2727
2728 /**
2729 * @var Page
2730 */
2731 private $page;
2732
2733 /**
2734 * @var string
2735 */
2736 private $cacheKey;
2737
2738 /**
2739 * @var integer
2740 */
2741 private $revid;
2742
2743 /**
2744 * @var ParserOptions
2745 */
2746 private $parserOptions;
2747
2748 /**
2749 * @var string|null
2750 */
2751 private $text;
2752
2753 /**
2754 * @var ParserOutput|false
2755 */
2756 private $parserOutput = false;
2757
2758 /**
2759 * @var bool
2760 */
2761 private $isDirty = false;
2762
2763 /**
2764 * @var Status|false
2765 */
2766 private $error = false;
2767
2768 /**
2769 * Constructor
2770 *
2771 * @param $page Page
2772 * @param $revid Integer: ID of the revision being parsed
2773 * @param $useParserCache Boolean: whether to use the parser cache
2774 * @param $parserOptions parserOptions to use for the parse operation
2775 * @param $text String: text to parse or null to load it
2776 */
2777 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $text = null ) {
2778 $this->page = $page;
2779 $this->revid = $revid;
2780 $this->cacheable = $useParserCache;
2781 $this->parserOptions = $parserOptions;
2782 $this->text = $text;
2783 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
2784 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
2785 }
2786
2787 /**
2788 * Get the ParserOutput from this object, or false in case of failure
2789 *
2790 * @return ParserOutput
2791 */
2792 public function getParserOutput() {
2793 return $this->parserOutput;
2794 }
2795
2796 /**
2797 * Get whether the ParserOutput is a dirty one (i.e. expired)
2798 *
2799 * @return bool
2800 */
2801 public function getIsDirty() {
2802 return $this->isDirty;
2803 }
2804
2805 /**
2806 * Get a Status object in case of error or false otherwise
2807 *
2808 * @return Status|false
2809 */
2810 public function getError() {
2811 return $this->error;
2812 }
2813
2814 /**
2815 * @return bool
2816 */
2817 function doWork() {
2818 global $wgParser, $wgUseFileCache;
2819
2820 $isCurrent = $this->revid === $this->page->getLatest();
2821
2822 if ( $this->text !== null ) {
2823 $text = $this->text;
2824 } elseif ( $isCurrent ) {
2825 $text = $this->page->getRawText();
2826 } else {
2827 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
2828 if ( $rev === null ) {
2829 return false;
2830 }
2831 $text = $rev->getText();
2832 }
2833
2834 $time = - wfTime();
2835 $this->parserOutput = $wgParser->parse( $text, $this->page->getTitle(),
2836 $this->parserOptions, true, true, $this->revid );
2837 $time += wfTime();
2838
2839 # Timing hack
2840 if ( $time > 3 ) {
2841 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2842 $this->page->getTitle()->getPrefixedDBkey() ) );
2843 }
2844
2845 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
2846 ParserCache::singleton()->save( $this->parserOutput, $this->page, $this->parserOptions );
2847 }
2848
2849 // Make sure file cache is not used on uncacheable content.
2850 // Output that has magic words in it can still use the parser cache
2851 // (if enabled), though it will generally expire sooner.
2852 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
2853 $wgUseFileCache = false;
2854 }
2855
2856 if ( $isCurrent ) {
2857 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
2858 }
2859
2860 return true;
2861 }
2862
2863 /**
2864 * @return bool
2865 */
2866 function getCachedWork() {
2867 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
2868
2869 if ( $this->parserOutput === false ) {
2870 wfDebug( __METHOD__ . ": parser cache miss\n" );
2871 return false;
2872 } else {
2873 wfDebug( __METHOD__ . ": parser cache hit\n" );
2874 return true;
2875 }
2876 }
2877
2878 /**
2879 * @return bool
2880 */
2881 function fallback() {
2882 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
2883
2884 if ( $this->parserOutput === false ) {
2885 wfDebugLog( 'dirty', "dirty missing\n" );
2886 wfDebug( __METHOD__ . ": no dirty cache\n" );
2887 return false;
2888 } else {
2889 wfDebug( __METHOD__ . ": sending dirty output\n" );
2890 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2891 $this->isDirty = true;
2892 return true;
2893 }
2894 }
2895
2896 /**
2897 * @param $status Status
2898 */
2899 function error( $status ) {
2900 $this->error = $status;
2901 return false;
2902 }
2903 }