-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathv2apiservice.php
More file actions
397 lines (327 loc) · 13.8 KB
/
v2apiservice.php
File metadata and controls
397 lines (327 loc) · 13.8 KB
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
<?php
class V2ApiService extends Rest
{
protected $table = "cdr";
protected $category = 'V2 Api Service';
public function get($f3, $from_child = true)
{
$db = $f3->get('DB');
$action = $f3->get('REQUEST.action') ?: 'cdr';
if ($action === 'cdr') {
$this->getCdrData($f3, $db);
} elseif ($action === 'player') {
$this->getPlayerData($f3);
} elseif ($action === 'cdr-monitor') {
$this->getCDRMonitor($f3, $db);
} elseif ($action === 'cdr-search') {
$this->getCdrDataSearch($f3, $db);
} elseif ($action === 'dst-monitor') {
$this->getCdrDataByDst($f3, $db);
} elseif ($action === 'channels') {
$this->getChannels();
} else {
$this->sendError('Invalid action.', 400);
}
}
private function getCdrDataByDst($f3, $db)
{
$dstNumber = $f3->get('REQUEST.dst') ?: 'all';
$extNumber = $f3->get('REQUEST.ext') ?: 'all';
if ($dstNumber === "all") {
$query = $db->exec(
"SELECT calldate, clid, src, dst, dcontext, channel, dstchannel, disposition, billsec, duration, uniqueid, recordingfile, cnum, cnam
FROM asteriskcdrdb.cdr
ORDER BY calldate DESC"
);
} else {
$query = $db->exec(
"SELECT calldate, clid, src, dst, dcontext, channel, dstchannel, disposition, billsec, duration, uniqueid, recordingfile, cnum, cnam
FROM asteriskcdrdb.cdr
WHERE dst = ? and (cnum=? OR cnam=? OR src=?)
ORDER BY calldate DESC",
[$dstNumber, $extNumber, $extNumber, $extNumber]
);
}
$export = [];
foreach ($query as $data) {
$dateParts = strtotime($data['calldate']);
$recordingFilePath = sprintf("/%s/%s/%s/%s", date("Y", $dateParts), date("m", $dateParts), date("d", $dateParts), $data['recordingfile']);
$data['recordingfile'] = $recordingFilePath;
$export[] = $data;
}
$this->sendSuccess($export);
}
private function getChannels()
{
$output = [];
exec("asterisk -rx 'core show channels'", $output);
if (count($output) > 4) {
$processedOutput = array_slice($output, 1, count($output) - 4);
} else {
$processedOutput = [];
}
$export = [];
foreach ($processedOutput as $line) {
if (preg_match('/(SIP\/(\d+)-\w+)\s+s@macro-dialout-trun\s+\w+\s+Dial\(SIP\/MMT-Out\/(\d+)/', $line, $matches)) {
$export[] = [
'channel' => $matches[1],
'extension' => $matches[2],
'destination' => $matches[3],
'status' => 'up'
];
} elseif (preg_match('/(SIP\/(\d+)-\w+)\s+s-BUSY@macro-dialout/', $line, $matches)) {
$export[] = [
'channel' => $matches[1],
'extension' => $matches[2],
'destination' => '-',
'status' => 'down'
];
} elseif (preg_match('/SIP\/MMT-Out-\w+\s+(\d+)@from-tr\w*\s+Ringing/', $line, $matches)) {
$export[] = [
'channel' => '-',
'extension' => '-',
'destination' => $matches[1],
'status' => 'ring'
];
}
}
$this->sendSuccess($export);
}
private function getCdrData($f3, $db)
{
$startDate = $f3->get('REQUEST.start_date') ?: '2025-01-01';
$endDate = $f3->get('REQUEST.end_date') ?: '2025-01-15';
$extension = $f3->get('REQUEST.extension') ?: 'all';
if (!$this->validateDate($startDate) || !$this->validateDate($endDate)) {
$this->sendError('Invalid date format. Use YYYY-MM-DD.', 400);
return;
}
if ($extension === "all") {
$query = $db->exec(
"SELECT calldate, clid, src, dst, dcontext, channel, dstchannel, disposition, billsec, duration, uniqueid, recordingfile, cnum, cnam FROM asteriskcdrdb.cdr WHERE calldate BETWEEN ? AND ? ORDER BY calldate DESC",
[$startDate, $endDate]
);
} else {
$query = $db->exec(
"SELECT calldate, clid, src, dst, dcontext, channel, dstchannel, disposition, billsec, duration, uniqueid, recordingfile, cnum, cnam FROM asteriskcdrdb.cdr WHERE (cnum=? OR cnam=? OR src=?) AND calldate BETWEEN ? AND ? ORDER BY calldate DESC",
[$extension, $extension, $extension, sprintf("%s 00:00:01", $startDate), sprintf("%s 23:59:59", $endDate)]
);
}
$export = [];
foreach ($query as $data) {
$dateParts = strtotime($data['calldate']);
$recordingFilePath = sprintf("/%s/%s/%s/%s", date("Y", $dateParts), date("m", $dateParts), date("d", $dateParts), $data['recordingfile']);
$data['recordingfile'] = $recordingFilePath;
$export[] = $data;
}
$this->sendSuccess($export);
}
private function getCdrDataSearch($f3, $db)
{
$startDate = $f3->get('REQUEST.start_date');
$endDate = $f3->get('REQUEST.end_date');
$extension = $f3->get('REQUEST.extension');
$calledNumber = $f3->get('REQUEST.called_number');
$disposition = $f3->get('REQUEST.disposition'); // Added disposition parameter
// Get pagination parameters
$page = (int)$f3->get('REQUEST.page') ?: 1;
$perPage = (int)$f3->get('REQUEST.per_page') ?: 20;
if (!$startDate || !$endDate || !$this->validateDate($startDate) || !$this->validateDate($endDate)) {
$this->sendError('Invalid date format or missing date parameters. Use YYYY-MM-DD.', 400);
return;
}
// Set the base condition to filter only records where both cnum and cnam are not empty
$conditions = "calldate BETWEEN ? AND ? AND cnum != '' AND cnam != ''";
$params = [sprintf("%s 00:00:01", $startDate), sprintf("%s 23:59:59", $endDate)];
if ($extension && $extension !== "all") {
$conditions .= " AND (cnum=? OR cnam=? OR src=?)";
$params = array_merge($params, [$extension, $extension, $extension]);
}
if ($calledNumber) {
$conditions .= " AND (dst=?)";
$params[] = $calledNumber;
}
// Add filter for disposition if it's provided
if ($disposition) {
$conditions .= " AND (disposition=?)";
$params[] = $disposition;
}
// Get total record count for pagination
$countSql = "SELECT COUNT(*) as total FROM asteriskcdrdb.cdr WHERE " . $conditions;
$totalRecords = $db->exec($countSql, $params)[0]['total'];
$totalPages = ceil($totalRecords / $perPage);
// Adjust page number if it's out of range
if ($page < 1) $page = 1;
if ($page > $totalPages && $totalPages > 0) $page = $totalPages;
$offset = ($page - 1) * $perPage;
// Main query with pagination
$sql = "SELECT * FROM asteriskcdrdb.cdr WHERE " . $conditions . " ORDER BY calldate DESC LIMIT ? OFFSET ?";
$params[] = $perPage;
$params[] = $offset;
$query = $db->exec($sql, $params);
// Process results
$data = [];
foreach ($query as $item) {
$dateParts = strtotime($item['calldate']);
// Make sure recordingfile exists before formatting the path
if (!empty($item['recordingfile'])) {
$recordingFilePath = sprintf("/%s/%s/%s/%s",
date("Y", $dateParts),
date("m", $dateParts),
date("d", $dateParts),
$item['recordingfile']
);
$item['recordingfile'] = $recordingFilePath;
}
$data[] = $item;
}
// Build pagination URLs
$baseUrl = $f3->get('PATH');
$queryParams = $f3->get('GET');
// Previous page URL
if ($page > 1) {
$prevQueryParams = $queryParams;
$prevQueryParams['page'] = $page - 1;
$prevPageUrl = $baseUrl . '?' . http_build_query($prevQueryParams);
} else {
$prevPageUrl = null;
}
// Next page URL
if ($page < $totalPages) {
$nextQueryParams = $queryParams;
$nextQueryParams['page'] = $page + 1;
$nextPageUrl = $baseUrl . '?' . http_build_query($nextQueryParams);
} else {
$nextPageUrl = null;
}
// First and last page URLs
$firstQueryParams = $queryParams;
$firstQueryParams['page'] = 1;
$firstPageUrl = $baseUrl . '?' . http_build_query($firstQueryParams);
$lastQueryParams = $queryParams;
$lastQueryParams['page'] = $totalPages > 0 ? $totalPages : 1;
$lastPageUrl = $baseUrl . '?' . http_build_query($lastQueryParams);
// Calculate from/to for pagination info
$from = $totalRecords ? ($offset + 1) : 0;
$to = min($offset + $perPage, $totalRecords);
// Prepare response
$response = [
'current_page' => $page,
'data' => $data,
'first_page_url' => $firstPageUrl,
'from' => $from,
'last_page' => $totalPages,
'last_page_url' => $lastPageUrl,
'next_page_url' => $nextPageUrl,
'path' => $baseUrl,
'per_page' => $perPage,
'prev_page_url' => $prevPageUrl,
'to' => $to,
'total' => $totalRecords
];
$this->sendSuccess($response);
}
private function getCDRMonitor($f3, $db)
{
$startDate = $f3->get('REQUEST.start_date') ?: date("Y-m-d 00:00:01", strtotime("-2 days"));
$endDate = $f3->get('REQUEST.end_date') ?: date("Y-m-d 23:59:01");
$extension = $f3->get('REQUEST.extension') ?: 'all';
if (!$this->validateDate($startDate) || !$this->validateDate($endDate)) {
$this->sendError('Invalid date format. Use YYYY-MM-DD.', 400);
return;
}
// Her zaman tüm disposition'ları grupla
if ($extension === 'all') {
$query = $db->prepare("
SELECT
disposition,
COUNT(*) AS total_calls,
SUM(duration) AS total_seconds,
SUM(duration)/60 AS total_minutes
FROM asteriskcdrdb.cdr
WHERE calldate BETWEEN ? AND ?
GROUP BY disposition
");
$query->execute([sprintf("%s 00:00:01", $startDate), sprintf("%s 23:59:59", $endDate)]);
} else {
// Belirli extension için tüm disposition'ları grupla
$query = $db->prepare("
SELECT
disposition,
COUNT(*) AS total_calls,
SUM(duration) AS total_seconds,
SUM(duration)/60 AS total_minutes
FROM asteriskcdrdb.cdr
WHERE (cnum=? OR cnam=? OR src=?)
AND calldate BETWEEN ? AND ?
GROUP BY disposition
");
$query->execute([$extension, $extension, $extension, sprintf("%s 00:00:01", $startDate), sprintf("%s 23:59:59", $endDate)]);
}
$results = $query->fetchAll(PDO::FETCH_ASSOC);
if (empty($results)) {
$results = [
[
'disposition' => 'NO DATA',
'total_calls' => 0,
'total_seconds' => 0,
'total_minutes' => 0
]
];
} else {
// Toplam sonuçları da ekle
$grandTotal = [
'disposition' => 'TOTAL',
'total_calls' => 0,
'total_seconds' => 0,
'total_minutes' => 0
];
foreach ($results as $result) {
$grandTotal['total_calls'] += $result['total_calls'];
$grandTotal['total_seconds'] += $result['total_seconds'];
$grandTotal['total_minutes'] += $result['total_minutes'];
}
$results[] = $grandTotal;
}
$this->sendSuccess($results);
}
private function getPlayerData($f3)
{
$file = $f3->get('REQUEST.file');
if (empty($file)) {
$this->sendError('File parameter is required for player action.', 400);
return;
}
if (file_exists("/var/spool/asterisk/monitor$file")) {
$filePath = "/var/spool/asterisk/monitor$file";
header('Content-Type: audio/mpeg');
header('Content-Length: ' . filesize($filePath));
header(sprintf('Content-Disposition: inline; filename="%s"', $file));
readfile($filePath);
} else if (file_exists("/var/spool/asterisk/monitor$file.mp3")) {
$filePath = "/var/spool/asterisk/monitor$file.mp3";
header('Content-Type: audio/mpeg');
header('Content-Length: ' . filesize($filePath));
header(sprintf('Content-Disposition: inline; filename="%s"', $file));
readfile($filePath);
} else {
echo 'File not found.';
}
}
private function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
private function sendSuccess($data)
{
header('Content-type: application/json');
echo json_encode(['status' => 'success', 'data' => $data]);
}
private function sendError($message, $code = 500)
{
header('Content-type: application/json');
http_response_code($code);
echo json_encode(['status' => 'error', 'message' => $message]);
}
}