Пример #1
0
    protected function _formatReportForExtension($smarty, $module_name, $extension, &$respuesta)
    {
        $dsnAsteriskCDR = generarDSNSistema("asteriskuser", "asteriskcdrdb");
        $pDB = new paloDB($dsnAsteriskCDR);
        if (!empty($pDB->errMsg)) {
            $respuesta['status'] = 'error';
            $respuesta['message'] = _tr('Error at read yours calls.') . $pDB->errMsg;
        } else {
            $sql = <<<SQL_LLAMADAS_RECIBIDAS
SELECT calldate, src, duration, disposition FROM cdr
WHERE dst = ? OR SUBSTRING_INDEX(SUBSTRING_INDEX(dstchannel,'-',1),'/',-1) = ?
ORDER BY calldate DESC LIMIT ?
SQL_LLAMADAS_RECIBIDAS;
            $recordset = $pDB->fetchTable($sql, TRUE, array($extension, $extension, MAX_CALL_RECORDS));
            if (!is_array($recordset)) {
                $respuesta['status'] = 'error';
                $respuesta['message'] = _tr('Error at read yours calls.') . $pDB->errMsg;
            } elseif (count($recordset) <= 0) {
                $respuesta['html'] = _tr("You don't recibed calls");
            } else {
                $estadoLlamadas = array();
                foreach ($recordset as $tupla) {
                    $answ = $tupla['disposition'] == 'ANSWERED';
                    $estadoLlamadas[] = str_replace(array('{status}', '{date}', '{source}'), array($answ ? _tr('answered') : _tr('missed'), $tupla['calldate'], empty($tupla['src']) ? _tr('unknow') : $tupla['src']), _tr('call record')) . ($answ ? str_replace('{time}', $tupla['duration'], _tr('call duration')) : '.');
                }
                $respuesta['html'] = implode('<br/>', $estadoLlamadas);
            }
        }
    }
Пример #2
0
    protected function _formatReportForExtension($smarty, $module_name, $extension, &$respuesta)
    {
        global $arrConf;
        $dbFax = new paloDB("sqlite3:///{$arrConf['elastix_dbdir']}/fax.db");
        $sql = <<<SQL_FAXES_EXTENSION
SELECT a.pdf_file, a.company_name, a.date, a.id
FROM info_fax_recvq a, fax b
WHERE b.extension = ? AND b.id = a.fax_destiny_id AND type='in'
ORDER BY a.id desc LIMIT ?
SQL_FAXES_EXTENSION;
        $recordset = $dbFax->fetchTable($sql, TRUE, array($extension, MAX_FAX_RECORDS));
        if (!is_array($recordset)) {
            $recordset = array();
        }
        if (count($recordset) <= 0) {
            $respuesta['status'] = 'error';
            $respuesta['message'] = _tr("You don't recibed faxes");
        } else {
            $estadoFaxes = array();
            foreach ($recordset as $tupla) {
                $estadoFaxes[] = str_replace(array('{file}', '{source}', '{date}'), array("<a href='?menu=faxviewer&action=download&rawmode=yes&id={$tupla['id']}'>{$tupla['pdf_file']}</a>", $tupla['company_name'] == 'XXXXXXX' ? _tr('unknow') : $tupla['company_name'], $tupla['date']), _tr('fax recived'));
            }
            $respuesta['html'] = implode("<br/>\n", $estadoFaxes);
        }
    }
Пример #3
0
    private function _leerRegistrosEventos($idUser)
    {
        global $arrConf;
        $db = new paloDB("sqlite3:///{$arrConf['elastix_dbdir']}/calendar.db");
        $sql = <<<SQL_EVENTOS
SELECT id, subject, asterisk_call, startdate, enddate, starttime, endtime, eventtype
FROM events
WHERE uid = ? AND enddate >= ?
ORDER BY id desc        
SQL_EVENTOS;
        $recordset = $db->fetchTable($sql, TRUE, array($idUser, date('Y-m-d')));
        if (!is_array($recordset)) {
            return array();
        }
        return $recordset;
    }
 function createNewDatabaseMySQL($path_script_db, $db_name, $datos_conexion)
 {
     $root_password = MYSQL_ROOT_PASSWORD;
     $db = 'mysql://*****:*****@localhost/';
     $pDB = new paloDB($db);
     $sPeticionSQL = "CREATE DATABASE {$db_name}";
     $result = $pDB->genExec($sPeticionSQL);
     if ($datos_conexion['locate'] == "") {
         $datos_conexion['locate'] = "localhost";
     }
     $GrantSQL = "GRANT SELECT, INSERT, UPDATE, DELETE ON {$db_name}.* TO ";
     $GrantSQL .= $datos_conexion['user'] . "@" . $datos_conexion['locate'] . " IDENTIFIED BY '" . $datos_conexion['password'] . "'";
     $result = $pDB->genExec($GrantSQL);
     $comando = "mysql --password="******" --user=root {$db_name} < {$path_script_db}";
     exec($comando, $output, $retval);
     return $retval;
 }
Пример #5
0
 private function _checkEmailPassword($email, $password)
 {
     global $arrConf;
     $pDB = new paloDB("sqlite3:///{$arrConf['elastix_dbdir']}/email.db");
     $tupla = $pDB->getFirstRowQuery('SELECT password FROM accountuser WHERE username = ?', TRUE, array($email));
     if (!is_array($tupla)) {
         $this->errMsg = $this->_DB->errMsg;
         return FALSE;
     }
     if (count($tupla) <= 0) {
         return FALSE;
     }
     return $password == $tupla['password'];
 }
 function setApplets_User($arrIDs_DAU, $user)
 {
     global $arrConf;
     $dsn = "sqlite3:///{$arrConf['elastix_dbdir']}/dashboard.db";
     $pDB = new paloDB($dsn);
     if (is_array($arrIDs_DAU) & count($arrIDs_DAU) > 0) {
         $pDB2 = new paloDB($arrConf['elastix_dsn']['elastix']);
         $pACL = new paloACL($pDB2);
         if ($pACL->isUserSuperAdmin($user)) {
             $typeUser = "******";
         } else {
             $typeUser = "******";
         }
         $pDB->beginTransaction();
         // Parte 1: Elimino todas las actuales
         $query1 = " delete from activated_applet_by_user \n                        where username=? and id_dabu in (select id from default_applet_by_user where username=?)";
         $result1 = $pDB->genQuery($query1, array($user, $typeUser));
         if ($result1 == FALSE) {
             $this->errMsg = $pDB->errMsg;
             $pDB->rollBack();
             return false;
         }
         // Parte 2: Inserto todas las checked
         foreach ($arrIDs_DAU as $key => $value) {
             $query2 = "insert into activated_applet_by_user (id_dabu, order_no, username) values (?,?,?)";
             $result2 = $pDB->genQuery($query2, array($value, $key + 1, $user));
             if ($result2 == FALSE) {
                 $this->errMsg = $pDB->errMsg;
                 $pDB->rollBack();
                 return false;
             }
         }
         $pDB->commit();
     }
     return true;
 }
Пример #7
0
 function getEventsCalendar($idUser, $numRegs)
 {
     global $arrConf;
     global $arrLang;
     $db = new paloDB("sqlite3:///{$arrConf['elastix_dbdir']}/calendar.db");
     $actual_date = date("Y-m-d");
     $actual_date_hour = date("Y-m-d H:i:s");
     $query = "SELECT id, subject, asterisk_call, startdate, enddate, starttime, eventtype " . "FROM events " . "WHERE uid={$idUser} and enddate>='{$actual_date}' " . "ORDER BY id desc;";
     $result = $db->fetchTable($query, TRUE);
     if (!$result) {
         return $arrLang["You don't have events"];
     }
     $data = "";
     $arrEventos = array();
     foreach ($result as $value) {
         $iStartTimestamp = strtotime($value['starttime']);
         $endstamp = strtotime($value['enddate']);
         $startstamp = strtotime($value['startdate']);
         if ($value['eventtype'] == 1 || $value['eventtype'] == 5) {
             if ($value['eventtype'] == 1) {
                 $segundos = 86400;
                 $num_dias = ($endstamp - $startstamp) / $segundos + 1;
                 //Sumo 1 para incluir el ultimo dia
             } else {
                 if ($value['eventtype'] == 5) {
                     $segundos = 604800;
                     $num_dias = ($endstamp - $startstamp) / $segundos + 1;
                     //Sumo 1 para incluir la ultima semana
                     $num_dias = (int) $num_dias;
                 }
             }
             for ($i = 0; $i < $num_dias; $i++) {
                 $sFechaEvento = date('Y-m-d H:i:s', $iStartTimestamp);
                 $iStartTimestamp += $segundos;
                 if ($sFechaEvento >= $actual_date_hour) {
                     $arrEventos[] = array("date" => $sFechaEvento, "subject" => $value['subject'], "call" => $value['asterisk_call'], "id" => $value['id']);
                 }
             }
         } else {
             if ($value['eventtype'] == 6) {
                 $i = 0;
                 while ($iStartTimestamp <= $endstamp) {
                     $sFechaEvento = date('Y-m-d H:i:s', $iStartTimestamp);
                     $iStartTimestamp = strtotime("+1 months", $iStartTimestamp);
                     if ($sFechaEvento >= $actual_date_hour) {
                         $arrEventos[] = array("date" => $sFechaEvento, "subject" => $value['subject'], "call" => $value['asterisk_call'], "id" => $value['id']);
                     }
                     $i++;
                 }
             }
         }
     }
     if (count($arrEventos) < 1) {
         return $arrLang["You don't have events"];
     }
     //Ordenamiento por fechas en orden descendente (antiguos primero)
     $fechas = array();
     //$horas  = array();
     foreach ($arrEventos as $llave => $valor) {
         $fechas[$llave] = $valor['date'];
     }
     array_multisort($fechas, SORT_ASC, $arrEventos);
     $i = 0;
     while ($i < count($arrEventos) && $i < $numRegs) {
         $temp = "<a href='?menu=calendar&action=display&id=" . $arrEventos[$i]["id"] . "&event_date=" . date("Y-m-d", strtotime($arrEventos[$i]["date"])) . "'>" . $arrEventos[$i]["subject"] . "</a>";
         $temp .= "&nbsp;&nbsp;&nbsp;";
         $temp .= "Date: ";
         $temp .= $arrEventos[$i]['date'];
         $temp .= " - Call: ";
         $temp .= $arrEventos[$i]['call'];
         $temp .= "<br>";
         $data .= $temp;
         $i++;
     }
     return $data;
 }
