Exemplo n.º 1
0
 public function testOnFactoryResponseTypes()
 {
     $htmlInstace = Factory::response(ResponseType::HTML);
     $this->assertInstanceOf("MyFrameWork\\Response\\HtmlResponse", $htmlInstace);
     $emtyInstace = Factory::response(ResponseType::EMPT);
     $this->assertInstanceOf("MyFrameWork\\Response\\EmptyResponse", $emtyInstace);
 }
Exemplo n.º 2
0
 /**
  * Cria um novo resultado de busca
  * @param string $termo Termo que foi pesquisado
  * @param int $total Quantos resultados foram encontrados ao realizar a busca
  * @param string $query Consulta realizada no banco de dados
  * @param string $sessionid Hash da sessão do usuário (somente utilizado quando o usuario não estiver logado)
  * @param int $usuario Codigo do usuario logado no sistema (se o mesmo estiver logado)
  * @return int
  */
 public function novo($termo, $total, $query, $sessionid, $usuario = null)
 {
     if (empty($sessionid)) {
         Factory::log()->info('Sessionid e usuário são vazios');
         return 0;
     }
     return $this->insert(array('termo' => $termo, 'totalresultado' => $total, 'query' => $query, 'sessionid' => $sessionid, 'usuario' => $usuario));
 }
 protected function _isValid($value, $params)
 {
     $dao = Factory::DAO(getValueFromArray($params, Flag::DAO_NAME, ''));
     if (!is_null($dao)) {
         return true;
     }
     return false;
 }
Exemplo n.º 4
0
 /**
  * Cria um novo log de acesso
  */
 public function novo($sessionid, $ip, $reverso, $navigator)
 {
     if (empty($sessionid)) {
         Factory::log()->info('Sessionid e usuário são vazios');
         return 0;
     }
     return $this->insert(array('sessionid' => $sessionid, 'ip' => $ip, 'ipreverso' => $reverso, 'navigatorso' => $navigator));
 }
Exemplo n.º 5
0
 protected function _isValid($value, $params)
 {
     $result = isValidEmail($value, getValueFromArray($params, Flag::VALIDATE_DOMAIN, false));
     if (!$result) {
         Factory::log()->warn("O e-mail {$value} não é um e-mail válido");
         return false;
     }
     return true;
 }
Exemplo n.º 6
0
 /**
  * 
  * @param array $params
  * @return mixed DAO se a Flag::DAO_NAME for setada ou null caso contrário
  */
 public function getDAO($params)
 {
     $daoname = getValueFromArray($params, Flag::DAO_NAME, "");
     if (empty($daoname)) {
         Factory::log()->fatal('É necessário informar o nome do DAO... use Flag::DAO_NAME no parameter!');
         return null;
     }
     return Factory::DAO($daoname);
 }
Exemplo n.º 7
0
 /**
  * Retorna o enum passado em $params
  * @param array $params
  * @return BasicEnum
  */
 private function getEnum($params)
 {
     $enumname = getValueFromArray($params, Flag::ENUM_NAME, '');
     if (empty($enumname)) {
         Factory::log()->fatal('É necessário informar o nome do tipo enum');
         require_once PATH_MYFRAME . '/enum/EmptyEnum.php';
         return new EmptyEnum();
     }
     return Factory::enum($enumname);
 }
Exemplo n.º 8
0
 public static function clear($type = null)
 {
     if (is_null($type)) {
         self::$lastError = null;
         self::$errors = array();
     } else {
         if (isset(self::$errors[$type])) {
             unset(self::$errors[$type]);
         } else {
             Factory::log()->info('O tipo "' . $type . '" não foi definido');
         }
     }
 }
Exemplo n.º 9
0
 /**
  *  As configurações são retornadas como um array associativo
  *  
  * @return array Retorna um array vazio em casos de falha
  */
 public function load()
 {
     $this->filename = str_replace("\\", "/", $this->filename);
     if (!file_exists($this->filename)) {
         Logger::log()->fatal("[" . date("H:i:s") . "] Arquivo de configuração de email não foi encontrado no path {$this->filename}");
         return array();
     }
     $has_parsed = parse_ini_file($this->filename, true);
     if (!$has_parsed) {
         return array();
     }
     return $has_parsed;
 }
