Beispiel #1
0
 function handleJSON_getContent($smarty, $module_name, $appletlist)
 {
     $respuesta = array('status' => 'success', 'message' => '(no message)');
     // Leer credenciales a partir del usuario y el perfil asociado
     global $arrConf;
     $dbAcl = new paloDB($arrConf["elastix_dsn"]["acl"]);
     $pACL = new paloACL($dbAcl);
     $userId = $pACL->getIdUser($_SESSION['elastix_user']);
     $mailCred = $this->leerPropiedadesWebmail($dbAcl, $userId);
     if (count($mailCred) <= 0) {
         $respuesta['status'] = 'error';
         $respuesta['message'] = _tr("You don't have a webmail account");
     } elseif (!$this->_checkEmailPassword("{$mailCred['login']}@{$mailCred['domain']}", isset($mailCred['password']) ? $mailCred['password'] : '')) {
         $respuesta['status'] = 'error';
         $respuesta['message'] = "{$mailCred['login']}@{$mailCred['domain']} " . _tr("does not exist locally or password is incorrect");
     } else {
         $imap = @imap_open("{localhost:143/notls}", "{$mailCred['login']}@{$mailCred['domain']}", isset($mailCred['password']) ? $mailCred['password'] : '');
         if (!$imap) {
             $respuesta['status'] = 'error';
             $respuesta['message'] = _tr('Imap: Connection error');
         } else {
             $this->leerInformacionImap($smarty, $module_name, $imap, $respuesta);
             imap_close($imap);
         }
     }
     $json = new Services_JSON();
     Header('Content-Type: application/json');
     return $json->encode($respuesta);
 }
Beispiel #2
0
function _moduleContent(&$smarty, $module_name)
{
    //global variables
    global $arrConf;
    global $arrConfModule;
    $arrConf = array_merge($arrConf, $arrConfModule);
    //folder path for custom templates
    $local_templates_dir = getWebDirModule($module_name);
    // se conecta a la base
    $pDB = new paloDB($arrConf['elastix_dsn']['elastix']);
    $pACL = new paloACL($pDB);
    $user = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : "";
    $uid = $pACL->getIdUser($user);
    //actions
    $accion = getAction();
    $content = "";
    switch ($accion) {
        case "save":
            $content = saveThemes($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $uid);
            break;
        default:
            $content = formThemes($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $uid);
            break;
    }
    return $content;
}
Beispiel #3
0
function _moduleContent(&$smarty, $module_name)
{
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    include_once "modules/{$module_name}/libs/paloSantoMyExtension.class.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);
    //folder path for custom templates
    $templates_dir = isset($arrConf['templates_dir']) ? $arrConf['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme'];
    //conexion resource
    $arrConf['dsn_conn_database'] = generarDSNSistema('asteriskuser', 'asterisk');
    $pDB = new paloDB($arrConf['dsn_conn_database']);
    $pDBACL = new paloDB($arrConf['elastix_dsn']['acl']);
    $pACL = new paloACL($pDBACL);
    $user = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : "";
    $extension = $pACL->getUserExtension($user);
    $isAdministrator = $pACL->isUserAdministratorGroup($user);
    if ($extension == "" || is_null($extension)) {
        if ($isAdministrator) {
            $smarty->assign("mb_message", "<b>" . $arrLang["no_extension"] . "</b>");
        } else {
            $smarty->assign("mb_message", "<b>" . $arrLang["contact_admin"] . "</b>");
        }
        return "";
    }
    //actions
    $action = getAction();
    $content = "";
    switch ($action) {
        case "save_new":
            $content = saveNewMyExtension($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang, $extension, $isAdministrator);
            break;
        default:
            // view_form
            $content = viewFormMyExtension($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang, $extension);
            break;
    }
    return $content;
}
Beispiel #4
0
 function handleJSON_getContent($smarty, $module_name, $appletlist)
 {
     $respuesta = array('status' => 'success', 'message' => '(no message)');
     // Leer credenciales a partir del usuario y el perfil asociado
     global $arrConf;
     $dbAcl = new paloDB($arrConf["elastix_dsn"]["acl"]);
     $pACL = new paloACL($dbAcl);
     $userId = $pACL->getIdUser($_SESSION['elastix_user']);
     $listaEventos = $this->_leerRegistrosEventos($userId);
     $listaEventosDias = $this->_expandirRegistrosEventos($listaEventos);
     $smarty->assign(array('NO_EVENTOS' => _tr("You don't have events"), 'EVENTOS_DIAS' => $listaEventosDias, 'tag_date' => _tr("Date"), 'tag_call' => _tr("Call")));
     $local_templates_dir = dirname($_SERVER['SCRIPT_FILENAME']) . "/modules/{$module_name}/applets/Calendar/tpl";
     $respuesta['html'] = $smarty->fetch("{$local_templates_dir}/calendar_events.tpl");
     $json = new Services_JSON();
     Header('Content-Type: application/json');
     return $json->encode($respuesta);
 }
