MediaWiki  master
Block.php
Go to the documentation of this file.
1 <?php
28 
29 class Block {
31  public $mReason;
32 
34  public $mTimestamp;
35 
37  public $mAuto;
38 
40  public $mExpiry;
41 
43  public $mHideName;
44 
47 
49  private $mId;
50 
52  private $mFromMaster;
53 
55  private $mBlockEmail;
56 
59 
61  private $mCreateAccount;
62 
64  private $target;
65 
67  private $forcedTargetID;
68 
70  private $type;
71 
73  private $blocker;
74 
76  private $isHardblock;
77 
79  private $isAutoblocking;
80 
83 
85  private $isSitewide;
86 
88  private $restrictions;
89 
90  # TYPE constants
91  const TYPE_USER = 1;
92  const TYPE_IP = 2;
93  const TYPE_RANGE = 3;
94  const TYPE_AUTO = 4;
95  const TYPE_ID = 5;
96 
123  function __construct( $options = [] ) {
124  $defaults = [
125  'address' => '',
126  'user' => null,
127  'by' => null,
128  'reason' => '',
129  'timestamp' => '',
130  'auto' => false,
131  'expiry' => '',
132  'anonOnly' => false,
133  'createAccount' => false,
134  'enableAutoblock' => false,
135  'hideName' => false,
136  'blockEmail' => false,
137  'allowUsertalk' => false,
138  'byText' => '',
139  'systemBlock' => null,
140  'sitewide' => true,
141  ];
142 
143  if ( func_num_args() > 1 || !is_array( $options ) ) {
144  $options = array_combine(
145  array_slice( array_keys( $defaults ), 0, func_num_args() ),
146  func_get_args()
147  );
148  wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
149  }
150 
151  $options += $defaults;
152 
153  $this->setTarget( $options['address'] );
154 
155  if ( $this->target instanceof User && $options['user'] ) {
156  # Needed for foreign users
157  $this->forcedTargetID = $options['user'];
158  }
159 
160  if ( $options['by'] ) {
161  # Local user
162  $this->setBlocker( User::newFromId( $options['by'] ) );
163  } else {
164  # Foreign user
165  $this->setBlocker( $options['byText'] );
166  }
167 
168  $this->mReason = $options['reason'];
169  $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
170  $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
171 
172  # Boolean settings
173  $this->mAuto = (bool)$options['auto'];
174  $this->mHideName = (bool)$options['hideName'];
175  $this->isHardblock( !$options['anonOnly'] );
176  $this->isAutoblocking( (bool)$options['enableAutoblock'] );
177  $this->isSitewide( (bool)$options['sitewide'] );
178 
179  # Prevention measures
180  $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
181  $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
182  $this->prevents( 'createaccount', (bool)$options['createAccount'] );
183 
184  $this->mFromMaster = false;
185  $this->systemBlockType = $options['systemBlock'];
186  }
187 
194  public static function newFromID( $id ) {
195  $dbr = wfGetDB( DB_REPLICA );
196  $blockQuery = self::getQueryInfo();
197  $res = $dbr->selectRow(
198  $blockQuery['tables'],
199  $blockQuery['fields'],
200  [ 'ipb_id' => $id ],
201  __METHOD__,
202  [],
203  $blockQuery['joins']
204  );
205  if ( $res ) {
206  return self::newFromRow( $res );
207  } else {
208  return null;
209  }
210  }
211 
218  public static function selectFields() {
220 
221  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
222  // If code is using this instead of self::getQueryInfo(), there's a
223  // decent chance it's going to try to directly access
224  // $row->ipb_by or $row->ipb_by_text and we can't give it
225  // useful values here once those aren't being used anymore.
226  throw new BadMethodCallException(
227  'Cannot use ' . __METHOD__
228  . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
229  );
230  }
231 
232  wfDeprecated( __METHOD__, '1.31' );
233  return [
234  'ipb_id',
235  'ipb_address',
236  'ipb_by',
237  'ipb_by_text',
238  'ipb_by_actor' => 'NULL',
239  'ipb_timestamp',
240  'ipb_auto',
241  'ipb_anon_only',
242  'ipb_create_account',
243  'ipb_enable_autoblock',
244  'ipb_expiry',
245  'ipb_deleted',
246  'ipb_block_email',
247  'ipb_allow_usertalk',
248  'ipb_parent_block_id',
249  'ipb_sitewide',
250  ] + CommentStore::getStore()->getFields( 'ipb_reason' );
251  }
252 
262  public static function getQueryInfo() {
263  $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
264  $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
265  return [
266  'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
267  'fields' => [
268  'ipb_id',
269  'ipb_address',
270  'ipb_timestamp',
271  'ipb_auto',
272  'ipb_anon_only',
273  'ipb_create_account',
274  'ipb_enable_autoblock',
275  'ipb_expiry',
276  'ipb_deleted',
277  'ipb_block_email',
278  'ipb_allow_usertalk',
279  'ipb_parent_block_id',
280  'ipb_sitewide',
281  ] + $commentQuery['fields'] + $actorQuery['fields'],
282  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
283  ];
284  }
285 
294  public function equals( Block $block ) {
295  return (
296  (string)$this->target == (string)$block->target
297  && $this->type == $block->type
298  && $this->mAuto == $block->mAuto
299  && $this->isHardblock() == $block->isHardblock()
300  && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
301  && $this->mExpiry == $block->mExpiry
302  && $this->isAutoblocking() == $block->isAutoblocking()
303  && $this->mHideName == $block->mHideName
304  && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
305  && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
306  && $this->mReason == $block->mReason
307  && $this->isSitewide() == $block->isSitewide()
308  // Block::getRestrictions() may perform a database query, so keep it at
309  // the end.
310  && BlockRestriction::equals( $this->getRestrictions(), $block->getRestrictions() )
311  );
312  }
313 
324  protected function newLoad( $vagueTarget = null ) {
325  $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
326 
327  if ( $this->type !== null ) {
328  $conds = [
329  'ipb_address' => [ (string)$this->target ],
330  ];
331  } else {
332  $conds = [ 'ipb_address' => [] ];
333  }
334 
335  # Be aware that the != '' check is explicit, since empty values will be
336  # passed by some callers (T31116)
337  if ( $vagueTarget != '' ) {
338  list( $target, $type ) = self::parseTarget( $vagueTarget );
339  switch ( $type ) {
340  case self::TYPE_USER:
341  # Slightly weird, but who are we to argue?
342  $conds['ipb_address'][] = (string)$target;
343  break;
344 
345  case self::TYPE_IP:
346  $conds['ipb_address'][] = (string)$target;
347  $conds[] = self::getRangeCond( IP::toHex( $target ) );
348  $conds = $db->makeList( $conds, LIST_OR );
349  break;
350 
351  case self::TYPE_RANGE:
352  list( $start, $end ) = IP::parseRange( $target );
353  $conds['ipb_address'][] = (string)$target;
354  $conds[] = self::getRangeCond( $start, $end );
355  $conds = $db->makeList( $conds, LIST_OR );
356  break;
357 
358  default:
359  throw new MWException( "Tried to load block with invalid type" );
360  }
361  }
362 
363  $blockQuery = self::getQueryInfo();
364  $res = $db->select(
365  $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
366  );
367 
368  # This result could contain a block on the user, a block on the IP, and a russian-doll
369  # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
370  $bestRow = null;
371 
372  # Lower will be better
373  $bestBlockScore = 100;
374 
375  # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
376  $bestBlockPreventsEdit = null;
377 
378  foreach ( $res as $row ) {
379  $block = self::newFromRow( $row );
380 
381  # Don't use expired blocks
382  if ( $block->isExpired() ) {
383  continue;
384  }
385 
386  # Don't use anon only blocks on users
387  if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
388  continue;
389  }
390 
391  if ( $block->getType() == self::TYPE_RANGE ) {
392  # This is the number of bits that are allowed to vary in the block, give
393  # or take some floating point errors
394  $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
395  $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
396  $size = log( $end - $start + 1, 2 );
397 
398  # This has the nice property that a /32 block is ranked equally with a
399  # single-IP block, which is exactly what it is...
400  $score = self::TYPE_RANGE - 1 + ( $size / 128 );
401 
402  } else {
403  $score = $block->getType();
404  }
405 
406  if ( $score < $bestBlockScore ) {
407  $bestBlockScore = $score;
408  $bestRow = $row;
409  $bestBlockPreventsEdit = $block->prevents( 'edit' );
410  }
411  }
412 
413  if ( $bestRow !== null ) {
414  $this->initFromRow( $bestRow );
415  $this->prevents( 'edit', $bestBlockPreventsEdit );
416  return true;
417  } else {
418  return false;
419  }
420  }
421 
428  public static function getRangeCond( $start, $end = null ) {
429  if ( $end === null ) {
430  $end = $start;
431  }
432  # Per T16634, we want to include relevant active rangeblocks; for
433  # rangeblocks, we want to include larger ranges which enclose the given
434  # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
435  # so we can improve performance by filtering on a LIKE clause
436  $chunk = self::getIpFragment( $start );
437  $dbr = wfGetDB( DB_REPLICA );
438  $like = $dbr->buildLike( $chunk, $dbr->anyString() );
439 
440  # Fairly hard to make a malicious SQL statement out of hex characters,
441  # but stranger things have happened...
442  $safeStart = $dbr->addQuotes( $start );
443  $safeEnd = $dbr->addQuotes( $end );
444 
445  return $dbr->makeList(
446  [
447  "ipb_range_start $like",
448  "ipb_range_start <= $safeStart",
449  "ipb_range_end >= $safeEnd",
450  ],
451  LIST_AND
452  );
453  }
454 
461  protected static function getIpFragment( $hex ) {
462  global $wgBlockCIDRLimit;
463  if ( substr( $hex, 0, 3 ) == 'v6-' ) {
464  return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
465  } else {
466  return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
467  }
468  }
469 
475  protected function initFromRow( $row ) {
476  $this->setTarget( $row->ipb_address );
478  $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
479  ) );
480 
481  $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
482  $this->mAuto = $row->ipb_auto;
483  $this->mHideName = $row->ipb_deleted;
484  $this->mId = (int)$row->ipb_id;
485  $this->mParentBlockId = $row->ipb_parent_block_id;
486 
487  // I wish I didn't have to do this
488  $db = wfGetDB( DB_REPLICA );
489  $this->mExpiry = $db->decodeExpiry( $row->ipb_expiry );
490  $this->mReason = CommentStore::getStore()
491  // Legacy because $row may have come from self::selectFields()
492  ->getCommentLegacy( $db, 'ipb_reason', $row )->text;
493 
494  $this->isHardblock( !$row->ipb_anon_only );
495  $this->isAutoblocking( $row->ipb_enable_autoblock );
496  $this->isSitewide( (bool)$row->ipb_sitewide );
497 
498  $this->prevents( 'createaccount', $row->ipb_create_account );
499  $this->prevents( 'sendemail', $row->ipb_block_email );
500  $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
501  }
502 
508  public static function newFromRow( $row ) {
509  $block = new Block;
510  $block->initFromRow( $row );
511  return $block;
512  }
513 
520  public function delete() {
521  if ( wfReadOnly() ) {
522  return false;
523  }
524 
525  if ( !$this->getId() ) {
526  throw new MWException( "Block::delete() requires that the mId member be filled\n" );
527  }
528 
529  $dbw = wfGetDB( DB_MASTER );
530 
531  BlockRestriction::deleteByParentBlockId( $this->getId() );
532  $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
533 
534  BlockRestriction::deleteByBlockId( $this->getId() );
535  $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
536 
537  return $dbw->affectedRows() > 0;
538  }
539 
548  public function insert( $dbw = null ) {
549  global $wgBlockDisablesLogin;
550 
551  if ( $this->getSystemBlockType() !== null ) {
552  throw new MWException( 'Cannot insert a system block into the database' );
553  }
554  if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
555  throw new MWException( 'Cannot insert a block without a blocker set' );
556  }
557 
558  wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
559 
560  if ( $dbw === null ) {
561  $dbw = wfGetDB( DB_MASTER );
562  }
563 
564  self::purgeExpired();
565 
566  $row = $this->getDatabaseArray( $dbw );
567 
568  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
569  $affected = $dbw->affectedRows();
570  if ( $affected ) {
571  $this->setId( $dbw->insertId() );
572  if ( $this->restrictions ) {
573  BlockRestriction::insert( $this->restrictions );
574  }
575  }
576 
577  # Don't collide with expired blocks.
578  # Do this after trying to insert to avoid locking.
579  if ( !$affected ) {
580  # T96428: The ipb_address index uses a prefix on a field, so
581  # use a standard SELECT + DELETE to avoid annoying gap locks.
582  $ids = $dbw->selectFieldValues( 'ipblocks',
583  'ipb_id',
584  [
585  'ipb_address' => $row['ipb_address'],
586  'ipb_user' => $row['ipb_user'],
587  'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
588  ],
589  __METHOD__
590  );
591  if ( $ids ) {
592  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
593  BlockRestriction::deleteByBlockId( $ids );
594  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
595  $affected = $dbw->affectedRows();
596  $this->setId( $dbw->insertId() );
597  if ( $this->restrictions ) {
598  BlockRestriction::insert( $this->restrictions );
599  }
600  }
601  }
602 
603  if ( $affected ) {
604  $auto_ipd_ids = $this->doRetroactiveAutoblock();
605 
606  if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
607  // Change user login token to force them to be logged out.
608  $this->target->setToken();
609  $this->target->saveSettings();
610  }
611 
612  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
613  }
614 
615  return false;
616  }
617 
625  public function update() {
626  wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
627  $dbw = wfGetDB( DB_MASTER );
628 
629  $dbw->startAtomic( __METHOD__ );
630 
631  $result = $dbw->update(
632  'ipblocks',
633  $this->getDatabaseArray( $dbw ),
634  [ 'ipb_id' => $this->getId() ],
635  __METHOD__
636  );
637 
638  // Only update the restrictions if they have been modified.
639  if ( $this->restrictions !== null ) {
640  // An empty array should remove all of the restrictions.
641  if ( empty( $this->restrictions ) ) {
642  $success = BlockRestriction::deleteByBlockId( $this->getId() );
643  } else {
644  $success = BlockRestriction::update( $this->restrictions );
645  }
646  // Update the result. The first false is the result, otherwise, true.
647  $result = $result && $success;
648  }
649 
650  if ( $this->isAutoblocking() ) {
651  // update corresponding autoblock(s) (T50813)
652  $dbw->update(
653  'ipblocks',
654  $this->getAutoblockUpdateArray( $dbw ),
655  [ 'ipb_parent_block_id' => $this->getId() ],
656  __METHOD__
657  );
658 
659  // Only update the restrictions if they have been modified.
660  if ( $this->restrictions !== null ) {
661  BlockRestriction::updateByParentBlockId( $this->getId(), $this->restrictions );
662  }
663  } else {
664  // autoblock no longer required, delete corresponding autoblock(s)
665  BlockRestriction::deleteByParentBlockId( $this->getId() );
666  $dbw->delete(
667  'ipblocks',
668  [ 'ipb_parent_block_id' => $this->getId() ],
669  __METHOD__
670  );
671  }
672 
673  $dbw->endAtomic( __METHOD__ );
674 
675  if ( $result ) {
676  $auto_ipd_ids = $this->doRetroactiveAutoblock();
677  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
678  }
679 
680  return $result;
681  }
682 
688  protected function getDatabaseArray( IDatabase $dbw ) {
689  $expiry = $dbw->encodeExpiry( $this->mExpiry );
690 
691  if ( $this->forcedTargetID ) {
692  $uid = $this->forcedTargetID;
693  } else {
694  $uid = $this->target instanceof User ? $this->target->getId() : 0;
695  }
696 
697  $a = [
698  'ipb_address' => (string)$this->target,
699  'ipb_user' => $uid,
700  'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
701  'ipb_auto' => $this->mAuto,
702  'ipb_anon_only' => !$this->isHardblock(),
703  'ipb_create_account' => $this->prevents( 'createaccount' ),
704  'ipb_enable_autoblock' => $this->isAutoblocking(),
705  'ipb_expiry' => $expiry,
706  'ipb_range_start' => $this->getRangeStart(),
707  'ipb_range_end' => $this->getRangeEnd(),
708  'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
709  'ipb_block_email' => $this->prevents( 'sendemail' ),
710  'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
711  'ipb_parent_block_id' => $this->mParentBlockId,
712  'ipb_sitewide' => $this->isSitewide(),
713  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
714  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
715 
716  return $a;
717  }
718 
723  protected function getAutoblockUpdateArray( IDatabase $dbw ) {
724  return [
725  'ipb_create_account' => $this->prevents( 'createaccount' ),
726  'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
727  'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
728  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
729  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
730  }
731 
738  protected function doRetroactiveAutoblock() {
739  $blockIds = [];
740  # If autoblock is enabled, autoblock the LAST IP(s) used
741  if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
742  wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
743 
744  $continue = Hooks::run(
745  'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
746 
747  if ( $continue ) {
748  self::defaultRetroactiveAutoblock( $this, $blockIds );
749  }
750  }
751  return $blockIds;
752  }
753 
761  protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
762  global $wgPutIPinRC;
763 
764  // No IPs are in recentchanges table, so nothing to select
765  if ( !$wgPutIPinRC ) {
766  return;
767  }
768 
769  // Autoblocks only apply to TYPE_USER
770  if ( $block->getType() !== self::TYPE_USER ) {
771  return;
772  }
773  $target = $block->getTarget(); // TYPE_USER => always a User object
774 
775  $dbr = wfGetDB( DB_REPLICA );
776  $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
777 
778  $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
779 
780  // Just the last IP used.
781  $options['LIMIT'] = 1;
782 
783  $res = $dbr->select(
784  [ 'recentchanges' ] + $rcQuery['tables'],
785  [ 'rc_ip' ],
786  $rcQuery['conds'],
787  __METHOD__,
788  $options,
789  $rcQuery['joins']
790  );
791 
792  if ( !$res->numRows() ) {
793  # No results, don't autoblock anything
794  wfDebug( "No IP found to retroactively autoblock\n" );
795  } else {
796  foreach ( $res as $row ) {
797  if ( $row->rc_ip ) {
798  $id = $block->doAutoblock( $row->rc_ip );
799  if ( $id ) {
800  $blockIds[] = $id;
801  }
802  }
803  }
804  }
805  }
806 
814  public static function isWhitelistedFromAutoblocks( $ip ) {
815  // Try to get the autoblock_whitelist from the cache, as it's faster
816  // than getting the msg raw and explode()'ing it.
817  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
818  $lines = $cache->getWithSetCallback(
819  $cache->makeKey( 'ip-autoblock', 'whitelist' ),
820  $cache::TTL_DAY,
821  function ( $curValue, &$ttl, array &$setOpts ) {
822  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
823 
824  return explode( "\n",
825  wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
826  }
827  );
828 
829  wfDebug( "Checking the autoblock whitelist..\n" );
830 
831  foreach ( $lines as $line ) {
832  # List items only
833  if ( substr( $line, 0, 1 ) !== '*' ) {
834  continue;
835  }
836 
837  $wlEntry = substr( $line, 1 );
838  $wlEntry = trim( $wlEntry );
839 
840  wfDebug( "Checking $ip against $wlEntry..." );
841 
842  # Is the IP in this range?
843  if ( IP::isInRange( $ip, $wlEntry ) ) {
844  wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
845  return true;
846  } else {
847  wfDebug( " No match\n" );
848  }
849  }
850 
851  return false;
852  }
853 
860  public function doAutoblock( $autoblockIP ) {
861  # If autoblocks are disabled, go away.
862  if ( !$this->isAutoblocking() ) {
863  return false;
864  }
865 
866  # Don't autoblock for system blocks
867  if ( $this->getSystemBlockType() !== null ) {
868  throw new MWException( 'Cannot autoblock from a system block' );
869  }
870 
871  # Check for presence on the autoblock whitelist.
872  if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
873  return false;
874  }
875 
876  // Avoid PHP 7.1 warning of passing $this by reference
877  $block = $this;
878  # Allow hooks to cancel the autoblock.
879  if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
880  wfDebug( "Autoblock aborted by hook.\n" );
881  return false;
882  }
883 
884  # It's okay to autoblock. Go ahead and insert/update the block...
885 
886  # Do not add a *new* block if the IP is already blocked.
887  $ipblock = self::newFromTarget( $autoblockIP );
888  if ( $ipblock ) {
889  # Check if the block is an autoblock and would exceed the user block
890  # if renewed. If so, do nothing, otherwise prolong the block time...
891  if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
892  $this->mExpiry > self::getAutoblockExpiry( $ipblock->mTimestamp )
893  ) {
894  # Reset block timestamp to now and its expiry to
895  # $wgAutoblockExpiry in the future
896  $ipblock->updateTimestamp();
897  }
898  return false;
899  }
900 
901  # Make a new block object with the desired properties.
902  $autoblock = new Block;
903  wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
904  $autoblock->setTarget( $autoblockIP );
905  $autoblock->setBlocker( $this->getBlocker() );
906  $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
907  ->inContentLanguage()->plain();
908  $timestamp = wfTimestampNow();
909  $autoblock->mTimestamp = $timestamp;
910  $autoblock->mAuto = 1;
911  $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
912  # Continue suppressing the name if needed
913  $autoblock->mHideName = $this->mHideName;
914  $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
915  $autoblock->mParentBlockId = $this->mId;
916  $autoblock->isSitewide( $this->isSitewide() );
917  $autoblock->setRestrictions( $this->getRestrictions() );
918 
919  if ( $this->mExpiry == 'infinity' ) {
920  # Original block was indefinite, start an autoblock now
921  $autoblock->mExpiry = self::getAutoblockExpiry( $timestamp );
922  } else {
923  # If the user is already blocked with an expiry date, we don't
924  # want to pile on top of that.
925  $autoblock->mExpiry = min( $this->mExpiry, self::getAutoblockExpiry( $timestamp ) );
926  }
927 
928  # Insert the block...
929  $status = $autoblock->insert();
930  return $status
931  ? $status['id']
932  : false;
933  }
934 
939  public function deleteIfExpired() {
940  if ( $this->isExpired() ) {
941  wfDebug( "Block::deleteIfExpired() -- deleting\n" );
942  $this->delete();
943  $retVal = true;
944  } else {
945  wfDebug( "Block::deleteIfExpired() -- not expired\n" );
946  $retVal = false;
947  }
948 
949  return $retVal;
950  }
951 
956  public function isExpired() {
957  $timestamp = wfTimestampNow();
958  wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
959 
960  if ( !$this->mExpiry ) {
961  return false;
962  } else {
963  return $timestamp > $this->mExpiry;
964  }
965  }
966 
971  public function isValid() {
972  return $this->getTarget() != null;
973  }
974 
978  public function updateTimestamp() {
979  if ( $this->mAuto ) {
980  $this->mTimestamp = wfTimestamp();
981  $this->mExpiry = self::getAutoblockExpiry( $this->mTimestamp );
982 
983  $dbw = wfGetDB( DB_MASTER );
984  $dbw->update( 'ipblocks',
985  [ /* SET */
986  'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
987  'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
988  ],
989  [ /* WHERE */
990  'ipb_id' => $this->getId(),
991  ],
992  __METHOD__
993  );
994  }
995  }
996 
1002  public function getRangeStart() {
1003  switch ( $this->type ) {
1004  case self::TYPE_USER:
1005  return '';
1006  case self::TYPE_IP:
1007  return IP::toHex( $this->target );
1008  case self::TYPE_RANGE:
1009  list( $start, /*...*/ ) = IP::parseRange( $this->target );
1010  return $start;
1011  default:
1012  throw new MWException( "Block with invalid type" );
1013  }
1014  }
1015 
1021  public function getRangeEnd() {
1022  switch ( $this->type ) {
1023  case self::TYPE_USER:
1024  return '';
1025  case self::TYPE_IP:
1026  return IP::toHex( $this->target );
1027  case self::TYPE_RANGE:
1028  list( /*...*/, $end ) = IP::parseRange( $this->target );
1029  return $end;
1030  default:
1031  throw new MWException( "Block with invalid type" );
1032  }
1033  }
1034 
1040  public function getBy() {
1041  $blocker = $this->getBlocker();
1042  return ( $blocker instanceof User )
1043  ? $blocker->getId()
1044  : 0;
1045  }
1046 
1052  public function getByName() {
1053  $blocker = $this->getBlocker();
1054  return ( $blocker instanceof User )
1055  ? $blocker->getName()
1056  : (string)$blocker; // username
1057  }
1058 
1063  public function getId() {
1064  return $this->mId;
1065  }
1066 
1073  private function setId( $blockId ) {
1074  $this->mId = (int)$blockId;
1075 
1076  if ( is_array( $this->restrictions ) ) {
1077  $this->restrictions = BlockRestriction::setBlockId( $blockId, $this->restrictions );
1078  }
1079 
1080  return $this;
1081  }
1082 
1088  public function getSystemBlockType() {
1089  return $this->systemBlockType;
1090  }
1091 
1098  public function fromMaster( $x = null ) {
1099  return wfSetVar( $this->mFromMaster, $x );
1100  }
1101 
1107  public function isHardblock( $x = null ) {
1108  wfSetVar( $this->isHardblock, $x );
1109 
1110  # You can't *not* hardblock a user
1111  return $this->getType() == self::TYPE_USER
1112  ? true
1114  }
1115 
1120  public function isAutoblocking( $x = null ) {
1121  wfSetVar( $this->isAutoblocking, $x );
1122 
1123  # You can't put an autoblock on an IP or range as we don't have any history to
1124  # look over to get more IPs from
1125  return $this->getType() == self::TYPE_USER
1126  ? $this->isAutoblocking
1127  : false;
1128  }
1129 
1138  public function isSitewide( $x = null ) {
1139  return wfSetVar( $this->isSitewide, $x );
1140  }
1141 
1149  public function prevents( $action, $x = null ) {
1150  $config = RequestContext::getMain()->getConfig();
1151  $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1152  $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1153 
1154  $res = null;
1155  switch ( $action ) {
1156  case 'edit':
1157  # For now... <evil laugh>
1158  $res = true;
1159  break;
1160  case 'createaccount':
1161  $res = wfSetVar( $this->mCreateAccount, $x );
1162  break;
1163  case 'sendemail':
1164  $res = wfSetVar( $this->mBlockEmail, $x );
1165  break;
1166  case 'upload':
1167  // Until T6995 is completed
1168  $res = $this->isSitewide();
1169  break;
1170  case 'editownusertalk':
1171  // NOTE: this check is not reliable on partial blocks
1172  // since partially blocked users are always allowed to edit
1173  // their own talk page unless a restriction exists on the
1174  // page or User_talk: namespace
1175  $res = wfSetVar( $this->mDisableUsertalk, $x );
1176 
1177  // edit own user talk can be disabled by config
1178  if ( !$blockAllowsUTEdit ) {
1179  $res = true;
1180  }
1181  break;
1182  case 'read':
1183  $res = false;
1184  break;
1185  }
1186  if ( !$res && $blockDisablesLogin ) {
1187  // If a block would disable login, then it should
1188  // prevent any action that all users cannot do
1189  $anon = new User;
1190  $res = $anon->isAllowed( $action ) ? $res : true;
1191  }
1192 
1193  return $res;
1194  }
1195 
1200  public function getRedactedName() {
1201  if ( $this->mAuto ) {
1202  return Html::rawElement(
1203  'span',
1204  [ 'class' => 'mw-autoblockid' ],
1205  wfMessage( 'autoblockid', $this->mId )
1206  );
1207  } else {
1208  return htmlspecialchars( $this->getTarget() );
1209  }
1210  }
1211 
1218  public static function getAutoblockExpiry( $timestamp ) {
1219  global $wgAutoblockExpiry;
1220 
1221  return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1222  }
1223 
1227  public static function purgeExpired() {
1228  if ( wfReadOnly() ) {
1229  return;
1230  }
1231 
1233  wfGetDB( DB_MASTER ),
1234  __METHOD__,
1235  function ( IDatabase $dbw, $fname ) {
1236  $ids = $dbw->selectFieldValues( 'ipblocks',
1237  'ipb_id',
1238  [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1239  $fname
1240  );
1241  if ( $ids ) {
1242  BlockRestriction::deleteByBlockId( $ids );
1243  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1244  }
1245  }
1246  ) );
1247  }
1248 
1269  public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1270  list( $target, $type ) = self::parseTarget( $specificTarget );
1271  if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1272  return self::newFromID( $target );
1273 
1274  } elseif ( $target === null && $vagueTarget == '' ) {
1275  # We're not going to find anything useful here
1276  # Be aware that the == '' check is explicit, since empty values will be
1277  # passed by some callers (T31116)
1278  return null;
1279 
1280  } elseif ( in_array(
1281  $type,
1282  [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1283  ) {
1284  $block = new Block();
1285  $block->fromMaster( $fromMaster );
1286 
1287  if ( $type !== null ) {
1288  $block->setTarget( $target );
1289  }
1290 
1291  if ( $block->newLoad( $vagueTarget ) ) {
1292  return $block;
1293  }
1294  }
1295  return null;
1296  }
1297 
1308  public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1309  if ( !count( $ipChain ) ) {
1310  return [];
1311  }
1312 
1313  $conds = [];
1314  $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1315  foreach ( array_unique( $ipChain ) as $ipaddr ) {
1316  # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1317  # necessarily trust the header given to us, make sure that we are only
1318  # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1319  # Do not treat private IP spaces as special as it may be desirable for wikis
1320  # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1321  if ( !IP::isValid( $ipaddr ) ) {
1322  continue;
1323  }
1324  # Don't check trusted IPs (includes local squids which will be in every request)
1325  if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1326  continue;
1327  }
1328  # Check both the original IP (to check against single blocks), as well as build
1329  # the clause to check for rangeblocks for the given IP.
1330  $conds['ipb_address'][] = $ipaddr;
1331  $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1332  }
1333 
1334  if ( !count( $conds ) ) {
1335  return [];
1336  }
1337 
1338  if ( $fromMaster ) {
1339  $db = wfGetDB( DB_MASTER );
1340  } else {
1341  $db = wfGetDB( DB_REPLICA );
1342  }
1343  $conds = $db->makeList( $conds, LIST_OR );
1344  if ( !$isAnon ) {
1345  $conds = [ $conds, 'ipb_anon_only' => 0 ];
1346  }
1347  $blockQuery = self::getQueryInfo();
1348  $rows = $db->select(
1349  $blockQuery['tables'],
1350  array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1351  $conds,
1352  __METHOD__,
1353  [],
1354  $blockQuery['joins']
1355  );
1356 
1357  $blocks = [];
1358  foreach ( $rows as $row ) {
1359  $block = self::newFromRow( $row );
1360  if ( !$block->isExpired() ) {
1361  $blocks[] = $block;
1362  }
1363  }
1364 
1365  return $blocks;
1366  }
1367 
1389  public static function chooseBlock( array $blocks, array $ipChain ) {
1390  if ( !count( $blocks ) ) {
1391  return null;
1392  } elseif ( count( $blocks ) == 1 ) {
1393  return $blocks[0];
1394  }
1395 
1396  // Sort hard blocks before soft ones and secondarily sort blocks
1397  // that disable account creation before those that don't.
1398  usort( $blocks, function ( Block $a, Block $b ) {
1399  $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1400  $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1401  return strcmp( $bWeight, $aWeight ); // highest weight first
1402  } );
1403 
1404  $blocksListExact = [
1405  'hard' => false,
1406  'disable_create' => false,
1407  'other' => false,
1408  'auto' => false
1409  ];
1410  $blocksListRange = [
1411  'hard' => false,
1412  'disable_create' => false,
1413  'other' => false,
1414  'auto' => false
1415  ];
1416  $ipChain = array_reverse( $ipChain );
1417 
1419  foreach ( $blocks as $block ) {
1420  // Stop searching if we have already have a "better" block. This
1421  // is why the order of the blocks matters
1422  if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1423  break;
1424  } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1425  break;
1426  }
1427 
1428  foreach ( $ipChain as $checkip ) {
1429  $checkipHex = IP::toHex( $checkip );
1430  if ( (string)$block->getTarget() === $checkip ) {
1431  if ( $block->isHardblock() ) {
1432  $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1433  } elseif ( $block->prevents( 'createaccount' ) ) {
1434  $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1435  } elseif ( $block->mAuto ) {
1436  $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1437  } else {
1438  $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1439  }
1440  // We found closest exact match in the ip list, so go to the next Block
1441  break;
1442  } elseif ( array_filter( $blocksListExact ) == []
1443  && $block->getRangeStart() <= $checkipHex
1444  && $block->getRangeEnd() >= $checkipHex
1445  ) {
1446  if ( $block->isHardblock() ) {
1447  $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1448  } elseif ( $block->prevents( 'createaccount' ) ) {
1449  $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1450  } elseif ( $block->mAuto ) {
1451  $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1452  } else {
1453  $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1454  }
1455  break;
1456  }
1457  }
1458  }
1459 
1460  if ( array_filter( $blocksListExact ) == [] ) {
1461  $blocksList = &$blocksListRange;
1462  } else {
1463  $blocksList = &$blocksListExact;
1464  }
1465 
1466  $chosenBlock = null;
1467  if ( $blocksList['hard'] ) {
1468  $chosenBlock = $blocksList['hard'];
1469  } elseif ( $blocksList['disable_create'] ) {
1470  $chosenBlock = $blocksList['disable_create'];
1471  } elseif ( $blocksList['other'] ) {
1472  $chosenBlock = $blocksList['other'];
1473  } elseif ( $blocksList['auto'] ) {
1474  $chosenBlock = $blocksList['auto'];
1475  } else {
1476  throw new MWException( "Proxy block found, but couldn't be classified." );
1477  }
1478 
1479  return $chosenBlock;
1480  }
1481 
1491  public static function parseTarget( $target ) {
1492  # We may have been through this before
1493  if ( $target instanceof User ) {
1494  if ( IP::isValid( $target->getName() ) ) {
1495  return [ $target, self::TYPE_IP ];
1496  } else {
1497  return [ $target, self::TYPE_USER ];
1498  }
1499  } elseif ( $target === null ) {
1500  return [ null, null ];
1501  }
1502 
1503  $target = trim( $target );
1504 
1505  if ( IP::isValid( $target ) ) {
1506  # We can still create a User if it's an IP address, but we need to turn
1507  # off validation checking (which would exclude IP addresses)
1508  return [
1510  self::TYPE_IP
1511  ];
1512 
1513  } elseif ( IP::isValidRange( $target ) ) {
1514  # Can't create a User from an IP range
1515  return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1516  }
1517 
1518  # Consider the possibility that this is not a username at all
1519  # but actually an old subpage (T31797)
1520  if ( strpos( $target, '/' ) !== false ) {
1521  # An old subpage, drill down to the user behind it
1522  $target = explode( '/', $target )[0];
1523  }
1524 
1525  $userObj = User::newFromName( $target );
1526  if ( $userObj instanceof User ) {
1527  # Note that since numbers are valid usernames, a $target of "12345" will be
1528  # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1529  # since hash characters are not valid in usernames or titles generally.
1530  return [ $userObj, self::TYPE_USER ];
1531 
1532  } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1533  # Autoblock reference in the form "#12345"
1534  return [ substr( $target, 1 ), self::TYPE_AUTO ];
1535 
1536  } else {
1537  # WTF?
1538  return [ null, null ];
1539  }
1540  }
1541 
1546  public function getType() {
1547  return $this->mAuto
1548  ? self::TYPE_AUTO
1549  : $this->type;
1550  }
1551 
1559  public function getTargetAndType() {
1560  return [ $this->getTarget(), $this->getType() ];
1561  }
1562 
1569  public function getTarget() {
1570  return $this->target;
1571  }
1572 
1578  public function getExpiry() {
1579  return $this->mExpiry;
1580  }
1581 
1586  public function setTarget( $target ) {
1587  list( $this->target, $this->type ) = self::parseTarget( $target );
1588  }
1589 
1594  public function getBlocker() {
1595  return $this->blocker;
1596  }
1597 
1602  public function setBlocker( $user ) {
1603  if ( is_string( $user ) ) {
1604  $user = User::newFromName( $user, false );
1605  }
1606 
1607  if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1608  throw new InvalidArgumentException(
1609  'Blocker must be a local user or a name that cannot be a local user'
1610  );
1611  }
1612 
1613  $this->blocker = $user;
1614  }
1615 
1624  public function setCookie( WebResponse $response ) {
1625  // Calculate the default expiry time.
1626  $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1627 
1628  // Use the Block's expiry time only if it's less than the default.
1629  $expiryTime = $this->getExpiry();
1630  if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1631  $expiryTime = $maxExpiryTime;
1632  }
1633 
1634  // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1635  $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1636  $cookieOptions = [ 'httpOnly' => false ];
1637  $cookieValue = $this->getCookieValue();
1638  $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1639  }
1640 
1648  public static function clearCookie( WebResponse $response ) {
1649  $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1650  }
1651 
1661  public function getCookieValue() {
1662  $config = RequestContext::getMain()->getConfig();
1663  $id = $this->getId();
1664  $secretKey = $config->get( 'SecretKey' );
1665  if ( !$secretKey ) {
1666  // If there's no secret key, don't append a HMAC.
1667  return $id;
1668  }
1669  $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1670  $cookieValue = $id . '!' . $hmac;
1671  return $cookieValue;
1672  }
1673 
1684  public static function getIdFromCookieValue( $cookieValue ) {
1685  // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1686  $bangPos = strpos( $cookieValue, '!' );
1687  $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1688  // Get the site-wide secret key.
1689  $config = RequestContext::getMain()->getConfig();
1690  $secretKey = $config->get( 'SecretKey' );
1691  if ( !$secretKey ) {
1692  // If there's no secret key, just use the ID as given.
1693  return $id;
1694  }
1695  $storedHmac = substr( $cookieValue, $bangPos + 1 );
1696  $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1697  if ( $calculatedHmac === $storedHmac ) {
1698  return $id;
1699  } else {
1700  return null;
1701  }
1702  }
1703 
1712  $params = $this->getBlockErrorParams( $context );
1713 
1714  $msg = 'blockedtext';
1715  if ( $this->getSystemBlockType() !== null ) {
1716  $msg = 'systemblockedtext';
1717  } elseif ( $this->mAuto ) {
1718  $msg = 'autoblockedtext';
1719  } elseif ( !$this->isSitewide() ) {
1720  $msg = 'blockedtext-partial';
1721  }
1722 
1723  array_unshift( $params, $msg );
1724 
1725  return $params;
1726  }
1727 
1735  $blocker = $this->getBlocker();
1736  if ( $blocker instanceof User ) { // local user
1737  $blockerUserpage = $blocker->getUserPage();
1738  $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1739  } else { // foreign user
1740  $link = $blocker;
1741  }
1742 
1743  $reason = $this->mReason;
1744  if ( $reason == '' ) {
1745  $reason = $context->msg( 'blockednoreason' )->text();
1746  }
1747 
1748  /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1749  * This could be a username, an IP range, or a single IP. */
1750  $intended = $this->getTarget();
1752  $lang = $context->getLanguage();
1753 
1754  return [
1755  $link,
1756  $reason,
1757  $context->getRequest()->getIP(),
1758  $this->getByName(),
1759  $systemBlockType ?? $this->getId(),
1760  $lang->formatExpiry( $this->mExpiry ),
1761  (string)$intended,
1762  $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1763  ];
1764  }
1765 
1774  public function getRestrictions() {
1775  if ( $this->restrictions === null ) {
1776  // If the block id has not been set, then do not attempt to load the
1777  // restrictions.
1778  if ( !$this->mId ) {
1779  return [];
1780  }
1781  $this->restrictions = BlockRestriction::loadByBlockId( $this->mId );
1782  }
1783 
1784  return $this->restrictions;
1785  }
1786 
1794  public function setRestrictions( array $restrictions ) {
1795  $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1796  return $restriction instanceof Restriction;
1797  } );
1798 
1799  return $this;
1800  }
1801 
1813  public function appliesToTitle( Title $title ) {
1814  if ( $this->isSitewide() ) {
1815  return true;
1816  }
1817 
1818  $restrictions = $this->getRestrictions();
1819  foreach ( $restrictions as $restriction ) {
1820  if ( $restriction->matches( $title ) ) {
1821  return true;
1822  }
1823  }
1824 
1825  return false;
1826  }
1827 }
getBy()
Get the user id of the blocking sysop.
Definition: Block.php:1040
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:508
bool $isHardblock
Definition: Block.php:76
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:2626
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:34
static newFromID( $id)
Load a blocked user from their block id.
Definition: Block.php:194
either a plain
Definition: hooks.txt:2057
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:761
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:1389
const TYPE_RANGE
Definition: Block.php:93
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:1149
bool $mFromMaster
Definition: Block.php:52
getSystemBlockType()
Get the system block type, if any.
Definition: Block.php:1088
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:971
getType()
Get the type of target for this particular block.
Definition: Block.php:1546
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:1269
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:1277
int $mParentBlockId
Definition: Block.php:46
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
bool $mDisableUsertalk
Definition: Block.php:58
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
equals(Block $block)
Check if two blocks are effectively equal.
Definition: Block.php:294
getCookieValue()
Get the BlockID cookie&#39;s value for this block.
Definition: Block.php:1661
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:461
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
getDatabaseArray(IDatabase $dbw)
Get an array suitable for passing to $dbw->insert() or $dbw->update()
Definition: Block.php:688
const SCHEMA_COMPAT_READ_NEW
Definition: Defines.php:287
static clearCookie(WebResponse $response)
Unset the &#39;BlockID&#39; cookie.
Definition: Block.php:1648
const TYPE_IP
Definition: Block.php:92
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:548
getId()
Get the block ID.
Definition: Block.php:1063
this hook is for auditing only $response
Definition: hooks.txt:785
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:324
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition: Block.php:1491
initFromRow( $row)
Given a database row from the ipblocks table, initialize member variables.
Definition: Block.php:475
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:2469
update()
Update a block in the DB with new parameters.
Definition: Block.php:625
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:1994
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:1624
getRangeEnd()
Get the IP address at the end of the range in Hex form.
Definition: Block.php:1021
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3043
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:1996
deleteIfExpired()
Check if a block has expired.
Definition: Block.php:939
__construct( $options=[])
Create a new block with specified parameters on a user, IP or IP range.
Definition: Block.php:123
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:1578
wfReadOnly()
Check whether the wiki is in read-only mode.
Restriction [] $restrictions
Definition: Block.php:88
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:70
appliesToTitle(Title $title)
Checks if a block applies to a particular title.
Definition: Block.php:1813
setRestrictions(array $restrictions)
Set Restrictions.
Definition: Block.php:1794
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
Definition: IP.php:152
isAutoblocking( $x=null)
Definition: Block.php:1120
getTargetAndType()
Get the target and target type for this particular Block.
Definition: Block.php:1559
getRedactedName()
Get the block name, but with autoblocked IPs hidden as per standard privacy policy.
Definition: Block.php:1200
bool $isAutoblocking
Definition: Block.php:79
$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:860
bool $mBlockEmail
Definition: Block.php:55
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:49
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:1996
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
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:1138
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:936
static purgeExpired()
Purge expired blocks from the ipblocks table.
Definition: Block.php:1227
static getRangeCond( $start, $end=null)
Get a set of SQL conditions which will select rangeblocks encompassing a given range.
Definition: Block.php:428
const TYPE_ID
Definition: Block.php:95
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new block object...
Definition: Block.php:262
const TYPE_AUTO
Definition: Block.php:94
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:814
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:121
const LIST_OR
Definition: Defines.php:46
User string $target
Definition: Block.php:64
doRetroactiveAutoblock()
Retroactively autoblocks the last IP used by the user (if it is a user) blocked by this Block...
Definition: Block.php:738
$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:1308
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the &#39;BlockID&#39; cookie.
Definition: Block.php:1684
bool $mAuto
Definition: Block.php:37
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:67
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:978
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:1594
getId()
Get the user&#39;s ID.
Definition: User.php:2444
getPermissionsError(IContextSource $context)
Get the key and parameters for the corresponding error message.
Definition: Block.php:1711
static selectFields()
Return the list of ipblocks fields that should be selected to create a new block. ...
Definition: Block.php:218
setBlocker( $user)
Set the user who implemented (or will implement) this block.
Definition: Block.php:1602
User $blocker
Definition: Block.php:73
string null $systemBlockType
Definition: Block.php:82
getBlockErrorParams(IContextSource $context)
Get block information used in different block error messages.
Definition: Block.php:1734
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:1569
fromMaster( $x=null)
Get/set a flag determining whether the master is used for reads.
Definition: Block.php:1098
getUserPage()
Get this user&#39;s personal page title.
Definition: User.php:4562
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and insert
Definition: hooks.txt:2075
getRestrictions()
Get Restrictions.
Definition: Block.php:1774
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:2626
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:91
getAutoblockUpdateArray(IDatabase $dbw)
Definition: Block.php:723
setTarget( $target)
Set the target for this block, and update $this->type accordingly.
Definition: Block.php:1586
bool $isSitewide
Definition: Block.php:85
setId( $blockId)
Set the block ID.
Definition: Block.php:1073
const DB_REPLICA
Definition: defines.php:25
string $mExpiry
Definition: Block.php:40
bool $mHideName
Definition: Block.php:43
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:585
isHardblock( $x=null)
Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range) ...
Definition: Block.php:1107
static getAutoblockExpiry( $timestamp)
Get a timestamp of the expiry for autoblocks.
Definition: Block.php:1218
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:29
getRangeStart()
Get the IP address at the start of the range in Hex form.
Definition: Block.php:1002
getByName()
Get the username of the blocking sysop.
Definition: Block.php:1052
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1487
string $mReason
Definition: Block.php:31
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:61
isExpired()
Has the block expired?
Definition: Block.php:956
$wgAutoblockExpiry
Number of seconds before autoblock entries expire.