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