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