Follow-up r83825: fix Block::parseTarget to recognise autoblocks separately, and...
[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 $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
19 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
20 $mBlockEmail, $mByName, $mAngryAutoblock, $mAllowUsertalk;
21 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
22
23 const EB_KEEP_EXPIRED = 1;
24 const EB_FOR_UPDATE = 2;
25 const EB_RANGE_ONLY = 4;
26
27 const TYPE_USER = 1;
28 const TYPE_IP = 2;
29 const TYPE_RANGE = 3;
30 const TYPE_AUTO = 4;
31 const TYPE_ID = 5;
32
33 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
34 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
35 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byName = false )
36 {
37 $this->mId = 0;
38 # Expand valid IPv6 addresses
39 $address = IP::sanitizeIP( $address );
40 $this->mAddress = $address;
41 $this->mUser = $user;
42 $this->mBy = $by;
43 $this->mReason = $reason;
44 $this->mTimestamp = wfTimestamp( TS_MW, $timestamp );
45 $this->mAuto = $auto;
46 $this->mAnonOnly = $anonOnly;
47 $this->mCreateAccount = $createAccount;
48 $this->mExpiry = self::decodeExpiry( $expiry );
49 $this->mEnableAutoblock = $enableAutoblock;
50 $this->mHideName = $hideName;
51 $this->mBlockEmail = $blockEmail;
52 $this->mAllowUsertalk = $allowUsertalk;
53 $this->mForUpdate = false;
54 $this->mFromMaster = false;
55 $this->mByName = $byName;
56 $this->mAngryAutoblock = false;
57 $this->initialiseRange();
58 }
59
60 /**
61 * Load a block from the database, using either the IP address or
62 * user ID. Tries the user ID first, and if that doesn't work, tries
63 * the address.
64 *
65 * @param $address String: IP address of user/anon
66 * @param $user Integer: user id of user
67 * @param $killExpired Boolean: delete expired blocks on load
68 * @return Block Object
69 */
70 public static function newFromDB( $address, $user = 0, $killExpired = true ) {
71 $block = new Block;
72 $block->load( $address, $user, $killExpired );
73 if ( $block->isValid() ) {
74 return $block;
75 } else {
76 return null;
77 }
78 }
79
80 /**
81 * Load a blocked user from their block id.
82 *
83 * @param $id Integer: Block id to search for
84 * @return Block object
85 */
86 public static function newFromID( $id ) {
87 $dbr = wfGetDB( DB_SLAVE );
88 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
89 array( 'ipb_id' => $id ), __METHOD__ ) );
90 $block = new Block;
91
92 if ( $block->loadFromResult( $res ) ) {
93 return $block;
94 } else {
95 return null;
96 }
97 }
98
99 /**
100 * Check if two blocks are effectively equal
101 *
102 * @return Boolean
103 */
104 public function equals( Block $block ) {
105 return (
106 $this->mAddress == $block->mAddress
107 && $this->mUser == $block->mUser
108 && $this->mAuto == $block->mAuto
109 && $this->mAnonOnly == $block->mAnonOnly
110 && $this->mCreateAccount == $block->mCreateAccount
111 && $this->mExpiry == $block->mExpiry
112 && $this->mEnableAutoblock == $block->mEnableAutoblock
113 && $this->mHideName == $block->mHideName
114 && $this->mBlockEmail == $block->mBlockEmail
115 && $this->mAllowUsertalk == $block->mAllowUsertalk
116 && $this->mReason == $block->mReason
117 );
118 }
119
120 /**
121 * Clear all member variables in the current object. Does not clear
122 * the block from the DB.
123 */
124 public function clear() {
125 $this->mAddress = $this->mReason = $this->mTimestamp = '';
126 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
127 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
128 $this->mBy = $this->mHideName = $this->mBlockEmail = $this->mAllowUsertalk = 0;
129 $this->mByName = false;
130 }
131
132 /**
133 * Get the DB object and set the reference parameter to the select options.
134 * The options array will contain FOR UPDATE if appropriate.
135 *
136 * @param $options Array
137 * @return Database
138 */
139 protected function &getDBOptions( &$options ) {
140 global $wgAntiLockFlags;
141
142 if ( $this->mForUpdate || $this->mFromMaster ) {
143 $db = wfGetDB( DB_MASTER );
144 if ( !$this->mForUpdate || ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) ) {
145 $options = array();
146 } else {
147 $options = array( 'FOR UPDATE' );
148 }
149 } else {
150 $db = wfGetDB( DB_SLAVE );
151 $options = array();
152 }
153
154 return $db;
155 }
156
157 /**
158 * Get a block from the DB, with either the given address or the given username
159 *
160 * @param $address string The IP address of the user, or blank to skip IP blocks
161 * @param $user int The user ID, or zero for anonymous users
162 * @param $killExpired bool Whether to delete expired rows while loading
163 * @return Boolean: the user is blocked from editing
164 *
165 */
166 public function load( $address = '', $user = 0, $killExpired = true ) {
167 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
168
169 $options = array();
170 $db = $this->getDBOptions( $options );
171
172 if ( 0 == $user && $address === '' ) {
173 # Invalid user specification, not blocked
174 $this->clear();
175
176 return false;
177 }
178
179 # Try user block
180 if ( $user ) {
181 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
182 __METHOD__, $options ) );
183
184 if ( $this->loadFromResult( $res, $killExpired ) ) {
185 return true;
186 }
187 }
188
189 # Try IP block
190 # TODO: improve performance by merging this query with the autoblock one
191 # Slightly tricky while handling killExpired as well
192 if ( $address !== '' ) {
193 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
194 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
195
196 if ( $this->loadFromResult( $res, $killExpired ) ) {
197 if ( $user && $this->mAnonOnly ) {
198 # Block is marked anon-only
199 # Whitelist this IP address against autoblocks and range blocks
200 # (but not account creation blocks -- bug 13611)
201 if ( !$this->mCreateAccount ) {
202 $this->clear();
203 }
204
205 return false;
206 } else {
207 return true;
208 }
209 }
210 }
211
212 # Try range block
213 if ( $this->loadRange( $address, $killExpired, $user ) ) {
214 if ( $user && $this->mAnonOnly ) {
215 # Respect account creation blocks on logged-in users -- bug 13611
216 if ( !$this->mCreateAccount ) {
217 $this->clear();
218 }
219
220 return false;
221 } else {
222 return true;
223 }
224 }
225
226 # Try autoblock
227 if ( $address ) {
228 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
229
230 if ( $user ) {
231 $conds['ipb_anon_only'] = 0;
232 }
233
234 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
235
236 if ( $this->loadFromResult( $res, $killExpired ) ) {
237 return true;
238 }
239 }
240
241 # Give up
242 $this->clear();
243 return false;
244 }
245
246 /**
247 * Fill in member variables from a result wrapper
248 *
249 * @param $res ResultWrapper: row from the ipblocks table
250 * @param $killExpired Boolean: whether to delete expired rows while loading
251 * @return Boolean
252 */
253 protected function loadFromResult( ResultWrapper $res, $killExpired = true ) {
254 $ret = false;
255
256 if ( 0 != $res->numRows() ) {
257 # Get first block
258 $row = $res->fetchObject();
259 $this->initFromRow( $row );
260
261 if ( $killExpired ) {
262 # If requested, delete expired rows
263 do {
264 $killed = $this->deleteIfExpired();
265 if ( $killed ) {
266 $row = $res->fetchObject();
267 if ( $row ) {
268 $this->initFromRow( $row );
269 }
270 }
271 } while ( $killed && $row );
272
273 # If there were any left after the killing finished, return true
274 if ( $row ) {
275 $ret = true;
276 }
277 } else {
278 $ret = true;
279 }
280 }
281 $res->free();
282
283 return $ret;
284 }
285
286 /**
287 * Search the database for any range blocks matching the given address, and
288 * load the row if one is found.
289 *
290 * @param $address String: IP address range
291 * @param $killExpired Boolean: whether to delete expired rows while loading
292 * @param $user Integer: if not 0, then sets ipb_anon_only
293 * @return Boolean
294 */
295 public function loadRange( $address, $killExpired = true, $user = 0 ) {
296 $iaddr = IP::toHex( $address );
297
298 if ( $iaddr === false ) {
299 # Invalid address
300 return false;
301 }
302
303 # Only scan ranges which start in this /16, this improves search speed
304 # Blocks should not cross a /16 boundary.
305 $range = substr( $iaddr, 0, 4 );
306
307 $options = array();
308 $db = $this->getDBOptions( $options );
309 $conds = array(
310 'ipb_range_start' . $db->buildLike( $range, $db->anyString() ),
311 "ipb_range_start <= '$iaddr'",
312 "ipb_range_end >= '$iaddr'"
313 );
314
315 if ( $user ) {
316 $conds['ipb_anon_only'] = 0;
317 }
318
319 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
320 $success = $this->loadFromResult( $res, $killExpired );
321
322 return $success;
323 }
324
325 /**
326 * Given a database row from the ipblocks table, initialize
327 * member variables
328 *
329 * @param $row ResultWrapper: a row from the ipblocks table
330 */
331 public function initFromRow( $row ) {
332 $this->mAddress = $row->ipb_address;
333 $this->mReason = $row->ipb_reason;
334 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
335 $this->mUser = $row->ipb_user;
336 $this->mBy = $row->ipb_by;
337 $this->mAuto = $row->ipb_auto;
338 $this->mAnonOnly = $row->ipb_anon_only;
339 $this->mCreateAccount = $row->ipb_create_account;
340 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
341 $this->mBlockEmail = $row->ipb_block_email;
342 $this->mAllowUsertalk = $row->ipb_allow_usertalk;
343 $this->mHideName = $row->ipb_deleted;
344 $this->mId = $row->ipb_id;
345 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
346
347 if ( isset( $row->user_name ) ) {
348 $this->mByName = $row->user_name;
349 } else {
350 $this->mByName = $row->ipb_by_text;
351 }
352
353 $this->mRangeStart = $row->ipb_range_start;
354 $this->mRangeEnd = $row->ipb_range_end;
355 }
356
357 /**
358 * Once $mAddress has been set, get the range they came from.
359 * Wrapper for IP::parseRange
360 */
361 protected function initialiseRange() {
362 $this->mRangeStart = '';
363 $this->mRangeEnd = '';
364
365 if ( $this->mUser == 0 ) {
366 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
367 }
368 }
369
370 /**
371 * Delete the row from the IP blocks table.
372 *
373 * @return Boolean
374 */
375 public function delete() {
376 if ( wfReadOnly() ) {
377 return false;
378 }
379
380 if ( !$this->mId ) {
381 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
382 }
383
384 $dbw = wfGetDB( DB_MASTER );
385 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
386
387 return $dbw->affectedRows() > 0;
388 }
389
390 /**
391 * Insert a block into the block table. Will fail if there is a conflicting
392 * block (same name and options) already in the database.
393 *
394 * @return Boolean: whether or not the insertion was successful.
395 */
396 public function insert( $dbw = null ) {
397 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
398
399 if ( $dbw === null )
400 $dbw = wfGetDB( DB_MASTER );
401
402 $this->validateBlockParams();
403 $this->initialiseRange();
404
405 # Don't collide with expired blocks
406 Block::purgeExpired();
407
408 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
409 $dbw->insert(
410 'ipblocks',
411 array(
412 'ipb_id' => $ipb_id,
413 'ipb_address' => $this->mAddress,
414 'ipb_user' => $this->mUser,
415 'ipb_by' => $this->mBy,
416 'ipb_by_text' => $this->mByName,
417 'ipb_reason' => $this->mReason,
418 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
419 'ipb_auto' => $this->mAuto,
420 'ipb_anon_only' => $this->mAnonOnly,
421 'ipb_create_account' => $this->mCreateAccount,
422 'ipb_enable_autoblock' => $this->mEnableAutoblock,
423 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
424 'ipb_range_start' => $this->mRangeStart,
425 'ipb_range_end' => $this->mRangeEnd,
426 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
427 'ipb_block_email' => $this->mBlockEmail,
428 'ipb_allow_usertalk' => $this->mAllowUsertalk
429 ),
430 'Block::insert',
431 array( 'IGNORE' )
432 );
433 $affected = $dbw->affectedRows();
434
435 if ( $affected )
436 $this->doRetroactiveAutoblock();
437
438 return (bool)$affected;
439 }
440
441 /**
442 * Update a block in the DB with new parameters.
443 * The ID field needs to be loaded first.
444 */
445 public function update() {
446 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
447 $dbw = wfGetDB( DB_MASTER );
448
449 $this->validateBlockParams();
450
451 $dbw->update(
452 'ipblocks',
453 array(
454 'ipb_user' => $this->mUser,
455 'ipb_by' => $this->mBy,
456 'ipb_by_text' => $this->mByName,
457 'ipb_reason' => $this->mReason,
458 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
459 'ipb_auto' => $this->mAuto,
460 'ipb_anon_only' => $this->mAnonOnly,
461 'ipb_create_account' => $this->mCreateAccount,
462 'ipb_enable_autoblock' => $this->mEnableAutoblock,
463 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
464 'ipb_range_start' => $this->mRangeStart,
465 'ipb_range_end' => $this->mRangeEnd,
466 'ipb_deleted' => $this->mHideName,
467 'ipb_block_email' => $this->mBlockEmail,
468 'ipb_allow_usertalk' => $this->mAllowUsertalk
469 ),
470 array( 'ipb_id' => $this->mId ),
471 'Block::update'
472 );
473
474 return $dbw->affectedRows();
475 }
476
477 /**
478 * Make sure all the proper members are set to sane values
479 * before adding/updating a block
480 */
481 protected function validateBlockParams() {
482 # Unset ipb_anon_only for user blocks, makes no sense
483 if ( $this->mUser ) {
484 $this->mAnonOnly = 0;
485 }
486
487 # Unset ipb_enable_autoblock for IP blocks, makes no sense
488 if ( !$this->mUser ) {
489 $this->mEnableAutoblock = 0;
490 }
491
492 # bug 18860: non-anon-only IP blocks should be allowed to block email
493 if ( !$this->mUser && $this->mAnonOnly ) {
494 $this->mBlockEmail = 0;
495 }
496
497 if ( !$this->mByName ) {
498 if ( $this->mBy ) {
499 $this->mByName = User::whoIs( $this->mBy );
500 } else {
501 global $wgUser;
502 $this->mByName = $wgUser->getName();
503 }
504 }
505 }
506
507 /**
508 * Retroactively autoblocks the last IP used by the user (if it is a user)
509 * blocked by this Block.
510 *
511 * @return Boolean: whether or not a retroactive autoblock was made.
512 */
513 public function doRetroactiveAutoblock() {
514 $dbr = wfGetDB( DB_SLAVE );
515 # If autoblock is enabled, autoblock the LAST IP used
516 # - stolen shamelessly from CheckUser_body.php
517
518 if ( $this->mEnableAutoblock && $this->mUser ) {
519 wfDebug( "Doing retroactive autoblocks for " . $this->mAddress . "\n" );
520
521 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
522 $conds = array( 'rc_user_text' => $this->mAddress );
523
524 if ( $this->mAngryAutoblock ) {
525 // Block any IP used in the last 7 days. Up to five IPs.
526 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
527 $options['LIMIT'] = 5;
528 } else {
529 // Just the last IP used.
530 $options['LIMIT'] = 1;
531 }
532
533 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
534 __METHOD__ , $options );
535
536 if ( !$dbr->numRows( $res ) ) {
537 # No results, don't autoblock anything
538 wfDebug( "No IP found to retroactively autoblock\n" );
539 } else {
540 foreach ( $res as $row ) {
541 if ( $row->rc_ip ) {
542 $this->doAutoblock( $row->rc_ip );
543 }
544 }
545 }
546 }
547 }
548
549 /**
550 * Checks whether a given IP is on the autoblock whitelist.
551 *
552 * @param $ip String: The IP to check
553 * @return Boolean
554 */
555 public static function isWhitelistedFromAutoblocks( $ip ) {
556 global $wgMemc;
557
558 // Try to get the autoblock_whitelist from the cache, as it's faster
559 // than getting the msg raw and explode()'ing it.
560 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
561 $lines = $wgMemc->get( $key );
562 if ( !$lines ) {
563 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
564 $wgMemc->set( $key, $lines, 3600 * 24 );
565 }
566
567 wfDebug( "Checking the autoblock whitelist..\n" );
568
569 foreach ( $lines as $line ) {
570 # List items only
571 if ( substr( $line, 0, 1 ) !== '*' ) {
572 continue;
573 }
574
575 $wlEntry = substr( $line, 1 );
576 $wlEntry = trim( $wlEntry );
577
578 wfDebug( "Checking $ip against $wlEntry..." );
579
580 # Is the IP in this range?
581 if ( IP::isInRange( $ip, $wlEntry ) ) {
582 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
583 return true;
584 } else {
585 wfDebug( " No match\n" );
586 }
587 }
588
589 return false;
590 }
591
592 /**
593 * Autoblocks the given IP, referring to this Block.
594 *
595 * @param $autoblockIP String: the IP to autoblock.
596 * @param $justInserted Boolean: the main block was just inserted
597 * @return Boolean: whether or not an autoblock was inserted.
598 */
599 public function doAutoblock( $autoblockIP, $justInserted = false ) {
600 # If autoblocks are disabled, go away.
601 if ( !$this->mEnableAutoblock ) {
602 return;
603 }
604
605 # Check for presence on the autoblock whitelist
606 if ( Block::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
607 return;
608 }
609
610 # # Allow hooks to cancel the autoblock.
611 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
612 wfDebug( "Autoblock aborted by hook.\n" );
613 return false;
614 }
615
616 # It's okay to autoblock. Go ahead and create/insert the block.
617
618 $ipblock = Block::newFromDB( $autoblockIP );
619 if ( $ipblock ) {
620 # If the user is already blocked. Then check if the autoblock would
621 # exceed the user block. If it would exceed, then do nothing, else
622 # prolong block time
623 if ( $this->mExpiry &&
624 ( $this->mExpiry < Block::getAutoblockExpiry( $ipblock->mTimestamp ) )
625 ) {
626 return;
627 }
628
629 # Just update the timestamp
630 if ( !$justInserted ) {
631 $ipblock->updateTimestamp();
632 }
633
634 return;
635 } else {
636 $ipblock = new Block;
637 }
638
639 # Make a new block object with the desired properties
640 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
641 $ipblock->mAddress = $autoblockIP;
642 $ipblock->mUser = 0;
643 $ipblock->mBy = $this->mBy;
644 $ipblock->mByName = $this->mByName;
645 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
646 $ipblock->mTimestamp = wfTimestampNow();
647 $ipblock->mAuto = 1;
648 $ipblock->mCreateAccount = $this->mCreateAccount;
649 # Continue suppressing the name if needed
650 $ipblock->mHideName = $this->mHideName;
651 $ipblock->mAllowUsertalk = $this->mAllowUsertalk;
652
653 # If the user is already blocked with an expiry date, we don't
654 # want to pile on top of that!
655 if ( $this->mExpiry ) {
656 $ipblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ) );
657 } else {
658 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
659 }
660
661 # Insert it
662 return $ipblock->insert();
663 }
664
665 /**
666 * Check if a block has expired. Delete it if it is.
667 * @return Boolean
668 */
669 public function deleteIfExpired() {
670 wfProfileIn( __METHOD__ );
671
672 if ( $this->isExpired() ) {
673 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
674 $this->delete();
675 $retVal = true;
676 } else {
677 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
678 $retVal = false;
679 }
680
681 wfProfileOut( __METHOD__ );
682 return $retVal;
683 }
684
685 /**
686 * Has the block expired?
687 * @return Boolean
688 */
689 public function isExpired() {
690 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
691
692 if ( !$this->mExpiry ) {
693 return false;
694 } else {
695 return wfTimestampNow() > $this->mExpiry;
696 }
697 }
698
699 /**
700 * Is the block address valid (i.e. not a null string?)
701 * @return Boolean
702 */
703 public function isValid() {
704 return $this->mAddress != '';
705 }
706
707 /**
708 * Update the timestamp on autoblocks.
709 */
710 public function updateTimestamp() {
711 if ( $this->mAuto ) {
712 $this->mTimestamp = wfTimestamp();
713 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
714
715 $dbw = wfGetDB( DB_MASTER );
716 $dbw->update( 'ipblocks',
717 array( /* SET */
718 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
719 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
720 ), array( /* WHERE */
721 'ipb_address' => $this->mAddress
722 ), 'Block::updateTimestamp'
723 );
724 }
725 }
726
727 /**
728 * Get the user id of the blocking sysop
729 *
730 * @return Integer
731 */
732 public function getBy() {
733 return $this->mBy;
734 }
735
736 /**
737 * Get the username of the blocking sysop
738 *
739 * @return String
740 */
741 public function getByName() {
742 return $this->mByName;
743 }
744
745 /**
746 * Get/set the SELECT ... FOR UPDATE flag
747 */
748 public function forUpdate( $x = null ) {
749 return wfSetVar( $this->mForUpdate, $x );
750 }
751
752 /**
753 * Get/set a flag determining whether the master is used for reads
754 */
755 public function fromMaster( $x = null ) {
756 return wfSetVar( $this->mFromMaster, $x );
757 }
758
759 /**
760 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
761 * @return String, text is escaped
762 */
763 public function getRedactedName() {
764 if ( $this->mAuto ) {
765 return HTML::rawElement(
766 'span',
767 array( 'class' => 'mw-autoblockid' ),
768 wfMessage( 'autoblockid', $this->mId )
769 );
770 } else {
771 return htmlspecialchars( $this->mAddress );
772 }
773 }
774
775 /**
776 * Encode expiry for DB
777 *
778 * @param $expiry String: timestamp for expiry, or
779 * @param $db Database object
780 * @return String
781 */
782 public static function encodeExpiry( $expiry, $db ) {
783 if ( $expiry == '' || $expiry == Block::infinity() ) {
784 return Block::infinity();
785 } else {
786 return $db->timestamp( $expiry );
787 }
788 }
789
790 /**
791 * Decode expiry which has come from the DB
792 *
793 * @param $expiry String: Database expiry format
794 * @param $timestampType Requested timestamp format
795 * @return String
796 */
797 public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
798 if ( $expiry == '' || $expiry == Block::infinity() ) {
799 return Block::infinity();
800 } else {
801 return wfTimestamp( $timestampType, $expiry );
802 }
803 }
804
805 /**
806 * Get a timestamp of the expiry for autoblocks
807 *
808 * @return String
809 */
810 public static function getAutoblockExpiry( $timestamp ) {
811 global $wgAutoblockExpiry;
812
813 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
814 }
815
816 /**
817 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
818 * For example, 127.111.113.151/24 -> 127.111.113.0/24
819 * @param $range String: IP address to normalize
820 * @return string
821 */
822 public static function normaliseRange( $range ) {
823 $parts = explode( '/', $range );
824 if ( count( $parts ) == 2 ) {
825 // IPv6
826 if ( IP::isIPv6( $range ) && $parts[1] >= 64 && $parts[1] <= 128 ) {
827 $bits = $parts[1];
828 $ipint = IP::toUnsigned( $parts[0] );
829 # Native 32 bit functions WON'T work here!!!
830 # Convert to a padded binary number
831 $network = wfBaseConvert( $ipint, 10, 2, 128 );
832 # Truncate the last (128-$bits) bits and replace them with zeros
833 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
834 # Convert back to an integer
835 $network = wfBaseConvert( $network, 2, 10 );
836 # Reform octet address
837 $newip = IP::toOctet( $network );
838 $range = "$newip/{$parts[1]}";
839 } // IPv4
840 elseif ( IP::isIPv4( $range ) && $parts[1] >= 16 && $parts[1] <= 32 ) {
841 $shift = 32 - $parts[1];
842 $ipint = IP::toUnsigned( $parts[0] );
843 $ipint = $ipint >> $shift << $shift;
844 $newip = long2ip( $ipint );
845 $range = "$newip/{$parts[1]}";
846 }
847 }
848
849 return $range;
850 }
851
852 /**
853 * Purge expired blocks from the ipblocks table
854 */
855 public static function purgeExpired() {
856 $dbw = wfGetDB( DB_MASTER );
857 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
858 }
859
860 /**
861 * Get a value to insert into expiry field of the database when infinite expiry
862 * is desired
863 *
864 * @return String
865 */
866 public static function infinity() {
867 return wfGetDB( DB_SLAVE )->getInfinity();
868 }
869
870 /**
871 * Convert a DB-encoded expiry into a real string that humans can read.
872 *
873 * @param $encoded_expiry String: Database encoded expiry time
874 * @return Html-escaped String
875 */
876 public static function formatExpiry( $encoded_expiry ) {
877 static $msg = null;
878
879 if ( is_null( $msg ) ) {
880 $msg = array();
881 $keys = array( 'infiniteblock', 'expiringblock' );
882
883 foreach ( $keys as $key ) {
884 $msg[$key] = wfMsgHtml( $key );
885 }
886 }
887
888 $expiry = Block::decodeExpiry( $encoded_expiry );
889 if ( $expiry == 'infinity' ) {
890 $expirystr = $msg['infiniteblock'];
891 } else {
892 global $wgLang;
893 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
894 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
895 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
896 }
897
898 return $expirystr;
899 }
900
901 /**
902 * Convert a typed-in expiry time into something we can put into the database.
903 * @param $expiry_input String: whatever was typed into the form
904 * @return String: more database friendly
905 */
906 public static function parseExpiryInput( $expiry_input ) {
907 if ( $expiry_input == 'infinite' || $expiry_input == 'indefinite' ) {
908 $expiry = 'infinity';
909 } else {
910 $expiry = strtotime( $expiry_input );
911
912 if ( $expiry < 0 || $expiry === false ) {
913 return false;
914 }
915 }
916
917 return $expiry;
918 }
919
920 # FIXME: everything above here is a mess, needs much cleaning up
921
922 /**
923 * Given a target and the target's type, get a Block object if possible
924 * @param $target String|User|Int a block target, which may be one of several types:
925 * * A user to block, in which case $target will be a User
926 * * An IP to block, in which case $target will be a User generated by using
927 * User::newFromName( $ip, false ) to turn off name validation
928 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
929 * * The ID of an existing block, in which case $target will be an Int
930 * @param $type Block::TYPE_ constant the type of block as described above
931 * @return Block|null (null if the target is not blocked)
932 */
933 public static function newFromTargetAndType( $target, $type ){
934 if( $target instanceof User ){
935 if( $type == Block::TYPE_IP ){
936 return Block::newFromDB( $target->getName(), 0 );
937 } elseif( $type == Block::TYPE_USER ) {
938 return Block::newFromDB( '', $target->getId() );
939 } else {
940 # Should be unreachable;
941 return null;
942 }
943
944 } elseif( $type == Block::TYPE_RANGE ){
945 return Block::newFromDB( '', $target );
946
947 } elseif( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ){
948 return Block::newFromID( $target );
949
950 } else {
951 return null;
952 }
953 }
954
955 public static function newFromTarget( $target ){
956 list( $target, $type ) = self::parseTarget( $target );
957 return self::newFromTargetAndType( $target, $type );
958 }
959
960 /**
961 * From an existing Block, get the target and the type of target. Note that it is
962 * always safe to treat the target as a string; for User objects this will return
963 * User::__toString() which in turn gives User::getName().
964 * @return array( User|String, Block::TYPE_ constant )
965 */
966 public static function parseTarget( $target ){
967 $target = trim( $target );
968
969 $userObj = User::newFromName( $target );
970 if( $userObj instanceof User ){
971 return array( $userObj, Block::TYPE_USER );
972
973 } elseif( IP::isValid( $target ) ){
974 # We can still create a User if it's an IP address, but we need to turn
975 # off validation checking (which would exclude IP addresses)
976 return array(
977 User::newFromName( IP::sanitizeIP( $target ), false ),
978 Block::TYPE_IP
979 );
980
981 } elseif( IP::isValidBlock( $target ) ){
982 # Can't create a User from an IP range
983 return array( Block::normaliseRange( $target ), Block::TYPE_RANGE );
984
985 } elseif( preg_match( '/^#\d+$/', $target ) ){
986 # Autoblock reference in the form "#12345"
987 return array( substr( $target, 1 ), Block::TYPE_AUTO );
988
989 } elseif( preg_match( '/^\d+$/', $target ) ){
990 # Block id reference as a pure number
991 return array( $target, Block::TYPE_ID );
992 }
993 }
994
995 /**
996 * Get the target and target type for this particular Block. Note that for autoblocks,
997 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
998 * in this situation.
999 * @return array( User|String, Block::TYPE_ constant )
1000 * FIXME: this should be an integral part of the Block member variables
1001 */
1002 public function getTargetAndType(){
1003 list( $target, $type ) = self::parseTarget( $this->mAddress );
1004
1005 # Check whether it's an autoblock
1006 if( $type == self::TYPE_ID && $this->mAuto ){
1007 $type = self::TYPE_AUTO;
1008 }
1009
1010 return array( $target, $type );
1011 }
1012 }