MediaWiki  master
Block.php
Go to the documentation of this file.
1 <?php
30 
31 class Block {
33  public $mReason;
34 
36  public $mTimestamp;
37 
39  public $mAuto;
40 
42  public $mExpiry;
43 
45  public $mHideName;
46 
49 
51  private $mId;
52 
54  private $mFromMaster;
55 
57  private $mBlockEmail;
58 
61 
63  private $mCreateAccount;
64 
66  private $target;
67 
69  private $forcedTargetID;
70 
75  private $type;
76 
78  private $blocker;
79 
81  private $isHardblock;
82 
84  private $isAutoblocking;
85 
88 
90  private $isSitewide;
91 
93  private $restrictions;
94 
95  # TYPE constants
96  const TYPE_USER = 1;
97  const TYPE_IP = 2;
98  const TYPE_RANGE = 3;
99  const TYPE_AUTO = 4;
100  const TYPE_ID = 5;
101 
128  function __construct( $options = [] ) {
129  $defaults = [
130  'address' => '',
131  'user' => null,
132  'by' => null,
133  'reason' => '',
134  'timestamp' => '',
135  'auto' => false,
136  'expiry' => '',
137  'anonOnly' => false,
138  'createAccount' => false,
139  'enableAutoblock' => false,
140  'hideName' => false,
141  'blockEmail' => false,
142  'allowUsertalk' => false,
143  'byText' => '',
144  'systemBlock' => null,
145  'sitewide' => true,
146  ];
147 
148  if ( func_num_args() > 1 || !is_array( $options ) ) {
149  $options = array_combine(
150  array_slice( array_keys( $defaults ), 0, func_num_args() ),
151  func_get_args()
152  );
153  wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
154  }
155 
156  $options += $defaults;
157 
158  $this->setTarget( $options['address'] );
159 
160  if ( $this->target instanceof User && $options['user'] ) {
161  # Needed for foreign users
162  $this->forcedTargetID = $options['user'];
163  }
164 
165  if ( $options['by'] ) {
166  # Local user
167  $this->setBlocker( User::newFromId( $options['by'] ) );
168  } else {
169  # Foreign user
170  $this->setBlocker( $options['byText'] );
171  }
172 
173  $this->mReason = $options['reason'];
174  $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
175  $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
176 
177  # Boolean settings
178  $this->mAuto = (bool)$options['auto'];
179  $this->mHideName = (bool)$options['hideName'];
180  $this->isHardblock( !$options['anonOnly'] );
181  $this->isAutoblocking( (bool)$options['enableAutoblock'] );
182  $this->isSitewide( (bool)$options['sitewide'] );
183 
184  # Prevention measures
185  $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
186  $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
187  $this->prevents( 'createaccount', (bool)$options['createAccount'] );
188 
189  $this->mFromMaster = false;
190  $this->systemBlockType = $options['systemBlock'];
191  }
192 
199  public static function newFromID( $id ) {
200  $dbr = wfGetDB( DB_REPLICA );
201  $blockQuery = self::getQueryInfo();
202  $res = $dbr->selectRow(
203  $blockQuery['tables'],
204  $blockQuery['fields'],
205  [ 'ipb_id' => $id ],
206  __METHOD__,
207  [],
208  $blockQuery['joins']
209  );
210  if ( $res ) {
211  return self::newFromRow( $res );
212  } else {
213  return null;
214  }
215  }
216 
223  public static function selectFields() {
225 
226  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
227  // If code is using this instead of self::getQueryInfo(), there's a
228  // decent chance it's going to try to directly access
229  // $row->ipb_by or $row->ipb_by_text and we can't give it
230  // useful values here once those aren't being used anymore.
231  throw new BadMethodCallException(
232  'Cannot use ' . __METHOD__
233  . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
234  );
235  }
236 
237  wfDeprecated( __METHOD__, '1.31' );
238  return [
239  'ipb_id',
240  'ipb_address',
241  'ipb_by',
242  'ipb_by_text',
243  'ipb_by_actor' => 'NULL',
244  'ipb_timestamp',
245  'ipb_auto',
246  'ipb_anon_only',
247  'ipb_create_account',
248  'ipb_enable_autoblock',
249  'ipb_expiry',
250  'ipb_deleted',
251  'ipb_block_email',
252  'ipb_allow_usertalk',
253  'ipb_parent_block_id',
254  'ipb_sitewide',
255  ] + CommentStore::getStore()->getFields( 'ipb_reason' );
256  }
257 
267  public static function getQueryInfo() {
268  $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
269  $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
270  return [
271  'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
272  'fields' => [
273  'ipb_id',
274  'ipb_address',
275  'ipb_timestamp',
276  'ipb_auto',
277  'ipb_anon_only',
278  'ipb_create_account',
279  'ipb_enable_autoblock',
280  'ipb_expiry',
281  'ipb_deleted',
282  'ipb_block_email',
283  'ipb_allow_usertalk',
284  'ipb_parent_block_id',
285  'ipb_sitewide',
286  ] + $commentQuery['fields'] + $actorQuery['fields'],
287  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
288  ];
289  }
290 
299  public function equals( Block $block ) {
300  return (
301  (string)$this->target == (string)$block->target
302  && $this->type == $block->type
303  && $this->mAuto == $block->mAuto
304  && $this->isHardblock() == $block->isHardblock()
305  && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
306  && $this->mExpiry == $block->mExpiry
307  && $this->isAutoblocking() == $block->isAutoblocking()
308  && $this->mHideName == $block->mHideName
309  && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
310  && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
311  && $this->mReason == $block->mReason
312  && $this->isSitewide() == $block->isSitewide()
313  // Block::getRestrictions() may perform a database query, so keep it at
314  // the end.
315  && BlockRestriction::equals( $this->getRestrictions(), $block->getRestrictions() )
316  );
317  }
318 
329  protected function newLoad( $vagueTarget = null ) {
330  $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
331 
332  if ( $this->type !== null ) {
333  $conds = [
334  'ipb_address' => [ (string)$this->target ],
335  ];
336  } else {
337  $conds = [ 'ipb_address' => [] ];
338  }
339 
340  # Be aware that the != '' check is explicit, since empty values will be
341  # passed by some callers (T31116)
342  if ( $vagueTarget != '' ) {
343  list( $target, $type ) = self::parseTarget( $vagueTarget );
344  switch ( $type ) {
345  case self::TYPE_USER:
346  # Slightly weird, but who are we to argue?
347  $conds['ipb_address'][] = (string)$target;
348  break;
349 
350  case self::TYPE_IP:
351  $conds['ipb_address'][] = (string)$target;
352  $conds[] = self::getRangeCond( IP::toHex( $target ) );
353  $conds = $db->makeList( $conds, LIST_OR );
354  break;
355 
356  case self::TYPE_RANGE:
357  list( $start, $end ) = IP::parseRange( $target );
358  $conds['ipb_address'][] = (string)$target;
359  $conds[] = self::getRangeCond( $start, $end );
360  $conds = $db->makeList( $conds, LIST_OR );
361  break;
362 
363  default:
364  throw new MWException( "Tried to load block with invalid type" );
365  }
366  }
367 
368  $blockQuery = self::getQueryInfo();
369  $res = $db->select(
370  $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
371  );
372 
373  # This result could contain a block on the user, a block on the IP, and a russian-doll
374  # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
375  $bestRow = null;
376 
377  # Lower will be better
378  $bestBlockScore = 100;
379 
380  # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
381  $bestBlockPreventsEdit = null;
382 
383  foreach ( $res as $row ) {
384  $block = self::newFromRow( $row );
385 
386  # Don't use expired blocks
387  if ( $block->isExpired() ) {
388  continue;
389  }
390 
391  # Don't use anon only blocks on users
392  if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
393  continue;
394  }
395 
396  if ( $block->getType() == self::TYPE_RANGE ) {
397  # This is the number of bits that are allowed to vary in the block, give
398  # or take some floating point errors
399  $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
400  $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
401  $size = log( $end - $start + 1, 2 );
402 
403  # This has the nice property that a /32 block is ranked equally with a
404  # single-IP block, which is exactly what it is...
405  $score = self::TYPE_RANGE - 1 + ( $size / 128 );
406 
407  } else {
408  $score = $block->getType();
409  }
410 
411  if ( $score < $bestBlockScore ) {
412  $bestBlockScore = $score;
413  $bestRow = $row;
414  $bestBlockPreventsEdit = $block->prevents( 'edit' );
415  }
416  }
417 
418  if ( $bestRow !== null ) {
419  $this->initFromRow( $bestRow );
420  $this->prevents( 'edit', $bestBlockPreventsEdit );
421  return true;
422  } else {
423  return false;
424  }
425  }
426 
433  public static function getRangeCond( $start, $end = null ) {
434  if ( $end === null ) {
435  $end = $start;
436  }
437  # Per T16634, we want to include relevant active rangeblocks; for
438  # rangeblocks, we want to include larger ranges which enclose the given
439  # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
440  # so we can improve performance by filtering on a LIKE clause
441  $chunk = self::getIpFragment( $start );
442  $dbr = wfGetDB( DB_REPLICA );
443  $like = $dbr->buildLike( $chunk, $dbr->anyString() );
444 
445  # Fairly hard to make a malicious SQL statement out of hex characters,
446  # but stranger things have happened...
447  $safeStart = $dbr->addQuotes( $start );
448  $safeEnd = $dbr->addQuotes( $end );
449 
450  return $dbr->makeList(
451  [
452  "ipb_range_start $like",
453  "ipb_range_start <= $safeStart",
454  "ipb_range_end >= $safeEnd",
455  ],
456  LIST_AND
457  );
458  }
459 
466  protected static function getIpFragment( $hex ) {
467  global $wgBlockCIDRLimit;
468  if ( substr( $hex, 0, 3 ) == 'v6-' ) {
469  return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
470  } else {
471  return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
472  }
473  }
474 
480  protected function initFromRow( $row ) {
481  $this->setTarget( $row->ipb_address );
483  $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
484  ) );
485 
486  $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
487  $this->mAuto = $row->ipb_auto;
488  $this->mHideName = $row->ipb_deleted;
489  $this->mId = (int)$row->ipb_id;
490  $this->mParentBlockId = $row->ipb_parent_block_id;
491 
492  // I wish I didn't have to do this
493  $db = wfGetDB( DB_REPLICA );
494  $this->mExpiry = $db->decodeExpiry( $row->ipb_expiry );
495  $this->mReason = CommentStore::getStore()
496  // Legacy because $row may have come from self::selectFields()
497  ->getCommentLegacy( $db, 'ipb_reason', $row )->text;
498 
499  $this->isHardblock( !$row->ipb_anon_only );
500  $this->isAutoblocking( $row->ipb_enable_autoblock );
501  $this->isSitewide( (bool)$row->ipb_sitewide );
502 
503  $this->prevents( 'createaccount', $row->ipb_create_account );
504  $this->prevents( 'sendemail', $row->ipb_block_email );
505  $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
506  }
507 
513  public static function newFromRow( $row ) {
514  $block = new Block;
515  $block->initFromRow( $row );
516  return $block;
517  }
518 
525  public function delete() {
526  if ( wfReadOnly() ) {
527  return false;
528  }
529 
530  if ( !$this->getId() ) {
531  throw new MWException( "Block::delete() requires that the mId member be filled\n" );
532  }
533 
534  $dbw = wfGetDB( DB_MASTER );
535 
536  BlockRestriction::deleteByParentBlockId( $this->getId() );
537  $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
538 
539  BlockRestriction::deleteByBlockId( $this->getId() );
540  $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
541 
542  return $dbw->affectedRows() > 0;
543  }
544 
553  public function insert( $dbw = null ) {
554  global $wgBlockDisablesLogin;
555 
556  if ( $this->getSystemBlockType() !== null ) {
557  throw new MWException( 'Cannot insert a system block into the database' );
558  }
559  if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
560  throw new MWException( 'Cannot insert a block without a blocker set' );
561  }
562 
563  wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
564 
565  if ( $dbw === null ) {
566  $dbw = wfGetDB( DB_MASTER );
567  }
568 
569  self::purgeExpired();
570 
571  $row = $this->getDatabaseArray( $dbw );
572 
573  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
574  $affected = $dbw->affectedRows();
575  if ( $affected ) {
576  $this->setId( $dbw->insertId() );
577  if ( $this->restrictions ) {
578  BlockRestriction::insert( $this->restrictions );
579  }
580  }
581 
582  # Don't collide with expired blocks.
583  # Do this after trying to insert to avoid locking.
584  if ( !$affected ) {
585  # T96428: The ipb_address index uses a prefix on a field, so
586  # use a standard SELECT + DELETE to avoid annoying gap locks.
587  $ids = $dbw->selectFieldValues( 'ipblocks',
588  'ipb_id',
589  [
590  'ipb_address' => $row['ipb_address'],
591  'ipb_user' => $row['ipb_user'],
592  'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
593  ],
594  __METHOD__
595  );
596  if ( $ids ) {
597  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
598  BlockRestriction::deleteByBlockId( $ids );
599  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
600  $affected = $dbw->affectedRows();
601  $this->setId( $dbw->insertId() );
602  if ( $this->restrictions ) {
603  BlockRestriction::insert( $this->restrictions );
604  }
605  }
606  }
607 
608  if ( $affected ) {
609  $auto_ipd_ids = $this->doRetroactiveAutoblock();
610 
611  if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
612  // Change user login token to force them to be logged out.
613  $this->target->setToken();
614  $this->target->saveSettings();
615  }
616 
617  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
618  }
619 
620  return false;
621  }
622 
630  public function update() {
631  wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
632  $dbw = wfGetDB( DB_MASTER );
633 
634  $dbw->startAtomic( __METHOD__ );
635 
636  $result = $dbw->update(
637  'ipblocks',
638  $this->getDatabaseArray( $dbw ),
639  [ 'ipb_id' => $this->getId() ],
640  __METHOD__
641  );
642 
643  // Only update the restrictions if they have been modified.
644  if ( $this->restrictions !== null ) {
645  // An empty array should remove all of the restrictions.
646  if ( empty( $this->restrictions ) ) {
647  $success = BlockRestriction::deleteByBlockId( $this->getId() );
648  } else {
649  $success = BlockRestriction::update( $this->restrictions );
650  }
651  // Update the result. The first false is the result, otherwise, true.
652  $result = $result && $success;
653  }
654 
655  if ( $this->isAutoblocking() ) {
656  // update corresponding autoblock(s) (T50813)
657  $dbw->update(
658  'ipblocks',
659  $this->getAutoblockUpdateArray( $dbw ),
660  [ 'ipb_parent_block_id' => $this->getId() ],
661  __METHOD__
662  );
663 
664  // Only update the restrictions if they have been modified.
665  if ( $this->restrictions !== null ) {
666  BlockRestriction::updateByParentBlockId( $this->getId(), $this->restrictions );
667  }
668  } else {
669  // autoblock no longer required, delete corresponding autoblock(s)
670  BlockRestriction::deleteByParentBlockId( $this->getId() );
671  $dbw->delete(
672  'ipblocks',
673  [ 'ipb_parent_block_id' => $this->getId() ],
674  __METHOD__
675  );
676  }
677 
678  $dbw->endAtomic( __METHOD__ );
679 
680  if ( $result ) {
681  $auto_ipd_ids = $this->doRetroactiveAutoblock();
682  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
683  }
684 
685  return $result;
686  }
687 
693  protected function getDatabaseArray( IDatabase $dbw ) {
694  $expiry = $dbw->encodeExpiry( $this->mExpiry );
695 
696  if ( $this->forcedTargetID ) {
697  $uid = $this->forcedTargetID;
698  } else {
699  $uid = $this->target instanceof User ? $this->target->getId() : 0;
700  }
701 
702  $a = [
703  'ipb_address' => (string)$this->target,
704  'ipb_user' => $uid,
705  'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
706  'ipb_auto' => $this->mAuto,
707  'ipb_anon_only' => !$this->isHardblock(),
708  'ipb_create_account' => $this->prevents( 'createaccount' ),
709  'ipb_enable_autoblock' => $this->isAutoblocking(),
710  'ipb_expiry' => $expiry,
711  'ipb_range_start' => $this->getRangeStart(),
712  'ipb_range_end' => $this->getRangeEnd(),
713  'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
714  'ipb_block_email' => $this->prevents( 'sendemail' ),
715  'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
716  'ipb_parent_block_id' => $this->mParentBlockId,
717  'ipb_sitewide' => $this->isSitewide(),
718  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
719  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
720 
721  return $a;
722  }
723 
728  protected function getAutoblockUpdateArray( IDatabase $dbw ) {
729  return [
730  'ipb_create_account' => $this->prevents( 'createaccount' ),
731  'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
732  'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
733  'ipb_sitewide' => $this->isSitewide(),
734  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
735  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
736  }
737 
744  protected function doRetroactiveAutoblock() {
745  $blockIds = [];
746  # If autoblock is enabled, autoblock the LAST IP(s) used
747  if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
748  wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
749 
750  $continue = Hooks::run(
751  'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
752 
753  if ( $continue ) {
754  self::defaultRetroactiveAutoblock( $this, $blockIds );
755  }
756  }
757  return $blockIds;
758  }
759 
767  protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
768  global $wgPutIPinRC;
769 
770  // No IPs are in recentchanges table, so nothing to select
771  if ( !$wgPutIPinRC ) {
772  return;
773  }
774 
775  // Autoblocks only apply to TYPE_USER
776  if ( $block->getType() !== self::TYPE_USER ) {
777  return;
778  }
779  $target = $block->getTarget(); // TYPE_USER => always a User object
780 
781  $dbr = wfGetDB( DB_REPLICA );
782  $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
783 
784  $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
785 
786  // Just the last IP used.
787  $options['LIMIT'] = 1;
788 
789  $res = $dbr->select(
790  [ 'recentchanges' ] + $rcQuery['tables'],
791  [ 'rc_ip' ],
792  $rcQuery['conds'],
793  __METHOD__,
794  $options,
795  $rcQuery['joins']
796  );
797 
798  if ( !$res->numRows() ) {
799  # No results, don't autoblock anything
800  wfDebug( "No IP found to retroactively autoblock\n" );
801  } else {
802  foreach ( $res as $row ) {
803  if ( $row->rc_ip ) {
804  $id = $block->doAutoblock( $row->rc_ip );
805  if ( $id ) {
806  $blockIds[] = $id;
807  }
808  }
809  }
810  }
811  }
812 
820  public static function isWhitelistedFromAutoblocks( $ip ) {
821  // Try to get the autoblock_whitelist from the cache, as it's faster
822  // than getting the msg raw and explode()'ing it.
823  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
824  $lines = $cache->getWithSetCallback(
825  $cache->makeKey( 'ip-autoblock', 'whitelist' ),
826  $cache::TTL_DAY,
827  function ( $curValue, &$ttl, array &$setOpts ) {
828  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
829 
830  return explode( "\n",
831  wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
832  }
833  );
834 
835  wfDebug( "Checking the autoblock whitelist..\n" );
836 
837  foreach ( $lines as $line ) {
838  # List items only
839  if ( substr( $line, 0, 1 ) !== '*' ) {
840  continue;
841  }
842 
843  $wlEntry = substr( $line, 1 );
844  $wlEntry = trim( $wlEntry );
845 
846  wfDebug( "Checking $ip against $wlEntry..." );
847 
848  # Is the IP in this range?
849  if ( IP::isInRange( $ip, $wlEntry ) ) {
850  wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
851  return true;
852  } else {
853  wfDebug( " No match\n" );
854  }
855  }
856 
857  return false;
858  }
859 
866  public function doAutoblock( $autoblockIP ) {
867  # If autoblocks are disabled, go away.
868  if ( !$this->isAutoblocking() ) {
869  return false;
870  }
871 
872  # Don't autoblock for system blocks
873  if ( $this->getSystemBlockType() !== null ) {
874  throw new MWException( 'Cannot autoblock from a system block' );
875  }
876 
877  # Check for presence on the autoblock whitelist.
878  if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
879  return false;
880  }
881 
882  // Avoid PHP 7.1 warning of passing $this by reference
883  $block = $this;
884  # Allow hooks to cancel the autoblock.
885  if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
886  wfDebug( "Autoblock aborted by hook.\n" );
887  return false;
888  }
889 
890  # It's okay to autoblock. Go ahead and insert/update the block...
891 
892  # Do not add a *new* block if the IP is already blocked.
893  $ipblock = self::newFromTarget( $autoblockIP );
894  if ( $ipblock ) {
895  # Check if the block is an autoblock and would exceed the user block
896  # if renewed. If so, do nothing, otherwise prolong the block time...
897  if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
898  $this->mExpiry > self::getAutoblockExpiry( $ipblock->mTimestamp )
899  ) {
900  # Reset block timestamp to now and its expiry to
901  # $wgAutoblockExpiry in the future
902  $ipblock->updateTimestamp();
903  }
904  return false;
905  }
906 
907  # Make a new block object with the desired properties.
908  $autoblock = new Block;
909  wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
910  $autoblock->setTarget( $autoblockIP );
911  $autoblock->setBlocker( $this->getBlocker() );
912  $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
913  ->inContentLanguage()->plain();
914  $timestamp = wfTimestampNow();
915  $autoblock->mTimestamp = $timestamp;
916  $autoblock->mAuto = 1;
917  $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
918  # Continue suppressing the name if needed
919  $autoblock->mHideName = $this->mHideName;
920  $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
921  $autoblock->mParentBlockId = $this->mId;
922  $autoblock->isSitewide( $this->isSitewide() );
923  $autoblock->setRestrictions( $this->getRestrictions() );
924 
925  if ( $this->mExpiry == 'infinity' ) {
926  # Original block was indefinite, start an autoblock now
927  $autoblock->mExpiry = self::getAutoblockExpiry( $timestamp );
928  } else {
929  # If the user is already blocked with an expiry date, we don't
930  # want to pile on top of that.
931  $autoblock->mExpiry = min( $this->mExpiry, self::getAutoblockExpiry( $timestamp ) );
932  }
933 
934  # Insert the block...
935  $status = $autoblock->insert();
936  return $status
937  ? $status['id']
938  : false;
939  }
940 
945  public function deleteIfExpired() {
946  if ( $this->isExpired() ) {
947  wfDebug( "Block::deleteIfExpired() -- deleting\n" );
948  $this->delete();
949  $retVal = true;
950  } else {
951  wfDebug( "Block::deleteIfExpired() -- not expired\n" );
952  $retVal = false;
953  }
954 
955  return $retVal;
956  }
957 
962  public function isExpired() {
963  $timestamp = wfTimestampNow();
964  wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
965 
966  if ( !$this->mExpiry ) {
967  return false;
968  } else {
969  return $timestamp > $this->mExpiry;
970  }
971  }
972 
977  public function isValid() {
978  return $this->getTarget() != null;
979  }
980 
984  public function updateTimestamp() {
985  if ( $this->mAuto ) {
986  $this->mTimestamp = wfTimestamp();
987  $this->mExpiry = self::getAutoblockExpiry( $this->mTimestamp );
988 
989  $dbw = wfGetDB( DB_MASTER );
990  $dbw->update( 'ipblocks',
991  [ /* SET */
992  'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
993  'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
994  ],
995  [ /* WHERE */
996  'ipb_id' => $this->getId(),
997  ],
998  __METHOD__
999  );
1000  }
1001  }
1002 
1008  public function getRangeStart() {
1009  switch ( $this->type ) {
1010  case self::TYPE_USER:
1011  return '';
1012  case self::TYPE_IP:
1013  return IP::toHex( $this->target );
1014  case self::TYPE_RANGE:
1015  list( $start, /*...*/ ) = IP::parseRange( $this->target );
1016  return $start;
1017  default:
1018  throw new MWException( "Block with invalid type" );
1019  }
1020  }
1021 
1027  public function getRangeEnd() {
1028  switch ( $this->type ) {
1029  case self::TYPE_USER:
1030  return '';
1031  case self::TYPE_IP:
1032  return IP::toHex( $this->target );
1033  case self::TYPE_RANGE:
1034  list( /*...*/, $end ) = IP::parseRange( $this->target );
1035  return $end;
1036  default:
1037  throw new MWException( "Block with invalid type" );
1038  }
1039  }
1040 
1046  public function getBy() {
1047  $blocker = $this->getBlocker();
1048  return ( $blocker instanceof User )
1049  ? $blocker->getId()
1050  : 0;
1051  }
1052 
1058  public function getByName() {
1059  $blocker = $this->getBlocker();
1060  return ( $blocker instanceof User )
1061  ? $blocker->getName()
1062  : (string)$blocker; // username
1063  }
1064 
1069  public function getId() {
1070  return $this->mId;
1071  }
1072 
1079  private function setId( $blockId ) {
1080  $this->mId = (int)$blockId;
1081 
1082  if ( is_array( $this->restrictions ) ) {
1083  $this->restrictions = BlockRestriction::setBlockId( $blockId, $this->restrictions );
1084  }
1085 
1086  return $this;
1087  }
1088 
1094  public function getSystemBlockType() {
1095  return $this->systemBlockType;
1096  }
1097 
1104  public function fromMaster( $x = null ) {
1105  return wfSetVar( $this->mFromMaster, $x );
1106  }
1107 
1113  public function isHardblock( $x = null ) {
1114  wfSetVar( $this->isHardblock, $x );
1115 
1116  # You can't *not* hardblock a user
1117  return $this->getType() == self::TYPE_USER
1118  ? true
1120  }
1121 
1126  public function isAutoblocking( $x = null ) {
1127  wfSetVar( $this->isAutoblocking, $x );
1128 
1129  # You can't put an autoblock on an IP or range as we don't have any history to
1130  # look over to get more IPs from
1131  return $this->getType() == self::TYPE_USER
1132  ? $this->isAutoblocking
1133  : false;
1134  }
1135 
1145  public function isSitewide( $x = null ) {
1146  return wfSetVar( $this->isSitewide, $x );
1147  }
1148 
1156  public function prevents( $action, $x = null ) {
1157  $config = RequestContext::getMain()->getConfig();
1158  $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1159  $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1160 
1161  $res = null;
1162  switch ( $action ) {
1163  case 'edit':
1164  # For now... <evil laugh>
1165  $res = true;
1166  break;
1167  case 'createaccount':
1168  $res = wfSetVar( $this->mCreateAccount, $x );
1169  break;
1170  case 'sendemail':
1171  $res = wfSetVar( $this->mBlockEmail, $x );
1172  break;
1173  case 'upload':
1174  // Until T6995 is completed
1175  $res = $this->isSitewide();
1176  break;
1177  case 'editownusertalk':
1178  // NOTE: this check is not reliable on partial blocks
1179  // since partially blocked users are always allowed to edit
1180  // their own talk page unless a restriction exists on the
1181  // page or User_talk: namespace
1182  $res = wfSetVar( $this->mDisableUsertalk, $x );
1183 
1184  // edit own user talk can be disabled by config
1185  if ( !$blockAllowsUTEdit ) {
1186  $res = true;
1187  }
1188  break;
1189  case 'read':
1190  $res = false;
1191  break;
1192  case 'purge':
1193  $res = false;
1194  break;
1195  }
1196  if ( !$res && $blockDisablesLogin ) {
1197  // If a block would disable login, then it should
1198  // prevent any action that all users cannot do
1199  $anon = new User;
1200  $res = $anon->isAllowed( $action ) ? $res : true;
1201  }
1202 
1203  return $res;
1204  }
1205 
1210  public function getRedactedName() {
1211  if ( $this->mAuto ) {
1212  return Html::rawElement(
1213  'span',
1214  [ 'class' => 'mw-autoblockid' ],
1215  wfMessage( 'autoblockid', $this->mId )
1216  );
1217  } else {
1218  return htmlspecialchars( $this->getTarget() );
1219  }
1220  }
1221 
1228  public static function getAutoblockExpiry( $timestamp ) {
1229  global $wgAutoblockExpiry;
1230 
1231  return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1232  }
1233 
1237  public static function purgeExpired() {
1238  if ( wfReadOnly() ) {
1239  return;
1240  }
1241 
1243  wfGetDB( DB_MASTER ),
1244  __METHOD__,
1245  function ( IDatabase $dbw, $fname ) {
1246  $ids = $dbw->selectFieldValues( 'ipblocks',
1247  'ipb_id',
1248  [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1249  $fname
1250  );
1251  if ( $ids ) {
1252  BlockRestriction::deleteByBlockId( $ids );
1253  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1254  }
1255  }
1256  ) );
1257  }
1258 
1279  public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1280  list( $target, $type ) = self::parseTarget( $specificTarget );
1281  if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1282  return self::newFromID( $target );
1283 
1284  } elseif ( $target === null && $vagueTarget == '' ) {
1285  # We're not going to find anything useful here
1286  # Be aware that the == '' check is explicit, since empty values will be
1287  # passed by some callers (T31116)
1288  return null;
1289 
1290  } elseif ( in_array(
1291  $type,
1292  [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1293  ) {
1294  $block = new Block();
1295  $block->fromMaster( $fromMaster );
1296 
1297  if ( $type !== null ) {
1298  $block->setTarget( $target );
1299  }
1300 
1301  if ( $block->newLoad( $vagueTarget ) ) {
1302  return $block;
1303  }
1304  }
1305  return null;
1306  }
1307 
1318  public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1319  if ( $ipChain === [] ) {
1320  return [];
1321  }
1322 
1323  $conds = [];
1324  $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1325  foreach ( array_unique( $ipChain ) as $ipaddr ) {
1326  # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1327  # necessarily trust the header given to us, make sure that we are only
1328  # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1329  # Do not treat private IP spaces as special as it may be desirable for wikis
1330  # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1331  if ( !IP::isValid( $ipaddr ) ) {
1332  continue;
1333  }
1334  # Don't check trusted IPs (includes local squids which will be in every request)
1335  if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1336  continue;
1337  }
1338  # Check both the original IP (to check against single blocks), as well as build
1339  # the clause to check for rangeblocks for the given IP.
1340  $conds['ipb_address'][] = $ipaddr;
1341  $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1342  }
1343 
1344  if ( $conds === [] ) {
1345  return [];
1346  }
1347 
1348  if ( $fromMaster ) {
1349  $db = wfGetDB( DB_MASTER );
1350  } else {
1351  $db = wfGetDB( DB_REPLICA );
1352  }
1353  $conds = $db->makeList( $conds, LIST_OR );
1354  if ( !$isAnon ) {
1355  $conds = [ $conds, 'ipb_anon_only' => 0 ];
1356  }
1357  $blockQuery = self::getQueryInfo();
1358  $rows = $db->select(
1359  $blockQuery['tables'],
1360  array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1361  $conds,
1362  __METHOD__,
1363  [],
1364  $blockQuery['joins']
1365  );
1366 
1367  $blocks = [];
1368  foreach ( $rows as $row ) {
1369  $block = self::newFromRow( $row );
1370  if ( !$block->isExpired() ) {
1371  $blocks[] = $block;
1372  }
1373  }
1374 
1375  return $blocks;
1376  }
1377 
1399  public static function chooseBlock( array $blocks, array $ipChain ) {
1400  if ( $blocks === [] ) {
1401  return null;
1402  } elseif ( count( $blocks ) == 1 ) {
1403  return $blocks[0];
1404  }
1405 
1406  // Sort hard blocks before soft ones and secondarily sort blocks
1407  // that disable account creation before those that don't.
1408  usort( $blocks, function ( Block $a, Block $b ) {
1409  $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1410  $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1411  return strcmp( $bWeight, $aWeight ); // highest weight first
1412  } );
1413 
1414  $blocksListExact = [
1415  'hard' => false,
1416  'disable_create' => false,
1417  'other' => false,
1418  'auto' => false
1419  ];
1420  $blocksListRange = [
1421  'hard' => false,
1422  'disable_create' => false,
1423  'other' => false,
1424  'auto' => false
1425  ];
1426  $ipChain = array_reverse( $ipChain );
1427 
1429  foreach ( $blocks as $block ) {
1430  // Stop searching if we have already have a "better" block. This
1431  // is why the order of the blocks matters
1432  if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1433  break;
1434  } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1435  break;
1436  }
1437 
1438  foreach ( $ipChain as $checkip ) {
1439  $checkipHex = IP::toHex( $checkip );
1440  if ( (string)$block->getTarget() === $checkip ) {
1441  if ( $block->isHardblock() ) {
1442  $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1443  } elseif ( $block->prevents( 'createaccount' ) ) {
1444  $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1445  } elseif ( $block->mAuto ) {
1446  $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1447  } else {
1448  $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1449  }
1450  // We found closest exact match in the ip list, so go to the next Block
1451  break;
1452  } elseif ( array_filter( $blocksListExact ) == []
1453  && $block->getRangeStart() <= $checkipHex
1454  && $block->getRangeEnd() >= $checkipHex
1455  ) {
1456  if ( $block->isHardblock() ) {
1457  $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1458  } elseif ( $block->prevents( 'createaccount' ) ) {
1459  $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1460  } elseif ( $block->mAuto ) {
1461  $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1462  } else {
1463  $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1464  }
1465  break;
1466  }
1467  }
1468  }
1469 
1470  if ( array_filter( $blocksListExact ) == [] ) {
1471  $blocksList = &$blocksListRange;
1472  } else {
1473  $blocksList = &$blocksListExact;
1474  }
1475 
1476  $chosenBlock = null;
1477  if ( $blocksList['hard'] ) {
1478  $chosenBlock = $blocksList['hard'];
1479  } elseif ( $blocksList['disable_create'] ) {
1480  $chosenBlock = $blocksList['disable_create'];
1481  } elseif ( $blocksList['other'] ) {
1482  $chosenBlock = $blocksList['other'];
1483  } elseif ( $blocksList['auto'] ) {
1484  $chosenBlock = $blocksList['auto'];
1485  } else {
1486  throw new MWException( "Proxy block found, but couldn't be classified." );
1487  }
1488 
1489  return $chosenBlock;
1490  }
1491 
1501  public static function parseTarget( $target ) {
1502  # We may have been through this before
1503  if ( $target instanceof User ) {
1504  if ( IP::isValid( $target->getName() ) ) {
1505  return [ $target, self::TYPE_IP ];
1506  } else {
1507  return [ $target, self::TYPE_USER ];
1508  }
1509  } elseif ( $target === null ) {
1510  return [ null, null ];
1511  }
1512 
1513  $target = trim( $target );
1514 
1515  if ( IP::isValid( $target ) ) {
1516  # We can still create a User if it's an IP address, but we need to turn
1517  # off validation checking (which would exclude IP addresses)
1518  return [
1520  self::TYPE_IP
1521  ];
1522 
1523  } elseif ( IP::isValidRange( $target ) ) {
1524  # Can't create a User from an IP range
1525  return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1526  }
1527 
1528  # Consider the possibility that this is not a username at all
1529  # but actually an old subpage (T31797)
1530  if ( strpos( $target, '/' ) !== false ) {
1531  # An old subpage, drill down to the user behind it
1532  $target = explode( '/', $target )[0];
1533  }
1534 
1535  $userObj = User::newFromName( $target );
1536  if ( $userObj instanceof User ) {
1537  # Note that since numbers are valid usernames, a $target of "12345" will be
1538  # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1539  # since hash characters are not valid in usernames or titles generally.
1540  return [ $userObj, self::TYPE_USER ];
1541 
1542  } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1543  # Autoblock reference in the form "#12345"
1544  return [ substr( $target, 1 ), self::TYPE_AUTO ];
1545 
1546  } else {
1547  # WTF?
1548  return [ null, null ];
1549  }
1550  }
1551 
1558  public function getType() {
1559  return $this->mAuto
1560  ? self::TYPE_AUTO
1561  : $this->type;
1562  }
1563 
1571  public function getTargetAndType() {
1572  return [ $this->getTarget(), $this->getType() ];
1573  }
1574 
1581  public function getTarget() {
1582  return $this->target;
1583  }
1584 
1590  public function getExpiry() {
1591  return $this->mExpiry;
1592  }
1593 
1598  public function setTarget( $target ) {
1599  list( $this->target, $this->type ) = self::parseTarget( $target );
1600  }
1601 
1606  public function getBlocker() {
1607  return $this->blocker;
1608  }
1609 
1614  public function setBlocker( $user ) {
1615  if ( is_string( $user ) ) {
1616  $user = User::newFromName( $user, false );
1617  }
1618 
1619  if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1620  throw new InvalidArgumentException(
1621  'Blocker must be a local user or a name that cannot be a local user'
1622  );
1623  }
1624 
1625  $this->blocker = $user;
1626  }
1627 
1636  public function setCookie( WebResponse $response ) {
1637  // Calculate the default expiry time.
1638  $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1639 
1640  // Use the Block's expiry time only if it's less than the default.
1641  $expiryTime = $this->getExpiry();
1642  if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1643  $expiryTime = $maxExpiryTime;
1644  }
1645 
1646  // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1647  $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1648  $cookieOptions = [ 'httpOnly' => false ];
1649  $cookieValue = $this->getCookieValue();
1650  $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1651  }
1652 
1660  public static function clearCookie( WebResponse $response ) {
1661  $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1662  }
1663 
1673  public function getCookieValue() {
1674  $config = RequestContext::getMain()->getConfig();
1675  $id = $this->getId();
1676  $secretKey = $config->get( 'SecretKey' );
1677  if ( !$secretKey ) {
1678  // If there's no secret key, don't append a HMAC.
1679  return $id;
1680  }
1681  $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1682  $cookieValue = $id . '!' . $hmac;
1683  return $cookieValue;
1684  }
1685 
1696  public static function getIdFromCookieValue( $cookieValue ) {
1697  // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1698  $bangPos = strpos( $cookieValue, '!' );
1699  $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1700  // Get the site-wide secret key.
1701  $config = RequestContext::getMain()->getConfig();
1702  $secretKey = $config->get( 'SecretKey' );
1703  if ( !$secretKey ) {
1704  // If there's no secret key, just use the ID as given.
1705  return $id;
1706  }
1707  $storedHmac = substr( $cookieValue, $bangPos + 1 );
1708  $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1709  if ( $calculatedHmac === $storedHmac ) {
1710  return $id;
1711  } else {
1712  return null;
1713  }
1714  }
1715 
1724  $params = $this->getBlockErrorParams( $context );
1725 
1726  $msg = 'blockedtext';
1727  if ( $this->getSystemBlockType() !== null ) {
1728  $msg = 'systemblockedtext';
1729  } elseif ( $this->mAuto ) {
1730  $msg = 'autoblockedtext';
1731  } elseif ( !$this->isSitewide() ) {
1732  $msg = 'blockedtext-partial';
1733  }
1734 
1735  array_unshift( $params, $msg );
1736 
1737  return $params;
1738  }
1739 
1748  $blocker = $this->getBlocker();
1749  if ( $blocker instanceof User ) { // local user
1750  $blockerUserpage = $blocker->getUserPage();
1751  $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1752  } else { // foreign user
1753  $link = $blocker;
1754  }
1755 
1756  $reason = $this->mReason;
1757  if ( $reason == '' ) {
1758  $reason = $context->msg( 'blockednoreason' )->text();
1759  }
1760 
1761  /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1762  * This could be a username, an IP range, or a single IP. */
1763  $intended = $this->getTarget();
1765  $lang = $context->getLanguage();
1766 
1767  return [
1768  $link,
1769  $reason,
1770  $context->getRequest()->getIP(),
1771  $this->getByName(),
1772  $systemBlockType ?? $this->getId(),
1773  $lang->formatExpiry( $this->mExpiry ),
1774  (string)$intended,
1775  $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1776  ];
1777  }
1778 
1788  public function getRestrictions() {
1789  if ( $this->restrictions === null ) {
1790  // If the block id has not been set, then do not attempt to load the
1791  // restrictions.
1792  if ( !$this->mId ) {
1793  return [];
1794  }
1795  $this->restrictions = BlockRestriction::loadByBlockId( $this->mId );
1796  }
1797 
1798  return $this->restrictions;
1799  }
1800 
1808  public function setRestrictions( array $restrictions ) {
1809  $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1810  return $restriction instanceof Restriction;
1811  } );
1812 
1813  return $this;
1814  }
1815 
1827  public function appliesToTitle( Title $title ) {
1828  if ( $this->isSitewide() ) {
1829  return true;
1830  }
1831 
1832  $restrictions = $this->getRestrictions();
1833  foreach ( $restrictions as $restriction ) {
1834  if ( $restriction->matches( $title ) ) {
1835  return true;
1836  }
1837  }
1838 
1839  return false;
1840  }
1841 
1850  public function appliesToNamespace( $ns ) {
1851  if ( $this->isSitewide() ) {
1852  return true;
1853  }
1854 
1855  // Blocks do not apply to virtual namespaces.
1856  if ( $ns < 0 ) {
1857  return false;
1858  }
1859 
1860  $restriction = $this->findRestriction( NamespaceRestriction::TYPE, $ns );
1861 
1862  return (bool)$restriction;
1863  }
1864 
1878  public function appliesToPage( $pageId ) {
1879  if ( $this->isSitewide() ) {
1880  return true;
1881  }
1882 
1883  // If the pageId is not over zero, the block cannot apply to it.
1884  if ( $pageId <= 0 ) {
1885  return false;
1886  }
1887 
1888  $restriction = $this->findRestriction( PageRestriction::TYPE, $pageId );
1889 
1890  return (bool)$restriction;
1891  }
1892 
1900  private function findRestriction( $type, $value ) {
1901  $restrictions = $this->getRestrictions();
1902  foreach ( $restrictions as $restriction ) {
1903  if ( $restriction->getType() !== $type ) {
1904  continue;
1905  }
1906 
1907  if ( $restriction->getValue() === $value ) {
1908  return $restriction;
1909  }
1910  }
1911 
1912  return null;
1913  }
1914 }
getBy()
Get the user id of the blocking sysop.
Definition: Block.php:1046
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))
static isValidRange( $ipRange)
Validate an IP range (valid address with a valid CIDR prefix).
Definition: IP.php:138
static newFromRow( $row)
Create a new Block object from a database row.
Definition: Block.php:513
bool $isHardblock
Definition: Block.php:81
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:2625
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
static toHex( $ip)
Return a zero-padded upper case hexadecimal representation of an IP address.
Definition: IP.php:417
string $mTimestamp
Definition: Block.php:36
static newFromID( $id)
Load a block from the block id.
Definition: Block.php:199
either a plain
Definition: hooks.txt:2056
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:767
setCookie( $name, $value, $expire=0, $options=[])
Set the browser cookie.
static chooseBlock(array $blocks, array $ipChain)
From a list of multiple blocks, find the most exact and strongest Block.
Definition: Block.php:1399
findRestriction( $type, $value)
Find Restriction by type and value.
Definition: Block.php:1900
const TYPE_RANGE
Definition: Block.php:98
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:513
$success
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
prevents( $action, $x=null)
Get/set whether the Block prevents a given action.
Definition: Block.php:1156
bool $mFromMaster
Definition: Block.php:54
getSystemBlockType()
Get the system block type, if any.
Definition: Block.php:1094
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
isValid()
Is the block address valid (i.e.
Definition: Block.php:977
getType()
Get the type of target for this particular block.
Definition: Block.php:1558
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
if(!isset( $args[0])) $lang
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target&#39;s type, get an existing Block object if possible.
Definition: Block.php:1279
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:1276
int $mParentBlockId
Definition: Block.php:48
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
bool $mDisableUsertalk
Definition: Block.php:60
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
equals(Block $block)
Check if two blocks are effectively equal.
Definition: Block.php:299
getCookieValue()
Get the BlockID cookie&#39;s value for this block.
Definition: Block.php:1673
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:466
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
getDatabaseArray(IDatabase $dbw)
Get an array suitable for passing to $dbw->insert() or $dbw->update()
Definition: Block.php:693
const SCHEMA_COMPAT_READ_NEW
Definition: Defines.php:287
static clearCookie(WebResponse $response)
Unset the &#39;BlockID&#39; cookie.
Definition: Block.php:1660
const TYPE_IP
Definition: Block.php:97
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
insert( $dbw=null)
Insert a block into the block table.
Definition: Block.php:553
getId()
Get the block ID.
Definition: Block.php:1069
this hook is for auditing only $response
Definition: hooks.txt:780
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:329
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition: Block.php:1501
initFromRow( $row)
Given a database row from the ipblocks table, initialize member variables.
Definition: Block.php:480
const DB_MASTER
Definition: defines.php:26
static sanitizeRange( $range)
Gets rid of unneeded numbers in quad-dotted/octet IP strings For example, 127.111.113.151/24 -> 127.111.113.0/24.
Definition: IP.php:725
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2487
update()
Update a block in the DB with new parameters.
Definition: Block.php:630
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. '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:1993
clearCookie( $name, $options=[])
Unset a browser cookie.
Deferrable Update for closure/callback updates that should use auto-commit mode.
setCookie(WebResponse $response)
Set the &#39;BlockID&#39; cookie to this block&#39;s ID and expiry time.
Definition: Block.php:1636
getRangeEnd()
Get the IP address at the end of the range in Hex form.
Definition: Block.php:1027
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3042
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
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:1995
deleteIfExpired()
Check if a block has expired.
Definition: Block.php:945
__construct( $options=[])
Create a new block with specified parameters on a user, IP or IP range.
Definition: Block.php:128
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$wgBlockCIDRLimit
Limits on the possible sizes of range blocks.
getExpiry()
Definition: Block.php:1590
wfReadOnly()
Check whether the wiki is in read-only mode.
Restriction [] $restrictions
Definition: Block.php:93
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.
const LIST_AND
Definition: Defines.php:43
int $type
Block::TYPE_ constant.
Definition: Block.php:75
appliesToTitle(Title $title)
Checks if a block applies to a particular title.
Definition: Block.php:1827
setRestrictions(array $restrictions)
Set Restrictions.
Definition: Block.php:1808
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
Definition: IP.php:152
isAutoblocking( $x=null)
Definition: Block.php:1126
getTargetAndType()
Get the target and target type for this particular Block.
Definition: Block.php:1571
getRedactedName()
Get the block name, but with autoblocked IPs hidden as per standard privacy policy.
Definition: Block.php:1210
bool $isAutoblocking
Definition: Block.php:84
$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
doAutoblock( $autoblockIP)
Autoblocks the given IP, referring to this Block.
Definition: Block.php:866
bool $mBlockEmail
Definition: Block.php:57
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
int $mId
Definition: Block.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 & $options
Definition: hooks.txt:1995
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
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:780
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
Definition: User.php:1041
isSitewide( $x=null)
Indicates that the block is a sitewide block.
Definition: Block.php:1145
static isInRange( $addr, $range)
Determine if a given IPv4/IPv6 address is in a given CIDR network.
Definition: IP.php:650
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:935
static purgeExpired()
Purge expired blocks from the ipblocks table.
Definition: Block.php:1237
static getRangeCond( $start, $end=null)
Get a set of SQL conditions which will select rangeblocks encompassing a given range.
Definition: Block.php:433
const TYPE_ID
Definition: Block.php:100
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new block object...
Definition: Block.php:267
const TYPE_AUTO
Definition: Block.php:99
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
static isWhitelistedFromAutoblocks( $ip)
Checks whether a given IP is on the autoblock whitelist.
Definition: Block.php:820
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
const LIST_OR
Definition: Defines.php:46
User string $target
Definition: Block.php:66
doRetroactiveAutoblock()
Retroactively autoblocks the last IP used by the user (if it is a user) blocked by this Block...
Definition: Block.php:744
$expiryTime
msg( $key)
This is the method for getting translated interface messages.
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
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...
static getBlocksForIPList(array $ipChain, $isAnon, $fromMaster=false)
Get all blocks that match any IP from an array of IP addresses.
Definition: Block.php:1318
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the &#39;BlockID&#39; cookie.
Definition: Block.php:1696
appliesToNamespace( $ns)
Checks if a block applies to a particular namespace.
Definition: Block.php:1850
bool $mAuto
Definition: Block.php:39
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
int $forcedTargetID
Hack for foreign blocking (CentralAuth)
Definition: Block.php:69
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:608
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
updateTimestamp()
Update the timestamp on autoblocks.
Definition: Block.php:984
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
Definition: User.php:675
$lines
Definition: router.php:61
static getStore()
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
getBlocker()
Get the user who implemented this block.
Definition: Block.php:1606
getId()
Get the user&#39;s ID.
Definition: User.php:2460
getPermissionsError(IContextSource $context)
Get the key and parameters for the corresponding error message.
Definition: Block.php:1723
static selectFields()
Return the list of ipblocks fields that should be selected to create a new block. ...
Definition: Block.php:223
setBlocker( $user)
Set the user who implemented (or will implement) this block.
Definition: Block.php:1614
User $blocker
Definition: Block.php:78
string null $systemBlockType
Definition: Block.php:87
getBlockErrorParams(IContextSource $context)
Get block information used in different block error messages.
Definition: Block.php:1747
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$line
Definition: cdb.php:59
getTarget()
Get the target for this particular Block.
Definition: Block.php:1581
fromMaster( $x=null)
Get/set a flag determining whether the master is used for reads.
Definition: Block.php:1104
getUserPage()
Get this user&#39;s personal page title.
Definition: User.php:4588
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and insert
Definition: hooks.txt:2074
getRestrictions()
Get Restrictions.
Definition: Block.php:1788
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:2625
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:28
const TYPE_USER
Definition: Block.php:96
getAutoblockUpdateArray(IDatabase $dbw)
Definition: Block.php:728
setTarget( $target)
Set the target for this block, and update $this->type accordingly.
Definition: Block.php:1598
bool $isSitewide
Definition: Block.php:90
setId( $blockId)
Set the block ID.
Definition: Block.php:1079
const DB_REPLICA
Definition: defines.php:25
string $mExpiry
Definition: Block.php:42
bool $mHideName
Definition: Block.php:45
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:584
isHardblock( $x=null)
Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range) ...
Definition: Block.php:1113
static getAutoblockExpiry( $timestamp)
Get a timestamp of the expiry for autoblocks.
Definition: Block.php:1228
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
addQuotes( $s)
Adds quotes and backslashes.
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
Definition: Block.php:31
getRangeStart()
Get the IP address at the start of the range in Hex form.
Definition: Block.php:1008
getByName()
Get the username of the blocking sysop.
Definition: Block.php:1058
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1486
appliesToPage( $pageId)
Checks if a block applies to a particular page.
Definition: Block.php:1878
string $mReason
Definition: Block.php:33
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
bool $mCreateAccount
Definition: Block.php:63
isExpired()
Has the block expired?
Definition: Block.php:962
$wgAutoblockExpiry
Number of seconds before autoblock entries expire.