Merge branch 'Wikidata' of ssh://review/mediawiki/core into Wikidata
[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 if ( !$old_content ) $old_content = null;
1379 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1380 }
1381
1382 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1383 $serialized = $editInfo->pst;
1384 $content = $editInfo->pstContent;
1385 $newsize = $content->getSize();
1386
1387 $dbw = wfGetDB( DB_MASTER );
1388 $now = wfTimestampNow();
1389 $this->mTimestamp = $now;
1390
1391 if ( $flags & EDIT_UPDATE ) {
1392 # Update article, but only if changed.
1393 $status->value['new'] = false;
1394
1395 if ( !$oldid ) {
1396 # Article gone missing
1397 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1398 $status->fatal( 'edit-gone-missing' );
1399
1400 wfProfileOut( __METHOD__ );
1401 return $status;
1402 }
1403
1404 # Make sure the revision is either completely inserted or not inserted at all
1405 if ( !$wgDBtransactions ) {
1406 $userAbort = ignore_user_abort( true );
1407 }
1408
1409 $revision = new Revision( array(
1410 'page' => $this->getId(),
1411 'comment' => $summary,
1412 'minor_edit' => $isminor,
1413 'text' => $serialized,
1414 'len' => $newsize,
1415 'parent_id' => $oldid,
1416 'user' => $user->getId(),
1417 'user_text' => $user->getName(),
1418 'timestamp' => $now,
1419 'content_model' => $content->getModelName(),
1420 'content_format' => $serialisation_format,
1421 ) );
1422
1423 $changed = !$content->equals( $old_content );
1424
1425 if ( $changed ) {
1426 $dbw->begin();
1427 $revisionId = $revision->insertOn( $dbw );
1428
1429 # Update page
1430 #
1431 # Note that we use $this->mLatest instead of fetching a value from the master DB
1432 # during the course of this function. This makes sure that EditPage can detect
1433 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1434 # before this function is called. A previous function used a separate query, this
1435 # creates a window where concurrent edits can cause an ignored edit conflict.
1436 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1437
1438 if ( !$ok ) {
1439 /* Belated edit conflict! Run away!! */
1440 $status->fatal( 'edit-conflict' );
1441
1442 # Delete the invalid revision if the DB is not transactional
1443 if ( !$wgDBtransactions ) {
1444 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1445 }
1446
1447 $revisionId = 0;
1448 $dbw->rollback();
1449 } else {
1450 global $wgUseRCPatrol;
1451 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1452 # Update recentchanges
1453 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1454 # Mark as patrolled if the user can do so
1455 $patrolled = $wgUseRCPatrol && !count(
1456 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1457 # Add RC row to the DB
1458 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1459 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1460 $revisionId, $patrolled
1461 );
1462
1463 # Log auto-patrolled edits
1464 if ( $patrolled ) {
1465 PatrolLog::record( $rc, true );
1466 }
1467 }
1468 $user->incEditCount();
1469 $dbw->commit();
1470 }
1471 } else {
1472 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1473 // related variables correctly
1474 $revision->setId( $this->getLatest() );
1475 }
1476
1477 if ( !$wgDBtransactions ) {
1478 ignore_user_abort( $userAbort );
1479 }
1480
1481 // Now that ignore_user_abort is restored, we can respond to fatal errors
1482 if ( !$status->isOK() ) {
1483 wfProfileOut( __METHOD__ );
1484 return $status;
1485 }
1486
1487 # Update links tables, site stats, etc.
1488 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1489 'oldcountable' => $oldcountable ) );
1490
1491 if ( !$changed ) {
1492 $status->warning( 'edit-no-change' );
1493 $revision = null;
1494 // Update page_touched, this is usually implicit in the page update
1495 // Other cache updates are done in onArticleEdit()
1496 $this->mTitle->invalidateCache();
1497 }
1498 } else {
1499 # Create new article
1500 $status->value['new'] = true;
1501
1502 $dbw->begin();
1503
1504 # Add the page record; stake our claim on this title!
1505 # This will return false if the article already exists
1506 $newid = $this->insertOn( $dbw );
1507
1508 if ( $newid === false ) {
1509 $dbw->rollback();
1510 $status->fatal( 'edit-already-exists' );
1511
1512 wfProfileOut( __METHOD__ );
1513 return $status;
1514 }
1515
1516 # Save the revision text...
1517 $revision = new Revision( array(
1518 'page' => $newid,
1519 'comment' => $summary,
1520 'minor_edit' => $isminor,
1521 'text' => $serialized,
1522 'len' => $newsize,
1523 'user' => $user->getId(),
1524 'user_text' => $user->getName(),
1525 'timestamp' => $now,
1526 'content_model' => $content->getModelName(),
1527 'content_format' => $serialisation_format,
1528 ) );
1529 $revisionId = $revision->insertOn( $dbw );
1530
1531 # Update the page record with revision data
1532 $this->updateRevisionOn( $dbw, $revision, 0 );
1533
1534 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1535
1536 # Update recentchanges
1537 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1538 global $wgUseRCPatrol, $wgUseNPPatrol;
1539
1540 # Mark as patrolled if the user can do so
1541 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1542 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1543 # Add RC row to the DB
1544 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1545 '', $content->getSize(), $revisionId, $patrolled );
1546
1547 # Log auto-patrolled edits
1548 if ( $patrolled ) {
1549 PatrolLog::record( $rc, true );
1550 }
1551 }
1552 $user->incEditCount();
1553 $dbw->commit();
1554
1555 # Update links, etc.
1556 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1557
1558 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1559 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1560
1561 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1562 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1563 }
1564
1565 # Do updates right now unless deferral was requested
1566 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1567 DeferredUpdates::doUpdates();
1568 }
1569
1570 // Return the new revision (or null) to the caller
1571 $status->value['revision'] = $revision;
1572
1573 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary, #FIXME: deprecate legacy hook
1574 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1575
1576 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary, #FIXME: document new hook
1577 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1578
1579 # Promote user to any groups they meet the criteria for
1580 $user->addAutopromoteOnceGroups( 'onEdit' );
1581
1582 wfProfileOut( __METHOD__ );
1583 return $status;
1584 }
1585
1586 /**
1587 * Get parser options suitable for rendering the primary article wikitext
1588 * @param User|string $user User object or 'canonical'
1589 * @return ParserOptions
1590 */
1591 public function makeParserOptions( $user ) {
1592 global $wgContLang;
1593 if ( $user instanceof User ) { // settings per user (even anons)
1594 $options = ParserOptions::newFromUser( $user );
1595 } else { // canonical settings
1596 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
1597 }
1598 $options->enableLimitReport(); // show inclusion/loop reports
1599 $options->setTidy( true ); // fix bad HTML
1600 return $options;
1601 }
1602
1603 /**
1604 * Prepare text which is about to be saved.
1605 * Returns a stdclass with source, pst and output members
1606 * @deprecated in 1.20: use prepareContentForEdit instead.
1607 */
1608 public function prepareTextForEdit( $text, $revid = null, User $user = null ) { #FIXME: use prepareContentForEdit() instead #XXX: who uses this?!
1609 #TODO: log use of deprecated function
1610 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1611 return $this->prepareContentForEdit( $content, $revid , $user );
1612 }
1613
1614 /**
1615 * Prepare content which is about to be saved.
1616 * Returns a stdclass with source, pst and output members
1617 *
1618 * @param \Content $content
1619 * @param null $revid
1620 * @param null|\User $user
1621 * @param null $serialization_format
1622 * @return bool|object
1623 */
1624 public function prepareContentForEdit( Content $content, $revid = null, User $user = null, $serialization_format = null ) { #FIXME: use this #XXX: really public?!
1625 global $wgParser, $wgContLang, $wgUser;
1626 $user = is_null( $user ) ? $wgUser : $user;
1627 // @TODO fixme: check $user->getId() here???
1628
1629 if ( $this->mPreparedEdit
1630 && $this->mPreparedEdit->newContent
1631 && $this->mPreparedEdit->newContent->equals( $content )
1632 && $this->mPreparedEdit->revid == $revid
1633 && $this->mPreparedEdit->format == $serialization_format
1634 #XXX: also check $user here?
1635 ) {
1636 // Already prepared
1637 return $this->mPreparedEdit;
1638 }
1639
1640 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
1641 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1642
1643 $edit = (object)array();
1644 $edit->revid = $revid;
1645
1646 $edit->pstContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
1647 $edit->pst = $edit->pstContent->serialize( $serialization_format );
1648 $edit->format = $serialization_format;
1649
1650 $edit->popts = $this->makeParserOptions( 'canonical' );
1651 $edit->output = $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts );
1652
1653 $edit->newContent = $content;
1654 $edit->oldContent = $this->getContent( Revision::RAW );
1655
1656 $edit->newText = ContentHandler::getContentText( $edit->newContent ); #FIXME: B/C only! don't use this field!
1657 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : ''; #FIXME: B/C only! don't use this field!
1658
1659 $this->mPreparedEdit = $edit;
1660
1661 return $edit;
1662 }
1663
1664 /**
1665 * Do standard deferred updates after page edit.
1666 * Update links tables, site stats, search index and message cache.
1667 * Purges pages that include this page if the text was changed here.
1668 * Every 100th edit, prune the recent changes table.
1669 *
1670 * @private
1671 * @param $revision Revision object
1672 * @param $user User object that did the revision
1673 * @param $options Array of options, following indexes are used:
1674 * - changed: boolean, whether the revision changed the content (default true)
1675 * - created: boolean, whether the revision created the page (default false)
1676 * - oldcountable: boolean or null (default null):
1677 * - boolean: whether the page was counted as an article before that
1678 * revision, only used in changed is true and created is false
1679 * - null: don't change the article count
1680 */
1681 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
1682 global $wgEnableParserCache;
1683
1684 wfProfileIn( __METHOD__ );
1685
1686 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1687 $content = $revision->getContent();
1688
1689 # Parse the text
1690 # Be careful not to double-PST: $text is usually already PST-ed once
1691 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
1692 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
1693 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1694 } else {
1695 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
1696 $editInfo = $this->mPreparedEdit;
1697 }
1698
1699 # Save it to the parser cache
1700 if ( $wgEnableParserCache ) {
1701 $parserCache = ParserCache::singleton();
1702 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
1703 }
1704
1705 # Update the links tables and other secondary data
1706 $updates = $editInfo->output->getLinksUpdateAndOtherUpdates( $this->mTitle );
1707 SecondaryDataUpdate::runUpdates( $updates );
1708
1709 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1710
1711 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1712 if ( 0 == mt_rand( 0, 99 ) ) {
1713 // Flush old entries from the `recentchanges` table; we do this on
1714 // random requests so as to avoid an increase in writes for no good reason
1715 global $wgRCMaxAge;
1716
1717 $dbw = wfGetDB( DB_MASTER );
1718 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1719 $dbw->delete(
1720 'recentchanges',
1721 array( "rc_timestamp < '$cutoff'" ),
1722 __METHOD__
1723 );
1724 }
1725 }
1726
1727 if ( !$this->mTitle->exists() ) {
1728 wfProfileOut( __METHOD__ );
1729 return;
1730 }
1731
1732 $id = $this->getId();
1733 $title = $this->mTitle->getPrefixedDBkey();
1734 $shortTitle = $this->mTitle->getDBkey();
1735
1736 if ( !$options['changed'] ) {
1737 $good = 0;
1738 $total = 0;
1739 } elseif ( $options['created'] ) {
1740 $good = (int)$this->isCountable( $editInfo );
1741 $total = 1;
1742 } elseif ( $options['oldcountable'] !== null ) {
1743 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1744 $total = 0;
1745 } else {
1746 $good = 0;
1747 $total = 0;
1748 }
1749
1750 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1751 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) );
1752
1753 # If this is another user's talk page, update newtalk.
1754 # Don't do this if $options['changed'] = false (null-edits) nor if
1755 # it's a minor edit and the user doesn't want notifications for those.
1756 if ( $options['changed']
1757 && $this->mTitle->getNamespace() == NS_USER_TALK
1758 && $shortTitle != $user->getTitleKey()
1759 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1760 ) {
1761 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1762 $other = User::newFromName( $shortTitle, false );
1763 if ( !$other ) {
1764 wfDebug( __METHOD__ . ": invalid username\n" );
1765 } elseif ( User::isIP( $shortTitle ) ) {
1766 // An anonymous user
1767 $other->setNewtalk( true );
1768 } elseif ( $other->isLoggedIn() ) {
1769 $other->setNewtalk( true );
1770 } else {
1771 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
1772 }
1773 }
1774 }
1775
1776 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1777 $msgtext = ContentHandler::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
1778 if ( $msgtext === false || $msgtext === null ) $msgtext = '';
1779
1780 MessageCache::singleton()->replace( $shortTitle, $msgtext );
1781 }
1782
1783 if( $options['created'] ) {
1784 self::onArticleCreate( $this->mTitle );
1785 } else {
1786 self::onArticleEdit( $this->mTitle );
1787 }
1788
1789 wfProfileOut( __METHOD__ );
1790 }
1791
1792 /**
1793 * Edit an article without doing all that other stuff
1794 * The article must already exist; link tables etc
1795 * are not updated, caches are not flushed.
1796 *
1797 * @param $text String: text submitted
1798 * @param $user User The relevant user
1799 * @param $comment String: comment submitted
1800 * @param $minor Boolean: whereas it's a minor modification
1801 */
1802 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
1803 #TODO: log use of deprecated function
1804 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1805 return $this->doQuickEdit( $content, $user, $comment , $minor );
1806 }
1807
1808 /**
1809 * Edit an article without doing all that other stuff
1810 * The article must already exist; link tables etc
1811 * are not updated, caches are not flushed.
1812 *
1813 * @param $content Content: content submitted
1814 * @param $user User The relevant user
1815 * @param $comment String: comment submitted
1816 * @param $serialisation_format String: format for storing the content in the database
1817 * @param $minor Boolean: whereas it's a minor modification
1818 */
1819 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = 0, $serialisation_format = null ) {
1820 wfProfileIn( __METHOD__ );
1821
1822 $serialized = $content->serialize( $serialisation_format );
1823
1824 $dbw = wfGetDB( DB_MASTER );
1825 $revision = new Revision( array(
1826 'page' => $this->getId(),
1827 'text' => $serialized,
1828 'length' => $content->getSize(),
1829 'comment' => $comment,
1830 'minor_edit' => $minor ? 1 : 0,
1831 ) );
1832 $revision->insertOn( $dbw );
1833 $this->updateRevisionOn( $dbw, $revision );
1834
1835 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1836
1837 wfProfileOut( __METHOD__ );
1838 }
1839
1840 /**
1841 * Update the article's restriction field, and leave a log entry.
1842 * This works for protection both existing and non-existing pages.
1843 *
1844 * @param $limit Array: set of restriction keys
1845 * @param $reason String
1846 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1847 * @param $expiry Array: per restriction type expiration
1848 * @param $user User The user updating the restrictions
1849 * @return bool true on success
1850 */
1851 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
1852 global $wgContLang;
1853
1854 if ( wfReadOnly() ) {
1855 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
1856 }
1857
1858 $restrictionTypes = $this->mTitle->getRestrictionTypes();
1859
1860 $id = $this->mTitle->getArticleID();
1861
1862 if ( !$cascade ) {
1863 $cascade = false;
1864 }
1865
1866 // Take this opportunity to purge out expired restrictions
1867 Title::purgeExpiredRestrictions();
1868
1869 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1870 # we expect a single selection, but the schema allows otherwise.
1871 $isProtected = false;
1872 $protect = false;
1873 $changed = false;
1874
1875 $dbw = wfGetDB( DB_MASTER );
1876
1877 foreach ( $restrictionTypes as $action ) {
1878 if ( !isset( $expiry[$action] ) ) {
1879 $expiry[$action] = $dbw->getInfinity();
1880 }
1881 if ( !isset( $limit[$action] ) ) {
1882 $limit[$action] = '';
1883 } elseif ( $limit[$action] != '' ) {
1884 $protect = true;
1885 }
1886
1887 # Get current restrictions on $action
1888 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
1889 if ( $current != '' ) {
1890 $isProtected = true;
1891 }
1892
1893 if ( $limit[$action] != $current ) {
1894 $changed = true;
1895 } elseif ( $limit[$action] != '' ) {
1896 # Only check expiry change if the action is actually being
1897 # protected, since expiry does nothing on an not-protected
1898 # action.
1899 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1900 $changed = true;
1901 }
1902 }
1903 }
1904
1905 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
1906 $changed = true;
1907 }
1908
1909 # If nothing's changed, do nothing
1910 if ( !$changed ) {
1911 return Status::newGood();
1912 }
1913
1914 if ( !$protect ) { # No protection at all means unprotection
1915 $revCommentMsg = 'unprotectedarticle';
1916 $logAction = 'unprotect';
1917 } elseif ( $isProtected ) {
1918 $revCommentMsg = 'modifiedarticleprotection';
1919 $logAction = 'modify';
1920 } else {
1921 $revCommentMsg = 'protectedarticle';
1922 $logAction = 'protect';
1923 }
1924
1925 $encodedExpiry = array();
1926 $protectDescription = '';
1927 foreach ( $limit as $action => $restrictions ) {
1928 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1929 if ( $restrictions != '' ) {
1930 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1931 if ( $encodedExpiry[$action] != 'infinity' ) {
1932 $protectDescription .= wfMsgForContent( 'protect-expiring',
1933 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1934 $wgContLang->date( $expiry[$action], false, false ) ,
1935 $wgContLang->time( $expiry[$action], false, false ) );
1936 } else {
1937 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1938 }
1939
1940 $protectDescription .= ') ';
1941 }
1942 }
1943 $protectDescription = trim( $protectDescription );
1944
1945 if ( $id ) { # Protection of existing page
1946 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1947 return Status::newGood();
1948 }
1949
1950 # Only restrictions with the 'protect' right can cascade...
1951 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1952 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1953
1954 # The schema allows multiple restrictions
1955 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1956 $cascade = false;
1957 }
1958
1959 # Update restrictions table
1960 foreach ( $limit as $action => $restrictions ) {
1961 if ( $restrictions != '' ) {
1962 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1963 array( 'pr_page' => $id,
1964 'pr_type' => $action,
1965 'pr_level' => $restrictions,
1966 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
1967 'pr_expiry' => $encodedExpiry[$action]
1968 ),
1969 __METHOD__
1970 );
1971 } else {
1972 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1973 'pr_type' => $action ), __METHOD__ );
1974 }
1975 }
1976
1977 # Prepare a null revision to be added to the history
1978 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle->getPrefixedText() ) );
1979 if ( $reason ) {
1980 $editComment .= ": $reason";
1981 }
1982 if ( $protectDescription ) {
1983 $editComment .= " ($protectDescription)";
1984 }
1985 if ( $cascade ) {
1986 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1987 }
1988
1989 # Insert a null revision
1990 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1991 $nullRevId = $nullRevision->insertOn( $dbw );
1992
1993 $latest = $this->getLatest();
1994 # Update page record
1995 $dbw->update( 'page',
1996 array( /* SET */
1997 'page_touched' => $dbw->timestamp(),
1998 'page_restrictions' => '',
1999 'page_latest' => $nullRevId
2000 ), array( /* WHERE */
2001 'page_id' => $id
2002 ), __METHOD__
2003 );
2004
2005 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2006 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2007 } else { # Protection of non-existing page (also known as "title protection")
2008 # Cascade protection is meaningless in this case
2009 $cascade = false;
2010
2011 if ( $limit['create'] != '' ) {
2012 $dbw->replace( 'protected_titles',
2013 array( array( 'pt_namespace', 'pt_title' ) ),
2014 array(
2015 'pt_namespace' => $this->mTitle->getNamespace(),
2016 'pt_title' => $this->mTitle->getDBkey(),
2017 'pt_create_perm' => $limit['create'],
2018 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2019 'pt_expiry' => $encodedExpiry['create'],
2020 'pt_user' => $user->getId(),
2021 'pt_reason' => $reason,
2022 ), __METHOD__
2023 );
2024 } else {
2025 $dbw->delete( 'protected_titles',
2026 array(
2027 'pt_namespace' => $this->mTitle->getNamespace(),
2028 'pt_title' => $this->mTitle->getDBkey()
2029 ), __METHOD__
2030 );
2031 }
2032 }
2033
2034 $this->mTitle->flushRestrictions();
2035
2036 if ( $logAction == 'unprotect' ) {
2037 $logParams = array();
2038 } else {
2039 $logParams = array( $protectDescription, $cascade ? 'cascade' : '' );
2040 }
2041
2042 # Update the protection log
2043 $log = new LogPage( 'protect' );
2044 $log->addEntry( $logAction, $this->mTitle, trim( $reason ), $logParams, $user );
2045
2046 return Status::newGood();
2047 }
2048
2049 /**
2050 * Take an array of page restrictions and flatten it to a string
2051 * suitable for insertion into the page_restrictions field.
2052 * @param $limit Array
2053 * @return String
2054 */
2055 protected static function flattenRestrictions( $limit ) {
2056 if ( !is_array( $limit ) ) {
2057 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2058 }
2059
2060 $bits = array();
2061 ksort( $limit );
2062
2063 foreach ( $limit as $action => $restrictions ) {
2064 if ( $restrictions != '' ) {
2065 $bits[] = "$action=$restrictions";
2066 }
2067 }
2068
2069 return implode( ':', $bits );
2070 }
2071
2072 /**
2073 * Back-end article deletion
2074 * Deletes the article with database consistency, writes logs, purges caches
2075 *
2076 * @param $reason string delete reason for deletion log
2077 * @param $suppress bitfield
2078 * Revision::DELETED_TEXT
2079 * Revision::DELETED_COMMENT
2080 * Revision::DELETED_USER
2081 * Revision::DELETED_RESTRICTED
2082 * @param $id int article ID
2083 * @param $commit boolean defaults to true, triggers transaction end
2084 * @param &$errors Array of errors to append to
2085 * @param $user User The relevant user
2086 * @return boolean true if successful
2087 */
2088 public function doDeleteArticle(
2089 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2090 ) {
2091 global $wgUser;
2092 $user = is_null( $user ) ? $wgUser : $user;
2093
2094 wfDebug( __METHOD__ . "\n" );
2095
2096 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2097 return false;
2098 }
2099 $dbw = wfGetDB( DB_MASTER );
2100 $t = $this->mTitle->getDBkey();
2101 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
2102
2103 if ( $t === '' || $id == 0 ) {
2104 return false;
2105 }
2106
2107 // Bitfields to further suppress the content
2108 if ( $suppress ) {
2109 $bitfield = 0;
2110 // This should be 15...
2111 $bitfield |= Revision::DELETED_TEXT;
2112 $bitfield |= Revision::DELETED_COMMENT;
2113 $bitfield |= Revision::DELETED_USER;
2114 $bitfield |= Revision::DELETED_RESTRICTED;
2115 } else {
2116 $bitfield = 'rev_deleted';
2117 }
2118
2119 $dbw->begin();
2120 // For now, shunt the revision data into the archive table.
2121 // Text is *not* removed from the text table; bulk storage
2122 // is left intact to avoid breaking block-compression or
2123 // immutable storage schemes.
2124 //
2125 // For backwards compatibility, note that some older archive
2126 // table entries will have ar_text and ar_flags fields still.
2127 //
2128 // In the future, we may keep revisions and mark them with
2129 // the rev_deleted field, which is reserved for this purpose.
2130 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2131 array(
2132 'ar_namespace' => 'page_namespace',
2133 'ar_title' => 'page_title',
2134 'ar_comment' => 'rev_comment',
2135 'ar_user' => 'rev_user',
2136 'ar_user_text' => 'rev_user_text',
2137 'ar_timestamp' => 'rev_timestamp',
2138 'ar_minor_edit' => 'rev_minor_edit',
2139 'ar_rev_id' => 'rev_id',
2140 'ar_parent_id' => 'rev_parent_id',
2141 'ar_text_id' => 'rev_text_id',
2142 'ar_text' => '\'\'', // Be explicit to appease
2143 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2144 'ar_len' => 'rev_len',
2145 'ar_page_id' => 'page_id',
2146 'ar_deleted' => $bitfield,
2147 'ar_sha1' => 'rev_content_model',
2148 'ar_content_format' => 'rev_content_format',
2149 'ar_content_format' => 'rev_sha1'
2150 ), array(
2151 'page_id' => $id,
2152 'page_id = rev_page'
2153 ), __METHOD__
2154 );
2155
2156 # Now that it's safely backed up, delete it
2157 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2158 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2159
2160 if ( !$ok ) {
2161 $dbw->rollback();
2162 return false;
2163 }
2164
2165 $this->doDeleteUpdates( $id );
2166
2167 # Log the deletion, if the page was suppressed, log it at Oversight instead
2168 $logtype = $suppress ? 'suppress' : 'delete';
2169
2170 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2171 $logEntry->setPerformer( $user );
2172 $logEntry->setTarget( $this->mTitle );
2173 $logEntry->setComment( $reason );
2174 $logid = $logEntry->insert();
2175 $logEntry->publish( $logid );
2176
2177 if ( $commit ) {
2178 $dbw->commit();
2179 }
2180
2181 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2182 return true;
2183 }
2184
2185 /**
2186 * Do some database updates after deletion
2187 *
2188 * @param $id Int: page_id value of the page being deleted
2189 */
2190 public function doDeleteUpdates( $id ) {
2191 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2192
2193 $dbw = wfGetDB( DB_MASTER );
2194
2195 # Delete restrictions for it
2196 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2197
2198 # Fix category table counts
2199 $cats = array();
2200 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2201
2202 foreach ( $res as $row ) {
2203 $cats [] = $row->cl_to;
2204 }
2205
2206 $this->updateCategoryCounts( array(), $cats );
2207
2208 # If using cascading deletes, we can skip some explicit deletes
2209 if ( !$dbw->cascadingDeletes() ) {
2210 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2211
2212 # Delete outgoing links
2213 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__ );
2214 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__ );
2215 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__ );
2216 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__ );
2217 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__ );
2218 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__ );
2219 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__ );
2220 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__ );
2221 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__ );
2222 }
2223
2224 # If using cleanup triggers, we can skip some manual deletes
2225 if ( !$dbw->cleanupTriggers() ) {
2226 # Clean up recentchanges entries...
2227 $dbw->delete( 'recentchanges',
2228 array( 'rc_type != ' . RC_LOG,
2229 'rc_namespace' => $this->mTitle->getNamespace(),
2230 'rc_title' => $this->mTitle->getDBkey() ),
2231 __METHOD__ );
2232 $dbw->delete( 'recentchanges',
2233 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
2234 __METHOD__ );
2235 }
2236
2237 # Clear caches
2238 self::onArticleDelete( $this->mTitle );
2239
2240 # Clear the cached article id so the interface doesn't act like we exist
2241 $this->mTitle->resetArticleID( 0 );
2242 }
2243
2244 /**
2245 * Roll back the most recent consecutive set of edits to a page
2246 * from the same user; fails if there are no eligible edits to
2247 * roll back to, e.g. user is the sole contributor. This function
2248 * performs permissions checks on $user, then calls commitRollback()
2249 * to do the dirty work
2250 *
2251 * @todo: seperate the business/permission stuff out from backend code
2252 *
2253 * @param $fromP String: Name of the user whose edits to rollback.
2254 * @param $summary String: Custom summary. Set to default summary if empty.
2255 * @param $token String: Rollback token.
2256 * @param $bot Boolean: If true, mark all reverted edits as bot.
2257 *
2258 * @param $resultDetails Array: contains result-specific array of additional values
2259 * 'alreadyrolled' : 'current' (rev)
2260 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2261 *
2262 * @param $user User The user performing the rollback
2263 * @return array of errors, each error formatted as
2264 * array(messagekey, param1, param2, ...).
2265 * On success, the array is empty. This array can also be passed to
2266 * OutputPage::showPermissionsErrorPage().
2267 */
2268 public function doRollback(
2269 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2270 ) {
2271 $resultDetails = null;
2272
2273 # Check permissions
2274 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2275 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2276 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2277
2278 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2279 $errors[] = array( 'sessionfailure' );
2280 }
2281
2282 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2283 $errors[] = array( 'actionthrottledtext' );
2284 }
2285
2286 # If there were errors, bail out now
2287 if ( !empty( $errors ) ) {
2288 return $errors;
2289 }
2290
2291 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2292 }
2293
2294 /**
2295 * Backend implementation of doRollback(), please refer there for parameter
2296 * and return value documentation
2297 *
2298 * NOTE: This function does NOT check ANY permissions, it just commits the
2299 * rollback to the DB. Therefore, you should only call this function direct-
2300 * ly if you want to use custom permissions checks. If you don't, use
2301 * doRollback() instead.
2302 * @param $fromP String: Name of the user whose edits to rollback.
2303 * @param $summary String: Custom summary. Set to default summary if empty.
2304 * @param $bot Boolean: If true, mark all reverted edits as bot.
2305 *
2306 * @param $resultDetails Array: contains result-specific array of additional values
2307 * @param $guser User The user performing the rollback
2308 */
2309 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2310 global $wgUseRCPatrol, $wgContLang;
2311
2312 $dbw = wfGetDB( DB_MASTER );
2313
2314 if ( wfReadOnly() ) {
2315 return array( array( 'readonlytext' ) );
2316 }
2317
2318 # Get the last editor
2319 $current = Revision::newFromTitle( $this->mTitle );
2320 if ( is_null( $current ) ) {
2321 # Something wrong... no page?
2322 return array( array( 'notanarticle' ) );
2323 }
2324
2325 $from = str_replace( '_', ' ', $fromP );
2326 # User name given should match up with the top revision.
2327 # If the user was deleted then $from should be empty.
2328 if ( $from != $current->getUserText() ) {
2329 $resultDetails = array( 'current' => $current );
2330 return array( array( 'alreadyrolled',
2331 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2332 htmlspecialchars( $fromP ),
2333 htmlspecialchars( $current->getUserText() )
2334 ) );
2335 }
2336
2337 # Get the last edit not by this guy...
2338 # Note: these may not be public values
2339 $user = intval( $current->getRawUser() );
2340 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2341 $s = $dbw->selectRow( 'revision',
2342 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2343 array( 'rev_page' => $current->getPage(),
2344 "rev_user != {$user} OR rev_user_text != {$user_text}"
2345 ), __METHOD__,
2346 array( 'USE INDEX' => 'page_timestamp',
2347 'ORDER BY' => 'rev_timestamp DESC' )
2348 );
2349 if ( $s === false ) {
2350 # No one else ever edited this page
2351 return array( array( 'cantrollback' ) );
2352 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2353 # Only admins can see this text
2354 return array( array( 'notvisiblerev' ) );
2355 }
2356
2357 $set = array();
2358 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2359 # Mark all reverted edits as bot
2360 $set['rc_bot'] = 1;
2361 }
2362
2363 if ( $wgUseRCPatrol ) {
2364 # Mark all reverted edits as patrolled
2365 $set['rc_patrolled'] = 1;
2366 }
2367
2368 if ( count( $set ) ) {
2369 $dbw->update( 'recentchanges', $set,
2370 array( /* WHERE */
2371 'rc_cur_id' => $current->getPage(),
2372 'rc_user_text' => $current->getUserText(),
2373 "rc_timestamp > '{$s->rev_timestamp}'",
2374 ), __METHOD__
2375 );
2376 }
2377
2378 # Generate the edit summary if necessary
2379 $target = Revision::newFromId( $s->rev_id );
2380 if ( empty( $summary ) ) {
2381 if ( $from == '' ) { // no public user name
2382 $summary = wfMsgForContent( 'revertpage-nouser' );
2383 } else {
2384 $summary = wfMsgForContent( 'revertpage' );
2385 }
2386 }
2387
2388 # Allow the custom summary to use the same args as the default message
2389 $args = array(
2390 $target->getUserText(), $from, $s->rev_id,
2391 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2392 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2393 );
2394 $summary = wfMsgReplaceArgs( $summary, $args );
2395
2396 # Save
2397 $flags = EDIT_UPDATE;
2398
2399 if ( $guser->isAllowed( 'minoredit' ) ) {
2400 $flags |= EDIT_MINOR;
2401 }
2402
2403 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2404 $flags |= EDIT_FORCE_BOT;
2405 }
2406
2407 # Actually store the edit
2408 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2409 if ( !empty( $status->value['revision'] ) ) {
2410 $revId = $status->value['revision']->getId();
2411 } else {
2412 $revId = false;
2413 }
2414
2415 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2416
2417 $resultDetails = array(
2418 'summary' => $summary,
2419 'current' => $current,
2420 'target' => $target,
2421 'newid' => $revId
2422 );
2423
2424 return array();
2425 }
2426
2427 /**
2428 * The onArticle*() functions are supposed to be a kind of hooks
2429 * which should be called whenever any of the specified actions
2430 * are done.
2431 *
2432 * This is a good place to put code to clear caches, for instance.
2433 *
2434 * This is called on page move and undelete, as well as edit
2435 *
2436 * @param $title Title object
2437 */
2438 public static function onArticleCreate( $title ) {
2439 # Update existence markers on article/talk tabs...
2440 if ( $title->isTalkPage() ) {
2441 $other = $title->getSubjectPage();
2442 } else {
2443 $other = $title->getTalkPage();
2444 }
2445
2446 $other->invalidateCache();
2447 $other->purgeSquid();
2448
2449 $title->touchLinks();
2450 $title->purgeSquid();
2451 $title->deleteTitleProtection();
2452 }
2453
2454 /**
2455 * Clears caches when article is deleted
2456 *
2457 * @param $title Title
2458 */
2459 public static function onArticleDelete( $title ) {
2460 # Update existence markers on article/talk tabs...
2461 if ( $title->isTalkPage() ) {
2462 $other = $title->getSubjectPage();
2463 } else {
2464 $other = $title->getTalkPage();
2465 }
2466
2467 $other->invalidateCache();
2468 $other->purgeSquid();
2469
2470 $title->touchLinks();
2471 $title->purgeSquid();
2472
2473 # File cache
2474 HTMLFileCache::clearFileCache( $title );
2475
2476 # Messages
2477 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2478 MessageCache::singleton()->replace( $title->getDBkey(), false );
2479 }
2480
2481 # Images
2482 if ( $title->getNamespace() == NS_FILE ) {
2483 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2484 $update->doUpdate();
2485 }
2486
2487 # User talk pages
2488 if ( $title->getNamespace() == NS_USER_TALK ) {
2489 $user = User::newFromName( $title->getText(), false );
2490 if ( $user ) {
2491 $user->setNewtalk( false );
2492 }
2493 }
2494
2495 # Image redirects
2496 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2497 }
2498
2499 /**
2500 * Purge caches on page update etc
2501 *
2502 * @param $title Title object
2503 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2504 */
2505 public static function onArticleEdit( $title ) {
2506 // Invalidate caches of articles which include this page
2507 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2508
2509
2510 // Invalidate the caches of all pages which redirect here
2511 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2512
2513 # Purge squid for this page only
2514 $title->purgeSquid();
2515
2516 # Clear file cache for this page only
2517 HTMLFileCache::clearFileCache( $title );
2518 }
2519
2520 /**#@-*/
2521
2522 /**
2523 * Returns a list of hidden categories this page is a member of.
2524 * Uses the page_props and categorylinks tables.
2525 *
2526 * @return Array of Title objects
2527 */
2528 public function getHiddenCategories() {
2529 $result = array();
2530 $id = $this->mTitle->getArticleID();
2531
2532 if ( $id == 0 ) {
2533 return array();
2534 }
2535
2536 $dbr = wfGetDB( DB_SLAVE );
2537 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2538 array( 'cl_to' ),
2539 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2540 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2541 __METHOD__ );
2542
2543 if ( $res !== false ) {
2544 foreach ( $res as $row ) {
2545 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2546 }
2547 }
2548
2549 return $result;
2550 }
2551
2552 /**
2553 * Return an applicable autosummary if one exists for the given edit.
2554 * @param $oldtext String: the previous text of the page.
2555 * @param $newtext String: The submitted text of the page.
2556 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2557 * @return string An appropriate autosummary, or an empty string.
2558 * @deprecated since 1.20, use ContentHandler::getAutosummary() instead
2559 */
2560 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2561 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2562
2563 $handler = ContentHandler::getForModelName( CONTENT_MODEL_WIKITEXT );
2564 $oldContent = $oldtext ? $handler->unserialize( $oldtext ) : null;
2565 $newContent = $newtext ? $handler->unserialize( $newtext ) : null;
2566
2567 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2568 }
2569
2570 /**
2571 * Auto-generates a deletion reason
2572 *
2573 * @param &$hasHistory Boolean: whether the page has a history
2574 * @return mixed String containing deletion reason or empty string, or boolean false
2575 * if no revision occurred
2576 * @deprecated since 1.20, use ContentHandler::getAutoDeleteReason() instead
2577 */
2578 public function getAutoDeleteReason( &$hasHistory ) {
2579 #NOTE: stub for backwards-compatibility.
2580
2581 $handler = ContentHandler::getForTitle( $this->getTitle() );
2582 $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2583 }
2584
2585 /**
2586 * Update all the appropriate counts in the category table, given that
2587 * we've added the categories $added and deleted the categories $deleted.
2588 *
2589 * @param $added array The names of categories that were added
2590 * @param $deleted array The names of categories that were deleted
2591 */
2592 public function updateCategoryCounts( $added, $deleted ) {
2593 $ns = $this->mTitle->getNamespace();
2594 $dbw = wfGetDB( DB_MASTER );
2595
2596 # First make sure the rows exist. If one of the "deleted" ones didn't
2597 # exist, we might legitimately not create it, but it's simpler to just
2598 # create it and then give it a negative value, since the value is bogus
2599 # anyway.
2600 #
2601 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2602 $insertCats = array_merge( $added, $deleted );
2603 if ( !$insertCats ) {
2604 # Okay, nothing to do
2605 return;
2606 }
2607
2608 $insertRows = array();
2609
2610 foreach ( $insertCats as $cat ) {
2611 $insertRows[] = array(
2612 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2613 'cat_title' => $cat
2614 );
2615 }
2616 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2617
2618 $addFields = array( 'cat_pages = cat_pages + 1' );
2619 $removeFields = array( 'cat_pages = cat_pages - 1' );
2620
2621 if ( $ns == NS_CATEGORY ) {
2622 $addFields[] = 'cat_subcats = cat_subcats + 1';
2623 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2624 } elseif ( $ns == NS_FILE ) {
2625 $addFields[] = 'cat_files = cat_files + 1';
2626 $removeFields[] = 'cat_files = cat_files - 1';
2627 }
2628
2629 if ( $added ) {
2630 $dbw->update(
2631 'category',
2632 $addFields,
2633 array( 'cat_title' => $added ),
2634 __METHOD__
2635 );
2636 }
2637
2638 if ( $deleted ) {
2639 $dbw->update(
2640 'category',
2641 $removeFields,
2642 array( 'cat_title' => $deleted ),
2643 __METHOD__
2644 );
2645 }
2646 }
2647
2648 /**
2649 * Updates cascading protections
2650 *
2651 * @param $parserOutput ParserOutput object for the current version
2652 */
2653 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
2654 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
2655 return;
2656 }
2657
2658 // templatelinks table may have become out of sync,
2659 // especially if using variable-based transclusions.
2660 // For paranoia, check if things have changed and if
2661 // so apply updates to the database. This will ensure
2662 // that cascaded protections apply as soon as the changes
2663 // are visible.
2664
2665 # Get templates from templatelinks
2666 $id = $this->mTitle->getArticleID();
2667
2668 $tlTemplates = array();
2669
2670 $dbr = wfGetDB( DB_SLAVE );
2671 $res = $dbr->select( array( 'templatelinks' ),
2672 array( 'tl_namespace', 'tl_title' ),
2673 array( 'tl_from' => $id ),
2674 __METHOD__
2675 );
2676
2677 foreach ( $res as $row ) {
2678 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2679 }
2680
2681 # Get templates from parser output.
2682 $poTemplates = array();
2683 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2684 foreach ( $templates as $dbk => $id ) {
2685 $poTemplates["$ns:$dbk"] = true;
2686 }
2687 }
2688
2689 # Get the diff
2690 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2691
2692 if ( count( $templates_diff ) > 0 ) {
2693 # Whee, link updates time.
2694 # Note: we are only interested in links here. We don't need to get other SecondaryDataUpdate items from the parser output.
2695 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
2696 $u->doUpdate();
2697 }
2698 }
2699
2700 /**
2701 * Return a list of templates used by this article.
2702 * Uses the templatelinks table
2703 *
2704 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2705 * @return Array of Title objects
2706 */
2707 public function getUsedTemplates() {
2708 return $this->mTitle->getTemplateLinksFrom();
2709 }
2710
2711 /**
2712 * Perform article updates on a special page creation.
2713 *
2714 * @param $rev Revision object
2715 *
2716 * @todo This is a shitty interface function. Kill it and replace the
2717 * other shitty functions like doEditUpdates and such so it's not needed
2718 * anymore.
2719 * @deprecated since 1.18, use doEditUpdates()
2720 */
2721 public function createUpdates( $rev ) {
2722 wfDeprecated( __METHOD__, '1.18' );
2723 global $wgUser;
2724 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2725 }
2726
2727 /**
2728 * This function is called right before saving the wikitext,
2729 * so we can do things like signatures and links-in-context.
2730 *
2731 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2732 * @param $text String article contents
2733 * @param $user User object: user doing the edit
2734 * @param $popts ParserOptions object: parser options, default options for
2735 * the user loaded if null given
2736 * @return string article contents with altered wikitext markup (signatures
2737 * converted, {{subst:}}, templates, etc.)
2738 */
2739 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
2740 global $wgParser, $wgUser;
2741
2742 wfDeprecated( __METHOD__, '1.19' );
2743
2744 $user = is_null( $user ) ? $wgUser : $user;
2745
2746 if ( $popts === null ) {
2747 $popts = ParserOptions::newFromUser( $user );
2748 }
2749
2750 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2751 }
2752
2753 /**
2754 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2755 *
2756 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2757 * @return bool
2758 */
2759 public function isBigDeletion() {
2760 wfDeprecated( __METHOD__, '1.19' );
2761 return $this->mTitle->isBigDeletion();
2762 }
2763
2764 /**
2765 * Get the approximate revision count of this page.
2766 *
2767 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2768 * @return int
2769 */
2770 public function estimateRevisionCount() {
2771 wfDeprecated( __METHOD__, '1.19' );
2772 return $this->mTitle->estimateRevisionCount();
2773 }
2774
2775 /**
2776 * Update the article's restriction field, and leave a log entry.
2777 *
2778 * @deprecated since 1.19
2779 * @param $limit Array: set of restriction keys
2780 * @param $reason String
2781 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2782 * @param $expiry Array: per restriction type expiration
2783 * @param $user User The user updating the restrictions
2784 * @return bool true on success
2785 */
2786 public function updateRestrictions(
2787 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
2788 ) {
2789 global $wgUser;
2790
2791 $user = is_null( $user ) ? $wgUser : $user;
2792
2793 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2794 }
2795
2796 /**
2797 * @deprecated since 1.18
2798 */
2799 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2800 wfDeprecated( __METHOD__, '1.18' );
2801 global $wgUser;
2802 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2803 }
2804
2805 /**
2806 * @deprecated since 1.18
2807 */
2808 public function viewUpdates() {
2809 wfDeprecated( __METHOD__, '1.18' );
2810 global $wgUser;
2811 return $this->doViewUpdates( $wgUser );
2812 }
2813
2814 /**
2815 * @deprecated since 1.18
2816 */
2817 public function useParserCache( $oldid ) {
2818 wfDeprecated( __METHOD__, '1.18' );
2819 global $wgUser;
2820 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
2821 }
2822 }
2823
2824 class PoolWorkArticleView extends PoolCounterWork {
2825
2826 /**
2827 * @var Page
2828 */
2829 private $page;
2830
2831 /**
2832 * @var string
2833 */
2834 private $cacheKey;
2835
2836 /**
2837 * @var integer
2838 */
2839 private $revid;
2840
2841 /**
2842 * @var ParserOptions
2843 */
2844 private $parserOptions;
2845
2846 /**
2847 * @var string|null
2848 */
2849 private $text;
2850
2851 /**
2852 * @var ParserOutput|false
2853 */
2854 private $parserOutput = false;
2855
2856 /**
2857 * @var bool
2858 */
2859 private $isDirty = false;
2860
2861 /**
2862 * @var Status|false
2863 */
2864 private $error = false;
2865
2866 /**
2867 * Constructor
2868 *
2869 * @param $page Page
2870 * @param $revid Integer: ID of the revision being parsed
2871 * @param $useParserCache Boolean: whether to use the parser cache
2872 * @param $parserOptions parserOptions to use for the parse operation
2873 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
2874 */
2875 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $content = null ) {
2876 if ( is_string($content) ) { #BC: old style call
2877 $modelName = $page->getRevision()->getContentModelName();
2878 $format = $page->getRevision()->getContentFormat();
2879 $content = ContentHandler::makeContent( $content, $page->getTitle(), $modelName, $format );
2880 }
2881
2882 $this->page = $page;
2883 $this->revid = $revid;
2884 $this->cacheable = $useParserCache;
2885 $this->parserOptions = $parserOptions;
2886 $this->content = $content;
2887 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
2888 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
2889 }
2890
2891 /**
2892 * Get the ParserOutput from this object, or false in case of failure
2893 *
2894 * @return ParserOutput
2895 */
2896 public function getParserOutput() {
2897 return $this->parserOutput;
2898 }
2899
2900 /**
2901 * Get whether the ParserOutput is a dirty one (i.e. expired)
2902 *
2903 * @return bool
2904 */
2905 public function getIsDirty() {
2906 return $this->isDirty;
2907 }
2908
2909 /**
2910 * Get a Status object in case of error or false otherwise
2911 *
2912 * @return Status|false
2913 */
2914 public function getError() {
2915 return $this->error;
2916 }
2917
2918 /**
2919 * @return bool
2920 */
2921 function doWork() {
2922 global $wgParser, $wgUseFileCache;
2923
2924 $isCurrent = $this->revid === $this->page->getLatest();
2925
2926 if ( $this->content !== null ) {
2927 $content = $this->content;
2928 } elseif ( $isCurrent ) {
2929 $content = $this->page->getContent( Revision::RAW ); #XXX: why use RAW audience here, and PUBLIC (default) below?
2930 } else {
2931 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
2932 if ( $rev === null ) {
2933 return false;
2934 }
2935 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
2936 }
2937
2938 $time = - wfTime();
2939 $this->parserOutput = $content->getParserOutput( $this->page->getTitle(), $this->revid, $this->parserOptions );
2940 $time += wfTime();
2941
2942 # Timing hack
2943 if ( $time > 3 ) {
2944 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2945 $this->page->getTitle()->getPrefixedDBkey() ) );
2946 }
2947
2948 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
2949 ParserCache::singleton()->save( $this->parserOutput, $this->page, $this->parserOptions );
2950 }
2951
2952 // Make sure file cache is not used on uncacheable content.
2953 // Output that has magic words in it can still use the parser cache
2954 // (if enabled), though it will generally expire sooner.
2955 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
2956 $wgUseFileCache = false;
2957 }
2958
2959 if ( $isCurrent ) {
2960 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
2961 }
2962
2963 return true;
2964 }
2965
2966 /**
2967 * @return bool
2968 */
2969 function getCachedWork() {
2970 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
2971
2972 if ( $this->parserOutput === false ) {
2973 wfDebug( __METHOD__ . ": parser cache miss\n" );
2974 return false;
2975 } else {
2976 wfDebug( __METHOD__ . ": parser cache hit\n" );
2977 return true;
2978 }
2979 }
2980
2981 /**
2982 * @return bool
2983 */
2984 function fallback() {
2985 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
2986
2987 if ( $this->parserOutput === false ) {
2988 wfDebugLog( 'dirty', "dirty missing\n" );
2989 wfDebug( __METHOD__ . ": no dirty cache\n" );
2990 return false;
2991 } else {
2992 wfDebug( __METHOD__ . ": sending dirty output\n" );
2993 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2994 $this->isDirty = true;
2995 return true;
2996 }
2997 }
2998
2999 /**
3000 * @param $status Status
3001 */
3002 function error( $status ) {
3003 $this->error = $status;
3004 return false;
3005 }
3006 }