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
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
|
<?php
/**
* Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
*
* 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
*/
use MediaWiki\Api\ApiHookRunner;
use MediaWiki\Api\Validator\SubmoduleDef;
use MediaWiki\Block\Block;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\Language\RawMessage;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiServices;
use MediaWiki\Page\PageIdentity;
use MediaWiki\ParamValidator\TypeDef\NamespaceDef;
use MediaWiki\Permissions\Authority;
use MediaWiki\Permissions\PermissionManager;
use MediaWiki\Permissions\PermissionStatus;
use MediaWiki\Specials\SpecialVersion;
use MediaWiki\Status\Status;
use MediaWiki\Title\Title;
use MediaWiki\User\User;
use MediaWiki\User\UserRigorOptions;
use Wikimedia\ParamValidator\ParamValidator;
use Wikimedia\ParamValidator\TypeDef\EnumDef;
use Wikimedia\ParamValidator\TypeDef\IntegerDef;
use Wikimedia\ParamValidator\TypeDef\StringDef;
use Wikimedia\Rdbms\IReadableDatabase;
use Wikimedia\Timestamp\TimestampException;
/**
* This abstract class implements many basic API functions, and is the base of
* all API classes.
*
* The class functions are divided into several areas of functionality:
*
* Module parameters: Derived classes can define getAllowedParams() to specify
* which parameters to expect, how to parse and validate them.
*
* Self-documentation: code to allow the API to document its own state
*
* @stable to extend
*
* @ingroup API
*/
abstract class ApiBase extends ContextSource {
use ApiBlockInfoTrait;
/** @var HookContainer */
private $hookContainer;
/** @var ApiHookRunner */
private $hookRunner;
/**
* @name Old constants for ::getAllowedParams() arrays
* @{
*/
/**
* @deprecated since 1.35, use ParamValidator::PARAM_DEFAULT instead
*/
public const PARAM_DFLT = ParamValidator::PARAM_DEFAULT;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI instead
*/
public const PARAM_ISMULTI = ParamValidator::PARAM_ISMULTI;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_TYPE instead
*/
public const PARAM_TYPE = ParamValidator::PARAM_TYPE;
/**
* @deprecated since 1.35, use IntegerDef::PARAM_MAX instead
*/
public const PARAM_MAX = IntegerDef::PARAM_MAX;
/**
* @deprecated since 1.35, use IntegerDef::PARAM_MAX2 instead
*/
public const PARAM_MAX2 = IntegerDef::PARAM_MAX2;
/**
* @deprecated since 1.35, use IntegerDef::PARAM_MIN instead
*/
public const PARAM_MIN = IntegerDef::PARAM_MIN;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_ALLOW_DUPLICATES instead
*/
public const PARAM_ALLOW_DUPLICATES = ParamValidator::PARAM_ALLOW_DUPLICATES;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_DEPRECATED instead
*/
public const PARAM_DEPRECATED = ParamValidator::PARAM_DEPRECATED;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_REQUIRED instead
*/
public const PARAM_REQUIRED = ParamValidator::PARAM_REQUIRED;
/**
* @deprecated since 1.35, use SubmoduleDef::PARAM_SUBMODULE_MAP instead
*/
public const PARAM_SUBMODULE_MAP = SubmoduleDef::PARAM_SUBMODULE_MAP;
/**
* @deprecated since 1.35, use SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX instead
*/
public const PARAM_SUBMODULE_PARAM_PREFIX = SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_ALL instead
*/
public const PARAM_ALL = ParamValidator::PARAM_ALL;
/**
* @deprecated since 1.35, use NamespaceDef::PARAM_EXTRA_NAMESPACES instead
*/
public const PARAM_EXTRA_NAMESPACES = NamespaceDef::PARAM_EXTRA_NAMESPACES;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_SENSITIVE instead
*/
public const PARAM_SENSITIVE = ParamValidator::PARAM_SENSITIVE;
/**
* @deprecated since 1.35, use EnumDef::PARAM_DEPRECATED_VALUES instead
*/
public const PARAM_DEPRECATED_VALUES = EnumDef::PARAM_DEPRECATED_VALUES;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI_LIMIT1 instead
*/
public const PARAM_ISMULTI_LIMIT1 = ParamValidator::PARAM_ISMULTI_LIMIT1;
/**
* @deprecated since 1.35, use ParamValidator::PARAM_ISMULTI_LIMIT2 instead
*/
public const PARAM_ISMULTI_LIMIT2 = ParamValidator::PARAM_ISMULTI_LIMIT2;
/**
* @deprecated since 1.35, use StringDef::PARAM_MAX_BYTES instead
*/
public const PARAM_MAX_BYTES = StringDef::PARAM_MAX_BYTES;
/**
* @deprecated since 1.35, use StringDef::PARAM_MAX_CHARS instead
*/
public const PARAM_MAX_CHARS = StringDef::PARAM_MAX_CHARS;
/** @} */
/**
* (boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
* @deprecated since 1.35
*/
public const PARAM_RANGE_ENFORCE = 'api-param-range-enforce';
// region API-specific constants for ::getAllowedParams() arrays
/** @name API-specific constants for ::getAllowedParams() arrays */
/**
* (string|array|Message) Specify an alternative i18n documentation message
* for this parameter. Default is apihelp-{$path}-param-{$param}.
* @since 1.25
*/
public const PARAM_HELP_MSG = 'api-param-help-msg';
/**
* ((string|array|Message)[]) Specify additional i18n messages to append to
* the normal message for this parameter.
* @since 1.25
*/
public const PARAM_HELP_MSG_APPEND = 'api-param-help-msg-append';
/**
* (array) Specify additional information tags for the parameter.
* The value is an array of arrays, with the first member being the 'tag' for the info
* and the remaining members being the values. In the help, this is
* formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
* $1 = count, $2 = comma-joined list of values, $3 = module prefix.
* @since 1.25
*/
public const PARAM_HELP_MSG_INFO = 'api-param-help-msg-info';
/**
* Deprecated and unused.
* @since 1.25
* @deprecated since 1.35
*/
public const PARAM_VALUE_LINKS = 'api-param-value-links';
/**
* ((string|array|Message)[]) When PARAM_TYPE is an array, or 'string'
* with PARAM_ISMULTI, this is an array mapping parameter values to help
* message specifiers (to be passed to ApiBase::makeMessage()) about
* those values.
*
* When PARAM_TYPE is an array, any value not having a mapping will use
* the apihelp-{$path}-paramvalue-{$param}-{$value} message. (This means
* you can use an empty array to use the default message key for all
* values.)
*
* @since 1.25
* @note Use with PARAM_TYPE = 'string' is allowed since 1.40.
*/
public const PARAM_HELP_MSG_PER_VALUE = 'api-param-help-msg-per-value';
/**
* (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
* placeholders in the parameter name and values are the names of (unprefixed) parameters from
* which the replacement values are taken.
*
* For example, a parameter "foo-{ns}-{title}" could be defined with
* PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
* namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
*
* All placeholders must be present in the parameter's name. Each target parameter must have
* PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
* be a subset of the referring parameter's, mapping the same placeholders to the same targets.
* A parameter cannot target itself.
*
* @since 1.32
*/
public const PARAM_TEMPLATE_VARS = 'param-template-vars';
// endregion -- end of API-specific constants for ::getAllowedParams() arrays
public const ALL_DEFAULT_STRING = '*';
/** Fast query, standard limit. */
public const LIMIT_BIG1 = 500;
/** Fast query, apihighlimits limit. */
public const LIMIT_BIG2 = 5000;
/** Slow query, standard limit. */
public const LIMIT_SML1 = 50;
/** Slow query, apihighlimits limit. */
public const LIMIT_SML2 = 500;
/**
* getAllowedParams() flag: When this is set, the result could take longer to generate,
* but should be more thorough. E.g. get the list of generators for ApiSandBox extension
* @since 1.21
*/
public const GET_VALUES_FOR_HELP = 1;
/** @var array Maps extension paths to info arrays */
private static $extensionInfo = null;
/** @var stdClass[][] Cache for self::filterIDs() */
private static $filterIDsCache = [];
/** @var array Map of web UI block messages which magically gain machine-readable block info */
private const BLOCK_CODE_MAP = [
'blockedtext' => true,
'blockedtext-partial' => true,
'autoblockedtext' => true,
'systemblockedtext' => true,
'blockedtext-composite' => true,
];
/** @var array Map of web UI block messages to corresponding API messages and codes */
private const MESSAGE_CODE_MAP = [
'actionthrottled' => [ 'apierror-ratelimited', 'ratelimited' ],
'actionthrottledtext' => [ 'apierror-ratelimited', 'ratelimited' ],
];
/** @var ApiMain */
private $mMainModule;
/** @var string */
private $mModuleName, $mModulePrefix;
private $mReplicaDB = null;
/**
* @var array
*/
private $mParamCache = [];
/** @var array|null|false */
private $mModuleSource = false;
/**
* @stable to call
* @param ApiMain $mainModule
* @param string $moduleName Name of this module
* @param string $modulePrefix Prefix to use for parameter names
*/
public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
$this->mMainModule = $mainModule;
$this->mModuleName = $moduleName;
$this->mModulePrefix = $modulePrefix;
if ( !$this->isMain() ) {
$this->setContext( $mainModule->getContext() );
}
}
/***************************************************************************/
// region Methods to implement
/** @name Methods to implement */
/**
* Evaluates the parameters, performs the requested query, and sets up
* the result. Concrete implementations of ApiBase must override this
* method to provide whatever functionality their module offers.
* Implementations must not produce any output on their own and are not
* expected to handle any errors.
*
* The execute() method will be invoked directly by ApiMain immediately
* before the result of the module is output. Aside from the
* constructor, implementations should assume that no other methods
* will be called externally on the module before the result is
* processed.
*
* The result data should be stored in the ApiResult object available
* through getResult().
*/
abstract public function execute();
/**
* Get the module manager, or null if this module has no submodules.
*
* @since 1.21
* @stable to override
* @return ApiModuleManager|null
*/
public function getModuleManager() {
return null;
}
/**
* If the module may only be used with a certain format module,
* it should override this method to return an instance of that formatter.
* A value of null means the default format will be used.
*
* @note Do not use this just because you don't want to support non-json
* formats. This should be used only when there is a fundamental
* requirement for a specific format.
*
* @stable to override
* @return ApiFormatBase|null An instance of a class derived from ApiFormatBase, or null
*/
public function getCustomPrinter() {
return null;
}
/**
* Returns usage examples for this module.
*
* Return value has query strings as keys, with values being either strings
* (message key), arrays (message key + parameter), or Message objects.
*
* Do not call this base class implementation when overriding this method.
*
* @since 1.25
* @stable to override
* @return array
*/
protected function getExamplesMessages() {
return [];
}
/**
* Return links to more detailed help pages about the module.
*
* @since 1.25, returning boolean false is deprecated
* @stable to override
* @return string|array
*/
public function getHelpUrls() {
return [];
}
/**
* Returns an array of allowed parameters (parameter name) => (default
* value) or (parameter name) => (array with PARAM_* constants as keys)
* Don't call this function directly: use getFinalParams() to allow
* hooks to modify parameters as needed.
*
* Some derived classes may choose to handle an integer $flags parameter
* in the overriding methods. Callers of this method can pass zero or
* more OR-ed flags like GET_VALUES_FOR_HELP.
*
* @stable to override
* @return array
*/
protected function getAllowedParams( /* $flags = 0 */ ) {
// $flags is not declared because it causes "Strict standards"
// warning. Most derived classes do not implement it.
return [];
}
/**
* Indicates if this module needs maxlag to be checked.
*
* @stable to override
* @return bool
*/
public function shouldCheckMaxlag() {
return true;
}
/**
* Indicates whether this module requires read rights.
*
* @stable to override
* @return bool
*/
public function isReadMode() {
return true;
}
/**
* Indicates whether this module requires write mode.
*
* This should return true for modules that may require synchronous database writes.
* Modules that do not need such writes should also not rely on primary database access,
* since only read queries are needed and each primary DB is a single point of failure.
* Additionally, requests that only need replica DBs can be efficiently routed to any
* datacenter via the Promise-Non-Write-API-Action header.
*
* @stable to override
* @return bool
*/
public function isWriteMode() {
return false;
}
/**
* Indicates whether this module must be called with a POST request.
*
* @stable to override
* @return bool
*/
public function mustBePosted() {
return $this->needsToken() !== false;
}
/**
* Indicates whether this module is deprecated.
*
* @since 1.25
* @stable to override
* @return bool
*/
public function isDeprecated() {
return false;
}
/**
* Indicates whether this module is considered to be "internal".
*
* Internal API modules are not (yet) intended for 3rd party use and may be unstable.
*
* @since 1.25
* @stable to override
* @return bool
*/
public function isInternal() {
return false;
}
/**
* Returns the token type this module requires in order to execute.
*
* Modules are strongly encouraged to use the core 'csrf' type unless they
* have specialized security needs. If the token type is not one of the
* core types, you must use the ApiQueryTokensRegisterTypes hook to
* register it.
*
* Returning a non-falsey value here will force the addition of an
* appropriate 'token' parameter in self::getFinalParams(). Also,
* self::mustBePosted() must return true when tokens are used.
*
* In previous versions of MediaWiki, true was a valid return value.
* Returning true will generate errors indicating that the API module needs
* updating.
*
* @stable to override
* @return string|false
*/
public function needsToken() {
return false;
}
/**
* Fetch the salt used in the Web UI corresponding to this module.
*
* Only override this if the Web UI uses a token with a non-constant salt.
*
* @since 1.24
* @param array $params All supplied parameters for the module
* @stable to override
* @return string|array|null
*/
protected function getWebUITokenSalt( array $params ) {
return null;
}
/**
* Returns data for HTTP conditional request mechanisms.
*
* @since 1.26
* @stable to override
* @param string $condition Condition being queried:
* - last-modified: Return a timestamp representing the maximum of the
* last-modified dates for all resources involved in the request. See
* RFC 7232 § 2.2 for semantics.
* - etag: Return an entity-tag representing the state of all resources involved
* in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
* @return string|bool|null As described above, or null if no value is available.
*/
public function getConditionalRequestData( $condition ) {
return null;
}
// endregion -- end of methods to implement
/***************************************************************************/
// region Data access methods
/** @name Data access methods */
/**
* Get the name of the module being executed by this instance.
*
* @return string
*/
public function getModuleName() {
return $this->mModuleName;
}
/**
* Get parameter prefix (usually two letters or an empty string).
*
* @return string
*/
public function getModulePrefix() {
return $this->mModulePrefix;
}
/**
* Get the main module.
*
* @return ApiMain
*/
public function getMain() {
return $this->mMainModule;
}
/**
* Returns true if this module is the main module ($this === $this->mMainModule),
* false otherwise.
*
* @return bool
*/
public function isMain() {
return $this === $this->mMainModule;
}
/**
* Get the parent of this module.
*
* @stable to override
* @since 1.25
* @return ApiBase|null
*/
public function getParent() {
return $this->isMain() ? null : $this->getMain();
}
/**
* Used to avoid infinite loops - the ApiMain class should override some
* methods, if it doesn't and uses the default ApiBase implementation, which
* just calls the same method for the ApiMain instance, it'll lead to an infinite loop
*
* @param string $methodName used for debug messages
*/
private function dieIfMain( string $methodName ) {
if ( $this->isMain() ) {
self::dieDebug( $methodName, 'base method was called on main module.' );
}
}
/**
* Returns true if the current request breaks the same-origin policy.
*
* For example, json with callbacks.
*
* https://en.wikipedia.org/wiki/Same-origin_policy
*
* @since 1.25
* @return bool
*/
public function lacksSameOriginSecurity() {
// The Main module has this method overridden, avoid infinite loops
$this->dieIfMain( __METHOD__ );
return $this->getMain()->lacksSameOriginSecurity();
}
/**
* Get the path to this module.
*
* @since 1.25
* @return string
*/
public function getModulePath() {
if ( $this->isMain() ) {
return 'main';
}
if ( $this->getParent()->isMain() ) {
return $this->getModuleName();
}
return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
}
/**
* Get a module from its module path.
*
* @since 1.25
* @param string $path
* @return ApiBase|null
* @throws ApiUsageException
*/
public function getModuleFromPath( $path ) {
$module = $this->getMain();
if ( $path === 'main' ) {
return $module;
}
$parts = explode( '+', $path );
if ( count( $parts ) === 1 ) {
// In case the '+' was typed into URL, it resolves as a space
$parts = explode( ' ', $path );
}
foreach ( $parts as $i => $v ) {
$parent = $module;
$manager = $parent->getModuleManager();
if ( $manager === null ) {
$errorPath = implode( '+', array_slice( $parts, 0, $i ) );
$this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
}
$module = $manager->getModule( $v );
if ( $module === null ) {
$errorPath = $i
? implode( '+', array_slice( $parts, 0, $i ) )
: $parent->getModuleName();
$this->dieWithError(
[ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $v ) ],
'badmodule'
);
}
}
return $module;
}
/**
* Get the result object.
*
* @return ApiResult
*/
public function getResult() {
// The Main module has this method overridden, avoid infinite loops
$this->dieIfMain( __METHOD__ );
return $this->getMain()->getResult();
}
/**
* @stable to override
* @return ApiErrorFormatter
*/
public function getErrorFormatter() {
// The Main module has this method overridden, avoid infinite loops
$this->dieIfMain( __METHOD__ );
return $this->getMain()->getErrorFormatter();
}
/**
* Gets a default replica DB connection object.
*
* @stable to override
* @return IReadableDatabase
*/
protected function getDB() {
if ( !isset( $this->mReplicaDB ) ) {
$this->mReplicaDB = MediaWikiServices::getInstance()
->getConnectionProvider()
->getReplicaDatabase( false, 'api' );
}
return $this->mReplicaDB;
}
/**
* @return ApiContinuationManager|null
*/
public function getContinuationManager() {
// The Main module has this method overridden, avoid infinite loops
$this->dieIfMain( __METHOD__ );
return $this->getMain()->getContinuationManager();
}
/**
* @param ApiContinuationManager|null $manager
*/
public function setContinuationManager( ApiContinuationManager $manager = null ) {
// The Main module has this method overridden, avoid infinite loops
$this->dieIfMain( __METHOD__ );
$this->getMain()->setContinuationManager( $manager );
}
/**
* Obtain a PermissionManager instance that subclasses may use in their authorization checks.
*
* @since 1.34
* @return PermissionManager
*/
protected function getPermissionManager(): PermissionManager {
return MediaWikiServices::getInstance()->getPermissionManager();
}
/**
* Get a HookContainer, for running extension hooks or for hook metadata.
*
* @since 1.35
* @return HookContainer
*/
protected function getHookContainer() {
if ( !$this->hookContainer ) {
$this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
}
return $this->hookContainer;
}
/**
* Get an ApiHookRunner for running core API hooks.
*
* @internal This is for use by core only. Hook interfaces may be removed
* without notice.
* @since 1.35
* @return ApiHookRunner
*/
protected function getHookRunner() {
if ( !$this->hookRunner ) {
$this->hookRunner = new ApiHookRunner( $this->getHookContainer() );
}
return $this->hookRunner;
}
// endregion -- end of data access methods
/***************************************************************************/
// region Parameter handling
/** @name Parameter handling */
/**
* Indicate if the module supports dynamically-determined parameters that
* cannot be included in self::getAllowedParams().
* @stable to override
* @return string|array|Message|null Return null if the module does not
* support additional dynamic parameters, otherwise return a message
* describing them.
*/
public function dynamicParameterDocumentation() {
return null;
}
/**
* This method mangles parameter name based on the prefix supplied to the constructor.
* Override this method to change parameter name during runtime.
*
* @param string|string[] $paramName Parameter name
* @return string|string[] Prefixed parameter name
* @since 1.29 accepts an array of strings
*/
public function encodeParamName( $paramName ) {
if ( is_array( $paramName ) ) {
return array_map( function ( $name ) {
return $this->mModulePrefix . $name;
}, $paramName );
}
return $this->mModulePrefix . $paramName;
}
/**
* Using getAllowedParams(), this function makes an array of the values
* provided by the user, with the key being the name of the variable, and
* value - validated value from user or default. limits will not be
* parsed if $parseLimit is set to false; use this when the max
* limit is not definitive yet, e.g. when getting revisions.
* @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
* - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
* - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
* Returned parameter values might be ApiUsageException instances.
* @return array
*/
public function extractRequestParams( $options = [] ) {
if ( is_bool( $options ) ) {
$options = [ 'parseLimit' => $options ];
}
$options += [
'parseLimit' => true,
'safeMode' => false,
];
// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
$parseLimit = (bool)$options['parseLimit'];
$cacheKey = (int)$parseLimit;
// Cache parameters, for performance and to avoid T26564.
if ( !isset( $this->mParamCache[$cacheKey] ) ) {
$params = $this->getFinalParams() ?: [];
$results = [];
$warned = [];
// Process all non-templates and save templates for secondary
// processing.
$toProcess = [];
foreach ( $params as $paramName => $paramSettings ) {
if ( isset( $paramSettings[self::PARAM_TEMPLATE_VARS] ) ) {
$toProcess[] = [ $paramName, $paramSettings[self::PARAM_TEMPLATE_VARS], $paramSettings ];
} else {
try {
$results[$paramName] = $this->getParameterFromSettings(
$paramName, $paramSettings, $parseLimit
);
} catch ( ApiUsageException $ex ) {
$results[$paramName] = $ex;
}
}
}
// Now process all the templates by successively replacing the
// placeholders with all client-supplied values.
// This bit duplicates JavaScript logic in
// ApiSandbox.PageLayout.prototype.updateTemplatedParams().
// If you update this, see if that needs updating too.
while ( $toProcess ) {
[ $name, $targets, $settings ] = array_shift( $toProcess );
foreach ( $targets as $placeholder => $target ) {
if ( !array_key_exists( $target, $results ) ) {
// The target wasn't processed yet, try the next one.
// If all hit this case, the parameter has no expansions.
continue;
}
if ( !is_array( $results[$target] ) || !$results[$target] ) {
// The target was processed but has no (valid) values.
// That means it has no expansions.
break;
}
// Expand this target in the name and all other targets,
// then requeue if there are more targets left or put in
// $results if all are done.
unset( $targets[$placeholder] );
$placeholder = '{' . $placeholder . '}';
// @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
foreach ( $results[$target] as $value ) {
if ( !preg_match( '/^[^{}]*$/', $value ) ) {
// Skip values that make invalid parameter names.
$encTargetName = $this->encodeParamName( $target );
if ( !isset( $warned[$encTargetName][$value] ) ) {
$warned[$encTargetName][$value] = true;
$this->addWarning( [
'apiwarn-ignoring-invalid-templated-value',
wfEscapeWikiText( $encTargetName ),
wfEscapeWikiText( $value ),
] );
}
continue;
}
$newName = str_replace( $placeholder, $value, $name );
if ( !$targets ) {
try {
$results[$newName] = $this->getParameterFromSettings(
$newName,
$settings,
$parseLimit
);
} catch ( ApiUsageException $ex ) {
$results[$newName] = $ex;
}
} else {
$newTargets = [];
foreach ( $targets as $k => $v ) {
$newTargets[$k] = str_replace( $placeholder, $value, $v );
}
$toProcess[] = [ $newName, $newTargets, $settings ];
}
}
break;
}
}
$this->mParamCache[$cacheKey] = $results;
}
$ret = $this->mParamCache[$cacheKey];
if ( !$options['safeMode'] ) {
foreach ( $ret as $v ) {
if ( $v instanceof ApiUsageException ) {
throw $v;
}
}
}
return $this->mParamCache[$cacheKey];
}
/**
* Get a value for the given parameter.
*
* @param string $paramName Parameter name
* @param bool $parseLimit See extractRequestParams()
* @return mixed Parameter value
*/
protected function getParameter( $paramName, $parseLimit = true ) {
$ret = $this->extractRequestParams( [
'parseLimit' => $parseLimit,
'safeMode' => true,
] )[$paramName];
if ( $ret instanceof ApiUsageException ) {
throw $ret;
}
return $ret;
}
/**
* Die if 0 or more than one of a certain set of parameters is set and not false.
*
* @param array $params User provided parameter set, as from $this->extractRequestParams()
* @param string ...$required Names of parameters of which exactly one must be set
*/
public function requireOnlyOneParameter( $params, ...$required ) {
$intersection = array_intersect( array_keys( array_filter( $params,
[ $this, 'parameterNotEmpty' ] ) ), $required );
if ( count( $intersection ) > 1 ) {
$this->dieWithError( [
'apierror-invalidparammix',
Message::listParam( array_map(
function ( $p ) {
return '<var>' . $this->encodeParamName( $p ) . '</var>';
},
array_values( $intersection )
) ),
count( $intersection ),
] );
} elseif ( count( $intersection ) == 0 ) {
$this->dieWithError( [
'apierror-missingparam-one-of',
Message::listParam( array_map(
function ( $p ) {
return '<var>' . $this->encodeParamName( $p ) . '</var>';
},
$required
) ),
count( $required ),
], 'missingparam' );
}
}
/**
* Dies if more than one parameter from a certain set of parameters are set and not false.
*
* @param array $params User provided parameters set, as from $this->extractRequestParams()
* @param string ...$required Parameter names that cannot have more than one set
*/
public function requireMaxOneParameter( $params, ...$required ) {
$intersection = array_intersect( array_keys( array_filter( $params,
[ $this, 'parameterNotEmpty' ] ) ), $required );
if ( count( $intersection ) > 1 ) {
$this->dieWithError( [
'apierror-invalidparammix',
Message::listParam( array_map(
function ( $p ) {
return '<var>' . $this->encodeParamName( $p ) . '</var>';
},
array_values( $intersection )
) ),
count( $intersection ),
] );
}
}
/**
* Die if 0 of a certain set of parameters is set and not false.
*
* @since 1.23
* @param array $params User provided parameters set, as from $this->extractRequestParams()
* @param string ...$required Names of parameters of which at least one must be set
*/
public function requireAtLeastOneParameter( $params, ...$required ) {
$intersection = array_intersect(
array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
$required
);
if ( count( $intersection ) == 0 ) {
$this->dieWithError( [
'apierror-missingparam-at-least-one-of',
Message::listParam( array_map(
function ( $p ) {
return '<var>' . $this->encodeParamName( $p ) . '</var>';
},
$required
) ),
count( $required ),
], 'missingparam' );
}
}
/**
* Die if any of the specified parameters were found in the query part of
* the URL rather than the HTTP post body contents.
*
* @since 1.28
* @param string[] $params Parameters to check
* @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
*/
public function requirePostedParameters( $params, $prefix = 'prefix' ) {
if ( !$this->mustBePosted() ) {
// In order to allow client code to choose the correct method (GET or POST) depending *only*
// on mustBePosted(), make sure that the module requires posting if any of its potential
// parameters require posting.
// TODO: Uncomment this
// throw new LogicException( 'mustBePosted() must be true when using requirePostedParameters()' );
// This seems to already be the case in all modules in practice, but deprecate it first just
// in case.
wfDeprecatedMsg( 'mustBePosted() must be true when using requirePostedParameters()',
'1.42' );
}
// Skip if $wgDebugAPI is set, or if we're in internal mode
if ( $this->getConfig()->get( MainConfigNames::DebugAPI ) ||
$this->getMain()->isInternalMode() ) {
return;
}
$queryValues = $this->getRequest()->getQueryValuesOnly();
$badParams = [];
foreach ( $params as $param ) {
if ( $prefix !== 'noprefix' ) {
$param = $this->encodeParamName( $param );
}
if ( array_key_exists( $param, $queryValues ) ) {
$badParams[] = $param;
}
}
if ( $badParams ) {
$this->dieWithError(
[ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
);
}
}
/**
* Callback function used in requireOnlyOneParameter to check whether required parameters are set.
*
* @param mixed $x Parameter to check is not null/false
* @return bool
*/
private function parameterNotEmpty( $x ) {
return $x !== null && $x !== false;
}
/**
* Attempts to load a WikiPage object from a title or pageid parameter, if possible.
* It can die if no param is set or if the title or page ID is not valid.
*
* @param array $params User provided parameter set, as from $this->extractRequestParams()
* @param string|false $load Whether load the object's state from the database:
* - false: don't load (if the pageid is given, it will still be loaded)
* - 'fromdb': load from a replica DB
* - 'fromdbmaster': load from the primary database
* @return WikiPage
*/
public function getTitleOrPageId( $params, $load = false ) {
$this->requireOnlyOneParameter( $params, 'title', 'pageid' );
$pageObj = null;
if ( isset( $params['title'] ) ) {
$titleObj = Title::newFromText( $params['title'] );
if ( !$titleObj || $titleObj->isExternal() ) {
$this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
}
if ( !$titleObj->canExist() ) {
$this->dieWithError( 'apierror-pagecannotexist' );
}
// @phan-suppress-next-line PhanTypeMismatchArgumentNullable T240141
$pageObj = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $titleObj );
if ( $load !== false ) {
$pageObj->loadPageData( $load );
}
} elseif ( isset( $params['pageid'] ) ) {
if ( $load === false ) {
$load = 'fromdb';
}
$pageObj = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromID( $params['pageid'], $load );
if ( !$pageObj ) {
$this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
}
}
// @phan-suppress-next-line PhanTypeMismatchReturnNullable requireOnlyOneParameter guard it is always set
return $pageObj;
}
/**
* Get a Title object from a title or pageid param, if it is possible.
* It can die if no param is set or if the title or page ID is not valid.
*
* @since 1.29
* @param array $params User provided parameter set, as from $this->extractRequestParams()
* @return Title
*/
public function getTitleFromTitleOrPageId( $params ) {
$this->requireOnlyOneParameter( $params, 'title', 'pageid' );
$titleObj = null;
if ( isset( $params['title'] ) ) {
$titleObj = Title::newFromText( $params['title'] );
if ( !$titleObj || $titleObj->isExternal() ) {
$this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
}
// @phan-suppress-next-line PhanTypeMismatchReturnNullable T240141
return $titleObj;
}
if ( isset( $params['pageid'] ) ) {
$titleObj = Title::newFromID( $params['pageid'] );
if ( !$titleObj ) {
$this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
}
}
// @phan-suppress-next-line PhanTypeMismatchReturnNullable requireOnlyOneParameter guard it is always set
return $titleObj;
}
/**
* Using the settings, determine the value for the given parameter.
*
* @param string $name Parameter name
* @param array|mixed $settings Default value or an array of settings
* using PARAM_* constants.
* @param bool $parseLimit Whether to parse and validate 'limit' parameters
* @return mixed Parameter value
*/
protected function getParameterFromSettings( $name, $settings, $parseLimit ) {
$validator = $this->getMain()->getParamValidator();
$value = $validator->getValue( $this, $name, $settings, [
'parse-limit' => $parseLimit,
'raw' => ( $settings[ParamValidator::PARAM_TYPE] ?? '' ) === 'raw',
] );
// @todo Deprecate and remove this, if possible.
if ( $parseLimit && isset( $settings[ParamValidator::PARAM_TYPE] ) &&
$settings[ParamValidator::PARAM_TYPE] === 'limit' &&
$this->getMain()->getVal( $this->encodeParamName( $name ) ) === 'max'
) {
$this->getResult()->addParsedLimit( $this->getModuleName(), $value );
}
return $value;
}
/**
* Handle when a parameter was Unicode-normalized.
*
* @since 1.28
* @since 1.35 $paramName is prefixed
* @internal For overriding by subclasses and use by ApiParamValidatorCallbacks only.
* @param string $paramName Prefixed parameter name
* @param string $value Input that will be used.
* @param string $rawValue Input before normalization.
*/
public function handleParamNormalization( $paramName, $value, $rawValue ) {
$this->addWarning( [ 'apiwarn-badutf8', $paramName ] );
}
/**
* Validate the supplied token.
*
* @since 1.24
* @param string $token Supplied token
* @param array $params All supplied parameters for the module
* @return bool
*/
final public function validateToken( $token, array $params ) {
$tokenType = $this->needsToken();
$salts = ApiQueryTokens::getTokenTypeSalts();
if ( !isset( $salts[$tokenType] ) ) {
throw new LogicException(
"Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
'without registering it'
);
}
$tokenObj = ApiQueryTokens::getToken(
$this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
);
if ( $tokenObj->match( $token ) ) {
return true;
}
$webUiSalt = $this->getWebUITokenSalt( $params );
return $webUiSalt !== null && $this->getUser()->matchEditToken(
$token, $webUiSalt, $this->getRequest()
);
}
// endregion -- end of parameter handling
/***************************************************************************/
// region Utility methods
/** @name Utility methods */
/**
* Gets the user for whom to get the watchlist
*
* @param array $params
* @return User
*/
public function getWatchlistUser( $params ) {
if ( $params['owner'] !== null && $params['token'] !== null ) {
$services = MediaWikiServices::getInstance();
$user = $services->getUserFactory()->newFromName( $params['owner'], UserRigorOptions::RIGOR_NONE );
if ( !$user || !$user->isRegistered() ) {
$this->dieWithError(
[ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
);
}
// @phan-suppress-next-line PhanTypeMismatchArgumentNullable T240141
$token = $services->getUserOptionsLookup()->getOption( $user, 'watchlisttoken' );
if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
$this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
}
} else {
$user = $this->getUser();
if ( !$user->isRegistered() ) {
$this->dieWithError( 'watchlistanontext', 'notloggedin' );
}
$this->checkUserRightsAny( 'viewmywatchlist' );
}
// @phan-suppress-next-line PhanTypeMismatchReturnNullable T240141
return $user;
}
/**
* Create a Message from a string or array
*
* A string is used as a message key. An array has the message key as the
* first value and message parameters as subsequent values.
*
* @since 1.25
* @param string|array|Message $msg
* @phan-param string|non-empty-array|Message $msg
* @param IContextSource $context
* @param array|null $params
* @return Message|null
*/
public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
if ( is_string( $msg ) ) {
$msg = wfMessage( $msg );
} elseif ( is_array( $msg ) ) {
$msg = wfMessage( ...$msg );
}
if ( !$msg instanceof Message ) {
return null;
}
$msg->setContext( $context );
if ( $params ) {
$msg->params( $params );
}
return $msg;
}
/**
* Turn an array of messages into a Status.
*
* @see ApiMessage::create
*
* @since 1.29
* @param array $errors A list of message keys, MessageSpecifier objects,
* or arrays containing the message key and parameters.
* @param Authority|null $performer
* @return Status
*/
public function errorArrayToStatus( array $errors, Authority $performer = null ) {
$performer ??= $this->getAuthority();
$block = $performer->getBlock();
$status = Status::newGood();
foreach ( $errors as $error ) {
if ( !is_array( $error ) ) {
$error = [ $error ];
}
$head = reset( $error );
$key = ( $head instanceof MessageSpecifier ) ? $head->getKey() : (string)$head;
if ( isset( self::BLOCK_CODE_MAP[$key] ) && $block ) {
$status->fatal( ApiMessage::create(
$error,
$this->getBlockCode( $block ),
[ 'blockinfo' => $this->getBlockDetails( $block ) ]
) );
} elseif ( isset( self::MESSAGE_CODE_MAP[$key] ) ) {
[ $msg, $code ] = self::MESSAGE_CODE_MAP[$key];
$status->fatal( ApiMessage::create( $msg, $code ) );
} else {
// @phan-suppress-next-line PhanParamTooFewUnpack
$status->fatal( ...$error );
}
}
return $status;
}
/**
* Add block info to block messages in a Status
* @since 1.33
* @internal since 1.37, should become protected in the future.
* @param StatusValue $status
* @param Authority|null $user
*/
public function addBlockInfoToStatus( StatusValue $status, Authority $user = null ) {
if ( $status instanceof PermissionStatus ) {
$block = $status->getBlock();
} else {
$user = $user ?: $this->getAuthority();
$block = $user->getBlock();
}
if ( !$block ) {
return;
}
foreach ( $status->getErrors() as $error ) {
$msgKey = $error['message'] instanceof MessageSpecifier ?
$error['message']->getKey() :
$error['message'];
if ( isset( self::BLOCK_CODE_MAP[$msgKey] ) ) {
$status->replaceMessage( $msgKey, ApiMessage::create(
$error,
$this->getBlockCode( $block ),
[ 'blockinfo' => $this->getBlockDetails( $block ) ]
) );
}
}
}
/**
* Call wfTransactionalTimeLimit() if this request was POSTed.
*
* @since 1.26
*/
protected function useTransactionalTimeLimit() {
if ( $this->getRequest()->wasPosted() ) {
wfTransactionalTimeLimit();
}
}
/**
* Reset static caches of database state.
*
* @internal For testing only
*/
public static function clearCacheForTest(): void {
if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
throw new LogicException( 'Not allowed outside tests' );
}
self::$filterIDsCache = [];
}
/**
* Filter out-of-range values from a list of positive integer IDs
*
* @since 1.33
* @param string[][] $fields Array of table and field pairs to check
* @param (string|int)[] $ids IDs to filter. Strings in the array are
* expected to be stringified integers.
* @return (string|int)[] Filtered IDs.
*/
protected function filterIDs( $fields, array $ids ) {
$min = INF;
$max = 0;
foreach ( $fields as [ $table, $field ] ) {
if ( isset( self::$filterIDsCache[$table][$field] ) ) {
$row = self::$filterIDsCache[$table][$field];
} else {
$row = $this->getDB()->newSelectQueryBuilder()
->select( [ 'min_id' => "MIN($field)", 'max_id' => "MAX($field)" ] )
->from( $table )
->caller( __METHOD__ )->fetchRow();
self::$filterIDsCache[$table][$field] = $row;
}
$min = min( $min, $row->min_id );
$max = max( $max, $row->max_id );
}
return array_filter( $ids, static function ( $id ) use ( $min, $max ) {
return ( is_int( $id ) && $id >= 0 || ctype_digit( (string)$id ) )
&& $id >= $min && $id <= $max;
} );
}
// endregion -- end of utility methods
/***************************************************************************/
// region Warning and error reporting
/** @name Warning and error reporting */
/**
* Add a warning for this module.
*
* Users should monitor this section to notice any changes in the API.
*
* Multiple calls to this function will result in multiple warning messages.
*
* If $msg is not an ApiMessage, the message code will be derived from the
* message key by stripping any "apiwarn-" or "apierror-" prefix.
*
* @since 1.29
* @param string|array|Message $msg See ApiErrorFormatter::addWarning()
* @param string|null $code See ApiErrorFormatter::addWarning()
* @param array|null $data See ApiErrorFormatter::addWarning()
*/
public function addWarning( $msg, $code = null, $data = null ) {
$this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
}
/**
* Add a deprecation warning for this module.
*
* A combination of $this->addWarning() and $this->logFeatureUsage()
*
* @since 1.29
* @param string|array|Message $msg See ApiErrorFormatter::addWarning()
* @param string|null $feature See ApiBase::logFeatureUsage()
* @param array|null $data See ApiErrorFormatter::addWarning()
*/
public function addDeprecation( $msg, $feature, $data = [] ) {
$data = (array)$data;
if ( $feature !== null ) {
$data['feature'] = $feature;
$this->logFeatureUsage( $feature );
}
$this->addWarning( $msg, 'deprecation', $data );
// No real need to deduplicate here, ApiErrorFormatter does that for
// us (assuming the hook is deterministic).
$msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
$this->getHookRunner()->onApiDeprecationHelp( $msgs );
if ( count( $msgs ) > 1 ) {
$key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
$msg = ( new RawMessage( $key ) )->params( $msgs );
} else {
$msg = reset( $msgs );
}
$this->getMain()->addWarning( $msg, 'deprecation-help' );
}
/**
* Add an error for this module without aborting
*
* If $msg is not an ApiMessage, the message code will be derived from the
* message key by stripping any "apiwarn-" or "apierror-" prefix.
*
* @note If you want to abort processing, use self::dieWithError() instead.
* @since 1.29
* @param string|array|Message $msg See ApiErrorFormatter::addError()
* @param string|null $code See ApiErrorFormatter::addError()
* @param array|null $data See ApiErrorFormatter::addError()
*/
public function addError( $msg, $code = null, $data = null ) {
$this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
}
/**
* Add warnings and/or errors from a Status
*
* @note If you want to abort processing, use self::dieStatus() instead.
* @since 1.29
* @param StatusValue $status
* @param string[] $types 'warning' and/or 'error'
* @param string[] $filter Message keys to filter out (since 1.33)
*/
public function addMessagesFromStatus(
StatusValue $status, $types = [ 'warning', 'error' ], array $filter = []
) {
$this->getErrorFormatter()->addMessagesFromStatus(
$this->getModulePath(), $status, $types, $filter
);
}
/**
* Abort execution with an error
*
* If $msg is not an ApiMessage, the message code will be derived from the
* message key by stripping any "apiwarn-" or "apierror-" prefix.
*
* @since 1.29
* @param string|array|Message $msg See ApiErrorFormatter::addError()
* @param string|null $code See ApiErrorFormatter::addError()
* @param array|null $data See ApiErrorFormatter::addError()
* @param int $httpCode HTTP error code to use
* @throws ApiUsageException always
* @return never
*/
public function dieWithError( $msg, $code = null, $data = null, $httpCode = 0 ) {
throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
}
/**
* Abort execution with an error derived from a throwable
*
* @since 1.29
* @param Throwable $exception See ApiErrorFormatter::getMessageFromException()
* @param array $options See ApiErrorFormatter::getMessageFromException()
* @throws ApiUsageException always
* @return never
*/
public function dieWithException( Throwable $exception, array $options = [] ) {
$this->dieWithError(
// @phan-suppress-next-line PhanTypeMismatchArgument
$this->getErrorFormatter()->getMessageFromException( $exception, $options )
);
}
/**
* Throw an ApiUsageException, which will (if uncaught) call the main module's
* error handler and die with an error message including block info.
*
* @since 1.27
* @param Block $block The block used to generate the ApiUsageException
* @throws ApiUsageException always
* @return never
*/
public function dieBlocked( Block $block ) {
$blockErrorFormatter = MediaWikiServices::getInstance()->getFormatterFactory()
->getBlockErrorFormatter( $this->getContext() );
$msg = $blockErrorFormatter->getMessage(
$block,
$this->getUser(),
null,
$this->getRequest()->getIP()
);
$this->dieWithError(
$msg,
$this->getBlockCode( $block ),
[ 'blockinfo' => $this->getBlockDetails( $block ) ]
);
}
/**
* Throw an ApiUsageException based on the Status object.
*
* @since 1.22
* @since 1.29 Accepts a StatusValue
* @param StatusValue $status
* @throws ApiUsageException always
* @return never
*/
public function dieStatus( StatusValue $status ) {
if ( $status->isGood() ) {
throw new InvalidArgumentException( 'Successful status passed to ApiBase::dieStatus' );
}
foreach ( self::MESSAGE_CODE_MAP as $msg => [ $apiMsg, $code ] ) {
if ( $status->hasMessage( $msg ) ) {
$status->replaceMessage( $msg, ApiMessage::create( $apiMsg, $code ) );
}
}
if (
$status instanceof PermissionStatus
&& $status->isRateLimitExceeded()
&& !$status->hasMessage( 'apierror-ratelimited' )
) {
$status->fatal( ApiMessage::create( 'apierror-ratelimited', 'ratelimited' ) );
}
// ApiUsageException needs a fatal status, but this method has
// historically accepted any non-good status. Convert it if necessary.
$status->setOK( false );
if ( !$status->getErrorsByType( 'error' ) ) {
$newStatus = Status::newGood();
foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
$newStatus->fatal( $err['message'], ...$err['params'] );
}
if ( !$newStatus->getErrorsByType( 'error' ) ) {
$newStatus->fatal( 'unknownerror-nocode' );
}
$status = $newStatus;
}
$this->addBlockInfoToStatus( $status );
throw new ApiUsageException( $this, $status );
}
/**
* Helper function for readonly errors.
*
* @throws ApiUsageException always
* @return never
*/
public function dieReadOnly() {
$this->dieWithError(
'apierror-readonly',
'readonly',
[ 'readonlyreason' => MediaWikiServices::getInstance()->getReadOnlyMode()->getReason() ]
);
}
/**
* Helper function for permission-denied errors.
*
* @since 1.29
* @param string|string[] $rights
* @throws ApiUsageException if the user doesn't have any of the rights.
* The error message is based on $rights[0].
*/
public function checkUserRightsAny( $rights ) {
$rights = (array)$rights;
if ( !$this->getAuthority()->isAllowedAny( ...$rights ) ) {
$this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
}
}
/**
* Helper function for permission-denied errors.
*
* @param PageIdentity $pageIdentity
* @param string|string[] $actions
* @param array $options Additional options
* - user: (User) User to use rather than $this->getUser().
* - autoblock: (bool, default false) Whether to spread autoblocks.
* @phan-param array{user?:User,autoblock?:bool} $options
*
* @throws ApiUsageException if the user doesn't have all the necessary rights.
*
* @since 1.29
* @since 1.33 Changed the third parameter from $user to $options.
* @since 1.36 deprecated passing LinkTarget as first parameter
*/
public function checkTitleUserPermissions(
PageIdentity $pageIdentity,
$actions,
array $options = []
) {
$authority = $options['user'] ?? $this->getAuthority();
$status = new PermissionStatus();
foreach ( (array)$actions as $action ) {
if ( $this->isWriteMode() ) {
$authority->authorizeWrite( $action, $pageIdentity, $status );
} else {
$authority->authorizeRead( $action, $pageIdentity, $status );
}
}
if ( !$status->isGood() ) {
if ( !empty( $options['autoblock'] ) ) {
$this->getUser()->spreadAnyEditBlock();
}
$this->dieStatus( $status );
}
}
/**
* Will only set a warning instead of failing if the global $wgDebugAPI
* is set to true.
*
* Otherwise, it behaves exactly as self::dieWithError().
*
* @since 1.29
* @param string|array|Message $msg
* @param string|null $code
* @param array|null $data
* @param int|null $httpCode
* @throws ApiUsageException
*/
public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
if ( $this->getConfig()->get( MainConfigNames::DebugAPI ) !== true ) {
$this->dieWithError( $msg, $code, $data, $httpCode );
} else {
$this->addWarning( $msg, $code, $data );
}
}
/**
* Parse the 'continue' parameter in the usual format and validate the types of each part,
* or die with the 'badcontinue' error if the format, types, or the number of parts is wrong.
*
* @param string $continue Value of 'continue' parameter obtained from extractRequestParams()
* @param string[] $types Types of the expected parts in order, 'string', 'int' or 'timestamp'
* @return mixed[] Array containing strings, integers or timestamps
* @throws ApiUsageException
* @since 1.40
*/
protected function parseContinueParamOrDie( string $continue, array $types ): array {
$cont = explode( '|', $continue );
$this->dieContinueUsageIf( count( $cont ) != count( $types ) );
foreach ( $cont as $i => &$value ) {
switch ( $types[$i] ) {
case 'string':
// Do nothing
break;
case 'int':
$this->dieContinueUsageIf( $value !== (string)(int)$value );
$value = (int)$value;
break;
case 'timestamp':
try {
$dbTs = $this->getDB()->timestamp( $value );
} catch ( TimestampException $ex ) {
$dbTs = false;
}
$this->dieContinueUsageIf( $value !== $dbTs );
break;
default:
throw new InvalidArgumentException( "Unknown type '{$types[$i]}'" );
}
}
return $cont;
}
/**
* Die with the 'badcontinue' error.
*
* This call is common enough to make it into the base method.
*
* @param bool $condition Will only die if this value is true
* @throws ApiUsageException
* @since 1.21
* @phan-assert-false-condition $condition
*/
protected function dieContinueUsageIf( $condition ) {
if ( $condition ) {
$this->dieWithError( 'apierror-badcontinue' );
}
}
/**
* Internal code errors should be reported with this method.
*
* @param string $method Method or function name
* @param string $message Error message
* @return never
*/
protected static function dieDebug( $method, $message ) {
throw new MWException( "Internal error in $method: $message" );
}
/**
* Write logging information for API features to a debug log, for usage
* analysis.
*
* @note Consider using $this->addDeprecation() instead to both warn and log.
* @param string $feature Feature being used.
*/
public function logFeatureUsage( $feature ) {
static $loggedFeatures = [];
// Only log each feature once per request. We can get multiple calls from calls to
// extractRequestParams() with different values for 'parseLimit', for example.
if ( isset( $loggedFeatures[$feature] ) ) {
return;
}
$loggedFeatures[$feature] = true;
$request = $this->getRequest();
$ctx = [
'feature' => $feature,
// Replace spaces with underscores in 'username' for historical reasons.
'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
'clientip' => $request->getIP(),
'referer' => (string)$request->getHeader( 'Referer' ),
'agent' => $this->getMain()->getUserAgent(),
];
// Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
$s = '"' . addslashes( $ctx['feature'] ) . '"' .
' "' . wfUrlencode( $ctx['username'] ) . '"' .
' "' . $ctx['clientip'] . '"' .
' "' . addslashes( $ctx['referer'] ) . '"' .
' "' . addslashes( $ctx['agent'] ) . '"';
wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
}
// endregion -- end of warning and error reporting
/***************************************************************************/
// region Help message generation
/** @name Help message generation */
/**
* Return the summary message.
*
* This is a one-line description of the module, suitable for display in a
* list of modules.
*
* @since 1.30
* @stable to override
* @return string|array|Message
*/
protected function getSummaryMessage() {
return "apihelp-{$this->getModulePath()}-summary";
}
/**
* Return the extended help text message.
*
* This is additional text to display at the top of the help section, below
* the summary.
*
* @since 1.30
* @stable to override
* @return string|array|Message
*/
protected function getExtendedDescription() {
return [ [
"apihelp-{$this->getModulePath()}-extended-description",
'api-help-no-extended-description',
] ];
}
/**
* Get the final module summary
*
* @since 1.30
* @stable to override
* @return Message
*/
public function getFinalSummary() {
return self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
$this->getModulePrefix(),
$this->getModuleName(),
$this->getModulePath(),
] );
}
/**
* Get the final module description, after hooks have had a chance to tweak it as
* needed.
*
* @since 1.25, returns Message[] rather than string[]
* @return Message[]
*/
public function getFinalDescription() {
$summary = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
$this->getModulePrefix(),
$this->getModuleName(),
$this->getModulePath(),
] );
$extendedDescription = self::makeMessage(
$this->getExtendedDescription(), $this->getContext(), [
$this->getModulePrefix(),
$this->getModuleName(),
$this->getModulePath(),
]
);
$msgs = [ $summary, $extendedDescription ];
$this->getHookRunner()->onAPIGetDescriptionMessages( $this, $msgs );
return $msgs;
}
/**
* Get the final list of parameters, after hooks have had a chance to
* tweak it as needed.
*
* @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
* @return array
* @since 1.21 $flags param added
*/
public function getFinalParams( $flags = 0 ) {
// @phan-suppress-next-line PhanParamTooMany
$params = $this->getAllowedParams( $flags );
if ( !$params ) {
$params = [];
}
if ( $this->needsToken() ) {
$params['token'] = [
ParamValidator::PARAM_TYPE => 'string',
ParamValidator::PARAM_REQUIRED => true,
ParamValidator::PARAM_SENSITIVE => true,
self::PARAM_HELP_MSG => [
'api-help-param-token',
$this->needsToken(),
],
] + ( $params['token'] ?? [] );
}
$this->getHookRunner()->onAPIGetAllowedParams( $this, $params, $flags );
return $params;
}
/**
* Get final parameter descriptions, after hooks have had a chance to tweak it as
* needed.
*
* @since 1.25, returns array of Message[] rather than array of string[]
* @return array Keys are parameter names, values are arrays of Message objects
*/
public function getFinalParamDescription() {
$prefix = $this->getModulePrefix();
$name = $this->getModuleName();
$path = $this->getModulePath();
$params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
$msgs = [];
foreach ( $params as $param => $settings ) {
if ( !is_array( $settings ) ) {
$settings = [];
}
$msg = $settings[self::PARAM_HELP_MSG]
?? $this->msg( [ "apihelp-$path-param-$param", 'api-help-param-no-description' ] );
$msg = self::makeMessage( $msg, $this->getContext(),
[ $prefix, $param, $name, $path ] );
if ( !$msg ) {
self::dieDebug( __METHOD__,
'Value in ApiBase::PARAM_HELP_MSG is not valid' );
}
$msgs[$param] = [ $msg ];
if ( isset( $settings[ParamValidator::PARAM_TYPE] ) &&
$settings[ParamValidator::PARAM_TYPE] === 'submodule'
) {
if ( isset( $settings[SubmoduleDef::PARAM_SUBMODULE_MAP] ) ) {
$map = $settings[SubmoduleDef::PARAM_SUBMODULE_MAP];
} else {
$prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
$map = [];
foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
$map[$submoduleName] = $prefix . $submoduleName;
}
}
$submodules = [];
$submoduleFlags = []; // for sorting: higher flags are sorted later
$submoduleNames = []; // for sorting: lexicographical, ascending
foreach ( $map as $v => $m ) {
$isDeprecated = false;
$isInternal = false;
$summary = null;
try {
$submod = $this->getModuleFromPath( $m );
if ( $submod ) {
$summary = $submod->getFinalSummary();
$isDeprecated = $submod->isDeprecated();
$isInternal = $submod->isInternal();
}
} catch ( ApiUsageException $ex ) {
// Ignore
}
if ( $summary ) {
$key = $summary->getKey();
$params = $summary->getParams();
} else {
$key = 'api-help-undocumented-module';
$params = [ $m ];
}
$m = new ApiHelpParamValueMessage(
"[[Special:ApiHelp/$m|$v]]",
$key,
$params,
$isDeprecated,
$isInternal
);
$submodules[] = $m->setContext( $this->getContext() );
$submoduleFlags[] = ( $isDeprecated ? 1 : 0 ) | ( $isInternal ? 2 : 0 );
$submoduleNames[] = $v;
}
// sort $submodules by $submoduleFlags and $submoduleNames
array_multisort( $submoduleFlags, $submoduleNames, $submodules );
$msgs[$param] = array_merge( $msgs[$param], $submodules );
} elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
self::dieDebug( __METHOD__,
'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
}
$isArrayOfStrings = is_array( $settings[ParamValidator::PARAM_TYPE] )
|| (
$settings[ParamValidator::PARAM_TYPE] === 'string'
&& ( $settings[ParamValidator::PARAM_ISMULTI] ?? false )
);
if ( !$isArrayOfStrings ) {
self::dieDebug( __METHOD__,
'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
'ParamValidator::PARAM_TYPE is an array or it is \'string\' and ' .
'ParamValidator::PARAM_ISMULTI is true' );
}
$values = is_array( $settings[ParamValidator::PARAM_TYPE] ) ?
$settings[ParamValidator::PARAM_TYPE] :
array_keys( $settings[self::PARAM_HELP_MSG_PER_VALUE] );
$valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
$deprecatedValues = $settings[EnumDef::PARAM_DEPRECATED_VALUES] ?? [];
foreach ( $values as $value ) {
$msg = $valueMsgs[$value] ?? "apihelp-$path-paramvalue-$param-$value";
$m = self::makeMessage( $msg, $this->getContext(),
[ $prefix, $param, $name, $path, $value ] );
if ( $m ) {
$m = new ApiHelpParamValueMessage(
$value,
// @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal
[ $m->getKey(), 'api-help-param-no-description' ],
$m->getParams(),
isset( $deprecatedValues[$value] )
);
$msgs[$param][] = $m->setContext( $this->getContext() );
} else {
self::dieDebug( __METHOD__,
"Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
}
}
}
if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
self::dieDebug( __METHOD__,
'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
}
foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
$m = self::makeMessage( $m, $this->getContext(),
[ $prefix, $param, $name, $path ] );
if ( $m ) {
$msgs[$param][] = $m;
} else {
self::dieDebug( __METHOD__,
'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
}
}
}
}
$this->getHookRunner()->onAPIGetParamDescriptionMessages( $this, $msgs );
return $msgs;
}
/**
* Generates the list of flags for the help screen and for action=paraminfo.
*
* Corresponding messages: api-help-flag-deprecated,
* api-help-flag-internal, api-help-flag-readrights,
* api-help-flag-writerights, api-help-flag-mustbeposted
*
* @return string[]
*/
protected function getHelpFlags() {
$flags = [];
if ( $this->isDeprecated() ) {
$flags[] = 'deprecated';
}
if ( $this->isInternal() ) {
$flags[] = 'internal';
}
if ( $this->isReadMode() ) {
$flags[] = 'readrights';
}
if ( $this->isWriteMode() ) {
$flags[] = 'writerights';
}
if ( $this->mustBePosted() ) {
$flags[] = 'mustbeposted';
}
return $flags;
}
/**
* Returns information about the source of this module, if known
*
* Returned array is an array with the following keys:
* - path: Install path
* - name: Extension name, or "MediaWiki" for core
* - namemsg: (optional) i18n message key for a display name
* - license-name: (optional) Name of license
*
* @return array|null
*/
protected function getModuleSourceInfo() {
if ( $this->mModuleSource !== false ) {
return $this->mModuleSource;
}
// First, try to find where the module comes from...
$rClass = new ReflectionClass( $this );
$path = $rClass->getFileName();
if ( !$path ) {
// No path known?
$this->mModuleSource = null;
return null;
}
$path = realpath( $path ) ?: $path;
// Build a map of extension directories to extension info
if ( self::$extensionInfo === null ) {
$extDir = $this->getConfig()->get( MainConfigNames::ExtensionDirectory );
$baseDir = $this->getConfig()->get( MainConfigNames::BaseDirectory );
self::$extensionInfo = [
realpath( __DIR__ ) ?: __DIR__ => [
'path' => $baseDir,
'name' => 'MediaWiki',
'license-name' => 'GPL-2.0-or-later',
],
realpath( "$baseDir/extensions" ) ?: "$baseDir/extensions" => null,
realpath( $extDir ) ?: $extDir => null,
];
$keep = [
'path' => null,
'name' => null,
'namemsg' => null,
'license-name' => null,
];
$credits = SpecialVersion::getCredits( ExtensionRegistry::getInstance(), $this->getConfig() );
foreach ( $credits as $group ) {
foreach ( $group as $ext ) {
if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
// This shouldn't happen, but does anyway.
continue;
}
$extpath = $ext['path'];
if ( !is_dir( $extpath ) ) {
$extpath = dirname( $extpath );
}
self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
array_intersect_key( $ext, $keep );
}
}
}
// Now traverse parent directories until we find a match or run out of parents.
do {
if ( array_key_exists( $path, self::$extensionInfo ) ) {
// Found it!
$this->mModuleSource = self::$extensionInfo[$path];
return $this->mModuleSource;
}
$oldpath = $path;
$path = dirname( $path );
} while ( $path !== $oldpath );
// No idea what extension this might be.
$this->mModuleSource = null;
return null;
}
/**
* Called from ApiHelp before the pieces are joined together and returned.
*
* This exists mainly for ApiMain to add the Permissions and Credits
* sections. Other modules probably don't need it.
*
* @stable to override
* @param string[] &$help Array of help data
* @param array $options Options passed to ApiHelp::getHelp
* @param array &$tocData If a TOC is being generated, this array has keys
* as anchors in the page and values as for Linker::generateTOC().
*/
public function modifyHelp( array &$help, array $options, array &$tocData ) {
}
// endregion -- end of help message generation
}
/*
* This file uses VisualStudio style region/endregion fold markers which are
* recognised by PHPStorm. If modelines are enabled, the following editor
* configuration will also enable folding in vim, if it is in the last 5 lines
* of the file. We also use "@name" which creates sections in Doxygen.
*
* vim: foldmarker=//\ region,//\ endregion foldmethod=marker
*/
|