Fixed dependencies for jquery.collapsibleTabs
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * Blocks and bans object
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22 class Block {
23 /* public*/ var $mReason, $mTimestamp, $mAuto, $mExpiry, $mHideName;
24
25 protected
26 $mId,
27 $mFromMaster,
28
29 $mBlockEmail,
30 $mDisableUsertalk,
31 $mCreateAccount,
32 $mParentBlockId;
33
34 /// @var User|String
35 protected $target;
36
37 // @var Integer Hack for foreign blocking (CentralAuth)
38 protected $forcedTargetID;
39
40 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
41 protected $type;
42
43 /// @var User
44 protected $blocker;
45
46 /// @var Bool
47 protected $isHardblock = true;
48
49 /// @var Bool
50 protected $isAutoblocking = true;
51
52 # TYPE constants
53 const TYPE_USER = 1;
54 const TYPE_IP = 2;
55 const TYPE_RANGE = 3;
56 const TYPE_AUTO = 4;
57 const TYPE_ID = 5;
58
59 /**
60 * Constructor
61 * @todo FIXME: Don't know what the best format to have for this constructor is, but fourteen
62 * optional parameters certainly isn't it.
63 */
64 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
65 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
66 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byText = '' )
67 {
68 if( $timestamp === 0 ){
69 $timestamp = wfTimestampNow();
70 }
71
72 if( count( func_get_args() ) > 0 ){
73 # Soon... :D
74 # wfDeprecated( __METHOD__ . " with arguments" );
75 }
76
77 $this->setTarget( $address );
78 if ( $this->target instanceof User && $user ) {
79 $this->forcedTargetID = $user; // needed for foreign users
80 }
81 if ( $by ) { // local user
82 $this->setBlocker( User::newFromID( $by ) );
83 } else { // foreign user
84 $this->setBlocker( $byText );
85 }
86 $this->mReason = $reason;
87 $this->mTimestamp = wfTimestamp( TS_MW, $timestamp );
88 $this->mAuto = $auto;
89 $this->isHardblock( !$anonOnly );
90 $this->prevents( 'createaccount', $createAccount );
91 if ( $expiry == 'infinity' || $expiry == wfGetDB( DB_SLAVE )->getInfinity() ) {
92 $this->mExpiry = 'infinity';
93 } else {
94 $this->mExpiry = wfTimestamp( TS_MW, $expiry );
95 }
96 $this->isAutoblocking( $enableAutoblock );
97 $this->mHideName = $hideName;
98 $this->prevents( 'sendemail', $blockEmail );
99 $this->prevents( 'editownusertalk', !$allowUsertalk );
100
101 $this->mFromMaster = false;
102 }
103
104 /**
105 * Load a block from the database, using either the IP address or
106 * user ID. Tries the user ID first, and if that doesn't work, tries
107 * the address.
108 *
109 * @param $address String: IP address of user/anon
110 * @param $user Integer: user id of user
111 * @return Block Object
112 * @deprecated since 1.18
113 */
114 public static function newFromDB( $address, $user = 0 ) {
115 wfDeprecated( __METHOD__, '1.18' );
116 return self::newFromTarget( User::whoIs( $user ), $address );
117 }
118
119 /**
120 * Load a blocked user from their block id.
121 *
122 * @param $id Integer: Block id to search for
123 * @return Block object or null
124 */
125 public static function newFromID( $id ) {
126 $dbr = wfGetDB( DB_SLAVE );
127 $res = $dbr->selectRow(
128 'ipblocks',
129 self::selectFields(),
130 array( 'ipb_id' => $id ),
131 __METHOD__
132 );
133 if ( $res ) {
134 return self::newFromRow( $res );
135 } else {
136 return null;
137 }
138 }
139
140 /**
141 * Return the list of ipblocks fields that should be selected to create
142 * a new block.
143 * @return array
144 */
145 public static function selectFields() {
146 return array(
147 'ipb_id',
148 'ipb_address',
149 'ipb_by',
150 'ipb_by_text',
151 'ipb_reason',
152 'ipb_timestamp',
153 'ipb_auto',
154 'ipb_anon_only',
155 'ipb_create_account',
156 'ipb_enable_autoblock',
157 'ipb_expiry',
158 'ipb_deleted',
159 'ipb_block_email',
160 'ipb_allow_usertalk',
161 'ipb_parent_block_id',
162 );
163 }
164
165 /**
166 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
167 * the blocking user or the block timestamp, only things which affect the blocked user *
168 *
169 * @param $block Block
170 *
171 * @return bool
172 */
173 public function equals( Block $block ) {
174 return (
175 (string)$this->target == (string)$block->target
176 && $this->type == $block->type
177 && $this->mAuto == $block->mAuto
178 && $this->isHardblock() == $block->isHardblock()
179 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
180 && $this->mExpiry == $block->mExpiry
181 && $this->isAutoblocking() == $block->isAutoblocking()
182 && $this->mHideName == $block->mHideName
183 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
184 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
185 && $this->mReason == $block->mReason
186 );
187 }
188
189 /**
190 * Clear all member variables in the current object. Does not clear
191 * the block from the DB.
192 * @deprecated since 1.18
193 */
194 public function clear() {
195 wfDeprecated( __METHOD__, '1.18' );
196 # Noop
197 }
198
199 /**
200 * Get a block from the DB, with either the given address or the given username
201 *
202 * @param $address string The IP address of the user, or blank to skip IP blocks
203 * @param $user int The user ID, or zero for anonymous users
204 * @return Boolean: the user is blocked from editing
205 * @deprecated since 1.18
206 */
207 public function load( $address = '', $user = 0 ) {
208 wfDeprecated( __METHOD__, '1.18' );
209 if( $user ){
210 $username = User::whoIs( $user );
211 $block = self::newFromTarget( $username, $address );
212 } else {
213 $block = self::newFromTarget( null, $address );
214 }
215
216 if( $block instanceof Block ){
217 # This is mildly evil, but hey, it's B/C :D
218 foreach( $block as $variable => $value ){
219 $this->$variable = $value;
220 }
221 return true;
222 } else {
223 return false;
224 }
225 }
226
227 /**
228 * Load a block from the database which affects the already-set $this->target:
229 * 1) A block directly on the given user or IP
230 * 2) A rangeblock encompasing the given IP (smallest first)
231 * 3) An autoblock on the given IP
232 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
233 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
234 * @return Bool whether a relevant block was found
235 */
236 protected function newLoad( $vagueTarget = null ) {
237 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_SLAVE );
238
239 if( $this->type !== null ){
240 $conds = array(
241 'ipb_address' => array( (string)$this->target ),
242 );
243 } else {
244 $conds = array( 'ipb_address' => array() );
245 }
246
247 # Be aware that the != '' check is explicit, since empty values will be
248 # passed by some callers (bug 29116)
249 if( $vagueTarget != ''){
250 list( $target, $type ) = self::parseTarget( $vagueTarget );
251 switch( $type ) {
252 case self::TYPE_USER:
253 # Slightly wierd, but who are we to argue?
254 $conds['ipb_address'][] = (string)$target;
255 break;
256
257 case self::TYPE_IP:
258 $conds['ipb_address'][] = (string)$target;
259 $conds[] = self::getRangeCond( IP::toHex( $target ) );
260 $conds = $db->makeList( $conds, LIST_OR );
261 break;
262
263 case self::TYPE_RANGE:
264 list( $start, $end ) = IP::parseRange( $target );
265 $conds['ipb_address'][] = (string)$target;
266 $conds[] = self::getRangeCond( $start, $end );
267 $conds = $db->makeList( $conds, LIST_OR );
268 break;
269
270 default:
271 throw new MWException( "Tried to load block with invalid type" );
272 }
273 }
274
275 $res = $db->select( 'ipblocks', self::selectFields(), $conds, __METHOD__ );
276
277 # This result could contain a block on the user, a block on the IP, and a russian-doll
278 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
279 $bestRow = null;
280
281 # Lower will be better
282 $bestBlockScore = 100;
283
284 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
285 $bestBlockPreventsEdit = null;
286
287 foreach( $res as $row ){
288 $block = self::newFromRow( $row );
289
290 # Don't use expired blocks
291 if( $block->deleteIfExpired() ){
292 continue;
293 }
294
295 # Don't use anon only blocks on users
296 if( $this->type == self::TYPE_USER && !$block->isHardblock() ){
297 continue;
298 }
299
300 if( $block->getType() == self::TYPE_RANGE ){
301 # This is the number of bits that are allowed to vary in the block, give
302 # or take some floating point errors
303 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
304 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
305 $size = log( $end - $start + 1, 2 );
306
307 # This has the nice property that a /32 block is ranked equally with a
308 # single-IP block, which is exactly what it is...
309 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
310
311 } else {
312 $score = $block->getType();
313 }
314
315 if( $score < $bestBlockScore ){
316 $bestBlockScore = $score;
317 $bestRow = $row;
318 $bestBlockPreventsEdit = $block->prevents( 'edit' );
319 }
320 }
321
322 if( $bestRow !== null ){
323 $this->initFromRow( $bestRow );
324 $this->prevents( 'edit', $bestBlockPreventsEdit );
325 return true;
326 } else {
327 return false;
328 }
329 }
330
331 /**
332 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
333 * @param $start String Hexadecimal IP representation
334 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
335 * @return String
336 */
337 public static function getRangeCond( $start, $end = null ) {
338 if ( $end === null ) {
339 $end = $start;
340 }
341 # Per bug 14634, we want to include relevant active rangeblocks; for
342 # rangeblocks, we want to include larger ranges which enclose the given
343 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
344 # so we can improve performance by filtering on a LIKE clause
345 $chunk = self::getIpFragment( $start );
346 $dbr = wfGetDB( DB_SLAVE );
347 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
348
349 # Fairly hard to make a malicious SQL statement out of hex characters,
350 # but stranger things have happened...
351 $safeStart = $dbr->addQuotes( $start );
352 $safeEnd = $dbr->addQuotes( $end );
353
354 return $dbr->makeList(
355 array(
356 "ipb_range_start $like",
357 "ipb_range_start <= $safeStart",
358 "ipb_range_end >= $safeEnd",
359 ),
360 LIST_AND
361 );
362 }
363
364 /**
365 * Get the component of an IP address which is certain to be the same between an IP
366 * address and a rangeblock containing that IP address.
367 * @param $hex String Hexadecimal IP representation
368 * @return String
369 */
370 protected static function getIpFragment( $hex ) {
371 global $wgBlockCIDRLimit;
372 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
373 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
374 } else {
375 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
376 }
377 }
378
379 /**
380 * Given a database row from the ipblocks table, initialize
381 * member variables
382 * @param $row ResultWrapper: a row from the ipblocks table
383 */
384 protected function initFromRow( $row ) {
385 $this->setTarget( $row->ipb_address );
386 if ( $row->ipb_by ) { // local user
387 $this->setBlocker( User::newFromID( $row->ipb_by ) );
388 } else { // foreign user
389 $this->setBlocker( $row->ipb_by_text );
390 }
391
392 $this->mReason = $row->ipb_reason;
393 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
394 $this->mAuto = $row->ipb_auto;
395 $this->mHideName = $row->ipb_deleted;
396 $this->mId = $row->ipb_id;
397 $this->mParentBlockId = $row->ipb_parent_block_id;
398
399 // I wish I didn't have to do this
400 $db = wfGetDB( DB_SLAVE );
401 if ( $row->ipb_expiry == $db->getInfinity() ) {
402 $this->mExpiry = 'infinity';
403 } else {
404 $this->mExpiry = wfTimestamp( TS_MW, $row->ipb_expiry );
405 }
406
407 $this->isHardblock( !$row->ipb_anon_only );
408 $this->isAutoblocking( $row->ipb_enable_autoblock );
409
410 $this->prevents( 'createaccount', $row->ipb_create_account );
411 $this->prevents( 'sendemail', $row->ipb_block_email );
412 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
413 }
414
415 /**
416 * Create a new Block object from a database row
417 * @param $row ResultWrapper row from the ipblocks table
418 * @return Block
419 */
420 public static function newFromRow( $row ){
421 $block = new Block;
422 $block->initFromRow( $row );
423 return $block;
424 }
425
426 /**
427 * Delete the row from the IP blocks table.
428 *
429 * @return Boolean
430 */
431 public function delete() {
432 if ( wfReadOnly() ) {
433 return false;
434 }
435
436 if ( !$this->getId() ) {
437 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
438 }
439
440 $dbw = wfGetDB( DB_MASTER );
441 $dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__ );
442 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__ );
443
444 return $dbw->affectedRows() > 0;
445 }
446
447 /**
448 * Insert a block into the block table. Will fail if there is a conflicting
449 * block (same name and options) already in the database.
450 *
451 * @param $dbw DatabaseBase if you have one available
452 * @return mixed: false on failure, assoc array on success:
453 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
454 */
455 public function insert( $dbw = null ) {
456 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
457
458 if ( $dbw === null ) {
459 $dbw = wfGetDB( DB_MASTER );
460 }
461
462 # Don't collide with expired blocks
463 Block::purgeExpired();
464
465 $row = $this->getDatabaseArray();
466 $row['ipb_id'] = $dbw->nextSequenceValue("ipblocks_ipb_id_seq");
467
468 $dbw->insert(
469 'ipblocks',
470 $row,
471 __METHOD__,
472 array( 'IGNORE' )
473 );
474 $affected = $dbw->affectedRows();
475 $this->mId = $dbw->insertId();
476
477 if ( $affected ) {
478 $auto_ipd_ids = $this->doRetroactiveAutoblock();
479 return array( 'id' => $this->mId, 'autoIds' => $auto_ipd_ids );
480 }
481
482 return false;
483 }
484
485 /**
486 * Update a block in the DB with new parameters.
487 * The ID field needs to be loaded first.
488 *
489 * @return Int number of affected rows, which should probably be 1 or something's
490 * gone slightly awry
491 */
492 public function update() {
493 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
494 $dbw = wfGetDB( DB_MASTER );
495
496 $dbw->update(
497 'ipblocks',
498 $this->getDatabaseArray( $dbw ),
499 array( 'ipb_id' => $this->getId() ),
500 __METHOD__
501 );
502
503 return $dbw->affectedRows();
504 }
505
506 /**
507 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
508 * @param $db DatabaseBase
509 * @return Array
510 */
511 protected function getDatabaseArray( $db = null ){
512 if( !$db ){
513 $db = wfGetDB( DB_SLAVE );
514 }
515 $expiry = $db->encodeExpiry( $this->mExpiry );
516
517 if ( $this->forcedTargetID ) {
518 $uid = $this->forcedTargetID;
519 } else {
520 $uid = $this->target instanceof User ? $this->target->getID() : 0;
521 }
522
523 $a = array(
524 'ipb_address' => (string)$this->target,
525 'ipb_user' => $uid,
526 'ipb_by' => $this->getBy(),
527 'ipb_by_text' => $this->getByName(),
528 'ipb_reason' => $this->mReason,
529 'ipb_timestamp' => $db->timestamp( $this->mTimestamp ),
530 'ipb_auto' => $this->mAuto,
531 'ipb_anon_only' => !$this->isHardblock(),
532 'ipb_create_account' => $this->prevents( 'createaccount' ),
533 'ipb_enable_autoblock' => $this->isAutoblocking(),
534 'ipb_expiry' => $expiry,
535 'ipb_range_start' => $this->getRangeStart(),
536 'ipb_range_end' => $this->getRangeEnd(),
537 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
538 'ipb_block_email' => $this->prevents( 'sendemail' ),
539 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
540 'ipb_parent_block_id' => $this->mParentBlockId
541 );
542
543 return $a;
544 }
545
546 /**
547 * Retroactively autoblocks the last IP used by the user (if it is a user)
548 * blocked by this Block.
549 *
550 * @return Array: block IDs of retroactive autoblocks made
551 */
552 protected function doRetroactiveAutoblock() {
553 $blockIds = array();
554 # If autoblock is enabled, autoblock the LAST IP(s) used
555 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
556 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
557
558 $continue = wfRunHooks(
559 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
560
561 if ( $continue ) {
562 self::defaultRetroactiveAutoblock( $this, $blockIds );
563 }
564 }
565 return $blockIds;
566 }
567
568 /**
569 * Retroactively autoblocks the last IP used by the user (if it is a user)
570 * blocked by this Block. This will use the recentchanges table.
571 *
572 * @param Block $block
573 * @param Array &$blockIds
574 * @return Array: block IDs of retroactive autoblocks made
575 */
576 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
577 $dbr = wfGetDB( DB_SLAVE );
578
579 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
580 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
581
582 // Just the last IP used.
583 $options['LIMIT'] = 1;
584
585 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
586 __METHOD__ , $options );
587
588 if ( !$dbr->numRows( $res ) ) {
589 # No results, don't autoblock anything
590 wfDebug( "No IP found to retroactively autoblock\n" );
591 } else {
592 foreach ( $res as $row ) {
593 if ( $row->rc_ip ) {
594 $id = $block->doAutoblock( $row->rc_ip );
595 if ( $id ) $blockIds[] = $id;
596 }
597 }
598 }
599 }
600
601 /**
602 * Checks whether a given IP is on the autoblock whitelist.
603 * TODO: this probably belongs somewhere else, but not sure where...
604 *
605 * @param $ip String: The IP to check
606 * @return Boolean
607 */
608 public static function isWhitelistedFromAutoblocks( $ip ) {
609 global $wgMemc;
610
611 // Try to get the autoblock_whitelist from the cache, as it's faster
612 // than getting the msg raw and explode()'ing it.
613 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
614 $lines = $wgMemc->get( $key );
615 if ( !$lines ) {
616 $lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
617 $wgMemc->set( $key, $lines, 3600 * 24 );
618 }
619
620 wfDebug( "Checking the autoblock whitelist..\n" );
621
622 foreach ( $lines as $line ) {
623 # List items only
624 if ( substr( $line, 0, 1 ) !== '*' ) {
625 continue;
626 }
627
628 $wlEntry = substr( $line, 1 );
629 $wlEntry = trim( $wlEntry );
630
631 wfDebug( "Checking $ip against $wlEntry..." );
632
633 # Is the IP in this range?
634 if ( IP::isInRange( $ip, $wlEntry ) ) {
635 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
636 return true;
637 } else {
638 wfDebug( " No match\n" );
639 }
640 }
641
642 return false;
643 }
644
645 /**
646 * Autoblocks the given IP, referring to this Block.
647 *
648 * @param $autoblockIP String: the IP to autoblock.
649 * @return mixed: block ID if an autoblock was inserted, false if not.
650 */
651 public function doAutoblock( $autoblockIP ) {
652 # If autoblocks are disabled, go away.
653 if ( !$this->isAutoblocking() ) {
654 return false;
655 }
656
657 # Check for presence on the autoblock whitelist.
658 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
659 return false;
660 }
661
662 # Allow hooks to cancel the autoblock.
663 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
664 wfDebug( "Autoblock aborted by hook.\n" );
665 return false;
666 }
667
668 # It's okay to autoblock. Go ahead and insert/update the block...
669
670 # Do not add a *new* block if the IP is already blocked.
671 $ipblock = Block::newFromTarget( $autoblockIP );
672 if ( $ipblock ) {
673 # Check if the block is an autoblock and would exceed the user block
674 # if renewed. If so, do nothing, otherwise prolong the block time...
675 if ( $ipblock->mAuto && // @TODO: why not compare $ipblock->mExpiry?
676 $this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
677 ) {
678 # Reset block timestamp to now and its expiry to
679 # $wgAutoblockExpiry in the future
680 $ipblock->updateTimestamp();
681 }
682 return false;
683 }
684
685 # Make a new block object with the desired properties.
686 $autoblock = new Block;
687 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
688 $autoblock->setTarget( $autoblockIP );
689 $autoblock->setBlocker( $this->getBlocker() );
690 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )->inContentLanguage()->text();
691 $timestamp = wfTimestampNow();
692 $autoblock->mTimestamp = $timestamp;
693 $autoblock->mAuto = 1;
694 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
695 # Continue suppressing the name if needed
696 $autoblock->mHideName = $this->mHideName;
697 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
698 $autoblock->mParentBlockId = $this->mId;
699
700 if ( $this->mExpiry == 'infinity' ) {
701 # Original block was indefinite, start an autoblock now
702 $autoblock->mExpiry = Block::getAutoblockExpiry( $timestamp );
703 } else {
704 # If the user is already blocked with an expiry date, we don't
705 # want to pile on top of that.
706 $autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $timestamp ) );
707 }
708
709 # Insert the block...
710 $status = $autoblock->insert();
711 return $status
712 ? $status['id']
713 : false;
714 }
715
716 /**
717 * Check if a block has expired. Delete it if it is.
718 * @return Boolean
719 */
720 public function deleteIfExpired() {
721 wfProfileIn( __METHOD__ );
722
723 if ( $this->isExpired() ) {
724 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
725 $this->delete();
726 $retVal = true;
727 } else {
728 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
729 $retVal = false;
730 }
731
732 wfProfileOut( __METHOD__ );
733 return $retVal;
734 }
735
736 /**
737 * Has the block expired?
738 * @return Boolean
739 */
740 public function isExpired() {
741 $timestamp = wfTimestampNow();
742 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
743
744 if ( !$this->mExpiry ) {
745 return false;
746 } else {
747 return $timestamp > $this->mExpiry;
748 }
749 }
750
751 /**
752 * Is the block address valid (i.e. not a null string?)
753 * @return Boolean
754 */
755 public function isValid() {
756 return $this->getTarget() != null;
757 }
758
759 /**
760 * Update the timestamp on autoblocks.
761 */
762 public function updateTimestamp() {
763 if ( $this->mAuto ) {
764 $this->mTimestamp = wfTimestamp();
765 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
766
767 $dbw = wfGetDB( DB_MASTER );
768 $dbw->update( 'ipblocks',
769 array( /* SET */
770 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
771 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
772 ),
773 array( /* WHERE */
774 'ipb_address' => (string)$this->getTarget()
775 ),
776 __METHOD__
777 );
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 getRangeStart() {
786 switch( $this->type ) {
787 case self::TYPE_USER:
788 return '';
789 case self::TYPE_IP:
790 return IP::toHex( $this->target );
791 case self::TYPE_RANGE:
792 list( $start, /*...*/ ) = IP::parseRange( $this->target );
793 return $start;
794 default: throw new MWException( "Block with invalid type" );
795 }
796 }
797
798 /**
799 * Get the IP address at the start of the range in Hex form
800 * @return String IP in Hex form
801 */
802 public function getRangeEnd() {
803 switch( $this->type ) {
804 case self::TYPE_USER:
805 return '';
806 case self::TYPE_IP:
807 return IP::toHex( $this->target );
808 case self::TYPE_RANGE:
809 list( /*...*/, $end ) = IP::parseRange( $this->target );
810 return $end;
811 default: throw new MWException( "Block with invalid type" );
812 }
813 }
814
815 /**
816 * Get the user id of the blocking sysop
817 *
818 * @return Integer (0 for foreign users)
819 */
820 public function getBy() {
821 $blocker = $this->getBlocker();
822 return ( $blocker instanceof User )
823 ? $blocker->getId()
824 : 0;
825 }
826
827 /**
828 * Get the username of the blocking sysop
829 *
830 * @return String
831 */
832 public function getByName() {
833 $blocker = $this->getBlocker();
834 return ( $blocker instanceof User )
835 ? $blocker->getName()
836 : (string)$blocker; // username
837 }
838
839 /**
840 * Get the block ID
841 * @return int
842 */
843 public function getId() {
844 return $this->mId;
845 }
846
847 /**
848 * Get/set the SELECT ... FOR UPDATE flag
849 * @deprecated since 1.18
850 *
851 * @param $x Bool
852 */
853 public function forUpdate( $x = null ) {
854 wfDeprecated( __METHOD__, '1.18' );
855 # noop
856 }
857
858 /**
859 * Get/set a flag determining whether the master is used for reads
860 *
861 * @param $x Bool
862 * @return Bool
863 */
864 public function fromMaster( $x = null ) {
865 return wfSetVar( $this->mFromMaster, $x );
866 }
867
868 /**
869 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
870 * @param $x Bool
871 * @return Bool
872 */
873 public function isHardblock( $x = null ) {
874 wfSetVar( $this->isHardblock, $x );
875
876 # You can't *not* hardblock a user
877 return $this->getType() == self::TYPE_USER
878 ? true
879 : $this->isHardblock;
880 }
881
882 public function isAutoblocking( $x = null ) {
883 wfSetVar( $this->isAutoblocking, $x );
884
885 # You can't put an autoblock on an IP or range as we don't have any history to
886 # look over to get more IPs from
887 return $this->getType() == self::TYPE_USER
888 ? $this->isAutoblocking
889 : false;
890 }
891
892 /**
893 * Get/set whether the Block prevents a given action
894 * @param $action String
895 * @param $x Bool
896 * @return Bool
897 */
898 public function prevents( $action, $x = null ) {
899 switch( $action ) {
900 case 'edit':
901 # For now... <evil laugh>
902 return true;
903
904 case 'createaccount':
905 return wfSetVar( $this->mCreateAccount, $x );
906
907 case 'sendemail':
908 return wfSetVar( $this->mBlockEmail, $x );
909
910 case 'editownusertalk':
911 return wfSetVar( $this->mDisableUsertalk, $x );
912
913 default:
914 return null;
915 }
916 }
917
918 /**
919 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
920 * @return String, text is escaped
921 */
922 public function getRedactedName() {
923 if ( $this->mAuto ) {
924 return Html::rawElement(
925 'span',
926 array( 'class' => 'mw-autoblockid' ),
927 wfMessage( 'autoblockid', $this->mId )
928 );
929 } else {
930 return htmlspecialchars( $this->getTarget() );
931 }
932 }
933
934 /**
935 * Encode expiry for DB
936 *
937 * @param $expiry String: timestamp for expiry, or
938 * @param $db DatabaseBase object
939 * @return String
940 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
941 */
942 public static function encodeExpiry( $expiry, $db ) {
943 wfDeprecated( __METHOD__, '1.18' );
944 return $db->encodeExpiry( $expiry );
945 }
946
947 /**
948 * Decode expiry which has come from the DB
949 *
950 * @param $expiry String: Database expiry format
951 * @param $timestampType Int Requested timestamp format
952 * @return String
953 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
954 */
955 public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
956 wfDeprecated( __METHOD__, '1.18' );
957 global $wgContLang;
958 return $wgContLang->formatExpiry( $expiry, $timestampType );
959 }
960
961 /**
962 * Get a timestamp of the expiry for autoblocks
963 *
964 * @param $timestamp String|Int
965 * @return String
966 */
967 public static function getAutoblockExpiry( $timestamp ) {
968 global $wgAutoblockExpiry;
969
970 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
971 }
972
973 /**
974 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
975 * For example, 127.111.113.151/24 -> 127.111.113.0/24
976 * @param $range String: IP address to normalize
977 * @return string
978 * @deprecated since 1.18, call IP::sanitizeRange() directly
979 */
980 public static function normaliseRange( $range ) {
981 wfDeprecated( __METHOD__, '1.18' );
982 return IP::sanitizeRange( $range );
983 }
984
985 /**
986 * Purge expired blocks from the ipblocks table
987 */
988 public static function purgeExpired() {
989 $dbw = wfGetDB( DB_MASTER );
990 $dbw->delete( 'ipblocks',
991 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
992 }
993
994 /**
995 * Get a value to insert into expiry field of the database when infinite expiry
996 * is desired
997 * @deprecated since 1.18, call $dbr->getInfinity() directly
998 * @return String
999 */
1000 public static function infinity() {
1001 wfDeprecated( __METHOD__, '1.18' );
1002 return wfGetDB( DB_SLAVE )->getInfinity();
1003 }
1004
1005 /**
1006 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1007 * ("24 May 2034"), into an absolute timestamp we can put into the database.
1008 * @param $expiry String: whatever was typed into the form
1009 * @return String: timestamp or "infinity" string for th DB implementation
1010 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
1011 */
1012 public static function parseExpiryInput( $expiry ) {
1013 wfDeprecated( __METHOD__, '1.18' );
1014 return SpecialBlock::parseExpiryInput( $expiry );
1015 }
1016
1017 /**
1018 * Given a target and the target's type, get an existing Block object if possible.
1019 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1020 * * A user to block, in which case $target will be a User
1021 * * An IP to block, in which case $target will be a User generated by using
1022 * User::newFromName( $ip, false ) to turn off name validation
1023 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1024 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1025 * usernames
1026 * Calling this with a user, IP address or range will not select autoblocks, and will
1027 * only select a block where the targets match exactly (so looking for blocks on
1028 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1029 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1030 * affects that target (so for an IP address, get ranges containing that IP; and also
1031 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1032 * @param $fromMaster Bool whether to use the DB_MASTER database
1033 * @return Block|null (null if no relevant block could be found). The target and type
1034 * of the returned Block will refer to the actual block which was found, which might
1035 * not be the same as the target you gave if you used $vagueTarget!
1036 */
1037 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1038
1039 list( $target, $type ) = self::parseTarget( $specificTarget );
1040 if( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ){
1041 return Block::newFromID( $target );
1042
1043 } elseif( $target === null && $vagueTarget == '' ){
1044 # We're not going to find anything useful here
1045 # Be aware that the == '' check is explicit, since empty values will be
1046 # passed by some callers (bug 29116)
1047 return null;
1048
1049 } elseif( in_array( $type, array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE ) ) ) {
1050 $block = new Block();
1051 $block->fromMaster( $fromMaster );
1052
1053 if( $type !== null ){
1054 $block->setTarget( $target );
1055 }
1056
1057 if( $block->newLoad( $vagueTarget ) ){
1058 return $block;
1059 }
1060 }
1061 return null;
1062 }
1063
1064 /**
1065 * From an existing Block, get the target and the type of target. Note that it is
1066 * always safe to treat the target as a string; for User objects this will return
1067 * User::__toString() which in turn gives User::getName().
1068 *
1069 * @param $target String|Int|User
1070 * @return array( User|String, Block::TYPE_ constant )
1071 */
1072 public static function parseTarget( $target ) {
1073 # We may have been through this before
1074 if( $target instanceof User ){
1075 if( IP::isValid( $target->getName() ) ){
1076 return array( $target, self::TYPE_IP );
1077 } else {
1078 return array( $target, self::TYPE_USER );
1079 }
1080 } elseif( $target === null ){
1081 return array( null, null );
1082 }
1083
1084 $target = trim( $target );
1085
1086 if ( IP::isValid( $target ) ) {
1087 # We can still create a User if it's an IP address, but we need to turn
1088 # off validation checking (which would exclude IP addresses)
1089 return array(
1090 User::newFromName( IP::sanitizeIP( $target ), false ),
1091 Block::TYPE_IP
1092 );
1093
1094 } elseif ( IP::isValidBlock( $target ) ) {
1095 # Can't create a User from an IP range
1096 return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
1097 }
1098
1099 # Consider the possibility that this is not a username at all
1100 # but actually an old subpage (bug #29797)
1101 if( strpos( $target, '/' ) !== false ){
1102 # An old subpage, drill down to the user behind it
1103 $parts = explode( '/', $target );
1104 $target = $parts[0];
1105 }
1106
1107 $userObj = User::newFromName( $target );
1108 if ( $userObj instanceof User ) {
1109 # Note that since numbers are valid usernames, a $target of "12345" will be
1110 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1111 # since hash characters are not valid in usernames or titles generally.
1112 return array( $userObj, Block::TYPE_USER );
1113
1114 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1115 # Autoblock reference in the form "#12345"
1116 return array( substr( $target, 1 ), Block::TYPE_AUTO );
1117
1118 } else {
1119 # WTF?
1120 return array( null, null );
1121 }
1122 }
1123
1124 /**
1125 * Get the type of target for this particular block
1126 * @return Block::TYPE_ constant, will never be TYPE_ID
1127 */
1128 public function getType() {
1129 return $this->mAuto
1130 ? self::TYPE_AUTO
1131 : $this->type;
1132 }
1133
1134 /**
1135 * Get the target and target type for this particular Block. Note that for autoblocks,
1136 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1137 * in this situation.
1138 * @return array( User|String, Block::TYPE_ constant )
1139 * @todo FIXME: This should be an integral part of the Block member variables
1140 */
1141 public function getTargetAndType() {
1142 return array( $this->getTarget(), $this->getType() );
1143 }
1144
1145 /**
1146 * Get the target for this particular Block. Note that for autoblocks,
1147 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1148 * in this situation.
1149 * @return User|String
1150 */
1151 public function getTarget() {
1152 return $this->target;
1153 }
1154
1155 /**
1156 * @since 1.19
1157 *
1158 * @return Mixed|string
1159 */
1160 public function getExpiry() {
1161 return $this->mExpiry;
1162 }
1163
1164 /**
1165 * Set the target for this block, and update $this->type accordingly
1166 * @param $target Mixed
1167 */
1168 public function setTarget( $target ){
1169 list( $this->target, $this->type ) = self::parseTarget( $target );
1170 }
1171
1172 /**
1173 * Get the user who implemented this block
1174 * @return User|string Local User object or string for a foreign user
1175 */
1176 public function getBlocker(){
1177 return $this->blocker;
1178 }
1179
1180 /**
1181 * Set the user who implemented (or will implement) this block
1182 * @param $user User|string Local User object or username string for foriegn users
1183 */
1184 public function setBlocker( $user ){
1185 $this->blocker = $user;
1186 }
1187 }