Beispiel #5
0
function new_module($smarty, $module_name, $local_templates_dir, $arrLangModule, &$pDB_acl)
{
    require_once 'libs/paloSantoACL.class.php';
    global $arrConfig;
    $pACL = new paloACL($pDB_acl);
    $groups = $pACL->getGroups();
    $ip = $_SERVER["SERVER_ADDR"];
    foreach ($groups as $value) {
        $arrGroups[$value[0]] = $value[1];
    }
    $arrFormElements = array("group_permissions" => array("LABEL" => $arrLangModule["Group Permission"], "REQUIRED" => "yes", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => $arrGroups, "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => "", "EDITABLE" => "no", "SIZE" => "3", "MULTIPLE" => true));
    $oForm = new paloForm($smarty, $arrFormElements);
    $smarty->assign("SAVE", $arrLangModule["Save"]);
    $smarty->assign("REQUIRED_FIELD", $arrLangModule["Required field"]);
    $smarty->assign("general_information", $arrLangModule["General Information"]);
    $smarty->assign("location", $arrLangModule["Location"]);
    $smarty->assign("module_description", $arrLangModule["Module Description"]);
    $smarty->assign("option_type", $arrConfig['arr_type']);
    $smarty->assign("email", $arrLangModule["Your e-mail"]);
    $smarty->assign("module_name_label", $arrLangModule["Module Name"]);
    $smarty->assign("id_module_label", $arrLangModule["Module Id"]);
    $smarty->assign("arrGroups", $arrGroups);
    $smarty->assign("your_name_label", $arrLangModule["Your Name"]);
    $smarty->assign("module_type", $arrLangModule["Module Type"]);
    $smarty->assign("type_grid", $arrLangModule["Grid"]);
    $smarty->assign("type_form", $arrLangModule["Form"]);
    $smarty->assign("type_framed", $arrLangModule["Framed"]);
    $smarty->assign("Field_Name", $arrLangModule["Field Name"]);
    $smarty->assign("Type_Field", $arrLangModule["Type Field"]);
    $smarty->assign("Url", $arrLangModule["Url"]);
    $smarty->assign("level_2", $arrLangModule["Level 2"]);
    $smarty->assign("level_3", $arrLangModule["Level 3"]);
    $smarty->assign("parent_1_exists", $arrLangModule["Level 1 Parent Exists"]);
    $smarty->assign("parent_2_exists", $arrLangModule["Level 2 Parent Exists"]);
    $smarty->assign("peYes", $arrLangModule["Yes"]);
    $smarty->assign("peNo", $arrLangModule["No"]);
    $smarty->assign("module_level", $arrLangModule["Module Level"]);
    $smarty->assign("level_1_parent_name", $arrLangModule["Level 1 Parent Name"]);
    $smarty->assign("level_1_parent_id", $arrLangModule["Level 1 Parent Id"]);
    $smarty->assign("icon", "modules/{$module_name}/images/developer.png");
    $html = $oForm->fetchForm("{$local_templates_dir}/new_module.tpl", $arrLangModule["Build Module"], $_POST);
    //$contenidoModulo = "<form method='POST' style='margin-bottom:0;' action='?menu=$module_name'>".$html."</form>";
    return $html;
}
 function Obtain_Protocol_Current_User($arrConf)
 {
     $pDB_acl = new paloDB($arrConf['elastix_dsn']['acl']);
     $pACL = new paloACL($pDB_acl);
     $username = $_SESSION["elastix_user"];
     $extension = $pACL->getUserExtension($username);
     if ($extension) {
         $dsnAsterisk = generarDSNSistema('asteriskuser', 'asterisk');
         $pDB = new paloDB($dsnAsterisk);
         $query = "SELECT dial, description, id FROM devices WHERE id={$extension}";
         $result = $pDB->getFirstRowQuery($query, TRUE);
         if ($result != FALSE) {
             return $result;
         } else {
             return FALSE;
         }
     } else {
         return FALSE;
     }
 }
 function handleJSON_getContent($smarty, $module_name, $appletlist)
 {
     $respuesta = array('status' => 'success', 'message' => '(no message)');
     // Obtener extensión del usuario logoneado
     global $arrConf;
     $dbAcl = new paloDB($arrConf["elastix_dsn"]["acl"]);
     $pACL = new paloACL($dbAcl);
     $extension = $pACL->getUserExtension($_SESSION["elastix_user"]);
     if (empty($extension) || !ctype_digit($extension)) {
         $respuesta['status'] = 'error';
         $respuesta['message'] = _tr("You haven't extension");
         if (!empty($pACL->errMsg)) {
             $respuesta['message'] = $pACL->errMsg;
         }
     } else {
         $this->_formatReportForExtension($smarty, $module_name, $extension, $respuesta);
     }
     $json = new Services_JSON();
     Header('Content-Type: application/json');
     return $json->encode($respuesta);
 }
 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;
 }
Beispiel #9
0
function saveNewKey($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrAST, $arrAMP)
{
    $arrFormNew = createFieldForm($pDB);
    $arrValues['id'] = getParameter("Extension");
    $arrValues['key'] = getParameter("Current_Secret");
    $arrValues['new_key'] = getParameter("New_Secret");
    $confirmation = getParameter("Confirm_New_Secret");
    $pDB2 = new paloDB($arrConf['elastix_dsn']['acl']);
    $pACL = new paloACL($pDB2);
    $oForm = new paloForm($smarty, $arrFormNew);
    if (!$oForm->validateForm($_POST)) {
        // Falla la validación básica del formulario
        $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br/>";
        $arrErrores = $oForm->arrErroresValidacion;
        if (is_array($arrErrores) && count($arrErrores) > 0) {
            foreach ($arrErrores as $k => $v) {
                $strErrorMsg .= "{$k}: [{$v['mensaje']}] <br /> ";
            }
        }
        $smarty->assign("mb_title", _tr("Validation Error"));
        $smarty->assign("mb_message", $strErrorMsg);
        return editWeakKeys($smarty, $module_name, $local_templates_dir, $arrConf, $pDB, $arrValues['id']);
    }
    $pWeakKeys = new paloSantoWeakKeys($pDB);
    $device = $pWeakKeys->getWeakKeyById($arrValues['id']);
    if (!$pACL->isUserAdministratorGroup($_SESSION['elastix_user'])) {
        if ($arrValues['key'] != $device['data']) {
            $smarty->assign("mb_title", _tr("Error"));
            $smarty->assign("mb_message", _tr("The Current Secret is invalid"));
            return editWeakKeys($smarty, $module_name, $local_templates_dir, $arrConf, $pDB, $arrValues['id']);
        }
    }
    if ($arrValues['new_key'] != $confirmation) {
        $smarty->assign("mb_title", _tr("Error"));
        $smarty->assign("mb_message", _tr("The New Secret does not match with the Confirmation Secret"));
        return editWeakKeys($smarty, $module_name, $local_templates_dir, $arrConf, $pDB, $arrValues['id']);
    }
    $mensaje = getMensaje($arrValues['id'], $arrValues['new_key']);
    if ($mensaje != "OK") {
        $smarty->assign("mb_title", _tr("Error"));
        $smarty->assign("mb_message", $mensaje);
        return editWeakKeys($smarty, $module_name, $local_templates_dir, $arrConf, $pDB, $arrValues['id']);
    }
    if (!$pWeakKeys->saveNewKey($arrValues, $device['tech'])) {
        $smarty->assign("mb_title", _tr("Error"));
        $smarty->assign("mb_message", $pWeakKeys->errMsg);
        return editWeakKeys($smarty, $module_name, $local_templates_dir, $arrConf, $pDB, $arrValues['id']);
    }
    $data_connection = array('host' => $arrConf['AMI_HOST'], 'user' => $arrConf['AMI_USER'], 'password' => $arrConf['AMI_PASS']);
    $pLoadExtension = new paloSantoLoadExtension($pDB);
    if (!$pLoadExtension->do_reloadAll($data_connection, $arrAST, $arrAMP)) {
        $smarty->assign("mb_title", _tr("Error"));
        $smarty->assign("mb_message", $pLoadExtension->errMsg);
        return editWeakKeys($smarty, $module_name, $local_templates_dir, $arrConf, $pDB, $arrValues['id']);
    }
    $smarty->assign("mb_title", _tr("Message"));
    $smarty->assign("mb_message", _tr("Successful Secret Update"));
    return reportWeakKeys($smarty, $module_name, $local_templates_dir, $pDB, $arrConf);
}
Beispiel #10
0
function _moduleContent(&$smarty, $module_name)
{
    require_once "modules/{$module_name}/libs/ringgroup.php";
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    load_language_module($module_name);
    global $arrConf;
    global $arrConfModule;
    $arrConf = array_merge($arrConf, $arrConfModule);
    //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'];
    // DSN para consulta de cdrs
    $dsn = generarDSNSistema('asteriskuser', 'asteriskcdrdb');
    $pDB = new paloDB($dsn);
    $oCDR = new paloSantoCDR($pDB);
    $pDBACL = new paloDB($arrConf['elastix_dsn']['acl']);
    if (!empty($pDBACL->errMsg)) {
        return "ERROR DE DB: {$pDBACL->errMsg}";
    }
    $pACL = new paloACL($pDBACL);
    if (!empty($pACL->errMsg)) {
        return "ERROR DE ACL: {$pACL->errMsg}";
    }
    $exten = '6868';
    //$pACL->getUserExtension($_SESSION['elastix_user']);
    $isAdministrator = true;
    //$pACL->isUserAdministratorGroup($_SESSION['elastix_user']);
    if (is_null($exten) || $exten == "") {
        if (!$isAdministrator) {
            $smarty->assign('mb_message', "<b>" . _tr("contact_admin") . "</b>");
            return "";
        } else {
            $smarty->assign('mb_message', "<b>" . _tr("no_extension") . "</b>");
        }
    }
    // Para usuarios que no son administradores, se restringe a los CDR de la
    // propia extensión
    $sExtension = $isAdministrator ? '' : $pACL->getUserExtension($_SESSION['elastix_user']);
    // DSN para consulta de ringgroups
    $dsn_asterisk = generarDSNSistema('asteriskuser', 'asterisk');
    $pDB_asterisk = new paloDB($dsn_asterisk);
    $oRG = new RingGroup($pDB_asterisk);
    $dataRG = $oRG->getRingGroup();
    $dataRG[''] = _tr('(Any ringgroup)');
    // Cadenas estáticas en la plantilla
    $smarty->assign(array("Filter" => _tr("Filter")));
    $arrFormElements = array("date_start" => array("LABEL" => _tr("Start Date"), "REQUIRED" => "yes", "INPUT_TYPE" => "DATE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}\$"), "date_end" => array("LABEL" => _tr("End Date"), "REQUIRED" => "yes", "INPUT_TYPE" => "DATE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}\$"), "field_name" => array("LABEL" => _tr("Field Name"), "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => array("dst" => _tr("Destination"), "src" => _tr("Source"), "channel" => _tr("Src. Channel"), "accountcode" => _tr("Account Code"), "dstchannel" => _tr("Dst. Channel")), "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^(dst|src|channel|dstchannel|accountcode)\$"), "field_pattern" => array("LABEL" => _tr("Field"), "REQUIRED" => "no", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[\\*|[:alnum:]@_\\.,/\\-]+\$"), "status" => array("LABEL" => _tr("Status"), "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => array("ALL" => _tr("ALL"), "ANSWERED" => _tr("ANSWERED"), "BUSY" => _tr("BUSY"), "FAILED" => _tr("FAILED"), "NO ANSWER " => _tr("NO ANSWER")), "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "ringgroup" => array("LABEL" => _tr("Ring Group"), "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => $dataRG, "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""));
    $oFilterForm = new paloForm($smarty, $arrFormElements);
    // Parámetros base y validación de parámetros
    $url = array('menu' => $module_name);
    $paramFiltroBase = $paramFiltro = array('date_start' => date("d M Y"), 'date_end' => date("d M Y"), 'field_name' => 'dst', 'field_pattern' => '', 'status' => 'ALL', 'ringgroup' => '');
    foreach (array_keys($paramFiltro) as $k) {
        if (!is_null(getParameter($k))) {
            $paramFiltro[$k] = getParameter($k);
        }
    }
    $oGrid = new paloSantoGrid($smarty);
    if ($paramFiltro['date_start'] === "") {
        $paramFiltro['date_start'] = " ";
    }
    if ($paramFiltro['date_end'] === "") {
        $paramFiltro['date_end'] = " ";
    }
    $valueFieldName = $arrFormElements['field_name']["INPUT_EXTRA_PARAM"][$paramFiltro['field_name']];
    $valueStatus = $arrFormElements['status']["INPUT_EXTRA_PARAM"][$paramFiltro['status']];
    $valueRingGRoup = $arrFormElements['ringgroup']["INPUT_EXTRA_PARAM"][$paramFiltro['ringgroup']];
    $oGrid->addFilterControl(_tr("Filter applied: ") . _tr("Start Date") . " = " . $paramFiltro['date_start'] . ", " . _tr("End Date") . " = " . $paramFiltro['date_end'], $paramFiltro, array('date_start' => date("d M Y"), 'date_end' => date("d M Y")), true);
    $oGrid->addFilterControl(_tr("Filter applied: ") . $valueFieldName . " = " . $paramFiltro['field_pattern'], $paramFiltro, array('field_name' => "dst", 'field_pattern' => ""));
    $oGrid->addFilterControl(_tr("Filter applied: ") . _tr("Status") . " = " . $valueStatus, $paramFiltro, array('status' => 'ALL'), true);
    $oGrid->addFilterControl(_tr("Filter applied: ") . _tr("Ring Group") . " = " . $valueRingGRoup, $paramFiltro, array('ringgroup' => ''));
    $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $paramFiltro);
    if (!$oFilterForm->validateForm($paramFiltro)) {
        $smarty->assign(array('mb_title' => _tr('Validation Error'), 'mb_message' => '<b>' . _tr('The following fields contain errors') . ':</b><br/>' . implode(', ', array_keys($oFilterForm->arrErroresValidacion))));
        $paramFiltro = $paramFiltroBase;
        unset($_POST['delete']);
        // Se aborta el intento de borrar CDRs, si había uno.
    }
    // Tradudir fechas a formato ISO para comparación y para API de CDRs.
    $url = array_merge($url, $paramFiltro);
    $paramFiltro['date_start'] = translateDate($paramFiltro['date_start']) . ' 00:00:00';
    $paramFiltro['date_end'] = translateDate($paramFiltro['date_end']) . ' 23:59:59';
    // Valores de filtrado que no se seleccionan mediante filtro
    if ($sExtension != '') {
        $paramFiltro['extension'] = $sExtension;
    }
    // Ejecutar el borrado, si se ha validado.
    if (isset($_POST['delete'])) {
        if ($isAdministrator) {
            if ($paramFiltro['date_start'] <= $paramFiltro['date_end']) {
                $r = $oCDR->borrarCDRs($paramFiltro);
                if (!$r) {
                    $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => $oCDR->errMsg));
                }
            } else {
                $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => _tr("Please End Date must be greater than Start Date")));
            }
        } else {
            $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => _tr("Only administrators can delete CDRs")));
        }
    }
    $oGrid->setTitle(_tr("CDR Report"));
    $oGrid->pagingShow(true);
    // show paging section.
    $oGrid->enableExport();
    // enable export.
    $oGrid->setNameFile_Export(_tr("CDRReport"));
    $oGrid->setURL($url);
    //if($isAdministrator)
    //$oGrid->deleteList("Are you sure you wish to delete CDR(s) Report(s)?","delete",_tr("Delete"));
    $arrData = null;
    if (!isset($sExtension) || $sExtension == "" && !$isAdministrator) {
        $total = 0;
    } else {
        $total = $oCDR->contarCDRs($paramFiltro);
    }
    if ($oGrid->isExportAction()) {
        $limit = $total;
        $offset = 0;
        $arrColumns = array(_tr("Date"), _tr("Source"), _tr("Ring Group"), _tr("Destination"), _tr("Src. Channel"), _tr("Account Code"), _tr("Dst. Channel"), _tr("Status"), _tr("Duration"));
        $oGrid->setColumns($arrColumns);
        $arrResult = $oCDR->listarCDRs($paramFiltro, $limit, $offset);
        if (is_array($arrResult['cdrs']) && $total > 0) {
            foreach ($arrResult['cdrs'] as $key => $value) {
                $arrTmp[0] = date("d-m-Y H:i:s", strtotime($value[0]));
                $arrTmp[1] = $value[1];
                $arrTmp[2] = $value[11];
                $arrTmp[3] = $value[3];
                $arrTmp[4] = $value[9];
                $arrTmp[5] = $value[5];
                $iDuracion = $value[8];
                $iSec = $iDuracion % 60;
                $iDuracion = (int) (($iDuracion - $iSec) / 60);
                $iMin = $iDuracion % 60;
                $iDuracion = (int) (($iDuracion - $iMin) / 60);
                $sTiempo = "{$value[6]}s";
                if ($value[6] >= 60) {
                    if ($iDuracion > 0) {
                        $sTiempo .= " ({$iDuracion}h {$iMin}m {$iSec}s)";
                    } elseif ($iMin > 0) {
                        $sTiempo .= " ({$iMin}m {$iSec}s)";
                    }
                }
                $arrTmp[7] = $sTiempo;
                $arrData[] = $arrTmp;
            }
        }
        if (!is_array($arrResult)) {
            $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => $oCDR->errMsg));
        }
    } else {
        $limit = 20;
        $oGrid->setLimit($limit);
        $oGrid->setTotal($total);
        $offset = $oGrid->calculateOffset();
        $arrResult = $oCDR->listarCDRs($paramFiltro, $limit, $offset);
        $arrColumns = array('STT', _tr("Date"), _tr("Source"), _tr("Destination"), _tr("Src. Channel"), _tr("Dst. Channel"), _tr("Status"), _tr("Duration"));
        $oGrid->setColumns($arrColumns);
        if (is_array($arrResult['cdrs']) && $total > 0) {
            $index = 0;
            foreach ($arrResult['cdrs'] as $key => $value) {
                $arrTmp[0] = $index;
                $arrTmp[1] = date("d-m-Y H:i:s", strtotime($value[0]));
                $arrTmp[2] = $value[1];
                $arrTmp[3] = $value[2];
                $arrTmp[4] = channel_lookup($pDB_asterisk, $value[3]);
                $arrTmp[5] = channel_lookup($pDB_asterisk, $value[4]);
                $arrTmp[6] = $value[5];
                $iDuracion = $value[8];
                $iSec = $iDuracion % 60;
                $iDuracion = (int) (($iDuracion - $iSec) / 60);
                $iMin = $iDuracion % 60;
                $iDuracion = (int) (($iDuracion - $iMin) / 60);
                $sTiempo = "{$value[8]}s";
                if ($value[7] >= 60) {
                    if ($iDuracion > 0) {
                        $sTiempo .= " ({$iDuracion}h {$iMin}m {$iSec}s)";
                    } elseif ($iMin > 0) {
                        $sTiempo .= " ({$iMin}m {$iSec}s)";
                    }
                }
                $arrTmp[7] = $sTiempo;
                $arrData[] = $arrTmp;
                $index++;
            }
        }
        if (!is_array($arrResult)) {
            $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => $oCDR->errMsg));
        }
    }
    $oGrid->setData($arrData);
    $smarty->assign("SHOW", _tr("Show"));
    $oGrid->showFilter($htmlFilter);
    $content = $oGrid->fetchGrid();
    return $content;
}
Beispiel #11
0
function addRemovePortsUser($smarty, $module_name, $local_templates_dir, $pDB, $arrConf)
{
    // Listar los usuarios y preparar el combo de usuarios disponibles
    $pACL = new paloACL($arrConf['elastix_dsn']['acl']);
    $id_user = getParameter('id_user');
    $userlist = $pACL->getUsers();
    $cbo_users = array();
    foreach ($userlist as $userinfo) {
        $cbo_users[$userinfo[0]] = $userinfo[1] . ' - ' . $userinfo[2];
    }
    // Verificar si el usuario existe
    if (!is_null($id_user)) {
        if (!isset($cbo_users[$id_user])) {
            Header("Location: ?menu={$module_name}");
            return NULL;
        }
    } else {
        $id_user = $userlist[0][0];
    }
    $ps = new paloSantoPortService($pDB);
    $pk = new paloSantoPortKnockUsers($pDB);
    // Construir lista de puertos autorizados
    $userauth = $pk->listAuthorizationsForUser($id_user);
    $portauths = array();
    if (is_array($userauth)) {
        foreach ($userauth as $auth) {
            $portauths[$auth['id_port']] = $auth['id'];
        }
    }
    $portlist = $ps->ObtainPuertos($ps->ObtainNumPuertos('', ''), 0, '', '');
    $listaIdPuertos = array();
    foreach ($portlist as $portinfo) {
        $listaIdPuertos[] = $portinfo['id'];
    }
    if (isset($_POST['apply']) && is_array($_POST['auth_port'])) {
        // Se requiere aplicar lista de cambios
        $listaNuevosPuertos = array_keys($_POST['auth_port']);
        $bReglasBorradas = FALSE;
        // Borrar la autorización de todos los puertos que ya no aparecen
        $bExito = TRUE;
        foreach ($portauths as $id_port => $id_auth) {
            if (!in_array($id_port, $listaNuevosPuertos)) {
                if (!$pk->deleteAuthorization($id_auth)) {
                    $smarty->assign("mb_title", _tr("ERROR"));
                    $smarty->assign("mb_message", $pk->errMsg);
                    $bExito = FALSE;
                    break;
                } else {
                    unset($portauths[$id_port]);
                    $bReglasBorradas = TRUE;
                }
            }
        }
        if (!$bExito) {
            break;
        }
        // Ingresar la autorización de los puertos nuevos
        foreach ($listaNuevosPuertos as $id_port) {
            if (in_array($id_port, $listaIdPuertos) && !isset($portauths[$id_port])) {
                $id_nueva_auth = $pk->insertAuthorization($id_user, $id_port);
                if (is_null($id_nueva_auth)) {
                    $smarty->assign("mb_title", _tr("ERROR"));
                    $smarty->assign("mb_message", $pk->errMsg);
                    $bExito = FALSE;
                    break;
                } else {
                    $portauths[$id_port] = $id_nueva_auth;
                }
            }
        }
        if ($bExito) {
            if ($bReglasBorradas) {
                // Ejecutar iptables para revocar las reglas del usuario
                require_once "modules/sec_rules/libs/paloSantoRules.class.php";
                $pr = new paloSantoRules($pDB);
                $pr->activateRules();
            }
            Header("Location: ?menu={$module_name}");
            return NULL;
        }
    }
    $data = array();
    if (is_array($portlist)) {
        foreach ($portlist as $portinfo) {
            $id_port = $portinfo['id'];
            $protocol_details = '';
            switch ($portinfo['protocol']) {
                case 'TCP':
                case 'UDP':
                    $protocol_details = (stripos($portinfo['details'], ':') === false ? _tr('Port') : _tr('Ports')) . ' ' . $portinfo['details'];
                    break;
                case 'ICMP':
                    $arr = explode(':', $portinfo['details']);
                    if (isset($arr[1])) {
                        $protocol_details = _tr('Type') . ": " . $arr[0] . " " . _tr('Code') . ": " . $arr[1];
                    }
                    break;
                default:
                    $protocol_details = _tr('Protocol Number') . ': ' . $portinfo['details'];
                    break;
            }
            $data[] = array("<input type=\"checkbox\" name=\"auth_port[{$id_port}]\" " . (isset($portauths[$id_port]) ? 'checked="checked"' : '') . ' />', htmlentities($portinfo['name'], ENT_COMPAT, 'UTF-8'), htmlentities($portinfo['protocol'], ENT_COMPAT, 'UTF-8'), $protocol_details);
        }
    }
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->setTitle(_tr('Add/remove ports for user'));
    $oGrid->setColumns(array('', _tr('Port'), _tr('Protocol'), _tr('Details')));
    $oGrid->addSubmitAction('apply', _tr('Apply changes'), "modules/{$module_name}/images/Check.png");
    $oGrid->addComboAction('id_user', _tr('User'), $cbo_users, $id_user, 'refresh', 'submit();');
    // Construcción de la vista de puertos autorizados
    $oGrid->pagingShow(false);
    $url = array("menu" => $module_name);
    $oGrid->setURL($url);
    $oGrid->setData($data);
    return $oGrid->fetchGrid();
}
 function getDataUserLogon($nameUser)
 {
     global $arrConf;
     //consulto datos del usuario logoneado
     $dbAcl = new paloDB($arrConf["elastix_dsn"]["acl"]);
     $pACL = new paloACL($dbAcl);
     $arrData = null;
     //paso 1: consulta de los datos de webmail si existen
     $userId = $pACL->getIdUser($nameUser);
     $arrData = $this->leerPropiedadesWebmail($dbAcl, $userId);
     if (!$arrData) {
         $arrData['login'] = '';
         $arrData['domain'] = '';
         $arrData['password'] = '';
     }
     //paso 2: consulta de la extension si tiene asignada
     $extension = $pACL->getUserExtension($nameUser);
     if ($extension) {
         $arrData['extension'] = $extension;
     }
     $arrData['id'] = $userId;
     return $arrData;
 }
 function deleteUserOrganization($idUser)
 {
     $pACL = new paloACL($this->_DB);
     $pEmail = new paloEmail($this->_DB);
     $pFax = new paloFax($this->_DB);
     $Exito = false;
     //1)se comprueba de que el ID de USUARIO se un numero
     //2)se verifica que exista dicho usuario
     //3)se recompila los datos del usuario de las tablas acl_user y user_properties
     //4)se elimina al usuario de la base
     //5)se elimina la extension de uso del usuario y la extension de fax
     //6)se trata de eliminar la cuenta de fax
     //7)se elimina el buzon de correo
     if (!preg_match('/^[[:digit:]]+$/', "{$idUser}")) {
         $this->errMsg = _tr("User ID is not numeric");
         return false;
     } else {
         $arrUser = $pACL->getUsers($idUser);
         if ($arrUser === false || count($arrUser) == 0) {
             $this->errMsg = _tr("User dosen't exist");
             return false;
         }
     }
     $idDomain = $arrUser[0][4];
     $query = "Select domain from organization where id=?";
     $getDomain = $this->_DB->getFirstRowQuery($query, false, array($idDomain));
     if ($getDomain == false) {
         $this->errMsg = $this->_DB->errMsg;
         return false;
     }
     $pDevice = new paloDevice($getDomain[0], "sip", $this->_DB);
     $arrExten = $pDevice->getExtension($arrUser[0][5]);
     $faxList = $pFax->getFaxList($arrUser[0][6], $getDomain[0]);
     $arrFaxExten = $faxList[0];
     $this->_DB->beginTransaction();
     //tomamos un backup de las extensiones que se van a eliminar de la base astDB por si algo sale mal
     //y ahi que restaurar la extension
     $arrExt = $pDevice->backupAstDBEXT($arrUser[0][5]);
     if ($pDevice->deleteExtension($arrUser[0][5])) {
         if ($pFax->deleteFaxByUser($idUser)) {
             if ($pACL->deleteUser($idUser)) {
                 if ($pEmail->deleteAccount($arrUser[0][1])) {
                     $Exito = true;
                     $this->_DB->commit();
                     $pDevice->tecnologia->prunePeer($arrExten["device"], $arrExten["tech"]);
                     $pDevice->tecnologia->prunePeer($arrFaxExten["device"], $arrFaxExten["tech"]);
                     $pFax->restartService();
                 } else {
                     $this->errMsg = _tr("Email Account cannot be deleted") . $pEmail->errMsg;
                     $this->_DB->rollBack();
                     $pDevice->restoreBackupAstDBEXT($arrExt);
                     $pFax->createFaxFileConfig($arrFaxExten['dev_id'], $getDomain[0]);
                 }
             } else {
                 $this->errMsg = $pACL->errMsg;
                 $this->_DB->rollBack();
                 $pDevice->restoreBackupAstDBEXT($arrExt);
                 $pFax->createFaxFileConfig($arrFaxExten['dev_id'], $getDomain[0]);
             }
         } else {
             $this->errMsg = _tr("Fax cannot be deleted") . $pFax->errMsg;
             $this->_DB->rollBack();
             $pDevice->restoreBackupAstDBEXT($arrExt);
         }
     } else {
         $this->errMsg = _tr("User Extension can't be deleted") . $pDevice->errMsg;
         $this->_DB->rollBack();
         $pDevice->restoreBackupAstDBEXT($arrExt);
     }
     return $Exito;
 }
