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