Пример #1
0
 public function indexAction()
 {
     $exten = $this->getRequest()->getParam("exten");
     if ($exten === null) {
         throw new Zend_Controller_Action_Exception('Page not found.', 404);
     }
     try {
         PBX_Usuarios::get($exten);
     } catch (PBX_Exception_NotFound $ex) {
         throw new Zend_Controller_Action_Exception($this->view->translate("Extension %s does not exists.", $exten), 404);
     }
     $this->view->exten = $exten;
     $this->view->breadcrumb = Snep_Breadcrumb::renderPath(array("Manage", "Extensions", "Permissions"));
     $resources = array();
     foreach (Snep_Acl::getInstance()->getResources() as $resource) {
         $res_tree = explode("_", $resource);
         $resource = array();
         while ($element = array_pop($res_tree)) {
             $resource = array($element => $resource);
         }
         $resources = array_merge_recursive($resources, $resource);
     }
     $this->view->resources = $resources;
 }
Пример #2
0
 /**
  * Defined by Zend_Validate_Interface
  *
  * Returns true if and only if $value contains only alphabetic and digit characters
  *
  * @param  string $value
  * @return boolean
  */
 public function isValid($value)
 {
     $valueString = (string) $value;
     $this->_setValue($valueString);
     if ('' === $valueString && !$this->getAllowEmpty()) {
         $this->_error(self::STRING_EMPTY);
         return false;
     }
     try {
         PBX_Usuarios::get($value);
     } catch (PBX_Exception_NotFound $ex) {
         $this->_error(self::NOT_EXTEN);
         return false;
     }
     return true;
 }
Пример #3
0
 /**
  * Procura o dono de uma interface baseado em canal.
  *
  * @param string $channel Canal da interface
  * @return object Objeto que representa o dono da interface (se houver)
  */
 public static function getChannelOwner($channel)
 {
     $db = Snep_Db::getInstance();
     $select = $db->select()->from('trunks');
     $trunk_ifaces = $db->query($select)->fetchAll();
     foreach ($trunk_ifaces as $interface) {
         if (preg_match("#^{$interface['id_regex']}\$#i", $channel)) {
             return PBX_Trunks::get($interface['id']);
         }
     }
     $select = $db->select()->from('peers')->where("name != 'admin' AND peer_type='R'");
     $interfaces = $db->query($select)->fetchAll();
     foreach ($interfaces as $interface) {
         if (preg_match("#^{$interface['canal']}\$#i", $channel)) {
             return PBX_Usuarios::get($interface['name']);
         }
     }
     return null;
 }
Пример #4
0
 *  SNEP is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  SNEP is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SNEP.  If not, see <http://www.gnu.org/licenses/>.
 */
require_once "agi_base.php";
if ($argc != 2) {
    $asterisk->verbose("This agi script requires one extension as parameter.");
    exit(1);
}
$sigame = "";
try {
    $ramal = PBX_Usuarios::get($argv[1]);
    if ($ramal->getFollowMe() != "") {
        $ramal2 = PBX_Usuarios::get($ramal->getFollowMe());
        $sigame = $ramal2->getInterface()->getCanal();
    }
} catch (Exception $e) {
    $asterisk->verbose("[{$requestid}] Failure to resolv extension: " . $e->getMessage(), 1);
    exit(1);
}
$asterisk->set_variable("DND", $ramal->isDNDActive() ? "1" : "0");
$asterisk->set_variable("SIGAME", "\"{$sigame}\"");
Пример #5
0
 *
 *  SNEP is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  SNEP is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SNEP.  If not, see <http://www.gnu.org/licenses/>.
 */
