summaryrefslogtreecommitdiff
path: root/fs_selfservice/fri/modules/callmonitor.module
blob: 36f5f285acda5630fa51af0aa3cbdc9c2cc321e0 (plain)
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
<?php

/**
 * @file
 * Functions for the interface to the call monitor recordings
 */

/**
  * Class for Callmonitor
  */
class Callmonitor {

  /*
   * rank (for prioritizing modules)
   */
  function rank() {

    $rank = 2;
    return $rank;
  }

  /*
   * init
   */
  function init() {
  }

  /*
   * Adds menu item to nav menu
   *
   * @param $args
   *   Common arguments
   */
  function navMenu($args) {

    $ret .= "<p><small><small><a href='" . $_SESSION['ARI_ROOT'] . "?m=Callmonitor&f=display'>" . _("Call History") . "</a></small></small></p><br>";

    return $ret;
  }

  /*
   * Acts on the selected call monitor recordings in the method indicated by the action and updates page
   *
   * @param $args
   *   Common arguments
   */
  function recAction($args) {

    // args
    $m = getArgument($args,'m');
    $a = getArgument($args,'a');
    $q = getArgument($args,'q');
    $start = getArgument($args,'start');
    $span = getArgument($args,'span');
    $order = getArgument($args,'order');
    $sort = getArgument($args,'sort');
    $duration_filter = getArgument($args,'duration_filter');

    // get files
    $files = array();
    foreach($_REQUEST as $key => $value) {
      if (preg_match('/selected/',$key)) {
        array_push($files, $value);
      }
    }

    if ($a=='delete') {
      $this->deleteRecData($files);
    }

    if ($a=='ignore') {

      $start = 0;

      setcookie("ari_duration_filter", $duration_filter, time()+365*24*60*60);
    }

    // redirect to see updated page
    $ret .= "
      <head>
        <script>
        <!--
          window.location = \"" . $_SESSION['ARI_ROOT'] . "?m=" . $m . "&q=" . $q . "&start=" . $start . "&span=" . $span . "&order=" . $order . "&sort=" . $sort . "&duration_filter=" . $duration_filter . "\"
        // -->
        </script>
      </head>";

    return $ret;
  }

