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