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