Example #1
0
 /**
  * 退出登录处理
  *
  */
 public function doLogout()
 {
     $_SESSION['admin'] = false;
     session_destroy();
     $this->app->redirect($this->app->cfg['url']['root'] . 'system/');
     exit;
 }
Example #2
0
 public function output()
 {
     $writer = new PHPExcel_Writer_Excel2007($this->spreadsheet);
     $file = "app/temp/" . uniqid() . "_report.xlsx";
     $writer->save($file);
     Application::redirect("/{$file}");
 }
Example #3
0
 public function getContents()
 {
     User::log("Logged out");
     $_SESSION = array();
     Application::$template = "login.tpl";
     Application::redirect("/");
 }
Example #4
0
 function indexAction()
 {
     try {
         $conexao = $this->conexao->getConexao();
         $breadcrumbs = array();
         $breadcrumbs[] = array("Logs" => "");
         $quantidade = 0;
         $logs = array();
         $quantidadePorPagina = isset($_REQUEST["exibir"]) && $_GET["exibir"] != '' ? (int) $_GET["exibir"] : QUANTIDADE_POR_PAGINA;
         $pagina = isset($_GET['p']) ? $_GET['p'] : 1;
         $pagina = $pagina <= 0 ? 1 : $pagina;
         $limit = $pagina == 1 ? $quantidadePorPagina : $quantidadePorPagina * ($pagina - 1);
         $offset = $pagina == 1 ? 0 : $quantidadePorPagina;
         //if (!temPermissao(array('logs:visualizarLogs'), $_SESSION['permissoes']))
         //	throw new Exception("Você não tem permissão para visualizar logs");
         $quantidade = $this->logDAO->getQuantidade($conexao, "logs");
         $logs = $this->logDAO->getDados($conexao, "logs", array("limit" => $limit, "offset" => $offset, "order" => array("data" => "desc")));
         if (count($logs) == 0 && $pagina > 1) {
             Application::redirect("?modulo=" . $_GET["modulo"] . "&p=" . ($pagina - 1));
         }
     } catch (Exception $e) {
         setMensagem("error", $e->getMessage());
     }
     $conexao->disconnect();
     $view = new View("views/logs/index.phtml");
     $view->setParams(array("title" => getTitulo($breadcrumbs), "logs" => $logs, "quantidade" => $quantidade, "quantidadePorPagina" => $quantidadePorPagina, "pagina" => $pagina, "breadcrumbs" => $breadcrumbs));
     $view->showContents();
 }
Example #5
0
 public function indexAction()
 {
     try {
         if (count($_POST) > 0) {
             if (Util::isEmpty($_POST['login']) && Util::isEmpty($_POST['senha'])) {
                 throw new Exception('Login inválido!');
             }
             $usuario = $this->dao->find($this->conexao->getConexao(), "usuarios", array("where" => array("login" => $_POST['login'], "senha" => md5($_POST['senha']))));
             if (count($usuario) == 0) {
                 throw new Exception("Login inválido!");
             }
             $_SESSION[PREFIX . "loginId"] = $usuario["id"];
             $_SESSION[PREFIX . "loginNome"] = $usuario["nome"];
             $_SESSION[PREFIX . "loginPermissao"] = $usuario["permissao"];
             //$this->logDAO->adicionar ($conexao->getConexao(), "fez", "login", $_SESSION["loginNome"], "Painel de administração");
             $this->conexao->getConexao()->disconnect();
             Application::redirect('index.php');
             exit;
         }
     } catch (Exception $e) {
         $this->conexao->getConexao()->disconnect();
         setMensagem("error", $e->getMessage());
     }
     $view = new View($_GET["modulo"], "painel", "index.phtml");
     $view->setParams(array("title" => "Login"));
     $view->showContents();
 }