Beispiel #14
0
function transferCALL($smarty, $module_name, $local_templates_dir, $pDB, $pDB_2, $arrLang, $arrConf, $dsn_agi_manager, $dsnAsterisk)
{
    $padress_book = new paloAdressBook($pDB);
    $pACL = new paloACL($pDB_2);
    $id_user = $pACL->getIdUser($_SESSION["elastix_user"]);
    if ($id_user != FALSE) {
        $user = $pACL->getUsers($id_user);
        if ($user != FALSE) {
            $extension = $user[0][3];
            if ($extension != "") {
                $id = isset($_GET['id']) ? $_GET['id'] : (isset($_POST['id']) ? $_POST['id'] : "");
                $phone2tranfer = '';
                if (isset($_GET['type']) && $_GET['type'] == 'external') {
                    $contactData = $padress_book->contactData($id, $id_user, "external", false, null);
                    $phone2tranfer = $contactData['telefono'];
                } else {
                    $phone2tranfer = $id;
                }
                $result = $padress_book->Obtain_Protocol_from_Ext($dsnAsterisk, $extension);
                if ($result != FALSE) {
                    $result = $padress_book->TranferCall($dsn_agi_manager, $extension, $phone2tranfer, $result['dial'], $result['description']);
                    if (!$result) {
                        $smarty->assign("mb_title", $arrLang['ERROR'] . ":");
                        $smarty->assign("mb_message", $arrLang["The transfer couldn't be realized, maybe you don't have any conversation now."]);
                    }
                } else {
                    $smarty->assign("mb_title", $arrLang["Validation Error"]);
                    $smarty->assign("mb_message", $padress_book->errMsg);
                }
            }
        } else {
            $smarty->assign("mb_title", $arrLang["Validation Error"]);
            $smarty->assign("mb_message", $padress_book->errMsg);
        }
    } else {
        $smarty->assign("mb_title", $arrLang["Validation Error"]);
        $smarty->assign("mb_message", $padress_book->errMsg);
    }
    $content = report_adress_book($smarty, $module_name, $local_templates_dir, $pDB, $pDB_2, $arrLang, $arrConf, $dsn_agi_manager, $dsnAsterisk);
    return $content;
}
 /**
  * Function that verifies if the user in the variable $_SERVER['PHP_AUTH_USER'] is correctly authenticated
  *
  * @return  boolean   True if the authentication was successfully, or false if not
  */
 public function authentication()
 {
     global $arrConf;
     // Obligar a pedir un usuario y contraseña de ACL
     if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] == '') {
         $this->errorMSG["fc"] = 'UNAUTHORIZED';
         $this->errorMSG["fm"] = 'Not authorized';
         $this->errorMSG["fd"] = 'This method requires username/password authentication.';
         $this->errorMSG["cn"] = get_class($this);
         return false;
     }
     $pDB = new paloDB($arrConf['elastix_dsn']['acl']);
     $pACL = new paloACL($pDB);
     if (!empty($pACL->errMsg)) {
         $this->errorMSG["fc"] = 'UNAUTHORIZED';
         $this->errorMSG["fm"] = 'Authentication failed';
         $this->errorMSG["fd"] = 'Unable to authenticate due to DB error: ' . $pACL->errMsg;
         $this->errorMSG["cn"] = get_class($this);
         return false;
     }
     if (!$pACL->authenticateUser($_SERVER['PHP_AUTH_USER'], md5($_SERVER['PHP_AUTH_PW']))) {
         $this->errorMSG["fc"] = 'UNAUTHORIZED';
         $this->errorMSG["fm"] = 'Authentication failed';
         $this->errorMSG["fd"] = 'Invalid username or password';
         $this->errorMSG["cn"] = get_class($this);
         return false;
     }
     return true;
 }
