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