Example #6
0
 public function alterarAction()
 {
     try {
         $conexao = $this->conexao->getConexao();
         //$redirecionar = montaRedirect($_SERVER["QUERY_STRING"], array("id", "acao"));
         $breadcrumbs = array();
         $dadosUsuario = $this->dao->findByPk($conexao, "usuarios", getVariavel("id"));
         // usuário só poderá alterar os dados dele mesmo
         if ($dadosUsuario["id"] != $_SESSION[PREFIX . "loginId"]) {
             throw new Exception("Você não tem permissão para atualizar dados de outros usuários");
         }
         $breadcrumbs[] = array($dadosUsuario["nome"] => "", "Alterar dados" => "");
         // armazena a senha atual em uma variável
         $senhaAtual = $dadosUsuario["senha"];
         $novaSenha = $dadosUsuario["senha"];
         // se submeteu dados
         if (count($_POST) > 0) {
             $redirecionar = NULL;
             $dados = $_POST;
             // todos os dados são obrigatórios
             $obrigatorios = array("nome" => array("tipo" => "input", "nome" => "Nome"), "login" => array("tipo" => "input", "nome" => "Login"), "email" => array("tipo" => "input", "nome" => "E-mail"));
             // se o usuário informar a nova senha, deverá informar a senha atual
             if (!empty($dados["novaSenha"])) {
                 $obrigatorios["senhaAtual"] = array("tipo" => "input", "nome" => "Senha atual");
             }
             // valida
             $mensagem = validaPost($obrigatorios, $dados);
             if (!empty($mensagem)) {
                 throw new Exception($mensagem);
             }
             // recebe e codifica a senha atual
             $dados["senhaAtual"] = !empty($dados["senhaAtual"]) ? md5(trim($dados["senhaAtual"])) : $senhaAtual;
             if ($dados["senhaAtual"] != $senhaAtual) {
                 throw new Exception("Senha atual não confere");
             }
             $dados["senha"] = $dados["novaSenha"] = !empty($dados["novaSenha"]) ? md5(trim($dados["novaSenha"])) : $novaSenha;
             $dados = retiraDoArray(array("novaSenha", "senhaAtual"), $dados);
             $dados = $this->dao->salva($conexao, "usuarios", $dados);
             // adiciona nos logs
             //$this->logDAO->adicionar ($conexao, "alterou", "dados", $_SESSION[PREFIX . "loginNome"], $dados["nome"], "Usuário atualizou seus dados.");
             $conexao->commit();
             $conexao->disconnect();
             setMensagem("info", "Dados atualizados");
             Application::redirect('?modulo=index&acao=alterar&id=' . $dados["id"]);
             exit;
         }
     } catch (Exception $e) {
         $conexao->rollback();
         setMensagem("error", $e->getMessage());
         if ($redirecionar != NULL) {
             Application::redirect($redirecionar);
             exit;
         }
     }
     $conexao->disconnect();
     $view = new View($_GET["modulo"], "extendido", "alterar.phtml");
     $view->setParams(array("title" => getTitulo($breadcrumbs), "breadcrumbs" => $breadcrumbs, "usuario" => $dadosUsuario));
     $view->showContents();
 }