Exemplo n.º 10
0
function createDefaultUser()
{
    echo '<li>CreateDefaultUser</li>';
    $dao = Factory::DAO('usuario');
    /* @var $dao UsuarioDAO */
    $email = '*****@*****.**';
    $user = $dao->getByEmail($email);
    if (empty($user)) {
        assert($dao->novo('Administrator', $email, hashit('admin')));
        $dao = Factory::DAO('usuarioGrupo');
        /* @var $dao UsuarioGrupoDAO */
        assert($dao->novo($email, 'admin'));
    }
}
Exemplo n.º 11
0
 protected function createDatabaseItems($folder)
 {
     $db = Factory::database();
     foreach (glob($folder . '*.sql') as $sqlfile) {
         echo "<li>{$sqlfile}</li>";
         $items = explode(';', file_get_contents($sqlfile));
         foreach ($items as $object) {
             //echo $object . '<br>';
             if (!$db->execute($object)) {
                 //echo "<pre>" . $object . "</pre><hr>";
             }
         }
     }
 }
Exemplo n.º 12
0
 /**
  * Retorna o ultimo id inserido
  * @param string $nameOrTable Nome da tabela
  * @param string $column Nome da coluna
  * @return int
  */
 public function lastInsertId($nameOrTable = null, $column = null)
 {
     try {
         if (empty($column)) {
             return parent::lastInsertId($nameOrTable);
         } else {
             return parent::lastInsertId($nameOrTable . '_' . $column . '_seq');
         }
     } catch (PDOException $e) {
         Factory::log()->info($e->getMessage());
         Factory::log()->fatal("[" . date('H:m:i') . "]Falha ao executar uma query\nerror: {$e->getMessage()}", $e);
         return -1;
     }
 }
Exemplo n.º 13
0
 public function showPage()
 {
     $dao = Factory::DAO('StaticPage');
     $page = $dao->getByNome($this->method);
     if (empty($page)) {
         redirect('/');
     }
     $this->pageTitle = $page['titulo'];
     $this->pagedata['nome'] = $page['nome'];
     $this->pagedata['titulo'] = $page['titulo'];
     $this->pagedata['conteudo'] = Factory::datatype('html')->toHumanFormat($page['conteudo']);
     if (empty($this->pageTitle)) {
         $this->pageTitle = $this->pagedata['titulo'];
     }
 }
Exemplo n.º 14
0
 /**
  * Define um ou mais grupos para o usuário
  * 
  * @param string|int $usuario  Email ou id do usuário
  * @param mixed      $grupos   Vetor de ids ou emails ou apenas um id ou email
  * @return int                 Número de grupos inseridos
  */
 public function novo($usuario, $grupos)
 {
     $usuario = $this->getUsuarioId($usuario);
     if ($usuario < 0) {
         Factory::log()->warn('Usuário inválido');
         return 0;
     }
     if (!is_array($grupos)) {
         $grupos = array($grupos);
     }
     $total = 0;
     foreach ($grupos as $grupo) {
         $grupo = $this->getGrupoId($grupo);
         if ($grupo < 0) {
             continue;
         }
         $total += $this->insert(array('usuario' => $usuario, 'grupo' => $grupo));
     }
     return $total;
 }
Exemplo n.º 15
0
    protected function setUp()
    {
        LoggerApp::clear();
        $this->db = Factory::database();
        $this->assertFalse(LoggerApp::hasError(), LoggerApp::getLastError());
        $this->assertNotNull($this->db, 'Invalid connection');
        $sql = <<<'SQL'
   CREATE TABLE IF NOT EXISTS test (
     id    serial PRIMARY KEY,
     name  varchar(40) NOT NULL CHECK (name <> '')
   )
SQL;
        try {
            $this->db->exec($sql);
            $this->db->exec('DELETE FROM test');
            $this->assertTrue($this->db->exec("INSERT INTO test (name) VALUES ('value 1')") > 0);
            $this->assertTrue($this->db->exec("INSERT INTO test (name) VALUES ('value 2')") > 0);
            $this->assertTrue($this->db->exec("INSERT INTO test (name) VALUES ('value 3')") > 0);
        } catch (Exception $e) {
            $this->fail($e->getMessage());
        }
    }
