Block.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. <?php
  2. /**
  3. * Blocks and bans object
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use Wikimedia\Rdbms\Database;
  23. use Wikimedia\Rdbms\IDatabase;
  24. use MediaWiki\MediaWikiServices;
  25. class Block {
  26. /** @var string */
  27. public $mReason;
  28. /** @var string */
  29. public $mTimestamp;
  30. /** @var bool */
  31. public $mAuto;
  32. /** @var string */
  33. public $mExpiry;
  34. /** @var bool */
  35. public $mHideName;
  36. /** @var int */
  37. public $mParentBlockId;
  38. /** @var int */
  39. private $mId;
  40. /** @var bool */
  41. private $mFromMaster;
  42. /** @var bool */
  43. private $mBlockEmail;
  44. /** @var bool */
  45. private $mDisableUsertalk;
  46. /** @var bool */
  47. private $mCreateAccount;
  48. /** @var User|string */
  49. private $target;
  50. /** @var int Hack for foreign blocking (CentralAuth) */
  51. private $forcedTargetID;
  52. /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
  53. private $type;
  54. /** @var User */
  55. private $blocker;
  56. /** @var bool */
  57. private $isHardblock;
  58. /** @var bool */
  59. private $isAutoblocking;
  60. /** @var string|null */
  61. private $systemBlockType;
  62. # TYPE constants
  63. const TYPE_USER = 1;
  64. const TYPE_IP = 2;
  65. const TYPE_RANGE = 3;
  66. const TYPE_AUTO = 4;
  67. const TYPE_ID = 5;
  68. /**
  69. * Create a new block with specified parameters on a user, IP or IP range.
  70. *
  71. * @param array $options Parameters of the block:
  72. * address string|User Target user name, User object, IP address or IP range
  73. * user int Override target user ID (for foreign users)
  74. * by int User ID of the blocker
  75. * reason string Reason of the block
  76. * timestamp string The time at which the block comes into effect
  77. * auto bool Is this an automatic block?
  78. * expiry string Timestamp of expiration of the block or 'infinity'
  79. * anonOnly bool Only disallow anonymous actions
  80. * createAccount bool Disallow creation of new accounts
  81. * enableAutoblock bool Enable automatic blocking
  82. * hideName bool Hide the target user name
  83. * blockEmail bool Disallow sending emails
  84. * allowUsertalk bool Allow the target to edit its own talk page
  85. * byText string Username of the blocker (for foreign users)
  86. * systemBlock string Indicate that this block is automatically
  87. * created by MediaWiki rather than being stored
  88. * in the database. Value is a string to return
  89. * from self::getSystemBlockType().
  90. *
  91. * @since 1.26 accepts $options array instead of individual parameters; order
  92. * of parameters above reflects the original order
  93. */
  94. function __construct( $options = [] ) {
  95. $defaults = [
  96. 'address' => '',
  97. 'user' => null,
  98. 'by' => null,
  99. 'reason' => '',
  100. 'timestamp' => '',
  101. 'auto' => false,
  102. 'expiry' => '',
  103. 'anonOnly' => false,
  104. 'createAccount' => false,
  105. 'enableAutoblock' => false,
  106. 'hideName' => false,
  107. 'blockEmail' => false,
  108. 'allowUsertalk' => false,
  109. 'byText' => '',
  110. 'systemBlock' => null,
  111. ];
  112. if ( func_num_args() > 1 || !is_array( $options ) ) {
  113. $options = array_combine(
  114. array_slice( array_keys( $defaults ), 0, func_num_args() ),
  115. func_get_args()
  116. );
  117. wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
  118. }
  119. $options += $defaults;
  120. $this->setTarget( $options['address'] );
  121. if ( $this->target instanceof User && $options['user'] ) {
  122. # Needed for foreign users
  123. $this->forcedTargetID = $options['user'];
  124. }
  125. if ( $options['by'] ) {
  126. # Local user
  127. $this->setBlocker( User::newFromId( $options['by'] ) );
  128. } else {
  129. # Foreign user
  130. $this->setBlocker( $options['byText'] );
  131. }
  132. $this->mReason = $options['reason'];
  133. $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
  134. $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
  135. # Boolean settings
  136. $this->mAuto = (bool)$options['auto'];
  137. $this->mHideName = (bool)$options['hideName'];
  138. $this->isHardblock( !$options['anonOnly'] );
  139. $this->isAutoblocking( (bool)$options['enableAutoblock'] );
  140. # Prevention measures
  141. $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
  142. $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
  143. $this->prevents( 'createaccount', (bool)$options['createAccount'] );
  144. $this->mFromMaster = false;
  145. $this->systemBlockType = $options['systemBlock'];
  146. }
  147. /**
  148. * Load a blocked user from their block id.
  149. *
  150. * @param int $id Block id to search for
  151. * @return Block|null
  152. */
  153. public static function newFromID( $id ) {
  154. $dbr = wfGetDB( DB_REPLICA );
  155. $res = $dbr->selectRow(
  156. 'ipblocks',
  157. self::selectFields(),
  158. [ 'ipb_id' => $id ],
  159. __METHOD__
  160. );
  161. if ( $res ) {
  162. return self::newFromRow( $res );
  163. } else {
  164. return null;
  165. }
  166. }
  167. /**
  168. * Return the list of ipblocks fields that should be selected to create
  169. * a new block.
  170. * @todo Deprecate this in favor of a method that returns tables and joins
  171. * as well, and use CommentStore::getJoin().
  172. * @return array
  173. */
  174. public static function selectFields() {
  175. return [
  176. 'ipb_id',
  177. 'ipb_address',
  178. 'ipb_by',
  179. 'ipb_by_text',
  180. 'ipb_timestamp',
  181. 'ipb_auto',
  182. 'ipb_anon_only',
  183. 'ipb_create_account',
  184. 'ipb_enable_autoblock',
  185. 'ipb_expiry',
  186. 'ipb_deleted',
  187. 'ipb_block_email',
  188. 'ipb_allow_usertalk',
  189. 'ipb_parent_block_id',
  190. ] + CommentStore::newKey( 'ipb_reason' )->getFields();
  191. }
  192. /**
  193. * Check if two blocks are effectively equal. Doesn't check irrelevant things like
  194. * the blocking user or the block timestamp, only things which affect the blocked user
  195. *
  196. * @param Block $block
  197. *
  198. * @return bool
  199. */
  200. public function equals( Block $block ) {
  201. return (
  202. (string)$this->target == (string)$block->target
  203. && $this->type == $block->type
  204. && $this->mAuto == $block->mAuto
  205. && $this->isHardblock() == $block->isHardblock()
  206. && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
  207. && $this->mExpiry == $block->mExpiry
  208. && $this->isAutoblocking() == $block->isAutoblocking()
  209. && $this->mHideName == $block->mHideName
  210. && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
  211. && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
  212. && $this->mReason == $block->mReason
  213. );
  214. }
  215. /**
  216. * Load a block from the database which affects the already-set $this->target:
  217. * 1) A block directly on the given user or IP
  218. * 2) A rangeblock encompassing the given IP (smallest first)
  219. * 3) An autoblock on the given IP
  220. * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
  221. * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
  222. * @throws MWException
  223. * @return bool Whether a relevant block was found
  224. */
  225. protected function newLoad( $vagueTarget = null ) {
  226. $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
  227. if ( $this->type !== null ) {
  228. $conds = [
  229. 'ipb_address' => [ (string)$this->target ],
  230. ];
  231. } else {
  232. $conds = [ 'ipb_address' => [] ];
  233. }
  234. # Be aware that the != '' check is explicit, since empty values will be
  235. # passed by some callers (T31116)
  236. if ( $vagueTarget != '' ) {
  237. list( $target, $type ) = self::parseTarget( $vagueTarget );
  238. switch ( $type ) {
  239. case self::TYPE_USER:
  240. # Slightly weird, but who are we to argue?
  241. $conds['ipb_address'][] = (string)$target;
  242. break;
  243. case self::TYPE_IP:
  244. $conds['ipb_address'][] = (string)$target;
  245. $conds[] = self::getRangeCond( IP::toHex( $target ) );
  246. $conds = $db->makeList( $conds, LIST_OR );
  247. break;
  248. case self::TYPE_RANGE:
  249. list( $start, $end ) = IP::parseRange( $target );
  250. $conds['ipb_address'][] = (string)$target;
  251. $conds[] = self::getRangeCond( $start, $end );
  252. $conds = $db->makeList( $conds, LIST_OR );
  253. break;
  254. default:
  255. throw new MWException( "Tried to load block with invalid type" );
  256. }
  257. }
  258. $res = $db->select( 'ipblocks', self::selectFields(), $conds, __METHOD__ );
  259. # This result could contain a block on the user, a block on the IP, and a russian-doll
  260. # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
  261. $bestRow = null;
  262. # Lower will be better
  263. $bestBlockScore = 100;
  264. # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
  265. $bestBlockPreventsEdit = null;
  266. foreach ( $res as $row ) {
  267. $block = self::newFromRow( $row );
  268. # Don't use expired blocks
  269. if ( $block->isExpired() ) {
  270. continue;
  271. }
  272. # Don't use anon only blocks on users
  273. if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
  274. continue;
  275. }
  276. if ( $block->getType() == self::TYPE_RANGE ) {
  277. # This is the number of bits that are allowed to vary in the block, give
  278. # or take some floating point errors
  279. $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
  280. $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
  281. $size = log( $end - $start + 1, 2 );
  282. # This has the nice property that a /32 block is ranked equally with a
  283. # single-IP block, which is exactly what it is...
  284. $score = self::TYPE_RANGE - 1 + ( $size / 128 );
  285. } else {
  286. $score = $block->getType();
  287. }
  288. if ( $score < $bestBlockScore ) {
  289. $bestBlockScore = $score;
  290. $bestRow = $row;
  291. $bestBlockPreventsEdit = $block->prevents( 'edit' );
  292. }
  293. }
  294. if ( $bestRow !== null ) {
  295. $this->initFromRow( $bestRow );
  296. $this->prevents( 'edit', $bestBlockPreventsEdit );
  297. return true;
  298. } else {
  299. return false;
  300. }
  301. }
  302. /**
  303. * Get a set of SQL conditions which will select rangeblocks encompassing a given range
  304. * @param string $start Hexadecimal IP representation
  305. * @param string $end Hexadecimal IP representation, or null to use $start = $end
  306. * @return string
  307. */
  308. public static function getRangeCond( $start, $end = null ) {
  309. if ( $end === null ) {
  310. $end = $start;
  311. }
  312. # Per T16634, we want to include relevant active rangeblocks; for
  313. # rangeblocks, we want to include larger ranges which enclose the given
  314. # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
  315. # so we can improve performance by filtering on a LIKE clause
  316. $chunk = self::getIpFragment( $start );
  317. $dbr = wfGetDB( DB_REPLICA );
  318. $like = $dbr->buildLike( $chunk, $dbr->anyString() );
  319. # Fairly hard to make a malicious SQL statement out of hex characters,
  320. # but stranger things have happened...
  321. $safeStart = $dbr->addQuotes( $start );
  322. $safeEnd = $dbr->addQuotes( $end );
  323. return $dbr->makeList(
  324. [
  325. "ipb_range_start $like",
  326. "ipb_range_start <= $safeStart",
  327. "ipb_range_end >= $safeEnd",
  328. ],
  329. LIST_AND
  330. );
  331. }
  332. /**
  333. * Get the component of an IP address which is certain to be the same between an IP
  334. * address and a rangeblock containing that IP address.
  335. * @param string $hex Hexadecimal IP representation
  336. * @return string
  337. */
  338. protected static function getIpFragment( $hex ) {
  339. global $wgBlockCIDRLimit;
  340. if ( substr( $hex, 0, 3 ) == 'v6-' ) {
  341. return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
  342. } else {
  343. return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
  344. }
  345. }
  346. /**
  347. * Given a database row from the ipblocks table, initialize
  348. * member variables
  349. * @param stdClass $row A row from the ipblocks table
  350. */
  351. protected function initFromRow( $row ) {
  352. $this->setTarget( $row->ipb_address );
  353. if ( $row->ipb_by ) { // local user
  354. $this->setBlocker( User::newFromId( $row->ipb_by ) );
  355. } else { // foreign user
  356. $this->setBlocker( $row->ipb_by_text );
  357. }
  358. $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
  359. $this->mAuto = $row->ipb_auto;
  360. $this->mHideName = $row->ipb_deleted;
  361. $this->mId = (int)$row->ipb_id;
  362. $this->mParentBlockId = $row->ipb_parent_block_id;
  363. // I wish I didn't have to do this
  364. $db = wfGetDB( DB_REPLICA );
  365. $this->mExpiry = $db->decodeExpiry( $row->ipb_expiry );
  366. $this->mReason = CommentStore::newKey( 'ipb_reason' )
  367. // Legacy because $row probably came from self::selectFields()
  368. ->getCommentLegacy( $db, $row )->text;
  369. $this->isHardblock( !$row->ipb_anon_only );
  370. $this->isAutoblocking( $row->ipb_enable_autoblock );
  371. $this->prevents( 'createaccount', $row->ipb_create_account );
  372. $this->prevents( 'sendemail', $row->ipb_block_email );
  373. $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
  374. }
  375. /**
  376. * Create a new Block object from a database row
  377. * @param stdClass $row Row from the ipblocks table
  378. * @return Block
  379. */
  380. public static function newFromRow( $row ) {
  381. $block = new Block;
  382. $block->initFromRow( $row );
  383. return $block;
  384. }
  385. /**
  386. * Delete the row from the IP blocks table.
  387. *
  388. * @throws MWException
  389. * @return bool
  390. */
  391. public function delete() {
  392. if ( wfReadOnly() ) {
  393. return false;
  394. }
  395. if ( !$this->getId() ) {
  396. throw new MWException( "Block::delete() requires that the mId member be filled\n" );
  397. }
  398. $dbw = wfGetDB( DB_MASTER );
  399. $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
  400. $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
  401. return $dbw->affectedRows() > 0;
  402. }
  403. /**
  404. * Insert a block into the block table. Will fail if there is a conflicting
  405. * block (same name and options) already in the database.
  406. *
  407. * @param IDatabase $dbw If you have one available
  408. * @return bool|array False on failure, assoc array on success:
  409. * ('id' => block ID, 'autoIds' => array of autoblock IDs)
  410. */
  411. public function insert( $dbw = null ) {
  412. global $wgBlockDisablesLogin;
  413. if ( $this->getSystemBlockType() !== null ) {
  414. throw new MWException( 'Cannot insert a system block into the database' );
  415. }
  416. wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
  417. if ( $dbw === null ) {
  418. $dbw = wfGetDB( DB_MASTER );
  419. }
  420. # Periodic purge via commit hooks
  421. if ( mt_rand( 0, 9 ) == 0 ) {
  422. self::purgeExpired();
  423. }
  424. $row = $this->getDatabaseArray( $dbw );
  425. $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
  426. $affected = $dbw->affectedRows();
  427. $this->mId = $dbw->insertId();
  428. # Don't collide with expired blocks.
  429. # Do this after trying to insert to avoid locking.
  430. if ( !$affected ) {
  431. # T96428: The ipb_address index uses a prefix on a field, so
  432. # use a standard SELECT + DELETE to avoid annoying gap locks.
  433. $ids = $dbw->selectFieldValues( 'ipblocks',
  434. 'ipb_id',
  435. [
  436. 'ipb_address' => $row['ipb_address'],
  437. 'ipb_user' => $row['ipb_user'],
  438. 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
  439. ],
  440. __METHOD__
  441. );
  442. if ( $ids ) {
  443. $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
  444. $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
  445. $affected = $dbw->affectedRows();
  446. $this->mId = $dbw->insertId();
  447. }
  448. }
  449. if ( $affected ) {
  450. $auto_ipd_ids = $this->doRetroactiveAutoblock();
  451. if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
  452. // Change user login token to force them to be logged out.
  453. $this->target->setToken();
  454. $this->target->saveSettings();
  455. }
  456. return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
  457. }
  458. return false;
  459. }
  460. /**
  461. * Update a block in the DB with new parameters.
  462. * The ID field needs to be loaded first.
  463. *
  464. * @return bool|array False on failure, array on success:
  465. * ('id' => block ID, 'autoIds' => array of autoblock IDs)
  466. */
  467. public function update() {
  468. wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
  469. $dbw = wfGetDB( DB_MASTER );
  470. $dbw->startAtomic( __METHOD__ );
  471. $dbw->update(
  472. 'ipblocks',
  473. $this->getDatabaseArray( $dbw ),
  474. [ 'ipb_id' => $this->getId() ],
  475. __METHOD__
  476. );
  477. $affected = $dbw->affectedRows();
  478. if ( $this->isAutoblocking() ) {
  479. // update corresponding autoblock(s) (T50813)
  480. $dbw->update(
  481. 'ipblocks',
  482. $this->getAutoblockUpdateArray( $dbw ),
  483. [ 'ipb_parent_block_id' => $this->getId() ],
  484. __METHOD__
  485. );
  486. } else {
  487. // autoblock no longer required, delete corresponding autoblock(s)
  488. $dbw->delete(
  489. 'ipblocks',
  490. [ 'ipb_parent_block_id' => $this->getId() ],
  491. __METHOD__
  492. );
  493. }
  494. $dbw->endAtomic( __METHOD__ );
  495. if ( $affected ) {
  496. $auto_ipd_ids = $this->doRetroactiveAutoblock();
  497. return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
  498. }
  499. return false;
  500. }
  501. /**
  502. * Get an array suitable for passing to $dbw->insert() or $dbw->update()
  503. * @param IDatabase $dbw
  504. * @return array
  505. */
  506. protected function getDatabaseArray( IDatabase $dbw ) {
  507. $expiry = $dbw->encodeExpiry( $this->mExpiry );
  508. if ( $this->forcedTargetID ) {
  509. $uid = $this->forcedTargetID;
  510. } else {
  511. $uid = $this->target instanceof User ? $this->target->getId() : 0;
  512. }
  513. $a = [
  514. 'ipb_address' => (string)$this->target,
  515. 'ipb_user' => $uid,
  516. 'ipb_by' => $this->getBy(),
  517. 'ipb_by_text' => $this->getByName(),
  518. 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
  519. 'ipb_auto' => $this->mAuto,
  520. 'ipb_anon_only' => !$this->isHardblock(),
  521. 'ipb_create_account' => $this->prevents( 'createaccount' ),
  522. 'ipb_enable_autoblock' => $this->isAutoblocking(),
  523. 'ipb_expiry' => $expiry,
  524. 'ipb_range_start' => $this->getRangeStart(),
  525. 'ipb_range_end' => $this->getRangeEnd(),
  526. 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
  527. 'ipb_block_email' => $this->prevents( 'sendemail' ),
  528. 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
  529. 'ipb_parent_block_id' => $this->mParentBlockId
  530. ] + CommentStore::newKey( 'ipb_reason' )->insert( $dbw, $this->mReason );
  531. return $a;
  532. }
  533. /**
  534. * @param IDatabase $dbw
  535. * @return array
  536. */
  537. protected function getAutoblockUpdateArray( IDatabase $dbw ) {
  538. return [
  539. 'ipb_by' => $this->getBy(),
  540. 'ipb_by_text' => $this->getByName(),
  541. 'ipb_create_account' => $this->prevents( 'createaccount' ),
  542. 'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
  543. 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
  544. ] + CommentStore::newKey( 'ipb_reason' )->insert( $dbw, $this->mReason );
  545. }
  546. /**
  547. * Retroactively autoblocks the last IP used by the user (if it is a user)
  548. * blocked by this Block.
  549. *
  550. * @return array Block IDs of retroactive autoblocks made
  551. */
  552. protected function doRetroactiveAutoblock() {
  553. $blockIds = [];
  554. # If autoblock is enabled, autoblock the LAST IP(s) used
  555. if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
  556. wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
  557. $continue = Hooks::run(
  558. 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
  559. if ( $continue ) {
  560. self::defaultRetroactiveAutoblock( $this, $blockIds );
  561. }
  562. }
  563. return $blockIds;
  564. }
  565. /**
  566. * Retroactively autoblocks the last IP used by the user (if it is a user)
  567. * blocked by this Block. This will use the recentchanges table.
  568. *
  569. * @param Block $block
  570. * @param array &$blockIds
  571. */
  572. protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
  573. global $wgPutIPinRC;
  574. // No IPs are in recentchanges table, so nothing to select
  575. if ( !$wgPutIPinRC ) {
  576. return;
  577. }
  578. $dbr = wfGetDB( DB_REPLICA );
  579. $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
  580. $conds = [ 'rc_user_text' => (string)$block->getTarget() ];
  581. // Just the last IP used.
  582. $options['LIMIT'] = 1;
  583. $res = $dbr->select( 'recentchanges', [ 'rc_ip' ], $conds,
  584. __METHOD__, $options );
  585. if ( !$res->numRows() ) {
  586. # No results, don't autoblock anything
  587. wfDebug( "No IP found to retroactively autoblock\n" );
  588. } else {
  589. foreach ( $res as $row ) {
  590. if ( $row->rc_ip ) {
  591. $id = $block->doAutoblock( $row->rc_ip );
  592. if ( $id ) {
  593. $blockIds[] = $id;
  594. }
  595. }
  596. }
  597. }
  598. }
  599. /**
  600. * Checks whether a given IP is on the autoblock whitelist.
  601. * TODO: this probably belongs somewhere else, but not sure where...
  602. *
  603. * @param string $ip The IP to check
  604. * @return bool
  605. */
  606. public static function isWhitelistedFromAutoblocks( $ip ) {
  607. // Try to get the autoblock_whitelist from the cache, as it's faster
  608. // than getting the msg raw and explode()'ing it.
  609. $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
  610. $lines = $cache->getWithSetCallback(
  611. $cache->makeKey( 'ipb', 'autoblock', 'whitelist' ),
  612. $cache::TTL_DAY,
  613. function ( $curValue, &$ttl, array &$setOpts ) {
  614. $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
  615. return explode( "\n",
  616. wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
  617. }
  618. );
  619. wfDebug( "Checking the autoblock whitelist..\n" );
  620. foreach ( $lines as $line ) {
  621. # List items only
  622. if ( substr( $line, 0, 1 ) !== '*' ) {
  623. continue;
  624. }
  625. $wlEntry = substr( $line, 1 );
  626. $wlEntry = trim( $wlEntry );
  627. wfDebug( "Checking $ip against $wlEntry..." );
  628. # Is the IP in this range?
  629. if ( IP::isInRange( $ip, $wlEntry ) ) {
  630. wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
  631. return true;
  632. } else {
  633. wfDebug( " No match\n" );
  634. }
  635. }
  636. return false;
  637. }
  638. /**
  639. * Autoblocks the given IP, referring to this Block.
  640. *
  641. * @param string $autoblockIP The IP to autoblock.
  642. * @return int|bool Block ID if an autoblock was inserted, false if not.
  643. */
  644. public function doAutoblock( $autoblockIP ) {
  645. # If autoblocks are disabled, go away.
  646. if ( !$this->isAutoblocking() ) {
  647. return false;
  648. }
  649. # Don't autoblock for system blocks
  650. if ( $this->getSystemBlockType() !== null ) {
  651. throw new MWException( 'Cannot autoblock from a system block' );
  652. }
  653. # Check for presence on the autoblock whitelist.
  654. if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
  655. return false;
  656. }
  657. // Avoid PHP 7.1 warning of passing $this by reference
  658. $block = $this;
  659. # Allow hooks to cancel the autoblock.
  660. if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
  661. wfDebug( "Autoblock aborted by hook.\n" );
  662. return false;
  663. }
  664. # It's okay to autoblock. Go ahead and insert/update the block...
  665. # Do not add a *new* block if the IP is already blocked.
  666. $ipblock = self::newFromTarget( $autoblockIP );
  667. if ( $ipblock ) {
  668. # Check if the block is an autoblock and would exceed the user block
  669. # if renewed. If so, do nothing, otherwise prolong the block time...
  670. if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
  671. $this->mExpiry > self::getAutoblockExpiry( $ipblock->mTimestamp )
  672. ) {
  673. # Reset block timestamp to now and its expiry to
  674. # $wgAutoblockExpiry in the future
  675. $ipblock->updateTimestamp();
  676. }
  677. return false;
  678. }
  679. # Make a new block object with the desired properties.
  680. $autoblock = new Block;
  681. wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
  682. $autoblock->setTarget( $autoblockIP );
  683. $autoblock->setBlocker( $this->getBlocker() );
  684. $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
  685. ->inContentLanguage()->plain();
  686. $timestamp = wfTimestampNow();
  687. $autoblock->mTimestamp = $timestamp;
  688. $autoblock->mAuto = 1;
  689. $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
  690. # Continue suppressing the name if needed
  691. $autoblock->mHideName = $this->mHideName;
  692. $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
  693. $autoblock->mParentBlockId = $this->mId;
  694. if ( $this->mExpiry == 'infinity' ) {
  695. # Original block was indefinite, start an autoblock now
  696. $autoblock->mExpiry = self::getAutoblockExpiry( $timestamp );
  697. } else {
  698. # If the user is already blocked with an expiry date, we don't
  699. # want to pile on top of that.
  700. $autoblock->mExpiry = min( $this->mExpiry, self::getAutoblockExpiry( $timestamp ) );
  701. }
  702. # Insert the block...
  703. $status = $autoblock->insert();
  704. return $status
  705. ? $status['id']
  706. : false;
  707. }
  708. /**
  709. * Check if a block has expired. Delete it if it is.
  710. * @return bool
  711. */
  712. public function deleteIfExpired() {
  713. if ( $this->isExpired() ) {
  714. wfDebug( "Block::deleteIfExpired() -- deleting\n" );
  715. $this->delete();
  716. $retVal = true;
  717. } else {
  718. wfDebug( "Block::deleteIfExpired() -- not expired\n" );
  719. $retVal = false;
  720. }
  721. return $retVal;
  722. }
  723. /**
  724. * Has the block expired?
  725. * @return bool
  726. */
  727. public function isExpired() {
  728. $timestamp = wfTimestampNow();
  729. wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
  730. if ( !$this->mExpiry ) {
  731. return false;
  732. } else {
  733. return $timestamp > $this->mExpiry;
  734. }
  735. }
  736. /**
  737. * Is the block address valid (i.e. not a null string?)
  738. * @return bool
  739. */
  740. public function isValid() {
  741. return $this->getTarget() != null;
  742. }
  743. /**
  744. * Update the timestamp on autoblocks.
  745. */
  746. public function updateTimestamp() {
  747. if ( $this->mAuto ) {
  748. $this->mTimestamp = wfTimestamp();
  749. $this->mExpiry = self::getAutoblockExpiry( $this->mTimestamp );
  750. $dbw = wfGetDB( DB_MASTER );
  751. $dbw->update( 'ipblocks',
  752. [ /* SET */
  753. 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
  754. 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
  755. ],
  756. [ /* WHERE */
  757. 'ipb_id' => $this->getId(),
  758. ],
  759. __METHOD__
  760. );
  761. }
  762. }
  763. /**
  764. * Get the IP address at the start of the range in Hex form
  765. * @throws MWException
  766. * @return string IP in Hex form
  767. */
  768. public function getRangeStart() {
  769. switch ( $this->type ) {
  770. case self::TYPE_USER:
  771. return '';
  772. case self::TYPE_IP:
  773. return IP::toHex( $this->target );
  774. case self::TYPE_RANGE:
  775. list( $start, /*...*/ ) = IP::parseRange( $this->target );
  776. return $start;
  777. default:
  778. throw new MWException( "Block with invalid type" );
  779. }
  780. }
  781. /**
  782. * Get the IP address at the end of the range in Hex form
  783. * @throws MWException
  784. * @return string IP in Hex form
  785. */
  786. public function getRangeEnd() {
  787. switch ( $this->type ) {
  788. case self::TYPE_USER:
  789. return '';
  790. case self::TYPE_IP:
  791. return IP::toHex( $this->target );
  792. case self::TYPE_RANGE:
  793. list( /*...*/, $end ) = IP::parseRange( $this->target );
  794. return $end;
  795. default:
  796. throw new MWException( "Block with invalid type" );
  797. }
  798. }
  799. /**
  800. * Get the user id of the blocking sysop
  801. *
  802. * @return int (0 for foreign users)
  803. */
  804. public function getBy() {
  805. $blocker = $this->getBlocker();
  806. return ( $blocker instanceof User )
  807. ? $blocker->getId()
  808. : 0;
  809. }
  810. /**
  811. * Get the username of the blocking sysop
  812. *
  813. * @return string
  814. */
  815. public function getByName() {
  816. $blocker = $this->getBlocker();
  817. return ( $blocker instanceof User )
  818. ? $blocker->getName()
  819. : (string)$blocker; // username
  820. }
  821. /**
  822. * Get the block ID
  823. * @return int
  824. */
  825. public function getId() {
  826. return $this->mId;
  827. }
  828. /**
  829. * Get the system block type, if any
  830. * @since 1.29
  831. * @return string|null
  832. */
  833. public function getSystemBlockType() {
  834. return $this->systemBlockType;
  835. }
  836. /**
  837. * Get/set a flag determining whether the master is used for reads
  838. *
  839. * @param bool|null $x
  840. * @return bool
  841. */
  842. public function fromMaster( $x = null ) {
  843. return wfSetVar( $this->mFromMaster, $x );
  844. }
  845. /**
  846. * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
  847. * @param bool|null $x
  848. * @return bool
  849. */
  850. public function isHardblock( $x = null ) {
  851. wfSetVar( $this->isHardblock, $x );
  852. # You can't *not* hardblock a user
  853. return $this->getType() == self::TYPE_USER
  854. ? true
  855. : $this->isHardblock;
  856. }
  857. /**
  858. * @param null|bool $x
  859. * @return bool
  860. */
  861. public function isAutoblocking( $x = null ) {
  862. wfSetVar( $this->isAutoblocking, $x );
  863. # You can't put an autoblock on an IP or range as we don't have any history to
  864. # look over to get more IPs from
  865. return $this->getType() == self::TYPE_USER
  866. ? $this->isAutoblocking
  867. : false;
  868. }
  869. /**
  870. * Get/set whether the Block prevents a given action
  871. *
  872. * @param string $action Action to check
  873. * @param bool|null $x Value for set, or null to just get value
  874. * @return bool|null Null for unrecognized rights.
  875. */
  876. public function prevents( $action, $x = null ) {
  877. global $wgBlockDisablesLogin;
  878. $res = null;
  879. switch ( $action ) {
  880. case 'edit':
  881. # For now... <evil laugh>
  882. $res = true;
  883. break;
  884. case 'createaccount':
  885. $res = wfSetVar( $this->mCreateAccount, $x );
  886. break;
  887. case 'sendemail':
  888. $res = wfSetVar( $this->mBlockEmail, $x );
  889. break;
  890. case 'editownusertalk':
  891. $res = wfSetVar( $this->mDisableUsertalk, $x );
  892. break;
  893. case 'read':
  894. $res = false;
  895. break;
  896. }
  897. if ( !$res && $wgBlockDisablesLogin ) {
  898. // If a block would disable login, then it should
  899. // prevent any action that all users cannot do
  900. $anon = new User;
  901. $res = $anon->isAllowed( $action ) ? $res : true;
  902. }
  903. return $res;
  904. }
  905. /**
  906. * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
  907. * @return string Text is escaped
  908. */
  909. public function getRedactedName() {
  910. if ( $this->mAuto ) {
  911. return Html::rawElement(
  912. 'span',
  913. [ 'class' => 'mw-autoblockid' ],
  914. wfMessage( 'autoblockid', $this->mId )
  915. );
  916. } else {
  917. return htmlspecialchars( $this->getTarget() );
  918. }
  919. }
  920. /**
  921. * Get a timestamp of the expiry for autoblocks
  922. *
  923. * @param string|int $timestamp
  924. * @return string
  925. */
  926. public static function getAutoblockExpiry( $timestamp ) {
  927. global $wgAutoblockExpiry;
  928. return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
  929. }
  930. /**
  931. * Purge expired blocks from the ipblocks table
  932. */
  933. public static function purgeExpired() {
  934. if ( wfReadOnly() ) {
  935. return;
  936. }
  937. DeferredUpdates::addUpdate( new AtomicSectionUpdate(
  938. wfGetDB( DB_MASTER ),
  939. __METHOD__,
  940. function ( IDatabase $dbw, $fname ) {
  941. $dbw->delete(
  942. 'ipblocks',
  943. [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
  944. $fname
  945. );
  946. }
  947. ) );
  948. }
  949. /**
  950. * Given a target and the target's type, get an existing Block object if possible.
  951. * @param string|User|int $specificTarget A block target, which may be one of several types:
  952. * * A user to block, in which case $target will be a User
  953. * * An IP to block, in which case $target will be a User generated by using
  954. * User::newFromName( $ip, false ) to turn off name validation
  955. * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
  956. * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
  957. * usernames
  958. * Calling this with a user, IP address or range will not select autoblocks, and will
  959. * only select a block where the targets match exactly (so looking for blocks on
  960. * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
  961. * @param string|User|int $vagueTarget As above, but we will search for *any* block which
  962. * affects that target (so for an IP address, get ranges containing that IP; and also
  963. * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
  964. * @param bool $fromMaster Whether to use the DB_MASTER database
  965. * @return Block|null (null if no relevant block could be found). The target and type
  966. * of the returned Block will refer to the actual block which was found, which might
  967. * not be the same as the target you gave if you used $vagueTarget!
  968. */
  969. public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
  970. list( $target, $type ) = self::parseTarget( $specificTarget );
  971. if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
  972. return self::newFromID( $target );
  973. } elseif ( $target === null && $vagueTarget == '' ) {
  974. # We're not going to find anything useful here
  975. # Be aware that the == '' check is explicit, since empty values will be
  976. # passed by some callers (T31116)
  977. return null;
  978. } elseif ( in_array(
  979. $type,
  980. [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
  981. ) {
  982. $block = new Block();
  983. $block->fromMaster( $fromMaster );
  984. if ( $type !== null ) {
  985. $block->setTarget( $target );
  986. }
  987. if ( $block->newLoad( $vagueTarget ) ) {
  988. return $block;
  989. }
  990. }
  991. return null;
  992. }
  993. /**
  994. * Get all blocks that match any IP from an array of IP addresses
  995. *
  996. * @param array $ipChain List of IPs (strings), usually retrieved from the
  997. * X-Forwarded-For header of the request
  998. * @param bool $isAnon Exclude anonymous-only blocks if false
  999. * @param bool $fromMaster Whether to query the master or replica DB
  1000. * @return array Array of Blocks
  1001. * @since 1.22
  1002. */
  1003. public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
  1004. if ( !count( $ipChain ) ) {
  1005. return [];
  1006. }
  1007. $conds = [];
  1008. $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
  1009. foreach ( array_unique( $ipChain ) as $ipaddr ) {
  1010. # Discard invalid IP addresses. Since XFF can be spoofed and we do not
  1011. # necessarily trust the header given to us, make sure that we are only
  1012. # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
  1013. # Do not treat private IP spaces as special as it may be desirable for wikis
  1014. # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
  1015. if ( !IP::isValid( $ipaddr ) ) {
  1016. continue;
  1017. }
  1018. # Don't check trusted IPs (includes local squids which will be in every request)
  1019. if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
  1020. continue;
  1021. }
  1022. # Check both the original IP (to check against single blocks), as well as build
  1023. # the clause to check for rangeblocks for the given IP.
  1024. $conds['ipb_address'][] = $ipaddr;
  1025. $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
  1026. }
  1027. if ( !count( $conds ) ) {
  1028. return [];
  1029. }
  1030. if ( $fromMaster ) {
  1031. $db = wfGetDB( DB_MASTER );
  1032. } else {
  1033. $db = wfGetDB( DB_REPLICA );
  1034. }
  1035. $conds = $db->makeList( $conds, LIST_OR );
  1036. if ( !$isAnon ) {
  1037. $conds = [ $conds, 'ipb_anon_only' => 0 ];
  1038. }
  1039. $selectFields = array_merge(
  1040. [ 'ipb_range_start', 'ipb_range_end' ],
  1041. self::selectFields()
  1042. );
  1043. $rows = $db->select( 'ipblocks',
  1044. $selectFields,
  1045. $conds,
  1046. __METHOD__
  1047. );
  1048. $blocks = [];
  1049. foreach ( $rows as $row ) {
  1050. $block = self::newFromRow( $row );
  1051. if ( !$block->isExpired() ) {
  1052. $blocks[] = $block;
  1053. }
  1054. }
  1055. return $blocks;
  1056. }
  1057. /**
  1058. * From a list of multiple blocks, find the most exact and strongest Block.
  1059. *
  1060. * The logic for finding the "best" block is:
  1061. * - Blocks that match the block's target IP are preferred over ones in a range
  1062. * - Hardblocks are chosen over softblocks that prevent account creation
  1063. * - Softblocks that prevent account creation are chosen over other softblocks
  1064. * - Other softblocks are chosen over autoblocks
  1065. * - If there are multiple exact or range blocks at the same level, the one chosen
  1066. * is random
  1067. * This should be used when $blocks where retrieved from the user's IP address
  1068. * and $ipChain is populated from the same IP address information.
  1069. *
  1070. * @param array $blocks Array of Block objects
  1071. * @param array $ipChain List of IPs (strings). This is used to determine how "close"
  1072. * a block is to the server, and if a block matches exactly, or is in a range.
  1073. * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
  1074. * local-squid, ...)
  1075. * @throws MWException
  1076. * @return Block|null The "best" block from the list
  1077. */
  1078. public static function chooseBlock( array $blocks, array $ipChain ) {
  1079. if ( !count( $blocks ) ) {
  1080. return null;
  1081. } elseif ( count( $blocks ) == 1 ) {
  1082. return $blocks[0];
  1083. }
  1084. // Sort hard blocks before soft ones and secondarily sort blocks
  1085. // that disable account creation before those that don't.
  1086. usort( $blocks, function ( Block $a, Block $b ) {
  1087. $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
  1088. $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
  1089. return strcmp( $bWeight, $aWeight ); // highest weight first
  1090. } );
  1091. $blocksListExact = [
  1092. 'hard' => false,
  1093. 'disable_create' => false,
  1094. 'other' => false,
  1095. 'auto' => false
  1096. ];
  1097. $blocksListRange = [
  1098. 'hard' => false,
  1099. 'disable_create' => false,
  1100. 'other' => false,
  1101. 'auto' => false
  1102. ];
  1103. $ipChain = array_reverse( $ipChain );
  1104. /** @var Block $block */
  1105. foreach ( $blocks as $block ) {
  1106. // Stop searching if we have already have a "better" block. This
  1107. // is why the order of the blocks matters
  1108. if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
  1109. break;
  1110. } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
  1111. break;
  1112. }
  1113. foreach ( $ipChain as $checkip ) {
  1114. $checkipHex = IP::toHex( $checkip );
  1115. if ( (string)$block->getTarget() === $checkip ) {
  1116. if ( $block->isHardblock() ) {
  1117. $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
  1118. } elseif ( $block->prevents( 'createaccount' ) ) {
  1119. $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
  1120. } elseif ( $block->mAuto ) {
  1121. $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
  1122. } else {
  1123. $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
  1124. }
  1125. // We found closest exact match in the ip list, so go to the next Block
  1126. break;
  1127. } elseif ( array_filter( $blocksListExact ) == []
  1128. && $block->getRangeStart() <= $checkipHex
  1129. && $block->getRangeEnd() >= $checkipHex
  1130. ) {
  1131. if ( $block->isHardblock() ) {
  1132. $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
  1133. } elseif ( $block->prevents( 'createaccount' ) ) {
  1134. $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
  1135. } elseif ( $block->mAuto ) {
  1136. $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
  1137. } else {
  1138. $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
  1139. }
  1140. break;
  1141. }
  1142. }
  1143. }
  1144. if ( array_filter( $blocksListExact ) == [] ) {
  1145. $blocksList = &$blocksListRange;
  1146. } else {
  1147. $blocksList = &$blocksListExact;
  1148. }
  1149. $chosenBlock = null;
  1150. if ( $blocksList['hard'] ) {
  1151. $chosenBlock = $blocksList['hard'];
  1152. } elseif ( $blocksList['disable_create'] ) {
  1153. $chosenBlock = $blocksList['disable_create'];
  1154. } elseif ( $blocksList['other'] ) {
  1155. $chosenBlock = $blocksList['other'];
  1156. } elseif ( $blocksList['auto'] ) {
  1157. $chosenBlock = $blocksList['auto'];
  1158. } else {
  1159. throw new MWException( "Proxy block found, but couldn't be classified." );
  1160. }
  1161. return $chosenBlock;
  1162. }
  1163. /**
  1164. * From an existing Block, get the target and the type of target.
  1165. * Note that, except for null, it is always safe to treat the target
  1166. * as a string; for User objects this will return User::__toString()
  1167. * which in turn gives User::getName().
  1168. *
  1169. * @param string|int|User|null $target
  1170. * @return array [ User|String|null, Block::TYPE_ constant|null ]
  1171. */
  1172. public static function parseTarget( $target ) {
  1173. # We may have been through this before
  1174. if ( $target instanceof User ) {
  1175. if ( IP::isValid( $target->getName() ) ) {
  1176. return [ $target, self::TYPE_IP ];
  1177. } else {
  1178. return [ $target, self::TYPE_USER ];
  1179. }
  1180. } elseif ( $target === null ) {
  1181. return [ null, null ];
  1182. }
  1183. $target = trim( $target );
  1184. if ( IP::isValid( $target ) ) {
  1185. # We can still create a User if it's an IP address, but we need to turn
  1186. # off validation checking (which would exclude IP addresses)
  1187. return [
  1188. User::newFromName( IP::sanitizeIP( $target ), false ),
  1189. self::TYPE_IP
  1190. ];
  1191. } elseif ( IP::isValidRange( $target ) ) {
  1192. # Can't create a User from an IP range
  1193. return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
  1194. }
  1195. # Consider the possibility that this is not a username at all
  1196. # but actually an old subpage (bug #29797)
  1197. if ( strpos( $target, '/' ) !== false ) {
  1198. # An old subpage, drill down to the user behind it
  1199. $target = explode( '/', $target )[0];
  1200. }
  1201. $userObj = User::newFromName( $target );
  1202. if ( $userObj instanceof User ) {
  1203. # Note that since numbers are valid usernames, a $target of "12345" will be
  1204. # considered a User. If you want to pass a block ID, prepend a hash "#12345",
  1205. # since hash characters are not valid in usernames or titles generally.
  1206. return [ $userObj, self::TYPE_USER ];
  1207. } elseif ( preg_match( '/^#\d+$/', $target ) ) {
  1208. # Autoblock reference in the form "#12345"
  1209. return [ substr( $target, 1 ), self::TYPE_AUTO ];
  1210. } else {
  1211. # WTF?
  1212. return [ null, null ];
  1213. }
  1214. }
  1215. /**
  1216. * Get the type of target for this particular block
  1217. * @return int Block::TYPE_ constant, will never be TYPE_ID
  1218. */
  1219. public function getType() {
  1220. return $this->mAuto
  1221. ? self::TYPE_AUTO
  1222. : $this->type;
  1223. }
  1224. /**
  1225. * Get the target and target type for this particular Block. Note that for autoblocks,
  1226. * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
  1227. * in this situation.
  1228. * @return array [ User|String, Block::TYPE_ constant ]
  1229. * @todo FIXME: This should be an integral part of the Block member variables
  1230. */
  1231. public function getTargetAndType() {
  1232. return [ $this->getTarget(), $this->getType() ];
  1233. }
  1234. /**
  1235. * Get the target for this particular Block. Note that for autoblocks,
  1236. * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
  1237. * in this situation.
  1238. * @return User|string
  1239. */
  1240. public function getTarget() {
  1241. return $this->target;
  1242. }
  1243. /**
  1244. * @since 1.19
  1245. *
  1246. * @return mixed|string
  1247. */
  1248. public function getExpiry() {
  1249. return $this->mExpiry;
  1250. }
  1251. /**
  1252. * Set the target for this block, and update $this->type accordingly
  1253. * @param mixed $target
  1254. */
  1255. public function setTarget( $target ) {
  1256. list( $this->target, $this->type ) = self::parseTarget( $target );
  1257. }
  1258. /**
  1259. * Get the user who implemented this block
  1260. * @return User|string Local User object or string for a foreign user
  1261. */
  1262. public function getBlocker() {
  1263. return $this->blocker;
  1264. }
  1265. /**
  1266. * Set the user who implemented (or will implement) this block
  1267. * @param User|string $user Local User object or username string for foreign users
  1268. */
  1269. public function setBlocker( $user ) {
  1270. $this->blocker = $user;
  1271. }
  1272. /**
  1273. * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
  1274. * the same as the block's, to a maximum of 24 hours.
  1275. *
  1276. * @since 1.29
  1277. *
  1278. * @param WebResponse $response The response on which to set the cookie.
  1279. */
  1280. public function setCookie( WebResponse $response ) {
  1281. // Calculate the default expiry time.
  1282. $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
  1283. // Use the Block's expiry time only if it's less than the default.
  1284. $expiryTime = $this->getExpiry();
  1285. if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
  1286. $expiryTime = $maxExpiryTime;
  1287. }
  1288. // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
  1289. $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
  1290. $cookieOptions = [ 'httpOnly' => false ];
  1291. $cookieValue = $this->getCookieValue();
  1292. $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
  1293. }
  1294. /**
  1295. * Unset the 'BlockID' cookie.
  1296. *
  1297. * @since 1.29
  1298. *
  1299. * @param WebResponse $response The response on which to unset the cookie.
  1300. */
  1301. public static function clearCookie( WebResponse $response ) {
  1302. $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
  1303. }
  1304. /**
  1305. * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
  1306. * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
  1307. * be the block ID.
  1308. *
  1309. * @since 1.29
  1310. *
  1311. * @return string The block ID, probably concatenated with "!" and the HMAC.
  1312. */
  1313. public function getCookieValue() {
  1314. $config = RequestContext::getMain()->getConfig();
  1315. $id = $this->getId();
  1316. $secretKey = $config->get( 'SecretKey' );
  1317. if ( !$secretKey ) {
  1318. // If there's no secret key, don't append a HMAC.
  1319. return $id;
  1320. }
  1321. $hmac = MWCryptHash::hmac( $id, $secretKey, false );
  1322. $cookieValue = $id . '!' . $hmac;
  1323. return $cookieValue;
  1324. }
  1325. /**
  1326. * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
  1327. * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
  1328. *
  1329. * @since 1.29
  1330. *
  1331. * @param string $cookieValue The string in which to find the ID.
  1332. *
  1333. * @return int|null The block ID, or null if the HMAC is present and invalid.
  1334. */
  1335. public static function getIdFromCookieValue( $cookieValue ) {
  1336. // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
  1337. $bangPos = strpos( $cookieValue, '!' );
  1338. $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
  1339. // Get the site-wide secret key.
  1340. $config = RequestContext::getMain()->getConfig();
  1341. $secretKey = $config->get( 'SecretKey' );
  1342. if ( !$secretKey ) {
  1343. // If there's no secret key, just use the ID as given.
  1344. return $id;
  1345. }
  1346. $storedHmac = substr( $cookieValue, $bangPos + 1 );
  1347. $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
  1348. if ( $calculatedHmac === $storedHmac ) {
  1349. return $id;
  1350. } else {
  1351. return null;
  1352. }
  1353. }
  1354. /**
  1355. * Get the key and parameters for the corresponding error message.
  1356. *
  1357. * @since 1.22
  1358. * @param IContextSource $context
  1359. * @return array
  1360. */
  1361. public function getPermissionsError( IContextSource $context ) {
  1362. $blocker = $this->getBlocker();
  1363. if ( $blocker instanceof User ) { // local user
  1364. $blockerUserpage = $blocker->getUserPage();
  1365. $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
  1366. } else { // foreign user
  1367. $link = $blocker;
  1368. }
  1369. $reason = $this->mReason;
  1370. if ( $reason == '' ) {
  1371. $reason = $context->msg( 'blockednoreason' )->text();
  1372. }
  1373. /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
  1374. * This could be a username, an IP range, or a single IP. */
  1375. $intended = $this->getTarget();
  1376. $systemBlockType = $this->getSystemBlockType();
  1377. $lang = $context->getLanguage();
  1378. return [
  1379. $systemBlockType !== null
  1380. ? 'systemblockedtext'
  1381. : ( $this->mAuto ? 'autoblockedtext' : 'blockedtext' ),
  1382. $link,
  1383. $reason,
  1384. $context->getRequest()->getIP(),
  1385. $this->getByName(),
  1386. $systemBlockType !== null ? $systemBlockType : $this->getId(),
  1387. $lang->formatExpiry( $this->mExpiry ),
  1388. (string)$intended,
  1389. $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
  1390. ];
  1391. }
  1392. }