Example #7
0
 public function reset($params)
 {
     $this->model->queryResolve = false;
     $user = $this->model->getWithField2('user_id', $params[0]);
     $user[0]['user_status'] = '2';
     $this->model->setData($user[0]);
     $this->model->update('user_id', $params[0]);
     Application::redirect($this->urlPath);
 }
 /**
  * Gerencia a requisições de exclusão dos consulta
  */
 public function apagarConsultaAction()
 {
     if (DataValidator::isNumeric($_GET['in_con'])) {
         //apagando o contato
         $o_consulta = new ConsultaModel();
         $o_consulta->loadById($_GET['in_con']);
         $o_consulta->delete();
         Application::redirect('?controle=Consulta&acao=listarConsulta');
     }
 }
 public function apagarTelefoneAction()
 {
     if (isset($_GET['in_tel'])) {
         if (DataValidator::isInteger($_GET['in_tel'])) {
             $o_telefone = new TelefoneModel();
             $o_telefone->loadById($_GET['in_tel']);
             $o_telefone->delete();
             Application::redirect('?controle=Telefone&acao=listarTelefones&in_con=' . $_GET['in_con']);
         }
     }
 }
        private function savePart()
        {
            $form = 'frost.views.cms.part.text.TextAdd';
            $part = Part::addMediaToPart($form,'Text');
            
            // Add the 'preview' to the part 
            $part = new Part();
            $part->clauseSafe('part_id',Application::param('part_id')); 
            $part->parse(); 
            $part->save();

            //Part::setParttagsAndSave($part,Application::param('current_tags'));
    
            Application::setParam('module_id',Application::param('module_id'));
            Application::redirect('ModuleDetail');
        }
 /**
  * Gerencia a requisições de exclusão dos contatos
  */
 public function apagarContatoAction()
 {
     if (DataValidator::isNumeric($_GET['in_con'])) {
         //apagando o contato
         $o_contato = new ContatoModel();
         $o_contato->loadById($_GET['in_con']);
         $o_contato->delete();
         //Apagando os telefones do contato
         $o_telefone = new TelefoneModel();
         $v_telefone = $o_telefone->_list($_GET['in_con']);
         foreach ($v_telefone as $o_telefone) {
             $o_telefone->delete();
         }
         Application::redirect('?controle=Contato&acao=listarContato');
     }
 }
 public static function callback($data, $form, $that)
 {
     $users = Model::load('system.users')->setQueryResolve(false);
     $user = reset($users->getWithField('user_id', $_SESSION['user_id']));
     if ($user['password'] == md5($data['current_password'])) {
         if ($data['new_password'] == $data['repeat_new_password']) {
             $user['password'] = md5($data['new_password']);
             $users->setData($user);
             $users->update('user_id', $user['user_id']);
             Application::redirect($that->path, 'Password succesfully changed.');
         } else {
             $form->addError('Please enter both passwords correctly');
         }
     } else {
         $form->addError('Please enter your current password correctly');
     }
 }
Example #13
0
 protected function postNewNote()
 {
     $noteAttachments = Model::load('system.note_attachments');
     $model = Model::load('system.notes');
     $model->datastore->beginTransaction();
     $data = array('note' => $_POST['note'], 'note_time' => time(), 'item_id' => $this->id, 'user_id' => $_SESSION['user_id'], 'item_type' => $this->model->package);
     $model->setData($data);
     $id = $model->save();
     for ($i = 1; $i < 5; $i++) {
         $file = $_FILES["attachment_{$i}"];
         if ($file['error'] == 0) {
             $noteAttachments->setData(array('note_id' => $id, 'description' => $file['name'], 'object_id' => PgFileStore::addFile($file['tmp_name'])));
             $noteAttachments->save();
         }
     }
     $model->datastore->endTransaction();
     Application::redirect("{$this->urlPath}/notes/{$params[0]}");
 }
Example #14
0
 public function add()
 {
     if (isset($_POST['Post'])) {
         $data = $_POST['Post'];
         $post = new Post();
         $post->title = $data['title'];
         $post->content = strip_tags($data['content']);
         if (isset($_FILES['Post'])) {
             $post->uploadImage($_FILES['Post']);
         }
         $post->status = $data['status'];
         $post_id = $post->save();
         if (isset($data['tags'])) {
             $post->addTags($post_id, $data['tags']);
         }
         Application::redirect(array('post' => 'index'));
     }
     $this->render('post/add', array('post' => new Post()));
 }
 public function removerAction()
 {
     try {
         $conexao = $this->conexao->getConexao();
         $redirecionar = "?modulo=pacientes";
         $objeto = $this->dao->findByPk($conexao, "pacientes", (int) $_GET["id"]);
         $redirecionar .= "&acao=cadastrar&id=" . $objeto["id"];
         $diretorio = DIR_UPLOADS . SEPARADOR_DIRETORIO . "pacientes" . SEPARADOR_DIRETORIO . $objeto["id"];
         $diretorio .= SEPARADOR_DIRETORIO . $objeto["foto"];
         if (!existeArquivo($diretorio)) {
             throw new Exception("Imagem não encontrada");
         }
         if (excluiArquivo($diretorio)) {
             $objeto["foto"] = NULL;
             $this->dao->salva($conexao, "pacientes", $objeto);
             $conexao->commit();
             setMensagem("info", "Foto excluída");
         }
         Application::redirect($redirecionar);
         exit;
     } catch (Exception $e) {
         $conexao->rollback();
         setMensagem("error", $e->getMessage());
         if ($redirecionar != NULL) {
             Application::redirect($redirecionar);
             exit;
         }
     }
 }
