function KickCallers($smarty, &$pDB, $module_name, $credentials)
{
    global $arrPermission;
    $id_conf = getParameter("id_conf");
    $domain = getParameter('organization');
    if ($credentials['userlevel'] != 'superadmin') {
        $domain = $credentials['domain'];
    }
    $type_kick = getParameter("type");
    $jsonObject = new PaloSantoJSON();
    //permission
    $invite_part = in_array("admin_conference_participant", $arrPermission);
    if (!$invite_part) {
        $jsonObject->set_error(_tr("You are not authorized to perform this action"));
    } else {
        $pConf = new paloConference($pDB, $domain);
        $conference = $pConf->getConferenceById($id_conf);
        if ($conference == false) {
            $jsonObject->set_error(_tr($pConf->errMsg));
        } else {
            $room = $conference["confno"];
            $date = time();
            if ($date >= strtotime($conference["startTime"]) && $date <= strtotime($conference["endtime"]) || $conference["startTime"] == "1900-01-01 12:00:00") {
                if ($type_kick == "all") {
                    $result = $pConf->KickCaller($room, "all");
                } else {
                    $keys = array_keys($_POST);
                    foreach ($keys as $value) {
                        if (preg_match("/^kick_[0-9]+\$/", $value)) {
                            $result = $pConf->KickCaller($room, $_POST[$value]);
                        }
                    }
                }
                $jsonObject->set_message(_tr("Changes has been applied") . print_r($result));
            } else {
                $jsonObject->set_error(_tr("Conference out of Time"));
            }
        }
    }
    return $jsonObject->createJSON();
}
function changeStatusFestival()
{
    $pFestival = new paloSantoFestival();
    $jsonObject = new PaloSantoJSON();
    $status = getParameter("status");
    $message = "";
    $arrMessage["button_title"] = _tr("Dismiss");
    if ($status == "activate") {
        $arrMessage["mb_message"] = '';
        $arrMessage["mb_title"] = _tr("Message") . ":<br/>";
        switch ($pFestival->activateFestival()) {
            case 1:
                // Servicio iniciado, se modificó archivo
                $arrMessage["mb_message"] = _tr("");
                // cae al siguiente caso
            // cae al siguiente caso
            case 0:
                // Servicio iniciado, sin modificación
                $arrMessage["mb_message"] .= _tr("Festival has been successfully activated");
                break;
            case -1:
                // Error al iniciar servicio
                $arrMessage["mb_title"] = _tr("ERROR") . ":<br/>";
                $arrMessage["mb_message"] = $pFestival->getError();
                break;
        }
    } elseif ($status == "deactivate") {
        if (!$pFestival->isFestivalActivated()) {
            $arrMessage["mb_title"] = _tr("ERROR") . ":<br/>";
            $arrMessage["mb_message"] = _tr("Festival is already deactivated");
            $jsonObject->set_message($arrMessage);
            return $jsonObject->createJSON();
        }
        if ($pFestival->deactivateFestival()) {
            $arrMessage["mb_title"] = _tr("Message") . ":<br/>";
            $arrMessage["mb_message"] = _tr("Festival has been successfully deactivated");
        } else {
            $arrMessage["mb_title"] = _tr("ERROR") . ":<br/>";
            $arrMessage["mb_message"] = _tr("Festival could not be deactivated");
        }
    }
    $jsonObject->set_message($arrMessage);
    return $jsonObject->createJSON();
}
Beispiel #3
0
function addExttoQueueAction(&$pDB1, &$pDB2)
{
    $jsonObject = new PaloSantoJSON();
    $number_org = getParameter('extStart');
    $queue = getParameter('queue');
    $pControlPanel = new paloSantoControlPanel($pDB1, $pDB2);
    $pControlPanel->queueAddMember($queue, $number_org);
    $jsonObject->set_message("");
    return $jsonObject->createJSON();
}
Beispiel #4
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 #5
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();
}
function getChatContactsStatus($searchFilter)
{
    $jsonObject = new PaloSantoJSON();
    $dummy = NULL;
    $newListContacts = getNewListElastixAccounts($searchFilter, $dummy);
    if ($newListContacts === false) {
        $status = FALSE;
    } else {
        // 1 COMPARA EL VALOR DEVUELTO CON EL VALOR QUE ESTA EN SESION
        //SI HUBO UN CAMBIO
        // si hay cambio status true
        // poner el nuevo valor el seesion
        $session = getSession();
        //var_dump($session['chatlistStatus']);
        //print_r("---------------------------------------------------------------------------------------");
        //var_dump($newListContacts);
        //file_put_contents("/tmp/testchat",);
        if ($session['chatlistStatus'] != $newListContacts) {
            $msgResponse = $newListContacts;
            $status = true;
        } else {
            $status = false;
        }
        if ($status) {
            //hubo un cambio
            $jsonObject->set_status("CHANGED");
            $jsonObject->set_message($msgResponse);
            //el valor del status actual
        } else {
            $jsonObject->set_status("NOCHANGED");
        }
    }
    $session['chatlistStatus'] = $newListContacts;
    putSession($session);
    return array("there_was_change" => $status, "data" => $jsonObject->createJSON());
}
Beispiel #7
0
function mostrar_menu()
{
    global $arrLangModule;
    global $arrConf;
    $jsonObject = new PaloSantoJSON();
    $respuesta = array();
    $level = getParameter("level");
    $parent_1_existing = getParameter("parent_1_existing");
    $parent_2_existing = getParameter("parent_2_existing");
    $id_parent = getParameter("id_parent");
    //Nivel 2
    if ($level == 0) {
        //Padre nivel 1 SI existe
        if ($parent_1_existing == 0) {
            $pDB_menu = new paloDB($arrConf['elastix_dsn']['menu']);
            if (!empty($pDB_menu->errMsg)) {
                $jsonObject->set_error("ERROR DE DB: {$pDB_menu->errMsg}");
                return $jsonObject->createJSON();
            }
            $pMenu = new paloMenu($pDB_menu);
            $arrMenuOptions = $pMenu->getRootMenus();
            $parent_Menu = "<td align='left'><b>{$arrLangModule["Level 1 Parent"]}: <span  class='required'>*</span></b></td>";
            $parent_Menu .= "<td align='left'>";
            $parent_Menu .= "<select name='parent_module' id='parent_module'>";
            foreach ($arrMenuOptions as $key => $valor) {
                $parent_Menu .= "<option value='{$key}'>{$valor}</option>";
            }
            $parent_Menu .= "</select>";
            $parent_Menu .= "</td>";
        } else {
            $parent_Menu = "<td align='left'><b>{$arrLangModule["Level 1 Parent Name"]}: <span  class='required'>*</span></b></td>";
            $parent_Menu .= "<td align='left' width='21%'><input type='text' name='parent_1_name' id='parent_1_name' value='' onkeyup='generateId(this,\"parent_1_id\")'></td>";
            $parent_Menu .= "<td align='left' width='11%'><b>{$arrLangModule["Level 1 Parent Id"]}: </b></td>";
            $parent_Menu .= "<td align='left'><i id='parent_1_id'></i></td>";
        }
        $respuesta["parent_menu_1"] = $parent_Menu;
        $respuesta["level2_exist"] = "";
        $respuesta["parent_menu_2"] = "";
        $respuesta["label_level2"] = "";
    } else {
        //Padre nivel 1 SI existe
        if ($parent_1_existing == 0) {
            //Padre nivel 2 SI existe
            if ($parent_2_existing == 0) {
                require_once 'libs/paloSantoNavigation.class.php';
                $pMenu = new paloMenu($arrConf['elastix_dsn']['menu']);
                $arrMenu = $pMenu->cargar_menu();
                $smarty = NULL;
                $pNav = new paloSantoNavigation($arrMenu, $smarty);
                $arrMenuOptions = $pNav->getArrSubMenu($id_parent);
                if (is_array($arrMenuOptions)) {
                    $parent_Menu2 = "<td align='left'><b>{$arrLangModule["Level 2 Parent"]}: <span  class='required'>*</span></b></td>";
                    $parent_Menu2 .= "<td>";
                    $parent_Menu2 .= "<select name='parent_module_2' id='parent_module_2'>";
                    foreach ($arrMenuOptions as $key => $valor) {
                        $parent_Menu2 .= "<option value='{$key}'>{$valor['Name']}</option>";
                    }
                    $parent_Menu2 .= "</select>";
                    $parent_Menu2 .= "</td>";
                    $parent_Menu2 .= "<td></td><td></td><td></td>";
                    $respuesta["parent_menu_2"] = $parent_Menu2;
                }
            } else {
                if ($parent_2_existing == 1) {
                    $parent_Menu2 = "<td align='left'><b>{$arrLangModule["Level 2 Parent Name"]}: <span  class='required'>*</span></b></td>";
                    $parent_Menu2 .= "<td align='left' width='21%'><input type='text' name='parent_2_name' id='parent_2_name' value='' onkeyup='generateId(this,\"parent_2_id\")'></td>";
                    $parent_Menu2 .= "<td align='left' width='11%'><b>{$arrLangModule["Level 2 Parent Id"]}: </b></td>";
                    $parent_Menu2 .= "<td align='left'><i id='parent_2_id'></i></td>";
                    $respuesta["parent_menu_2"] = $parent_Menu2;
                } else {
                    $pDB_menu = new paloDB($arrConf['elastix_dsn']['menu']);
                    if (!empty($pDB_menu->errMsg)) {
                        $jsonObject->set_error("ERROR DE DB: {$pDB_menu->errMsg}");
                        return $jsonObject->createJSON();
                    }
                    $pMenu = new paloMenu($pDB_menu);
                    $arrMenuOptions = $pMenu->getRootMenus();
                    $parent_Menu = "<td align='left'><b>{$arrLangModule["Level 1 Parent"]}: <span  class='required'>*</span></b></td>";
                    $parent_Menu .= "<td align='left'>";
                    $parent_Menu .= "<select name='parent_module' id='parent_module' onchange='mostrar_menu()'>";
                    foreach ($arrMenuOptions as $key => $valor) {
                        $parent_Menu .= "<option value='{$key}'>{$valor}</option>";
                    }
                    $parent_Menu .= "</select>";
                    $parent_Menu .= "</td>";
                    $parent_Menu .= "<td></td><td></td><td></td>";
                    $respuesta["parent_menu_1"] = $parent_Menu;
                    //$respuesta->addAssign("parent_menu_1","innerHTML", "");
                    $parent_exist = "<b>{$arrLangModule["Level 2 Parent Exists"]}: <span  class='required'>*</span></b>";
                    $respuesta["label_level2"] = $parent_exist;
                    $parent_option = "<select id='parent_2_existing_option' name='parent_2_existing_option' onchange='mostrar_menu()'>";
                    $parent_option .= "<option value='{$arrLangModule["Yes"]}'>{$arrLangModule["Yes"]}</option>";
                    $parent_option .= "<option value='{$arrLangModule["No"]}' selected='selected'>{$arrLangModule["No"]}</option>";
                    $parent_option .= "</select>";
                    $respuesta["level2_exist"] = $parent_option;
                    $parent_Menu2 = "<td align='left'><b>{$arrLangModule["Level 2 Parent Name"]}: <span  class='required'>*</span></b></td>";
                    $parent_Menu2 .= "<td align='left' width='22%'><input type='text' name='parent_2_name' id='parent_2_name' value='' onkeyup='generateId(this,\"parent_2_id\")'></td>";
                    $parent_Menu2 .= "<td align='left' width='11%'><b>{$arrLangModule["Level 2 Parent Id"]}: </b></td>";
                    $parent_Menu2 .= "<td align='left'><i id='parent_2_id'></i></td>";
                    $respuesta["parent_menu_2"] = $parent_Menu2;
                }
            }
        } else {
            $parent_Menu = "<td align='left'><b>{$arrLangModule["Level 1 Parent Name"]}: <span  class='required'>*</span></b></td>";
            $parent_Menu .= "<td align='left' width='22%'><input type='text' name='parent_1_name' id='parent_1_name' value='' onkeyup='generateId(this,\"parent_1_id\")'></td>";
            $parent_Menu .= "<td align='left' width='11%'><b>{$arrLangModule["Level 1 Parent Id"]}: </b></td>";
            $parent_Menu .= "<td align='left'><i id='parent_1_id'></i></td>";
            $respuesta["parent_menu_1"] = $parent_Menu;
            $parent_Menu2 = "<td align='left'><b>{$arrLangModule["Level 2 Parent Name"]}: <span  class='required'>*</span></b></td>";
            $parent_Menu2 .= "<td align='left' width='22%'><input type='text' name='parent_2_name' id='parent_2_name' value='' onkeyup='generateId(this,\"parent_2_id\")'></td>";
            $parent_Menu2 .= "<td align='left' width='11%'><b>{$arrLangModule["Level 2 Parent Id"]}: </b></td>";
            $parent_Menu2 .= "<td align='left'><i id='parent_2_id'></i></td>";
            $respuesta["parent_menu_2"] = $parent_Menu2;
            $respuesta["level2_exist"] = "";
            $respuesta["label_level2"] = "";
        }
    }
    $jsonObject->set_message($respuesta);
    return $jsonObject->createJSON();
}
function validate_delete($pDB, $credentials)
{
    $jsonObject = new PaloSantoJSON();
    $id_did = getParameter("id_did");
    $pDB = "Select did, organization_domain from did where id_did=?";
    $result = $pDB->getFirstRowQuery($query, true, array($id_did));
    if ($arrSettings == false) {
        $jsonObject->error(_tr("Did doesn't exist"));
    } else {
        $message = "";
        if (!is_null($result["organization_domain"])) {
            $message = "DID " . $result["did"] . _tr("<b>is assigned</b> to the organzanization with domain <b>") . _tr($result["organization_domain"]) . "</b>";
        }
        $jsonObject->set_message($message . _tr("Are you sure you wish to continue?"));
    }
    return $jsonObject->createJSON();
}
Beispiel #9
0
function getDataRegistration($smarty, $module_name, $local_templates_dir, &$pDB, $arrConf, &$pDBACL)
{
    $pRegister = new paloSantoRegistration($pDB);
    $jsonObject = new PaloSantoJSON();
    if (is_file("/etc/elastix.key")) {
        $_DATA = $pRegister->getDataServerRegistration();
        if ($_DATA === null) {
            // no se puede conectar al web service o existe un problema de red
            $jsonObject->set_error(_tr("Impossible connect to Elastix Web services. Please check your internet connection."));
            $jsonObject->set_status("error");
            $jsonObject->set_message($_DATA);
        } elseif ($_DATA === "FALSE") {
            // su elastix no esta registrado, el idServer enviado no existe en la base de datos
            $_DATA = $pRegister->getDataRegister();
            $jsonObject->set_error(_tr("Your Server ID is not valid. Please update your information to generate a new Server ID."));
            $jsonObject->set_status("error-update");
            $jsonObject->set_message($_DATA);
        } else {
            $jsonObject->set_message($_DATA);
        }
    } else {
        // elastix no registrado
        $jsonObject->set_error("no registrado");
        $jsonObject->set_status("error");
        $jsonObject->set_message("empty");
    }
    return $jsonObject->createJSON();
}
Beispiel #10
0
function actDesactTrunk($smarty, &$pDB)
{
    $pTrunk = new paloSantoTrunk($pDB);
    $error = "";
    $idTrunk = getParameter("id_trunk");
    $action = getParameter("trunk_action");
    $jsonObject = new PaloSantoJSON();
    if (!preg_match('/^[[:digit:]]+$/', "{$idTrunk}")) {
        $error = _tr("Invalid Trunk Id");
    } else {
        $pDB->beginTransaction();
        $result = $pTrunk->actDesacTrunk($idTrunk, $action);
        if ($result == true) {
            $pDB->commit();
        } else {
            $error = $pTrunk->errMsg();
            $pDB->rollBack();
        }
    }
    if ($error != "") {
        $jsonObject->set_error($error);
    } else {
        $state = $action == "on" ? "desactivated" : "activated";
        $jsonObject->set_message(_tr("Trunk have been {$state} successfully"));
    }
    return $jsonObject->createJSON();
}
Beispiel #11
0
function faxListStatus($smarty, $module_name, $local_templates_dir, $arrConf, $arrLang)
{
    $oFax = new paloFax();
    $arrFax = $oFax->getFaxList();
    $status = TRUE;
    $end = count($arrFax);
    $arrFaxStatus = $oFax->getFaxStatus();
    $arrData = array();
    foreach ($arrFax as $fax) {
        $arrData[$fax['extension']] = $arrFaxStatus['modems']['ttyIAX' . $fax['dev_id']] . ' on ttyIAX' . $fax['dev_id'];
    }
    $statusArr = thereChanges($arrData);
    if (empty($statusArr)) {
        $status = FALSE;
    }
    $jsonObject = new PaloSantoJSON();
    if ($status) {
        //este status es true solo cuando el tecnico acepto al customer (al hacer click)
        //sleep(2); //por si acaso se desincroniza en la tabla customer el campo attended y llenarse los datos de id_chat y id_chat_time
        $msgResponse["faxes"] = $statusArr;
        $jsonObject->set_status("CHANGED");
        $jsonObject->set_message($msgResponse);
    } else {
        $jsonObject->set_status("NOCHANGED");
    }
    return array("there_was_change" => $status, "data" => $jsonObject->createJSON());
}
Beispiel #12
0
function call_status($smarty, $module_name, $local_templates_dir, &$pDB, $arrConf, $dsn_agi_manager, $credentials)
{
    session_commit();
    if ($credentials['userlevel'] != 'superadmin') {
        $domain = $credentials["domain"];
    } else {
        $jsonObject->set_status("HANGUP");
        return array("there_was_change" => true, "data" => $jsonObject->createJSON());
    }
    $status = true;
    $pRecording = new paloSantoRecordings($pDB, $domain);
    $extension = getParameter("extension");
    $result = $pRecording->Obtain_Protocol_Current_User($domain, $extension);
    $state = $pRecording->callStatus($result['dial']);
    $jsonObject = new PaloSantoJSON();
    if ($state == "hangup") {
        $status = FALSE;
    }
    if ($status) {
        $msgResponse["status"] = $state;
        $jsonObject->set_status("RECORDING");
        $jsonObject->set_message($msgResponse);
        return array("there_was_change" => false, "data" => $jsonObject->createJSON());
    } else {
        $jsonObject->set_status("HANGUP");
        return array("there_was_change" => true, "data" => $jsonObject->createJSON());
    }
}
Beispiel #13
0
function getContactEmails($arrConf)
{
    $pDBACL = new paloDB($arrConf['dsn_conn_database1']);
    $pACL = new paloACL($pDBACL);
    $id_user = $pACL->getIdUser($_SESSION["elastix_user"]);
    $tag = getParameter('tag');
    if (isset($id_user) && $id_user != "") {
        $pDB = new paloDB($arrConf['dsn_conn_database']);
        $pDBAddress = new paloDB($arrConf['dsn_conn_database3']);
        $pCalendar = new paloSantoCalendar($pDB);
        $salida = $pCalendar->getContactByTag($pDBAddress, $tag, $id_user);
    } else {
        $salida = array();
    }
    // se instancia a JSON
    $jsonObject = new PaloSantoJSON();
    $jsonObject->set_message($salida);
    return $jsonObject->createJSON();
}
Beispiel #14
0
function updateStatusAnonymousSIP($arrConf)
{
    $pAdvanceSecuritySettings = new paloSantoAdvancedSecuritySettings($arrConf);
    $jsonObject = new PaloSantoJSON();
    $statusAnonymousSIP = getParameter("new_status_anonymous_sip");
    $result = $pAdvanceSecuritySettings->updateStatusAnonymousSIP($statusAnonymousSIP);
    $arrData['result'] = $result;
    $arrData['button_title'] = _tr("Dismiss");
    if ($statusAnonymousSIP == "1") {
        $word = "enabled";
    } else {
        $word = "disabled";
    }
    if ($result) {
        $arrData['message_title'] = _tr("Information") . ":<br/>";
        $arrData['message'] = _tr("Anonymous SIP calls are now {$word}.");
    } else {
        $arrData['message_title'] = _tr("Error") . ":<br/>";
        $arrData['message'] = _tr("Anonymous SIP calls cannot be {$word}.");
    }
    $jsonObject->set_message($arrData);
    Header('Content-Type: application/json');
    return $jsonObject->createJSON();
}
Beispiel #15
0
function getDevices($dsnAsterisk, $dsnSqlite)
{
    $jsonObject = new PaloSantoJSON();
    $paloEndPoint = new paloSantoEndPoint($dsnAsterisk, $dsnSqlite);
    $idModel = getParameter("id_model");
    if ($idModel == "unselected") {
        $jsonObject->set_message(array("Unselected" => _tr("Unselected")));
    } else {
        $iaxSupport = $paloEndPoint->modelSupportIAX($idModel);
        if ($iaxSupport === null) {
            $jsonObject->set_error("yes");
        } else {
            if ($iaxSupport) {
                $jsonObject->set_message($paloEndPoint->getDeviceFreePBX(true));
            } else {
                $jsonObject->set_message($paloEndPoint->getDeviceFreePBX());
            }
        }
    }
    return $jsonObject->createJSON();
}
Beispiel #16
0
function changeDIDfilter($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $credentials)
{
    $jsonObject = new PaloSantoJSON();
    $pDID = new paloDidPBX($pDB);
    $prop["country"] = getParameter("country");
    $prop["city"] = getParameter("city");
    $listDID = $pDID->getDIDFree($prop);
    if ($listDID === false) {
        $jsonObject->set_error(_tr("An error has ocurred to retrieve DID data"));
    } else {
        $arrDID = array();
        if (count($listDID) > 0) {
            //debemos quitar de la lista de did  aquellos que ya han sido seleccionados
            $selectDID = getParameter("listDIDOrg");
            if (!empty($selectDID)) {
                $listDIDOrg = explode(",", $selectDID);
                foreach ($listDID as $value) {
                    if (!in_array($value['id'], $listDIDOrg)) {
                        $arrDID[] = array('id' => $value['id'], 'did' => $value['did'], 'country_code' => $value['country_code'], 'area_code' => $value['area_code']);
                    }
                }
            } else {
                foreach ($listDID as $value) {
                    $arrDID[] = array('id' => $value['id'], 'did' => $value['did'], 'country_code' => $value['country_code'], 'area_code' => $value['area_code']);
                }
            }
        }
        $jsonObject->set_message($arrDID);
    }
    return $jsonObject->createJSON();
}
Beispiel #17
0
function ordenRoute($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $credentials)
{
    global $arrPermission;
    $jsonObject = new PaloSantoJSON();
    $seq = getParameter("seq");
    $out_id = getParameter("out_id");
    $domain = getParameter("organization");
    if (!in_array('edit', $arrPermission)) {
        $jsonObject->set_error(_tr("You are not authorized to perform this action"));
        return $jsonObject->createJSON();
    }
    if ($credentials['userlevel'] != 'superadmin') {
        $domain = $credentials['domain'];
    }
    $pOutbound = new paloSantoOutbound($pDB, $domain);
    $pDB->beginTransaction();
    $result = $pOutbound->reorderRoute($out_id, $seq);
    if ($result == false) {
        $pDB->rollBack();
        $jsonObject->set_error(_tr($pOutbound->errMsg));
    } else {
        $pDB->commit();
        $pAstConf = new paloSantoASteriskConfig($pDB, new paloDB($arrConf['elastix_dsn']['elastix']));
        $pAstConf->setReloadDialplan($domain, true);
        $content = reportOutbound($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $credentials);
        $jsonObject->set_message(array(_tr("Changes Applied"), $content));
    }
    return $jsonObject->createJSON();
}
Beispiel #18
0
function saveNewConfSpan($smarty, $module_name, $local_templates_dir, &$pDB, $arrConf)
{
    $bExito = TRUE;
    $estadoAnterior = NULL;
    $estadoNuevo = array('span_num' => getParameter('idSpan'), 'tmsource' => getParameter('tmsource'), 'lnbuildout' => getParameter('lnbuildout'), 'framing' => getParameter('framing'), 'coding' => getParameter('coding'), 'crc' => getParameter('crc'), 'wanpipe_force_media' => getParameter('media_pri'));
    $response = array('msg' => _tr('Saved'), 'reload' => FALSE);
    $oPortsDetails = new PaloSantoHardwareDetection();
    if ($bExito) {
        $listaSpans = $oPortsDetails->leerSpanConfig($pDB, $estadoNuevo['span_num']);
        if (!is_array($listaSpans) || count($listaSpans) <= 0) {
            $bExito = FALSE;
            $response['msg'] = _tr('Span is invalid or out of range') . $oPortsDetails->errMsg;
        } else {
            $estadoAnterior = $listaSpans[$estadoNuevo['span_num']];
            if (is_null($estadoAnterior['wanpipe_force_media'])) {
                $estadoNuevo['wanpipe_force_media'] = NULL;
            }
        }
    }
    if ($bExito) {
        $bExito = $oPortsDetails->guardarSpanConfig($pDB, $estadoNuevo['span_num'], $estadoNuevo['tmsource'], $estadoNuevo['lnbuildout'], $estadoNuevo['framing'], $estadoNuevo['coding'], $estadoNuevo['crc'], $estadoNuevo['wanpipe_force_media']);
        if (!$bExito) {
            $response['msg'] = $oPortsDetails->errMsg;
        }
    }
    if ($bExito) {
        // Se verifica si se cambia medio de tarjeta Sangoma.
        if (!is_null($estadoAnterior['wanpipe_force_media']) && $estadoAnterior['wanpipe_force_media'] != $estadoNuevo['wanpipe_force_media']) {
            /* Se requiere re-enumerar las tarjetas con hardware detector. Se
             * asume que se debe de agregar la bandera de detectar Sangoma. 
             * También se asume que el acto de iniciar la detección de hardware
             * no cambia el ID de span que fue modificado. */
            $response['reload'] = TRUE;
            $resultado = $oPortsDetails->hardwareDetection('', "/etc/asterisk", 'true', '');
            /* Invalidar la configuración anterior de cancelador de eco */
            $oPortsDetails->getPorts($pDB);
            // Volver a escribir el estado deseado
            $bExito = $oPortsDetails->guardarSpanConfig($pDB, $estadoNuevo['span_num'], $estadoNuevo['tmsource'], $estadoNuevo['lnbuildout'], $estadoNuevo['framing'], $estadoNuevo['coding'], $estadoNuevo['crc'], $estadoNuevo['wanpipe_force_media']);
            if (!$bExito) {
                $response['msg'] = $oPortsDetails->errMsg;
            }
        }
    }
    if ($bExito) {
        $bExito = $oPortsDetails->refreshDahdiConfiguration();
        if (!$bExito) {
            $response['msg'] = $oPortsDetails->errMsg;
        }
        $oPortsDetails->transferirSpanConfig($pDB);
    }
    if (!$bExito) {
        $response['msg'] = 'FAILED: ' . $response['msg'];
    }
    $jsonObject = new PaloSantoJSON();
    $jsonObject->set_message($response);
    return $jsonObject->createJSON();
}
Beispiel #19
0
function faxAttachmentUpload($smarty, $module_name, $local_templates_dir, $pDB, $arrConf)
{
    $jsonObject = new PaloSantoJSON();
    $tmpfaxdocs = "/var/www/elastixdir/tmpfaxdocs/";
    if (!file_exists($tmpfaxdocs)) {
        $jsonObject->set_error(_tr("Error uploading your file"));
        return $jsonObject->createJSON();
    }
    foreach ($_FILES['faxFile']['error'] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $tmpFileName = tempnam($tmpfaxdocs, "");
            if ($tmpFileName == false) {
                $jsonObject->set_error(_tr("Error uploading your file"));
                return $jsonObject->createJSON();
            }
            if (move_uploaded_file($_FILES['faxFile']['tmp_name'][$key], $tmpFileName) === false) {
                $jsonObject->set_error(_tr("Failed to move file"));
                return $jsonObject->createJSON();
            }
            if (empty($_SESSION['faxFileAattached'])) {
                $_SESSION['faxFileAattached'] = $tmpFileName;
            } else {
                if (!empty($_SESSION['faxFileAattached'])) {
                    unlink($_SESSION['faxFileAattached']);
                    unset($_SESSION['faxFileAattached']);
                    $_SESSION['faxFileAattached'] = $tmpFileName;
                }
            }
            $jsonObject->set_message($_SESSION['faxFileAattached']);
        } else {
            $jsonObject->set_error(_tr("Error uploading your file"));
        }
    }
    return $jsonObject->createJSON();
}
Beispiel #20
0
function saveVacationSettings($smarty, $module_name, $local_templates_dir, $pDB, $arrConf)
{
    global $arrCredentials;
    $objAntispam = new paloSantoAntispam($arrConf['path_postfix'], $arrConf['path_spamassassin'], $arrConf['file_master_cf'], $arrConf['file_local_cf']);
    $pVacations = new paloMyVacation($pDB, $arrCredentials['idUser']);
    $jsonObject = new PaloSantoJSON();
    $myVacation['init_date'] = getParameter('intiDate');
    $myVacation['end_date'] = getParameter('endDate');
    $myVacation['email_subject'] = getParameter('emailSubject');
    $myVacation['email_body'] = getParameter('emailBody');
    $email = $_SESSION['elastix_user'];
    $subject = $myVacation['email_subject'];
    $body = $myVacation['email_body'];
    $ini_date = $myVacation['init_date'];
    $end_date = $myVacation['end_date'];
    $timestamp0 = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
    $timestamp1 = mktime(0, 0, 0, date("m", strtotime($ini_date)), date("d", strtotime($ini_date)), date("Y", strtotime($ini_date)));
    $timeSince = $timestamp0 - $timestamp1;
    if ($timeSince >= 0) {
        $myVacation['vacation'] = "yes";
    } else {
        $myVacation['vacation'] = "no";
    }
    $scripts = $objAntispam->existScriptSieve($email, "scriptTest.sieve");
    $spamCapture = false;
    // si CapturaSpam=OFF y Vacations=OFF
    if ($scripts['actived'] != "") {
        // hay un script activo
        if (preg_match("/scriptTest.sieve/", $scripts['actived'])) {
            // si CapturaSpam=ON y Vacations=OFF
            $spamCapture = true;
        }
        // si CapturaSpam=ON y Vacations=OFF
    }
    $pVacations->_DB->beginTransaction();
    if (!$pVacations->editVacation($myVacation)) {
        $pVacations->_DB->rollBack();
        $jsonObject->set_error($pVacations->getErrorMsg());
        return $jsonObject->createJSON();
    } else {
        //mandamos a actualizar el script del sieve
        if ($timeSince >= 0) {
            $body = str_replace("{END_DATE}", $end_date, $body);
            $result = $pVacations->uploadVacationScript($email, $subject, $body, $objAntispam, $spamCapture);
        } else {
            $result = true;
        }
        if ($result) {
            $pVacations->_DB->commit();
            $jsonObject->set_message("Changes were saved succefully");
        } else {
            $pVacations->_DB->rollBack();
            $jsonObject->set_error($pVacations->getErrorMsg());
        }
        return $jsonObject->createJSON();
    }
}
Beispiel #21
0
function changeOtherPage($pDB, $module_name)
{
    $jsonObject = new PaloSantoJSON();
    $pRules = new paloSantoRules($pDB);
    $direction = getParameter("direction");
    $actualrow = getParameter("actualrow");
    $tmp = explode("_", $actualrow);
    $actual_id = $tmp[1];
    $actual_order = $tmp[2];
    $correct = false;
    if ($direction == "up") {
        if ($actual_order != 1) {
            $correct = true;
            $rule = $pRules->getPreviousRule($actual_order);
        }
    } else {
        $rule = $pRules->getNextRule($actual_order);
        if (count($rule) != 0) {
            $correct = true;
        }
    }
    if ($correct) {
        if (is_array($rule)) {
            $Exito1 = $pRules->updateOrder($actual_id, $rule["rule_order"]);
            $Exito2 = $pRules->updateOrder($rule["id"], $actual_order);
            $mensaje = _tr("You have made changes to the definition of firewall rules, for this to take effect in the system press the next button");
            $mensaje2 = _tr("Save Changes");
            if ($Exito1 && $Exito2) {
                $jsonObject->set_status(_tr("Successful Change") . ":{$mensaje}:{$mensaje2}:" . _tr("Dismiss") . ":" . _tr("MESSAGE"));
                $arrayResult["id"] = $rule["id"];
                if ($rule['traffic'] == "INPUT") {
                    $arrayResult["traffic"]["image"] = "modules/{$module_name}/images/fw_input.gif";
                    $arrayResult["traffic"]["title"] = _tr("INPUT");
                    $arrayResult["interface"] = _tr("IN") . ": {$rule['eth_in']}";
                } elseif ($rule['traffic'] == "OUTPUT") {
                    $arrayResult["traffic"]["image"] = "modules/{$module_name}/images/fw_output.gif";
                    $arrayResult["traffic"]["title"] = _tr("OUTPUT");
                    $arrayResult["interface"] = _tr("OUT") . ": {$rule['eth_out']}";
                } else {
                    $arrayResult["traffic"]["image"] = "modules/{$module_name}/images/fw_forward.gif";
                    $arrayResult["traffic"]["title"] = _tr("FORWARD");
                    $arrayResult["interface"] = _tr("IN") . ":  {$rule['eth_in']}<br />" . _tr("OUT") . ": {$rule['eth_out']}";
                }
                if ($rule['target'] == "ACCEPT") {
                    $arrayResult["target"]["image"] = "modules/{$module_name}/images/target_accept.gif";
                    $arrayResult["target"]["title"] = _tr("ACCEPT");
                } elseif ($rule['target'] == "DROP") {
                    $arrayResult["target"]["image"] = "modules/{$module_name}/images/target_drop.gif";
                    $arrayResult["target"]["title"] = _tr("DROP");
                } else {
                    $arrayResult["target"]["image"] = "modules/{$module_name}/images/target_drop.gif";
                    $arrayResult["target"]["title"] = _tr("REJECT");
                }
                $arrayResult["ipSource"] = $rule["ip_source"];
                $arrayResult["ipDestiny"] = $rule["ip_destiny"];
                $arrayResult["protocol"] = $rule["protocol"];
                if ($rule['protocol'] == "ICMP") {
                    $arrayResult["details"] = _tr("Type") . ": {$rule['icmp_type']}";
                } else {
                    if ($rule['protocol'] == "IP") {
                        $arrayResult["details"] = _tr("Number Protocol IP") . ": {$rule['number_ip']}";
                    } else {
                        if ($rule['protocol'] == "TCP" || $rule['protocol'] == "UDP") {
                            if ($rule['sport'] != "" && $rule["sport"] != "ANY") {
                                $sportName = $pRules->getProtocolName($rule["sport"]);
                            } else {
                                $sportName = $rule["sport"];
                            }
                            if ($rule["dport"] != "" && $rule["dport"] != "ANY") {
                                $dportName = $pRules->getProtocolName($rule["dport"]);
                            } else {
                                $dportName = $rule["dport"];
                            }
                            $arrayResult["details"] = _tr("Source Port") . ": {$sportName}" . "<br />" . _tr("Destiny Port") . ": {$dportName}";
                        } else {
                            if ($rule['protocol'] == "STATE") {
                                $arrayResult["details"] = $rule['state'];
                            } else {
                                $arrayResult["details"] = "";
                            }
                        }
                    }
                }
                if ($rule['activated'] == 1) {
                    $image = "modules/{$module_name}/images/foco_on.gif";
                    $activated = "Desactivate";
                } else {
                    $image = "modules/{$module_name}/images/foco_off.gif";
                    $activated = "Activate";
                }
                $arrayResult["activate"] = "<a href='?menu={$module_name}&action=" . $activated . "&id=" . $rule['id'] . "'>" . "<img src='{$image}' border=0 title='" . _tr($activated) . "'</a>";
                $arrayResult["edit"] = "<a href='?menu={$module_name}&action=edit&id=" . $rule['id'] . "'>" . "<img src='modules/{$module_name}/images/edit.gif' border=0 title='" . _tr('Edit') . "'</a>";
                $jsonObject->set_message($arrayResult);
            } else {
                $jsonObject->set_error($pRules->errMsg);
            }
        } else {
            $jsonObject->set_error($pRules->errMsg);
        }
    } else {
        $jsonObject->set_status(_tr("Invalid Action"));
    }
    return $jsonObject->createJSON();
}
Beispiel #22
0
function getGroups(&$pDB, $arrCredentiasls)
{
    $pACL = new paloACL($pDB);
    $pORGZ = new paloSantoOrganization($pDB);
    $jsonObject = new PaloSantoJSON();
    $idOrgSel = getParameter("idOrganization");
    $arrGrupos = array();
    if ($idOrgSel == 0) {
        $arrGrupos = array();
    } else {
        if ($arrCredentiasls['userlevel'] != 'superadmin') {
            if ($idOrgSel != $arrCredentiasls['id_organization']) {
                $jsonObject->set_error("Invalid Action");
                $arrGrupos = array();
            }
        } else {
            $arrGrupos[0] = array("country_code", $pORGZ->getOrganizationProp($idOrgSel, "country_code"));
            $arrGrupos[1] = array("area_code", $pORGZ->getOrganizationProp($idOrgSel, "area_code"));
            $arrGrupos[2] = array("email_quota", $pORGZ->getOrganizationProp($idOrgSel, "email_quota"));
            $temp = $pACL->getGroupsPaging(null, null, $idOrgSel);
            if ($temp === false) {
                $jsonObject->set_error(_tr($pACL->errMsg));
            } else {
                $i = 3;
                foreach ($temp as $value) {
                    $arrGrupos[$i] = array($value[0], $value[1]);
                    $i++;
                }
            }
        }
    }
    $jsonObject->set_message($arrGrupos);
    return $jsonObject->createJSON();
}
Beispiel #23
0
function get_destination_category($smarty, $module_name, $pDB, $arrConf, $credentials)
{
    $jsonObject = new PaloSantoJSON();
    $categoria = getParameter("category");
    $domain = getParameter("organization");
    if ($credentials['userlevel'] != 'superadmin') {
        $domain = $credentials['domain'];
    }
    $pQueue = new paloQueuePBX($pDB, $domain);
    $arrDestine = $pQueue->getDefaultDestination($domain, $categoria);
    if ($arrDestine == FALSE) {
        $jsonObject->set_error(_tr($pQueue->errMsg));
    } else {
        $jsonObject->set_message($arrDestine);
    }
    return $jsonObject->createJSON();
}
Beispiel #24
0
function handleJSON_getPublishState($smarty, $module_name)
{
    Header('Content-Type: application/json');
    $publishState = array('ETag' => NULL, 'note' => 'Online', 'activities' => array());
    if (isset($_SESSION['publish_state'])) {
        $publishState = $_SESSION['publish_state'];
    }
    $jsonObject = new PaloSantoJSON();
    $jsonObject->set_message($publishState);
    return $jsonObject->createJSON();
}
Beispiel #25
0
                $smarty->assign("CONTENT", $sModuleContent['JS_CSS_HEAD'] . $sModuleContent['data']);
            } else {
                $smarty->assign("CONTENT", $sModuleContent['data']);
            }
            $smarty->assign('MENU', count($arrMenuFiltered) > 0 ? $smarty->fetch("_common/_menu.tpl") : _tr('No modules'));
        }
        $smarty->display("_common/index.tpl");
    }
} else {
    $rawmode = getParameter("rawmode");
    if (isset($rawmode) && $rawmode == 'yes') {
        include_once "libs/paloSantoJSON.class.php";
        $jsonObject = new PaloSantoJSON();
        $jsonObject->set_status("ERROR_SESSION");
        $jsonObject->set_error(_tr("Your session has expired. If you want to do a login please press the button 'Accept'."));
        $jsonObject->set_message(null);
        Header('Content-Type: application/json');
        echo $jsonObject->createJSON();
    } else {
        $oPn = new paloSantoNavigation(array(), $smarty);
        $oPn->putHEAD_JQUERY_HTML();
        $smarty->assign("THEMENAME", $arrConf['mainTheme']);
        $smarty->assign("WEBPATH", "web/");
        $smarty->assign("WEBCOMMON", "../" . $arrConf['webCommon'] . "/");
        $smarty->assign("currentyear", date("Y"));
        $smarty->assign("PAGE_NAME", _tr('Login page'));
        $smarty->assign("WELCOME", _tr('Welcome to Elastix'));
        $smarty->assign("ENTER_USER_PASSWORD", _tr('Please enter your username and password'));
        $smarty->assign("USERNAME", _tr('Username'));
        $smarty->assign("PASSWORD", _tr('Password'));
        $smarty->assign("SUBMIT", _tr('Submit'));
Beispiel #26
0
function uploadCSV($smarty, $module_name, $local_templates_dir, &$pDB, $arrConf)
{
    $jsonObject = new PaloSantoJSON();
    $coreContact = new coreContact($pDB);
    foreach ($_FILES['elx_uploadFile']['error'] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            if (!preg_match('/\\.csv$/i', $_FILES['elx_uploadFile']['name'][$key])) {
                $smarty->assign("MSG_ERROR_FIELD", _tr("Invalid file extension.- It must be csv"));
                $jsonObject->set_error(_tr('Invalid file extension.- It must be csv'));
                return $jsonObject->createJSON();
            } else {
                if (is_uploaded_file($_FILES['elx_uploadFile']['tmp_name'][$key])) {
                    //Funcion para cargar las extensiones
                    $result = $coreContact->load_contacts_from_csv($_FILES['elx_uploadFile']['tmp_name'][$key]);
                    if ($result === false) {
                        $jsonObject->set_error($coreContact->getErrorMsg());
                        return $jsonObject->createJSON();
                    }
                    $jsonObject->set_message(_tr("contacts created"));
                } else {
                    $smarty->assign("MSG_ERROR_FIELD", _tr("Possible file upload attack. Filename"));
                    $jsonObject->set_error(_tr('Possible file upload attack. Filename'));
                    return $jsonObject->createJSON();
                }
            }
        } else {
            $jsonObject->set_error('algo paso');
        }
    }
    return $jsonObject->createJSON();
}
Beispiel #27
0
function saveEditANI($pDB, $credentials)
{
    $jsonObject = new PaloSantoJSON();
    $ani_domain = getParameter("ani_domain");
    $ani_trunkid = getParameter("ani_trunkid");
    $ani_prefix = getParameter("ani_prefix");
    $ani_prefix = trim($ani_prefix);
    if ($ani_prefix == "") {
        $ani_prefix = NULL;
    }
    if ($credentials['userlevel'] != 'superadmin') {
        $ani_domain = $credentials['domain'];
    }
    $pANI = new paloSantoANI($pDB, $ani_domain);
    $pDB->beginTransaction();
    $success = $pANI->updateANI_Prefix($ani_trunkid, $ani_prefix);
    if ($success) {
        $pDB->commit();
        $jsonObject->set_message(_tr("Prefix ANI was saved successfully.") . " [{$ani_prefix}] -> {$ani_domain}");
    } else {
        $pDB->rollBack();
        $error = $pANI->errMsg;
        $jsonObject->set_error($error);
    }
    return $jsonObject->createJSON();
}
Beispiel #28
0
function saveExtensionSettings($smarty, $module_name, $local_templates_dir, $pDB, $arrConf)
{
    $jsonObject = new PaloSantoJSON();
    global $arrCredentials;
    $pMyExten = new paloMyExten($pDB, $arrCredentials['idUser']);
    $myExten['secret'] = getParameter('secretExtension');
    $myExten['language'] = getParameter('language_vm');
    $myExten['doNotDisturb'] = getParameter('doNotDisturb');
    $myExten['callwaiting'] = getParameter('callWaiting');
    $myExten['callForwardOpt'] = getParameter('callForwardOpt');
    //n
    $myExten['callForwardUnavailableOpt'] = getParameter('callForwardUnavailableOpt');
    //n
    $myExten['callForwardBusyOpt'] = getParameter('callForwardBusyOpt');
    //n
    $myExten['callForwardInp'] = getParameter('callForwardInp');
    //n
    $myExten['callForwardUnavailableInp'] = getParameter('callForwardUnavailableInp');
    //n
    $myExten['callForwardBusyInp'] = getParameter('callForwardBusyInp');
    //n
    $myExten['record_in'] = getParameter('recordIncoming');
    $myExten['record_out'] = getParameter('recordOutgoing');
    $myExten['create_vm'] = getParameter('status_vm');
    $myExten['vmemail'] = getParameter('email_vm');
    $myExten['vmpassword'] = getParameter('password_vm');
    $myExten['vmattach'] = getParameter('emailAttachment_vm');
    $myExten['vmsaycid'] = getParameter('playCid_vm');
    $myExten['vmenvelope'] = getParameter('playEnvelope_vm');
    $myExten['vmdelete'] = getParameter('deleteVmail');
    $pMyExten = new paloMyExten($pDB, $arrCredentials['idUser']);
    $pMyExten->_DB->beginTransaction();
    if (!$pMyExten->editExten($myExten)) {
        $pMyExten->_DB->rollBack();
        $jsonObject->set_error($pMyExten->getErrorMsg());
        //$jsonObject->set_error($myExten);
    } else {
        $pMyExten->_DB->commit();
        //$jsonObject->set_message($myExten);
        $jsonObject->set_message("Changes were saved succefully");
    }
    return $jsonObject->createJSON();
}
Beispiel #29
0
function attachFile($smarty, $module_name, $local_templates_dir, $arrConf, &$pImap)
{
    $jsonObject = new PaloSantoJSON();
    try {
        if (!defined("PATH_UPLOAD_ATTACHS")) {
            throw new RuntimeException(_tr("Error uploading your file.") . _tr("Temporary directory does not exist"));
        }
        if (!is_dir(PATH_UPLOAD_ATTACHS)) {
            throw new RuntimeException(_tr("Error uploading your file.") . _tr("Temporary directory does not exist"));
        }
        // Undefined | Multiple Files | $_FILES Corruption Attack
        // If this request falls under any of them, treat it invalid.
        if (!isset($_FILES['attachFileButton']['error'][0])) {
            throw new RuntimeException('Invalid parameters.');
        }
        // Check $_FILES['upfile']['error'] value.
        switch ($_FILES['attachFileButton']['error'][0]) {
            case UPLOAD_ERR_OK:
                break;
            case UPLOAD_ERR_NO_FILE:
                throw new RuntimeException('No file sent.');
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                throw new RuntimeException('Exceeded filesize limit.');
                //chequea el limite seteado en php.ini
            //chequea el limite seteado en php.ini
            default:
                throw new RuntimeException('Unknown errors.');
        }
        // You should also check filesize here.
        // TODO:definir cual debe ser el máximo tamaño de los archivos adjuntos
        // o sacarlo de lagun archivo de ocnfiguracion
        $uploadSize = '10000000';
        //10Mega Bytes
        if ($_FILES['attachFileButton']['size'][0] > $uploadSize) {
            throw new RuntimeException('Exceeded filesize limit.');
        }
        if (preg_match("/(\\.php)/", $_FILES['attachFileButton']['name'][0])) {
            throw new RuntimeException('Possible file upload attack.');
        }
        //En los archivos adjuntos todos los tipo están permitidos
        //TODO: Definir cual es la lista de archivos adjunto que están permitidos
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimetype = $finfo->file($_FILES["attachFileButton"]["tmp_name"][0]);
        //Movemos el archivo subido a la ruta definida en PATH_UPLOAD_ATTACHS
        //aqui se almacenan hasta ser enviados
        //Para asegurarnos de que el archvo subido tenga un nombre único
        //usamos la funcion tempnam para crear un archivo temporal con nombre único
        //y después usamos ese nombre para el archivo que subido
        $tmpFileName = tempnam(PATH_UPLOAD_ATTACHS, "");
        if ($tmpFileName == false) {
            throw new RuntimeException('Failed to create temporary file file.');
        }
        if (!move_uploaded_file($_FILES['attachFileButton']['tmp_name'][0], $tmpFileName)) {
            throw new RuntimeException('Failed to move uploaded file.');
        }
        //una vez que el archivo a sido subido procedemos a guardar
        //la información de este en sesión para luego ser adjunto al momento de enviar el correo
        $idAttach = md5($tmpFileName);
        $_SESSION["elastix_emailAttachs"][$idAttach]['filename'] = $tmpFileName;
        $_SESSION["elastix_emailAttachs"][$idAttach]['name'] = $_FILES['attachFileButton']['name'][0];
        $_SESSION["elastix_emailAttachs"][$idAttach]['mime'] = $mimetype;
        $_SESSION["elastix_emailAttachs"][$idAttach]['type'] = "file";
        $jsonObject->set_message(array('idAttach' => $idAttach, 'name' => htmlentities($_FILES['attachFileButton']['name'][0], ENT_COMPAT, 'UTF-8')));
        unset($_POST);
        unset($_FILES);
    } catch (RuntimeException $e) {
        $jsonObject->set_error($e->getMessage());
    }
    return $jsonObject->createJSON();
}
Beispiel #30
0
function _moduleContent(&$smarty, $module_name)
{
    include_once "libs/paloSantoDB.class.php";
    include_once "libs/paloSantoConfig.class.php";
    include_once "libs/paloSantoGrid.class.php";
    include_once "libs/paloSantoACL.class.php";
    include_once "modules/{$module_name}/configs/default.conf.php";
    //include file language agree to elastix configuration
    //if file language not exists, then include language by default (en)
    $lang = get_language();
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $lang_file = "modules/{$module_name}/lang/{$lang}.lang";
    if (file_exists("{$base_dir}/{$lang_file}")) {
        include_once "{$lang_file}";
    } else {
        include_once "modules/{$module_name}/lang/en.lang";
    }
    //global variables
    global $arrConf;
    global $arrConfModule;
    global $arrLang;
    global $arrLangModule;
    $arrConf = array_merge($arrConf, $arrConfModule);
    $arrLang = array_merge($arrLang, $arrLangModule);
    //conexion acl.db
    $pDB = new paloDB($arrConf['elastix_dsn']['acl']);
    //folder path for custom templates
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($arrConf['templates_dir']) ? $arrConf['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme'];
    $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*");
    $arrConfig = $pConfig->leer_configuracion(false);
    $dsn = $arrConfig['AMPDBENGINE']['valor'] . "://" . $arrConfig['AMPDBUSER']['valor'] . ":" . $arrConfig['AMPDBPASS']['valor'] . "@" . $arrConfig['AMPDBHOST']['valor'] . "/asterisk";
    $pDBa = new paloDB($dsn);
    ////////////////////
    if (!empty($pDB->errMsg)) {
        echo "ERROR DE DB: {$pDB->errMsg} <br>";
    }
    $arrData = array();
    $arrData[""] = $arrLang["no extension"];
    $pACL = new paloACL($pDB);
    if (!empty($pACL->errMsg)) {
        echo "ERROR DE ACL: {$pACL->errMsg} <br>";
    }
    /*******/
    $typeUser = "";
    $userLevel1 = "";
    $extOther = "";
    $userAccount = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : "";
    $idUserAccount = $pACL->isUserAdministratorGroup($userAccount);
    $idUserInt = $pACL->getIdUser($userAccount);
    if ($idUserAccount) {
        $userLevel1 = "admin";
    } else {
        $userLevel1 = "other";
    }
    $smarty->assign("userLevel1", $userLevel1);
    /*******/
    $sQuery = "select extension from users order by extension;";
    $arrayResult = $pDBa->fetchTable($sQuery, true);
    if (!$arrayResult) {
        $error = $pDBa->errMsg;
    } else {
        if (is_array($arrayResult) && count($arrayResult) > 0) {
            //$arrData[$item["null"]] = "No extension";
            if ($idUserAccount) {
                foreach ($arrayResult as $item) {
                    $arrData[$item["extension"]] = $item["extension"];
                }
            } else {
                $idOther = $pACL->getIdUser($userAccount);
                $arrUserOther = $pACL->getUsers($idOther);
                $extOther = $arrUserOther[0][3];
                $arrData[$extOther] = $extOther;
            }
        }
    }
    $arrGruposACL = $pACL->getGroups();
    for ($i = 0; $i < count($arrGruposACL); $i++) {
        if ($arrGruposACL[$i][1] == 'administrator') {
            $arrGruposACL[$i][1] = $arrLang['administrator'];
        } else {
            if ($arrGruposACL[$i][1] == 'operator') {
                $arrGruposACL[$i][1] = $arrLang['operator'];
            } else {
                if ($arrGruposACL[$i][1] == 'extension') {
                    $arrGruposACL[$i][1] = $arrLang['extension'];
                }
            }
        }
        if ($idUserAccount) {
            $arrGrupos[$arrGruposACL[$i][0]] = $arrGruposACL[$i][1];
        } else {
            $arrUserPer = $pACL->getMembership($idUserInt);
            foreach ($arrUserPer as $key => $value) {
                if ($arrGruposACL[$i][1] == $key) {
                    $arrGrupos[$arrGruposACL[$i][0]] = $arrGruposACL[$i][1];
                }
            }
        }
    }
    $arrFormElements = array("description" => array("LABEL" => "{$arrLang['Name']} {$arrLang['(Ex. John Doe)']}", "REQUIRED" => "no", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "name" => array("LABEL" => $arrLang["Login"], "REQUIRED" => "yes", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => "", "EDITABLE" => "no"), "password1" => array("LABEL" => $arrLang["Password"], "REQUIRED" => "yes", "INPUT_TYPE" => "PASSWORD", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "password2" => array("LABEL" => $arrLang["Retype password"], "REQUIRED" => "yes", "INPUT_TYPE" => "PASSWORD", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "group" => array("LABEL" => $arrLang["Group"], "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => $arrGrupos, "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "extension" => array("LABEL" => $arrLang["Extension"], "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => $arrData, "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "webmailpassword1" => array("LABEL" => $arrLang["Webmail Password"], "REQUIRED" => "no", "INPUT_TYPE" => "PASSWORD", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "webmailuser" => array("LABEL" => $arrLang["Webmail User"], "REQUIRED" => "no", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "webmaildomain" => array("LABEL" => $arrLang["Webmail Domain"], "REQUIRED" => "no", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""));
    $contenidoModulo = "";
    $smarty->assign("REQUIRED_FIELD", $arrLang["Required field"]);
    $smarty->assign("CANCEL", $arrLang["Cancel"]);
    $smarty->assign("APPLY_CHANGES", $arrLang["Apply changes"]);
    $smarty->assign("SAVE", $arrLang["Save"]);
    $smarty->assign("EDIT", $arrLang["Edit"]);
    $smarty->assign("DELETE", $arrLang["Delete"]);
    $smarty->assign("CONFIRM_CONTINUE", $arrLang["Are you sure you wish to continue?"]);
    $smarty->assign("icon", "images/user.png");
    $smarty->assign("title_webmail", $arrLang["Mail Profile"]);
    if (isset($_POST['submit_create_user'])) {
        // Implementar
        include_once "libs/paloSantoForm.class.php";
        $arrFillUser['description'] = '';
        $arrFillUser['name'] = '';
        $arrFillUser['group'] = '';
        $arrFillUser['extension'] = '';
        $arrFillUser['password1'] = '';
        $arrFillUser['password2'] = '';
        $oForm = new paloForm($smarty, $arrFormElements);
        $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["New User"], $arrFillUser);
    } else {
        if (!is_null(getParameter("edit"))) {
            $contenidoModulo = editUser($userAccount, $pACL, $pDB, $arrFormElements, $smarty, $local_templates_dir, $arrLang, $idUserAccount, $userLevel1);
        } else {
            if (isset($_POST['submit_save_user'])) {
                include_once "libs/paloSantoForm.class.php";
                $oForm = new paloForm($smarty, $arrFormElements);
                if ($oForm->validateForm($_POST)) {
                    // Exito, puedo procesar los datos ahora.
                    $pACL = new paloACL($pDB);
                    if (empty($_POST['password1']) or $_POST['password1'] != $_POST['password2']) {
                        // Error claves
                        $smarty->assign("mb_message", $arrLang["The passwords are empty or don't match"]);
                        $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["New User"], $_POST);
                    } else {
                        if ($userLevel1 == "admin") {
                            // Creo al usuario
                            $md5_password = md5($_POST['password1']);
                            $pACL->createUser($_POST['name'], $_POST['description'], $md5_password, $_POST['extension']);
                            $idUser = $pACL->getIdUser($_POST['name']);
                            // Versiones viejas del archivo acl.db tienen una fila con una
                            // tupla que asocia al usuario inexistente con ID 2, con el
                            // grupo 2 (Operadores). Se limpia cualquier membresía extraña.
                            $listaMembresia = $pACL->getMembership($idUser);
                            if (is_array($listaMembresia) && count($listaMembresia) > 0) {
                                foreach ($listaMembresia as $idGrupo) {
                                    $pACL->delFromGroup($idUser, $idGrupo);
                                }
                            }
                            // Creo la membresia
                            $pACL->addToGroup($idUser, $_POST['group']);
                            $bExito = TRUE;
                            if (empty($pACL->errMsg)) {
                                $nuevasPropiedades = array();
                                if (!empty($_POST['webmailuser'])) {
                                    $nuevasPropiedades['login'] = $_POST['webmailuser'];
                                }
                                if (!empty($_POST['webmailpassword1'])) {
                                    $nuevasPropiedades['password'] = $_POST['webmailpassword1'];
                                }
                                if (!empty($_POST['webmaildomain'])) {
                                    $nuevasPropiedades['domain'] = $_POST['webmaildomain'];
                                }
                                $bExito = actualizarPropiedades($pDB, $smarty, $idUser, 'webmail', 'default', $nuevasPropiedades);
                            }
                            if (!empty($pACL->errMsg)) {
                                // Ocurrio algun error aqui
                                $smarty->assign("mb_message", "ERROR: {$pACL->errMsg}");
                                $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["New User"], $_POST);
                            } else {
                                if ($bExito) {
                                    header("Location: ?menu=userlist");
                                }
                            }
                        } else {
                            $smarty->assign("mb_message", $arrLang["userNoAllowed"]);
                        }
                    }
                } else {
                    // Error
                    $smarty->assign("mb_title", $arrLang["Validation Error"]);
                    $arrErrores = $oForm->arrErroresValidacion;
                    $strErrorMsg = "<b>{$arrLang['The following fields contain errors']}:</b><br>";
                    foreach ($arrErrores as $k => $v) {
                        $strErrorMsg .= "{$k}, ";
                    }
                    $strErrorMsg .= "";
                    $smarty->assign("mb_message", $strErrorMsg);
                    $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["New User"], $_POST);
                }
            } else {
                if (isset($_POST['submit_apply_changes'])) {
                    $arrayContent = applyChanges($userAccount, $pACL, $smarty, $arrLang, $idUserAccount, $userLevel1, $arrFormElements, $pDB, $local_templates_dir, $idUserInt, $extOther);
                    if (isset($arrayContent["mb_title"]) && isset($arrayContent["mb_message"])) {
                        $smarty->assign("mb_title", $arrayContent["mb_title"]);
                        $smarty->assign("mb_message", $arrayContent["mb_message"]);
                    }
                    if ($arrayContent["success"]) {
                        header("Location: ?menu=userlist");
                    } else {
                        if (isset($arrayContent["id_user"])) {
                            $smarty->assign("id_user", $_POST['id_user']);
                        }
                        if (isset($arrayContent["fill_user"])) {
                            $contenidoModulo = $arrayContent["form"]->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["Edit User"], $arrayContent["fill_user"]);
                        } else {
                            $contenidoModulo = $arrayContent["content"];
                        }
                    }
                } else {
                    if (isset($_GET['action']) && $_GET['action'] == "view") {
                        if (!$pACL->isUserAdministratorGroup($userAccount)) {
                            if ($pACL->getIdUser($userAccount) != $_GET['id']) {
                                $smarty->assign("mb_title", $arrLang["ERROR"]);
                                $smarty->assign("mb_message", $arrLang["You are not authorized to access to information of that user"]);
                                return reportUserList($arrLang, $pACL, $idUserAccount, $smarty, $userLevel1, $userAccount);
                            }
                        }
                        include_once "libs/paloSantoForm.class.php";
                        $oForm = new paloForm($smarty, $arrFormElements);
                        //- TODO: Tengo que validar que el id sea valido, si no es valido muestro un mensaje de error
                        $oForm->setViewMode();
                        // Esto es para activar el modo "preview"
                        $arrUser = $pACL->getUsers($_GET['id']);
                        // Conversion de formato
                        $arrTmp['name'] = $arrUser[0][1];
                        $arrTmp['description'] = $arrUser[0][2];
                        $arrTmp['password1'] = "****";
                        $arrTmp['password2'] = "****";
                        $arrTmp['extension'] = $arrUser[0][3];
                        //- TODO: Falta llenar el grupo
                        $arrMembership = $pACL->getMembership($_GET['id']);
                        $id_group = "";
                        if (is_array($arrMembership)) {
                            foreach ($arrMembership as $groupName => $groupId) {
                                $id_group = $groupId;
                                // Asumo que cada usuario solo puede pertenecer a un grupo
                                break;
                            }
                        }
                        $arrTmp['group'] = $id_group;
                        $listaPropiedades = leerPropiedadesWebmail($pDB, $smarty, $_GET['id']);
                        if (isset($listaPropiedades['login'])) {
                            $arrTmp['webmailuser'] = $listaPropiedades['login'];
                        }
                        if (isset($listaPropiedades['domain'])) {
                            $arrTmp['webmaildomain'] = $listaPropiedades['domain'];
                        }
                        if (isset($listaPropiedades['password'])) {
                            $arrTmp['webmailpassword1'] = '****';
                        }
                        //if (isset($listaPropiedades['imapsvr'])) $arrTmp['webmailimapsvr'] = $listaPropiedades['imapsvr'];
                        $smarty->assign("id_user", $_GET['id']);
                        $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $arrLang["View User"], $arrTmp);
                        // hay que pasar el arreglo
                    } else {
                        if (getParameter('action') == "edit_userExtension") {
                            $smarty->assign("editUserExtension", "yes");
                            $html = editUser($userAccount, $pACL, $pDB, $arrFormElements, $smarty, $local_templates_dir, $arrLang, $idUserAccount, $userLevel1);
                            $smarty->assign("CONTENT", $html);
                            $smarty->assign("THEMENAME", $arrConf['mainTheme']);
                            $smarty->assign("MODULE_NAME", $module_name);
                            $smarty->assign("path", "");
                            $contenidoModulo = $smarty->display("{$local_templates_dir}/edit_userExtension.tpl");
                        } else {
                            if (getParameter('action') == "apply_changes_UserExtension") {
                                include_once "libs/paloSantoJSON.class.php";
                                $jsonObject = new PaloSantoJSON();
                                $result = applyChanges($userAccount, $pACL, $smarty, $arrLang, $idUserAccount, $userLevel1, $arrFormElements, $pDB, $local_templates_dir, $idUserInt, $extOther);
                                $arrMessage["mb_title"] = isset($result["mb_title"]) ? $result["mb_title"] : null;
                                $arrMessage["mb_message"] = isset($result["mb_message"]) ? $result["mb_message"] : null;
                                $arrMessage["success"] = $result["success"];
                                $jsonObject->set_message($arrMessage);
                                $contenidoModulo = $jsonObject->createJSON();
                            } else {
                                $contenidoModulo = reportUserList($arrLang, $pACL, $idUserAccount, $smarty, $userLevel1, $userAccount);
                            }
                        }
                    }
                }
            }
        }
    }
    return $contenidoModulo;
}