summaryrefslogtreecommitdiff
path: root/includes/Block.php
blob: 34b89e73a30f4396592001cfc271dc8a6f476ea7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
<?php
/**
 * Blocks and bans object
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */
class Block {
	/* public*/ var $mReason, $mTimestamp, $mAuto, $mExpiry, $mHideName;

	protected
		$mId,
		$mFromMaster,

		$mBlockEmail,
		$mDisableUsertalk,
		$mCreateAccount,
		$mParentBlockId;

	/// @var User|String
	protected $target;

	// @var Integer Hack for foreign blocking (CentralAuth)
	protected $forcedTargetID;

	/// @var Block::TYPE_ constant.  Can only be USER, IP or RANGE internally
	protected $type;

	/// @var User
	protected $blocker;

	/// @var Bool
	protected $isHardblock = true;

	/// @var Bool
	protected $isAutoblocking = true;

	# TYPE constants
	const TYPE_USER = 1;
	const TYPE_IP = 2;
	const TYPE_RANGE = 3;
	const TYPE_AUTO = 4;
	const TYPE_ID = 5;

	/**
	 * Constructor
	 * @todo FIXME: Don't know what the best format to have for this constructor is, but fourteen
	 * optional parameters certainly isn't it.
	 */
	function __construct( $address = '', $user = 0, $by = 0, $reason = '',
		$timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
		$hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byText = '' )
	{
		if ( $timestamp === 0 ) {
			$timestamp = wfTimestampNow();
		}

		if ( count( func_get_args() ) > 0 ) {
			# Soon... :D
			# wfDeprecated( __METHOD__ . " with arguments" );
		}

		$this->setTarget( $address );
		if ( $this->target instanceof User && $user ) {
			$this->forcedTargetID = $user; // needed for foreign users
		}
		if ( $by ) { // local user
			$this->setBlocker( User::newFromID( $by ) );
		} else { // foreign user
			$this->setBlocker( $byText );
		}
		$this->mReason = $reason;
		$this->mTimestamp = wfTimestamp( TS_MW, $timestamp );
		$this->mAuto = $auto;
		$this->isHardblock( !$anonOnly );
		$this->prevents( 'createaccount', $createAccount );
		if ( $expiry == 'infinity' || $expiry == wfGetDB( DB_SLAVE )->getInfinity() ) {
			$this->mExpiry = 'infinity';
		} else {
			$this->mExpiry = wfTimestamp( TS_MW, $expiry );
		}
		$this->isAutoblocking( $enableAutoblock );
		$this->mHideName = $hideName;
		$this->prevents( 'sendemail', $blockEmail );
		$this->prevents( 'editownusertalk', !$allowUsertalk );

		$this->mFromMaster = false;
	}

	/**
	 * Load a block from the database, using either the IP address or
	 * user ID. Tries the user ID first, and if that doesn't work, tries
	 * the address.
	 *
	 * @param string $address IP address of user/anon
	 * @param $user Integer: user id of user
	 * @return Block Object
	 * @deprecated since 1.18
	 */
	public static function newFromDB( $address, $user = 0 ) {
		wfDeprecated( __METHOD__, '1.18' );
		return self::newFromTarget( User::whoIs( $user ), $address );
	}

	/**
	 * Load a blocked user from their block id.
	 *
	 * @param $id Integer: Block id to search for
	 * @return Block object or null
	 */
	public static function newFromID( $id ) {
		$dbr = wfGetDB( DB_SLAVE );
		$res = $dbr->selectRow(
			'ipblocks',
			self::selectFields(),
			array( 'ipb_id' => $id ),
			__METHOD__
		);
		if ( $res ) {
			return self::newFromRow( $res );
		} else {
			return null;
		}
	}

	/**
	 * Return the list of ipblocks fields that should be selected to create
	 * a new block.
	 * @return array
	 */
	public static function selectFields() {
		return array(
			'ipb_id',
			'ipb_address',
			'ipb_by',
			'ipb_by_text',
			'ipb_reason',
			'ipb_timestamp',
			'ipb_auto',
			'ipb_anon_only',
			'ipb_create_account',
			'ipb_enable_autoblock',
			'ipb_expiry',
			'ipb_deleted',
			'ipb_block_email',
			'ipb_allow_usertalk',
			'ipb_parent_block_id',
		);
	}

	/**
	 * Check if two blocks are effectively equal.  Doesn't check irrelevant things like
	 * the blocking user or the block timestamp, only things which affect the blocked user
	 *
	 * @param $block Block
	 *
	 * @return bool
	 */
	public function equals( Block $block ) {
		return (
			(string)$this->target == (string)$block->target
			&& $this->type == $block->type
			&& $this->mAuto == $block->mAuto
			&& $this->isHardblock() == $block->isHardblock()
			&& $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
			&& $this->mExpiry == $block->mExpiry
			&& $this->isAutoblocking() == $block->isAutoblocking()
			&& $this->mHideName == $block->mHideName
			&& $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
			&& $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
			&& $this->mReason == $block->mReason
		);
	}

