'\1es', # search, switch, fix, box, process, address '/series$/' => '\1series', '/([^aeiouy]|qu)ies$/' => '\1y', '/([^aeiouy]|qu)y$/' => '\1ies', # query, ability, agency '/(?:([^f])fe|([lr])f)$/' => '\1\2ves', # half, safe, wife '/sis$/' => 'ses', # basis, diagnosis '/([ti])um$/' => '\1a', # datum, medium '/person$/' => 'people', # person, salesperson '/man$/' => 'men', # man, woman, spokesman '/child$/' => 'children', # child '/(.+)status$/' => '\1statuses', '/s$/' => 's', # no change (compatibility) '/$/' => 's' ); private static $singular_rules = array( '/(x|ch|ss)es$/' => '\1', '/movies$/' => 'movie', '/series$/' => 'series', '/([^aeiouy]|qu)ies$/' => '\1y', '/([lr])ves$/' => '\1f', '/([^f])ves$/' => '\1fe', '/(analy|ba|diagno|parenthe|progno|synop|the)ses$/' => '\1sis', '/([ti])a$/' => '\1um', '/people$/' => 'person', '/men$/' => 'man', '/(.+)status$/' => '\1status', '/children$/' => 'child', '/news$/' => 'news', '/s$/' => '' ); /** * Muda o select da query * @param String select, por ex: "nome, sobrenome" * @example select('nome,sobrenome') */ public function select($select){ $this->select = $select; return $this; } /** * Muda o where da query * @param String where * @example where('nome='joão' and sobrenome='da silva') */ public function where($where){ $this->where = $where; return $this; } /** * Muda o group da query * @param String * @example group('by nome') */ public function group($group){ $this->group = $group; return $this; } /** * Muda o order da query * @param String order * @example order('nome asc') */ public function order($order){ $this->order = $order; return $this; } /** * Muda o limit da query * @param String limit * @example limit('0,20') */ public function limit($limit){ $this->limit = $limit; return $this; } /** * Adiciona Join a query * @param String table, Sring type * @example join('profiles','left') */ public function join($table, $type){ $this->join = strtoupper($type)." JOIN ".$table; return $this; } /** * Adiciona On a query(precisa ser usado com join) * @param String on * @example on(tabela1.idUser = tabela2.idUser) */ public function on($on){ $this->on = "ON ".$on; return $this; } /** * Adiciona from a query * @param String from * @example from(tabela1) */ public function from($from){ $this->from = $from; return $this; } /** * Adiciona from a query * @param String from * @example from(tabela1) */ public function having($having){ $this->having = " HAVING ".$having; return $this; } /** * Construtor da classe, cria uma conexao com o banco de dados */ public function __construct(){ $this->config(); (!$this->tableName) ? $this->tableName = $this->pluralize(strtolower(get_class($this))) : $this->tableName = $this->tableName; //define table name (!$this->tableId) ? $this->tableId = "id". ucwords($this->singularize($this->tableName)) : $this->tableId = $this->tableId; //define table id name try{ if(!self::$dbConnection){ self::$dbConnection = new PDO("mysql:host={$this->dbHost};dbname={$this->dbName}", $this->dbUser, $this->dbPassword); self::$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); } } catch (PDOException $e){ print "erro : " . $e->getMessage() . "
"; die(); } }//end construct /** * Dentro dessa função sao feitas configurações, como mudar o nome da tabela e seu id */ public function config(){ } /** * Muda o nome de uma tabela, é usada dentro da função config no model * @param String id da tabela */ protected function set_table_name($tableName){ $this->tableName = $tableName; } /** * Muda o nome do id da tabela, é usada dentro da função config no model * @param String nome da tabela */ protected function set_table_id($tableId){ $this->tableId = $tableId; } /** * Retorna o nome do id de uma tabela * @param String nome da tabela no plural ou singular * @return mome do id da tabela */ public function getTableId($tableName){ $tableName = $this->singularize(ucwords($tableName)); return "id".$tableName; } // ################################################################# // MÉTODOS MÁGICOS : public function __set($field, $value){ $this->tableFields[$field] = $value; } public function __get($field){ return $this->tableFields[$field]; } public function __call($method, $args){ /*######## FIND ALL BY ###########################*/ if (substr($method,0,11) === 'find_all_by') { $rawExp = substr($method,12); $where = $this->build_where($rawExp); return $this->find_by('find_all', $where, $args); } /*######## FIND BY ###########################*/ elseif(substr($method,0,7) === 'find_by') { $rawExp = substr($method,8); $where = $this->build_where($rawExp); return $this->find_by('find_all', $where, $args); } /*######## USING JOIN ###########################*/ elseif(substr($method,-4, strlen($method)) == 'join'){ $joinType = substr($method, 0, strlen($method)-4); $joinType = str_replace("_", " ", $joinType); $this->join($args[0], $joinType); return $this; } /*######## DELETE BY ###########################*/ elseif(substr($method,0,9) === 'delete_by') { $rawExp = substr($method,10); $this->select(null); $this->where($this->build_where($rawExp)); $this->args = $args; return $this->delete(); } }//end call // ################################################################# /** * Deleta um registro * @access public. * @param Array args * @param String rawExp (string no formato algo_assim) * @return resultset or false. */ public function delete($id=null){ if($id){ $this->where("$this->tableId = ?"); $this->args[0] = $id; } $query = $this->build_delete(); $return = $this->execute_delete($query, $this->args); return $return; }//end delete /** * Controi a expressao de delete * @access private. * @return string. */ private function build_delete(){ $this->where = ($this->where) ? "WHERE ".$this->where : null; return "DELETE FROM $this->tableName $this->where"; }//end build_delete /** * Realiza prepared query para deletar * @access public. * @param String query * @param Array args * @return resultset or false. */ public function execute_delete($query, $args=null){ if($args){ if(!is_array($args)) $args = array('0'=>$args); }else{ $args = array('0'=>'0'); } $sth = self::$dbConnection->prepare($query); $return = $sth->execute($args); if($return){ return true; }else{ return false; } }//end executeDelete /** * Constroi o where baseado numa expressao algo_and_algo * @param String rawExp (string no formato algo_assim) * @return resultset or false. */ private function build_where($where) { $where= preg_split('/(_and_|_or_)/i',$where,-1,PREG_SPLIT_DELIM_CAPTURE); $return = null; for($i=0;$itableName.".".$where[$i].' = ? '; else $return .= str_replace('_', '', $where[$i]).' '; } return $return; } public function find($args){ //retira o excesso de espaços em branco //$args = func_get_args(); //$toFind = $args[0]; //$args = preg_replace('/s+/', ' ', $args[1], 0); //$options = explode("|", $args); //$toFind = $options[0]; //array_shift($options); //$findType = preg_split('/(first by|last by|all|first|last|by)/i',$toFind,-1,PREG_SPLIT_DELIM_CAPTURE); //find first, last, all, id switch($args){ case 'last': $this->order = "$this->tableName.$this->tableId DESC"; $this->limit = "0,1"; break; case 'first': $this->order = "$this->tableName.$this->tableId ASC"; $this->limit = '0,1'; break; case 'all': $this->limit = null; break; default: $this->where = "$this->tableName.$this->tableId = ?"; $this->limit = "0,1"; $this->args[] = $args; break; }//end switch // se tiver mais opções /* if($options) foreach($options as $option){ $temp = null; $temp = explode(":", $option); $method = trim($temp[0]); $this->{$method}($temp[1]); } */ //endfor return $this; }//end find /** * Conta valores de uma pesquisa * @param String (por ex: "* as total") * @return object. */ public function count($field){ $field = strtolower($field); $field = explode('as',$field); $this->select = "COUNT($field[0]) AS $field[1]"; return $this; }//end count private function find_by($type, $where, $args){ //find first, last, all, id switch($type){ case 'find_all': $this->order = "$this->tableName.$this->tableId DESC"; $this->where = $where; break; case 'find': $this->order = "$this->tableName.$this->tableId ASC"; $this->where = $where; $this->limit = '0,1'; break; default: die('error'); break; }//end switch $this->args = $args; return $this; }//end find_by /** * Controi a expressao de select * @return string. */ private function build_select(){ $this->limit = ($this->limit) ? "LIMIT ".$this->limit : null; $this->where = ($this->where) ? "WHERE ".$this->where : null; $this->order = ($this->order) ? "ORDER BY ".$this->order : null; $this->operation = "SELECT"; $query = "$this->operation $this->select FROM $this->tableName $this->join $this->on $this->where $this->group $this->having $this->order $this->limit"; return $query; }//end build_select /** * Retorna um array com os resultados deuma busca * @return array. */ public function toArray(){ $query = $this->build_select(); $args = $this->args; $this->clear_properties(); return $this->execute_select($query, $args); }//end to array /** * Escreve na tela uma tabela com os resultados de uma busca * @return Table. */ public function toTable(){ $result = $this->toArray(); echo "
"; if($result){ $colunas = array_keys($result[0]); echo ""; foreach($colunas as $coluna){ echo ""; } echo ""; for($i=0; $i"; foreach($colunas as $coluna){ echo ""; } echo ""; }//endfor } echo "
"; echo $coluna; echo "
"; if($result[$i][$coluna]) echo $result[$i][$coluna]; else echo "null"; echo "
"; $this->clear_properties(); }// end toTable /** * Retorna uma consulta no formato json * @return json array or false. */ public function toJson(){ $return = $this->toArray(); if($return){ $return = $this->array2json($return); $return2 = str_replace("\r\n","
",trim($return)); return $return2; }else{ return false; } /* die(); try { $return = json_encode($return2); echo $return; } catch (Exception $e) { require 'json.php'; $json = new Services_JSON(); $return = $json->encode($return); } */ }//end toJson //função temporaria q transforma array em json, sem problemas de encode public function array2json($arr) { $parts = array(); $is_list = false; //Find out if the given array is a numerical array $keys = array_keys($arr); $max_length = count($arr)-1; if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1 $is_list = true; for($i=0; $i$value) { if(is_array($value)) { //Custom handling for arrays if($is_list) $parts[] = $this->array2json($value); /* :RECURSION: */ else $parts[] = '"' . $key . '":' . $this->array2json($value); /* :RECURSION: */ } else { $str = ''; if(!$is_list) $str = '"' . $key . '":'; //Custom handling for multiple data types if(is_numeric($value)) $str .= $value; //Numbers elseif($value === false) $str .= 'false'; //The booleans elseif($value === true) $str .= 'true'; else $str .= '"' . addslashes($value) . '"'; //All other things // :TODO: Is there any more datatype we should be in the lookout for? (Object?) $parts[] = $str; } } $json = implode(',',$parts); if($is_list) return '[' . $json . ']';//Return numerical JSON return '{' . $json . '}';//Return associative JSON } /** * Retorna uma consulta no formato xml * @return json array or false. */ public function toXML(){ $return = $this->toArray(); if($return){ require_once 'xml.Class.php'; $return = ArrayToXML::toXml($return,"data"); return $return; }else return $false; } /** * Limpa as propridades usadas em consultas, para evitar conflitos */ private function clear_properties(){ $this->where = null; $this->select = "*"; $this->group = null; $this->order = null; $this->limit = null; $this->from = null; $this->having = null; $this->method = null; $this->join = null; $this->on = null; $this->args = null; }//end clear_properties /** * Realiza prepared query * @access public. * @param String query * @param Array args * @return resultset or false. */ public function execute_select($query, $args=null){ $sth = self::$dbConnection->prepare($query); $sth->execute($args); $result = $sth->fetchAll(PDO::FETCH_ASSOC); $this->clear_properties(); if($result){ return $result; }else{ return false; } }//end select public function getConnection(){ return self::$dbConnection; } /** * salva um registro na tabela * @access public. * @return lastInsertId or false. */ public function save(){ $this->before_save(); unset($this->tableFields[$this->tableId]);//retira o tableId, ele nao pode ser salvo! $fields = implode(",",array_keys($this->tableFields)); $values = implode(",:",array_keys($this->tableFields)); $sql = "INSERT INTO ".$this->tableName." (".$fields.") VALUES (:".$values.")"; $sth = self::$dbConnection->prepare($sql); if($sth->execute($this->tableFields)){ $this->clear_properties(); return self::$dbConnection->lastInsertId(); }else return false; }//end save /** * realiza update na tabela * @access public. * @param Int id * @return true or false. */ public function update($id=null){ ($id) ? true : $id = $this->{$this->tableId}; $this->where = ($id) ? $this->tableId." = ".$id : $this->where; $fields = array(); foreach ($this->tableFields as $key => $value) { if($key != $this->tableId){ $fields[] = $key." = ?"; $values[] = $value; } } $fields= implode(", ",$fields); $sql = "UPDATE ".$this->tableName." SET ".$fields." WHERE $this->where"; $sth = self::$dbConnection->prepare($sql); $this->clear_properties(); if($sth->execute($values)) return true; else return false; } /** * transforma uma palavra para o plural * @access public. * @param String word * @return word pluralized. */ protected function pluralize($word) { $original = $word; foreach(self::$plural_rules as $rule => $replacement) { $word = preg_replace($rule,$replacement,$word); if($original != $word) break; } return $word; } /** * transforma uma palavra para o singular * @access public. * @param String word * @return word singularized. */ protected function singularize($word) { $original = $word; foreach(self::$singular_rules as $rule => $replacement) { $word = preg_replace($rule,$replacement,$word); if($original != $word) break; } return $word; } public function before_save(){ } }//end class ?>has_many = array('ads'); //$this->set_table_name('marias'); } function truncate($str, $maxlen) { if ( strlen($str) <= $maxlen ) return $str; $newstr = substr($str, 0, $maxlen); if ( substr($newstr,-1,1) != ' ' ) $newstr = substr($newstr, 0, strrpos($newstr, " ")); return $newstr; } } ?>has_many = array('ads'); //$this->set_table_name('marias'); } function truncate($str, $maxlen) { if ( strlen($str) <= $maxlen ) return $str; $newstr = substr($str, 0, $maxlen); if ( substr($newstr,-1,1) != ' ' ) $newstr = substr($newstr, 0, strrpos($newstr, " ")); return $newstr; } } ?>has_many = array('ads'); //$this->set_table_name('marias'); } function truncate($str, $maxlen) { if ( strlen($str) <= $maxlen ) return $str; $newstr = substr($str, 0, $maxlen); if ( substr($newstr,-1,1) != ' ' ) $newstr = substr($newstr, 0, strrpos($newstr, " ")); return $newstr; } } ?>css_class = $css_class; } public function get_begin(){ if (!isset($this->current_page)) $this->current_page = 1; else $this->current_page = $this->current_page; $this->offset= $this->itens_per_page; //itens por página $this->begin = $this->current_page - 1; $this->begin = $this->offset * $this->begin; return $this->begin; }//end get_begin public function get_offset(){ if (!isset($this->current_page)) $this->current_page = 1; else $this->current_page = $this->current_page; $this->offset= $this->itens_per_page; //itens por página $this->begin = $this->current_page - 1; $this->begin = $this->offset * $this->begin; return $this->offset; }//end get_offset public function write(){ if(!$this->url) $this->url = parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH); if($this->total) { echo " "; } }//end write public function write_inverse(){ if(!$this->url) $this->url = parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH); if($this->total) { echo " "; } }//end write inverse public function write_prev_next(){ if(!$this->url) $this->url = parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH); if($this->total) { echo " "; } }//end write public function write_next($label='Próxima'){ if(!$this->url) $this->url = parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH); if($this->total) { echo " "; } }//end write public function set_url($url){ $this->url = $url; } public function set_itens_per_page($itens_per_page){ $this->itens_per_page = $itens_per_page; } public function set_current_page($current_page){ //if(!is_int($current_page)) if($current_page === "") $this->current_page = null; else $this->current_page = $current_page; } public function set_url_vars($url_vars){ $this->url_vars = $url_vars; } public function example(){ print '

