Fixed daft error in r84523 so "angry" autoblocks work again
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * @file
4 * Blocks and bans object
5 */
6
7 /**
8 * The block class
9 * All the functions in this class assume the object is either explicitly
10 * loaded or filled. It is not load-on-demand. There are no accessors.
11 *
12 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
13 *
14 * @todo This could be used everywhere, but it isn't.
15 * FIXME: this whole class is a cesspit, needs a complete rewrite
16 */
17 class Block {
18 /* public*/ var $mUser, $mReason, $mTimestamp, $mAuto, $mExpiry,
19 $mHideName,
20 $mAngryAutoblock;
21 protected
22 $mAddress,
23 $mId,
24 $mBy,
25 $mByName,
26 $mFromMaster,
27 $mRangeStart,
28 $mRangeEnd,
29 $mAnonOnly,
30 $mEnableAutoblock,
31 $mBlockEmail,
32 $mAllowUsertalk,
33 $mCreateAccount;
34
35 /// @var User|String
36 protected $target;
37
38 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
39 protected $type;
40
41 /// @var User
42 protected $blocker;
43
44 # TYPE constants
45 const TYPE_USER = 1;
46 const TYPE_IP = 2;
47 const TYPE_RANGE = 3;
48 const TYPE_AUTO = 4;
49 const TYPE_ID = 5;
50
51 /**
52 * Constructor
53 * FIXME: Don't know what the best format to have for this constructor is, but fourteen
54 * optional parameters certainly isn't it.
55 */
56 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
57 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
58 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byName = false )
59 {
60 if( $timestamp === 0 ){
61 $timestamp = wfTimestampNow();
62 }
63
64 $this->mId = 0;
65 # Expand valid IPv6 addresses
66 $address = IP::sanitizeIP( $address );
67 $this->mAddress = $address;
68 $this->mUser = $user;
69 $this->mBy = $by;
70 $this->mReason = $reason;
71 $this->mTimestamp = wfTimestamp( TS_MW, $timestamp );
72 $this->mAuto = $auto;
73 $this->mAnonOnly = $anonOnly;
74 $this->mCreateAccount = $createAccount;
75 $this->mExpiry = $expiry;
76 $this->mEnableAutoblock = $enableAutoblock;
77 $this->mHideName = $hideName;
78 $this->mBlockEmail = $blockEmail;
79 $this->mAllowUsertalk = $allowUsertalk;
80 $this->mFromMaster = false;
81 $this->mByName = $byName;
82 $this->mAngryAutoblock = false;
83 $this->initialiseRange();
84 }
85
86 /**
87 * Load a block from the database, using either the IP address or
88 * user ID. Tries the user ID first, and if that doesn't work, tries
89 * the address.
90 *
91 * @param $address String: IP address of user/anon
92 * @param $user Integer: user id of user
93 * @param $killExpired Boolean: delete expired blocks on load
94 * @return Block Object
95 */
96 public static function newFromDB( $address, $user = 0, $killExpired = true ) {
97 $block = new Block;
98 $block->load( $address, $user, $killExpired );
99 if ( $block->isValid() ) {
100 return $block;
101 } else {
102 return null;
103 }
104 }
105
106 /**
107 * Load a blocked user from their block id.
108 *
109 * @param $id Integer: Block id to search for
110 * @return Block object
111 */
112 public static function newFromID( $id ) {
113 $dbr = wfGetDB( DB_SLAVE );
114 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
115 array( 'ipb_id' => $id ), __METHOD__ ) );
116 $block = new Block;
117
118 if ( $block->loadFromResult( $res ) ) {
119 return $block;
120 } else {
121 return null;
122 }
123 }
124
125 /**
126 * Check if two blocks are effectively equal
127 *
128 * @return Boolean
129 */
130 public function equals( Block $block ) {
131 return (
132 $this->mAddress == $block->mAddress
133 && $this->mUser == $block->mUser
134 && $this->mAuto == $block->mAuto
135 && $this->mAnonOnly == $block->mAnonOnly
136 && $this->mCreateAccount == $block->mCreateAccount
137 && $this->mExpiry == $block->mExpiry
138 && $this->mEnableAutoblock == $block->mEnableAutoblock
139 && $this->mHideName == $block->mHideName
140 && $this->mBlockEmail == $block->mBlockEmail
141 && $this->mAllowUsertalk == $block->mAllowUsertalk
142 && $this->mReason == $block->mReason
143 );
144 }
145
146 /**
147 * Clear all member variables in the current object. Does not clear
148 * the block from the DB.
149 */
150 public function clear() {
151 $this->mAddress = $this->mReason = $this->mTimestamp = '';
152 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
153 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
154 $this->mBy = $this->mHideName = $this->mBlockEmail = $this->mAllowUsertalk = 0;
155 $this->mByName = false;
156 }
157
158 /**
159 * Get a block from the DB, with either the given address or the given username
160 *
161 * @param $address string The IP address of the user, or blank to skip IP blocks
162 * @param $user int The user ID, or zero for anonymous users
163 * @param $killExpired bool Whether to delete expired rows while loading
164 * @return Boolean: the user is blocked from editing
165 * @deprecated since 1.18
166 */
167 public function load( $address = '', $user = 0, $killExpired = true ) {
168 wfDeprecated( __METHOD__ );
169 if( $user ){
170 $username = User::whoIs( $user );
171 $block = self::newFromTarget( $username, $address );
172 } else {
173 $block = self::newFromTarget( null, $address );
174 }
175
176 if( $block instanceof Block ){
177 # This is mildly evil, but hey, it's B/C :D
178 foreach( $block as $variable => $value ){
179 $this->$variable = $value;
180 }
181 return true;
182 } else {
183 return false;
184 }
185 }
186
187 /**
188 * Load a block from the database which affects the already-set $this->target:
189 * 1) A block directly on the given user or IP
190 * 2) A rangeblock encompasing the given IP (smallest first)
191 * 3) An autoblock on the given IP
192 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
193 * make any sense to use TYPE_AUTO / TYPE_ID here
194 * @return Bool whether a relevant block was found
195 */
196 protected function newLoad( $vagueTarget = null ) {
197 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_SLAVE );
198
199 if( $this->type !== null ){
200 $conds = array(
201 'ipb_address' => array( (string)$this->target ),
202 );
203 } else {
204 $conds = array( 'ipb_address' => array() );
205 }
206
207 if( $vagueTarget !== null ){
208 list( $target, $type ) = self::parseTarget( $vagueTarget );
209 switch( $type ) {
210 case self::TYPE_USER:
211 # Slightly wierd, but who are we to argue?
212 $conds['ipb_address'][] = (string)$target;
213 break;
214
215 case self::TYPE_IP:
216 $conds['ipb_address'][] = (string)$target;
217 $conds[] = self::getRangeCond( IP::toHex( $target ) );
218 $conds = $db->makeList( $conds, LIST_OR );
219 break;
220
221 case self::TYPE_RANGE:
222 list( $start, $end ) = IP::parseRange( $target );
223 $conds['ipb_address'][] = (string)$target;
224 $conds[] = self::getRangeCond( $start, $end );
225 $conds = $db->makeList( $conds, LIST_OR );
226 break;
227
228 default:
229 throw new MWException( "Tried to load block with invalid type" );
230 }
231 }
232
233 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__ );
234
235 # This result could contain a block on the user, a block on the IP, and a russian-doll
236 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
237 $bestRow = null;
238
239 # Lower will be better
240 $bestBlockScore = 100;
241
242 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
243 $bestBlockPreventsEdit = null;
244
245 foreach( $res as $row ){
246 $block = Block::newFromRow( $row );
247
248 # Don't use expired blocks
249 if( $block->deleteIfExpired() ){
250 continue;
251 }
252
253 # Don't use anon only blocks on users
254 if( $this->type == self::TYPE_USER && !$block->isHardblock() ){
255 continue;
256 }
257
258 if( $block->getType() == self::TYPE_RANGE ){
259 # This is the number of bits that are allowed to vary in the block, give
260 # or take some floating point errors
261 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
262 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
263 $size = log( $end - $start + 1, 2 );
264
265 # This has the nice property that a /32 block is ranked equally with a
266 # single-IP block, which is exactly what it is...
267 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
268
269 } else {
270 $score = $block->getType();
271 }
272
273 if( $score < $bestBlockScore ){
274 $bestBlockScore = $score;
275 $bestRow = $row;
276 $bestBlockPreventsEdit = $block->prevents( 'edit' );
277 }
278 }
279
280 if( $bestRow !== null ){
281 $this->initFromRow( $bestRow );
282 $this->prevents( 'edit', $bestBlockPreventsEdit );
283 return true;
284 } else {
285 return false;
286 }
287 }
288
289 /**
290 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
291 * @param $start String Hexadecimal IP representation
292 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
293 * @return String
294 */
295 public static function getRangeCond( $start, $end = null ) {
296 if ( $end === null ) {
297 $end = $start;
298 }
299 # Per bug 14634, we want to include relevant active rangeblocks; for
300 # rangeblocks, we want to include larger ranges which enclose the given
301 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
302 # so we can improve performance by filtering on a LIKE clause
303 $chunk = self::getIpFragment( $start );
304 $dbr = wfGetDB( DB_SLAVE );
305 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
306
307 # Fairly hard to make a malicious SQL statement out of hex characters,
308 # but stranger things have happened...
309 $safeStart = $dbr->addQuotes( $start );
310 $safeEnd = $dbr->addQuotes( $end );
311
312 return $dbr->makeList(
313 array(
314 "ipb_range_start $like",
315 "ipb_range_start <= $safeStart",
316 "ipb_range_end >= $safeEnd",
317 ),
318 LIST_AND
319 );
320 }
321
322 /**
323 * Get the component of an IP address which is certain to be the same between an IP
324 * address and a rangeblock containing that IP address.
325 * @param $hex String Hexadecimal IP representation
326 * @return String
327 */
328 protected static function getIpFragment( $hex ) {
329 global $wgBlockCIDRLimit;
330 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
331 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
332 } else {
333 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
334 }
335 }
336
337 /**
338 * Fill in member variables from a result wrapper
339 *
340 * @param $res ResultWrapper: row from the ipblocks table
341 * @param $killExpired Boolean: whether to delete expired rows while loading
342 * @return Boolean
343 */
344 protected function loadFromResult( ResultWrapper $res, $killExpired = true ) {
345 $ret = false;
346
347 if ( 0 != $res->numRows() ) {
348 # Get first block
349 $row = $res->fetchObject();
350 $this->initFromRow( $row );
351
352 if ( $killExpired ) {
353 # If requested, delete expired rows
354 do {
355 $killed = $this->deleteIfExpired();
356 if ( $killed ) {
357 $row = $res->fetchObject();
358 if ( $row ) {
359 $this->initFromRow( $row );
360 }
361 }
362 } while ( $killed && $row );
363
364 # If there were any left after the killing finished, return true
365 if ( $row ) {
366 $ret = true;
367 }
368 } else {
369 $ret = true;
370 }
371 }
372 $res->free();
373
374 return $ret;
375 }
376
377 /**
378 * Search the database for any range blocks matching the given address, and
379 * load the row if one is found.
380 *
381 * @param $address String: IP address range
382 * @param $killExpired Boolean: whether to delete expired rows while loading
383 * @param $user Integer: if not 0, then sets ipb_anon_only
384 * @return Boolean
385 */
386 protected function loadRange( $address, $killExpired = true, $user = 0 ) {
387 $iaddr = IP::toHex( $address );
388
389 if ( $iaddr === false ) {
390 # Invalid address
391 return false;
392 }
393
394 # Only scan ranges which start in this /16, this improves search speed
395 # Blocks should not cross a /16 boundary.
396 $range = substr( $iaddr, 0, 4 );
397
398 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_SLAVE );
399 $conds = array(
400 'ipb_range_start' . $db->buildLike( $range, $db->anyString() ),
401 "ipb_range_start <= '$iaddr'",
402 "ipb_range_end >= '$iaddr'"
403 );
404
405 if ( $user ) {
406 $conds['ipb_anon_only'] = 0;
407 }
408
409 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__ ) );
410 $success = $this->loadFromResult( $res, $killExpired );
411
412 return $success;
413 }
414
415 /**
416 * Given a database row from the ipblocks table, initialize
417 * member variables
418 *
419 * @param $row ResultWrapper: a row from the ipblocks table
420 */
421 protected function initFromRow( $row ) {
422 list( $this->target, $this->type ) = self::parseTarget( $row->ipb_address );
423
424 $this->setTarget( $row->ipb_address );
425 $this->setBlocker( User::newFromId( $row->ipb_by ) );
426
427 $this->mReason = $row->ipb_reason;
428 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
429 $this->mAuto = $row->ipb_auto;
430 $this->mAnonOnly = $row->ipb_anon_only;
431 $this->mCreateAccount = $row->ipb_create_account;
432 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
433 $this->mBlockEmail = $row->ipb_block_email;
434 $this->mAllowUsertalk = $row->ipb_allow_usertalk;
435 $this->mHideName = $row->ipb_deleted;
436 $this->mId = $row->ipb_id;
437 $this->mExpiry = $row->ipb_expiry;
438 $this->mRangeStart = $row->ipb_range_start;
439 $this->mRangeEnd = $row->ipb_range_end;
440 }
441
442 /**
443 * Create a new Block object from a database row
444 * @param $row ResultWrapper row from the ipblocks table
445 * @return Block
446 */
447 public static function newFromRow( $row ){
448 $block = new Block;
449 $block->initFromRow( $row );
450 return $block;
451 }
452
453 /**
454 * Once $mAddress has been set, get the range they came from.
455 * Wrapper for IP::parseRange
456 */
457 protected function initialiseRange() {
458 $this->mRangeStart = '';
459 $this->mRangeEnd = '';
460
461 if ( $this->mUser == 0 ) {
462 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
463 }
464 }
465
466 /**
467 * Delete the row from the IP blocks table.
468 *
469 * @return Boolean
470 */
471 public function delete() {
472 if ( wfReadOnly() ) {
473 return false;
474 }
475
476 if ( !$this->mId ) {
477 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
478 }
479
480 $dbw = wfGetDB( DB_MASTER );
481 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
482
483 return $dbw->affectedRows() > 0;
484 }
485
486 /**
487 * Insert a block into the block table. Will fail if there is a conflicting
488 * block (same name and options) already in the database.
489 *
490 * @return mixed: false on failure, assoc array on success:
491 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
492 */
493 public function insert( $dbw = null ) {
494 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
495
496 if ( $dbw === null ) {
497 $dbw = wfGetDB( DB_MASTER );
498 }
499
500 $this->validateBlockParams();
501 $this->initialiseRange();
502
503 # Don't collide with expired blocks
504 Block::purgeExpired();
505
506 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
507 $dbw->insert(
508 'ipblocks',
509 array(
510 'ipb_id' => $ipb_id,
511 'ipb_address' => $this->mAddress,
512 'ipb_user' => $this->mUser,
513 'ipb_by' => $this->mBy,
514 'ipb_by_text' => $this->mByName,
515 'ipb_reason' => $this->mReason,
516 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
517 'ipb_auto' => $this->mAuto,
518 'ipb_anon_only' => $this->mAnonOnly,
519 'ipb_create_account' => $this->mCreateAccount,
520 'ipb_enable_autoblock' => $this->mEnableAutoblock,
521 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry ),
522 'ipb_range_start' => $this->mRangeStart,
523 'ipb_range_end' => $this->mRangeEnd,
524 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
525 'ipb_block_email' => $this->mBlockEmail,
526 'ipb_allow_usertalk' => $this->mAllowUsertalk
527 ),
528 'Block::insert',
529 array( 'IGNORE' )
530 );
531 $affected = $dbw->affectedRows();
532
533 if ( $affected ) {
534 $auto_ipd_ids = $this->doRetroactiveAutoblock();
535 return array( 'id' => $ipb_id, 'autoIds' => $auto_ipd_ids );
536 }
537
538 return false;
539 }
540
541 /**
542 * Update a block in the DB with new parameters.
543 * The ID field needs to be loaded first.
544 */
545 public function update() {
546 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
547 $dbw = wfGetDB( DB_MASTER );
548
549 $this->validateBlockParams();
550
551 $dbw->update(
552 'ipblocks',
553 array(
554 'ipb_user' => $this->mUser,
555 'ipb_by' => $this->mBy,
556 'ipb_by_text' => $this->mByName,
557 'ipb_reason' => $this->mReason,
558 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
559 'ipb_auto' => $this->mAuto,
560 'ipb_anon_only' => $this->mAnonOnly,
561 'ipb_create_account' => $this->mCreateAccount,
562 'ipb_enable_autoblock' => $this->mEnableAutoblock,
563 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry ),
564 'ipb_range_start' => $this->mRangeStart,
565 'ipb_range_end' => $this->mRangeEnd,
566 'ipb_deleted' => $this->mHideName,
567 'ipb_block_email' => $this->mBlockEmail,
568 'ipb_allow_usertalk' => $this->mAllowUsertalk
569 ),
570 array( 'ipb_id' => $this->mId ),
571 'Block::update'
572 );
573
574 return $dbw->affectedRows();
575 }
576
577 /**
578 * Make sure all the proper members are set to sane values
579 * before adding/updating a block
580 */
581 protected function validateBlockParams() {
582 # Unset ipb_anon_only for user blocks, makes no sense
583 if ( $this->mUser ) {
584 $this->mAnonOnly = 0;
585 }
586
587 # Unset ipb_enable_autoblock for IP blocks, makes no sense
588 if ( !$this->mUser ) {
589 $this->mEnableAutoblock = 0;
590 }
591
592 # bug 18860: non-anon-only IP blocks should be allowed to block email
593 if ( !$this->mUser && $this->mAnonOnly ) {
594 $this->mBlockEmail = 0;
595 }
596
597 if ( !$this->mByName ) {
598 if ( $this->mBy ) {
599 $this->mByName = User::whoIs( $this->mBy );
600 } else {
601 global $wgUser;
602 $this->mByName = $wgUser->getName();
603 }
604 }
605 }
606
607 /**
608 * Retroactively autoblocks the last IP used by the user (if it is a user)
609 * blocked by this Block.
610 *
611 * @return Array: block IDs of retroactive autoblocks made
612 */
613 protected function doRetroactiveAutoblock() {
614 $blockIds = array();
615
616 $dbr = wfGetDB( DB_SLAVE );
617 # If autoblock is enabled, autoblock the LAST IP used
618 # - stolen shamelessly from CheckUser_body.php
619
620 if ( $this->mEnableAutoblock && $this->mUser ) {
621 wfDebug( "Doing retroactive autoblocks for " . $this->mAddress . "\n" );
622
623 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
624 $conds = array( 'rc_user_text' => $this->mAddress );
625
626 if ( $this->mAngryAutoblock ) {
627 // Block any IP used in the last 7 days. Up to five IPs.
628 $conds[] = 'rc_timestamp < ' .
629 $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
630 $options['LIMIT'] = 5;
631 } else {
632 // Just the last IP used.
633 $options['LIMIT'] = 1;
634 }
635
636 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
637 __METHOD__ , $options );
638
639 if ( !$dbr->numRows( $res ) ) {
640 # No results, don't autoblock anything
641 wfDebug( "No IP found to retroactively autoblock\n" );
642 } else {
643 foreach ( $res as $row ) {
644 if ( $row->rc_ip ) {
645 $id = $this->doAutoblock( $row->rc_ip );
646 if ( $id ) $blockIds[] = $id;
647 }
648 }
649 }
650 }
651 return $blockIds;
652 }
653
654 /**
655 * Checks whether a given IP is on the autoblock whitelist.
656 *
657 * @param $ip String: The IP to check
658 * @return Boolean
659 */
660 public static function isWhitelistedFromAutoblocks( $ip ) {
661 global $wgMemc;
662
663 // Try to get the autoblock_whitelist from the cache, as it's faster
664 // than getting the msg raw and explode()'ing it.
665 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
666 $lines = $wgMemc->get( $key );
667 if ( !$lines ) {
668 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
669 $wgMemc->set( $key, $lines, 3600 * 24 );
670 }
671
672 wfDebug( "Checking the autoblock whitelist..\n" );
673
674 foreach ( $lines as $line ) {
675 # List items only
676 if ( substr( $line, 0, 1 ) !== '*' ) {
677 continue;
678 }
679
680 $wlEntry = substr( $line, 1 );
681 $wlEntry = trim( $wlEntry );
682
683 wfDebug( "Checking $ip against $wlEntry..." );
684
685 # Is the IP in this range?
686 if ( IP::isInRange( $ip, $wlEntry ) ) {
687 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
688 return true;
689 } else {
690 wfDebug( " No match\n" );
691 }
692 }
693
694 return false;
695 }
696
697 /**
698 * Autoblocks the given IP, referring to this Block.
699 *
700 * @param $autoblockIP String: the IP to autoblock.
701 * @param $justInserted Boolean: the main block was just inserted.
702 * @return mixed: block ID if an autoblock was inserted, false if not.
703 */
704 public function doAutoblock( $autoblockIP, $justInserted = false ) {
705 # If autoblocks are disabled, go away.
706 if ( !$this->mEnableAutoblock ) {
707 return false;
708 }
709
710 # Check for presence on the autoblock whitelist
711 if ( Block::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
712 return false;
713 }
714
715 # # Allow hooks to cancel the autoblock.
716 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
717 wfDebug( "Autoblock aborted by hook.\n" );
718 return false;
719 }
720
721 # It's okay to autoblock. Go ahead and create/insert the block.
722
723 $ipblock = Block::newFromTarget( $autoblockIP );
724 if ( $ipblock ) {
725 # If the user is already blocked. Then check if the autoblock would
726 # exceed the user block. If it would exceed, then do nothing, else
727 # prolong block time
728 if ( $this->mExpiry &&
729 ( $this->mExpiry < Block::getAutoblockExpiry( $ipblock->mTimestamp ) )
730 ) {
731 return false;
732 }
733
734 # Just update the timestamp
735 if ( !$justInserted ) {
736 $ipblock->updateTimestamp();
737 }
738
739 return false;
740 } else {
741 $ipblock = new Block;
742 }
743
744 # Make a new block object with the desired properties
745 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
746 $ipblock->mAddress = $autoblockIP;
747 $ipblock->mUser = 0;
748 $ipblock->mBy = $this->mBy;
749 $ipblock->mByName = $this->mByName;
750 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
751 $ipblock->mTimestamp = wfTimestampNow();
752 $ipblock->mAuto = 1;
753 $ipblock->mCreateAccount = $this->mCreateAccount;
754 # Continue suppressing the name if needed
755 $ipblock->mHideName = $this->mHideName;
756 $ipblock->mAllowUsertalk = $this->mAllowUsertalk;
757
758 # If the user is already blocked with an expiry date, we don't
759 # want to pile on top of that!
760 if ( $this->mExpiry ) {
761 $ipblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ) );
762 } else {
763 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
764 }
765
766 # Insert it
767 $status = $ipblock->insert();
768 return $status ? $status['id'] : false;
769 }
770
771 /**
772 * Check if a block has expired. Delete it if it is.
773 * @return Boolean
774 */
775 public function deleteIfExpired() {
776 wfProfileIn( __METHOD__ );
777
778 if ( $this->isExpired() ) {
779 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
780 $this->delete();
781 $retVal = true;
782 } else {
783 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
784 $retVal = false;
785 }
786
787 wfProfileOut( __METHOD__ );
788 return $retVal;
789 }
790
791 /**
792 * Has the block expired?
793 * @return Boolean
794 */
795 public function isExpired() {
796 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
797
798 if ( !$this->mExpiry ) {
799 return false;
800 } else {
801 return wfTimestampNow() > $this->mExpiry;
802 }
803 }
804
805 /**
806 * Is the block address valid (i.e. not a null string?)
807 * @return Boolean
808 */
809 public function isValid() {
810 return $this->mAddress != '';
811 }
812
813 /**
814 * Update the timestamp on autoblocks.
815 */
816 public function updateTimestamp() {
817 if ( $this->mAuto ) {
818 $this->mTimestamp = wfTimestamp();
819 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
820
821 $dbw = wfGetDB( DB_MASTER );
822 $dbw->update( 'ipblocks',
823 array( /* SET */
824 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
825 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
826 ), array( /* WHERE */
827 'ipb_address' => $this->mAddress
828 ), 'Block::updateTimestamp'
829 );
830 }
831 }
832
833 /**
834 * Get the IP address at the start of the range in Hex form
835 * @return String IP in Hex form
836 */
837 public function getRangeStart() {
838 switch( $this->type ) {
839 case self::TYPE_USER:
840 return null;
841 case self::TYPE_IP:
842 return IP::toHex( $this->target );
843 case self::TYPE_RANGE:
844 return $this->mRangeStart;
845 default: throw new MWException( "Block with invalid type" );
846 }
847 }
848
849 /**
850 * Get the IP address at the start of the range in Hex form
851 * @return String IP in Hex form
852 */
853 public function getRangeEnd() {
854 switch( $this->type ) {
855 case self::TYPE_USER:
856 return null;
857 case self::TYPE_IP:
858 return IP::toHex( $this->target );
859 case self::TYPE_RANGE:
860 return $this->mRangeEnd;
861 default: throw new MWException( "Block with invalid type" );
862 }
863 }
864
865 /**
866 * Get the user id of the blocking sysop
867 *
868 * @return Integer
869 */
870 public function getBy() {
871 return $this->mBy;
872 }
873
874 /**
875 * Get the username of the blocking sysop
876 *
877 * @return String
878 */
879 public function getByName() {
880 return $this->mByName;
881 }
882
883 /**
884 * Get the block ID
885 * @return int
886 */
887 public function getId() {
888 return $this->mId;
889 }
890
891 /**
892 * Get/set the SELECT ... FOR UPDATE flag
893 * @deprecated since 1.18
894 */
895 public function forUpdate( $x = null ) {
896 # noop
897 }
898
899 /**
900 * Get/set a flag determining whether the master is used for reads
901 */
902 public function fromMaster( $x = null ) {
903 return wfSetVar( $this->mFromMaster, $x );
904 }
905
906 /**
907 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
908 * @param $x Bool
909 * @return Bool
910 */
911 public function isHardblock( $x = null ) {
912 $y = $this->mAnonOnly;
913 if ( $x !== null ) {
914 $this->mAnonOnly = !$x;
915 }
916 return !$y;
917 }
918
919 public function isAutoblocking( $x = null ) {
920 return wfSetVar( $this->mEnableAutoblock, $x );
921 }
922
923 /**
924 * Get/set whether the Block prevents a given action
925 * @param $action String
926 * @param $x Bool
927 * @return Bool
928 */
929 public function prevents( $action, $x = null ) {
930 switch( $action ) {
931 case 'edit':
932 # For now... <evil laugh>
933 return true;
934
935 case 'createaccount':
936 return wfSetVar( $this->mCreateAccount, $x );
937
938 case 'sendemail':
939 return wfSetVar( $this->mBlockEmail, $x );
940
941 case 'editownusertalk':
942 $y = $this->mAllowUsertalk;
943 if ( $x !== null ) {
944 $this->mAllowUsertalk = !$x;
945 }
946 return !$y;
947
948 default:
949 return null;
950 }
951 }
952
953 /**
954 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
955 * @return String, text is escaped
956 */
957 public function getRedactedName() {
958 if ( $this->mAuto ) {
959 return HTML::rawElement(
960 'span',
961 array( 'class' => 'mw-autoblockid' ),
962 wfMessage( 'autoblockid', $this->mId )
963 );
964 } else {
965 return htmlspecialchars( $this->mAddress );
966 }
967 }
968
969 /**
970 * Encode expiry for DB
971 *
972 * @param $expiry String: timestamp for expiry, or
973 * @param $db Database object
974 * @return String
975 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
976 */
977 public static function encodeExpiry( $expiry, $db ) {
978 return $db->encodeExpiry( $expiry );
979 }
980
981 /**
982 * Decode expiry which has come from the DB
983 *
984 * @param $expiry String: Database expiry format
985 * @param $timestampType Requested timestamp format
986 * @return String
987 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
988 */
989 public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
990 global $wgContLang;
991 return $wgContLang->formatExpiry( $expiry, $timestampType );
992 }
993
994 /**
995 * Get a timestamp of the expiry for autoblocks
996 *
997 * @return String
998 */
999 public static function getAutoblockExpiry( $timestamp ) {
1000 global $wgAutoblockExpiry;
1001
1002 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1003 }
1004
1005 /**
1006 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
1007 * For example, 127.111.113.151/24 -> 127.111.113.0/24
1008 * @param $range String: IP address to normalize
1009 * @return string
1010 * @deprecated since 1.18, call IP::sanitizeRange() directly
1011 */
1012 public static function normaliseRange( $range ) {
1013 return IP::sanitizeRange( $range );
1014 }
1015
1016 /**
1017 * Purge expired blocks from the ipblocks table
1018 */
1019 public static function purgeExpired() {
1020 $dbw = wfGetDB( DB_MASTER );
1021 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
1022 }
1023
1024 /**
1025 * Get a value to insert into expiry field of the database when infinite expiry
1026 * is desired
1027 * @deprecated since 1.18, call $dbr->getInfinity() directly
1028 * @return String
1029 */
1030 public static function infinity() {
1031 return wfGetDB( DB_SLAVE )->getInfinity();
1032 }
1033
1034 /**
1035 * Convert a DB-encoded expiry into a real string that humans can read.
1036 *
1037 * @param $encoded_expiry String: Database encoded expiry time
1038 * @return Html-escaped String
1039 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
1040 */
1041 public static function formatExpiry( $encoded_expiry ) {
1042 global $wgContLang;
1043 static $msg = null;
1044
1045 if ( is_null( $msg ) ) {
1046 $msg = array();
1047 $keys = array( 'infiniteblock', 'expiringblock' );
1048
1049 foreach ( $keys as $key ) {
1050 $msg[$key] = wfMsgHtml( $key );
1051 }
1052 }
1053
1054 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW );
1055 if ( $expiry == wfGetDB( DB_SLAVE )->getInfinity() ) {
1056 $expirystr = $msg['infiniteblock'];
1057 } else {
1058 global $wgLang;
1059 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
1060 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
1061 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
1062 }
1063
1064 return $expirystr;
1065 }
1066
1067 # FIXME: everything above here is a mess, needs much cleaning up
1068
1069 /**
1070 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1071 * ("24 May 2034"), into an absolute timestamp we can put into the database.
1072 * @param $expiry String: whatever was typed into the form
1073 * @return String: timestamp or "infinity" string for th DB implementation
1074 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
1075 */
1076 public static function parseExpiryInput( $expiry ) {
1077 wfDeprecated( __METHOD__ );
1078 return SpecialBlock::parseExpiryInput( $expiry );
1079 }
1080
1081 /**
1082 * Given a target and the target's type, get an existing Block object if possible.
1083 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1084 * * A user to block, in which case $target will be a User
1085 * * An IP to block, in which case $target will be a User generated by using
1086 * User::newFromName( $ip, false ) to turn off name validation
1087 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1088 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1089 * usernames
1090 * Calling this with a user, IP address or range will not select autoblocks, and will
1091 * only select a block where the targets match exactly (so looking for blocks on
1092 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1093 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1094 * affects that target (so for an IP address, get ranges containing that IP; and also
1095 * get any relevant autoblocks)
1096 * @param $fromMaster Bool whether to use the DB_MASTER database
1097 * @return Block|null (null if no relevant block could be found). The target and type
1098 * of the returned Block will refer to the actual block which was found, which might
1099 * not be the same as the target you gave if you used $vagueTarget!
1100 */
1101 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1102 list( $target, $type ) = self::parseTarget( $specificTarget );
1103 if( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ){
1104 return Block::newFromID( $target );
1105
1106 } elseif( $target === null && $vagueTarget === null ){
1107 # We're not going to find anything useful here
1108 return null;
1109
1110 } elseif( in_array( $type, array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ) ) ) {
1111 $block = new Block();
1112 $block->fromMaster( $fromMaster );
1113
1114 if( $type !== null ){
1115 $block->setTarget( $target );
1116 }
1117
1118 if( $block->newLoad( $vagueTarget ) ){
1119 return $block;
1120 } else {
1121 return null;
1122 }
1123 } else {
1124 return null;
1125 }
1126 }
1127
1128 /**
1129 * From an existing Block, get the target and the type of target. Note that it is
1130 * always safe to treat the target as a string; for User objects this will return
1131 * User::__toString() which in turn gives User::getName().
1132 * @return array( User|String, Block::TYPE_ constant )
1133 */
1134 public static function parseTarget( $target ) {
1135 $target = trim( $target );
1136
1137 # We may have been through this before
1138 if( $target instanceof User ){
1139 if( IP::isValid( $target->getName() ) ){
1140 return self::TYPE_IP;
1141 } else {
1142 return self::TYPE_USER;
1143 }
1144 } elseif( $target === null ){
1145 return array( null, null );
1146 }
1147
1148 $userObj = User::newFromName( $target );
1149 if ( $userObj instanceof User ) {
1150 # Note that since numbers are valid usernames, a $target of "12345" will be
1151 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1152 # since hash characters are not valid in usernames or titles generally.
1153 return array( $userObj, Block::TYPE_USER );
1154
1155 } elseif ( IP::isValid( $target ) ) {
1156 # We can still create a User if it's an IP address, but we need to turn
1157 # off validation checking (which would exclude IP addresses)
1158 return array(
1159 User::newFromName( IP::sanitizeIP( $target ), false ),
1160 Block::TYPE_IP
1161 );
1162
1163 } elseif ( IP::isValidBlock( $target ) ) {
1164 # Can't create a User from an IP range
1165 return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
1166
1167 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1168 # Autoblock reference in the form "#12345"
1169 return array( substr( $target, 1 ), Block::TYPE_AUTO );
1170
1171 } else {
1172 # WTF?
1173 return array( null, null );
1174 }
1175 }
1176
1177 /**
1178 * Get the type of target for this particular block
1179 * @return Block::TYPE_ constant, will never be TYPE_ID
1180 */
1181 public function getType() {
1182 return $this->mAuto
1183 ? self::TYPE_AUTO
1184 : $this->type;
1185 }
1186
1187 /**
1188 * Get the target and target type for this particular Block. Note that for autoblocks,
1189 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1190 * in this situation.
1191 * @return array( User|String, Block::TYPE_ constant )
1192 * FIXME: this should be an integral part of the Block member variables
1193 */
1194 public function getTargetAndType() {
1195 return array( $this->getTarget(), $this->getType() );
1196 }
1197
1198 /**
1199 * Get the target for this particular Block. Note that for autoblocks,
1200 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1201 * in this situation.
1202 * @return User|String
1203 */
1204 public function getTarget() {
1205 return $this->target;
1206 }
1207
1208 /**
1209 * Set the target for this block, and update $this->type accordingly
1210 * @param $target Mixed
1211 */
1212 public function setTarget( $target ){
1213 list( $this->target, $this->type ) = self::parseTarget( $target );
1214
1215 $this->mAddress = (string)$this->target;
1216 if( $this->type == self::TYPE_USER ){
1217 if( $this->target instanceof User ){
1218 # Cheat
1219 $this->mUser = $this->target->getID();
1220 } else {
1221 $this->mUser = User::idFromName( $this->target );
1222 }
1223 } else {
1224 $this->mUser = 0;
1225 }
1226 }
1227
1228 /**
1229 * Get the user who implemented this block
1230 * @return User
1231 */
1232 public function getBlocker(){
1233 return $this->blocker;
1234 }
1235
1236 /**
1237 * Set the user who implemented (or will implement) this block
1238 * @param $user User
1239 */
1240 public function setBlocker( User $user ){
1241 $this->blocker = $user;
1242
1243 $this->mBy = $user->getID();
1244 $this->mByName = $user->getName();
1245 }
1246 }