forked from d8ahazard/Phlex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.php
2195 lines (2084 loc) · 64.4 KB
/
util.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
use Cz\Git\GitRepository;
require_once dirname(__FILE__) . '/vendor/autoload.php';
// Checks whether an API Token exists for the current user, generates and saves one if none exists.
// Returns generated or existing API Token.
function checkSetUser(Array $userData) {
// Check that we have generated an API token for our user, create and save one if none exists
$userName = strtolower(trim($userData['plexUserName']));
$apiToken = false;
foreach ($GLOBALS['config'] as $section => $user) {
if ($section !== "general") {
$checkName = strtolower(trim($user['plexUserName']));
$checkEmail = strtolower(trim($user['plexEmail']));
write_log("Checking $userName against $checkName and $checkEmail");
if (($userName === $checkName) || ($userName === $checkEmail)) {
write_log("Found matching token for " . $user['plexUserName'] . ".");
$apiToken = $user['apiToken'];
break;
}
}
}
if (!$apiToken) {
dumpRequest();
write_log("NO API TOKEN FOUND, generating one for " . $userName, "INFO");
$apiToken = randomToken(21);
$userData['apiToken'] = $apiToken;
$cleaned = str_repeat("X", strlen($apiToken));
write_log("API token created " . $cleaned);
$userString = $userData['string'];
unset ($userData['string']);
foreach ($userData as $item => $value) {
$GLOBALS['config']->set($userString, $item, $value);
}
saveConfig($GLOBALS['config']);
$_SESSION['newToken'] = true;
} else {
$userData['apiToken'] = $apiToken;
}
return $userData;
}
function validateToken($token) {
$config = new Config_Lite('config.ini.php');
// Check that we have some form of set credentials
foreach ($config as $section => $setting) {
$checkToken = false;
if ($section != "general") {
$checkToken = $setting['apiToken'] ?? false;
if (trim($checkToken) == trim($token)) {
$user = [
'string' => $section,
'plexUserName' => $setting['plexUserName'],
'plexToken' => $setting['plexToken'],
"plexEmail" => $setting['plexEmail'],
"plexAvatar" => $setting['plexAvatar'],
"plexCred" => $setting['plexCred'],
"apiToken" => $setting['apiToken']
];
return $user;
}
}
}
$caller = getCaller("validateToken");
write_log("ERROR, api token $token not recognized, called by $caller.", "ERROR");
dumpRequest();
return false;
}
function cleanCommandString($string) {
$string = trim(strtolower($string));
$string = preg_replace("/ask Flex TV/", "", $string);
$string = preg_replace("/tell Flex TV/", "", $string);
$string = preg_replace("/Flex TV/", "", $string);
$stringArray = explode(" ", $string);
$stripIn = ["of", "an", "a", "at", "th", "nd", "in", "from", "and"];
$stringArray = array_diff($stringArray, array_intersect($stringArray, $stripIn));
foreach ($stringArray as &$word) {
$word = preg_replace("/[^\w\']+|\'(?!\w)|(?<!\w)\'/", "", $word);
}
$result = implode(" ", $stringArray);
return $result;
}
function TTS($text) {
$res = false;
$words = substr($text, 0, 2000);
write_log("Building speech for '$words'");
$words = urlencode($words);
$file = md5($words);
$cacheDir = file_build_path(dirname(__FILE__), "img", "cache");
checkCache($cacheDir);
$payload = [
"engine"=>"Google",
"data"=>[
"text"=>$text,
"voice"=>"en-US"
]
];
$url = "https://soundoftext.com/api/sounds";
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($payload)
));
$mp3 = curl_exec($ch);
$data = json_decode($mp3,true);
write_log("Response: ".json_encode($data));
if ($data['success']) {
$id = $data['id'];
$url = "https://soundoftext.com/api/sounds/$id";
$data = curlGet($url,null,10);
if ($data) {
$response = json_decode($data,true);
if (isset($response['location'])) return $response['location'];
}
}
return false;
}
function flattenXML($xml) {
libxml_use_internal_errors(true);
$return = [];
if (is_string($xml)) {
$xml = new SimpleXMLElement($xml);
}
if (!($xml instanceof SimpleXMLElement)) {
return false;
}
$_value = trim((string)$xml);
if (strlen($_value) == 0) {
$_value = null;
};
if ($_value !== null) {
$return = $_value;
}
$children = [];
$first = true;
foreach ($xml->children() as $elementName => $child) {
$value = flattenXML($child);
if (isset($children[$elementName])) {
if ($first) {
$temp = $children[$elementName];
unset($children[$elementName]);
$children[$elementName][] = $temp;
$first = false;
}
$children[$elementName][] = $value;
} else {
$children[$elementName] = $value;
}
}
if (count($children) > 0) {
$return = array_merge($return, $children);
}
$attributes = [];
foreach ($xml->attributes() as $name => $value) {
$attributes[$name] = trim($value);
}
if (count($attributes) > 0) {
$return = array_merge($return, $attributes);
}
return $return;
}
// Generate a random token using the first available PHP function
function randomToken($length = 32) {
write_log("Function fired.");
if (!isset($length) || intval($length) <= 8) {
$length = 32;
}
if (function_exists('mcrypt_create_iv')) {
write_log("Generating using mcrypt_create.");
return bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM));
}
if (function_exists('openssl_random_pseudo_bytes')) {
write_log("Generating using pseudo_random.");
return bin2hex(openssl_random_pseudo_bytes($length));
}
// Keep this last, as there appear to be issues with random_bytes and Docker.
if (function_exists('random_bytes')) {
write_log("Generating using random_bytes.");
return bin2hex(random_bytes($length));
}
return false;
}
// Generate a timestamp and return it
function timeStamp() {
return date(DATE_RFC2822, time());
}
// Recursively filter empty keys from an array
// Returns filtered array.
function array_filter_recursive(array $array, callable $callback = null) {
$array = is_callable($callback) ? array_filter($array, $callback) : array_filter($array);
foreach ($array as &$value) {
if (is_array($value)) {
$value = call_user_func(__FUNCTION__, $value, $callback);
}
}
return $array;
}
//Get the current protocol of the server
function serverProtocol() {
return (((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://');
}
//Get the relative path to $to in relation to where $from is
function getRelativePath($from, $to) {
// some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;
foreach ($from as $depth => $dir) {
// find first non-matching dir
if ($dir === $to[$depth]) {
// ignore this directory
array_shift($relPath);
} else {
// get number of remaining dirs to $from
$remaining = count($from) - $depth;
if ($remaining > 1) {
// add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
$relPath[0] = '/' . $relPath[0];
}
}
}
return implode('/', $relPath);
}
// Grab an image from a server and save it locally
function cacheImage($url, $image = false) {
write_log("Function fired, caching " . $url);
$path = $url;
$cached_filename = false;
try {
$URL_REF = $_SESSION['publicAddress'] ?? fetchUrl(false);
$cacheDir = file_build_path(dirname(__FILE__), "img", "cache");
checkCache($cacheDir);
if ($url) {
$cached_filename = md5($url);
$files = glob($cacheDir . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$now = time();
foreach ($files as $file) {
$fileName = explode('.', basename($file));
if ($fileName[0] == $cached_filename) {
write_log("File is already cached.");
$path = $URL_REF . getRelativePath(dirname(__FILE__), $file);
} else {
if (is_file($file)) {
if ($now - filemtime($file) >= 60 * 60 * 24 * 5) { // 5 days
unlink($file);
}
}
}
}
}
if ($image) {
$cached_filename = md5($image);
}
if ((($path == $url) || ($image)) && ($cached_filename)) {
write_log("Caching file.");
if (!$image) $image = file_get_contents($url);
if ($image) {
write_log("Image retrieved successfully!");
$tempName = file_build_path($cacheDir, $cached_filename);
file_put_contents($tempName, $image);
$imageData = getimagesize($tempName);
$extension = image_type_to_extension($imageData[2]);
if ($extension) {
write_log("Extension detected successfully!");
$filenameOut = file_build_path($cacheDir, $cached_filename . $extension);
$result = file_put_contents($filenameOut, $image);
if ($result) {
rename($tempName, $filenameOut);
$path = $URL_REF . getRelativePath(dirname(__FILE__), $filenameOut);
write_log("Success, returning cached URL: " . $path);
}
} else {
unset($tempName);
}
}
}
} catch (\Exception $e) {
write_log('Exception: ' . $e->getMessage());
}
return $path;
}
function checkCache($cacheDir) {
if (!file_exists($cacheDir)) {
write_log("No cache directory found, creating.", "INFO");
mkdir($cacheDir, 0777, true);
}
}
function setStartUrl() {
$fileOut = dirname(__FILE__) . "/manifest.json";
$file = (file_exists($fileOut)) ? $fileOut : dirname(__FILE__) . "/manifest_template.json";
$json = json_decode(file_get_contents($file), true);
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url = parse_url($url);
$url = $url['scheme']."://". $url['host'] . $url['path'];
$url = str_replace("\api.php","",$url);
if ($json['start_url'] !== $url) {
$json['start_url'] = $url;
file_put_contents($fileOut, json_encode($json, JSON_PRETTY_PRINT));
}
}
function transcodeImage($path, $uri = "", $token = "") {
if (preg_match("/library/", $path)) {
if ($uri) $server = $uri;
$server = $server ?? $_SESSION['plexServerPublicUri'] ?? $_SESSION['plexServerUri'] ?? false;
if ($token) $serverToken = $token;
$token = $serverToken ?? $_SESSION['plexServerToken'];
if ($server && $token) {
return $server . "/photo/:/transcode?width=1920&height=1920&minSize=1&url=" . urlencode($path) . "%3FX-Plex-Token%3D" . $token . "&X-Plex-Token=" . $token;
}
}
write_log("Invalid image path, returning generic image.", "WARN");
$path = 'https://phlexchat.com/img/avatar.png';
return $path;
}
// Check if string is present in an array
function arrayContains($str, array $arr) {
//write_log("Function Fired.");
$result = array_intersect($arr, explode(" ", $str));
if (count($result) == 1) $result = true;
if (count($result) == 0) $result = false;
return $result;
}
function initMCurl() {
return JMathai\PhpMultiCurl\MultiCurl::getInstance();
}
// Fetch data from a URL using CURL
function curlGet($url, $headers = null, $timeout = 4) {
$cert = getContent(file_build_path(dirname(__FILE__), "cacert.pem"), 'https://curl.haxx.se/ca/cacert.pem');
if (!$cert) $cert = file_build_path(dirname(__FILE__), "cert", "cacert.pem");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CAINFO, $cert);
if ($headers !== null) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200:
break;
default:
write_log('Unexpected HTTP code: ' . $http_code . ', URL: ' . $url, "ERROR");
$result = false;
}
}
curl_close($ch);
return $result;
}
function curlPost($url, $content = false, $JSON = false, Array $headers = null) {
$cert = getContent(file_build_path(dirname(__FILE__), "cacert.pem"), 'https://curl.haxx.se/ca/cacert.pem');
if (!$cert) $cert = file_build_path(dirname(__FILE__), "cert", "cacert.pem");
$mc = JMathai\PhpMultiCurl\MultiCurl::getInstance();
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CAINFO, $cert);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 4);
curl_setopt($curl, CURLOPT_TIMEOUT, 3);
if ($headers) {
if ($JSON) {
$headers = array_merge($headers, ["Content-type: application/json"]);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
} else {
if ($JSON) {
$headers = ["Content-type: application/json"];
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
}
if ($content) curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
//$response = curl_exec($curl);
//curl_close($curl);
$call = $mc->addCurl($curl);
// Access response(s) from your cURL calls.
$result = $call->response;
return $result;
}
// Write log information to $filename
// Auto rotates files larger than 2MB
function write_log($text, $level = null, $caller = false) {
$filename = file_build_path(dirname(__FILE__), 'logs', "Phlex.log.php");
if ($level === null) $level = 'DEBUG';
if (isset($_SESSION) && $level === 'DEBUG' && !$_SESSION['Debug']) return;
if (isset($_GET['pollPlayer']) || !file_exists($filename) || (trim($text) === "")) return;
$caller = $caller ? $caller : getCaller();
$text = '[' . date(DATE_RFC2822) . '] [' . $level . '] [' . $caller . "] - " . trim($text) . PHP_EOL;
$youIdiot = file_build_path(dirname(__FILE__),'logs',"Phlex.log.php.old");
if (file_exists($youIdiot)) unlink($youIdiot);
if (filesize($filename) > 5 * 1024 * 1024) {
$filename2 = "Phlex.log.old.php";
if (file_exists($filename2)) unlink($filename2);
rename($filename, $filename2);
touch($filename);
chmod($filename, 0666);
$authString = "; <?php die('Access denied'); ?>".PHP_EOL;
file_put_contents($filename,$authString);
}
if (!is_writable($filename)) return;
if (!$handle = fopen($filename, 'a+')) return;
if (fwrite($handle, $text) === FALSE) return;
fclose($handle);
}
function isDomainAvailible($domain) {
//check, if a valid url is provided
if (!filter_var($domain, FILTER_VALIDATE_URL)) {
return false;
}
//initialize curl
$curlInit = curl_init($domain);
curl_setopt($curlInit, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curlInit, CURLOPT_HEADER, true);
curl_setopt($curlInit, CURLOPT_NOBODY, true);
curl_setopt($curlInit, CURLOPT_RETURNTRANSFER, true);
//get answer
$response = curl_exec($curlInit);
curl_close($curlInit);
if ($response) return true;
return false;
}
function logUpdate(array $log) {
$config = new Config_Lite('config.ini.php');
$filename = file_build_path(dirname(__FILE__), 'logs', "Phlex_update.log.php");
$data['installed'] = date(DATE_RFC2822);
$data['commits'] = $log;
$config->set("general", "lastUpdate", $data['installed']);
saveConfig($config);
unset($_SESSION['updateAvailable']);
if (!file_exists($filename)) {
touch($filename);
chmod($filename, 0666);
}
if (filesize($filename) > 2 * 1024 * 1024) {
$filename2 = "$filename.old";
if (file_exists($filename2)) unlink($filename2);
rename($filename, $filename2);
touch($filename);
chmod($filename, 0666);
}
if (!is_writable($filename)) die;
$json = json_decode(file_get_contents($filename), true) ?? [];
array_unshift($json, $data);
file_put_contents($filename, json_encode($json));
}
function readUpdate() {
$log = false;
$filename = file_build_path(dirname(__FILE__), 'logs', "Phlex_update.log.php");
if (file_exists($filename)) {
$authString = "'; <?php die('Access denied'); ?>".PHP_EOL;
$file = file_get_contents($filename);
$file = str_replace($authString,"",$file);
$log = json_decode($file, true) ?? [];
}
return $log;
}
function clientHeaders() {
return ['X-Plex-Client-Identifier:' . checkSetDeviceID(), 'X-Plex-Target-Client-Identifier:' . $_SESSION['plexClientId'], 'X-Plex-Device:PhlexWeb', 'X-Plex-Device-Name:Phlex', 'X-Plex-Device-Screen-Resolution:1520x707,1680x1050,1920x1080', 'X-Plex-Platform:Web', 'X-Plex-Platform-Version:1.0.0', 'X-Plex-Product:Phlex', 'X-Plex-Version:3.9.1'];
}
function clientHeaderArray() {
return ['X-Plex-Client-Identifier' => checkSetDeviceID(), 'X-Plex-Target-Client-Identifier' => $_SESSION['plexClientId'], 'X-Plex-Device' => 'PhlexWeb', 'X-Plex-Device-Name' => 'Phlex', 'X-Plex-Device-Screen-Resolution' => '1520x707,1680x1050,1920x1080', 'X-Plex-Platform' => 'Web', 'X-Plex-Platform-Version' => '1.0.0', 'X-Plex-Product' => 'Phlex', 'X-Plex-Version' => '3.9.1'];
}
function clientString() {
$string = '&X-Plex-Product=Phlex' . '&X-Plex-Version=3.9.1' . '&X-Plex-Client-Identifier=' . checkSetDeviceID() . '&X-Plex-Platform=Web' . '&X-Plex-Platform-Version=1.0.0' . '&X-Plex-Device=PhlexWeb' . '&X-Plex-Device-Name=Phlex' . '&X-Plex-Device-Screen-Resolution=1520x707,1680x1050,1920x1080' . '&X-Plex-Token=' . $_SESSION['plexServerToken'] . '&X-Plex-Target-Client-Identifier=' . $_SESSION['plexClientId'];
return $string;
}
// Get the name of the function calling write_log
function getCaller($custom = "foo") {
$trace = debug_backtrace();
$useNext = false;
$caller = false;
//write_log("TRACE: ".print_r($trace,true),null,true);
foreach ($trace as $event) {
if ($useNext) {
if (($event['function'] != 'require') && ($event['function'] != 'include')) {
$caller .= "::" . $event['function'];
break;
}
}
if (($event['function'] == 'write_log') || ($event['function'] == 'doRequest') || ($event['function'] == $custom)) {
$useNext = true;
// Set our caller as the calling file until we get a function
$file = pathinfo($event['file']);
$caller = $file['filename'] . "." . $file['extension'];
}
}
return $caller;
}
// Save the specified configuration file using CONFIG_LITE
function saveConfig(Config_Lite $inConfig) {
$configFile = file_build_path(dirname(__FILE__), "config.ini.php");
if (!is_writable($configFile)) write_log("Configuration file is NOT writeable.","ERROR");
try {
$inConfig->save();
} catch (Config_Lite_Exception $e) {
$msg = $e->getMessage();
write_log("Error saving configuration: $msg", 'ERROR');
}
$configFile = file_build_path(dirname(__FILE__), "config.ini.php");
$cache_new = "'; <?php die('Access denied'); ?>"; // Adds this to the top of the config so that PHP kills the execution if someone tries to request the config-file remotely.
if (file_exists($configFile)) {
$cache_new .= file_get_contents($configFile);
} else {
$fh = fopen($configFile, 'w') or write_log("Can't create config file!","ERROR");
}
if (file_put_contents($configFile, $cache_new)) write_log("Config saved successfully by " . getCaller("saveConfig")); else write_log("Config save failed!", "ERROR");
}
function protectURL($string) {
if ($_SESSION['cleanLogs']) {
$keys = parse_url($string);
$parts = explode(".", $keys['host']);
if (count($parts) >= 2) {
$i = 0;
foreach ($parts as $part) {
if ($i != 0) {
$parts[$i] = str_repeat("X", strlen($part));
}
$i++;
}
$cleaned = implode(".", $parts);
} else {
$cleaned = str_repeat("X", strlen($keys['host']));
}
$string = str_replace($keys['host'], $cleaned, $string);
$cleaned = str_repeat("X", strlen($keys['host']));
$string = str_replace($keys['host'], $cleaned, $string);
$pairs = [];
if ($keys['query']) {
parse_str($keys['query'], $pairs);
foreach ($pairs as $key => $value) {
if ((preg_match("/token/", $key)) || (preg_match("/Token/", $key))) {
$cleaned = str_repeat("X", strlen($value));
$string = str_replace($value, $cleaned, $string);
}
if (preg_match("/address/", $key)) {
$parts = explode(".", $value);
write_log("Parts: " . json_encode($parts));
if (count($parts) >= 2) {
$i = 0;
foreach ($parts as &$part) {
if ($i <= count($parts) - 1) {
$part = str_repeat("X", strlen($part));
}
$i++;
}
$cleaned = implode(".", $parts);
} else {
$cleaned = str_repeat("X", strlen($value));
}
$string = str_replace($value, $cleaned, $string);
}
}
}
}
return $string;
}
// A more precise way of calculating the similarity between two strings
function similarity($str1, $str2) {
$len1 = strlen($str1);
$len2 = strlen($str2);
$max = max($len1, $len2);
$similarity = $i = $j = 0;
while (($i < $len1) && isset($str2[$j])) {
if ($str1[$i] == $str2[$j]) {
$similarity++;
$i++;
$j++;
} elseif ($len1 < $len2) {
$len1++;
$j++;
} elseif ($len1 > $len2) {
$i++;
$len1--;
} else {
$i++;
$j++;
}
}
return round($similarity / $max, 2);
}
// Check if we have a running session before trying to start one
function session_started() {
if (php_sapi_name() !== 'cli') {
if (version_compare(phpversion(), '5.4.0', '>=')) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
// Check the validity of a URL response
function check_url($url, $post = false,$device=false) {
if (!$device) write_log("Checking URL: " . $url); else write_log("Checking URL for device $device");
$certPath = file_build_path(dirname(__FILE__), "cert", "cacert.pem");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_CAINFO, $certPath);
if ($post) {
write_log("Using POST in check_url, instead of GET");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $_SESSION['plex_headers']);
}
/* Get the HTML or whatever is linked in $url. */
curl_exec($ch);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
/* If the document has loaded successfully without any redirection or error */
if ($httpCode >= 200 && $httpCode < 300) {
write_log("Connection is valid: " . $url);
return true;
} else {
write_log("Connection failed with error code " . $httpCode . ": " . $url, "ERROR");
return false;
}
}
// Build a path with OS-agnostic separator
function file_build_path(...$segments) {
return join(DIRECTORY_SEPARATOR, $segments);
}
function buildSpeech(...$segments) {
return join(" ", $segments);
}
function fetchCastDevices() {
$returns = false;
if (!(isset($_GET['pollPlayer']))) write_log("Function fired.");
$result = Chromecast::scan();
if ($result) $returns = [];
if (!(isset($_GET['pollPlayer']))) write_log("Returns: " . json_encode($result));
if ($result[0] == "Error") return false;
foreach ($result as $key => $value) {
$deviceOut = [];
$nameString = preg_replace("/\._googlecast.*/", "", $key);
$nameArray = explode('-', $nameString);
$id = array_pop($nameArray);
$deviceOut['name'] = $value['friendlyname'];
$deviceOut['product'] = 'cast';
$deviceOut['id'] = $id;
$deviceOut['token'] = 'none';
$ip = $value['ip'];
$deviceOut['uri'] = "https://" . $value['ip'] . ":" . $value['port'];
array_push($returns, $deviceOut);
}
return $returns;
}
// Sign in, get a token if we need it
function signIn($credString) {
$token = $_SESSION['plex_token'] ?? false;
if ($token) {
$url = 'https://plex.tv/pms/servers.xml?X-Plex-Token=' . $token;
$result = curlGet($url);
if (strpos($result, 'Please sign in.')) {
write_log("Token invalid, signing in.");
$token = false;
} else {
unset($token);
$token['authToken'] = $_SESSION['plex_token'];
}
}
if (!$token) {
write_log("No token or not signed in, signing into Plex.");
$url = 'https://plex.tv/users/sign_in.xml';
$headers = ['X-Plex-Client-Identifier: ' . checkSetDeviceID(), 'X-Plex-Device:PhlexWeb', 'X-Plex-Device-Screen-Resolution:1520x707,1680x1050,1920x1080', 'X-Plex-Device-Name:Phlex', 'X-Plex-Platform:Web', 'X-Plex-Platform-Version:1.0.0', 'X-Plex-Product:Phlex', 'X-Plex-Version:1.0.0', 'X-Plex-Provides:player,controller,sync-target,pubsub-player', 'Authorization:Basic ' . $credString];
$result = curlPost($url, false, false, $headers);
if ($result) {
$container = new SimpleXMLElement($result);
$container = json_decode(json_encode($container), true)['@attributes'];
write_log("Container: " . json_encode($container));
$token = $container;
}
}
return $token;
}
function checkSetDeviceID() {
$config = new Config_Lite('config.ini.php', LOCK_EX);
$deviceID = $config->get('general', 'deviceID', false);
if (!$deviceID) {
$deviceID = randomToken(12);
$config->set("general", "deviceID", $deviceID);
saveConfig($config);
}
return $deviceID;
}
function fetchDirectory($id = 1) {
if ($id == 1) return base64_decode("Y2QyMjlmNTU5NWZjYWEyNzI3MGI0NDU4OTIyOGE0OTI=");
if ($id == 2) return base64_decode("Njk0Nzg2RjBBMkVCNEUwOQ==");
if ($id == 3) return base64_decode("NjU2NTRmODIwZDQ2NDdhYjljZjdlZGRkZGJiYTZlMDI=");
return false;
}
function setDefaults() {
$GLOBALS['config'] = new Config_Lite(dirname(__FILE__) . '/config.ini.php', LOCK_EX);
ini_set("log_errors", 1);
ini_set('max_execution_time', 300);
error_reporting(E_ERROR);
$errorLogPath = file_build_path(dirname(__FILE__), 'logs', "Phlex_error.log.php");
ini_set("error_log", $errorLogPath);
date_default_timezone_set((date_default_timezone_get() ? date_default_timezone_get() : "America/Chicago"));
}
function checkFiles() {
$messages = [];
$extensions = ['sockets', 'curl', 'xml'];
$logDir = file_build_path(dirname(__FILE__), "logs");
$logPath = file_build_path($logDir, "Phlex.log.php");
$errorLogPath = file_build_path($logDir, "Phlex_error.log.php");
$updateLogPath = file_build_path($logDir, "Phlex_update.log.php");
$old = [
file_build_path($logDir, "PhlexUpdate.log"),
file_build_path($logDir, "Phlex.log"),
file_build_path($logDir, "Phlex.log.old"),
file_build_path($logDir, "Phlex_error.log"),
file_build_path($logDir, "Phlex_update.log")
];
foreach ($old as $delete) {
if (file_exists($delete)) {
write_log("Deleting insecure file $delete","INFO");
unlink($delete);
}
}
$files = [$logPath, $errorLogPath, $updateLogPath, 'config.ini.php', 'commands.php'];
$secureString = "'; <?php die('Access denied'); ?>";
if (!file_exists($logDir)) {
if (!mkdir($logDir, 0777, true)) {
$message = "Unable to create log folder directory, please check permissions and try again.";
$error = [
'title' => 'Permission error.',
'message' => $message,
'url' => false
];
array_push($messages, $error);
}
}
foreach ($files as $file) {
if (!file_exists($file)) {
mkdir(dirname($file), 0777, true);
touch($file);
chmod($file, 0777);
file_put_contents($file,$secureString);
}
if ((file_exists($file) && (!is_writable(dirname($file)) || !is_writable($file))) || !is_writable(dirname($file))) { // If file exists, check both file and directory writeable, else check that the directory is writeable.
$message = 'Either the file ' . $file . ' and/or it\'s parent directory is not writable by the PHP process. Check the permissions & ownership and try again.';
$url = '';
if (PHP_SHLIB_SUFFIX === "so") { //Check for POSIX systems.
$message .= " Current permission mode of " . $file . " is " . decoct(fileperms($file) & 0777);
$message .= " Current owner of " . $file . " is " . posix_getpwuid(fileowner($file))['name'];
$message .= " Refer to the README on instructions how to change permissions on the aforementioned files.";
$url = 'http://www.computernetworkingnotes.com/ubuntu-12-04-tips-and-tricks/how-to-fix-permission-of-htdocs-in-ubuntu.html';
} else if (PHP_SHLIB_SUFFIX === "dll") {
$message .= " Detected Windows system, refer to guides on how to set appropriate permissions."; //Can't get fileowner in a trivial manner.
$url = 'https://stackoverflow.com/questions/32017161/xampp-on-windows-8-1-cant-edit-files-in-htdocs';
}
write_log($message, "ERROR");
$error = ['title' => 'File error.', 'message' => $message, 'url' => $url];
array_push($messages, $error);
}
}
foreach ($extensions as $extension) {
if (!load_lib($extension)) {
$message = "The " . $extension . " PHP extension, which is required for Phlex to work correctly, is not loaded." . " Please enable it in php.ini, restart your webserver, and then reload this page to continue.";
write_log($message, "ERROR");
$url = "http://php.net/manual/en/book.$extension.php";
$error = ['title' => 'PHP Extension not loaded.', 'message' => $message, 'url' => $url];
array_push($messages, $error);
}
}
try {
new Config_Lite('config.ini.php');
} catch (Config_Lite_Exception_Runtime $e) {
$message = "An exception occurred trying to load config.ini.php. Please check that the directory and file are writeable by your webserver application and try again.";
$error = ['title' => 'Config error.', 'message' => $message, 'url' => false];
array_push($messages, $error);
};
//$testMessage = ['title'=>'Test message.','message'=>"This is a test of the emergency alert system. If this were a real emergency, you'd be screwed.",'url'=>'https://www.google.com'];
//array_push($messages,$testMessage);
return $messages;
}
function load_lib($ext) {
if (extension_loaded($ext)) return true;
write_log("Extension is not loaded, attempting to load $ext...", "INFO");
if (function_exists('dl')) return dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . $ext . '.' . PHP_SHLIB_SUFFIX);
write_log("DL function not available.", "WARN");
return false;
}
function clearSession() {
write_log("Function fired");
if (!session_started()) session_start();
if (isset($_SERVER['HTTP_COOKIE'])) {
write_log("Cookies found, unsetting.");
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach ($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
write_log("Cookie: " . $name);
setcookie($name, '', time() - 1000);
setcookie($name, '', time() - 1000, '/');
}
}
session_start();
session_unset();
$has_session = session_status() == PHP_SESSION_ACTIVE;
if ($has_session) session_destroy();
session_write_close();
setcookie(session_name(), '', 0, '/');
session_regenerate_id(true);
}
function addScheme($url, $scheme = 'http://') {
return parse_url($url, PHP_URL_SCHEME) === null ? $scheme . $url : $url;
}
// Shamelessly stolen from https://davidwalsh.name/php-cache-function
// But slightly updated to do what I needed it to do.
function getContent($file, $url, $hours = 56, $fn = '', $fn_args = '') {
$current_time = time();
$expire_time = $hours * 60 * 60;
$file_time = filemtime($file);
if (file_exists($file) && ($current_time - $expire_time < $file_time)) {
return $file;
} else {
$content = getUrl($url);
if ($content) {
if ($fn) {
$content = $fn($content, $fn_args);
}
$content .= '<!-- cached: ' . time() . '-->';
file_put_contents($file, $content);
write_log('Retrieved fresh from ' . $url, "INFO");
if (file_exists($file)) return $file;
}
return false;
}
}
function toBool($var) {
if (!is_string($var)) return $var;
switch (strtolower($var)) {
case 'true':
return true;
case 'false':
return false;
default:
return $var;
}
}
function checkSSL() {
$forceSSL = false;
if (file_exists(dirname(__FILE__) . "/config.ini.php")) {
$config = new Config_Lite('config.ini.php');
$forceSSL = $config->getBool('general', 'forceSsl', false);
}
return $forceSSL;
}
function checkSetLanguage($locale = false) {
$locale = $locale ? $locale : getDefaultLocale();
listLocales();
if (file_exists(dirname(__FILE__) . "/lang/" . $locale . ".json")) {
$langJSON = file_get_contents(dirname(__FILE__) . "/lang/" . $locale . ".json");
} else {
write_log("Couldn't find the selected locale, defaulting to 'Murica.");
$langJSON = file_get_contents(dirname(__FILE__) . "/lang/en.json");
}
// This gets added automagically, ignore IDE warnings about it...
return json_decode($langJSON, true);
}
function listLocales() {
$dir = file_build_path(dirname(__FILE__), "lang");
$list = "";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
$name = trim(str_replace(".", "", trim($file)));
if ($name) {
$locale = str_replace("json", "", $name);
$localeName = localeName($locale);
$json = file_get_contents(file_build_path($dir, $file));
$json = json_decode($json, true);
if ($json) {
$selected = ($_SESSION["appLanguage"] == $locale ? 'selected' : '');
$list .= "<option data-value='$locale' id='$locale' $selected>$localeName</option>" . PHP_EOL;
}
}
}
closedir($dh);
}
}
return $list;
}
function getDefaultLocale() {
$locale = false;
$defaultLocale = setlocale(LC_ALL, 0);
// If a session language is set
if (isset($_SESSION['appLanguage'])) {
$locale = $_SESSION['appLanguage'];
} else {
if (file_exists(dirname(__FILE__) . "/config.ini.php") && isset($_SESSION['plexUserName'])) {
$config = new Config_Lite('config.ini.php');
$locale = $config->get('user-_-' . $_SESSION['plexUserName'], "appLanguage", false);
if ($locale) $_SESSION['appLanguage'] = $locale;
write_log("Locale not set for session, but saved in config: $locale");
} else {
write_log("No session username, can't look in settings.", "ERROR");
}
}
if (!$locale) {