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