  /*
   * Displays stats page
   *
   * @param $args
   *   Common arguments
   */
  function display($args) {

    global $ASTERISK_CALLMONITOR_PATH;
    global $CALLMONITOR_ALLOW_DELETE;
    global $AJAX_PAGE_REFRESH_ENABLE;

    $display = new DisplaySearch();

    // get the search string
    $m = getArgument($args,'m');
    $f = getArgument($args,'f');
    $q = getArgument($args,'q');
    $start = getArgument($args,'start');
    $span = getArgument($args,'span');
    $order = getArgument($args,'order');
    $sort = getArgument($args,'sort');
    $duration_filter = getArgument($args,'duration_filter');

    $start = $start=='' ? 0 : $start;
    $span = $span=='' ? 15 : $span;
    $order = $order=='' ? 'calldate' : $order;
    $sort = $sort=='' ? 'desc' : $sort;

    $displayname = $_SESSION['ari_user']['displayname'];
    $extension = $_SESSION['ari_user']['extension'];

    // get data
    $record_count = $this->getCdrCount($q,$duration_filter);
    $data = $this->getCdrData($q,$duration_filter,$start,$span,$order,$sort);

    // get the call monitor recording files
    $paths = split(';',$ASTERISK_CALLMONITOR_PATH);
    foreach($paths as $key => $path) {
      if (!is_dir($path)) {
        $_SESSION['ari_error'] .= sprintf(_("Path is not a directory: %s"),$path) . "<br>";
      }
    }
    $recordings = $this->getRecordings($ASTERISK_CALLMONITOR_PATH,$data);

    // build controls
    if ($CALLMONITOR_ALLOW_DELETE) {
      $controls .= "
        <button class='infobar' type='submit' onclick=\"document.callmonitor_form.a.value='delete'\">
        " . _("delete") . "
        </button>
        &nbsp;";
    }

    $controls .= " 
      <small>" . _("duration") . "</small>
      <input name='duration_filter' type='text' size=4 maxlength=8 value='" . $_COOKIE['ari_duration_filter'] . "'>
      <button class='infobar' type='submit' onclick=\"document.callmonitor_form.a.value='ignore'\">
      " . _("ignore") . "
      </button>";

    // table header
    if ($CALLMONITOR_ALLOW_DELETE) {
      $recording_delete_header = "<th></th>";
    }

    $fields[0]['field'] = "calldate";
    $fields[0]['text'] = _("Date");
    $fields[1]['field'] = "calldate";
    $fields[1]['text'] = _("Time");
    $fields[2]['field'] = "clid";
    $fields[2]['text'] = _("Caller ID");
    $fields[3]['field'] = "src";
    $fields[3]['text'] = _("Source");
    $fields[4]['field'] = "dst";
    $fields[4]['text'] = _("Destination");
    $fields[5]['field'] = "dcontext";
    $fields[5]['text'] = _("Context");
    $fields[6]['field'] = "duration";
    $fields[6]['text'] = _("Duration");

    $i = 0;
    while ($fields[$i]) {

      $field = $fields[$i]['field'];
      $text = $fields[$i]['text'];
      if ($order==$field) { 
        if ($sort=='asc') {
          $currentSort = 'desc';
          $arrowImg = "<img src='theme/images/arrow-asc.gif' alt='sort'>";
        }
        else {
          $currentSort = 'asc';
          $arrowImg = "<img src='theme/images/arrow-desc.gif' alt='sort'>";
        }   

        if ($i==1) {
          $arrowImg = '';
        }    
      }
      else {
        $arrowImg = '';
        $currentSort = 'desc';
      }

      $unicode_q = urlencode($q);
      $recording_header .= "<th><a href=" .  $_SESSION['ARI_ROOT'] . "?m=" . $m . "&f=" . $f . "&q=" . $unicode_q . "&order=" . $field . "&sort=" . $currentSort . ">" . $text . $arrowImg . "</a></th>";

      $i++;
    }
    $recording_header .= "<th>" . _("Monitor") . "</th>";

    // table body
    foreach($data as $key=>$value) {

      // recording file
      $recording = $recordings[$value['uniqueid'] . $value['calldate']];

      // date and time
      $buf = split(' ', $value[calldate]);
      $date = $buf[0];
      $time = $buf[1];

      // recording delete checkbox
      if ($CALLMONITOR_ALLOW_DELETE) {
        $recording_delete_checkbox = "<td class='checkbox'><input type=checkbox name='selected" . ++$i . "' value=" . $recording . "></td>";
      }

      $recordingLink = '';
      if (is_file($recordings[$value['uniqueid'] . $value['calldate']])) {
        $recordingLink = "<a href='#' onClick=\"javascript:popUp('misc/recording_popup.php?recording=" . $recording . "&date=" . $date . "&time=" . $time . "'); return false;\">" . _("play") . "</a>";
      }
    
      $recording_body .= "<tr>
                       " . $recording_delete_checkbox . "
	               <td width=70>" . $date . "</td>
	               <td>" . $time . "</td>
	               <td>" . $value[clid] . "</td>
	               <td>" . $value[src] . "</td>
	               <td>" . $value[dst] . "</td>
	               <td>" . $value[dcontext] . "</td>
	               <td width=90>" . $value[duration] . " sec</td>
	               <td>" . $recordingLink . "</td>
	             </tr>";
    }
    if (!count($data)) {
      $recording_body .= "<tr></tr>";
    }

    // options
    $url_opts = array();
    $url_opts['sort'] = $sort;
    $url_opts['order'] = $order;
    $url_opts['duration_filter'] = $duration_filter;

    // build page content
    $ret .= checkErrorMessage();

    // ajax page refresh script
    if ($AJAX_PAGE_REFRESH_ENABLE) {
 //     $ret .= ajaxRefreshScript($args);
    }

    // header
    if ($_SESSION['ari_user']['admin_callmonitor']) {
      $header_text = _("Call History");
    } else {
      $header_text = sprintf(_("Call History for %s (%s)"),$displayname,$extension);
    }
    $ret .= $display->displayHeaderText($header_text);
    $ret .= $display->displaySearchBlock('left',$m,$q,$url_opts,true);

    // start form
    if ($CALLMONITOR_ALLOW_DELETE) {

      $ret .= "
        <form  name='callmonitor_form' action='" . $_SESSION['ARI_ROOT'] . "' method='GET'>
          <input type=hidden name=m value=" . $m . ">	
          <input type=hidden name=f value=recAction>
          <input type=hidden name=a value=''>
          <input type=hidden name=q value=" . $q . ">
          <input type=hidden name=start value=" . $start . ">
          <input type=hidden name=span value=" . $span . ">
          <input type=hidden name=order value=" . $order . ">
          <input type=hidden name=sort value=" . $sort . ">";
    }

    $ret .= $display->displayInfoBarBlock($controls,$q,$start,$span,$record_count);

    // javascript for popup and message actions
    $ret .= "
      <SCRIPT LANGUAGE='JavaScript'>
      <!-- Begin
      function popUp(URL) {
        eval(\"page = window.open(URL, 'play', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=324,height=110');\");
      }

      function checkAll(form,set) {
        var elem = 0;
        var i = 0;
        while (elem = form.elements[i]) {
          if (set) {
            elem.checked = true;
          } else {
            elem.checked = false;
          }
          i++;
        }
        return true;
      }
      // End -->
      </script>";

    // call monitor delete recording controls
    if ($CALLMONITOR_ALLOW_DELETE) {
      $ret .= "
        <table>
          <tr>
            <td>
              <small>" . _("select") . ": </small>
              <small><a href='' OnClick=\"checkAll(document.callmonitor_form,true); return false;\">" . _("all") . "</a></small>
              <small><a href='' OnClick=\"checkAll(document.callmonitor_form,false); return false;\">" . _("none") . "</a></small>
            </td>
          </tr>
        </table>";
    }
    else {
      $ret .= "<br>";
    }

    // table
    $ret .= "
      <table class='callmonitor'>
        <tr>
          " . $recording_delete_header . "
          " . $recording_header . "
        </tr>
        " . $recording_body . "
      </table>";

    $start = getArgument($args,'start');
    $span = getArgument($args,'span');
    $order = getArgument($args,'order');
    $sort = getArgument($args,'sort');

    // end form
    if ($CALLMONITOR_ALLOW_DELETE) {
      $ret .= "</form>";
    }

    $ret .= $display->displaySearchBlock('center',$m,$q,$url_opts,false);
    $ret .= $display->displayNavigationBlock($m,$q,$url_opts,$start,$span,$record_count);

    return $ret;
  }

  /*
   * Checks for a recording file
   *
   * @param $asterisk_callmonitor_path
   *   path call monitor recording directory on the asterisk server
   * @param $data
   *   current call monitor recordings on the asterisk server
   * @return $recording
   *   returns an array of $recording file names if found
   */
  function getRecordings($asterisk_callmonitor_path,$data) {

    global $CALLMONITOR_ONLY_EXACT_MATCHING;
    global $CALLMONITOR_AGGRESSIVE_MATCHING;

    $recordings = array();

    $extension = $_SESSION['ari_user']['extension'];

    $paths = split(';',$asterisk_callmonitor_path);
    foreach($paths as $key => $path) {
      $paths[$key] = fixPathSlash($paths[$key]);
    }

    $files = array();
    if (!$CALLMONITOR_ONLY_EXACT_MATCHING) {
      $filter = '';
      $recursiveMax = 6;
      $recursiveCount = 0;
      foreach($paths as $key => $path) {
        $path_files = getFiles($path,$filter,$recursiveMax,$recursiveCount);
        if ($path_files) {
          $files = array_merge($files,$path_files);
        }
      }
      rsort($files);
    }

    foreach($data as $data_key => $data_value) {

      $recording='';

      $calldate = $data_value['calldate'];
      $duration = $data_value['duration'];
      $lastdata = $data_value['lastdata'];
      $uniqueid = $data_value['uniqueid'];
      $userfield = $data_value['userfield'];

      // timestamps
      $st = trim(strtotime($calldate));
      $et = trim(strtotime($calldate) + $duration);   // for on-demand call recordings

      // unique file key
      if ($uniqueid) {
        $buf = preg_replace('/\-|\:/', '', $calldate);
        $calldate_key = preg_replace('/\s+/', '-', $buf);
        $unique_file_key = $calldate_key . "-" . $uniqueid;
      }
      if ($unique_file_key=='') {
        $buf = preg_split("/\|/", $lastdata);
        $unique_file_key = $buf[1];
      }

      $recordingLink = '';
      foreach($paths as $callmonitor_key => $path) {

        // try to find an exact match using the uniqueid
        if (isset($uniqueid)) {

          $check_files = array();
          array_push($check_files,$path . $uniqueid . ".WAV");
          array_push($check_files,$path . $uniqueid . ".wav");
          array_push($check_files,$path . $uniqueid . ".gsm");

          array_push($check_files,$path . $unique_file_key . ".WAV");
          array_push($check_files,$path . $unique_file_key . ".wav");
          array_push($check_files,$path . $unique_file_key . ".gsm");

          array_push($check_files,$path . "g" . $extension . "-" . $unique_file_key . ".WAV");
          array_push($check_files,$path . "g" . $extension . "-" . $unique_file_key . ".wav");
          array_push($check_files,$path . "g" . $extension . "-" . $unique_file_key . ".gsm");

          array_push($check_files,$path . "q" . $extension . "-" . $unique_file_key . ".WAV");
          array_push($check_files,$path . "q" . $extension . "-" . $unique_file_key . ".wav");
          array_push($check_files,$path . "q" . $extension . "-" . $unique_file_key . ".gsm");

          array_push($check_files,$path . "OUT" . $extension . "-" . $unique_file_key . ".WAV");
          array_push($check_files,$path . "OUT" . $extension . "-" . $unique_file_key . ".wav");
          array_push($check_files,$path . "OUT" . $extension . "-" . $unique_file_key . ".gsm");

          array_push($check_files,$path . $userfield);

          // try to match 
          foreach($check_files as $check_file) {
            if (is_file($check_file)) {
              $recording = $check_file;
              break;
            }
          }
        } 

        // if found do not need to check the rest of the paths
        if ($recording!='') {
          break;
        }
      }

      // get all the callmonitor recordings on server and try to find a non-exact match for this log entry
      if (!$CALLMONITOR_ONLY_EXACT_MATCHING) {

        // try to find a file using the uniqueid
        if (!$recording) {

          // try and match the unique id
          if (!$recording) { 
            foreach($files as $key => $path) {
              if (strlen($uniqueid)>1 && strpos($path,$uniqueid)!==FALSE) {
                $recording = $path;
                $files[$key] = '';  // remove it from the recording files so it will not be matched twice
                break;
              }
            } 
          }
        } 

        // try and match a file using the calldate (if no unique number from database) 
        if (!$recording) { 

          foreach($files as $key => $path) {
            $parts = split("-", $path);
            if (strlen($st)>1 && 
                   (strpos($path,$st)!==FALSE) || 
                   (strpos($path,"auto")!==FALSE && $parts[1] >= $st && $parts[1] <= $et)) {
              $recording = $path;
              $files[$key] = '';  // remove it from the recording files so it will not be matched twice
              break;
            }
          } 
        }

        if ($CALLMONITOR_AGGRESSIVE_MATCHING) {

          // one last stab at finding a recording by adding one or two seconds to the call time 
          if (!$recording) { 
            $st_1 = trim($st+1);
            $st_2 = trim($st+2);
            $et_1 = trim($et+1);
            $et_2 = trim($et+2);
            foreach($files as $key => $path) {
              $split = explode("-", $path);
              if (strlen($st)>1 
                    && ((strpos($path,$st_1)!==FALSE) || 
                        (strpos($path,$st_2)!==FALSE) ||
                        (strpos($path,"auto")!==FALSE && $parts[1] >= $st_1 && $parts[1] <= $et_1) ||
                        (strpos($path,"auto")!==FALSE && $parts[1] >= $st_2 && $parts[1] <= $et_2))) {
                $recording = $path;
                $files[$key] = '';  // remove it from the recording files so it will not be matched twice
                break;
              }
            } 
          }
        }
      }

      // add to array to be returned
      if ($recording) {
        $recordings[$uniqueid . $calldate] = $recording;
      }
    }

    return $recordings;
  }

  /*
   * Deletes selected call monitor recordings
   *
   * @param $files
   *   Array of files to delete
   */
  function deleteRecData($files) {

    foreach($files as $key => $file) {
      if (is_writable($file)) {
        unlink($file);
      } else {
        $_SESSION['ari_error'] = _("Only deletes recording files, not cdr log");
      }
    }
  }

  /*
   * Gets cdr record count
   *
   * @param $q
   *   query text
   */
  function getSearchText($q,$duration_filter) {

    // search text
    if ($q!='*' && $q!=NULL) {
      $searchText .= "WHERE ";
      $tok = strtok($q," \n\t");
      while ($tok) {
        $searchText .= " (calldate regexp '" . $tok . "'
                         OR clid regexp '" . $tok . "'
                         OR src regexp '" . $tok . "'
                         OR dst regexp '" . $tok . "'
                         OR dstchannel regexp '" . $tok . "'
                         OR dcontext regexp '" . $tok . "'
                         OR duration regexp '" . $tok . "'
                         OR disposition regexp '" . $tok . "'
                         OR uniqueid regexp '" . $tok . "'
                         OR userfield regexp '" . $tok . "'
                       )";
        $tok = strtok(" \n\t");
        if ($tok) {
          $searchText .= " AND";
        }
      }
    }

    // duration_filter
    if ($duration_filter) {
      if (!$searchText) {
        $searchText .= "WHERE ";
      } else {
        $searchText .= "AND ";
      }
      $searchText .= "duration>" . $duration_filter . " "; 
    }

    // admin
    if (!$_SESSION['ari_user']['admin_callmonitor']) {
      if (!$searchText) {
        $searchText .= "WHERE ";
      } else {
        $searchText .= "AND ";
      }

      // allow entries to be viewed with users extension
      $searchText .= "(src = '" . $_SESSION['ari_user']['extension'] . "'
                      OR dst = '" . $_SESSION['ari_user']['extension'] . "'

					OR channel LIKE 'IAX2/" . $_SESSION['ari_user']['extension'] ."-%'
					OR dstchannel LIKE 'IAX2/" . $_SESSION['ari_user']['extension'] ."-%'

		      OR channel LIKE 'SIP/" . $_SESSION['ari_user']['extension'] ."-%'
		      OR dstchannel LIKE 'SIP/" . $_SESSION['ari_user']['extension'] ."-%')";

      // allow entries to be viewed with users outbound CID
      if (isset($_SESSION['ari_user']['outboundCID']) && trim($_SESSION['ari_user']['outboundCID']) != '') {
        $searchText .= "OR (src = '" . $_SESSION['ari_user']['outboundCID'] . "'
                        OR dst = '" . $_SESSION['ari_user']['outboundCID'] . "')";
      }
    }

    return $searchText;
  }

  /*
   * Gets cdr record count
   *
   * @param $q
   *   query text
   * @return $count
   *   Number of cdr records counted
   */
  function getCdrCount($q,$duration_filter) {

    global $ASTERISKCDR_DBTABLE;

    $searchText = $this->getSearchText($q,$duration_filter);

    $dbh = $_SESSION['dbh_cdr'];
    $sql = "SELECT count(*) 
            FROM " . $ASTERISKCDR_DBTABLE . "
            " . $searchText;

    $result = $dbh->getAll($sql);
    if (DB::isError($result)) {
      $_SESSION['ari_error'] = $result->getMessage();
      return;
    }
    $count = $result[0][0];

    return $count;
  }

  /*
   * Gets cdr data
   *
   * @param $q
   *   query text
   * @param $start
   *   start record
   * @param $span
   *   number of records to return
   * @return $data
   *   cdr data to be returned
   */
  function getCdrData($q,$duration_filter,$start,$span,$order,$sort) {

    global $ASTERISKCDR_DBTABLE;

    $data = array();

    $searchText = $this->getSearchText($q,$duration_filter);

    $dbh = $_SESSION['dbh_cdr'];
    $sql = "SELECT *
            FROM " . $ASTERISKCDR_DBTABLE . " 
            " . $searchText . "
            ORDER BY " . $order . " " . $sort . "
            LIMIT " . $start . "," . $span;
    $result = $dbh->getAll($sql,DB_FETCHMODE_ASSOC);
    if (DB::isError($result)) {
      $_SESSION['ari_error'] = $result->getMessage();
      return;
    }
    $data = $result;

    return $data;
  }


}


?>