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