MediaWiki  master
Block.php
Go to the documentation of this file.
1 <?php
30 
31 class Block {
33  public $mReason;
34 
36  public $mTimestamp;
37 
39  public $mAuto;
40 
42  public $mExpiry;
43 
45  public $mHideName;
46 
49 
51  private $mId;
52 
54  private $mFromMaster;
55 
57  private $mBlockEmail;
58 
60  private $allowUsertalk;
61 
64 
66  private $target;
67 
69  private $forcedTargetID;
70 
75  private $type;
76 
78  private $blocker;
79 
81  private $isHardblock;
82 
84  private $isAutoblocking;
85 
88 
90  private $isSitewide;
91 
93  private $restrictions;
94 
95  # TYPE constants
96  const TYPE_USER = 1;
97  const TYPE_IP = 2;
98  const TYPE_RANGE = 3;
99  const TYPE_AUTO = 4;
100  const TYPE_ID = 5;
101 
131  function __construct( $options = [] ) {
132  $defaults = [
133  'address' => '',
134  'user' => null,
135  'by' => null,
136  'reason' => '',
137  'timestamp' => '',
138  'auto' => false,
139  'expiry' => '',
140  'anonOnly' => false,
141  'createAccount' => false,
142  'enableAutoblock' => false,
143  'hideName' => false,
144  'blockEmail' => false,
145  'allowUsertalk' => false,
146  'byText' => '',
147  'systemBlock' => null,
148  'sitewide' => true,
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->setReason( $options['reason'] );
169  $this->setTimestamp( wfTimestamp( TS_MW, $options['timestamp'] ) );
170  $this->setExpiry( wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] ) );
171 
172  # Boolean settings
173  $this->mAuto = (bool)$options['auto'];
174  $this->setHideName( (bool)$options['hideName'] );
175  $this->isHardblock( !$options['anonOnly'] );
176  $this->isAutoblocking( (bool)$options['enableAutoblock'] );
177  $this->isSitewide( (bool)$options['sitewide'] );
178  $this->isEmailBlocked( (bool)$options['blockEmail'] );
179  $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
180  $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
181 
182  $this->mFromMaster = false;
183  $this->systemBlockType = $options['systemBlock'];
184  }
185 
192  public static function newFromID( $id ) {
193  $dbr = wfGetDB( DB_REPLICA );
194  $blockQuery = self::getQueryInfo();
195  $res = $dbr->selectRow(
196  $blockQuery['tables'],
197  $blockQuery['fields'],
198  [ 'ipb_id' => $id ],
199  __METHOD__,
200  [],
201  $blockQuery['joins']
202  );
203  if ( $res ) {
204  return self::newFromRow( $res );
205  } else {
206  return null;
207  }
208  }
209 
216  public static function selectFields() {
218 
219  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
220  // If code is using this instead of self::getQueryInfo(), there's a
221  // decent chance it's going to try to directly access
222  // $row->ipb_by or $row->ipb_by_text and we can't give it
223  // useful values here once those aren't being used anymore.
224  throw new BadMethodCallException(
225  'Cannot use ' . __METHOD__
226  . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
227  );
228  }
229 
230  wfDeprecated( __METHOD__, '1.31' );
231  return [
232  'ipb_id',
233  'ipb_address',
234  'ipb_by',
235  'ipb_by_text',
236  'ipb_by_actor' => 'NULL',
237  'ipb_timestamp',
238  'ipb_auto',
239  'ipb_anon_only',
240  'ipb_create_account',
241  'ipb_enable_autoblock',
242  'ipb_expiry',
243  'ipb_deleted',
244  'ipb_block_email',
245  'ipb_allow_usertalk',
246  'ipb_parent_block_id',
247  'ipb_sitewide',
248  ] + CommentStore::getStore()->getFields( 'ipb_reason' );
249  }
250 
260  public static function getQueryInfo() {
261  $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
262  $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
263  return [
264  'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
265  'fields' => [
266  'ipb_id',
267  'ipb_address',
268  'ipb_timestamp',
269  'ipb_auto',
270  'ipb_anon_only',
271  'ipb_create_account',
272  'ipb_enable_autoblock',
273  'ipb_expiry',
274  'ipb_deleted',
275  'ipb_block_email',
276  'ipb_allow_usertalk',
277  'ipb_parent_block_id',
278  'ipb_sitewide',
279  ] + $commentQuery['fields'] + $actorQuery['fields'],
280  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
281  ];
282  }
283 
292  public function equals( Block $block ) {
293  return (
294  (string)$this->target == (string)$block->target
295  && $this->type == $block->type
296  && $this->mAuto == $block->mAuto
297  && $this->isHardblock() == $block->isHardblock()
298  && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
299  && $this->getExpiry() == $block->getExpiry()
300  && $this->isAutoblocking() == $block->isAutoblocking()
301  && $this->getHideName() == $block->getHideName()
302  && $this->isEmailBlocked() == $block->isEmailBlocked()
303  && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
304  && $this->getReason() == $block->getReason()
305  && $this->isSitewide() == $block->isSitewide()
306  // Block::getRestrictions() may perform a database query, so keep it at
307  // the end.
308  && BlockRestriction::equals( $this->getRestrictions(), $block->getRestrictions() )
309  );
310  }
311 
322  protected function newLoad( $vagueTarget = null ) {
323  $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
324 
325  if ( $this->type !== null ) {
326  $conds = [
327  'ipb_address' => [ (string)$this->target ],
328  ];
329  } else {
330  $conds = [ 'ipb_address' => [] ];
331  }
332 
333  # Be aware that the != '' check is explicit, since empty values will be
334  # passed by some callers (T31116)
335  if ( $vagueTarget != '' ) {
336  list( $target, $type ) = self::parseTarget( $vagueTarget );
337  switch ( $type ) {
338  case self::TYPE_USER:
339  # Slightly weird, but who are we to argue?
340  $conds['ipb_address'][] = (string)$target;
341  break;
342 
343  case self::TYPE_IP:
344  $conds['ipb_address'][] = (string)$target;
345  $conds[] = self::getRangeCond( IP::toHex( $target ) );
346  $conds = $db->makeList( $conds, LIST_OR );
347  break;
348 
349  case self::TYPE_RANGE:
350  list( $start, $end ) = IP::parseRange( $target );
351  $conds['ipb_address'][] = (string)$target;
352  $conds[] = self::getRangeCond( $start, $end );
353  $conds = $db->makeList( $conds, LIST_OR );
354  break;
355 
356  default:
357  throw new MWException( "Tried to load block with invalid type" );
358  }
359  }
360 
361  $blockQuery = self::getQueryInfo();
362  $res = $db->select(
363  $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
364  );
365 
366  # This result could contain a block on the user, a block on the IP, and a russian-doll
367  # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
368  $bestRow = null;
369 
370  # Lower will be better
371  $bestBlockScore = 100;
372 
373  foreach ( $res as $row ) {
374  $block = self::newFromRow( $row );
375 
376  # Don't use expired blocks
377  if ( $block->isExpired() ) {
378  continue;
379  }
380 
381  # Don't use anon only blocks on users
382  if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
383  continue;
384  }
385 
386  if ( $block->getType() == self::TYPE_RANGE ) {
387  # This is the number of bits that are allowed to vary in the block, give
388  # or take some floating point errors
389  $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
390  $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
391  $size = log( $end - $start + 1, 2 );
392 
393  # This has the nice property that a /32 block is ranked equally with a
394  # single-IP block, which is exactly what it is...
395  $score = self::TYPE_RANGE - 1 + ( $size / 128 );
396 
397  } else {
398  $score = $block->getType();
399  }
400 
401  if ( $score < $bestBlockScore ) {
402  $bestBlockScore = $score;
403  $bestRow = $row;
404  }
405  }
406 
407  if ( $bestRow !== null ) {
408  $this->initFromRow( $bestRow );
409  return true;
410  } else {
411  return false;
412  }
413  }
414 
421  public static function getRangeCond( $start, $end = null ) {
422  if ( $end === null ) {
423  $end = $start;
424  }
425  # Per T16634, we want to include relevant active rangeblocks; for
426  # rangeblocks, we want to include larger ranges which enclose the given
427  # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
428  # so we can improve performance by filtering on a LIKE clause
429  $chunk = self::getIpFragment( $start );
430  $dbr = wfGetDB( DB_REPLICA );
431  $like = $dbr->buildLike( $chunk, $dbr->anyString() );
432 
433  # Fairly hard to make a malicious SQL statement out of hex characters,
434  # but stranger things have happened...
435  $safeStart = $dbr->addQuotes( $start );
436  $safeEnd = $dbr->addQuotes( $end );
437 
438  return $dbr->makeList(
439  [
440  "ipb_range_start $like",
441  "ipb_range_start <= $safeStart",
442  "ipb_range_end >= $safeEnd",
443  ],
444  LIST_AND
445  );
446  }
447 
454  protected static function getIpFragment( $hex ) {
455  global $wgBlockCIDRLimit;
456  if ( substr( $hex, 0, 3 ) == 'v6-' ) {
457  return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
458  } else {
459  return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
460  }
461  }
462 
468  protected function initFromRow( $row ) {
469  $this->setTarget( $row->ipb_address );
471  $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
472  ) );
473 
474  $this->setTimestamp( wfTimestamp( TS_MW, $row->ipb_timestamp ) );
475  $this->mAuto = $row->ipb_auto;
476  $this->setHideName( $row->ipb_deleted );
477  $this->mId = (int)$row->ipb_id;
478  $this->mParentBlockId = $row->ipb_parent_block_id;
479 
480  // I wish I didn't have to do this
481  $db = wfGetDB( DB_REPLICA );
482  $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry ) );
483  $this->setReason(
485  // Legacy because $row may have come from self::selectFields()
486  ->getCommentLegacy( $db, 'ipb_reason', $row )->text
487  );
488 
489  $this->isHardblock( !$row->ipb_anon_only );
490  $this->isAutoblocking( $row->ipb_enable_autoblock );
491  $this->isSitewide( (bool)$row->ipb_sitewide );
492 
493  $this->isCreateAccountBlocked( $row->ipb_create_account );
494  $this->isEmailBlocked( $row->ipb_block_email );
495  $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk );
496  }
497 
503  public static function newFromRow( $row ) {
504  $block = new Block;
505  $block->initFromRow( $row );
506  return $block;
507  }
508 
515  public function delete() {
516  if ( wfReadOnly() ) {
517  return false;
518  }
519 
520  if ( !$this->getId() ) {
521  throw new MWException( "Block::delete() requires that the mId member be filled\n" );
522  }
523 
524  $dbw = wfGetDB( DB_MASTER );
525 
526  BlockRestriction::deleteByParentBlockId( $this->getId() );
527  $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
528 
529  BlockRestriction::deleteByBlockId( $this->getId() );
530  $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
531 
532  return $dbw->affectedRows() > 0;
533  }
534 
543  public function insert( $dbw = null ) {
544  global $wgBlockDisablesLogin;
545 
546  if ( $this->getSystemBlockType() !== null ) {
547  throw new MWException( 'Cannot insert a system block into the database' );
548  }
549  if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
550  throw new MWException( 'Cannot insert a block without a blocker set' );
551  }
552 
553  wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
554 
555  if ( $dbw === null ) {
556  $dbw = wfGetDB( DB_MASTER );
557  }
558 
559  self::purgeExpired();
560 
561  $row = $this->getDatabaseArray( $dbw );
562 
563  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
564  $affected = $dbw->affectedRows();
565  if ( $affected ) {
566  $this->setId( $dbw->insertId() );
567  if ( $this->restrictions ) {
568  BlockRestriction::insert( $this->restrictions );
569  }
570  }
571 
572  # Don't collide with expired blocks.
573  # Do this after trying to insert to avoid locking.
574  if ( !$affected ) {
575  # T96428: The ipb_address index uses a prefix on a field, so
576  # use a standard SELECT + DELETE to avoid annoying gap locks.
577  $ids = $dbw->selectFieldValues( 'ipblocks',
578  'ipb_id',
579  [
580  'ipb_address' => $row['ipb_address'],
581  'ipb_user' => $row['ipb_user'],
582  'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
583  ],
584  __METHOD__
585  );
586  if ( $ids ) {
587  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
588  BlockRestriction::deleteByBlockId( $ids );
589  $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
590  $affected = $dbw->affectedRows();
591  $this->setId( $dbw->insertId() );
592  if ( $this->restrictions ) {
593  BlockRestriction::insert( $this->restrictions );
594  }
595  }
596  }
597 
598  if ( $affected ) {
599  $auto_ipd_ids = $this->doRetroactiveAutoblock();
600 
601  if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
602  // Change user login token to force them to be logged out.
603  $this->target->setToken();
604  $this->target->saveSettings();
605  }
606 
607  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
608  }
609 
610  return false;
611  }
612 
620  public function update() {
621  wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
622  $dbw = wfGetDB( DB_MASTER );
623 
624  $dbw->startAtomic( __METHOD__ );
625 
626  $result = $dbw->update(
627  'ipblocks',
628  $this->getDatabaseArray( $dbw ),
629  [ 'ipb_id' => $this->getId() ],
630  __METHOD__
631  );
632 
633  // Only update the restrictions if they have been modified.
634  if ( $this->restrictions !== null ) {
635  // An empty array should remove all of the restrictions.
636  if ( empty( $this->restrictions ) ) {
637  $success = BlockRestriction::deleteByBlockId( $this->getId() );
638  } else {
639  $success = BlockRestriction::update( $this->restrictions );
640  }
641  // Update the result. The first false is the result, otherwise, true.
642  $result = $result && $success;
643  }
644 
645  if ( $this->isAutoblocking() ) {
646  // update corresponding autoblock(s) (T50813)
647  $dbw->update(
648  'ipblocks',
649  $this->getAutoblockUpdateArray( $dbw ),
650  [ 'ipb_parent_block_id' => $this->getId() ],
651  __METHOD__
652  );
653 
654  // Only update the restrictions if they have been modified.
655  if ( $this->restrictions !== null ) {
656  BlockRestriction::updateByParentBlockId( $this->getId(), $this->restrictions );
657  }
658  } else {
659  // autoblock no longer required, delete corresponding autoblock(s)
660  BlockRestriction::deleteByParentBlockId( $this->getId() );
661  $dbw->delete(
662  'ipblocks',
663  [ 'ipb_parent_block_id' => $this->getId() ],
664  __METHOD__
665  );
666  }
667 
668  $dbw->endAtomic( __METHOD__ );
669 
670  if ( $result ) {
671  $auto_ipd_ids = $this->doRetroactiveAutoblock();
672  return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
673  }
674 
675  return $result;
676  }
677 
683  protected function getDatabaseArray( IDatabase $dbw ) {
684  $expiry = $dbw->encodeExpiry( $this->getExpiry() );
685 
686  if ( $this->forcedTargetID ) {
687  $uid = $this->forcedTargetID;
688  } else {
689  $uid = $this->target instanceof User ? $this->target->getId() : 0;
690  }
691 
692  $a = [
693  'ipb_address' => (string)$this->target,
694  'ipb_user' => $uid,
695  'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
696  'ipb_auto' => $this->mAuto,
697  'ipb_anon_only' => !$this->isHardblock(),
698  'ipb_create_account' => $this->isCreateAccountBlocked(),
699  'ipb_enable_autoblock' => $this->isAutoblocking(),
700  'ipb_expiry' => $expiry,
701  'ipb_range_start' => $this->getRangeStart(),
702  'ipb_range_end' => $this->getRangeEnd(),
703  'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
704  'ipb_block_email' => $this->isEmailBlocked(),
705  'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
706  'ipb_parent_block_id' => $this->mParentBlockId,
707  'ipb_sitewide' => $this->isSitewide(),
708  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
709  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
710 
711  return $a;
712  }
713 
718  protected function getAutoblockUpdateArray( IDatabase $dbw ) {
719  return [
720  'ipb_create_account' => $this->isCreateAccountBlocked(),
721  'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
722  'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
723  'ipb_sitewide' => $this->isSitewide(),
724  ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
725  + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
726  }
727 
734  protected function doRetroactiveAutoblock() {
735  $blockIds = [];
736  # If autoblock is enabled, autoblock the LAST IP(s) used
737  if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
738  wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
739 
740  $continue = Hooks::run(
741  'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
742 
743  if ( $continue ) {
744  self::defaultRetroactiveAutoblock( $this, $blockIds );
745  }
746  }
747  return $blockIds;
748  }
749 
757  protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
758  global $wgPutIPinRC;
759 
760  // No IPs are in recentchanges table, so nothing to select
761  if ( !$wgPutIPinRC ) {
762  return;
763  }
764 
765  // Autoblocks only apply to TYPE_USER
766  if ( $block->getType() !== self::TYPE_USER ) {
767  return;
768  }
769  $target = $block->getTarget(); // TYPE_USER => always a User object
770 
771  $dbr = wfGetDB( DB_REPLICA );
772  $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
773 
774  $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
775 
776  // Just the last IP used.
777  $options['LIMIT'] = 1;
778 
779  $res = $dbr->select(
780  [ 'recentchanges' ] + $rcQuery['tables'],
781  [ 'rc_ip' ],
782  $rcQuery['conds'],
783  __METHOD__,
784  $options,
785  $rcQuery['joins']
786  );
787 
788  if ( !$res->numRows() ) {
789  # No results, don't autoblock anything
790  wfDebug( "No IP found to retroactively autoblock\n" );
791  } else {
792  foreach ( $res as $row ) {
793  if ( $row->rc_ip ) {
794  $id = $block->doAutoblock( $row->rc_ip );
795  if ( $id ) {
796  $blockIds[] = $id;
797  }
798  }
799  }
800  }
801  }
802 
810  public static function isWhitelistedFromAutoblocks( $ip ) {
811  // Try to get the autoblock_whitelist from the cache, as it's faster
812  // than getting the msg raw and explode()'ing it.
813  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
814  $lines = $cache->getWithSetCallback(
815  $cache->makeKey( 'ip-autoblock', 'whitelist' ),
816  $cache::TTL_DAY,
817  function ( $curValue, &$ttl, array &$setOpts ) {
818  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
819 
820  return explode( "\n",
821  wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
822  }
823  );
824 
825  wfDebug( "Checking the autoblock whitelist..\n" );
826 
827  foreach ( $lines as $line ) {
828  # List items only
829  if ( substr( $line, 0, 1 ) !== '*' ) {
830  continue;
831  }
832 
833  $wlEntry = substr( $line, 1 );
834  $wlEntry = trim( $wlEntry );
835 
836  wfDebug( "Checking $ip against $wlEntry..." );
837 
838  # Is the IP in this range?
839  if ( IP::isInRange( $ip, $wlEntry ) ) {
840  wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
841  return true;
842  } else {
843  wfDebug( " No match\n" );
844  }
845  }
846 
847  return false;
848  }
849 
856  public function doAutoblock( $autoblockIP ) {
857  # If autoblocks are disabled, go away.
858  if ( !$this->isAutoblocking() ) {
859  return false;
860  }
861 
862  # Don't autoblock for system blocks
863  if ( $this->getSystemBlockType() !== null ) {
864  throw new MWException( 'Cannot autoblock from a system block' );
865  }
866 
867  # Check for presence on the autoblock whitelist.
868  if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
869  return false;
870  }
871 
872  // Avoid PHP 7.1 warning of passing $this by reference
873  $block = $this;
874  # Allow hooks to cancel the autoblock.
875  if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
876  wfDebug( "Autoblock aborted by hook.\n" );
877  return false;
878  }
879 
880  # It's okay to autoblock. Go ahead and insert/update the block...
881 
882  # Do not add a *new* block if the IP is already blocked.
883  $ipblock = self::newFromTarget( $autoblockIP );
884  if ( $ipblock ) {
885  # Check if the block is an autoblock and would exceed the user block
886  # if renewed. If so, do nothing, otherwise prolong the block time...
887  if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
888  $this->getExpiry() > self::getAutoblockExpiry( $ipblock->getTimestamp() )
889  ) {
890  # Reset block timestamp to now and its expiry to
891  # $wgAutoblockExpiry in the future
892  $ipblock->updateTimestamp();
893  }
894  return false;
895  }
896 
897  # Make a new block object with the desired properties.
898  $autoblock = new Block;
899  wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
900  $autoblock->setTarget( $autoblockIP );
901  $autoblock->setBlocker( $this->getBlocker() );
902  $autoblock->setReason(
903  wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
904  ->inContentLanguage()->plain()
905  );
906  $timestamp = wfTimestampNow();
907  $autoblock->setTimestamp( $timestamp );
908  $autoblock->mAuto = 1;
909  $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
910  # Continue suppressing the name if needed
911  $autoblock->setHideName( $this->getHideName() );
912  $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
913  $autoblock->mParentBlockId = $this->mId;
914  $autoblock->isSitewide( $this->isSitewide() );
915  $autoblock->setRestrictions( $this->getRestrictions() );
916 
917  if ( $this->getExpiry() == 'infinity' ) {
918  # Original block was indefinite, start an autoblock now
919  $autoblock->setExpiry( self::getAutoblockExpiry( $timestamp ) );
920  } else {
921  # If the user is already blocked with an expiry date, we don't
922  # want to pile on top of that.
923  $autoblock->setExpiry( min( $this->getExpiry(), self::getAutoblockExpiry( $timestamp ) ) );
924  }
925 
926  # Insert the block...
927  $status = $autoblock->insert();
928  return $status
929  ? $status['id']
930  : false;
931  }
932 
937  public function deleteIfExpired() {
938  if ( $this->isExpired() ) {
939  wfDebug( "Block::deleteIfExpired() -- deleting\n" );
940  $this->delete();
941  $retVal = true;
942  } else {
943  wfDebug( "Block::deleteIfExpired() -- not expired\n" );
944  $retVal = false;
945  }
946 
947  return $retVal;
948  }
949 
954  public function isExpired() {
955  $timestamp = wfTimestampNow();
956  wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
957 
958  if ( !$this->getExpiry() ) {
959  return false;
960  } else {
961  return $timestamp > $this->getExpiry();
962  }
963  }
964 
971  public function isValid() {
972  wfDeprecated( __METHOD__, '1.33' );
973  return $this->getTarget() != null;
974  }
975 
979  public function updateTimestamp() {
980  if ( $this->mAuto ) {
981  $this->setTimestamp( wfTimestamp() );
982  $this->setExpiry( self::getAutoblockExpiry( $this->getTimestamp() ) );
983 
984  $dbw = wfGetDB( DB_MASTER );
985  $dbw->update( 'ipblocks',
986  [ /* SET */
987  'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
988  'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
989  ],
990  [ /* WHERE */
991  'ipb_id' => $this->getId(),
992  ],
993  __METHOD__
994  );
995  }
996  }
997 
1003  public function getRangeStart() {
1004  switch ( $this->type ) {
1005  case self::TYPE_USER:
1006  return '';
1007  case self::TYPE_IP:
1008  return IP::toHex( $this->target );
1009  case self::TYPE_RANGE:
1010  list( $start, /*...*/ ) = IP::parseRange( $this->target );
1011  return $start;
1012  default:
1013  throw new MWException( "Block with invalid type" );
1014  }
1015  }
1016 
1022  public function getRangeEnd() {
1023  switch ( $this->type ) {
1024  case self::TYPE_USER:
1025  return '';
1026  case self::TYPE_IP:
1027  return IP::toHex( $this->target );
1028  case self::TYPE_RANGE:
1029  list( /*...*/, $end ) = IP::parseRange( $this->target );
1030  return $end;
1031  default:
1032  throw new MWException( "Block with invalid type" );
1033  }
1034  }
1035 
1041  public function getBy() {
1042  return $this->getBlocker()->getId();
1043  }
1044 
1050  public function getByName() {
1051  return $this->getBlocker()->getName();
1052  }
1053 
1058  public function getId() {
1059  return $this->mId;
1060  }
1061 
1068  private function setId( $blockId ) {
1069  $this->mId = (int)$blockId;
1070 
1071  if ( is_array( $this->restrictions ) ) {
1072  $this->restrictions = BlockRestriction::setBlockId( $blockId, $this->restrictions );
1073  }
1074 
1075  return $this;
1076  }
1077 
1084  public function getReason() {
1085  return $this->mReason;
1086  }
1087 
1094  public function setReason( $reason ) {
1095  $this->mReason = $reason;
1096  }
1097 
1104  public function getHideName() {
1105  return $this->mHideName;
1106  }
1107 
1114  public function setHideName( $hideName ) {
1115  $this->mHideName = $hideName;
1116  }
1117 
1123  public function getSystemBlockType() {
1124  return $this->systemBlockType;
1125  }
1126 
1133  public function fromMaster( $x = null ) {
1134  return wfSetVar( $this->mFromMaster, $x );
1135  }
1136 
1142  public function isHardblock( $x = null ) {
1143  wfSetVar( $this->isHardblock, $x );
1144 
1145  # You can't *not* hardblock a user
1146  return $this->getType() == self::TYPE_USER
1147  ? true
1149  }
1150 
1155  public function isAutoblocking( $x = null ) {
1156  wfSetVar( $this->isAutoblocking, $x );
1157 
1158  # You can't put an autoblock on an IP or range as we don't have any history to
1159  # look over to get more IPs from
1160  return $this->getType() == self::TYPE_USER
1161  ? $this->isAutoblocking
1162  : false;
1163  }
1164 
1174  public function isSitewide( $x = null ) {
1175  return wfSetVar( $this->isSitewide, $x );
1176  }
1177 
1187  public function isCreateAccountBlocked( $x = null ) {
1188  return wfSetVar( $this->blockCreateAccount, $x );
1189  }
1190 
1200  public function isEmailBlocked( $x = null ) {
1201  return wfSetVar( $this->mBlockEmail, $x );
1202  }
1203 
1213  public function isUsertalkEditAllowed( $x = null ) {
1214  return wfSetVar( $this->allowUsertalk, $x );
1215  }
1216 
1227  public function appliesToRight( $right ) {
1228  $config = RequestContext::getMain()->getConfig();
1229  $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1230 
1231  $res = null;
1232  switch ( $right ) {
1233  case 'edit':
1234  // TODO: fix this case to return proper value
1235  $res = true;
1236  break;
1237  case 'createaccount':
1238  $res = $this->isCreateAccountBlocked();
1239  break;
1240  case 'sendemail':
1241  $res = $this->isEmailBlocked();
1242  break;
1243  case 'upload':
1244  // Until T6995 is completed
1245  $res = $this->isSitewide();
1246  break;
1247  case 'read':
1248  $res = false;
1249  break;
1250  case 'purge':
1251  $res = false;
1252  break;
1253  }
1254  if ( !$res && $blockDisablesLogin ) {
1255  // If a block would disable login, then it should
1256  // prevent any right that all users cannot do
1257  $anon = new User;
1258  $res = $anon->isAllowed( $right ) ? $res : true;
1259  }
1260 
1261  return $res;
1262  }
1263 
1273  public function prevents( $action, $x = null ) {
1274  $config = RequestContext::getMain()->getConfig();
1275  $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1276  $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1277 
1278  $res = null;
1279  switch ( $action ) {
1280  case 'edit':
1281  # For now... <evil laugh>
1282  $res = true;
1283  break;
1284  case 'createaccount':
1285  $res = wfSetVar( $this->blockCreateAccount, $x );
1286  break;
1287  case 'sendemail':
1288  $res = wfSetVar( $this->mBlockEmail, $x );
1289  break;
1290  case 'upload':
1291  // Until T6995 is completed
1292  $res = $this->isSitewide();
1293  break;
1294  case 'editownusertalk':
1295  // NOTE: this check is not reliable on partial blocks
1296  // since partially blocked users are always allowed to edit
1297  // their own talk page unless a restriction exists on the
1298  // page or User_talk: namespace
1299  wfSetVar( $this->allowUsertalk, $x === null ? null : !$x );
1300  $res = !$this->isUsertalkEditAllowed();
1301 
1302  // edit own user talk can be disabled by config
1303  if ( !$blockAllowsUTEdit ) {
1304  $res = true;
1305  }
1306  break;
1307  case 'read':
1308  $res = false;
1309  break;
1310  case 'purge':
1311  $res = false;
1312  break;
1313  }
1314  if ( !$res && $blockDisablesLogin ) {
1315  // If a block would disable login, then it should
1316  // prevent any action that all users cannot do
1317  $anon = new User;
1318  $res = $anon->isAllowed( $action ) ? $res : true;
1319  }
1320 
1321  return $res;
1322  }
1323 
1328  public function getRedactedName() {
1329  if ( $this->mAuto ) {
1330  return Html::element(
1331  'span',
1332  [ 'class' => 'mw-autoblockid' ],
1333  wfMessage( 'autoblockid', $this->mId )->text()
1334  );
1335  } else {
1336  return htmlspecialchars( $this->getTarget() );
1337  }
1338  }
1339 
1346  public static function getAutoblockExpiry( $timestamp ) {
1347  global $wgAutoblockExpiry;
1348 
1349  return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1350  }
1351 
1355  public static function purgeExpired() {
1356  if ( wfReadOnly() ) {
1357  return;
1358  }
1359 
1361  wfGetDB( DB_MASTER ),
1362  __METHOD__,
1363  function ( IDatabase $dbw, $fname ) {
1364  $ids = $dbw->selectFieldValues( 'ipblocks',
1365  'ipb_id',
1366  [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1367  $fname
1368  );
1369  if ( $ids ) {
1370  BlockRestriction::deleteByBlockId( $ids );
1371  $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1372  }
1373  }
1374  ) );
1375  }
1376 
1397  public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1398  list( $target, $type ) = self::parseTarget( $specificTarget );
1399  if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1400  return self::newFromID( $target );
1401 
1402  } elseif ( $target === null && $vagueTarget == '' ) {
1403  # We're not going to find anything useful here
1404  # Be aware that the == '' check is explicit, since empty values will be
1405  # passed by some callers (T31116)
1406  return null;
1407 
1408  } elseif ( in_array(
1409  $type,
1410  [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1411  ) {
1412  $block = new Block();
1413  $block->fromMaster( $fromMaster );
1414 
1415  if ( $type !== null ) {
1416  $block->setTarget( $target );
1417  }
1418 
1419  if ( $block->newLoad( $vagueTarget ) ) {
1420  return $block;
1421  }
1422  }
1423  return null;
1424  }
1425 
1436  public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1437  if ( $ipChain === [] ) {
1438  return [];
1439  }
1440 
1441  $conds = [];
1442  $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1443  foreach ( array_unique( $ipChain ) as $ipaddr ) {
1444  # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1445  # necessarily trust the header given to us, make sure that we are only
1446  # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1447  # Do not treat private IP spaces as special as it may be desirable for wikis
1448  # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1449  if ( !IP::isValid( $ipaddr ) ) {
1450  continue;
1451  }
1452  # Don't check trusted IPs (includes local squids which will be in every request)
1453  if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1454  continue;
1455  }
1456  # Check both the original IP (to check against single blocks), as well as build
1457  # the clause to check for rangeblocks for the given IP.
1458  $conds['ipb_address'][] = $ipaddr;
1459  $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1460  }
1461 
1462  if ( $conds === [] ) {
1463  return [];
1464  }
1465 
1466  if ( $fromMaster ) {
1467  $db = wfGetDB( DB_MASTER );
1468  } else {
1469  $db = wfGetDB( DB_REPLICA );
1470  }
1471  $conds = $db->makeList( $conds, LIST_OR );
1472  if ( !$isAnon ) {
1473  $conds = [ $conds, 'ipb_anon_only' => 0 ];
1474  }
1475  $blockQuery = self::getQueryInfo();
1476  $rows = $db->select(
1477  $blockQuery['tables'],
1478  array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1479  $conds,
1480  __METHOD__,
1481  [],
1482  $blockQuery['joins']
1483  );
1484 
1485  $blocks = [];
1486  foreach ( $rows as $row ) {
1487  $block = self::newFromRow( $row );
1488  if ( !$block->isExpired() ) {
1489  $blocks[] = $block;
1490  }
1491  }
1492 
1493  return $blocks;
1494  }
1495 
1517  public static function chooseBlock( array $blocks, array $ipChain ) {
1518  if ( $blocks === [] ) {
1519  return null;
1520  } elseif ( count( $blocks ) == 1 ) {
1521  return $blocks[0];
1522  }
1523 
1524  // Sort hard blocks before soft ones and secondarily sort blocks
1525  // that disable account creation before those that don't.
1526  usort( $blocks, function ( Block $a, Block $b ) {
1527  $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1528  $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1529  return strcmp( $bWeight, $aWeight ); // highest weight first
1530  } );
1531 
1532  $blocksListExact = [
1533  'hard' => false,
1534  'disable_create' => false,
1535  'other' => false,
1536  'auto' => false
1537  ];
1538  $blocksListRange = [
1539  'hard' => false,
1540  'disable_create' => false,
1541  'other' => false,
1542  'auto' => false
1543  ];
1544  $ipChain = array_reverse( $ipChain );
1545 
1547  foreach ( $blocks as $block ) {
1548  // Stop searching if we have already have a "better" block. This
1549  // is why the order of the blocks matters
1550  if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1551  break;
1552  } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1553  break;
1554  }
1555 
1556  foreach ( $ipChain as $checkip ) {
1557  $checkipHex = IP::toHex( $checkip );
1558  if ( (string)$block->getTarget() === $checkip ) {
1559  if ( $block->isHardblock() ) {
1560  $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1561  } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1562  $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1563  } elseif ( $block->mAuto ) {
1564  $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1565  } else {
1566  $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1567  }
1568  // We found closest exact match in the ip list, so go to the next Block
1569  break;
1570  } elseif ( array_filter( $blocksListExact ) == []
1571  && $block->getRangeStart() <= $checkipHex
1572  && $block->getRangeEnd() >= $checkipHex
1573  ) {
1574  if ( $block->isHardblock() ) {
1575  $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1576  } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1577  $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1578  } elseif ( $block->mAuto ) {
1579  $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1580  } else {
1581  $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1582  }
1583  break;
1584  }
1585  }
1586  }
1587 
1588  if ( array_filter( $blocksListExact ) == [] ) {
1589  $blocksList = &$blocksListRange;
1590  } else {
1591  $blocksList = &$blocksListExact;
1592  }
1593 
1594  $chosenBlock = null;
1595  if ( $blocksList['hard'] ) {
1596  $chosenBlock = $blocksList['hard'];
1597  } elseif ( $blocksList['disable_create'] ) {
1598  $chosenBlock = $blocksList['disable_create'];
1599  } elseif ( $blocksList['other'] ) {
1600  $chosenBlock = $blocksList['other'];
1601  } elseif ( $blocksList['auto'] ) {
1602  $chosenBlock = $blocksList['auto'];
1603  } else {
1604  throw new MWException( "Proxy block found, but couldn't be classified." );
1605  }
1606 
1607  return $chosenBlock;
1608  }
1609 
1619  public static function parseTarget( $target ) {
1620  # We may have been through this before
1621  if ( $target instanceof User ) {
1622  if ( IP::isValid( $target->getName() ) ) {
1623  return [ $target, self::TYPE_IP ];
1624  } else {
1625  return [ $target, self::TYPE_USER ];
1626  }
1627  } elseif ( $target === null ) {
1628  return [ null, null ];
1629  }
1630 
1631  $target = trim( $target );
1632 
1633  if ( IP::isValid( $target ) ) {
1634  # We can still create a User if it's an IP address, but we need to turn
1635  # off validation checking (which would exclude IP addresses)
1636  return [
1638  self::TYPE_IP
1639  ];
1640 
1641  } elseif ( IP::isValidRange( $target ) ) {
1642  # Can't create a User from an IP range
1643  return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1644  }
1645 
1646  # Consider the possibility that this is not a username at all
1647  # but actually an old subpage (T31797)
1648  if ( strpos( $target, '/' ) !== false ) {
1649  # An old subpage, drill down to the user behind it
1650  $target = explode( '/', $target )[0];
1651  }
1652 
1653  $userObj = User::newFromName( $target );
1654  if ( $userObj instanceof User ) {
1655  # Note that since numbers are valid usernames, a $target of "12345" will be
1656  # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1657  # since hash characters are not valid in usernames or titles generally.
1658  return [ $userObj, self::TYPE_USER ];
1659 
1660  } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1661  # Autoblock reference in the form "#12345"
1662  return [ substr( $target, 1 ), self::TYPE_AUTO ];
1663 
1664  } else {
1665  # WTF?
1666  return [ null, null ];
1667  }
1668  }
1669 
1676  public function getType() {
1677  return $this->mAuto
1678  ? self::TYPE_AUTO
1679  : $this->type;
1680  }
1681 
1689  public function getTargetAndType() {
1690  return [ $this->getTarget(), $this->getType() ];
1691  }
1692 
1699  public function getTarget() {
1700  return $this->target;
1701  }
1702 
1709  public function getExpiry() {
1710  return $this->mExpiry;
1711  }
1712 
1719  public function setExpiry( $expiry ) {
1720  $this->mExpiry = $expiry;
1721  }
1722 
1729  public function getTimestamp() {
1730  return $this->mTimestamp;
1731  }
1732 
1739  public function setTimestamp( $timestamp ) {
1740  $this->mTimestamp = $timestamp;
1741  }
1742 
1747  public function setTarget( $target ) {
1748  list( $this->target, $this->type ) = self::parseTarget( $target );
1749  }
1750 
1755  public function getBlocker() {
1756  return $this->blocker;
1757  }
1758 
1763  public function setBlocker( $user ) {
1764  if ( is_string( $user ) ) {
1765  $user = User::newFromName( $user, false );
1766  }
1767 
1768  if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1769  throw new InvalidArgumentException(
1770  'Blocker must be a local user or a name that cannot be a local user'
1771  );
1772  }
1773 
1774  $this->blocker = $user;
1775  }
1776 
1785  public function setCookie( WebResponse $response ) {
1786  // Calculate the default expiry time.
1787  $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1788 
1789  // Use the Block's expiry time only if it's less than the default.
1790  $expiryTime = $this->getExpiry();
1791  if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1792  $expiryTime = $maxExpiryTime;
1793  }
1794 
1795  // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1796  $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1797  $cookieOptions = [ 'httpOnly' => false ];
1798  $cookieValue = $this->getCookieValue();
1799  $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1800  }
1801 
1809  public static function clearCookie( WebResponse $response ) {
1810  $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1811  }
1812 
1822  public function getCookieValue() {
1823  $config = RequestContext::getMain()->getConfig();
1824  $id = $this->getId();
1825  $secretKey = $config->get( 'SecretKey' );
1826  if ( !$secretKey ) {
1827  // If there's no secret key, don't append a HMAC.
1828  return $id;
1829  }
1830  $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1831  $cookieValue = $id . '!' . $hmac;
1832  return $cookieValue;
1833  }
1834 
1845  public static function getIdFromCookieValue( $cookieValue ) {
1846  // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1847  $bangPos = strpos( $cookieValue, '!' );
1848  $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1849  // Get the site-wide secret key.
1850  $config = RequestContext::getMain()->getConfig();
1851  $secretKey = $config->get( 'SecretKey' );
1852  if ( !$secretKey ) {
1853  // If there's no secret key, just use the ID as given.
1854  return $id;
1855  }
1856  $storedHmac = substr( $cookieValue, $bangPos + 1 );
1857  $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1858  if ( $calculatedHmac === $storedHmac ) {
1859  return $id;
1860  } else {
1861  return null;
1862  }
1863  }
1864 
1873  $params = $this->getBlockErrorParams( $context );
1874 
1875  $msg = 'blockedtext';
1876  if ( $this->getSystemBlockType() !== null ) {
1877  $msg = 'systemblockedtext';
1878  } elseif ( $this->mAuto ) {
1879  $msg = 'autoblockedtext';
1880  } elseif ( !$this->isSitewide() ) {
1881  $msg = 'blockedtext-partial';
1882  }
1883 
1884  array_unshift( $params, $msg );
1885 
1886  return $params;
1887  }
1888 
1897  $blocker = $this->getBlocker();
1898  if ( $blocker instanceof User ) { // local user
1899  $blockerUserpage = $blocker->getUserPage();
1900  $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1901  } else { // foreign user
1902  $link = $blocker;
1903  }
1904 
1905  $reason = $this->getReason();
1906  if ( $reason == '' ) {
1907  $reason = $context->msg( 'blockednoreason' )->text();
1908  }
1909 
1910  /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1911  * This could be a username, an IP range, or a single IP. */
1912  $intended = $this->getTarget();
1914  $lang = $context->getLanguage();
1915 
1916  return [
1917  $link,
1918  $reason,
1919  $context->getRequest()->getIP(),
1920  $this->getByName(),
1921  $systemBlockType ?? $this->getId(),
1922  $lang->formatExpiry( $this->getExpiry() ),
1923  (string)$intended,
1924  $lang->userTimeAndDate( $this->getTimestamp(), $context->getUser() ),
1925  ];
1926  }
1927 
1937  public function getRestrictions() {
1938  if ( $this->restrictions === null ) {
1939  // If the block id has not been set, then do not attempt to load the
1940  // restrictions.
1941  if ( !$this->mId ) {
1942  return [];
1943  }
1944  $this->restrictions = BlockRestriction::loadByBlockId( $this->mId );
1945  }
1946 
1947  return $this->restrictions;
1948  }
1949 
1957  public function setRestrictions( array $restrictions ) {
1958  $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1959  return $restriction instanceof Restriction;
1960  } );
1961 
1962  return $this;
1963  }
1964 
1991  public function appliesToUsertalk( Title $usertalk = null ) {
1992  if ( !$usertalk ) {
1993  if ( $this->target instanceof User ) {
1994  $usertalk = $this->target->getTalkPage();
1995  } else {
1996  throw new InvalidArgumentException(
1997  '$usertalk must be provided if block target is not a user/IP'
1998  );
1999  }
2000  }
2001 
2002  if ( $usertalk->getNamespace() !== NS_USER_TALK ) {
2003  throw new InvalidArgumentException(
2004  '$usertalk must be a user talk page'
2005  );
2006  }
2007 
2008  if ( !$this->isSitewide() ) {
2009  if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
2010  return true;
2011  }
2012  if ( !$this->appliesToNamespace( NS_USER_TALK ) ) {
2013  return false;
2014  }
2015  }
2016 
2017  // This is a type of block which uses the ipb_allow_usertalk
2018  // flag. The flag can still be overridden by global configs.
2019  $config = RequestContext::getMain()->getConfig();
2020  if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
2021  return true;
2022  }
2023  return !$this->isUsertalkEditAllowed();
2024  }
2025 
2037  public function appliesToTitle( Title $title ) {
2038  if ( $this->isSitewide() ) {
2039  return true;
2040  }
2041 
2042  $restrictions = $this->getRestrictions();
2043  foreach ( $restrictions as $restriction ) {
2044  if ( $restriction->matches( $title ) ) {
2045  return true;
2046  }
2047  }
2048 
2049  return false;
2050  }
2051 
2060  public function appliesToNamespace( $ns ) {
2061  if ( $this->isSitewide() ) {
2062  return true;
2063  }
2064 
2065  // Blocks do not apply to virtual namespaces.
2066  if ( $ns < 0 ) {
2067  return false;
2068  }
2069 
2070  $restriction = $this->findRestriction( NamespaceRestriction::TYPE, $ns );
2071 
2072  return (bool)$restriction;
2073  }
2074 
2088  public function appliesToPage( $pageId ) {
2089  if ( $this->isSitewide() ) {
2090  return true;
2091  }
2092 
2093  // If the pageId is not over zero, the block cannot apply to it.
2094  if ( $pageId <= 0 ) {
2095  return false;
2096  }
2097 
2098  $restriction = $this->findRestriction( PageRestriction::TYPE, $pageId );
2099 
2100  return (bool)$restriction;
2101  }
2102 
2110  private function findRestriction( $type, $value ) {
2111  $restrictions = $this->getRestrictions();
2112  foreach ( $restrictions as $restriction ) {
2113  if ( $restriction->getType() !== $type ) {
2114  continue;
2115  }
2116 
2117  if ( $restriction->getValue() === $value ) {
2118  return $restriction;
2119  }
2120  }
2121 
2122  return null;
2123  }
2124 
2132  public function shouldTrackWithCookie( $isIpUser ) {
2133  $config = RequestContext::getMain()->getConfig();
2134  switch ( $this->getType() ) {
2135  case self::TYPE_IP:
2136  case self::TYPE_RANGE:
2137  return $isIpUser && $config->get( 'CookieSetOnIpBlock' );
2138  case self::TYPE_USER:
2139  return !$isIpUser && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
2140  default:
2141  return false;
2142  }
2143  }
2144 
2151  public function appliesToPasswordReset() {
2152  switch ( $this->getSystemBlockType() ) {
2153  case null:
2154  case 'global-block':
2155  return $this->isCreateAccountBlocked();
2156  case 'proxy':
2157  return true;
2158  case 'dnsbl':
2159  case 'wgSoftBlockRanges':
2160  return false;
2161  default:
2162  return true;
2163  }
2164  }
2165 
2166 }
getBy()
Get the user id of the blocking sysop.
Definition: Block.php:1041
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:503
bool $isHardblock
Definition: Block.php:81
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2633
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
static toHex( $ip)
Return a zero-padded upper case hexadecimal representation of an IP address.
Definition: IP.php:417
string $mTimestamp
Definition: Block.php:36
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:232
static newFromID( $id)
Load a block from the block id.
Definition: Block.php:192
either a plain
Definition: hooks.txt:2043
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:757
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:1517
findRestriction( $type, $value)
Find Restriction by type and value.
Definition: Block.php:2110
const TYPE_RANGE
Definition: Block.php:98
static parseRange( $range)
Given a string range in a number of formats, return the start and end of the range in hexadecimal...
Definition: IP.php:513
$success
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
prevents( $action, $x=null)
Get/set whether the Block prevents a given action.
Definition: Block.php:1273
bool $mFromMaster
Definition: Block.php:54
getSystemBlockType()
Get the system block type, if any.
Definition: Block.php:1123
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getTimestamp()
Get the timestamp indicating when the block was created.
Definition: Block.php:1729
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:1676
isCreateAccountBlocked( $x=null)
Get or set the flag indicating whether this block blocks the target from creating an account...
Definition: Block.php:1187
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:1397
int $mParentBlockId
Definition: Block.php:48
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
equals(Block $block)
Check if two blocks are effectively equal.
Definition: Block.php:292
getCookieValue()
Get the BlockID cookie&#39;s value for this block.
Definition: Block.php:1822
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:454
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
$value
getDatabaseArray(IDatabase $dbw)
Get an array suitable for passing to $dbw->insert() or $dbw->update()
Definition: Block.php:683
const SCHEMA_COMPAT_READ_NEW
Definition: Defines.php:287
static clearCookie(WebResponse $response)
Unset the &#39;BlockID&#39; cookie.
Definition: Block.php:1809
const TYPE_IP
Definition: Block.php:97
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
insert( $dbw=null)
Insert a block into the block table.
Definition: Block.php:543
setReason( $reason)
Set the reason for creating the block.
Definition: Block.php:1094
getId()
Get the block ID.
Definition: Block.php:1058
this hook is for auditing only $response
Definition: hooks.txt:780
newLoad( $vagueTarget=null)
Load a block from the database which affects the already-set $this->target: 1) A block directly on th...
Definition: Block.php:322
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition: Block.php:1619
initFromRow( $row)
Given a database row from the ipblocks table, initialize member variables.
Definition: Block.php:468
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
isEmailBlocked( $x=null)
Get or set the flag indicating whether this block blocks the target from sending emails.
Definition: Block.php:1200
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:2443
update()
Update a block in the DB with new parameters.
Definition: Block.php:620
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:1980
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:1785
getRangeEnd()
Get the IP address at the end of the range in Hex form.
Definition: Block.php:1022
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3050
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:48
bool $allowUsertalk
Definition: Block.php:60
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:1982
deleteIfExpired()
Check if a block has expired.
Definition: Block.php:937
__construct( $options=[])
Create a new block with specified parameters on a user, IP or IP range.
Definition: Block.php:131
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1263
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()
Get the block expiry time.
Definition: Block.php:1709
wfReadOnly()
Check whether the wiki is in read-only mode.
Restriction [] $restrictions
Definition: Block.php:93
static newMigration()
Static constructor.
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
setTimestamp( $timestamp)
Set the timestamp indicating when the block was created.
Definition: Block.php:1739
static getMain()
Get the RequestContext object associated with the main request.
const LIST_AND
Definition: Defines.php:43
int $type
Block::TYPE_ constant.
Definition: Block.php:75
appliesToTitle(Title $title)
Checks if a block applies to a particular title.
Definition: Block.php:2037
setRestrictions(array $restrictions)
Set Restrictions.
Definition: Block.php:1957
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
Definition: IP.php:152
isAutoblocking( $x=null)
Definition: Block.php:1155
getTargetAndType()
Get the target and target type for this particular Block.
Definition: Block.php:1689
getRedactedName()
Get the block name, but with autoblocked IPs hidden as per standard privacy policy.
Definition: Block.php:1328
bool $isAutoblocking
Definition: Block.php:84
$res
Definition: database.txt:21
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
$wgBlockDisablesLogin
If true, blocked users will not be allowed to login.
static isValid( $ip)
Validate an IP address.
Definition: IP.php:111
doAutoblock( $autoblockIP)
Autoblocks the given IP, referring to this Block.
Definition: Block.php:856
bool $mBlockEmail
Definition: Block.php:57
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
$wgPutIPinRC
Log IP addresses in the recentchanges table; can be accessed only by extensions (e.g.
$cache
Definition: mcc.php:33
$params
int $mId
Definition: Block.php:51
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
Definition: User.php:1044
isSitewide( $x=null)
Indicates that the block is a sitewide block.
Definition: Block.php:1174
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:925
static purgeExpired()
Purge expired blocks from the ipblocks table.
Definition: Block.php:1355
static getRangeCond( $start, $end=null)
Get a set of SQL conditions which will select rangeblocks encompassing a given range.
Definition: Block.php:421
const TYPE_ID
Definition: Block.php:100
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new block object...
Definition: Block.php:260
const TYPE_AUTO
Definition: Block.php:99
appliesToUsertalk(Title $usertalk=null)
Determine whether the block allows the user to edit their own user talk page.
Definition: Block.php:1991
appliesToRight( $right)
Determine whether the Block prevents a given right.
Definition: Block.php:1227
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:810
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
bool $blockCreateAccount
Definition: Block.php:63
const LIST_OR
Definition: Defines.php:46
User string $target
Definition: Block.php:66
doRetroactiveAutoblock()
Retroactively autoblocks the last IP used by the user (if it is a user) blocked by this Block...
Definition: Block.php:734
$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:1436
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the &#39;BlockID&#39; cookie.
Definition: Block.php:1845
appliesToNamespace( $ns)
Checks if a block applies to a particular namespace.
Definition: Block.php:2060
bool $mAuto
Definition: Block.php:39
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
int $forcedTargetID
Hack for foreign blocking (CentralAuth)
Definition: Block.php:69
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:611
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:979
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:678
$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:1755
getId()
Get the user&#39;s ID.
Definition: User.php:2416
getPermissionsError(IContextSource $context)
Get the key and parameters for the corresponding error message.
Definition: Block.php:1872
static selectFields()
Return the list of ipblocks fields that should be selected to create a new block. ...
Definition: Block.php:216
setBlocker( $user)
Set the user who implemented (or will implement) this block.
Definition: Block.php:1763
User $blocker
Definition: Block.php:78
string null $systemBlockType
Definition: Block.php:87
getBlockErrorParams(IContextSource $context)
Get block information used in different block error messages.
Definition: Block.php:1896
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:1699
fromMaster( $x=null)
Get/set a flag determining whether the master is used for reads.
Definition: Block.php:1133
getUserPage()
Get this user&#39;s personal page title.
Definition: User.php:4538
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and insert
Definition: hooks.txt:2061
getRestrictions()
Get Restrictions.
Definition: Block.php:1937
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:2633
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:28
const TYPE_USER
Definition: Block.php:96
getAutoblockUpdateArray(IDatabase $dbw)
Definition: Block.php:718
setExpiry( $expiry)
Set the block expiry time.
Definition: Block.php:1719
setTarget( $target)
Set the target for this block, and update $this->type accordingly.
Definition: Block.php:1747
bool $isSitewide
Definition: Block.php:90
setId( $blockId)
Set the block ID.
Definition: Block.php:1068
const DB_REPLICA
Definition: defines.php:25
string $mExpiry
Definition: Block.php:42
bool $mHideName
Definition: Block.php:45
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:587
isHardblock( $x=null)
Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range) ...
Definition: Block.php:1142
static getAutoblockExpiry( $timestamp)
Get a timestamp of the expiry for autoblocks.
Definition: Block.php:1346
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
appliesToPasswordReset()
Check if the block prevents a user from resetting their password.
Definition: Block.php:2151
const NS_USER_TALK
Definition: Defines.php:67
shouldTrackWithCookie( $isIpUser)
Check if the block should be tracked with a cookie.
Definition: Block.php:2132
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 ...
setHideName( $hideName)
Set whether ths block hides the target&#39;s username.
Definition: Block.php:1114
Definition: Block.php:31
getRangeStart()
Get the IP address at the start of the range in Hex form.
Definition: Block.php:1003
isUsertalkEditAllowed( $x=null)
Get or set the flag indicating whether this block blocks the target from editing their own user talk ...
Definition: Block.php:1213
getByName()
Get the username of the blocking sysop.
Definition: Block.php:1050
getReason()
Get the reason given for creating the block.
Definition: Block.php:1084
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
appliesToPage( $pageId)
Checks if a block applies to a particular page.
Definition: Block.php:2088
string $mReason
Definition: Block.php:33
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
getHideName()
Get whether the block hides the target&#39;s username.
Definition: Block.php:1104
isExpired()
Has the block expired?
Definition: Block.php:954
$wgAutoblockExpiry
Number of seconds before autoblock entries expire.