Bug 32238 - phaseout wgEnableTooltipsAndAccesskeys
[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 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 global $wgParser;
737
738 wfProfileIn( __METHOD__ );
739
740 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
741 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
742 if ( $parserOptions->getStubThreshold() ) {
743 wfIncrStats( 'pcache_miss_stub' );
744 }
745
746 if ( $useParserCache ) {
747 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
748 if ( $parserOutput !== false ) {
749 wfProfileOut( __METHOD__ );
750 return $parserOutput;
751 }
752 }
753
754 if ( $oldid === null || $oldid === 0 ) {
755 $oldid = $this->getLatest();
756 }
757
758 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
759 $pool->execute();
760
761 wfProfileOut( __METHOD__ );
762
763 return $pool->getParserOutput();
764 }
765
766 /**
767 * Perform the actions of a page purging
768 */
769 public function doPurge() {
770 global $wgUseSquid;
771
772 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
773 return false;
774 }
775
776 // Invalidate the cache
777 $this->mTitle->invalidateCache();
778 $this->clear();
779
780 if ( $wgUseSquid ) {
781 // Commit the transaction before the purge is sent
782 $dbw = wfGetDB( DB_MASTER );
783 $dbw->commit();
784
785 // Send purge
786 $update = SquidUpdate::newSimplePurge( $this->mTitle );
787 $update->doUpdate();
788 }
789
790 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
791 if ( $this->getId() == 0 ) {
792 $text = false;
793 } else {
794 $text = $this->getRawText();
795 }
796
797 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
798 }
799 return true;
800 }
801
802 /**
803 * Insert a new empty page record for this article.
804 * This *must* be followed up by creating a revision
805 * and running $this->updateRevisionOn( ... );
806 * or else the record will be left in a funky state.
807 * Best if all done inside a transaction.
808 *
809 * @param $dbw DatabaseBase
810 * @return int The newly created page_id key, or false if the title already existed
811 */
812 public function insertOn( $dbw ) {
813 wfProfileIn( __METHOD__ );
814
815 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
816 $dbw->insert( 'page', array(
817 'page_id' => $page_id,
818 'page_namespace' => $this->mTitle->getNamespace(),
819 'page_title' => $this->mTitle->getDBkey(),
820 'page_counter' => 0,
821 'page_restrictions' => '',
822 'page_is_redirect' => 0, # Will set this shortly...
823 'page_is_new' => 1,
824 'page_random' => wfRandom(),
825 'page_touched' => $dbw->timestamp(),
826 'page_latest' => 0, # Fill this in shortly...
827 'page_len' => 0, # Fill this in shortly...
828 ), __METHOD__, 'IGNORE' );
829
830 $affected = $dbw->affectedRows();
831
832 if ( $affected ) {
833 $newid = $dbw->insertId();
834 $this->mTitle->resetArticleID( $newid );
835 }
836 wfProfileOut( __METHOD__ );
837
838 return $affected ? $newid : false;
839 }
840
841 /**
842 * Update the page record to point to a newly saved revision.
843 *
844 * @param $dbw DatabaseBase: object
845 * @param $revision Revision: For ID number, and text used to set
846 * length and redirect status fields
847 * @param $lastRevision Integer: if given, will not overwrite the page field
848 * when different from the currently set value.
849 * Giving 0 indicates the new page flag should be set
850 * on.
851 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
852 * removing rows in redirect table.
853 * @return bool true on success, false on failure
854 * @private
855 */
856 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
857 wfProfileIn( __METHOD__ );
858
859 $text = $revision->getText();
860 $len = strlen( $text );
861 $rt = Title::newFromRedirectRecurse( $text );
862
863 $conditions = array( 'page_id' => $this->getId() );
864
865 if ( !is_null( $lastRevision ) ) {
866 # An extra check against threads stepping on each other
867 $conditions['page_latest'] = $lastRevision;
868 }
869
870 $now = wfTimestampNow();
871 $dbw->update( 'page',
872 array( /* SET */
873 'page_latest' => $revision->getId(),
874 'page_touched' => $dbw->timestamp( $now ),
875 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
876 'page_is_redirect' => $rt !== null ? 1 : 0,
877 'page_len' => $len,
878 ),
879 $conditions,
880 __METHOD__ );
881
882 $result = $dbw->affectedRows() != 0;
883 if ( $result ) {
884 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
885 $this->setLastEdit( $revision );
886 $this->setCachedLastEditTime( $now );
887 $this->mLatest = $revision->getId();
888 $this->mIsRedirect = (bool)$rt;
889 # Update the LinkCache.
890 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect, $this->mLatest );
891 }
892
893 wfProfileOut( __METHOD__ );
894 return $result;
895 }
896
897 /**
898 * Get the cached timestamp for the last time the page changed.
899 * This is only used to help handle slave lag by comparing to page_touched.
900 * @return string MW timestamp
901 */
902 protected function getCachedLastEditTime() {
903 global $wgMemc;
904 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
905 return $wgMemc->get( $key );
906 }
907
908 /**
909 * Set the cached timestamp for the last time the page changed.
910 * This is only used to help handle slave lag by comparing to page_touched.
911 * @param $timestamp string
912 * @return void
913 */
914 public function setCachedLastEditTime( $timestamp ) {
915 global $wgMemc;
916 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
917 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60*15 );
918 }
919
920 /**
921 * Add row to the redirect table if this is a redirect, remove otherwise.
922 *
923 * @param $dbw DatabaseBase
924 * @param $redirectTitle Title object pointing to the redirect target,
925 * or NULL if this is not a redirect
926 * @param $lastRevIsRedirect If given, will optimize adding and
927 * removing rows in redirect table.
928 * @return bool true on success, false on failure
929 * @private
930 */
931 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
932 // Always update redirects (target link might have changed)
933 // Update/Insert if we don't know if the last revision was a redirect or not
934 // Delete if changing from redirect to non-redirect
935 $isRedirect = !is_null( $redirectTitle );
936
937 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
938 return true;
939 }
940
941 wfProfileIn( __METHOD__ );
942 if ( $isRedirect ) {
943 $this->insertRedirectEntry( $redirectTitle );
944 } else {
945 // This is not a redirect, remove row from redirect table
946 $where = array( 'rd_from' => $this->getId() );
947 $dbw->delete( 'redirect', $where, __METHOD__ );
948 }
949
950 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
951 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
952 }
953 wfProfileOut( __METHOD__ );
954
955 return ( $dbw->affectedRows() != 0 );
956 }
957
958 /**
959 * If the given revision is newer than the currently set page_latest,
960 * update the page record. Otherwise, do nothing.
961 *
962 * @param $dbw Database object
963 * @param $revision Revision object
964 * @return mixed
965 */
966 public function updateIfNewerOn( $dbw, $revision ) {
967 wfProfileIn( __METHOD__ );
968
969 $row = $dbw->selectRow(
970 array( 'revision', 'page' ),
971 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
972 array(
973 'page_id' => $this->getId(),
974 'page_latest=rev_id' ),
975 __METHOD__ );
976
977 if ( $row ) {
978 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
979 wfProfileOut( __METHOD__ );
980 return false;
981 }
982 $prev = $row->rev_id;
983 $lastRevIsRedirect = (bool)$row->page_is_redirect;
984 } else {
985 # No or missing previous revision; mark the page as new
986 $prev = 0;
987 $lastRevIsRedirect = null;
988 }
989
990 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
991
992 wfProfileOut( __METHOD__ );
993 return $ret;
994 }
995
996 /**
997 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
998 * @param $text String: new text of the section
999 * @param $summary String: new section's subject, only if $section is 'new'
1000 * @param $edittime String: revision timestamp or null to use the current revision
1001 * @return string Complete article text, or null if error
1002 */
1003 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1004 wfProfileIn( __METHOD__ );
1005
1006 if ( strval( $section ) == '' ) {
1007 // Whole-page edit; let the whole text through
1008 } else {
1009 if ( is_null( $edittime ) ) {
1010 $rev = Revision::newFromTitle( $this->mTitle );
1011 } else {
1012 $dbw = wfGetDB( DB_MASTER );
1013 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1014 }
1015
1016 if ( !$rev ) {
1017 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1018 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1019 wfProfileOut( __METHOD__ );
1020 return null;
1021 }
1022
1023 $oldtext = $rev->getText();
1024
1025 if ( $section == 'new' ) {
1026 # Inserting a new section
1027 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1028 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1029 $text = strlen( trim( $oldtext ) ) > 0
1030 ? "{$oldtext}\n\n{$subject}{$text}"
1031 : "{$subject}{$text}";
1032 }
1033 } else {
1034 # Replacing an existing section; roll out the big guns
1035 global $wgParser;
1036
1037 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1038 }
1039 }
1040
1041 wfProfileOut( __METHOD__ );
1042 return $text;
1043 }
1044
1045 /**
1046 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1047 * @param $flags Int
1048 * @return Int updated $flags
1049 */
1050 function checkFlags( $flags ) {
1051 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1052 if ( $this->mTitle->getArticleID() ) {
1053 $flags |= EDIT_UPDATE;
1054 } else {
1055 $flags |= EDIT_NEW;
1056 }
1057 }
1058
1059 return $flags;
1060 }
1061
1062 /**
1063 * Change an existing article or create a new article. Updates RC and all necessary caches,
1064 * optionally via the deferred update array.
1065 *
1066 * @param $text String: new text
1067 * @param $summary String: edit summary
1068 * @param $flags Integer bitfield:
1069 * EDIT_NEW
1070 * Article is known or assumed to be non-existent, create a new one
1071 * EDIT_UPDATE
1072 * Article is known or assumed to be pre-existing, update it
1073 * EDIT_MINOR
1074 * Mark this edit minor, if the user is allowed to do so
1075 * EDIT_SUPPRESS_RC
1076 * Do not log the change in recentchanges
1077 * EDIT_FORCE_BOT
1078 * Mark the edit a "bot" edit regardless of user rights
1079 * EDIT_DEFER_UPDATES
1080 * Defer some of the updates until the end of index.php
1081 * EDIT_AUTOSUMMARY
1082 * Fill in blank summaries with generated text where possible
1083 *
1084 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1085 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1086 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1087 * edit-already-exists error will be returned. These two conditions are also possible with
1088 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1089 *
1090 * @param $baseRevId the revision ID this edit was based off, if any
1091 * @param $user User the user doing the edit
1092 *
1093 * @return Status object. Possible errors:
1094 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1095 * edit-gone-missing: In update mode, but the article didn't exist
1096 * edit-conflict: In update mode, the article changed unexpectedly
1097 * edit-no-change: Warning that the text was the same as before
1098 * edit-already-exists: In creation mode, but the article already exists
1099 *
1100 * Extensions may define additional errors.
1101 *
1102 * $return->value will contain an associative array with members as follows:
1103 * new: Boolean indicating if the function attempted to create a new article
1104 * revision: The revision object for the inserted revision, or null
1105 *
1106 * Compatibility note: this function previously returned a boolean value indicating success/failure
1107 */
1108 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1109 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1110
1111 # Low-level sanity check
1112 if ( $this->mTitle->getText() === '' ) {
1113 throw new MWException( 'Something is trying to edit an article with an empty title' );
1114 }
1115
1116 wfProfileIn( __METHOD__ );
1117
1118 $user = is_null( $user ) ? $wgUser : $user;
1119 $status = Status::newGood( array() );
1120
1121 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1122 $this->loadPageData( 'fromdbmaster' );
1123
1124 $flags = $this->checkFlags( $flags );
1125
1126 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1127 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1128 {
1129 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1130
1131 if ( $status->isOK() ) {
1132 $status->fatal( 'edit-hook-aborted' );
1133 }
1134
1135 wfProfileOut( __METHOD__ );
1136 return $status;
1137 }
1138
1139 # Silently ignore EDIT_MINOR if not allowed
1140 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1141 $bot = $flags & EDIT_FORCE_BOT;
1142
1143 $oldtext = $this->getRawText(); // current revision
1144 $oldsize = strlen( $oldtext );
1145 $oldid = $this->getLatest();
1146 $oldIsRedirect = $this->isRedirect();
1147 $oldcountable = $this->isCountable();
1148
1149 # Provide autosummaries if one is not provided and autosummaries are enabled.
1150 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1151 $summary = self::getAutosummary( $oldtext, $text, $flags );
1152 }
1153
1154 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1155 $text = $editInfo->pst;
1156 $newsize = strlen( $text );
1157
1158 $dbw = wfGetDB( DB_MASTER );
1159 $now = wfTimestampNow();
1160 $this->mTimestamp = $now;
1161
1162 if ( $flags & EDIT_UPDATE ) {
1163 # Update article, but only if changed.
1164 $status->value['new'] = false;
1165
1166 # Make sure the revision is either completely inserted or not inserted at all
1167 if ( !$wgDBtransactions ) {
1168 $userAbort = ignore_user_abort( true );
1169 }
1170
1171 $revision = new Revision( array(
1172 'page' => $this->getId(),
1173 'comment' => $summary,
1174 'minor_edit' => $isminor,
1175 'text' => $text,
1176 'parent_id' => $oldid,
1177 'user' => $user->getId(),
1178 'user_text' => $user->getName(),
1179 'timestamp' => $now
1180 ) );
1181
1182 $changed = ( strcmp( $text, $oldtext ) != 0 );
1183
1184 if ( $changed ) {
1185 if ( !$this->mLatest ) {
1186 # Article gone missing
1187 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1188 $status->fatal( 'edit-gone-missing' );
1189
1190 wfProfileOut( __METHOD__ );
1191 return $status;
1192 }
1193
1194 $dbw->begin();
1195 $revisionId = $revision->insertOn( $dbw );
1196
1197 # Update page
1198 #
1199 # Note that we use $this->mLatest instead of fetching a value from the master DB
1200 # during the course of this function. This makes sure that EditPage can detect
1201 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1202 # before this function is called. A previous function used a separate query, this
1203 # creates a window where concurrent edits can cause an ignored edit conflict.
1204 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1205
1206 if ( !$ok ) {
1207 /* Belated edit conflict! Run away!! */
1208 $status->fatal( 'edit-conflict' );
1209
1210 # Delete the invalid revision if the DB is not transactional
1211 if ( !$wgDBtransactions ) {
1212 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1213 }
1214
1215 $revisionId = 0;
1216 $dbw->rollback();
1217 } else {
1218 global $wgUseRCPatrol;
1219 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1220 # Update recentchanges
1221 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1222 # Mark as patrolled if the user can do so
1223 $patrolled = $wgUseRCPatrol && !count(
1224 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1225 # Add RC row to the DB
1226 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1227 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1228 $revisionId, $patrolled
1229 );
1230
1231 # Log auto-patrolled edits
1232 if ( $patrolled ) {
1233 PatrolLog::record( $rc, true );
1234 }
1235 }
1236 $user->incEditCount();
1237 $dbw->commit();
1238 }
1239 }
1240
1241 if ( !$wgDBtransactions ) {
1242 ignore_user_abort( $userAbort );
1243 }
1244
1245 // Now that ignore_user_abort is restored, we can respond to fatal errors
1246 if ( !$status->isOK() ) {
1247 wfProfileOut( __METHOD__ );
1248 return $status;
1249 }
1250
1251 # Update links tables, site stats, etc.
1252 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1253 'oldcountable' => $oldcountable ) );
1254
1255 if ( !$changed ) {
1256 $status->warning( 'edit-no-change' );
1257 $revision = null;
1258 // Keep the same revision ID, but do some updates on it
1259 $revisionId = $this->getLatest();
1260 // Update page_touched, this is usually implicit in the page update
1261 // Other cache updates are done in onArticleEdit()
1262 $this->mTitle->invalidateCache();
1263 }
1264 } else {
1265 # Create new article
1266 $status->value['new'] = true;
1267
1268 $dbw->begin();
1269
1270 # Add the page record; stake our claim on this title!
1271 # This will return false if the article already exists
1272 $newid = $this->insertOn( $dbw );
1273
1274 if ( $newid === false ) {
1275 $dbw->rollback();
1276 $status->fatal( 'edit-already-exists' );
1277
1278 wfProfileOut( __METHOD__ );
1279 return $status;
1280 }
1281
1282 # Save the revision text...
1283 $revision = new Revision( array(
1284 'page' => $newid,
1285 'comment' => $summary,
1286 'minor_edit' => $isminor,
1287 'text' => $text,
1288 'user' => $user->getId(),
1289 'user_text' => $user->getName(),
1290 'timestamp' => $now
1291 ) );
1292 $revisionId = $revision->insertOn( $dbw );
1293
1294 # Update the page record with revision data
1295 $this->updateRevisionOn( $dbw, $revision, 0 );
1296
1297 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1298
1299 # Update recentchanges
1300 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1301 global $wgUseRCPatrol, $wgUseNPPatrol;
1302
1303 # Mark as patrolled if the user can do so
1304 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1305 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1306 # Add RC row to the DB
1307 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1308 '', strlen( $text ), $revisionId, $patrolled );
1309
1310 # Log auto-patrolled edits
1311 if ( $patrolled ) {
1312 PatrolLog::record( $rc, true );
1313 }
1314 }
1315 $user->incEditCount();
1316 $dbw->commit();
1317
1318 # Update links, etc.
1319 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1320
1321 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1322 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1323 }
1324
1325 # Do updates right now unless deferral was requested
1326 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1327 DeferredUpdates::doUpdates();
1328 }
1329
1330 // Return the new revision (or null) to the caller
1331 $status->value['revision'] = $revision;
1332
1333 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1334 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1335
1336 # Promote user to any groups they meet the criteria for
1337 $user->addAutopromoteOnceGroups( 'onEdit' );
1338
1339 wfProfileOut( __METHOD__ );
1340 return $status;
1341 }
1342
1343 /**
1344 * Update the article's restriction field, and leave a log entry.
1345 *
1346 * @todo: seperate the business/permission stuff out from backend code
1347 *
1348 * @param $limit Array: set of restriction keys
1349 * @param $reason String
1350 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1351 * @param $expiry Array: per restriction type expiration
1352 * @param $user User The user updating the restrictions
1353 * @return bool true on success
1354 */
1355 public function updateRestrictions(
1356 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
1357 ) {
1358 global $wgUser, $wgContLang;
1359 $user = is_null( $user ) ? $wgUser : $user;
1360
1361 $restrictionTypes = $this->mTitle->getRestrictionTypes();
1362
1363 $id = $this->mTitle->getArticleID();
1364
1365 if ( $id <= 0 ) {
1366 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1367 return false;
1368 }
1369
1370 if ( wfReadOnly() ) {
1371 wfDebug( "updateRestrictions failed: read-only\n" );
1372 return false;
1373 }
1374
1375 if ( count( $this->mTitle->getUserPermissionsErrors( 'protect', $user ) ) ) {
1376 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1377 return false;
1378 }
1379
1380 if ( !$cascade ) {
1381 $cascade = false;
1382 }
1383
1384 // Take this opportunity to purge out expired restrictions
1385 Title::purgeExpiredRestrictions();
1386
1387 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1388 # we expect a single selection, but the schema allows otherwise.
1389 $current = array();
1390 $updated = self::flattenRestrictions( $limit );
1391 $changed = false;
1392
1393 foreach ( $restrictionTypes as $action ) {
1394 if ( isset( $expiry[$action] ) ) {
1395 # Get current restrictions on $action
1396 $aLimits = $this->mTitle->getRestrictions( $action );
1397 $current[$action] = implode( '', $aLimits );
1398 # Are any actual restrictions being dealt with here?
1399 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
1400
1401 # If something changed, we need to log it. Checking $aRChanged
1402 # assures that "unprotecting" a page that is not protected does
1403 # not log just because the expiry was "changed".
1404 if ( $aRChanged &&
1405 $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] )
1406 {
1407 $changed = true;
1408 }
1409 }
1410 }
1411
1412 $current = self::flattenRestrictions( $current );
1413
1414 $changed = ( $changed || $current != $updated );
1415 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
1416 $protect = ( $updated != '' );
1417
1418 # If nothing's changed, do nothing
1419 if ( $changed ) {
1420 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1421 $dbw = wfGetDB( DB_MASTER );
1422
1423 # Prepare a null revision to be added to the history
1424 $modified = $current != '' && $protect;
1425
1426 if ( $protect ) {
1427 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1428 } else {
1429 $comment_type = 'unprotectedarticle';
1430 }
1431
1432 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1433
1434 # Only restrictions with the 'protect' right can cascade...
1435 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1436 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1437
1438 # The schema allows multiple restrictions
1439 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1440 $cascade = false;
1441 }
1442
1443 $cascade_description = '';
1444
1445 if ( $cascade ) {
1446 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1447 }
1448
1449 if ( $reason ) {
1450 $comment .= ": $reason";
1451 }
1452
1453 $editComment = $comment;
1454 $encodedExpiry = array();
1455 $protect_description = '';
1456 foreach ( $limit as $action => $restrictions ) {
1457 if ( !isset( $expiry[$action] ) )
1458 $expiry[$action] = $dbw->getInfinity();
1459
1460 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1461 if ( $restrictions != '' ) {
1462 $protect_description .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1463 if ( $encodedExpiry[$action] != 'infinity' ) {
1464 $protect_description .= wfMsgForContent( 'protect-expiring',
1465 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1466 $wgContLang->date( $expiry[$action], false, false ) ,
1467 $wgContLang->time( $expiry[$action], false, false ) );
1468 } else {
1469 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1470 }
1471
1472 $protect_description .= ') ';
1473 }
1474 }
1475 $protect_description = trim( $protect_description );
1476
1477 if ( $protect_description && $protect ) {
1478 $editComment .= " ($protect_description)";
1479 }
1480
1481 if ( $cascade ) {
1482 $editComment .= "$cascade_description";
1483 }
1484
1485 # Update restrictions table
1486 foreach ( $limit as $action => $restrictions ) {
1487 if ( $restrictions != '' ) {
1488 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1489 array( 'pr_page' => $id,
1490 'pr_type' => $action,
1491 'pr_level' => $restrictions,
1492 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
1493 'pr_expiry' => $encodedExpiry[$action]
1494 ),
1495 __METHOD__
1496 );
1497 } else {
1498 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1499 'pr_type' => $action ), __METHOD__ );
1500 }
1501 }
1502
1503 # Insert a null revision
1504 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1505 $nullRevId = $nullRevision->insertOn( $dbw );
1506
1507 $latest = $this->getLatest();
1508 # Update page record
1509 $dbw->update( 'page',
1510 array( /* SET */
1511 'page_touched' => $dbw->timestamp(),
1512 'page_restrictions' => '',
1513 'page_latest' => $nullRevId
1514 ), array( /* WHERE */
1515 'page_id' => $id
1516 ), __METHOD__
1517 );
1518
1519 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1520 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1521
1522 # Update the protection log
1523 $log = new LogPage( 'protect' );
1524 if ( $protect ) {
1525 $params = array( $protect_description, $cascade ? 'cascade' : '' );
1526 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
1527 } else {
1528 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1529 }
1530 } # End hook
1531 } # End "changed" check
1532
1533 return true;
1534 }
1535
1536 /**
1537 * Take an array of page restrictions and flatten it to a string
1538 * suitable for insertion into the page_restrictions field.
1539 * @param $limit Array
1540 * @return String
1541 */
1542 protected static function flattenRestrictions( $limit ) {
1543 if ( !is_array( $limit ) ) {
1544 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1545 }
1546
1547 $bits = array();
1548 ksort( $limit );
1549
1550 foreach ( $limit as $action => $restrictions ) {
1551 if ( $restrictions != '' ) {
1552 $bits[] = "$action=$restrictions";
1553 }
1554 }
1555
1556 return implode( ':', $bits );
1557 }
1558
1559 /**
1560 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1561 */
1562 public function isBigDeletion() {
1563 global $wgDeleteRevisionsLimit;
1564
1565 if ( $wgDeleteRevisionsLimit ) {
1566 $revCount = $this->estimateRevisionCount();
1567
1568 return $revCount > $wgDeleteRevisionsLimit;
1569 }
1570
1571 return false;
1572 }
1573
1574 /**
1575 * @return int approximate revision count
1576 */
1577 public function estimateRevisionCount() {
1578 $dbr = wfGetDB( DB_SLAVE );
1579 return $dbr->estimateRowCount( 'revision', '*',
1580 array( 'rev_page' => $this->getId() ), __METHOD__ );
1581 }
1582
1583 /**
1584 * Get the last N authors
1585 * @param $num Integer: number of revisions to get
1586 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1587 * @return array Array of authors, duplicates not removed
1588 */
1589 public function getLastNAuthors( $num, $revLatest = 0 ) {
1590 wfProfileIn( __METHOD__ );
1591 // First try the slave
1592 // If that doesn't have the latest revision, try the master
1593 $continue = 2;
1594 $db = wfGetDB( DB_SLAVE );
1595
1596 do {
1597 $res = $db->select( array( 'page', 'revision' ),
1598 array( 'rev_id', 'rev_user_text' ),
1599 array(
1600 'page_namespace' => $this->mTitle->getNamespace(),
1601 'page_title' => $this->mTitle->getDBkey(),
1602 'rev_page = page_id'
1603 ), __METHOD__,
1604 array(
1605 'ORDER BY' => 'rev_timestamp DESC',
1606 'LIMIT' => $num
1607 )
1608 );
1609
1610 if ( !$res ) {
1611 wfProfileOut( __METHOD__ );
1612 return array();
1613 }
1614
1615 $row = $db->fetchObject( $res );
1616
1617 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1618 $db = wfGetDB( DB_MASTER );
1619 $continue--;
1620 } else {
1621 $continue = 0;
1622 }
1623 } while ( $continue );
1624
1625 $authors = array( $row->rev_user_text );
1626
1627 foreach ( $res as $row ) {
1628 $authors[] = $row->rev_user_text;
1629 }
1630
1631 wfProfileOut( __METHOD__ );
1632 return $authors;
1633 }
1634
1635 /**
1636 * Back-end article deletion
1637 * Deletes the article with database consistency, writes logs, purges caches
1638 *
1639 * @param $reason string delete reason for deletion log
1640 * @param $suppress bitfield
1641 * Revision::DELETED_TEXT
1642 * Revision::DELETED_COMMENT
1643 * Revision::DELETED_USER
1644 * Revision::DELETED_RESTRICTED
1645 * @param $id int article ID
1646 * @param $commit boolean defaults to true, triggers transaction end
1647 * @param &$errors Array of errors to append to
1648 * @param $user User The relevant user
1649 * @return boolean true if successful
1650 */
1651 public function doDeleteArticle(
1652 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
1653 ) {
1654 global $wgUseTrackbacks, $wgUser;
1655 $user = is_null( $user ) ? $wgUser : $user;
1656
1657 wfDebug( __METHOD__ . "\n" );
1658
1659 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1660 return false;
1661 }
1662 $dbw = wfGetDB( DB_MASTER );
1663 $t = $this->mTitle->getDBkey();
1664 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
1665
1666 if ( $t === '' || $id == 0 ) {
1667 return false;
1668 }
1669
1670 DeferredUpdates::addUpdate(
1671 new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 )
1672 );
1673
1674 // Bitfields to further suppress the content
1675 if ( $suppress ) {
1676 $bitfield = 0;
1677 // This should be 15...
1678 $bitfield |= Revision::DELETED_TEXT;
1679 $bitfield |= Revision::DELETED_COMMENT;
1680 $bitfield |= Revision::DELETED_USER;
1681 $bitfield |= Revision::DELETED_RESTRICTED;
1682 } else {
1683 $bitfield = 'rev_deleted';
1684 }
1685
1686 $dbw->begin();
1687 // For now, shunt the revision data into the archive table.
1688 // Text is *not* removed from the text table; bulk storage
1689 // is left intact to avoid breaking block-compression or
1690 // immutable storage schemes.
1691 //
1692 // For backwards compatibility, note that some older archive
1693 // table entries will have ar_text and ar_flags fields still.
1694 //
1695 // In the future, we may keep revisions and mark them with
1696 // the rev_deleted field, which is reserved for this purpose.
1697 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1698 array(
1699 'ar_namespace' => 'page_namespace',
1700 'ar_title' => 'page_title',
1701 'ar_comment' => 'rev_comment',
1702 'ar_user' => 'rev_user',
1703 'ar_user_text' => 'rev_user_text',
1704 'ar_timestamp' => 'rev_timestamp',
1705 'ar_minor_edit' => 'rev_minor_edit',
1706 'ar_rev_id' => 'rev_id',
1707 'ar_parent_id' => 'rev_parent_id',
1708 'ar_text_id' => 'rev_text_id',
1709 'ar_text' => '\'\'', // Be explicit to appease
1710 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1711 'ar_len' => 'rev_len',
1712 'ar_page_id' => 'page_id',
1713 'ar_deleted' => $bitfield,
1714 'ar_sha1' => 'rev_sha1'
1715 ), array(
1716 'page_id' => $id,
1717 'page_id = rev_page'
1718 ), __METHOD__
1719 );
1720
1721 # Delete restrictions for it
1722 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
1723
1724 # Now that it's safely backed up, delete it
1725 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
1726 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1727
1728 if ( !$ok ) {
1729 $dbw->rollback();
1730 return false;
1731 }
1732
1733 # Fix category table counts
1734 $cats = array();
1735 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
1736
1737 foreach ( $res as $row ) {
1738 $cats [] = $row->cl_to;
1739 }
1740
1741 $this->updateCategoryCounts( array(), $cats );
1742
1743 # If using cascading deletes, we can skip some explicit deletes
1744 if ( !$dbw->cascadingDeletes() ) {
1745 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
1746
1747 if ( $wgUseTrackbacks ) {
1748 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
1749 }
1750
1751 # Delete outgoing links
1752 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__ );
1753 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__ );
1754 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__ );
1755 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__ );
1756 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__ );
1757 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__ );
1758 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__ );
1759 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__ );
1760 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__ );
1761 }
1762
1763 # If using cleanup triggers, we can skip some manual deletes
1764 if ( !$dbw->cleanupTriggers() ) {
1765 # Clean up recentchanges entries...
1766 $dbw->delete( 'recentchanges',
1767 array( 'rc_type != ' . RC_LOG,
1768 'rc_namespace' => $this->mTitle->getNamespace(),
1769 'rc_title' => $this->mTitle->getDBkey() ),
1770 __METHOD__ );
1771 $dbw->delete( 'recentchanges',
1772 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
1773 __METHOD__ );
1774 }
1775
1776 # Clear caches
1777 self::onArticleDelete( $this->mTitle );
1778
1779 # Clear the cached article id so the interface doesn't act like we exist
1780 $this->mTitle->resetArticleID( 0 );
1781
1782 # Log the deletion, if the page was suppressed, log it at Oversight instead
1783 $logtype = $suppress ? 'suppress' : 'delete';
1784
1785 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1786 $logEntry->setPerformer( $user );
1787 $logEntry->setTarget( $this->mTitle );
1788 $logEntry->setComment( $reason );
1789 $logid = $logEntry->insert();
1790 $logEntry->publish( $logid );
1791
1792 if ( $commit ) {
1793 $dbw->commit();
1794 }
1795
1796 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1797 return true;
1798 }
1799
1800 /**
1801 * Roll back the most recent consecutive set of edits to a page
1802 * from the same user; fails if there are no eligible edits to
1803 * roll back to, e.g. user is the sole contributor. This function
1804 * performs permissions checks on $user, then calls commitRollback()
1805 * to do the dirty work
1806 *
1807 * @todo: seperate the business/permission stuff out from backend code
1808 *
1809 * @param $fromP String: Name of the user whose edits to rollback.
1810 * @param $summary String: Custom summary. Set to default summary if empty.
1811 * @param $token String: Rollback token.
1812 * @param $bot Boolean: If true, mark all reverted edits as bot.
1813 *
1814 * @param $resultDetails Array: contains result-specific array of additional values
1815 * 'alreadyrolled' : 'current' (rev)
1816 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1817 *
1818 * @param $user User The user performing the rollback
1819 * @return array of errors, each error formatted as
1820 * array(messagekey, param1, param2, ...).
1821 * On success, the array is empty. This array can also be passed to
1822 * OutputPage::showPermissionsErrorPage().
1823 */
1824 public function doRollback(
1825 $fromP, $summary, $token, $bot, &$resultDetails, User $user
1826 ) {
1827 $resultDetails = null;
1828
1829 # Check permissions
1830 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
1831 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
1832 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1833
1834 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
1835 $errors[] = array( 'sessionfailure' );
1836 }
1837
1838 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
1839 $errors[] = array( 'actionthrottledtext' );
1840 }
1841
1842 # If there were errors, bail out now
1843 if ( !empty( $errors ) ) {
1844 return $errors;
1845 }
1846
1847 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
1848 }
1849
1850 /**
1851 * Backend implementation of doRollback(), please refer there for parameter
1852 * and return value documentation
1853 *
1854 * NOTE: This function does NOT check ANY permissions, it just commits the
1855 * rollback to the DB. Therefore, you should only call this function direct-
1856 * ly if you want to use custom permissions checks. If you don't, use
1857 * doRollback() instead.
1858 * @param $fromP String: Name of the user whose edits to rollback.
1859 * @param $summary String: Custom summary. Set to default summary if empty.
1860 * @param $bot Boolean: If true, mark all reverted edits as bot.
1861 *
1862 * @param $resultDetails Array: contains result-specific array of additional values
1863 * @param $guser User The user performing the rollback
1864 */
1865 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
1866 global $wgUseRCPatrol, $wgContLang;
1867
1868 $dbw = wfGetDB( DB_MASTER );
1869
1870 if ( wfReadOnly() ) {
1871 return array( array( 'readonlytext' ) );
1872 }
1873
1874 # Get the last editor
1875 $current = Revision::newFromTitle( $this->mTitle );
1876 if ( is_null( $current ) ) {
1877 # Something wrong... no page?
1878 return array( array( 'notanarticle' ) );
1879 }
1880
1881 $from = str_replace( '_', ' ', $fromP );
1882 # User name given should match up with the top revision.
1883 # If the user was deleted then $from should be empty.
1884 if ( $from != $current->getUserText() ) {
1885 $resultDetails = array( 'current' => $current );
1886 return array( array( 'alreadyrolled',
1887 htmlspecialchars( $this->mTitle->getPrefixedText() ),
1888 htmlspecialchars( $fromP ),
1889 htmlspecialchars( $current->getUserText() )
1890 ) );
1891 }
1892
1893 # Get the last edit not by this guy...
1894 # Note: these may not be public values
1895 $user = intval( $current->getRawUser() );
1896 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1897 $s = $dbw->selectRow( 'revision',
1898 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1899 array( 'rev_page' => $current->getPage(),
1900 "rev_user != {$user} OR rev_user_text != {$user_text}"
1901 ), __METHOD__,
1902 array( 'USE INDEX' => 'page_timestamp',
1903 'ORDER BY' => 'rev_timestamp DESC' )
1904 );
1905 if ( $s === false ) {
1906 # No one else ever edited this page
1907 return array( array( 'cantrollback' ) );
1908 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
1909 # Only admins can see this text
1910 return array( array( 'notvisiblerev' ) );
1911 }
1912
1913 $set = array();
1914 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1915 # Mark all reverted edits as bot
1916 $set['rc_bot'] = 1;
1917 }
1918
1919 if ( $wgUseRCPatrol ) {
1920 # Mark all reverted edits as patrolled
1921 $set['rc_patrolled'] = 1;
1922 }
1923
1924 if ( count( $set ) ) {
1925 $dbw->update( 'recentchanges', $set,
1926 array( /* WHERE */
1927 'rc_cur_id' => $current->getPage(),
1928 'rc_user_text' => $current->getUserText(),
1929 "rc_timestamp > '{$s->rev_timestamp}'",
1930 ), __METHOD__
1931 );
1932 }
1933
1934 # Generate the edit summary if necessary
1935 $target = Revision::newFromId( $s->rev_id );
1936 if ( empty( $summary ) ) {
1937 if ( $from == '' ) { // no public user name
1938 $summary = wfMsgForContent( 'revertpage-nouser' );
1939 } else {
1940 $summary = wfMsgForContent( 'revertpage' );
1941 }
1942 }
1943
1944 # Allow the custom summary to use the same args as the default message
1945 $args = array(
1946 $target->getUserText(), $from, $s->rev_id,
1947 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
1948 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1949 );
1950 $summary = wfMsgReplaceArgs( $summary, $args );
1951
1952 # Save
1953 $flags = EDIT_UPDATE;
1954
1955 if ( $guser->isAllowed( 'minoredit' ) ) {
1956 $flags |= EDIT_MINOR;
1957 }
1958
1959 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1960 $flags |= EDIT_FORCE_BOT;
1961 }
1962
1963 # Actually store the edit
1964 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1965 if ( !empty( $status->value['revision'] ) ) {
1966 $revId = $status->value['revision']->getId();
1967 } else {
1968 $revId = false;
1969 }
1970
1971 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1972
1973 $resultDetails = array(
1974 'summary' => $summary,
1975 'current' => $current,
1976 'target' => $target,
1977 'newid' => $revId
1978 );
1979
1980 return array();
1981 }
1982
1983 /**
1984 * Do standard deferred updates after page view
1985 * @param $user User The relevant user
1986 */
1987 public function doViewUpdates( User $user ) {
1988 global $wgDisableCounters;
1989 if ( wfReadOnly() ) {
1990 return;
1991 }
1992
1993 # Don't update page view counters on views from bot users (bug 14044)
1994 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getId() ) {
1995 DeferredUpdates::addUpdate( new ViewCountUpdate( $this->getId() ) );
1996 DeferredUpdates::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1997 }
1998
1999 # Update newtalk / watchlist notification status
2000 $user->clearNotification( $this->mTitle );
2001 }
2002
2003 /**
2004 * Prepare text which is about to be saved.
2005 * Returns a stdclass with source, pst and output members
2006 */
2007 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2008 global $wgParser, $wgContLang, $wgUser;
2009 $user = is_null( $user ) ? $wgUser : $user;
2010 // @TODO fixme: check $user->getId() here???
2011 if ( $this->mPreparedEdit
2012 && $this->mPreparedEdit->newText == $text
2013 && $this->mPreparedEdit->revid == $revid
2014 ) {
2015 // Already prepared
2016 return $this->mPreparedEdit;
2017 }
2018
2019 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2020 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2021
2022 $edit = (object)array();
2023 $edit->revid = $revid;
2024 $edit->newText = $text;
2025 $edit->pst = $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2026 $edit->popts = $this->makeParserOptions( 'canonical' );
2027 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
2028 $edit->oldText = $this->getRawText();
2029
2030 $this->mPreparedEdit = $edit;
2031
2032 return $edit;
2033 }
2034
2035 /**
2036 * Do standard deferred updates after page edit.
2037 * Update links tables, site stats, search index and message cache.
2038 * Purges pages that include this page if the text was changed here.
2039 * Every 100th edit, prune the recent changes table.
2040 *
2041 * @private
2042 * @param $revision Revision object
2043 * @param $user User object that did the revision
2044 * @param $options Array of options, following indexes are used:
2045 * - changed: boolean, whether the revision changed the content (default true)
2046 * - created: boolean, whether the revision created the page (default false)
2047 * - oldcountable: boolean or null (default null):
2048 * - boolean: whether the page was counted as an article before that
2049 * revision, only used in changed is true and created is false
2050 * - null: don't change the article count
2051 */
2052 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2053 global $wgEnableParserCache;
2054
2055 wfProfileIn( __METHOD__ );
2056
2057 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2058 $text = $revision->getText();
2059
2060 # Parse the text
2061 # Be careful not to double-PST: $text is usually already PST-ed once
2062 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2063 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2064 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
2065 } else {
2066 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2067 $editInfo = $this->mPreparedEdit;
2068 }
2069
2070 # Save it to the parser cache
2071 if ( $wgEnableParserCache ) {
2072 $parserCache = ParserCache::singleton();
2073 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
2074 }
2075
2076 # Update the links tables
2077 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2078 $u->doUpdate();
2079
2080 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2081
2082 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2083 if ( 0 == mt_rand( 0, 99 ) ) {
2084 // Flush old entries from the `recentchanges` table; we do this on
2085 // random requests so as to avoid an increase in writes for no good reason
2086 global $wgRCMaxAge;
2087
2088 $dbw = wfGetDB( DB_MASTER );
2089 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2090 $dbw->delete(
2091 'recentchanges',
2092 array( "rc_timestamp < '$cutoff'" ),
2093 __METHOD__
2094 );
2095 }
2096 }
2097
2098 $id = $this->getId();
2099 $title = $this->mTitle->getPrefixedDBkey();
2100 $shortTitle = $this->mTitle->getDBkey();
2101
2102 if ( 0 == $id ) {
2103 wfProfileOut( __METHOD__ );
2104 return;
2105 }
2106
2107 if ( !$options['changed'] ) {
2108 $good = 0;
2109 $total = 0;
2110 } elseif ( $options['created'] ) {
2111 $good = (int)$this->isCountable( $editInfo );
2112 $total = 1;
2113 } elseif ( $options['oldcountable'] !== null ) {
2114 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2115 $total = 0;
2116 } else {
2117 $good = 0;
2118 $total = 0;
2119 }
2120
2121 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2122 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $text ) );
2123
2124 # If this is another user's talk page, update newtalk.
2125 # Don't do this if $options['changed'] = false (null-edits) nor if
2126 # it's a minor edit and the user doesn't want notifications for those.
2127 if ( $options['changed']
2128 && $this->mTitle->getNamespace() == NS_USER_TALK
2129 && $shortTitle != $user->getTitleKey()
2130 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2131 ) {
2132 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2133 $other = User::newFromName( $shortTitle, false );
2134 if ( !$other ) {
2135 wfDebug( __METHOD__ . ": invalid username\n" );
2136 } elseif ( User::isIP( $shortTitle ) ) {
2137 // An anonymous user
2138 $other->setNewtalk( true );
2139 } elseif ( $other->isLoggedIn() ) {
2140 $other->setNewtalk( true );
2141 } else {
2142 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2143 }
2144 }
2145 }
2146
2147 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2148 MessageCache::singleton()->replace( $shortTitle, $text );
2149 }
2150
2151 if( $options['created'] ) {
2152 self::onArticleCreate( $this->mTitle );
2153 } else {
2154 self::onArticleEdit( $this->mTitle );
2155 }
2156
2157 wfProfileOut( __METHOD__ );
2158 }
2159
2160 /**
2161 * Perform article updates on a special page creation.
2162 *
2163 * @param $rev Revision object
2164 *
2165 * @todo This is a shitty interface function. Kill it and replace the
2166 * other shitty functions like doEditUpdates and such so it's not needed
2167 * anymore.
2168 * @deprecated since 1.18, use doEditUpdates()
2169 */
2170 public function createUpdates( $rev ) {
2171 global $wgUser;
2172 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2173 }
2174
2175 /**
2176 * This function is called right before saving the wikitext,
2177 * so we can do things like signatures and links-in-context.
2178 *
2179 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2180 * @param $text String article contents
2181 * @param $user User object: user doing the edit
2182 * @param $popts ParserOptions object: parser options, default options for
2183 * the user loaded if null given
2184 * @return string article contents with altered wikitext markup (signatures
2185 * converted, {{subst:}}, templates, etc.)
2186 */
2187 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
2188 global $wgParser, $wgUser;
2189
2190 wfDeprecated( __METHOD__ );
2191
2192 $user = is_null( $user ) ? $wgUser : $user;
2193
2194 if ( $popts === null ) {
2195 $popts = ParserOptions::newFromUser( $user );
2196 }
2197
2198 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2199 }
2200
2201 /**
2202 * Loads page_touched and returns a value indicating if it should be used
2203 * @return boolean true if not a redirect
2204 */
2205 public function checkTouched() {
2206 if ( !$this->mDataLoaded ) {
2207 $this->loadPageData();
2208 }
2209 return !$this->mIsRedirect;
2210 }
2211
2212 /**
2213 * Get the page_touched field
2214 * @return string containing GMT timestamp
2215 */
2216 public function getTouched() {
2217 if ( !$this->mDataLoaded ) {
2218 $this->loadPageData();
2219 }
2220 return $this->mTouched;
2221 }
2222
2223 /**
2224 * Get the page_latest field
2225 * @return integer rev_id of current revision
2226 */
2227 public function getLatest() {
2228 if ( !$this->mDataLoaded ) {
2229 $this->loadPageData();
2230 }
2231 return (int)$this->mLatest;
2232 }
2233
2234 /**
2235 * Edit an article without doing all that other stuff
2236 * The article must already exist; link tables etc
2237 * are not updated, caches are not flushed.
2238 *
2239 * @param $text String: text submitted
2240 * @param $user User The relevant user
2241 * @param $comment String: comment submitted
2242 * @param $minor Boolean: whereas it's a minor modification
2243 */
2244 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2245 wfProfileIn( __METHOD__ );
2246
2247 $dbw = wfGetDB( DB_MASTER );
2248 $revision = new Revision( array(
2249 'page' => $this->getId(),
2250 'text' => $text,
2251 'comment' => $comment,
2252 'minor_edit' => $minor ? 1 : 0,
2253 ) );
2254 $revision->insertOn( $dbw );
2255 $this->updateRevisionOn( $dbw, $revision );
2256
2257 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2258
2259 wfProfileOut( __METHOD__ );
2260 }
2261
2262 /**
2263 * The onArticle*() functions are supposed to be a kind of hooks
2264 * which should be called whenever any of the specified actions
2265 * are done.
2266 *
2267 * This is a good place to put code to clear caches, for instance.
2268 *
2269 * This is called on page move and undelete, as well as edit
2270 *
2271 * @param $title Title object
2272 */
2273 public static function onArticleCreate( $title ) {
2274 # Update existence markers on article/talk tabs...
2275 if ( $title->isTalkPage() ) {
2276 $other = $title->getSubjectPage();
2277 } else {
2278 $other = $title->getTalkPage();
2279 }
2280
2281 $other->invalidateCache();
2282 $other->purgeSquid();
2283
2284 $title->touchLinks();
2285 $title->purgeSquid();
2286 $title->deleteTitleProtection();
2287 }
2288
2289 /**
2290 * Clears caches when article is deleted
2291 *
2292 * @param $title Title
2293 */
2294 public static function onArticleDelete( $title ) {
2295 # Update existence markers on article/talk tabs...
2296 if ( $title->isTalkPage() ) {
2297 $other = $title->getSubjectPage();
2298 } else {
2299 $other = $title->getTalkPage();
2300 }
2301
2302 $other->invalidateCache();
2303 $other->purgeSquid();
2304
2305 $title->touchLinks();
2306 $title->purgeSquid();
2307
2308 # File cache
2309 HTMLFileCache::clearFileCache( $title );
2310
2311 # Messages
2312 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2313 MessageCache::singleton()->replace( $title->getDBkey(), false );
2314 }
2315
2316 # Images
2317 if ( $title->getNamespace() == NS_FILE ) {
2318 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2319 $update->doUpdate();
2320 }
2321
2322 # User talk pages
2323 if ( $title->getNamespace() == NS_USER_TALK ) {
2324 $user = User::newFromName( $title->getText(), false );
2325 $user->setNewtalk( false );
2326 }
2327
2328 # Image redirects
2329 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2330 }
2331
2332 /**
2333 * Purge caches on page update etc
2334 *
2335 * @param $title Title object
2336 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2337 */
2338 public static function onArticleEdit( $title ) {
2339 // Invalidate caches of articles which include this page
2340 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2341
2342
2343 // Invalidate the caches of all pages which redirect here
2344 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2345
2346 # Purge squid for this page only
2347 $title->purgeSquid();
2348
2349 # Clear file cache for this page only
2350 HTMLFileCache::clearFileCache( $title );
2351 }
2352
2353 /**#@-*/
2354
2355 /**
2356 * Return a list of templates used by this article.
2357 * Uses the templatelinks table
2358 *
2359 * @return Array of Title objects
2360 */
2361 public function getUsedTemplates() {
2362 $result = array();
2363 $id = $this->mTitle->getArticleID();
2364
2365 if ( $id == 0 ) {
2366 return array();
2367 }
2368
2369 $dbr = wfGetDB( DB_SLAVE );
2370 $res = $dbr->select( array( 'templatelinks' ),
2371 array( 'tl_namespace', 'tl_title' ),
2372 array( 'tl_from' => $id ),
2373 __METHOD__ );
2374
2375 if ( $res !== false ) {
2376 foreach ( $res as $row ) {
2377 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2378 }
2379 }
2380
2381 return $result;
2382 }
2383
2384 /**
2385 * Returns a list of hidden categories this page is a member of.
2386 * Uses the page_props and categorylinks tables.
2387 *
2388 * @return Array of Title objects
2389 */
2390 public function getHiddenCategories() {
2391 $result = array();
2392 $id = $this->mTitle->getArticleID();
2393
2394 if ( $id == 0 ) {
2395 return array();
2396 }
2397
2398 $dbr = wfGetDB( DB_SLAVE );
2399 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2400 array( 'cl_to' ),
2401 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2402 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2403 __METHOD__ );
2404
2405 if ( $res !== false ) {
2406 foreach ( $res as $row ) {
2407 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2408 }
2409 }
2410
2411 return $result;
2412 }
2413
2414 /**
2415 * Return an applicable autosummary if one exists for the given edit.
2416 * @param $oldtext String: the previous text of the page.
2417 * @param $newtext String: The submitted text of the page.
2418 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2419 * @return string An appropriate autosummary, or an empty string.
2420 */
2421 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2422 global $wgContLang;
2423
2424 # Decide what kind of autosummary is needed.
2425
2426 # Redirect autosummaries
2427 $ot = Title::newFromRedirect( $oldtext );
2428 $rt = Title::newFromRedirect( $newtext );
2429
2430 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
2431 $truncatedtext = $wgContLang->truncate(
2432 str_replace( "\n", ' ', $newtext ),
2433 max( 0, 250
2434 - strlen( wfMsgForContent( 'autoredircomment' ) )
2435 - strlen( $rt->getFullText() )
2436 ) );
2437 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2438 }
2439
2440 # New page autosummaries
2441 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
2442 # If they're making a new article, give its text, truncated, in the summary.
2443
2444 $truncatedtext = $wgContLang->truncate(
2445 str_replace( "\n", ' ', $newtext ),
2446 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2447
2448 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2449 }
2450
2451 # Blanking autosummaries
2452 if ( $oldtext != '' && $newtext == '' ) {
2453 return wfMsgForContent( 'autosumm-blank' );
2454 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2455 # Removing more than 90% of the article
2456
2457 $truncatedtext = $wgContLang->truncate(
2458 $newtext,
2459 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2460
2461 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2462 }
2463
2464 # If we reach this point, there's no applicable autosummary for our case, so our
2465 # autosummary is empty.
2466 return '';
2467 }
2468
2469 /**
2470 * Auto-generates a deletion reason
2471 *
2472 * @param &$hasHistory Boolean: whether the page has a history
2473 * @return mixed String containing deletion reason or empty string, or boolean false
2474 * if no revision occurred
2475 */
2476 public function getAutoDeleteReason( &$hasHistory ) {
2477 global $wgContLang;
2478
2479 $dbw = wfGetDB( DB_MASTER );
2480 // Get the last revision
2481 $rev = Revision::newFromTitle( $this->getTitle() );
2482
2483 if ( is_null( $rev ) ) {
2484 return false;
2485 }
2486
2487 // Get the article's contents
2488 $contents = $rev->getText();
2489 $blank = false;
2490
2491 // If the page is blank, use the text from the previous revision,
2492 // which can only be blank if there's a move/import/protect dummy revision involved
2493 if ( $contents == '' ) {
2494 $prev = $rev->getPrevious();
2495
2496 if ( $prev ) {
2497 $contents = $prev->getText();
2498 $blank = true;
2499 }
2500 }
2501
2502 // Find out if there was only one contributor
2503 // Only scan the last 20 revisions
2504 $res = $dbw->select( 'revision', 'rev_user_text',
2505 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2506 __METHOD__,
2507 array( 'LIMIT' => 20 )
2508 );
2509
2510 if ( $res === false ) {
2511 // This page has no revisions, which is very weird
2512 return false;
2513 }
2514
2515 $hasHistory = ( $res->numRows() > 1 );
2516 $row = $dbw->fetchObject( $res );
2517
2518 if ( $row ) { // $row is false if the only contributor is hidden
2519 $onlyAuthor = $row->rev_user_text;
2520 // Try to find a second contributor
2521 foreach ( $res as $row ) {
2522 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2523 $onlyAuthor = false;
2524 break;
2525 }
2526 }
2527 } else {
2528 $onlyAuthor = false;
2529 }
2530
2531 // Generate the summary with a '$1' placeholder
2532 if ( $blank ) {
2533 // The current revision is blank and the one before is also
2534 // blank. It's just not our lucky day
2535 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2536 } else {
2537 if ( $onlyAuthor ) {
2538 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2539 } else {
2540 $reason = wfMsgForContent( 'excontent', '$1' );
2541 }
2542 }
2543
2544 if ( $reason == '-' ) {
2545 // Allow these UI messages to be blanked out cleanly
2546 return '';
2547 }
2548
2549 // Replace newlines with spaces to prevent uglyness
2550 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2551 // Calculate the maximum amount of chars to get
2552 // Max content length = max comment length - length of the comment (excl. $1)
2553 $maxLength = 255 - ( strlen( $reason ) - 2 );
2554 $contents = $wgContLang->truncate( $contents, $maxLength );
2555 // Remove possible unfinished links
2556 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2557 // Now replace the '$1' placeholder
2558 $reason = str_replace( '$1', $contents, $reason );
2559
2560 return $reason;
2561 }
2562
2563 /**
2564 * Get parser options suitable for rendering the primary article wikitext
2565 * @param User|string $user User object or 'canonical'
2566 * @return ParserOptions
2567 */
2568 public function makeParserOptions( $user ) {
2569 global $wgContLang;
2570 if ( $user instanceof User ) { // settings per user (even anons)
2571 $options = ParserOptions::newFromUser( $user );
2572 } else { // canonical settings
2573 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
2574 }
2575 $options->enableLimitReport(); // show inclusion/loop reports
2576 $options->setTidy( true ); // fix bad HTML
2577 return $options;
2578 }
2579
2580 /**
2581 * Update all the appropriate counts in the category table, given that
2582 * we've added the categories $added and deleted the categories $deleted.
2583 *
2584 * @param $added array The names of categories that were added
2585 * @param $deleted array The names of categories that were deleted
2586 */
2587 public function updateCategoryCounts( $added, $deleted ) {
2588 $ns = $this->mTitle->getNamespace();
2589 $dbw = wfGetDB( DB_MASTER );
2590
2591 # First make sure the rows exist. If one of the "deleted" ones didn't
2592 # exist, we might legitimately not create it, but it's simpler to just
2593 # create it and then give it a negative value, since the value is bogus
2594 # anyway.
2595 #
2596 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2597 $insertCats = array_merge( $added, $deleted );
2598 if ( !$insertCats ) {
2599 # Okay, nothing to do
2600 return;
2601 }
2602
2603 $insertRows = array();
2604
2605 foreach ( $insertCats as $cat ) {
2606 $insertRows[] = array(
2607 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2608 'cat_title' => $cat
2609 );
2610 }
2611 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2612
2613 $addFields = array( 'cat_pages = cat_pages + 1' );
2614 $removeFields = array( 'cat_pages = cat_pages - 1' );
2615
2616 if ( $ns == NS_CATEGORY ) {
2617 $addFields[] = 'cat_subcats = cat_subcats + 1';
2618 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2619 } elseif ( $ns == NS_FILE ) {
2620 $addFields[] = 'cat_files = cat_files + 1';
2621 $removeFields[] = 'cat_files = cat_files - 1';
2622 }
2623
2624 if ( $added ) {
2625 $dbw->update(
2626 'category',
2627 $addFields,
2628 array( 'cat_title' => $added ),
2629 __METHOD__
2630 );
2631 }
2632
2633 if ( $deleted ) {
2634 $dbw->update(
2635 'category',
2636 $removeFields,
2637 array( 'cat_title' => $deleted ),
2638 __METHOD__
2639 );
2640 }
2641 }
2642
2643 /**
2644 * Updates cascading protections
2645 *
2646 * @param $parserOutput ParserOutput object for the current version
2647 */
2648 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
2649 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
2650 return;
2651 }
2652
2653 // templatelinks table may have become out of sync,
2654 // especially if using variable-based transclusions.
2655 // For paranoia, check if things have changed and if
2656 // so apply updates to the database. This will ensure
2657 // that cascaded protections apply as soon as the changes
2658 // are visible.
2659
2660 # Get templates from templatelinks
2661 $id = $this->mTitle->getArticleID();
2662
2663 $tlTemplates = array();
2664
2665 $dbr = wfGetDB( DB_SLAVE );
2666 $res = $dbr->select( array( 'templatelinks' ),
2667 array( 'tl_namespace', 'tl_title' ),
2668 array( 'tl_from' => $id ),
2669 __METHOD__
2670 );
2671
2672 foreach ( $res as $row ) {
2673 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2674 }
2675
2676 # Get templates from parser output.
2677 $poTemplates = array();
2678 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2679 foreach ( $templates as $dbk => $id ) {
2680 $poTemplates["$ns:$dbk"] = true;
2681 }
2682 }
2683
2684 # Get the diff
2685 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2686
2687 if ( count( $templates_diff ) > 0 ) {
2688 # Whee, link updates time.
2689 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
2690 $u->doUpdate();
2691 }
2692 }
2693
2694 /**
2695 * @deprecated since 1.18
2696 */
2697 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2698 global $wgUser;
2699 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2700 }
2701
2702 /**
2703 * @deprecated since 1.18
2704 */
2705 public function viewUpdates() {
2706 global $wgUser;
2707 return $this->doViewUpdates( $wgUser );
2708 }
2709
2710 /**
2711 * @deprecated since 1.18
2712 */
2713 public function useParserCache( $oldid ) {
2714 global $wgUser;
2715 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
2716 }
2717 }
2718
2719 class PoolWorkArticleView extends PoolCounterWork {
2720
2721 /**
2722 * @var Page
2723 */
2724 private $page;
2725
2726 /**
2727 * @var string
2728 */
2729 private $cacheKey;
2730
2731 /**
2732 * @var integer
2733 */
2734 private $revid;
2735
2736 /**
2737 * @var ParserOptions
2738 */
2739 private $parserOptions;
2740
2741 /**
2742 * @var string|null
2743 */
2744 private $text;
2745
2746 /**
2747 * @var ParserOutput|false
2748 */
2749 private $parserOutput = false;
2750
2751 /**
2752 * @var bool
2753 */
2754 private $isDirty = false;
2755
2756 /**
2757 * @var Status|false
2758 */
2759 private $error = false;
2760
2761 /**
2762 * Constructor
2763 *
2764 * @param $page Page
2765 * @param $revid Integer: ID of the revision being parsed
2766 * @param $useParserCache Boolean: whether to use the parser cache
2767 * @param $parserOptions parserOptions to use for the parse operation
2768 * @param $text String: text to parse or null to load it
2769 */
2770 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $text = null ) {
2771 $this->page = $page;
2772 $this->revid = $revid;
2773 $this->cacheable = $useParserCache;
2774 $this->parserOptions = $parserOptions;
2775 $this->text = $text;
2776 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
2777 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
2778 }
2779
2780 /**
2781 * Get the ParserOutput from this object, or false in case of failure
2782 *
2783 * @return ParserOutput
2784 */
2785 public function getParserOutput() {
2786 return $this->parserOutput;
2787 }
2788
2789 /**
2790 * Get whether the ParserOutput is a dirty one (i.e. expired)
2791 *
2792 * @return bool
2793 */
2794 public function getIsDirty() {
2795 return $this->isDirty;
2796 }
2797
2798 /**
2799 * Get a Status object in case of error or false otherwise
2800 *
2801 * @return Status|false
2802 */
2803 public function getError() {
2804 return $this->error;
2805 }
2806
2807 /**
2808 * @return bool
2809 */
2810 function doWork() {
2811 global $wgParser, $wgUseFileCache;
2812
2813 $isCurrent = $this->revid === $this->page->getLatest();
2814
2815 if ( $this->text !== null ) {
2816 $text = $this->text;
2817 } elseif ( $isCurrent ) {
2818 $text = $this->page->getRawText();
2819 } else {
2820 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
2821 if ( $rev === null ) {
2822 return false;
2823 }
2824 $text = $rev->getText();
2825 }
2826
2827 $time = - wfTime();
2828 $this->parserOutput = $wgParser->parse( $text, $this->page->getTitle(),
2829 $this->parserOptions, true, true, $this->revid );
2830 $time += wfTime();
2831
2832 # Timing hack
2833 if ( $time > 3 ) {
2834 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2835 $this->page->getTitle()->getPrefixedDBkey() ) );
2836 }
2837
2838 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
2839 ParserCache::singleton()->save( $this->parserOutput, $this->page, $this->parserOptions );
2840 }
2841
2842 // Make sure file cache is not used on uncacheable content.
2843 // Output that has magic words in it can still use the parser cache
2844 // (if enabled), though it will generally expire sooner.
2845 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
2846 $wgUseFileCache = false;
2847 }
2848
2849 if ( $isCurrent ) {
2850 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
2851 }
2852
2853 return true;
2854 }
2855
2856 /**
2857 * @return bool
2858 */
2859 function getCachedWork() {
2860 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
2861
2862 if ( $this->parserOutput === false ) {
2863 wfDebug( __METHOD__ . ": parser cache miss\n" );
2864 return false;
2865 } else {
2866 wfDebug( __METHOD__ . ": parser cache hit\n" );
2867 return true;
2868 }
2869 }
2870
2871 /**
2872 * @return bool
2873 */
2874 function fallback() {
2875 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
2876
2877 if ( $this->parserOutput === false ) {
2878 wfDebugLog( 'dirty', "dirty missing\n" );
2879 wfDebug( __METHOD__ . ": no dirty cache\n" );
2880 return false;
2881 } else {
2882 wfDebug( __METHOD__ . ": sending dirty output\n" );
2883 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2884 $this->isDirty = true;
2885 return true;
2886 }
2887 }
2888
2889 /**
2890 * @param $status Status
2891 */
2892 function error( $status ) {
2893 $this->error = $status;
2894 return false;
2895 }
2896 }