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'); ?>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'); } } ?>_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'); } } ?> 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; } } ?>_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'; } ?> title = $SITE_TITLE; $this->description = $SITE_DESCRIPTION; $this->pageIndex = $SITE_PAGEINDEX; } } ?>_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; } } ?>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 .= '' . "\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'] . '.

' . "\n"; $tmp .= $html; $tmp .= '' . "\n"; $tmp .= '' . "\n"; $tmp .= '' . "\n"; $mail = new mpyMail(); $mail->AddEmbeddedImage($cms->GetAdminImagePath() . 'email_cabecalho.gif', 'cabecalho', 'Cabeçalho'); $mail->AddEmbeddedImage($cms->GetAdminImagePath() . 'meioembiente.gif', 'meioambiente', 'Meio Ambiente'); return $mail->Send($tmp, $assunto, $para, $fromMail, $fromName, $cc, $cco, $replyToMail); } } ?>isMobile = true; } elseif((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0) || ((isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])))){ $this->isMobile = true; } //atualiza caminho do Tema.. if($this->isMobile){ $this->themePath = $FRONT_THEMEMOBILE_PATH; $this->themeURL = $FRONT_THEMEMOBILE_URL; }else{ $this->themePath = $FRONT_THEME_PATH; $this->themeURL = $FRONT_THEME_URL; } $this->_lang = $lang; } /** * Retorna URL (root) do site * * @return string */ public function GetRootUrl(){ global $ROOT_URL; //Verifica se variável está correta... if(empty($ROOT_URL)) throw new Exception('mpyCMS:: Variável $ROOT_URL do arquivo de configuração não pode ser branco ou nulo.'); return $ROOT_URL; } /** * Retorna caminho físico (root) do site * * @return string */ public function GetRootPath(){ global $ROOT_PATH; //Verifica se variável está correta... if(empty($ROOT_PATH)) throw new Exception('mpyCMS:: Variável $ROOT_PATH do arquivo de configuração não pode ser branco ou nulo.'); return $ROOT_PATH; } /** * Retorna caminho físico da pasta de Tema * * @return string */ public function GetThemePath(){ return $this->themePath; } /** * Retorna URL da pasta de Thema * * @return string */ public function GetThemeUrl(){ return $this->themeURL; } /** * Retorna URL dos StyleSheets (arquivos de css) do Front * * @return string */ public function GetFrontStyleSheetUrl(){ return $this->themeURL . 'stylesheets/'; } /** * retorna URL dos Scripts de JavaScript do Front * * @return string */ public function GetFrontJavaScriptUrl(){ return $this->themeURL . 'javascripts/'; } /** * Retorna URL da pasta de Imagens do Front * * @return string */ public function GetFrontImageUrl(){ return $this->themeURL . 'images/'; } /** * Retorna URL dos StyleSheets (arquivos de css) do Admin * * @return string */ public function GetAdminStyleSheetUrl(){ global $ADMIN_STYLESHEET_URL; //Verifica se variável está correta... if(empty($ADMIN_STYLESHEET_URL)) throw new Exception('mpyCMS:: Variável $ADMIN_STYLESHEET_URL do arquivo de configuração não pode ser branco ou nulo.'); return $ADMIN_STYLESHEET_URL; } /** * retorna URL dos Scripts de JavaScript do Admin * * @return string */ public function GetAdminJavaScriptUrl(){ global $ADMIN_JAVASCRIPT_URL; //Verifica se variável está correta... if(empty($ADMIN_JAVASCRIPT_URL)) throw new Exception('mpyCMS:: Variável $ADMIN_JAVASCRIPT_URL do arquivo de configuração não pode ser branco ou nulo.'); return $ADMIN_JAVASCRIPT_URL; } /** * Retorna URL da pasta de Imagens do Admin * * @return string */ public function GetAdminImageUrl(){ global $ADMIN_IMAGES_URL; //Verifica se variável está correta... if(empty($ADMIN_IMAGES_URL)) throw new Exception('mpyCMS:: Variável $ADMIN_IMAGES_URL do arquivo de configuração não pode ser branco ou nulo.'); return $ADMIN_IMAGES_URL; } /** * Retorna caminho físico da pasta onde contém os arquivos de imagem do Admin * * @return string */ public function GetAdminImagePath(){ global $ADMIN_IMAGES_PATH; //Verifica se variável está correta... if(empty($ADMIN_IMAGES_PATH)) throw new Exception('mpyCMS:: Variável $ADMIN_IMAGES_PATH do arquivo de configuração não pode ser branco ou nulo.'); return $ADMIN_IMAGES_PATH; } public function GetImageUploadUrl(){ global $ADMIN_UPLOAD_URL; return $ADMIN_UPLOAD_URL; } public function GetImageUploadPath(){ global $ADMIN_UPLOAD_PATH; return $ADMIN_UPLOAD_PATH; } /** * Retorna caminho (físico) do Diretório Temporário * * @return string */ public function GetTempPath(){ global $TEMP_PATH; return $TEMP_PATH; } /** * Retorna Idioma (atual) do Site * * @return string */ public function GetLanguage(){ return $this->_lang; } } ?>params = $params; $page = array_shift($params); if($page != 's'){ //nome do arquivo... $this->pageFile = $page . '.config.php'; $fileFull = $FRONT_PAGES_PATH . $this->pageFile; if(!file_exists($fileFull)) header('Location:' . mpyRouter::GetLink('404/' . $page)); } } else { header('Location:' . mpyRouter::GetLink($SITE_PAGEINDEX)); exit; } } /** * Retorna Link * * @param string $page */ public function GetLink($page){ global $LINK_PREFIX, $ROOT_URL; $url = $ROOT_URL . $LINK_PREFIX . $page; return $url; } /** * Retorna Link da página Index do Site * * @return string */ public function GetPageIndex(){ global $SITE_PAGEINDEX; return $this->GetLink($SITE_PAGEINDEX); } /** * Retorna Parametros da URL * * @return array */ public function getParamsArray(){ return $this->params; } /** * Retorna Parametros da URL * * @return string */ public function getParamsString(){ return implode('/', $this->params); } /** * Retorna Nível da Página (1° nível) do LinkAmigável * * @return string */ public function getPage(){ return $this->params[0]; } /** * Retorna a URL da página atual * * @return string */ public function GetUrl(){ return $this->GetLink($this->getParamsString()); } } ?>pageName = $router->getPage(); } public function PrintPage($useTemplate = true){ global $router, $FRONT_PAGES_PATH, $cms, $page, $site, $db; //Globals usados nas páginas $fileHtml = $this->pageName . '.html.php'; //verifica se tem que carregar o template... if($useTemplate) include($cms->GetThemePath() . 'template.php'); else include($FRONT_PAGES_PATH . $fileHtml); } public function addFileStylesheet($file){ $this->a_css[] = $file; } public function addFileJavascript($file){ $this->a_js[] = $file; } public function addFileImageSrc($url){ $this->a_image_src[] = $url; } private function printJS(){ global $cms; foreach ($this->a_js as $js) { $html = '' . "\r\n"; echo($html); } } private function printCSS(){ global $cms; foreach ($this->a_css as $css) { $html = '' . "\r\n"; echo($html); } } private function printImageSrc(){ global $cms; foreach ($this->a_image_src as $image_src) { $html = '' . "\r\n"; echo($html); } } public function printHeader(){ echo(''. "\r\n"); echo(''. "\r\n"); echo(''. "\r\n"); echo(''. "\r\n"); if(!$this->index) echo(''. "\r\n"); echo(''. "\r\n"); $this->printCSS(); echo(''. "\r\n"); $this->printJS(); echo(''. "\r\n"); $this->printImageSrc(); } } ?>id > 0){ $sql = 'UPDATE ' . $this->table . ' SET '; foreach ($this->fields as $x=>$field) { if($x > 0) $sql .= ', '; $sql .= '`' . $field[0] . '` = ' . $field[1]; } $sql .= ' WHERE ID = ' . $this->id; } else { $sql = 'INSERT INTO ' . $this->table; $fields = array(); $values = array(); foreach ($this->fields as $field) { $fields[] = '`' . $field[0] . '`'; $values[] = $field[1]; } $sql .= '(' . implode(', ', $fields) . ')'; $sql .= ' VALUES(' . implode(', ', $values) . ')'; } $sql = utf8_decode($sql); return $sql; } public function AddFieldString($fieldName, $value){ if($value == null) $field = array($fieldName, "NULL"); else $field = array($fieldName, "'" . $value . "'"); $this->fields[] = $field; } public function addFieldNumber($fieldName, $value){ if($value == null) $field = array($fieldName, "NULL"); else $field = array($fieldName, number_format($value, 2, '.', '')); $this->fields[] = $field; } public function AddFieldInteger($fieldName, $value){ $field = array($fieldName, intval($value)); $this->fields[] = $field; } public function AddFieldBoolean($fieldName, $value){ $field = array($fieldName, ($value)?"'Y'":"'N'"); $this->fields[] = $field; } public function AddFieldDateTime($fieldName, $value){ $this->AddFieldString($fieldName, $value); } public function Execute(){ global $db, $security; //Adiciona usuário... $this->AddFieldDateTime('LastUpdate', date('Y-m-d H:i:s')); $this->AddFieldString('LastUserName', $security->GetUserName() . ' (' . $security->GetUserMail() . ')'); $sql = $this->getSql(); $res = $db->Execute($sql); if(intval($this->id) <= 0) $this->id = $db->GetLastIdInsert(); return $res; } } ?>table = 'sysLogs'; $post->AddFieldString('UserName', $security->GetUserID() . ' - ' . $security->GetUserName()); $post->AddFieldString('UserMail', $security->GetUserMail()); $post->AddFieldString('IP', $_SERVER["REMOTE_ADDR"]); $post->AddFieldString('Browser', $browser); $post->AddFieldString('OS', $os); $post->AddFieldString('Action', $action); $post->AddFieldString('Description', $description); $post->AddFieldDateTime('DateTime', date('Y-m-d H:i:s')); $post->Execute(); } } ?>params = $_SESSION['mpy_dataSet']; //verifica se trouxe dados por post if($this->ExistParam('_post')){ $_POST = $this->GetParam('_post'); $this->DeleteParam('_post'); } } private function updateSession(){ $_SESSION['mpy_dataSet'] = $this->params; } /** * Adiciona (ou atualiza) parâmetro na Sessão * * @param string $name * @param string $value */ public function SetParam($name, $value){ $this->params[$name] = $value; $this->updateSession(); } /** * Verifica se parâmetro está declarado na sessão * * @param string $name * @return boolean */ public function ExistParam($name){ return ( (isset($this->params[$name])) && (!empty($this->params[$name])) ); } /** * Retorna parâmetro na Sessão * * @param string $name */ public function GetParam($name){ if($this->ExistParam($name)) return $this->params[$name]; else return null; } public function DeleteParam($name){ $n_params = array(); foreach ($this->params as $key=>$param) { if($key != $name) $n_params[$key] = $param; } $this->params = $n_params; $this->updateSession(); } } ?>title = $title; parent::__construct($orientacao, 'pt', $papel); } /** * Renderizar em formato PDF */ public function PreparePDF() { $this->SetDisplayMode(100); // Margens $this->lMargin = 10; $this->rMargin = 10; $this->tMargin = 10; $this->bMargin = 10; $this->cMargin = 1; $this->areaW = ($this->w - $this->lMargin - $this->rMargin); $this->SetAutoPageBreak(true, 30); $this->AddPage(); } /** * Fechar relatório */ public function RenderPDF($fileName = false, $dest = '') { if ($fileName === false) $this->Output(); else $this->Output($fileName, $dest); } /** * Cabeçalho */ public function Header() { global $cms; $height = 60; $this->SetXY($this->lMargin, $this->tMargin); // Logo $logo_w = 120; $this->RenderImage($cms->GetAdminImagePath() . 'logoPDF.jpg', $logo_w); $logo_w_sp = $logo_w + 8; // Parâmetros $this->SetXY($this->lMargin + $logo_w_sp, $this->tMargin); $info_w = 96; $param_w = ($this->w - $this->lMargin - $this->rMargin - $logo_w_sp - $info_w); // Linha 1 //$this->RenderText('ABC' . $this->title, $param_w, 'left', 'Arial, 18, B,#000000'); $this->SpaceW($param_w + 2); $this->RenderText('Pagina:', 40, 'right', 'Arial,8,B,#000000'); $this->SpaceW(2); $this->RenderText($this->PageNo(), 52, 'right'); $this->NewLine(0, $logo_w_sp); // Linha 2 //$this->RenderText('$this->rep->GetFilterText(1)', $param_w, 'left'); $this->SpaceW($param_w + 2); $this->RenderText('Data:', 40, 'right', 'Arial,8,B,#000000'); $this->SpaceW(2); $this->RenderText(date('d/m/Y'), 52, 'right'); $this->NewLine(0, $logo_w_sp); // Linha 3 //$this->RenderText('$this->rep->GetFilterText(2)', $param_w, 'left'); $this->SpaceW($param_w + 2); $this->RenderText('Hora:', 40, 'right', 'Arial,8,B,#000000'); $this->SpaceW(2); $this->RenderText(date('H:i:s'), 52, 'right'); $this->NewLine(0, $logo_w_sp); // Linha 4 //$this->RenderText('$this->rep->GetFilterText(3)', $param_w, 'left'); $this->SpaceW($param_w + 2); $this->RenderText('Doc:', 40, 'right', 'Arial,8,B,#000000'); $this->SpaceW(2); $this->RenderText($this->rep->code, 52, 'right'); $this->NewLine(0, 0); // Título $this->RenderText($this->title, ($this->w - $this->lMargin - $this->rMargin), 'center', 'Arial,14,B,#000000'); // Linha $top = ($this->tMargin + $height); $this->Line($this->lMargin, $top, ($this->w - $this->rMargin), $top); // Inicio dorelatorio $this->SetXY($this->lMargin, $top + 5); // Verificar se objeto implementa Header if ($this->objImp != null) { if (method_exists($this->objImp, 'Header')) $this->objImp->Header(); } } /** * Rodapé */ public function Footer() { global $_security; $top = $this->PageBreakTrigger; $this->Line($this->lMargin, $top, ($this->w - $this->rMargin), $top); $this->SetXY($this->lMargin, $top + 1); $col_w = (($this->w - $this->lMargin - $this->rMargin) / 2); $cols = array(); $cols[1] = $this->title; $cols[2] = $_security->userName; $this->RenderText($cols[1], $col_w, 'left'); $this->RenderText($cols[2], $col_w, 'right'); } /** * Escrever Texto * * @param unknown_type $param1 */ public function RenderText($text, $width = false, $align = 'left', $fonte = 'Arial,8,,#000000', $borda = false, $fundo = false) { // Fonte $this->SetFonte($fonte); // Alinhamento $n_align = array('left' => 'L', 'center' => 'C', 'right' => 'R'); $align = $n_align[$align]; // Height $height = $this->FontSize + (2 * $this->cMargin); // Bordas e cor da borda $border = $this->GetBorda($borda); // Cor de fundo $fundo = ($this->designer ? '#FFDDDD' : $fundo); $this->SetFundo($fundo); // Link $link = ''; // Descobrir largura if (($width === false) && ($text != '')) $width = ($this->GetStringWidth($text) + 2); // Tratar largura da string while (($this->GetStringWidth($text) > $width) && ($text != '')) $text = substr($text, 0, -1); // Quebra de linha automotica if (($this->autoBreakLine) && (($this->x + $width) > ($this->w - $this->rMargin))) $this->NewLine(); // Escrever $this->Cell($width, $height, utf8_decode($text), $border, 0, $align, ($fundo !== false), $link); // Retorno $info = array(); $info['width'] = $width; $info['height'] = $height; $info['x'] = $this->x; $info['y'] = $this->y; return $info; } /** * Adicionar espa�o horizontal * * @param integer $val */ public function SpaceW($val) { $this->SetXY($this->x + $val, $this->y); } /** * Adicionar espa�o vertical * * @param integer $val */ public function SpaceH($val) { $this->SetXY($this->x, $this->y + $val); } /** * Nova linha * * @param integer $spTop * @param integer $spLeft */ public function NewLine($spTop = 0, $spLeft = 0) { $this->y += ($this->lasth + $spTop); $this->x = ($this->lMargin + $spLeft); } /** * RenderImage * * @param unknown_type $param1 * @return unknown */ public function RenderImage($file, $img_w = 0, $img_h = 0) { $this->Image($file, null, null, $img_w, $img_h); } /** * Setar fonte * * @param string $fonte */ protected function SetFonte($fonte) { // Ex.: Arial,8,BIU,#000000 if ($fonte === false) return; $info = explode(',', $fonte); $this->SetFont($info[0], trim($info[2]), intval($info[1])); // Cor $c = $this->HexColor($info[3]); $this->SetTextColor($c['r'], $c['g'], $c['b']); } /** * Setar borda * * @param string $borda */ protected function GetBorda($borda) { // Ex.: S,S,S,S,#000000,1 if ($borda === false) return ''; $info = $this->GetBordaInfo($borda); $borda = ($info['left'] ? 'L' : ''); $borda .= ($info['right'] ? 'R' : ''); $borda .= ($info['top'] ? 'T' : ''); $borda .= ($info['bottom'] ? 'B' : ''); // Setar API de Borda $this->SetBordaApi($info); return $borda; } /** * Retorna informa��es da Borda * * @param string $borda */ public function GetBordaInfo($borda) { // Ex.: S,S,S,S,#000000,1 if ($borda === false) $borda = 'N,N,N,N,#000000,1'; $info = explode(',', $borda); $res = array(); $res['left'] = ($info[0] == 'S'); $res['right'] = ($info[1] == 'S'); $res['top'] = ($info[2] == 'S'); $res['bottom'] = ($info[3] == 'S'); $res['color'] = $info[4]; $res['width'] = intval($info[5]); return $res; } /** * Setar informa��es de Borda * * @param Array $info */ public function SetBordaApi($info) { // Cor $c = $this->HexColor($info['color']); $this->SetDrawColor($c['r'], $c['g'], $c['b']); // Largura //... } /** * Seta cor de fundo * * @param string $cor */ public function SetFundo($cor) { // Ex.: #000000 if ($cor === false) return; $c = $this->HexColor($cor); $this->SetFillColor($c['r'], $c['g'], $c['b']); } /** * Retorna o RGB de uma cor * * @param string $hexcor * @return Array */ public function HexColor($hexcolor) { if (strlen($hexcolor) != 7) { if ($hexcolor[0] != '#') $hexcolor = '#' . $hexcolor; } while (strlen($hexcolor) < 7) $hexcolor .= '0'; $res = array(); $res['r'] = hexdec(substr($hexcolor, 1, 2)); $res['g'] = hexdec(substr($hexcolor, 3, 2)); $res['b'] = hexdec(substr($hexcolor, 5, 2)); return $res; } } ?>title = $title; $this->message = $message; } public function RedirectPage(){ global $router; $msg_str = utf8_encode($this->title . '||' . $this->message); $msg_str = base64_encode($msg_str); header('location:' . $router->GetLink('msg/' . $msg_str)); } } ?>templateFile) ; } function printPageStyleSheet(){ global $page, $cms; $styles = str_replace(',', ';', $page->fileStyleSheet); $styles = explode(';', $styles); foreach ($styles as $styles) { $file = $cms->GetFrontStyleSheetUrl() . trim($styles); print('' . "\r\n"); } } function printPageJavaScript(){ global $page, $cms; $scripts = str_replace(',', ';', $page->fileJavaScript); $scripts = explode(';', $scripts); foreach ($scripts as $script) { $file = $cms->GetFrontJavaScriptUrl() . trim($script); print('' . "\r\n"); } } function printWidgets($placeHolders){ global $db, $cms, $page, $hub, $site, $MODULES_URL, $MODULES_PATH, $router; $sql = 'SELECT cmsPageContents.Parameters, cmsWidgets.File WidgetFile FROM cmsPageContents'; $sql .= ' LEFT JOIN cmsPlaceHolders ON(cmsPlaceHolders.ID = cmsPageContents.PlaceHolder)'; $sql .= ' LEFT JOIN cmsWidgets ON(cmsWidgets.ID = cmsPageContents.Widget)'; $sql .= " WHERE Page = " . $page->id . " AND cmsPlaceHolders.Name = '$placeHolders'"; $sql .= " ORDER BY `Order` ASC"; $widgets = $db->LoadObjects($sql); foreach ($widgets as $widget) { $x = $widget->Parameters; $x = explode("\n", $x); $params = array(); foreach ($x as $values) { $value = explode('=', $values); $params[trim(utf8_encode($value[0]))] = trim(utf8_encode($value[1])); } include($MODULES_PATH . $widget->WidgetFile); } } /** * Retorna Registro */ function LoadRecord($tableName, $id){ global $db; $sql = 'SELECT * FROM `' . $tableName . '` WHERE ID = ' . $id; $res = $db->LoadObjects($sql); return $res[0]; } ?> 1) $nlink = $link . '-' . $num; else $nlink = $link; $sql = "SELECT * FROM `$tableName` WHERE $fieldName = '$nlink'"; if($id > 0) $sql .= ' AND ID <> ' . $id; $res = $db->LoadObjects($sql); if(count($res) > 0){ return ValidaLinkAmigavel($tableName, $link, $fieldName, $num+1, $id); } else return $nlink; } ?>