Fatal error: Call to undefined function wfMemc() in includes/Block.php on line 550
[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 */
16 class Block
17 {
18 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
19 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
20 $mBlockEmail, $mByName, $mAngryAutoblock;
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 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
28 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
29 $hideName = 0, $blockEmail = 0 )
30 {
31 $this->mId = 0;
32 # Expand valid IPv6 addresses
33 $address = IP::sanitizeIP( $address );
34 $this->mAddress = $address;
35 $this->mUser = $user;
36 $this->mBy = $by;
37 $this->mReason = $reason;
38 $this->mTimestamp = wfTimestamp(TS_MW,$timestamp);
39 $this->mAuto = $auto;
40 $this->mAnonOnly = $anonOnly;
41 $this->mCreateAccount = $createAccount;
42 $this->mExpiry = self::decodeExpiry( $expiry );
43 $this->mEnableAutoblock = $enableAutoblock;
44 $this->mHideName = $hideName;
45 $this->mBlockEmail = $blockEmail;
46 $this->mForUpdate = false;
47 $this->mFromMaster = false;
48 $this->mByName = false;
49 $this->mAngryAutoblock = false;
50 $this->initialiseRange();
51 }
52
53 /**
54 * Load a block from the database, using either the IP address or
55 * userid.
56 *
57 * @return Block Object
58 * @param $address string IP address of user/anon
59 * @param $user int User id of user
60 * @param $killExpired bool Delete expired blocks on load
61 */
62 static function newFromDB( $address, $user = 0, $killExpired = true )
63 {
64 $block = new Block();
65 $block->load( $address, $user, $killExpired );
66 if ( $block->isValid() ) {
67 return $block;
68 } else {
69 return null;
70 }
71 }
72
73 /**
74 * Load a blocked user from their block id.
75 * @return Block object
76 * @param $id int Block id to search for
77 */
78 static function newFromID( $id )
79 {
80 $dbr = wfGetDB( DB_SLAVE );
81 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
82 array( 'ipb_id' => $id ), __METHOD__ ) );
83 $block = new Block;
84 if ( $block->loadFromResult( $res ) ) {
85 return $block;
86 } else {
87 return null;
88 }
89 }
90
91 /**
92 * Clear all member variables in the current object. Does not clear
93 * the block from the DB.
94 */
95 function clear()
96 {
97 $this->mAddress = $this->mReason = $this->mTimestamp = '';
98 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
99 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
100 $this->mBy = $this->mHideName = $this->mBlockEmail = 0;
101 $this->mByName = false;
102 }
103
104 /**
105 * Get the DB object and set the reference parameter to the query options
106 * @return Database
107 */
108 function &getDBOptions( &$options ) {
109 global $wgAntiLockFlags;
110 if ( $this->mForUpdate || $this->mFromMaster ) {
111 $db = wfGetDB( DB_MASTER );
112 if ( !$this->mForUpdate || ($wgAntiLockFlags & ALF_NO_BLOCK_LOCK) ) {
113 $options = array();
114 } else {
115 $options = array( 'FOR UPDATE' );
116 }
117 } else {
118 $db = wfGetDB( DB_SLAVE );
119 $options = array();
120 }
121 return $db;
122 }
123
124 /**
125 * Get a ban from the DB, with either the given address or the given username
126 *
127 * @param $address string The IP address of the user, or blank to skip IP blocks
128 * @param $user int The user ID, or zero for anonymous users
129 * @param $killExpired bool Whether to delete expired rows while loading
130 *
131 */
132 function load( $address = '', $user = 0, $killExpired = true )
133 {
134 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
135
136 $options = array();
137 $db =& $this->getDBOptions( $options );
138
139 if ( 0 == $user && $address == '' ) {
140 # Invalid user specification, not blocked
141 $this->clear();
142 return false;
143 }
144
145 # Try user block
146 if ( $user ) {
147 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
148 __METHOD__, $options ) );
149 if ( $this->loadFromResult( $res, $killExpired ) ) {
150 return true;
151 }
152 }
153
154 # Try IP block
155 # TODO: improve performance by merging this query with the autoblock one
156 # Slightly tricky while handling killExpired as well
157 if ( $address ) {
158 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
159 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
160 if ( $this->loadFromResult( $res, $killExpired ) ) {
161 if ( $user && $this->mAnonOnly ) {
162 # Block is marked anon-only
163 # Whitelist this IP address against autoblocks and range blocks
164 $this->clear();
165 return false;
166 } else {
167 return true;
168 }
169 }
170 }
171
172 # Try range block
173 if ( $this->loadRange( $address, $killExpired, $user ) ) {
174 if ( $user && $this->mAnonOnly ) {
175 $this->clear();
176 return false;
177 } else {
178 return true;
179 }
180 }
181
182 # Try autoblock
183 if ( $address ) {
184 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
185 if ( $user ) {
186 $conds['ipb_anon_only'] = 0;
187 }
188 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
189 if ( $this->loadFromResult( $res, $killExpired ) ) {
190 return true;
191 }
192 }
193
194 # Give up
195 $this->clear();
196 return false;
197 }
198
199 /**
200 * Fill in member variables from a result wrapper
201 * @return bool
202 * @param $res ResultWrapper Row from the ipblocks table
203 * @param $killExpired bool Whether to delete expired rows while loading
204 */
205 function loadFromResult( ResultWrapper $res, $killExpired = true )
206 {
207 $ret = false;
208 if ( 0 != $res->numRows() ) {
209 # Get first block
210 $row = $res->fetchObject();
211 $this->initFromRow( $row );
212
213 if ( $killExpired ) {
214 # If requested, delete expired rows
215 do {
216 $killed = $this->deleteIfExpired();
217 if ( $killed ) {
218 $row = $res->fetchObject();
219 if ( $row ) {
220 $this->initFromRow( $row );
221 }
222 }
223 } while ( $killed && $row );
224
225 # If there were any left after the killing finished, return true
226 if ( $row ) {
227 $ret = true;
228 }
229 } else {
230 $ret = true;
231 }
232 }
233 $res->free();
234 return $ret;
235 }
236
237 /**
238 * Search the database for any range blocks matching the given address, and
239 * load the row if one is found.
240 * @return bool
241 * @param $address string IP address range
242 * @param $killExpired bool Whether to delete expired rows while loading
243 * @param $userid int If not 0, then sets ipb_anon_only
244 */
245 function loadRange( $address, $killExpired = true, $user = 0 )
246 {
247 $iaddr = IP::toHex( $address );
248 if ( $iaddr === false ) {
249 # Invalid address
250 return false;
251 }
252
253 # Only scan ranges which start in this /16, this improves search speed
254 # Blocks should not cross a /16 boundary.
255 $range = substr( $iaddr, 0, 4 );
256
257 $options = array();
258 $db =& $this->getDBOptions( $options );
259 $conds = array(
260 "ipb_range_start LIKE '$range%'",
261 "ipb_range_start <= '$iaddr'",
262 "ipb_range_end >= '$iaddr'"
263 );
264
265 if ( $user ) {
266 $conds['ipb_anon_only'] = 0;
267 }
268
269 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
270 $success = $this->loadFromResult( $res, $killExpired );
271 return $success;
272 }
273
274 /**
275 * Determine if a given integer IPv4 address is in a given CIDR network
276 * @deprecated Use IP::isInRange
277 */
278 function isAddressInRange( $addr, $range ) {
279 return IP::isInRange( $addr, $range );
280 }
281
282 /**
283 * Given a database row from the ipblocks table, initialize
284 * member variables
285 * @param $row ResultWrapper A row from the ipblocks table
286 */
287 function initFromRow( $row )
288 {
289 $this->mAddress = $row->ipb_address;
290 $this->mReason = $row->ipb_reason;
291 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
292 $this->mUser = $row->ipb_user;
293 $this->mBy = $row->ipb_by;
294 $this->mAuto = $row->ipb_auto;
295 $this->mAnonOnly = $row->ipb_anon_only;
296 $this->mCreateAccount = $row->ipb_create_account;
297 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
298 $this->mBlockEmail = $row->ipb_block_email;
299 $this->mHideName = $row->ipb_deleted;
300 $this->mId = $row->ipb_id;
301 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
302 if ( isset( $row->user_name ) ) {
303 $this->mByName = $row->user_name;
304 } else {
305 $this->mByName = $row->ipb_by_text;
306 }
307 $this->mRangeStart = $row->ipb_range_start;
308 $this->mRangeEnd = $row->ipb_range_end;
309 }
310
311 /**
312 * Once $mAddress has been set, get the range they came from.
313 * Wrapper for IP::parseRange
314 */
315 function initialiseRange()
316 {
317 $this->mRangeStart = '';
318 $this->mRangeEnd = '';
319
320 if ( $this->mUser == 0 ) {
321 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
322 }
323 }
324
325 /**
326 * Callback with a Block object for every block
327 * @return integer number of blocks;
328 */
329 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
330 {
331 global $wgAntiLockFlags;
332
333 $block = new Block();
334 if ( $flags & Block::EB_FOR_UPDATE ) {
335 $db = wfGetDB( DB_MASTER );
336 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) {
337 $options = '';
338 } else {
339 $options = 'FOR UPDATE';
340 }
341 $block->forUpdate( true );
342 } else {
343 $db = wfGetDB( DB_SLAVE );
344 $options = '';
345 }
346 if ( $flags & Block::EB_RANGE_ONLY ) {
347 $cond = " AND ipb_range_start <> ''";
348 } else {
349 $cond = '';
350 }
351
352 $now = wfTimestampNow();
353
354 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
355
356 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
357 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
358 $res = $db->query( $sql, 'Block::enumBlocks' );
359 $num_rows = $db->numRows( $res );
360
361 while ( $row = $db->fetchObject( $res ) ) {
362 $block->initFromRow( $row );
363 if ( ( $flags & Block::EB_RANGE_ONLY ) && $block->mRangeStart == '' ) {
364 continue;
365 }
366
367 if ( !( $flags & Block::EB_KEEP_EXPIRED ) ) {
368 if ( $block->mExpiry && $now > $block->mExpiry ) {
369 $block->delete();
370 } else {
371 call_user_func( $callback, $block, $tag );
372 }
373 } else {
374 call_user_func( $callback, $block, $tag );
375 }
376 }
377 $db->freeResult( $res );
378 return $num_rows;
379 }
380
381 /**
382 * Delete the row from the IP blocks table.
383 * @return bool
384 */
385 function delete()
386 {
387 if (wfReadOnly()) {
388 return false;
389 }
390 if ( !$this->mId ) {
391 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
392 }
393
394 $dbw = wfGetDB( DB_MASTER );
395 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
396 return $dbw->affectedRows() > 0;
397 }
398
399 /**
400 * Insert a block into the block table.
401 * @return bool Whether or not the insertion was successful.
402 */
403 function insert()
404 {
405 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
406 $dbw = wfGetDB( DB_MASTER );
407
408 $this->validateBlockParams();
409
410 # Don't collide with expired blocks
411 Block::purgeExpired();
412
413 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
414 $dbw->insert( 'ipblocks',
415 array(
416 'ipb_id' => $ipb_id,
417 'ipb_address' => $this->mAddress,
418 'ipb_user' => $this->mUser,
419 'ipb_by' => $this->mBy,
420 'ipb_by_text' => $this->mByName,
421 'ipb_reason' => $this->mReason,
422 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
423 'ipb_auto' => $this->mAuto,
424 'ipb_anon_only' => $this->mAnonOnly,
425 'ipb_create_account' => $this->mCreateAccount,
426 'ipb_enable_autoblock' => $this->mEnableAutoblock,
427 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
428 'ipb_range_start' => $this->mRangeStart,
429 'ipb_range_end' => $this->mRangeEnd,
430 'ipb_deleted' => $this->mHideName,
431 'ipb_block_email' => $this->mBlockEmail
432 ), 'Block::insert', array( 'IGNORE' )
433 );
434 $affected = $dbw->affectedRows();
435
436 if ($affected)
437 $this->doRetroactiveAutoblock();
438
439 return $affected;
440 }
441
442 /**
443 * Update block with new parameters.
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( 'ipblocks',
452 array(
453 'ipb_user' => $this->mUser,
454 'ipb_by' => $this->mBy,
455 'ipb_by_text' => $this->mByName,
456 'ipb_reason' => $this->mReason,
457 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
458 'ipb_auto' => $this->mAuto,
459 'ipb_anon_only' => $this->mAnonOnly,
460 'ipb_create_account' => $this->mCreateAccount,
461 'ipb_enable_autoblock' => $this->mEnableAutoblock,
462 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
463 'ipb_range_start' => $this->mRangeStart,
464 'ipb_range_end' => $this->mRangeEnd,
465 'ipb_deleted' => $this->mHideName,
466 'ipb_block_email' => $this->mBlockEmail ),
467 array( 'ipb_id' => $this->mId ),
468 'Block::update' );
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 private 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 $this->mBlockEmail = 0; //Same goes for email...
487 }
488
489 if( !$this->mByName ) {
490 if( $this->mBy ) {
491 $this->mByName = User::whoIs( $this->mBy );
492 } else {
493 global $wgUser;
494 $this->mByName = $wgUser->getName();
495 }
496 }
497 }
498
499
500 /**
501 * Retroactively autoblocks the last IP used by the user (if it is a user)
502 * blocked by this Block.
503 * @return bool Whether or not a retroactive autoblock was made.
504 */
505 function doRetroactiveAutoblock() {
506 $dbr = wfGetDB( DB_SLAVE );
507 #If autoblock is enabled, autoblock the LAST IP used
508 # - stolen shamelessly from CheckUser_body.php
509
510 if ($this->mEnableAutoblock && $this->mUser) {
511 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
512
513 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
514 $conds = array( 'rc_user_text' => $this->mAddress );
515
516 if ($this->mAngryAutoblock) {
517 // Block any IP used in the last 7 days. Up to five IPs.
518 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - (7*86400) ) );
519 $options['LIMIT'] = 5;
520 } else {
521 // Just the last IP used.
522 $options['LIMIT'] = 1;
523 }
524
525 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
526 __METHOD__ , $options);
527
528 if ( !$dbr->numRows( $res ) ) {
529 #No results, don't autoblock anything
530 wfDebug("No IP found to retroactively autoblock\n");
531 } else {
532 while ( $row = $dbr->fetchObject( $res ) ) {
533 if ( $row->rc_ip )
534 $this->doAutoblock( $row->rc_ip );
535 }
536 }
537 }
538 }
539
540 /**
541 * Checks whether a given IP is on the autoblock whitelist.
542 * @return bool
543 * @param string $autoblockip The IP to check
544 */
545 function isWhitelistedFromAutoblocks( $ip ) {
546 global $wgMemc;
547
548 // Try to get the autoblock_whitelist from the cache, as it's faster
549 // than getting the msg raw and explode()'ing it.
550 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
551 $lines = $wgMemc->get( $key );
552 if ( !$lines ) {
553 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
554 $wgMemc->set( $key, $lines, 3600 * 24 );
555 }
556
557 wfDebug("Checking the autoblock whitelist..\n");
558
559 foreach( $lines as $line ) {
560 # List items only
561 if ( substr( $line, 0, 1 ) !== '*' ) {
562 continue;
563 }
564
565 $wlEntry = substr($line, 1);
566 $wlEntry = trim($wlEntry);
567
568 wfDebug("Checking $ip against $wlEntry...");
569
570 # Is the IP in this range?
571 if (IP::isInRange( $ip, $wlEntry )) {
572 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
573 return true;
574 } else {
575 wfDebug( " No match\n" );
576 }
577 }
578
579 return false;
580 }
581
582 /**
583 * Autoblocks the given IP, referring to this Block.
584 * @param string $autoblockip The IP to autoblock.
585 * @param bool $justInserted The main block was just inserted
586 * @return bool Whether or not an autoblock was inserted.
587 */
588 function doAutoblock( $autoblockip, $justInserted = false ) {
589 # If autoblocks are disabled, go away.
590 if ( !$this->mEnableAutoblock ) {
591 return;
592 }
593
594 # Check for presence on the autoblock whitelist
595 if (Block::isWhitelistedFromAutoblocks($autoblockip)) {
596 return;
597 }
598
599 ## Allow hooks to cancel the autoblock.
600 if (!wfRunHooks( 'AbortAutoblock', array( $autoblockip, &$this ) )) {
601 wfDebug( "Autoblock aborted by hook." );
602 return false;
603 }
604
605 # It's okay to autoblock. Go ahead and create/insert the block.
606
607 $ipblock = Block::newFromDB( $autoblockip );
608 if ( $ipblock ) {
609 # If the user is already blocked. Then check if the autoblock would
610 # exceed the user block. If it would exceed, then do nothing, else
611 # prolong block time
612 if ($this->mExpiry &&
613 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
614 return;
615 }
616 # Just update the timestamp
617 if ( !$justInserted ) {
618 $ipblock->updateTimestamp();
619 }
620 return;
621 } else {
622 $ipblock = new Block;
623 }
624
625 # Make a new block object with the desired properties
626 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
627 $ipblock->mAddress = $autoblockip;
628 $ipblock->mUser = 0;
629 $ipblock->mBy = $this->mBy;
630 $ipblock->mByName = $this->mByName;
631 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
632 $ipblock->mTimestamp = wfTimestampNow();
633 $ipblock->mAuto = 1;
634 $ipblock->mCreateAccount = $this->mCreateAccount;
635 # Continue suppressing the name if needed
636 $ipblock->mHideName = $this->mHideName;
637
638 # If the user is already blocked with an expiry date, we don't
639 # want to pile on top of that!
640 if($this->mExpiry) {
641 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
642 } else {
643 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
644 }
645 # Insert it
646 return $ipblock->insert();
647 }
648
649 /**
650 * Check if a block has expired. Delete it if it is.
651 * @return bool
652 */
653 function deleteIfExpired()
654 {
655 $fname = 'Block::deleteIfExpired';
656 wfProfileIn( $fname );
657 if ( $this->isExpired() ) {
658 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
659 $this->delete();
660 $retVal = true;
661 } else {
662 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
663 $retVal = false;
664 }
665 wfProfileOut( $fname );
666 return $retVal;
667 }
668
669 /**
670 * Has the block expired?
671 * @return bool
672 */
673 function isExpired()
674 {
675 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
676 if ( !$this->mExpiry ) {
677 return false;
678 } else {
679 return wfTimestampNow() > $this->mExpiry;
680 }
681 }
682
683 /**
684 * Is the block address valid (i.e. not a null string?)
685 * @return bool
686 */
687 function isValid()
688 {
689 return $this->mAddress != '';
690 }
691
692 /**
693 * Update the timestamp on autoblocks.
694 */
695 function updateTimestamp()
696 {
697 if ( $this->mAuto ) {
698 $this->mTimestamp = wfTimestamp();
699 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
700
701 $dbw = wfGetDB( DB_MASTER );
702 $dbw->update( 'ipblocks',
703 array( /* SET */
704 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
705 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
706 ), array( /* WHERE */
707 'ipb_address' => $this->mAddress
708 ), 'Block::updateTimestamp'
709 );
710 }
711 }
712
713 /*
714 function getIntegerAddr()
715 {
716 return $this->mIntegerAddr;
717 }
718
719 function getNetworkBits()
720 {
721 return $this->mNetworkBits;
722 }*/
723
724 /**
725 * Get the user id of the blocking sysop
726 * @return int
727 */
728 public function getBy() {
729 return $this->mBy;
730 }
731
732 /**
733 * Get the username of the blocking sysop
734 * @return string
735 */
736 function getByName()
737 {
738 return $this->mByName;
739 }
740
741 function forUpdate( $x = NULL ) {
742 return wfSetVar( $this->mForUpdate, $x );
743 }
744
745 function fromMaster( $x = NULL ) {
746 return wfSetVar( $this->mFromMaster, $x );
747 }
748
749 function getRedactedName() {
750 if ( $this->mAuto ) {
751 return '#' . $this->mId;
752 } else {
753 return $this->mAddress;
754 }
755 }
756
757 /**
758 * Encode expiry for DB
759 * @return string
760 * @param $expiry string Timestamp for expiry, or
761 * @param $db Database object
762 */
763 static function encodeExpiry( $expiry, $db ) {
764 if ( $expiry == '' || $expiry == Block::infinity() ) {
765 return Block::infinity();
766 } else {
767 return $db->timestamp( $expiry );
768 }
769 }
770
771 /**
772 * Decode expiry which has come from the DB
773 * @return string
774 * @param $expiry string Database expiry format
775 * @param $timestampType Requested timestamp format
776 */
777 static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
778 if ( $expiry == '' || $expiry == Block::infinity() ) {
779 return Block::infinity();
780 } else {
781 return wfTimestamp( $timestampType, $expiry );
782 }
783 }
784
785 /**
786 * Get a timestamp of the expiry for autoblocks
787 * @return string
788 */
789 static function getAutoblockExpiry( $timestamp )
790 {
791 global $wgAutoblockExpiry;
792 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
793 }
794
795 /**
796 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
797 * For example, 127.111.113.151/24 -> 127.111.113.0/24
798 * @param $range string IP address to normalize
799 * @return string
800 */
801 static function normaliseRange( $range ) {
802 $parts = explode( '/', $range );
803 if ( count( $parts ) == 2 ) {
804 // IPv6
805 if ( IP::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
806 $bits = $parts[1];
807 $ipint = IP::toUnsigned6( $parts[0] );
808 # Native 32 bit functions WONT work here!!!
809 # Convert to a padded binary number
810 $network = wfBaseConvert( $ipint, 10, 2, 128 );
811 # Truncate the last (128-$bits) bits and replace them with zeros
812 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
813 # Convert back to an integer
814 $network = wfBaseConvert( $network, 2, 10 );
815 # Reform octet address
816 $newip = IP::toOctet( $network );
817 $range = "$newip/{$parts[1]}";
818 } // IPv4
819 else if ( IP::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
820 $shift = 32 - $parts[1];
821 $ipint = IP::toUnsigned( $parts[0] );
822 $ipint = $ipint >> $shift << $shift;
823 $newip = long2ip( $ipint );
824 $range = "$newip/{$parts[1]}";
825 }
826 }
827 return $range;
828 }
829
830 /**
831 * Purge expired blocks from the ipblocks table
832 */
833 static function purgeExpired() {
834 $dbw = wfGetDB( DB_MASTER );
835 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
836 }
837
838 /**
839 * This is a special keyword for timestamps in PostgreSQL, and
840 * works with CHAR(14) as well because "i" sorts after all numbers.
841 * @return string
842 */
843 static function infinity() {
844 return 'infinity';
845 }
846
847 /**
848 * Convert a DB-encoded expiry into a real string that humans can read.
849 * @param $encoded_expiry string Database encoded expiry time
850 * @return string
851 */
852 static function formatExpiry( $encoded_expiry ) {
853
854 static $msg = null;
855
856 if( is_null( $msg ) ) {
857 $msg = array();
858 $keys = array( 'infiniteblock', 'expiringblock' );
859 foreach( $keys as $key ) {
860 $msg[$key] = wfMsgHtml( $key );
861 }
862 }
863
864 $expiry = Block::decodeExpiry( $encoded_expiry );
865 if ($expiry == 'infinity') {
866 $expirystr = $msg['infiniteblock'];
867 } else {
868 global $wgLang;
869 $expiretimestr = $wgLang->timeanddate( $expiry, true );
870 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array($expiretimestr) );
871 }
872
873 return $expirystr;
874 }
875
876 /**
877 * Convert a typed-in expiry time into something we can put into the database.
878 * @param $expiry_input string Whatever was typed into the form
879 * @return string More database friendly
880 */
881 static function parseExpiryInput( $expiry_input ) {
882 if ( $expiry_input == 'infinite' || $expiry_input == 'indefinite' ) {
883 $expiry = 'infinity';
884 } else {
885 $expiry = strtotime( $expiry_input );
886 if ($expiry < 0 || $expiry === false) {
887 return false;
888 }
889 }
890
891 return $expiry;
892 }
893
894 }