Example #16
0
 /**
  * @inheritDoc
  */
 public function redirect($url, $flushMessage = null)
 {
     \Application::redirect($url, $flushMessage);
 }
Example #17
0
 private static function redirectToChangePassword($data)
 {
     $_SESSION["logged_in"] = true;
     $_SESSION["user_id"] = $data[0]["user_id"];
     $_SESSION["user_name"] = $data[0]["user_name"];
     $_SESSION["role_id"] = $data[0]["role_id"];
     $_SESSION["department_id"] = $data[0]['department_id'];
     $_SESSION["user_firstname"] = $data[0]["first_name"];
     $_SESSION["user_lastname"] = $data[0]["last_name"];
     $_SESSION['branch_id'] = $data[0]['branch_id'];
     $_SESSION["user_mode"] = "2";
     $_SESSION["user_status"] = $data[0]['user_status'];
     //this is added to pass the user status as wyf hard codes the "2" to redirect
     Sessions::bindUser($data[0]['user_id']);
     User::log("Logged in for first time");
     Application::redirect(self::getHomeRedirect());
 }
 public function redirectOnAccessDenied()
 {
     Application::setParam('author_id', Logbook::current()->authorId());
     Application::setParam('entry_id', Application::param('entry_id'));
     Application::redirect(Application::defaultHandler());
 }
Example #19
0
 public static function validate($request)
 {
     $config = \Configure::instance();
     $data = $config->authentication;
     if (empty($data)) {
         return null;
     }
     foreach ($data as $url => $values) {
         $redirect = isset($values['on_fail']) ? $values['on_fail'] : "/";
         if (preg_match('@' . $url . '/?@i', $request)) {
             // Match the requested url.
             if (!isset($values['allow'])) {
                 throw new Exception('Invalid user type or user type not set for protected url ' . $request);
             }
             $valid_user = $values['allow'];
             if (is_array($valid_user)) {
                 // Access list is an array of user types.
                 $pass = false;
                 foreach ($valid_user as $user) {
                     if (self::get() == $user) {
                         $pass = true;
                     }
                 }
                 // Check list of users for match
                 if ($pass == false) {
                     if (!preg_match('@' . $request . '/?@i', $redirect)) {
                         \Controller\Flash::instance()->error('You must be logged in to access this page.');
                         Application::redirect($redirect);
                         break;
                     }
                 }
             } else {
                 // Access list is a single user type.
                 $valid_user = strtolower($valid_user);
                 if (self::get() != $valid_user) {
                     // If user isn't allowed, redirect.
                     if (!preg_match('@' . $request . '/?@i', $redirect)) {
                         \Controller\Flash::instance()->error('You must be logged in to access this page.');
                         header('HTTP/1.0 401 Unauthorized');
                         header("Location:" . $redirect);
                         exit;
                     }
                 }
             }
         }
     }
 }
