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