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