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