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