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