Exemplo n.º 16
0
 public function send(AbstractEmail $email)
 {
     try {
         //Set who the message is to be sent from
         $this->mailer->setFrom($email->getFromEmail(), $email->getFromName());
         //Set an alternative reply-to address
         //$mail->addReplyTo($email->getFromEmail(), $email->getFromName());
         $this->mailer->setTo($email->getTo());
         $this->mailer->setCc($email->getCc());
         $this->mailer->setBCc($email->getBCc());
         $this->mailer->setSubject($email->getAssunto());
         if ($email instanceof \MyFrameWork\Email\HtmlInterface) {
             $mustache = Template::singleton();
             $html_body = $mustache->renderHTML(file_get_contents($email->getTemplatePath()), $email->getTemplateParams());
             $this->mailer->setMessage($html_body);
         } else {
             $this->mailer->disableHtml();
             $this->mailer->setMessage($email->getMessage());
         }
         //Replace the plain text body with one created manually
         //$mail->AltBody = 'This is a plain-text message body';
         $this->mailer->addAttachments($email->getAnexos());
         //send the message, check for errors
         if (!$this->mailer->send()) {
             Logger::log()->fatal("Mailer Send Error: " . $this->mailer->getErrorInfo());
             return false;
         }
         return true;
     } catch (phpmailerException $e) {
         Logger::log()->fatal("phpmailer Exception : " . $e->errorMessage());
         //Pretty error messages from PHPMailer
     } catch (\Exception $e) {
         Logger::log()->fatal("phpMailer Exception : " . $e->getMessage());
         //Boring error messages from anything else!
     }
     return false;
 }
Exemplo n.º 17
0
 /**
  * Retorna um queryresult no formato de erro
  * @param string $msg Mensagem de erro
  * @return array queryresult
  */
 protected function returnQueryResultError($msg)
 {
     Factory::log()->error($msg);
     return $this->getQueryResult('', array(), false, $msg);
 }
Exemplo n.º 18
0
 /**
  * Limpa um valor da sessão
  * @param string $key
  */
 public function removeData($key)
 {
     if (in_array($key, $this->blocked)) {
         Factory::log()->debug('A chave "' . $key . '" é um valor protegido e não pode ser removido');
     } else {
         if (isset($_SESSION[$key])) {
             unset($_SESSION[$key]);
         }
     }
 }
Exemplo n.º 19
0
 /**
  * Carrega um DAO único
  * 
  * @param string $dao Nome do DAO
  */
 protected function loadDAO($dao)
 {
     $dao = ucfirst(str_replace('DAO', '', $dao));
     if (!isset($this->daos[$dao])) {
         $this->daos[$dao] = Factory::DAO($dao, $this->getDatabase());
     }
     return $this->daos[$dao];
 }
Exemplo n.º 20
0
 protected function getDataType($params, $fieldname, $formvalues)
 {
     $datatype = Factory::datatype($params['type'])->getHTMLEditable($fieldname, getValueFromArray($formvalues, $fieldname, ''), $params['params']);
     if (null === $datatype or empty($datatype)) {
         //tentar criar um datatype da aplicação
         //$datatype = \Application\Model\DataType\DataTypeFactory::create($params["type"]);
     }
     return $datatype;
 }
Exemplo n.º 21
0
 public function testParams()
 {
     $this->assertEquals('test', $this->dao->getTableName());
     $this->assertEquals('id', $this->dao->getPKFieldName());
     $this->dao->changeToTable2();
     $this->assertEquals('test2', $this->dao->getTableName());
     $this->assertEquals(array('id1', 'id2'), $this->dao->getPKFieldName());
     $this->assertEquals(Factory::database(), $this->dao->getDatabase());
     //Invalid database object - Dont do this
     $dao = new MyDAO(Factory::log());
     $this->assertEquals(Factory::log(), $dao->getDatabase());
 }
