/
Debug.class.php
859 lines (659 loc) · 31 KB
/
Debug.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
<?php
/**
* Клас 'log_Debug' - Мениджър за запис на действията на потребителите
*
*
* @category bgerp
* @package core
*
* @author Yusein Yuseinov <yyuseinov@gmail.com>
* @copyright 2006 - 2018 Experta OOD
* @license GPL 3
*
* @since v 0.1
* @link
*/
class log_Debug extends core_Manager
{
/**
* Заглавие на мениджъра
*/
public $title = 'Дебъг лог';
/**
* Кой може да листва и разглежда?
*/
public $canRead = 'no_one';
/**
* Кой може да добавя, редактира и изтрива?
*/
public $canWrite = 'no_one';
/**
* Кой може да го разглежда?
*/
public $canList = 'debug';
/**
* Кой може да репортва грешките
*/
public $canReport = 'user';
/**
* Плъгини и MVC класове за предварително зареждане
*/
public $loadList = 'plg_SystemWrapper';
/**
* Връща линк към създаване на сигнал от грешката
*
* @param string $debugFile
* @param string $btnName
* @param string $icon
* @param NULL|string $class
*
* @return core_ET
*/
public static function getReportLink($debugFile, $btnName = 'Сигнал', $icon = 'img/16/debug_bug.png', $class = null)
{
$btnName = tr($btnName);
$urlArr = array('log_Debug', 'report', 'debugFile' => $debugFile, 'ret_url' => true);
$url = toUrl($urlArr);
// Ако е мобилен/тесем режим
if (Mode::is('screenMode', 'narrow')) {
// Парамтери към отварянето на прозореца
$args = 'resizable=yes,scrollbars=yes,status=no,location=no,menubar=no,location=no';
} else {
$args = 'width=450,height=600,resizable=yes,scrollbars=yes,status=no,location=no,menubar=no,location=no';
}
$attr = array('onClick' => "openWindow('{$url}', 'bgerp_tracer_report', '{$args}'); return false;", 'title' => 'Изпращане на сигнал към разработчиците на bgERP');
if ($icon) {
$attr['ef_icon'] = $icon;
}
if ($class) {
$attr['class'] = $class;
}
$attr['target'] = '_blank';
$link = ht::createLink($btnName, $urlArr, false, $attr);
return $link;
}
/**
* Показва дебъг лога
*/
public function act_Default()
{
$this->requireRightFor('list');
if (Mode::is('screenMode', 'wide')) {
$tpl = new ET(tr('|*<div class="headerLine">[#SHOW_DEBUG_INFO#]<!--ET_BEGIN CREATED_DATE--><span style="margin-left: 20px;">[#CREATED_DATE#]</span><!--ET_END CREATED_DATE--><div class="aright"><span class="debugActions"> [#SIGNAL#]</span> <span class="debugActions"> [#DOWNLOAD_FILE#]</span> <span class="debugActions">[#BEFORE_LINK#]</span><span class="debugActions">[#AFTER_LINK#] </span></div><div style="clear: both;"></div></div><div class="debugHolder"><div class="debugList">[#LIST_FILE#]</div><div class="debugPreview">[#ERR_FILE#]</div></div>'));
} else {
$tpl = new ET(tr('|*<div class="headerLine">[#SHOW_DEBUG_INFO#]<!--ET_BEGIN CREATED_DATE--><span>[#CREATED_DATE#]</span><!--ET_END CREATED_DATE--><div class="aright"><span class="debugActions"> [#SIGNAL#]</span> <span class="debugActions"> [#DOWNLOAD_FILE#]</span> <span class="debugActions">[#BEFORE_LINK#]</span><span class="debugActions">[#AFTER_LINK#] </span></div><div style="clear: both;"></div></div><div class="debugList">[#LIST_FILE#]</div><div class="debugPreview">[#ERR_FILE#]</div>'));
}
// Подготвяме листовия изглед за избор на дебъг файл
$data = new stdClass();
$data->query = $this->getQuery();
$this->prepareListFilter($data);
$data->listFilter->layout = "<form [#FORM_ATTR#] >[#FORM_FIELDS#][#FORM_TOOLBAR#][#FORM_HIDDEN#]</form>\n";
$data->listFilter->FNC('search', 'varchar', 'caption=Файл, input, silent');
$data->listFilter->FNC('debugFile', 'varchar', 'caption=Файл, input=hidden, silent');
$data->listFilter->showFields = 'search, debugFile';
$data->listFilter->toolbar->addSbBtn(' ', 'default', 'id=filter', 'ef_icon = img/16/find.png');
$tplList = new ET(tr('|*[#ListFilter#]<!--ET_BEGIN DEBUG_LINK--><div class="linksGroup">[#DEBUG_LINK#]</div><!--ET_END DEBUG_LINK-->'));
$data->listFilter->title = 'Дебъг';
$data->listFilter->view = 'horizontal';
$data->listFilter->input(null, true);
$tplList->append($this->renderListFilter($data), 'ListFilter');
$otherFilesFromSameHit = array();
$debugFileName = null;
if ($debugFile = Request::get('debugFile')) {
Mode::set('stopLoggingDebug', true);
$debugFileName = $debugFile . '.debug';
}
$before = 25;
$after = 25;
$oDebugFileName = $debugFileName;
$fPathStr = $this->getDebugFilePath($debugFileName, false);
if (!file_exists($fPathStr) && strpos($debugFile, 'x') === false) {
$dFileNameArr = explode('_', $debugFile, 2);
$debugFileName = 'x_' . $dFileNameArr[1] . '_x.debug';
}
// Вземаме файловете, които да се показват
$fArr = $this->getDebugFilesArr($debugFileName, $before, $after, $otherFilesFromSameHit, $data->listFilter->rec->search);
if ($oDebugFileName != $debugFileName) {
list($debugFile) = explode('.', $debugFileName);
}
$fArrCnt = count($fArr);
$fLink = '';
if ($fArrCnt > 1) {
$fArr = array_reverse($fArr);
}
// Показваме линкове за навигиране
$aPos = array_search($debugFileName, array_keys($fArr));
$otherLinkUrl = array($this, 'Default', 'search' => $data->listFilter->rec->search);
if ($debugFile) {
// Ако има следващ дебъг файл
$bLinkArr = array();
if ($fArrCnt != ($aPos + 1)) {
if ($bPosArr = array_slice($fArr, $aPos + 1, 1)) {
if ($fNameBefore = key($bPosArr)) {
$fNameBefore = fileman::getNameAndExt($fNameBefore);
if ($fNameBefore['name']) {
$bLinkArr = $otherLinkUrl;
$bLinkArr['debugFile'] = $fNameBefore['name'];
}
}
}
}
$aLink = ht::createLink(tr(' << '), $bLinkArr);
$tpl->replace($aLink, 'BEFORE_LINK');
// Ако има предишен дебъг файл
$aLinkArr = array();
if ($aPos) {
if ($aPosArr = array_slice($fArr, $aPos - 1, 1)) {
if ($fNameAfter = key($aPosArr)) {
$fPathStr = $this->getDebugFilePath($fNameAfter, false);
if (DEBUG_FATAL_ERRORS_FILE != $fPathStr) {
$fNameAfter = fileman::getNameAndExt($fNameAfter);
if ($fNameAfter['name']) {
$aLinkArr = $otherLinkUrl;
$aLinkArr['debugFile'] = $fNameAfter['name'];
}
}
}
}
}
$bLink = ht::createLink(tr(' >> '), $aLinkArr);
$tpl->replace($bLink, 'AFTER_LINK');
}
// Показваме всички файлове
foreach ($fArr as $fNameWithExt => $dummy) {
list($fName) = explode('.', $fNameWithExt, 2);
$fPathStr = $this->getDebugFilePath($fName);
if (DEBUG_FATAL_ERRORS_FILE == $fPathStr) {
continue;
}
$cls = 'debugLink';
$linkUrl = array($this, 'Default', 'debugFile' => $fName);
if ($data->listFilter->rec->search) {
$linkUrl['search'] = $data->listFilter->rec->search;
}
if ($fName == $debugFile) {
$cls .= ' current';
$linkUrl = array();
} elseif ($otherFilesFromSameHit[$fNameWithExt]) {
$cls .= ' same';
}
$fLink .= ht::createLink($fName, $linkUrl, false, array('class' => $cls, 'target' => '_parent'));
if ($mCnt++ > 200) {
break;
}
}
$tplList->append($fLink, 'DEBUG_LINK');
$tpl->append($tplList, 'LIST_FILE');
$tpl->append('bgERP tracer', 'PAGE_TITLE');
$this->logInAct('Листване', null, 'read');
// Показва съдъражаниете на дебъга, ако е избран файла
if ($debugFile) {
$fPath = $this->getDebugFilePath($debugFile);
if ($fPath) {
$dUrl = fileman_Download::getDownloadUrl($fPath, 1, 'path');
if ($dUrl) {
$tpl->replace(ht::createLink(tr('Сваляне'), $dUrl, null, 'ef_icon=img/16/debug_download.png'), 'DOWNLOAD_FILE');
}
$tpl->replace($this->getDebuFileInfo($fPath, $rArr), 'ERR_FILE');
$tpl->replace($rArr['_info'], 'SHOW_DEBUG_INFO');
if (is_file($fPath) && is_readable($fPath)) {
$date = @filemtime($fPath);
$date = dt::timestamp2Mysql($date);
$date = dt::mysql2verbal($date, 'smartTime');
$tpl->replace($date, 'CREATED_DATE');
}
}
if ($this->haveRightFor('report')) {
$singal = $this->getReportLink($debugFile);
$tpl->append($singal, 'SIGNAL');
}
Mode::set('wrapper', 'page_Empty');
$tpl->push('css/debug.css', 'CSS');
// Плъгин за лайаута
jquery_Jquery::run($tpl, 'debugLayout();');
// Рендираме страницата
return $tpl;
}
// Рендираме страницата
return $this->renderWrapping($tpl);
}
/**
* Екшън за репортване на грешката
*
* @return Redirect|ET
*/
public function act_Report()
{
$this->requireRightFor('report');
$form = cls::get('core_Form');
$form->FNC('title', 'varchar(128)', 'caption=Заглавие, mandatory, input');
$form->FNC('description', 'text(rows=10)', 'caption=Описание, mandatory, input');
$form->FNC('name', 'varchar(64)', 'caption=Данни за обратна връзка->Име, mandatory, input');
$form->FNC('email', 'email', 'caption=Данни за обратна връзка->Имейл, mandatory, input');
$form->FNC('debugFile', 'varchar(64)', 'caption=Данни за обратна връзка->Файл, silent, input=hidden');
$img = ht::createElement('img', array('src' => sbf('img/16/headset.png', '')));
$form->title = '|*' . $img . ' |Сигнал към разработчиците на bgERP';
$form->toolbar->addSbBtn('Изпрати', 'save', 'id=save, ef_icon = img/16/ticket.png,title=Изпращане на сигнала');
$retUrl = getRetUrl();
if (empty($retUrl)) {
$retUrl = array('Portal', 'Show');
}
$form->toolbar->addBtn('Отказ', $retUrl, 'id=cancel, ef_icon = img/16/close-red.png,title=Отказ, onclick=self.close();');
$email = email_Inboxes::getUserEmail();
if (!$email) {
$email = core_Users::getCurrent('email');
}
list($user, $domain) = explode('@', $email);
$name = core_Users::getCurrent('names');
$form->setDefault('email', $email);
$form->setDefault('name', $name);
$form->input(null, true);
$form->setDefault('title', $_SERVER['HTTP_HOST']);
$form->input();
Mode::set('wrapper', 'page_Dialog');
if ($form->isSubmitted()) {
$dataArr = array();
$fPath = $this->getDebugFilePath($form->rec->debugFile);
if ($fPath && is_file($fPath)) {
$data = @file_get_contents($fPath);
if ($data) {
$dataArr['data'] = gzcompress($data);
$dataArr['fName'] = $form->rec->debugFile;
}
}
$dataArr['name'] = $form->rec->name;
$dataArr['email'] = $form->rec->email;
$dataArr['description'] = gzcompress($form->rec->description);
$dataArr['Lg'] = core_Lg::getCurrent();
$dataArr['streamReport'] = true;
$dataArr['title'] = $form->rec->title;
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($dataArr),
),
);
$context = stream_context_create($options);
$url = help_Setup::get('BGERP_SUPPORT_URL', true);
$resStr = @file_get_contents($url, false, $context);
if ($resStr == 'OK') {
$tpl = new ET();
jquery_Jquery::run($tpl, 'self.close();');
} else {
$form->setError('description', 'Възникна грешка при изпращане на сигнала.');
$tpl = $form->renderHtml();
}
$this->logInAct('Изпращане на сигнал');
} else {
$tpl = $form->renderHtml();
}
// Добавяме клас към бодито
$tpl->append('dialog-window', 'BODY_CLASS_NAME');
$tpl->append("<button onclick='javascript:window.close();' class='dialog-close'>X</button>");
return $tpl;
}
/**
* Показва дебъг страницата
*
* @param string $fPath
* @param array $rArr
*/
public function getDebuFileInfo($fPath, &$rArr = array())
{
expect($fPath);
// Рендираме лога
if (is_file($fPath) && is_readable($fPath)) {
$content = @file_get_contents($fPath);
$rArr = @json_decode($content);
// Вероятно не е json, a e сериализирано
if (!$rArr) {
list(, , $content) = explode(' ', $content, 3);
$rArr = unserialize($content);
}
if ($rArr) {
$rArr = (array) $rArr;
$rArr['update'] = false;
$bDebugTime = null;
if ($rArr['debugTime']) {
$bDebugTime = core_Debug::$debugTime;
core_Debug::$debugTime = $rArr['debugTime'];
}
$bTimers = null;
if ($rArr['timers']) {
$bTimers = core_Debug::$timers;
core_Debug::$timers = (array) $rArr['timers'];
}
if (!$rArr['contex']) {
$rArr['contex'] = (object) $rArr['SERVER'];
} else {
$rArr['contex'] = (object) $rArr['contex'];
if ($rArr['SERVER']) {
$rArr['contex']->_SERVER = $rArr['SERVER'];
}
}
if ($rArr['GET']) {
$rArr['contex']->_GET = $rArr['GET'];
}
if ($rArr['POST']) {
$rArr['contex']->_POST = $rArr['POST'];
}
if (!$rArr['errType']) {
if ($rArr['_debugCode']) {
$rArr['header'] .= $rArr['_debugCode'];
}
if ($rArr['_Ctr']) {
$rArr['header'] .= ' ' . $rArr['_Ctr'];
}
if ($rArr['_Act']) {
$rArr['header'] .= ' » ' . $rArr['_Act'];
}
if ($rArr['_executionTime']) {
$rArr['header'] .= ' (' . number_format($rArr['_executionTime'], 2) . ' s)';
}
if (!trim($rArr['header'])) {
if ($rArr['GET']) {
$rArr['header'] = $rArr['GET']->virtual_url;
}
}
if ($rArr['_debugCode'] && ($rArr['_debugCode']{0} == 2 || $rArr['_debugCode']{0} == 8)) {
$rArr['headerCls'] = 'okMsg';
} else {
$rArr['headerCls'] = 'warningMsg';
}
}
$rArr['_showDownloadUrl'] = false;
Mode::set('debugExecutionTime', $rArr['_executionTime']);
Mode::set('showDebug', true);
$res = core_Debug::getDebugPage($rArr);
Mode::set('showDebug', false);
Mode::set('debugExecutionTime', null);
if (isset($bDebugTime)) {
core_Debug::$debugTime = $bDebugTime;
}
if (isset($bTimers)) {
core_Debug::$timers = $bTimers;
}
}
}
if (!$res) {
$res = '<p style="padding-left: 20px">' . tr('Възникна грешка при показване на') . ' ' . $fPath . '</p>';
}
return $res;
}
/**
* Връща името/пътя на дебъг файла
*
* @param string $errCode
* @param string $fileName
* @param bool $addPath
* @param bool $addExt
* @param NULL|int $cu
*
* @return string
*/
public static function getDebugLogFile($errCode, $fileName = '', $addPath = true, $addExt = true, $cu = null)
{
if (!isset($cu)) {
$cu = (int) @core_Users::getCurrent();
}
$cu = str_pad($cu, 5, '0', STR_PAD_LEFT);
list(, $dFileName) = explode('_', $fileName, 2);
$debugFile = $errCode . '_' . $cu . '_' . $dFileName;
$debugPath = self::getDebugFilePath($debugFile, $addExt, $addPath);
return $debugPath;
}
/**
* Връща пътя до дебъг файла
*
* @param string $debugFile
* @param bool $addExt
* @param bool $addPath
*
* @return string
*/
protected static function getDebugFilePath($debugFile, $addExt = true, $addPath = true)
{
$fPath = '';
if ($addPath) {
$fPath = rtrim(DEBUG_FATAL_ERRORS_PATH, '/') . '/';
}
$fPath .= $debugFile;
if ($addExt) {
$fPath .= '.debug';
}
return $fPath;
}
/**
* Връща файловете в дебъг директорията
*
* @param NULL|string $fName
* @param NULL|int $before
* @param NULL|int $after
* @param array $otherFilesFromSameHitArr
* @param NULL|string $search
*
* @return array
*/
protected static function getDebugFilesArr(&$fName = null, $before = null, $after = null, &$otherFilesFromSameHitArr = array(), $search = null)
{
$fArr = array();
if (!defined('DEBUG_FATAL_ERRORS_PATH')) {
return $fArr;
}
$dir = DEBUG_FATAL_ERRORS_PATH;
try {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY);
$iterator->setFlags(FilesystemIterator::NEW_CURRENT_AND_KEY | FilesystemIterator::SKIP_DOTS);
} catch (ErrorException $e) {
self::logNotice('Не може да се обходи директорията', $dir);
return $fArr;
} catch (Throwable $e) {
self::logNotice('Не може да се обходи директорията', $dir);
return $fArr;
}
// Намираме шаблонното име от файла
$fNameTemplate = null;
if (isset($fName)) {
list($fNameTemplate) = explode('.', $fName, 2);
$fNameTemplateArr = explode('_', $fNameTemplate);
unset($fNameTemplateArr[0]);
unset($fNameTemplateArr[1]);
unset($fNameTemplateArr[6]);
foreach ($fNameTemplateArr as $k => $t) {
if ($t == 'x') {
unset($fNameTemplateArr[$k]);
}
}
$fNameTemplate = implode('_', $fNameTemplateArr);
}
// Намираме всички файлове и им вземаме времето на създаване
while ($iterator->valid()) {
try {
$mTime = null;
$fileName = $iterator->key();
$path = $iterator->current()->getPath();
@$currentDepth = $iterator->getDepth();
if (($currentDepth < 1) && !$iterator->isDir()) {
$canShow = true;
$search = trim($search);
if ($search) {
if (strpos($fileName, $search) === false) {
$canShow = false;
}
}
// Ако се търси определен файл и отговаря на изискванията - го показваме
if ($canShow) {
$mTime = $iterator->current()->getMTime();
$fArr[$fileName] = $mTime . '|' . $fileName;
}
if ($fName) {
if (strpos($fileName, $fNameTemplate)) {
if ($fileName != $fName) {
if (!isset($mTime)) {
$mTime = $iterator->current()->getMTime();
}
// Ако има друг файл от същия хит
$otherFilesFromSameHitArr[$fileName] = $mTime . '|' . $fileName;
}
}
}
}
} catch (Exception $e) {
// Не правим нищо
} catch (Throwable $e) {
// Не правим нищо
}
$iterator->next();
}
if (!empty($fArr)) {
if (($before || $after)) {
if ($fName) {
// Премахваме файловете от същия хит - за да ги добавим по-късно
if (!empty($otherFilesFromSameHitArr)) {
$pregPattern = '/^' . preg_quote($fName, '/') . '$/';
$pregPattern = str_replace('x', '.+', $pregPattern);
$foundFName = false;
if ($fArr[$fName]) {
$foundFName = true;
}
foreach ($otherFilesFromSameHitArr as $sameFName => $time) {
// Ако в името има неизвестни стойности, намираме файла от системата
if (!$foundFName && preg_match($pregPattern, $sameFName)) {
$fName = $sameFName;
$fArr[$fName] = $time;
$foundFName = true;
unset($otherFilesFromSameHitArr[$fName]);
continue;
}
unset($fArr[$sameFName]);
}
}
asort($fArr);
$aPos = array_search($fName, array_keys($fArr));
$fArrCnt = count($fArr);
$nArr = $fArr;
if ($fArrCnt > ($before + $after)) {
if ($fArrCnt > ($aPos + $before)) {
$bPos = $aPos - $before;
} else {
$bPos = $fArrCnt - $after - $before;
}
$bPos = max(0, $bPos);
$nArr = array_slice($fArr, $bPos, $after + $before);
}
// Добавяме файловете от същия хит
if (!empty($otherFilesFromSameHitArr)) {
$nArr += $otherFilesFromSameHitArr;
asort($nArr);
}
} else {
asort($fArr);
// Ако няма зададен файл, показваме по ограничение
$nArr = array_slice($fArr, -1 * ($before + $after));
}
$fArr = $nArr;
}
}
return $fArr;
}
/**
* Изпълнява се след подготовката на ролите, които могат да изпълняват това действие.
*
* @param core_Mvc $mvc
* @param string $requiredRoles
* @param string $action
* @param stdClass $rec
* @param int $userId
*/
public static function on_AfterGetRequiredRoles($mvc, &$requiredRoles, $action, $rec = null, $userId = null)
{
if ($action == 'list' && $requiredRoles != 'no_one') {
if (!isDebug()) {
$requiredRoles = 'no_one';
}
if ($requiredRoles != 'no_one') {
if (!haveRole('user', $userId)) {
$requiredRoles = 'no_one';
}
}
if ($requiredRoles != 'no_one') {
if (!defined('DEBUG_FATAL_ERRORS_PATH')) {
$requiredRoles = 'no_one';
}
}
}
if ($action == 'report' && $requiredRoles != 'no_one') {
if (!defined('DEBUG_FATAL_ERRORS_PATH')) {
$requiredRoles = 'no_one';
}
if ($requiredRoles != 'no_one') {
$supportUrl = help_Setup::get('BGERP_SUPPORT_URL', true);
if (!$supportUrl || strpos($supportUrl, '//') === false) {
$requiredRoles = 'no_one';
}
}
}
}
/**
* Крон метод за изтриване на старите дебъг файлове
*/
public static function cron_clearOldDebugFiles()
{
$me = cls::get(get_called_class());
$fArr = $me->getDebugFilesArr();
if (empty($fArr)) {
return ;
}
// Колко часа да се пазят грешките в директорията
$delTimeMapArr = array('def' => 30, '000' => 30, '0' => 100, '150' => 100, '2' => 5, '8' => 5, '5' => 100, '404' => 5);
$nowT = dt::mysql2timestamp();
// Преобразуваме часовете в минути валидност
$delTimeMapArr = array_map(function ($h) {
$nowT = dt::mysql2timestamp();
return ($nowT - ($h * 60 * 60));
}, $delTimeMapArr);
$cnt = 0;
$allCnt = count($fArr);
foreach ($fArr as $fName => $cDate) {
list($v) = explode('_', $fName, 2);
$delOn = $delTimeMapArr[$v];
if (!$delOn) {
$delOn = $delTimeMapArr[$v{0}];
}
if (!$delOn) {
$delOn = $delTimeMapArr['def'];
}
list($cDate) = explode('|', $cDate, 2);
if ($delOn < $cDate) {
continue;
}
$fPath = $me->getDebugFilePath($fName, false);
$cnt++;
if (!@unlink($fPath)) {
$me->logWarning("Грешка при изтриване на файла: '{$fPath}'");
}
}
if ($cnt) {
$me->logNotice("Изтрити дебъг файлове {$cnt} от {$allCnt}");
}
}
/**
* Начално установяване на модела
*/
public static function on_AfterSetupMVC($mvc, &$res)
{
// Нагласяване на Крон за изтриване на старите дебъг файлов
$rec = new stdClass();
$rec->systemId = 'Clear Old Debug Files';
$rec->description = 'Изтриване на старите дебъг файлове';
$rec->controller = $mvc->className;
$rec->action = 'clearOldDebugFiles';
$rec->period = 24 * 60;
$rec->offset = rand(60, 180); // от 1h до 3h
$rec->delay = 0;
$rec->timeLimit = 600;
$res .= core_Cron::addOnce($rec);
}
}