require_once 'agi_base.php';
$ramal = PBX_Usuarios::get($request->callerid);
if (!$ramal->isLocked()) {
    $db->update('peers', array("authenticate" => true), "name='{$ramal->getNumero()}'");
    $asterisk->answer();
    $asterisk->stream_file('activated');
} else {
    if ($ramal->isLocked()) {
        $auth = $asterisk->exec('AUTHENTICATE', array($ramal->getPassword(), '', strlen((string) $ramal->getPassword())));
        if ($auth['result'] == -1) {
            $log->info("Wrong password to lock extension {$ramal}");
        } else {
            $db->update('peers', array("authenticate" => false), "name='{$ramal->getNumero()}'");
            $asterisk->answer();
            $asterisk->stream_file('de-activated');
        }
    }
Пример #6
0
 /**
  * Executa a ação.
  * @param Asterisk_AGI $asterisk
  * @param Asterisk_AGI_Request $request
  */
 public function execute($asterisk, $request)
 {
     $log = Zend_Registry::get('log');
     try {
         if (!$this->ramal instanceof Snep_Exten) {
             $ramal = PBX_Usuarios::get($request->destino);
         } else {
             $ramal = $this->ramal;
         }
     } catch (PBX_Exception_NotFound $ex) {
         $log->info($ex->getMessage());
         return;
     }
     if ($ramal->isDNDActive()) {
         $log->info("Extension {$ramal} have do not disturb enabled.");
     } else {
         if ($ramal->getFollowMe() != null) {
             $log->info("Follow-me, trying to find: " . $ramal->getFollowMe());
             $fake_request = $asterisk->request;
             $fake_request['agi_callerid'] = $ramal->getNumero();
             $fake_request['agi_extension'] = $ramal->getFollowMe();
             $request = new PBX_Asterisk_AGI_Request($fake_request);
             $dialplan = new PBX_Dialplan();
             $dialplan->setRequest($request);
             $dialplan->parse();
             $regra = $dialplan->getLastRule();
             $original_request = $asterisk->requestObj;
             $asterisk->requestObj = $request;
             $regra->setAsteriskInterface($asterisk);
             $regra->execute();
             $asterisk->requestObj = $original_request;
             $dialstatus = $asterisk->get_variable("DIALSTATUS");
             $log->debug("DIALSTATUS: " . $dialstatus['data']);
             switch ($dialstatus['data']) {
                 case 'ANSWER':
                 case 'CANCEL':
                     throw new PBX_Rule_Action_Exception_StopExecution("End of call detected");
                     break;
                 case 'CHANUNAVAIL':
                     $log->warn($dialstatus['data'] . " dialing to extension {$ramal}");
             }
         } else {
             $canal = $ramal->getInterface()->getCanal();
             if ($this->diff_ring) {
                 if ($ramal->getInterface()->getTech() == "SIP") {
                     $asterisk->exec('SIPAddHeader', 'Alert-Info: Bellcore-r3');
                 } else {
                     if ($ramal->getInterface()->getTech() == "KHOMP") {
                         $canal .= "/ring=400.200:ring_ext=400.2000";
                     }
                 }
             }
             if ($ramal->getPickupGroup() != null) {
                 $asterisk->set_variable('__PICKUPMARK', $ramal->getPickupGroup());
             }
             $log->info("Discando para ramal {$ramal} no canal {$canal}.");
             $asterisk->exec_dial($canal, $this->dial_timeout, $this->dial_flags);
             $dialstatus = $asterisk->get_variable("DIALSTATUS");
             $log->debug("DIALSTATUS: " . $dialstatus['data']);
             if ($dialstatus['data'] != "ANSWER" && $dialstatus['data'] != "CANCEL" && $this->allow_voicemail && $ramal->hasVoiceMail()) {
                 $log->info("Executing voicemail to extension {$ramal} due to {$dialstatus['data']}");
                 $vm_params = array($ramal->getMailBox(), "u");
                 $asterisk->exec('voicemail', $vm_params);
                 throw new PBX_Rule_Action_Exception_StopExecution("End of call");
             }
             switch ($dialstatus['data']) {
                 case 'ANSWER':
                 case 'CANCEL':
                     throw new PBX_Rule_Action_Exception_StopExecution("End of call");
                     break;
                 case 'NOANSWER':
                 case 'BUSY':
                     if ($this->dont_overflow) {
                         throw new PBX_Rule_Action_Exception_StopExecution("End of call");
                     }
                     break;
                 default:
                     $log->err($dialstatus['data'] . " ao discar para {$request->destino}");
             }
         }
     }
 }
Пример #7
0
 /**
  * Verifica se um destino é válido para essa regra.
  *
  * @param string $extension
  * @return boolean validity
  */
 public function isValidDst($extension)
 {
     foreach ($this->getDstList() as $dst) {
         if ($dst['type'] == 'G') {
             try {
                 $peer = PBX_Usuarios::get($extension);
             } catch (PBX_Exception_NotFound $ex) {
                 $peer = false;
             }
             if ($peer instanceof Snep_Usuario && PBX_Usuarios::hasGroupInheritance($dst['value'], $peer->getGroup())) {
                 return true;
             }
         } else {
             if ($this->checkExpr($dst['type'], $dst['value'], $extension)) {
                 return true;
             }
         }
     }
     return false;
 }
Пример #8
0
 public function createAction()
 {
     $my_object = new Formata();
     $formData = $this->_request->getParams();
     $db = Zend_Registry::get('db');
     $config = Zend_Registry::get('config');
     $prefix_inout = $config->ambiente->prefix_inout;
     $dst_exceptions = $config->ambiente->dst_exceptions;
     $init_day = $formData['period']['initDay'];
     $final_day = $formData['period']['finalDay'];
     $formated_init_day = new Zend_Date($init_day);
     $formated_init_day = $formated_init_day->toString('yyyy-MM-dd hh:mm');
     $formated_final_day = new Zend_Date($final_day);
     $formated_final_day = $formated_final_day->toString('yyyy-MM-dd hh:mm');
     $ordernar = $formData['period']['order'];
     $groupsrc = $formData['source']['selectSrc'];
     if (isset($formData['source']['groupSrc'])) {
         $src = $formData['source']['groupSrc'];
     } else {
         $src = "";
     }
     if (isset($formData['source']['srctype'])) {
         $srctype = $formData['source']['srctype'];
     } else {
         $srctype = "";
     }
     $groupdst = $formData['destination']['selectDst'];
     if (isset($formData['destination']['groupDst'])) {
         $dst = $formData['destination']['groupDst'];
     } else {
         $dst = "";
     }
     if (isset($formData['destination']['dsttype'])) {
         $dsttype = $formData['destination']['dsttype'];
     } else {
         $dsttype = "";
     }
     if (isset($formData['calls']['costs_center'])) {
         $contas = $formData['calls']['costs_center'];
     }
     $duration1 = $formData['calls']['duration_init'];
     $duration2 = $formData['calls']['duration_end'];
     $status = $formData['calls']['status'];
     $status_ans = $status_noa = $status_fai = $status_bus = $status_all = '';
     foreach ($status as $stat) {
         switch ($stat) {
             case 'ANSWERED':
                 $status_ans = 'ANSWERED';
                 break;
             case 'NOANSWER':
                 $status_noa = 'NO ANSWER';
                 break;
             case 'FAILED':
                 $status_fai = 'FAILED';
                 break;
             case 'BUSY':
                 $status_bus = 'BUSY';
                 break;
         }
     }
     $call_type = $formData['calls']['type'];
     $view_files = $formData['others']['show_records'];
     $view_tarif = $formData['others']['charging'];
     // $graph_type	= $formData['others']['graph_type'];
     $rel_type = $formData['others']['report_type'];
     $this->view->back = $this->view->translate("Back");
     // Default submit
     $acao = 'relatorio';
     if (key_exists('submit_csv', $formData)) {
         $acao = 'csv';
     } else {
         if (key_exists('submit_graph', $formData)) {
             $acao = 'grafico';
         }
     }
     /* Busca os ramais pertencentes ao grupo de ramal de origem selecionado */
     $ramaissrc = $ramaisdst = "";
     if ($groupsrc) {
         $origens = PBX_Usuarios::getByGroup($groupsrc);
         if (count($origens) == 0) {
             $this->view->error = $this->view->translate("There are no extensions in the selected group.");
             $this->_helper->viewRenderer('error');
         } else {
             $ramalsrc = "";
             foreach ($origens as $ramal) {
                 $num = $ramal->getNumero();
                 if (is_numeric($num)) {
                     $ramalsrc .= $num . ',';
                 }
             }
             $ramaissrc = " AND src in (" . trim($ramalsrc, ',') . ") ";
         }
     }
     /* Busca os ramais pertencentes ao grupo de ramal de destino selecionado */
     if ($groupdst) {
         $destinos = PBX_Usuarios::getByGroup($groupdst);
         if (count($destinos) == 0) {
             $this->view->error = $this->view->translate("There are no extensions in the selected group.");
             $this->_helper->viewRenderer('error');
         } else {
             $ramaldst = "";
             foreach ($destinos as $ramal) {
                 $num = $ramal->getNumero();
                 if (is_numeric($num)) {
                     $ramaldst .= $num . ',';
                 }
             }
             $ramaisdst = " AND dst in (" . trim($ramaldst, ',') . ") ";
         }
     }
     /* Verificando existencia de vinculos no ramal */
     $name = $_SESSION['name_user'];
     $sql = "SELECT id_peer, id_vinculado FROM permissoes_vinculos WHERE id_peer ='{$name}'";
     $result = $db->query($sql)->fetchObject();
     $vinculo_table = "";
     $vinculo_where = "";
     if ($result) {
         $vinculo_table = " ,permissoes_vinculos ";
         $vinculo_where = " ( permissoes_vinculos.id_peer='{$result->id_peer}' AND (cdr.src = permissoes_vinculos.id_vinculado OR cdr.dst = permissoes_vinculos.id_vinculado) ) AND ";
     }
     /* Clausula do where: periodos inicial e final                                */
     $dia_inicial = $formated_init_day;
     $dia_final = $formated_final_day;
     $date_clause = " ( calldate >= '{$dia_inicial}'";
     $date_clause .= " AND calldate <= '{$dia_final}' )  ";
     $CONDICAO = $date_clause;
     $ORIGENS = '';
     // Clausula do where: Origens
     if ($src !== "") {
         if (strpos($src, ",")) {
             $SRC = '';
             $arrSrc = explode(",", $src);
             foreach ($arrSrc as $srcs) {
                 $SRC .= ' OR src LIKE \'' . $srcs . '\' ';
             }
             $SRC = " AND (" . substr($SRC, 3) . ")";
         } else {
             $CONDICAO = $this->do_field($CONDICAO, $src, substr($srctype, 3), 'src');
         }
     }
     // Clausula do where: Destinos
     if ($dst !== "") {
         if (strpos($dst, ",")) {
             $DST = '';
             $arrDst = explode(",", $dst);
             foreach ($arrDst as $dsts) {
                 $DST .= ' OR dst LIKE \'' . $dsts . '\' ';
             }
             $DST = " AND (" . substr($DST, 3) . ")";
         } else {
             $CONDICAO = $this->do_field($CONDICAO, $dst, substr($dsttype, 3), 'dst');
         }
     }
     if (isset($ORIGENS)) {
         $CONDICAO .= $ORIGENS;
     }
     if (isset($DST)) {
         $CONDICAO .= $DST;
     }
     if (isset($SRC)) {
         if (isset($DST)) {
             $CONDICAO .= " OR " . ($SRC = substr($SRC, 4));
         } else {
             $CONDICAO .= $SRC;
         }
     }
     /* Clausula do where: Duracao da Chamada                                      */
     if ($duration1) {
         $CONDICAO .= " AND duration >= {$duration1} ";
     } else {
         $CONDICAO .= " AND duration > 0 ";
     }
     if ($duration2) {
         $CONDICAO .= " AND duration <= {$duration2} ";
     }
     /* Clausula do where:  Filtro de desccarte                                    */
     $TMP_COND = "";
     $dst_exceptions = explode(";", $dst_exceptions);
     foreach ($dst_exceptions as $valor) {
         $TMP_COND .= " dst != '{$valor}' ";
         $TMP_COND .= " AND ";
     }
     $CONDICAO .= " AND ( " . substr($TMP_COND, 0, strlen($TMP_COND) - 4) . " ) ";
     /* Clausula do where: // Centro de Custos Selecionado(s)                      */
     if (isset($contas) && count($contas) > 0) {
         $TMP_COND = "";
         foreach ($contas as $valor) {
             $TMP_COND .= " accountcode like '" . $valor . "%'";
             $TMP_COND .= " OR ";
         }
         $contas = implode(",", $contas);
         if ($TMP_COND != "") {
             $CONDICAO .= " AND ( " . substr($TMP_COND, 0, strlen($TMP_COND) - 3) . " ) ";
         }
     }
     /* Clausula do where: Status/Tipo Ligacao                                     */
     if ($status_all || $status_ans && $status_noa && $status_bus && $status_fai) {
         $CONDICAO .= "";
     } else {
         if ($status_ans && $status_noa && $status_bus) {
             $CONDICAO .= " AND ( disposition = '{$status_ans}' OR disposition = '{$status_noa}' ";
             $CONDICAO .= " OR disposition = '{$status_bus}' ) ";
         } elseif ($status_ans && $status_noa && $status_fai) {
             $CONDICAO .= " AND ( disposition = '{$status_ans}' OR disposition = '{$status_noa}' ";
             $CONDICAO .= " OR disposition = '{$status_fai}' ) ";
         } elseif ($status_ans && $status_fai && $status_bus) {
             $CONDICAO .= " AND ( disposition = '{$status_ans}' OR disposition = '{$status_bus}' ";
         } elseif ($status_noa && $status_bus && $status_fai) {
             $CONDICAO .= " AND ( disposition = '{$status_noa}' OR disposition = '{$status_bus}' ";
             $CONDICAO .= " OR disposition = '{$status_fai}' ) ";
         } elseif ($status_ans && $status_noa) {
             $CONDICAO .= " AND ( disposition = '{$status_ans}' OR disposition = '{$status_noa}' ) ";
         } elseif ($status_ans && $status_bus) {
             $CONDICAO .= " AND ( disposition = '{$status_ans}' OR disposition = '{$status_bus}' ) ";
         } elseif ($status_ans && $status_fai) {
             $CONDICAO .= " AND ( disposition = '{$status_ans}' OR disposition = '{$status_fai}' ) ";
         } elseif ($status_noa && $status_bus) {
             $CONDICAO .= " AND ( disposition = '{$status_bus}' OR disposition = '{$status_noa}' ) ";
         } elseif ($status_fai && $status_noa) {
             $CONDICAO .= " AND ( disposition = '{$status_fai}' OR disposition = '{$status_noa}' ) ";
         } elseif ($status_bus && $status_fai) {
             $CONDICAO .= " AND ( disposition = '{$status_bus}' OR disposition = '{$status_fai}' ) ";
         } elseif ($status_ans) {
             $CONDICAO .= " AND ( disposition = '{$status_ans}' ) ";
         } elseif ($status_noa) {
             $CONDICAO .= " AND ( disposition = '{$status_noa}' ) ";
         } elseif ($status_bus) {
             $CONDICAO .= " AND ( disposition = '{$status_bus}' ) ";
         } elseif ($status_fai) {
             $CONDICAO .= " AND ( disposition = '{$status_fai}' ) ";
         }
     }
     /* Clausula do where: Tipo de Chamada (Originada/Recebida/Outra))             */
     if ($call_type == "S") {
         // Chamadas Originadas
         $CONDICAO .= " AND (ccustos.tipo = 'S')";
     } elseif ($call_type == "E") {
         // Chamadas Recebidas
         $CONDICAO .= " AND (ccustos.tipo = 'E')";
     } elseif ($call_type == "O") {
         // Chamadas Outras
         $CONDICAO .= " AND (ccustos.tipo = 'O')";
     }
     /* Clausula do where: Prefixos de Login/Logout                                */
     if (strlen($prefix_inout) > 3) {
         $COND_PIO = "";
         $array_prefixo = explode(";", $prefix_inout);
         foreach ($array_prefixo as $valor) {
             $par = explode("/", $valor);
             $pio_in = $par[0];
             if (!empty($par[1])) {
                 $pio_out = $par[1];
             }
             $t_pio_in = strlen($pio_in);
             $t_pio_out = strlen($pio_out);
             $COND_PIO .= " substr(dst,1,{$t_pio_in}) != '{$pio_in}' ";
             if (!$pio_out == '') {
                 $COND_PIO .= " AND substr(dst,1,{$t_pio_out}) != '{$pio_out}' ";
             }
             $COND_PIO .= " AND ";
         }
         if ($COND_PIO != "") {
             $CONDICAO .= " AND ( " . substr($COND_PIO, 0, strlen($COND_PIO) - 4) . " ) ";
         }
     }
     $CONDICAO .= " AND ( locate('ZOMBIE',channel) = 0 ) ";
     /* Montagem do SELECT de Consulta */
     $SELECT = "ccustos.codigo,ccustos.tipo,ccustos.nome, date_format(calldate,\"%d/%m/%Y\") AS key_dia, date_format(calldate,\"%d/%m/%Y %H:%i:%s\") AS dia, src, dst, disposition, duration, billsec, accountcode, userfield, dcontext, amaflags, uniqueid, calldate ";
     $tot_tarifado = 0;
     /* Consulta de sql para verificar quantidade de registros selecionados e
        Montar lista de Totais por tipo de Status */
     try {
         unset($duration, $billsec);
         $sql_ctds = "SELECT " . $SELECT . " FROM cdr, ccustos {$vinculo_table} ";
         $sql_ctds .= " WHERE (cdr.accountcode = ccustos.codigo) AND {$vinculo_where} " . $CONDICAO;
         $sql_ctds .= ($ramaissrc === null ? '' : $ramaissrc) . ($ramaisdst === null ? '' : $ramaisdst);
         $sql_ctds .= " GROUP BY userfield ORDER BY calldate, userfield";
         if ($acao == "grafico") {
             $tot_fai = $tot_bus = $tot_ans = $tot_noa = $tot_oth = array();
         } else {
             $tot_fai = $tot_bus = $tot_ans = $tot_noa = $tot_bil = $tot_dur = $tot_oth = 0;
         }
         $flag_ini = True;
         // Flag para controle do 1o. registro lido
         $userfield = "XXXXXXX";
         // Flag para controle do Userfield
         unset($result);
         foreach ($db->query($sql_ctds) as $row) {
             /* Incializa array se tipo = grafico                                   */
             $key_dia = $row['key_dia'];
             if ($acao == "grafico") {
                 $tot_dias[$key_dia] = $key_dia;
                 $tot_ans[$key_dia] = !array_key_exists($key_dia, $tot_ans) ? 0 : $tot_ans[$key_dia];
                 $tot_noa[$key_dia] = !array_key_exists($key_dia, $tot_noa) ? 0 : $tot_noa[$key_dia];
                 $tot_bus[$key_dia] = !array_key_exists($key_dia, $tot_bus) ? 0 : $tot_bus[$key_dia];
                 $tot_fai[$key_dia] = !array_key_exists($key_dia, $tot_fai) ? 0 : $tot_fai[$key_dia];
                 $tot_oth[$key_dia] = !array_key_exists($key_dia, $tot_oth) ? 0 : $tot_oth[$key_dia];
             }
             /*  Faz verificacoes para contabilizar valores dentro do mesmo userfield
                 So vai contabilziar resultados por userfield */
             if ($userfield != $row['userfield']) {
                 if ($flag_ini) {
                     $result[$row['uniqueid']] = $row;
                     $userfield = $row['userfield'];
                     $flag_ini = False;
                     continue;
                 }
             } else {
                 $result[$row['uniqueid']] = $row;
                 continue;
             }
             if ($row['uniqueid'] == '') {
                 continue;
             }
             /* Varre o array da chamada com mesmo userfield                        */
             foreach ($result as $val) {
                 switch ($val['disposition']) {
                     case "ANSWERED":
                         if ($acao == 'grafico') {
                             $tot_ans[$key_dia]++;
                         } else {
                             $tot_ans++;
                         }
                         $tot_bil += $val['billsec'];
                         $tot_dur += $val['duration'];
                         if ($view_tarif) {
                             $valor = money_format('%.2n', $my_object->fmt_tarifa(array("a" => $val['dst'], "b" => $val['billsec'], "c" => $val['accountcode'], "d" => $val['calldate']), "A"));
                             $tot_tarifado += $valor;
                         }
                         break;
                     case "NO ANSWER":
                         if ($acao == 'grafico') {
                             $tot_noa[$key_dia]++;
                         } else {
                             $tot_noa++;
                         }
                         break;
                     case "BUSY":
                         if ($acao == 'grafico') {
                             $tot_bus[$key_dia]++;
                         } else {
                             $tot_bus++;
                         }
                         break;
                     case "FAILED":
                         if ($acao == 'grafico') {
                             $tot_fai[$key_dia]++;
                         } else {
                             $tot_fai++;
                         }
                         break;
                     default:
                         if ($acao == 'grafico') {
                             $tot_oth[$key_dia]++;
                         } else {
                             $tot_oth++;
                         }
                         break;
                 }
                 // Fim do Switch
             }
             // Fim do Foreach do array "result"
             unset($result);
             $result[$row['uniqueid']] = $row;
             $userfield = $row['userfield'];
         }
         /* Switch a seguir é para pegar um possível último registro               */
         if (isset($result)) {
             foreach ($result as $val) {
                 switch ($val['disposition']) {
                     case "ANSWERED":
                         if ($acao == 'grafico') {
                             $tot_ans[$key_dia]++;
                         } else {
                             $tot_ans++;
                             $tot_bil += $val['billsec'];
                             $tot_dur += $val['duration'];
                             if ($view_tarif) {
                                 $valor = money_format('%.2n', $my_object->fmt_tarifa(array("a" => $val['dst'], "b" => $val['billsec'], "c" => $val['accountcode'], "d" => $val['calldate']), "A"));
                                 $tot_tarifado += $valor;
                             }
                         }
                         break;
                     case "NO ANSWER":
                         if ($acao == 'grafico') {
                             $tot_noa[$key_dia]++;
                         } else {
                             $tot_noa++;
                         }
                         break;
                     case "BUSY":
                         if ($acao == 'grafico') {
                             $tot_bus[$key_dia]++;
                         } else {
                             $tot_bus++;
                         }
                         break;
                     case "FAILED":
                         if ($acao == 'grafico') {
                             $tot_fai[$key_dia]++;
                         } else {
                             $tot_fai++;
                         }
                         break;
                     default:
                         if ($acao == 'grafico') {
                             $tot_oth[$key_dia]++;
                         } else {
                             $tot_oth++;
                         }
                         break;
                 }
                 // Fim do Switch
             }
         }
         // Fim do Foreach do array result para possivel ultimo registro
     } catch (Exception $e) {
         $this->view->error = $this->view->translate("Error");
         $this->_helper->viewRenderer('error');
     }
     if ($acao == "relatorio") {
         if ($tot_fai + $tot_bus + $tot_ans + $tot_noa == 0) {
             $this->view->error = $this->view->translate("No entries found!.");
             $this->_helper->viewRenderer('error');
         }
         $tot_wait = $tot_dur - $tot_bil;
         $totais = array("answered" => $tot_ans, "notanswer" => $tot_noa, "busy" => $tot_bus, "fail" => $tot_fai, "billsec" => $tot_bil, "duration" => $tot_dur, "espera" => $tot_wait, "oth" => $tot_oth, "tot_tarifado" => $tot_tarifado);
         // "tot_tarifado"=>number_format($tot_tarifado,2,",","."));
     } else {
         if (count($tot_fai) == 0 && count($tot_bus) == 0 && count($tot_ans) == 0 && count($tot_noa) == 0 && count($tot_oth) == 0) {
             $this->view->error = $this->view->translate("No entries found!");
             $this->_helper->viewRenderer('error');
             return;
         }
         if ($acao != "grafico") {
             $totais = array("ans" => $tot_ans, "noa" => $tot_noa, "bus" => $tot_bus, "fai" => $tot_fai, "dias" => $tot_dias, "dur" => $tot_dur, "bil" => $tot_bil);
         } else {
             $totais = array();
         }
     }
     /* Define um SQL de Exibicao no Template, agrupado e com ctdor de agrupamentos */
     $sql_chamadas = "SELECT count(userfield) as qtdade," . $SELECT . " FROM cdr, ccustos {$vinculo_table} ";
     $sql_chamadas .= " WHERE (cdr.accountcode = ccustos.codigo) AND {$vinculo_where} " . $CONDICAO;
     $sql_chamadas .= ($ramaissrc === null ? '' : $ramaissrc) . ($ramaisdst === null ? '' : $ramaisdst);
     switch ($ordernar) {
         case "data":
             $ordernar = " calldate ";
             break;
         case "src":
             $ordernar = " src, calldate ";
             break;
         case "dst":
             $ordernar = "  dst, calldate ";
             break;
     }
     $sql_chamadas .= " GROUP BY userfield ORDER BY {$ordernar} ";
     $defaultNS = new Zend_Session_Namespace('call_sql');
     $defaultNS->sql = $sql_chamadas;
     $defaultNS->totais = $totais;
     $defaultNS->view_tarif = $view_tarif;
     $defaultNS->view_files = $view_files;
     $defaultNS->status = $status;
     if (isset($contas)) {
         $defaultNS->contas = $contas;
     }
     $defaultNS->report_type = $rel_type;
     $defaultNS->src = $src;
     $defaultNS->groupsrc = $groupsrc;
     $defaultNS->dst = $dst;
     $defaultNS->groupdst = $groupdst;
     $defaultNS->sub_title = $this->view->translate($formData['period']['initDay'] . " - " . $formData['period']['initDay']);
     $row = $db->query($sql_chamadas)->fetchAll();
     for ($i = 0; $i <= count($row) - 1; $i++) {
         $row[$i]['id'] = $i + 1;
     }
     $defaultNS->row = $row;
     if (count($defaultNS->row) == 0) {
         $this->view->error = $this->view->translate("No entries found!");
         $this->_helper->viewRenderer('error');
         return;
     }
     switch ($acao) {
         case 'relatorio':
             $this->reportAction();
             break;
             /* case 'grafico':
                 $this->graphAction();
                 break;
                 case 'csv':
                 $this->csvAction();
                 break;
                */
     }
 }
Пример #9
0
 /**
  * Executa a ação.
  * @param Asterisk_AGI $asterisk
  * @param PBX_Asterisk_AGI_Request $request
  */
 public function execute($asterisk, $request)
 {
     $log = Zend_Registry::get('log');
     if (isset($this->ask_peer) && $this->ask_peer === true) {
         $asterisk->answer();
         $asterisk->exec("READ", "RAMAL|agent-user|10|||4");
         $ramal = $asterisk->get_variable("RAMAL");
         try {
             $ramal = PBX_Usuarios::get($ramal['data']);
         } catch (PBX_Exception_NotFound $ex) {
             throw new PBX_Exception_AuthFail("Ivalid Extension");
         }
         $request->setSrcObj($ramal);
         $request->origem = $ramal->getNumero();
         $asterisk->set_variable("CALLERID(all)", $ramal->getNumero());
     }
     $senha = "";
     if ((!isset($this->config['senha']) || isset($this->config['senha']) && $this->config['senha'] == "") && $request->getSrcObj() instanceof Snep_Usuario) {
         $senha = $request->getSrcObj()->getPassword();
     } else {
         if (isset($this->config['senha']) && $this->config['senha'] != "") {
             $senha = $this->config['senha'];
         } else {
             return;
         }
     }
     $auth = $asterisk->exec('AUTHENTICATE', array($senha, '', strlen((string) $senha)));
     if ($auth['result'] == -1) {
         throw new PBX_Exception_AuthFail();
     }
 }
Пример #10
0
 /**
  * Construtor da requisição.
  *
  * Para identificar o objeto de origem estamos considerando seu callerid
  * como número de ramal. Isso, obviamente, irá identificar somente ramais.
  * Importante ressaltar que a "falsidade ideológica" entre os canais é mais
  * fácil de ser praticada nesse sistema.
  *
  * @param int $origem
  * @param string $destino
  * @param string $contexto
  */
 public function __construct($agi_request)
 {
     parent::__construct($agi_request);
     $log = Snep_Logger::getInstance();
     // Descobrindo se esse canal criado pertence a alguma entidade
     // cadastrada no snep.
     $channel = $this->request['channel'];
     // removendo o hash de controle do asterisk
     // de TECH/ID-HASH para TECH/ID
     $channel = strpos($channel, '-') ? substr($channel, 0, strpos($channel, '-')) : $channel;
     $object = PBX_Interfaces::getChannelOwner($channel);
     if ($object instanceof Snep_Trunk && $object->allowExtensionMapping()) {
         try {
             $exten = PBX_Usuarios::get($this->origem);
             if ($exten->getInterface() instanceof PBX_Asterisk_Interface_VIRTUAL) {
                 $object = $exten;
             }
         } catch (PBX_Exception_NotFound $ex) {
             // Ignore
         }
     }
     $this->setSrcObj($object);
     if (is_object($object)) {
         $classname = get_class($this->getSrcObj());
         $log->info("Identified source: {$this->getSrcObj()} ({$classname})");
     }
 }
Пример #11
0
 public function indexAction()
 {
     $this->view->breadcrumb = Snep_Breadcrumb::renderPath(array($this->view->translate("Routing"), $this->view->translate("Routes"), $this->view->translate("Simulator")));
     $trunks = array();
     foreach (PBX_Trunks::getAll() as $value) {
         $trunks[$value->getId()] = $value->getId() . " - " . $value->getName();
     }
     $this->view->trunks = $trunks;
     if ($this->_request->getPost()) {
         $formData = $this->_request->getParams();
         $extension = isset($formData['dst']) && $formData['dst'] != "" ? $formData['dst'] : 's';
         $srcType = isset($formData['srcType']) ? $formData['srcType'] : NULL;
         $trunk = isset($formData['trunk']) ? $formData['trunk'] : NULL;
         $caller = isset($formData['caller']) && $formData['caller'] != "" ? $formData['caller'] : "unknown";
         $time = isset($formData['time']) ? $formData['time'] : NULL;
         $dialplan = new PBX_Dialplan_Verbose();
         if ($srcType == "exten") {
             try {
                 $srcObj = PBX_Usuarios::get($caller);
             } catch (PBX_Exception_NotFound $ex) {
                 $this->view->error = $this->view->translate($ex->getMessage());
                 $this->view->back = $this->view->translate("Back");
                 $this->renderScript('simulator/error.phtml');
                 return;
             }
             $channel = $srcObj->getInterface()->getCanal();
         } else {
             if ($srcType == "trunk") {
                 $srcObj = PBX_Trunks::get($trunk);
                 $channel = $srcObj->getInterface()->getCanal();
             } else {
                 $srcObj = null;
                 $channel = "unknown";
             }
         }
         $request = new PBX_Asterisk_AGI_Request(array("agi_callerid" => $caller, "agi_extension" => $extension, "agi_channel" => $channel));
         $request->setSrcObj($srcObj);
         $dialplan->setRequest($request);
         if ($time) {
             if (preg_match("/^[0-9]:([0-9]{2})\$/", $time)) {
                 $time = "0" . $time;
             }
             $dialplan->setTime($time);
         }
         try {
             $dialplan->parse();
         } catch (PBX_Exception_NotFound $ex) {
             $this->view->error = $this->view->translate("No rule found.");
             $this->view->back = $this->view->translate("Back");
             $this->renderScript('simulator/error.phtml');
             return;
         }
         if (count($dialplan->getMatches()) > 0) {
             $found = false;
             foreach ($dialplan->getMatches() as $index => $rule) {
                 if ($rule->getId() == $dialplan->getLastRule()->getId()) {
                     $state = "torun";
                     $found = true;
                 } else {
                     if ($found) {
                         $state = "ignored";
                     } else {
                         $state = "outdated";
                     }
                 }
                 $actions = array();
                 foreach ($rule->getAcoes() as $action) {
                     $config = $action->getConfigArray();
                     if ($action instanceof CCustos) {
                         $actions[] = $this->view->translate("Define Cost Center to ") . $config['ccustos'];
                     } else {
                         if ($action instanceof DiscarTronco) {
                             $tronco = PBX_Trunks::get($config['tronco']);
                             $actions[] = $this->view->translate("Dial through Trunk ") . $tronco->getName();
                         } else {
                             if ($action instanceof DiscarRamal) {
                                 if (isset($config['ramal']) && $config['ramal'] != "") {
                                     $peer = $config['ramal'];
                                 } else {
                                     $peer = $extension;
                                 }
                                 try {
                                     $ramal = PBX_Usuarios::get($peer);
                                     $actions[] = $this->view->translate("Dial to extension %s", $ramal->getCallerid());
                                 } catch (PBX_Exception_NotFound $ex) {
                                     $actions[] = "<strong style='color:red'>" . $this->view->translate("Failure on trial to dial extension %: non existent extension", $extension) . "</strong>";
                                 }
                             } else {
                                 if ($action instanceof Queue) {
                                     $actions[] = $this->view->translate("Direct to queue %s", $config['queue']);
                                 } else {
                                     if ($action instanceof Cadeado) {
                                         $actions[] = $this->view->translate("Request password");
                                     } else {
                                         if ($action instanceof Context) {
                                             $actions[] = $this->view->translate("Redirect to context %s", $config['context']);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
                 $srcs = array();
                 foreach ($rule->getSrcList() as $src) {
                     $srcs[] = trim(implode(":", $src), ':');
                 }
                 $srcs = implode(",", $srcs);
                 $dsts = array();
                 foreach ($rule->getDstList() as $dst) {
                     $dsts[] = trim(implode(":", $dst), ':');
                 }
                 $dsts = implode(",", $dsts);
                 $result[$index] = array("id" => $rule->getId(), "state" => $state, "caller" => $srcs, "dst" => $dsts, "desc" => $rule->getDesc(), "valid" => join(";", $rule->getValidTimeList()), "actions" => $actions);
             }
             $input = array("caller" => $caller, "dst" => $extension, "time" => $dialplan->getLastExecutionTime());
             $this->view->input = $input;
             $this->view->result = $result;
         }
     }
 }
Пример #12
0
 protected function getQuery($data, $ExportCsv = false)
 {
     $fromDay = $data["period"]["init_day"];
     $tillDay = $data["period"]["till_day"];
     $fromDay = new Zend_Date($fromDay);
     $tillDay = new Zend_Date($tillDay);
     $extenList = $data["exten"]["exten_select"];
     $extenGroup = $data["exten"]["group_select"];
     $services = $data["service"]["serv_select"];
     $state = $data["service"]["stat_select"];
     $configFile = "./includes/setup.conf";
     $config = new Zend_Config_Ini($configFile, null, true);
     $srv = '';
     if (count($services) > 0) {
         foreach ($services as $service) {
             $srv .= "'{$service}',";
         }
         $srv = " AND service IN (" . substr($srv, 0, -1) . ")";
     }
     $extenSrc = $extenDst = $cond = "";
     if ($extenGroup) {
         $origins = PBX_Usuarios::getByGroup($extenGroup);
         if (count($origins) == 0) {
             throw new Zend_Exception('Group not registered');
         } else {
             foreach ($origins as $ext) {
                 $extenSrc .= "'{$ext->getNumero()}'" . ',';
             }
             $extenSrc = " AND peer in (" . trim($extenSrc, ',') . ") ";
         }
     } else {
         if ($extenList) {
             $extenList = explode(";", $extenList);
             $list = '';
             foreach ($extenList as $value) {
                 $list .= trim($value) . ',';
             }
             $extenSrc = " AND services_log.peer IN ('" . substr($list, 0, -1) . "') ";
         }
     }
     $state_cnt = count($state);
     if ($state_cnt == 2) {
         $state = " ";
     } else {
         if ($state[0] == "D") {
             $state = " AND services_log.state = '0' ";
         }
         if ($state[0] == "A") {
             $state = " AND services_log.state = '1' ";
         }
     }
     $dateClause = " ( date >= '{$fromDay->toString('yyyy-MM-dd hh:mm')}'";
     $dateClause .= " AND date <= '{$tillDay->toString('yyyy-MM-dd hh:mm')}') ";
     //'
     $cond .= " {$dateClause} ";
     $sql = " SELECT *, DATE_FORMAT(date,'%d/%m/%Y %T') as date FROM services_log WHERE ";
     $sql .= $cond . $state;
     $sql .= $extenSrc ? $extenSrc : '';
     $sql .= $srv ? $srv : '';
     $db = Zend_Registry::get('db');
     $stmt = $db->query($sql);
     $dataTmp = $stmt->fetchAll();
     foreach ($dataTmp as $key => $value) {
         if (!$ExportCsv) {
             if ($value['state'] == 1) {
                 $dataTmp[$key]['state'] = $this->view->translate(' - Activated');
             } else {
                 $dataTmp[$key]['state'] = $this->view->translate(' - Deactivated');
             }
         } else {
             if ($value['state'] == 1) {
                 $dataTmp[$key]['state'] = $this->view->translate('Activated');
             } else {
                 $dataTmp[$key]['state'] = $this->view->translate('Deactivated');
             }
             $dataTmp[$key]['status'] = '"' . $value['status'] . '"';
         }
     }
     return $dataTmp;
 }
Пример #13
0
 *
 *  SNEP is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  SNEP is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SNEP.  If not, see <http://www.gnu.org/licenses/>.
 */
require_once "agi_base.php";
if ($argc != 3) {
    $asterisk->verbose("This script requires one extension and a variable name as parameter");
    exit(1);
}
// Procurando no banco pelo canal do peer
try {
    $ramal = PBX_Usuarios::get($argv[1]);
} catch (Exception $e) {
    $asterisk->verbose("[{$requestid}] Failure to resolv interface: " . $e->getMessage(), 1);
    exit(1);
}
$channel = $ramal->getInterface()->getCanal();
if (substr($channel, 0, 1) == "k" || substr($channel, 0, 1) == "K") {
    $channel = "Khomp/" . strtoupper(substr($channel, strpos($channel, '/') + 1));
}
$asterisk->set_variable($argv[2], $channel);