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