Example #20
0
 public static function constraint_callback($data, $form)
 {
     if ($data['hour_start'] == '' || $data['hour_end'] == '') {
         $errors[] = "The Hour fields cannot be empty";
     }
     if ($data['minutes_start'] == '' || $data['minutes_end'] == '') {
         $errors[] = "The Minutes fields cannot be empty";
     }
     if ($data['mode'] == '') {
         $errors[] = "The Mode field cannot be empty";
     }
     foreach ($errors as $error) {
         $form->addError($error);
     }
     //if there are errors, return to form with the errors
     if (!empty($errors)) {
         return true;
     }
     $constraintModel = Model::load('auth.constraints');
     $constraints = $constraintModel->getWithField('role_id', $data['role_id']);
     //merge all inputs into variables
     //counter to exit the loop after the days of the week are done
     $count = 1;
     $days_of_week_value = 0;
     foreach ($data as $d) {
         if ((int) $d != 0) {
             $days_of_week_value = $days_of_week_value | (int) $d;
         }
         ++$count;
         if ($count == 8) {
             break;
         }
     }
     //concatenate times
     $time_range_start = $data['hour_start'] . ":" . $data['minutes_start'];
     $time_range_end = $data['hour_end'] . ":" . $data['minutes_end'];
     //If the constraint does not exist for the role, add a new constraint
     if (count($constraints) == 0) {
         $constraintModel->setData(array('days_of_week_value' => $days_of_week_value, 'time_range_start' => $time_range_start, 'time_range_end' => $time_range_end, 'mode' => $data['mode'], 'role_id' => $data['role_id'], 'time' => time()));
         $constraintModel->save();
         if (empty($errors)) {
             Application::redirect("/auth/roles?notification=Contraint added successfully");
         }
     } else {
         $constraints[0]['days_of_week_value'] = $days_of_week_value;
         $constraints[0]['time_range_start'] = $time_range_start;
         $constraints[0]['time_range_end'] = $time_range_end;
         $constraints[0]['mode'] = $data['mode'];
         $constraints[0]['role_id'] = $data['role_id'];
         $constraints[0]['time'] = time();
         $constraintModel->setData($constraints[0]);
         $constraintModel->update("role_id", $data['role_id']);
         if (empty($errors)) {
             Application::redirect("/auth/roles?notification=Contraint updated successfully");
         }
     }
     return true;
 }
 /**
  * @param \Application $app
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function index(\Application $app)
 {
     return $app->redirect($app->path('hello', array('name' => 'World')));
 }
Example #22
0
 public function notes($params)
 {
     $noteAttachments = Model::load('system.note_attachments');
     if ($params[1] == 'delete') {
         $model = Model::load('system.notes');
         $model->delete('note_id', $params[2]);
         Application::redirect("{$this->path}/notes/{$params[0]}");
     }
     if (isset($_POST['is_form_sent'])) {
         $model = Model::load('system.notes');
         $model->datastore->beginTransaction();
         $data = array('note' => $_POST['note'], 'note_time' => time(), 'item_id' => $params[0], 'user_id' => $_SESSION['user_id'], 'item_type' => $this->model->package);
         $model->setData($data);
         $id = $model->save();
         for ($i = 1; $i < 5; $i++) {
             $file = $_FILES["attachment_{$i}"];
             if ($file['error'] == 0) {
                 $noteAttachments->setData(array('note_id' => $id, 'description' => $file['name'], 'object_id' => PgFileStore::addFile($file['tmp_name'])));
                 $noteAttachments->save();
             }
         }
         $model->datastore->endTransaction();
         Application::redirect("{$this->urlPath}/notes/{$params[0]}");
     }
     $notes = SQLDBDataStore::getMulti(array('fields' => array('system.notes.note_id', 'system.notes.note', 'system.notes.note_time', 'system.users.first_name', 'system.users.last_name'), 'conditions' => Model::condition(array('item_type' => $this->model->package, 'item_id' => $params[0]))));
     foreach ($notes as $i => $note) {
         $attachments = $noteAttachments->getWithField2('note_id', $note['note_id']);
         foreach ($attachments as $j => $attachment) {
             $attachments[$j]['path'] = PgFileStore::getFilePath($attachment['object_id'], $attachment['description']);
         }
         $notes[$i]['attachments'] = $attachments;
     }
     $this->label = "Notes on item";
     $form = Element::create('Form')->add(Element::create('TextArea', 'Note', 'note'), Element::create('FieldSet', 'Add Attachments')->add(Element::create('UploadField', 'Attachment', 'attachment_1'), Element::create('UploadField', 'Attachment', 'attachment_2'), Element::create('UploadField', 'Attachment', 'attachment_3'), Element::create('UploadField', 'Attachment', 'attachment_4'))->setId('attachments')->setCollapsible(true))->setRenderer('default');
     return $this->arbitraryTemplate(Application::getWyfHome('controllers/notes.tpl'), array('form' => $form->render(), 'notes' => $notes, 'route' => $this->path, 'id' => $params[0]));
 }
Example #23
0
 /**
  * A callback function which checks the validity of passwords on the form.
  * It checks to ensure that the right user is logging in with the right
  * password.
  * 
  * @param $data
  * @param $form
  * @param $callback_pass
  * @return unknown_type
  */
 public static function callback($data, $form, $callback_pass = null)
 {
     $user = Model::load(".users");
     $userData = $user->get(array("conditions" => "user_name='{$data["username"]}'"), Model::MODE_ASSOC, false, false);
     if (count($userData) == 0) {
         $form->addError("Please check your username or password");
         return true;
     } else {
         if ($userData[0]["role_id"] == null) {
             $form->addError("Sorry! your account has no role attached!");
             return true;
         } else {
             if (User::getPermission("can_log_in_to_web", $userData[0]["role_id"])) {
                 $home = Application::getLink("/");
                 /* Verify the password of the user or check if the user is logging in
                  * for the first time.
                  */
                 if ($userData[0]["password"] == md5($data["password"]) || $userData[0]["user_status"] == 2) {
                     switch ($userData[0]["user_status"]) {
                         case "0":
                             $form->addError("Your account is currently inactive" . "please contact the system administrator.");
                             return true;
                             break;
                         case "1":
                             $_SESSION["logged_in"] = true;
                             $_SESSION["user_id"] = $userData[0]["user_id"];
                             $_SESSION["user_name"] = $userData[0]["user_name"];
                             $_SESSION["user_firstname"] = $userData[0]["first_name"];
                             $_SESSION["user_lastname"] = $userData[0]["last_name"];
                             $_SESSION["read_only"] = $userData[0]['read_only'];
                             $_SESSION["role_id"] = $userData[0]["role_id"];
                             $_SESSION['branch_id'] = $userData[0]['branch_id'];
                             $_SESSION["department_id"] = $userData[0]['department_id'];
                             Sessions::bindUser($userData[0]['user_id']);
                             User::log("Logged in");
                             Application::redirect($home);
                             break;
                         case "2":
                             $_SESSION["logged_in"] = true;
                             $_SESSION["user_id"] = $userData[0]["user_id"];
                             $_SESSION["user_name"] = $userData[0]["user_name"];
                             $_SESSION["role_id"] = $userData[0]["role_id"];
                             $_SESSION["department_id"] = $userData[0]['department_id'];
                             $_SESSION["user_firstname"] = $userData[0]["first_name"];
                             $_SESSION["user_lastname"] = $userData[0]["last_name"];
                             $_SESSION['branch_id'] = $userData[0]['branch_id'];
                             $_SESSION["user_mode"] = "2";
                             Sessions::bindUser($userData[0]['user_id']);
                             User::log("Logged in for first time");
                             Application::redirect($home);
                             break;
                     }
                 } else {
                     $form->addError("Please check your username or password");
                     return true;
                 }
             } else {
                 $form->addError("You are not allowed to log in from this terminal");
                 return true;
             }
         }
     }
 }