Exemplo n.º 22
0
 /**
  * Realiza um delete no banco de dados
  * Se não houver uma condição WHERE por segurança não será executado o comando
  * 
  * @param string $table O nome da tabela
  * @param mixed  $where Array associativo no formato wherearray ou um objeto Where
  * 
  *   example
  *   $db->delete("tabela1", ['id' => 33])
  * 
  * @return mixed        Retorna 0 em caso de falha e boolean em caso de sucesso    
  */
 public function delete($table, $where)
 {
     try {
         $ret = $this->getQuery()->delete($table, $where);
         if ($ret['status']) {
             return $this->execute($ret['sql'], $ret['values']);
         }
         return 0;
     } catch (PDOException $e) {
         Factory::log()->info("[info]error ao deletar na camada DataBase: " . $e->getMessage());
         return 0;
     }
 }
Exemplo n.º 23
0
 /**
  * 
  * @return \Application\Model\Dao\UsuariogrupoDAO
  */
 public function getUsuariogrupoDAO()
 {
     return Factory::DAO('usuarioGrupo', $this->getDatabase());
 }
Exemplo n.º 24
0
 * 
 *      /[page]/[id]/[action]
 *      /[page]/[id]/[action]?responseType=[format]
 * 
 *      /[page]/[id]/[action]/[format]
 * 
 *      
 */
require_once "vendor/autoload.php";
/**
* Display all errors when APPLICATION_ENV is development.
*/
if ($_SERVER['APPLICATION_ENV'] == 'development') {
    error_reporting(E_ALL);
    ini_set("display_errors", 1);
}
require_once 'bootstrap.php';
$pageclass = filter_input(INPUT_GET, '_page', FILTER_SANITIZE_STRING);
if (empty($pageclass)) {
    $pageclass = 'main';
}
$action = filter_input(INPUT_GET, '_action', FILTER_SANITIZE_STRING);
if (empty($action)) {
    $action = '';
}
$type = filter_input(INPUT_GET, 'responseType', FILTER_CALLBACK, array("options" => "ResponseType::getDefaultType"));
$page = Factory::page($pageclass);
if (filter_has_var(INPUT_GET, '_id')) {
    $page->setId(filter_input(INPUT_GET, '_id', FILTER_SANITIZE_STRING));
}
$page->service(ProcessRequest::getMethod(), $action, $type);
Exemplo n.º 25
0
/**
 * 
 * @param string $application_config   O caminho para o arquivo de configuração
 * @return mixed                       Retorna array em sucesso ou null em caso de falhas. Em casos de falhas é logado os detalhes em temp/log
 */