Пример #8
0
      webmail.login  Login a usar frente a RoundCube para el usuario actual
      webmail.domain Dominio al que pertenece el login de RoundCube
      webmail.password   Clave de acceso para el login de RoundCube
      webmail.imapsvr    Servidor IMAP a contactar, o localhost si no se define     
    */
 $webmail_login = NULL;
 $webmail_domain = NULL;
 $webmail_password = NULL;
 $webmail_imapsvr = 'localhost';
 $path_root = $_SERVER["DOCUMENT_ROOT"];
 include_once "{$path_root}/libs/misc.lib.php";
 include_once "{$path_root}/configs/default.conf.php";
 include_once "{$path_root}/libs/paloSantoDB.class.php";
 include_once "{$path_root}/libs/paloSantoACL.class.php";
 global $arrConf;
 $pDB = new paloDB($arrConf["elastix_dsn"]["acl"]);
 if (!empty($pDB->errMsg)) {
     echo "ERROR DE DB: {$pDB->errMsg} <br/>";
 } else {
     $pACL = new paloACL($pDB);
     $idUser = $pACL->getIdUser($_SESSION['elastix_user']);
     $sPeticionPropiedades = 'SELECT pp.property, pp.value ' . 'FROM acl_profile_properties pp, acl_user_profile up, acl_resource r ' . 'WHERE up.id_user = ? ' . 'AND up.profile = "default" ' . 'AND up.id_profile = pp.id_profile ' . 'AND up.id_resource = r.id ' . 'AND r.name = "webmail"';
     $tabla = $pDB->fetchTable($sPeticionPropiedades, FALSE, array($idUser));
     if ($tabla === FALSE) {
         print "ERROR DE DB: " . $pDB->errMsg;
     } else {
         foreach ($tabla as $tupla) {
             switch ($tupla[0]) {
                 case 'login':
                     $webmail_login = $tupla[1];
                     break;
Пример #9
0
 function setDefaultActivatedAppletsByUser($user)
 {
     global $arrConf;
     $dsn = "sqlite3:///{$arrConf['elastix_dbdir']}/dashboard.db";
     $pDB = new paloDB($dsn);
     $pDB2 = new paloDB($arrConf['elastix_dsn']['acl']);
     $pACL = new paloACL($pDB2);
     if ($pACL->isUserAdministratorGroup($user)) {
         $id_dabu = 1;
     } else {
         $id_dabu = 13;
     }
     for ($i = 1; $i <= 5; $i++) {
         $query = "insert into activated_applet_by_user (id_dabu,order_no,username) values (?,?,?)";
         $result = $pDB->genQuery($query, array($id_dabu, $i, $user));
         if ($result == FALSE) {
             $this->errMsg = $pDB->errMsg;
             return false;
         }
         $id_dabu++;
     }
     return true;
 }
Пример #10
0
function getNewListElastixAccounts($searchFilter, &$errmsg)
{
    global $arrConf;
    $error = '';
    $pDB = new paloDB($arrConf['elastix_dsn']["elastix"]);
    $pACL = new paloACL($pDB);
    $astMang = AsteriskManagerConnect($error);
    if ($astMang == false) {
        $this->errMsg = $error;
        return false;
    }
    $arrCredentials = getUserCredentials($_SESSION['elastix_user']);
    //obtenemos el codigo pbx de la organizacion
    $query = "SELECT code from organization where id=?";
    $result = $pDB->getFirstRowQuery($query, false, array($arrCredentials["id_organization"]));
    if ($result == false) {
        $errmsg = "An error has ocurred to retrieved organization data. ";
        return false;
    } else {
        $pbxCode = $result[0];
    }
    //1) obtenemos los parametros generales de configuracion para asterisk websocket y el cliente de chat de elastix
    $chatConfig = getChatClientConfig($pDB, $error);
    if ($chatConfig == false) {
        $errmsg = "An error has ocurred to retrieved server configuration params. " . $error;
        return false;
    }
    //2) TODO:obtener el dominio sip de la organizacion si no se encuentra configurado utilizar
    //   el ws_server
    $dominio = $chatConfig['elastix_chat_server'];
    //3) obtenemos la informacion de las cuentas de los usuarios
    $name = null;
    if (!empty($searchFilter)) {
        $name = $searchFilter;
    }
    $result = $pACL->getUsersAccountsInfoByDomain($arrCredentials["id_organization"], $name);
    if ($result === false) {
        //hubo un error de la base de datos ahi que desactivar la columna lateral
        $errmsg = "An error has ocurred to retrieved Contacts Info. " . $pACL->errMsg;
        return false;
    } else {
        $arrContacts = array();
        foreach ($result as $key => $value) {
            //TODO: por el momento se obtine la presencia del usuario al
            // travès de AMI con la función que extension_state
            // en el futuro esto debe ser manejado con la libreria jssip
            // actualmente este libreria no tiene esa funcion implementada
            /*
            -1 = Extension not found
            0 = Idle
            1 = In Use
            2 = Busy
            4 = Unavailable
            8 = Ringing
            16 = On Hold
            */
            if ($value['extension'] != '' && isset($value['extension'])) {
                $result = $astMang->send_request('ExtensionState', array('Exten' => "{$value['extension']}", 'Context' => "{$pbxCode}-ext-local"));
                if ($result['Response'] == 'Success') {
                    $status = getStatusContactFromCode($result['Status']);
                    $st_code = $result['Status'];
                    if ($result['Status'] == '-1') {
                        $index_st = 'not_found';
                    } elseif ($result['Status'] == '4') {
                        $index_st = 'unava';
                    } else {
                        $index_st = 'ava';
                    }
                } else {
                    //TODO:ahi un error con el manager y nopuede determinar le estado de los
                    //contactos por lo tanto dejo a todas como disponibles
                    $index_st = 'ava';
                    $st_code = 0;
                    $status = _tr('Idle');
                }
                if ($value['id'] != $arrCredentials['idUser']) {
                    $arrContacts[$index_st][$key]['idUser'] = $value['id'];
                    $arrContacts[$index_st][$key]['display_name'] = $value['name'];
                    $arrContacts[$index_st][$key]['username'] = $value['username'];
                    $arrContacts[$index_st][$key]['presence'] = $status;
                    $arrContacts[$index_st][$key]['st_code'] = $st_code;
                    $arrContacts[$index_st][$key]['uri'] = "{$value['elxweb_device']}@{$dominio}";
                    $arrContacts[$index_st][$key]['alias'] = "{$value['alias']}@{$dominio}";
                } else {
                    $arrContacts['my_info']['uri'] = "{$value['elxweb_device']}@{$dominio}";
                    $arrContacts['my_info']['ws_servers'] = $chatConfig['ws_servers'];
                    $arrContacts['my_info']['password'] = $_SESSION['elastix_pass2'];
                    $arrContacts['my_info']['display_name'] = $value['name'];
                    $arrContacts['my_info']['elxuser_username'] = $value['username'];
                    $arrContacts['my_info']['elxuser_exten'] = $value['extension'];
                    $arrContacts['my_info']['elxuser_faxexten'] = $value['fax_extension'];
                    $arrContacts['my_info']['st_code'] = $st_code;
                    foreach ($chatConfig as $key => $value) {
                        $arrContacts['my_info'][$key] = $value;
                    }
                }
            }
        }
        $resultado = $arrContacts;
    }
    $astMang->disconnect();
    return $resultado;
}
Пример #11
0
function _moduleContent(&$smarty, $module_name)
{
    include_once "libs/paloSantoDB.class.php";
    include_once "libs/paloSantoConfig.class.php";
    include_once "libs/paloSantoGrid.class.php";
    include_once "libs/paloSantoACL.class.php";
    include_once "modules/{$module_name}/configs/default.conf.php";
    //include file language agree to elastix configuration
    //if file language not exists, then include language by default (en)
    $lang = get_language();
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $lang_file = "modules/{$module_name}/lang/{$lang}.lang";
    if (file_exists("{$base_dir}/{$lang_file}")) {
        include_once "{$lang_file}";
    } else {
        include_once "modules/{$module_name}/lang/en.lang";
    }
    //global variables
    global $arrConf;
    global $arrConfModule;
    global $arrLang;
    global $arrLangModule;
    $arrConf = array_merge($arrConf, $arrConfModule);
    $arrLang = array_merge($arrLang, $arrLangModule);
    //conexion acl.db
    $pDB = new paloDB($arrConf['elastix_dsn']['acl']);
    //folder path for custom templates
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($arrConf['templates_dir']) ? $arrConf['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme'];
    $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*");
    $arrConfig = $pConfig->leer_configuracion(false);
    $dsn = $arrConfig['AMPDBENGINE']['valor'] . "://" . $arrConfig['AMPDBUSER']['valor'] . ":" . $arrConfig['AMPDBPASS']['valor'] . "@" . $arrConfig['AMPDBHOST']['valor'] . "/asterisk";
    $pDBa = new paloDB($dsn);
    ////////////////////
    if (!empty($pDB->errMsg)) {
        echo "ERROR DE DB: {$pDB->errMsg} <br>";
    }
    $arrData = array();
    $arrData[""] = $arrLang["no extension"];
    $pACL = new paloACL($pDB);
    if (!empty($pACL->errMsg)) {
        echo "ERROR DE ACL: {$pACL->errMsg} <br>";
    }
    /*******/
    $typeUser = "";
    $userLevel1 = "";
    $extOther = "";
    $userAccount = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : "";
    $idUserAccount = $pACL->isUserAdministratorGroup($userAccount);
    $idUserInt = $pACL->getIdUser($userAccount);
    if ($idUserAccount) {
        $userLevel1 = "admin";
    } else {
        $userLevel1 = "other";
    }
    $smarty->assign("userLevel1", $userLevel1);
    /*******/
    $sQuery = "select extension from users order by extension;";
    $arrayResult = $pDBa->fetchTable($sQuery, true);
    if (!$arrayResult) {
        $error = $pDBa->errMsg;
    } else {
        if (is_array($arrayResult) && count($arrayResult) > 0) {
            //$arrData[$item["null"]] = "No extension";
            if ($idUserAccount) {
                foreach ($arrayResult as $item) {
                    $arrData[$item["extension"]] = $item["extension"];
                }
            } else {
                $idOther = $pACL->getIdUser($userAccount);
                $arrUserOther = $pACL->getUsers($idOther);
                $extOther = $arrUserOther[0][3];
                $arrData[$extOther] = $extOther;
            }
        }
    }
    $arrGruposACL = $pACL->getGroups();
    for ($i = 0; $i < count($arrGruposACL); $i++) {
        if ($arrGruposACL[$i][1] == 'administrator') {
            $arrGruposACL[$i][1] = $arrLang['administrator'];
        } else {
            if ($arrGruposACL[$i][1] == 'operator') {
                $arrGruposACL[$i][1] = $arrLang['operator'];
            } else {
                if ($arrGruposACL[$i][1] == 'extension') {
                    $arrGruposACL[$i][1] = $arrLang['extension'];
                }
            }
        }
        if ($idUserAccount) {
            $arrGrupos[$arrGruposACL[$i][0]] = $arrGruposACL[$i][1];
        } else {
            $arrUserPer = $pACL->getMembership($idUserInt);
            foreach ($arrUserPer as $key => $value) {
                if ($arrGruposACL[$i][1] == $key) {
                    $arrGrupos[$arrGruposACL[$i][0]] = $arrGruposACL[$i][1];
                }
            }
        }
    }
    $arrFormElements = array("description" => array("LABEL" => "{$arrLang['Name']} {$arrLang['(Ex. John Doe)']}", "REQUIRED" => "no", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "name" => array("LABEL" => $arrLang["Login"], "REQUIRED" => "yes", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => "", "EDITABLE" => "no"), "password1" => array("LABEL" => $arrLang["Password"], "REQUIRED" => "yes", "INPUT_TYPE" => "PASSWORD", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "password2" => array("LABEL" => $arrLang["Retype password"], "REQUIRED" => "yes", "INPUT_TYPE" => "PASSWORD", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "group" => array("LABEL" => $arrLang["Group"], "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => $arrGrupos, "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "extension" => array("LABEL" => $arrLang["Extension"], "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => $arrData, "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "webmailpassword1" => array("LABEL" => $arrLang["Webmail Password"], "REQUIRED" => "no", "INPUT_TYPE" => "PASSWORD", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "webmailuser" => array("LABEL" => $arrLang["Webmail User"], "REQUIRED" => "no", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "webmaildomain" => array("LABEL" => $arrLang["Webmail Domain"], "REQUIRED" => "no", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""));
    $contenidoModulo = "";
    $smarty->assign("REQUIRED_FIELD", $arrLang["Required field"]);
    $smarty->assign("CANCEL", $arrLang["Cancel"]);
    $smarty->assign("APPLY_CHANGES", $arrLang["Apply changes"]);
    $smarty->assign("SAVE", $arrLang["Save"]);
    $smarty->assign("EDIT", $arrLang["Edit"]);
    $smarty->assign("DELETE", $arrLang["Delete"]);
    $smarty->assign("CONFIRM_CONTINUE", $arrLang["Are you sure you wish to continue?"]);
    $smarty->assign("icon", "images/user.png");
    $smarty->assign("title_webmail", $arrLang["Mail Profile"]);
    if (isset($_POST['submit_create_user'])) {
        // Implementar
        include_once "libs/paloSantoForm.class.php";
        $arrFillUser['description'] = '';
        $arrFillUser['name'] = '';
        $arrFillUser['group'] = '';
        $arrFillUser['extension'] = '';
        $arrFillUser['password1'] = '';
        $arrFillUser['password2'] = '';
        $oForm = new paloForm($smarty, $arrFormElements);
        $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["New User"], $arrFillUser);
    } else {
        if (!is_null(getParameter("edit"))) {
            $contenidoModulo = editUser($userAccount, $pACL, $pDB, $arrFormElements, $smarty, $local_templates_dir, $arrLang, $idUserAccount, $userLevel1);
        } else {
            if (isset($_POST['submit_save_user'])) {
                include_once "libs/paloSantoForm.class.php";
                $oForm = new paloForm($smarty, $arrFormElements);
                if ($oForm->validateForm($_POST)) {
                    // Exito, puedo procesar los datos ahora.
                    $pACL = new paloACL($pDB);
                    if (empty($_POST['password1']) or $_POST['password1'] != $_POST['password2']) {
                        // Error claves
                        $smarty->assign("mb_message", $arrLang["The passwords are empty or don't match"]);
                        $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["New User"], $_POST);
                    } else {
                        if ($userLevel1 == "admin") {
                            // Creo al usuario
                            $md5_password = md5($_POST['password1']);
                            $pACL->createUser($_POST['name'], $_POST['description'], $md5_password, $_POST['extension']);
                            $idUser = $pACL->getIdUser($_POST['name']);
                            // Versiones viejas del archivo acl.db tienen una fila con una
                            // tupla que asocia al usuario inexistente con ID 2, con el
                            // grupo 2 (Operadores). Se limpia cualquier membresía extraña.
                            $listaMembresia = $pACL->getMembership($idUser);
                            if (is_array($listaMembresia) && count($listaMembresia) > 0) {
                                foreach ($listaMembresia as $idGrupo) {
                                    $pACL->delFromGroup($idUser, $idGrupo);
                                }
                            }
                            // Creo la membresia
                            $pACL->addToGroup($idUser, $_POST['group']);
                            $bExito = TRUE;
                            if (empty($pACL->errMsg)) {
                                $nuevasPropiedades = array();
                                if (!empty($_POST['webmailuser'])) {
                                    $nuevasPropiedades['login'] = $_POST['webmailuser'];
                                }
                                if (!empty($_POST['webmailpassword1'])) {
                                    $nuevasPropiedades['password'] = $_POST['webmailpassword1'];
                                }
                                if (!empty($_POST['webmaildomain'])) {
                                    $nuevasPropiedades['domain'] = $_POST['webmaildomain'];
                                }
                                $bExito = actualizarPropiedades($pDB, $smarty, $idUser, 'webmail', 'default', $nuevasPropiedades);
                            }
                            if (!empty($pACL->errMsg)) {
                                // Ocurrio algun error aqui
                                $smarty->assign("mb_message", "ERROR: {$pACL->errMsg}");
                                $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["New User"], $_POST);
                            } else {
                                if ($bExito) {
                                    header("Location: ?menu=userlist");
                                }
                            }
                        } else {
                            $smarty->assign("mb_message", $arrLang["userNoAllowed"]);
                        }
                    }
                } else {
                    // Error
                    $smarty->assign("mb_title", $arrLang["Validation Error"]);
                    $arrErrores = $oForm->arrErroresValidacion;
                    $strErrorMsg = "<b>{$arrLang['The following fields contain errors']}:</b><br>";
                    foreach ($arrErrores as $k => $v) {
                        $strErrorMsg .= "{$k}, ";
                    }
                    $strErrorMsg .= "";
                    $smarty->assign("mb_message", $strErrorMsg);
                    $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["New User"], $_POST);
                }
            } else {
                if (isset($_POST['submit_apply_changes'])) {
                    $arrayContent = applyChanges($userAccount, $pACL, $smarty, $arrLang, $idUserAccount, $userLevel1, $arrFormElements, $pDB, $local_templates_dir, $idUserInt, $extOther);
                    if (isset($arrayContent["mb_title"]) && isset($arrayContent["mb_message"])) {
                        $smarty->assign("mb_title", $arrayContent["mb_title"]);
                        $smarty->assign("mb_message", $arrayContent["mb_message"]);
                    }
                    if ($arrayContent["success"]) {
                        header("Location: ?menu=userlist");
                    } else {
                        if (isset($arrayContent["id_user"])) {
                            $smarty->assign("id_user", $_POST['id_user']);
                        }
                        if (isset($arrayContent["fill_user"])) {
                            $contenidoModulo = $arrayContent["form"]->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["Edit User"], $arrayContent["fill_user"]);
                        } else {
                            $contenidoModulo = $arrayContent["content"];
                        }
                    }
                } else {
                    if (isset($_GET['action']) && $_GET['action'] == "view") {
                        if (!$pACL->isUserAdministratorGroup($userAccount)) {
                            if ($pACL->getIdUser($userAccount) != $_GET['id']) {
                                $smarty->assign("mb_title", $arrLang["ERROR"]);
                                $smarty->assign("mb_message", $arrLang["You are not authorized to access to information of that user"]);
                                return reportUserList($arrLang, $pACL, $idUserAccount, $smarty, $userLevel1, $userAccount);
                            }
                        }
                        include_once "libs/paloSantoForm.class.php";
                        $oForm = new paloForm($smarty, $arrFormElements);
                        //- TODO: Tengo que validar que el id sea valido, si no es valido muestro un mensaje de error
                        $oForm->setViewMode();
                        // Esto es para activar el modo "preview"
                        $arrUser = $pACL->getUsers($_GET['id']);
                        // Conversion de formato
                        $arrTmp['name'] = $arrUser[0][1];
                        $arrTmp['description'] = $arrUser[0][2];
                        $arrTmp['password1'] = "****";
                        $arrTmp['password2'] = "****";
                        $arrTmp['extension'] = $arrUser[0][3];
                        //- TODO: Falta llenar el grupo
                        $arrMembership = $pACL->getMembership($_GET['id']);
                        $id_group = "";
                        if (is_array($arrMembership)) {
                            foreach ($arrMembership as $groupName => $groupId) {
                                $id_group = $groupId;
                                // Asumo que cada usuario solo puede pertenecer a un grupo
                                break;
                            }
                        }
                        $arrTmp['group'] = $id_group;
                        $listaPropiedades = leerPropiedadesWebmail($pDB, $smarty, $_GET['id']);
                        if (isset($listaPropiedades['login'])) {
                            $arrTmp['webmailuser'] = $listaPropiedades['login'];
                        }
                        if (isset($listaPropiedades['domain'])) {
                            $arrTmp['webmaildomain'] = $listaPropiedades['domain'];
                        }
                        if (isset($listaPropiedades['password'])) {
                            $arrTmp['webmailpassword1'] = '****';
                        }
                        //if (isset($listaPropiedades['imapsvr'])) $arrTmp['webmailimapsvr'] = $listaPropiedades['imapsvr'];
                        $smarty->assign("id_user", $_GET['id']);
                        $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["View User"], $arrTmp);
                        // hay que pasar el arreglo
                    } else {
                        if (getParameter('action') == "edit_userExtension") {
                            $smarty->assign("editUserExtension", "yes");
                            $html = editUser($userAccount, $pACL, $pDB, $arrFormElements, $smarty, $local_templates_dir, $arrLang, $idUserAccount, $userLevel1);
                            $smarty->assign("CONTENT", $html);
                            $smarty->assign("THEMENAME", $arrConf['mainTheme']);
                            $smarty->assign("MODULE_NAME", $module_name);
                            $smarty->assign("path", "");
                            $contenidoModulo = $smarty->display("{$local_templates_dir}/edit_userExtension.tpl");
                        } else {
                            if (getParameter('action') == "apply_changes_UserExtension") {
                                include_once "libs/paloSantoJSON.class.php";
                                $jsonObject = new PaloSantoJSON();
                                $result = applyChanges($userAccount, $pACL, $smarty, $arrLang, $idUserAccount, $userLevel1, $arrFormElements, $pDB, $local_templates_dir, $idUserInt, $extOther);
                                $arrMessage["mb_title"] = isset($result["mb_title"]) ? $result["mb_title"] : null;
                                $arrMessage["mb_message"] = isset($result["mb_message"]) ? $result["mb_message"] : null;
                                $arrMessage["success"] = $result["success"];
                                $jsonObject->set_message($arrMessage);
                                $contenidoModulo = $jsonObject->createJSON();
                            } else {
                                $contenidoModulo = reportUserList($arrLang, $pACL, $idUserAccount, $smarty, $userLevel1, $userAccount);
                            }
                        }
                    }
                }
            }
        }
    }
    return $contenidoModulo;
}
Пример #12
0
 /**
  * Procedimiento para borrar una lista de trunks para billing
  *
  * @param array   $listaTrunks 
  *
  * @return bool VERDADERO si se pudieron borrar correctamente
  */
 function deleteTrunksBill($listaTrunks)
 {
     $bExito = FALSE;
     if (!is_array($listaTrunks)) {
         $this->errMsg = "Values for trunks are invalid";
     } else {
         $this->errMsg = "";
         foreach ($listaTrunks as $trunk) {
             $sPeticionSQL = "DELETE FROM trunk_bill WHERE trunk = " . paloDB::DBCAMPO($trunk);
             $bExito = TRUE;
             $bExito = $this->_DB->genQuery($sPeticionSQL);
             if (!$bExito) {
                 print $sPeticionSQL;
                 $this->errMsg = $this->_DB->errMsg;
                 break;
             }
         }
     }
     return $bExito;
 }
Пример #13
0
/**
    funcion que sirve para obtener las credenciales de un usuario
    @return
    Array => ( idUser => (idUser or ""),
               id_organization => (ID_ORG or false),
               userlevel => (superadmin,organization),
               domain => (dominio de la ORG or false)
             )
*/
function getUserCredentials($username)
{
    global $arrConf, $elxPath;
    require_once "{$elxPath}/libs/paloSantoACL.class.php";
    $pdbACL = new paloDB($arrConf['elastix_dsn']['elastix']);
    $pACL = new paloACL($pdbACL);
    $userLevel1 = "other";
    $idOrganization = $domain = false;
    $idUser = $pACL->getIdUser($username);
    if ($idUser != false) {
        $idOrganization = $pACL->getIdOrganizationUser($idUser);
        if ($idOrganization != false) {
            if ($pACL->isUserSuperAdmin($username)) {
                $userLevel1 = "superadmin";
            } elseif ($pACL->isUserAdministratorGroup($username)) {
                $userLevel1 = "admin";
            }
        }
    }
    if ($idOrganization != false) {
        //obtenemos el dominio de las organizacion
        $query = "SELECT domain from organization where id=?";
        $result = $pdbACL->getFirstRowQuery($query, false, array($idOrganization));
        if ($result == false) {
            $domain = false;
        } else {
            if (!preg_match("/^(([[:alnum:]-]+)\\.)+([[:alnum:]])+\$/", $result[0])) {
                $domain = false;
            } else {
                $domain = $result[0];
            }
        }
    }
    return array("idUser" => $idUser, "id_organization" => $idOrganization, "userlevel" => $userLevel1, "domain" => $domain);
}
Пример #14
0
 function get_hint()
 {
     // We should always check the EXTUSER in case they logged into a device
     // but we will fall back to the old methond if $astman not open although
     // I'm pretty sure everything else will puke anyhow if not running
     //
     $error = "";
     $pDB = new paloDB(generarDSNSistema("asteriskuser", "elxpbx"));
     $astman = AsteriskManagerConnect($error);
     if ($astman != false) {
         //se obtine los dispositivos a los cuales la extension esta asociada
         $deviceDB = $astman->database_get("EXTUSER", $this->code . "/" . $this->exten . "/device");
         $device_arr = explode('&', $deviceDB);
         //se obtine como se marca a dichos dispositivos
         foreach ($device_arr as $device) {
             $tmp_dial = $astman->database_get("DEVICE", $this->code . "/" . $device . "/dial");
             if ($tmp_dial !== "ERROR") {
                 $dial[] = $tmp_dial;
             }
         }
     } else {
         $query = "SELECT dial from extension where exten=? and organization_domain=?";
         $arrayParam = array($this->exten, $this->domain);
         $results = $pDB->fetchTable($query, false, $arrayParam);
         //create an array of strings
         if (is_array($results)) {
             foreach ($results as $result) {
                 $dial[] = str_replace('ZAP', 'DAHDI', $result[0]);
             }
         }
     }
     //create a string with & delimiter
     if (isset($dial) && is_array($dial)) {
         $hint = implode($dial, "&");
     } else {
         $query = "SELECT dial from extension where exten=? and organization_domain=?";
         $results = $pDB->getFirstRowQuery($query, false, array($this->exten, $this->domain));
         if (isset($results[0])) {
             $hint = $results[0];
         } else {
             $hint = "";
         }
     }
     return $hint;
 }
 private function _recogerPaquetesTransaccion($sContenido)
 {
     $lineas = explode("\n", $sContenido);
     $this->_estadoPaquete['progreso'] = array();
     $bReporte = FALSE;
     $sOperacion = NULL;
     $sLineaPrevia = '';
     foreach ($lineas as $sLinea) {
         $regs = NULL;
         if (!$bReporte && preg_match('/^\\s+Package\\s+Arch\\s+Version\\s+Repository\\s+Size/', $sLinea)) {
             $bReporte = TRUE;
         } elseif (strpos($sLinea, "Transaction Summary") !== FALSE) {
             $bReporte = FALSE;
         } elseif ($bReporte) {
             /* Si el nombre de paquete es muy largo, puede que el resto de la 
                información haya sido desplazada a la línea siguiente. Sin
                embargo, no se espera que hayan más de dos líneas. */
             $regs = NULL;
             $sLineaCompleta = ' ' . $sLineaPrevia . $sLinea;
             if (preg_match('/^\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+([0-9\\.\\,]+)\\s+[kM]?/', $sLineaCompleta, $regs)) {
                 $this->_estadoPaquete['progreso'][] = array('pkgaction' => $sOperacion, 'nombre' => $regs[1], 'arch' => $regs[2], 'version' => $regs[3], 'repo' => $regs[4], 'longitud' => $regs[5], 'rpmfile' => NULL, 'descargado' => '-', 'currstatus' => $sOperacion == 'remove' ? 'installed' : 'waiting', 'provides' => NULL, 'requires' => NULL);
                 $sLineaPrevia = '';
             } elseif (strpos($sLinea, 'Installing') === 0) {
                 $sOperacion = 'install';
                 $sLineaPrevia = '';
             } elseif (strpos($sLinea, 'Updating') === 0) {
                 $sOperacion = 'update';
                 $sLineaPrevia = '';
             } elseif (strpos($sLinea, 'Removing') === 0) {
                 $sOperacion = 'remove';
                 $sLineaPrevia = '';
             } else {
                 if (preg_match('/^\\s+(\\S+)\\s*$/', $sLinea)) {
                     $sLineaPrevia = $sLinea;
                 } else {
                     $sLineaPrevia = '';
                 }
             }
         }
         if (preg_match('/No package (\\S+) available/', $sLinea, $regs)) {
             $this->_estadoPaquete['status'] = 'error';
             $this->_estadoPaquete['errores'][] = "The following package is not available: " . $regs[1];
         }
     }
     if ($this->_estadoPaquete['status'] != 'error' && count($this->_estadoPaquete['progreso']) <= 0) {
         $this->_estadoPaquete['action'] = 'none';
         $this->_estadoPaquete['warning'][] = 'No packages to install or update';
     }
     /* La información de tamaño que proporciona yum es demasiado poco detallada
          para poder seguir la pista de la descarga con precisión de bytes. Por lo
          tanto, hay que abrir las bases SQLITE3 de yum y leer los datos de allí.
        */
     // Validar las rutas base de los repos
     $infoRepo = array();
     if ($this->_estadoPaquete['status'] != 'error') {
         $sRutaCache = $this->_cachedir;
         foreach ($this->_estadoPaquete['progreso'] as $paquete) {
             if (!isset($infoRepo[$paquete['repo']])) {
                 $sNombreRepo = $paquete['repo'];
                 if ($sNombreRepo == 'installed') {
                     continue;
                 }
                 if ($sNombreRepo[0] == '@') {
                     continue;
                 }
                 $sRutaRepo = $sRutaCache . '/' . $paquete['repo'] . '/';
                 $infoRepo[$sNombreRepo] = array('ruta' => $sRutaRepo);
                 if (!is_dir($sRutaRepo)) {
                     $this->_estadoPaquete['status'] = 'error';
                     $this->_estadoPaquete['errores'][] = "Unable to figure out cache directory for repo: {$sNombreRepo}";
                 } elseif (!is_readable($sRutaRepo . 'repomd.xml')) {
                     $this->_estadoPaquete['status'] = 'error';
                     $this->_estadoPaquete['errores'][] = "Unable to read file repomd.xml from repo: {$sNombreRepo}";
                 } else {
                     // El siguiente código require el módulo php-xml
                     $repomd = new SimpleXMLElement(file_get_contents($sRutaRepo . 'repomd.xml'));
                     foreach ($repomd->data as $dataObj) {
                         if ($dataObj['type'] == 'primary_db') {
                             $sRutaPrimary = $dataObj->location['href'];
                             $regs = NULL;
                             if (preg_match('|^(.*)/(\\S+)(\\.bz2)|', $sRutaPrimary, $regs)) {
                                 $sRutaPrimary = $regs[2];
                             }
                             $infoRepo[$sNombreRepo]['primary_db'] = $sRutaPrimary;
                         } elseif (!isset($infoRepo[$sNombreRepo]['primary_db']) && $dataObj['type'] == 'primary') {
                             $sRutaPrimary = $dataObj->location['href'];
                             $regs = NULL;
                             if (preg_match('|^(.*)/(\\S+)|', $sRutaPrimary, $regs)) {
                                 $sRutaPrimary = $regs[2];
                             }
                             // CentOS 5 usa $sRutaRepo/primary.xml.gz.sqlite
                             // Fedora 17 usa $sRutaRepo/gen/primary.xml.sqlite
                             if (file_exists($sRutaRepo . 'gen/' . basename($sRutaPrimary, '.gz') . '.sqlite')) {
                                 $infoRepo[$sNombreRepo]['primary_db'] = 'gen/' . basename($sRutaPrimary, '.gz') . '.sqlite';
                             } else {
                                 $infoRepo[$sNombreRepo]['primary_db'] = $sRutaPrimary . '.sqlite';
                             }
                         }
                     }
                     if (!isset($infoRepo[$sNombreRepo]['primary_db'])) {
                         $this->_estadoPaquete['status'] = 'error';
                         $this->_estadoPaquete['errores'][] = "Unable to locate primary_db from repo: {$sNombreRepo}";
                     } elseif (!is_readable($sRutaRepo . $infoRepo[$sNombreRepo]['primary_db'])) {
                         $this->_estadoPaquete['status'] = 'error';
                         $this->_estadoPaquete['errores'][] = "Unable to read primary_db from repo: {$sNombreRepo}";
                         unset($infoRepo[$sNombreRepo]['primary_db']);
                     }
                 }
             }
         }
     }
     // Para cada paquete, se abre el archivo primary_db de su correspondiente
     // repo y se consulta vía SQL el tamaño del paquete.
     if ($this->_estadoPaquete['status'] != 'error') {
         foreach ($this->_estadoPaquete['progreso'] as &$infoPaquete) {
             if ($infoPaquete['repo'] == 'installed') {
                 continue;
             }
             if ($infoPaquete['repo'][0] == '@') {
                 continue;
             }
             $repo =& $infoRepo[$infoPaquete['repo']];
             $regs = NULL;
             if (!preg_match('/^((\\S+):)?(\\S+)-(\\S+)$/', $infoPaquete['version'], $regs)) {
                 $this->_estadoPaquete['status'] = 'error';
                 $this->_estadoPaquete['errores'][] = "Unable to parse version string for package: " . $infoPaquete['nombre'];
             } else {
                 $sEpoch = $regs[2] == "" ? 0 : $regs[2];
                 $sVersion = $regs[3];
                 $sRelease = $regs[4];
                 // Abrir la conexión a la base de datos
                 $dsn = "sqlite3:///" . $repo['ruta'] . $repo['primary_db'];
                 $oDB = new paloDB($dsn);
                 if ($oDB->connStatus) {
                     $this->_estadoPaquete['status'] = 'error';
                     $this->_estadoPaquete['errores'][] = "Unable to open primary_db for package: " . $infoPaquete['nombre'];
                 } else {
                     $pkgKey = NULL;
                     // select size_package from packages where name = "pidgin" and arch = "x86_64" and epoch = "0" and version = "2.6.6" and release = "1.el5"
                     $sql = 'SELECT size_package, location_href, pkgKey FROM packages ' . 'WHERE name = ? AND arch = ? AND epoch = ? AND version = ? AND release = ?';
                     $recordset = $oDB->fetchTable($sql, FALSE, array($infoPaquete['nombre'], $infoPaquete['arch'], $sEpoch, $sVersion, $sRelease));
                     if (!is_array($recordset)) {
                         $this->_estadoPaquete['status'] = 'error';
                         $this->_estadoPaquete['errores'][] = "Unable to query primary_db for package: " . $infoPaquete['nombre'];
                     } elseif (count($recordset) <= 0) {
                         $this->_estadoPaquete['status'] = 'error';
                         $this->_estadoPaquete['errores'][] = "Unable to locate package in primary_db for package: " . $infoPaquete['nombre'] . " {$infoPaquete['arch']} {$sEpoch} {$sVersion} {$sRelease}";
                     } elseif (count($recordset) > 1) {
                         $this->_estadoPaquete['status'] = 'error';
                         $this->_estadoPaquete['errores'][] = "Duplicate package information in primary_db for package: " . $infoPaquete['nombre'];
                     } else {
                         $pkgKey = $recordset[0][2];
                         $infoPaquete['longitud'] = $recordset[0][0];
                         if ($infoPaquete['pkgaction'] != 'remove') {
                             $infoPaquete['descargado'] = 0;
                         }
                         $regs = NULL;
                         if (preg_match('|^((.*)/)?(\\S+\\.rpm)$|', $recordset[0][1], $regs)) {
                             $infoPaquete['rpmfile'] = $repo['ruta'] . 'packages/' . $regs[3];
                         } else {
                             $this->_estadoPaquete['status'] = 'error';
                             $this->_estadoPaquete['errores'][] = "Unable to discover RPM filename for package: " . $infoPaquete['nombre'];
                         }
                     }
                     // Leer los datos de lo que provee y lo que requiere
                     if (!is_null($pkgKey)) {
                         $infoPaquete['provides'] = $oDB->fetchTable('SELECT * FROM provides WHERE pkgKey = ?', TRUE, array($pkgKey));
                         $infoPaquete['requires'] = $oDB->fetchTable('SELECT * FROM requires WHERE pkgKey = ?', TRUE, array($pkgKey));
                     }
                     $oDB->disconnect();
                 }
             }
         }
     }
 }
Пример #16
0
 /**
  * Procedimiento para modificar el rate con el prefix 
  *
  * @param string    $prefix       prefix para el rate
  * @param string    $name         nombre para el rate
  * @param string    $rate         rate
  * @param string    $rate_offset  rate_offset
  * @param string    $trunk        trunk
  *
  * @return bool VERDADERO si se ha modificar correctamente el usuario, FALSO si ocurre un error.
  */
 function updateRate($id_rate, $prefix, $name, $rate, $rate_offset, $trunk)
 {
     $bExito = FALSE;
     if (!preg_match("/^[[:digit:]]+\$/", "{$id_rate}")) {
         $this->errMsg = "Rate ID is not valid";
     } else {
         //modificar rate
         $sPeticionSQL = paloDB::construirUpdate("rate", array("name" => paloDB::DBCAMPO($name), "rate" => paloDB::DBCAMPO($rate), "rate_offset" => paloDB::DBCAMPO($rate_offset), "trunk" => paloDB::DBCAMPO($trunk)), array("id" => $id_rate));
         if ($this->_DB->genQuery($sPeticionSQL)) {
             $bExito = TRUE;
         } else {
             $this->errMsg = $this->_DB->errMsg;
         }
     }
     return $bExito;
 }
Пример #17
0
 /**
  * Procedimiento para crear un nuevo menu 
  *
  * @param string    $id       
  * @param string    $name   
  * @param string    $id_parent       
  * @param string    $type         
  * @param string    $link  
  * @param string    $order
  *
  * @return bool     VERDADERO si el menu se crea correctamente, FALSO en error
  */
 function createMenu($id, $name, $id_parent, $type = 'module', $link = '', $order = -1)
 {
     $bExito = FALSE;
     if ($id == "" && $name == "") {
         $this->errMsg = "ID and module name can't be empty";
     } else {
         //verificar que no exista el mismo menu
         $sPeticionSQL = "SELECT id FROM menu " . " WHERE id = '{$id}' AND Name='{$name}' AND IdParent='{$id_parent}'";
         $arr_result =& $this->_DB->fetchTable($sPeticionSQL);
         if (is_array($arr_result) && count($arr_result) > 0) {
             $bExito = FALSE;
             $this->errMsg = "Menu already exists";
         } else {
             if ($order != -1) {
                 $sPeticionSQL = paloDB::construirInsert("menu", array("id" => paloDB::DBCAMPO($id), "Name" => paloDB::DBCAMPO($name), "Type" => paloDB::DBCAMPO($type), "Link" => paloDB::DBCAMPO($link), "IdParent" => paloDB::DBCAMPO($id_parent), "order_no" => paloDB::DBCAMPO($order)));
             } else {
                 $sPeticionSQL = paloDB::construirInsert("menu", array("id" => paloDB::DBCAMPO($id), "Name" => paloDB::DBCAMPO($name), "Type" => paloDB::DBCAMPO($type), "Link" => paloDB::DBCAMPO($link), "IdParent" => paloDB::DBCAMPO($id_parent)));
             }
             if ($this->_DB->genQuery($sPeticionSQL)) {
                 $bExito = TRUE;
             } else {
                 $this->errMsg = $this->_DB->errMsg;
             }
         }
     }
     return $bExito;
 }
Пример #18
0
 /**
  * Procedimiento que agrega números a una campaña existente. La lista de
  * números consiste en un arreglo de tuplas, cuyo elemento __PHONE_NUMBER
  * es el número de teléfono, y el resto de claves es el conjunto clave->valor
  * a guardar en la tabla call_attribute para cada llamada
  *
  * @param int $idCampaign   ID de Campaña
  * @param array $listaNumeros   Lista de números como se describe arriba
  *      array('__PHONE_NUMBER' => '1234567', 'Name' => 'Fulano de Tal', 'Address' => 'La Conchinchina')
  *
  * @return bool VERDADERO si todos los números fueron insertados, FALSO en error
  */
 function addCampaignNumbers($idCampaign, $listaNumeros)
 {
     $bExito = FALSE;
     if (!ereg('^[[:digit:]]+$', $idCampaign)) {
         $this->errMsg = 'ID de campaña no es numérico';
     } elseif (!is_array($listaNumeros)) {
         $this->errMsg = 'Lista de números tiene que ser un arreglo';
     } else {
         $bContinuar = TRUE;
         $listaValidada = array();
         // Se usa copia porque tupla se modifica en validación
         // Verificar si todos los elementos son de max. 4 parametros y son
         // todos numéricos o NULL
         if ($bContinuar) {
             foreach ($listaNumeros as $tuplaNumero) {
                 /*
                         			if (count($tuplaNumero) < 1) {
                         				$this->errMsg = "Encontrado elemento sin número telefónico";
                         				$bContinuar = FALSE;
                         			} elseif (!ereg('^[[:digit:]]+$', $tuplaNumero[0])) {
                         				$this->errMsg = "Teléfono encontrado que no es numerico";
                         				$bContinuar = FALSE;
                         			} elseif (count($tuplaNumero) > 1 + 4) {
                 						$this->errMsg = "Para teléfono $tuplaNumero[0]: implementación actual soporta máximo 4 parámetros";
                 						break;
                         			} else {
                         				$iCount = count($tuplaNumero) - 1;
                         				for ($i = 1; $i <= $iCount; $i++) {
                         					if (trim($tuplaNumero[$i]) == '') $tuplaNumero[$i] = NULL;
                         					if (!is_null($tuplaNumero[$i]) && !is_numeric($tuplaNumero[$i])) {
                         						$this->errMsg = "Para teléfono $tuplaNumero[0] se encontró parámetro $i = $tuplaNumero[$i] no numérico";
                         						$bContinuar = FALSE;
                         					}
                         				}
                         				if ($bContinuar) $listaValidada[] = $tuplaNumero;
                         			}
                 */
                 if (!isset($tuplaNumero['__PHONE_NUMBER'])) {
                     $this->errMsg = "Encontrado elemento sin número telefónico";
                     $bContinuar = FALSE;
                 } elseif (!ereg('^[[:digit:]#*]+$', $tuplaNumero['__PHONE_NUMBER'])) {
                     $this->errMsg = "Teléfono encontrado que no es numerico";
                     $bContinuar = FALSE;
                 } else {
                     if ($bContinuar) {
                         $listaValidada[] = $tuplaNumero;
                     }
                 }
                 if (!$bContinuar) {
                     break;
                 }
             }
         }
         if ($bContinuar) {
             // Inicia transacción
             if (!$this->_DB->genQuery("BEGIN TRANSACTION")) {
                 $this->errMsg = $this->_DB->errMsg;
             } else {
                 foreach ($listaValidada as $tuplaNumero) {
                     $campos = array('id_campaign' => $idCampaign, 'phone' => paloDB::DBCAMPO($tuplaNumero['__PHONE_NUMBER']), 'status' => NULL);
                     $sPeticionSQL = paloDB::construirInsert("calls", $campos);
                     $result = $this->_DB->genQuery($sPeticionSQL);
                     if (!$result) {
                         $bContinuar = FALSE;
                         $this->errMsg = $this->_DB->errMsg . "<br/>{$sPeticionSQL}";
                         break;
                     }
                     $id_call = NULL;
                     // TODO: investigar equivalente de LAST_INSERT_ID() en SQLite
                     $sPeticionSQL = "SELECT MAX(id) FROM calls WHERE id_campaign = {$idCampaign} and phone = '{$tuplaNumero['__PHONE_NUMBER']}' and status IS NULL";
                     $tupla =& $this->_DB->getFirstRowQuery($sPeticionSQL);
                     if (!is_array($tupla)) {
                         $this->errMsg = $this->_DB->errMsg . "<br/>{$sPeticionSQL}";
                         $bContinuar = FALSE;
                     } else {
                         $id_call = (int) $tupla[0];
                     }
                     if ($bContinuar) {
                         foreach ($tuplaNumero as $sClave => $sValor) {
                             if ($sClave !== '__PHONE_NUMBER') {
                                 $campos = array('id_call' => $id_call, 'key' => paloDB::DBCAMPO($sClave), 'value' => paloDB::DBCAMPO($sValor));
                                 $sPeticionSQL = paloDB::construirInsert("call_attribute", $campos);
                                 $result = $this->_DB->genQuery($sPeticionSQL);
                                 if (!$result) {
                                     $bContinuar = FALSE;
                                     $this->errMsg = $this->_DB->errMsg . "<br/>{$sPeticionSQL}";
                                     break;
                                 }
                             }
                         }
                     }
                     if (!$bContinuar) {
                         break;
                     }
                 }
                 $bExito = $bContinuar;
                 if ($bExito) {
                     $this->_DB->genQuery("COMMIT");
                 } else {
                     $this->_DB->genQuery("ROLLBACK");
                 }
             }
         }
     }
     return $bExito;
 }
Пример #19
0
 function getDeviceFreePBX($dsn)
 {
     global $arrLang;
     $pDB = new paloDB($dsn);
     if ($pDB->connStatus) {
         return false;
     }
     $sqlPeticion = "select id, concat(description,' <',user,'>') label FROM devices WHERE tech = 'sip' ORDER BY id ASC;";
     $result = $pDB->fetchTable($sqlPeticion, true);
     //se consulta a la base asterisk
     $pDB->disconnect();
     $arrDevices = array();
     if (is_array($result) && count($result) > 0) {
         $arrDevices['unselected'] = "-- {$arrLang['Unselected']} --";
         foreach ($result as $key => $device) {
             $arrDevices[$device['id']] = $device['label'];
         }
     } else {
         $arrDevices['no_device'] = "-- {$arrLang['No Extensions']} --";
     }
     return $arrDevices;
 }
Пример #20
0
 function getListExternalContacts()
 {
     global $arrCredentials, $arrConf;
     $pDB = new paloDB($arrConf['elastix_dsn']['elastix']);
     $data = array($arrCredentials['idUser'], $arrCredentials['id_organization'], $arrCredentials['idUser']);
     $query = "(select concat (name,' ',last_name) as name, " . "email as username from contacts where iduser=? AND email!='' AND email IS NOT NULL) " . "UNION (select concat (c.name,' ',c.last_name) as name, " . "c.email as username from contacts c where c.iduser IN " . "(select acu.id from acl_user acu " . "join acl_group acg on acu.id_group = acg.id " . "WHERE acg.id_organization = ? AND acu.id!=?) " . " AND c.email!='' AND c.email IS NOT NULL AND c.status='isPublic') ORDER BY name ASC";
     $result = $pDB->fetchTable($query, true, $data);
     if ($result === FALSE) {
         $this->errMsg = $pDB->errMsg;
         return false;
     } else {
         return $result;
     }
 }
Пример #21
0
function saveNeoToggleTabByUser($menu, $action_status)
{
    include_once "libs/paloSantoACL.class.php";
    $arrResult['status'] = FALSE;
    $arrResult['msg'] = _tr("Please your session id does not exist. Refresh the browser and try again.");
    if ($menu != "") {
        $user = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : "";
        global $arrConf;
        $pdbACL = new paloDB("sqlite3:///{$arrConf['elastix_dbdir']}/acl.db");
        $pACL = new paloACL($pdbACL);
        $uid = $pACL->getIdUser($user);
        if ($uid !== FALSE) {
            $exist = false;
            $togglesTabs = "SELECT * FROM acl_user_shortcut WHERE id_user = ? AND type = 'NeoToggleTab'";
            $arr_result1 = $pdbACL->getFirstRowQuery($togglesTabs, TRUE, array($uid));
            if ($arr_result1 !== FALSE && count($arr_result1) > 0) {
                $exist = true;
            }
            if ($exist) {
                $pdbACL->beginTransaction();
                $query = "UPDATE acl_user_shortcut SET description = ? WHERE id_user = ? AND type = ?";
                $r = $pdbACL->genQuery($query, array($action_status, $uid, "NeoToggleTab"));
                if (!$r) {
                    $pdbACL->rollBack();
                    $arrResult['status'] = FALSE;
                    $arrResult['msg'] = _tr("Request cannot be completed. Please try again or contact with your elastix administrator and notify the next error: ") . $pdbACL->errMsg;
                    return $arrResult;
                } else {
                    $pdbACL->commit();
                    $arrResult['status'] = TRUE;
                    $arrResult['msg'] = _tr("Request has been sent.");
                    return $arrResult;
                }
            } else {
                $pdbACL->beginTransaction();
                $query = "INSERT INTO acl_user_shortcut(id_user, id_resource, type, description) VALUES(?, ?, ?, ?)";
                $r = $pdbACL->genQuery($query, array($uid, $uid, "NeoToggleTab", $action_status));
                if (!$r) {
                    $pdbACL->rollBack();
                    $arrResult['status'] = FALSE;
                    $arrResult['msg'] = _tr("Request cannot be completed. Please try again or contact with your elastix administrator and notify the next error: ") . $pdbACL->errMsg;
                    return $arrResult;
                } else {
                    $pdbACL->commit();
                    $arrResult['status'] = TRUE;
                    $arrResult['msg'] = _tr("Request has been sent.");
                    return $arrResult;
                }
            }
        }
    }
    return $arrResult;
}
Пример #22
0
 function Obtain_Protocol_from_Ext($dsn, $id)
 {
     $pDB = new paloDB($dsn);
     $query = "SELECT dial, description FROM devices WHERE id={$id}";
     $result = $pDB->getFirstRowQuery($query, TRUE);
     if ($result != FALSE) {
         return $result;
     } else {
         $this->errMsg = $pDB->errMsg;
         return FALSE;
     }
 }
 function paloContexto($code, $name)
 {
     global $arrConf;
     //valido que el codigo exista
     $pDB = new paloDB($arrConf['elastix_dsn']['elastix']);
     $queryCode = "SELECT count(code) from organization where code=?";
     $recode = $pDB->getFirstRowQuery($queryCode, false, array($code));
     if ($recode === false) {
         $this->errMsg = $pDB->errMsg;
         return false;
     } elseif (count($recode) == 0) {
         $this->errMsg = _tr("Organization doesn't exist");
         return false;
     }
     $this->code = $code;
     if (preg_match("/^[A-Za-z0-9\\-_]+\$/", $name) || strlen($name) > 62) {
         if (substr($name, 0, 6) == "macro-") {
             $this->name = "[macro-" . $this->code . "-" . substr($name, 6) . "]";
         } else {
             $this->name = "[" . $this->code . "-" . $name . "]";
         }
     } else {
         $this->errMsg = _tr("Context names cannot contain special characters and have a maximum length of 62 characters");
         return false;
     }
 }
Пример #24
0
 function procesarValorCampos($caller_id, $pDB, &$numActualizados, &$numInsertados)
 {
     $SQLConsultaCallerId = 'select * from dont_call where caller_id=' . paloDB::DBCAMPO($caller_id);
     $resConsultaCallerId = $pDB->fetchTable($SQLConsultaCallerId, true);
     if (!count($resConsultaCallerId) > 0) {
         $sPeticionSQL = paloDB::construirInsert("dont_call", array("caller_id" => paloDB::DBCAMPO($caller_id), "date_income" => paloDB::DBCAMPO(date('Y-m-d H-i-s')), "status" => paloDB::DBCAMPO('I')));
         $result = $pDB->genQuery($sPeticionSQL);
         if (!$result) {
             $this->guardarMensaje("Error al ingresar el registro");
         } else {
             $numInsertados++;
         }
     }
 }
 function Obtain_Protocol($extension)
 {
     if ($extension) {
         $dsnAsterisk = generarDSNSistema('asteriskuser', 'asterisk');
         $pDB = new paloDB($dsnAsterisk);
         $query = "SELECT dial, description, id FROM devices WHERE id=?";
         $result = $pDB->getFirstRowQuery($query, TRUE, array($extension));
         if ($result != FALSE) {
             return $result;
         } else {
             return FALSE;
         }
     } else {
         return FALSE;
     }
 }
 function createQueue($arrProp, $arrMembers)
 {
     if ($this->validateQueuePBX() == false) {
         return false;
     }
     if (!preg_match("/^[0-9]*\$/", $arrProp["name"])) {
         $this->errMsg = _tr("Invalid Queue Number");
         return false;
     }
     //validamos que el numero de la cola no este siendo usado dentro del plan de marcado
     if ($this->existExtension($arrProp["name"], $this->domain)) {
         return false;
     }
     //validamos que no se haya alcanzado el maximo numero de colas en el servidor
     global $arrConf;
     $pDB = new paloDB($arrConf['elastix_dsn']['elastix']);
     $qOrg = "SELECT value from organization_properties where key=? and category=? and id_organization=(SELECT id from organization where domain=?)";
     $res_num_queues = $pDB->getFirstRowQuery($qOrg, false, array("max_num_queues", "limit", $this->domain));
     if ($res_num_queues != false) {
         $max_num_queues = $res_num_queues[0];
         if (ctype_digit($max_num_queues)) {
             if ($max_num_queues != 0) {
                 $numQueues = $this->getTotalQueues($this->domain);
                 if ($numQueues >= $max_num_queues) {
                     $this->errMsg = _tr("Err: You can't create new queues because you have reached the max numbers of  queues permitted") . " ({$numQueues}) " . " Contact with the server's admin";
                     return false;
                 }
             }
         }
     }
     $arrProp["organization_domain"] = $this->domain;
     $arrProp["queue_number"] = $arrProp["name"];
     if (isset($arrProp["musicclass"])) {
         if ($arrProp["musicclass"] == "ring") {
             $arrProp["ringing_detail"] = "yes";
         } else {
             $arrProp["ringing_detail"] = "no";
         }
         if ($arrProp["musicclass"] == "ring" || $arrProp["musicclass"] == "inherit") {
             $arrProp["musicclass"] = null;
         }
     }
     if (isset($arrProp["monitor_format"])) {
         if ($arrProp["monitor_format"] == "no") {
             $arrProp["monitor_format"] = null;
         }
     }
     if (isset($arrProp["retry"])) {
         if ($arrProp["retry"] == "no_retry") {
             $arrProp["retry_detail"] = "no";
             $arrProp["retry"] = "0";
         } else {
             $arrProp["retry_detail"] = "yes";
         }
     }
     if (isset($arrProp["skip_busy_detail"])) {
         if ($arrProp["skip_busy_detail"] == "0" || $arrProp["skip_busy_detail"] == "1") {
             $arrProp["ringinuse"] = "yes";
         } else {
             $arrProp["ringinuse"] = "no";
         }
     }
     if (isset($arrProp["min_announce_frequency"])) {
         if ($arrProp["min_announce_frequency"] == "0") {
             $arrProp["min_announce_frequency"] = null;
         }
     }
     if (isset($arrProp["announce_detail"])) {
         if ($arrProp["announce_detail"] == "none") {
             $arrProp["announce_detail"] = null;
         } else {
             //validamos que exista la grabacion y que pertenezca a dicha organizacion
             $file = $this->getFileRecordings($this->domain, $arrProp["announce_detail"]);
             if (is_null($file)) {
                 $arrProp["announce_detail"] = null;
             }
         }
     }
     if (isset($arrProp["announce_caller_detail"])) {
         if ($arrProp["announce_caller_detail"] == "none") {
             $arrProp["announce_caller_detail"] = null;
         } else {
             //validamos que exista la grabacion y que pertenezca a dicha organizacion
             $file = $this->getFileRecordings($this->domain, $arrProp["announce_caller_detail"]);
             if (is_null($file)) {
                 $arrProp["announce_caller_detail"] = null;
             }
         }
     }
     if (isset($arrProp["destination_detail"])) {
         if ($this->validateDestine($this->domain, $arrProp["destination_detail"]) == false) {
             $arrProp["destination_detail"] = null;
         }
     }
     if ($this->insertQueueDB($arrProp) == false) {
         $this->errMsg = _tr("Error trying created queue. ") . $this->errMsg;
         return false;
     }
     $code = $this->code;
     //insertamos los miembros a la cola
     //los miembros pueden ser de tipo dinamico o estaticos
     //si son de tipo dinamico los tenemos que registrar en la base ast_db
     //si son de tipos estaticos se deben registrar en la tabla queue_member
     $queryExt = "SELECT dial from extension where organization_domain=? and exten=?";
     $queryIn = "INSERT INTO queue_member (queue_name,membername,interface,penalty,state_interface,exten) values(?,?,?,?,?,?)";
     if (isset($arrMembers["static_members"])) {
         $arrMember = array();
         $members = explode("\n", $arrMembers["static_members"]);
         foreach ($members as $value) {
             if (preg_match("/([0-9]+)((,)([0-9]+)){0,1}/", $value, $match)) {
                 $exten = $match[1];
                 $penalty = isset($match[4]) ? $match[4] : 0;
                 $interfaz = "Local/{$exten}@{$code}-from-queue/n";
                 //buscamos si el numero de extension introducio pertenece a una extension definida dentro del sistema
                 //en ese caso obtenemos la interfaz de la extension
                 $result = $this->_DB->getFirstRowQuery($queryExt, true, array($this->domain, $exten));
                 if ($result != false) {
                     $state_int = $result["dial"];
                 } else {
                     $state_int = "hint:{$exten}@{$code}-ext-local";
                 }
                 $exito = $this->executeQuery($queryIn, array($code . "_" . $arrProp["name"], $exten, $interfaz, $penalty, $state_int, $exten));
                 if ($exito == false) {
                     $this->errMsg = _tr("Error insert queue_members. ") . $this->errMsg;
                     return false;
                 }
             }
         }
     }
     $error = false;
     if (isset($arrMembers["dynamic_members"])) {
         $astMang = AsteriskManagerConnect($errorM);
         if ($astMang == false) {
             $this->errMsg .= $errorM;
             return false;
         }
         $familia = "QPENALTY/{$code}/{$code}" . "_" . $arrProp["name"] . "/agents";
         $arrMember = array();
         $members = explode("\n", $arrMembers["dynamic_members"]);
         foreach ($members as $value) {
             if (preg_match("/([0-9]+)((,)([0-9]+)){0,1}/", $value, $match)) {
                 $exten = $match[1];
                 $penalty = isset($match[4]) ? $match[4] : 0;
                 $result = $astMang->database_put($familia, $exten, $penalty);
                 if (strtoupper($result["Response"]) == "ERROR") {
                     $error = true;
                     break;
                 }
             }
         }
     }
     $dinamic = "no";
     if (isset($arrProp["restriction_agent"])) {
         if ($arrProp["restriction_agent"] == "yes") {
             $dinamic = "yes";
         }
     }
     $result = $astMang->database_put("QPENALTY/{$code}/{$code}" . "_" . $arrProp["name"], "dynmemberonly", $dinamic);
     if (strtoupper($result["Response"]) == "ERROR") {
         $error = true;
     }
     if ($error) {
         $this->errMsg = _tr("Error setting queue_member. ") . $this->errMsg;
         $result = $astMang->database_delTree("QPENALTY/{$code}/{$code}" . "_" . $arrProp["name"]);
         return false;
     } else {
         return true;
     }
 }
 function getChannels($type)
 {
     $param = array();
     $where = "";
     global $arrConf;
     $pDB = new paloDB("sqlite3:///{$arrConf['elastix_dbdir']}/hardware_detector.db");
     //los canales disponibles se los obtine de la tabla echo_canceller que pertenece a la base hardware_detector
     if (!is_null($type)) {
         if (preg_match("/^(analog|digital)\$/", $type)) {
             if ($type == "analog") {
                 $where = " where name_port=? or name_port=?";
             } else {
                 $where = " where name_port!=? && name_port!=?";
             }
             $param[] = "FXO";
             $param[] = "FXS";
         }
     }
     $query = "SELECT num_port,name_port,id_card FROM echo_canceller {$where}";
     $result = $pDB->fetchTable($query, true, $param);
     if ($result === false) {
         $this->errMsg = $pDB->errMsg;
         return false;
     } else {
         return $result;
     }
 }
Пример #28
0
 function getDeviceFreePBX($dsn, $limit = NULL, $offset = NULL, $field_name = NULL, $field_pattern = NULL, $count = FALSE)
 {
     //Defining the fields to get. If the param $count is true, then we will get the result of the sql function count(), else, we will get all fields in the table.
     $fields = $count ? "count(id) as total" : "*";
     //Begin to build the query.
     $query = "SELECT {$fields} FROM devices ";
     $strWhere = "";
     $arrParam = array();
     if (!is_null($field_name) and !is_null($field_pattern)) {
         if ($field_name == 'name') {
             $strWhere .= " description like ? ";
             $arrParam[] = $field_pattern;
         } else {
             if ($field_name == 'telefono') {
                 $strWhere .= " id like ? ";
                 $arrParam[] = $field_pattern;
             }
         }
     }
     // Clausula WHERE aqui
     if (!empty($strWhere)) {
         $query .= "WHERE {$strWhere} ";
     }
     //ORDER BY
     $query .= " ORDER BY  description";
     // Limit
     if (!is_null($limit)) {
         $limit = (int) $limit;
         $query .= " LIMIT {$limit} ";
     }
     if (!is_null($offset) and $offset > 0) {
         $offset = (int) $offset;
         $query .= " OFFSET {$offset}";
     }
     $pDB = new paloDB($dsn);
     if ($pDB->connStatus) {
         return false;
     }
     $result = $pDB->fetchTable($query, true, $arrParam);
     //se consulta a la base asterisk
     return $result;
 }
Пример #29
0
 /**
  * Procedimiento para obtener los datos de la extension usada por el usuario dentro de
    asterisk
  * @param int $idUser Id del usuario del que se quiere obtener los datos de su extension
  * @return array $ext Devuelte un arreglo donde esta el numero de la extension, la tegnologia usada y el nombre del dispositivo usado
 */
 function getExtUser($id_user)
 {
     $arr_result2 = array();
     $pDB2 = new paloDB(generarDSNSistema("asteriskuser", "elxpbx"));
     if (!preg_match('/^[[:digit:]]+$/', "{$id_user}")) {
         $this->errMsg = _tr("User ID must be numeric");
     } else {
         $query = "SELECT a.extension, (Select domain from organization o where o.id=g.id_organization) FROM acl_user as a JOIN  acl_group as g on a.id_group=g.id where a.id=?";
         $arr_result = $this->_DB->getFirstRowQuery($query, false, array($id_user));
         if ($arr_result === false) {
             $this->errMsg = _tr("Can't get extension user") . $this->_DB->errMsg;
         } elseif (count($arr_result) == 0) {
             $this->errMsg = _tr("User doesn't have a associated extension");
         } else {
             $query2 = "SELECT id, exten, organization_domain, tech, dial, voicemail, device FROM extension where exten=? and  organization_domain=?";
             $arr_result2 = $pDB2->getFirstRowQuery($query2, true, array($arr_result[0], $arr_result[1]));
             if (!is_array($arr_result2) || count($arr_result2) == 0) {
                 $this->errMsg = _tr("Can't get extension user") . $pDB2->errMsg;
             }
         }
     }
     return $arr_result2;
 }
Пример #30
0
 /**
   Retorna un array de extensiones de la PBX no utilizadas como callback extensions.
 */
 public function getUnusedExtensions()
 {
     // Consultar todas las extensiones disponibles
     $sPwdFreepbx = obtenerClaveConocidaMySQL('asteriskuser');
     if (is_null($sPwdFreepbx)) {
         $this->errMsg = 'No se puede leer clave DB para FreePBX';
         return NULL;
     }
     // BUG del framework: para asteriskuser se devuelve un array
     if (is_array($sPwdFreepbx)) {
         $sPwdFreepbx = $sPwdFreepbx['valor'];
     }
     $dsn = "mysql://*****:*****@localhost/asterisk";
     $dbFreepbx = new paloDB($dsn);
     if ($dbFreepbx->connStatus) {
         $this->errMsg = 'No se puede conectar a DB para FreePBX';
         return NULL;
     }
     $extensiones = array();
     $recordset = $dbFreepbx->fetchTable('SELECT data FROM sip WHERE keyword = "Dial" UNION ' . 'SELECT data FROM iax WHERE keyword = "Dial"', TRUE);
     if (!is_array($recordset)) {
         $this->errMsg = 'No se pueden consultar extensiones en FreePBX - ' . $dbFreepbx->errMsg;
         return NULL;
     }
     foreach ($recordset as $tupla) {
         $extensiones[$tupla['data']] = $tupla['data'];
     }
     $dbFreepbx = NULL;
     // Quitar de la lista las extensiones ya registradas
     $listaAgentes = $this->getAgents();
     if (!is_array($listaAgentes)) {
         return NULL;
     }
     foreach ($listaAgentes as $agente) {
         $k = $agente['type'] . '/' . $agente['number'];
         if (isset($extensiones[$k])) {
             unset($extensiones[$k]);
         }
     }
     return $extensiones;
 }