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