Beispiel #16
0
    }
    $viewname = str_replace('..', '.', $viewname);
    // protect against going to subdirectories
    if (file_exists("{$documentRoot}/admin/views/" . $viewname . '.php')) {
        include "{$documentRoot}/admin/views/" . $viewname . '.php';
    }
}
/*******Empieza validación para saber si el usuario tiene permisos o no para ingresar al fop********/
$documentRoot = $_SERVER["DOCUMENT_ROOT"];
include_once "{$documentRoot}/libs/paloSantoDB.class.php";
include_once "{$documentRoot}/libs/paloSantoACL.class.php";
session_name("elastixSession");
session_start();
$elastix_user = isset($_SESSION["elastix_user"]) ? $_SESSION["elastix_user"] : null;
$pDB = new paloDB("sqlite3:////var/www/db/acl.db");
$pACL = new paloACL($pDB);
if (!$pACL->isUserAuthorized($elastix_user, "access", "fop")) {
    include_once "{$documentRoot}/libs/misc.lib.php";
    include_once "{$documentRoot}/configs/default.conf.php";
    $lang = get_language("{$documentRoot}/");
    if (file_exists("{$documentRoot}/lang/{$lang}.lang")) {
        include_once "{$documentRoot}/lang/{$lang}.lang";
    } else {
        include_once "{$documentRoot}/lang/en.lang";
    }
    global $arrConf;
    global $arrLang;
    $advice = isset($arrLang["Unauthorized"]) ? $arrLang["Unauthorized"] : "Unauthorized";
    $msg1 = isset($arrLang['You are not authorized to access this page.']) ? $arrLang['You are not authorized to access this page.'] : 'You are not authorized to access this page.';
    $msg2 = isset($arrLang['You have not permissions to access to Flash Operator Panel. Please contact your administrator.']) ? $arrLang['You have not permissions to access to Flash Operator Panel. Please contact your administrator.'] : 'You have not permissions to access to Flash Operator Panel. Please contact your administrator.';
    $title = isset($arrLang['Advice']) ? $arrLang['Advice'] : 'Advice';
Beispiel #17
0
    session_name("elastixSession");
    session_start();
    header("Location: index.php");
    exit;
}
//cargar el archivo de idioma
load_language();
$lang = get_language();
if (file_exists("langmenus/{$lang}.lang")) {
    include_once "langmenus/{$lang}.lang";
    global $arrLangMenu;
    global $arrLang;
    $arrLang = array_merge($arrLang, $arrLangMenu);
}
$pdbACL = new paloDB($arrConf['elastix_dsn']['elastix']);
$pACL = new paloACL($pdbACL);
if (!empty($pACL->errMsg)) {
    echo "ERROR DE DB: {$pACL->errMsg} <br>";
}
// Load smarty
$smarty = getSmarty($arrConf['mainTheme']);
//- 1) SUBMIT. Si se hizo submit en el formulario de ingreso
//-            autentico al usuario y lo ingreso a la sesion
if (isset($_POST['submit_login']) and !empty($_POST['input_user'])) {
    $pass_md5 = md5(trim($_POST['input_pass']));
    if ($pACL->authenticateUser($_POST['input_user'], $pass_md5)) {
        session_regenerate_id(TRUE);
        $_SESSION['elastix_user'] = trim($_POST['input_user']);
        $_SESSION['elastix_pass'] = $pass_md5;
        //fue necesario incluir esto aqui porque cuando te logueas en la interfaz
        //de usario final haces uso de esta variable
Beispiel #18
0
    */
 $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;
                 case 'domain':
                     $webmail_domain = $tupla[1];
                     break;
                 case 'password':
Beispiel #19
0
function handleJSON_get_sticky_note($smarty, $module_name)
{
    $jsonObject = new PaloSantoJSON();
    $id_menu = getParameter("id_menu");
    if (empty($id_menu)) {
        $jsonObject->set_status('ERROR');
        $jsonObject->set_error(_tr('Module not specified'));
    } else {
        global $arrConf;
        $pdbACL = new paloDB($arrConf['elastix_dsn']['acl']);
        $pACL = new paloACL($pdbACL);
        $idUser = $pACL->getIdUser($_SESSION['elastix_user']);
        $output = getStickyNote($pdbACL, $idUser, $id_menu);
        $jsonObject->set_status($output['status'] === TRUE ? 'OK' : 'ERROR');
        $jsonObject->set_error($output['msg']);
        $jsonObject->set_message($output['data']);
    }
    return $jsonObject->createJSON();
}
Beispiel #20
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;
}
Beispiel #21
0
function _moduleContent(&$smarty, $module_name)
{
    include_once "libs/paloSantoGrid.class.php";
    include_once "libs/paloSantoConfig.class.php";
    include_once "libs/paloSantoACL.class.php";
    include_once "libs/paloSantoForm.class.php";
    require_once "libs/misc.lib.php";
    include_once "lib/paloSantoVoiceMail.class.php";
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    $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);
    //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'];
    //segun el usuario que esta logoneado consulto si tiene asignada extension para buscar los voicemails
    $pDB = new paloDB($arrConf['elastix_dsn']['acl']);
    $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*");
    $arrAMP = $pConfig->leer_configuracion(false);
    $dsnAsterisk = $arrAMP['AMPDBENGINE']['valor'] . "://" . $arrAMP['AMPDBUSER']['valor'] . ":" . $arrAMP['AMPDBPASS']['valor'] . "@" . $arrAMP['AMPDBHOST']['valor'] . "/asterisk";
    $pDB_ast = new paloDB($dsnAsterisk);
    if (!empty($pDB->errMsg)) {
        echo "ERROR DE DB: {$pDB->errMsg} <br>";
    }
    $arrData = array();
    $pACL = new paloACL($pDB);
    if (!empty($pACL->errMsg)) {
        echo "ERROR DE ACL: {$pACL->errMsg} <br>";
    }
    $arrVoiceData = array();
    $inicio = $fin = $total = 0;
    $extension = $pACL->getUserExtension($_SESSION['elastix_user']);
    $ext = $extension;
    $esAdministrador = $pACL->isUserAdministratorGroup($_SESSION['elastix_user']);
    $bandCustom = true;
    if (is_null($ext) || $ext == "") {
        $bandCustom = false;
        if (!$esAdministrador) {
            $smarty->assign("mb_message", "<b>" . $arrLang["contact_admin"] . "</b>");
            return "";
        }
    }
    if ($esAdministrador) {
        $extension = "[[:digit:]]+";
    }
    $smarty->assign("menu", "voicemail");
    $smarty->assign("Filter", $arrLang['Show']);
    //formulario para el filtro
    $arrFormElements = createFieldFormVoiceList($arrLang);
    $oFilterForm = new paloForm($smarty, $arrFormElements);
    // Por omision las fechas toman el sgte. valor (la fecha de hoy)
    $date_start = date("Y-m-d") . " 00:00:00";
    $date_end = date("Y-m-d") . " 23:59:59";
    $dateStartFilter = getParameter('date_start');
    $dateEndFilter = getParameter('date_end');
    $report = false;
    if (getParameter('filter')) {
        if ($oFilterForm->validateForm($_POST)) {
            // Exito, puedo procesar los datos ahora.
            $date_start = translateDate($dateStartFilter) . " 00:00:00";
            $date_end = translateDate($dateEndFilter) . " 23:59:59";
            $arrFilterExtraVars = array("date_start" => $dateStartFilter, "date_end" => $dateEndFilter);
        } else {
            // Error
            $smarty->assign("mb_title", $arrLang["Validation Error"]);
            $arrErrores = $oFilterForm->arrErroresValidacion;
            $strErrorMsg = "<b>{$arrLang['The following fields contain errors']}:</b><br>";
            foreach ($arrErrores as $k => $v) {
                $strErrorMsg .= "{$k}, ";
            }
            $strErrorMsg .= "";
            $smarty->assign("mb_message", $strErrorMsg);
        }
        if ($dateStartFilter == "") {
            $dateStartFilter = " ";
        }
        if ($dateEndFilter == "") {
            $dateEndFilter = " ";
        }
        //se añade control a los filtros
        $report = true;
        $arrDate = array('date_start' => $dateStartFilter, 'date_end' => $dateEndFilter);
        $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST);
    } else {
        if (isset($dateStartFilter) and isset($dateEndFilter)) {
            $report = true;
            $date_start = translateDate($dateStartFilter) . " 00:00:00";
            $date_end = translateDate($dateEndFilter) . " 23:59:59";
            $arrDate = array('date_start' => $dateStartFilter, 'date_end' => $dateEndFilter);
            $arrFilterExtraVars = array("date_start" => $dateStartFilter, "date_end" => $dateEndFilter);
            $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_GET);
        } else {
            $report = true;
            //se añade control a los filtros
            $arrDate = array('date_start' => date("d M Y"), 'date_end' => date("d M Y"));
            $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", array('date_start' => date("d M Y"), 'date_end' => date("d M Y")));
        }
    }
    $oGrid = new paloSantoGrid($smarty);
    if ($report) {
        $oGrid->addFilterControl(_tr("Filter applied ") . _tr("Start Date") . " = " . $arrDate['date_start'] . ", " . _tr("End Date") . " = " . $arrDate['date_end'], $arrDate, array('date_start' => date("d M Y"), 'date_end' => date("d M Y")), true);
    }
    if (getParameter('submit_eliminar')) {
        borrarVoicemails();
        if ($oFilterForm->validateForm($_POST)) {
            // Exito, puedo procesar los datos ahora.
            $date_start = translateDate($_POST['date_start']) . " 00:00:00";
            $date_end = translateDate($_POST['date_end']) . " 23:59:59";
            $arrFilterExtraVars = array("date_start" => $_POST['date_start'], "date_end" => $_POST['date_end']);
        }
        $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST);
    }
    if (getParameter('config')) {
        if (!(is_null($ext) || $ext == "")) {
            return form_config($smarty, $module_name, $local_templates_dir, $arrLang, $ext, $pDB_ast);
        }
    }
    if (getParameter('save')) {
        if (!save_config($smarty, $module_name, $local_templates_dir, $arrLang, $ext, $pDB_ast)) {
            return form_config($smarty, $module_name, $local_templates_dir, $arrLang, $ext, $pDB_ast);
        }
    }
    if (getParameter('action') == "display_record") {
        $file = getParameter("name");
        $ext = getParameter("ext");
        $user = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : "";
        $extension = $pACL->getUserExtension($user);
        $esAdministrador = $pACL->isUserAdministratorGroup($user);
        $path = "/var/spool/asterisk/voicemail/default";
        $voicemailPath = "{$path}/{$ext}/INBOX/" . base64_decode($file);
        $tmpfile = basename($voicemailPath);
        $filetmp = "{$path}/{$ext}/INBOX/{$tmpfile}";
        if (!is_file($filetmp)) {
            die("<b>404 " . $arrLang["no_file"] . "</b>");
        }
        if (!$esAdministrador) {
            if ($extension != $ext) {
                die("<b>404 " . $arrLang["no_file"] . "</b>");
            }
            $voicemailPath = "{$path}/{$extension}/INBOX/" . base64_decode($file);
        }
        if (isset($file) && preg_match("/^[[:alpha:]]+[[:digit:]]+\\.(wav|WAV|Wav|mp3|gsm)\$/", base64_decode($file))) {
            if (!is_file($voicemailPath)) {
                die("<b>404 " . $arrLang["no_file"] . "</b>");
            }
            $sContenido = "";
            $name = basename($voicemailPath);
            $format = substr(strtolower($name), -3);
            // This will set the Content-Type to the appropriate setting for the file
            $ctype = '';
            switch ($format) {
                case "mp3":
                    $ctype = "audio/mpeg";
                    break;
                case "wav":
                    $ctype = "audio/x-wav";
                    break;
                case "Wav":
                    $ctype = "audio/x-wav";
                    break;
                case "WAV":
                    $ctype = "audio/x-wav";
                    break;
                case "gsm":
                    $ctype = "audio/x-gsm";
                    break;
                    // not downloadable
                // not downloadable
                default:
                    die("<b>404 " . $arrLang["no_file"] . "</b>");
                    break;
            }
            if ($sContenido == "") {
                $session_id = session_id();
            }
            $sContenido = <<<contenido
                    <embed src='index.php?menu={$module_name}&action=download&ext={$ext}&name={$file}&rawmode=yes&elastixSession={$session_id}' width=300, height=20 autoplay=true loop=false type="{$ctype}"></embed><br>
contenido;
            $smarty->assign("CONTENT", $sContenido);
            $smarty->display("_common/popup.tpl");
        } else {
            die("<b>404 " . $arrLang["no_file"] . "</b>");
        }
        return;
    }
    if (getParameter('action') == "download") {
        $user = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : "";
        $extension = $pACL->getUserExtension($user);
        $esAdministrador = $pACL->isUserAdministratorGroup($user);
        $record = getParameter("name");
        $ext = getParameter("ext");
        if (!preg_match("/^[[:digit:]]+\$/", $ext)) {
            Header("HTTP/1.1 404 Not Found");
            die("<b>404 " . $arrLang["no_file"] . "</b>");
        }
        $record = base64_decode($record);
        $path = "/var/spool/asterisk/voicemail/default";
        $voicemailPath = "{$path}/{$ext}/INBOX/" . $record;
        //"$path/$record";
        $tmpfile = basename($voicemailPath);
        $filetmp = "{$path}/{$ext}/INBOX/{$tmpfile}";
        if (!is_file($filetmp)) {
            die("<b>404 " . $arrLang["no_file"] . "</b>");
        }
        if (!$esAdministrador) {
            if ($extension != $ext) {
                Header("HTTP/1.1 404 Not Found");
                die("<b>404 " . $arrLang["no_extension"] . "</b>");
            }
            $voicemailPath = "{$path}/{$extension}/INBOX/" . $record;
        }
        if (isset($record) && preg_match("/^[[:alpha:]]+[[:digit:]]+\\.(wav|WAV|Wav|mp3|gsm)\$/", $record)) {
            // See if the file exists
            if (!is_file($voicemailPath)) {
                Header("HTTP/1.1 404 Not Found");
                die("<b>404 " . $arrLang["no_file"] . "</b>");
            }
            // Gather relevent info about file
            $size = filesize($voicemailPath);
            $name = basename($voicemailPath);
            //$extension = strtolower(substr(strrchr($name,"."),1));
            $extension = substr(strtolower($name), -3);
            // This will set the Content-Type to the appropriate setting for the file
            $ctype = '';
            switch ($extension) {
                case "mp3":
                    $ctype = "audio/mpeg";
                    break;
                case "wav":
                    $ctype = "audio/x-wav";
                    break;
                case "Wav":
                    $ctype = "audio/x-wav";
                    break;
                case "WAV":
                    $ctype = "audio/x-wav";
                    break;
                case "gsm":
                    $ctype = "audio/x-gsm";
                    break;
                    // not downloadable
                // not downloadable
                default:
                    die("<b>404 " . $arrLang["no_file"] . "</b>");
                    break;
            }
            // need to check if file is mislabeled or a liar.
            $fp = fopen($voicemailPath, "rb");
            if ($size && $ctype && $fp) {
                header("Pragma: public");
                header("Expires: 0");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Cache-Control: public");
                header("Content-Description: wav file");
                header("Content-Type: " . $ctype);
                header("Content-Disposition: attachment; filename=" . $name);
                header("Content-Transfer-Encoding: binary");
                header("Content-length: " . $size);
                fpassthru($fp);
            }
        } else {
            Header("HTTP/1.1 404 Not Found");
            die("<b>404 " . $arrLang["no_file"] . "</b>");
        }
        return;
    }
    $end = 0;
    $url = array('menu' => $module_name);
    //si tiene extension consulto sino, muestro un mensaje de que no tiene asociada extension
    $archivos = array();
    if (!(is_null($ext) || $ext == "") || $esAdministrador) {
        if (is_null($ext) || $ext == "") {
            $smarty->assign("mb_message", "<b>" . $arrLang["no_extension_assigned"] . "</b>");
        }
        $path = "/var/spool/asterisk/voicemail/default";
        $folder = "INBOX";
        if ($esAdministrador) {
            if ($handle = opendir($path)) {
                while (false !== ($dir = readdir($handle))) {
                    if ($dir != "." && $dir != ".." && ereg($extension, $dir, $regs) && is_dir($path . "/" . $dir)) {
                        $directorios[] = $dir;
                    }
                }
            }
        } else {
            $directorios[] = $extension;
        }
        //if($esAdministrador)
        $arrData = array();
        foreach ($directorios as $directorio) {
            $voicemailPath = "{$path}/{$directorio}/{$folder}";
            if (file_exists($voicemailPath)) {
                if ($handle = opendir($voicemailPath)) {
                    $bExito = true;
                    while (false !== ($file = readdir($handle))) {
                        //no tomar en cuenta . y ..
                        //buscar los archivos de texto (txt) que son los que contienen los datos de las llamadas
                        if ($file != "." && $file != ".." && ereg("(.+)\\.[txt|TXT]", $file, $regs)) {
                            //leer la info del archivo
                            $pConfig = new paloConfig($voicemailPath, $file, "=", "[[:space:]]*=[[:space:]]*");
                            $arrVoiceMailDes = array();
                            $arrVoiceMailDes = $pConfig->leer_configuracion(false);
                            //verifico que tenga datos
                            if (is_array($arrVoiceMailDes) && count($arrVoiceMailDes) > 0 && isset($arrVoiceMailDes['origtime']['valor'])) {
                                //uso las fechas del filtro
                                //si la fecha de llamada esta dentro del rango, la muestro
                                $fecha = date("Y-m-d", $arrVoiceMailDes['origtime']['valor']);
                                $hora = date("H:i:s", $arrVoiceMailDes['origtime']['valor']);
                                if (strtotime("{$fecha} {$hora}") <= strtotime($date_end) && strtotime("{$fecha} {$hora}") >= strtotime($date_start)) {
                                    $arrTmp[0] = "<input type='checkbox' name='" . utf8_encode("voc-" . $file) . ",{$directorio}' />";
                                    $arrTmp[1] = $fecha;
                                    $arrTmp[2] = $hora;
                                    $arrTmp[3] = $arrVoiceMailDes['callerid']['valor'];
                                    $arrTmp[4] = $arrVoiceMailDes['origmailbox']['valor'];
                                    $arrTmp[5] = $arrVoiceMailDes['duration']['valor'] . ' sec.';
                                    $pathRecordFile = base64_encode($regs[1] . '.wav');
                                    $recordingLink = "<a href='#' onClick=\"javascript:popUp('index.php?menu={$module_name}&action=display_record&ext={$directorio}&name={$pathRecordFile}&rawmode=yes',350,100); return false;\">{$arrLang['Listen']}</a>&nbsp;";
                                    $recordingLink .= "<a href='?menu={$module_name}&action=download&ext={$directorio}&name={$pathRecordFile}&rawmode=yes'>{$arrLang['Download']}</a>";
                                    $arrTmp[6] = $recordingLink;
                                    $arrData[] = $arrTmp;
                                }
                            }
                        }
                    }
                    closedir($handle);
                }
            } else {
                // No vale la ruta
            }
        }
        /*
        function sort_voicemails_hora_desc($a, $b) { return ($a[2] == $b[2]) ? 0 : (($a[2] < $b[2]) ? 1 : -1); }
        function sort_voicemails_fecha_desc($a, $b) { return ($a[1] == $b[1]) ? 0 : (($a[1] < $b[1]) ? 1 : -1); }
        usort($arrData, 'sort_voicemails_hora_desc');
        usort($arrData, 'sort_voicemails_fecha_desc');
        */
        $fechas = array();
        $horas = array();
        foreach ($arrData as $llave => $fila) {
            $fechas[$llave] = $fila[1];
            $horas[$llave] = $fila[2];
        }
        array_multisort($fechas, SORT_DESC, $horas, SORT_DESC, $arrData);
        //Paginacion
        $limit = 15;
        $total = count($arrData);
        $oGrid->setLimit($limit);
        $oGrid->setTotal($total);
        $offset = $oGrid->calculateOffset();
        $end = $offset + $limit <= $total ? $offset + $limit : $total;
        // Construyo el URL base
        if (isset($arrFilterExtraVars) && is_array($arrFilterExtraVars) and count($arrFilterExtraVars) > 0) {
            $url = array_merge($url, $arrFilterExtraVars);
        }
        //Fin Paginacion
        $arrVoiceData = array_slice($arrData, $offset, $limit);
    } else {
        $smarty->assign("mb_message", "<b>" . $arrLang["contact_admin"] . "</b>");
    }
    $arrGrid = array("title" => $arrLang["Voicemail List"], "url" => $url, "icon" => "/modules/{$module_name}/images/pbx_voicemail.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $end, "total" => $total, "columns" => array(0 => array("name" => "", "property1" => ""), 1 => array("name" => $arrLang["Date"], "property1" => ""), 2 => array("name" => $arrLang["Time"], "property1" => ""), 3 => array("name" => $arrLang["CallerID"], "property1" => ""), 4 => array("name" => $arrLang["Extension"], "property1" => ""), 5 => array("name" => $arrLang["Duration"], "property1" => ""), 6 => array("name" => $arrLang["Message"], "property1" => "")));
    if ($bandCustom == true) {
        $oGrid->customAction("config", _tr("Configuration"));
    }
    $oGrid->deleteList(_tr("Are you sure you wish to delete voicemails?"), "submit_eliminar", _tr("Delete"));
    $oGrid->showFilter($htmlFilter);
    $contenidoModulo = $oGrid->fetchGrid($arrGrid, $arrVoiceData, $arrLang);
    if (strpos($contenidoModulo, '<form') === FALSE) {
        $contenidoModulo = "<form style='margin-bottom:0;' method='POST' action='?menu={$module_name}'>{$contenidoModulo}</form>";
    }
    return $contenidoModulo;
}
Beispiel #22
0
function getSelected(&$pDB, $userLevel1)
{
    $jsonObject = new PaloSantoJSON();
    $pACL = new paloACL($pDB);
    $pORGZ = new paloSantoOrganization($pDB);
    $arrData = array();
    if ($userLevel1 != "superadmin") {
        $jsonObject->set_error("You are not authorized to perform this action. ");
    } else {
        $idOrg = getParameter("idOrg");
        //validamos que la organization exista
        $orgTmp = $pORGZ->getOrganization(array("id" => $idOrg));
        //valido que al menos exista una organizacion creada
        if ($orgTmp === false) {
            $jsonObject->set_error(_tr($pORGZ->errMsg));
        } elseif (count($orgTmp) <= 0) {
            $jsonObject->set_error(_tr("Organization doesn't exist"));
        } else {
            //obtengo los recursos asignados a la organizacion
            $arrResourceOrg = $pACL->getResourcesByOrg($idOrg);
            if ($arrResourceOrg === false) {
                $jsonObject->set_error(_tr($pACL->errMsg));
            } else {
                foreach ($arrResourceOrg as $resource) {
                    $arrData[] = $resource["id"];
                }
                $jsonObject->set_message($arrData);
            }
        }
    }
    return $jsonObject->createJSON();
}
Beispiel #23
0
function deleteGroup($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $userLevel1, $userAccount, $idOrganization)
{
    $pACL = new paloACL($pDB);
    $pORGZ = new paloSantoOrganization($pDB);
    $error = "";
    $idGroup = getParameter("id");
    if (isset($idGroup)) {
        // No se puede eliminar al grupo superadmin
        if ($idGroup == 0) {
            $error = _tr("This group  can't be deleted because is used to admin elastix.");
        } elseif ($pACL->getGroupNameByid($idGroup) == "administrator") {
            $error = _tr("The administrator group cannot be deleted because is the default Elastix Group. You can delete any other group.");
        } else {
            if ($userLevel1 == "superadmin") {
                $arrGroup = $pACL->getGroups($idGroup);
            } else {
                $arrGroup = $pACL->getGroups($idGroup, $idOrganization);
            }
            if ($arrGroup == false) {
                $error = _tr("Group doesn't exist") . $pACL->errMsg;
            }
        }
        if ($error == "") {
            if ($pACL->deleteGroup($idGroup)) {
                $smarty->assign("mb_title", _tr("MESSAGE"));
                $error = _tr("Group was deleted successfully");
            } else {
                $smarty->assign("mb_title", _tr("ERROR"));
                $error = _tr($pACL->errMsg);
            }
        } else {
            $smarty->assign("mb_title", _tr("ERROR"));
        }
    } else {
        $smarty->assign("mb_title", _tr("ERROR"));
        $error = _tr("Invalid Group");
    }
    $smarty->assign("mb_message", $error);
    return reportGroup($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $userLevel1, $userAccount, $idOrganization);
}
Beispiel #24
0
  | the License for the specific language governing rights and           |
  | limitations under the License.                                       |
  +----------------------------------------------------------------------+
  | The Original Code is: Elastix Open Source.                           |
  | The Initial Developer of the Original Code is PaloSanto Solutions    |
  +----------------------------------------------------------------------+
  $Id: openfireWrapper.php,v 1.0 2007/10/30 10:20:03 bmacias Exp $ */