Example #24
0
 public function bulkdelete()
 {
     $this->model->delete("{$this->model->getKeyField('primary')} in (" . implode(",", json_decode($_GET['ids'])) . ")");
     Application::redirect($this->urlPath);
 }
Example #25
0
 /**
  * Delete a particular item from the model.
  * @param $params
  * @return unknown_type
  */
 public function delete($params)
 {
     if (User::getPermission($this->permissionPrefix . "_can_delete")) {
         $data = $this->model->getWithField($this->model->getKeyField(), $params[0]);
         $this->model->delete($this->model->getKeyField(), $params[0]);
         User::log("Deleted " . $this->model->name, $data[0]);
         Application::redirect("{$this->urlPath}?notification=Successfully+deleted+" . strtolower($this->label));
     }
 }
 public function redirectWithoutPost($handler)
 {
     Application::redirect($handler, false);
 }
Example #27
0
 public function opcoesAction()
 {
     if (count($_POST) > 0) {
         if (isset($_POST["acoes"])) {
             $processados = 0;
             $naoProcessados = 0;
             $ids = isset($_POST["objetos"]) ? $_POST["objetos"] : array();
             // retira o elemento -1, caso exista
             if (count($ids) > 0 && $ids[0] == -1) {
                 array_shift($ids);
             }
             try {
                 $conexao = $this->conexao->getConexao();
                 //if (!temPermissao(array('pacientes:manterCursos'), $_SESSION[PREFIX . "permissoes"]))
                 //	throw new Exception("Você não tem permissão para realizar esta ação.");
                 foreach ($ids as $id) {
                     $dados = $this->dao->findByPk($conexao, "usuarios", $id);
                     switch ($_POST["acoes"]) {
                         case "excluir":
                             $opcao = "excluído(s)";
                             try {
                                 if (in_array((int) $dados["id"], array(1))) {
                                     $naoProcessados += 1;
                                 } else {
                                     if (true) {
                                     } else {
                                         $affectedRows = $this->dao->exclui($conexao, "usuarios", array("where" => array("id" => (int) $id)));
                                         if ($affectedRows > 0) {
                                             $processados += 1;
                                         }
                                     }
                                 }
                             } catch (Exception $e) {
                                 $naoProcessados += 1;
                             }
                             break;
                     }
                 }
                 if ($processados > 0) {
                     $conexao->commit();
                     setMensagem("info", $processados . " usuário(s) " . $opcao);
                 }
                 if ($naoProcessados > 0) {
                     setMensagem("error", $naoProcessados . " usuário(s) não podem ser " . $opcao);
                 }
                 $conexao->disconnect();
             } catch (Exception $e) {
                 setMensagem("error", $e->getMessage());
                 $conexao->rollback();
             }
         }
     }
     Application::redirect(WWW_ROOT . "/?modulo=usuarios");
     exit;
 }
