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