MediaWiki REL1_32
Block.php
Go to the documentation of this file.
1<?php
26
27class Block {
29 public $mReason;
30
33
35 public $mAuto;
36
38 public $mExpiry;
39
41 public $mHideName;
42
45
47 private $mId;
48
50 private $mFromMaster;
51
53 private $mBlockEmail;
54
57
60
62 private $target;
63
66
68 private $type;
69
71 private $blocker;
72
74 private $isHardblock;
75
78
81
82 # TYPE constants
83 const TYPE_USER = 1;
84 const TYPE_IP = 2;
85 const TYPE_RANGE = 3;
86 const TYPE_AUTO = 4;
87 const TYPE_ID = 5;
88
115 function __construct( $options = [] ) {
116 $defaults = [
117 'address' => '',
118 'user' => null,
119 'by' => null,
120 'reason' => '',
121 'timestamp' => '',
122 'auto' => false,
123 'expiry' => '',
124 'anonOnly' => false,
125 'createAccount' => false,
126 'enableAutoblock' => false,
127 'hideName' => false,
128 'blockEmail' => false,
129 'allowUsertalk' => false,
130 'byText' => '',
131 'systemBlock' => null,
132 ];
133
134 if ( func_num_args() > 1 || !is_array( $options ) ) {
135 $options = array_combine(
136 array_slice( array_keys( $defaults ), 0, func_num_args() ),
137 func_get_args()
138 );
139 wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
140 }
141
142 $options += $defaults;
143
144 $this->setTarget( $options['address'] );
145
146 if ( $this->target instanceof User && $options['user'] ) {
147 # Needed for foreign users
148 $this->forcedTargetID = $options['user'];
149 }
150
151 if ( $options['by'] ) {
152 # Local user
153 $this->setBlocker( User::newFromId( $options['by'] ) );
154 } else {
155 # Foreign user
156 $this->setBlocker( $options['byText'] );
157 }
158
159 $this->mReason = $options['reason'];
160 $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
161 $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
162
163 # Boolean settings
164 $this->mAuto = (bool)$options['auto'];
165 $this->mHideName = (bool)$options['hideName'];
166 $this->isHardblock( !$options['anonOnly'] );
167 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
168
169 # Prevention measures
170 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
171 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
172 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
173
174 $this->mFromMaster = false;
175 $this->systemBlockType = $options['systemBlock'];
176 }
177
184 public static function newFromID( $id ) {
186 $blockQuery = self::getQueryInfo();
187 $res = $dbr->selectRow(
188 $blockQuery['tables'],
189 $blockQuery['fields'],
190 [ 'ipb_id' => $id ],
191 __METHOD__,
192 [],
193 $blockQuery['joins']
194 );
195 if ( $res ) {
196 return self::newFromRow( $res );
197 } else {
198 return null;
199 }
200 }
201
208 public static function selectFields() {
210
212 // If code is using this instead of self::getQueryInfo(), there's a
213 // decent chance it's going to try to directly access
214 // $row->ipb_by or $row->ipb_by_text and we can't give it
215 // useful values here once those aren't being used anymore.
216 throw new BadMethodCallException(
217 'Cannot use ' . __METHOD__
218 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
219 );
220 }
221
222 wfDeprecated( __METHOD__, '1.31' );
223 return [
224 'ipb_id',
225 'ipb_address',
226 'ipb_by',
227 'ipb_by_text',
228 'ipb_by_actor' => 'NULL',
229 'ipb_timestamp',
230 'ipb_auto',
231 'ipb_anon_only',
232 'ipb_create_account',
233 'ipb_enable_autoblock',
234 'ipb_expiry',
235 'ipb_deleted',
236 'ipb_block_email',
237 'ipb_allow_usertalk',
238 'ipb_parent_block_id',
239 ] + CommentStore::getStore()->getFields( 'ipb_reason' );
240 }
241
251 public static function getQueryInfo() {
252 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
253 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
254 return [
255 'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
256 'fields' => [
257 'ipb_id',
258 'ipb_address',
259 'ipb_timestamp',
260 'ipb_auto',
261 'ipb_anon_only',
262 'ipb_create_account',
263 'ipb_enable_autoblock',
264 'ipb_expiry',
265 'ipb_deleted',
266 'ipb_block_email',
267 'ipb_allow_usertalk',
268 'ipb_parent_block_id',
269 ] + $commentQuery['fields'] + $actorQuery['fields'],
270 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
271 ];
272 }
273
282 public function equals( Block $block ) {
283 return (
284 (string)$this->target == (string)$block->target
285 && $this->type == $block->type
286 && $this->mAuto == $block->mAuto
287 && $this->isHardblock() == $block->isHardblock()
288 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
289 && $this->mExpiry == $block->mExpiry
290 && $this->isAutoblocking() == $block->isAutoblocking()
291 && $this->mHideName == $block->mHideName
292 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
293 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
294 && $this->mReason == $block->mReason
295 );
296 }
297
308 protected function newLoad( $vagueTarget = null ) {
309 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
310
311 if ( $this->type !== null ) {
312 $conds = [
313 'ipb_address' => [ (string)$this->target ],
314 ];
315 } else {
316 $conds = [ 'ipb_address' => [] ];
317 }
318
319 # Be aware that the != '' check is explicit, since empty values will be
320 # passed by some callers (T31116)
321 if ( $vagueTarget != '' ) {
322 list( $target, $type ) = self::parseTarget( $vagueTarget );
323 switch ( $type ) {
324 case self::TYPE_USER:
325 # Slightly weird, but who are we to argue?
326 $conds['ipb_address'][] = (string)$target;
327 break;
328
329 case self::TYPE_IP:
330 $conds['ipb_address'][] = (string)$target;
331 $conds[] = self::getRangeCond( IP::toHex( $target ) );
332 $conds = $db->makeList( $conds, LIST_OR );
333 break;
334
335 case self::TYPE_RANGE:
336 list( $start, $end ) = IP::parseRange( $target );
337 $conds['ipb_address'][] = (string)$target;
338 $conds[] = self::getRangeCond( $start, $end );
339 $conds = $db->makeList( $conds, LIST_OR );
340 break;
341
342 default:
343 throw new MWException( "Tried to load block with invalid type" );
344 }
345 }
346
347 $blockQuery = self::getQueryInfo();
348 $res = $db->select(
349 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
350 );
351
352 # This result could contain a block on the user, a block on the IP, and a russian-doll
353 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
354 $bestRow = null;
355
356 # Lower will be better
357 $bestBlockScore = 100;
358
359 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
360 $bestBlockPreventsEdit = null;
361
362 foreach ( $res as $row ) {
363 $block = self::newFromRow( $row );
364
365 # Don't use expired blocks
366 if ( $block->isExpired() ) {
367 continue;
368 }
369
370 # Don't use anon only blocks on users
371 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
372 continue;
373 }
374
375 if ( $block->getType() == self::TYPE_RANGE ) {
376 # This is the number of bits that are allowed to vary in the block, give
377 # or take some floating point errors
378 $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
379 $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
380 $size = log( $end - $start + 1, 2 );
381
382 # This has the nice property that a /32 block is ranked equally with a
383 # single-IP block, which is exactly what it is...
384 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
385
386 } else {
387 $score = $block->getType();
388 }
389
390 if ( $score < $bestBlockScore ) {
391 $bestBlockScore = $score;
392 $bestRow = $row;
393 $bestBlockPreventsEdit = $block->prevents( 'edit' );
394 }
395 }
396
397 if ( $bestRow !== null ) {
398 $this->initFromRow( $bestRow );
399 $this->prevents( 'edit', $bestBlockPreventsEdit );
400 return true;
401 } else {
402 return false;
403 }
404 }
405
412 public static function getRangeCond( $start, $end = null ) {
413 if ( $end === null ) {
414 $end = $start;
415 }
416 # Per T16634, we want to include relevant active rangeblocks; for
417 # rangeblocks, we want to include larger ranges which enclose the given
418 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
419 # so we can improve performance by filtering on a LIKE clause
420 $chunk = self::getIpFragment( $start );
422 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
423
424 # Fairly hard to make a malicious SQL statement out of hex characters,
425 # but stranger things have happened...
426 $safeStart = $dbr->addQuotes( $start );
427 $safeEnd = $dbr->addQuotes( $end );
428
429 return $dbr->makeList(
430 [
431 "ipb_range_start $like",
432 "ipb_range_start <= $safeStart",
433 "ipb_range_end >= $safeEnd",
434 ],
436 );
437 }
438
445 protected static function getIpFragment( $hex ) {
446 global $wgBlockCIDRLimit;
447 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
448 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
449 } else {
450 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
451 }
452 }
453
459 protected function initFromRow( $row ) {
460 $this->setTarget( $row->ipb_address );
462 $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
463 ) );
464
465 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
466 $this->mAuto = $row->ipb_auto;
467 $this->mHideName = $row->ipb_deleted;
468 $this->mId = (int)$row->ipb_id;
469 $this->mParentBlockId = $row->ipb_parent_block_id;
470
471 // I wish I didn't have to do this
472 $db = wfGetDB( DB_REPLICA );
473 $this->mExpiry = $db->decodeExpiry( $row->ipb_expiry );
474 $this->mReason = CommentStore::getStore()
475 // Legacy because $row may have come from self::selectFields()
476 ->getCommentLegacy( $db, 'ipb_reason', $row )->text;
477
478 $this->isHardblock( !$row->ipb_anon_only );
479 $this->isAutoblocking( $row->ipb_enable_autoblock );
480
481 $this->prevents( 'createaccount', $row->ipb_create_account );
482 $this->prevents( 'sendemail', $row->ipb_block_email );
483 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
484 }
485
491 public static function newFromRow( $row ) {
492 $block = new Block;
493 $block->initFromRow( $row );
494 return $block;
495 }
496
503 public function delete() {
504 if ( wfReadOnly() ) {
505 return false;
506 }
507
508 if ( !$this->getId() ) {
509 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
510 }
511
512 $dbw = wfGetDB( DB_MASTER );
513 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
514 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
515
516 return $dbw->affectedRows() > 0;
517 }
518
527 public function insert( $dbw = null ) {
529
530 if ( $this->getSystemBlockType() !== null ) {
531 throw new MWException( 'Cannot insert a system block into the database' );
532 }
533 if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
534 throw new MWException( 'Cannot insert a block without a blocker set' );
535 }
536
537 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
538
539 if ( $dbw === null ) {
540 $dbw = wfGetDB( DB_MASTER );
541 }
542
544
545 $row = $this->getDatabaseArray( $dbw );
546
547 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
548 $affected = $dbw->affectedRows();
549 $this->mId = $dbw->insertId();
550
551 # Don't collide with expired blocks.
552 # Do this after trying to insert to avoid locking.
553 if ( !$affected ) {
554 # T96428: The ipb_address index uses a prefix on a field, so
555 # use a standard SELECT + DELETE to avoid annoying gap locks.
556 $ids = $dbw->selectFieldValues( 'ipblocks',
557 'ipb_id',
558 [
559 'ipb_address' => $row['ipb_address'],
560 'ipb_user' => $row['ipb_user'],
561 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
562 ],
563 __METHOD__
564 );
565 if ( $ids ) {
566 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
567 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
568 $affected = $dbw->affectedRows();
569 $this->mId = $dbw->insertId();
570 }
571 }
572
573 if ( $affected ) {
574 $auto_ipd_ids = $this->doRetroactiveAutoblock();
575
576 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
577 // Change user login token to force them to be logged out.
578 $this->target->setToken();
579 $this->target->saveSettings();
580 }
581
582 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
583 }
584
585 return false;
586 }
587
595 public function update() {
596 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
597 $dbw = wfGetDB( DB_MASTER );
598
599 $dbw->startAtomic( __METHOD__ );
600
601 $dbw->update(
602 'ipblocks',
603 $this->getDatabaseArray( $dbw ),
604 [ 'ipb_id' => $this->getId() ],
605 __METHOD__
606 );
607
608 $affected = $dbw->affectedRows();
609
610 if ( $this->isAutoblocking() ) {
611 // update corresponding autoblock(s) (T50813)
612 $dbw->update(
613 'ipblocks',
614 $this->getAutoblockUpdateArray( $dbw ),
615 [ 'ipb_parent_block_id' => $this->getId() ],
616 __METHOD__
617 );
618 } else {
619 // autoblock no longer required, delete corresponding autoblock(s)
620 $dbw->delete(
621 'ipblocks',
622 [ 'ipb_parent_block_id' => $this->getId() ],
623 __METHOD__
624 );
625 }
626
627 $dbw->endAtomic( __METHOD__ );
628
629 if ( $affected ) {
630 $auto_ipd_ids = $this->doRetroactiveAutoblock();
631 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
632 }
633
634 return false;
635 }
636
642 protected function getDatabaseArray( IDatabase $dbw ) {
643 $expiry = $dbw->encodeExpiry( $this->mExpiry );
644
645 if ( $this->forcedTargetID ) {
647 } else {
648 $uid = $this->target instanceof User ? $this->target->getId() : 0;
649 }
650
651 $a = [
652 'ipb_address' => (string)$this->target,
653 'ipb_user' => $uid,
654 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
655 'ipb_auto' => $this->mAuto,
656 'ipb_anon_only' => !$this->isHardblock(),
657 'ipb_create_account' => $this->prevents( 'createaccount' ),
658 'ipb_enable_autoblock' => $this->isAutoblocking(),
659 'ipb_expiry' => $expiry,
660 'ipb_range_start' => $this->getRangeStart(),
661 'ipb_range_end' => $this->getRangeEnd(),
662 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
663 'ipb_block_email' => $this->prevents( 'sendemail' ),
664 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
665 'ipb_parent_block_id' => $this->mParentBlockId
666 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
667 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
668
669 return $a;
670 }
671
676 protected function getAutoblockUpdateArray( IDatabase $dbw ) {
677 return [
678 'ipb_create_account' => $this->prevents( 'createaccount' ),
679 'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
680 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
681 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
682 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
683 }
684
691 protected function doRetroactiveAutoblock() {
692 $blockIds = [];
693 # If autoblock is enabled, autoblock the LAST IP(s) used
694 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
695 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
696
697 $continue = Hooks::run(
698 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
699
700 if ( $continue ) {
701 self::defaultRetroactiveAutoblock( $this, $blockIds );
702 }
703 }
704 return $blockIds;
705 }
706
714 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
715 global $wgPutIPinRC;
716
717 // No IPs are in recentchanges table, so nothing to select
718 if ( !$wgPutIPinRC ) {
719 return;
720 }
721
722 $target = $block->getTarget();
723 if ( is_string( $target ) ) {
725 }
726
728 $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
729
730 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
731
732 // Just the last IP used.
733 $options['LIMIT'] = 1;
734
735 $res = $dbr->select(
736 [ 'recentchanges' ] + $rcQuery['tables'],
737 [ 'rc_ip' ],
738 $rcQuery['conds'],
739 __METHOD__,
740 $options,
741 $rcQuery['joins']
742 );
743
744 if ( !$res->numRows() ) {
745 # No results, don't autoblock anything
746 wfDebug( "No IP found to retroactively autoblock\n" );
747 } else {
748 foreach ( $res as $row ) {
749 if ( $row->rc_ip ) {
750 $id = $block->doAutoblock( $row->rc_ip );
751 if ( $id ) {
752 $blockIds[] = $id;
753 }
754 }
755 }
756 }
757 }
758
766 public static function isWhitelistedFromAutoblocks( $ip ) {
767 // Try to get the autoblock_whitelist from the cache, as it's faster
768 // than getting the msg raw and explode()'ing it.
769 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
770 $lines = $cache->getWithSetCallback(
771 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
772 $cache::TTL_DAY,
773 function ( $curValue, &$ttl, array &$setOpts ) {
774 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
775
776 return explode( "\n",
777 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
778 }
779 );
780
781 wfDebug( "Checking the autoblock whitelist..\n" );
782
783 foreach ( $lines as $line ) {
784 # List items only
785 if ( substr( $line, 0, 1 ) !== '*' ) {
786 continue;
787 }
788
789 $wlEntry = substr( $line, 1 );
790 $wlEntry = trim( $wlEntry );
791
792 wfDebug( "Checking $ip against $wlEntry..." );
793
794 # Is the IP in this range?
795 if ( IP::isInRange( $ip, $wlEntry ) ) {
796 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
797 return true;
798 } else {
799 wfDebug( " No match\n" );
800 }
801 }
802
803 return false;
804 }
805
812 public function doAutoblock( $autoblockIP ) {
813 # If autoblocks are disabled, go away.
814 if ( !$this->isAutoblocking() ) {
815 return false;
816 }
817
818 # Don't autoblock for system blocks
819 if ( $this->getSystemBlockType() !== null ) {
820 throw new MWException( 'Cannot autoblock from a system block' );
821 }
822
823 # Check for presence on the autoblock whitelist.
824 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
825 return false;
826 }
827
828 // Avoid PHP 7.1 warning of passing $this by reference
829 $block = $this;
830 # Allow hooks to cancel the autoblock.
831 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
832 wfDebug( "Autoblock aborted by hook.\n" );
833 return false;
834 }
835
836 # It's okay to autoblock. Go ahead and insert/update the block...
837
838 # Do not add a *new* block if the IP is already blocked.
839 $ipblock = self::newFromTarget( $autoblockIP );
840 if ( $ipblock ) {
841 # Check if the block is an autoblock and would exceed the user block
842 # if renewed. If so, do nothing, otherwise prolong the block time...
843 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
844 $this->mExpiry > self::getAutoblockExpiry( $ipblock->mTimestamp )
845 ) {
846 # Reset block timestamp to now and its expiry to
847 # $wgAutoblockExpiry in the future
848 $ipblock->updateTimestamp();
849 }
850 return false;
851 }
852
853 # Make a new block object with the desired properties.
854 $autoblock = new Block;
855 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
856 $autoblock->setTarget( $autoblockIP );
857 $autoblock->setBlocker( $this->getBlocker() );
858 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
859 ->inContentLanguage()->plain();
860 $timestamp = wfTimestampNow();
861 $autoblock->mTimestamp = $timestamp;
862 $autoblock->mAuto = 1;
863 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
864 # Continue suppressing the name if needed
865 $autoblock->mHideName = $this->mHideName;
866 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
867 $autoblock->mParentBlockId = $this->mId;
868
869 if ( $this->mExpiry == 'infinity' ) {
870 # Original block was indefinite, start an autoblock now
871 $autoblock->mExpiry = self::getAutoblockExpiry( $timestamp );
872 } else {
873 # If the user is already blocked with an expiry date, we don't
874 # want to pile on top of that.
875 $autoblock->mExpiry = min( $this->mExpiry, self::getAutoblockExpiry( $timestamp ) );
876 }
877
878 # Insert the block...
879 $status = $autoblock->insert();
880 return $status
881 ? $status['id']
882 : false;
883 }
884
889 public function deleteIfExpired() {
890 if ( $this->isExpired() ) {
891 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
892 $this->delete();
893 $retVal = true;
894 } else {
895 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
896 $retVal = false;
897 }
898
899 return $retVal;
900 }
901
906 public function isExpired() {
907 $timestamp = wfTimestampNow();
908 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
909
910 if ( !$this->mExpiry ) {
911 return false;
912 } else {
913 return $timestamp > $this->mExpiry;
914 }
915 }
916
921 public function isValid() {
922 return $this->getTarget() != null;
923 }
924
928 public function updateTimestamp() {
929 if ( $this->mAuto ) {
930 $this->mTimestamp = wfTimestamp();
931 $this->mExpiry = self::getAutoblockExpiry( $this->mTimestamp );
932
933 $dbw = wfGetDB( DB_MASTER );
934 $dbw->update( 'ipblocks',
935 [ /* SET */
936 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
937 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
938 ],
939 [ /* WHERE */
940 'ipb_id' => $this->getId(),
941 ],
942 __METHOD__
943 );
944 }
945 }
946
952 public function getRangeStart() {
953 switch ( $this->type ) {
954 case self::TYPE_USER:
955 return '';
956 case self::TYPE_IP:
957 return IP::toHex( $this->target );
958 case self::TYPE_RANGE:
959 list( $start, /*...*/ ) = IP::parseRange( $this->target );
960 return $start;
961 default:
962 throw new MWException( "Block with invalid type" );
963 }
964 }
965
971 public function getRangeEnd() {
972 switch ( $this->type ) {
973 case self::TYPE_USER:
974 return '';
975 case self::TYPE_IP:
976 return IP::toHex( $this->target );
977 case self::TYPE_RANGE:
978 list( /*...*/, $end ) = IP::parseRange( $this->target );
979 return $end;
980 default:
981 throw new MWException( "Block with invalid type" );
982 }
983 }
984
990 public function getBy() {
991 $blocker = $this->getBlocker();
992 return ( $blocker instanceof User )
993 ? $blocker->getId()
994 : 0;
995 }
996
1002 public function getByName() {
1003 $blocker = $this->getBlocker();
1004 return ( $blocker instanceof User )
1005 ? $blocker->getName()
1006 : (string)$blocker; // username
1007 }
1008
1013 public function getId() {
1014 return $this->mId;
1015 }
1016
1022 public function getSystemBlockType() {
1024 }
1025
1032 public function fromMaster( $x = null ) {
1033 return wfSetVar( $this->mFromMaster, $x );
1034 }
1035
1041 public function isHardblock( $x = null ) {
1042 wfSetVar( $this->isHardblock, $x );
1043
1044 # You can't *not* hardblock a user
1045 return $this->getType() == self::TYPE_USER
1046 ? true
1048 }
1049
1054 public function isAutoblocking( $x = null ) {
1055 wfSetVar( $this->isAutoblocking, $x );
1056
1057 # You can't put an autoblock on an IP or range as we don't have any history to
1058 # look over to get more IPs from
1059 return $this->getType() == self::TYPE_USER
1060 ? $this->isAutoblocking
1061 : false;
1062 }
1063
1071 public function prevents( $action, $x = null ) {
1072 global $wgBlockDisablesLogin;
1073 $res = null;
1074 switch ( $action ) {
1075 case 'edit':
1076 # For now... <evil laugh>
1077 $res = true;
1078 break;
1079 case 'createaccount':
1080 $res = wfSetVar( $this->mCreateAccount, $x );
1081 break;
1082 case 'sendemail':
1083 $res = wfSetVar( $this->mBlockEmail, $x );
1084 break;
1085 case 'editownusertalk':
1086 $res = wfSetVar( $this->mDisableUsertalk, $x );
1087 break;
1088 case 'read':
1089 $res = false;
1090 break;
1091 }
1092 if ( !$res && $wgBlockDisablesLogin ) {
1093 // If a block would disable login, then it should
1094 // prevent any action that all users cannot do
1095 $anon = new User;
1096 $res = $anon->isAllowed( $action ) ? $res : true;
1097 }
1098
1099 return $res;
1100 }
1101
1106 public function getRedactedName() {
1107 if ( $this->mAuto ) {
1108 return Html::rawElement(
1109 'span',
1110 [ 'class' => 'mw-autoblockid' ],
1111 wfMessage( 'autoblockid', $this->mId )
1112 );
1113 } else {
1114 return htmlspecialchars( $this->getTarget() );
1115 }
1116 }
1117
1124 public static function getAutoblockExpiry( $timestamp ) {
1125 global $wgAutoblockExpiry;
1126
1127 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1128 }
1129
1133 public static function purgeExpired() {
1134 if ( wfReadOnly() ) {
1135 return;
1136 }
1137
1138 DeferredUpdates::addUpdate( new AutoCommitUpdate(
1139 wfGetDB( DB_MASTER ),
1140 __METHOD__,
1141 function ( IDatabase $dbw, $fname ) {
1142 $ids = $dbw->selectFieldValues( 'ipblocks',
1143 'ipb_id',
1144 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1145 $fname
1146 );
1147 if ( $ids ) {
1148 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1149 }
1150 }
1151 ) );
1152 }
1153
1174 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1175 list( $target, $type ) = self::parseTarget( $specificTarget );
1176 if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1177 return self::newFromID( $target );
1178
1179 } elseif ( $target === null && $vagueTarget == '' ) {
1180 # We're not going to find anything useful here
1181 # Be aware that the == '' check is explicit, since empty values will be
1182 # passed by some callers (T31116)
1183 return null;
1184
1185 } elseif ( in_array(
1186 $type,
1187 [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1188 ) {
1189 $block = new Block();
1190 $block->fromMaster( $fromMaster );
1191
1192 if ( $type !== null ) {
1193 $block->setTarget( $target );
1194 }
1195
1196 if ( $block->newLoad( $vagueTarget ) ) {
1197 return $block;
1198 }
1199 }
1200 return null;
1201 }
1202
1213 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1214 if ( !count( $ipChain ) ) {
1215 return [];
1216 }
1217
1218 $conds = [];
1219 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1220 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1221 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1222 # necessarily trust the header given to us, make sure that we are only
1223 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1224 # Do not treat private IP spaces as special as it may be desirable for wikis
1225 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1226 if ( !IP::isValid( $ipaddr ) ) {
1227 continue;
1228 }
1229 # Don't check trusted IPs (includes local squids which will be in every request)
1230 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1231 continue;
1232 }
1233 # Check both the original IP (to check against single blocks), as well as build
1234 # the clause to check for rangeblocks for the given IP.
1235 $conds['ipb_address'][] = $ipaddr;
1236 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1237 }
1238
1239 if ( !count( $conds ) ) {
1240 return [];
1241 }
1242
1243 if ( $fromMaster ) {
1244 $db = wfGetDB( DB_MASTER );
1245 } else {
1246 $db = wfGetDB( DB_REPLICA );
1247 }
1248 $conds = $db->makeList( $conds, LIST_OR );
1249 if ( !$isAnon ) {
1250 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1251 }
1252 $blockQuery = self::getQueryInfo();
1253 $rows = $db->select(
1254 $blockQuery['tables'],
1255 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1256 $conds,
1257 __METHOD__,
1258 [],
1259 $blockQuery['joins']
1260 );
1261
1262 $blocks = [];
1263 foreach ( $rows as $row ) {
1264 $block = self::newFromRow( $row );
1265 if ( !$block->isExpired() ) {
1266 $blocks[] = $block;
1267 }
1268 }
1269
1270 return $blocks;
1271 }
1272
1294 public static function chooseBlock( array $blocks, array $ipChain ) {
1295 if ( !count( $blocks ) ) {
1296 return null;
1297 } elseif ( count( $blocks ) == 1 ) {
1298 return $blocks[0];
1299 }
1300
1301 // Sort hard blocks before soft ones and secondarily sort blocks
1302 // that disable account creation before those that don't.
1303 usort( $blocks, function ( Block $a, Block $b ) {
1304 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1305 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1306 return strcmp( $bWeight, $aWeight ); // highest weight first
1307 } );
1308
1309 $blocksListExact = [
1310 'hard' => false,
1311 'disable_create' => false,
1312 'other' => false,
1313 'auto' => false
1314 ];
1315 $blocksListRange = [
1316 'hard' => false,
1317 'disable_create' => false,
1318 'other' => false,
1319 'auto' => false
1320 ];
1321 $ipChain = array_reverse( $ipChain );
1322
1324 foreach ( $blocks as $block ) {
1325 // Stop searching if we have already have a "better" block. This
1326 // is why the order of the blocks matters
1327 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1328 break;
1329 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1330 break;
1331 }
1332
1333 foreach ( $ipChain as $checkip ) {
1334 $checkipHex = IP::toHex( $checkip );
1335 if ( (string)$block->getTarget() === $checkip ) {
1336 if ( $block->isHardblock() ) {
1337 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1338 } elseif ( $block->prevents( 'createaccount' ) ) {
1339 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1340 } elseif ( $block->mAuto ) {
1341 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1342 } else {
1343 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1344 }
1345 // We found closest exact match in the ip list, so go to the next Block
1346 break;
1347 } elseif ( array_filter( $blocksListExact ) == []
1348 && $block->getRangeStart() <= $checkipHex
1349 && $block->getRangeEnd() >= $checkipHex
1350 ) {
1351 if ( $block->isHardblock() ) {
1352 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1353 } elseif ( $block->prevents( 'createaccount' ) ) {
1354 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1355 } elseif ( $block->mAuto ) {
1356 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1357 } else {
1358 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1359 }
1360 break;
1361 }
1362 }
1363 }
1364
1365 if ( array_filter( $blocksListExact ) == [] ) {
1366 $blocksList = &$blocksListRange;
1367 } else {
1368 $blocksList = &$blocksListExact;
1369 }
1370
1371 $chosenBlock = null;
1372 if ( $blocksList['hard'] ) {
1373 $chosenBlock = $blocksList['hard'];
1374 } elseif ( $blocksList['disable_create'] ) {
1375 $chosenBlock = $blocksList['disable_create'];
1376 } elseif ( $blocksList['other'] ) {
1377 $chosenBlock = $blocksList['other'];
1378 } elseif ( $blocksList['auto'] ) {
1379 $chosenBlock = $blocksList['auto'];
1380 } else {
1381 throw new MWException( "Proxy block found, but couldn't be classified." );
1382 }
1383
1384 return $chosenBlock;
1385 }
1386
1396 public static function parseTarget( $target ) {
1397 # We may have been through this before
1398 if ( $target instanceof User ) {
1399 if ( IP::isValid( $target->getName() ) ) {
1400 return [ $target, self::TYPE_IP ];
1401 } else {
1402 return [ $target, self::TYPE_USER ];
1403 }
1404 } elseif ( $target === null ) {
1405 return [ null, null ];
1406 }
1407
1408 $target = trim( $target );
1409
1410 if ( IP::isValid( $target ) ) {
1411 # We can still create a User if it's an IP address, but we need to turn
1412 # off validation checking (which would exclude IP addresses)
1413 return [
1414 User::newFromName( IP::sanitizeIP( $target ), false ),
1416 ];
1417
1418 } elseif ( IP::isValidRange( $target ) ) {
1419 # Can't create a User from an IP range
1420 return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1421 }
1422
1423 # Consider the possibility that this is not a username at all
1424 # but actually an old subpage (T31797)
1425 if ( strpos( $target, '/' ) !== false ) {
1426 # An old subpage, drill down to the user behind it
1427 $target = explode( '/', $target )[0];
1428 }
1429
1430 $userObj = User::newFromName( $target );
1431 if ( $userObj instanceof User ) {
1432 # Note that since numbers are valid usernames, a $target of "12345" will be
1433 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1434 # since hash characters are not valid in usernames or titles generally.
1435 return [ $userObj, self::TYPE_USER ];
1436
1437 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1438 # Autoblock reference in the form "#12345"
1439 return [ substr( $target, 1 ), self::TYPE_AUTO ];
1440
1441 } else {
1442 # WTF?
1443 return [ null, null ];
1444 }
1445 }
1446
1451 public function getType() {
1452 return $this->mAuto
1454 : $this->type;
1455 }
1456
1464 public function getTargetAndType() {
1465 return [ $this->getTarget(), $this->getType() ];
1466 }
1467
1474 public function getTarget() {
1475 return $this->target;
1476 }
1477
1483 public function getExpiry() {
1484 return $this->mExpiry;
1485 }
1486
1491 public function setTarget( $target ) {
1492 list( $this->target, $this->type ) = self::parseTarget( $target );
1493 }
1494
1499 public function getBlocker() {
1500 return $this->blocker;
1501 }
1502
1507 public function setBlocker( $user ) {
1508 if ( is_string( $user ) ) {
1509 $user = User::newFromName( $user, false );
1510 }
1511
1512 if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1513 throw new InvalidArgumentException(
1514 'Blocker must be a local user or a name that cannot be a local user'
1515 );
1516 }
1517
1518 $this->blocker = $user;
1519 }
1520
1529 public function setCookie( WebResponse $response ) {
1530 // Calculate the default expiry time.
1531 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1532
1533 // Use the Block's expiry time only if it's less than the default.
1534 $expiryTime = $this->getExpiry();
1535 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1536 $expiryTime = $maxExpiryTime;
1537 }
1538
1539 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1540 $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1541 $cookieOptions = [ 'httpOnly' => false ];
1542 $cookieValue = $this->getCookieValue();
1543 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1544 }
1545
1553 public static function clearCookie( WebResponse $response ) {
1554 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1555 }
1556
1566 public function getCookieValue() {
1567 $config = RequestContext::getMain()->getConfig();
1568 $id = $this->getId();
1569 $secretKey = $config->get( 'SecretKey' );
1570 if ( !$secretKey ) {
1571 // If there's no secret key, don't append a HMAC.
1572 return $id;
1573 }
1574 $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1575 $cookieValue = $id . '!' . $hmac;
1576 return $cookieValue;
1577 }
1578
1589 public static function getIdFromCookieValue( $cookieValue ) {
1590 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1591 $bangPos = strpos( $cookieValue, '!' );
1592 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1593 // Get the site-wide secret key.
1594 $config = RequestContext::getMain()->getConfig();
1595 $secretKey = $config->get( 'SecretKey' );
1596 if ( !$secretKey ) {
1597 // If there's no secret key, just use the ID as given.
1598 return $id;
1599 }
1600 $storedHmac = substr( $cookieValue, $bangPos + 1 );
1601 $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1602 if ( $calculatedHmac === $storedHmac ) {
1603 return $id;
1604 } else {
1605 return null;
1606 }
1607 }
1608
1617 $blocker = $this->getBlocker();
1618 if ( $blocker instanceof User ) { // local user
1619 $blockerUserpage = $blocker->getUserPage();
1620 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1621 } else { // foreign user
1622 $link = $blocker;
1623 }
1624
1625 $reason = $this->mReason;
1626 if ( $reason == '' ) {
1627 $reason = $context->msg( 'blockednoreason' )->text();
1628 }
1629
1630 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1631 * This could be a username, an IP range, or a single IP. */
1632 $intended = $this->getTarget();
1633
1635
1636 $lang = $context->getLanguage();
1637 return [
1638 $systemBlockType !== null
1639 ? 'systemblockedtext'
1640 : ( $this->mAuto ? 'autoblockedtext' : 'blockedtext' ),
1641 $link,
1642 $reason,
1643 $context->getRequest()->getIP(),
1644 $this->getByName(),
1645 $systemBlockType ?? $this->getId(),
1646 $lang->formatExpiry( $this->mExpiry ),
1647 (string)$intended,
1648 $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1649 ];
1650 }
1651}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgAutoblockExpiry
Number of seconds before autoblock entries expire.
$wgBlockCIDRLimit
Limits on the possible sizes of range blocks.
$wgPutIPinRC
Log IP addresses in the recentchanges table; can be accessed only by extensions (e....
$wgBlockDisablesLogin
If true, blocked users will not be allowed to login.
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:121
$line
Definition cdb.php:59
Deferrable Update for closure/callback updates that should use auto-commit mode.
bool $mCreateAccount
Definition Block.php:59
int $forcedTargetID
Hack for foreign blocking (CentralAuth)
Definition Block.php:65
static selectFields()
Return the list of ipblocks fields that should be selected to create a new block.
Definition Block.php:208
setCookie(WebResponse $response)
Set the 'BlockID' cookie to this block's ID and expiry time.
Definition Block.php:1529
getPermissionsError(IContextSource $context)
Get the key and parameters for the corresponding error message.
Definition Block.php:1616
static clearCookie(WebResponse $response)
Unset the 'BlockID' cookie.
Definition Block.php:1553
bool $isAutoblocking
Definition Block.php:77
insert( $dbw=null)
Insert a block into the block table.
Definition Block.php:527
static getRangeCond( $start, $end=null)
Get a set of SQL conditions which will select rangeblocks encompassing a given range.
Definition Block.php:412
newLoad( $vagueTarget=null)
Load a block from the database which affects the already-set $this->target: 1) A block directly on th...
Definition Block.php:308
update()
Update a block in the DB with new parameters.
Definition Block.php:595
prevents( $action, $x=null)
Get/set whether the Block prevents a given action.
Definition Block.php:1071
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new block object.
Definition Block.php:251
static newFromRow( $row)
Create a new Block object from a database row.
Definition Block.php:491
getDatabaseArray(IDatabase $dbw)
Get an array suitable for passing to $dbw->insert() or $dbw->update()
Definition Block.php:642
isHardblock( $x=null)
Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
Definition Block.php:1041
isValid()
Is the block address valid (i.e.
Definition Block.php:921
User string $target
Definition Block.php:62
bool $isHardblock
Definition Block.php:74
setBlocker( $user)
Set the user who implemented (or will implement) this block.
Definition Block.php:1507
getRedactedName()
Get the block name, but with autoblocked IPs hidden as per standard privacy policy.
Definition Block.php:1106
isExpired()
Has the block expired?
Definition Block.php:906
static newFromID( $id)
Load a blocked user from their block id.
Definition Block.php:184
static getAutoblockExpiry( $timestamp)
Get a timestamp of the expiry for autoblocks.
Definition Block.php:1124
int $mId
Definition Block.php:47
static getBlocksForIPList(array $ipChain, $isAnon, $fromMaster=false)
Get all blocks that match any IP from an array of IP addresses.
Definition Block.php:1213
getRangeEnd()
Get the IP address at the end of the range in Hex form.
Definition Block.php:971
getAutoblockUpdateArray(IDatabase $dbw)
Definition Block.php:676
static getIpFragment( $hex)
Get the component of an IP address which is certain to be the same between an IP address and a rangeb...
Definition Block.php:445
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition Block.php:1396
bool $mBlockEmail
Definition Block.php:53
string null $systemBlockType
Definition Block.php:80
static chooseBlock(array $blocks, array $ipChain)
From a list of multiple blocks, find the most exact and strongest Block.
Definition Block.php:1294
bool $mDisableUsertalk
Definition Block.php:56
getSystemBlockType()
Get the system block type, if any.
Definition Block.php:1022
initFromRow( $row)
Given a database row from the ipblocks table, initialize member variables.
Definition Block.php:459
static isWhitelistedFromAutoblocks( $ip)
Checks whether a given IP is on the autoblock whitelist.
Definition Block.php:766
getId()
Get the block ID.
Definition Block.php:1013
getExpiry()
Definition Block.php:1483
getType()
Get the type of target for this particular block.
Definition Block.php:1451
const TYPE_ID
Definition Block.php:87
__construct( $options=[])
Create a new block with specified parameters on a user, IP or IP range.
Definition Block.php:115
getBy()
Get the user id of the blocking sysop.
Definition Block.php:990
setTarget( $target)
Set the target for this block, and update $this->type accordingly.
Definition Block.php:1491
const TYPE_RANGE
Definition Block.php:85
string $mExpiry
Definition Block.php:38
updateTimestamp()
Update the timestamp on autoblocks.
Definition Block.php:928
fromMaster( $x=null)
Get/set a flag determining whether the master is used for reads.
Definition Block.php:1032
doAutoblock( $autoblockIP)
Autoblocks the given IP, referring to this Block.
Definition Block.php:812
bool $mHideName
Definition Block.php:41
deleteIfExpired()
Check if a block has expired.
Definition Block.php:889
User $blocker
Definition Block.php:71
doRetroactiveAutoblock()
Retroactively autoblocks the last IP used by the user (if it is a user) blocked by this Block.
Definition Block.php:691
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
Definition Block.php:1589
bool $mFromMaster
Definition Block.php:50
int $mParentBlockId
Definition Block.php:44
getTargetAndType()
Get the target and target type for this particular Block.
Definition Block.php:1464
getTarget()
Get the target for this particular Block.
Definition Block.php:1474
const TYPE_USER
Definition Block.php:83
static purgeExpired()
Purge expired blocks from the ipblocks table.
Definition Block.php:1133
getRangeStart()
Get the IP address at the start of the range in Hex form.
Definition Block.php:952
getCookieValue()
Get the BlockID cookie's value for this block.
Definition Block.php:1566
getByName()
Get the username of the blocking sysop.
Definition Block.php:1002
equals(Block $block)
Check if two blocks are effectively equal.
Definition Block.php:282
isAutoblocking( $x=null)
Definition Block.php:1054
string $mReason
Definition Block.php:29
const TYPE_AUTO
Definition Block.php:86
static defaultRetroactiveAutoblock(Block $block, array &$blockIds)
Retroactively autoblocks the last IP used by the user (if it is a user) blocked by this Block.
Definition Block.php:714
getBlocker()
Get the user who implemented this block.
Definition Block.php:1499
bool $mAuto
Definition Block.php:35
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target's type, get an existing Block object if possible.
Definition Block.php:1174
int $type
Block::TYPE_ constant.
Definition Block.php:68
string $mTimestamp
Definition Block.php:32
const TYPE_IP
Definition Block.php:84
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
MediaWiki exception.
MediaWikiServices is the service locator for the application scope of MediaWiki.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
getName()
Get the user name, or the IP of an anonymous user.
Definition User.php:2462
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition User.php:592
isAllowed( $action='')
Internal mechanics of testing a permission.
Definition User.php:3856
getId()
Get the user's ID.
Definition User.php:2437
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
Definition User.php:682
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition User.php:615
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
Definition User.php:1046
getUserPage()
Get this user's personal page title.
Definition User.php:4539
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
setCookie( $name, $value, $expire=0, $options=[])
Set the browser cookie.
Relational database abstraction object.
Definition Database.php:48
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const SCHEMA_COMPAT_READ_NEW
Definition Defines.php:287
const LIST_OR
Definition Defines.php:46
const LIST_AND
Definition Defines.php:43
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition hooks.txt:2857
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition hooks.txt:181
either a plain
Definition hooks.txt:2105
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1305
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2050
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2885
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2055
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:3106
this hook is for auditing only $response
Definition hooks.txt:813
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:247
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback function
Definition injection.txt:30
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Interface for objects which can provide a MediaWiki context on request.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
addQuotes( $s)
Adds quotes and backslashes.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
$cache
Definition mcc.php:33
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$expiryTime
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition postgres.txt:36
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26
$lines
Definition router.php:61
if(!isset( $args[0])) $lang