	/**
	 * Clear all member variables in the current object. Does not clear
	 * the block from the DB.
	 * @deprecated since 1.18
	 */
	public function clear() {
		wfDeprecated( __METHOD__, '1.18' );
		# Noop
	}

	/**
	 * Get a block from the DB, with either the given address or the given username
	 *
	 * @param string $address The IP address of the user, or blank to skip IP blocks
	 * @param int $user The user ID, or zero for anonymous users
	 * @return Boolean: the user is blocked from editing
	 * @deprecated since 1.18
	 */
	public function load( $address = '', $user = 0 ) {
		wfDeprecated( __METHOD__, '1.18' );
		if ( $user ) {
			$username = User::whoIs( $user );
			$block = self::newFromTarget( $username, $address );
		} else {
			$block = self::newFromTarget( null, $address );
		}

		if ( $block instanceof Block ) {
			# This is mildly evil, but hey, it's B/C :D
			foreach ( $block as $variable => $value ) {
				$this->$variable = $value;
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Load a block from the database which affects the already-set $this->target:
	 *     1) A block directly on the given user or IP
	 *     2) A rangeblock encompassing the given IP (smallest first)
	 *     3) An autoblock on the given IP
	 * @param $vagueTarget User|String also search for blocks affecting this target.  Doesn't
	 *     make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
	 * @throws MWException
	 * @return Bool whether a relevant block was found
	 */
	protected function newLoad( $vagueTarget = null ) {
		$db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_SLAVE );

		if ( $this->type !== null ) {
			$conds = array(
				'ipb_address' => array( (string)$this->target ),
			);
		} else {
			$conds = array( 'ipb_address' => array() );
		}

		# Be aware that the != '' check is explicit, since empty values will be
		# passed by some callers (bug 29116)
		if ( $vagueTarget != '' ) {
			list( $target, $type ) = self::parseTarget( $vagueTarget );
			switch ( $type ) {
				case self::TYPE_USER:
					# Slightly weird, but who are we to argue?
					$conds['ipb_address'][] = (string)$target;
					break;

				case self::TYPE_IP:
					$conds['ipb_address'][] = (string)$target;
					$conds[] = self::getRangeCond( IP::toHex( $target ) );
					$conds = $db->makeList( $conds, LIST_OR );
					break;

				case self::TYPE_RANGE:
					list( $start, $end ) = IP::parseRange( $target );
					$conds['ipb_address'][] = (string)$target;
					$conds[] = self::getRangeCond( $start, $end );
					$conds = $db->makeList( $conds, LIST_OR );
					break;

				default:
					throw new MWException( "Tried to load block with invalid type" );
			}
		}

		$res = $db->select( 'ipblocks', self::selectFields(), $conds, __METHOD__ );

		# This result could contain a block on the user, a block on the IP, and a russian-doll
		# set of rangeblocks.  We want to choose the most specific one, so keep a leader board.
		$bestRow = null;

		# Lower will be better
		$bestBlockScore = 100;

		# This is begging for $this = $bestBlock, but that's not allowed in PHP :(
		$bestBlockPreventsEdit = null;

		foreach ( $res as $row ) {
			$block = self::newFromRow( $row );

			# Don't use expired blocks
			if ( $block->deleteIfExpired() ) {
				continue;
			}

			# Don't use anon only blocks on users
			if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
				continue;
			}

			if ( $block->getType() == self::TYPE_RANGE ) {
				# This is the number of bits that are allowed to vary in the block, give
				# or take some floating point errors
				$end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
				$start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
				$size = log( $end - $start + 1, 2 );

				# This has the nice property that a /32 block is ranked equally with a
				# single-IP block, which is exactly what it is...
				$score = self::TYPE_RANGE - 1 + ( $size / 128 );

			} else {
				$score = $block->getType();
			}

