class mpyDB { /** * Versão da Classe */ const version = '1.0'; /** * Administra conexão persistente (não abre nova conexao se ja tem uma semelhante aberta) * * @var boolean */ private $_persistent; /** * Especifica qual é o usuário usado na conexão * * @var string */ public $user; /** * Especifica o host de conexão do banco de dados * * @var string */ public $host; /** * Especifica a senha de acesso ao banco de dados * * @var string */ public $pass; /** * Especifica qual database é selecionado nesta conex�o * * @var string */ public $database; /** * Especifica qual porta é utilizada para a conex�o * * @var unknown_type */ public $port; /** * Caso o banco retorna algum erro, será setado essa propriedade com a mensagem retornada * * @var string */ /** * Caso o banco retorna algum erro, será setado essa propriedade com o número do erro. * * @var string */ public $errorNumber; public $errorMsg; /** * Id da Conexão com o banco de dados * * @var connection */ private $connection; private function _setErrorMsg() { switch ($this->type) { case enumDb_TypeConnection::MYSQL: $this->errorMsg = mysql_error($this->connection); $this->errorNumber = mysql_errno($this->connection); break; case enumDb_TypeConnection::ANYWHERE: $this->errorMsg = sqlanywhere_error($this->connection); case enumDb_TypeConnection::SYBASE: $this->errorMsg = sybase_get_last_message(); } } private function _connect(){ //Verifica se é persistente e gerencia conexão (no caso verifica se tem uma semelhante j� aberta) if($this->_persistent) { global $mpyDB_conns; foreach ($mpyDB_conns as $conn){ if($conn->host == $this->host && $conn->pass == $this->pass && $conn ->user == $this->user && $conn->database == $this->database) { $this->connection = $conn->connection; return; } } } switch ($this->type){ case enumDb_TypeConnection::MYSQL: /* //Verifica se extensão está habilitada no PHP if(!function_exists('mysql_connect')) throw new Exception('mpyDB: A extensão mysql de conexão com o banco de dados não está habilitada no seu servidor.'); */ $this->connection = mysql_connect($this->host, $this->user, $this->pass); if($this->connection === false){ $this->_setErrorMsg(); throw new Exception('mpyDB: Ocorreu um erro ao tentar conectar a seu banco de dados MySql.'); } $selectionDb = mysql_select_db($this->database, $this->connection); if($selectionDb === false){ $this->_setErrorMsg(); throw new Exception('mpyDB: Ocorreu um erro ao tentar selecionar um database ao seu banco de dados.'); } break; case enumDb_TypeConnection::ANYWHERE: //Verifica se extensão está habilitada no PHP if(!function_exists('sqlanywhere_connect')) throw new Exception('mpyDB: O extensão sqlanywhere de conexão com o banco de dados não está habilitada no seu servidor.'); $connstr = 'uid=' . $this->user.";pwd=" . $this->pass; $connstr .= ';ENG=' . $this->database . ';' . 'links=tcpip(host=' . $this->host; $connstr .= ';port=' . $this->port .')'; $this->connection = sqlanywhere_connect($connstr); if($this->connection === false){ $this->_setErrorMsg(); throw new Exception('mpyDB: Ocorreu um erro ao tentar conectar a seu banco de dados.'); } break; case enumDb_TypeConnection::SYBASE: if(!function_exists('sybase_connect')) throw new Exception('mpyDB: O extensão sybase de conexão com o banco de dados não está habilitada no seu servidor.'); $this->connection = sybase_connect($this->host, $this->user, $this->pass); if($this->connection === false){ $this->_setErrorMsg(); throw new Exception('mpyDB: Ocorreu um erro ao tentar conectar a seu banco de dados Sybase.'); } $selectionDb = sybase_select_db($this->database, $this->connection); if($selectionDb === false){ $this->_setErrorMsg(); throw new Exception('mpyDB: Ocorreu um erro ao tentar selecionar um database ao seu banco de dados.'); } break; default: //Se não identificar a conexão throw new Exception('mpyDB: Este tipo de conexão não foi identificado pelo objeto.'); } //Se for conexão persistente joga conexao no cache if($this->_persistent) array_push($mpyDB_conns, $this); } public function _read($sql){ //Verifica se é um sql de SELECT if((strpos(strtolower($sql), 'select') === false) && (strpos(strtolower($sql), 'call') === false)) throw new Exception('mpyDB: Você só pode fazer uma consulta ao banco dados utilizando um sql de SELECT'); switch ($this->type) { case enumDb_TypeConnection::MYSQL: return mysql_query($sql, $this->connection); case enumDb_TypeConnection::ANYWHERE: return sqlanywhere_query($this->connection, $sql); case enumDb_TypeConnection::SYBASE : return sybase_query($sql, $this->connection); } } /** * Classe que gerencia conexão com banco de dados * * @param enumDb_TypeConnection $type * @param string $host * @param string $user * @param string $pass * @param string $database * @param string $port * @param boolean $persistent * */ public function __construct(){ global $DB_TYPE, $DB_HOST, $DB_USER, $DB_PASS, $DB_PORT, $DB_DATABASE, $DB_PERSISTENT; //Seta parâmetros de conexão $this->type = $DB_TYPE; $this->host = $DB_HOST; $this->user = $DB_USER; $this->pass = $DB_PASS; $this->port = $DB_PORT; $this->database = $DB_DATABASE; $this->_persistent = $DB_PERSISTENT; //Faz conexão $this->_connect(); } function __destruct(){ //Se não for conexão persistente, ele força o fechamento da conexão if(!$this->_persistent) $this->Close(); } /** * Execute comando SQL no servidor * * @param string $sql * $return boolean */ public function Execute($sql) { $this->sql = $sql; switch ($this->type){ case enumDb_TypeConnection::MYSQL: $resource = mysql_query($sql, $this->connection); if($resource === false) { $this->_setErrorMsg(); throw new Exception('mpyDB: Não foi possível concluir a execução do comando enviado ao banco de dados:' . $sql); } return true; case enumDb_TypeConnection::ANYWHERE: $resource = sqlanywhere_query($this->connection, $sql); if($resource === false) { $this->_setErrorMsg(); throw new Exception('mpyDB: Não foi poss�vel concluir a execução do comando enviado ao banco de dados.'); } return true; case enumDb_TypeConnection::SYBASE: $resource = sybase_query($sql); if($resource === false) { $this->_setErrorMsg(); throw new Exception('mpyDB: Não foi poss�vel concluir a execução do comando enviado ao banco de dados.'); } return true; } } /** * Retorna ID inserido no INSERT * * @return integer */ public function GetLastIdInsert() { //Verifica se última ação foi um insert if(strpos(strtoupper($this->sql), 'INSERT') === false) throw new Exception('mpyDB: Você só pode solicitar o ID inserido após ter executado um comando INSERT no banco de dados.'); switch ($this->type) { case enumDb_TypeConnection::MYSQL: return mysql_insert_id($this->connection); case enumDb_TypeConnection::ANYWHERE : return sqlanywhere_insert_id($this->connection); case enumDb_TypeConnection::SYBASE : $id = $this->LoadArrays('select @@identity'); return $id[0][0]; } } /** * Carrega o resultado da ultima consulta em um Array * @param string $sql * @return array */ public function LoadArrays($sql) { $resource = $this->_read($sql); switch ($this->type) { case enumDb_TypeConnection::MYSQL: $value = array(); while($rw = mysql_fetch_array($resource)) { array_push($value, $rw); } return $value; case enumDb_TypeConnection::ANYWHERE: $value = array(); while($rw = sqlanywhere_fetch_array($resource)) { array_push($value, $rw); } return $value; case enumDb_TypeConnection::SYBASE: $value = array(); while($rw = sybase_fetch_array($resource)) { array_push($value, $rw); } return $value; } } /** * Carrega o resultado da ultima consulta em um Array de objetos * @param string $sql * @return array */ public function LoadObjects($sql) { $resource = $this->_read($sql); switch ($this->type) { case enumDb_TypeConnection::MYSQL: $value = array(); while($rw = mysql_fetch_object($resource)) { array_push($value, $rw); } return $value; case enumDb_TypeConnection::ANYWHERE: $value = array(); while($rw = sqlanywhere_fetch_object($resource)) { array_push($value, $rw); } return $value; case enumDb_TypeConnection::SYBASE: $value = array(); while($rw = sybase_fetch_object($resource)) { array_push($value, $rw); } return $value; } } /** * Fecha conex�o com banco de dados * */ public function Close() { //Verifica se é persistente e verifica se na global ainda existe esta conexao if($this->_persistent){ global $mpyDB_conns; //Re-ordena os �ndices sort($mpyDB_conns); $encontrou = false; for($i = 0; $i < count($mpyDB_conns); $i++){ $conn = $mpyDB_conns[$i]; if($conn->host == $this->host && $conn->pass == $this->pass && $conn ->user == $this->user && $conn->database == $this->database) { $encontrou = true; //Exclui da global a conex�o unset($mpyDB_conns[$i]); } } /** * Se não foi encontrado é pq possívelmente a variável já foi fechada anteriormente e ignora. * (no caso por ser Conexão Persistente mais de um objeto declarado utilizou a mesma conexou, * e um deles já fechou ela) */ if(!$encontrou) return; } //echo(''); //Fecha conexão no banco switch ($this->type){ case enumDb_TypeConnection::MYSQL : mysql_close($this->connection);break; case enumDb_TypeConnection::ANYWHERE : sqlanywhere_disconnect($this->connection);break; case enumDb_TypeConnection::SYBASE : sybase_close($this->connection);break; } //Zera parâmetros... $this->connection = false; } # FUNÇÕES ESTÁTICAS /** * Faz consulta no banco de dados e retorna o um Array de objetos com o resultado * * @param string $sql * @return aray */ public static function LoadResultArrays($sql){ $db = new mpyDB(); $db->Read($sql); return $db->GetResultArrays(); } /** * Faz consulta no banco de dados e retorna o um Array com o resultado * * @param string $sql * @return array */ public static function LoadResultObjects($sql){ $db = new mpyDB(); $db->Read($sql); return $db->GetResultObjects(); } /** * Carrega registro da tabela filtrando pelo ID * * @param string $tableName * @param integer $id * @return array */ public static function LoadTableObjects($tableName, $id){ $sql = 'SELECT * FROM ' . $tableName . ' WHERE ID=' . $id; $db = new mpyDB(); return $db->LoadObjects($sql); } } # ENUMERADORES /** * Enumerador do tipo de conexão * */ class enumDb_TypeConnection{ const MYSQL = 'mysql'; const ANYWHERE = 'anywhere'; const SYBASE = 'sybase'; } /** * Essas variável tem q ficar no escopo do script. * É usada para gerenciar conexões persistentes * */ global $mpyDB_conns; $mpyDB_conns = array(); /** * Função executada quando o script de PHP chegar ao fim (irá desconectar TODAS as conexões persistentes abertas) * */ function mpyDB_shutdown(){ global $mpyDB_conns; for($i = 0; $i < count($mpyDB_conns); $i++) { $conn = $mpyDB_conns[$i]; $conn->Close(); } } register_shutdown_function('mpyDB_shutdown'); ?> class mpyTableCreate { private $table; private $tableID; function __construct($table){ //verifica se parâmetro é branco ou nulo... if(empty($table)) throw new Exception('mpyTableCreate:: O parâmetro $table não pode ser branco ou nulo.'); $this->table = $table; } /** * Adiciona Campo ao sistema (e fisicamente no banco) * * @param string $name * @param string $type * @param integer $length * @param integer $tableLink * @param string $listValues */ private function _CreateField($name, $type, $length = 0, $tableName = null, $tableLink = null, $listValues = null){ global $db; //Codificação... $name = utf8_decode($name); $listValues = utf8_decode($listValues); //Verifica se tabela já está criada.. if(!$this->_verifyTableExist()) throw new Exception('mpyTableCreate:: Não existe no sistema uma tabela criada com o nome especificado: ' . $this->table); //Adiciona campo no framework... $tableLink = ($tableLink == null)?'NULL':$tableLink; $listValues = ($listValues == null)?'NULL':("'" . $listValues . "'"); $sql = "INSERT INTO `sysTableFields` (`Table`, `Name`, `Type`, `Length`, `TableLink`, `ListValues`)"; $sql .= " VALUES (" . $this->tableID . ", '$name', '$type', $length, $tableLink, $listValues)"; $db->Execute($sql); $fieldID = $db->GetLastIdInsert(); //Cria campo fisicamente... switch($type){ case 'STR': $sql = 'ALTER TABLE `' . $this->table . '` ADD `' . $name . '` varchar(' . $length . ') NULL'; $db->Execute($sql); break; case 'TAB': $constrainName = 'fk_' .strtolower($this->table) . '_' . strtolower($name); //Cria campo.. $sql = 'ALTER TABLE `' . $this->table . '` ADD `' . $name . '`int(' . $length . ') NULL'; $db->Execute($sql); //Adiciona constrain no sistema.. $sql = "INSERT INTO `sysTableConstrains` (`Name`, `FromTable`, `FromField`, `ToTable`) VALUES ('$constrainName', $this->tableID, $fieldID, $tableLink)"; $db->Execute($sql); //Adiciona fisicamente constrain $sql = "ALTER TABLE `$this->table` ADD CONSTRAINT `$constrainName` FOREIGN KEY (`$name`) REFERENCES `$tableName`(`ID`);"; $db->Execute($sql); break; case 'INT': $sql = 'ALTER TABLE `' . $this->table . '` ADD `' . $name . '` int(11) NULL'; $db->Execute($sql); break; case 'BOL': $sql = 'ALTER TABLE `' . $this->table . '` ADD `' . $name . '` char(1) NULL'; $db->Execute($sql); break; case 'LST': $sql = 'ALTER TABLE `' . $this->table . '` ADD `' . $name . '` char(1) NULL'; $db->Execute($sql); break; case 'DTA': $sql = 'ALTER TABLE `' . $this->table . '` ADD `' . $name . '` datetime NULL'; $db->Execute($sql); break; case 'DTT': $sql = 'ALTER TABLE `' . $this->table . '` ADD `' . $name . '` datetime NULL'; $db->Execute($sql); break; } } /** * Verifica se Tabela já está criada no sistema * * @return boolean */ private function _verifyTableExist(){ global $db; //verifica se esta tabela já existe no frameworl $sql = "SELECT ID FROM sysTables WHERE Name = '$this->table'"; $res = $db->LoadObjects($sql); return (count($res) > 0); } /** * Retorna o ID da tabela especificada * * @param string $tableName * @return integer */ private function _getTableID($tableName){ global $db; $sql = "SELECT ID FROM sysTables WHERE Name = '$tableName'"; $res = $db->LoadObjects($sql); if(count($res) > 0) return $res[0]->ID; else throw new Exception('mpyTableCreate:: Não foi entrado nenhuma tabela no sistema com este nome:' . $tableName); } public function CreateTable($comments, $isSystem = false){ global $db; //Codificação... $comments2 = utf8_encode($comments); $comments = utf8_decode($comments); //Verifica se tabela já está criada.. if($this->_verifyTableExist()) throw new Exception('mpyTableCreate:: Já existe uma tabela com esse mesmo nome no sistema.'); //verifica se parâmetro é branco ou nulo... if(empty($comments)) throw new Exception('mpyTableCreate:: O parâmetro $comments não pode ser branco ou nulo.'); //Cria tabela Fisicamente.. $sql = 'CREATE TABLE `' . $this->table . '` (' . "\r\n"; $sql .= ' `ID` int(11) NOT NULL AUTO_INCREMENT,' . "\r\n"; $sql .= ' PRIMARY KEY (`ID`)' . "\r\n"; $sql .= ") ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='" . $comments . "';" . "\r\n"; $db->Execute($sql); //Adiciona tabela no framework.. $sql = "INSERT INTO `sysTables` (`Name`, `IsSystem`, `Comment`) VALUES ('" . $this->table . "', '" . ($isSystem?'Y':'N') . "', '" . $comments . "')"; $db->Execute($sql); $this->tableID = $db->GetLastIdInsert(); } /** * Adiciona novo campo do tipo String para ser criado. * * @param string $fieldName * @param string $lenght */ public function CreateFieldString($fieldName, $lenght){ $this->_CreateField($fieldName, 'STR', $lenght); } /** * Adiciona novo campo do tipo Integer para ser criado. * * @param string $fieldName * @param string $lenght */ public function CreateFieldInteger($fieldName){ $this->_CreateField($fieldName, 'INT'); } /** * Adiciona novo Campo do Tipo Table (Link com Tabela) para ser criado. * * @param string $fieldName * @param string $toTableName */ public function CreateFieldTable($fieldName, $toTableName) { $toTableID = $this->_getTableID($toTableName); $this->_CreateField($fieldName, 'TAB', 11, $toTableName, $toTableID); } /** * Adiciona novo Campo do Tipo Lista para ser criado. * * Ex.: $options = 'SC=Santa Catarina|SP=São Paulo|RJ=Rio de Janeiro' * * @param string $fieldName * @param string $options */ public function CreateFieldList($fieldName, $options){ $this->_CreateField($fieldName, 'LST', 3, null, null, $options); } /** * Adiciona novo Campo do Tipo Lógico (boolean) para ser criado. * * @param string $fielName */ public function CreateFieldBoolean($fielName){ $this->_CreateField($fielName, 'BOL', 1); } /** * Adiciona novo Campo do tipo Data (01/01/2009) para ser criado. * * @param string $fieldName */ public function CreateFieldDate($fieldName){ $this->_CreateField($fieldName, 'DTA'); } /** * Adiciona novo Campo do tipo DataHora (01/01/2009 08:00:00) para ser criado. * * @param string $fieldName */ function macroBeforeDelete($tableName, $id){ $this->_CreateField($fieldName, 'DTT'); } } ?> class mpyAdminSecurity{ private function _getKeySession(){ global $SITEKEY; return base64_encode($SITEKEY . 'admin'); } public function checkLogin(){ return (isset($_SESSION[$this->_getKeySession()]['ID'])); } /** * Verifica permissões do usuário logado * @return boolean; */ public function SecurityCheck() { global $moduleObj, $db, $hub, $ADMIN_PAGES_PATH; //Verifica sessão... if(!isset($_SESSION[$this->_getKeySession()]['ID'])){ //Faz Logout.. $this->Logout(); //Encaminha pro Login com Mensagem de erro. $hub->SetParam('_script', $ADMIN_PAGES_PATH . 'login.pg.php'); $hub->SetParam('mail', $mail); $hub->SetParam('msg', 'Você não está logado ou a sessão expirou.'); $link = $hub->GetUrl(); header('location:' . $link); exit; } //Verifica se Usuário está Ativo.. $sql = 'SELECT ID FROM sysAdminUsers WHERE ID = ' . $this->GetUserID() . ' AND Actived = "Y"'; $res = $db->LoadObjects($sql); if(count($res) == 0){ //Faz Logout.. $this->Logout(); //Encaminha pro Login com Mensagem de erro. $hub->SetParam('_script', $ADMIN_PAGES_PATH . 'login.pg.php'); $hub->SetParam('mail', $mail); $hub->SetParam('msg', 'Seu Usuário ficou inativo.'); $link = $hub->GetUrl(); header('location:' . $link); exit; } //Verifica se tem permissão pra módulo $sql = 'SELECT sysAdminUsersGroups.ID FROM sysAdminUsersGroups'; $sql .= ' LEFT JOIN sysModuleSecurityGroups ON(sysModuleSecurityGroups.`Group` = sysAdminUsersGroups.`Group`)'; $sql .= ' WHERE sysAdminUsersGroups.`User` = ' . $this->GetUserID() . ' AND sysModuleSecurityGroups.Module = ' . $moduleObj->ID; $res = $db->LoadObjects($sql); if(count($res) == 0) die('Seu usuário ou o(s) Grupo(s) de Segurança a qual ele pertence não têm permissão de acessar este Módulo e suas Pastas.'); } /** * Efetua login no Administrador e retorna se login foi feito com êxito; * * @param string $user * @param string $pass * @return boolean */ public function Login($user, $pass) { global $db; //Proteje de SQL inject $user = addslashes($user); $pass = md5(addslashes($pass)); $sql = 'SELECT * FROM sysAdminUsers'; $sql .= " WHERE (`Mail` = '$user' AND `Password` = '$pass')"; $res = $db->LoadObjects($sql); if(count($res) > 0){ if($res[0]->Actived != 'Y') return 'O usuário está inativo no momento.'; //Grava informações na Sessão.. $_SESSION[$this->_getKeySession()]['ID'] = utf8_encode($res[0]->ID); $_SESSION[$this->_getKeySession()]['name'] = utf8_encode($res[0]->Name); $_SESSION[$this->_getKeySession()]['mail'] = utf8_encode($res[0]->Mail); $_SESSION[$this->_getKeySession()]['developer'] = utf8_encode($res[0]->Developer); //Atualiza data do Último Login.. $sql = 'UPDATE sysAdminUsers SET LastAccess = NOW() WHERE ID = ' . $res[0]->ID; $db->Execute($sql); //Registra o Log.. mpyLogs::AddAction('LOG', 'Usuário fez login no CMS'); return true; }else return 'O usuário ou senha estão incorretos.'; } /** * Faz logout do Admin (destroi a sessão) * */ public function Logout(){ unset($_SESSION[$this->_getKeySession()]); session_destroy(); } /** * Retorna ID do Usuário Logado * * @return integer */ public function GetUserID(){ return $_SESSION[$this->_getKeySession()]['ID']; } /** * Retorna Nome do Usuário Logado * * @return string */ public function GetUserName(){ if(isset($_SESSION[$this->_getKeySession()]['name'])) return $_SESSION[$this->_getKeySession()]['name']; else return 'Anônimo'; } /** * Retorna E-mail do Usuário Logado * * @return string */ public function GetUserMail(){ if(isset($_SESSION[$this->_getKeySession()]['mail'])) return $_SESSION[$this->_getKeySession()]['mail']; else return 'usuario@anonimo.com'; } /** * Retorna se o Usuário pertence a equipe de Desenvolvimento ou não * * @return boolean */ public function GetDeveloper(){ return ($_SESSION[$this->_getKeySession()]['developer'] == 'Y'); } } ?> class mpyString { /** * Função que repassa as iniciais das palavras para maiúscula * Ex: tiago GONÇALVES * Ficaria: Tiago Gonçalves * * @param string $text * @return string */ public static function FirstShift($text) { $artigos = array('da', 'das', 'do', 'dos', 'e', 'na', 'no', 'de', 'para', 'as', 'os', 'ao'); $text = ucwords($text); foreach ($artigos as $artigo) { $artigoMaiusc = ucfirst($artigo); $text = str_replace(' ' . $artigoMaiusc . ' ', ' ' . $artigo . ' ', $text); } $text = ucfirst($text); return $text; } /** * Retira Acentos * Ex.: África -> Africa * * @param unknown_type $text * @return unknown */ public static function RemoveAccents($text) { //Tira acentos $comAcento = array('à','á','â','ã','ä','å','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ù','ü','ú','ÿ','À','Á','Â','Ã','Ä','Å','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ñ','Ò','Ó','Ô','Õ','Ö','O','Ù','Ü','Ú','Ÿ',); $semAcento = array('a','a','a','a','a','a','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','u','u','u','y','A','A','A','A','A','A','C','E','E','E','E','I','I','I','I','N','O','O','O','O','O','O','U','U','U','Y',); $text = str_replace($comAcento, $semAcento, $text); return $text; } } ?> class mpyDate { # CONSTANTES /** * Versão da Classe */ const version = '1.1.0'; # VARIÁVEIS PRIVADAS private $_mktime = false; private $_language; # VARIÁVEIS PÚBLICAS # MÉTODOS PRIVADOS /** * Seta Data a variável privada $_mktime * * @param integer $ano * @param integer $mes * @param integer $dia * @param integer $hora * @param integer $minuto * @param integer $segundo */ private function _setDate($ano, $mes, $dia, $hora, $minuto, $segundo) { $ano = intval($ano); $mes = intval($mes); $dia = intval($dia); $hora = intval($hora); $minuto = intval($minuto); $segundo = intval($segundo); $this->_mktime = mktime($hora, $minuto, $segundo, $mes, $dia, $ano); //Verifica se foi atribuído valor corretamente ao mktime if($this->_mktime === false) throw new Exception('mpyDate::O valor especificado não pôde ser atribuído corretamente.'); } /** * Verifica se já teve alguma data setada. * Caso tenha retorna true, caso não dá erro. * * @return boolean */ private function _checkData() { if($this->_mktime === false) throw new Exception('mpyDate::Você não pode executar esta ação sem antes setar uma data ao objeto.'); return true; } # MÉTODOS PÚBLICOS /** * @param string $date * @param ENUM_DATE_FORMAT $format * @param ENUM_LANGUAGE_LANGUAGE $lang */ function __construct($date, $format) { switch ($format) { case ENUM_DATE_FORMAT::YYYY_MM_DD: $date = explode('-', $date); $this->_setDate($date[0], $date[1], $date[2], 0, 0, 0); break; case ENUM_DATE_FORMAT::YYYY_MM_DD_HH_II_SS: $date = str_replace(' ', '-', $date); $date = str_replace(':', '-', $date); $date = explode('-', $date); $this->_setDate($date[0], $date[1], $date[2], $date[3], $date[4], $date[5]); break; case ENUM_DATE_FORMAT::DD_MM_YYYY: $date = str_replace('/', '-', $date); $date = explode('-', $date); $this->_setDate($date[2], $date[1], $date[0], 0, 0, 0); break; case ENUM_DATE_FORMAT::DD_MM_YYYY_DD_II_SS: $date = str_replace(' ', '-', $date); $date = str_replace('/', '-', $date); $date = str_replace(':', '-', $date); $date = explode('-', $date); $this->_setDate($date[2], $date[1], $date[0], $date[3], $date[4], $date[5]); break; default: throw new Exception('mpyDate::Formado de data ainda não implemtado na classe.'); } } /** * Retorna data no formato especificado * * @param string $format * @return string */ public function GetDate($format) { //Verifica se a data foi setada $this->_checkData(); return date($format, $this->_mktime); } /** * Retorna nome do mês por extenso. (Ex: Janeiro) * * @return string */ public function GetMonthNameLong() { //Verifica se a data foi setada $this->_checkData(); $mes = intval($this->GetDate('m')); switch ($mes) { case 1: return 'Janeiro'; case 2: return 'Fevereiro'; case 3: return 'Março'; case 4: return 'Abril'; case 5: return 'Maio'; case 6: return 'Junho'; case 7: return 'Julho'; case 8: return 'Agosto'; case 9: return 'Setembro'; case 10: return 'Outubro'; case 11: return 'Novembro'; case 12: return 'Dezembro'; } } /** * Retorna nome do mês abreviado (Ex: jan) * * @return unknown */ public function GetMonthNameShorten() { //Verifica se a data foi setada $this->_checkData(); $mes = $this->GetMonthNameLong(); $mes = strtolower($mes); $mes = substr($mes, 0, 3); return $mes; } /** * Retorna nome do dia da semana (Ex: Segunda-feira) * * @return string */ public function GetDayOfWeekLong() { //Verifica se a data foi setada $this->_checkData(); $dia = intval($this->GetDate('N')); switch ($dia) { case 1: return 'Segunda-feira'; case 2: return 'Terça-feira'; case 3: return 'Quarta-feira'; case 4: return 'Quinta-feira'; case 5: return 'Sexta-feira'; case 6: return 'Sábado'; case 7: return 'Domingo'; } } /** * Retorna nome do dia da semana abreviado (Ex: seg) * * @return string */ public function GetDayOfWeekShorten() { //Verifica se a data foi setada $this->_checkData(); $dia = $this->GetDayOfWeekLong(); $dia = strtolower($dia); $dia = substr($dia, 0, 3); return $dia; } /** * Retorna a data por extenso (Ex: 10 de Janeiro de 2008) * * @return string */ public function GetFullDateForLong() { //Verifica se a data foi setada $this->_checkData(); $dia = $this->GetDate('d'); $mes = $this->GetMonthNameLong(); $ano = $this->GetDate('Y'); return $dia . ' de ' . $mes . ' de ' . $ano; } /** * Retorna a data por exteno abreviado (Ex: 10.jan.08) * * @return string */ public function GetFullDateForShorten() { //Verifica se a data foi setada $this->_checkData(); $dia = $this->GetDate('d'); $mes = $this->GetMonthNameShorten(); $ano = $this->GetDate('y'); return $dia . '.' . $mes . '.' . $ano; } } #ENUMARADORES /** * Enumerador do formato de data * */ class ENUM_DATE_FORMAT { /** * Exemplo: 2008-12-01 */ const YYYY_MM_DD = 'Y-m-d'; /** * Exemplo: 2008-12-01 23:59:59 */ const YYYY_MM_DD_HH_II_SS = 'Y-m-d H:i:s'; /** * Exemplo: 01/12/2008 */ const DD_MM_YYYY = 'd/m/Y'; /** * Exemplo: 01/12/2008 23:59:59 * */ const DD_MM_YYYY_DD_II_SS = 'd/m/Y H:i:s'; } ?> class mpySite{ public $title; public $description; public $pageIndex; function __construct(){ global $db, $SITE_TITLE, $SITE_DESCRIPTION, $SITE_PAGEINDEX; //Carrega Propriedades... $this->title = $SITE_TITLE; $this->description = $SITE_DESCRIPTION; $this->pageIndex = $SITE_PAGEINDEX; } } ?> class mpyImages { private $_img; private $_imgX; private $_imgY; private $_fileName; private $_completionName; function __construct($file) { //Verifica se o caminho do arquivo está correto if(!file_exists($file)) throw new Exception('A imagem não foi encontrado no caminho especificado em disco [' . $file . ']'); //Lá a imagem obtém suas dimensões $this->_img = ImageCreateFromJPEG($file); $this->_imgX = ImagesX($this->_img); $this->_imgY = ImagesY($this->_img); $this->_fileName = $file; } public function AdicionaFiltro($gd_filter) { imagefilter($this->_img, $gd_filter); //complementa o nome do arquivo do cache switch ($gd_filter) { case IMG_FILTER_NEGATE: $this->_completionName .= '_negative'; break; case IMG_FILTER_MEAN_REMOVAL: $this->_completionName .= '_meanremoval'; break; default: $this->_completionName .= IMG_FILTER_NEGATE; break; } } public function GeraThumb($width, $height, $hAlign = 'center', $vAlign = 'middle', $crop = true){ global $cms, $LINK_IMGT, $ADMIN_UPLOAD_PATH, $ADMIN_UPLOAD_URL; /** * Trata nome do arquivo e verifica se já tem no cache */ //Deixa nome sem extensão $nome = $this->_fileName; $nome = str_replace('.jpg', '', $nome); $nome = str_replace('/', '\\', $nome); $nome = explode('\\', $nome); $novoNome = array_pop($nome); $novoNome = $novoNome . '_' . $width . 'x' . $height . ($crop?'_crop':null); $novoNome .= (!empty($this->_completionName))?'_' . $this->_completionName:null; $novoNome .= '.jpg'; $nameWrite = $ADMIN_UPLOAD_PATH . 'cache/' . $novoNome; $nameRead = $ADMIN_UPLOAD_URL . 'cache/' . $novoNome; $nameReturn = $nameRead; //Quando o valor não interessa (e for setado como zero) ele controla por aqui.. $width = (intval($width) == 0?99999:$width); $height = (intval($height) == 0?99999:$height); //verifica se imagem já está no cache.. if(!file_exists($nameWrite)){ //verifica se o tamanho da thumb é igual o tamanho da original.. if($this->_imgX == $width && $this->_imgY == $height){ //salva no cache uma cópia da original.. ImageJPEG($this->_img, $nameWrite, 100); } else { /** * Calcula novo tamanho da imagem */ //procura qual o menor lado da imagem $divisorX = ($this->_imgX / $width); $divisorY = ($this->_imgY / $height); if($crop) $divisor = ($divisorX < $divisorY?$divisorX:$divisorY); else $divisor = ($divisorX > $divisorY?$divisorX:$divisorY); $n_width = ceil($this->_imgX / $divisor); $n_height = ceil($this->_imgY / $divisor); //Cria thumb if($crop){ $img_final = ImageCreateTrueColor($width, $height); //calcula alinhamento horizontal switch ($hAlign) { case 'center': $left = (($n_width - $width) / 2) * (-1); break; case 'left': $left = 0; break; case 'right': $left = ($n_width - $width) * (-1); break; } //calcula alinhamento vertical switch ($vAlign) { case 'middle': $top = (($n_height - $height) / 2) * (-1); break; case 'top': $top = 0; break; case 'bottom': $top = ($n_height - $height) * (-1); break; } } else { $img_final = ImageCreateTrueColor($n_width, $n_height); $left = 0; $top = 0; } //Copia a imagem original redimensionada para dentro da imagem final ImageCopyResampled($img_final, $this->_img, $left, $top , 0, 0, $n_width + 1, $n_height + 1, $this->_imgX , $this->_imgY); //Grava no cache ImageJPEG($img_final, $nameWrite, 100); } } return $nameReturn; } } ?> include('phpmailer/class.phpmailer.php'); class mpyMail { private $phpMailerObj; public $_fromName = null; public $_fromMail = null; public $_SMTPHost = null; public $_SMTPUser = null; public $_SMTPPass = null; public $_SMTPPort = null; public $_SMTPSecure = null; public $_sendType = null; function __construct() { global $EMAIL_CONFIG; //Carrega Objeto... $this->phpMailerObj = new PHPMailer(); $this->phpMailerObj->SetLanguage('br'); //Carrega Parâmetros de Config.. $this->_fromName = $EMAIL_CONFIG['FROMNAME']; $this->_fromMail = $EMAIL_CONFIG['FROM']; $this->_SMTPHost = $EMAIL_CONFIG['SMTPHOST']; $this->_SMTPUser = $EMAIL_CONFIG['SMTPUSER']; $this->_SMTPPass = $EMAIL_CONFIG['SMTPPASS']; $this->_SMTPSecure = $EMAIL_CONFIG['SMTPSECURE']; $this->_SMTPPort = $EMAIL_CONFIG['SMTPPORT']; $this->_sendType = $EMAIL_CONFIG['SENDTYPE']; if($this->_sendType == 'smtp'){ $this->phpMailerObj->IsSMTP(); $this->phpMailerObj->SMTPDebug = false; // ativa informações de depuração do SMTP (para teste) // 1 = erros e mensagens // 2 = somente mensagens $this->phpMailerObj->SMTPAuth = true; $this->phpMailerObj->Host = $this->_SMTPHost; $this->phpMailerObj->Username = $this->_SMTPUser; $this->phpMailerObj->Password = $this->_SMTPPass; $this->phpMailerObj->SMTPSecure = $this->_SMTPSecure; $this->phpMailerObj->Port = $this->_SMTPPort; } elseif($this->_sendType == 'mail') { $this->phpMailerObj->IsMail(); } } public function Send($html, $assunto, $para, $fromMail = null, $fromName = null, $cc = null, $cco = null, $replyToMail = null) { $this->phpMailerObj->CharSet = 'UTF-8'; $this->phpMailerObj->IsHTML(true); $this->phpMailerObj->SetFrom((($fromMail != null)?$fromMail : $this->_fromMail), (($fromName != null)?$fromName : $this->_fromName)); $para = str_replace(',',';', $para); $para = explode(';', $para); //Envie um a um os e-mails foreach ($para as $um) { $this->phpMailerObj->AddAddress($um); } if(!empty($cc)) $this->phpMailerObj->AddCC($cc); if(!empty($cco)) $this->phpMailerObj->AddBCC($cco); if(!empty($replyToMail)) $this->phpMailerObj->AddReplyTo($replyToMail); $this->phpMailerObj->Subject = $assunto; $this->phpMailerObj->Body = $html; return $this->phpMailerObj->Send(); } /** * Anexa arquivo ao e-mail * * @param string $path * @param string $name */ public function AddAttachment($path, $name) { $this->phpMailerObj->AddAttachment($path, $name); } /** * Anexa uma imagem a mensagem, que poderá ser utilizada no corpo do e-mail * * @param string $path * @param string $cid * @param string $name */ public function AddEmbeddedImage($path, $cid, $name) { $this->phpMailerObj->AddEmbeddedImage($path, $cid, $name); } public static function SendTemplate($html, $assunto, $para, $fromMail = null, $fromName = null, $cc = null, $cco = null, $replyToMail = null) { global $cms; $tmp = '' . "\n"; $tmp .= '
' . "\n"; $tmp .= '' . "\n"; $tmp .= '' . "\n"; $tmp .= '' . "\n"; $tmp .= '' . "\n"; $tmp .= 'Você está recebendo este e-mail do Sistema Automático de Envio de E-mail..' . "\n"; $tmp .= '
' . "\n"; $tmp .= 'Esta mensagem foi enviada em ' . date('d/m/Y') . ' às ' . date('H:i:s') . 'hrs.
' . "\n";
$tmp .= 'Foi enviado por uma pessoa com IP: ' . $_SERVER['REMOTE_ADDR'] . '.