MediaWiki  master
DatabaseBlock.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Block;
24 
30 use Hooks;
31 use Html;
33 use IP;
41 use Title;
42 use User;
46 
57  public $mAuto;
58 
61 
63  private $mId;
64 
66  private $mFromMaster;
67 
69  private $forcedTargetID;
70 
72  private $isHardblock;
73 
75  private $isAutoblocking;
76 
78  private $restrictions;
79 
99  public function __construct( array $options = [] ) {
100  parent::__construct( $options );
101 
102  $defaults = [
103  'user' => null,
104  'auto' => false,
105  'expiry' => '',
106  'anonOnly' => false,
107  'createAccount' => false,
108  'enableAutoblock' => false,
109  'hideName' => false,
110  'blockEmail' => false,
111  'allowUsertalk' => false,
112  'sitewide' => true,
113  ];
114 
115  $options += $defaults;
116 
117  if ( $this->target instanceof User && $options['user'] ) {
118  # Needed for foreign users
119  $this->forcedTargetID = $options['user'];
120  }
121 
122  $this->setExpiry( wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] ) );
123 
124  # Boolean settings
125  $this->mAuto = (bool)$options['auto'];
126  $this->setHideName( (bool)$options['hideName'] );
127  $this->isHardblock( !$options['anonOnly'] );
128  $this->isAutoblocking( (bool)$options['enableAutoblock'] );
129  $this->isSitewide( (bool)$options['sitewide'] );
130  $this->isEmailBlocked( (bool)$options['blockEmail'] );
131  $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
132  $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
133 
134  $this->mFromMaster = false;
135  }
136 
143  public static function newFromID( $id ) {
144  $dbr = wfGetDB( DB_REPLICA );
145  $blockQuery = self::getQueryInfo();
146  $res = $dbr->selectRow(
147  $blockQuery['tables'],
148  $blockQuery['fields'],
149  [ 'ipb_id' => $id ],
150  __METHOD__,
151  [],
152  $blockQuery['joins']
153  );
154  if ( $res ) {
155  return self::newFromRow( $res );
156  } else {
157  return null;
158  }
159  }
160 
167  public static function selectFields() {
169 
170  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
171  // If code is using this instead of self::getQueryInfo(), there's a
172  // decent chance it's going to try to directly access
173  // $row->ipb_by or $row->ipb_by_text and we can't give it
174  // useful values here once those aren't being used anymore.
175  throw new BadMethodCallException(
176  'Cannot use ' . __METHOD__
177  . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
178  );
179  }
180 
181  wfDeprecated( __METHOD__, '1.31' );
182  return [
183  'ipb_id',
184  'ipb_address',
185  'ipb_by',
186  'ipb_by_text',
187  'ipb_by_actor' => 'NULL',
188  'ipb_timestamp',
189  'ipb_auto',
190  'ipb_anon_only',
191  'ipb_create_account',
192  'ipb_enable_autoblock',
193  'ipb_expiry',
194  'ipb_deleted',
195  'ipb_block_email',
196  'ipb_allow_usertalk',
197  'ipb_parent_block_id',
198  'ipb_sitewide',
199  ] + CommentStore::getStore()->getFields( 'ipb_reason' );
200  }
201 
211  public static function getQueryInfo() {
212  $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
213  $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
214  return [
215  'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
216  'fields' => [
217  'ipb_id',
218  'ipb_address',
219  'ipb_timestamp',
220  'ipb_auto',
221  'ipb_anon_only',
222  'ipb_create_account',
223  'ipb_enable_autoblock',
224  'ipb_expiry',
225  'ipb_deleted',
226  'ipb_block_email',
227  'ipb_allow_usertalk',
228  'ipb_parent_block_id',
229  'ipb_sitewide',
230  ] + $commentQuery['fields'] + $actorQuery['fields'],
231  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
232  ];
233  }
234 
242  public function equals( DatabaseBlock $block ) {
243  return (
244  (string)$this->target == (string)$block->target
245  && $this->type == $block->type
246  && $this->mAuto == $block->mAuto
247  && $this->isHardblock() == $block->isHardblock()
248  && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
249  && $this->getExpiry() == $block->getExpiry()
250  && $this->isAutoblocking() == $block->isAutoblocking()
251  && $this->getHideName() == $block->getHideName()
252  && $this->isEmailBlocked() == $block->isEmailBlocked()
253  && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
254  && $this->getReason() == $block->getReason()
255  && $this->isSitewide() == $block->isSitewide()
256  // DatabaseBlock::getRestrictions() may perform a database query, so
257  // keep it at the end.
258  && $this->getBlockRestrictionStore()->equals(
259  $this->getRestrictions(), $block->getRestrictions()
260  )
261  );
262  }
263 
276  protected static function newLoad(
277  $specificTarget,
278  $specificType,
279  $fromMaster,
280  $vagueTarget = null
281  ) {
282  $db = wfGetDB( $fromMaster ? DB_MASTER : DB_REPLICA );
283 
284  if ( $specificType !== null ) {
285  $conds = [
286  'ipb_address' => [ (string)$specificTarget ],
287  ];
288  } else {
289  $conds = [ 'ipb_address' => [] ];
290  }
291 
292  # Be aware that the != '' check is explicit, since empty values will be
293  # passed by some callers (T31116)
294  if ( $vagueTarget != '' ) {
295  list( $target, $type ) = self::parseTarget( $vagueTarget );
296  switch ( $type ) {
297  case self::TYPE_USER:
298  # Slightly weird, but who are we to argue?
299  $conds['ipb_address'][] = (string)$target;
300  break;
301 
302  case self::TYPE_IP:
303  $conds['ipb_address'][] = (string)$target;
304  $conds[] = self::getRangeCond( IP::toHex( $target ) );
305  $conds = $db->makeList( $conds, LIST_OR );
306  break;
307 
308  case self::TYPE_RANGE:
309  list( $start, $end ) = IP::parseRange( $target );
310  $conds['ipb_address'][] = (string)$target;
311  $conds[] = self::getRangeCond( $start, $end );
312  $conds = $db->makeList( $conds, LIST_OR );
313  break;
314 
315  default:
316  throw new MWException( "Tried to load block with invalid type" );
317  }
318  }
319 
320  $blockQuery = self::getQueryInfo();
321  $res = $db->select(
322  $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
323  );
324 
325  $blocks = [];
326  $blockIds = [];
327  $autoBlocks = [];
328  foreach ( $res as $row ) {
329  $block = self::newFromRow( $row );
330 
331  # Don't use expired blocks
332  if ( $block->isExpired() ) {
333  continue;
334  }
335 
336  # Don't use anon only blocks on users
337  if ( $specificType == self::TYPE_USER && !$block->isHardblock() ) {
338  continue;
339  }
340 
341  // Check for duplicate autoblocks
342  if ( $block->getType() === self::TYPE_AUTO ) {
343  $autoBlocks[] = $block;
344  } else {
345  $blocks[] = $block;
346  $blockIds[] = $block->getId();
347  }
348  }
349 
350  // Only add autoblocks that aren't duplicates
351  foreach ( $autoBlocks as $block ) {
352  if ( !in_array( $block->mParentBlockId, $blockIds ) ) {
353  $blocks[] = $block;
354  }
355  }
356 
357  return $blocks;
358  }
359 
372  protected static function chooseMostSpecificBlock( array $blocks ) {
373  if ( count( $blocks ) === 1 ) {
374  return $blocks[0];
375  }
376 
377  # This result could contain a block on the user, a block on the IP, and a russian-doll
378  # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
379  $bestBlock = null;
380 
381  # Lower will be better
382  $bestBlockScore = 100;
383  foreach ( $blocks as $block ) {
384  if ( $block->getType() == self::TYPE_RANGE ) {
385  # This is the number of bits that are allowed to vary in the block, give
386  # or take some floating point errors
387  $target = $block->getTarget();
388  $max = IP::isIPv6( $target ) ? 128 : 32;
389  list( $network, $bits ) = IP::parseCIDR( $target );
390  $size = $max - $bits;
391 
392  # Rank a range block covering a single IP equally with a single-IP block
393  $score = self::TYPE_RANGE - 1 + ( $size / $max );
394 
395  } else {
396  $score = $block->getType();
397  }
398 
399  if ( $score < $bestBlockScore ) {
400  $bestBlockScore = $score;
401  $bestBlock = $block;
402  }
403  }
404 
405  return $bestBlock;
406  }
407 
414  public static function getRangeCond( $start, $end = null ) {
415  if ( $end === null ) {
416  $end = $start;
417  }
418  # Per T16634, we want to include relevant active rangeblocks; for
419  # rangeblocks, we want to include larger ranges which enclose the given
420  # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
421  # so we can improve performance by filtering on a LIKE clause
422  $chunk = self::getIpFragment( $start );
423  $dbr = wfGetDB( DB_REPLICA );
424  $like = $dbr->buildLike( $chunk, $dbr->anyString() );
425 
426  # Fairly hard to make a malicious SQL statement out of hex characters,
427  # but stranger things have happened...
428  $safeStart = $dbr->addQuotes( $start );
429  $safeEnd = $dbr->addQuotes( $end );
430 
431  return $dbr->makeList(
432  [
433  "ipb_range_start $like",
434  "ipb_range_start <= $safeStart",
435  "ipb_range_end >= $safeEnd",
436  ],
437  LIST_AND
438  );
439  }
440 
447  protected static function getIpFragment( $hex ) {
448  global $wgBlockCIDRLimit;
449  if ( substr( $hex, 0, 3 ) == 'v6-' ) {
450  return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
451  } else {
452  return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
453  }
454  }
455 
461  protected function initFromRow( $row ) {
462  $this->setTarget( $row->ipb_address );
464  $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
465  ) );
466 
467  $this->setTimestamp( wfTimestamp( TS_MW, $row->ipb_timestamp ) );
468  $this->mAuto = $row->ipb_auto;
469  $this->setHideName( $row->ipb_deleted );
470  $this->mId = (int)$row->ipb_id;
471  $this->mParentBlockId = $row->ipb_parent_block_id;
472 
473  // I wish I didn't have to do this
474  $db = wfGetDB( DB_REPLICA );
475  $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry ) );
476  $this->setReason(
478  // Legacy because $row may have come from self::selectFields()
479  ->getCommentLegacy( $db, 'ipb_reason', $row )->text
480  );
481 
482  $this->isHardblock( !$row->ipb_anon_only );
483  $this->isAutoblocking( $row->ipb_enable_autoblock );
484  $this->isSitewide( (bool)$row->ipb_sitewide );
485 
486  $this->isCreateAccountBlocked( $row->ipb_create_account );
487  $this->isEmailBlocked( $row->ipb_block_email );
488  $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk );
489  }
490 
496  public static function newFromRow( $row ) {
497  $block = new DatabaseBlock;
498  $block->initFromRow( $row );
499  return $block;
500  }
501 
508  public function delete() {
509  if ( wfReadOnly() ) {
510  return false;
511  }
512 
513  if ( !$this->getId() ) {
514  throw new MWException(
515  __METHOD__ . " requires that the mId member be filled\n"
516  );
517  }
518 
519  $dbw = wfGetDB( DB_MASTER );
520 
521  $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
522  $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
523 
524  $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
525  $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
526 
527  return $dbw->affectedRows() > 0;
528  }
529 
538  public function insert( IDatabase $dbw = null ) {
539  global $wgBlockDisablesLogin;
540 
541  if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
542  throw new MWException( 'Cannot insert a block without a blocker set' );
543  }
544 
545  wfDebug( __METHOD__ . "; timestamp {$this->mTimestamp}\n" );
546 
547  if ( $dbw === null ) {
548  $dbw = wfGetDB( DB_MASTER );
549  }
550 
551  self::purgeExpired();
552 
553  $row = $this->getDatabaseArray( $dbw );
554 
555  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
556  $affected = $dbw->affectedRows();
557  if ( $affected ) {
558  $this->setId( $dbw->insertId() );
559  if ( $this->restrictions ) {
560  $this->getBlockRestrictionStore()->insert( $this->restrictions );
561  }
562  }
563 
564  # Don't collide with expired blocks.
565  # Do this after trying to insert to avoid locking.
566  if ( !$affected ) {
567  # T96428: The ipb_address index uses a prefix on a field, so
568  # use a standard SELECT + DELETE to avoid annoying gap locks.
569  $ids = $dbw->selectFieldValues( 'ipblocks',
570  'ipb_id',
571  [
572  'ipb_address' => $row['ipb_address'],
573  'ipb_user' => $row['ipb_user'],
574  'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
575  ],
576  __METHOD__
577  );
578  if ( $ids ) {
579  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
580  $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
581  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
582  $affected = $dbw->affectedRows();
583  $this->setId( $dbw->insertId() );
584  if ( $this->restrictions ) {
585  $this->getBlockRestrictionStore()->insert( $this->restrictions );
586  }
587  }
588  }
589 
590  if ( $affected ) {
591  $auto_ipd_ids = $this->doRetroactiveAutoblock();
592 
593  if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
594  // Change user login token to force them to be logged out.
595  $this->target->setToken();
596  $this->target->saveSettings();
597  }
598 
599  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
600  }
601 
602  return false;
603  }
604 
612  public function update() {
613  wfDebug( __METHOD__ . "; timestamp {$this->mTimestamp}\n" );
614  $dbw = wfGetDB( DB_MASTER );
615 
616  $dbw->startAtomic( __METHOD__ );
617 
618  $result = $dbw->update(
619  'ipblocks',
620  $this->getDatabaseArray( $dbw ),
621  [ 'ipb_id' => $this->getId() ],
622  __METHOD__
623  );
624 
625  // Only update the restrictions if they have been modified.
626  if ( $this->restrictions !== null ) {
627  // An empty array should remove all of the restrictions.
628  if ( empty( $this->restrictions ) ) {
629  $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
630  } else {
631  $success = $this->getBlockRestrictionStore()->update( $this->restrictions );
632  }
633  // Update the result. The first false is the result, otherwise, true.
634  $result = $result && $success;
635  }
636 
637  if ( $this->isAutoblocking() ) {
638  // update corresponding autoblock(s) (T50813)
639  $dbw->update(
640  'ipblocks',
641  $this->getAutoblockUpdateArray( $dbw ),
642  [ 'ipb_parent_block_id' => $this->getId() ],
643  __METHOD__
644  );
645 
646  // Only update the restrictions if they have been modified.
647  if ( $this->restrictions !== null ) {
648  $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions );
649  }
650  } else {
651  // autoblock no longer required, delete corresponding autoblock(s)
652  $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
653  $dbw->delete(
654  'ipblocks',
655  [ 'ipb_parent_block_id' => $this->getId() ],
656  __METHOD__
657  );
658  }
659 
660  $dbw->endAtomic( __METHOD__ );
661 
662  if ( $result ) {
663  $auto_ipd_ids = $this->doRetroactiveAutoblock();
664  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
665  }
666 
667  return $result;
668  }
669 
675  protected function getDatabaseArray( IDatabase $dbw ) {
676  $expiry = $dbw->encodeExpiry( $this->getExpiry() );
677 
678  if ( $this->forcedTargetID ) {
679  $uid = $this->forcedTargetID;
680  } else {
681  $uid = $this->target instanceof User ? $this->target->getId() : 0;
682  }
683 
684  $a = [
685  'ipb_address' => (string)$this->target,
686  'ipb_user' => $uid,
687  'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
688  'ipb_auto' => $this->mAuto,
689  'ipb_anon_only' => !$this->isHardblock(),
690  'ipb_create_account' => $this->isCreateAccountBlocked(),
691  'ipb_enable_autoblock' => $this->isAutoblocking(),
692  'ipb_expiry' => $expiry,
693  'ipb_range_start' => $this->getRangeStart(),
694  'ipb_range_end' => $this->getRangeEnd(),
695  'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
696  'ipb_block_email' => $this->isEmailBlocked(),
697  'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
698  'ipb_parent_block_id' => $this->mParentBlockId,
699  'ipb_sitewide' => $this->isSitewide(),
700  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
701  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
702 
703  return $a;
704  }
705 
710  protected function getAutoblockUpdateArray( IDatabase $dbw ) {
711  return [
712  'ipb_create_account' => $this->isCreateAccountBlocked(),
713  'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
714  'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
715  'ipb_sitewide' => $this->isSitewide(),
716  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
717  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
718  }
719 
726  protected function doRetroactiveAutoblock() {
727  $blockIds = [];
728  # If autoblock is enabled, autoblock the LAST IP(s) used
729  if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
730  wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
731 
732  $continue = Hooks::run(
733  'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
734 
735  if ( $continue ) {
736  self::defaultRetroactiveAutoblock( $this, $blockIds );
737  }
738  }
739  return $blockIds;
740  }
741 
749  protected static function defaultRetroactiveAutoblock( DatabaseBlock $block, array &$blockIds ) {
750  global $wgPutIPinRC;
751 
752  // No IPs are in recentchanges table, so nothing to select
753  if ( !$wgPutIPinRC ) {
754  return;
755  }
756 
757  // Autoblocks only apply to TYPE_USER
758  if ( $block->getType() !== self::TYPE_USER ) {
759  return;
760  }
761  $target = $block->getTarget(); // TYPE_USER => always a User object
762 
763  $dbr = wfGetDB( DB_REPLICA );
764  $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
765 
766  $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
767 
768  // Just the last IP used.
769  $options['LIMIT'] = 1;
770 
771  $res = $dbr->select(
772  [ 'recentchanges' ] + $rcQuery['tables'],
773  [ 'rc_ip' ],
774  $rcQuery['conds'],
775  __METHOD__,
776  $options,
777  $rcQuery['joins']
778  );
779 
780  if ( !$res->numRows() ) {
781  # No results, don't autoblock anything
782  wfDebug( "No IP found to retroactively autoblock\n" );
783  } else {
784  foreach ( $res as $row ) {
785  if ( $row->rc_ip ) {
786  $id = $block->doAutoblock( $row->rc_ip );
787  if ( $id ) {
788  $blockIds[] = $id;
789  }
790  }
791  }
792  }
793  }
794 
802  public static function isWhitelistedFromAutoblocks( $ip ) {
803  // Try to get the autoblock_whitelist from the cache, as it's faster
804  // than getting the msg raw and explode()'ing it.
805  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
806  $lines = $cache->getWithSetCallback(
807  $cache->makeKey( 'ip-autoblock', 'whitelist' ),
808  $cache::TTL_DAY,
809  function ( $curValue, &$ttl, array &$setOpts ) {
811 
812  return explode( "\n",
813  wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
814  }
815  );
816 
817  wfDebug( "Checking the autoblock whitelist..\n" );
818 
819  foreach ( $lines as $line ) {
820  # List items only
821  if ( substr( $line, 0, 1 ) !== '*' ) {
822  continue;
823  }
824 
825  $wlEntry = substr( $line, 1 );
826  $wlEntry = trim( $wlEntry );
827 
828  wfDebug( "Checking $ip against $wlEntry..." );
829 
830  # Is the IP in this range?
831  if ( IP::isInRange( $ip, $wlEntry ) ) {
832  wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
833  return true;
834  } else {
835  wfDebug( " No match\n" );
836  }
837  }
838 
839  return false;
840  }
841 
848  public function doAutoblock( $autoblockIP ) {
849  # If autoblocks are disabled, go away.
850  if ( !$this->isAutoblocking() ) {
851  return false;
852  }
853 
854  # Check for presence on the autoblock whitelist.
855  if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
856  return false;
857  }
858 
859  // Avoid PHP 7.1 warning of passing $this by reference
860  $block = $this;
861  # Allow hooks to cancel the autoblock.
862  if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
863  wfDebug( "Autoblock aborted by hook.\n" );
864  return false;
865  }
866 
867  # It's okay to autoblock. Go ahead and insert/update the block...
868 
869  # Do not add a *new* block if the IP is already blocked.
870  $ipblock = self::newFromTarget( $autoblockIP );
871  if ( $ipblock ) {
872  # Check if the block is an autoblock and would exceed the user block
873  # if renewed. If so, do nothing, otherwise prolong the block time...
874  if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
875  $this->getExpiry() > self::getAutoblockExpiry( $ipblock->getTimestamp() )
876  ) {
877  # Reset block timestamp to now and its expiry to
878  # $wgAutoblockExpiry in the future
879  $ipblock->updateTimestamp();
880  }
881  return false;
882  }
883 
884  # Make a new block object with the desired properties.
885  $autoblock = new DatabaseBlock;
886  wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
887  $autoblock->setTarget( $autoblockIP );
888  $autoblock->setBlocker( $this->getBlocker() );
889  $autoblock->setReason(
890  wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
891  ->inContentLanguage()->plain()
892  );
893  $timestamp = wfTimestampNow();
894  $autoblock->setTimestamp( $timestamp );
895  $autoblock->mAuto = 1;
896  $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
897  # Continue suppressing the name if needed
898  $autoblock->setHideName( $this->getHideName() );
899  $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
900  $autoblock->mParentBlockId = $this->mId;
901  $autoblock->isSitewide( $this->isSitewide() );
902  $autoblock->setRestrictions( $this->getRestrictions() );
903 
904  if ( $this->getExpiry() == 'infinity' ) {
905  # Original block was indefinite, start an autoblock now
906  $autoblock->setExpiry( self::getAutoblockExpiry( $timestamp ) );
907  } else {
908  # If the user is already blocked with an expiry date, we don't
909  # want to pile on top of that.
910  $autoblock->setExpiry( min( $this->getExpiry(), self::getAutoblockExpiry( $timestamp ) ) );
911  }
912 
913  # Insert the block...
914  $status = $autoblock->insert();
915  return $status
916  ? $status['id']
917  : false;
918  }
919 
924  public function deleteIfExpired() {
925  if ( $this->isExpired() ) {
926  wfDebug( __METHOD__ . " -- deleting\n" );
927  $this->delete();
928  $retVal = true;
929  } else {
930  wfDebug( __METHOD__ . " -- not expired\n" );
931  $retVal = false;
932  }
933 
934  return $retVal;
935  }
936 
941  public function isExpired() {
942  $timestamp = wfTimestampNow();
943  wfDebug( __METHOD__ . " checking current " . $timestamp . " vs $this->mExpiry\n" );
944 
945  if ( !$this->getExpiry() ) {
946  return false;
947  } else {
948  return $timestamp > $this->getExpiry();
949  }
950  }
951 
958  public function isValid() {
959  wfDeprecated( __METHOD__, '1.33' );
960  return $this->getTarget() != null;
961  }
962 
966  public function updateTimestamp() {
967  if ( $this->mAuto ) {
968  $this->setTimestamp( wfTimestamp() );
969  $this->setExpiry( self::getAutoblockExpiry( $this->getTimestamp() ) );
970 
971  $dbw = wfGetDB( DB_MASTER );
972  $dbw->update( 'ipblocks',
973  [ /* SET */
974  'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
975  'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
976  ],
977  [ /* WHERE */
978  'ipb_id' => $this->getId(),
979  ],
980  __METHOD__
981  );
982  }
983  }
984 
990  public function getRangeStart() {
991  switch ( $this->type ) {
992  case self::TYPE_USER:
993  return '';
994  case self::TYPE_IP:
995  return IP::toHex( $this->target );
996  case self::TYPE_RANGE:
997  list( $start, /*...*/ ) = IP::parseRange( $this->target );
998  return $start;
999  default:
1000  throw new MWException( "Block with invalid type" );
1001  }
1002  }
1003 
1009  public function getRangeEnd() {
1010  switch ( $this->type ) {
1011  case self::TYPE_USER:
1012  return '';
1013  case self::TYPE_IP:
1014  return IP::toHex( $this->target );
1015  case self::TYPE_RANGE:
1016  list( /*...*/, $end ) = IP::parseRange( $this->target );
1017  return $end;
1018  default:
1019  throw new MWException( "Block with invalid type" );
1020  }
1021  }
1022 
1026  public function getId() {
1027  return $this->mId;
1028  }
1029 
1036  private function setId( $blockId ) {
1037  $this->mId = (int)$blockId;
1038 
1039  if ( is_array( $this->restrictions ) ) {
1040  $this->restrictions = $this->getBlockRestrictionStore()->setBlockId(
1041  $blockId, $this->restrictions
1042  );
1043  }
1044 
1045  return $this;
1046  }
1047 
1052  public function getParentBlockId() {
1053  return $this->mParentBlockId;
1054  }
1055 
1062  public function fromMaster( $x = null ) {
1063  return wfSetVar( $this->mFromMaster, $x );
1064  }
1065 
1071  public function isHardblock( $x = null ) {
1072  wfSetVar( $this->isHardblock, $x );
1073 
1074  # You can't *not* hardblock a user
1075  return $this->getType() == self::TYPE_USER
1076  ? true
1078  }
1079 
1084  public function isAutoblocking( $x = null ) {
1085  wfSetVar( $this->isAutoblocking, $x );
1086 
1087  # You can't put an autoblock on an IP or range as we don't have any history to
1088  # look over to get more IPs from
1089  return $this->getType() == self::TYPE_USER
1090  ? $this->isAutoblocking
1091  : false;
1092  }
1093 
1098  public function getRedactedName() {
1099  if ( $this->mAuto ) {
1100  return Html::element(
1101  'span',
1102  [ 'class' => 'mw-autoblockid' ],
1103  wfMessage( 'autoblockid', $this->mId )->text()
1104  );
1105  } else {
1106  return htmlspecialchars( $this->getTarget() );
1107  }
1108  }
1109 
1116  public static function getAutoblockExpiry( $timestamp ) {
1117  global $wgAutoblockExpiry;
1118 
1119  return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1120  }
1121 
1125  public static function purgeExpired() {
1126  if ( wfReadOnly() ) {
1127  return;
1128  }
1129 
1131  wfGetDB( DB_MASTER ),
1132  __METHOD__,
1133  function ( IDatabase $dbw, $fname ) {
1134  $ids = $dbw->selectFieldValues( 'ipblocks',
1135  'ipb_id',
1136  [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1137  $fname
1138  );
1139  if ( $ids ) {
1140  $blockRestrictionStore = MediaWikiServices::getInstance()->getBlockRestrictionStore();
1141  $blockRestrictionStore->deleteByBlockId( $ids );
1142 
1143  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1144  }
1145  }
1146  ) );
1147  }
1148 
1169  public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1170  $blocks = self::newListFromTarget( $specificTarget, $vagueTarget, $fromMaster );
1171  return self::chooseMostSpecificBlock( $blocks );
1172  }
1173 
1183  public static function newListFromTarget(
1184  $specificTarget,
1185  $vagueTarget = null,
1186  $fromMaster = false
1187  ) {
1188  list( $target, $type ) = self::parseTarget( $specificTarget );
1189  if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1190  $block = self::newFromID( $target );
1191  return $block ? [ $block ] : [];
1192  } elseif ( $target === null && $vagueTarget == '' ) {
1193  # We're not going to find anything useful here
1194  # Be aware that the == '' check is explicit, since empty values will be
1195  # passed by some callers (T31116)
1196  return [];
1197  } elseif ( in_array(
1198  $type,
1199  [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1200  ) {
1201  return self::newLoad( $target, $type, $fromMaster, $vagueTarget );
1202  }
1203  return [];
1204  }
1205 
1216  public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1217  if ( $ipChain === [] ) {
1218  return [];
1219  }
1220 
1221  $conds = [];
1222  $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1223  foreach ( array_unique( $ipChain ) as $ipaddr ) {
1224  # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1225  # necessarily trust the header given to us, make sure that we are only
1226  # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1227  # Do not treat private IP spaces as special as it may be desirable for wikis
1228  # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1229  if ( !IP::isValid( $ipaddr ) ) {
1230  continue;
1231  }
1232  # Don't check trusted IPs (includes local CDNs which will be in every request)
1233  if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1234  continue;
1235  }
1236  # Check both the original IP (to check against single blocks), as well as build
1237  # the clause to check for rangeblocks for the given IP.
1238  $conds['ipb_address'][] = $ipaddr;
1239  $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1240  }
1241 
1242  if ( $conds === [] ) {
1243  return [];
1244  }
1245 
1246  if ( $fromMaster ) {
1247  $db = wfGetDB( DB_MASTER );
1248  } else {
1249  $db = wfGetDB( DB_REPLICA );
1250  }
1251  $conds = $db->makeList( $conds, LIST_OR );
1252  if ( !$isAnon ) {
1253  $conds = [ $conds, 'ipb_anon_only' => 0 ];
1254  }
1255  $blockQuery = self::getQueryInfo();
1256  $rows = $db->select(
1257  $blockQuery['tables'],
1258  array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1259  $conds,
1260  __METHOD__,
1261  [],
1262  $blockQuery['joins']
1263  );
1264 
1265  $blocks = [];
1266  foreach ( $rows as $row ) {
1267  $block = self::newFromRow( $row );
1268  if ( !$block->isExpired() ) {
1269  $blocks[] = $block;
1270  }
1271  }
1272 
1273  return $blocks;
1274  }
1275 
1297  public static function chooseBlock( array $blocks, array $ipChain ) {
1298  if ( $blocks === [] ) {
1299  return null;
1300  } elseif ( count( $blocks ) == 1 ) {
1301  return $blocks[0];
1302  }
1303 
1304  // Sort hard blocks before soft ones and secondarily sort blocks
1305  // that disable account creation before those that don't.
1306  usort( $blocks, function ( DatabaseBlock $a, DatabaseBlock $b ) {
1307  $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1308  $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1309  return strcmp( $bWeight, $aWeight ); // highest weight first
1310  } );
1311 
1312  $blocksListExact = [
1313  'hard' => false,
1314  'disable_create' => false,
1315  'other' => false,
1316  'auto' => false
1317  ];
1318  $blocksListRange = [
1319  'hard' => false,
1320  'disable_create' => false,
1321  'other' => false,
1322  'auto' => false
1323  ];
1324  $ipChain = array_reverse( $ipChain );
1325 
1326  foreach ( $blocks as $block ) {
1327  // Stop searching if we have already have a "better" block. This
1328  // is why the order of the blocks matters
1329  if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1330  break;
1331  } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1332  break;
1333  }
1334 
1335  foreach ( $ipChain as $checkip ) {
1336  $checkipHex = IP::toHex( $checkip );
1337  if ( (string)$block->getTarget() === $checkip ) {
1338  if ( $block->isHardblock() ) {
1339  $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1340  } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1341  $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1342  } elseif ( $block->mAuto ) {
1343  $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1344  } else {
1345  $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1346  }
1347  // We found closest exact match in the ip list, so go to the next block
1348  break;
1349  } elseif ( array_filter( $blocksListExact ) == []
1350  && $block->getRangeStart() <= $checkipHex
1351  && $block->getRangeEnd() >= $checkipHex
1352  ) {
1353  if ( $block->isHardblock() ) {
1354  $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1355  } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1356  $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1357  } elseif ( $block->mAuto ) {
1358  $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1359  } else {
1360  $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1361  }
1362  break;
1363  }
1364  }
1365  }
1366 
1367  if ( array_filter( $blocksListExact ) == [] ) {
1368  $blocksList = &$blocksListRange;
1369  } else {
1370  $blocksList = &$blocksListExact;
1371  }
1372 
1373  $chosenBlock = null;
1374  if ( $blocksList['hard'] ) {
1375  $chosenBlock = $blocksList['hard'];
1376  } elseif ( $blocksList['disable_create'] ) {
1377  $chosenBlock = $blocksList['disable_create'];
1378  } elseif ( $blocksList['other'] ) {
1379  $chosenBlock = $blocksList['other'];
1380  } elseif ( $blocksList['auto'] ) {
1381  $chosenBlock = $blocksList['auto'];
1382  } else {
1383  throw new MWException( "Proxy block found, but couldn't be classified." );
1384  }
1385 
1386  return $chosenBlock;
1387  }
1388 
1395  public function getType() {
1396  return $this->mAuto
1397  ? self::TYPE_AUTO
1398  : parent::getType();
1399  }
1400 
1409  public function setCookie( WebResponse $response ) {
1410  MediaWikiServices::getInstance()->getBlockManager()->setBlockCookie( $this, $response );
1411  }
1412 
1420  public static function clearCookie( WebResponse $response ) {
1421  MediaWikiServices::getInstance()->getBlockManager()->clearBlockCookie( $response );
1422  }
1423 
1434  public function getCookieValue() {
1435  return MediaWikiServices::getInstance()->getBlockManager()->getCookieValue( $this );
1436  }
1437 
1447  public static function getIdFromCookieValue( $cookieValue ) {
1448  return MediaWikiServices::getInstance()->getBlockManager()->getIdFromCookieValue( $cookieValue );
1449  }
1450 
1457  $params = $this->getBlockErrorParams( $context );
1458 
1459  $msg = 'blockedtext';
1460  if ( $this->mAuto ) {
1461  $msg = 'autoblockedtext';
1462  } elseif ( !$this->isSitewide() ) {
1463  $msg = 'blockedtext-partial';
1464  }
1465 
1466  array_unshift( $params, $msg );
1467 
1468  return $params;
1469  }
1470 
1480  public function getRestrictions() {
1481  if ( $this->restrictions === null ) {
1482  // If the block id has not been set, then do not attempt to load the
1483  // restrictions.
1484  if ( !$this->mId ) {
1485  return [];
1486  }
1487  $this->restrictions = $this->getBlockRestrictionStore()->loadByBlockId( $this->mId );
1488  }
1489 
1490  return $this->restrictions;
1491  }
1492 
1500  public function setRestrictions( array $restrictions ) {
1501  $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1502  return $restriction instanceof Restriction;
1503  } );
1504 
1505  return $this;
1506  }
1507 
1511  public function appliesToTitle( Title $title ) {
1512  if ( $this->isSitewide() ) {
1513  return true;
1514  }
1515 
1516  $restrictions = $this->getRestrictions();
1517  foreach ( $restrictions as $restriction ) {
1518  if ( $restriction->matches( $title ) ) {
1519  return true;
1520  }
1521  }
1522 
1523  return false;
1524  }
1525 
1529  public function appliesToNamespace( $ns ) {
1530  if ( $this->isSitewide() ) {
1531  return true;
1532  }
1533 
1534  // Blocks do not apply to virtual namespaces.
1535  if ( $ns < 0 ) {
1536  return false;
1537  }
1538 
1539  $restriction = $this->findRestriction( NamespaceRestriction::TYPE, $ns );
1540 
1541  return (bool)$restriction;
1542  }
1543 
1547  public function appliesToPage( $pageId ) {
1548  if ( $this->isSitewide() ) {
1549  return true;
1550  }
1551 
1552  // If the pageId is not over zero, the block cannot apply to it.
1553  if ( $pageId <= 0 ) {
1554  return false;
1555  }
1556 
1557  $restriction = $this->findRestriction( PageRestriction::TYPE, $pageId );
1558 
1559  return (bool)$restriction;
1560  }
1561 
1569  private function findRestriction( $type, $value ) {
1570  $restrictions = $this->getRestrictions();
1571  foreach ( $restrictions as $restriction ) {
1572  if ( $restriction->getType() !== $type ) {
1573  continue;
1574  }
1575 
1576  if ( $restriction->getValue() === $value ) {
1577  return $restriction;
1578  }
1579  }
1580 
1581  return null;
1582  }
1583 
1589  public function shouldTrackWithCookie( $isAnon ) {
1590  wfDeprecated( __METHOD__, '1.34' );
1591  $config = RequestContext::getMain()->getConfig();
1592  switch ( $this->getType() ) {
1593  case self::TYPE_IP:
1594  case self::TYPE_RANGE:
1595  return $isAnon && $config->get( 'CookieSetOnIpBlock' );
1596  case self::TYPE_USER:
1597  return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
1598  default:
1599  return false;
1600  }
1601  }
1602 
1609  return MediaWikiServices::getInstance()->getBlockRestrictionStore();
1610  }
1611 }
1612 
1616 class_alias( DatabaseBlock::class, 'Block' );
insert(IDatabase $dbw=null)
Insert a block into the block table.
isUsertalkEditAllowed( $x=null)
Get or set the flag indicating whether this block blocks the target from editing their own user talk ...
Config $config
Definition: MediaWiki.php:43
static chooseBlock(array $blocks, array $ipChain)
From a list of multiple blocks, find the most exact and strongest block.
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:2620
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
initFromRow( $row)
Given a database row from the ipblocks table, initialize member variables.
static toHex( $ip)
Return a zero-padded upper case hexadecimal representation of an IP address.
Definition: IP.php:404
isCreateAccountBlocked( $x=null)
Get or set the flag indicating whether this block blocks the target from creating an account...
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
either a plain
Definition: hooks.txt:2032
getRangeStart()
Get the IP address at the start of the range in Hex form.
getDatabaseArray(IDatabase $dbw)
Get an array suitable for passing to $dbw->insert() or $dbw->update()
__construct(array $options=[])
Create a new block with specified option parameters on a user, IP or IP range.
static parseRange( $range)
Given a string range in a number of formats, return the start and end of the range in hexadecimal...
Definition: IP.php:500
$success
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
int $type
AbstractBlock::TYPE_ constant.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
equals(DatabaseBlock $block)
Check if two blocks are effectively equal.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
static newFromAnyId( $userId, $userName, $actorId, $dbDomain=false)
Static factory method for creation from an ID, name, and/or actor ID.
Definition: User.php:627
getAutoblockUpdateArray(IDatabase $dbw)
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:175
$value
getCookieValue()
Get the BlockID cookie&#39;s value for this block.
const SCHEMA_COMPAT_READ_NEW
Definition: Defines.php:267
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 MediaWikiServices
Definition: injection.txt:23
deleteIfExpired()
Check if a block has expired.
setBlocker( $user)
Set the user who implemented (or will implement) this block.
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
this hook is for auditing only $response
Definition: hooks.txt:767
static getInstance()
Returns the global default instance of the top level service locator.
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
const DB_MASTER
Definition: defines.php:26
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
doRetroactiveAutoblock()
Retroactively autoblocks the last IP used by the user (if it is a user) blocked by this block...
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1969
static getBlocksForIPList(array $ipChain, $isAnon, $fromMaster=false)
Get all blocks that match any IP from an array of IP addresses.
static defaultRetroactiveAutoblock(DatabaseBlock $block, array &$blockIds)
Retroactively autoblocks the last IP used by the user (if it is a user) blocked by this block...
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
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:1971
int $forcedTargetID
Hack for foreign blocking (CentralAuth)
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 '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:1244
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$wgBlockCIDRLimit
Limits on the possible sizes of range blocks.
static isWhitelistedFromAutoblocks( $ip)
Checks whether a given IP is on the autoblock whitelist.
wfReadOnly()
Check whether the wiki is in read-only mode.
static newMigration()
Static constructor.
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
static getMain()
Get the RequestContext object associated with the main request.
IContextSource $context
Definition: MediaWiki.php:38
const LIST_AND
Definition: Defines.php:39
setRestrictions(array $restrictions)
Set Restrictions.
isExpired()
Has the block expired?
getRangeEnd()
Get the IP address at the end of the range in Hex form.
isSitewide( $x=null)
Indicates that the block is a sitewide block.
fromMaster( $x=null)
Get/set a flag determining whether the master is used for reads.
$res
Definition: database.txt:21
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
$wgBlockDisablesLogin
If true, blocked users will not be allowed to login.
static isValid( $ip)
Validate an IP address.
Definition: IP.php:111
getRedactedName()
Get the block name, but with autoblocked IPs hidden as per standard privacy policy.
static getRangeCond( $start, $end=null)
Get a set of SQL conditions which will select rangeblocks encompassing a given range.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
$wgPutIPinRC
Log IP addresses in the recentchanges table; can be accessed only by extensions (e.g.
$cache
Definition: mcc.php:33
$params
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:1971
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
static newLoad( $specificTarget, $specificType, $fromMaster, $vagueTarget=null)
Load blocks from the database which target the specific target exactly, or which cover the vague targ...
getBlockErrorParams(IContextSource $context)
Get block information used in different block error messages.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
isEmailBlocked( $x=null)
Get or set the flag indicating whether this block blocks the target from sending emails.
static isInRange( $addr, $range)
Determine if a given IPv4/IPv6 address is in a given CIDR network.
Definition: IP.php:637
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static purgeExpired()
Purge expired blocks from the ipblocks table.
static newFromRow( $row)
Create a new DatabaseBlock object from a database row.
getPermissionsError(IContextSource $context)
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
Definition: distributors.txt:9
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:131
appliesToRight( $right)
Determine whether the block prevents a given right.
getBlockRestrictionStore()
Get a BlockRestrictionStore instance.
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the &#39;BlockID&#39; cookie.
const LIST_OR
Definition: Defines.php:42
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:35
getTimestamp()
Get the timestamp indicating when the block was created.
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...
setTimestamp( $timestamp)
Set the timestamp indicating when the block was created.
static isIPv6( $ip)
Given a string, determine if it as valid IP in IPv6 only.
Definition: IP.php:88
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
getBlocker()
Get the user who implemented this block.
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:22
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
$lines
Definition: router.php:61
static getStore()
static getAutoblockExpiry( $timestamp)
Get a timestamp of the expiry for autoblocks.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
getId()
Get the user&#39;s ID.
Definition: User.php:2224
getHideName()
Get whether the block hides the target&#39;s username.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
update()
Update a block in the DB with new parameters.
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new block object...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$line
Definition: cdb.php:59
static clearCookie(WebResponse $response)
Unset the &#39;BlockID&#39; cookie.
static selectFields()
Return the list of ipblocks fields that should be selected to create a new block. ...
isHardblock( $x=null)
Get/set whether the block is a hardblock (affects logged-in users on a given IP/range) ...
setHideName( $hideName)
Set whether ths block hides the target&#39;s username.
setId( $blockId)
Set the block ID.
setTarget( $target)
Set the target for this block, and update $this->type accordingly.
setExpiry( $expiry)
Set the block expiry time.
getExpiry()
Get the block expiry time.
static getCacheSetOptions(IDatabase $db1, IDatabase $db2=null)
Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estima...
Definition: Database.php:4392
getTarget()
Get the target for this particular block.
const DB_REPLICA
Definition: defines.php:25
getRestrictions()
Get Restrictions.
static newListFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
This is similar to DatabaseBlock::newFromTarget, but it returns all the relevant blocks.
static newFromID( $id)
Load a block from the block id.
static getIpFragment( $hex)
Get the component of an IP address which is certain to be the same between an IP address and a rangeb...
doAutoblock( $autoblockIP)
Autoblocks the given IP, referring to this block.
isValid()
Is the block address valid (i.e.
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
findRestriction( $type, $value)
Find Restriction by type and value.
setReason( $reason)
Set the reason for creating the block.
static parseCIDR( $range)
Convert a network specification in CIDR notation to an integer network and a number of bits...
Definition: IP.php:457
addQuotes( $s)
Adds quotes and backslashes.
static chooseMostSpecificBlock(array $blocks)
Choose the most specific block from some combination of user, IP and IP range blocks.
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target&#39;s type, get an existing block object if possible.
getReason()
Get the reason given for creating the block.
setCookie(WebResponse $response)
Set the &#39;BlockID&#39; cookie to this block&#39;s ID and expiry time.
updateTimestamp()
Update the timestamp on autoblocks.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
$wgAutoblockExpiry
Number of seconds before autoblock entries expire.