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