MediaWiki  REL1_31
Block.php
Go to the documentation of this file.
1 <?php
26 
27 class Block {
29  public $mReason;
30 
32  public $mTimestamp;
33 
35  public $mAuto;
36 
38  public $mExpiry;
39 
41  public $mHideName;
42 
45 
47  private $mId;
48 
50  private $mFromMaster;
51 
53  private $mBlockEmail;
54 
57 
59  private $mCreateAccount;
60 
62  private $target;
63 
65  private $forcedTargetID;
66 
68  private $type;
69 
71  private $blocker;
72 
74  private $isHardblock;
75 
77  private $isAutoblocking;
78 
81 
82  # TYPE constants
83  const TYPE_USER = 1;
84  const TYPE_IP = 2;
85  const TYPE_RANGE = 3;
86  const TYPE_AUTO = 4;
87  const TYPE_ID = 5;
88 
115  function __construct( $options = [] ) {
116  $defaults = [
117  'address' => '',
118  'user' => null,
119  'by' => null,
120  'reason' => '',
121  'timestamp' => '',
122  'auto' => false,
123  'expiry' => '',
124  'anonOnly' => false,
125  'createAccount' => false,
126  'enableAutoblock' => false,
127  'hideName' => false,
128  'blockEmail' => false,
129  'allowUsertalk' => false,
130  'byText' => '',
131  'systemBlock' => null,
132  ];
133 
134  if ( func_num_args() > 1 || !is_array( $options ) ) {
135  $options = array_combine(
136  array_slice( array_keys( $defaults ), 0, func_num_args() ),
137  func_get_args()
138  );
139  wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
140  }
141 
142  $options += $defaults;
143 
144  $this->setTarget( $options['address'] );
145 
146  if ( $this->target instanceof User && $options['user'] ) {
147  # Needed for foreign users
148  $this->forcedTargetID = $options['user'];
149  }
150 
151  if ( $options['by'] ) {
152  # Local user
153  $this->setBlocker( User::newFromId( $options['by'] ) );
154  } else {
155  # Foreign user
156  $this->setBlocker( $options['byText'] );
157  }
158 
159  $this->mReason = $options['reason'];
160  $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
161  $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
162 
163  # Boolean settings
164  $this->mAuto = (bool)$options['auto'];
165  $this->mHideName = (bool)$options['hideName'];
166  $this->isHardblock( !$options['anonOnly'] );
167  $this->isAutoblocking( (bool)$options['enableAutoblock'] );
168 
169  # Prevention measures
170  $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
171  $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
172  $this->prevents( 'createaccount', (bool)$options['createAccount'] );
173 
174  $this->mFromMaster = false;
175  $this->systemBlockType = $options['systemBlock'];
176  }
177 
184  public static function newFromID( $id ) {
185  $dbr = wfGetDB( DB_REPLICA );
186  $blockQuery = self::getQueryInfo();
187  $res = $dbr->selectRow(
188  $blockQuery['tables'],
189  $blockQuery['fields'],
190  [ 'ipb_id' => $id ],
191  __METHOD__,
192  [],
193  $blockQuery['joins']
194  );
195  if ( $res ) {
196  return self::newFromRow( $res );
197  } else {
198  return null;
199  }
200  }
201 
208  public static function selectFields() {
210 
212  // If code is using this instead of self::getQueryInfo(), there's a
213  // decent chance it's going to try to directly access
214  // $row->ipb_by or $row->ipb_by_text and we can't give it
215  // useful values here once those aren't being written anymore.
216  throw new BadMethodCallException(
217  'Cannot use ' . __METHOD__ . ' when $wgActorTableSchemaMigrationStage > MIGRATION_WRITE_BOTH'
218  );
219  }
220 
221  wfDeprecated( __METHOD__, '1.31' );
222  return [
223  'ipb_id',
224  'ipb_address',
225  'ipb_by',
226  'ipb_by_text',
227  'ipb_by_actor' => $wgActorTableSchemaMigrationStage > MIGRATION_OLD ? 'ipb_by_actor' : 'NULL',
228  'ipb_timestamp',
229  'ipb_auto',
230  'ipb_anon_only',
231  'ipb_create_account',
232  'ipb_enable_autoblock',
233  'ipb_expiry',
234  'ipb_deleted',
235  'ipb_block_email',
236  'ipb_allow_usertalk',
237  'ipb_parent_block_id',
238  ] + CommentStore::getStore()->getFields( 'ipb_reason' );
239  }
240 
250  public static function getQueryInfo() {
251  $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
252  $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
253  return [
254  'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
255  'fields' => [
256  'ipb_id',
257  'ipb_address',
258  'ipb_timestamp',
259  'ipb_auto',
260  'ipb_anon_only',
261  'ipb_create_account',
262  'ipb_enable_autoblock',
263  'ipb_expiry',
264  'ipb_deleted',
265  'ipb_block_email',
266  'ipb_allow_usertalk',
267  'ipb_parent_block_id',
268  ] + $commentQuery['fields'] + $actorQuery['fields'],
269  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
270  ];
271  }
272 
281  public function equals( Block $block ) {
282  return (
283  (string)$this->target == (string)$block->target
284  && $this->type == $block->type
285  && $this->mAuto == $block->mAuto
286  && $this->isHardblock() == $block->isHardblock()
287  && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
288  && $this->mExpiry == $block->mExpiry
289  && $this->isAutoblocking() == $block->isAutoblocking()
290  && $this->mHideName == $block->mHideName
291  && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
292  && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
293  && $this->mReason == $block->mReason
294  );
295  }
296 
307  protected function newLoad( $vagueTarget = null ) {
308  $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
309 
310  if ( $this->type !== null ) {
311  $conds = [
312  'ipb_address' => [ (string)$this->target ],
313  ];
314  } else {
315  $conds = [ 'ipb_address' => [] ];
316  }
317 
318  # Be aware that the != '' check is explicit, since empty values will be
319  # passed by some callers (T31116)
320  if ( $vagueTarget != '' ) {
321  list( $target, $type ) = self::parseTarget( $vagueTarget );
322  switch ( $type ) {
323  case self::TYPE_USER:
324  # Slightly weird, but who are we to argue?
325  $conds['ipb_address'][] = (string)$target;
326  break;
327 
328  case self::TYPE_IP:
329  $conds['ipb_address'][] = (string)$target;
330  $conds[] = self::getRangeCond( IP::toHex( $target ) );
331  $conds = $db->makeList( $conds, LIST_OR );
332  break;
333 
334  case self::TYPE_RANGE:
335  list( $start, $end ) = IP::parseRange( $target );
336  $conds['ipb_address'][] = (string)$target;
337  $conds[] = self::getRangeCond( $start, $end );
338  $conds = $db->makeList( $conds, LIST_OR );
339  break;
340 
341  default:
342  throw new MWException( "Tried to load block with invalid type" );
343  }
344  }
345 
346  $blockQuery = self::getQueryInfo();
347  $res = $db->select(
348  $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
349  );
350 
351  # This result could contain a block on the user, a block on the IP, and a russian-doll
352  # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
353  $bestRow = null;
354 
355  # Lower will be better
356  $bestBlockScore = 100;
357 
358  # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
359  $bestBlockPreventsEdit = null;
360 
361  foreach ( $res as $row ) {
362  $block = self::newFromRow( $row );
363 
364  # Don't use expired blocks
365  if ( $block->isExpired() ) {
366  continue;
367  }
368 
369  # Don't use anon only blocks on users
370  if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
371  continue;
372  }
373 
374  if ( $block->getType() == self::TYPE_RANGE ) {
375  # This is the number of bits that are allowed to vary in the block, give
376  # or take some floating point errors
377  $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
378  $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
379  $size = log( $end - $start + 1, 2 );
380 
381  # This has the nice property that a /32 block is ranked equally with a
382  # single-IP block, which is exactly what it is...
383  $score = self::TYPE_RANGE - 1 + ( $size / 128 );
384 
385  } else {
386  $score = $block->getType();
387  }
388 
389  if ( $score < $bestBlockScore ) {
390  $bestBlockScore = $score;
391  $bestRow = $row;
392  $bestBlockPreventsEdit = $block->prevents( 'edit' );
393  }
394  }
395 
396  if ( $bestRow !== null ) {
397  $this->initFromRow( $bestRow );
398  $this->prevents( 'edit', $bestBlockPreventsEdit );
399  return true;
400  } else {
401  return false;
402  }
403  }
404 
411  public static function getRangeCond( $start, $end = null ) {
412  if ( $end === null ) {
413  $end = $start;
414  }
415  # Per T16634, we want to include relevant active rangeblocks; for
416  # rangeblocks, we want to include larger ranges which enclose the given
417  # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
418  # so we can improve performance by filtering on a LIKE clause
419  $chunk = self::getIpFragment( $start );
420  $dbr = wfGetDB( DB_REPLICA );
421  $like = $dbr->buildLike( $chunk, $dbr->anyString() );
422 
423  # Fairly hard to make a malicious SQL statement out of hex characters,
424  # but stranger things have happened...
425  $safeStart = $dbr->addQuotes( $start );
426  $safeEnd = $dbr->addQuotes( $end );
427 
428  return $dbr->makeList(
429  [
430  "ipb_range_start $like",
431  "ipb_range_start <= $safeStart",
432  "ipb_range_end >= $safeEnd",
433  ],
434  LIST_AND
435  );
436  }
437 
444  protected static function getIpFragment( $hex ) {
446  if ( substr( $hex, 0, 3 ) == 'v6-' ) {
447  return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
448  } else {
449  return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
450  }
451  }
452 
458  protected function initFromRow( $row ) {
459  $this->setTarget( $row->ipb_address );
461  $row->ipb_by, $row->ipb_by_text, isset( $row->ipb_by_actor ) ? $row->ipb_by_actor : null
462  ) );
463 
464  $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
465  $this->mAuto = $row->ipb_auto;
466  $this->mHideName = $row->ipb_deleted;
467  $this->mId = (int)$row->ipb_id;
468  $this->mParentBlockId = $row->ipb_parent_block_id;
469 
470  // I wish I didn't have to do this
471  $db = wfGetDB( DB_REPLICA );
472  $this->mExpiry = $db->decodeExpiry( $row->ipb_expiry );
473  $this->mReason = CommentStore::getStore()
474  // Legacy because $row may have come from self::selectFields()
475  ->getCommentLegacy( $db, 'ipb_reason', $row )->text;
476 
477  $this->isHardblock( !$row->ipb_anon_only );
478  $this->isAutoblocking( $row->ipb_enable_autoblock );
479 
480  $this->prevents( 'createaccount', $row->ipb_create_account );
481  $this->prevents( 'sendemail', $row->ipb_block_email );
482  $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
483  }
484 
490  public static function newFromRow( $row ) {
491  $block = new Block;
492  $block->initFromRow( $row );
493  return $block;
494  }
495 
502  public function delete() {
503  if ( wfReadOnly() ) {
504  return false;
505  }
506 
507  if ( !$this->getId() ) {
508  throw new MWException( "Block::delete() requires that the mId member be filled\n" );
509  }
510 
511  $dbw = wfGetDB( DB_MASTER );
512  $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
513  $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
514 
515  return $dbw->affectedRows() > 0;
516  }
517 
526  public function insert( $dbw = null ) {
528 
529  if ( $this->getSystemBlockType() !== null ) {
530  throw new MWException( 'Cannot insert a system block into the database' );
531  }
532  if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
533  throw new MWException( 'Cannot insert a block without a blocker set' );
534  }
535 
536  wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
537 
538  if ( $dbw === null ) {
539  $dbw = wfGetDB( DB_MASTER );
540  }
541 
543 
544  $row = $this->getDatabaseArray( $dbw );
545 
546  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
547  $affected = $dbw->affectedRows();
548  $this->mId = $dbw->insertId();
549 
550  # Don't collide with expired blocks.
551  # Do this after trying to insert to avoid locking.
552  if ( !$affected ) {
553  # T96428: The ipb_address index uses a prefix on a field, so
554  # use a standard SELECT + DELETE to avoid annoying gap locks.
555  $ids = $dbw->selectFieldValues( 'ipblocks',
556  'ipb_id',
557  [
558  'ipb_address' => $row['ipb_address'],
559  'ipb_user' => $row['ipb_user'],
560  'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
561  ],
562  __METHOD__
563  );
564  if ( $ids ) {
565  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
566  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
567  $affected = $dbw->affectedRows();
568  $this->mId = $dbw->insertId();
569  }
570  }
571 
572  if ( $affected ) {
573  $auto_ipd_ids = $this->doRetroactiveAutoblock();
574 
575  if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
576  // Change user login token to force them to be logged out.
577  $this->target->setToken();
578  $this->target->saveSettings();
579  }
580 
581  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
582  }
583 
584  return false;
585  }
586 
594  public function update() {
595  wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
596  $dbw = wfGetDB( DB_MASTER );
597 
598  $dbw->startAtomic( __METHOD__ );
599 
600  $dbw->update(
601  'ipblocks',
602  $this->getDatabaseArray( $dbw ),
603  [ 'ipb_id' => $this->getId() ],
604  __METHOD__
605  );
606 
607  $affected = $dbw->affectedRows();
608 
609  if ( $this->isAutoblocking() ) {
610  // update corresponding autoblock(s) (T50813)
611  $dbw->update(
612  'ipblocks',
613  $this->getAutoblockUpdateArray( $dbw ),
614  [ 'ipb_parent_block_id' => $this->getId() ],
615  __METHOD__
616  );
617  } else {
618  // autoblock no longer required, delete corresponding autoblock(s)
619  $dbw->delete(
620  'ipblocks',
621  [ 'ipb_parent_block_id' => $this->getId() ],
622  __METHOD__
623  );
624  }
625 
626  $dbw->endAtomic( __METHOD__ );
627 
628  if ( $affected ) {
629  $auto_ipd_ids = $this->doRetroactiveAutoblock();
630  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
631  }
632 
633  return false;
634  }
635 
641  protected function getDatabaseArray( IDatabase $dbw ) {
642  $expiry = $dbw->encodeExpiry( $this->mExpiry );
643 
644  if ( $this->forcedTargetID ) {
645  $uid = $this->forcedTargetID;
646  } else {
647  $uid = $this->target instanceof User ? $this->target->getId() : 0;
648  }
649 
650  $a = [
651  'ipb_address' => (string)$this->target,
652  'ipb_user' => $uid,
653  'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
654  'ipb_auto' => $this->mAuto,
655  'ipb_anon_only' => !$this->isHardblock(),
656  'ipb_create_account' => $this->prevents( 'createaccount' ),
657  'ipb_enable_autoblock' => $this->isAutoblocking(),
658  'ipb_expiry' => $expiry,
659  'ipb_range_start' => $this->getRangeStart(),
660  'ipb_range_end' => $this->getRangeEnd(),
661  'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
662  'ipb_block_email' => $this->prevents( 'sendemail' ),
663  'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
664  'ipb_parent_block_id' => $this->mParentBlockId
665  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
666  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
667 
668  return $a;
669  }
670 
675  protected function getAutoblockUpdateArray( IDatabase $dbw ) {
676  return [
677  'ipb_create_account' => $this->prevents( 'createaccount' ),
678  'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
679  'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
680  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
681  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
682  }
683 
690  protected function doRetroactiveAutoblock() {
691  $blockIds = [];
692  # If autoblock is enabled, autoblock the LAST IP(s) used
693  if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
694  wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
695 
696  $continue = Hooks::run(
697  'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
698 
699  if ( $continue ) {
700  self::defaultRetroactiveAutoblock( $this, $blockIds );
701  }
702  }
703  return $blockIds;
704  }
705 
713  protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
715 
716  // No IPs are in recentchanges table, so nothing to select
717  if ( !$wgPutIPinRC ) {
718  return;
719  }
720 
721  $target = $block->getTarget();
722  if ( is_string( $target ) ) {
723  $target = User::newFromName( $target, false );
724  }
725 
726  $dbr = wfGetDB( DB_REPLICA );
727  $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
728 
729  $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
730 
731  // Just the last IP used.
732  $options['LIMIT'] = 1;
733 
734  $res = $dbr->select(
735  [ 'recentchanges' ] + $rcQuery['tables'],
736  [ 'rc_ip' ],
737  $rcQuery['conds'],
738  __METHOD__,
739  $options,
740  $rcQuery['joins']
741  );
742 
743  if ( !$res->numRows() ) {
744  # No results, don't autoblock anything
745  wfDebug( "No IP found to retroactively autoblock\n" );
746  } else {
747  foreach ( $res as $row ) {
748  if ( $row->rc_ip ) {
749  $id = $block->doAutoblock( $row->rc_ip );
750  if ( $id ) {
751  $blockIds[] = $id;
752  }
753  }
754  }
755  }
756  }
757 
765  public static function isWhitelistedFromAutoblocks( $ip ) {
766  // Try to get the autoblock_whitelist from the cache, as it's faster
767  // than getting the msg raw and explode()'ing it.
768  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
769  $lines = $cache->getWithSetCallback(
770  $cache->makeKey( 'ip-autoblock', 'whitelist' ),
771  $cache::TTL_DAY,
772  function ( $curValue, &$ttl, array &$setOpts ) {
773  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
774 
775  return explode( "\n",
776  wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
777  }
778  );
779 
780  wfDebug( "Checking the autoblock whitelist..\n" );
781 
782  foreach ( $lines as $line ) {
783  # List items only
784  if ( substr( $line, 0, 1 ) !== '*' ) {
785  continue;
786  }
787 
788  $wlEntry = substr( $line, 1 );
789  $wlEntry = trim( $wlEntry );
790 
791  wfDebug( "Checking $ip against $wlEntry..." );
792 
793  # Is the IP in this range?
794  if ( IP::isInRange( $ip, $wlEntry ) ) {
795  wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
796  return true;
797  } else {
798  wfDebug( " No match\n" );
799  }
800  }
801 
802  return false;
803  }
804 
811  public function doAutoblock( $autoblockIP ) {
812  # If autoblocks are disabled, go away.
813  if ( !$this->isAutoblocking() ) {
814  return false;
815  }
816 
817  # Don't autoblock for system blocks
818  if ( $this->getSystemBlockType() !== null ) {
819  throw new MWException( 'Cannot autoblock from a system block' );
820  }
821 
822  # Check for presence on the autoblock whitelist.
823  if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
824  return false;
825  }
826 
827  // Avoid PHP 7.1 warning of passing $this by reference
828  $block = $this;
829  # Allow hooks to cancel the autoblock.
830  if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
831  wfDebug( "Autoblock aborted by hook.\n" );
832  return false;
833  }
834 
835  # It's okay to autoblock. Go ahead and insert/update the block...
836 
837  # Do not add a *new* block if the IP is already blocked.
838  $ipblock = self::newFromTarget( $autoblockIP );
839  if ( $ipblock ) {
840  # Check if the block is an autoblock and would exceed the user block
841  # if renewed. If so, do nothing, otherwise prolong the block time...
842  if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
843  $this->mExpiry > self::getAutoblockExpiry( $ipblock->mTimestamp )
844  ) {
845  # Reset block timestamp to now and its expiry to
846  # $wgAutoblockExpiry in the future
847  $ipblock->updateTimestamp();
848  }
849  return false;
850  }
851 
852  # Make a new block object with the desired properties.
853  $autoblock = new Block;
854  wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
855  $autoblock->setTarget( $autoblockIP );
856  $autoblock->setBlocker( $this->getBlocker() );
857  $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
858  ->inContentLanguage()->plain();
859  $timestamp = wfTimestampNow();
860  $autoblock->mTimestamp = $timestamp;
861  $autoblock->mAuto = 1;
862  $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
863  # Continue suppressing the name if needed
864  $autoblock->mHideName = $this->mHideName;
865  $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
866  $autoblock->mParentBlockId = $this->mId;
867 
868  if ( $this->mExpiry == 'infinity' ) {
869  # Original block was indefinite, start an autoblock now
870  $autoblock->mExpiry = self::getAutoblockExpiry( $timestamp );
871  } else {
872  # If the user is already blocked with an expiry date, we don't
873  # want to pile on top of that.
874  $autoblock->mExpiry = min( $this->mExpiry, self::getAutoblockExpiry( $timestamp ) );
875  }
876 
877  # Insert the block...
878  $status = $autoblock->insert();
879  return $status
880  ? $status['id']
881  : false;
882  }
883 
888  public function deleteIfExpired() {
889  if ( $this->isExpired() ) {
890  wfDebug( "Block::deleteIfExpired() -- deleting\n" );
891  $this->delete();
892  $retVal = true;
893  } else {
894  wfDebug( "Block::deleteIfExpired() -- not expired\n" );
895  $retVal = false;
896  }
897 
898  return $retVal;
899  }
900 
905  public function isExpired() {
906  $timestamp = wfTimestampNow();
907  wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
908 
909  if ( !$this->mExpiry ) {
910  return false;
911  } else {
912  return $timestamp > $this->mExpiry;
913  }
914  }
915 
920  public function isValid() {
921  return $this->getTarget() != null;
922  }
923 
927  public function updateTimestamp() {
928  if ( $this->mAuto ) {
929  $this->mTimestamp = wfTimestamp();
930  $this->mExpiry = self::getAutoblockExpiry( $this->mTimestamp );
931 
932  $dbw = wfGetDB( DB_MASTER );
933  $dbw->update( 'ipblocks',
934  [ /* SET */
935  'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
936  'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
937  ],
938  [ /* WHERE */
939  'ipb_id' => $this->getId(),
940  ],
941  __METHOD__
942  );
943  }
944  }
945 
951  public function getRangeStart() {
952  switch ( $this->type ) {
953  case self::TYPE_USER:
954  return '';
955  case self::TYPE_IP:
956  return IP::toHex( $this->target );
957  case self::TYPE_RANGE:
958  list( $start, /*...*/ ) = IP::parseRange( $this->target );
959  return $start;
960  default:
961  throw new MWException( "Block with invalid type" );
962  }
963  }
964 
970  public function getRangeEnd() {
971  switch ( $this->type ) {
972  case self::TYPE_USER:
973  return '';
974  case self::TYPE_IP:
975  return IP::toHex( $this->target );
976  case self::TYPE_RANGE:
977  list( /*...*/, $end ) = IP::parseRange( $this->target );
978  return $end;
979  default:
980  throw new MWException( "Block with invalid type" );
981  }
982  }
983 
989  public function getBy() {
990  $blocker = $this->getBlocker();
991  return ( $blocker instanceof User )
992  ? $blocker->getId()
993  : 0;
994  }
995 
1001  public function getByName() {
1002  $blocker = $this->getBlocker();
1003  return ( $blocker instanceof User )
1004  ? $blocker->getName()
1005  : (string)$blocker; // username
1006  }
1007 
1012  public function getId() {
1013  return $this->mId;
1014  }
1015 
1021  public function getSystemBlockType() {
1022  return $this->systemBlockType;
1023  }
1024 
1031  public function fromMaster( $x = null ) {
1032  return wfSetVar( $this->mFromMaster, $x );
1033  }
1034 
1040  public function isHardblock( $x = null ) {
1041  wfSetVar( $this->isHardblock, $x );
1042 
1043  # You can't *not* hardblock a user
1044  return $this->getType() == self::TYPE_USER
1045  ? true
1047  }
1048 
1053  public function isAutoblocking( $x = null ) {
1054  wfSetVar( $this->isAutoblocking, $x );
1055 
1056  # You can't put an autoblock on an IP or range as we don't have any history to
1057  # look over to get more IPs from
1058  return $this->getType() == self::TYPE_USER
1059  ? $this->isAutoblocking
1060  : false;
1061  }
1062 
1070  public function prevents( $action, $x = null ) {
1072  $res = null;
1073  switch ( $action ) {
1074  case 'edit':
1075  # For now... <evil laugh>
1076  $res = true;
1077  break;
1078  case 'createaccount':
1079  $res = wfSetVar( $this->mCreateAccount, $x );
1080  break;
1081  case 'sendemail':
1082  $res = wfSetVar( $this->mBlockEmail, $x );
1083  break;
1084  case 'editownusertalk':
1085  $res = wfSetVar( $this->mDisableUsertalk, $x );
1086  break;
1087  case 'read':
1088  $res = false;
1089  break;
1090  }
1091  if ( !$res && $wgBlockDisablesLogin ) {
1092  // If a block would disable login, then it should
1093  // prevent any action that all users cannot do
1094  $anon = new User;
1095  $res = $anon->isAllowed( $action ) ? $res : true;
1096  }
1097 
1098  return $res;
1099  }
1100 
1105  public function getRedactedName() {
1106  if ( $this->mAuto ) {
1107  return Html::rawElement(
1108  'span',
1109  [ 'class' => 'mw-autoblockid' ],
1110  wfMessage( 'autoblockid', $this->mId )
1111  );
1112  } else {
1113  return htmlspecialchars( $this->getTarget() );
1114  }
1115  }
1116 
1123  public static function getAutoblockExpiry( $timestamp ) {
1125 
1126  return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1127  }
1128 
1132  public static function purgeExpired() {
1133  if ( wfReadOnly() ) {
1134  return;
1135  }
1136 
1138  wfGetDB( DB_MASTER ),
1139  __METHOD__,
1140  function ( IDatabase $dbw, $fname ) {
1141  $ids = $dbw->selectFieldValues( 'ipblocks',
1142  'ipb_id',
1143  [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1144  $fname
1145  );
1146  if ( $ids ) {
1147  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1148  }
1149  }
1150  ) );
1151  }
1152 
1173  public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1174  list( $target, $type ) = self::parseTarget( $specificTarget );
1175  if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1176  return self::newFromID( $target );
1177 
1178  } elseif ( $target === null && $vagueTarget == '' ) {
1179  # We're not going to find anything useful here
1180  # Be aware that the == '' check is explicit, since empty values will be
1181  # passed by some callers (T31116)
1182  return null;
1183 
1184  } elseif ( in_array(
1185  $type,
1186  [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1187  ) {
1188  $block = new Block();
1189  $block->fromMaster( $fromMaster );
1190 
1191  if ( $type !== null ) {
1192  $block->setTarget( $target );
1193  }
1194 
1195  if ( $block->newLoad( $vagueTarget ) ) {
1196  return $block;
1197  }
1198  }
1199  return null;
1200  }
1201 
1212  public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1213  if ( !count( $ipChain ) ) {
1214  return [];
1215  }
1216 
1217  $conds = [];
1218  $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1219  foreach ( array_unique( $ipChain ) as $ipaddr ) {
1220  # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1221  # necessarily trust the header given to us, make sure that we are only
1222  # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1223  # Do not treat private IP spaces as special as it may be desirable for wikis
1224  # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1225  if ( !IP::isValid( $ipaddr ) ) {
1226  continue;
1227  }
1228  # Don't check trusted IPs (includes local squids which will be in every request)
1229  if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1230  continue;
1231  }
1232  # Check both the original IP (to check against single blocks), as well as build
1233  # the clause to check for rangeblocks for the given IP.
1234  $conds['ipb_address'][] = $ipaddr;
1235  $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1236  }
1237 
1238  if ( !count( $conds ) ) {
1239  return [];
1240  }
1241 
1242  if ( $fromMaster ) {
1243  $db = wfGetDB( DB_MASTER );
1244  } else {
1245  $db = wfGetDB( DB_REPLICA );
1246  }
1247  $conds = $db->makeList( $conds, LIST_OR );
1248  if ( !$isAnon ) {
1249  $conds = [ $conds, 'ipb_anon_only' => 0 ];
1250  }
1251  $blockQuery = self::getQueryInfo();
1252  $rows = $db->select(
1253  $blockQuery['tables'],
1254  array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1255  $conds,
1256  __METHOD__,
1257  [],
1258  $blockQuery['joins']
1259  );
1260 
1261  $blocks = [];
1262  foreach ( $rows as $row ) {
1263  $block = self::newFromRow( $row );
1264  if ( !$block->isExpired() ) {
1265  $blocks[] = $block;
1266  }
1267  }
1268 
1269  return $blocks;
1270  }
1271 
1293  public static function chooseBlock( array $blocks, array $ipChain ) {
1294  if ( !count( $blocks ) ) {
1295  return null;
1296  } elseif ( count( $blocks ) == 1 ) {
1297  return $blocks[0];
1298  }
1299 
1300  // Sort hard blocks before soft ones and secondarily sort blocks
1301  // that disable account creation before those that don't.
1302  usort( $blocks, function ( Block $a, Block $b ) {
1303  $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1304  $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1305  return strcmp( $bWeight, $aWeight ); // highest weight first
1306  } );
1307 
1308  $blocksListExact = [
1309  'hard' => false,
1310  'disable_create' => false,
1311  'other' => false,
1312  'auto' => false
1313  ];
1314  $blocksListRange = [
1315  'hard' => false,
1316  'disable_create' => false,
1317  'other' => false,
1318  'auto' => false
1319  ];
1320  $ipChain = array_reverse( $ipChain );
1321 
1323  foreach ( $blocks as $block ) {
1324  // Stop searching if we have already have a "better" block. This
1325  // is why the order of the blocks matters
1326  if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1327  break;
1328  } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1329  break;
1330  }
1331 
1332  foreach ( $ipChain as $checkip ) {
1333  $checkipHex = IP::toHex( $checkip );
1334  if ( (string)$block->getTarget() === $checkip ) {
1335  if ( $block->isHardblock() ) {
1336  $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1337  } elseif ( $block->prevents( 'createaccount' ) ) {
1338  $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1339  } elseif ( $block->mAuto ) {
1340  $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1341  } else {
1342  $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1343  }
1344  // We found closest exact match in the ip list, so go to the next Block
1345  break;
1346  } elseif ( array_filter( $blocksListExact ) == []
1347  && $block->getRangeStart() <= $checkipHex
1348  && $block->getRangeEnd() >= $checkipHex
1349  ) {
1350  if ( $block->isHardblock() ) {
1351  $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1352  } elseif ( $block->prevents( 'createaccount' ) ) {
1353  $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1354  } elseif ( $block->mAuto ) {
1355  $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1356  } else {
1357  $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1358  }
1359  break;
1360  }
1361  }
1362  }
1363 
1364  if ( array_filter( $blocksListExact ) == [] ) {
1365  $blocksList = &$blocksListRange;
1366  } else {
1367  $blocksList = &$blocksListExact;
1368  }
1369 
1370  $chosenBlock = null;
1371  if ( $blocksList['hard'] ) {
1372  $chosenBlock = $blocksList['hard'];
1373  } elseif ( $blocksList['disable_create'] ) {
1374  $chosenBlock = $blocksList['disable_create'];
1375  } elseif ( $blocksList['other'] ) {
1376  $chosenBlock = $blocksList['other'];
1377  } elseif ( $blocksList['auto'] ) {
1378  $chosenBlock = $blocksList['auto'];
1379  } else {
1380  throw new MWException( "Proxy block found, but couldn't be classified." );
1381  }
1382 
1383  return $chosenBlock;
1384  }
1385 
1395  public static function parseTarget( $target ) {
1396  # We may have been through this before
1397  if ( $target instanceof User ) {
1398  if ( IP::isValid( $target->getName() ) ) {
1399  return [ $target, self::TYPE_IP ];
1400  } else {
1401  return [ $target, self::TYPE_USER ];
1402  }
1403  } elseif ( $target === null ) {
1404  return [ null, null ];
1405  }
1406 
1407  $target = trim( $target );
1408 
1409  if ( IP::isValid( $target ) ) {
1410  # We can still create a User if it's an IP address, but we need to turn
1411  # off validation checking (which would exclude IP addresses)
1412  return [
1415  ];
1416 
1417  } elseif ( IP::isValidRange( $target ) ) {
1418  # Can't create a User from an IP range
1420  }
1421 
1422  # Consider the possibility that this is not a username at all
1423  # but actually an old subpage (bug #29797)
1424  if ( strpos( $target, '/' ) !== false ) {
1425  # An old subpage, drill down to the user behind it
1426  $target = explode( '/', $target )[0];
1427  }
1428 
1429  $userObj = User::newFromName( $target );
1430  if ( $userObj instanceof User ) {
1431  # Note that since numbers are valid usernames, a $target of "12345" will be
1432  # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1433  # since hash characters are not valid in usernames or titles generally.
1434  return [ $userObj, self::TYPE_USER ];
1435 
1436  } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1437  # Autoblock reference in the form "#12345"
1438  return [ substr( $target, 1 ), self::TYPE_AUTO ];
1439 
1440  } else {
1441  # WTF?
1442  return [ null, null ];
1443  }
1444  }
1445 
1450  public function getType() {
1451  return $this->mAuto
1452  ? self::TYPE_AUTO
1453  : $this->type;
1454  }
1455 
1463  public function getTargetAndType() {
1464  return [ $this->getTarget(), $this->getType() ];
1465  }
1466 
1473  public function getTarget() {
1474  return $this->target;
1475  }
1476 
1482  public function getExpiry() {
1483  return $this->mExpiry;
1484  }
1485 
1490  public function setTarget( $target ) {
1491  list( $this->target, $this->type ) = self::parseTarget( $target );
1492  }
1493 
1498  public function getBlocker() {
1499  return $this->blocker;
1500  }
1501 
1506  public function setBlocker( $user ) {
1507  if ( is_string( $user ) ) {
1508  $user = User::newFromName( $user, false );
1509  }
1510 
1511  if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1512  throw new InvalidArgumentException(
1513  'Blocker must be a local user or a name that cannot be a local user'
1514  );
1515  }
1516 
1517  $this->blocker = $user;
1518  }
1519 
1528  public function setCookie( WebResponse $response ) {
1529  // Calculate the default expiry time.
1530  $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1531 
1532  // Use the Block's expiry time only if it's less than the default.
1533  $expiryTime = $this->getExpiry();
1534  if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1535  $expiryTime = $maxExpiryTime;
1536  }
1537 
1538  // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1539  $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1540  $cookieOptions = [ 'httpOnly' => false ];
1541  $cookieValue = $this->getCookieValue();
1542  $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1543  }
1544 
1552  public static function clearCookie( WebResponse $response ) {
1553  $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1554  }
1555 
1565  public function getCookieValue() {
1566  $config = RequestContext::getMain()->getConfig();
1567  $id = $this->getId();
1568  $secretKey = $config->get( 'SecretKey' );
1569  if ( !$secretKey ) {
1570  // If there's no secret key, don't append a HMAC.
1571  return $id;
1572  }
1573  $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1574  $cookieValue = $id . '!' . $hmac;
1575  return $cookieValue;
1576  }
1577 
1588  public static function getIdFromCookieValue( $cookieValue ) {
1589  // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1590  $bangPos = strpos( $cookieValue, '!' );
1591  $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1592  // Get the site-wide secret key.
1593  $config = RequestContext::getMain()->getConfig();
1594  $secretKey = $config->get( 'SecretKey' );
1595  if ( !$secretKey ) {
1596  // If there's no secret key, just use the ID as given.
1597  return $id;
1598  }
1599  $storedHmac = substr( $cookieValue, $bangPos + 1 );
1600  $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1601  if ( $calculatedHmac === $storedHmac ) {
1602  return $id;
1603  } else {
1604  return null;
1605  }
1606  }
1607 
1616  $blocker = $this->getBlocker();
1617  if ( $blocker instanceof User ) { // local user
1618  $blockerUserpage = $blocker->getUserPage();
1619  $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1620  } else { // foreign user
1621  $link = $blocker;
1622  }
1623 
1624  $reason = $this->mReason;
1625  if ( $reason == '' ) {
1626  $reason = $context->msg( 'blockednoreason' )->text();
1627  }
1628 
1629  /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1630  * This could be a username, an IP range, or a single IP. */
1631  $intended = $this->getTarget();
1632 
1634 
1635  $lang = $context->getLanguage();
1636  return [
1637  $systemBlockType !== null
1638  ? 'systemblockedtext'
1639  : ( $this->mAuto ? 'autoblockedtext' : 'blockedtext' ),
1640  $link,
1641  $reason,
1642  $context->getRequest()->getIP(),
1643  $this->getByName(),
1644  $systemBlockType !== null ? $systemBlockType : $this->getId(),
1645  $lang->formatExpiry( $this->mExpiry ),
1646  (string)$intended,
1647  $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1648  ];
1649  }
1650 }
Block\prevents
prevents( $action, $x=null)
Get/set whether the Block prevents a given action.
Definition: Block.php:1070
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:247
IP\toHex
static toHex( $ip)
Return a zero-padded upper case hexadecimal representation of an IP address.
Definition: IP.php:417
Block\isHardblock
isHardblock( $x=null)
Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
Definition: Block.php:1040
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:614
Block\getSystemBlockType
getSystemBlockType()
Get the system block type, if any.
Definition: Block.php:1021
Block\equals
equals(Block $block)
Check if two blocks are effectively equal.
Definition: Block.php:281
type
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 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:30
Block\getType
getType()
Get the type of target for this particular block.
Definition: Block.php:1450
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
User\getId
getId()
Get the user's ID.
Definition: User.php:2457
Block\getCookieValue
getCookieValue()
Get the BlockID cookie's value for this block.
Definition: Block.php:1565
MWCryptHash\hmac
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: MWCryptHash.php:106
$rows
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:2783
Block\clearCookie
static clearCookie(WebResponse $response)
Unset the 'BlockID' cookie.
Definition: Block.php:1552
Block\$mCreateAccount
bool $mCreateAccount
Definition: Block.php:59
Block\getIpFragment
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:444
wfMessage
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 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
$response
this hook is for auditing only $response
Definition: hooks.txt:783
array
the array() calling protocol came about after MediaWiki 1.4rc1.
plain
either a plain
Definition: hooks.txt:2056
Block\isExpired
isExpired()
Has the block expired?
Definition: Block.php:905
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
Block\newFromID
static newFromID( $id)
Load a blocked user from their block id.
Definition: Block.php:184
wfSetVar
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...
Definition: GlobalFunctions.php:1699
Block\$isHardblock
bool $isHardblock
Definition: Block.php:74
AutoCommitUpdate
Deferrable Update for closure/callback updates that should use auto-commit mode.
Definition: AutoCommitUpdate.php:9
Block\TYPE_IP
const TYPE_IP
Definition: Block.php:84
Block\TYPE_RANGE
const TYPE_RANGE
Definition: Block.php:85
Block\getBy
getBy()
Get the user id of the blocking sysop.
Definition: Block.php:989
Block\chooseBlock
static chooseBlock(array $blocks, array $ipChain)
From a list of multiple blocks, find the most exact and strongest Block.
Definition: Block.php:1293
string
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:181
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1980
$wgAutoblockExpiry
$wgAutoblockExpiry
Number of seconds before autoblock entries expire.
Definition: DefaultSettings.php:4997
Wikimedia\Rdbms\IDatabase\encodeExpiry
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
Block\update
update()
Update a block in the DB with new parameters.
Definition: Block.php:594
Block\getId
getId()
Get the block ID.
Definition: Block.php:1012
Block\setCookie
setCookie(WebResponse $response)
Set the 'BlockID' cookie to this block's ID and expiry time.
Definition: Block.php:1528
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
Definition: DeferredUpdates.php:76
WebResponse\setCookie
setCookie( $name, $value, $expire=0, $options=[])
Set the browser cookie.
Definition: WebResponse.php:141
Block\newFromTarget
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target's type, get an existing Block object if possible.
Definition: Block.php:1173
MIGRATION_WRITE_BOTH
const MIGRATION_WRITE_BOTH
Definition: Defines.php:303
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1262
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:591
Block\isValid
isValid()
Is the block address valid (i.e.
Definition: Block.php:920
Block\initFromRow
initFromRow( $row)
Given a database row from the ipblocks table, initialize member variables.
Definition: Block.php:458
User\getUserPage
getUserPage()
Get this user's personal page title.
Definition: User.php:4520
Block\getRangeEnd
getRangeEnd()
Get the IP address at the end of the range in Hex form.
Definition: Block.php:970
User\newFromAnyId
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
Definition: User.php:657
Block\$mDisableUsertalk
bool $mDisableUsertalk
Definition: Block.php:56
$res
$res
Definition: database.txt:21
Block\__construct
__construct( $options=[])
Create a new block with specified parameters on a user, IP or IP range.
Definition: Block.php:115
User
User
Definition: All_system_messages.txt:425
Block\$mParentBlockId
int $mParentBlockId
Definition: Block.php:44
Block\getExpiry
getExpiry()
Definition: Block.php:1482
Block\deleteIfExpired
deleteIfExpired()
Check if a block has expired.
Definition: Block.php:888
Block\getDatabaseArray
getDatabaseArray(IDatabase $dbw)
Get an array suitable for passing to $dbw->insert() or $dbw->update()
Definition: Block.php:641
Block\insert
insert( $dbw=null)
Insert a block into the block table.
Definition: Block.php:526
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:89
true
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:2006
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:37
LIST_AND
const LIST_AND
Definition: Defines.php:53
$wgPutIPinRC
$wgPutIPinRC
Log IP addresses in the recentchanges table; can be accessed only by extensions (e....
Definition: DefaultSettings.php:5762
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
Block\getRedactedName
getRedactedName()
Get the block name, but with autoblocked IPs hidden as per standard privacy policy.
Definition: Block.php:1105
Block\newLoad
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:307
$dbr
$dbr
Definition: testCompression.php:50
Block\$type
int $type
Block::TYPE_ constant.
Definition: Block.php:68
IP\isValidRange
static isValidRange( $ipRange)
Validate an IP range (valid address with a valid CIDR prefix).
Definition: IP.php:138
Wikimedia\Rdbms\IDatabase\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
LIST_OR
const LIST_OR
Definition: Defines.php:56
MWException
MediaWiki exception.
Definition: MWException.php:26
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1123
Block\parseTarget
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition: Block.php:1395
Block\$mBlockEmail
bool $mBlockEmail
Definition: Block.php:53
if
if(file_exists("$IP/StartProfiler.php"))
Definition: Setup.php:42
Block\getRangeCond
static getRangeCond( $start, $end=null)
Get a set of SQL conditions which will select rangeblocks encompassing a given range.
Definition: Block.php:411
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2812
Block\doAutoblock
doAutoblock( $autoblockIP)
Autoblocks the given IP, referring to this Block.
Definition: Block.php:811
Block\TYPE_ID
const TYPE_ID
Definition: Block.php:87
Block\isWhitelistedFromAutoblocks
static isWhitelistedFromAutoblocks( $ip)
Checks whether a given IP is on the autoblock whitelist.
Definition: Block.php:765
function
when a variable name is used in a function
Definition: design.txt:93
$lines
$lines
Definition: router.php:61
$link
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3021
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:95
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
IP\isInRange
static isInRange( $addr, $range)
Determine if a given IPv4/IPv6 address is in a given CIDR network.
Definition: IP.php:650
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:2009
Block\isAutoblocking
isAutoblocking( $x=null)
Definition: Block.php:1053
Block\$isAutoblocking
bool $isAutoblocking
Definition: Block.php:77
DB_MASTER
const DB_MASTER
Definition: defines.php:26
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:994
list
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
Block\getBlocksForIPList
static getBlocksForIPList(array $ipChain, $isAnon, $fromMaster=false)
Get all blocks that match any IP from an array of IP addresses.
Definition: Block.php:1212
MIGRATION_OLD
const MIGRATION_OLD
Definition: Defines.php:302
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:112
$options
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:2001
Block\getTargetAndType
getTargetAndType()
Get the target and target type for this particular Block.
Definition: Block.php:1463
$line
$line
Definition: cdb.php:59
Block\doRetroactiveAutoblock
doRetroactiveAutoblock()
Retroactively autoblocks the last IP used by the user (if it is a user) blocked by this Block.
Definition: Block.php:690
$expiryTime
$expiryTime
Definition: opensearch_desc.php:42
Block\getIdFromCookieValue
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
Definition: Block.php:1588
Block\updateTimestamp
updateTimestamp()
Update the timestamp on autoblocks.
Definition: Block.php:927
Block\$systemBlockType
string null $systemBlockType
Definition: Block.php:80
IP\parseRange
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
Block\$mId
int $mId
Definition: Block.php:47
Block\getBlocker
getBlocker()
Get the user who implemented this block.
Definition: Block.php:1498
Block\setBlocker
setBlocker( $user)
Set the user who implemented (or will implement) this block.
Definition: Block.php:1506
Block\$blocker
User $blocker
Definition: Block.php:71
$wgBlockDisablesLogin
$wgBlockDisablesLogin
If true, blocked users will not be allowed to login.
Definition: DefaultSettings.php:5035
Block\fromMaster
fromMaster( $x=null)
Get/set a flag determining whether the master is used for reads.
Definition: Block.php:1031
Block\getQueryInfo
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new block object.
Definition: Block.php:250
$status
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. '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:1255
Block\getTarget
getTarget()
Get the target for this particular Block.
Definition: Block.php:1473
Block\purgeExpired
static purgeExpired()
Purge expired blocks from the ipblocks table.
Definition: Block.php:1132
Block\TYPE_AUTO
const TYPE_AUTO
Definition: Block.php:86
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:434
IP\isValid
static isValid( $ip)
Validate an IP address.
Definition: IP.php:111
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:53
Block\TYPE_USER
const TYPE_USER
Definition: Block.php:83
IP\sanitizeIP
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
Definition: IP.php:152
$wgBlockCIDRLimit
$wgBlockCIDRLimit
Limits on the possible sizes of range blocks.
Definition: DefaultSettings.php:5023
$cache
$cache
Definition: mcc.php:33
Block\$mAuto
bool $mAuto
Definition: Block.php:35
Wikimedia\Rdbms\IDatabase\addQuotes
addQuotes( $s)
Adds quotes and backslashes.
Block\selectFields
static selectFields()
Return the list of ipblocks fields that should be selected to create a new block.
Definition: Block.php:208
Block\$mHideName
bool $mHideName
Definition: Block.php:41
Block\$forcedTargetID
int $forcedTargetID
Hack for foreign blocking (CentralAuth)
Definition: Block.php:65
Block\$target
User string $target
Definition: Block.php:62
as
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:22
Block\$mExpiry
string $mExpiry
Definition: Block.php:38
Block
Definition: Block.php:27
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
Wikimedia\Rdbms\IDatabase\selectFieldValues
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
Block\getRangeStart
getRangeStart()
Get the IP address at the start of the range in Hex form.
Definition: Block.php:951
Block\$mReason
string $mReason
Definition: Block.php:29
Block\getPermissionsError
getPermissionsError(IContextSource $context)
Get the key and parameters for the corresponding error message.
Definition: Block.php:1615
Block\getByName
getByName()
Get the username of the blocking sysop.
Definition: Block.php:1001
MediaWikiServices
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:25
User\isUsableName
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
Definition: User.php:1018
WebResponse
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:30
CommentStore\getStore
static getStore()
Definition: CommentStore.php:130
Block\newFromRow
static newFromRow( $row)
Create a new Block object from a database row.
Definition: Block.php:490
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:53
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
Block\getAutoblockUpdateArray
getAutoblockUpdateArray(IDatabase $dbw)
Definition: Block.php:675
User\getName
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2482
Block\defaultRetroactiveAutoblock
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:713
IP\sanitizeRange
static sanitizeRange( $range)
Gets rid of unneeded numbers in quad-dotted/octet IP strings For example, 127.111....
Definition: IP.php:725
$context
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:2811
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
Wikimedia\Rdbms\IDatabase\delete
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
Block\setTarget
setTarget( $target)
Set the target for this block, and update $this->type accordingly.
Definition: Block.php:1490
IContextSource\getLanguage
getLanguage()
Block\$mFromMaster
bool $mFromMaster
Definition: Block.php:50
Block\$mTimestamp
string $mTimestamp
Definition: Block.php:32
Block\getAutoblockExpiry
static getAutoblockExpiry( $timestamp)
Get a timestamp of the expiry for autoblocks.
Definition: Block.php:1123
$wgActorTableSchemaMigrationStage
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
Definition: DefaultSettings.php:8878