Example #28
0
 public static function roles_callback($data, $form)
 {
     $usersRolesModel = Model::load("auth.users_roles");
     $usersRolesModel->datastore->beginTransaction();
     $userId = array_pop($data);
     $loggedInUsersRoles = $usersRolesModel->getWithField("user_id", $_SESSION['user_id']);
     //this is for hackers who try to use scripts of a kind to bypass the UI..this throws an exception to prevent
     //the user from giving himself super user access
     //the exception is thrown and basically the use's roles are deleted from the table -> bug or not
     //If a user tries to set the role to 1 and the user is not super user throw exception
     foreach ($data as $role) {
         if ($role == 1) {
             foreach ($loggedInUsersRoles as $userRole) {
                 if ($userRole['role_id'] == 1) {
                     $throwException = false;
                     break;
                 } else {
                     $throwException = true;
                 }
             }
             if ($throwException) {
                 throw new Exception('Unauthorised Action');
             }
         }
     }
     //delete all the entries related to that user
     $usersRolesModel->delete('user_id', $userId);
     //defaults to true and changes to false if the logged in user is really superuser
     $throwException = true;
     foreach ($data as $role) {
         if ($role != 0) {
             $usersRolesModel->setData(array('user_id' => $userId, 'role_id' => $role));
             $usersRolesModel->save();
         }
     }
     $menuFile = __DIR__ . "/cache/menus/side_menu_u{$userId}.html";
     $objectFile = __DIR__ . "/cache/menus/menu_u{$userId}.object";
     //delete menu & object file for user
     if (file_exists($menuFile)) {
         unlink($menuFile);
     }
     if (file_exists($objectFile)) {
         unlink($objectFile);
     }
     //generate menu for user
     AuthMenu::generate($userId);
     $usersRolesModel->datastore->endTransaction();
     Application::redirect("/auth/users?notification=Role(s) saved successfully");
     return true;
 }