function getConfig($application_config)
{
    $dist = $application_config . ".dist";
    $isDev = strpos($application_config, "local");
    if ($isDev === false) {
        $isDev = false;
    }
    if (!file_exists($application_config)) {
        if (file_exists($dist)) {
            $data = file_get_contents($dist);
            //se o arquivo não existe então o mesmo é criado
            $putted = file_put_contents($application_config, $data);
            if (false === $putted) {
                Factory::log()->fatal(" não foi possível criar arquivo de configuração : " . $application_config);
                return null;
            }
            //removendo o arquivo de distribuição caso seja ambiente de produção
            if (!$isDev) {
                $wasDeleted = unlink($dist);
                if (!$wasDeleted) {
                    unlink(realpath($dist));
                }
            }
            $parsedConfigs = parse_ini_file($application_config, true);
            if (!$parsedConfigs) {
                Factory::log()->fatal(" não foi possivel fazer o parse do arquivo de configuração :  " . $application_config);
                return null;
            }
            return $parsedConfigs;
        }
        Factory::log()->fatal(" não existe nenhum arquivo de configuração :  " . $application_config);
        return null;
    }
    $parsedConfigs = parse_ini_file($application_config, true);
    if (!$parsedConfigs) {
        Factory::log()->fatal(" não foi  possivel fazer o parse do arquivo de configuração :  " . $application_config);
        return null;
    }
    return $parsedConfigs;
}
Exemplo n.º 26
0
 public function testDatatype()
 {
     $int = Factory::datatype('int');
     $this->assertNotNull($int);
     $this->assertSame($int, Factory::datatype('int'));
     $this->assertSame($int, Factory::datatype('Int'));
     $this->assertSame($int, Factory::datatype('DatatypeInt'));
     //TODO listar os tipos dinamicamente
     $datatypes = array('bool', 'boolean', 'email', 'HTML', 'int', 'integer', 'numeric', 'string', 'stringBase', 'text');
     foreach ($datatypes as $type) {
         $type = str_replace('.php', '', $type);
         if ($type == 'Datatype') {
             continue;
         }
         $this->assertNotNull(Factory::datatype($type), "Falha para o tipo: " . $type);
     }
     $this->assertNull(Factory::datatype('invalid'));
     $this->assertNull(Factory::datatype('Datatype'));
 }
Exemplo n.º 27
0
 /**
  * Renderiza varias vezes o mesmo template e retorna um vetor com o conteúdo renderizado
  * NÃO imprime o resultado na tela.
  * 
  * @param  string $filename  O nome do arquivo de template
  * @param  array  $listdata  Um vetor de parâmetros que serão passados para o template
  * @return array
  */
 public function renderLoopTemplate($filename, $listdata)
 {
     try {
         $tpl = $this->loadTemplate($filename);
         $content = array();
         foreach ($listdata as $data) {
             $content[] = $tpl->render($data);
         }
         return $content;
     } catch (Exception $e) {
         Factory::log()->info($e->getMessage());
         return array();
     }
 }
Exemplo n.º 28
0
 /**
  * Verifica se o valor é negativo
  * @param float $value
  * @return boolean
  */
 protected function validNegative($value)
 {
     if (!v::numeric()->negative()->validate($value)) {
         Factory::log()->warn('Valor deve ser negativo');
         return false;
     }
     return true;
 }
Exemplo n.º 29
0
 /**
  * Adiciona uma lista de parâmetros para um determinado valor
  * Se o parâmetro existe ele será sobrescrito
  * 
  * @param string $name Nome do parâmetro
  * @param string $type Nome do tipo do parâmetro (Deve ser um Datatype)
  * @param array $params Lista de parâmetros
  * @param string $method Tipo do método (GET ou POST) se nenhum for informado o método padrão é utilizado
  * @return ProcessRequest
  */
 protected final function addParameter($name, $type, $params = array(), $method = null)
 {
     //Se o tipo é válido
     if (Factory::datatype($type) != null) {
         if (!RequestType::isValid($method)) {
             $method = self::getMethod();
         }
         $this->parametersMeta[$method][$name] = array('type' => $type, 'params' => $params);
     }
     return $this;
 }
Exemplo n.º 30
0
 /**
  * @covers LoggerApp::clear
  */
 public function testClear()
 {
     $this->assertEmpty(LoggerApp::getErrors());
     Factory::log()->error('error1');
     $this->assertNotEmpty(LoggerApp::getErrors());
     Factory::log()->warn('warn1');
     $this->assertNotEmpty(LoggerApp::getErrors());
     LoggerApp::clear('error');
     $this->assertNotEmpty(LoggerApp::getErrors());
     $this->assertNotEmpty(LoggerApp::getErrors('warn'));
     $this->assertEmpty(LoggerApp::getErrors('error'));
     Factory::log()->error('error1');
     LoggerApp::clear('xyz');
     $this->assertNotEmpty(LoggerApp::getErrors('error'));
     LoggerApp::clear();
     $this->assertEmpty(LoggerApp::getErrors('error'));
     $this->assertEmpty(LoggerApp::getErrors('warn'));
     $this->assertEmpty(LoggerApp::getErrors());
 }