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