Relate block log entries to block table rows (useful for bug 25763)
[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, 'autoId' => autoblock ID or false)
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 $this->validateBlockParams();
500 $this->initialiseRange();
501
502 # Don't collide with expired blocks
503 Block::purgeExpired();
504
505 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
506 $dbw->insert(
507 'ipblocks',
508 array(
509 'ipb_id' => $ipb_id,
510 'ipb_address' => $this->mAddress,
511 'ipb_user' => $this->mUser,
512 'ipb_by' => $this->mBy,
513 'ipb_by_text' => $this->mByName,
514 'ipb_reason' => $this->mReason,
515 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
516 'ipb_auto' => $this->mAuto,
517 'ipb_anon_only' => $this->mAnonOnly,
518 'ipb_create_account' => $this->mCreateAccount,
519 'ipb_enable_autoblock' => $this->mEnableAutoblock,
520 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry ),
521 'ipb_range_start' => $this->mRangeStart,
522 'ipb_range_end' => $this->mRangeEnd,
523 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
524 'ipb_block_email' => $this->mBlockEmail,
525 'ipb_allow_usertalk' => $this->mAllowUsertalk
526 ),
527 'Block::insert',
528 array( 'IGNORE' )
529 );
530 $affected = $dbw->affectedRows();
531
532 if ( $affected ) {
533 $auto_ipd_id = $this->doRetroactiveAutoblock();
534 return array( 'id' => $ipb_id, 'autoId' => $auto_ipd_id );
535 }
536
537 return false;
538 }
539
540 /**
541 * Update a block in the DB with new parameters.
542 * The ID field needs to be loaded first.
543 */
544 public function update() {
545 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
546 $dbw = wfGetDB( DB_MASTER );
547
548 $this->validateBlockParams();
549
550 $dbw->update(
551 'ipblocks',
552 array(
553 'ipb_user' => $this->mUser,
554 'ipb_by' => $this->mBy,
555 'ipb_by_text' => $this->mByName,
556 'ipb_reason' => $this->mReason,
557 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
558 'ipb_auto' => $this->mAuto,
559 'ipb_anon_only' => $this->mAnonOnly,
560 'ipb_create_account' => $this->mCreateAccount,
561 'ipb_enable_autoblock' => $this->mEnableAutoblock,
562 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry ),
563 'ipb_range_start' => $this->mRangeStart,
564 'ipb_range_end' => $this->mRangeEnd,
565 'ipb_deleted' => $this->mHideName,
566 'ipb_block_email' => $this->mBlockEmail,
567 'ipb_allow_usertalk' => $this->mAllowUsertalk
568 ),
569 array( 'ipb_id' => $this->mId ),
570 'Block::update'
571 );
572
573 return $dbw->affectedRows();
574 }
575
576 /**
577 * Make sure all the proper members are set to sane values
578 * before adding/updating a block
579 */
580 protected function validateBlockParams() {
581 # Unset ipb_anon_only for user blocks, makes no sense
582 if ( $this->mUser ) {
583 $this->mAnonOnly = 0;
584 }
585
586 # Unset ipb_enable_autoblock for IP blocks, makes no sense
587 if ( !$this->mUser ) {
588 $this->mEnableAutoblock = 0;
589 }
590
591 # bug 18860: non-anon-only IP blocks should be allowed to block email
592 if ( !$this->mUser && $this->mAnonOnly ) {
593 $this->mBlockEmail = 0;
594 }
595
596 if ( !$this->mByName ) {
597 if ( $this->mBy ) {
598 $this->mByName = User::whoIs( $this->mBy );
599 } else {
600 global $wgUser;
601 $this->mByName = $wgUser->getName();
602 }
603 }
604 }
605
606 /**
607 * Retroactively autoblocks the last IP used by the user (if it is a user)
608 * blocked by this Block.
609 *
610 * @return mixed: block ID if a retroactive autoblock was made, false if not.
611 */
612 protected function doRetroactiveAutoblock() {
613 $dbr = wfGetDB( DB_SLAVE );
614 # If autoblock is enabled, autoblock the LAST IP used
615 # - stolen shamelessly from CheckUser_body.php
616
617 if ( $this->mEnableAutoblock && $this->mUser ) {
618 wfDebug( "Doing retroactive autoblocks for " . $this->mAddress . "\n" );
619
620 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
621 $conds = array( 'rc_user_text' => $this->mAddress );
622
623 if ( $this->mAngryAutoblock ) {
624 // Block any IP used in the last 7 days. Up to five IPs.
625 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
626 $options['LIMIT'] = 5;
627 } else {
628 // Just the last IP used.
629 $options['LIMIT'] = 1;
630 }
631
632 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
633 __METHOD__ , $options );
634
635 if ( !$dbr->numRows( $res ) ) {
636 # No results, don't autoblock anything
637 wfDebug( "No IP found to retroactively autoblock\n" );
638 } else {
639 foreach ( $res as $row ) {
640 if ( $row->rc_ip ) {
641 return $this->doAutoblock( $row->rc_ip );
642 }
643 }
644 }
645 }
646 return false;
647 }
648
649 /**
650 * Checks whether a given IP is on the autoblock whitelist.
651 *
652 * @param $ip String: The IP to check
653 * @return Boolean
654 */
655 public static function isWhitelistedFromAutoblocks( $ip ) {
656 global $wgMemc;
657
658 // Try to get the autoblock_whitelist from the cache, as it's faster
659 // than getting the msg raw and explode()'ing it.
660 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
661 $lines = $wgMemc->get( $key );
662 if ( !$lines ) {
663 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
664 $wgMemc->set( $key, $lines, 3600 * 24 );
665 }
666
667 wfDebug( "Checking the autoblock whitelist..\n" );
668
669 foreach ( $lines as $line ) {
670 # List items only
671 if ( substr( $line, 0, 1 ) !== '*' ) {
672 continue;
673 }
674
675 $wlEntry = substr( $line, 1 );
676 $wlEntry = trim( $wlEntry );
677
678 wfDebug( "Checking $ip against $wlEntry..." );
679
680 # Is the IP in this range?
681 if ( IP::isInRange( $ip, $wlEntry ) ) {
682 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
683 return true;
684 } else {
685 wfDebug( " No match\n" );
686 }
687 }
688
689 return false;
690 }
691
692 /**
693 * Autoblocks the given IP, referring to this Block.
694 *
695 * @param $autoblockIP String: the IP to autoblock.
696 * @param $justInserted Boolean: the main block was just inserted.
697 * @return mixed: block ID if an autoblock was inserted, false if not.
698 */
699 public function doAutoblock( $autoblockIP, $justInserted = false ) {
700 # If autoblocks are disabled, go away.
701 if ( !$this->mEnableAutoblock ) {
702 return false;
703 }
704
705 # Check for presence on the autoblock whitelist
706 if ( Block::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
707 return false;
708 }
709
710 # # Allow hooks to cancel the autoblock.
711 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
712 wfDebug( "Autoblock aborted by hook.\n" );
713 return false;
714 }
715
716 # It's okay to autoblock. Go ahead and create/insert the block.
717
718 $ipblock = Block::newFromTarget( $autoblockIP );
719 if ( $ipblock ) {
720 # If the user is already blocked. Then check if the autoblock would
721 # exceed the user block. If it would exceed, then do nothing, else
722 # prolong block time
723 if ( $this->mExpiry &&
724 ( $this->mExpiry < Block::getAutoblockExpiry( $ipblock->mTimestamp ) )
725 ) {
726 return false;
727 }
728
729 # Just update the timestamp
730 if ( !$justInserted ) {
731 $ipblock->updateTimestamp();
732 }
733
734 return false;
735 } else {
736 $ipblock = new Block;
737 }
738
739 # Make a new block object with the desired properties
740 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
741 $ipblock->mAddress = $autoblockIP;
742 $ipblock->mUser = 0;
743 $ipblock->mBy = $this->mBy;
744 $ipblock->mByName = $this->mByName;
745 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
746 $ipblock->mTimestamp = wfTimestampNow();
747 $ipblock->mAuto = 1;
748 $ipblock->mCreateAccount = $this->mCreateAccount;
749 # Continue suppressing the name if needed
750 $ipblock->mHideName = $this->mHideName;
751 $ipblock->mAllowUsertalk = $this->mAllowUsertalk;
752
753 # If the user is already blocked with an expiry date, we don't
754 # want to pile on top of that!
755 if ( $this->mExpiry ) {
756 $ipblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ) );
757 } else {
758 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
759 }
760
761 # Insert it
762 $status = $ipblock->insert();
763 return $status ? $status['id'] : false;
764 }
765
766 /**
767 * Check if a block has expired. Delete it if it is.
768 * @return Boolean
769 */
770 public function deleteIfExpired() {
771 wfProfileIn( __METHOD__ );
772
773 if ( $this->isExpired() ) {
774 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
775 $this->delete();
776 $retVal = true;
777 } else {
778 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
779 $retVal = false;
780 }
781
782 wfProfileOut( __METHOD__ );
783 return $retVal;
784 }
785
786 /**
787 * Has the block expired?
788 * @return Boolean
789 */
790 public function isExpired() {
791 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
792
793 if ( !$this->mExpiry ) {
794 return false;
795 } else {
796 return wfTimestampNow() > $this->mExpiry;
797 }
798 }
799
800 /**
801 * Is the block address valid (i.e. not a null string?)
802 * @return Boolean
803 */
804 public function isValid() {
805 return $this->mAddress != '';
806 }
807
808 /**
809 * Update the timestamp on autoblocks.
810 */
811 public function updateTimestamp() {
812 if ( $this->mAuto ) {
813 $this->mTimestamp = wfTimestamp();
814 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
815
816 $dbw = wfGetDB( DB_MASTER );
817 $dbw->update( 'ipblocks',
818 array( /* SET */
819 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
820 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
821 ), array( /* WHERE */
822 'ipb_address' => $this->mAddress
823 ), 'Block::updateTimestamp'
824 );
825 }
826 }
827
828 /**
829 * Get the IP address at the start of the range in Hex form
830 * @return String IP in Hex form
831 */
832 public function getRangeStart() {
833 switch( $this->type ) {
834 case self::TYPE_USER:
835 return null;
836 case self::TYPE_IP:
837 return IP::toHex( $this->target );
838 case self::TYPE_RANGE:
839 return $this->mRangeStart;
840 default: throw new MWException( "Block with invalid type" );
841 }
842 }
843
844 /**
845 * Get the IP address at the start of the range in Hex form
846 * @return String IP in Hex form
847 */
848 public function getRangeEnd() {
849 switch( $this->type ) {
850 case self::TYPE_USER:
851 return null;
852 case self::TYPE_IP:
853 return IP::toHex( $this->target );
854 case self::TYPE_RANGE:
855 return $this->mRangeEnd;
856 default: throw new MWException( "Block with invalid type" );
857 }
858 }
859
860 /**
861 * Get the user id of the blocking sysop
862 *
863 * @return Integer
864 */
865 public function getBy() {
866 return $this->mBy;
867 }
868
869 /**
870 * Get the username of the blocking sysop
871 *
872 * @return String
873 */
874 public function getByName() {
875 return $this->mByName;
876 }
877
878 /**
879 * Get the block ID
880 * @return int
881 */
882 public function getId() {
883 return $this->mId;
884 }
885
886 /**
887 * Get/set the SELECT ... FOR UPDATE flag
888 * @deprecated since 1.18
889 */
890 public function forUpdate( $x = null ) {
891 # noop
892 }
893
894 /**
895 * Get/set a flag determining whether the master is used for reads
896 */
897 public function fromMaster( $x = null ) {
898 return wfSetVar( $this->mFromMaster, $x );
899 }
900
901 /**
902 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
903 * @param $x Bool
904 * @return Bool
905 */
906 public function isHardblock( $x = null ) {
907 $y = $this->mAnonOnly;
908 if ( $x !== null ) {
909 $this->mAnonOnly = !$x;
910 }
911 return !$y;
912 }
913
914 public function isAutoblocking( $x = null ) {
915 return wfSetVar( $this->mEnableAutoblock, $x );
916 }
917
918 /**
919 * Get/set whether the Block prevents a given action
920 * @param $action String
921 * @param $x Bool
922 * @return Bool
923 */
924 public function prevents( $action, $x = null ) {
925 switch( $action ) {
926 case 'edit':
927 # For now... <evil laugh>
928 return true;
929
930 case 'createaccount':
931 return wfSetVar( $this->mCreateAccount, $x );
932
933 case 'sendemail':
934 return wfSetVar( $this->mBlockEmail, $x );
935
936 case 'editownusertalk':
937 $y = $this->mAllowUsertalk;
938 if ( $x !== null ) {
939 $this->mAllowUsertalk = !$x;
940 }
941 return !$y;
942
943 default:
944 return null;
945 }
946 }
947
948 /**
949 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
950 * @return String, text is escaped
951 */
952 public function getRedactedName() {
953 if ( $this->mAuto ) {
954 return HTML::rawElement(
955 'span',
956 array( 'class' => 'mw-autoblockid' ),
957 wfMessage( 'autoblockid', $this->mId )
958 );
959 } else {
960 return htmlspecialchars( $this->mAddress );
961 }
962 }
963
964 /**
965 * Encode expiry for DB
966 *
967 * @param $expiry String: timestamp for expiry, or
968 * @param $db Database object
969 * @return String
970 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
971 */
972 public static function encodeExpiry( $expiry, $db ) {
973 return $db->encodeExpiry( $expiry );
974 }
975
976 /**
977 * Decode expiry which has come from the DB
978 *
979 * @param $expiry String: Database expiry format
980 * @param $timestampType Requested timestamp format
981 * @return String
982 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
983 */
984 public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
985 global $wgContLang;
986 return $wgContLang->formatExpiry( $expiry, $timestampType );
987 }
988
989 /**
990 * Get a timestamp of the expiry for autoblocks
991 *
992 * @return String
993 */
994 public static function getAutoblockExpiry( $timestamp ) {
995 global $wgAutoblockExpiry;
996
997 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
998 }
999
1000 /**
1001 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
1002 * For example, 127.111.113.151/24 -> 127.111.113.0/24
1003 * @param $range String: IP address to normalize
1004 * @return string
1005 * @deprecated since 1.18, call IP::sanitizeRange() directly
1006 */
1007 public static function normaliseRange( $range ) {
1008 return IP::sanitizeRange( $range );
1009 }
1010
1011 /**
1012 * Purge expired blocks from the ipblocks table
1013 */
1014 public static function purgeExpired() {
1015 $dbw = wfGetDB( DB_MASTER );
1016 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
1017 }
1018
1019 /**
1020 * Get a value to insert into expiry field of the database when infinite expiry
1021 * is desired
1022 * @deprecated since 1.18, call $dbr->getInfinity() directly
1023 * @return String
1024 */
1025 public static function infinity() {
1026 return wfGetDB( DB_SLAVE )->getInfinity();
1027 }
1028
1029 /**
1030 * Convert a DB-encoded expiry into a real string that humans can read.
1031 *
1032 * @param $encoded_expiry String: Database encoded expiry time
1033 * @return Html-escaped String
1034 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
1035 */
1036 public static function formatExpiry( $encoded_expiry ) {
1037 global $wgContLang;
1038 static $msg = null;
1039
1040 if ( is_null( $msg ) ) {
1041 $msg = array();
1042 $keys = array( 'infiniteblock', 'expiringblock' );
1043
1044 foreach ( $keys as $key ) {
1045 $msg[$key] = wfMsgHtml( $key );
1046 }
1047 }
1048
1049 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW );
1050 if ( $expiry == wfGetDB( DB_SLAVE )->getInfinity() ) {
1051 $expirystr = $msg['infiniteblock'];
1052 } else {
1053 global $wgLang;
1054 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
1055 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
1056 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
1057 }
1058
1059 return $expirystr;
1060 }
1061
1062 # FIXME: everything above here is a mess, needs much cleaning up
1063
1064 /**
1065 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1066 * ("24 May 2034"), into an absolute timestamp we can put into the database.
1067 * @param $expiry String: whatever was typed into the form
1068 * @return String: timestamp or "infinity" string for th DB implementation
1069 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
1070 */
1071 public static function parseExpiryInput( $expiry ) {
1072 wfDeprecated( __METHOD__ );
1073 return SpecialBlock::parseExpiryInput( $expiry );
1074 }
1075
1076 /**
1077 * Given a target and the target's type, get an existing Block object if possible.
1078 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1079 * * A user to block, in which case $target will be a User
1080 * * An IP to block, in which case $target will be a User generated by using
1081 * User::newFromName( $ip, false ) to turn off name validation
1082 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1083 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1084 * usernames
1085 * Calling this with a user, IP address or range will not select autoblocks, and will
1086 * only select a block where the targets match exactly (so looking for blocks on
1087 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1088 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1089 * affects that target (so for an IP address, get ranges containing that IP; and also
1090 * get any relevant autoblocks)
1091 * @param $fromMaster Bool whether to use the DB_MASTER database
1092 * @return Block|null (null if no relevant block could be found). The target and type
1093 * of the returned Block will refer to the actual block which was found, which might
1094 * not be the same as the target you gave if you used $vagueTarget!
1095 */
1096 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1097 list( $target, $type ) = self::parseTarget( $specificTarget );
1098 if( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ){
1099 return Block::newFromID( $target );
1100
1101 } elseif( in_array( $type, array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ) ) ) {
1102 $block = new Block();
1103 $block->fromMaster( $fromMaster );
1104
1105 if( $type !== null ){
1106 $block->setTarget( $target );
1107 }
1108
1109 if( $block->newLoad( $vagueTarget ) ){
1110 return $block;
1111 } else {
1112 return null;
1113 }
1114 } else {
1115 return null;
1116 }
1117 }
1118
1119 /**
1120 * From an existing Block, get the target and the type of target. Note that it is
1121 * always safe to treat the target as a string; for User objects this will return
1122 * User::__toString() which in turn gives User::getName().
1123 * @return array( User|String, Block::TYPE_ constant )
1124 */
1125 public static function parseTarget( $target ) {
1126 $target = trim( $target );
1127
1128 # We may have been through this before
1129 if( $target instanceof User ){
1130 if( IP::isValid( $target->getName() ) ){
1131 return self::TYPE_IP;
1132 } else {
1133 return self::TYPE_USER;
1134 }
1135 } elseif( $target === null ){
1136 return array( null, null );
1137 }
1138
1139 $userObj = User::newFromName( $target );
1140 if ( $userObj instanceof User ) {
1141 # Note that since numbers are valid usernames, a $target of "12345" will be
1142 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1143 # since hash characters are not valid in usernames or titles generally.
1144 return array( $userObj, Block::TYPE_USER );
1145
1146 } elseif ( IP::isValid( $target ) ) {
1147 # We can still create a User if it's an IP address, but we need to turn
1148 # off validation checking (which would exclude IP addresses)
1149 return array(
1150 User::newFromName( IP::sanitizeIP( $target ), false ),
1151 Block::TYPE_IP
1152 );
1153
1154 } elseif ( IP::isValidBlock( $target ) ) {
1155 # Can't create a User from an IP range
1156 return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
1157
1158 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1159 # Autoblock reference in the form "#12345"
1160 return array( substr( $target, 1 ), Block::TYPE_AUTO );
1161
1162 } else {
1163 # WTF?
1164 return array( null, null );
1165 }
1166 }
1167
1168 /**
1169 * Get the type of target for this particular block
1170 * @return Block::TYPE_ constant, will never be TYPE_ID
1171 */
1172 public function getType() {
1173 return $this->mAuto
1174 ? self::TYPE_AUTO
1175 : $this->type;
1176 }
1177
1178 /**
1179 * Get the target and target type for this particular Block. Note that for autoblocks,
1180 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1181 * in this situation.
1182 * @return array( User|String, Block::TYPE_ constant )
1183 * FIXME: this should be an integral part of the Block member variables
1184 */
1185 public function getTargetAndType() {
1186 return array( $this->getTarget(), $this->getType() );
1187 }
1188
1189 /**
1190 * Get the target for this particular Block. Note that for autoblocks,
1191 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1192 * in this situation.
1193 * @return User|String
1194 */
1195 public function getTarget() {
1196 return $this->target;
1197 }
1198
1199 /**
1200 * Set the target for this block, and update $this->type accordingly
1201 * @param $target Mixed
1202 */
1203 public function setTarget( $target ){
1204 list( $this->target, $this->type ) = self::parseTarget( $target );
1205
1206 $this->mAddress = (string)$this->target;
1207 if( $this->type == self::TYPE_USER ){
1208 if( $this->target instanceof User ){
1209 # Cheat
1210 $this->mUser = $this->target->getID();
1211 } else {
1212 $this->mUser = User::idFromName( $this->target );
1213 }
1214 } else {
1215 $this->mUser = 0;
1216 }
1217 }
1218
1219 /**
1220 * Get the user who implemented this block
1221 * @return User
1222 */
1223 public function getBlocker(){
1224 return $this->blocker;
1225 }
1226
1227 /**
1228 * Set the user who implemented (or will implement) this block
1229 * @param $user User
1230 */
1231 public function setBlocker( User $user ){
1232 $this->blocker = $user;
1233
1234 $this->mBy = $user->getID();
1235 $this->mByName = $user->getName();
1236 }
1237 }