/** * Retorna uma instância já existente ou nova instância do banco de dados. * * @return Zend_Db_Adapter_Abstract $instance */ public static function getInstance() { if (self::$instance === null) { $config = Snep_Config::getConfig()->ambiente->db->toArray(); $adapter = array_shift($config); if (strtoupper($adapter) == "PDO_MYSQL") { $config["driver_options"] = array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true); } self::$instance = self::factory($adapter, $config); Zend_Db_Table_Abstract::setDefaultAdapter(self::$instance); require_once "Zend/Registry.php"; Zend_Registry::set("db", self::$instance); } return self::$instance; }
public static function loadConfFromDb() { $view = new Zend_View(); $db = Snep_Db::getInstance(); // TODO - buscar informações da tabela extensions foreach (array("sip", "iax2") as $tech) { $config = Zend_Registry::get('config'); $asteriskDirectory = $config->system->path->asterisk->conf; $extenFileConf = "{$asteriskDirectory}/snep/snep-{$tech}.conf"; $trunkFileConf = "{$asteriskDirectory}/snep/snep-{$tech}-trunks.conf"; if (!is_writable($extenFileConf)) { throw new PBX_Exception_IO($view->translate("Failed to open file %s with write permission.", $extenFileConf)); } if (!is_writable($trunkFileConf)) { throw new PBX_Exception_IO($view->translate("Failed to open file %s with write permission.", $trunkFileConf)); } /* clean snep-sip.conf file */ file_put_contents($extenFileConf, ''); /* Register header on output string of the file */ $todayDate = date("d/m/Y H:m:s"); $header = ";------------------------------------------------------------------------------------\n"; $header .= "; Arquivo: snep-{$tech}.conf - Cadastro de ramais \n"; $header .= "; \n"; $header .= "; Atualizado em: {$todayDate} \n"; $header .= "; Copyright(c) 2008 Opens Tecnologia \n"; $header .= ";------------------------------------------------------------------------------------\n"; $header .= "; Os registros a Seguir sao gerados pelo Software SNEP. \n"; $header .= "; Este Arquivo NAO DEVE ser editado Manualmente sob riscos de \n"; $header .= "; causar mau funcionamento do Asterisk \n"; $header .= ";------------------------------------------------------------------------------------\n"; /* query that gets information of the peers on the DB */ $sql = "SELECT * FROM peers WHERE name != 'admin' AND canal like '" . strtoupper($tech) . "%'"; $peer_data = $db->query($sql)->fetchAll(); $peers = "\n"; $trunk_config = "\n"; if (count($peer_data) > 0) { foreach ($peer_data as $peer) { $sipallow = explode(";", $peer['allow']); $allow = ''; foreach ($sipallow as $siper) { if ($siper != '') { $allow .= $siper . ","; } } $allow = substr($allow, 0, strlen($allow) - 1); if ($peer['peer_type'] == 'T') { $select = $db->select()->from('trunks')->where("name = {$peer['name']}")->limit(1); $trunk = $db->query($select)->fetchObject(); if ($trunk->type == "SNEPSIP") { /* Assemble trunk entries */ $peers .= '[' . $peer['username'] . "]\n"; $peers .= 'type=' . $peer['type'] . "\n"; $peers .= 'context=' . $peer['context'] . "\n"; $peers .= 'canreinvite=' . $peer['canreinvite'] . "\n"; $peers .= 'dtmfmode=' . ($peer['dtmfmode'] ? $peer['dtmfmode'] : "rfc2833") . "\n"; $peers .= 'host=' . $peer['host'] . "\n"; $peers .= 'qualify=' . ($peer['qualify'] == "no" ? "no" : "yes") . "\n"; $peers .= 'nat=' . $peer['nat'] . "\n"; $peers .= 'disallow=' . $peer['disallow'] . "\n"; $peers .= 'allow=' . $allow . "\n"; $peers .= "\n"; } else { if ($trunk->type == "SNEPIAX2") { /* Assemble Extension entries */ $peers .= '[' . $peer['username'] . "]\n"; $peers .= 'type=' . $peer['type'] . "\n"; $peers .= 'username='******'username'] . "\n"; $peers .= 'secret=' . $peer['username'] . "\n"; $peers .= 'context=' . $peer['context'] . "\n"; $peers .= 'canreinvite=' . $peer['canreinvite'] . "\n"; $peers .= 'dtmfmode=' . ($peer['dtmfmode'] ? $peer['dtmfmode'] : "rfc2833") . "\n"; $peers .= 'host=' . $peer['host'] . "\n"; $peers .= 'qualify=' . ($peer['qualify'] == "no" ? "no" : "yes") . "\n"; $peers .= 'nat=' . $peer['nat'] . "\n"; $peers .= 'disallow=' . $peer['disallow'] . "\n"; $peers .= 'allow=' . $allow . "\n"; $peers .= "\n"; } else { if ($trunk->dialmethod != "NOAUTH") { /* Assemble trunk entries */ $peers .= '[' . $peer['username'] . "]\n"; $peers .= 'type=' . $peer['type'] . "\n"; $peers .= 'context=' . $peer['context'] . "\n"; $peers .= $peer['fromdomain'] != "" ? 'fromdomain=' . $peer['fromdomain'] . "\n" : ""; $peers .= $peer['fromuser'] != "" ? 'fromuser='******'fromuser'] . "\n" : ""; $peers .= 'canreinvite=' . $peer['canreinvite'] . "\n"; $peers .= 'dtmfmode=' . ($peer['dtmfmode'] ? $peer['dtmfmode'] : "rfc2833") . "\n"; $peers .= 'host=' . $peer['host'] . "\n"; $peers .= 'qualify=' . $peer['qualify'] . "\n"; $peers .= 'nat=' . $peer['nat'] . "\n"; $peers .= 'disallow=' . $peer['disallow'] . "\n"; $peers .= 'allow=' . $allow . "\n"; if ($peer['port'] != "") { $peers .= 'port=' . $peer['port'] . "\n"; } if ($peer['call-limit'] != "" && $trunk->type == "SIP") { $peers .= 'call-limit=' . $peer['call-limit'] . "\n"; } if ($trunk->insecure != "") { $peers .= 'insecure=' . $trunk->insecure . "\n"; } if ($trunk->domain != "" && $trunk->type == "SIP") { $peers .= 'domain=' . $trunk->domain . "\n"; } if ($trunk->type == "IAX2") { $peers .= 'trunk=' . $peer['trunk'] . "\n"; } if ($trunk->reverse_auth) { $peers .= 'username='******'username'] . "\n"; $peers .= 'secret=' . $peer['secret'] . "\n"; } $peers .= "\n"; } } } $trunk_config .= $trunk->dialmethod != "NOAUTH" && !preg_match("/SNEP/", $trunk->type) ? "register => " . $peer['username'] . ":" . $peer['secret'] . "@" . $peer['host'] . "\n" : ""; } else { /* Assemble Extension entries */ $peers .= '[' . $peer['name'] . "]\n"; $peers .= 'type=' . $peer['type'] . "\n"; $peers .= 'context=' . $peer['context'] . "\n"; $peers .= 'host=' . $peer['host'] . "\n"; # dinamyc $peers .= 'secret=' . $peer['secret'] . "\n"; $peers .= 'callerid=' . $peer['callerid'] . "\n"; $peers .= 'canreinvite=' . $peer['canreinvite'] . "\n"; $peers .= 'dtmfmode=' . ($peer['dtmfmode'] ? $peer['dtmfmode'] : "rfc2833") . "\n"; $peers .= 'nat=' . $peer['nat'] . "\n"; $peers .= 'qualify=' . $peer['qualify'] . "\n"; $peers .= 'disallow=' . $peer['disallow'] . "\n"; $peers .= 'allow=' . $allow . "\n"; $peers .= 'username='******'name'] . "\n"; $peers .= 'fromuser='******'name'] . "\n"; $peers .= 'call-limit=' . $peer['call-limit'] . "\n"; $peers .= "\n"; } } } $trunkcont = str_replace(".conf", "-trunks.conf", $header) . $trunk_config; file_put_contents($trunkFileConf, $trunkcont); $content = $header . $peers; file_put_contents($extenFileConf, $content); } // Forcing asterisk to reload the configs $asteriskAmi = PBX_Asterisk_AMI::getInstance(); $asteriskAmi->Command("sip reload"); $asteriskAmi->Command("iax2 reload"); }
/** * Procura o dono de uma interface baseado em canal. * * @param string $channel Canal da interface * @return object Objeto que representa o dono da interface (se houver) */ public static function getChannelOwner($channel) { $db = Snep_Db::getInstance(); $select = $db->select()->from('trunks'); $trunk_ifaces = $db->query($select)->fetchAll(); foreach ($trunk_ifaces as $interface) { if (preg_match("#^{$interface['id_regex']}\$#i", $channel)) { return PBX_Trunks::get($interface['id']); } } $select = $db->select()->from('peers')->where("name != 'admin' AND peer_type='R'"); $interfaces = $db->query($select)->fetchAll(); foreach ($interfaces as $interface) { if (preg_match("#^{$interface['canal']}\$#i", $channel)) { return PBX_Usuarios::get($interface['name']); } } return null; }
/** * Verifica se um grupo sofre herança de outro. Se um grupo é filho de outro. * * A forma mais fácil que encontrei de fazer essa checagem é criar uma * instancia do Zend_Acl e colocar as informações todas lá e fazer uma * checagem simples. * * @param string $parent suposto pai * @param string $node suposto filho * @return boolean resultado do teste */ public static function hasGroupInheritance($parent, $node) { $db = Snep_Db::getInstance(); $select = $db->select()->from('groups')->where("name != 'admin' AND name != 'users' AND name != 'all'"); $stmt = $db->query($select); $groups = $stmt->fetchAll(); $acl = new Zend_Acl(); $acl->addRole(new Zend_Acl_Role('all'), null); $acl->addRole(new Zend_Acl_Role('users'), 'all'); $acl->addRole(new Zend_Acl_Role('admin'), 'all'); foreach ($groups as $group) { $inherit = $group['inherit'] ? $group['inherit'] : null; $acl->addRole(new Zend_Acl_Role($group['name']), $inherit); } $acl->deny(); $acl->allow($parent); return $acl->isAllowed($node); }
defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__))); // Add standard library to the include path set_include_path(implode(PATH_SEPARATOR, array(APPLICATION_PATH . '/lib', get_include_path()))); // Initializing Snep Config require_once "Snep/Config.php"; Snep_Config::setConfigFile(APPLICATION_PATH . '/includes/setup.conf'); $config = Snep_Config::getConfig(); defined('SNEP_VENDOR') || define('SNEP_VENDOR', $config->ambiente->emp_nome); defined('SNEP_VERSION') || define('SNEP_VERSION', trim(file_get_contents(APPLICATION_PATH . "/configs/snep_version"))); // Define application environment $snep_env = Snep_Config::getConfig()->system->debug ? "development" : "production"; defined('APPLICATION_ENV') || define('APPLICATION_ENV', getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : $snep_env); if (APPLICATION_ENV === "development") { require_once "Zend/Debug.php"; } // Adds the modules directory to the snep module system require_once "Snep/Modules.php"; Snep_Modules::getInstance()->addPath(APPLICATION_PATH . "/modules"); /** Zend_Application */ require_once 'Zend/Application.php'; require_once 'Zend/Config/Ini.php'; // Create application, bootstrap, and run $application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/application.ini'); // Adding standard lib autoloader capabilities to keep old code running $application->setAutoloaderNamespaces(array("Asterisk_", "PBX_", "Snep_")); // Keeping old links to avoid rework in too much stuff. require_once "Zend/Registry.php"; Zend_Registry::set("config", $config); Zend_Registry::set("db", Snep_Db::getInstance()); /* Fight! */ $application->bootstrap()->run();
public function boot() { set_time_limit(0); // Iniciando ambiente para ideal funcionamento da Lib $this->startAutoLoader(); $this->startLocale(); // Coletando informações enviadas pelo asterisk $this->startAsterisk(); // Iniciando logs do sistema $this->startLogger(); // Iniciando objeto para comunicação com banco de dados Snep_Db::getInstance(); $this->registerCCustos(); $this->registerQueues(); // Atualizando request para facilitar trabalho das ações $this->updateRequest(); // Iniciando modulos e Actions das regras de negócio $this->startModules(); $this->startActions(); // Coletando plugins para regras de negócio $this->startRulePlugins(); }
/** * Cadastra uma regra de negócio no banco de dados do Snep. * * @param PBX_Rule $rule */ public static function register($rule) { $srcs = ""; foreach ($rule->getSrcList() as $src) { $srcs .= "," . trim($src['type'] . ":" . $src['value'], ':'); } $srcs = trim($srcs, ','); $dsts = ""; foreach ($rule->getDstList() as $dst) { $dsts .= "," . trim($dst['type'] . ":" . $dst['value'], ':'); } $dsts = trim($dsts, ','); $validade = implode(",", $rule->getValidTimeList()); $diasDaSemana = implode(",", $rule->getValidWeekDays()); $insert_data = array("prio" => $rule->getPriority(), "desc" => $rule->getDesc(), "origem" => $srcs, "destino" => $dsts, "validade" => $validade, "diasDaSemana" => $diasDaSemana, "record" => $rule->isRecording()); $db = Snep_Db::getInstance(); $db->beginTransaction(); try { $db->insert("regras_negocio", $insert_data); $rule->setId((int) $db->lastInsertId('regras_negocio_id')); $action_prio = 0; foreach ($rule->getAcoes() as $acao) { $action_insert_data = array("regra_id" => $rule->getId(), "prio" => $action_prio, "action" => get_class($acao)); $db->insert("regras_negocio_actions", $action_insert_data); foreach ($acao->getConfigArray() as $chave => $valor) { $action_config_data = array("regra_id" => $rule->getId(), "prio" => $action_prio, "key" => $chave, "value" => $valor); $db->insert("regras_negocio_actions_config", $action_config_data); } $action_prio++; } $db->commit(); } catch (Exception $ex) { $db->rollBack(); throw $ex; } }
public function editAction() { $id = mysql_escape_string($this->getRequest()->getParam("trunk")); $this->view->breadcrumb = $this->view->breadcrumb = Snep_Breadcrumb::renderPath(array($this->view->translate("Manage"), $this->view->translate("Trunks"), $this->view->translate("Edit trunk %s", $id))); Zend_Registry::set('cancel_url', $this->getFrontController()->getBaseUrl() . '/' . $this->getRequest()->getControllerName() . '/index'); $form = $this->getForm(); $form->setAction($this->view->baseUrl() . "/index.php/trunks/edit/trunk/{$id}"); if ($this->getRequest()->isPost()) { if ($this->form->isValid($_POST)) { $trunk_data = $this->preparePost(); $sql = "SELECT name FROM trunks WHERE id='{$id}' LIMIT 1"; $name_data = Snep_Db::getInstance()->query($sql)->fetch(); $trunk_data['trunk']['name'] = $trunk_data['ip']['name'] = $name_data['name']; $db = Snep_Db::getInstance(); $db->beginTransaction(); try { $db->update("trunks", $trunk_data['trunk'], "id='{$id}'"); if ($trunk_data['trunk']['trunktype'] == "I") { $db->update("peers", $trunk_data['ip'], "name='{$trunk_data['trunk']['name']}' and peer_type='T'"); } $db->commit(); } catch (Exception $ex) { $db->rollBack(); throw $ex; } Snep_InterfaceConf::loadConfFromDb(); $this->_redirect("trunks"); } } $this->populateFromTrunk($form, $id); $this->view->form = $form; $this->renderScript("trunks/add_edit.phtml"); }