Merge "(bug 47070) check content model namespace on import."
[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 blocked user from their block id.
106 *
107 * @param $id Integer: Block id to search for
108 * @return Block object or null
109 */
110 public static function newFromID( $id ) {
111 $dbr = wfGetDB( DB_SLAVE );
112 $res = $dbr->selectRow(
113 'ipblocks',
114 self::selectFields(),
115 array( 'ipb_id' => $id ),
116 __METHOD__
117 );
118 if ( $res ) {
119 return self::newFromRow( $res );
120 } else {
121 return null;
122 }
123 }
124
125 /**
126 * Return the list of ipblocks fields that should be selected to create
127 * a new block.
128 * @return array
129 */
130 public static function selectFields() {
131 return array(
132 'ipb_id',
133 'ipb_address',
134 'ipb_by',
135 'ipb_by_text',
136 'ipb_reason',
137 'ipb_timestamp',
138 'ipb_auto',
139 'ipb_anon_only',
140 'ipb_create_account',
141 'ipb_enable_autoblock',
142 'ipb_expiry',
143 'ipb_deleted',
144 'ipb_block_email',
145 'ipb_allow_usertalk',
146 'ipb_parent_block_id',
147 );
148 }
149
150 /**
151 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
152 * the blocking user or the block timestamp, only things which affect the blocked user
153 *
154 * @param $block Block
155 *
156 * @return bool
157 */
158 public function equals( Block $block ) {
159 return (
160 (string)$this->target == (string)$block->target
161 && $this->type == $block->type
162 && $this->mAuto == $block->mAuto
163 && $this->isHardblock() == $block->isHardblock()
164 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
165 && $this->mExpiry == $block->mExpiry
166 && $this->isAutoblocking() == $block->isAutoblocking()
167 && $this->mHideName == $block->mHideName
168 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
169 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
170 && $this->mReason == $block->mReason
171 );
172 }
173
174 /**
175 * Load a block from the database which affects the already-set $this->target:
176 * 1) A block directly on the given user or IP
177 * 2) A rangeblock encompassing the given IP (smallest first)
178 * 3) An autoblock on the given IP
179 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
180 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
181 * @throws MWException
182 * @return Bool whether a relevant block was found
183 */
184 protected function newLoad( $vagueTarget = null ) {
185 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_SLAVE );
186
187 if ( $this->type !== null ) {
188 $conds = array(
189 'ipb_address' => array( (string)$this->target ),
190 );
191 } else {
192 $conds = array( 'ipb_address' => array() );
193 }
194
195 # Be aware that the != '' check is explicit, since empty values will be
196 # passed by some callers (bug 29116)
197 if ( $vagueTarget != '' ) {
198 list( $target, $type ) = self::parseTarget( $vagueTarget );
199 switch ( $type ) {
200 case self::TYPE_USER:
201 # Slightly weird, but who are we to argue?
202 $conds['ipb_address'][] = (string)$target;
203 break;
204
205 case self::TYPE_IP:
206 $conds['ipb_address'][] = (string)$target;
207 $conds[] = self::getRangeCond( IP::toHex( $target ) );
208 $conds = $db->makeList( $conds, LIST_OR );
209 break;
210
211 case self::TYPE_RANGE:
212 list( $start, $end ) = IP::parseRange( $target );
213 $conds['ipb_address'][] = (string)$target;
214 $conds[] = self::getRangeCond( $start, $end );
215 $conds = $db->makeList( $conds, LIST_OR );
216 break;
217
218 default:
219 throw new MWException( "Tried to load block with invalid type" );
220 }
221 }
222
223 $res = $db->select( 'ipblocks', self::selectFields(), $conds, __METHOD__ );
224
225 # This result could contain a block on the user, a block on the IP, and a russian-doll
226 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
227 $bestRow = null;
228
229 # Lower will be better
230 $bestBlockScore = 100;
231
232 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
233 $bestBlockPreventsEdit = null;
234
235 foreach ( $res as $row ) {
236 $block = self::newFromRow( $row );
237
238 # Don't use expired blocks
239 if ( $block->deleteIfExpired() ) {
240 continue;
241 }
242
243 # Don't use anon only blocks on users
244 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
245 continue;
246 }
247
248 if ( $block->getType() == self::TYPE_RANGE ) {
249 # This is the number of bits that are allowed to vary in the block, give
250 # or take some floating point errors
251 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
252 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
253 $size = log( $end - $start + 1, 2 );
254
255 # This has the nice property that a /32 block is ranked equally with a
256 # single-IP block, which is exactly what it is...
257 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
258
259 } else {
260 $score = $block->getType();
261 }
262
263 if ( $score < $bestBlockScore ) {
264 $bestBlockScore = $score;
265 $bestRow = $row;
266 $bestBlockPreventsEdit = $block->prevents( 'edit' );
267 }
268 }
269
270 if ( $bestRow !== null ) {
271 $this->initFromRow( $bestRow );
272 $this->prevents( 'edit', $bestBlockPreventsEdit );
273 return true;
274 } else {
275 return false;
276 }
277 }
278
279 /**
280 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
281 * @param string $start Hexadecimal IP representation
282 * @param string $end Hexadecimal IP representation, or null to use $start = $end
283 * @return String
284 */
285 public static function getRangeCond( $start, $end = null ) {
286 if ( $end === null ) {
287 $end = $start;
288 }
289 # Per bug 14634, we want to include relevant active rangeblocks; for
290 # rangeblocks, we want to include larger ranges which enclose the given
291 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
292 # so we can improve performance by filtering on a LIKE clause
293 $chunk = self::getIpFragment( $start );
294 $dbr = wfGetDB( DB_SLAVE );
295 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
296
297 # Fairly hard to make a malicious SQL statement out of hex characters,
298 # but stranger things have happened...
299 $safeStart = $dbr->addQuotes( $start );
300 $safeEnd = $dbr->addQuotes( $end );
301
302 return $dbr->makeList(
303 array(
304 "ipb_range_start $like",
305 "ipb_range_start <= $safeStart",
306 "ipb_range_end >= $safeEnd",
307 ),
308 LIST_AND
309 );
310 }
311
312 /**
313 * Get the component of an IP address which is certain to be the same between an IP
314 * address and a rangeblock containing that IP address.
315 * @param $hex String Hexadecimal IP representation
316 * @return String
317 */
318 protected static function getIpFragment( $hex ) {
319 global $wgBlockCIDRLimit;
320 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
321 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
322 } else {
323 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
324 }
325 }
326
327 /**
328 * Given a database row from the ipblocks table, initialize
329 * member variables
330 * @param $row ResultWrapper: a row from the ipblocks table
331 */
332 protected function initFromRow( $row ) {
333 $this->setTarget( $row->ipb_address );
334 if ( $row->ipb_by ) { // local user
335 $this->setBlocker( User::newFromID( $row->ipb_by ) );
336 } else { // foreign user
337 $this->setBlocker( $row->ipb_by_text );
338 }
339
340 $this->mReason = $row->ipb_reason;
341 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
342 $this->mAuto = $row->ipb_auto;
343 $this->mHideName = $row->ipb_deleted;
344 $this->mId = $row->ipb_id;
345 $this->mParentBlockId = $row->ipb_parent_block_id;
346
347 // I wish I didn't have to do this
348 $db = wfGetDB( DB_SLAVE );
349 if ( $row->ipb_expiry == $db->getInfinity() ) {
350 $this->mExpiry = 'infinity';
351 } else {
352 $this->mExpiry = wfTimestamp( TS_MW, $row->ipb_expiry );
353 }
354
355 $this->isHardblock( !$row->ipb_anon_only );
356 $this->isAutoblocking( $row->ipb_enable_autoblock );
357
358 $this->prevents( 'createaccount', $row->ipb_create_account );
359 $this->prevents( 'sendemail', $row->ipb_block_email );
360 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
361 }
362
363 /**
364 * Create a new Block object from a database row
365 * @param $row ResultWrapper row from the ipblocks table
366 * @return Block
367 */
368 public static function newFromRow( $row ) {
369 $block = new Block;
370 $block->initFromRow( $row );
371 return $block;
372 }
373
374 /**
375 * Delete the row from the IP blocks table.
376 *
377 * @throws MWException
378 * @return Boolean
379 */
380 public function delete() {
381 if ( wfReadOnly() ) {
382 return false;
383 }
384
385 if ( !$this->getId() ) {
386 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
387 }
388
389 $dbw = wfGetDB( DB_MASTER );
390 $dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__ );
391 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__ );
392
393 return $dbw->affectedRows() > 0;
394 }
395
396 /**
397 * Insert a block into the block table. Will fail if there is a conflicting
398 * block (same name and options) already in the database.
399 *
400 * @param $dbw DatabaseBase if you have one available
401 * @return mixed: false on failure, assoc array on success:
402 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
403 */
404 public function insert( $dbw = null ) {
405 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
406
407 if ( $dbw === null ) {
408 $dbw = wfGetDB( DB_MASTER );
409 }
410
411 # Don't collide with expired blocks
412 Block::purgeExpired();
413
414 $row = $this->getDatabaseArray();
415 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
416
417 $dbw->insert(
418 'ipblocks',
419 $row,
420 __METHOD__,
421 array( 'IGNORE' )
422 );
423 $affected = $dbw->affectedRows();
424 $this->mId = $dbw->insertId();
425
426 if ( $affected ) {
427 $auto_ipd_ids = $this->doRetroactiveAutoblock();
428 return array( 'id' => $this->mId, 'autoIds' => $auto_ipd_ids );
429 }
430
431 return false;
432 }
433
434 /**
435 * Update a block in the DB with new parameters.
436 * The ID field needs to be loaded first.
437 *
438 * @return Int number of affected rows, which should probably be 1 or something has
439 * gone slightly awry
440 */
441 public function update() {
442 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
443 $dbw = wfGetDB( DB_MASTER );
444
445 $dbw->update(
446 'ipblocks',
447 $this->getDatabaseArray( $dbw ),
448 array( 'ipb_id' => $this->getId() ),
449 __METHOD__
450 );
451
452 return $dbw->affectedRows();
453 }
454
455 /**
456 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
457 * @param $db DatabaseBase
458 * @return Array
459 */
460 protected function getDatabaseArray( $db = null ) {
461 if ( !$db ) {
462 $db = wfGetDB( DB_SLAVE );
463 }
464 $expiry = $db->encodeExpiry( $this->mExpiry );
465
466 if ( $this->forcedTargetID ) {
467 $uid = $this->forcedTargetID;
468 } else {
469 $uid = $this->target instanceof User ? $this->target->getID() : 0;
470 }
471
472 $a = array(
473 'ipb_address' => (string)$this->target,
474 'ipb_user' => $uid,
475 'ipb_by' => $this->getBy(),
476 'ipb_by_text' => $this->getByName(),
477 'ipb_reason' => $this->mReason,
478 'ipb_timestamp' => $db->timestamp( $this->mTimestamp ),
479 'ipb_auto' => $this->mAuto,
480 'ipb_anon_only' => !$this->isHardblock(),
481 'ipb_create_account' => $this->prevents( 'createaccount' ),
482 'ipb_enable_autoblock' => $this->isAutoblocking(),
483 'ipb_expiry' => $expiry,
484 'ipb_range_start' => $this->getRangeStart(),
485 'ipb_range_end' => $this->getRangeEnd(),
486 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
487 'ipb_block_email' => $this->prevents( 'sendemail' ),
488 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
489 'ipb_parent_block_id' => $this->mParentBlockId
490 );
491
492 return $a;
493 }
494
495 /**
496 * Retroactively autoblocks the last IP used by the user (if it is a user)
497 * blocked by this Block.
498 *
499 * @return Array: block IDs of retroactive autoblocks made
500 */
501 protected function doRetroactiveAutoblock() {
502 $blockIds = array();
503 # If autoblock is enabled, autoblock the LAST IP(s) used
504 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
505 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
506
507 $continue = wfRunHooks(
508 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
509
510 if ( $continue ) {
511 self::defaultRetroactiveAutoblock( $this, $blockIds );
512 }
513 }
514 return $blockIds;
515 }
516
517 /**
518 * Retroactively autoblocks the last IP used by the user (if it is a user)
519 * blocked by this Block. This will use the recentchanges table.
520 *
521 * @param Block $block
522 * @param array &$blockIds
523 * @return Array: block IDs of retroactive autoblocks made
524 */
525 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
526 global $wgPutIPinRC;
527
528 // No IPs are in recentchanges table, so nothing to select
529 if ( !$wgPutIPinRC ) {
530 return;
531 }
532
533 $dbr = wfGetDB( DB_SLAVE );
534
535 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
536 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
537
538 // Just the last IP used.
539 $options['LIMIT'] = 1;
540
541 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
542 __METHOD__, $options );
543
544 if ( !$res->numRows() ) {
545 # No results, don't autoblock anything
546 wfDebug( "No IP found to retroactively autoblock\n" );
547 } else {
548 foreach ( $res as $row ) {
549 if ( $row->rc_ip ) {
550 $id = $block->doAutoblock( $row->rc_ip );
551 if ( $id ) {
552 $blockIds[] = $id;
553 }
554 }
555 }
556 }
557 }
558
559 /**
560 * Checks whether a given IP is on the autoblock whitelist.
561 * TODO: this probably belongs somewhere else, but not sure where...
562 *
563 * @param string $ip The IP to check
564 * @return Boolean
565 */
566 public static function isWhitelistedFromAutoblocks( $ip ) {
567 global $wgMemc;
568
569 // Try to get the autoblock_whitelist from the cache, as it's faster
570 // than getting the msg raw and explode()'ing it.
571 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
572 $lines = $wgMemc->get( $key );
573 if ( !$lines ) {
574 $lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
575 $wgMemc->set( $key, $lines, 3600 * 24 );
576 }
577
578 wfDebug( "Checking the autoblock whitelist..\n" );
579
580 foreach ( $lines as $line ) {
581 # List items only
582 if ( substr( $line, 0, 1 ) !== '*' ) {
583 continue;
584 }
585
586 $wlEntry = substr( $line, 1 );
587 $wlEntry = trim( $wlEntry );
588
589 wfDebug( "Checking $ip against $wlEntry..." );
590
591 # Is the IP in this range?
592 if ( IP::isInRange( $ip, $wlEntry ) ) {
593 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
594 return true;
595 } else {
596 wfDebug( " No match\n" );
597 }
598 }
599
600 return false;
601 }
602
603 /**
604 * Autoblocks the given IP, referring to this Block.
605 *
606 * @param string $autoblockIP the IP to autoblock.
607 * @return mixed: block ID if an autoblock was inserted, false if not.
608 */
609 public function doAutoblock( $autoblockIP ) {
610 # If autoblocks are disabled, go away.
611 if ( !$this->isAutoblocking() ) {
612 return false;
613 }
614
615 # Check for presence on the autoblock whitelist.
616 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
617 return false;
618 }
619
620 # Allow hooks to cancel the autoblock.
621 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
622 wfDebug( "Autoblock aborted by hook.\n" );
623 return false;
624 }
625
626 # It's okay to autoblock. Go ahead and insert/update the block...
627
628 # Do not add a *new* block if the IP is already blocked.
629 $ipblock = Block::newFromTarget( $autoblockIP );
630 if ( $ipblock ) {
631 # Check if the block is an autoblock and would exceed the user block
632 # if renewed. If so, do nothing, otherwise prolong the block time...
633 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
634 $this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
635 ) {
636 # Reset block timestamp to now and its expiry to
637 # $wgAutoblockExpiry in the future
638 $ipblock->updateTimestamp();
639 }
640 return false;
641 }
642
643 # Make a new block object with the desired properties.
644 $autoblock = new Block;
645 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
646 $autoblock->setTarget( $autoblockIP );
647 $autoblock->setBlocker( $this->getBlocker() );
648 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )->inContentLanguage()->plain();
649 $timestamp = wfTimestampNow();
650 $autoblock->mTimestamp = $timestamp;
651 $autoblock->mAuto = 1;
652 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
653 # Continue suppressing the name if needed
654 $autoblock->mHideName = $this->mHideName;
655 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
656 $autoblock->mParentBlockId = $this->mId;
657
658 if ( $this->mExpiry == 'infinity' ) {
659 # Original block was indefinite, start an autoblock now
660 $autoblock->mExpiry = Block::getAutoblockExpiry( $timestamp );
661 } else {
662 # If the user is already blocked with an expiry date, we don't
663 # want to pile on top of that.
664 $autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $timestamp ) );
665 }
666
667 # Insert the block...
668 $status = $autoblock->insert();
669 return $status
670 ? $status['id']
671 : false;
672 }
673
674 /**
675 * Check if a block has expired. Delete it if it is.
676 * @return Boolean
677 */
678 public function deleteIfExpired() {
679 wfProfileIn( __METHOD__ );
680
681 if ( $this->isExpired() ) {
682 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
683 $this->delete();
684 $retVal = true;
685 } else {
686 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
687 $retVal = false;
688 }
689
690 wfProfileOut( __METHOD__ );
691 return $retVal;
692 }
693
694 /**
695 * Has the block expired?
696 * @return Boolean
697 */
698 public function isExpired() {
699 $timestamp = wfTimestampNow();
700 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
701
702 if ( !$this->mExpiry ) {
703 return false;
704 } else {
705 return $timestamp > $this->mExpiry;
706 }
707 }
708
709 /**
710 * Is the block address valid (i.e. not a null string?)
711 * @return Boolean
712 */
713 public function isValid() {
714 return $this->getTarget() != null;
715 }
716
717 /**
718 * Update the timestamp on autoblocks.
719 */
720 public function updateTimestamp() {
721 if ( $this->mAuto ) {
722 $this->mTimestamp = wfTimestamp();
723 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
724
725 $dbw = wfGetDB( DB_MASTER );
726 $dbw->update( 'ipblocks',
727 array( /* SET */
728 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
729 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
730 ),
731 array( /* WHERE */
732 'ipb_address' => (string)$this->getTarget()
733 ),
734 __METHOD__
735 );
736 }
737 }
738
739 /**
740 * Get the IP address at the start of the range in Hex form
741 * @throws MWException
742 * @return String IP in Hex form
743 */
744 public function getRangeStart() {
745 switch ( $this->type ) {
746 case self::TYPE_USER:
747 return '';
748 case self::TYPE_IP:
749 return IP::toHex( $this->target );
750 case self::TYPE_RANGE:
751 list( $start, /*...*/ ) = IP::parseRange( $this->target );
752 return $start;
753 default:
754 throw new MWException( "Block with invalid type" );
755 }
756 }
757
758 /**
759 * Get the IP address at the end of the range in Hex form
760 * @throws MWException
761 * @return String IP in Hex form
762 */
763 public function getRangeEnd() {
764 switch ( $this->type ) {
765 case self::TYPE_USER:
766 return '';
767 case self::TYPE_IP:
768 return IP::toHex( $this->target );
769 case self::TYPE_RANGE:
770 list( /*...*/, $end ) = IP::parseRange( $this->target );
771 return $end;
772 default:
773 throw new MWException( "Block with invalid type" );
774 }
775 }
776
777 /**
778 * Get the user id of the blocking sysop
779 *
780 * @return Integer (0 for foreign users)
781 */
782 public function getBy() {
783 $blocker = $this->getBlocker();
784 return ( $blocker instanceof User )
785 ? $blocker->getId()
786 : 0;
787 }
788
789 /**
790 * Get the username of the blocking sysop
791 *
792 * @return String
793 */
794 public function getByName() {
795 $blocker = $this->getBlocker();
796 return ( $blocker instanceof User )
797 ? $blocker->getName()
798 : (string)$blocker; // username
799 }
800
801 /**
802 * Get the block ID
803 * @return int
804 */
805 public function getId() {
806 return $this->mId;
807 }
808
809 /**
810 * Get/set a flag determining whether the master is used for reads
811 *
812 * @param $x Bool
813 * @return Bool
814 */
815 public function fromMaster( $x = null ) {
816 return wfSetVar( $this->mFromMaster, $x );
817 }
818
819 /**
820 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
821 * @param $x Bool
822 * @return Bool
823 */
824 public function isHardblock( $x = null ) {
825 wfSetVar( $this->isHardblock, $x );
826
827 # You can't *not* hardblock a user
828 return $this->getType() == self::TYPE_USER
829 ? true
830 : $this->isHardblock;
831 }
832
833 public function isAutoblocking( $x = null ) {
834 wfSetVar( $this->isAutoblocking, $x );
835
836 # You can't put an autoblock on an IP or range as we don't have any history to
837 # look over to get more IPs from
838 return $this->getType() == self::TYPE_USER
839 ? $this->isAutoblocking
840 : false;
841 }
842
843 /**
844 * Get/set whether the Block prevents a given action
845 * @param $action String
846 * @param $x Bool
847 * @return Bool
848 */
849 public function prevents( $action, $x = null ) {
850 switch ( $action ) {
851 case 'edit':
852 # For now... <evil laugh>
853 return true;
854
855 case 'createaccount':
856 return wfSetVar( $this->mCreateAccount, $x );
857
858 case 'sendemail':
859 return wfSetVar( $this->mBlockEmail, $x );
860
861 case 'editownusertalk':
862 return wfSetVar( $this->mDisableUsertalk, $x );
863
864 default:
865 return null;
866 }
867 }
868
869 /**
870 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
871 * @return String, text is escaped
872 */
873 public function getRedactedName() {
874 if ( $this->mAuto ) {
875 return Html::rawElement(
876 'span',
877 array( 'class' => 'mw-autoblockid' ),
878 wfMessage( 'autoblockid', $this->mId )
879 );
880 } else {
881 return htmlspecialchars( $this->getTarget() );
882 }
883 }
884
885 /**
886 * Get a timestamp of the expiry for autoblocks
887 *
888 * @param $timestamp String|Int
889 * @return String
890 */
891 public static function getAutoblockExpiry( $timestamp ) {
892 global $wgAutoblockExpiry;
893
894 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
895 }
896
897 /**
898 * Purge expired blocks from the ipblocks table
899 */
900 public static function purgeExpired() {
901 if ( wfReadOnly() ) {
902 return;
903 }
904
905 $method = __METHOD__;
906 $dbw = wfGetDB( DB_MASTER );
907 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
908 $dbw->delete( 'ipblocks',
909 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
910 } );
911 }
912
913 /**
914 * Given a target and the target's type, get an existing Block object if possible.
915 * @param $specificTarget String|User|Int a block target, which may be one of several types:
916 * * A user to block, in which case $target will be a User
917 * * An IP to block, in which case $target will be a User generated by using
918 * User::newFromName( $ip, false ) to turn off name validation
919 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
920 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
921 * usernames
922 * Calling this with a user, IP address or range will not select autoblocks, and will
923 * only select a block where the targets match exactly (so looking for blocks on
924 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
925 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
926 * affects that target (so for an IP address, get ranges containing that IP; and also
927 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
928 * @param bool $fromMaster whether to use the DB_MASTER database
929 * @return Block|null (null if no relevant block could be found). The target and type
930 * of the returned Block will refer to the actual block which was found, which might
931 * not be the same as the target you gave if you used $vagueTarget!
932 */
933 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
934
935 list( $target, $type ) = self::parseTarget( $specificTarget );
936 if ( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ) {
937 return Block::newFromID( $target );
938
939 } elseif ( $target === null && $vagueTarget == '' ) {
940 # We're not going to find anything useful here
941 # Be aware that the == '' check is explicit, since empty values will be
942 # passed by some callers (bug 29116)
943 return null;
944
945 } elseif ( in_array( $type, array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ) ) ) {
946 $block = new Block();
947 $block->fromMaster( $fromMaster );
948
949 if ( $type !== null ) {
950 $block->setTarget( $target );
951 }
952
953 if ( $block->newLoad( $vagueTarget ) ) {
954 return $block;
955 }
956 }
957 return null;
958 }
959
960 /**
961 * Get all blocks that match any IP from an array of IP addresses
962 *
963 * @param Array $ipChain list of IPs (strings), usually retrieved from the
964 * X-Forwarded-For header of the request
965 * @param Bool $isAnon Exclude anonymous-only blocks if false
966 * @param Bool $fromMaster Whether to query the master or slave database
967 * @return Array of Blocks
968 * @since 1.22
969 */
970 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
971 if ( !count( $ipChain ) ) {
972 return array();
973 }
974
975 wfProfileIn( __METHOD__ );
976 $conds = array();
977 foreach ( array_unique( $ipChain ) as $ipaddr ) {
978 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
979 # necessarily trust the header given to us, make sure that we are only
980 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
981 # Do not treat private IP spaces as special as it may be desirable for wikis
982 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
983 if ( !IP::isValid( $ipaddr ) ) {
984 continue;
985 }
986 # Don't check trusted IPs (includes local squids which will be in every request)
987 if ( wfIsTrustedProxy( $ipaddr ) ) {
988 continue;
989 }
990 # Check both the original IP (to check against single blocks), as well as build
991 # the clause to check for rangeblocks for the given IP.
992 $conds['ipb_address'][] = $ipaddr;
993 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
994 }
995
996 if ( !count( $conds ) ) {
997 wfProfileOut( __METHOD__ );
998 return array();
999 }
1000
1001 if ( $fromMaster ) {
1002 $db = wfGetDB( DB_MASTER );
1003 } else {
1004 $db = wfGetDB( DB_SLAVE );
1005 }
1006 $conds = $db->makeList( $conds, LIST_OR );
1007 if ( !$isAnon ) {
1008 $conds = array( $conds, 'ipb_anon_only' => 0 );
1009 }
1010 $selectFields = array_merge(
1011 array( 'ipb_range_start', 'ipb_range_end' ),
1012 Block::selectFields()
1013 );
1014 $rows = $db->select( 'ipblocks',
1015 $selectFields,
1016 $conds,
1017 __METHOD__
1018 );
1019
1020 $blocks = array();
1021 foreach ( $rows as $row ) {
1022 $block = self::newFromRow( $row );
1023 if ( !$block->deleteIfExpired() ) {
1024 $blocks[] = $block;
1025 }
1026 }
1027
1028 wfProfileOut( __METHOD__ );
1029 return $blocks;
1030 }
1031
1032 /**
1033 * From a list of multiple blocks, find the most exact and strongest Block.
1034 * The logic for finding the "best" block is:
1035 * - Blocks that match the block's target IP are preferred over ones in a range
1036 * - Hardblocks are chosen over softblocks that prevent account creation
1037 * - Softblocks that prevent account creation are chosen over other softblocks
1038 * - Other softblocks are chosen over autoblocks
1039 * - If there are multiple exact or range blocks at the same level, the one chosen
1040 * is random
1041
1042 * @param Array $ipChain list of IPs (strings). This is used to determine how "close"
1043 * a block is to the server, and if a block matches exactly, or is in a range.
1044 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1045 * local-squid, ...)
1046 * @param Array $block Array of blocks
1047 * @return Block|null the "best" block from the list
1048 */
1049 public static function chooseBlock( array $blocks, array $ipChain ) {
1050 if ( !count( $blocks ) ) {
1051 return null;
1052 } elseif ( count( $blocks ) == 1 ) {
1053 return $blocks[0];
1054 }
1055
1056 wfProfileIn( __METHOD__ );
1057
1058 // Sort hard blocks before soft ones and secondarily sort blocks
1059 // that disable account creation before those that don't.
1060 usort( $blocks, function( Block $a, Block $b ) {
1061 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1062 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1063 return strcmp( $bWeight, $aWeight ); // highest weight first
1064 } );
1065
1066 $blocksListExact = array(
1067 'hard' => false,
1068 'disable_create' => false,
1069 'other' => false,
1070 'auto' => false
1071 );
1072 $blocksListRange = array(
1073 'hard' => false,
1074 'disable_create' => false,
1075 'other' => false,
1076 'auto' => false
1077 );
1078 $ipChain = array_reverse( $ipChain );
1079
1080 foreach ( $blocks as $block ) {
1081 // Stop searching if we have already have a "better" block. This
1082 // is why the order of the blocks matters
1083 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1084 break;
1085 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1086 break;
1087 }
1088
1089 foreach ( $ipChain as $checkip ) {
1090 $checkipHex = IP::toHex( $checkip );
1091 if ( (string)$block->getTarget() === $checkip ) {
1092 if ( $block->isHardblock() ) {
1093 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1094 } elseif ( $block->prevents( 'createaccount' ) ) {
1095 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1096 } elseif ( $block->mAuto ) {
1097 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1098 } else {
1099 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1100 }
1101 // We found closest exact match in the ip list, so go to the next Block
1102 break;
1103 } elseif ( array_filter( $blocksListExact ) == array()
1104 && $block->getRangeStart() <= $checkipHex
1105 && $block->getRangeEnd() >= $checkipHex
1106 ) {
1107 if ( $block->isHardblock() ) {
1108 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1109 } elseif ( $block->prevents( 'createaccount' ) ) {
1110 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1111 } elseif ( $block->mAuto ) {
1112 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1113 } else {
1114 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1115 }
1116 break;
1117 }
1118 }
1119 }
1120
1121 if ( array_filter( $blocksListExact ) == array() ) {
1122 $blocksList = &$blocksListRange;
1123 } else {
1124 $blocksList = &$blocksListExact;
1125 }
1126
1127 $chosenBlock = null;
1128 if ( $blocksList['hard'] ) {
1129 $chosenBlock = $blocksList['hard'];
1130 } elseif ( $blocksList['disable_create'] ) {
1131 $chosenBlock = $blocksList['disable_create'];
1132 } elseif ( $blocksList['other'] ) {
1133 $chosenBlock = $blocksList['other'];
1134 } elseif ( $blocksList['auto'] ) {
1135 $chosenBlock = $blocksList['auto'];
1136 } else {
1137 wfProfileOut( __METHOD__ );
1138 throw new MWException( "Proxy block found, but couldn't be classified." );
1139 }
1140
1141 wfProfileOut( __METHOD__ );
1142 return $chosenBlock;
1143 }
1144
1145 /**
1146 * From an existing Block, get the target and the type of target.
1147 * Note that, except for null, it is always safe to treat the target
1148 * as a string; for User objects this will return User::__toString()
1149 * which in turn gives User::getName().
1150 *
1151 * @param $target String|Int|User|null
1152 * @return array( User|String|null, Block::TYPE_ constant|null )
1153 */
1154 public static function parseTarget( $target ) {
1155 # We may have been through this before
1156 if ( $target instanceof User ) {
1157 if ( IP::isValid( $target->getName() ) ) {
1158 return array( $target, self::TYPE_IP );
1159 } else {
1160 return array( $target, self::TYPE_USER );
1161 }
1162 } elseif ( $target === null ) {
1163 return array( null, null );
1164 }
1165
1166 $target = trim( $target );
1167
1168 if ( IP::isValid( $target ) ) {
1169 # We can still create a User if it's an IP address, but we need to turn
1170 # off validation checking (which would exclude IP addresses)
1171 return array(
1172 User::newFromName( IP::sanitizeIP( $target ), false ),
1173 Block::TYPE_IP
1174 );
1175
1176 } elseif ( IP::isValidBlock( $target ) ) {
1177 # Can't create a User from an IP range
1178 return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
1179 }
1180
1181 # Consider the possibility that this is not a username at all
1182 # but actually an old subpage (bug #29797)
1183 if ( strpos( $target, '/' ) !== false ) {
1184 # An old subpage, drill down to the user behind it
1185 $parts = explode( '/', $target );
1186 $target = $parts[0];
1187 }
1188
1189 $userObj = User::newFromName( $target );
1190 if ( $userObj instanceof User ) {
1191 # Note that since numbers are valid usernames, a $target of "12345" will be
1192 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1193 # since hash characters are not valid in usernames or titles generally.
1194 return array( $userObj, Block::TYPE_USER );
1195
1196 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1197 # Autoblock reference in the form "#12345"
1198 return array( substr( $target, 1 ), Block::TYPE_AUTO );
1199
1200 } else {
1201 # WTF?
1202 return array( null, null );
1203 }
1204 }
1205
1206 /**
1207 * Get the type of target for this particular block
1208 * @return Block::TYPE_ constant, will never be TYPE_ID
1209 */
1210 public function getType() {
1211 return $this->mAuto
1212 ? self::TYPE_AUTO
1213 : $this->type;
1214 }
1215
1216 /**
1217 * Get the target and target type for this particular Block. Note that for autoblocks,
1218 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1219 * in this situation.
1220 * @return array( User|String, Block::TYPE_ constant )
1221 * @todo FIXME: This should be an integral part of the Block member variables
1222 */
1223 public function getTargetAndType() {
1224 return array( $this->getTarget(), $this->getType() );
1225 }
1226
1227 /**
1228 * Get the target for this particular Block. Note that for autoblocks,
1229 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1230 * in this situation.
1231 * @return User|String
1232 */
1233 public function getTarget() {
1234 return $this->target;
1235 }
1236
1237 /**
1238 * @since 1.19
1239 *
1240 * @return Mixed|string
1241 */
1242 public function getExpiry() {
1243 return $this->mExpiry;
1244 }
1245
1246 /**
1247 * Set the target for this block, and update $this->type accordingly
1248 * @param $target Mixed
1249 */
1250 public function setTarget( $target ) {
1251 list( $this->target, $this->type ) = self::parseTarget( $target );
1252 }
1253
1254 /**
1255 * Get the user who implemented this block
1256 * @return User|string Local User object or string for a foreign user
1257 */
1258 public function getBlocker() {
1259 return $this->blocker;
1260 }
1261
1262 /**
1263 * Set the user who implemented (or will implement) this block
1264 * @param $user User|string Local User object or username string for foreign users
1265 */
1266 public function setBlocker( $user ) {
1267 $this->blocker = $user;
1268 }
1269
1270 /**
1271 * Get the key and parameters for the corresponding error message.
1272 *
1273 * @since 1.22
1274 * @param IContextSource $context
1275 * @return array
1276 */
1277 public function getPermissionsError( IContextSource $context ) {
1278 $blocker = $this->getBlocker();
1279 if ( $blocker instanceof User ) { // local user
1280 $blockerUserpage = $blocker->getUserPage();
1281 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1282 } else { // foreign user
1283 $link = $blocker;
1284 }
1285
1286 $reason = $this->mReason;
1287 if ( $reason == '' ) {
1288 $reason = $context->msg( 'blockednoreason' )->text();
1289 }
1290
1291 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1292 * This could be a username, an IP range, or a single IP. */
1293 $intended = $this->getTarget();
1294
1295 $lang = $context->getLanguage();
1296 return array(
1297 $this->mAuto ? 'autoblockedtext' : 'blockedtext',
1298 $link,
1299 $reason,
1300 $context->getRequest()->getIP(),
1301 $this->getByName(),
1302 $this->getId(),
1303 $lang->formatExpiry( $this->mExpiry ),
1304 (string)$intended,
1305 $lang->timeanddate( wfTimestamp( TS_MW, $this->mTimestamp ), true ),
1306 );
1307 }
1308 }