-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathGlobalFunctions.php
2069 lines (1916 loc) · 64.4 KB
/
GlobalFunctions.php
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
<?php
/**
* Global functions used everywhere.
*
* 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\Debug\MWDebug;
use MediaWiki\Exception\ProcOpenError;
use MediaWiki\FileRepo\File\File;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\Logger\LoggerFactory;
use MediaWiki\MediaWikiServices;
use MediaWiki\Message\Message;
use MediaWiki\Registration\ExtensionRegistry;
use MediaWiki\Request\WebRequest;
use MediaWiki\Shell\Shell;
use MediaWiki\Title\Title;
use MediaWiki\Utils\UrlUtils;
use Wikimedia\AtEase\AtEase;
use Wikimedia\FileBackend\FileBackend;
use Wikimedia\FileBackend\FSFile\TempFSFile;
use Wikimedia\Message\MessageParam;
use Wikimedia\Message\MessageSpecifier;
use Wikimedia\ParamValidator\TypeDef\ExpiryDef;
use Wikimedia\RequestTimeout\RequestTimeout;
use Wikimedia\Timestamp\ConvertibleTimestamp;
/**
* Load an extension
*
* This queues an extension to be loaded through
* the ExtensionRegistry system.
*
* @param string $ext Name of the extension to load
* @param string|null $path Absolute path of where to find the extension.json file
* @since 1.25
*/
function wfLoadExtension( $ext, $path = null ) {
if ( !$path ) {
global $wgExtensionDirectory;
$path = "$wgExtensionDirectory/$ext/extension.json";
}
ExtensionRegistry::getInstance()->queue( $path );
}
/**
* Load multiple extensions at once
*
* Same as wfLoadExtension, but more efficient if you
* are loading multiple extensions.
*
* If you want to specify custom paths, you should interact with
* ExtensionRegistry directly.
*
* @see wfLoadExtension
* @param string[] $exts Array of extension names to load
* @since 1.25
*/
function wfLoadExtensions( array $exts ) {
global $wgExtensionDirectory;
$registry = ExtensionRegistry::getInstance();
foreach ( $exts as $ext ) {
$registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
}
}
/**
* Load a skin
*
* @see wfLoadExtension
* @param string $skin Name of the extension to load
* @param string|null $path Absolute path of where to find the skin.json file
* @since 1.25
*/
function wfLoadSkin( $skin, $path = null ) {
if ( !$path ) {
global $wgStyleDirectory;
$path = "$wgStyleDirectory/$skin/skin.json";
}
ExtensionRegistry::getInstance()->queue( $path );
}
/**
* Load multiple skins at once
*
* @see wfLoadExtensions
* @param string[] $skins Array of extension names to load
* @since 1.25
*/
function wfLoadSkins( array $skins ) {
global $wgStyleDirectory;
$registry = ExtensionRegistry::getInstance();
foreach ( $skins as $skin ) {
$registry->queue( "$wgStyleDirectory/$skin/skin.json" );
}
}
/**
* Like array_diff( $arr1, $arr2 ) except that it works with two-dimensional arrays.
* @deprecated since 1.43 Use StatusValue::merge() instead
* @param string[]|array[] $arr1
* @param string[]|array[] $arr2
* @return array
*/
function wfArrayDiff2( $arr1, $arr2 ) {
wfDeprecated( __FUNCTION__, '1.43' );
/**
* @param string|array $a
* @param string|array $b
*/
$comparator = static function ( $a, $b ): int {
if ( is_string( $a ) && is_string( $b ) ) {
return strcmp( $a, $b );
}
if ( !is_array( $a ) && !is_array( $b ) ) {
throw new InvalidArgumentException(
'This function assumes that array elements are all strings or all arrays'
);
}
if ( count( $a ) !== count( $b ) ) {
return count( $a ) <=> count( $b );
} else {
reset( $a );
reset( $b );
while ( key( $a ) !== null && key( $b ) !== null ) {
$valueA = current( $a );
$valueB = current( $b );
$cmp = strcmp( $valueA, $valueB );
if ( $cmp !== 0 ) {
return $cmp;
}
next( $a );
next( $b );
}
return 0;
}
};
return array_udiff( $arr1, $arr2, $comparator );
}
/**
* Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal
* e.g.
* wfMergeErrorArrays(
* [ [ 'x' ] ],
* [ [ 'x', '2' ] ],
* [ [ 'x' ] ],
* [ [ 'y' ] ]
* );
* returns:
* [
* [ 'x', '2' ],
* [ 'x' ],
* [ 'y' ]
* ]
*
* @deprecated since 1.43 Use StatusValue::merge() instead
* @param array[] ...$args
* @return array
*/
function wfMergeErrorArrays( ...$args ) {
wfDeprecated( __FUNCTION__, '1.43' );
$out = [];
foreach ( $args as $errors ) {
foreach ( $errors as $params ) {
$originalParams = $params;
if ( $params[0] instanceof MessageSpecifier ) {
$params = [ $params[0]->getKey(), ...$params[0]->getParams() ];
}
# @todo FIXME: Sometimes get nested arrays for $params,
# which leads to E_NOTICEs
$spec = implode( "\t", $params );
$out[$spec] = $originalParams;
}
}
return array_values( $out );
}
/**
* Insert an array into another array after the specified key. If the key is
* not present in the input array, it is returned without modification.
*
* @param array $array
* @param array $insert The array to insert.
* @param mixed $after The key to insert after.
* @return array
*/
function wfArrayInsertAfter( array $array, array $insert, $after ) {
// Find the offset of the element to insert after.
$keys = array_keys( $array );
$offsetByKey = array_flip( $keys );
if ( !\array_key_exists( $after, $offsetByKey ) ) {
return $array;
}
$offset = $offsetByKey[$after];
// Insert at the specified offset
$before = array_slice( $array, 0, $offset + 1, true );
$after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
$output = $before + $insert + $after;
return $output;
}
/**
* Recursively converts the parameter (an object) to an array with the same data
*
* @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
* @param object|array $objOrArray
* @param bool $recursive
* @return array
*/
function wfObjectToArray( $objOrArray, $recursive = true ) {
$array = [];
if ( is_object( $objOrArray ) ) {
$objOrArray = get_object_vars( $objOrArray );
}
foreach ( $objOrArray as $key => $value ) {
if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
$value = wfObjectToArray( $value );
}
$array[$key] = $value;
}
return $array;
}
/**
* Get a random decimal value in the domain of [0, 1), in a way
* not likely to give duplicate values for any realistic
* number of articles.
*
* @note This is designed for use in relation to Special:RandomPage
* and the page_random database field.
*
* @return string
*/
function wfRandom() {
// The maximum random value is "only" 2^31-1, so get two random
// values to reduce the chance of dupes
$max = mt_getrandmax() + 1;
$rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
return $rand;
}
/**
* Get a random string containing a number of pseudo-random hex characters.
*
* @note This is not secure, if you are trying to generate some sort
* of token please use MWCryptRand instead.
*
* @param int $length The length of the string to generate
* @return string
* @since 1.20
*/
function wfRandomString( $length = 32 ) {
$str = '';
for ( $n = 0; $n < $length; $n += 7 ) {
$str .= sprintf( '%07x', mt_rand() & 0xfffffff );
}
return substr( $str, 0, $length );
}
/**
* We want some things to be included as literal characters in our title URLs
* for prettiness, which urlencode encodes by default. According to RFC 1738,
* all of the following should be safe:
*
* ;:@&=$-_.+!*'(),
*
* RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved
* character which should not be encoded. More importantly, google chrome
* always converts %7E back to ~, and converting it in this function can
* cause a redirect loop (T105265).
*
* But + is not safe because it's used to indicate a space; &= are only safe in
* paths and not in queries (and we don't distinguish here); ' seems kind of
* scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
* is reserved, we don't care. So the list we unescape is:
*
* ;:@$!*(),/~
*
* However, IIS7 redirects fail when the url contains a colon (see T24709),
* so no fancy : for IIS7.
*
* %2F in the page titles seems to fatally break for some reason.
*
* @param string $s
* @return string
*/
function wfUrlencode( $s ) {
static $needle;
if ( $s === null ) {
// Reset $needle for testing.
$needle = null;
return '';
}
if ( $needle === null ) {
$needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
!str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' )
) {
$needle[] = '%3A';
}
}
$s = urlencode( $s );
$s = str_ireplace(
$needle,
[ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
$s
);
return $s;
}
/**
* This function takes one or two arrays as input, and returns a CGI-style string, e.g.
* "days=7&limit=100". Options in the first array override options in the second.
* Options set to null or false will not be output.
*
* @param array $array1 ( String|Array )
* @param array|null $array2 ( String|Array )
* @param string $prefix
* @return string
*/
function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
if ( $array2 !== null ) {
$array1 += $array2;
}
$cgi = '';
foreach ( $array1 as $key => $value ) {
if ( $value !== null && $value !== false ) {
if ( $cgi != '' ) {
$cgi .= '&';
}
if ( $prefix !== '' ) {
$key = $prefix . "[$key]";
}
if ( is_array( $value ) ) {
$firstTime = true;
foreach ( $value as $k => $v ) {
$cgi .= $firstTime ? '' : '&';
if ( is_array( $v ) ) {
$cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
} else {
$cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
}
$firstTime = false;
}
} else {
if ( is_object( $value ) ) {
$value = $value->__toString();
}
$cgi .= urlencode( $key ) . '=' . urlencode( $value );
}
}
}
return $cgi;
}
/**
* This is the logical opposite of wfArrayToCgi(): it accepts a query string as
* its argument and returns the same string in array form. This allows compatibility
* with legacy functions that accept raw query strings instead of nice
* arrays. Of course, keys and values are urldecode()d.
*
* @param string $query Query string
* @return string[] Array version of input
*/
function wfCgiToArray( $query ) {
if ( isset( $query[0] ) && $query[0] == '?' ) {
$query = substr( $query, 1 );
}
$bits = explode( '&', $query );
$ret = [];
foreach ( $bits as $bit ) {
if ( $bit === '' ) {
continue;
}
if ( strpos( $bit, '=' ) === false ) {
// Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
$key = $bit;
$value = '';
} else {
[ $key, $value ] = explode( '=', $bit );
}
$key = urldecode( $key );
$value = urldecode( $value );
if ( strpos( $key, '[' ) !== false ) {
$keys = array_reverse( explode( '[', $key ) );
$key = array_pop( $keys );
$temp = $value;
foreach ( $keys as $k ) {
$k = substr( $k, 0, -1 );
$temp = [ $k => $temp ];
}
if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
$ret[$key] = array_merge( $ret[$key], $temp );
} else {
$ret[$key] = $temp;
}
} else {
$ret[$key] = $value;
}
}
return $ret;
}
/**
* Append a query string to an existing URL, which may or may not already
* have query string parameters already. If so, they will be combined.
*
* @param string $url
* @param string|array $query String or associative array
* @return string
*/
function wfAppendQuery( $url, $query ) {
if ( is_array( $query ) ) {
$query = wfArrayToCgi( $query );
}
if ( $query != '' ) {
// Remove the fragment, if there is one
$fragment = false;
$hashPos = strpos( $url, '#' );
if ( $hashPos !== false ) {
$fragment = substr( $url, $hashPos );
$url = substr( $url, 0, $hashPos );
}
// Add parameter
if ( strpos( $url, '?' ) === false ) {
$url .= '?';
} else {
$url .= '&';
}
$url .= $query;
// Put the fragment back
if ( $fragment !== false ) {
$url .= $fragment;
}
}
return $url;
}
/**
* @deprecated since 1.43; get a UrlUtils from services, or construct your own
* @internal
* @return UrlUtils from services if initialized, otherwise make one from globals
*/
function wfGetUrlUtils(): UrlUtils {
global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest, $wgHttpsPort,
$wgUrlProtocols;
if ( MediaWikiServices::hasInstance() ) {
$services = MediaWikiServices::getInstance();
if ( $services->hasService( 'UrlUtils' ) ) {
return $services->getUrlUtils();
}
}
return new UrlUtils( [
// UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
// implementations implicitly converted it to an empty string (presumably by mistake).
// Preserve the old behavior for compatibility.
UrlUtils::SERVER => $wgServer ?? '',
UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
: WebRequest::detectProtocol(),
UrlUtils::HTTPS_PORT => $wgHttpsPort,
UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
] );
}
/**
* Expand a potentially local URL to a fully-qualified URL using $wgServer
* (or one of its alternatives).
*
* The meaning of the PROTO_* constants is as follows:
* PROTO_HTTP: Output a URL starting with http://
* PROTO_HTTPS: Output a URL starting with https://
* PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
* PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
* on which protocol was used for the current incoming request
* PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
* For protocol-relative URLs, use the protocol of $wgCanonicalServer
* PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
*
* If $url specifies a protocol, or $url is domain-relative and $wgServer
* specifies a protocol, PROTO_HTTP, PROTO_HTTPS, PROTO_RELATIVE and
* PROTO_CURRENT do not change that.
*
* Parent references (/../) in the path are resolved (as in UrlUtils::removeDotSegments()).
*
* @deprecated since 1.39, use UrlUtils::expand()
* @param string $url An URL; can be absolute (e.g. http://example.com/foo/bar),
* protocol-relative (//example.com/foo/bar) or domain-relative (/foo/bar).
* @param string|int|null $defaultProto One of the PROTO_* constants, as described above.
* @return string|false Fully-qualified URL, current-path-relative URL or false if
* no valid URL can be constructed
*/
function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
}
/**
* Get the wiki's "server", i.e. the protocol and host part of the URL, with a
* protocol specified using a PROTO_* constant as in wfExpandUrl()
*
* @deprecated since 1.39, use UrlUtils::getServer(); hard-deprecated since 1.43
* @since 1.32
* @param string|int|null $proto One of the PROTO_* constants.
* @return string The URL
*/
function wfGetServerUrl( $proto ) {
wfDeprecated( __FUNCTION__, '1.39' );
return wfGetUrlUtils()->getServer( $proto ) ?? '';
}
/**
* This function will reassemble a URL parsed with wfParseURL. This is useful
* if you need to edit part of a URL and put it back together.
*
* This is the basic structure used (brackets contain keys for $urlParts):
* [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
*
* @deprecated since 1.39, use UrlUtils::assemble(); hard-deprecated since 1.44
* @since 1.19
* @param array $urlParts URL parts, as output from wfParseUrl
* @return string URL assembled from its component parts
*/
function wfAssembleUrl( $urlParts ) {
wfDeprecated( __FUNCTION__, '1.39' );
return UrlUtils::assemble( (array)$urlParts );
}
/**
* Returns a partial regular expression of recognized URL protocols, e.g. "http:\/\/|https:\/\/"
*
* @deprecated since 1.39, use UrlUtils::validProtocols(); hard-deprecated since 1.43
* @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
* DO NOT USE this directly, use UrlUtils::validAbsoluteProtocols() instead
* @return string
*/
function wfUrlProtocols( $includeProtocolRelative = true ) {
wfDeprecated( __FUNCTION__, '1.39' );
return $includeProtocolRelative ? wfGetUrlUtils()->validProtocols() :
wfGetUrlUtils()->validAbsoluteProtocols();
}
/**
* Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
* you need a regex that matches all URL protocols but does not match protocol-
* relative URLs
* @deprecated since 1.39, use UrlUtils::validAbsoluteProtocols(); hard-deprecated since 1.44
* @return string
*/
function wfUrlProtocolsWithoutProtRel() {
wfDeprecated( __FUNCTION__, '1.39' );
return wfGetUrlUtils()->validAbsoluteProtocols();
}
/**
* parse_url() work-alike, but non-broken. Differences:
*
* 1) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
* protocol-relative URLs) correctly.
* 2) Adds a "delimiter" element to the array (see (2)).
* 3) Verifies that the protocol is on the $wgUrlProtocols allowed list.
* 4) Rejects some invalid URLs that parse_url doesn't, e.g. the empty string or URLs starting with
* a line feed character.
*
* @deprecated since 1.39, use UrlUtils::parse()
* @param string $url A URL to parse
* @return string[]|false Bits of the URL in an associative array, or false on failure.
* Possible fields:
* - scheme: URI scheme (protocol), e.g. 'http', 'mailto'. Lowercase, always present, but can
* be an empty string for protocol-relative URLs.
* - delimiter: either '://', ':' or '//'. Always present.
* - host: domain name / IP. Always present, but could be an empty string, e.g. for file: URLs.
* - port: port number. Will be missing when port is not explicitly specified.
* - user: user name, e.g. for HTTP Basic auth URLs such as http://user:[email protected]/
* Missing when there is no username.
* - pass: password, same as above.
* - path: path including the leading /. Will be missing when empty (e.g. 'http://example.com')
* - query: query string (as a string; see wfCgiToArray() for parsing it), can be missing.
* - fragment: the part after #, can be missing.
*/
function wfParseUrl( $url ) {
return wfGetUrlUtils()->parse( (string)$url ) ?? false;
}
/**
* Take a URL, make sure it's expanded to fully qualified, and replace any
* encoded non-ASCII Unicode characters with their UTF-8 original forms
* for more compact display and legibility for local audiences.
*
* @deprecated since 1.39, use UrlUtils::expandIRI(); hard-deprecated since 1.43
* @param string $url
* @return string
*/
function wfExpandIRI( $url ) {
wfDeprecated( __FUNCTION__, '1.39' );
return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
}
/**
* Check whether a given URL has a domain that occurs in a given set of domains
*
* @deprecated since 1.39, use UrlUtils::matchesDomainList(); hard-deprecated since 1.44
* @param string $url
* @param array $domains Array of domains (strings)
* @return bool True if the host part of $url ends in one of the strings in $domains
*/
function wfMatchesDomainList( $url, $domains ) {
wfDeprecated( __FUNCTION__, '1.39' );
return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
}
/**
* Sends a line to the debug log if enabled or, optionally, to a comment in output.
* In normal operation this is a NOP.
*
* Controlling globals:
* $wgDebugLogFile - points to the log file
* $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
* $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
*
* @since 1.25 support for additional context data
*
* @param string $text
* @param string|bool $dest Destination of the message:
* - 'all': both to the log and HTML (debug toolbar or HTML comments)
* - 'private': excluded from HTML output
* For backward compatibility, it can also take a boolean:
* - true: same as 'all'
* - false: same as 'private'
* @param array $context Additional logging context data
*/
function wfDebug( $text, $dest = 'all', array $context = [] ) {
global $wgDebugRawPage, $wgDebugLogPrefix;
if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
return;
}
$text = trim( $text );
if ( $wgDebugLogPrefix !== '' ) {
$context['prefix'] = $wgDebugLogPrefix;
}
$context['private'] = ( $dest === false || $dest === 'private' );
$logger = LoggerFactory::getInstance( 'wfDebug' );
$logger->debug( $text, $context );
}
/**
* Returns true if debug logging should be suppressed if $wgDebugRawPage = false
* @return bool
*/
function wfIsDebugRawPage() {
static $cache;
if ( $cache !== null ) {
return $cache;
}
// Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
// phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
|| MW_ENTRY_POINT === 'load'
) {
$cache = true;
} else {
$cache = false;
}
return $cache;
}
/**
* Send a line to a supplementary debug log file, if configured, or main debug
* log if not.
*
* To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to
* a string filename or an associative array mapping 'destination' to the
* desired filename. The associative array may also contain a 'sample' key
* with an integer value, specifying a sampling factor. Sampled log events
* will be emitted with a 1 in N random chance.
*
* @since 1.23 support for sampling log messages via $wgDebugLogGroups.
* @since 1.25 support for additional context data
* @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
*
* @param string $logGroup
* @param string $text
* @param string|bool $dest Destination of the message:
* - 'all': both to the log and HTML (debug toolbar or HTML comments)
* - 'private': only to the specific log if set in $wgDebugLogGroups and
* discarded otherwise
* For backward compatibility, it can also take a boolean:
* - true: same as 'all'
* - false: same as 'private'
* @param array $context Additional logging context data
*/
function wfDebugLog(
$logGroup, $text, $dest = 'all', array $context = []
) {
$text = trim( $text );
$logger = LoggerFactory::getInstance( $logGroup );
$context['private'] = ( $dest === false || $dest === 'private' );
$logger->info( $text, $context );
}
/**
* Log for database errors
*
* @since 1.25 support for additional context data
*
* @param string $text Database error message.
* @param array $context Additional logging context data
*/
function wfLogDBError( $text, array $context = [] ) {
$logger = LoggerFactory::getInstance( 'wfLogDBError' );
$logger->error( trim( $text ), $context );
}
/**
* Logs a warning that a deprecated feature was used.
*
* To write a custom deprecation message, use wfDeprecatedMsg() instead.
*
* @param string $function Feature that is deprecated.
* @param string|false $version Version of MediaWiki that the feature
* was deprecated in (Added in 1.19).
* @param string|bool $component Component to which the feature belongs.
* If false, it is assumed the function is in MediaWiki core (Added in 1.19).
* @param int $callerOffset How far up the call stack is the original
* caller. 2 = function that called the function that called
* wfDeprecated (Added in 1.20).
* @throws InvalidArgumentException If the MediaWiki version
* number specified by $version is neither a string nor false.
*/
function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
if ( !is_string( $version ) && $version !== false ) {
throw new InvalidArgumentException(
"MediaWiki version must either be a string or false. " .
"Example valid version: '1.33'"
);
}
MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
}
/**
* Log a deprecation warning with arbitrary message text. A caller
* description will be appended. If the message has already been sent for
* this caller, it won't be sent again.
*
* Although there are component and version parameters, they are not
* automatically appended to the message. The message text should include
* information about when the thing was deprecated. The component and version
* are just used to implement $wgDeprecationReleaseLimit.
*
* @since 1.35
* @param string $msg The message
* @param string|false $version Version of MediaWiki that the function
* was deprecated in.
* @param string|bool $component Component to which the function belongs.
* If false, it is assumed the function is in MediaWiki core.
* @param int|false $callerOffset How far up the call stack is the original
* caller. 2 = function that called the function that called us. If false,
* the caller description will not be appended.
*/
function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
MWDebug::deprecatedMsg( $msg, $version, $component,
$callerOffset === false ? false : $callerOffset + 1 );
}
/**
* Send a warning either to the debug log or in a PHP error depending on
* $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
*
* @param string $msg Message to send
* @param int $callerOffset Number of items to go back in the backtrace to
* find the correct caller (1 = function calling wfWarn, ...)
* @param int $level PHP error level; defaults to E_USER_NOTICE;
* only used when $wgDevelopmentWarnings is true
*/
function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
}
/**
* Send a warning as a PHP error and the debug log. This is intended for logging
* warnings in production. For logging development warnings, use WfWarn instead.
*
* @param string $msg Message to send
* @param int $callerOffset Number of items to go back in the backtrace to
* find the correct caller (1 = function calling wfLogWarning, ...)
* @param int $level PHP error level; defaults to E_USER_WARNING
*/
function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
}
/**
* This is the function for getting translated interface messages.
*
* @see Message class for documentation how to use them.
* @see https://www.mediawiki.org/wiki/Manual:Messages_API
*
* This function replaces all old wfMsg* functions.
*
* When the MessageSpecifier object is an instance of Message, a clone of the object is returned.
* This is unlike the `new Message( … )` constructor, which returns a new object constructed from
* scratch with the same key. This difference is mostly relevant when the passed object is an
* instance of a subclass like RawMessage or ApiMessage.
*
* @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier
* @param MessageParam|MessageSpecifier|string|int|float|list<MessageParam|MessageSpecifier|string|int|float> ...$params
* See Message::params()
* @return Message
*
* @since 1.17
*
* @see Message::__construct
*/
function wfMessage( $key, ...$params ) {
if ( is_array( $key ) ) {
// Fallback keys are not allowed in message specifiers
$message = wfMessageFallback( ...$key );
} else {
$message = Message::newFromSpecifier( $key );
}
// We call Message::params() to reduce code duplication
if ( $params ) {
$message->params( ...$params );
}
return $message;
}
/**
* This function accepts multiple message keys and returns a message instance
* for the first message which is non-empty. If all messages are empty then an
* instance of the last message key is returned.
*
* @param string ...$keys Message keys
* @return Message
*
* @since 1.18
*
* @see Message::newFallbackSequence
*/
function wfMessageFallback( ...$keys ) {
return Message::newFallbackSequence( ...$keys );
}
/**
* Replace message parameter keys on the given formatted output.
*
* @param string $message
* @param array $args
* @return string
* @internal
*/
function wfMsgReplaceArgs( $message, $args ) {
# Fix windows line-endings
# Some messages are split with explode("\n", $msg)
$message = str_replace( "\r", '', $message );
// Replace arguments
if ( is_array( $args ) && $args ) {
if ( is_array( $args[0] ) ) {
$args = array_values( $args[0] );
}
$replacementKeys = [];
foreach ( $args as $n => $param ) {
$replacementKeys['$' . ( $n + 1 )] = $param;
}
$message = strtr( $message, $replacementKeys );
}
return $message;
}
/**
* Get host name of the current machine, for use in error reporting.
*
* This helps to know which machine in a data center generated the
* current page.
*
* @return string
*/
function wfHostname() {
// Hostname overriding
global $wgOverrideHostname;
if ( $wgOverrideHostname !== false ) {
return $wgOverrideHostname;
}
return php_uname( 'n' ) ?: 'unknown';
}
/**
* Safety wrapper for debug_backtrace().
*
* Will return an empty array if debug_backtrace is disabled, otherwise
* the output from debug_backtrace() (trimmed).
*
* @param int $limit This parameter can be used to limit the number of stack frames returned
*
* @return array Array of backtrace information
*/
function wfDebugBacktrace( $limit = 0 ) {
static $disabled = null;
if ( $disabled === null ) {
$disabled = !function_exists( 'debug_backtrace' );
if ( $disabled ) {
wfDebug( "debug_backtrace() is disabled" );
}
}
if ( $disabled ) {
return [];
}
if ( $limit ) {
return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
} else {
return array_slice( debug_backtrace(), 1 );
}
}
/**
* Get a debug backtrace as a string
*
* @param bool|null $raw If true, the return value is plain text. If false, HTML.
* Defaults to true if MW_ENTRY_POINT is 'cli', otherwise false.
* @return string
* @since 1.25 Supports $raw parameter.
*/
function wfBacktrace( $raw = null ) {
$raw ??= MW_ENTRY_POINT === 'cli';
if ( $raw ) {
$frameFormat = "%s line %s calls %s()\n";
$traceFormat = "%s";
} else {
$frameFormat = "<li>%s line %s calls %s()</li>\n";
$traceFormat = "<ul>\n%s</ul>\n";
}
$frames = array_map( static function ( $frame ) use ( $frameFormat ) {
$file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
$line = $frame['line'] ?? '-';
$call = $frame['function'];
if ( !empty( $frame['class'] ) ) {
$call = $frame['class'] . $frame['type'] . $call;
}
return sprintf( $frameFormat, $file, $line, $call );
}, wfDebugBacktrace() );
return sprintf( $traceFormat, implode( '', $frames ) );
}
/**
* Get the name of the function which called this function
* wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
* wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()