-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.php
executable file
·1607 lines (1480 loc) · 58.5 KB
/
functions.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
/**
* Chronolabs REST Short Link URIs API
*
* You may not change or alter any portion of this comment or credits
* of supporting developers from this source code or any supporting source code
* which is considered copyrighted (c) material of the original comment or credit authors.
* 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.
*
* @copyright Chronolabs Cooperative http://au.syd.labs.coop
* @license Academic + GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
* @package api
* @since 2.2.1
* @author Simon Roberts <wishcraft@users.sourceforge.net>
* @version 2.2.1
* @subpackage shortening-url
* @description Short Link URIs API
* @link http://internetfounder.wordpress.com
* @link http://sourceoforge.net/projects/chronolabsapis/files/jump.labs.coop
* @link https://github.com/Chronolabs-Cooperative/Jump-API-PHP
*/
require_once __DIR__ . DIRECTORY_SEPARATOR . 'xcp' . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'xcp.class.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'simple_html_dom.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'myip.php';
if (!function_exists('encode_sef'))
{
/**
* Xoops safe encoded url elements
*
* @param unknown $datab
* @param string $char
* @return string
*/
function encode_sef($datab, $char ='-')
{
$rejected = array("·", " ",".",",","<",">","/","?","'","\"",";",":","{","}","[","]","|","\\","=",
"+","_","(",")","*","&","^","%","$","#","@","!","`","~",NULL);
$return_data = (str_replace($rejected,$char,$datab));
while(substr($return_data, 0, 1) == $char)
$return_data = substr($return_data, 1, strlen($return_data)-1);
while(substr($return_data, strlen($return_data)-1, 1) == $char)
$return_data = substr($return_data, 0, strlen($return_data)-1);
while(strpos($return_data, $char . $char))
$return_data = str_replace($char . $char, $char, $return_data);
return(strtolower($return_data));
}
}
if (!function_exists("checkDisplayHelp")) {
/**
* checkDisplayHelp ~ checks if help will need to be displayed
*
* @param string $action
* @return boolean
*/
function checkDisplayHelp($action = '')
{
global $errors;
apiLoadLanguage('errors', _API_LANGUAGE_DEFAULT);
$errors = array();
if (!empty($action))
checkFunctionRequirements(basename(__DIR__), $action);
return (!empty($errors)?false:true);
}
}
if (!function_exists("checkFunctionRequirements")) {
/**
* checkFunctionRequirements ~ checks the requirements of an API Function for a form
*
* @param string $base
* @param string $func
* @return boolean
*/
function checkFunctionRequirements($base = 'salty', $func = '')
{
global $errors;
if (file_exists($file = API_PATH_IO_FUNCTIONS . DIRECTORY_SEPARATOR . "$base-$func.diz"))
{
foreach(file($file) as $fields)
{
$parts = explode("||", $fields);
if (isset($parts[2]) && $parts[2] == 'required')
{
switch ($parts[1])
{
default:
if (!isset($_REQUEST[$parts[0]]) && empty($_REQUEST[$parts[0]]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_SET, '$_' . sprintf('REQUEST["%s"]', $parts[0]));
elseif (isset($parts[3]) && checkValidField($_REQUEST[$parts[0]], str_replace(array("\n","\r","\t", " "), "", $parts[3]), str_replace(array("\n","\r","\t", " "), "", (isset($parts[4])?$parts[4]:"")), str_replace(array("\n","\r","\t", " "), "", (isset($parts[5])?$parts[5]:"")), $parts[0]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_VALID, '$_' . sprintf('REQUEST["%s"]', $parts[0]), $errors[$parts[0]]);
break;
case "get":
if (!isset($_GET[$parts[0]]) && empty($_GET[$parts[0]]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_SET, '$_' . sprintf('GET["%s"]', $parts[0]));
elseif (isset($parts[3]) && checkValidField($_GET[$parts[0]], str_replace(array("\n","\r","\t", " "), "", $parts[3]), str_replace(array("\n","\r","\t", " "), "", (isset($parts[4])?$parts[4]:"")), str_replace(array("\n","\r","\t", " "), "", (isset($parts[5])?$parts[5]:"")), $parts[0]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_VALID, '$_' . sprintf('GET["%s"]', $parts[0]), $errors[$parts[0]]);
break;
case "post":
if (!isset($_POST[$parts[0]]) && empty($_POST[$parts[0]]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_SET, '$_' . sprintf('POST["%s"]', $parts[0]));
elseif (isset($parts[3]) && checkValidField($_POST[$parts[0]], str_replace(array("\n","\r","\t", " "), "", $parts[3]), str_replace(array("\n","\r","\t", " "), "", (isset($parts[4])?$parts[4]:"")), str_replace(array("\n","\r","\t", " "), "", (isset($parts[5])?$parts[5]:"")), $parts[0]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_VALID, '$_' . sprintf('POST["%s"]', $parts[0]), $errors[$parts[0]]);
break;
}
} else {
switch ($parts[1])
{
default:
if (isset($_REQUEST[$parts[0]]) && isset($parts[3]) && checkValidField($_REQUEST[$parts[0]], str_replace(array("\n","\r","\t", " "), "", $parts[3]), str_replace(array("\n","\r","\t", " "), "", (isset($parts[4])?$parts[4]:"")), str_replace(array("\n","\r","\t", " "), "", (isset($parts[5])?$parts[5]:"")), $parts[0]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_VALID, '$_' . sprintf('REQUEST["%s"]', $parts[0]), $errors[$parts[0]]);
break;
case "get":
if (isset($_GET[$parts[0]]) && isset($parts[3]) && checkValidField($_GET[$parts[0]], str_replace(array("\n","\r","\t", " "), "", $parts[3]), str_replace(array("\n","\r","\t", " "), "", (isset($parts[4])?$parts[4]:"")), str_replace(array("\n","\r","\t", " "), "", (isset($parts[5])?$parts[5]:"")), $parts[0]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_VALID, '$_' . sprintf('GET["%s"]', $parts[0]), $errors[$parts[0]]);
break;
case "post":
if (isset($_POST[$parts[0]]) && isset($parts[3]) && checkValidField($_POST[$parts[0]], str_replace(array("\n","\r","\t", " "), "", $parts[3]), str_replace(array("\n","\r","\t", " "), "", (isset($parts[4])?$parts[4]:"")), str_replace(array("\n","\r","\t", " "), "", (isset($parts[5])?$parts[5]:"")), $parts[0]))
$errors[$parts[0]] = sprintf(_API_ERROR_FIELD_NOT_VALID, '$_' . sprintf('POST["%s"]', $parts[0]), $errors[$parts[0]]);
break;
}
}
if (empty($errors[$parts[0]]) || is_array($errors[$parts[0]]))
unset($errors[$parts[0]]);
}
}
return (!empty($errors)?true:false);
}
}
if (!function_exists("checkValidField")) {
/**
* checkValidField ~ Validates a value of a field for API Form from scipted .diz files
*
* @param string $value
* @param string $type
* @param string $typal
* @param string $sizes
* @param string $field
* @return boolean
*/
function checkValidField($value = '', $type = '', $typal = '', $sizes = '', $field = '')
{
global $errors;
$errors[$field] = '';
$pass = true;
if (strpos($typal, "-"))
{
$parts = explode("-", $typal);
$minimal = $parts[0];
$maximum = $parts[1];
}
if (strpos($sizes, "-"))
{
$parts = explode("-", $sizes);
$minimal = $parts[0];
$maximum = $parts[1];
}
switch ($type)
{
case "enumerator":
if (!in_array($value, explode("|", $typal)))
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_ENUMATOR, $value, "'" . implode("', '", explode("|", $typal)) . "'");
break;
case "words":
if (count($words = explode(" ", $value)))
{
if (strpos($typal, "-") != 0)
if (count($words)>=$minimal || count($words)<=$maximum )
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_WORDS_RANGE, $maximum, count($words), $minimal, count($words));
elseif(count($words)<=$typal)
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_WORDS_LESS, $typal, count($words));
}
break;
case "string":
if (!is_string($value))
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_STRING, $value);
elseif (!empty($typal))
{
if (strpos($typal, "-") != 0)
if (strlen($value)>=$minimal || strlen($value)<=$maximum )
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_LENGTH_RANGE, $maximum, strlen($value), $minimal, strlen($value));
elseif(strlen($value)<=$typal)
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_LENGTH_LESS, $typal, strlen($value));
}
break;
case "number":
if (!is_numeric($value))
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_NUMERIC, $value);
elseif (!empty($typal))
{
if (strpos($typal, "-") != 0)
if ((float)($value)>=(float)$minimal || (float)($value)<=(float)$maximum )
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_NUMERIC_RANGE, (float)$maximum, (float)($value), (float)$minimal, (float)($value));
elseif((float)($value)>=(float)$typal)
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_NUMERIC_GREATER, (float)$typal, (float)($value));
}
break;
case "email":
if (!checkEmail($value))
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_EMAIL, $value);
break;
case "uri":
if (substr($value,0,4)!="http")
$errors[$field] = sprintf(_API_ERROR_FIELD_NOT_, $value);
break;
}
if (empty($errors[$field]))
unset($errors[$field]);
return !isset($errors[$field])?false:true;
}
}
if (!function_exists("apiLoadLanguage")) {
/**
* apiLoadLanguage ~ loads a language files
*
* @param unknown_type $definition
* @param unknown_type $language
* @return boolean
*/
function apiLoadLanguage($definition = 'help', $language = 'english')
{
if (!empty($language)) $language = _API_LANGUAGE_DEFAULT;
if (file_exists($file = __DIR__ . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . "$definition.php"))
{
return include_once($file);
}
return false;
}
}
if (!function_exists("getURIData")) {
/* function yonkURIData()
*
* Get a supporting domain system for the API
* @author Simon Roberts (Chronolabs) simon@labs.coop
*
* @return float()
*/
function getURIData($uri = '', $timeout = 25, $connectout = 25, $post = array(), $headers = array())
{
if (!function_exists("curl_init"))
{
die("Install PHP Curl Extension ie: $ sudo apt-get install php-curl -y");
}
$GLOBALS['php-curl'][md5($uri)] = array();
if (!$btt = curl_init($uri)) {
return false;
}
if (count($post)==0 || empty($post))
curl_setopt($btt, CURLOPT_POST, false);
else {
$uploadfile = false;
foreach($post as $field => $value)
if (substr($value , 0, 1) == '@' && !file_exists(substr($value , 1, strlen($value) - 1)))
unset($post[$field]);
else
$uploadfile = true;
curl_setopt($btt, CURLOPT_POST, true);
curl_setopt($btt, CURLOPT_POSTFIELDS, http_build_query($post));
if (!empty($headers))
foreach($headers as $key => $value)
if ($uploadfile==true && substr($value, 0, strlen('Content-Type:')) == 'Content-Type:')
unset($headers[$key]);
if ($uploadfile==true)
$headers[] = 'Content-Type: multipart/form-data';
}
if (count($headers)==0 || empty($headers))
curl_setopt($btt, CURLOPT_HEADER, false);
else {
curl_setopt($btt, CURLOPT_HEADER, true);
curl_setopt($btt, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($btt, CURLOPT_CONNECTTIMEOUT, $connectout);
curl_setopt($btt, CURLOPT_TIMEOUT, $timeout);
curl_setopt($btt, CURLOPT_RETURNTRANSFER, true);
curl_setopt($btt, CURLOPT_VERBOSE, false);
curl_setopt($btt, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($btt, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($btt);
$GLOBALS['php-curl'][md5($uri)]['http']['posts'] = $post;
$GLOBALS['php-curl'][md5($uri)]['http']['headers'] = $headers;
$GLOBALS['php-curl'][md5($uri)]['http']['code'] = curl_getinfo($btt, CURLINFO_HTTP_CODE);
$GLOBALS['php-curl'][md5($uri)]['header']['size'] = curl_getinfo($btt, CURLINFO_HEADER_SIZE);
$GLOBALS['php-curl'][md5($uri)]['header']['value'] = curl_getinfo($btt, CURLINFO_HEADER_OUT);
$GLOBALS['php-curl'][md5($uri)]['size']['download'] = curl_getinfo($btt, CURLINFO_SIZE_DOWNLOAD);
$GLOBALS['php-curl'][md5($uri)]['size']['upload'] = curl_getinfo($btt, CURLINFO_SIZE_UPLOAD);
$GLOBALS['php-curl'][md5($uri)]['content']['length']['download'] = curl_getinfo($btt, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
$GLOBALS['php-curl'][md5($uri)]['content']['length']['upload'] = curl_getinfo($btt, CURLINFO_CONTENT_LENGTH_UPLOAD);
$GLOBALS['php-curl'][md5($uri)]['content']['type'] = curl_getinfo($btt, CURLINFO_CONTENT_TYPE);
curl_close($btt);
return $data;
}
}
if (!function_exists("readRawFile")) {
/**
* Return the contents of this File as a string.
*
* @param string $file
* @param string $bytes where to start
* @param string $mode
* @param boolean $force If true then the file will be re-opened even if its already opened, otherwise it won't
* @return mixed string on success, false on failure
* @access public
*/
function readRawFile($file = '', $bytes = false, $mode = 'rb', $force = false)
{
$success = false;
if ($bytes === false) {
$success = file_get_contents($file);
} elseif ($fhandle = fopen($file, $mode)) {
if (is_int($bytes)) {
$success = fread($fhandle, $bytes);
} else {
$data = '';
while (! feof($fhandle)) {
$data .= fgets($fhandle, 4096);
}
$success = trim($data);
}
fclose($fhandle);
}
return $success;
}
}
if (!function_exists("writeRawFile")) {
/**
*
* @param string $file
* @param string $data
*/
function writeRawFile($file = '', $data = '')
{
if (!is_dir(dirname($file)))
mkdir(dirname($file), 0777, true);
if (is_file($file))
unlink($file);
$ff = fopen($file, 'w');
fwrite($ff, $data, strlen($data));
return fclose($ff);
}
}
if (!function_exists("mkdirSecure")) {
/**
*
* @param unknown_type $path
* @param unknown_type $perm
* @param unknown_type $secure
*/
function mkdirSecure($path = '', $perm = 0777, $secure = true)
{
if (!is_dir($path))
{
mkdir($path, $perm, true);
if ($secure == true)
{
writeRawFile($path . DIRECTORY_SEPARATOR . '.htaccess', "<Files ~ \"^.*$\">\n\tdeny from all\n</Files>");
}
return true;
}
return false;
}
}
if (!function_exists("writeCache")) {
/**
* Write data for key into cache
*
* @param string $key Identifier for the data
* @param mixed $data Data to be cached
* @param mixed $duration How long to cache the data, in seconds
* @return boolean True if the data was succesfully cached, false on failure
* @access public
*/
function writeCache($key, $data = array(), $duration = 3600)
{
if (!isset($data)) {
return false;
}
if (!empty($key))
$key .= substr(md5($_SERVER["HTTP_HOST"]), 3, 7) . '--' . $key;
else
return false;
if ($duration == null) {
$duration = 3600;
}
$windows = false;
$lineBreak = "\n";
if (substr(PHP_OS, 0, 3) == "WIN") {
$lineBreak = "\r\n";
$windows = true;
}
$expires = time() + $duration;
$contents = $expires . $lineBreak . "return " . var_export($data, true) . ";" . $lineBreak;
return writeRawFile(API_PATH_IO_CACHE . DIRECTORY_SEPARATOR . $key . '.php');
}
}
if (!function_exists("readCache")) {
/**
* Read a key from the cache
*
* @param string $key Identifier for the data
* @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
* @access public
*/
function readCache($key)
{
if (!empty($key))
$key .= substr(md5($_SERVER["HTTP_HOST"]), 3, 7) . '--' . $key;
else
return false;
$cachetime = readRawFile(API_PATH_IO_CACHE . DIRECTORY_SEPARATOR . $key . '.php', 11);
if ($cachetime !== false && intval($cachetime) < time()) {
return false;
}
$data = readRawFile(API_PATH_IO_CACHE . DIRECTORY_SEPARATOR . $key . '.php', true);
if (!empty($data))
$data = eval($data);
return $data;
}
}
if (!function_exists("checkEmail")) {
/**
* checkEmail()
*
* @param mixed $email
* @return bool|mixed
*/
function checkEmail($email)
{
if (!$email || !preg_match('/^[^@]{1,64}@[^@]{1,255}$/', $email)) {
return false;
}
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/\=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/\=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return $email;
}
}
if (!function_exists("getBaseDomain")) {
/**
* getBaseDomain
*
* @param string $url
* @return string|unknown
*/
function getBaseDomain($url)
{
static $strata, $fallout, $stratas;
if (empty($strata))
{
if (!$strata = readCache('internets_stratas'))
{
if (empty($stratas))
$stratas = file(API_FILE_IO_STRATA);
shuffle($stratas);
$attempts = 0;
while(empty($strata) || $attempts < (count($strata) * 1.65))
{
$attempts++;
$strata = array_keys(unserialize(getURIData($stratas[mt_rand(0, count($stratas)-1)] ."/v1/strata/serial.api")));
}
if (!empty($strata))
writeCache('internets_stratas', $strata, 3600*24*mt(3.75,11));
}
}
if (empty($fallout))
{
if (!$fallout = readCache('internets_fallouts'))
{
if (empty($stratas))
$stratas = file(API_FILE_IO_STRATA);
shuffle($stratas);
$attempts = 0;
while(empty($fallout) || $attempts < (count($strata) * 1.65))
{
$attempts++;
$fallout = array_keys(unserialize(getURIData($stratas[mt_rand(0, count($stratas)-1)] ."/v1/fallout/serial.api")));
}
if (!empty($fallout))
writeCache('internets_fallouts', $fallout, 3600*24*mt(3.75,11));
}
}
// Get Full Hostname
$url = strtolower($url);
$hostname = parse_url($url, PHP_URL_HOST);
if (!filter_var($hostname, FILTER_VALIDATE_IP) === true)
return $hostname;
// break up domain, reverse
$elements = explode('.', $hostname);
$elements = array_reverse($elements);
// Returns Base Domain
if (in_array($elements[0], $fallout) && in_array($elements[1], $strata))
return $elements[2] . '.' . $elements[1] . '.' . $elements[0];
elseif (in_array($elements[0], $fallout) || in_array($elements[0], $strata))
return $elements[1] . '.' . $elements[0];
// Nothing Found
return $hostname;
}
}
if (!function_exists("whitelistGetIP")) {
/* function whitelistGetIPAddy()
*
* provides an associative array of whitelisted IP Addresses
* @author Simon Roberts (Chronolabs) simon@labs.coop
*
* @return array
*/
function whitelistGetIPAddy() {
return array_merge(whitelistGetNetBIOSIP(), file(dirname(dirname(dirname(dirname(__FILE__)))) . DIRECTORY_SEPARATOR . 'whitelist.txt'));
}
}
if (!function_exists("whitelistGetNetBIOSIP")) {
/* function whitelistGetNetBIOSIP()
*
* provides an associative array of whitelisted IP Addresses base on TLD and NetBIOS Addresses
* @author Simon Roberts (Chronolabs) simon@labs.coop
*
* @return array
*/
function whitelistGetNetBIOSIP() {
$ret = array();
foreach(file(dirname(dirname(dirname(dirname(__FILE__)))) . DIRECTORY_SEPARATOR . 'whitelist-domains.txt') as $domain) {
$ip = gethostbyname($domain);
$ret[$ip] = $ip;
}
return $ret;
}
}
if (!function_exists("getIP")) {
/* function whitelistGetIP()
*
* get the True IPv4/IPv6 address of the client using the API
* @author Simon Roberts (Chronolabs) simon@labs.coop
*
* @param boolean $asString Whether to return an address or network long integer
*
* @return mixed
*/
function getIP($asString = true){
// Gets the proxy ip sent by the user
$proxy_ip = '';
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else
if (!empty($_SERVER['HTTP_X_FORWARDED'])) {
$proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
} else
if (! empty($_SERVER['HTTP_FORWARDED_FOR'])) {
$proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
} else
if (!empty($_SERVER['HTTP_FORWARDED'])) {
$proxy_ip = $_SERVER['HTTP_FORWARDED'];
} else
if (!empty($_SERVER['HTTP_VIA'])) {
$proxy_ip = $_SERVER['HTTP_VIA'];
} else
if (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
$proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
} else
if (!empty($_SERVER['HTTP_COMING_FROM'])) {
$proxy_ip = $_SERVER['HTTP_COMING_FROM'];
}
if (!empty($proxy_ip) && $is_ip = preg_match('/^([0-9]{1,3}.){3,3}[0-9]{1,3}/', $proxy_ip, $regs) && count($regs) > 0) {
$the_IP = $regs[0];
} else {
$the_IP = $_SERVER['REMOTE_ADDR'];
}
$the_IP = ($asString) ? $the_IP : ip2long($the_IP);
return $the_IP;
}
}
if (!function_exists("getNetbios")) {
/* function whitelistGetIP()
*
* get the True IPv4/IPv6 address of the client using the API
* @author Simon Roberts (Chronolabs) simon@labs.coop
*
* @param boolean $asString Whether to return an address or network long integer
*
* @return mixed
*/
function getNetbios() {
// Gets the proxy ip sent by the user
$proxy_ip = '';
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else
if (!empty($_SERVER['HTTP_X_FORWARDED'])) {
$proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
} else
if (! empty($_SERVER['HTTP_FORWARDED_FOR'])) {
$proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
} else
if (!empty($_SERVER['HTTP_FORWARDED'])) {
$proxy_ip = $_SERVER['HTTP_FORWARDED'];
} else
if (!empty($_SERVER['HTTP_VIA'])) {
$proxy_ip = $_SERVER['HTTP_VIA'];
} else
if (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
$proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
} else
if (!empty($_SERVER['HTTP_COMING_FROM'])) {
$proxy_ip = $_SERVER['HTTP_COMING_FROM'];
}
if (!empty($proxy_ip) && $is_ip = preg_match('/^([0-9]{1,3}.){3,3}[0-9]{1,3}/', $proxy_ip, $regs) && count($regs) > 0) {
$the_IP = $regs[0];
} else {
$the_IP = $_SERVER['REMOTE_ADDR'];
}
return gethostbyaddr($the_IP);
}
}
/**
* validateMD5()
* Validates an MD5 Checksum
*
* @param string $email
* @return boolean
*/
if (!function_exists("validateMD5")) {
function validateMD5($md5) {
if(preg_match("/^[a-f0-9]{32}$/i", $md5)) {
return true;
} else {
return false;
}
}
}
/**
* validateEmail()
* Validates an Email Address
*
* @param string $email
* @return boolean
*/
if (!function_exists("validateEmail")) {
function validateEmail($email) {
if(preg_match("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|mobi|asia|museum|name|edu))$", $email)) {
return true;
} else {
return false;
}
}
}
/**
* validateDomain()
* Validates a Domain Name
*
* @param string $domain
* @return boolean
*/
if (!function_exists("validateDomain")) {
function validateDomain($domain) {
if(!preg_match("/^([-a-z0-9]{2,100})\.([a-z\.]{2,8})$/i", $domain)) {
return false;
}
return $domain;
}
}
/**
* validateIPv4()
* Validates and IPv6 Address
*
* @param string $ip
* @return boolean
*/
if (!function_exists("validateIPv4")) {
function validateIPv4($ip) {
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === FALSE) // returns IP is valid
{
return false;
} else {
return true;
}
}
}
/**
* validateIPv6()
* Validates and IPv6 Address
*
* @param string $ip
* @return boolean
*/
if (!function_exists("validateIPv6")) {
function validateIPv6($ip) {
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === FALSE) // returns IP is valid
{
return false;
} else {
return true;
}
}
}
if (!function_exists("mailparse_rfc822_parse_addresses")) {
function mailparse_rfc822_parse_addresses($str = '')
{
$emails = array();
if(preg_match_all('/\s*"?([^><,"]+)"?\s*((?:<[^><,]+>)?)\s*/', $str, $matches, PREG_SET_ORDER) > 0)
{
foreach($matches as $m)
{
if(! empty($m[2]))
{
$emails[trim($m[2], '<>')] = $m[1];
}
else
{
$emails[$m[1]] = '';
}
}
}
return $emails;
}
}
/**
* get A + AAAA record for $host
*
* if $try_a is true, if AAAA fails, it tries for A the first match found is returned otherwise returns false
*
* @param host string netbios networking name\
* @param try_a boolean try for A Record inclusive of AAAA Records
*
* return array
*/
if (!function_exists("getHostByName6")) {
function getHostByName6($host, $try_a = false) {
$dns6 = dns_get_record($host, DNS_AAAA);
if ($try_a == true) {
$dns4 = getHostByName($host);
$dns = array_merge($dns4, $dns6);
}
else { $dns = $dns6; }
if ($dns == false) { return false; }
else { return $dns; }
}
}
/**
* get A + AAAA record IPv4/IPv6 Addresses for $host
*
* if $try_a is true, if AAAA fails, it tries for A the first match found is returned otherwise returns false
*
* @param host string netbios networking name
* @param try_a boolean try for A Record inclusive of AAAA Records
*
* return array
*/
if (!function_exists("getHostByNamel6")) {
function getHostByNamel6($host, $try_a = false) {
$dns6 = dns_get_record($host, DNS_AAAA);
if ($try_a == true) {
$dns4 = getHostByName($host);
$dns = array_merge($dns4, $dns6);
}
else { $dns = $dns6; }
$ip6 = array();
$ip4 = array();
foreach ($dns as $record) {
if ($record["type"] == "A") {
$ip4[] = $record["ip"];
}
if ($record["type"] == "AAAA") {
$ip6[] = $record["ipv6"];
}
}
if (count($ip6) < 1) {
if ($try_a == true) {
if (count($ip4) < 1) {
return false;
}
else {
return $ip4;
}
}
else {
return false;
}
}
else {
return $ip6;
}
}
}
/**
* get A record for $host
*
* if $try_a is true, if AAAA fails, it tries for A the first match found is returned otherwise returns false
*
* @param host string netbios networking name
*
* return array
*/
if (!function_exists("getHostByName")) {
function getHostByName($host) {
$dns = dns_get_record($host, DNS_A);
if ($dns == false) { return false; }
else { return $dns; }
}
}
/**
* get A record IPv4 Addresses for $host
*
* if $try_a is true, if AAAA fails, it tries for A the first match found is returned otherwise returns false
*
* @param host string netbios networking name
*
* return array
*/
if (!function_exists("getHostByNamel")) {
function getHostByNamel($host) {
$dns4 = getHostByName($host);
$ip4 = array();
foreach ($dns4 as $record) {
if ($record["type"] == "A") {
$ip4[] = $record["ip"];
}
}
if (count($ip4) < 1) {
return false;
}
else {
return $ip4;
}
}
}
/**
*
* @param unknown $value
* @param number $limit
* @return unknown[]|string[]
*/
function extractKeywords($value, $limit = 7) {
$keywords = array();
$words = explode(" ", encode_sef($value, ' '));
foreach($words as $ele => $word)
if (strlen($word) > $limit - 1) {
if (strtoupper($word) == $word) {
$keywords[] = $word;
unset($words[$ele]);
} else {
$keywords[] = ucfirst(strtolower($word));
unset($words[$ele]);
}
} elseif (strlen($word) > 2)
if (strtoupper($word) == $word) {
$keywords[] = $word;
unset($words[$ele]);
}
return $keywords;
}
/**
*
* @param unknown $values
* @return unknown[]
*/
function setKeywordHashKeys($values) {
$keywords = array();
sort($values, SORT_ASC);
foreach($values as $value)
$keywords[hash('md4', (strtoupper($value)))] = $value;
return $keywords;
}
/**
*
* @param unknown_type $url
* @return multitype:number unknown |multitype:string number
*/
function jumpShortenURL($url = '')
{
if (!is_dir(API_PATH_IO_REFEREE))
mkdirSecure(API_PATH_IO_REFEREE, 0777);
if (!is_file($jumpsfile = API_PATH_IO_REFEREE . DIRECTORY_SEPARATOR . API_HOSTNAME . '.json'))
$jumps = array();
else
$jumps = json_decode(file_get_contents($jumpsfile), true);
if (!is_file($emailsfile = API_PATH_IO_REFEREE . DIRECTORY_SEPARATOR . API_HOSTNAME . '.emails.json'))
$emails = array();
else
$emails = json_decode(file_get_contents($emailsfile), true);
if (constant('API_DEPLOYMENT_CALLING') == true) {
$myip = new myip();
$ipdata = $myip->query('allmyip', 'json');
if (!is_file($callsfile = API_PATH_IO_REFEREE . DIRECTORY_SEPARATOR . API_HOSTNAME . '.calling.json'))
$calls = array();
else
$calls = json_decode(file_get_contents($callsfile), true);
}
if (!is_file($urlsfile = API_PATH_IO_REFEREE . DIRECTORY_SEPARATOR . basename(__DIR__) . '.urls.json'))
$urls = array();
else
$urls = json_decode(file_get_contents($urlsfile), true);
if (!is_file($hashwordsfile = API_PATH_IO_REFEREE . DIRECTORY_SEPARATOR . basename(__DIR__) . '.hashwords.json'))
$hashwords = array();
else
$hashwords = json_decode(file_get_contents($hashwordsfile), true);
if (!isset($urls[hash('md4', $url)]) || empty($urls[hash('md4', $url)]))
{
if (isset($_REQUEST['custom'])&&!empty($_REQUEST['custom']))
$urls[hash('md4', $url)] = $referee = encode_sef(trim($_REQUEST['custom']));
else
$referee = '';
while(testForShortenURL($referee)==true || empty($referee))
{
set_time_limit(120);
$crc = new xcp($url, mt_rand(0,254), mt_rand(5,9));
$urls[hash('md4', $url)] = $referee = $crc->calc($url);
}
} else {
$referee = $urls[hash('md4', $url)];
}
if (!is_file($refereesfile = API_PATH_IO_REFEREE . DIRECTORY_SEPARATOR . basename(__DIR__) . '.referees.json'))
$referees = array();