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