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