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