Código de exemplo do paginator:

//configurações:
$paginator = new Paginator(); //cria o objeto
$paginator->set_itens_per_page(1); //itens mostrados por página
$paginator->set_current_page($_GET[\'p\']); //variável da pagina corrente
$paginator->set_css_class(\'paginator\'); //classe css da ul do paginator
$paginator->set_url_vars("&nome=felipe&sobreome=joão"); //variaveis adicionais
$paginator->set_url(\'list.fotos.php\'); //url dos numeros do paginator, por default é a pagina atual

$total = $foto->count(\'* as total\')->toArray();
$paginator->total = $total[0][\'total\']; //total de itens da query

//seleciona os registros, usamos $paginator->get_begin() e $paginator->get_offset():
if ($paginator->total){

$fotos = $foto->find(\'all\')->order(\'idFoto DESC\')->limit($paginator->get_begin().",".$paginator->get_offset())->toArray();

} else

fotos = false;

//e finalmente escrevemos o paginator:
$paginator->write(); '; die(); } }//end class ?> decode($twitter_json); } public function get_posts_by_user($user, $limit){ $url = "http://twitter.com/statuses/user_timeline/".$user.".rss?count=".$limit; @$xml = simplexml_load_file($url); //print_r($xml); $return = array(); if ($xml == false) { $return = false; } else{ foreach($xml->channel->item as $node){ $item = array(); $item['title'] = utf8_decode($node->title); $item['description'] = utf8_decode(str_replace("Deputado_Jean:","",$node->description)); $item['pubDate'] = $node->pubDate; $item['guid'] = utf8_decode($node->guid); $item['link'] = utf8_decode($node->link); $data = explode(' ',$node->pubDate); $item['day'] = $data[1]; $item['month'] = $data[2]; $item['year'] = $data[3]; $return[] = $item; } } return $return; } }//end class ?>