Passed
Push — develop ( e7e772...77fa2f )
by Портнов
04:29
created

SelectCDR::getTmpDir()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 21
rs 9.8333
cc 4
nc 5
nop 0
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright © 2017-2021 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace MikoPBX\Core\Workers\Libs\WorkerCallEvents;
21
22
23
use MikoPBX\Common\Models\CallDetailRecords;
24
use MikoPBX\Common\Models\CallDetailRecordsTmp;
25
use MikoPBX\Core\System\Util;
26
use Phalcon\Di;
27
use phpDocumentor\Reflection\Utils;
28
use Throwable;
29
30
class SelectCDR
31
{
32
    public static function execute($filter):string
33
    {
34
35
        if(self::filterNotValid($filter)){
36
            return '[]';
37
        }
38
39
        $res    = null;
40
        try {
41
            if (isset($filter['miko_tmp_db'])) {
42
                $res = CallDetailRecordsTmp::find($filter);
43
            } else {
44
                $res = CallDetailRecords::find($filter);
45
            }
46
            $res_data = json_encode($res->toArray());
47
        } catch (Throwable $e) {
48
            $res_data = '[]';
49
        }
50
51
        if ($res && isset($filter['add_pack_query'])) {
52
            $arr = [];
53
            foreach ($res->toArray() as $row) {
54
                $arr[] = $row[$filter['columns']];
55
            }
56
            $filter['add_pack_query']['bind'][$filter['columns']] = $arr;
57
58
            if(self::filterNotValid($filter['add_pack_query'])){
59
                return '[]';
60
            }
61
62
            try {
63
                $res      = CallDetailRecords::find($filter['add_pack_query']);
64
                $res_data = json_encode($res->toArray(), JSON_THROW_ON_ERROR);
65
            } catch (Throwable $e) {
66
                $res_data = '[]';
67
            }
68
        }
69
70
        if (isset($filter['miko_result_in_file'])) {
71
            [$tmpDir, $downloadCacheDir] = self::getTmpDir();
72
            $fileBaseName = md5(microtime(true));
73
            // temp- в названии файла необходямо, чтобы файл был автоматом удален через 5 минут.
74
            $filename     = $tmpDir.'/temp-'.$fileBaseName;
75
            file_put_contents($filename, $res_data);
76
77
            if(!empty($downloadCacheDir)){
78
                $linkName     = $downloadCacheDir.'/'.$fileBaseName;
79
                // Для автоматического удаления файла.
80
                // Файл с такой ссылкой будет удален через 5 минут по cron.
81
                Util::createUpdateSymlink($filename, $linkName,true);
82
            }
83
            Util::addRegularWWWRights($filename);
84
            $res_data = json_encode($filename);
85
        }
86
87
        return $res_data;
88
89
    }
90
91
    /**
92
     * Проверка фильтра на корректность bind параметров.
93
     *
94
     * @param $filter
95
     *
96
     * @return bool
97
     */
98
    private static function filterNotValid($filter):bool{
99
        $haveErrors = false;
100
        $validValue = ['0',''];
101
        if(isset($filter['bind'])){
102
            if(is_array($filter)){
103
                foreach ($filter['bind'] as $bindValue) {
104
                    if(empty($bindValue) && !in_array($bindValue, $validValue, true)){
105
                        $haveErrors = true;
106
                    }
107
                }
108
            }else{
109
                $haveErrors = true;
110
            }
111
        }
112
        return $haveErrors;
113
    }
114
115
    private static function getTmpDir():array
116
    {
117
        $downloadCacheDir = '';
118
        $dirName    = '/tmp/';
119
        $di         = Di::getDefault();
120
        if($di){
121
            $dirsConfig = $di->getShared('config');
122
            $tmoDirName   = $dirsConfig->path('core.tempDir').'/SelectCdrService';
123
            Util::mwMkdir($tmoDirName, true);
124
            if(file_exists($tmoDirName)){
125
                $dirName = $tmoDirName;
126
            }
127
128
            $downloadCacheDir = $dirsConfig->path('www.downloadCacheDir');
129
            if(!file_exists($downloadCacheDir)){
130
                $downloadCacheDir = '';
131
            }
132
        }
133
134
135
        return [$dirName,$downloadCacheDir];
136
    }
137
}