			if ( $score < $bestBlockScore ) {
				$bestBlockScore = $score;
				$bestRow = $row;
				$bestBlockPreventsEdit = $block->prevents( 'edit' );
			}
		}

		if ( $bestRow !== null ) {
			$this->initFromRow( $bestRow );
			$this->prevents( 'edit', $bestBlockPreventsEdit );
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
	 * @param string $start Hexadecimal IP representation
	 * @param string $end Hexadecimal IP representation, or null to use $start = $end
	 * @return String
	 */
	public static function getRangeCond( $start, $end = null ) {
		if ( $end === null ) {
			$end = $start;
		}
		# Per bug 14634, we want to include relevant active rangeblocks; for
		# rangeblocks, we want to include larger ranges which enclose the given
		# range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
		# so we can improve performance by filtering on a LIKE clause
		$chunk = self::getIpFragment( $start );
		$dbr = wfGetDB( DB_SLAVE );
		$like = $dbr->buildLike( $chunk, $dbr->anyString() );

		# Fairly hard to make a malicious SQL statement out of hex characters,
		# but stranger things have happened...
		$safeStart = $dbr->addQuotes( $start );
		$safeEnd = $dbr->addQuotes( $end );

		return $dbr->makeList(
			array(
				"ipb_range_start $like",
				"ipb_range_start <= $safeStart",
				"ipb_range_end >= $safeEnd",
			),
			LIST_AND
		);
	}

	/**
	 * Get the component of an IP address which is certain to be the same between an IP
	 * address and a rangeblock containing that IP address.
	 * @param  $hex String Hexadecimal IP representation
	 * @return String
	 */
	protected static function getIpFragment( $hex ) {
		global $wgBlockCIDRLimit;
		if ( substr( $hex, 0, 3 ) == 'v6-' ) {
			return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
		} else {
			return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
		}
	}

	/**
	 * Given a database row from the ipblocks table, initialize
	 * member variables
	 * @param $row ResultWrapper: a row from the ipblocks table
	 */
	protected function initFromRow( $row ) {
		$this->setTarget( $row->ipb_address );
		if ( $row->ipb_by ) { // local user
			$this->setBlocker( User::newFromID( $row->ipb_by ) );
		} else { // foreign user
			$this->setBlocker( $row->ipb_by_text );
		}

		$this->mReason = $row->ipb_reason;
		$this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
		$this->mAuto = $row->ipb_auto;
		$this->mHideName = $row->ipb_deleted;
		$this->mId = $row->ipb_id;
		$this->mParentBlockId = $row->ipb_parent_block_id;

		// I wish I didn't have to do this
		$db = wfGetDB( DB_SLAVE );
		if ( $row->ipb_expiry == $db->getInfinity() ) {
			$this->mExpiry = 'infinity';
		} else {
			$this->mExpiry = wfTimestamp( TS_MW, $row->ipb_expiry );
		}

		$this->isHardblock( !$row->ipb_anon_only );
		$this->isAutoblocking( $row->ipb_enable_autoblock );

		$this->prevents( 'createaccount', $row->ipb_create_account );
		$this->prevents( 'sendemail', $row->ipb_block_email );
		$this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
	}

	/**
	 * Create a new Block object from a database row
	 * @param  $row ResultWrapper row from the ipblocks table
	 * @return Block
	 */
	public static function newFromRow( $row ) {
		$block = new Block;
		$block->initFromRow( $row );
		return $block;
	}

	/**
	 * Delete the row from the IP blocks table.
	 *
	 * @throws MWException
	 * @return Boolean
	 */
	public function delete() {
		if ( wfReadOnly() ) {
			return false;
		}

		if ( !$this->getId() ) {
			throw new MWException( "Block::delete() requires that the mId member be filled\n" );
		}

		$dbw = wfGetDB( DB_MASTER );
		$dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__ );
		$dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__ );

		return $dbw->affectedRows() > 0;
	}

	/**
	 * Insert a block into the block table. Will fail if there is a conflicting
	 * block (same name and options) already in the database.
	 *
	 * @param $dbw DatabaseBase if you have one available
	 * @return mixed: false on failure, assoc array on success:
	 *	('id' => block ID, 'autoIds' => array of autoblock IDs)
	 */
	public function insert( $dbw = null ) {
		wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );

		if ( $dbw === null ) {
			$dbw = wfGetDB( DB_MASTER );
		}

		# Don't collide with expired blocks
		Block::purgeExpired();

		$row = $this->getDatabaseArray();
		$row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );

		$dbw->insert(
			'ipblocks',
			$row,
			__METHOD__,
			array( 'IGNORE' )
		);
		$affected = $dbw->affectedRows();
		$this->mId = $dbw->insertId();

		if ( $affected ) {
			$auto_ipd_ids = $this->doRetroactiveAutoblock();
			return array( 'id' => $this->mId, 'autoIds' => $auto_ipd_ids );
		}

		return false;
	}

	/**
	 * Update a block in the DB with new parameters.
	 * The ID field needs to be loaded first.
	 *
	 * @return Int number of affected rows, which should probably be 1 or something has
	 *     gone slightly awry
	 */
	public function update() {
		wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
		$dbw = wfGetDB( DB_MASTER );

		$dbw->update(
			'ipblocks',
			$this->getDatabaseArray( $dbw ),
			array( 'ipb_id' => $this->getId() ),
			__METHOD__
		);

		return $dbw->affectedRows();
	}

	/**
	 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
	 * @param $db DatabaseBase
	 * @return Array
	 */
	protected function getDatabaseArray( $db = null ) {
		if ( !$db ) {
			$db = wfGetDB( DB_SLAVE );
		}
		$expiry = $db->encodeExpiry( $this->mExpiry );

		if ( $this->forcedTargetID ) {
			$uid = $this->forcedTargetID;
		} else {
			$uid = $this->target instanceof User ? $this->target->getID() : 0;
		}

		$a = array(
			'ipb_address'          => (string)$this->target,
			'ipb_user'             => $uid,
			'ipb_by'               => $this->getBy(),
			'ipb_by_text'          => $this->getByName(),
			'ipb_reason'           => $this->mReason,
			'ipb_timestamp'        => $db->timestamp( $this->mTimestamp ),
			'ipb_auto'             => $this->mAuto,
			'ipb_anon_only'        => !$this->isHardblock(),
			'ipb_create_account'   => $this->prevents( 'createaccount' ),
			'ipb_enable_autoblock' => $this->isAutoblocking(),
			'ipb_expiry'           => $expiry,
			'ipb_range_start'      => $this->getRangeStart(),
			'ipb_range_end'        => $this->getRangeEnd(),
			'ipb_deleted'          => intval( $this->mHideName ), // typecast required for SQLite
			'ipb_block_email'      => $this->prevents( 'sendemail' ),
			'ipb_allow_usertalk'   => !$this->prevents( 'editownusertalk' ),
			'ipb_parent_block_id'  => $this->mParentBlockId
		);

		return $a;
	}

	/**
	 * Retroactively autoblocks the last IP used by the user (if it is a user)
	 * blocked by this Block.
	 *
	 * @return Array: block IDs of retroactive autoblocks made
	 */
	protected function doRetroactiveAutoblock() {
		$blockIds = array();
		# If autoblock is enabled, autoblock the LAST IP(s) used
		if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
			wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );

			$continue = wfRunHooks(
				'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );

			if ( $continue ) {
				self::defaultRetroactiveAutoblock( $this, $blockIds );
			}
		}
		return $blockIds;
	}

	/**
	 * Retroactively autoblocks the last IP used by the user (if it is a user)
	 * blocked by this Block. This will use the recentchanges table.
	 *
	 * @param Block $block
	 * @param array &$blockIds
	 * @return Array: block IDs of retroactive autoblocks made
	 */
	protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
		global $wgPutIPinRC;

		// No IPs are in recentchanges table, so nothing to select
		if ( !$wgPutIPinRC ) {
			return;
		}

		$dbr = wfGetDB( DB_SLAVE );

		$options = array( 'ORDER BY' => 'rc_timestamp DESC' );
		$conds = array( 'rc_user_text' => (string)$block->getTarget() );

		// Just the last IP used.
		$options['LIMIT'] = 1;

		$res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
			__METHOD__, $options );

		if ( !$res->numRows() ) {
			# No results, don't autoblock anything
			wfDebug( "No IP found to retroactively autoblock\n" );
		} else {
			foreach ( $res as $row ) {
				if ( $row->rc_ip ) {
					$id = $block->doAutoblock( $row->rc_ip );
					if ( $id ) {
						$blockIds[] = $id;
					}
				}
			}
		}
	}

	/**
	 * Checks whether a given IP is on the autoblock whitelist.
	 * TODO: this probably belongs somewhere else, but not sure where...
	 *
	 * @param string $ip The IP to check
	 * @return Boolean
	 */
	public static function isWhitelistedFromAutoblocks( $ip ) {
		global $wgMemc;

		// Try to get the autoblock_whitelist from the cache, as it's faster
		// than getting the msg raw and explode()'ing it.
		$key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
		$lines = $wgMemc->get( $key );
		if ( !$lines ) {
			$lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
			$wgMemc->set( $key, $lines, 3600 * 24 );
		}

		wfDebug( "Checking the autoblock whitelist..\n" );

		foreach ( $lines as $line ) {
			# List items only
			if ( substr( $line, 0, 1 ) !== '*' ) {
				continue;
			}

			$wlEntry = substr( $line, 1 );
			$wlEntry = trim( $wlEntry );

			wfDebug( "Checking $ip against $wlEntry..." );

			# Is the IP in this range?
			if ( IP::isInRange( $ip, $wlEntry ) ) {
				wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
				return true;
			} else {
				wfDebug( " No match\n" );
			}
		}

		return false;
	}

	/**
	 * Autoblocks the given IP, referring to this Block.
	 *
	 * @param string $autoblockIP the IP to autoblock.
	 * @return mixed: block ID if an autoblock was inserted, false if not.
	 */
	public function doAutoblock( $autoblockIP ) {
		# If autoblocks are disabled, go away.
		if ( !$this->isAutoblocking() ) {
			return false;
		}

		# Check for presence on the autoblock whitelist.
		if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
			return false;
		}

		# Allow hooks to cancel the autoblock.
		if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
			wfDebug( "Autoblock aborted by hook.\n" );
			return false;
		}

		# It's okay to autoblock. Go ahead and insert/update the block...

		# Do not add a *new* block if the IP is already blocked.
		$ipblock = Block::newFromTarget( $autoblockIP );
		if ( $ipblock ) {
			# Check if the block is an autoblock and would exceed the user block
			# if renewed. If so, do nothing, otherwise prolong the block time...
			if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
				$this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
			) {
				# Reset block timestamp to now and its expiry to
				# $wgAutoblockExpiry in the future
				$ipblock->updateTimestamp();
			}
			return false;
		}

		# Make a new block object with the desired properties.
		$autoblock = new Block;
		wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
		$autoblock->setTarget( $autoblockIP );
		$autoblock->setBlocker( $this->getBlocker() );
		$autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )->inContentLanguage()->plain();
		$timestamp = wfTimestampNow();
		$autoblock->mTimestamp = $timestamp;
		$autoblock->mAuto = 1;
		$autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
		# Continue suppressing the name if needed
		$autoblock->mHideName = $this->mHideName;
		$autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
		$autoblock->mParentBlockId = $this->mId;

		if ( $this->mExpiry == 'infinity' ) {
			# Original block was indefinite, start an autoblock now
			$autoblock->mExpiry = Block::getAutoblockExpiry( $timestamp );
		} else {
			# If the user is already blocked with an expiry date, we don't
			# want to pile on top of that.
			$autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $timestamp ) );
		}

		# Insert the block...
		$status = $autoblock->insert();
		return $status
			? $status['id']
			: false;
	}

	/**
	 * Check if a block has expired. Delete it if it is.
	 * @return Boolean
	 */
	public function deleteIfExpired() {
		wfProfileIn( __METHOD__ );

		if ( $this->isExpired() ) {
			wfDebug( "Block::deleteIfExpired() -- deleting\n" );
			$this->delete();
			$retVal = true;
		} else {
			wfDebug( "Block::deleteIfExpired() -- not expired\n" );
			$retVal = false;
		}

		wfProfileOut( __METHOD__ );
		return $retVal;
	}

	/**
	 * Has the block expired?
	 * @return Boolean
	 */
	public function isExpired() {
		$timestamp = wfTimestampNow();
		wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );

		if ( !$this->mExpiry ) {
			return false;
		} else {
			return $timestamp > $this->mExpiry;
		}
	}

	/**
	 * Is the block address valid (i.e. not a null string?)
	 * @return Boolean
	 */
	public function isValid() {
		return $this->getTarget() != null;
	}

	/**
	 * Update the timestamp on autoblocks.
	 */
	public function updateTimestamp() {
		if ( $this->mAuto ) {
			$this->mTimestamp = wfTimestamp();
			$this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );

			$dbw = wfGetDB( DB_MASTER );
			$dbw->update( 'ipblocks',
				array( /* SET */
					'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
					'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
				),
				array( /* WHERE */
					'ipb_address' => (string)$this->getTarget()
				),
				__METHOD__
			);
		}
	}

	/**
	 * Get the IP address at the start of the range in Hex form
	 * @throws MWException
	 * @return String IP in Hex form
	 */
	public function getRangeStart() {
		switch ( $this->type ) {
			case self::TYPE_USER:
				return '';
			case self::TYPE_IP:
				return IP::toHex( $this->target );
			case self::TYPE_RANGE:
				list( $start, /*...*/ ) = IP::parseRange( $this->target );
				return $start;
			default:
				throw new MWException( "Block with invalid type" );
		}
	}

	/**
	 * Get the IP address at the end of the range in Hex form
	 * @throws MWException
	 * @return String IP in Hex form
	 */
	public function getRangeEnd() {
		switch ( $this->type ) {
			case self::TYPE_USER:
				return '';
			case self::TYPE_IP:
				return IP::toHex( $this->target );
			case self::TYPE_RANGE:
				list( /*...*/, $end ) = IP::parseRange( $this->target );
				return $end;
			default:
				throw new MWException( "Block with invalid type" );
		}
	}

	/**
	 * Get the user id of the blocking sysop
	 *
	 * @return Integer (0 for foreign users)
	 */
	public function getBy() {
		$blocker = $this->getBlocker();
		return ( $blocker instanceof User )
			? $blocker->getId()
			: 0;
	}

	/**
	 * Get the username of the blocking sysop
	 *
	 * @return String
	 */
	public function getByName() {
		$blocker = $this->getBlocker();
		return ( $blocker instanceof User )
			? $blocker->getName()
			: (string)$blocker; // username
	}

	/**
	 * Get the block ID
	 * @return int
	 */
	public function getId() {
		return $this->mId;
	}

	/**
	 * Get/set the SELECT ... FOR UPDATE flag
	 * @deprecated since 1.18
	 *
	 * @param $x Bool
	 */
	public function forUpdate( $x = null ) {
		wfDeprecated( __METHOD__, '1.18' );
		# noop
	}

	/**
	 * Get/set a flag determining whether the master is used for reads
	 *
	 * @param $x Bool
	 * @return Bool
	 */
	public function fromMaster( $x = null ) {
		return wfSetVar( $this->mFromMaster, $x );
	}

	/**
	 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
	 * @param $x Bool
	 * @return  Bool
	 */
	public function isHardblock( $x = null ) {
		wfSetVar( $this->isHardblock, $x );

		# You can't *not* hardblock a user
		return $this->getType() == self::TYPE_USER
			? true
			: $this->isHardblock;
	}

	public function isAutoblocking( $x = null ) {
		wfSetVar( $this->isAutoblocking, $x );

		# You can't put an autoblock on an IP or range as we don't have any history to
		# look over to get more IPs from
		return $this->getType() == self::TYPE_USER
			? $this->isAutoblocking
			: false;
	}

	/**
	 * Get/set whether the Block prevents a given action
	 * @param $action String
	 * @param $x Bool
	 * @return Bool
	 */
	public function prevents( $action, $x = null ) {
		switch ( $action ) {
			case 'edit':
				# For now... <evil laugh>
				return true;

			case 'createaccount':
				return wfSetVar( $this->mCreateAccount, $x );

			case 'sendemail':
				return wfSetVar( $this->mBlockEmail, $x );

			case 'editownusertalk':
				return wfSetVar( $this->mDisableUsertalk, $x );

			default:
				return null;
		}
	}

	/**
	 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
	 * @return String, text is escaped
	 */
	public function getRedactedName() {
		if ( $this->mAuto ) {
			return Html::rawElement(
				'span',
				array( 'class' => 'mw-autoblockid' ),
				wfMessage( 'autoblockid', $this->mId )
			);
		} else {
			return htmlspecialchars( $this->getTarget() );
		}
	}

	/**
	 * Encode expiry for DB
	 *
	 * @param string $expiry timestamp for expiry, or
	 * @param $db DatabaseBase object
	 * @return String
	 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
	 */
	public static function encodeExpiry( $expiry, $db ) {
		wfDeprecated( __METHOD__, '1.18' );
		return $db->encodeExpiry( $expiry );
	}

	/**
	 * Decode expiry which has come from the DB
	 *
	 * @param string $expiry Database expiry format
	 * @param int $timestampType Requested timestamp format
	 * @return String
	 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
	 */
	public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
		wfDeprecated( __METHOD__, '1.18' );
		global $wgContLang;
		return $wgContLang->formatExpiry( $expiry, $timestampType );
	}

	/**
	 * Get a timestamp of the expiry for autoblocks
	 *
	 * @param $timestamp String|Int
	 * @return String
	 */
	public static function getAutoblockExpiry( $timestamp ) {
		global $wgAutoblockExpiry;

		return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
	}

	/**
	 * Gets rid of unneeded numbers in quad-dotted/octet IP strings
	 * For example, 127.111.113.151/24 -> 127.111.113.0/24
	 * @param string $range IP address to normalize
	 * @return string
	 * @deprecated since 1.18, call IP::sanitizeRange() directly
	 */
	public static function normaliseRange( $range ) {
		wfDeprecated( __METHOD__, '1.18' );
		return IP::sanitizeRange( $range );
	}

	/**
	 * Purge expired blocks from the ipblocks table
	 */
	public static function purgeExpired() {
		if ( wfReadOnly() ) {
			return;
		}

		$method = __METHOD__;
		$dbw = wfGetDB( DB_MASTER );
		$dbw->onTransactionIdle( function() use ( $dbw, $method ) {
			$dbw->delete( 'ipblocks',
				array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
		} );
	}

	/**
	 * Get a value to insert into expiry field of the database when infinite expiry
	 * is desired
	 * @deprecated since 1.18, call $dbr->getInfinity() directly
	 * @return String
	 */
	public static function infinity() {
		wfDeprecated( __METHOD__, '1.18' );
		return wfGetDB( DB_SLAVE )->getInfinity();
	}

	/**
	 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
	 * ("24 May 2034"), into an absolute timestamp we can put into the database.
	 * @param string $expiry whatever was typed into the form
	 * @return String: timestamp or "infinity" string for th DB implementation
	 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
	 */
	public static function parseExpiryInput( $expiry ) {
		wfDeprecated( __METHOD__, '1.18' );
		return SpecialBlock::parseExpiryInput( $expiry );
	}

	/**
	 * Given a target and the target's type, get an existing Block object if possible.
	 * @param $specificTarget String|User|Int a block target, which may be one of several types:
	 *     * A user to block, in which case $target will be a User
	 *     * An IP to block, in which case $target will be a User generated by using
	 *       User::newFromName( $ip, false ) to turn off name validation
	 *     * An IP range, in which case $target will be a String "123.123.123.123/18" etc
	 *     * The ID of an existing block, in the format "#12345" (since pure numbers are valid
	 *       usernames
	 *     Calling this with a user, IP address or range will not select autoblocks, and will
	 *     only select a block where the targets match exactly (so looking for blocks on
	 *     1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
	 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
	 *     affects that target (so for an IP address, get ranges containing that IP; and also
	 *     get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
	 * @param bool $fromMaster whether to use the DB_MASTER database
	 * @return Block|null (null if no relevant block could be found).  The target and type
	 *     of the returned Block will refer to the actual block which was found, which might
	 *     not be the same as the target you gave if you used $vagueTarget!
	 */
	public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {

		list( $target, $type ) = self::parseTarget( $specificTarget );
		if ( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ) {
			return Block::newFromID( $target );

		} elseif ( $target === null && $vagueTarget == '' ) {
			# We're not going to find anything useful here
			# Be aware that the == '' check is explicit, since empty values will be
			# passed by some callers (bug 29116)
			return null;

		} elseif ( in_array( $type, array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ) ) ) {
			$block = new Block();
			$block->fromMaster( $fromMaster );

			if ( $type !== null ) {
				$block->setTarget( $target );
			}

			if ( $block->newLoad( $vagueTarget ) ) {
				return $block;
			}
		}
		return null;
	}


	/**
	 * Get all blocks that match any IP from an array of IP addresses
	 *
	 * @param Array $ipChain list of IPs (strings), usually retrieved from the
	 *	   X-Forwarded-For header of the request
	 * @param Bool $isAnon Exclude anonymous-only blocks if false
	 * @param Bool $fromMaster Whether to query the master or slave database
	 * @return Array of Blocks
	 * @since 1.22
	 */
	public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
		if ( !count( $ipChain ) ) {
			return array();
		}

		wfProfileIn( __METHOD__ );
		$conds = array();
		foreach ( array_unique( $ipChain ) as $ipaddr ) {
			# Discard invalid IP addresses. Since XFF can be spoofed and we do not
			# necessarily trust the header given to us, make sure that we are only
			# checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
			# Do not treat private IP spaces as special as it may be desirable for wikis
			# to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
			if ( !IP::isValid( $ipaddr ) ) {
				continue;
			}
			# Don't check trusted IPs (includes local squids which will be in every request)
			if ( wfIsTrustedProxy( $ipaddr ) ) {
				continue;
			}
			# Check both the original IP (to check against single blocks), as well as build
			# the clause to check for rangeblocks for the given IP.
			$conds['ipb_address'][] = $ipaddr;
			$conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
		}

		if ( !count( $conds ) ) {
			wfProfileOut( __METHOD__ );
			return array();
		}

		if ( $fromMaster ) {
			$db = wfGetDB( DB_MASTER );
		} else {
			$db = wfGetDB( DB_SLAVE );
		}
		$conds = $db->makeList( $conds, LIST_OR );
		if ( !$isAnon ) {
			$conds = array( $conds, 'ipb_anon_only' => 0 );
		}
		$selectFields = array_merge(
			array( 'ipb_range_start', 'ipb_range_end' ),
			Block::selectFields()
		);
		$rows = $db->select( 'ipblocks',
			$selectFields,
			$conds,
			__METHOD__
		);

		$blocks = array();
		foreach ( $rows as $row ) {
			$block = self::newFromRow( $row );
			if ( !$block->deleteIfExpired()  ) {
				$blocks[] = $block;
			}
		}

		wfProfileOut( __METHOD__ );
		return $blocks;
	}

	/**
	 * From a list of multiple blocks, find the most exact and strongest Block.
	 * The logic for finding the "best" block is:
	 *  - Blocks that match the block's target IP are preferred over ones in a range
	 *  - Hardblocks are chosen over softblocks that prevent account creation
	 *  - Softblocks that prevent account creation are chosen over other softblocks
	 *  - Other softblocks are chosen over autoblocks
	 *  - If there are multiple exact or range blocks at the same level, the one chosen
	 *    is random

	 * @param Array $ipChain list of IPs (strings). This is used to determine how "close"
	 * 	  a block is to the server, and if a block matches exactly, or is in a range.
	 *	  The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
	 *	  local-squid, ...)
	 * @param Array $block Array of blocks
	 * @return Block|null the "best" block from the list
	 */
	public static function chooseBlock( array $blocks, array $ipChain ) {
		if ( !count( $blocks ) ) {
			return null;
		} elseif ( count( $blocks ) == 1 ) {
			return $blocks[0];
		}

		wfProfileIn( __METHOD__ );

		// Sort hard blocks before soft ones and secondarily sort blocks
		// that disable account creation before those that don't.
		usort( $blocks, function( Block $a, Block $b ) {
			$aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
			$bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
			return strcmp( $bWeight, $aWeight ); // highest weight first
		} );

		$blocksListExact = array(
			'hard' => false,
			'disable_create' => false,
			'other' => false,
			'auto' => false
		);
		$blocksListRange = array(
			'hard' => false,
			'disable_create' => false,
			'other' => false,
			'auto' => false
		);
		$ipChain = array_reverse( $ipChain );

		foreach ( $blocks as $block ) {
			// Stop searching if we have already have a "better" block. This
			// is why the order of the blocks matters
			if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
				break;
			} elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
				break;
			}

			foreach ( $ipChain as $checkip ) {
				$checkipHex = IP::toHex( $checkip );
				if ( (string)$block->getTarget() === $checkip ) {
					if ( $block->isHardblock() ) {
						$blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
					} elseif ( $block->prevents( 'createaccount' ) ) {
						$blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
					} elseif ( $block->mAuto ) {
						$blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
					} else {
						$blocksListExact['other'] = $blocksListExact['other'] ?: $block;
					}
					// We found closest exact match in the ip list, so go to the next Block
					break;
				} elseif ( array_filter( $blocksListExact ) == array()
					&& $block->getRangeStart() <= $checkipHex
					&& $block->getRangeEnd() >= $checkipHex
				) {
					if ( $block->isHardblock() ) {
						$blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
					} elseif ( $block->prevents( 'createaccount' ) ) {
						$blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
					} elseif ( $block->mAuto ) {
						$blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
					} else {
						$blocksListRange['other'] = $blocksListRange['other'] ?: $block;
					}
					break;
				}
			}
		}

		if ( array_filter( $blocksListExact ) == array() ) {
			$blocksList = &$blocksListRange;
		} else {
			$blocksList = &$blocksListExact;
		}

		$chosenBlock = null;
		if ( $blocksList['hard'] ) {
			$chosenBlock = $blocksList['hard'];
		} elseif ( $blocksList['disable_create'] ) {
			$chosenBlock = $blocksList['disable_create'];
		} elseif ( $blocksList['other'] ) {
			$chosenBlock = $blocksList['other'];
		} elseif ( $blocksList['auto'] ) {
			$chosenBlock = $blocksList['auto'];
		} else {
			wfProfileOut( __METHOD__ );
			throw new MWException( "Proxy block found, but couldn't be classified." );
		}

		wfProfileOut( __METHOD__ );
		return $chosenBlock;
	}

	/**
	 * From an existing Block, get the target and the type of target.
	 * Note that, except for null, it is always safe to treat the target
	 * as a string; for User objects this will return User::__toString()
	 * which in turn gives User::getName().
	 *
	 * @param $target String|Int|User|null
	 * @return array( User|String|null, Block::TYPE_ constant|null )
	 */
	public static function parseTarget( $target ) {
		# We may have been through this before
		if ( $target instanceof User ) {
			if ( IP::isValid( $target->getName() ) ) {
				return array( $target, self::TYPE_IP );
			} else {
				return array( $target, self::TYPE_USER );
			}
		} elseif ( $target === null ) {
			return array( null, null );
		}

		$target = trim( $target );

		if ( IP::isValid( $target ) ) {
			# We can still create a User if it's an IP address, but we need to turn
			# off validation checking (which would exclude IP addresses)
			return array(
				User::newFromName( IP::sanitizeIP( $target ), false ),
				Block::TYPE_IP
			);

		} elseif ( IP::isValidBlock( $target ) ) {
			# Can't create a User from an IP range
			return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
		}

		# Consider the possibility that this is not a username at all
		# but actually an old subpage (bug #29797)
		if ( strpos( $target, '/' ) !== false ) {
			# An old subpage, drill down to the user behind it
			$parts = explode( '/', $target );
			$target = $parts[0];
		}

		$userObj = User::newFromName( $target );
		if ( $userObj instanceof User ) {
			# Note that since numbers are valid usernames, a $target of "12345" will be
			# considered a User.  If you want to pass a block ID, prepend a hash "#12345",
			# since hash characters are not valid in usernames or titles generally.
			return array( $userObj, Block::TYPE_USER );

		} elseif ( preg_match( '/^#\d+$/', $target ) ) {
			# Autoblock reference in the form "#12345"
			return array( substr( $target, 1 ), Block::TYPE_AUTO );

		} else {
			# WTF?
			return array( null, null );
		}
	}

	/**
	 * Get the type of target for this particular block
	 * @return Block::TYPE_ constant, will never be TYPE_ID
	 */
	public function getType() {
		return $this->mAuto
			? self::TYPE_AUTO
			: $this->type;
	}

	/**
	 * Get the target and target type for this particular Block.  Note that for autoblocks,
	 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
	 * in this situation.
	 * @return array( User|String, Block::TYPE_ constant )
	 * @todo FIXME: This should be an integral part of the Block member variables
	 */
	public function getTargetAndType() {
		return array( $this->getTarget(), $this->getType() );
	}

	/**
	 * Get the target for this particular Block.  Note that for autoblocks,
	 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
	 * in this situation.
	 * @return User|String
	 */
	public function getTarget() {
		return $this->target;
	}

	/**
	 * @since 1.19
	 *
	 * @return Mixed|string
	 */
	public function getExpiry() {
		return $this->mExpiry;
	}

	/**
	 * Set the target for this block, and update $this->type accordingly
	 * @param $target Mixed
	 */
	public function setTarget( $target ) {
		list( $this->target, $this->type ) = self::parseTarget( $target );
	}

	/**
	 * Get the user who implemented this block
	 * @return User|string Local User object or string for a foreign user
	 */
	public function getBlocker() {
		return $this->blocker;
	}

	/**
	 * Set the user who implemented (or will implement) this block
	 * @param $user User|string Local User object or username string for foreign users
	 */
	public function setBlocker( $user ) {
		$this->blocker = $user;
	}

	/**
	 * Get the key and parameters for the corresponding error message.
	 *
	 * @since 1.22
	 * @param IContextSource $context
	 * @return array
	 */
	public function getPermissionsError( IContextSource $context ) {
		$blocker = $this->getBlocker();
		if ( $blocker instanceof User ) { // local user
			$blockerUserpage = $blocker->getUserPage();
			$link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
		} else { // foreign user
			$link = $blocker;
		}

		$reason = $this->mReason;
		if ( $reason == '' ) {
			$reason = $context->msg( 'blockednoreason' )->text();
		}

		/* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
		 * This could be a username, an IP range, or a single IP. */
		$intended = $this->getTarget();

		$lang = $context->getLanguage();
		return array(
			$this->mAuto ? 'autoblockedtext' : 'blockedtext',
			$link,
			$reason,
			$context->getRequest()->getIP(),
			$this->getByName(),
			$this->getId(),
			$lang->formatExpiry( $this->mExpiry ),
			(string)$intended,
			$lang->timeanddate( wfTimestamp( TS_MW, $this->mTimestamp ), true ),
		);
	}
}