include_once "libs/misc.lib.php";
include_once "configs/default.conf.php";
include_once "libs/paloSantoACL.class.php";
include_once "libs/paloSantoDB.class.php";
load_language();
session_name("elastixSession");
session_start();
$pDB = new paloDB($arrConf["elastix_dsn"]["acl"]);
$pACL = new paloACL($pDB);
if (isset($_SESSION["elastix_user"])) {
    $elastix_user = $_SESSION["elastix_user"];
} else {
    $elastix_user = "";
}
session_commit();
if (!$pACL->isUserAdministratorGroup($elastix_user)) {
    $advice = _tr("Unauthorized");
    $msg1 = _tr("You are not authorized to access to this page");
    $msg2 = _tr("You need administrator privileges");
    $template['content']['theme'] = $arrConf['mainTheme'];
    $template['content']['title'] = _tr("Elastix Authentication");
    $template['content']['msg'] = "<br /><b style='font-size:1.5em;'>{$advice}</b> <p>{$msg1}<br/>{$msg2}</p>";
    extract($template);
    if (file_exists("elastix_warning_authentication.php")) {
Beispiel #25
0
function backup_contacts($pDB, $pDB_2, $arrLang)
{
    $Messages = "";
    $csv = "";
    $pAdressBook = new paloAdressBook($pDB);
    $fields = "name, last_name, telefono, email";
    $pACL = new paloACL($pDB_2);
    $id_user = $pACL->getIdUser($_SESSION["elastix_user"]);
    $arrResult = $pAdressBook->getAddressBookByCsv(null, null, $fields, null, null, $id_user);
    if (!$arrResult) {
        $Messages .= $arrLang["There aren't contacts"] . ". " . $pAdressBook->errMsg;
        echo $Messages;
    } else {
        //cabecera
        $csv .= "\"Name\",\"Last Name\",\"Phone Number\",\"Email\",\"Address\",\"Company\"\n";
        foreach ($arrResult as $key => $contact) {
            $csv .= "\"{$contact['name']}\",\"{$contact['last_name']}\"," . "\"{$contact['telefono']}\",\"{$contact['email']}\"," . "\"{$contact['address']}\",\"{$contact['company']}\"" . "\n";
        }
    }
    return $csv;
}
Beispiel #26
0
function manejarLogin_HTML($module_name, &$smarty, $sDirLocalPlantillas)
{
    global $arrConf;
    // Acciones para mostrar el formulario, fuera de cualquier acción AJAX
    $smarty->assign(array('FRAMEWORK_TIENE_TITULO_MODULO' => existeSoporteTituloFramework(), 'icon' => 'modules/' . $module_name . '/images/call_center.png', 'title' => "Màn hình chính dành cho tổng đài viên", 'WELCOME_AGENT' => _tr('Welcome to Agent Console'), 'ENTER_USER_PASSWORD' => _tr('Please select your agent number and your extension'), 'USERNAME' => _tr('Agent Number'), 'EXTENSION' => _tr('Extension'), 'CALLBACK_LOGIN' => _tr('Callback Login'), 'PASSWORD' => _tr('Password'), 'CALLBACK_EXTENSION' => _tr('Callback Extension'), 'LABEL_SUBMIT' => _tr('Enter'), 'LABEL_NOEXTENSIONS' => _tr('There are no extensions available. At least one extension is required for agent login.'), 'LABEL_NOAGENTS' => _tr('There are no agents available. At least one agent is required for agent login.'), 'ESTILO_FILA_ESTADO_LOGIN' => 'style="visibility: hidden; position: absolute;"', 'REANUDAR_VERIFICACION' => 0));
    $oPaloConsola = new PaloSantoConsola();
    $listaExtensiones = $oPaloConsola->listarExtensiones();
    $listaAgentes = $oPaloConsola->listarAgentes('static');
    $listaExtensionesCallback = $oPaloConsola->listarAgentes('dynamic');
    $oPaloConsola->desconectarTodo();
    $oPaloConsola = NULL;
    $bNoHayAgentes = count($listaAgentes) == 0 && count($listaExtensionesCallback) == 0;
    if (count($listaAgentes) == 0) {
        $listaAgentes[] = _tr('(no agents)');
    }
    if (count($listaExtensionesCallback) == 0) {
        $listaExtensionesCallback[] = _tr('(no agents)');
    }
    $smarty->assign(array('LISTA_EXTENSIONES' => $listaExtensiones, 'LISTA_AGENTES' => $listaAgentes, 'LISTA_EXTENSIONES_CALLBACK' => $listaExtensionesCallback, 'NO_EXTENSIONS' => count($listaExtensiones) == 0, 'NO_AGENTS' => $bNoHayAgentes));
    // Restaurar el estado de espera en caso de que se refresque la página
    if (!is_null($_SESSION['callcenter']['agente']) && !is_null($_SESSION['callcenter']['extension'])) {
        $smarty->assign(array('ID_AGENT' => $_SESSION['callcenter']['agente'], 'ID_EXTENSION' => $_SESSION['callcenter']['extension'], 'ID_EXTENSION_CALLBACK' => $_SESSION['callcenter']['agente'], 'ESTILO_FILA_ESTADO_LOGIN' => 'style="visibility: visible; position: none;"', 'MSG_ESPERA' => _tr('Logging agent in. Please wait...'), 'REANUDAR_VERIFICACION' => 1));
    } else {
        /* Si el usuario Elastix logoneado coincide con el número de agente de
         * la lista, se coloca este agente como opción por omisión para login.
         */
        if (isset($listaAgentes['Agent/' . $_SESSION['elastix_user']])) {
            $smarty->assign('ID_AGENT', 'Agent/' . $_SESSION['elastix_user']);
        }
        /* Si el usuario Elastix logoneado tiene una extensión y aparece en la
         * lista, se sugiere esta extension como la extensión a usar para 
         * marcar. */
        $pACL = new paloACL($arrConf['elastix_dsn']['acl']);
        $idUser = $pACL->getIdUser($_SESSION['elastix_user']);
        if ($idUser !== FALSE) {
            $tupla = $pACL->getUsers($idUser);
            if (is_array($tupla) && count($tupla) > 0) {
                $sExtension = $tupla[0][3];
                if (isset($listaExtensiones[$sExtension])) {
                    $smarty->assign('ID_EXTENSION', $sExtension);
                }
                foreach (array_keys($listaExtensionesCallback) as $k) {
                    $regs = NULL;
                    if (preg_match('|^(\\w+)/(\\d+)$|', $k, $regs) && $regs[2] == $sExtension) {
                        $smarty->assign('ID_EXTENSION_CALLBACK', $k);
                    }
                }
            }
        }
    }
    $sContenido = $smarty->fetch("{$sDirLocalPlantillas}/hnh_login_agent.tpl");
    return $sContenido;
}
Beispiel #27
0
function updateRow_TicketDelivery($pDB, $pDB_2, $module_name)
{
    $sTicketId = trim(getParameter('ticket_id'));
    $pTicket_Delivery = new Ticket_Delivery($pDB);
    $pACL = new paloACL($pDB_2);
    $arrResult = $pTicket_Delivery->getTicket_DeliveryById($sTicketId);
    $img_dir = "modules/{$module_name}/images/";
    $value = $arrResult[0];
    $ticket = '';
    $name = $pACL->getUsers($value['accounting_id']);
    $elastix_user = is_null($value['accounting_id']) ? '(Chưa nhận)' : $name[0][1];
    // show files
    $download = '';
    foreach ($value['ticket_attachment'] as $row) {
        $url = "/modules/agent_console/ajax-attachments-handler.php?download=" . $row['filepath'] . "&name=" . $row['filename'];
        $filename = $row['filename'];
        $download .= "*<a href='{$url}' target='_blank' title='{$filename}'>" . shorten($filename) . "</a><br/>";
    }
    $print = '<a href="javascript:void(0)" onclick="print(\'' . $value['id'] . '\')"><img src="' . $img_dir . 'print.png" title="In phiếu"></a>';
    $enable = $value['isActive'] == '1' ? '<a href="javascript:void(0)" onclick="disable(\'' . $value['id'] . '\')"><img src="' . $img_dir . 'disable.png" title="Hủy yêu cầu giao vé"></a>&nbsp;' : '<a href="javascript:void(0)" onclick="enable(\'' . $value['id'] . '\')"><img src="' . $img_dir . 'enable.png" title="Tạo lại yêu cầu giao vé"></a>';
    $print .= '&nbsp;&nbsp;' . $enable;
    if ($value['isActive'] == '0') {
        $value['status'] = 'Đã hủy';
    }
    // function show base on status
    switch ($value['status']) {
        case 'Mới':
            $function = '<a href="javascript:void(1)" onclick="assign_form(\'' . $value['id'] . '\')"><img src="' . $img_dir . 'assign.png" title="Phân công"></a>';
            break;
        case 'Đang giao':
            $function = '<a href="javascript:void(1)" onclick="assign_form(\'' . $value['id'] . '\')"><img src="' . $img_dir . 'assign.png" title="Đổi phân công"></a>&nbsp;
                        <a href="javascript:void(1)" onclick="collect_form(\'' . $value['id'] . '\',\'' . $elastix_user . '\')"><img src="' . $img_dir . 'result.png" title="Kết quả"></a>';
            break;
        case 'Đã nhận tiền':
            $function = '<a href="javascript:void(1)" onclick="uncollect_form(\'' . $value['id'] . '\',\'' . $elastix_user . '\')"><img src="' . $img_dir . 'unpaid.png" title="Hủy nhận tiền"></a>';
            break;
        case 'Chờ xử lý':
            $function = '<a href="javascript:void(1)" onclick="assign_form(\'' . $value['id'] . '\')"><img src="' . $img_dir . 'assign.png" title="Phân công"></a>';
            break;
        default:
            $function = '';
    }
    // show ticket code
    foreach ($value['ticket_code'] as $row) {
        $ticket .= $row . '<br>';
    }
    // append html
    $html = '';
    $html .= '<td class="table_data">' . $value['id'] . '</td>';
    $html .= '<td class="table_data">' . $value['customer_name'] . '</td>';
    $html .= '<td class="table_data">' . $value['customer_phone'] . '</td>';
    $html .= '<td class="table_data"><span title="Chi nhánh: ' . $value['office'] . '">' . $value['agent_name'] . '</span></td>';
    $html .= '<td class="table_data">' . '<a href="javascript:void(1)" title="' . $value['deliver_address'] . '"
			                onclick="view_address(\'' . $value['deliver_address'] . '\')">' . shorten($value['deliver_address']) . '
			              </a></td>';
    $html .= '<td class="table_data">' . $value['pay_amount'] . '</td>';
    $html .= '<td class="table_data">' . $ticket . '</td>';
    $html .= '<td class="table_data">' . showStatus($value['status']) . '</td>';
    $html .= '<td class="table_data">' . $value['delivery_name'] . '</td>';
    $html .= '<td class="table_data">' . (is_null($value['delivery_date']) ? '' : date("d-m-Y H:m:s", strtotime($value['delivery_date']))) . '</td>';
    $html .= '<td class="table_data">' . $download . '</td>';
    $html .= '<td class="table_data">' . (is_null($value['collection_date']) ? '' : date("d-m-Y H:m:s", strtotime($value['collection_date']))) . '</td>';
    $html .= '<td class="table_data">' . $function . '</td>';
    $html .= '<td class="table_data"><a href="javascript:void(1)" onclick="view_log(\'' . $value['id'] . '\')">
			            <img src="' . $img_dir . 'extra.png" title="Xem chi tiết"></a></td>';
    $html .= '<td class="table_data">' . $print . '</td>';
    return $html;
}
Beispiel #28
0
function reportGroupPermission($smarty, $module_name, $local_templates_dir, &$pDB, $arrConf, $credentials)
{
    $pACL = new paloACL($pDB);
    $pORGZ = new paloSantoOrganization($pDB);
    $arrGroups = array();
    $arrOrgz = array();
    $idOrgFil = getParameter("idOrganization");
    if ($credentials['userlevel'] == "superadmin") {
        $orgTmp = $pORGZ->getOrganization(array());
        if ($orgTmp === false) {
            $smarty->assign("mb_title", _tr("ERROR"));
            $smarty->assign("mb_message", _tr($pORGZ->errMsg));
        } elseif (count($orgTmp) == 0) {
            $smarty->assign("mb_title", _tr("MESSAGE"));
            $msg = _tr("You haven't created any organization");
            $smarty->assign("mb_message", $msg);
        } else {
            //si el usuario a selecionado una organizacion comprobamos que esta exista
            //caso contrario procedemos a sellecionar la primera disponible
            $flag = false;
            foreach ($orgTmp as $value) {
                $arrOrgz[$value["id"]] = $value["name"];
                if ($value["id"] == $idOrgFil) {
                    $flag = true;
                }
            }
            if (!$flag) {
                $idOrgFil = $orgTmp[0]['id'];
            }
        }
    } else {
        $idOrgFil = $credentials['id_organization'];
        $orgTmp = $pORGZ->getOrganizationById($idOrgFil);
        if ($orgTmp == false) {
            $smarty->assign("mb_title", _tr("ERROR"));
            $smarty->assign("mb_message", _tr("An error has ocurred to retrieved organization data"));
        } else {
            $arrOrgz = $orgTmp;
        }
    }
    if (count($arrOrgz) > 0) {
        //que se un arreglo y que tenga al menos una organizacion
        $groupTmp = $pACL->getGroupsPaging(null, null, $idOrgFil);
        if ($groupTmp === false) {
            $smarty->assign("mb_title", _tr("ERROR"));
            $smarty->assign("mb_message", _tr($pACL->errMsg));
        } else {
            foreach ($groupTmp as $value) {
                $arrGroups[$value[0]] = $value[1];
            }
        }
    }
    $filter_group = getParameter("filter_group");
    if (count($arrGroups) > 0) {
        if (empty($filter_group)) {
            //seleccionamos el primer grupo de la lista de grupos
            $filter_group = $groupTmp[0][0];
        }
        //valido que el grupo pertenzca a la organizacion
        if ($pACL->getGroups($filter_group, $idOrgFil) == false) {
            $smarty->assign("mb_title", _tr("ERROR"));
            $smarty->assign("mb_message", _tr("Invalid Group"));
            $filter_group = $groupTmp[0][0];
        }
    }
    $filter_resource = getParameter("filter_resource");
    $lang = get_language();
    if ($lang != "en") {
        if (isset($filter_resource)) {
            if (trim($filter_resource) != "") {
                global $arrLang;
                $filter_value = strtolower(trim($filter_resource));
                $parameter_to_find[] = $filter_value;
                //parametro de busqueda sin traduccion
                foreach ($arrLang as $key => $value) {
                    $langValue = strtolower(trim($value));
                    if (preg_match("/^[[:alnum:]| ]*\$/", $filter_value)) {
                        if (strpos($langValue, $filter_value) !== FALSE) {
                            $parameter_to_find[] = $key;
                        }
                    }
                }
            }
        }
    }
    if (isset($filter_resource)) {
        $parameter_to_find[] = $filter_resource;
    } else {
        $parameter_to_find = null;
    }
    $totalGroupPermission = 0;
    if (count($arrGroups) > 0) {
        $arrResourceOrg = $pACL->getResourcesByOrg($idOrgFil, $parameter_to_find);
        if ($arrResourceOrg === false) {
            $smarty->assign("mb_title", _tr("ERROR"));
            $smarty->assign("mb_message", _tr("An error has ocurred to retrieved Resources"));
        } else {
            $totalGroupPermission = count($arrResourceOrg);
        }
    }
    //begin grid parameters
    $oGrid = new paloSantoGrid($smarty);
    $limit = 25;
    $total = $totalGroupPermission;
    $oGrid->setLimit($limit);
    $oGrid->setTotal($total);
    $offset = $oGrid->calculateOffset();
    $end = $offset + $limit <= $total ? $offset + $limit : $total;
    $url['menu'] = $module_name;
    $url['idOrganization'] = $idOrgFil;
    $url['filter_group'] = $filter_group;
    $url['filter_resource'] = $filter_resource;
    $arrData = $arrResourceActions = $arrPermisos = array();
    $error = false;
    if (count($arrGroups) > 0 && $totalGroupPermission > 0) {
        $arrResource = array_slice($arrResourceOrg, $offset, $limit);
        $idGroup = $filter_group;
        foreach ($arrResource as $resource) {
            $listResource[] = $resource['id'];
            //lista de id de los recursos que queremos consulta
            $listResDes[$resource['id']] = $resource['description'];
        }
        //las acciones que tiene cada drecurso
        $arrResourceActions = $pACL->getResourcesActions($listResource);
        if ($arrResourceActions === false) {
            $smarty->assign("mb_title", _tr("ERROR"));
            $smarty->assign("mb_message", _tr("An error has ocurred to retrieved Resources Actions"));
            $error = true;
        }
        //los premisos que tiene el grupo
        $arrPermisos = $pACL->loadGroupPermissions($idGroup, $listResource);
        if ($arrPermisos === false) {
            $smarty->assign("mb_title", _tr("ERROR"));
            $smarty->assign("mb_message", _tr("An error has ocurred to retrieved Group Permissions"));
            $error = true;
        }
    }
    $max_actions = 0;
    $isAdministrator = $pACL->getGroupNameByid($idGroup) == _tr("administrator") ? true : false;
    if ($totalGroupPermission > 0 && !$error) {
        foreach ($arrResourceActions as $resource => $actions) {
            $arrTmp = array();
            $arrTmp[] = _tr($listResDes[$resource]);
            $disabled = "";
            if ($isAdministrator && ($resource == 'grouplist' || $resource == 'userlist' || $resource == 'group_permission')) {
                $disabled = "disabled='disabled'";
            }
            //dentro del modulo organizacion ahi acciones que unicamente las puede realizar el superadmin
            //por lo tando no deben aparecer listadas
            if ($resource == "organization") {
                $actions = array_diff($actions, array('change_org_status', 'create_org', 'delete_org', 'edit_DID'));
            } elseif ($resource == "dashboard") {
                $actions = array('access');
            } elseif ($resource == 'cdrreport') {
                $actions = array('access', 'export');
            }
            if (count($actions) > $max_actions) {
                $max_actions = count($actions);
            }
            $desactivar = false;
            if (isset($arrPermisos[$resource])) {
                //grupo no tiene nigun permiso
                if (!in_array('access', $arrPermisos[$resource])) {
                    $desactivar = true;
                }
            } else {
                $desactivar = true;
                $arrPermisos[$resource] = array();
            }
            foreach ($actions as $action) {
                $class = 'other_act';
                if ($action == 'access') {
                    $class = 'access_act';
                } elseif ($desactivar) {
                    $disabled = "disabled='disabled'";
                }
                $checked0 = '';
                //chequeamos si la accion se encuentra en la lista de acciones permitidas en el recurso
                if (in_array($action, $arrPermisos[$resource])) {
                    $checked0 = "checked";
                }
                $arrTmp[] = "<input type='checkbox' class='{$class}' {$disabled} name='groupPermission[" . $resource . "][{$action}]' {$checked0}> {$action}";
            }
            $arrData[] = $arrTmp;
        }
    }
    $oGrid->setTitle(_tr("Group Permission"));
    $oGrid->setURL($url);
    $oGrid->setWidth("99%");
    $oGrid->setStart($total == 0 ? 0 : $offset + 1);
    $oGrid->setEnd($end);
    $oGrid->setTotal($total);
    $arrColumn[] = _tr("Resource");
    for ($i = 1; $i <= $max_actions; $i++) {
        $act = _tr("Action");
        $arrColumn[] = "{$act}" . " {$i}";
    }
    $oGrid->setColumns($arrColumn);
    //begin section filter
    $arrFormFilter = createFieldFilter($arrGroups);
    $oFilterForm = new paloForm($smarty, $arrFormFilter);
    $smarty->assign("SHOW", _tr("Show"));
    $smarty->assign("limit_apply", htmlspecialchars($limit, ENT_COMPAT, 'UTF-8'));
    $smarty->assign("offset_apply", htmlspecialchars($offset, ENT_COMPAT, 'UTF-8'));
    $smarty->assign("resource_apply", htmlentities($filter_resource));
    $_POST["filter_group"] = htmlspecialchars($filter_group, ENT_COMPAT, 'UTF-8');
    $_POST["filter_resource"] = htmlspecialchars($filter_resource, ENT_COMPAT, 'UTF-8');
    $_POST["idOrganization"] = $idOrgFil;
    if (count($arrOrgz) > 0) {
        global $arrPermission;
        if (in_array('edit_permission', $arrPermission)) {
            $oGrid->addSubmitAction("apply", _tr("Save"));
        }
        if ($credentials['userlevel'] == "superadmin") {
            $oGrid->addComboAction("idOrganization", _tr("Organization"), $arrOrgz, $idOrgFil, "report");
        }
        $nameGroup = isset($arrGroups[$filter_group]) ? $arrGroups[$filter_group] : "";
        $oGrid->addFilterControl(_tr("Filter applied ") . _tr("Group") . " = {$nameGroup}", $_POST, array("filter_group" => $groupTmp[0][0]), true);
        $oGrid->addFilterControl(_tr("Filter applied ") . _tr("Resource") . " = {$filter_resource}", $_POST, array("filter_resource" => ""));
        $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST);
        $oGrid->showFilter(trim($htmlFilter));
    } else {
        $smarty->assign("mb_title", _tr("MESSAGE"));
        $smarty->assign("mb_message", _tr("You haven't created any organization"));
    }
    $contenidoModulo = $oGrid->fetchGrid(array(), $arrData);
    //end grid parameters
    return $contenidoModulo;
}
Beispiel #29
0
function compose_email($smarty, $module_name, $local_templates_dir, $arrConf, &$pImap)
{
    $jsonObject = new PaloSantoJSON();
    global $arrCredentials;
    $idUser = $arrCredentials['idUser'];
    //obtenemos el name del usuario
    $pDB = new paloDB($arrConf['elastix_dsn']['elastix']);
    $pACL = new paloACL($pDB);
    $result = $pACL->getUsers2($idUser);
    if ($result == false) {
        $jsonObject->set_error("Error to get user info");
        return $jsonObject->createJSON();
    } else {
        $name = $result[0]['name'];
    }
    $pCompose = new paloComposeEmail($_SESSION['elastix_user'], $_SESSION['elastix_pass2'], $name, $pImap);
    $headers['to'] = getParameter("to");
    $headers['cc'] = getParameter("cc");
    $headers['bcc'] = getParameter("bcc");
    $headers['reply_to'] = getParameter("reply_to");
    $subject = getParameter("subject");
    $content = getParameter("bodyMsg");
    $attachments = null;
    if (isset($_SESSION['elastix_emailAttachs'])) {
        $pCompose->setAttachments($_SESSION['elastix_emailAttachs']);
    }
    if ($pCompose->sendEmail($headers, $subject, $content)) {
        $strError = $pCompose->getErrorMsg();
        $jsonObject->set_message(_tr("Message was sent successfully.") . " {$strError}");
        unset($_SESSION['elastix_emailAttachs']);
    } else {
        $jsonObject->set_error($pCompose->getErrorMsg());
    }
    return $jsonObject->createJSON();
}
Beispiel #30
0
/**
 * Funcion que se encarga obtener un sticky note.
 *
 * @return array con la informacion como mensaje y estado de resultado
 * @param string $menu nombre del menu al cual se le va a agregar la nota
 *
 * @author Eduardo Cueva
 * @author ecueva@palosanto.com
 */
function getStickyNote($pdbACL, $uid, $menu)
{
    require_once 'libs/paloSantoACL.class.php';
    $arrResult = array('status' => FALSE, 'msg' => 'no_data', 'data' => _tr("Click here to leave a note."));
    $pACL = new paloACL($pdbACL);
    $tupla = $pdbACL->getFirstRowQuery('SELECT * FROM sticky_note WHERE id_user = ? AND id_resource = ?', TRUE, array($uid, $pACL->getResourceId($menu)));
    if (is_array($tupla) && count($tupla) > 0) {
        $arrResult = array('status' => TRUE, 'msg' => '', 'data' => $tupla['description'], 'popup' => $tupla['auto_popup']);
    }
    return $arrResult;
}