forked from project-open-data/csv-to-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
class.csv-to-api.php
1342 lines (1096 loc) · 41 KB
/
class.csv-to-api.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
class CSV_To_API {
public $ttl = 3600;
public $source = null;
public $source_format = null;
public $format = null;
public $callback = null;
public $sort = null;
public $sort_dir = null;
public $data;
/**
* Use the query (often the requested URL) to define some settings.
*/
function parse_query( $query = null ) {
// If a query has been passed to the function, turn it into an array.
if ( is_string( $query ) ) {
$query = $this->parse_args( $query );
}
// If a query has not been passed to this function, just use the array of variables that
// were passed in the URL.
if (is_null($query)) {
$query = $_GET;
}
// Define a series of configuration variables based on what was requested in the query.
$this->source = isset( $query['source'] ) ? $this->esc_url( $query['source'] ) : null;
$this->source_format = isset( $query['source_format'] ) ? $query['source_format'] : $this->get_extension( $this->source );
$this->format = isset( $query['format'] ) ? $query['format'] : 'json';
$this->callback = isset( $query['callback'] ) ? $this->jsonp_callback_filter( $query['callback'] ) : false;
$this->sort = isset( $query['sort'] ) ? $query['sort'] : null;
$this->sort_dir = isset( $query['sort_dir'] ) ? $query['sort_dir'] : "desc";
return get_object_vars( $this );
}
/**
* Fetch the requested file and turn it into a PHP array.
*/
function parse() {
// Create an instance of the parser for the requested file format (e.g. CSV)
$parser = 'parse_' . $this->source_format;
if ( !method_exists( $this, $parser ) ) {
header( '400 Bad Request' );
die( 'Format not supported' );
}
// Attempt to retrieve the data from cache
$key = 'csv_to_api_' . md5( $this->source );
$this->data = $this->get_cache( $key );
if ( !$this->data ) {
// Retrieve the requested source material via HTTP GET.
if (ini_get('allow_url_fopen') == true) {
$this->data = file_get_contents( $this->source );
}
else {
$this->data = $this->curl_get( $this->source );
}
if ( !$this->data ) {
header( '502 Bad Gateway' );
die( 'Bad data source' );
}
// Turn the raw file data (e.g. CSV) into a PHP array.
$this->data = $this->$parser( $this->data );
// Save the data to WordPress' cache via its Transients API.
$this->set_cache( $key, $this->data, $this->ttl );
}
$this->data = $this->query( $this->data );
return $this->data;
}
/**
* Return to the client the requested data in the requested format (e.g. JSON).
*/
function output() {
$function = 'object_to_' . $this->format;
if ( !method_exists( $this, $function) ) {
return false;
}
// Send to the browser a header specifying the proper MIME type for the requested format.
$this->header( $this->format );
$output = $this->$function( $this->data );
// Prepare a JSONP callback.
$callback = $this->jsonp_callback_filter( $this->callback );
// Only send back JSONP if that's appropriate for the request.
if ( $this->format == 'json' && $this->callback ) {
return "{$this->callback}($output);";
}
// If not JSONP, send back the data.
return $output;
}
/**
* Create a key name, based on a CSV column header name, that is safe to embed in JavaScript
* or XML.
*/
function sanitize_key( $key ) {
$key = $this->sanitize_title( $key );
$key = str_replace( '-', '_', $key );
return $key;
}
/**
* Determine the file type of the requested file based on its extension.
*/
function get_extension( $source = null ) {
if ( $source == null ) {
$source = $this->source;
}
$url_parts = parse_url( $source );
$url_parts = pathinfo( $url_parts['path'] );
return isset( $url_parts['extension'] ) ? $url_parts['extension'] : '';
}
/**
* Convert reserved XML characters into their entitity equivalents.
*/
function xml_entities( $string ) {
return str_replace( array("&", "<", ">", "\"", "'"), array("&", "<", ">", """, "'"), $string );
}
/**
* Normalize all line endings to Unix line endings
* @param string the mixed-ending string to normalized
* @return string the normalized string
*/
function normalize_line_endings( $string ) {
$string = str_replace( "\r\n", "\n", $string );
$string = str_replace( "\r", "\n", $string );
return $string;
}
/**
* Turn CSV into a PHP array.
*/
function parse_csv( $csv ) {
$csv = $this->normalize_line_endings( $csv );
$lines = explode( "\n", $csv );
$lines = $this->parse_lines( $lines );
$headers = array_shift( $lines );
$data = array();
foreach ( $lines as $line ) {
$row = array();
foreach ( $line as $key => $field ) {
$row[ $this->sanitize_key( $headers[ $key ] ) ] = $field;
}
$row = array_filter( $row );
$row = $this->array_to_object( $row );
$data[] = $row;
}
return $data;
}
/**
* Parse CSV into array of arrays
* Wrapper function to allow pre 5.3 compatability
* @param array the CSV data as an array of lines
* @return array array of preset objects
*/
function parse_lines( $lines ) {
//php 5.3+
if ( function_exists( 'str_getcsv' ) ) {
foreach ( $lines as &$line )
$line = str_getcsv( $line );
//php 5.2
// fgetcsv needs a file handle,
// so write the string to a temp file before parsing
} else {
$fh = tmpfile();
fwrite( $fh, implode( "\n", $lines ) );
fseek( $fh, 0 );
$lines = array();
while( $line = fgetcsv( $fh ) )
$lines[] = $line;
fclose( $fh );
}
return $lines;
}
/**
* Turn a PHP array into a PHP object.
*/
function array_to_object( $array ) {
$output = new stdClass();
foreach ( $array as $key => $value ) {
$output->$key = $value;
}
return $output;
}
/**
* Turn a PHP object into JSON text.
*/
function object_to_json( $data ) {
return json_encode( $data );
}
/**
* Turn a PHP object into XML text.
*/
function object_to_xml( $array, $xml = null, $tidy = true ) {
if ( $xml == null ) {
$xml = new SimpleXMLElement( '<records></records>' );
}
// Array of keys that will be treated as attributes, not children.
$attributes = array( 'id' );
// Recursively loop through each item.
foreach ( $array as $key => $value ) {
// If this is a numbered array, grab the parent node to determine the node name.
if ( is_numeric( $key ) ) {
$key = 'record';
}
// If this is an attribute, treat as an attribute.
if ( in_array( $key, $attributes ) ) {
$xml->addAttribute( $key, $value );
}
// If this value is an object or array, add a child node and treat recursively.
elseif ( is_object( $value ) || is_array( $value ) ) {
$child = $xml->addChild( $key );
$child = $this->object_to_xml( $value, $child, false );
}
// Simple key/value child pair.
else {
$value = $this->xml_entities( $value );
$xml->addChild( $key, $value );
}
}
if ( $tidy ) {
$xml = $this->tidy_xml( $xml );
}
return $xml;
}
/**
* Turn a PHP object into an HTML table.
*/
function object_to_html( $data ) {
$output = "<table>\n<thead>\n";
$output .= "<tr>";
foreach ( array_keys( get_object_vars( reset( $data ) ) ) as $header ) {
$output .= "\t<th>$header</th>";
}
$output .= "</tr>\n</thead>\n<tbody>";
foreach ( $data as $row ) {
$output .= "<tr>\n";
foreach ( $row as $key => $value ) {
$output .= "\t<td>$value</td>\n";
}
$output .= "</tr>\n";
}
$output .= "</tbody>\n</table>";
return $output;
}
/**
* Pass XML through PHP's DOMDocument class, which will tidy it up.
*/
function tidy_xml( $xml ) {
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML( $xml->asXML() );
return $dom->saveXML();
}
/**
* Send to the browser the MIME type that defines this content (JSON, XML, or HTML).
*/
function header( $extension = null ) {
if ( $extension == null ) {
$extension = $this->extension;
}
$mimes = $this->get_mimes();
if ( !isset( $mimes[ $extension ] ) || headers_sent() ) {
return;
}
header( 'Content-Type: ' . $mimes[ $extension ] );
}
/**
* Return MIME types
* This way we do not allow additional MIME types elsewhere.
*/
function get_mimes() {
return array(
'json' => 'application/json',
'xml' => 'text/xml',
'htm|html' => 'text/html',
);
}
/**
* Prevent malicious callbacks from being used in JSONP requests.
*/
function jsonp_callback_filter( $callback ) {
// As per <http://stackoverflow.com/a/10900911/1082542>.
if ( preg_match( '/[^0-9a-zA-Z\$_]|^(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|volatile|void|while|with|NaN|Infinity|undefined)$/', $callback) ) {
return false;
}
return $callback;
}
/**
* Parse the query parameters passed in the URL and use them to populate a complete list of
* settings.
*/
function query( $data, $query = null ) {
if ( $query == null ) {
$query = $_GET;
}
// Fill in any defaults that are missing.
$query = $this->default_vars( $this->get_query_vars( $data ), $query );
// Eliminate any value in $query that equal false.
$query = array_filter( $query );
$data = $this->list_filter( $data, $query );
if ( $this->sort == null ) {
return $data;
}
// Optionally sort the object.
if ( $this->sort != null )
usort( $data, array( &$this, 'object_sort' ) );
return $data;
}
/**
* Uses a PHP array to generate a list of all column names.
*/
function get_query_vars( $data ) {
$vars = array();
foreach ( $data as $row ) {
foreach ( $row as $key=>$value ) {
if ( !array_key_exists( $key, $vars ) ) {
$vars[ $key ] = null;
}
}
}
return $vars;
}
/**
* Sorts an object, in either ascending or descending order.
* @param object $a the first object
* @param object $b the second object
* @return int 0, 1, or -1 the ranking of $a to $b
*
* The comparison function must return an integer less than, equal to, or greater than zero
* if the first argument is considered to be respectively less than, equal to, or greater than the second.
* see http://php.net/manual/en/function.usort.php for more information
*/
function object_sort( $a, $b ) {
$sorter = $this->sort;
//no sort by field supplied or invalid sort field, tell usort not to do anything
if ( $sorter == null || !isset( $a->$sorter ) || !isset( $b->$sorter ) ) {
return 0;
}
// A = B, tell usort not to do anything
if ( $a->$sorter == $b->$sorter )
return 0;
//flip the return values depending on the sort direction
if ( $this->sort_dir == "desc" ) {
$up = -1;
$down = 1;
} else {
$up = 1;
$down = -1;
}
if ( $a->$sorter < $b->$sorter )
return $down;
if ( $a->$sorter > $b->$sorter )
return $up;
}
/**
* Retrieve data from Alternative PHP Cache (APC).
*/
function get_cache( $key ) {
if ( !extension_loaded('apc') || (ini_get('apc.enabled') != 1) ) {
if ( isset( $this->cache[ $key ] ) ) {
return $this->cache[ $key ];
}
}
else {
return apc_fetch( $key );
}
return false;
}
/**
* Store data in Alternative PHP Cache (APC).
*/
function set_cache( $key, $value, $ttl = null ) {
if ( $ttl == null )
$ttl = $this->ttl;
if ( extension_loaded('apc') && (ini_get('apc.enabled') == 1) ) {
return apc_store( $key, $value, $ttl );
}
$this->cache[$key] = $value;
}
function curl_get( $url ) {
if ( !isset($url) ) {
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1200);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// All functions below this point taken from WordPress
/**
* Merge user defined arguments into defaults array.
*
* This function is used throughout WordPress to allow for both string or array
* to be merged into another array.
*
* @since 2.2.0
*
* @param string|array $args Value to merge with $defaults
* @param array $defaults Array that serves as the defaults.
* @return array Merged user defined values with defaults.
*
* Source: WordPress, used under GPLv3 or Later
*/
function parse_args( $args, $defaults = '' ) {
if ( is_object( $args ) )
$r = get_object_vars( $args );
elseif ( is_array( $args ) )
$r =& $args;
else
$this->parse_str( $args, $r );
if ( is_array( $defaults ) )
return array_merge( $defaults, $r );
return $r;
}
/**
* Parses a string into variables to be stored in an array.
*
* Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
* {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
*
* @since 2.2.1
* @uses apply_filters() for the 'wp_parse_str' filter.
*
* @param string $string The string to be parsed.
* @param array $array Variables will be stored in this array.
*
* Source: WordPress, used under GPLv3 or Later
*/
function parse_str( $string, &$array ) {
parse_str( $string, $array );
if ( get_magic_quotes_gpc() )
$array = stripslashes_deep( $array );
}
/**
* Checks and cleans a URL.
*
* A number of characters are removed from the URL. If the URL is for displaying
* (the default behaviour) ampersands are also replaced. The 'clean_url' filter
* is applied to the returned cleaned URL.
*
* @since 2.8.0
* @uses wp_kses_bad_protocol() To only permit protocols in the URL set
* via $protocols or the common ones set in the function.
*
* @param string $url The URL to be cleaned.
* @param array $protocols Optional. An array of acceptable protocols.
* Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
* @param string $_context Private. Use esc_url_raw() for database usage.
* @return string The cleaned $url after the 'clean_url' filter is applied.
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function esc_url( $url, $protocols = null, $_context = 'display' ) {
$original_url = $url;
if ( '' == $url )
return $url;
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
$strip = array('%0d', '%0a', '%0D', '%0A');
$url = $this->_deep_replace($strip, $url);
$url = str_replace(';//', '://', $url);
/* If the URL doesn't appear to contain a scheme, we
* presume it needs http:// appended (unless a relative
* link starting with /, # or ? or a php file).
*/
if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
$url = 'http://' . $url;
// Replace ampersands and single quotes only when displaying.
if ( 'display' == $_context ) {
$url = $this->kses_normalize_entities( $url );
$url = str_replace( '&', '&', $url );
$url = str_replace( "'", ''', $url );
}
if ( ! is_array( $protocols ) )
$protocols = $this->allowed_protocols();
if ( $this->kses_bad_protocol( $url, $protocols ) != $url )
return '';
return $url;
}
/**
* Perform a deep string replace operation to ensure the values in $search are no longer present
*
* Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
* e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
* str_replace would return
*
* @since 2.8.1
* @access private
*
* @param string|array $search
* @param string $subject
* @return string The processed string
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function _deep_replace( $search, $subject ) {
$found = true;
$subject = (string) $subject;
while ( $found ) {
$found = false;
foreach ( (array) $search as $val ) {
while ( strpos( $subject, $val ) !== false ) {
$found = true;
$subject = str_replace( $val, '', $subject );
}
}
}
return $subject;
}
/**
* Converts and fixes HTML entities.
*
* This function normalizes HTML entities. It will convert "AT&T" to the correct
* "AT&T", ":" to ":", "&#XYZZY;" to "&#XYZZY;" and so on.
*
* @since 1.0.0
*
* @param string $string Content to normalize entities
* @return string Content with normalized entities
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function kses_normalize_entities($string) {
# Disarm all entities by converting & to &
$string = str_replace('&', '&', $string);
# Change back the allowed entities in our entity whitelist
$string = preg_replace_callback('/&([A-Za-z]{2,8});/', array( $this, 'kses_named_entities' ), $string);
$string = preg_replace_callback('/&#(0*[0-9]{1,7});/', array( $this, 'kses_normalize_entities2' ), $string);
$string = preg_replace_callback('/&#[Xx](0*[0-9A-Fa-f]{1,6});/', array( $this, 'kses_normalize_entities3' ), $string);
return $string;
}
/**
* Retrieve a list of protocols to allow in HTML attributes.
*
* @since 3.3.0
* @see wp_kses()
* @see esc_url()
*
* @return array Array of allowed protocols
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function allowed_protocols() {
static $protocols;
if ( empty( $protocols ) ) {
$protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp' );
}
return $protocols;
}
/**
* Sanitize string from bad protocols.
*
* This function removes all non-allowed protocols from the beginning of
* $string. It ignores whitespace and the case of the letters, and it does
* understand HTML entities. It does its work in a while loop, so it won't be
* fooled by a string like "javascript:javascript:alert(57)".
*
* @since 1.0.0
*
* @param string $string Content to filter bad protocols from
* @param array $allowed_protocols Allowed protocols to keep
* @return string Filtered content
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function kses_bad_protocol($string, $allowed_protocols) {
$string = $this->kses_no_null($string);
$iterations = 0;
do {
$original_string = $string;
$string = $this->kses_bad_protocol_once($string, $allowed_protocols);
} while ( $original_string != $string && ++$iterations < 6 );
if ( $original_string != $string )
return '';
return $string;
}
/**
* Removes any null characters in $string.
*
* @since 1.0.0
*
* @param string $string
* @return string
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function kses_no_null($string) {
$string = preg_replace('/\0+/', '', $string);
$string = preg_replace('/(\\\\0)+/', '', $string);
return $string;
}
/**
* Sanitizes content from bad protocols and other characters.
*
* This function searches for URL protocols at the beginning of $string, while
* handling whitespace and HTML entities.
*
* @since 1.0.0
*
* @param string $string Content to check for bad protocols
* @param string $allowed_protocols Allowed protocols
* @return string Sanitized content
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function kses_bad_protocol_once($string, $allowed_protocols, $count = 1 ) {
$string2 = preg_split( '/:|�*58;|�*3a;/i', $string, 2 );
if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) ) {
$string = trim( $string2[1] );
$protocol = $this->kses_bad_protocol_once2( $string2[0], $allowed_protocols );
if ( 'feed:' == $protocol ) {
if ( $count > 2 )
return '';
$string = $this->kses_bad_protocol_once( $string, $allowed_protocols, ++$count );
if ( empty( $string ) )
return $string;
}
$string = $protocol . $string;
}
return $string;
}
/**
* Callback for wp_kses_bad_protocol_once() regular expression.
*
* This function processes URL protocols, checks to see if they're in the
* whitelist or not, and returns different data depending on the answer.
*
* @access private
* @since 1.0.0
*
* @param string $string URI scheme to check against the whitelist
* @param string $allowed_protocols Allowed protocols
* @return string Sanitized content
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function kses_bad_protocol_once2( $string, $allowed_protocols ) {
$string2 = $this->kses_decode_entities($string);
$string2 = preg_replace('/\s/', '', $string2);
$string2 = $this->kses_no_null($string2);
$string2 = strtolower($string2);
$allowed = false;
foreach ( (array) $allowed_protocols as $one_protocol )
if ( strtolower($one_protocol) == $string2 ) {
$allowed = true;
break;
}
if ($allowed)
return "$string2:";
else
return '';
}
/**
* Convert all entities to their character counterparts.
*
* This function decodes numeric HTML entities (A and A). It doesn't do
* anything with other entities like ä, but we don't need them in the URL
* protocol whitelisting system anyway.
*
* @since 1.0.0
*
* @param string $string Content to change entities
* @return string Content after decoded entities
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function kses_decode_entities($string) {
$string = preg_replace_callback('/&#([0-9]+);/', array( $this, '_kses_decode_entities_chr' ), $string);
$string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', array( $this, '_kses_decode_entities_chr_hexdec' ), $string);
return $string;
}
/**
* Regex callback for wp_kses_decode_entities()
*
* @param array $match preg match
* @return string
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function _kses_decode_entities_chr( $match ) {
return chr( $match[1] );
}
/**
* Regex callback for wp_kses_decode_entities()
*
* @param array $match preg match
* @return string
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function _kses_decode_entities_chr_hexdec( $match ) {
return chr( hexdec( $match[1] ) );
}
/**
* Sanitizes title or use fallback title.
*
* Specifically, HTML and PHP tags are stripped. Further actions can be added
* via the plugin API. If $title is empty and $fallback_title is set, the latter
* will be used.
*
* @since 1.0.0
*
* @param string $title The string to be sanitized.
* @param string $fallback_title Optional. A title to use if $title is empty.
* @param string $context Optional. The operation for which the string is sanitized
* @return string The sanitized string.
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function sanitize_title($title, $fallback_title = '', $context = 'save') {
$raw_title = $title;
if ( 'save' == $context )
$title = $this->remove_accents($title);
if ( '' === $title || false === $title )
$title = $fallback_title;
return $title;
}
/**
* Converts all accent characters to ASCII characters.
*
* If there are no accent characters, then the string given is just returned.
*
* @since 1.2.1
*
* @param string $string Text that might have accent characters
* @return string Filtered string with replaced "nice" characters.
*
* Source: WordPress, used under GPLv3 or Later
*
*/
function remove_accents($string) {
if ( !preg_match('/[\x80-\xff]/', $string) )
return $string;
if (seems_utf8($string)) {
$chars = array(
// Decompositions for Latin-1 Supplement
chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
chr(195).chr(134) => 'AE', chr(195).chr(135) => 'C',
chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
chr(195).chr(158) => 'TH', chr(195).chr(159) => 's',
chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
chr(195).chr(166) => 'ae', chr(195).chr(167) => 'c',
chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
// Decompositions for Latin Extended-A
chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',