/
common.class.php
1545 lines (1355 loc) · 43.9 KB
/
common.class.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
function getSystemSerial($force_update = 0) {
$serial = gg('Serial');
if (!$serial || $serial == '0' || $force_update) {
$serial = '';
if (IsWindowsOS()) {
$data = exec('vol c:');
if (preg_match('/[\w]+\-[\w]+/', $data, $m)) {
$serial = strtolower($m[0]);
}
} else {
$data = trim(exec("cat /proc/cpuinfo | grep Serial | cut -d '':'' -f 2"));
if ($data == '') {
$data = trim(exec("sudo cat /proc/cpuinfo | grep Serial | cut -d '':'' -f 2"));
}
$serial = ltrim($data, '0');
}
if (!$serial) {
$serial = uniqid('uniq');
}
sg('Serial', $serial);
}
return $serial;
}
function sayReplySafe($ph, $level = 0, $replyto = '')
{
$data = array(
'sayReply' => 1,
'ph' => $ph,
'level' => $level,
'replyto' => $replyto,
);
if (session_id()) {
$data[session_name()] = session_id();
}
$url = BASE_URL . '/objects/?' . http_build_query($data);
if (is_array($params)) {
foreach ($params as $k => $v) {
$url .= '&' . $k . '=' . urlencode($v);
}
}
$result = getURLBackground($url, 0);
return $result;
}
/**
* Summary of sayReply
* @param mixed $ph Phrase
* @param mixed $level Level (default 0)
* @param mixed $replyto Original request
* @return void
*/
function sayReply($ph, $level = 0, $replyto = '')
{
$source = '';
if ($replyto) {
$terminal_rec = SQLSelectOne("SELECT * FROM terminals WHERE LATEST_REQUEST LIKE '%" . DBSafe($replyto) . "%' ORDER BY LATEST_REQUEST_TIME DESC LIMIT 1");
$orig_msg = SQLSelectOne("SELECT * FROM shouts WHERE SOURCE!='' AND MESSAGE LIKE '%" . DBSafe($replyto) . "%' AND ADDED>=(NOW() - INTERVAL 30 SECOND) ORDER BY ADDED DESC LIMIT 1");
if ($orig_msg['ID']) {
$source = $orig_msg['SOURCE'];
}
} else {
$terminal_rec = SQLSelectOne("SELECT * FROM terminals WHERE LATEST_REQUEST_TIME>=(NOW() - INTERVAL 5 SECOND) ORDER BY LATEST_REQUEST_TIME DESC LIMIT 1");
}
if (!$terminal_rec) {
$source = 'terminal_not_found';
say($ph, $level);
} else {
$source = 'terminal' . $terminal_rec['ID'];
$said_status = sayTo($ph, $level, $terminal_rec['NAME']);
if (!$said_status) {
say($ph, $level);
} else {
//$rec = array();
//$rec['MESSAGE'] = $ph;
//$rec['ADDED'] = date('Y-m-d H:i:s');
//$rec['ROOM_ID'] = 0;
//$rec['MEMBER_ID'] = 0;
//if ($level > 0) $rec['IMPORTANCE'] = $level;
//$rec['ID'] = SQLInsert('shouts', $rec);
}
}
processSubscriptionsSafe('SAYREPLY', array('level' => $level, 'message' => $ph, 'replyto' => $replyto, 'source' => $source));
}
function sayToSafe($ph, $level = 0, $destination = '')
{
$data = array(
'sayTo' => 1,
'ph' => $ph,
'level' => $level,
'destination' => $destination,
);
if (session_id()) {
$data[session_name()] = session_id();
}
$url = BASE_URL . '/objects/?' . http_build_query($data);
if (is_array($params)) {
foreach ($params as $k => $v) {
$url .= '&' . $k . '=' . urlencode($v);
}
}
$result = getURLBackground($url, 0);
return $result;
}
/**
* Summary of sayTo
* @param mixed $ph Phrase
* @param mixed $level Level (default 0)
* @param mixed $destination Destination terminal name
* @return void
*/
function sayTo($ph, $level = 0, $destination = '')
{
if (!$destination) {
return 0;
}
// add message to chat
$rec = array();
$rec['MESSAGE'] = $ph;
$rec['ADDED'] = date('Y-m-d H:i:s');
$rec['ROOM_ID'] = 0;
$rec['MEMBER_ID'] = 0;
if ($level > 0) $rec['IMPORTANCE'] = $level;
$rec['ID'] = SQLInsert('shouts', $rec);
$processed = processSubscriptionsSafe('SAYTO', array('level' => $level, 'message' => $ph, 'destination' => $destination));
return 1;
}
function saySafe($ph, $level = 0, $member_id = 0, $source = '')
{
$data = array(
'say' => 1,
'ph' => $ph,
'level' => $level,
'member_id' => $member_id,
'source' => $source,
);
if (session_id()) {
$data[session_name()] = session_id();
}
$url = BASE_URL . '/objects/?' . http_build_query($data);
if (is_array($params)) {
foreach ($params as $k => $v) {
$url .= '&' . $k . '=' . urlencode($v);
}
}
$result = getURLBackground($url, 0);
return $result;
}
/**
* Summary of say
* @param mixed $ph Phrase
* @param mixed $level Level (default 0)
* @param mixed $member_id Member ID (default 0)
* @return void
*/
function say($ph, $level = 0, $member_id = 0, $source = '')
{
//dprint(date('Y-m-d H:i:s')." Say started",false);
verbose_log("SAY (level: $level; member: $member; source: $source): " . $ph);
//DebMes("SAY (level: $level; member: $member; source: $source): ".$ph,'say');
$rec = array();
$rec['MESSAGE'] = $ph;
$rec['ADDED'] = date('Y-m-d H:i:s');
$rec['ROOM_ID'] = 0;
$rec['MEMBER_ID'] = $member_id;
$rec['SOURCE'] = $source;
if ($level > 0) $rec['IMPORTANCE'] = $level;
$rec['ID'] = SQLInsert('shouts', $rec);
if ($member_id) {
$processed = processSubscriptionsSafe('COMMAND', array('level' => $level, 'message' => $ph, 'member_id' => $member_id, 'source' => $source));
return;
}
if (defined('SETTINGS_HOOK_BEFORE_SAY') && SETTINGS_HOOK_BEFORE_SAY != '') {
eval(SETTINGS_HOOK_BEFORE_SAY);
}
if ($level >= (int)getGlobal('minMsgLevel') && !$ignoreVoice && !$member_id) {
if (!defined('SETTINGS_SPEAK_SIGNAL') || SETTINGS_SPEAK_SIGNAL == '1') {
$passed = time() - (int)getGlobal('lastSayTime');
if ($passed > 20) {
playSound('dingdong', 1, $level);
}
}
}
setGlobal('lastSayTime', time());
setGlobal('lastSayMessage', $ph);
processSubscriptionsSafe('SAY', array('level' => $level, 'message' => $ph, 'member_id' => $member_id)); //, 'ignoreVoice'=>$ignoreVoice
if (defined('SETTINGS_HOOK_AFTER_SAY') && SETTINGS_HOOK_AFTER_SAY != '') {
eval(SETTINGS_HOOK_AFTER_SAY);
}
//dprint(date('Y-m-d H:i:s')." Say OK",false);
}
function ask($prompt, $target = '')
{
processSubscriptionsSafe('ASK', array('prompt' => $prompt, 'message' => $prompt, 'target' => $target, 'destination' => $target));
}
/**
* Summary of processCommand
* @param mixed $command Command
* @return void
*/
function processCommand($command)
{
global $pattern_matched;
if (!$pattern_matched) {
getObject("ThisComputer")->callMethod("commandReceived", array("command" => $command));
}
}
/**
* Summary of timeConvert
* @param mixed $tm Time
* @return int|string
*/
function timeConvert($tm)
{
$tm = trim($tm);
if (preg_match('/^(\d+):(\d+)$/', $tm, $m)) {
$hour = $m[1];
$minute = $m[2];
$trueTime = mktime($hour, $minute, 0, (int)date('m'), (int)date('d'), (int)date('Y'));
} elseif (preg_match('/^(\d+)$/', $tm, $m)) {
$trueTime = $tm;
}
return $trueTime;
}
function getNumberWord($number, $suffix)
{
$keys = array(2, 0, 1, 1, 1, 2);
$mod = abs($number) % 100;
$suffix_key = ($mod > 7 && $mod < 20) ? 2 : $keys[min($mod % 10, 5)];
return $suffix[$suffix_key];
}
/**
* Summary of timeNow
* @param mixed $tm time (default 0)
* @return string
*/
function timeNow($tm = 0)
{
if (!$tm) {
$tm = time();
}
$h = (int)date('G', $tm);
$m = (int)date('i', $tm);
$ms = '';
if (LANG_HOURS_ARRAY and LANG_MINUTE_ARRAY) {
$array = explode(',', LANG_HOURS_ARRAY);
$hw = $h . ' ' . getNumberWord($h, $array);
if ($m > 0) {
$array = explode(',', LANG_MINUTE_ARRAY);
$ms = $m . ' ' . getNumberWord($m, $array);
}
} else {
$hw = date('H:i', $tm);
}
$res = trim($hw . " " . $ms);
return $res;
}
/**
* Summary of isWeekEnd
* @return bool
*/
function isWeekEnd()
{
if (date('w') == 0 || date('w') == 6)
return true; // sunday, saturday
return false;
}
/**
* Summary of isWeekDay
* @return bool
*/
function isWeekDay()
{
if (IsWeekEnd())
return false;
return true;
}
/**
* Summary of timeIs
* @param mixed $tm Time
* @return bool
*/
function timeIs($tm)
{
if (date('H:i') == $tm)
return true;
return false;
}
/**
* Summary of timeBefore
* @param mixed $tm Time
* @return bool
*/
function timeBefore($tm)
{
$trueTime = timeConvert($tm);
if (time() <= $trueTime)
return true;
return false;
}
/**
* Summary of timeAfter
* @param mixed $tm Time
* @return bool
*/
function timeAfter($tm)
{
$trueTime = timeConvert($tm);
if (time() >= $trueTime)
return true;
return false;
}
/**
* Summary of timeBetween
* @param mixed $tm1 Time 1
* @param mixed $tm2 Time 2
* @return bool
*/
function timeBetween($tm1, $tm2)
{
$trueTime1 = timeConvert($tm1);
$trueTime2 = timeConvert($tm2);
if ($trueTime1 > $trueTime2) {
if ($trueTime2 < time()) {
$trueTime2 += 24 * 60 * 60;
} else {
$trueTime1 -= 24 * 60 * 60;
}
}
if ((time() >= $trueTime1) && (time() <= $trueTime2))
return true;
return false;
}
/**
* Summary of addScheduledJob
* @param mixed $title Title
* @param mixed $commands Commands
* @param mixed $datetime Date
* @param mixed $expire Expire time (default 60)
* @return mixed
*/
function addScheduledJob($title, $commands, $datetime, $expire = 1800)
{
clearScheduledJob($title);
$rec = array();
$rec['TITLE'] = $title;
$rec['COMMANDS'] = $commands;
$rec['RUNTIME'] = date('Y-m-d H:i:s', $datetime);
$rec['EXPIRE'] = date('Y-m-d H:i:s', $datetime + $expire);
$rec['ID'] = SQLInsert('jobs', $rec);
return $rec['ID'];
}
/**
* Summary of clearScheduledJob
* @param mixed $title Title
* @return void
*/
function clearScheduledJob($title)
{
SQLExec("DELETE FROM jobs WHERE TITLE LIKE '" . DBSafe($title) . "'");
}
/**
* Delete job from schedule
* @param mixed $id Job id
* @return void
*/
function deleteScheduledJob($id)
{
SQLExec("DELETE FROM jobs WHERE ID = " . (int)$id);
}
/**
* Summary of setTimeOut
* @param mixed $title Title
* @param mixed $commands Commands
* @param mixed $timeout Timeout
* @return mixed
*/
function setTimeOut($title, $commands, $timeout)
{
startMeasure('setTimeout');
clearTimeOut($title);
$res = addScheduledJob($title, $commands, time() + $timeout);
endMeasure('setTimeout');
return $res;
}
/**
* Summary of clearTimeOut
* @param mixed $title Title
* @return void
*/
function clearTimeOut($title)
{
return clearScheduledJob($title);
}
/**
* Summary of timeOutExists
* @param mixed $title Title
* @return int
*/
function timeOutExists($title)
{
$job = SQLSelectOne("SELECT ID FROM jobs WHERE PROCESSED = 0 AND TITLE = '" . DBSafe($title) . "'");
return (int)$job['ID'];
}
/**
* Summary of runScheduledJobs
* @return void
*/
function runScheduledJobs()
{
SQLExec("DELETE FROM jobs WHERE EXPIRE <= '" . date('Y-m-d H:i:s') . "'");
$sqlQuery = "SELECT *
FROM jobs
WHERE PROCESSED = 0
AND EXPIRED = 0
AND RUNTIME <= '" . date('Y-m-d H:i:s') . "'";
$jobs = SQLSelect($sqlQuery);
$total = count($jobs);
for ($i = 0; $i < $total; $i++) {
//echo "Running job: " . $jobs[$i]['TITLE'] . "\n";
$jobs[$i]['PROCESSED'] = 1;
$jobs[$i]['STARTED'] = date('Y-m-d H:i:s');
SQLUpdate('jobs', $jobs[$i]);
if ($jobs[$i]['COMMANDS'] != '') {
$url = BASE_URL . '/objects/?job=' . $jobs[$i]['ID'];
$result = trim(getURL($url, 0));
$result = preg_replace('/<!--.+-->/is', '', $result);
if (!preg_match('/OK$/', $result)) {
//getLogger(__FILE__)->error(sprintf('Error executing job %s (%s): %s', $jobs[$i]['TITLE'], $jobs[$i]['ID'], $result));
DebMes(sprintf('Error executing job %s (%s): %s', $jobs[$i]['TITLE'], $jobs[$i]['ID'], $result) . ' (' . __FILE__ . ')','errors');
}
}
}
}
/**
* Summary of textToNumbers
* @param mixed $text Text
* @return mixed
*/
function textToNumbers($text)
{
$newtext = ($text);
return $newtext;
}
/**
* Summary of recognizeTime
* @param mixed $text Text
* @param mixed $newText New text
* @return array|double|int
*/
function recognizeTime($text, &$newText)
{
$result = 0;
$found = 0;
$new_time = time();
$text = ($text);
if (preg_match('/через (\d+) '.LANG_PATTERN_SECOND.'.?/isu', $text, $m)) {
$new_time = time() + $m[1];
$newText = trim(str_replace($m[0], '', $text));
$found = 1;
} elseif (preg_match('/через (\d+) '.LANG_PATTERN_MINUTE.'.?/isu', $text, $m)) {
$new_time = time() + $m[1] * 60;
$newText = trim(str_replace($m[0], '', $text));
$found = 1;
} elseif (preg_match('/через (\d+) '.LANG_PATTERN_HOUR.'.?/isu', $text, $m)) {
$new_time = time() + $m[1] * 60 * 60;
$newText = trim(str_replace($m[0], '', $text));
$found = 1;
} elseif (preg_match('/в (\d+):(\d+)/isu', $text, $m)) {
$new_time = mktime($m[1], $m[2], 0, (int)date('m'), (int)date('d'), (int)date('Y'));
$newText = trim(str_replace($m[0], '', $text));
$found = 1;
}
$newText = ($newText);
if ($found) {
$result = $new_time;
}
return $result;
}
/**
* Summary of registerEvent
* @param mixed $eventName Event name
* @param mixed $details Details (default '')
* @param mixed $expire_in Expire time (default 365)
* @return mixed
*/
function registerEvent($eventName, $details = '', $expire_in = 0)
{
include_once(DIR_MODULES . 'events/events.class.php');
$events = new events();
return $events->registerEvent($eventName, $details, $expire_in);
}
/**
* Summary of registeredEventTime
* @param mixed $eventName Event name
* @return mixed
*/
function registeredEventTime($eventName)
{
$sqlQuery = "SELECT ID, UNIX_TIMESTAMP(ADDED) AS TM
FROM events
WHERE EVENT_TYPE = 'system'
AND EVENT_NAME = '" . DBSafe($eventName) . "'
ORDER BY ADDED DESC
LIMIT 1";
$rec = SQLSelectOne($sqlQuery);
if ($rec['ID']) {
return $rec['TM'];
} else {
return -1;
}
}
/**
* Summary of getRandomLine
* @param mixed $filename File name
* @return mixed
*/
function getRandomLine($filename)
{
if (file_exists(ROOT . 'cms/texts/' . $filename . '.txt')) {
$filename = ROOT . 'cms/texts/' . $filename . '.txt';
}
if (file_exists($filename)) {
$data = LoadFile($filename);
$data = str_replace("\r", '', $data);
$data = str_replace("\n\n", "\n", $data);
$lines = mb_split("\n", $data);
$total = count($lines);
$line = $lines[round(rand(0, $total - 1))];
if ($line != '') {
return $line;
}
}
}
/**
* Summary of playSound
* @param mixed $filename File name
* @param mixed $exclusive Exclusive (default 0)
* @param mixed $priority Priority (default 0)
* @return void
*/
function playSound($filename, $exclusive = 0, $priority = 0)
{
global $ignoreSound;
if (file_exists(ROOT . 'cms/sounds/' . $filename . '.mp3'))
$filename = ROOT . 'cms/sounds/' . $filename . '.mp3';
elseif (file_exists(ROOT . 'cms/sounds/' . $filename))
$filename = ROOT . 'cms/sounds/' . $filename;
if (defined('SETTINGS_HOOK_BEFORE_PLAYSOUND') && SETTINGS_HOOK_BEFORE_PLAYSOUND != '')
eval(SETTINGS_HOOK_BEFORE_PLAYSOUND);
if (!$ignoreSound) {
if (file_exists($filename)) {
if (IsWindowsOS())
safe_exec(DOC_ROOT . '/rc/madplay.exe ' . $filename, $exclusive, $priority);
else {
if (defined('AUDIO_PLAYER') && AUDIO_PLAYER!='') {
$audio_player = AUDIO_PLAYER;
} else {
$audio_player = 'mplayer';
}
safe_exec($audio_player.' ' . $filename . " >/dev/null 2>&1", $exclusive, $priority);
}
}
}
if (defined('SETTINGS_HOOK_AFTER_PLAYSOUND') && SETTINGS_HOOK_AFTER_PLAYSOUND != '')
eval(SETTINGS_HOOK_AFTER_PLAYSOUND);
}
/**
* Summary of runScript
* @param mixed $id ID
* @param mixed $params Params (default '')
* @return mixed
*/
function runScript($id, $params = '')
{
include_once(DIR_MODULES . 'scripts/scripts.class.php');
$sc = new scripts();
return $sc->runScript($id, $params);
}
function runScriptSafe($id, $params = '')
{
$current_call = 'script.' . $id;
if (is_array($params)) {
$current_call.='.'.md5(json_encode($params));
}
$call_stack = array();
if (IsSet($_SERVER['REQUEST_URI']) && ($_SERVER['REQUEST_URI'] != '')) {
if (isset($_GET['m_c_s']) && is_array($_GET['m_c_s'])) {
$call_stack = $_GET['m_c_s'];
}
if (in_array($current_call, $call_stack)) {
$call_stack[] = $current_call;
DebMes("Warning: cross-linked call of " . $current_call . "\nlog:\n" . implode(" -> \n", $call_stack));
return 0;
}
}
$call_stack[] = $current_call;
if (!is_array($params)) {
$params = array();
}
if (isSet($_SERVER['REQUEST_URI'])) {
$result = runScript($id,$params);
} else {
$params['m_c_s'] = $call_stack;
if (session_id()) {
$params[session_name()] = session_id();
}
$result = callAPI('/api/script/' . urlencode($id), 'GET', $params);
}
return $result;
}
/**
* Summary of callScript
* @param mixed $id ID
* @param mixed $params Params (default '')
* @return void
*/
function callScript($id, $params = '')
{
runScript($id, $params);
}
function getURLBackground($url, $cache = 0, $username = '', $password = '')
{
//DebMes("URL: ".$url,'debug1');
getURL($url, $cache, $username, $password, true);
return true;
}
/**
* Summary of getURL
* @param mixed $url Url
* @param mixed $cache Cache (default 0)
* @param mixed $username User name (default '')
* @param mixed $password Password (default '')
* @return mixed
*/
function getURL($url, $cache = 0, $username = '', $password = '', $background = false)
{
startMeasure('getURL');
// DebMes($url,'urls');
$filename_part = preg_replace('/\W/is', '_', str_replace('http://', '', $url));
if (strlen($filename_part) > 200) {
$filename_part = substr($filename_part, 0, 200) . md5($filename_part);
}
$cache_file = ROOT . 'cms/cached/urls/' . $filename_part . '.html';
if (!$cache || !is_file($cache_file) || ((time() - filemtime($cache_file)) > $cache)) {
try {
//DebMes('Geturl started for '.$url. ' Source: ' .debug_backtrace()[1]['function'], 'geturl');
startMeasure('curl_prepare');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // connection timeout
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 45); // operation timeout 45 seconds
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // bad style, I know...
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
if ($background) {
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 50);
}
if ($username != '' || $password != '') {
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
}
$url_parsed = parse_url($url);
$host = $url_parsed['host'];
$use_proxy = false;
if (defined('USE_PROXY') && USE_PROXY != '') {
$use_proxy = true;
}
if ($host == '127.0.0.1' || $host == 'localhost') {
$use_proxy = false;
}
if ($use_proxy && defined('HOME_NETWORK') && HOME_NETWORK != '') {
$p = preg_quote(HOME_NETWORK);
$p = str_replace('\*', '\d+?', $p);
$p = str_replace(',', ' ', $p);
$p = str_replace(' ', ' ', $p);
$p = str_replace(' ', '|', $p);
if (preg_match('/' . $p . '/is', $host)) {
$use_proxy = false;
}
}
if ($use_proxy) {
curl_setopt($ch, CURLOPT_PROXY, USE_PROXY);
if (defined('USE_PROXY_AUTH') && USE_PROXY_AUTH != '') {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, USE_PROXY_AUTH);
}
}
$tmpfname = ROOT . 'cms/cached/cookie.txt';
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
endMeasure('curl_prepare');
startMeasure('curl_exec');
$result = curl_exec($ch);
endMeasure('curl_exec');
startMeasure('curl_post');
if (!$background && curl_errno($ch)) {
$errorInfo = curl_error($ch);
$info = curl_getinfo($ch);
$backtrace = debug_backtrace();
$callSource = $backtrace[1]['function'];
DebMes("GetURL to $url (source " . $callSource . ") finished with error: \n" . $errorInfo . "\n" . json_encode($info),'geturl_error');
}
curl_close($ch);
endMeasure('curl_post');
} catch (Exception $e) {
registerError('geturl', $url . ' ' . get_class($e) . ', ' . $e->getMessage());
}
if ($cache > 0) {
CreateDir(ROOT . 'cms/cached/urls');
SaveFile($cache_file, $result);
}
} else {
$result = LoadFile($cache_file);
}
endMeasure('getURL');
return $result;
}
/**
* Summary of safe_exec
* @param mixed $command Command
* @param mixed $exclusive Exclusive (default 0)
* @param mixed $priority Priority (default 0)
* @param mixed $on_complete On_Complete code (default '')
* @return mixed
*/
function safe_exec($command, $exclusive = 0, $priority = 0, $on_complete = '')
{
$rec = array();
$rec['ADDED'] = date('Y-m-d H:i:s');
$rec['COMMAND'] = $command;
$rec['EXCLUSIVE'] = (int)$exclusive;
$rec['PRIORITY'] = (int)$priority;
$rec['ON_COMPLETE'] = $on_complete;
$rec['ID'] = SQLInsert('safe_execs', $rec);
return $rec['ID'];
}
/**
* Summary of execInBackground
* @param mixed $cmd Command
* @return void
*/
function execInBackground($cmd)
{
if (IsWindowsOS()) {
//pclose(popen("start /B ". $cmd, "r"));
try {
//pclose(popen("start /B ". $cmd, "r"));
if (class_exists('COM')) {
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("cmd /C \"" . $cmd . "\"", 0, false);
} else {
system($cmd);
}
} catch (Exception $e) {
DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
}
} else {
exec($cmd . " > /dev/null &");
}
}
/**
* Summary of getFilesTree
* @param mixed $destination Destination
* @param mixed $sort Sort (default 'name')
* @return array
*/
function getFilesTree($destination, $sort = 'name')
{
if (substr($destination, -1) == '/' || substr($destination, -1) == '\\') {
$destination = substr($destination, 0, strlen($destination) - 1);
}
$res = array();
if (!is_dir($destination))
return $res;
if ($dir = @opendir($destination)) {
while (($file = readdir($dir)) !== false) {
if (is_dir($destination . "/" . $file) && ($file != '.') && ($file != '..')) {
$tmp = getFilesTree($destination . "/" . $file);
if (is_array($tmp)) {
foreach ($tmp as $elem) {
$res[] = $elem;
}
}
} elseif (is_file($destination . "/" . $file)) {
$res[] = ($destination . "/" . $file);
}
}
closedir($dir);
}
if ($sort == 'name') {
sort($res, SORT_STRING);
}
return $res;
}
/**
* Summary of isOnline
* @param mixed $host Host
* @return int
*/
function isOnline($host)
{
$sqlQuery = "SELECT *
FROM pinghosts
WHERE HOSTNAME = '" . DBSafe($host) . "'
OR TITLE = '" . DBSafe($host) . "'";
$rec = SQLSelectOne($sqlQuery);
if (!$rec['STATUS'] || $rec['STATUS'] == 2) {
return 0;
} else {
return 1;
}
}
/**
* Summary of checkAccess
* @param mixed $object_type Object type
* @param mixed $object_id Object ID
* @return bool
*/
function checkAccess($object_type, $object_id)
{
global $access_rules_cached;
startMeasure('checkAccess');
if (!isset($access_rules_cached)) {
$all_rules=SQLSelect("SELECT OBJECT_TYPE, OBJECT_ID FROM security_rules");
foreach($all_rules as $rule) {
$access_rules_cached[$rule['OBJECT_TYPE'].$rule['OBJECT_ID']]=1;
}
}
if (!isset($access_rules_cached[$object_type.$object_id])) {
endMeasure('checkAccess');
return true;
}
include_once(DIR_MODULES . 'security_rules/security_rules.class.php');
$sc = new security_rules();
$result = $sc->checkAccess($object_type, $object_id);
endMeasure('checkAccess');
return $result;
}
/**
* Summary of registerError
* @param mixed $code Code (default 'custom')
* @param mixed $details Details (default '')
* @return void
*/
function registerError($code = 'custom', $details = '')
{
$e = new \Exception;
$backtrace = $e->getTraceAsString();
DebMes("Error registered (type: $code):\n" . $details . "\nBacktrace:\n" . $backtrace, 'error');
$code = trim($code);
if ($code == 'sql') {
return 0;
}
$error_rec = SQLSelectOne("SELECT * FROM system_errors WHERE CODE = '" . DBSafe($code) . "'");
if (!$error_rec['ID']) {
$error_rec['CODE'] = $code;
$error_rec['KEEP_HISTORY'] = 1;
$error_rec['ID'] = SQLInsert('system_errors', $error_rec);
}
$error_rec['LATEST_UPDATE'] = date('Y-m-d H:i:s');
@$error_rec['ACTIVE'] = (int)$error_rec['ACTIVE'] + 1;
SQLUpdate('system_errors', $error_rec);