Example #29
0
 public function opcoesAction()
 {
     if (count($_POST) > 0) {
         if (isset($_POST["opcoes"])) {
             $processados = 0;
             $naoProcessados = 0;
             $ids = isset($_POST["agenda"]) ? $_POST["agenda"] : array();
             // retira o elemento -1, caso exista
             if (count($ids) > 0 && $ids[0] == -1) {
                 array_shift($ids);
             }
             try {
                 $conexao = $this->conexao->getConexao();
                 //if (!temPermissao(array('agenda:manterCursos'), $_SESSION[PREFIX . "permissoes"]))
                 //	throw new Exception("Você não tem permissão para realizar esta ação.");
                 foreach ($ids as $id) {
                     $dados = $this->dao->getById($conexao, "agenda", $id);
                     switch ($_POST["opcoes"]) {
                         case "excluir":
                             $opcao = "excluído(s)";
                             try {
                                 $affectedRows = $this->dao->excluir($conexao, "agenda", $id);
                                 if ($affectedRows > 0) {
                                     $processados += 1;
                                     $diretorio = DIR_UPLOADS . SEPARADOR_DIRETORIO . "agenda" . SEPARADOR_DIRETORIO . $id;
                                     excluiDiretorio($diretorio);
                                     //$this->logDAO->adicionar ($conexao, "excluiu", "paciente", $_SESSION[PREFIX . "loginNome"], $dados["nome"], "Usuário excluiu o paciente.");
                                 }
                             } catch (Exception $e) {
                                 $naoProcessados += 1;
                             }
                             break;
                         case "ativar":
                             $opcao = "ativado(s)";
                             $dados["status"] = 1;
                             $affectedRows = $this->dao->atualizar($conexao, "agenda", $dados);
                             if ($affectedRows > 0) {
                                 $processados += 1;
                                 //$this->logDAO->adicionar ($conexao, "ativou", "paciente", $_SESSION[PREFIX . "loginNome"], $dados["nome"], "Usuário ativou paciente.");
                             }
                             break;
                         case "desativar":
                             $opcao = "desativado(s)";
                             $dados["status"] = 0;
                             $affectedRows = $this->dao->atualizar($conexao, "agenda", $dados);
                             if ($affectedRows > 0) {
                                 $processados += 1;
                                 //$this->logDAO->adicionar ($conexao, "desativou", "paciente", $_SESSION[PREFIX . "loginNome"], $dados["nome"], "Usuário desativou paciente.");
                             }
                             break;
                     }
                 }
                 if ($processados > 0) {
                     $conexao->commit();
                     setMensagem("info", $processados . " paciente(s) " . $opcao);
                 }
                 if ($naoProcessados > 0) {
                     setMensagem("error", $naoProcessados . " paciente(s) não podem ser " . $opcao);
                 }
                 $conexao->disconnect();
             } catch (Exception $e) {
                 setMensagem("error", $e->getMessage());
                 $conexao->rollback();
             }
         }
     }
     Application::redirect(WWW_ROOT . "/?" . urldecode($_POST['q']));
     exit;
 }
 /**
  * Return a Twitch authentication URL.
  *
  * @param  string  $client
  * @param  string  $redirect
  * @param  string  $scopes
  * @return string
  */
 public static function url($client = null, $redirect = null, $scopes = null)
 {
     return sprintf("%s/oauth2/authorize?%s", Application::api(), http_build_query(['response_type' => 'code', 'client_id' => $client ?: Application::client(), 'redirect_uri' => $redirect ?: Application::redirect(), 'scope' => $scopes ?: Application::scopes()]));
 }