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