summaryrefslogtreecommitdiff
blob: 743065baa246abd4b2af9960bd43ffda59f54b10 (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
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
<?php

use MediaWiki\Block\DatabaseBlock;
use MediaWiki\Cache\LinkBatchFactory;
use MediaWiki\MediaWikiServices;
use MediaWiki\Revision\RevisionRecord;
use Wikimedia\IPUtils;
use Wikimedia\Rdbms\FakeResultWrapper;
use Wikimedia\Rdbms\IDatabase;
use Wikimedia\Rdbms\IResultWrapper;

class SpecialCheckUser extends SpecialPage {
	/**
	 * @var string[] $message Used to cache frequently used messages
	 */
	protected $message = [];

	/**
	 * @var null|string
	 */
	private $lastdate = null;

	/**
	 * Reason for executing a CheckUser
	 * @var string
	 */
	protected $reason = '';

	/** @var LinkBatchFactory */
	private $linkBatchFactory;

	public function __construct( LinkBatchFactory $linkBatchFactory ) {
		parent::__construct( 'CheckUser', 'checkuser' );
		$this->linkBatchFactory = $linkBatchFactory;
	}

	public function doesWrites() {
		return true; // logging
	}

	public function execute( $subpage ) {
		$this->setHeaders();
		$this->addHelpLink( 'Extension:CheckUser' );
		$this->checkPermissions();
		// Logging and blocking requires writing so stop from here if read-only mode
		$this->checkReadOnly();

		// Blocked users are not allowed to run checkuser queries (bug T157883)
		$block = $this->getUser()->getBlock();
		if ( $block && $block->isSitewide() ) {
			throw new UserBlockedError( $block );
		}

		$out = $this->getOutput();
		$request = $this->getRequest();
		$user = $request->getText( 'user', $request->getText( 'ip', $subpage ) );
		$user = trim( $user );
		$permissionManager = MediaWikiServices::getInstance()->getPermissionManager();

		if ( $permissionManager->userHasRight( $this->getUser(), 'checkuser-log' ) ) {
			$subtitleLink = $this->getLinkRenderer()->makeKnownLink(
				SpecialPage::getTitleFor( 'CheckUserLog' ),
				$this->msg( 'checkuser-showlog' )->text()
			);
			if ( !$user === false ) {
				$subtitleLink .= ' | ' . $this->getLinkRenderer()->makeKnownLink(
					SpecialPage::getTitleFor( 'CheckUserLog', $user ),
					$this->msg( 'checkuser-recent-checks' )->text()
				);
			}
			$out->addSubtitle( $subtitleLink );
		}

		if ( $this->getConfig()->get( 'CheckUserEnableSpecialInvestigate' ) ) {
			$out->enableOOUI();
			$out->addModuleStyles( 'oojs-ui.styles.icons-interactions' );
			$icon = new OOUI\IconWidget( [ 'icon' => 'lightbulb' ] );
			$investigateLink = $this->getLinkRenderer()->makeKnownLink(
				SpecialPage::getTitleFor( 'Investigate' ),
				$this->msg( 'checkuser-link-investigate-label' )->text()
			);
			$out->setIndicators( [ 'investigate-link' => $icon . $investigateLink ] );
		}

		$this->reason = $request->getText( 'reason' );
		$blockreason = $request->getText( 'blockreason', '' );
		$disableUserTalk = $request->getBool( 'blocktalk', false );
		$disableEmail = $request->getBool( 'blockemail', false );
		$checktype = $request->getVal( 'checktype' );
		$period = $request->getInt( 'period' );
		$users = $request->getArray( 'users' );
		$tag = $request->getBool( 'usetag' ) ?
			trim( $request->getVal( 'tag' ) ) : '';
		$talkTag = $request->getBool( 'usettag' ) ?
			trim( $request->getVal( 'talktag' ) ) : '';

		$blockParams = [
			'reason' => $blockreason,
			'talk' => $disableUserTalk,
			'email' => $disableEmail,
			'reblock' => $request->getBool( 'reblock' )
		];

		$ip = $name = $xff = '';
		$m = [];
		if ( IPUtils::isIPAddress( $user ) ) {
			// A single IP address or an IP range
			$ip = IPUtils::sanitizeIP( $user );
		} elseif ( preg_match( '/^(.+)\/xff$/', $user, $m ) && IPUtils::isIPAddress( $m[1] ) ) {
			// A single IP address or range with XFF string included
			$xff = IPUtils::sanitizeIP( $m[1] );
		} else {
			// A user?
			$name = $user;
		}

		$this->showIntroductoryText();
		$this->showForm( $user, $checktype, $ip, $xff, $name, $period );

		// Perform one of the various submit operations...
		if ( $request->wasPosted() ) {
			if ( !$this->getUser()->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
				$out->wrapWikiMsg( '<div class="error">$1</div>', 'checkuser-token-fail' );
			} elseif ( $request->getVal( 'action' ) === 'block' ) {
				$this->doMassUserBlock( $users, $blockParams, $tag, $talkTag );
			} elseif ( !$this->checkReason() ) {
				$out->addWikiMsg( 'checkuser-noreason' );
			} elseif ( $checktype == 'subuserips' ) {
				$this->doUserIPsRequest( $name, $period );
			} elseif ( $xff && $checktype == 'subedits' ) {
				$this->doIPEditsRequest( $xff, true, $period );
			} elseif ( $ip && $checktype == 'subedits' ) {
				$this->doIPEditsRequest( $ip, false, $period );
			} elseif ( $name && $checktype == 'subedits' ) {
				$this->doUserEditsRequest( $user, $period );
			} elseif ( $xff && $checktype == 'subipusers' ) {
				$this->doIPUsersRequest( $xff, true, $period, $tag, $talkTag );
			} elseif ( $checktype == 'subipusers' ) {
				$this->doIPUsersRequest( $ip, false, $period, $tag, $talkTag );
			}
		}
		// Add CIDR calculation convenience JS form
		$this->addJsCIDRForm();
		$out->addModules( 'ext.checkUser' );
		$out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
	}

	protected function showIntroductoryText() {
		$cidrLimit = $this->getConfig()->get( 'CheckUserCIDRLimit' );
		$this->getOutput()->addWikiMsg(
			'checkuser-summary',
			$cidrLimit['IPv4'],
			$cidrLimit['IPv6']
		);
	}

	/**
	 * Show the CheckUser query form
	 *
	 * @param string $user
	 * @param string $checktype
	 * @param string $ip
	 * @param string $xff
	 * @param string $name
	 * @param int $period
	 */
	protected function showForm( $user, $checktype, $ip, $xff, $name, $period ) {
		$action = htmlspecialchars( $this->getPageTitle()->getLocalURL() );
		// Fill in requested type if it makes sense
		$encipusers = $encedits = $encuserips = false;
		if ( $checktype == 'subipusers' && ( $ip || $xff ) ) {
			$encipusers = true;
		} elseif ( $checktype == 'subuserips' && $name ) {
			$encuserips = true;
		} elseif ( $checktype == 'subedits' ) {
			$encedits = true;
		// Defaults otherwise
		} elseif ( $ip || $xff ) {
			$encedits = true;
		} else {
			$encuserips = true;
		}

		$form = Xml::openElement( 'form', [ 'action' => $action,
			'name' => 'checkuserform', 'id' => 'checkuserform', 'method' => 'post' ] );
		$form .= '<fieldset><legend>' . $this->msg( 'checkuser-query' )->escaped() . '</legend>';
		$form .= Xml::openElement( 'table', [ 'style' => 'border:0' ] );
		$form .= '<tr>';
		$form .= '<td>' . $this->msg( 'checkuser-target' )->escaped() . '</td>';
		// User field should fit things like "2001:0db8:85a3:08d3:1319:8a2e:0370:7344/100/xff"
		$form .= '<td>' . Xml::input( 'user', 46, $user, [ 'id' => 'checktarget' ] );
		$form .= '&#160;' . $this->getPeriodMenu( $period ) . '</td>';
		$form .= '</tr><tr>';
		$form .= '<td></td>';
		$form .= Xml::openElement( 'td', [ 'class' => 'checkuserradios' ] );
		$form .= Xml::openElement( 'table', [ 'style' => 'border:0' ] );
		$form .= '<tr>';
		$form .= '<td>' .
			Xml::radio( 'checktype', 'subuserips', $encuserips, [ 'id' => 'subuserips' ] );
		$form .= ' ' . Xml::label( $this->msg( 'checkuser-ips' )->text(), 'subuserips' ) . '</td>';
		$form .= '<td>' .
			Xml::radio( 'checktype', 'subedits', $encedits, [ 'id' => 'subedits' ] );
		$form .= ' ' . Xml::label( $this->msg( 'checkuser-edits' )->text(), 'subedits' ) . '</td>';
		$form .= '<td>' .
			Xml::radio( 'checktype', 'subipusers', $encipusers, [ 'id' => 'subipusers' ] );
		$form .= ' ' .
			Xml::label( $this->msg( 'checkuser-users' )->text(), 'subipusers' ) . '</td>';
		$form .= '</tr>';
		$form .= Xml::closeElement( 'table' );
		$form .= Xml::closeElement( 'td' );
		$form .= '</tr><tr>';
		$form .= '<td>' . $this->msg( 'checkuser-reason' )->escaped() . '</td>';
		$form .= '<td>' . Xml::input( 'reason', 46, $this->reason,
			[ 'maxlength' => '150', 'id' => 'checkreason' ] );
		$form .= '&#160; &#160;' . Xml::submitButton( $this->msg( 'checkuser-check' )->text(),
			[ 'id' => 'checkusersubmit', 'name' => 'checkusersubmit' ] ) . '</td>';
		$form .= '</tr>';
		$form .= Xml::closeElement( 'table' );
		$form .= '</fieldset>';
		$form .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
		$form .= Xml::closeElement( 'form' );

		$this->getOutput()->addHTML( $form );
	}

	/**
	 * Get a selector of time period options
	 * @param int $selected Currently selected option
	 * @return string
	 */
	protected function getPeriodMenu( $selected ) {
		$s = '<label for="period">' .
			$this->msg( 'checkuser-period' )->escaped() . '</label>&#160;';
		$s .= Xml::openElement(
			'select',
			[ 'name' => 'period', 'id' => 'period', 'style' => 'margin-top:.2em;' ]
		);
		$s .= Xml::option( $this->msg( 'checkuser-week-1' )->text(), '7', $selected === 7 );
		$s .= Xml::option( $this->msg( 'checkuser-week-2' )->text(), '14', $selected === 14 );
		$s .= Xml::option( $this->msg( 'checkuser-month' )->text(), '31', $selected === 31 );
		$s .= Xml::option( $this->msg( 'checkuser-all' )->text(), '0', $selected === 0 );
		$s .= Xml::closeElement( 'select' ) . "\n";
		return $s;
	}

	/**
	 * Make a quick JS form for admins to calculate block ranges
	 */
	protected function addJsCIDRForm() {
		$s = '<fieldset id="mw-checkuser-cidrform" style="display:none; clear:both;">' .
			'<legend>' . $this->msg( 'checkuser-cidr-label' )->escaped() . '</legend>';
		$s .= '<textarea id="mw-checkuser-iplist" dir="ltr" rows="5" cols="50"></textarea><br />';
		$s .= $this->msg( 'checkuser-cidr-res' )->escaped() . '&#160;' .
			Xml::input( 'mw-checkuser-cidr-res', 35, '', [ 'id' => 'mw-checkuser-cidr-res' ] ) .
			'&#160;<strong id="mw-checkuser-ipnote"></strong>';
		$s .= '</fieldset>';
		$this->getOutput()->addHTML( $s );
	}

	/**
	 * @return bool
	 */
	protected function checkReason() {
		return ( !$this->getConfig()->get( 'CheckUserForceSummary' ) || strlen( $this->reason ) );
	}

	/**
	 * As we use the same small set of messages in various methods and that
	 * they are called often, we call them once and save them in $this->message
	 */
	protected function preCacheMessages() {
		if ( $this->message === [] ) {
			$msgKeys = [ 'diff', 'hist', 'minoreditletter', 'newpageletter', 'blocklink', 'log' ];
			foreach ( $msgKeys as $msg ) {
				$this->message[$msg] = $this->msg( $msg )->escaped();
			}
		}
	}

	/**
	 * Block a list of selected users
	 * @param array $users
	 * @param array $blockParams
	 * @param string $tag
	 * @param string $talkTag
	 */
	protected function doMassUserBlock( $users, $blockParams, $tag = '', $talkTag = '' ) {
		$usersCount = count( $users );
		$permissionManager = MediaWikiServices::getInstance()->getPermissionManager();

		if ( !$permissionManager->userHasRight( $this->getUser(), 'block' )
			|| $this->getUser()->getBlock()
			|| !$usersCount
		) {
			$this->getOutput()->addWikiMsg( 'checkuser-block-failure' );
			return;
		} elseif ( $usersCount > $this->getConfig()->get( 'CheckUserMaxBlocks' ) ) {
			$this->getOutput()->addWikiMsg( 'checkuser-block-limit' );
			return;
		} elseif ( !$blockParams['reason'] ) {
			$this->getOutput()->addWikiMsg( 'checkuser-block-noreason' );
			return;
		}

		$blockedUsers = $this->doMassUserBlockInternal(
			$users,
			$blockParams,
			$tag,
			$talkTag
		);
		$blockedCount = count( $blockedUsers );
		if ( $blockedCount > 0 ) {
			$lang = $this->getLanguage();
			$this->getOutput()->addWikiMsg( 'checkuser-block-success',
				$lang->listToText( $blockedUsers ),
				$lang->formatNum( $blockedCount )
			);
		} else {
			$this->getOutput()->addWikiMsg( 'checkuser-block-failure' );
		}
	}

	/**
	 * Block a list of selected users
	 *
	 * @param string[] $users
	 * @param array $blockParams
	 * @param string $tag replaces user pages
	 * @param string $talkTag replaces user talk pages
	 * @return string[] List of html-safe usernames which were actually were blocked
	 */
	protected function doMassUserBlockInternal(
		$users,
		array $blockParams,
		$tag = '',
		$talkTag = ''
	) {
		$currentUser = $this->getUser();
		$blockAllowsUTEdit = $this->getConfig()->get( 'BlockAllowsUTEdit' );
		$safeUsers = [];
		foreach ( $users as $name ) {
			$u = User::newFromName( $name, false );
			// Do some checks to make sure we can block this user first
			if ( $u === null ) {
				// Invalid user
				continue;
			}
			$isIP = IPUtils::isIPAddress( $u->getName() );
			if ( !$u->getId() && !$isIP ) {
				// Not a registered user or an IP
				continue;
			}

			if ( $u->getBlock() && !$blockParams['reblock'] ) {
				continue;
			}

			if (
				SpecialBlock::canBlockEmail( $this->getUser() ) ||
				!isset( $blockParams['email' ] ) ||
				$blockParams['email'] === false
			) {
				$res = SpecialBlock::processForm( [
					'Target' => $u->getName(),
					'Reason' => [ $blockParams['reason'] ],
					'Expiry' => $isIP ? '1 week' : 'indefinite',
					'HardBlock' => !$isIP,
					'CreateAccount' => true,
					'AutoBlock' => true,
					'DisableEmail' => $blockParams['email'] ?? false,
					'DisableUTEdit' => $blockParams['talk'],
					'Reblock' => $blockParams['reblock'],
					'Confirm' => true,
					'Watch' => false,
				], $this->getContext() );

				if ( $res === true ) {
					$userPage = $u->getUserPage();

					$safeUsers[] = "[[{$userPage->getPrefixedText()}|{$userPage->getText()}]]";

					// Tag user page and user talk page
					$this->tagPage( $userPage, $tag, $blockParams['reason'] );
					$this->tagPage( $u->getTalkPage(), $talkTag, $blockParams['reason'] );
				}

			}
		}

		return $safeUsers;
	}

	/**
	 * Make an edit to the given page with the tag provided
	 *
	 * @param Title $title
	 * @param string $tag
	 * @param string $summary
	 */
	protected function tagPage( Title $title, $tag, $summary ) {
		// Check length to avoid mistakes
		if ( strlen( $tag ) > 2 ) {
			$page = WikiPage::factory( $title );
			$flags = 0;
			if ( $page->exists() ) {
				$flags |= EDIT_MINOR;
			}
			$page->doEditContent( new WikitextContent( $tag ), $summary,
				$flags, false, $this->getUser() );
		}
	}

	/**
	 * Give a "no matches found for X" message.
	 * If $checkLast, then mention the last edit by this user or IP.
	 *
	 * @param string $userName
	 * @param bool $checkLast
	 * @return string
	 */
	protected function noMatchesMessage( $userName, $checkLast = true ) {
		if ( $checkLast ) {
			$dbr = wfGetDB( DB_REPLICA );
			$actorMigration = ActorMigration::newMigration();
			$user = User::newFromName( $userName, false );

			$lastEdit = false;

			$revWhere = $actorMigration->getWhere( $dbr, 'rev_user', $user );
			foreach ( $revWhere['orconds'] as $cond ) {
				$lastEdit = max( $lastEdit, $dbr->selectField(
					[ 'revision' ] + $revWhere['tables'],
					'rev_timestamp',
					$cond,
					__METHOD__,
					[ 'ORDER BY' => 'rev_timestamp DESC' ],
					$revWhere['joins']
				) );
			}
			$logWhere = $actorMigration->getWhere( $dbr, 'log_user', $user );
			foreach ( $logWhere['orconds'] as $cond ) {
				$lastEdit = max( $lastEdit, $dbr->selectField(
					[ 'logging' ] + $logWhere['tables'],
					'log_timestamp',
					$cond,
					__METHOD__,
					[ 'ORDER BY' => 'log_timestamp DESC' ],
					$logWhere['joins']
				) );
			}

			if ( $lastEdit ) {
				$lastEditTime = wfTimestamp( TS_MW, $lastEdit );
				$lang = $this->getLanguage();
				$contextUser = $this->getUser();
				// FIXME: don't pass around parsed messages
				return $this->msg( 'checkuser-nomatch-edits',
					$lang->userDate( $lastEditTime, $contextUser ),
					$lang->userTime( $lastEditTime, $contextUser )
				)->parseAsBlock();
			}
		}
		return $this->msg( 'checkuser-nomatch' )->parseAsBlock();
	}

	/**
	 * Show all the IPs used by a user
	 *
	 * @param string $user
	 * @param int $period
	 * @return void
	 */
	protected function doUserIPsRequest( $user, $period = 0 ) {
		$out = $this->getOutput();

		$userTitle = Title::newFromText( $user, NS_USER );
		if ( $userTitle !== null ) {
			// normalize the username
			$user = $userTitle->getText();
		}
		// IPs are passed in as a blank string
		if ( !$user ) {
			$out->addWikiMsg( 'nouserspecified' );
			return;
		}
		// Get ID, works better than text as user may have been renamed
		$user_id = User::idFromName( $user );

		// If user is not IP or nonexistent
		if ( !$user_id ) {
			$out->addWikiMsg( 'nosuchusershort', $user );
			return;
		}

		// Record check...
		self::addLogEntry( 'userips', 'user', $user, $this->reason, $user_id );

		$result = $this->doUserIPsDBRequest( $user_id, $period );
		$this->doUserIPsRequestOutput( $result, $user, $period );
	}

	/**
	 * Issue a DB query for doUserIPsRequestOutput
	 *
	 * @param int $user_id
	 * @param int $period
	 * @param int|null $limit
	 * @return IResultWrapper
	 */
	protected function doUserIPsDBRequest( $user_id, $period = 0, $limit = null ) : IResultWrapper {
		if ( $limit === null ) {
			// We add 1 to the row count here because the number of rows returned is used to determine
			// whether the data has been truncated.
			$limit = $this->getConfig()->get( 'CheckUserMaximumRowCount' ) + 1;
		}

		$dbr = wfGetDB( DB_REPLICA );
		$conds = [ 'cuc_user' => $user_id ];
		$time_conds = $this->getTimeConds( $period );
		if ( $time_conds !== false ) {
			$conds[] = $time_conds;
		}

		// Ordering by the latest timestamp makes a small filesort on the IP list
		return $dbr->select(
			'cu_changes',
			[
				'cuc_ip',
				'cuc_ip_hex',
				'count' => 'COUNT(*)',
				'first' => 'MIN(cuc_timestamp)',
				'last' => 'MAX(cuc_timestamp)',
			],
			$conds,
			__METHOD__,
			[
				'ORDER BY' => 'last DESC',
				'GROUP BY' => [ 'cuc_ip', 'cuc_ip_hex' ],
				'LIMIT' => $limit,
				'USE INDEX' => 'cuc_user_ip_time',
			]
		);
	}

	/**
	 * Return "checkuser-ipeditcount" number
	 *
	 * @param array $ips_hex
	 * @param string $ip
	 * @param int $period
	 * @return int
	 */
	protected function getCountForIPedits( array $ips_hex, $ip, $period = 0 ) {
		$dbr = wfGetDB( DB_REPLICA );
		$conds = [ 'cuc_ip_hex' => $ips_hex[$ip] ];
		$time_conds = $this->getTimeConds( $period );
		if ( $time_conds !== false ) {
			$conds[] = $time_conds;
		}

		$ipedits = $dbr->estimateRowCount(
			'cu_changes',
			'*',
			$conds,
			__METHOD__
		);
		// If small enough, get a more accurate count
		if ( $ipedits <= 1000 ) {
			$ipedits = $dbr->selectField(
				'cu_changes',
				'COUNT(*)',
				$conds,
				__METHOD__
			);
		}

		return $ipedits;
	}

	/**
	 * @param IResultWrapper $result
	 * @param int|null $limit
	 * @return array
	 */
	protected function getIPSets( IResultWrapper $result, $limit = null ) : array {
		if ( $limit === null ) {
			$limit = $this->getConfig()->get( 'CheckUserMaximumRowCount' );
		}

		$ipSets = [
			'edits' => [],
			'first' => [],
			'last' => [],
			'hex' => [],
			'exceed' => false
		];
		$counter = 0;

		foreach ( $result as $row ) {
			if ( $counter >= $limit ) {
				$ipSets['exceed'] = true;
				break;
			}
			$ipSets['edits'][$row->cuc_ip] = $row->count;
			$ipSets['first'][$row->cuc_ip] = $row->first;
			$ipSets['last'][$row->cuc_ip] = $row->last;
			$ipSets['hex'][$row->cuc_ip] = $row->cuc_ip_hex;
			++$counter;
		}
		// Count pinging might take some time...make sure it is there
		Wikimedia\suppressWarnings();
		set_time_limit( 60 );
		Wikimedia\restoreWarnings();

		return $ipSets;
	}

	/**
	 * Result output for doUserIPsRequest
	 *
	 * @param IResultWrapper $result
	 * @param string $user
	 * @param int $period
	 * @return void
	 */
	protected function doUserIPsRequestOutput( IResultWrapper $result, $user, $period ) {
		$out = $this->getOutput();
		$lang = $this->getLanguage();

		if ( !$result->numRows() ) {
			$out->addHTML( $this->noMatchesMessage( $user ) . "\n" );
			return;
		}

		$ipSets = $this->getIPSets( $result );
		$ips_edits = $ipSets['edits'];
		$ips_first = $ipSets['first'];
		$ips_last = $ipSets['last'];
		$ips_hex = $ipSets['hex'];

		if ( $ipSets['exceed'] ) {
			$out->addWikiMsg( 'checkuser-limited' );
		}

		$s = '<div id="checkuserresults"><ul>';
		foreach ( $ips_edits as $ip => $edits ) {
			$s .= '<li>';
			$s .= $this->getSelfLink( $ip,
				[
					'user' => $ip,
					'reason' => $this->reason,
				]
			);
			$s .= ' ' . $this->msg( 'parentheses' )->rawParams(
					$this->getLinkRenderer()->makeKnownLink(
						SpecialPage::getTitleFor( 'Block', $ip ),
						$this->msg( 'blocklink' )->text()
					)
				)->escaped();
			$s .= ' ' . $this->getTimeRangeString( $ips_first[$ip], $ips_last[$ip] ) . ' ';
			$s .= ' <strong>[' . htmlspecialchars( $lang->formatNum( $edits ) ) . ']</strong>';

			// If we get some results, it helps to know if the IP in general
			// has a lot more edits, e.g. "tip of the iceberg"...
			$ipedits = $this->getCountForIPedits( $ips_hex, $ip, $period );
			if ( $ipedits > $ips_edits[$ip] ) {
				$s .= ' <i>(' .
					$this->msg( 'checkuser-ipeditcount' )->numParams( $ipedits )->escaped() .
					')</i>';
			}

			// If this IP is blocked, give a link to the block log
			$s .= $this->getIPBlockInfo( $ip );
			$s .= '<div style="margin-left:5%">';
			$s .= '<small>' . $this->msg( 'checkuser-toollinks', urlencode( $ip ) )->parse() .
				'</small>';
			$s .= '</div>';
			$s .= "</li>\n";
		}
		$s .= '</ul></div>';
		$out->addHTML( $s );
	}

	protected function getIPBlockInfo( $ip ) {
		$block = DatabaseBlock::newFromTarget( null, $ip, false );
		if ( $block instanceof DatabaseBlock ) {
			return $this->getBlockFlag( $block );
		}
		return '';
	}

	/**
	 * Get a link to block information about the passed block for displaying to the user.
	 *
	 * @param DatabaseBlock $block
	 * @return string
	 */
	protected function getBlockFlag( DatabaseBlock $block ) {
		if ( $block->getType() == DatabaseBlock::TYPE_AUTO ) {
			$ret = $this->getLinkRenderer()->makeKnownLink(
				SpecialPage::getTitleFor( 'BlockList' ),
				$this->msg( 'checkuser-blocked' )->text(),
				[],
				[ 'wpTarget' => "#{$block->getId()}" ]
			);
		} else {
			$userPage = Title::makeTitle( NS_USER, $block->getTarget() );
			$ret = $this->getLinkRenderer()->makeKnownLink(
				SpecialPage::getTitleFor( 'Log' ),
				$this->msg( 'checkuser-blocked' )->text(),
				[],
				[
					'type' => 'block',
					'page' => $userPage->getPrefixedText()
				]
			);
		}

		// Add the blocked range if the block is on a range
		if ( $block->getType() == DatabaseBlock::TYPE_RANGE ) {
			$ret .= ' - ' . htmlspecialchars( $block->getTarget() );
		}

		return '<strong>' .
			$this->msg( 'parentheses' )->rawParams( $ret )->escaped()
			. '</strong>';
	}

	/**
	 * Shows all changes made by an IP address or range
	 *
	 * @param string $ip
	 * @param bool $xfor if query is for XFF
	 * @param int $period
	 * @return void
	 */
	protected function doIPEditsRequest( $ip, $xfor = false, $period = 0 ) {
		$out = $this->getOutput();
		$index = $xfor ? 'cuc_xff_hex_time' : 'cuc_ip_hex_time';

		// Invalid IPs are passed in as a blank string
		if ( !$ip || !self::isValidRange( $ip ) ) {
			$out->addWikiMsg( 'badipaddress' );
			return;
		}

		$logType = $xfor ? 'ipedits-xff' : 'ipedits';

		// Record check in the logs
		self::addLogEntry( $logType, 'ip', $ip, $this->reason );

		// Ordered in descent by timestamp. Can cause large filesorts on range scans.
		// Check how many rows will need sorting ahead of time to see if this is too big.
		// Also, if we only show 5000, too many will be ignored as well.
		$rangecount = $this->getIPEditsCount( $ip, $xfor, $index, $period );
		if ( $rangecount > $this->getConfig()->get( 'CheckUserMaximumRowCount' ) ) {
			// See what is best to do after testing the waters...
			$result = $this->IPEditsTooManyDB( $ip, $xfor, $index, $period );
			$this->IPEditsTooMany( $result, $ip, $xfor );
			return;
		} elseif ( $rangecount === 0 ) {
			$out->addHTML( $this->noMatchesMessage( $ip, !$xfor ) . "\n" );
			return;
		}

		// OK, do the real query...
		$result = $this->doIPEditsDBRequest( $ip, $xfor, $index, $period );
		$this->doIPEditsRequestOutput( $result, $ip, $xfor );
	}

	/**
	 * Get count for target IP range edits
	 *
	 * @param string $ip
	 * @param bool $xfor if query is for XFF
	 * @param string $index
	 * @param int $period
	 * @param int $timeLimit
	 * @return int
	 */
	protected function getIPEditsCount( $ip, $xfor, $index, $period = 0, $timeLimit = 60 ) {
		// Is not a IP range
		if ( strpos( $ip, '/' ) === false ) {
			return -1;
		}

		$dbr = wfGetDB( DB_REPLICA );
		$conds = self::getIpConds( $dbr, $ip, $xfor );
		if ( $conds === false ) {
			return -1;
		}
		// Quick index check only OK if no time constraint
		if ( $period ) {
			$time_conds = $this->getTimeConds( $period );
			if ( $time_conds !== false ) {
				$conds[] = $time_conds;
			}
			$rangecount = $dbr->selectField(
				'cu_changes',
				'COUNT(*)',
				$conds,
				__METHOD__,
				[ 'USE INDEX' => $index ]
			);
		} else {
			$rangecount = $dbr->estimateRowCount(
				'cu_changes',
				'*',
				$conds,
				__METHOD__,
				[ 'USE INDEX' => $index ]
			);
		}
		// Sorting might take some time...make sure it is there
		Wikimedia\suppressWarnings();
		set_time_limit( $timeLimit );
		Wikimedia\restoreWarnings();

		return $rangecount;
	}

	/**
	 * Issue a DB query for IPEditsTooMany
	 *
	 * @param string $ip
	 * @param bool $xfor if query is for XFF
	 * @param string $index
	 * @param int $period
	 * @param int|null $limit
	 * @return IResultWrapper
	 */
	protected function IPEditsTooManyDB(
		$ip, $xfor, $index, $period = 0, $limit = null
	) : IResultWrapper {
		if ( $limit === null ) {
			// We add 1 to the row count here because the number of rows returned is used to determine
			// whether the data has been truncated.
			$limit = $this->getConfig()->get( 'CheckUserMaximumRowCount' ) + 1;
		}

		$dbr = wfGetDB( DB_REPLICA );
		$conds = self::getIpConds( $dbr, $ip, $xfor );
		if ( $conds === false ) {
			return new FakeResultWrapper( [] );
		}
		$time_conds = $this->getTimeConds( $period );
		if ( $time_conds !== false ) {
			$conds[] = $time_conds;
		}

		return $dbr->select(
			'cu_changes',
			[
				'cuc_ip_hex',
				'count' => 'COUNT(*)',
				'first' => 'MIN(cuc_timestamp)',
				'last' => 'MAX(cuc_timestamp)',
			],
			$conds,
			__METHOD__,
			[
				'GROUP BY' => 'cuc_ip_hex',
				'ORDER BY' => 'cuc_ip_hex',
				'LIMIT' => $limit,
				'USE INDEX' => $index,
			]
		);
	}

	/**
	 * Return "checkuser-too-many" error with some hints
	 *
	 * @param IResultWrapper $result
	 * @param string $ip
	 * @param bool $xfor if query is for XFF
	 * @param int|null $limit
	 */
	protected function IPEditsTooMany( IResultWrapper $result, $ip, $xfor, $limit = null ) {
		if ( $limit === null ) {
			$limit = $this->getConfig()->get( 'CheckUserMaximumRowCount' );
		}

		$out = $this->getOutput();
		$lang = $this->getLanguage();

		// List out each IP that has edits
		$s = $this->msg( 'checkuser-too-many', $lang->formatNum( $limit ) )->parseAsBlock();
		$s .= '<ol>';

		$counter = 0;
		foreach ( $result as $row ) {
			if ( $counter >= $limit ) {
				$out->addWikiMsg( 'checkuser-limited' );
				break;
			}
			// Convert the IP hexes into normal form
			if ( strpos( $row->cuc_ip_hex, 'v6-' ) !== false ) {
				$ip = substr( $row->cuc_ip_hex, 3 );
				$ip = IPUtils::hexToOctet( $ip );
			} else {
				$ip = long2ip( Wikimedia\base_convert( $row->cuc_ip_hex, 16, 10, 8 ) );
			}
			$s .= '<li>';
			$s .= $this->getSelfLink( $ip,
				[
					'user' => $ip,
					'reason' => $this->reason,
					'checktype' => 'subipusers'
				]
			);
			$s .= ' ' . $this->getTimeRangeString( $row->first, $row->last ) . ' ';
			$s .= ' [<strong>' . htmlspecialchars( $lang->formatNum( $row->count ) ) .
				"</strong>]</li>\n";
			++$counter;
		}
		$s .= '</ol>';

		$out->addHTML( $s );
	}

	/**
	 * Issue a DB query for doIPEditsRequestOutput
	 *
	 * @param string $ip
	 * @param bool $xfor if query is for XFF
	 * @param string $index
	 * @param int $period
	 * @param int|null $limit
	 * @return IResultWrapper
	 */
	protected function doIPEditsDBRequest(
		$ip, $xfor, $index, $period = 0, $limit = null
	) : IResultWrapper {
		if ( $limit === null ) {
			// We add 1 to the row count here because the number of rows returned is used to determine
			// whether the data has been truncated.
			$limit = $this->getConfig()->get( 'CheckUserMaximumRowCount' ) + 1;
		}

		$dbr = wfGetDB( DB_REPLICA );
		$conds = self::getIpConds( $dbr, $ip, $xfor );
		if ( $conds === false ) {
			return new FakeResultWrapper( [] );
		}
		$time_conds = $this->getTimeConds( $period );
		if ( $time_conds !== false ) {
			$conds[] = $time_conds;
		}

		return $dbr->select(
			'cu_changes',
			[
				'cuc_namespace', 'cuc_title', 'cuc_user', 'cuc_user_text', 'cuc_comment',
				'cuc_actiontext', 'cuc_timestamp', 'cuc_minor', 'cuc_page_id', 'cuc_type',
				'cuc_this_oldid', 'cuc_last_oldid', 'cuc_ip', 'cuc_xff', 'cuc_agent',
			],
			$conds,
			__METHOD__,
			[
				'ORDER BY' => 'cuc_timestamp DESC',
				'LIMIT' => $limit,
				'USE INDEX' => $index,
			]
		);
	}

	/**
	 * Result output for doIPEditsRequest
	 *
	 * @param IResultWrapper $result
	 * @param string $ip
	 * @param bool $xfor
	 * @return void
	 */
	protected function doIPEditsRequestOutput( IResultWrapper $result, $ip, $xfor ) {
		$out = $this->getOutput();

		if ( !$result->numRows() ) {
			$out->addHTML( $this->noMatchesMessage( $ip, !$xfor ) . "\n" );
			return;
		}

		// Cache common messages
		$this->preCacheMessages();
		// Try to optimize this query
		$lb = $this->linkBatchFactory->newLinkBatch();
		foreach ( $result as $row ) {
			$userText = str_replace( ' ', '_', $row->cuc_user_text );
			if ( $row->cuc_title !== '' ) {
				$lb->add( $row->cuc_namespace, $row->cuc_title );
			}
			$lb->add( NS_USER, $userText );
			$lb->add( NS_USER_TALK, $userText );
		}
		$lb->execute();
		$result->seek( 0 );
		// List out the edits
		$s = '<div id="checkuserresults">';
		$counter = 0;
		foreach ( $result as $row ) {
			if ( $counter >= $this->getConfig()->get( 'CheckUserMaximumRowCount' ) ) {
				$out->addWikiMsg( 'checkuser-limited' );
				break;
			}
			$s .= $this->CUChangesLine( $row );
			++$counter;
		}
		$s .= '</ul></div>';

		$out->addHTML( $s );
	}

	/**
	 * @param IResultWrapper $rows Results with cuc_namespace and cuc_title field
	 */
	protected function doLinkCache( IResultWrapper $rows ) {
		$lb = $this->linkBatchFactory->newLinkBatch();
		$lb->setCaller( __METHOD__ );
		foreach ( $rows as $row ) {
			if ( $row->cuc_title !== '' ) {
				$lb->add( $row->cuc_namespace, $row->cuc_title );
			}
		}
		$lb->execute();
		$rows->seek( 0 );
	}

	/**
	 * Shows all changes made by a particular user
	 *
	 * @param string $user
	 * @param int $period
	 * @return void
	 */
	protected function doUserEditsRequest( $user, $period = 0 ) {
		$out = $this->getOutput();

		$userTitle = Title::newFromText( $user, NS_USER );
		if ( $userTitle !== null ) {
			// normalize the username
			$user = $userTitle->getText();
		}
		// IPs are passed in as a blank string
		if ( !$user ) {
			$out->addWikiMsg( 'nouserspecified' );
			return;
		}
		// Get ID, works better than text as user may have been renamed
		$user_id = User::idFromName( $user );

		// If user is not IP or nonexistent
		if ( !$user_id ) {
			$out->addHTML( $this->msg( 'nosuchusershort', $user )->parseAsBlock() );
			return;
		}

		// Record check...
		self::addLogEntry( 'useredits', 'user', $user, $this->reason, $user_id );

		// Cache common messages
		$this->preCacheMessages();
		$limit = $this->getConfig()->get( 'CheckUserMaximumRowCount' );

		// Sorting might take some time...make sure it is there
		Wikimedia\suppressWarnings();
		set_time_limit( 60 );
		Wikimedia\restoreWarnings();

		// OK, do the real query...
		$result = $this->doUserEditsDBRequest( $user_id, $period, $limit );
		$this->doUserEditsRequestOutput( $result, $user, $limit );
	}

	/**
	 * get count for the user edits
	 *
	 * @param int $user_id
	 * @param int $period
	 * @return int
	 */
	protected function getCountsForUserEdits( $user_id, $period = 0 ) {
		$dbr = wfGetDB( DB_REPLICA );
		$conds = [ 'cuc_user' => $user_id ];
		$time_conds = $this->getTimeConds( $period );
		if ( $time_conds !== false ) {
			$conds[] = $time_conds;
		}

		if ( $period ) {
			return $dbr->selectField(
				'cu_changes',
				'COUNT(*)',
				$conds,
				__METHOD__,
				[ 'USE INDEX' => 'cuc_user_ip_time' ]
			);
		} else {
			return $dbr->estimateRowCount(
				'cu_changes',
				'*',
				$conds,
				__METHOD__,
				[ 'USE INDEX' => 'cuc_user_ip_time' ]
			);
		}
	}

	/**
	 * Issue a DB query for doUserEditsRequestOutput
	 *
	 * @param int $user_id
	 * @param int $period
	 * @param int|null $limit
	 * @return IResultWrapper
	 */
	protected function doUserEditsDBRequest( $user_id, $period = 0, $limit = null ) : IResultWrapper {
		if ( $limit === null ) {
			$limit = $this->getConfig()->get( 'CheckUserMaximumRowCount' );
		}

		$dbr = wfGetDB( DB_REPLICA );
		$conds = [ 'cuc_user' => $user_id ];
		$time_conds = $this->getTimeConds( $period );
		if ( $time_conds !== false ) {
			$conds[] = $time_conds;
		}

		return $dbr->select(
			'cu_changes', [
				'cuc_namespace', 'cuc_title', 'cuc_user', 'cuc_user_text', 'cuc_comment',
				'cuc_actiontext', 'cuc_timestamp', 'cuc_minor', 'cuc_page_id', 'cuc_type',
				'cuc_this_oldid', 'cuc_last_oldid', 'cuc_ip', 'cuc_xff', 'cuc_agent',
			],
			$conds,
			__METHOD__,
			[
				'ORDER BY' => 'cuc_timestamp DESC',
				'LIMIT' => $limit,
				'USE INDEX' => 'cuc_user_ip_time'
			]
		);
	}

	/**
	 * Result output for doUserEditsRequest
	 *
	 * @param IResultWrapper $result
	 * @param string $user
	 * @param int|null $limit
	 * @return void
	 */
	protected function doUserEditsRequestOutput( IResultWrapper $result, $user, $limit = null ) {
		if ( $limit === null ) {
			$limit = $this->getConfig()->get( 'CheckUserMaximumRowCount' );
		}

		$out = $this->getOutput();

		if ( !$result->numRows() ) {
			$out->addHTML( $this->noMatchesMessage( $user ) . "\n" );
			return;
		}

		if ( $result->numRows() >= $limit ) {
			// If the actual row count is at or over the limit, provide a warning
			// that the results may have been truncated
			$out->addHTML( $this->msg( 'checkuser-limited' )->parse() );
		}

		$this->doLinkCache( $result );
		// List out the edits
		$html = '<div id="checkuserresults">';
		foreach ( $result as $row ) {
			$html .= $this->CUChangesLine( $row );
		}
		$html .= '</ul></div>';

		$out->addHTML( $html );
	}

	/**
	 * Lists all users in recent changes who used an IP, newest to oldest down
	 * Outputs usernames, latest and earliest found edit date, and count
	 * List unique IPs used for each user in time order, list corresponding user agent
	 *
	 * @param string $ip
	 * @param bool $xfor
	 * @param int $period
	 * @param string $tag
	 * @param string $talkTag
	 * @return void
	 */
	protected function doIPUsersRequest(
		$ip, $xfor = false, $period = 0, $tag = '', $talkTag = ''
	) {
		$out = $this->getOutput();
		$index = $xfor ? 'cuc_xff_hex_time' : 'cuc_ip_hex_time';

		// Invalid IPs are passed in as a blank string
		if ( !$ip || !self::isValidRange( $ip ) ) {
			$out->addWikiMsg( 'badipaddress' );
			return;
		}

		$logType = $xfor ? 'ipusers-xff' : 'ipusers';

		// Log the check...
		self::addLogEntry( $logType, 'ip', $ip, $this->reason );

		// Are there too many edits?
		$rangecount = $this->getIPUsersCount( $ip, $xfor, $index, $period );
		if ( $rangecount > 10000 ) {
			$result = $this->IPUsersTooManyDB( $ip, $xfor, $index, $period );
			$this->IPUsersTooMany( $result, $ip, $xfor );
			return;
		} elseif ( $rangecount === 0 ) {
			$out->addHTML( $this->noMatchesMessage( $ip, !$xfor ) . "\n" );
			return;
		}

		// OK, do the real query...
		$result = $this->doIPUsersDBRequest( $ip, $xfor, $index, $period );
		$this->doIPUsersRequestOutput( $result, $ip, $xfor, $tag, $talkTag );
	}

	/**
	 * Get count for target edits
	 *
	 * @param string $ip
	 * @param bool $xfor
	 * @param string $index
	 * @param int $period
	 * @param int $timeLimit
	 * @return int
	 */
	protected function getIPUsersCount( $ip, $xfor, $index, $period = 0, $timeLimit = 120 ) {
		return $this->getIPEditsCount( $ip, $xfor, $index, $period, $timeLimit );
	}

	/**
	 * Issue a DB query for IPUsersTooMany
	 *
	 * @param string $ip
	 * @param bool $xfor
	 * @param string $index
	 * @param int $period
	 * @return IResultWrapper
	 */
	protected function IPUsersTooManyDB( $ip, $xfor, $index, $period = 0 ) : IResultWrapper {
		return $this->IPEditsTooManyDB( $ip, $xfor, $index, $period );
	}

	/**
	 * Return 'checkuser-too-many' error with some hints
	 *
	 * @param IResultWrapper $result
	 * @param string $ip
	 * @param bool $xfor
	 * @return void
	 */
	protected function IPUsersTooMany( IResultWrapper $result, $ip, $xfor ) {
		$this->IPEditsTooMany( $result, $ip, $xfor );
	}

	/**
	 * Issue a DB query for doIPUsersRequestOutput
	 *
	 * @param string $ip
	 * @param bool $xfor
	 * @param string $index
	 * @param int $period
	 * @param int $limit
	 * @return IResultWrapper
	 */
	protected function doIPUsersDBRequest(
		$ip, $xfor, $index, $period = 0, $limit = 10000
	) : IResultWrapper {
		$dbr = wfGetDB( DB_REPLICA );
		$conds = self::getIpConds( $dbr, $ip, $xfor );
		if ( $conds === false ) {
			return new FakeResultWrapper( [] );
		}
		$time_conds = $this->getTimeConds( $period );
		if ( $time_conds !== false ) {
			$conds[] = $time_conds;
		}

		return $dbr->select(
			'cu_changes',
			[
				'cuc_user_text', 'cuc_timestamp', 'cuc_user', 'cuc_ip', 'cuc_agent', 'cuc_xff',
			],
			$conds,
			__METHOD__,
			[
				'ORDER BY' => 'cuc_timestamp DESC',
				'LIMIT' => $limit,
				'USE INDEX' => $index,
			]
		);
	}

	/**
	 * @param IResultWrapper $result
	 * @return array[]
	 */
	protected function getUserSets( IResultWrapper $result ) : array {
		$userSets = [
			'first' => [],
			'last' => [],
			'edits' => [],
			'ids' => [],
			'infosets' => [],
			'agentsets' => []
		];

		foreach ( $result as $row ) {
			if ( !array_key_exists( $row->cuc_user_text, $userSets['edits'] ) ) {
				$userSets['last'][$row->cuc_user_text] = $row->cuc_timestamp;
				$userSets['edits'][$row->cuc_user_text] = 0;
				$userSets['ids'][$row->cuc_user_text] = $row->cuc_user;
				$userSets['infosets'][$row->cuc_user_text] = [];
				$userSets['agentsets'][$row->cuc_user_text] = [];
			}
			$userSets['edits'][$row->cuc_user_text] += 1;
			$userSets['first'][$row->cuc_user_text] = $row->cuc_timestamp;
			// Treat blank or NULL xffs as empty strings
			$xff = empty( $row->cuc_xff ) ? null : $row->cuc_xff;
			$xff_ip_combo = [ $row->cuc_ip, $xff ];
			// Add this IP/XFF combo for this username if it's not already there
			if ( !in_array( $xff_ip_combo, $userSets['infosets'][$row->cuc_user_text] ) ) {
				$userSets['infosets'][$row->cuc_user_text][] = $xff_ip_combo;
			}
			// Add this agent string if it's not already there; 10 max.
			if ( count( $userSets['agentsets'][$row->cuc_user_text] ) < 10 ) {
				if ( !in_array( $row->cuc_agent, $userSets['agentsets'][$row->cuc_user_text] ) ) {
					$userSets['agentsets'][$row->cuc_user_text][] = $row->cuc_agent;
				}
			}
		}

		return $userSets;
	}

	/**
	 * Result output for doIPUsersRequest
	 *
	 * @param IResultWrapper $result
	 * @param string $ip
	 * @param bool $xfor
	 * @param string $tag
	 * @param string $talkTag
	 * @return void
	 */
	protected function doIPUsersRequestOutput(
		IResultWrapper $result, $ip, $xfor, $tag = '', $talkTag = ''
	) {
		$out = $this->getOutput();

		if ( !$result->numRows() ) {
			$out->addHTML( $this->noMatchesMessage( $ip, !$xfor ) . "\n" );
			return;
		}

		$userSets = $this->getUserSets( $result );
		$users_first = $userSets['first'];
		$users_last = $userSets['last'];
		$users_edits = $userSets['edits'];
		$users_ids = $userSets['ids'];
		$users_agentsets = $userSets['agentsets'];
		$users_infosets = $userSets['infosets'];

		$centralAuthToollink = ExtensionRegistry::getInstance()->isLoaded( 'CentralAuth' )
			? $this->getConfig()->get( 'CheckUserCAtoollink' ) : false;
		$globalBlockingToollink = ExtensionRegistry::getInstance()->isLoaded( 'GlobalBlocking' )
			? $this->getConfig()->get( 'CheckUserGBtoollink' ) : false;
		$linkrenderer = $this->getLinkRenderer();
		$splang = $this->getLanguage();
		$aliases = $splang->getSpecialPageAliases();
		$permissionManager = MediaWikiServices::getInstance()->getPermissionManager();

		// @todo FIXME: This form (and checkboxes) shouldn't be initiated for users without 'block' right
		$action = htmlspecialchars( $this->getPageTitle()->getLocalURL( 'action=block' ) );
		$s = "<form name='checkuserblock' id='checkuserblock' action=\"$action\" method='post'>";
		$s .= '<div id="checkuserresults"><ul>';
		foreach ( $users_edits as $name => $count ) {
			$s .= '<li>';
			$s .= Xml::check( 'users[]', false, [ 'value' => $name ] ) . '&#160;';
			// Load user object
			$usernfn = User::newFromName( $name, false );
			// Add user page and tool links
			if ( !IPUtils::isIPAddress( $usernfn ) ) {
				$idforlinknfn = -1;
				$user = User::newFromId( $users_ids[$name] );
			} else {
				$idforlinknfn = $users_ids[$name];
				$user = $usernfn;
			}
			$classnouser = false;
			if ( IPUtils::isIPAddress( $name ) !== IPUtils::isIPAddress( $user ) ) {
				// User does not exist
				$idforlink = -1;
				$classnouser = true;
			} else {
				$idforlink = $users_ids[$name];
			}
			if ( $classnouser === true ) {
				$s .= '<span class=\'mw-checkuser-nonexistent-user\'>';
			} else {
				$s .= '<span>';
			}
			$s .= Linker::userLink( $idforlinknfn, $name, $name ) . '</span> ';
			$ip = IPUtils::isIPAddress( $name ) ? $name : '';
			$s .= Linker::userToolLinksRedContribs(
				$idforlink,
				$name,
				$user->getEditCount(),
				// don't render parentheses in HTML markup (CSS will provide)
				false
			) . ' ';
			if ( $ip ) {
				$s .= $this->msg( 'checkuser-userlinks-ip', $name )->parse();
			} elseif ( !$classnouser ) {
				if ( $this->msg( 'checkuser-userlinks' )->exists() ) {
					$s .= ' ' . $this->msg( 'checkuser-userlinks', $name )->parse();
				}
			}
			// Add CheckUser link
			$s .= ' ' . $this->msg( 'parentheses' )->rawParams(
				$this->getSelfLink(
					$this->msg( 'checkuser-check' )->text(),
					[
						'user' => $name,
						'reason' => $this->reason
					]
				)
			)->escaped();
			// Add global user tools links
			// Add CentralAuth link for real registered users
			if ( $centralAuthToollink !== false
				&& !IPUtils::isIPAddress( $name )
				&& !$classnouser
			) {
				// Get CentralAuth SpecialPage name in UserLang from the first Alias name
				$spca = $aliases['CentralAuth'][0];
				$calinkAlias = str_replace( '_', ' ', $spca );
				$centralCAUrl = WikiMap::getForeignURL(
					$centralAuthToollink,
					'Special:CentralAuth'
				);
				if ( $centralCAUrl === false ) {
					throw new Exception(
						'Could not retrieve URL for {$centralAuthToollink}'
					);
				}
				$linkCA = Html::element( 'a',
					[
						'href' => $centralCAUrl . "/" . $name,
						'title' => $this->msg( 'centralauth' )->text(),
					],
					$calinkAlias
				);
				$s .= ' ' . $this->msg( 'parentheses' )->rawParams( $linkCA )->escaped();
			}
			// Add Globalblocking link to CentralWiki
			if ( $globalBlockingToollink !== false
				&& IPUtils::isIPAddress( $name )
			) {
				// Get GlobalBlock SpecialPage name in UserLang from the first Alias name
				$centralGBUrl = WikiMap::getForeignURL(
					$globalBlockingToollink['centralDB'],
					'Special:GlobalBlock'
				);
				$spgb = $aliases['GlobalBlock'][0];
				$gblinkAlias = str_replace( '_', ' ', $spgb );
				if ( ExtensionRegistry::getInstance()->isLoaded( 'CentralAuth' ) ) {
					$gbUserGroups = CentralAuthUser::getInstance( $this->getUser() )->getGlobalGroups();
					// Link to GB via WikiMap since CA require it
					if ( $centralGBUrl === false ) {
						throw new Exception(
							'Could not retrieve URL for {$globalBlockingToollink}'
						);
					}
					$linkGB = Html::element( 'a',
						[
							'href' => $centralGBUrl . "/" . $name,
							'title' => $this->msg( 'globalblocking-block-submit' )->text(),
						],
						$gblinkAlias
					);
				} elseif ( $centralGBUrl !== false ) {
					// Case wikimap configured without CentralAuth extension
					$user = $this->getUser();
					// Get effective Local user groups since there is a wikimap but there is no CA
					$gbUserGroups = $user->getEffectiveGroups();
					$linkGB = Html::element( 'a',
						[
							'href' => $centralGBUrl . "/" . $name,
							'title' => $this->msg( 'globalblocking-block-submit' )->text(),
						],
						$gblinkAlias
					);
				} else {
					// Load local user group instead
					$gbUserGroups = [ '' ];
					$user = $this->getUser();
					$gbtitle = $this->getTitleFor( 'GlobalBlock' );
					$linkGB = $linkrenderer->makeKnownLink(
						$gbtitle,
						$gblinkAlias,
						[ 'title' => $this->msg( 'globalblocking-block-submit' ) ]
					);
					$gbUserCanDo = $permissionManager->userHasRight( $user, 'globalblock' );
					if ( $gbUserCanDo === true ) {
						$globalBlockingToollink['groups'] = $gbUserGroups;
					}
				}
				// Only load the script for users in the configured global(local) group(s) or
				// for local user with globalblock permission if there is no WikiMap
				if ( count( array_intersect( $globalBlockingToollink['groups'], $gbUserGroups ) ) ) {
					$s .= ' ' . $this->msg( 'parentheses' )->rawParams( $linkGB )->escaped();
				}
			}
			// Show edit time range
			$s .= ' ' . $this->getTimeRangeString( $users_first[$name], $users_last[$name] ) . ' ';
			// Total edit count
			// @todo FIXME: i18n issue: Hard coded brackets.
			$s .= ' [<strong>' . htmlspecialchars( $count ) . '</strong>]<br />';
			// Check if this user or IP is blocked. If so, give a link to the block log...
			$flags = $this->userBlockFlags( $ip, $users_ids[$name], $user );
			$s .= implode( ' ', $flags );
			$s .= '<ol>';
			// List out each IP/XFF combo for this username
			for ( $i = ( count( $users_infosets[$name] ) - 1 ); $i >= 0; $i-- ) {
				// users_infosets[$name][$i] is array of [ $row->cuc_ip, XFF ];
				list( $clientIP, $xffString ) = $users_infosets[$name][$i];
				// IP link
				$s .= '<li>';
				$s .= $this->getSelfLink( $clientIP, [ 'user' => $clientIP ] );
				// XFF string, link to /xff search
				if ( $xffString ) {
					// Flag our trusted proxies
					list( $client ) = CheckUserHooks::getClientIPfromXFF( $xffString );
					// XFF was trusted if client came from it
					$trusted = ( $client === $clientIP );
					$c = $trusted ? '#F0FFF0' : '#FFFFCC';
					$s .= '&#160;&#160;&#160;<span style="background-color: ' . $c .
						'"><strong>XFF</strong>: ';
					$s .= $this->getSelfLink( $xffString, [ 'user' => $client . '/xff' ] ) .
						'</span>';
				}
				$s .= "</li>\n";
			}
			$s .= '</ol><br /><ol>';
			// List out each agent for this username
			for ( $i = ( count( $users_agentsets[$name] ) - 1 ); $i >= 0; $i-- ) {
				$agent = $users_agentsets[$name][$i];
				$s .= '<li><i dir="ltr">' . htmlspecialchars( $agent ) . "</i></li>\n";
			}
			$s .= '</ol>';
			$s .= '</li>';
		}
		$s .= "</ul></div>\n";
		if ( $permissionManager->userHasRight( $this->getUser(), 'block' )
			&& !$this->getUser()->getBlock()
		) {
			// FIXME: The block <form> is currently added for users without 'block' right
			// - only the user-visible form is shown appropriately
			$s .= $this->getBlockForm( $tag, $talkTag );
			$s .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
		}
		$s .= "</form>\n";

		// @phan-suppress-next-line SecurityCheck-XSS False positive
		$out->addHTML( $s );
	}

	/**
	 * @param string $tag
	 * @param string $talkTag
	 * @return string
	 */
	protected function getBlockForm( $tag, $talkTag ) {
		$config = $this->getConfig();
		$checkUserCAMultiLock = $config->get( 'CheckUserCAMultiLock' );
		if ( $checkUserCAMultiLock !== false ) {
			if ( !ExtensionRegistry::getInstance()->isLoaded( 'CentralAuth' ) ) {
				// $wgCheckUserCAMultiLock shouldn't be enabled if CA is not loaded
				throw new Exception( '$wgCheckUserCAMultiLock requires CentralAuth extension.' );
			}

			$caUserGroups = CentralAuthUser::getInstance( $this->getUser() )->getGlobalGroups();
			// Only load the script for users in the configured global group(s)
			if ( count( array_intersect( $checkUserCAMultiLock['groups'], $caUserGroups ) ) ) {
				$out = $this->getOutput();
				$centralMLUrl = WikiMap::getForeignURL(
					$checkUserCAMultiLock['centralDB'],
					// Use canonical name instead of local name so that it works
					// even if the local language is different from central wiki
					'Special:MultiLock'
				);
				if ( $centralMLUrl === false ) {
					throw new Exception(
						"Could not retrieve URL for {$checkUserCAMultiLock['centralDB']}"
					);
				}
				$out->addJsConfigVars( 'wgCUCAMultiLockCentral', $centralMLUrl );
				$out->addModules( 'ext.checkUser' );
			}
		}

		$s = "<fieldset>\n";
		$s .= '<legend>' . $this->msg( 'checkuser-massblock' )->escaped() . "</legend>\n";
		$s .= $this->msg( 'checkuser-massblock-text' )->parseAsBlock() . "\n";
		$s .= '<table><tr>' .
			'<td>' . Xml::check( 'usetag', false, [ 'id' => 'usetag' ] ) . '</td>' .
			'<td>' . Xml::label( $this->msg( 'checkuser-blocktag' )->text(), 'usetag' ) .
			'</td>' .
			'<td>' . Xml::input( 'tag', 46, $tag, [ 'id' => 'blocktag' ] ) . '</td>' .
			'</tr><tr>' .
			'<td>' . Xml::check( 'usettag', false, [ 'id' => 'usettag' ] ) . '</td>' .
			'<td>' . Xml::label( $this->msg( 'checkuser-blocktag-talk' )->text(), 'usettag' ) .
			'</td>' .
			'<td>' . Xml::input( 'talktag', 46, $talkTag, [ 'id' => 'talktag' ] ) . '</td>';
		if ( $config->get( 'BlockAllowsUTEdit' ) ) {
			$s .= '</tr><tr>' .
				'<td>' . Xml::check( 'blocktalk', false, [ 'id' => 'blocktalk' ] ) . '</td>' .
				'<td>' . Xml::label( $this->msg( 'checkuser-blocktalk' )->text(), 'blocktalk' ) .
				'</td>';
		}
		if ( SpecialBlock::canBlockEmail( $this->getUser() ) ) {
			$s .= '</tr><tr>' .
				'<td>' . Xml::check( 'blockemail', false, [ 'id' => 'blockemail' ] ) . '</td>' .
				'<td>' . Xml::label( $this->msg( 'checkuser-blockemail' )->text(), 'blockemail' )
				. '</td>';
		}
		$s .= '<tr><td>' . Xml::check( 'reblock', false, [ 'id' => 'reblock' ] ) . '</td>';
		$s .= '<td>' . Xml::label( $this->msg( 'checkuser-reblock' )->text(), 'reblock' )
			. '</td></tr>';
		$s .= '</tr></table>';
		$s .= '<p>' . $this->msg( 'checkuser-reason' )->escaped() . '&#160;';
		$s .= Xml::input( 'blockreason', 46, '', [ 'maxlength' => '150', 'id' => 'blockreason' ] );
		$s .= '&#160;' . Xml::submitButton( $this->msg( 'checkuser-massblock-commit' )->text(),
			[ 'id' => 'checkuserblocksubmit', 'name' => 'checkuserblock' ] ) . "</p>\n";
		$s .= "</fieldset>\n";

		return $s;
	}

	/**
	 * Get an HTML link (<a> element) to Special:CheckUser
	 *
	 * @param string $text content to use within <a> tag
	 * @param array $params query parameters to use in the URL
	 * @return string
	 */
	private function getSelfLink( $text, array $params ) {
		static $title;
		if ( $title === null ) {
			$title = $this->getPageTitle();
		}
		return $this->getLinkRenderer()->makeKnownLink(
			$title,
			new HtmlArmor( '<bdi>' . htmlspecialchars( $text ) . '</bdi>' ),
			[],
			$params
		);
	}

	/**
	 * @param string $ip
	 * @param int $userId
	 * @param User $user
	 * @return array
	 */
	protected function userBlockFlags( $ip, $userId, $user ) {
		$flags = [];

		$block = DatabaseBlock::newFromTarget( $user, $ip, false );
		if ( $block instanceof DatabaseBlock ) {
			// Locally blocked
			$flags[] = $this->getBlockFlag( $block );
		} elseif ( $ip == $user->getName() && $user->isBlockedGlobally( $ip ) ) {
			// Globally blocked IP
			$flags[] = '<strong>(' . $this->msg( 'checkuser-gblocked' )->escaped() . ')</strong>';
		} elseif ( self::userWasBlocked( $user->getName() ) ) {
			// Previously blocked
			$userpage = $user->getUserPage();
			$blocklog = $this->getLinkRenderer()->makeKnownLink(
				SpecialPage::getTitleFor( 'Log' ),
				$this->msg( 'checkuser-wasblocked' )->text(),
				[],
				[
					'type' => 'block',
					'page' => $userpage->getPrefixedText()
				]
			);
			// @todo FIXME: Hard coded parentheses.
			$flags[] = '<strong>(' . $blocklog . ')</strong>';
		}

		// Show if account is local only
		if ( $user->getId() &&
			CentralIdLookup::factory()
				->centralIdFromLocalUser( $user, CentralIdLookup::AUDIENCE_RAW ) === 0
		) {
			// @todo FIXME: i18n issue: Hard coded parentheses.
			$flags[] = '<strong>(' . $this->msg( 'checkuser-localonly' )->escaped() . ')</strong>';
		}
		// Check for extra user rights...
		if ( $userId ) {
			if ( $user->isLocked() ) {
				// @todo FIXME: i18n issue: Hard coded parentheses.
				$flags[] = '<b>(' . $this->msg( 'checkuser-locked' )->escaped() . ')</b>';
			}
			$list = [];
			foreach ( $user->getGroups() as $group ) {
				$list[] = self::buildGroupLink( $group, $user->getName() );
			}
			$groups = $this->getLanguage()->commaList( $list );
			if ( $groups ) {
				// @todo FIXME: i18n issue: Hard coded parentheses.
				$flags[] = '<i>(' . $groups . ')</i>';
			}
		}

		return $flags;
	}

	/**
	 * Get a streamlined recent changes line with IP data
	 *
	 * @param stdClass $row
	 * @return string
	 */
	protected function CUChangesLine( $row ) {
		static $flagCache = [];
		$line = '';
		// Add date headers as needed
		$date = htmlspecialchars(
			$this->getLanguage()->userDate( wfTimestamp( TS_MW, $row->cuc_timestamp ), $this->getUser() )
		);
		if ( $this->lastdate === null ) {
			$this->lastdate = $date;
			$line .= "\n<h4>$date</h4>\n<ul class=\"special\">";
		} elseif ( $date !== $this->lastdate ) {
			$line .= "</ul>\n<h4>$date</h4>\n<ul class=\"special\">";
			$this->lastdate = $date;
		}
		$line .= '<li>';
		// Create diff/hist/page links
		$line .= $this->getLinksFromRow( $row );
		// Show date
		$line .= ' . . ' . htmlspecialchars(
			$this->getLanguage()->userTime( wfTimestamp( TS_MW, $row->cuc_timestamp ), $this->getUser() )
			) . ' . . ';
		// Userlinks
		$user = User::newFromId( $row->cuc_user );
		if ( !IPUtils::isIPAddress( $row->cuc_user_text ) ) {
			$idforlinknfn = -1;
		} else {
			$idforlinknfn = $row->cuc_user;
		}
		$classnouser = false;
		if ( IPUtils::isIPAddress( $row->cuc_user_text ) !== IPUtils::isIPAddress( $user ) ) {
			// User does not exist
			$idforlink = -1;
			$classnouser = true;
		} else {
			$idforlink = $row->cuc_user;
		}
		if ( $classnouser === true ) {
			$line .= '<span class=\'mw-checkuser-nonexistent-user\'>';
		} else {
			$line .= '<span>';
		}
		$line .= Linker::userLink(
			$idforlinknfn, $row->cuc_user_text, $row->cuc_user_text ) . '</span>';
		$line .= Linker::userToolLinksRedContribs(
			$idforlink,
			$row->cuc_user_text,
			$user->getEditCount(),
			// don't render parentheses in HTML markup (CSS will provide)
			false
		);
		// Get block info
		if ( isset( $flagCache[$row->cuc_user_text] ) ) {
			$flags = $flagCache[$row->cuc_user_text];
		} else {
			$user = User::newFromName( $row->cuc_user_text, false );
			$ip = IPUtils::isIPAddress( $row->cuc_user_text ) ? $row->cuc_user_text : '';
			$flags = $this->userBlockFlags( $ip, $row->cuc_user, $user );
			$flagCache[$row->cuc_user_text] = $flags;
		}
		// Add any block information
		if ( count( $flags ) ) {
			$line .= ' ' . implode( ' ', $flags );
		}
		// Action text, hackish ...
		if ( $row->cuc_actiontext ) {
			$line .= ' ' . Linker::formatComment( $row->cuc_actiontext ) . ' ';
		}
		// Comment
		if ( $row->cuc_type == RC_EDIT || $row->cuc_type == RC_NEW ) {
			$revRecord = MediaWikiServices::getInstance()
				->getRevisionLookup()
				->getRevisionById( $row->cuc_this_oldid );
			if ( !$revRecord ) {
				// Assume revision is deleted
				$dbr = wfGetDB( DB_REPLICA );
				$queryInfo = MediaWikiServices::getInstance()
					->getRevisionStore()
					->getArchiveQueryInfo();
				$tmp = $dbr->selectRow(
					$queryInfo['tables'],
					$queryInfo['fields'],
					[ 'ar_rev_id' => $row->cuc_this_oldid ],
					__METHOD__,
					[],
					$queryInfo['joins']
				);
				if ( $tmp ) {
					$revRecord = MediaWikiServices::getInstance()
						->getRevisionFactory()
						->newRevisionFromArchiveRow( $tmp );
				}

				if ( !$revRecord ) {
					// This shouldn't happen, CheckUser points to a revision
					// that isn't in revision nor archive table?
					throw new Exception(
						"Couldn't fetch revision cu_changes table links to (cuc_this_oldid {$row->cuc_this_oldid})"
					);
				}
			}
			if ( RevisionRecord::userCanBitfield(
				$revRecord->getVisibility(),
				RevisionRecord::DELETED_COMMENT,
				$this->getUser()
			) ) {
				$line .= Linker::commentBlock( $row->cuc_comment );
			} else {
				$line .= Linker::commentBlock(
					$this->msg( 'rev-deleted-comment' )->text(),
					null,
					false,
					null,
					false
				);
			}
		} else {
			$line .= Linker::commentBlock( $row->cuc_comment );
		}
		$line .= '<br />&#160; &#160; &#160; &#160; <small>';
		// IP
		$line .= ' <strong>IP</strong>: ';
		$line .= $this->getSelfLink( $row->cuc_ip,
			[
				'user' => $row->cuc_ip,
				'reason' => $this->reason
			]
		);
		// XFF
		if ( $row->cuc_xff != null ) {
			// Flag our trusted proxies
			list( $client ) = CheckUserHooks::getClientIPfromXFF( $row->cuc_xff );
			$trusted = ( $client === $row->cuc_ip ); // XFF was trusted if client came from it
			$c = $trusted ? '#F0FFF0' : '#FFFFCC';
			$line .= '&#160;&#160;&#160;';
			$line .= '<span class="mw-checkuser-xff" style="background-color: ' . $c . '">' .
				'<strong>XFF</strong>: ';
			$line .= $this->getSelfLink( $row->cuc_xff,
				[
					'user' => $client . '/xff',
					'reason' => $this->reason
				]
			);
			$line .= '</span>';
		}
		// User agent
		$line .= '&#160;&#160;&#160;<span class="mw-checkuser-agent" style="color:#888;">' .
			htmlspecialchars( $row->cuc_agent ) . '</span>';

		$line .= "</small></li>\n";

		return $line;
	}

	/**
	 * Get formatted timestamp(s) to show the time of first and last change.
	 * If both timestamps are the same, it will be shown only once.
	 *
	 * @param string $first Timestamp of the first change
	 * @param string $last Timestamp of the last change
	 * @return string
	 */
	protected function getTimeRangeString( $first, $last ) {
		$s = $this->getFormattedTimestamp( $first );
		if ( $first !== $last ) {
			// @todo i18n issue - hardcoded string
			$s .= ' -- ';
			$s .= $this->getFormattedTimestamp( $last );
		}
		return $this->msg( 'parentheses' )->params( $s )->escaped();
	}

	/**
	 * Get a formatted timestamp string in the current language
	 * for displaying to the user.
	 *
	 * @param string $timestamp
	 * @return string
	 */
	protected function getFormattedTimestamp( $timestamp ) {
		return $this->getLanguage()->userTimeAndDate(
			wfTimestamp( TS_MW, $timestamp ), $this->getUser()
		);
	}

	/**
	 * @param stdClass $row
	 * @return string diff, hist and page other links related to the change
	 */
	protected function getLinksFromRow( $row ) {
		$links = [];
		// Log items
		if ( $row->cuc_type == RC_LOG ) {
			$title = Title::makeTitle( $row->cuc_namespace, $row->cuc_title );
			// @todo FIXME: Hard coded parentheses.
			$links['log'] = '(' . $this->getLinkRenderer()->makeKnownLink(
				SpecialPage::getTitleFor( 'Log' ),
				new HtmlArmor( $this->message['log'] ),
				[],
				[ 'page' => $title->getPrefixedText() ]
			) . ')';
		} else {
			$title = Title::makeTitle( $row->cuc_namespace, $row->cuc_title );
			// New pages
			if ( $row->cuc_type == RC_NEW ) {
				$links['diff'] = '(' . $this->message['diff'] . ') ';
			} else {
				// Diff link
				// @todo FIXME: Hard coded parentheses.
				$links['diff'] = ' (' . $this->getLinkRenderer()->makeKnownLink(
					$title,
					new HtmlArmor( $this->message['diff'] ),
					[],
					[
						'curid' => $row->cuc_page_id,
						'diff' => $row->cuc_this_oldid,
						'oldid' => $row->cuc_last_oldid
					]
				) . ') ';
			}
			// History link
			// @todo FIXME: Hard coded parentheses.
			$links['history'] = ' (' . $this->getLinkRenderer()->makeKnownLink(
				$title,
				new HtmlArmor( $this->message['hist'] ),
				[],
				[
					'curid' => $title->exists() ? $row->cuc_page_id : null,
					'action' => 'history'
				]
			) . ') . . ';
			// Some basic flags
			if ( $row->cuc_type == RC_NEW ) {
				$links['newpage'] = '<span class="newpage">' . $this->message['newpageletter'] .
					'</span>';
			}
			if ( $row->cuc_minor ) {
				$links['minor'] = '<span class="minor">' . $this->message['minoreditletter'] .
					'</span>';
			}
			// Page link
			$links['title'] = $this->getLinkRenderer()->makeLink( $title );
		}

		Hooks::run( 'SpecialCheckUserGetLinksFromRow', [ $this, $row, &$links ] );
		// @phan-suppress-next-line PhanRedundantCondition May set by hook
		if ( is_array( $links ) ) {
			return implode( ' ', $links );
		} else {
			wfDebugLog( __CLASS__,
				__METHOD__ . ': Expected array from SpecialCheckUserGetLinksFromRow $links param,'
				. ' but received ' . gettype( $links )
			);
			return '';
		}
	}

	protected static function userWasBlocked( $name ) {
		$userpage = Title::makeTitle( NS_USER, $name );
		return (bool)wfGetDB( DB_REPLICA )->selectField( 'logging', '1',
			[
				'log_type' => [ 'block', 'suppress' ],
				'log_action' => 'block',
				'log_namespace' => $userpage->getNamespace(),
				'log_title' => $userpage->getDBkey()
			],
			__METHOD__,
			[ 'USE INDEX' => 'page_time' ]
		);
	}

	/**
	 * Format a link to a group description page
	 *
	 * @param string $group
	 * @param string $username
	 * @return string
	 */
	protected static function buildGroupLink( $group, $username ) {
		static $cache = [];
		if ( !isset( $cache[$group] ) ) {
			$cache[$group] = UserGroupMembership::getLink(
				$group, RequestContext::getMain(), 'html'
			);
		}
		return $cache[$group];
	}

	/**
	 * @param string $target an IP address or CIDR range
	 * @return bool
	 */
	public static function isValidRange( $target ) {
		$CIDRLimit = \RequestContext::getMain()->getConfig()->get( 'CheckUserCIDRLimit' );
		if ( IPUtils::isValidRange( $target ) ) {
			list( $ip, $range ) = explode( '/', $target, 2 );
			if ( ( IPUtils::isIPv4( $ip ) && $range < $CIDRLimit['IPv4'] ) ||
				( IPUtils::isIPv6( $ip ) && $range < $CIDRLimit['IPv6'] ) ) {
					return false; // range is too wide
			}
			return true;
		}

		return IPUtils::isValid( $target );
	}

	/**
	 * @param IDatabase $db
	 * @param string $target an IP address or CIDR range
	 * @param string|bool $xfor
	 * @return array|false array for valid conditions, false if invalid
	 */
	public static function getIpConds( IDatabase $db, $target, $xfor = false ) {
		$type = $xfor ? 'xff' : 'ip';

		if ( !self::isValidRange( $target ) ) {
			return false;
		}

		if ( IPUtils::isValidRange( $target ) ) {
			list( $start, $end ) = IPUtils::parseRange( $target );
			return [ 'cuc_' . $type . '_hex BETWEEN ' . $db->addQuotes( $start ) .
				' AND ' . $db->addQuotes( $end ) ];
		} elseif ( IPUtils::isValid( $target ) ) {
				return [ "cuc_{$type}_hex" => IPUtils::toHex( $target ) ];
		}
		return false; // invalid IP
	}

	protected function getTimeConds( $period ) {
		if ( !$period ) {
			return false;
		}
		$dbr = wfGetDB( DB_REPLICA );
		$cutoff_unixtime = time() - ( $period * 24 * 3600 );
		$cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
		$cutoff = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
		return "cuc_timestamp > $cutoff";
	}

	public static function addLogEntry( $logType, $targetType, $target, $reason, $targetID = 0 ) {
		$user = RequestContext::getMain()->getUser();

		if ( $targetType == 'ip' ) {
			list( $rangeStart, $rangeEnd ) = IPUtils::parseRange( $target );
			$targetHex = $rangeStart;
			if ( $rangeStart == $rangeEnd ) {
				$rangeStart = $rangeEnd = '';
			}
		} else {
			$targetHex = $rangeStart = $rangeEnd = '';
		}

		$timestamp = time();
		$data = [
			'cul_user' => $user->getId(),
			'cul_user_text' => $user->getName(),
			'cul_reason' => $reason,
			'cul_type' => $logType,
			'cul_target_id' => $targetID,
			'cul_target_text' => trim( $target ),
			'cul_target_hex' => $targetHex,
			'cul_range_start' => $rangeStart,
			'cul_range_end' => $rangeEnd
		];
		$fname = __METHOD__;

		DeferredUpdates::addCallableUpdate(
			function () use ( $data, $timestamp, $fname ) {
				$dbw = wfGetDB( DB_MASTER );
				$dbw->insert(
					'cu_log',
					[
						'cul_timestamp' => $dbw->timestamp( $timestamp )
					] + $data,
					$fname
				);
			},
			DeferredUpdates::PRESEND // fail on error and show no output
		);
	}

	/**
	 * Return an array of subpages beginning with $search that this special page will accept.
	 *
	 * @param string $search Prefix to search for
	 * @param int $limit Maximum number of results to return (usually 10)
	 * @param int $offset Number of results to skip (usually 0)
	 * @return string[] Matching subpages
	 */
	public function prefixSearchSubpages( $search, $limit, $offset ) {
		$user = User::newFromName( $search );
		if ( !$user ) {
			// No prefix suggestion for invalid user
			return [];
		}
		// Autocomplete subpage as user list - public to allow caching
		return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
	}

	protected function getGroupName() {
		return 'users';
	}
}