--- /dev/null
+<?\r
+class Busca{\r
+ var $arr_alfabeto;\r
+ var $arr_resultado;\r
+ var $arr_ordenar;\r
+ function Busca(){\r
+ $this->arr_alfabeto = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','W');\r
+ $this->arr_resultado = array('08','16');\r
+ $this->arr_ordenar = array('Nome','Sistema','Patologia');\r
+ }\r
+ \r
+ \r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Busca{\r
+ var $busca;\r
+\r
+ function Busca($tmp_busca = ""){\r
+ // $this->busca = $tmp_busca;\r
+ // $this->somaBusca($tmp_busca);\r
+ }\r
+ function findPalavraAproximada($palavra, $sql = ""){\r
+ global $db;\r
+ global $load;\r
+ \r
+ $load->system("functions/text.php");\r
+ \r
+ $min = 55;\r
+ $mid = 80;\r
+ \r
+ $arr_busca = explode(' ',$palavra);\r
+ $arr_palavras = array();\r
+ if($sql == "")\r
+ $sql = "SELECT palavra FROM site_palavra WHERE status = 1";\r
+ $rs = $db->execute($sql);\r
+ while(!$rs->EOF){\r
+ $arr_now = explode(" ",$rs->fields("palavra"));\r
+ if(is_array($arr_now)) {\r
+ for($x=0,$total=sizeof($arr_now);$x<$total;$x++){\r
+ $arr_palavras[] = formatNameFile($arr_now[$x]);\r
+ }\r
+ } else {\r
+ $arr_palavras[] = formatNameFile($arr_now);\r
+ }\r
+ $rs->moveNext();\r
+ }\r
+ $arr_palavras = array_values(array_unique($arr_palavras));\r
+ $arr = array(array());\r
+ \r
+ $porcentagem = 0;\r
+ \r
+ // BUSCA TODA A PALAVRA\r
+ for($x=0,$total=sizeof($arr_palavras);$x<$total;$x++){\r
+ similar_text($palavra,$arr_palavras[$x],$r);\r
+ if ($r > $min) {\r
+ if ($r >= $mid) {\r
+ if ($porcentagem < $mid) {\r
+ $arr[0] = array();\r
+ }\r
+ }\r
+ \r
+ if ($porcentagem < $r) {\r
+ $porcentagem = $r;\r
+ $arr[0][] = $arr_palavras[$x];\r
+ }\r
+ }\r
+ }\r
+ \r
+ if (sizeof($arr_busca) > 1) {\r
+ $indice = 1;\r
+ //echo sizeof($arr_busca);\r
+ for ($x=0,$total=sizeof($arr_busca);$x<=$total;$x++) {\r
+ $porcentagem = 0;\r
+ //echo $x." - ".$total."<br>";\r
+ if(isset($arr_busca[$x])){\r
+ if (strlen($arr_busca[$x]) > 2) {\r
+ for($z=0,$total=sizeof($arr_palavras);$z<$total;$z++){\r
+ similar_text($arr_busca[$x],$arr_palavras[$z],$r);\r
+ if ($r > $min) {\r
+ if ($r >= $mid) {\r
+ if ($porcentagem < $mid) {\r
+ $arr[$indice] = array();\r
+ }\r
+ }\r
+ \r
+ if ($porcentagem < $r) {\r
+ $porcentagem = $r;\r
+ $arr[$indice][] = $arr_palavras[$z];\r
+ }\r
+ }\r
+ }\r
+ $indice++;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ \r
+ return $arr; \r
+ }\r
+ function makeSql($arrPalavra,$baseSql,$arrWherePalavra,$fixedWhere = ""){\r
+ //arrPalavra:\r
+ //Array com as palavras aproximadas. Lembrando, posição 0, array de palavras completas (frases, titulos), posição 1, todas as palavras 'quebradas'.\r
+ \r
+ //baseSql:\r
+ //Sql contendo todo o conteudo necessario para fazer a busca naquela tabela, no lugar da sentença WHERE, subtituir por #WHERE#, como no exemplo:\r
+ //SELECT id,nome,titulo,descricao,data FROM site_redacao r INNER JOIN site_teste t ON t.id = r.id_teste #WHERE# ORDER BY data DESC\r
+ \r
+ //arrWherePalavra:\r
+ //array com as condições, sem o where, e substituindo a palavra de busca por #PALAVRA#, como no exemplo:\r
+ //p.descricao LIKE '%#PALAVRA#%'\r
+ \r
+ //$fixedWhere:\r
+ //condições fixas a serem concatenadas com a query, como no exemplo:\r
+ //status = 1 AND data = '2009-10-20'\r
+ //note que não existe operador em nenhum dos lados (AND, OR, ou qualquer outro)\r
+ \r
+ if (isset($arrPalavra[0])) {\r
+ if ($arrPalavra[0] != '') {\r
+ $where = " AND (1=2 ";\r
+ for($x=0,$total=sizeof($arrPalavra[0]);$x<$total;$x++) {\r
+ $where .= " OR (";\r
+ for($w=0,$totalW=sizeof($arrWherePalavra);$w<$totalW;$w++){\r
+ if($w == 0){\r
+ $where .= " ".str_replace("#PALAVRA#",$arrPalavra[0][$x],$arrWherePalavra[$w])." ";\r
+ } else {\r
+ $where .= " OR ".str_replace("#PALAVRA#",$arrPalavra[0][$x],$arrWherePalavra[$w])." ";\r
+ }\r
+ }\r
+ $where .= " )";\r
+ }\r
+ $where .= ") ";\r
+ } else {\r
+ $where = 'AND 1=2';\r
+ }\r
+ } elseif(isset($arrPalavra[1])) {\r
+ $where = '';\r
+ for($i=1,$total=sizeof($arrPalavra);$i<=$total;$i++) {\r
+ $where .= " AND ((1=2) ";\r
+ for($x=0,$total=sizeof($arrPalavra[$i]);$x<=$total;$x++) {\r
+ if ($arrPalavra[$i][$x] != '') {\r
+ $where .= " OR (";\r
+ for($w=0,$totalW=sizeof($arrWherePalavra);$w<$totalW;$w++){\r
+ if($w == 0){\r
+ $where .= " ".str_replace("#PALAVRA#",$arrPalavra[$i][$x],$arrWherePalavra[$w])." ";\r
+ } else {\r
+ $where .= " OR ".str_replace("#PALAVRA#",$arrPalavra[$i][$x],$arrWherePalavra[$w])." ";\r
+ }\r
+ }\r
+ $where .= " )";\r
+ }\r
+ }\r
+ }\r
+ $where .= ") ";\r
+ }\r
+ if($fixedWhere == ""){\r
+ $fixedWhere = " 1 = 1 ";\r
+ } else {\r
+ $fixedWhere = " ".$fixedWhere." ";\r
+ }\r
+ $sql = str_replace("#WHERE#"," WHERE ".$fixedWhere.$where,$baseSql);\r
+ return $sql;\r
+ }\r
+ function findComplexAgenda($arrPalavra){\r
+ global $db;\r
+ $fixedWhere = "a.status = 1";\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "a.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "a.descricao like '%#PALAVRA#%'";\r
+ $arrWhere[] = "a.ingresso like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "c.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.site like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.endereco like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.numero like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.bairro like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT a.id,\r
+ CAST(a.data as DATE) as data,\r
+ if(strcmp(a.id_estabelecimento, 0), e.nome, a.outroestabelecimento) as nome, \r
+ a.nome as festa\r
+ FROM site_agenda a \r
+ LEFT OUTER JOIN site_estabelecimento e ON e.id = a.id_estabelecimento \r
+ LEFT OUTER JOIN global_estado es ON es.id = e.id_estado \r
+ LEFT OUTER JOIN global_cidade c ON c.id = e.id_cidade \r
+ LEFT OUTER JOIN site_agenda_genero ag ON ag.id_agenda = a.id \r
+ #WHERE#\r
+ GROUP BY a.id ORDER BY a.data ASC";\r
+ \r
+ return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function findComplexRedacao($arrPalavra){\r
+ global $db;\r
+ $fixedWhere = "status = 1";\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "descricao like '%#PALAVRA#%'";\r
+ $arrWhere[] = "titulo like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT id,nome,titulo,descricao,data FROM site_redacao #WHERE# ORDER BY data DESC";\r
+ \r
+ return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function findComplexFoto($arrPalavra){\r
+ global $db;\r
+ $fixedWhere = "g.status = 1";\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "e.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "f.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "g.outraagenda like '%#PALAVRA#%'";\r
+ $arrWhere[] = "a.nome like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT g.id,e.nome as estabelecimento,a.nome as festa,a.data as data, f.nome as fotografo \r
+ FROM site_galeria g LEFT OUTER JOIN site_estabelecimento e ON e.id = g.id_estabelecimento \r
+ LEFT OUTER JOIN site_agenda a ON a.id_estabelecimento = g.id_estabelecimento \r
+ LEFT OUTER JOIN site_fotografo f ON f.id = g.id_fotografo \r
+ #WHERE#\r
+ ORDER BY data DESC ";\r
+ \r
+ return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function findComplexArtista($arrPalavra){\r
+ global $db;\r
+ $fixedWhere = "a.status = 1";\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "a.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "g.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "a.nomeoutraagencia like '%#PALAVRA#%'";\r
+ $arrWhere[] = "a.descricao like '%#PALAVRA#%'";\r
+ $arrWhere[] = "age.nome like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT DISTINCT(a.id),a.nome\r
+ FROM (site_artista a \r
+ LEFT OUTER JOIN site_cadastro_artista ca ON(a.id=ca.id_artista) \r
+ LEFT OUTER JOIN site_artista_genero ag ON(a.id=ag.id_artista)\r
+ LEFT OUTER JOIN site_genero g ON(g.id=ag.id_genero)\r
+ LEFT OUTER JOIN site_agencia age ON(age.id=a.id_agencia)) \r
+ #WHERE#\r
+ GROUP BY a.id ";\r
+ \r
+ return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function findComplexEstabelecimento($arrPalavra){\r
+ global $db;\r
+ $fixedWhere = "e.status = 1";\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "e.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.nomeabreviado like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.endereco like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.numero like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.bairro like '%#PALAVRA#%'";\r
+ $arrWhere[] = "e.descricao like '%#PALAVRA#%'";\r
+ $arrWhere[] = "c.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "es.nome like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT e.id,e.nome FROM (site_estabelecimento e \r
+ LEFT OUTER JOIN site_cadastro_estabelecimento ce ON(ce.id_estabelecimento=e.id) \r
+ LEFT OUTER JOIN global_cidade c ON(e.id_cidade=c.id) \r
+ LEFT OUTER JOIN global_estado es ON(c.id_estado=es.id)) \r
+ #WHERE#\r
+ GROUP BY e.id ORDER BY e.nome ASC";\r
+ \r
+ return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function findSimpleAgenda($tmp_busca = ""){\r
+ if($tmp_busca == ""){\r
+ $tmp_busca = $this->busca;\r
+ }\r
+ \r
+ global $db;\r
+ \r
+ $sql = "SELECT a.id,\r
+ CAST(a.data as DATE) as data,\r
+ if(strcmp(a.id_estabelecimento, 0), e.nome, a.outroestabelecimento) as nome, \r
+ a.nome as festa\r
+ FROM site_agenda a \r
+ LEFT OUTER JOIN site_estabelecimento e ON e.id = a.id_estabelecimento \r
+ LEFT OUTER JOIN global_estado es ON es.id = e.id_estado \r
+ LEFT OUTER JOIN global_cidade c ON c.id = e.id_cidade \r
+ LEFT OUTER JOIN site_agenda_genero ag ON ag.id_agenda = a.id \r
+ WHERE a.status = 1 AND\r
+ (a.nome like '%".$tmp_busca."%'\r
+ OR a.descricao like '%".$tmp_busca."%'\r
+ OR a.ingresso like '%".$tmp_busca."%'\r
+ OR e.nome like '%".$tmp_busca."%'\r
+ OR c.nome like '%".$tmp_busca."%'\r
+ OR e.site like '%".$tmp_busca."%'\r
+ OR e.endereco like '%".$tmp_busca."%'\r
+ OR e.numero like '%".$tmp_busca."%'\r
+ OR e.bairro like '%".$tmp_busca."%')\r
+ GROUP BY a.id ORDER BY a.data ASC";\r
+ return $db->execute($sql);\r
+ }\r
+ function findSimpleRedacao($tmp_busca = ""){\r
+ if($tmp_busca == ""){\r
+ $tmp_busca = $this->busca;\r
+ }\r
+ \r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome,titulo,descricao,data FROM site_redacao WHERE status = 1 AND ((nome LIKE '%".$tmp_busca."%') OR (titulo LIKE '%".$tmp_busca."%') OR (descricao LIKE '%".$tmp_busca."%')) ORDER BY data DESC";\r
+ return $db->execute($sql);\r
+ }\r
+ function findSimpleFoto($tmp_busca = ""){\r
+ if($tmp_busca == ""){\r
+ $tmp_busca = $this->busca;\r
+ }\r
+ \r
+ global $db;\r
+ \r
+ $sql = "SELECT g.id,e.nome as estabelecimento,a.nome as festa,a.data as data, f.nome as fotografo \r
+ FROM site_galeria g LEFT OUTER JOIN site_estabelecimento e ON e.id = g.id_estabelecimento \r
+ LEFT OUTER JOIN site_agenda a ON a.id_estabelecimento = g.id_estabelecimento \r
+ LEFT OUTER JOIN site_fotografo f ON f.id = g.id_fotografo \r
+ WHERE g.status = 1 AND (\r
+ e.nome like '%".$tmp_busca."%'\r
+ OR f.nome like '%".$tmp_busca."%'\r
+ OR g.outraagenda like '%".$tmp_busca."%'\r
+ OR a.nome like '%".$tmp_busca."%'\r
+ )\r
+ ORDER BY data DESC ";\r
+ return $db->execute($sql);\r
+ }\r
+ function findSimpleArtista($tmp_busca = ""){\r
+ if($tmp_busca == ""){\r
+ $tmp_busca = $this->busca;\r
+ }\r
+ \r
+ global $db;\r
+ \r
+ $sql = "SELECT DISTINCT(a.id),a.nome\r
+ FROM (site_artista a \r
+ LEFT OUTER JOIN site_cadastro_artista ca ON(a.id=ca.id_artista) \r
+ LEFT OUTER JOIN site_artista_genero ag ON(a.id=ag.id_artista)\r
+ LEFT OUTER JOIN site_genero g ON(g.id=ag.id_genero)\r
+ LEFT OUTER JOIN site_agencia age ON(age.id=a.id_agencia)) \r
+ WHERE a.status=1 AND (\r
+ a.nome like '%".$tmp_busca."%'\r
+ OR g.nome like '%".$tmp_busca."%'\r
+ OR a.nomeoutraagencia like '%".$tmp_busca."%'\r
+ OR a.descricao like '%".$tmp_busca."%'\r
+ OR age.nome like '%".$tmp_busca."%'\r
+ )\r
+ GROUP BY a.id ";\r
+ return $db->execute($sql);\r
+ }\r
+ function findSimpleEstabelecimento($tmp_busca = ""){\r
+ if($tmp_busca == ""){\r
+ $tmp_busca = $this->busca;\r
+ }\r
+ \r
+ global $db;\r
+ \r
+ $sql = "SELECT e.id,e.nome FROM (site_estabelecimento e \r
+ LEFT OUTER JOIN site_cadastro_estabelecimento ce ON(ce.id_estabelecimento=e.id) \r
+ LEFT OUTER JOIN global_cidade c ON(e.id_cidade=c.id) \r
+ LEFT OUTER JOIN global_estado es ON(c.id_estado=es.id)) \r
+ WHERE e.status = 1 AND (\r
+ e.nome like '%".$tmp_busca."%'\r
+ OR e.nomeabreviado like '%".$tmp_busca."%'\r
+ OR e.endereco like '%".$tmp_busca."%'\r
+ OR e.numero like '%".$tmp_busca."%'\r
+ OR e.bairro like '%".$tmp_busca."%'\r
+ OR e.descricao like '%".$tmp_busca."%'\r
+ OR c.nome like '%".$tmp_busca."%'\r
+ OR es.nome like '%".$tmp_busca."%'\r
+ ) GROUP BY e.id ORDER BY e.nome ASC";\r
+ return $db->execute($sql);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class CasoEstudo{\r
+ //opções de listagem\r
+ var $arr_alfabeto;\r
+ var $arr_alfabeto_casoestudo;\r
+ var $arr_resultado;\r
+ var $arr_ordenar;\r
+ \r
+ //filtro - session\r
+ var $filtro_palavra;\r
+ var $filtro_procedencia;\r
+ var $filtro_sistema;\r
+ var $filtro_patologia;\r
+ var $filtro_alfabeto;\r
+ var $filtro_ordenar;\r
+ var $filtro_resultado;\r
+ \r
+ function CasoEstudo(){\r
+ $this->arr_alfabeto = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','W');\r
+ $this->arr_resultado = array('08','16','32');\r
+ $this->arr_ordenar = array('Nome','Especialidade');\r
+ $this->getFiltrosFromSession();\r
+ }\r
+ function setAlfabetoCasoEstudo() {\r
+ global $input;\r
+ \r
+ if ($input->session('session_letras_casoestudo') != '') {\r
+ $this->arr_alfabeto_casoestudo = unserialize($input->session('session_letras_casoestudo'));\r
+ if($this->arr_alfabeto_casoestudo == ''){\r
+ $this->arr_alfabeto_casoestudo = array();\r
+ }\r
+ } else {\r
+ $rowsLetra = $this->findLetraCasoEstudo();\r
+ $this->arr_alfabeto_casoestudo = array();\r
+ while (!$rowsLetra->EOF) {\r
+ $this->arr_alfabeto_casoestudo[] = strtoupper($rowsLetra->fields('letra'));\r
+ $rowsLetra->moveNext();\r
+ }\r
+ $input->setSession('session_letras_casoestudo',serialize($this->arr_alfabeto_casoestudo));\r
+ }\r
+ }\r
+ function findLetraCasoEstudo() {\r
+ global $db;\r
+ \r
+ $sql = "SELECT DISTINCT(SUBSTRING(nome,1,1)) AS letra FROM sis_casoestudo WHERE visualizacao = 1 ORDER BY nome ASC";\r
+ return $db->execute($sql);\r
+ }\r
+ function getFiltrosFromSession(){\r
+ $this->setAlfabetoCasoEstudo();\r
+ \r
+ global $input;\r
+ $this->filtro_palavra = $input->session('session_casoestudo_filtro_palavra');\r
+ $this->filtro_procedencia = $input->session('session_casoestudo_filtro_procedencia');\r
+ $this->filtro_sistema = $input->session('session_casoestudo_filtro_sistema');\r
+ $this->filtro_patologia = $input->session('session_casoestudo_filtro_patologia');\r
+ \r
+ $this->filtro_ordenar = $input->get('casoestudo_filtro_ordenar');\r
+ if($this->filtro_ordenar == ''){\r
+ $this->filtro_ordenar = $input->session('session_casoestudo_filtro_ordenar');\r
+ if($this->filtro_ordenar == ''){\r
+ $this->filtro_ordenar = $this->arr_ordenar[0];\r
+ }\r
+ } else {\r
+ $input->setSession('session_casoestudo_filtro_ordenar',$this->filtro_ordenar);\r
+ }\r
+ \r
+ $this->filtro_resultado = $input->get('casoestudo_filtro_resultado');\r
+ if($this->filtro_resultado == ''){\r
+ $this->filtro_resultado = $input->session('session_casoestudo_filtro_resultado');\r
+ if($this->filtro_resultado == ''){\r
+ $this->filtro_resultado = $this->arr_resultado[0];\r
+ }\r
+ } else {\r
+ $input->setSession('session_casoestudo_filtro_resultado',$this->filtro_resultado);\r
+ }\r
+ }\r
+ function getResultado($tmp_baseLink = ''){\r
+ $html = '<div class="resultados">Resultados por página: ';\r
+ $total = sizeof($this->arr_resultado);\r
+ for($r=0;$r<$total;$r++){\r
+ if($this->arr_resultado[$r] == $this->filtro_resultado){\r
+ $html .= '<a href="'.$tmp_baseLink.'&casoestudo_filtro_resultado='.$this->arr_resultado[$r].'" class="underlaine" style="font-weight:bold; text-decoration:none;">'.$this->arr_resultado[$r].'</a>';\r
+ } else {\r
+ $html .= '<a href="'.$tmp_baseLink.'&casoestudo_filtro_resultado='.$this->arr_resultado[$r].'" class="underlaine">'.$this->arr_resultado[$r].'</a>';\r
+ }\r
+ if(($r+1) < $total){\r
+ $html .= ' ';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ return $html;\r
+ }\r
+ function getAlfabeto(){\r
+ $html = '<table cellspacing="0" cellpadding="0" width="100%"><tr>';\r
+ $total = sizeof($this->arr_alfabeto);\r
+ for($a=0;$a<$total;$a++){\r
+ if(in_array($this->arr_alfabeto[$a],$this->arr_alfabeto_casoestudo)){\r
+ $html .= '<td align="center"><a href="?letra='.$this->arr_alfabeto[$a].'" class="ltra">'.$this->arr_alfabeto[$a].'</a></td>';\r
+ } else {\r
+ $html .= '<td align="center" class="nletra" style="padding-left:3px; padding-right:3px;">'.$this->arr_alfabeto[$a].'</td>';\r
+ }\r
+ }\r
+ $html .= '</tr></table>';\r
+ return $html;\r
+ }\r
+ function getImgesRelacionadas($tmp_id,$tmp_limit = ''){\r
+ global $db;\r
+ global $load;\r
+ global $input;\r
+ \r
+ $load->config('classes/Imagem.php');\r
+ $o_imagem = new Imagem();\r
+ \r
+ if($tmp_limit != ''){\r
+ $tmp_limit = " LIMIT ".$tmp_limit;\r
+ }\r
+ \r
+ $sql = "SELECT cei.id_imagem,i.nome FROM sis_casoestudo_imagem cei INNER JOIN \r
+ sis_imagem i ON i.id = id_imagem WHERE i.visualizacao = 1 AND cei.id_casoestudo = ".$tmp_id." ".$tmp_limit;\r
+ $rowsImagem = $db->execute($sql);\r
+ if(!$rowsImagem->EOF){\r
+ $html = '';\r
+ while(!$rowsImagem->EOF){\r
+ $src = $o_imagem->getImage($rowsImagem->fields('id_imagem'),'pp');\r
+ if($src != ''){\r
+ $html .= '<div style="float:left;margin-left:5px;margin-top:5px;"><div style="width:55px; height:48px; cursor:pointer;" onclick="javascript: url(\'../imagens/view.php?id='.$input->encode($rowsImagem->fields('id_imagem')).'\');"><img src="'.$src.'" alt="'.$rowsImagem->fields('nome').'" title="'.$rowsImagem->fields('nome').'" /></div></div>';\r
+ }\r
+ $rowsImagem->moveNext();\r
+ }\r
+ return $html;\r
+ } else {\r
+ if($tmp_limit == ''){\r
+ return 'Nenhuma imagem relacionada.';\r
+ }\r
+ return '';\r
+ }\r
+ }\r
+ function getOrdenar($tmp_baseLink = ''){\r
+ $html = '<div class="ordenar">Ordenar por: ';\r
+ $total = sizeof($this->arr_ordenar);\r
+ for($x=0;$x<$total;$x++){\r
+ if($this->arr_ordenar[$x] == $this->filtro_ordenar){\r
+ $html .= '<a href="'.$tmp_baseLink.'&casoestudo_filtro_ordenar='.$this->arr_ordenar[$x].'" class="underlaine" style="text-decoration:none;font-weight:bold;">'.$this->arr_ordenar[$x].'</a>';\r
+ } else {\r
+ $html .= '<a href="'.$tmp_baseLink.'&casoestudo_filtro_ordenar='.$this->arr_ordenar[$x].'" class="underlaine">'.$this->arr_ordenar[$x].'</a>';\r
+ }\r
+ if(($x+1) < $total){\r
+ $html .= ' ';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ return $html;\r
+ }\r
+ function searchLetter($tmp_letra){\r
+ global $db;\r
+ \r
+ $sql = "SELECT ce.id,ce.codigo,\r
+ ce.id_especialidade,\r
+ ce.id_usuario,\r
+ ce.nome,\r
+ SUBSTRING(ce.texto,1,250) as texto,\r
+ esp.nome as especialidade,\r
+ u.nome as professor\r
+ FROM sis_casoestudo ce \r
+ LEFT OUTER JOIN sis_especialidade esp ON ce.id_especialidade = esp.id \r
+ LEFT OUTER JOIN admin_usuario u ON ce.id_usuario = u.id \r
+ WHERE ce.visualizacao = 1 AND ce.nome like '".$tmp_letra."%' ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function simpleSeach($tmp_palavraChave,$tmp_professor = '',$tmp_especialidade = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = '',$tmp_codigo = ''){\r
+ global $db;\r
+ global $o_helper;\r
+ $o_helper->somaBusca($tmp_palavraChave);\r
+ \r
+ $andPalavraChave = '';\r
+ if($tmp_palavraChave != ''){\r
+ $andPalavraChave = " AND (\r
+ ce.nome like '%".$tmp_palavraChave."%' OR \r
+ ce.texto like '%".$tmp_palavraChave."%' OR \r
+ ce.palavrachave like '%".$tmp_palavraChave."%' OR \r
+ i.nome like '%".$tmp_palavraChave."%' OR \r
+ d.nome like '%".$tmp_palavraChave."%' OR \r
+ o.nome like '%".$tmp_palavraChave."%' OR \r
+ pat.nome like '%".$tmp_palavraChave."%' OR \r
+ sis.nome like '%".$tmp_palavraChave."%' \r
+ ) ";\r
+ }\r
+ $andProfessor = '';\r
+ if($tmp_professor != ''){\r
+ $andProfessor = ' AND ce.id_usuario = '.$tmp_professor.' ';\r
+ }\r
+ $andEspecialidade = '';\r
+ if($tmp_especialidade != ''){\r
+ $andEspecialidade = ' AND ce.id_especialidade = '.$tmp_especialidade.' ';\r
+ }\r
+ $andSistema = '';\r
+ if($tmp_sistema != ''){\r
+ $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' ';\r
+ }\r
+ $andPatologia = '';\r
+ if($tmp_patologia != ''){\r
+ $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' ';\r
+ }\r
+ $andGrupoOrgao = '';\r
+ if($tmp_grupoorgao != ''){\r
+ $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' ';\r
+ }\r
+ $andCodigo = '';\r
+ if($tmp_codigo != ''){\r
+ $andCodigo = " AND ce.codigo LIKE '%".$tmp_codigo."%'";\r
+ }\r
+ \r
+ $sql = "SELECT ce.id,ce.codigo,\r
+ ce.id_especialidade,\r
+ ce.id_usuario,\r
+ ce.nome,\r
+ SUBSTRING(ce.texto,1,250) as texto,\r
+ esp.nome as especialidade,\r
+ u.nome as professor\r
+ \r
+ FROM sis_casoestudo ce \r
+ LEFT OUTER JOIN sis_especialidade esp ON ce.id_especialidade = esp.id \r
+ LEFT OUTER JOIN admin_usuario u ON ce.id_usuario = u.id \r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_imagem cei ON ce.id = cei.id_casoestudo \r
+ LEFT OUTER JOIN sis_imagem i ON cei.id_imagem = i.id \r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_diagnostico ced ON ce.id = ced.id_casoestudo \r
+ LEFT OUTER JOIN sis_diagnostico d ON ced.id_diagnostico = d.id \r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_orgao ceo ON ce.id = ceo.id_casoestudo \r
+ LEFT OUTER JOIN sis_orgao o ON ceo.id_orgao = o.id \r
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao\r
+ \r
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id \r
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id \r
+ \r
+ WHERE ce.visualizacao = 1 ".$andPalavraChave.$andProfessor.$andEspecialidade.$andSistema.$andPatologia.$andGrupoOrgao.$andCodigo." GROUP BY ce.id ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function complexSeach($arrPalavra,$tmp_professor = '',$tmp_especialidade = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = '',$tmp_codigo = ''){\r
+ global $db;\r
+ global $o_helper;\r
+ \r
+ $andProfessor = '';\r
+ if($tmp_professor != ''){\r
+ $andProfessor = ' AND ce.id_usuario = '.$tmp_professor.' ';\r
+ }\r
+ $andEspecialidade = '';\r
+ if($tmp_especialidade != ''){\r
+ $andEspecialidade = ' AND ce.id_especialidade = '.$tmp_especialidade.' ';\r
+ }\r
+ $andSistema = '';\r
+ if($tmp_sistema != ''){\r
+ $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' ';\r
+ }\r
+ $andPatologia = '';\r
+ if($tmp_patologia != ''){\r
+ $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' ';\r
+ }\r
+ $andGrupoOrgao = '';\r
+ if($tmp_grupoorgao != ''){\r
+ $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' ';\r
+ }\r
+ $andCodigo = '';\r
+ if($tmp_codigo != ''){\r
+ $andCodigo = " AND ce.codigo LIKE '%".$tmp_codigo."%'";\r
+ }\r
+ \r
+ $fixedWhere = " ce.visualizacao = 1 ".$andProfessor.$andEspecialidade.$andSistema.$andPatologia.$andGrupoOrgao.$andCodigo;\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "ce.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "ce.texto like '%#PALAVRA#%'";\r
+ $arrWhere[] = "ce.palavrachave like '%#PALAVRA#%'";\r
+ $arrWhere[] = "i.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "d.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "o.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "pat.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "sis.nome like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT ce.id,ce.codigo,\r
+ ce.id_especialidade,\r
+ ce.id_usuario,\r
+ ce.nome,\r
+ SUBSTRING(ce.texto,1,250) as texto,\r
+ esp.nome as especialidade,\r
+ u.nome as professor\r
+ \r
+ FROM sis_casoestudo ce \r
+ LEFT OUTER JOIN sis_especialidade esp ON ce.id_especialidade = esp.id \r
+ LEFT OUTER JOIN admin_usuario u ON ce.id_usuario = u.id \r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_imagem cei ON ce.id = cei.id_casoestudo \r
+ LEFT OUTER JOIN sis_imagem i ON cei.id_imagem = i.id \r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_diagnostico ced ON ce.id = ced.id_casoestudo \r
+ LEFT OUTER JOIN sis_diagnostico d ON ced.id_diagnostico = d.id \r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_orgao ceo ON ce.id = ceo.id_casoestudo \r
+ LEFT OUTER JOIN sis_orgao o ON ceo.id_orgao = o.id \r
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao\r
+ \r
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id \r
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id\r
+ #WHERE#\r
+ ".$this->getOrderBy();\r
+ \r
+ return $db->execute($o_helper->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function getOrderBy(){\r
+ switch($this->filtro_ordenar){\r
+ case 'Nome':\r
+ return ' ORDER BY ce.nome ASC';\r
+ break;\r
+ case 'Especialidade':\r
+ return ' ORDER BY especialidade ASC';\r
+ break;\r
+ case 'Sistema':\r
+ return ' ORDER BY sistema ASC';\r
+ break;\r
+ case 'Patologia':\r
+ return ' ORDER BY patologia ASC';\r
+ break;\r
+ }\r
+ }\r
+ function findCasoEstudoById($tmp_id){\r
+ global $db;\r
+ \r
+ $sql = "SELECT ce.id,ce.codigo,\r
+ ce.id_especialidade,\r
+ ce.id_usuario,\r
+ ce.nome,\r
+ ce.texto,\r
+ esp.nome as especialidade,\r
+ u.nome as professor \r
+ FROM sis_casoestudo ce \r
+ LEFT OUTER JOIN sis_especialidade esp ON ce.id_especialidade = esp.id \r
+ LEFT OUTER JOIN admin_usuario u ON ce.id_usuario = u.id\r
+ WHERE ce.visualizacao = 1 AND ce.id = ".$tmp_id." GROUP BY ce.id ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function orgaosrelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT o.id, o.nome FROM sis_orgao o INNER JOIN sis_casoestudo_orgao io ON io.id_orgao = o.id WHERE io.id_casoestudo = ".$tmp_id." ORDER BY nome ASC";\r
+ $rowsOrgao = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsOrgao->EOF){\r
+ $obj .= 'Orgãos Relacionados:<br/>';\r
+ while(!$rowsOrgao->EOF){\r
+ $obj .= '<small><a href="javascript:url(\'../orgaos/view.php?id='.$input->encode($rowsOrgao->fields('id')).'\');">'.$rowsOrgao->fields('nome').'</a></small><br/>';\r
+ $rowsOrgao->moveNext();\r
+ }\r
+ }\r
+ return $obj;\r
+ }\r
+ function diagnosticosrelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT d.id, d.nome FROM sis_diagnostico d INNER JOIN sis_casoestudo_diagnostico di ON di.id_diagnostico = d.id WHERE d.visualizacao = 1 AND di.id_casoestudo = ".$tmp_id." ORDER BY d.nome ASC";\r
+ $rowsDiagnostico = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsDiagnostico->EOF){\r
+ while(!$rowsDiagnostico->EOF){\r
+ $obj .= '<div class="divlist"><a href="javascript:url(\'../diagnosticos/view.php?id='.$input->encode($rowsDiagnostico->fields('id')).'\');">'.$rowsDiagnostico->fields('nome').'</a></div>';\r
+ $rowsDiagnostico->moveNext();\r
+ }\r
+ } else {\r
+ $obj = 'Nenhum diagnóstico relacionado.';\r
+ }\r
+ return $obj;\r
+ }\r
+ function findComentariosByIdCasoEstudo($tmp_id){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id, id_casoestudo, nome, comentario FROM sis_casoestudo_comentario WHERE status = 1 AND id_casoestudo = ".$tmp_id." ORDER BY datacomentario DESC";\r
+ return $db->execute($sql);\r
+ }\r
+ function insertComentario(){\r
+ global $input;\r
+ global $db;\r
+ \r
+ $sql = "INSERT INTO sis_casoestudo_comentario (id_casoestudo,nome,email,comentario,datacomentario,status) VALUES ('".$input->post('id',true)."','".$input->post('nome')."','".$input->post('email')."','".$input->post('comentario')."','".date('Y-m-d H:i:s')."',1)";\r
+ $db->execute($sql);\r
+ if(mysql_insert_id() != 0){\r
+ return 1;\r
+ } else {\r
+ return 0;\r
+ }\r
+ }\r
+ function inativeComentario($tmp_id){\r
+ global $db;\r
+ \r
+ if($tmp_id != ''){\r
+ $sql = "UPDATE sis_casoestudo_comentario SET status = 0 WHERE id = ".$tmp_id;\r
+ $db->execute($sql);\r
+ return 1;\r
+ }\r
+ return 0;\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Diagnostico{\r
+ //opções de listagem\r
+ var $arr_alfabeto;\r
+ var $arr_resultado;\r
+ var $arr_ordenar;\r
+ \r
+ //filtro - session\r
+ var $filtro_palavra;\r
+ var $filtro_procedencia;\r
+ var $filtro_sistema;\r
+ var $filtro_patologia;\r
+ var $filtro_alfabeto;\r
+ var $filtro_ordenar;\r
+ var $filtro_resultado;\r
+ \r
+ function Diagnostico($tmp_patologia = ''){\r
+ $this->arr_alfabeto = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','W');\r
+ $this->arr_resultado = array('08','16','32');\r
+ $this->arr_ordenar = array('Nome','Especialidade');\r
+ $this->getFiltrosFromSession($tmp_patologia);\r
+ }\r
+ function setAlfabetoDiagnostico($tmp_patologia = '') {\r
+ global $input;\r
+ \r
+ $session = 'session_letras_diagnostico';\r
+ if($tmp_patologia != ''){\r
+ $session = 'session_letras_diagnostico_necropsia';\r
+ }\r
+ \r
+ if ($input->session($session) != '') {\r
+ $this->arr_alfabeto_diagnostico = unserialize($input->session($session));\r
+ if($this->arr_alfabeto_diagnostico == ''){\r
+ $this->arr_alfabeto_diagnostico = array();\r
+ }\r
+ } else {\r
+ $rowsLetra = $this->findLetraDiagnostico($tmp_patologia);\r
+ $this->arr_alfabeto_diagnostico = array();\r
+ while (!$rowsLetra->EOF) {\r
+ $this->arr_alfabeto_diagnostico[] = strtoupper($rowsLetra->fields('letra'));\r
+ $rowsLetra->moveNext();\r
+ }\r
+ $input->setSession($session,serialize($this->arr_alfabeto_diagnostico));\r
+ }\r
+ }\r
+ function findLetraDiagnostico($tmp_patologia = '') {\r
+ global $db;\r
+ \r
+ $sql = "SELECT DISTINCT(SUBSTRING(nome,1,1)) AS letra FROM sis_diagnostico WHERE visualizacao = 1 ORDER BY nome ASC"; \r
+ if($tmp_patologia != ''){\r
+ $sql = "SELECT DISTINCT(SUBSTRING(d.nome,1,1)) AS letra FROM sis_diagnostico d \r
+ INNER JOIN sis_diagnostico_imagem di ON d.id = di.id_diagnostico \r
+ INNER JOIN sis_imagem i ON di.id_imagem = i.id \r
+ WHERE d.visualizacao = 1 AND i.id_patologia = ".$tmp_patologia." \r
+ GROUP BY d.id\r
+ ORDER BY d.nome ASC";\r
+ }\r
+ return $db->execute($sql);\r
+ }\r
+ function getFiltrosFromSession($tmp_patologia = ''){\r
+ $this->setAlfabetoDiagnostico($tmp_patologia);\r
+ \r
+ global $input;\r
+ $this->filtro_palavra = $input->session('session_diagnostico_filtro_palavra');\r
+ $this->filtro_procedencia = $input->session('session_diagnostico_filtro_procedencia');\r
+ $this->filtro_sistema = $input->session('session_diagnostico_filtro_sistema');\r
+ $this->filtro_patologia = $input->session('session_diagnostico_filtro_patologia');\r
+ \r
+ $this->filtro_ordenar = $input->get('diagnostico_filtro_ordenar');\r
+ if($this->filtro_ordenar == ''){\r
+ $this->filtro_ordenar = $input->session('session_diagnostico_filtro_ordenar');\r
+ if($this->filtro_ordenar == ''){\r
+ $this->filtro_ordenar = $this->arr_ordenar[0];\r
+ }\r
+ } else {\r
+ $input->setSession('session_diagnostico_filtro_ordenar',$this->filtro_ordenar);\r
+ }\r
+ \r
+ $this->filtro_resultado = $input->get('diagnostico_filtro_resultado');\r
+ if($this->filtro_resultado == ''){\r
+ $this->filtro_resultado = $input->session('session_diagnostico_filtro_resultado');\r
+ if($this->filtro_resultado == ''){\r
+ $this->filtro_resultado = $this->arr_resultado[0];\r
+ }\r
+ } else {\r
+ $input->setSession('session_diagnostico_filtro_resultado',$this->filtro_resultado);\r
+ }\r
+ }\r
+ function getAlfabeto(){\r
+ $html = '<table cellspacing="0" cellpadding="0" width="100%"><tr>';\r
+ $total = sizeof($this->arr_alfabeto);\r
+ for($a=0;$a<$total;$a++){\r
+ if(in_array($this->arr_alfabeto[$a],$this->arr_alfabeto_diagnostico)){\r
+ $html .= '<td align="center"><a href="?letra='.$this->arr_alfabeto[$a].'" class="ltra">'.$this->arr_alfabeto[$a].'</a></td>';\r
+ } else {\r
+ $html .= '<td align="center" class="nletra" style="padding-left:3px; padding-right:3px;">'.$this->arr_alfabeto[$a].'</td>';\r
+ }\r
+ }\r
+ $html .= '</tr></table>';\r
+ return $html;\r
+ }\r
+ function getResultado($tmp_baseLink = ''){\r
+ $html = '<div class="resultados">Resultados por página: ';\r
+ $total = sizeof($this->arr_resultado);\r
+ for($r=0;$r<$total;$r++){\r
+ if($this->arr_resultado[$r] == $this->filtro_resultado){\r
+ $html .= '<a href="'.$tmp_baseLink.'&diagnostico_filtro_resultado='.$this->arr_resultado[$r].'" class="underlaine" style="font-weight:bold; text-decoration:none;">'.$this->arr_resultado[$r].'</a>';\r
+ } else {\r
+ $html .= '<a href="'.$tmp_baseLink.'&diagnostico_filtro_resultado='.$this->arr_resultado[$r].'" class="underlaine">'.$this->arr_resultado[$r].'</a>';\r
+ }\r
+ if(($r+1) < $total){\r
+ $html .= ' ';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ return $html;\r
+ }\r
+ function getOrdenar($tmp_baseLink = ''){\r
+ $html = '<div class="ordenar">Ordenar por: ';\r
+ $total = sizeof($this->arr_ordenar);\r
+ for($x=0;$x<$total;$x++){\r
+ if($this->arr_ordenar[$x] == $this->filtro_ordenar){\r
+ $html .= '<a href="'.$tmp_baseLink.'&diagnostico_filtro_ordenar='.$this->arr_ordenar[$x].'" class="underlaine" style="text-decoration:none;font-weight:bold;">'.$this->arr_ordenar[$x].'</a>';\r
+ } else {\r
+ $html .= '<a href="'.$tmp_baseLink.'&diagnostico_filtro_ordenar='.$this->arr_ordenar[$x].'" class="underlaine">'.$this->arr_ordenar[$x].'</a>';\r
+ }\r
+ if(($x+1) < $total){\r
+ $html .= ' ';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ return $html;\r
+ }\r
+ function getImages($tmp_id){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id, nome FROM sis_imagem i \r
+ INNER JOIN sis_diagnostico_imagem di ON di.id_imagem = i.id \r
+ WHERE di.id_diagnostico = ".$tmp_id;\r
+ return $db->execute($sql);\r
+ }\r
+ function searchLetter($tmp_letra,$tmp_patologia = ''){\r
+ global $db;\r
+ \r
+ $sql = "SELECT d.id,\r
+ d.id_especialidade,\r
+ d.nome,\r
+ d.cid10,\r
+ SUBSTRING(d.texto,0,250) as texto,\r
+ esp.nome as especialidade\r
+ \r
+ FROM sis_diagnostico d \r
+ LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id \r
+ WHERE d.visualizacao = 1 AND (\r
+ d.nome like '".$tmp_letra."%') GROUP BY d.id ".$this->getOrderBy();\r
+ if($tmp_patologia != ''){\r
+ $sql = "SELECT d.id,\r
+ d.id_especialidade,\r
+ d.nome,\r
+ d.cid10,\r
+ SUBSTRING(d.texto,0,250) as texto,\r
+ esp.nome as especialidade\r
+ \r
+ FROM sis_diagnostico d \r
+ INNER JOIN sis_diagnostico_imagem di ON d.id = di.id_diagnostico \r
+ INNER JOIN sis_imagem i ON di.id_imagem = i.id \r
+ LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id \r
+ WHERE d.visualizacao = 1 AND i.id_patologia = ".$tmp_patologia." AND (\r
+ d.nome like '".$tmp_letra."%') GROUP BY d.id ".$this->getOrderBy();\r
+ }\r
+ return $db->execute($sql);\r
+ }\r
+ function simpleSeach($tmp_palavraChave,$tmp_especialidade = '',$tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = ''){\r
+ global $db;\r
+ global $o_helper;\r
+ $o_helper->somaBusca($tmp_palavraChave);\r
+ \r
+ $andPalavraChave = '';\r
+ if($tmp_palavraChave != ''){\r
+ $andPalavraChave = " AND (\r
+ d.nome like '%".$tmp_palavraChave."%' OR \r
+ d.texto like '%".$tmp_palavraChave."%' OR \r
+ d.palavrachave like '%".$tmp_palavraChave."%' OR \r
+ i.nome like '%".$tmp_palavraChave."%' OR \r
+ proc.nome like '%".$tmp_palavraChave."%' OR \r
+ pat.nome like '%".$tmp_palavraChave."%' OR \r
+ sis.nome like '%".$tmp_palavraChave."%' OR \r
+ c.nome like '%".$tmp_palavraChave."%' OR \r
+ c.palavrachave like '%".$tmp_palavraChave."%' \r
+ ) ";\r
+ }\r
+ $andEspecialidade = '';\r
+ if($tmp_especialidade != ''){\r
+ $andEspecialidade = ' AND d.id_especialidade = '.$tmp_especialidade.' ';\r
+ }\r
+ $andProcedencia = '';\r
+ if($tmp_procedencia != ''){\r
+ $andProcedencia = ' AND i.id_procedencia = '.$tmp_procedencia.' ';\r
+ }\r
+ $andSistema = '';\r
+ if($tmp_sistema != ''){\r
+ $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' ';\r
+ }\r
+ $andPatologia = '';\r
+ if($tmp_patologia != ''){\r
+ $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' ';\r
+ }\r
+ $andGrupoOrgao = '';\r
+ if($tmp_grupoorgao != ''){\r
+ $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' ';\r
+ }\r
+ \r
+ $sql = "SELECT d.id,\r
+ d.id_especialidade,\r
+ d.nome,\r
+ d.cid10,\r
+ SUBSTRING(d.texto,1,250) as texto,\r
+ esp.nome as especialidade\r
+ \r
+ FROM sis_diagnostico d \r
+ LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id \r
+ \r
+ LEFT OUTER JOIN sis_diagnostico_imagem di ON d.id = di.id_diagnostico \r
+ LEFT OUTER JOIN sis_imagem i ON di.id_imagem = i.id \r
+ \r
+ LEFT OUTER JOIN sis_procedencia proc ON i.id_procedencia = proc.id \r
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id \r
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id \r
+ \r
+ LEFT OUTER JOIN sis_diagnostico_orgao do ON d.id = do.id_diagnostico\r
+ LEFT OUTER JOIN sis_orgao o ON do.id_orgao = o.id\r
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao\r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_diagnostico cd ON d.id = cd.id_diagnostico \r
+ LEFT OUTER JOIN sis_casoestudo c ON cd.id_casoestudo = c.id \r
+ WHERE d.visualizacao = 1 ".$andPalavraChave.$andEspecialidade.$andProcedencia.$andSistema.$andPatologia.$andGrupoOrgao." GROUP BY d.id ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function complexSeach($arrPalavra,$tmp_especialidade = '',$tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = ''){\r
+ global $db;\r
+ global $o_helper;\r
+ \r
+ $andEspecialidade = '';\r
+ if($tmp_especialidade != ''){\r
+ $andEspecialidade = ' AND d.id_especialidade = '.$tmp_especialidade.' ';\r
+ }\r
+ $andProcedencia = '';\r
+ if($tmp_procedencia != ''){\r
+ $andProcedencia = ' AND i.id_procedencia = '.$tmp_procedencia.' ';\r
+ }\r
+ $andSistema = '';\r
+ if($tmp_sistema != ''){\r
+ $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' ';\r
+ }\r
+ $andPatologia = '';\r
+ if($tmp_patologia != ''){\r
+ $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' ';\r
+ }\r
+ $andGrupoOrgao = '';\r
+ if($tmp_grupoorgao != ''){\r
+ $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' ';\r
+ }\r
+ \r
+ $fixedWhere = " d.visualizacao = 1 ".$andEspecialidade.$andProcedencia.$andSistema.$andPatologia.$andGrupoOrgao;\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "d.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "d.texto like '%#PALAVRA#%'";\r
+ $arrWhere[] = "d.palavrachave like '%#PALAVRA#%'";\r
+ $arrWhere[] = "i.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "proc.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "pat.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "sis.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "c.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "c.palavrachave like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT d.id,\r
+ d.id_especialidade,\r
+ d.nome,\r
+ d.cid10,\r
+ SUBSTRING(d.texto,1,250) as texto,\r
+ esp.nome as especialidade\r
+ \r
+ FROM sis_diagnostico d \r
+ LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id \r
+ \r
+ LEFT OUTER JOIN sis_diagnostico_imagem di ON d.id = di.id_diagnostico \r
+ LEFT OUTER JOIN sis_imagem i ON di.id_imagem = i.id \r
+ \r
+ LEFT OUTER JOIN sis_procedencia proc ON i.id_procedencia = proc.id \r
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id \r
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id \r
+ \r
+ LEFT OUTER JOIN sis_diagnostico_orgao do ON d.id = do.id_diagnostico\r
+ LEFT OUTER JOIN sis_orgao o ON do.id_orgao = o.id\r
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao\r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_diagnostico cd ON d.id = cd.id_diagnostico \r
+ LEFT OUTER JOIN sis_casoestudo c ON cd.id_casoestudo = c.id \r
+ #WHERE# \r
+ GROUP BY d.id \r
+ ".$this->getOrderBy();\r
+ \r
+ return $db->execute($o_helper->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function getImgesRelacionadas($tmp_id,$tmp_limit = ''){\r
+ global $db;\r
+ global $load;\r
+ global $input;\r
+ \r
+ $load->config('classes/Imagem.php');\r
+ $o_imagem = new Imagem();\r
+ \r
+ if($tmp_limit != ''){\r
+ $tmp_limit = " LIMIT ".$tmp_limit;\r
+ }\r
+ \r
+ $sql = "SELECT di.id_imagem,i.nome FROM sis_diagnostico_imagem di INNER JOIN \r
+ sis_imagem i ON i.id = id_imagem WHERE i.visualizacao = 1 AND di.id_diagnostico = ".$tmp_id." ".$tmp_limit;\r
+ $rowsImagem = $db->execute($sql);\r
+ if(!$rowsImagem->EOF){\r
+ $html = '';\r
+ while(!$rowsImagem->EOF){\r
+ $src = $o_imagem->getImage($rowsImagem->fields('id_imagem'),'pp');\r
+ if($src != ''){\r
+ $html .= '<div style="float:left;margin-left:5px;margin-top:5px;"><div style="width:55px; height:48px; cursor:pointer;" onclick="javascript: url(\'../imagens/view.php?id='.$input->encode($rowsImagem->fields('id_imagem')).'\');"><img src="'.$src.'" alt="'.$rowsImagem->fields('nome').'" title="'.$rowsImagem->fields('nome').'" /></div></div>';\r
+ }\r
+ $rowsImagem->moveNext();\r
+ }\r
+ return $html;\r
+ } else {\r
+ return '';\r
+ }\r
+ }\r
+ function findDiagnoticoById($tmp_id){\r
+ global $db;\r
+ \r
+ $sql = "SELECT d.id,\r
+ d.id_especialidade,\r
+ d.nome,\r
+ d.cid10,\r
+ d.texto,\r
+ esp.nome as especialidade\r
+ \r
+ FROM sis_diagnostico d \r
+ LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id \r
+ WHERE d.visualizacao = 1 AND d.id = ".$tmp_id." GROUP BY d.id ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function orgaosrelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT o.id, o.nome FROM sis_orgao o INNER JOIN sis_diagnostico_orgao io ON io.id_orgao = o.id WHERE io.id_diagnostico = ".$tmp_id." ORDER BY nome ASC";\r
+ $rowsOrgao = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsOrgao->EOF){\r
+ $obj .= 'Orgãos Relacionados:<br/>';\r
+ while(!$rowsOrgao->EOF){\r
+ $obj .= '<small><a href="javascript:url(\'../orgaos/view.php?id='.$input->encode($rowsOrgao->fields('id')).'\');">'.$rowsOrgao->fields('nome').'</a></small><br/>';\r
+ $rowsOrgao->moveNext();\r
+ }\r
+ }\r
+ return $obj;\r
+ }\r
+ function casosdeestudorelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT c.id, c.nome FROM sis_casoestudo c INNER JOIN sis_casoestudo_diagnostico ci ON ci.id_casoestudo = c.id WHERE c.visualizacao = 1 AND ci.id_diagnostico = ".$tmp_id." ORDER BY c.nome ASC";\r
+ $rowsDiagnostico = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsDiagnostico->EOF){\r
+ while(!$rowsDiagnostico->EOF){\r
+ $obj .= '<div class="divlist"><a href="javascript:url(\'../casosdeestudo/view.php?id='.$input->encode($rowsDiagnostico->fields('id')).'\');">'.$rowsDiagnostico->fields('nome').'</a></div>';\r
+ $rowsDiagnostico->moveNext();\r
+ }\r
+ } else {\r
+ $obj = 'Nenhum caso de estudo relacionado.';\r
+ }\r
+ return $obj;\r
+ }\r
+ function getOrderBy(){\r
+ switch($this->filtro_ordenar){\r
+ case 'Nome':\r
+ return ' ORDER BY d.nome ASC';\r
+ break;\r
+ case 'Especialidade':\r
+ return ' ORDER BY especialidade ASC';\r
+ break;\r
+ case 'Sistema':\r
+ return ' ORDER BY sistema ASC';\r
+ break;\r
+ case 'Patologia':\r
+ return ' ORDER BY patologia ASC';\r
+ break;\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class GrupoOrgao{\r
+ function GrupoOrgao(){\r
+ \r
+ }\r
+ function findCamadas(){\r
+ global $db;\r
+ \r
+ $sql = "SELECT DISTINCT c.id,c.nome FROM sis_grupoorgao_camada c \r
+ INNER JOIN sis_grupoorgao g ON g.id_camada = c.id \r
+ WHERE status = 1";\r
+ return $db->execute($sql);\r
+ }\r
+ function findGrupoByCamada($tmp_idCamada){\r
+ global $db;\r
+ \r
+ $sql = "SELECT g.id,g.nome,g.x1,g.y1,g.x2,g.y2,(g.x1 * g.y1) as area FROM sis_grupoorgao g \r
+ WHERE id_camada = ".$tmp_idCamada." ORDER BY area";\r
+ return $db->execute($sql);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Helper{\r
+ function hasFilter($tmp_letra = true){\r
+ global $input;\r
+ \r
+ if(($input->get('palavrachave') != '')\r
+ || ($input->get('grupoorgao') != '')\r
+ || ($input->get('procedencia') != '')\r
+ || ($input->get('sistema') != '')\r
+ || ($input->get('patologia') != '')\r
+ || ($input->get('especialidade') != '')\r
+ || ($input->get('professor') != '')\r
+ || ($input->get('boneco') != '')\r
+ || ($input->get('codigo') != '')\r
+ || (($input->get('letra') != '') && ($tmp_letra))){\r
+ return true;\r
+ } else {\r
+ return false;\r
+ }\r
+ }\r
+ function findTopografiaById($tmp_id){\r
+ if($tmp_id != ''){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome FROM sis_grupoorgao WHERE id = ".$tmp_id." ORDER BY nome ASC LIMIT 1";\r
+ $row = $db->execute($sql);\r
+ if($row->EOF){\r
+ return '';\r
+ } else {\r
+ return $row->fields('nome');\r
+ }\r
+ }\r
+ }\r
+ function findEspecialidade($tmp_asArray = false){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome FROM sis_especialidade ORDER BY nome ASC";\r
+ if($tmp_asArray){\r
+ return $this->rowsIdNomeToArray($db->execute($sql));\r
+ } else {\r
+ return $db->execute($sql);\r
+ }\r
+ }\r
+ function findGrupoOrgao($tmp_asArray = false){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome FROM sis_grupoorgao ORDER BY nome ASC";\r
+ if($tmp_asArray){\r
+ return $this->rowsIdNomeToArray($db->execute($sql));\r
+ } else {\r
+ return $db->execute($sql);\r
+ }\r
+ }\r
+ function findProfesores($tmp_asArray = false){\r
+ global $db;\r
+ \r
+ $sql = "SELECT u.id,u.nome FROM admin_usuario u \r
+ INNER JOIN sis_casoestudo ce ON ce.id_usuario = u.id \r
+ GROUP BY u.id ORDER BY u.nome ASC";\r
+ if($tmp_asArray){\r
+ return $this->rowsIdNomeToArray($db->execute($sql));\r
+ } else {\r
+ return $db->execute($sql);\r
+ }\r
+ }\r
+ function findProcedencias($tmp_asArray = false){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome FROM sis_procedencia ORDER BY nome ASC";\r
+ if($tmp_asArray){\r
+ return $this->rowsIdNomeToArray($db->execute($sql));\r
+ } else {\r
+ return $db->execute($sql);\r
+ }\r
+ }\r
+ function findSistemas($tmp_asArray = false){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome FROM sis_sistema ORDER BY nome ASC";\r
+ if($tmp_asArray){\r
+ return $this->rowsIdNomeToArray($db->execute($sql));\r
+ } else {\r
+ return $db->execute($sql);\r
+ }\r
+ }\r
+ function findPatologias($tmp_asArray = false){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome FROM sis_patologia ORDER BY nome ASC";\r
+ if($tmp_asArray){\r
+ return $this->rowsIdNomeToArray($db->execute($sql));\r
+ } else {\r
+ return $db->execute($sql);\r
+ }\r
+ }\r
+ function rowsIdNomeToArray($tmp_rows){\r
+ $arr = Array();\r
+ \r
+ while(!$tmp_rows->EOF){\r
+ $arr[$tmp_rows->fields("id")] = $tmp_rows->fields("nome");\r
+ $tmp_rows->moveNext();\r
+ }\r
+ return $arr;\r
+ }\r
+ function somaBusca($tmp_palavraChave){\r
+ global $db;\r
+ \r
+ if($tmp_palavraChave != ''){\r
+ $sql = "SELECT * FROM sis_palavrabusca WHERE palavra = '".$tmp_palavraChave."'";\r
+ $rowPalavra = $db->execute($sql);\r
+ if($rowPalavra->EOF){\r
+ $sql = "INSERT INTO sis_palavrabusca (palavra,quantidade) VALUES('".$tmp_palavraChave."',1)";\r
+ $db->execute($sql);\r
+ } else {\r
+ $sql = "UPDATE sis_palavrabusca SET quantidade = quantidade+1 WHERE palavra ='".$tmp_palavraChave."'";\r
+ $db->execute($sql);\r
+ }\r
+ }\r
+ }\r
+ function findPalavraAproximada($palavra, $sql = ""){\r
+ global $db;\r
+ global $load;\r
+ \r
+ $load->system("functions/text.php");\r
+ \r
+ $min = 55;\r
+ $mid = 80;\r
+ \r
+ $arr_busca = explode(' ',$palavra);\r
+ $arr_palavras = array();\r
+ if($sql == "")\r
+ $sql = "SELECT palavra FROM sis_palavra WHERE status = 1";\r
+ $rs = $db->execute($sql);\r
+ while(!$rs->EOF){\r
+ $arr_now = explode(" ",$rs->fields("palavra"));\r
+ if(is_array($arr_now)) {\r
+ for($x=0,$total=sizeof($arr_now);$x<$total;$x++){\r
+ $arr_palavras[] = formatNameFile($arr_now[$x]);\r
+ }\r
+ } else {\r
+ $arr_palavras[] = formatNameFile($arr_now);\r
+ }\r
+ $rs->moveNext();\r
+ }\r
+ $arr_palavras = array_values(array_unique($arr_palavras));\r
+ $arr = array(array());\r
+ \r
+ $porcentagem = 0;\r
+ \r
+ // BUSCA TODA A PALAVRA\r
+ for($x=0,$total=sizeof($arr_palavras);$x<$total;$x++){\r
+ similar_text($palavra,$arr_palavras[$x],$r);\r
+ if ($r > $min) {\r
+ if ($r >= $mid) {\r
+ if ($porcentagem < $mid) {\r
+ $arr[0] = array();\r
+ }\r
+ }\r
+ \r
+ if ($porcentagem < $r) {\r
+ $porcentagem = $r;\r
+ $arr[0][] = $arr_palavras[$x];\r
+ }\r
+ }\r
+ }\r
+ \r
+ if (sizeof($arr_busca) > 1) {\r
+ $indice = 1;\r
+ //echo sizeof($arr_busca);\r
+ for ($x=0,$total=sizeof($arr_busca);$x<=$total;$x++) {\r
+ $porcentagem = 0;\r
+ //echo $x." - ".$total."<br>";\r
+ if(isset($arr_busca[$x])){\r
+ if (strlen($arr_busca[$x]) > 2) {\r
+ for($z=0,$total=sizeof($arr_palavras);$z<$total;$z++){\r
+ similar_text($arr_busca[$x],$arr_palavras[$z],$r);\r
+ if ($r > $min) {\r
+ if ($r >= $mid) {\r
+ if ($porcentagem < $mid) {\r
+ $arr[$indice] = array();\r
+ }\r
+ }\r
+ \r
+ if ($porcentagem < $r) {\r
+ $porcentagem = $r;\r
+ $arr[$indice][] = $arr_palavras[$z];\r
+ }\r
+ }\r
+ }\r
+ $indice++;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ \r
+ return $arr; \r
+ }\r
+ function makeSql($arrPalavra,$baseSql,$arrWherePalavra,$fixedWhere = ""){\r
+ //arrPalavra:\r
+ //Array com as palavras aproximadas. Lembrando, posição 0, array de palavras completas (frases, titulos), posição 1, todas as palavras 'quebradas'.\r
+ \r
+ //baseSql:\r
+ //Sql contendo todo o conteudo necessario para fazer a busca naquela tabela, no lugar da sentença WHERE, subtituir por #WHERE#, como no exemplo:\r
+ //SELECT id,nome,titulo,descricao,data FROM site_redacao r INNER JOIN site_teste t ON t.id = r.id_teste #WHERE# ORDER BY data DESC\r
+ \r
+ //arrWherePalavra:\r
+ //array com as condições, sem o where, e substituindo a palavra de busca por #PALAVRA#, como no exemplo:\r
+ //p.descricao LIKE '%#PALAVRA#%'\r
+ \r
+ //$fixedWhere:\r
+ //condições fixas a serem concatenadas com a query, como no exemplo:\r
+ //status = 1 AND data = '2009-10-20'\r
+ //note que não existe operador em nenhum dos lados (AND, OR, ou qualquer outro)\r
+ \r
+ if (isset($arrPalavra[0])) {\r
+ if ($arrPalavra[0] != '') {\r
+ $where = " AND (1=2 ";\r
+ for($x=0,$total=sizeof($arrPalavra[0]);$x<$total;$x++) {\r
+ $where .= " OR (";\r
+ for($w=0,$totalW=sizeof($arrWherePalavra);$w<$totalW;$w++){\r
+ if($w == 0){\r
+ $where .= " ".str_replace("#PALAVRA#",$arrPalavra[0][$x],$arrWherePalavra[$w])." ";\r
+ } else {\r
+ $where .= " OR ".str_replace("#PALAVRA#",$arrPalavra[0][$x],$arrWherePalavra[$w])." ";\r
+ }\r
+ }\r
+ $where .= " )";\r
+ }\r
+ $where .= ") ";\r
+ } else {\r
+ $where = 'AND 1=2';\r
+ }\r
+ } elseif(isset($arrPalavra[1])) {\r
+ $where = '';\r
+ for($i=1,$total=sizeof($arrPalavra);$i<=$total;$i++) {\r
+ $where .= " AND ((1=2) ";\r
+ for($x=0,$total=sizeof($arrPalavra[$i]);$x<=$total;$x++) {\r
+ if ($arrPalavra[$i][$x] != '') {\r
+ $where .= " OR (";\r
+ for($w=0,$totalW=sizeof($arrWherePalavra);$w<$totalW;$w++){\r
+ if($w == 0){\r
+ $where .= " ".str_replace("#PALAVRA#",$arrPalavra[$i][$x],$arrWherePalavra[$w])." ";\r
+ } else {\r
+ $where .= " OR ".str_replace("#PALAVRA#",$arrPalavra[$i][$x],$arrWherePalavra[$w])." ";\r
+ }\r
+ }\r
+ $where .= " )";\r
+ }\r
+ }\r
+ }\r
+ $where .= ") ";\r
+ }\r
+ if($fixedWhere == ""){\r
+ $fixedWhere = " 1 = 1 ";\r
+ } else {\r
+ $fixedWhere = " ".$fixedWhere." ";\r
+ }\r
+ $sql = str_replace("#WHERE#"," WHERE ".$fixedWhere.$where,$baseSql);\r
+ return $sql;\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Html{\r
+ function Html(){\r
+ \r
+ }\r
+ function alt($alt){\r
+ return ' alt="'.$alt.'" title="'.$alt.'" ';\r
+ }\r
+ function getMenu($tmp_menu,$tmp_link){\r
+ global $selected;\r
+ \r
+ $link = ' onclick="javascript: url(\''.$tmp_link.'\');" ';\r
+ $func = ' onmouseover="javascript: swapM(\''.$tmp_menu.'\',true);" onmouseout="javascript: swapM(\''.$tmp_menu.'\',false);" ';\r
+ $over = '';\r
+ \r
+ if($selected == $tmp_menu){\r
+ $func = '';\r
+ $over = '_over';\r
+ }\r
+ \r
+ $obj = '<td style="padding-top:13px;" '.$func.$link.' ><img id="img_'.$tmp_menu.'" src="../../img/pt/menu/'.$tmp_menu.$over.'.jpg" /></td>';\r
+ return $obj;\r
+ }\r
+ function getInput($label,$sufixo,$name,$extra = "",$testDV = true,$type = "text"){\r
+ $obj = '';\r
+ switch($type){\r
+ case "text":\r
+ $func = ' onfocus="javascript: swapI(this,true);" onblur="javascript: swapI(this,false);" testDV="true" ';\r
+ $value = $label;\r
+ \r
+ if(!$testDV){\r
+ $func = '';\r
+ $value = '';\r
+ }\r
+ \r
+ $obj = '<input type="text" class="input" label="'.$label.'" id="'.$label.'_'.$sufixo.'" name="'.$name.'" value="'.$value.'" '.$extra.$func.' />';\r
+ break;\r
+ case "password":\r
+ $id = $label.'_'.$sufixo;\r
+ $func = ' onfocus="javascript: swapP(document.getElementById(\'div'.$id.'\'),true);" onblur="javascript: swapP(this,false);" ';\r
+ \r
+ $obj = '<div id="div'.$id.'" parent="'.$id.'" class="divPass" style="margin:7px;" onclick="javascript: swapP(this,true);">'.$label.'</div>';\r
+ if(!$testDV){\r
+ $func = '';\r
+ $obj = '';\r
+ }\r
+ $obj .= '<input type="password" class="input" label="'.$label.'" id="'.$id.'" name="'.$name.'" '.$extra.$func.' />';\r
+ break;\r
+ case "textarea":\r
+ $id = $label.'_'.$sufixo;\r
+ $func = ' onfocus="javascript: swapI(this,true);" onblur="javascript: swapI(this,false);" testDV="true" ';\r
+ $value = $label;\r
+ \r
+ if(!$testDV){\r
+ $func = '';\r
+ $value = '';\r
+ }\r
+ \r
+ $obj .= '<textarea class="input" label="'.$label.'" id="'.$id.'" name="'.$name.'" '.$extra.$func.' >'.$value.'</textarea>';\r
+ break;\r
+ }\r
+ return $obj;\r
+ }\r
+ function getSelect($arr,$label,$sufixo,$name,$extra = "",$secondItem = "------",$selected = ""){\r
+ $obj = '';\r
+ $total = sizeof($arr);\r
+ \r
+ if($total > 0){\r
+ $obj = '<select id="'.$label.'_'.$sufixo.'" name="'.$name.'" class="input" '.$extra.' '.$this->alt($label).' >';\r
+ $obj .= ' <option value="" '.$this->alt($label).'>'.$label.'</option>';\r
+ $obj .= ' <option value="" '.$this->alt($label).'>'.$secondItem.'</option>';\r
+ \r
+ $inlineSelected = "";\r
+ foreach($arr as $k => $v){\r
+ if(($selected == $k) && ($selected != "")){\r
+ $inlineSelected = " selected ";\r
+ } else {\r
+ $inlineSelected = "";\r
+ }\r
+ $obj .= ' <option value="'.$k.'" '.$inlineSelected.' '.$this->alt($v).'>'.$v.'</option>';\r
+ }\r
+ $obj .= '</select>';\r
+ }\r
+ \r
+ return $obj;\r
+ }\r
+ function getSelectByRows($rows,$label,$sufixo,$name,$extra = "",$secondItem = "------",$selected = ""){\r
+ $arr = Array();\r
+ \r
+ while(!$rows->EOF){\r
+ $arr[$rows->fields("id")] = $rows->fields("nome");\r
+ $rows->moveNext();\r
+ }\r
+ \r
+ return $this->getSelect($arr,$label,$sufixo,$name,$extra,$secondItem,$selected);\r
+ }\r
+ function getSelectByPagecount($pagecount,$label,$sufixo,$name,$extra = "",$zeroBased = true){\r
+ $arr = array();\r
+ for($x=1;$x<=$pagecount;$x++){\r
+ if($zeroBased){\r
+ $arr[] = $x;\r
+ } else {\r
+ $arr[$x] = $x;\r
+ }\r
+ }\r
+ \r
+ $obj = '';\r
+ $total = sizeof($arr);\r
+ \r
+ if($total > 0){\r
+ $obj = '<select id="'.$label.'_'.$sufixo.'" name="'.$name.'" class="input" '.$extra.' >';\r
+ foreach($arr as $k => $v){\r
+ $obj .= ' <option value="'.$k.'">'.$v.'</option>';\r
+ }\r
+ $obj .= '</select>';\r
+ }\r
+ \r
+ return $obj;\r
+ }\r
+ function getTitle($arr_caminho = array()){\r
+ global $cfg;\r
+ \r
+ if (sizeof($arr_caminho)>0) {\r
+ $titulo = '';\r
+ \r
+ for($x=0,$total=sizeof($arr_caminho);$x<$total;$x++){\r
+ $titulo .= $arr_caminho[$x][0] . ' - ';\r
+ }\r
+ $titulo .= 'FLY BY NIGHT';\r
+ } else {\r
+ $titulo = $cfg["site_title"]; \r
+ }\r
+ \r
+ echo('<title>'. $titulo .'</title>');\r
+ }\r
+ function getBoneco($label,$sufixo,$name){\r
+ $obj = '';\r
+ \r
+ $obj = '<div id="content_'.$name.'" style="padding-top:3px;">\r
+ <input type="hidden" label="'.$label.'" id="'.$label.'_'.$sufixo.'" name="'.$name.'" value="" />\r
+ <a href="javascript: openBoneco(\''.$name.'\');"><img src="../../img/common/body.gif" width="140" height="142" /></a><br />\r
+ <div id="results_'.$name.'"></div>\r
+ </div>';\r
+ \r
+ return $obj;\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Imagem{\r
+ //opções de listagem\r
+ var $arr_alfabeto;\r
+ var $arr_resultado;\r
+ var $arr_ordenar;\r
+ \r
+ //filtro - session\r
+ var $filtro_palavra;\r
+ var $filtro_procedencia;\r
+ var $filtro_sistema;\r
+ var $filtro_patologia;\r
+ var $filtro_alfabeto;\r
+ var $filtro_ordenar;\r
+ var $filtro_resultado;\r
+ \r
+ function Imagem(){\r
+ $this->arr_alfabeto = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','W');\r
+ $this->arr_resultado = array('08','16','32');\r
+ $this->arr_ordenar = array('Nome','Sistema','Patologia');\r
+ $this->getFiltrosFromSession();\r
+ }\r
+ function setAlfabetoImagem() {\r
+ global $input;\r
+ \r
+ if ($input->session('session_letras_imagem') != '') {\r
+ $this->arr_alfabeto_imagem = unserialize($input->session('session_letras_imagem'));\r
+ } else {\r
+ $rowsLetra = $this->findLetraImagem();\r
+ \r
+ while (!$rowsLetra->EOF) {\r
+ $this->arr_alfabeto_imagem[] = strtoupper($rowsLetra->fields('letra'));\r
+ $rowsLetra->moveNext();\r
+ }\r
+ $input->setSession('session_letras_imagem',serialize($this->arr_alfabeto_imagem));\r
+ }\r
+ }\r
+ function findLetraImagem() {\r
+ global $db;\r
+ \r
+ $sql = "SELECT DISTINCT(SUBSTRING(nome,1,1)) AS letra FROM sis_imagem WHERE visualizacao = 1 ORDER BY nome ASC";\r
+ return $db->execute($sql);\r
+ }\r
+ function getFiltrosFromSession(){\r
+ $this->setAlfabetoImagem();\r
+ \r
+ global $input;\r
+ $this->filtro_palavra = $input->session('session_image_filtro_palavra');\r
+ $this->filtro_procedencia = $input->session('session_image_filtro_procedencia');\r
+ $this->filtro_sistema = $input->session('session_image_filtro_sistema');\r
+ $this->filtro_patologia = $input->session('session_image_filtro_patologia');\r
+ \r
+ $this->filtro_ordenar = $input->get('image_filtro_ordenar');\r
+ if($this->filtro_ordenar == ''){\r
+ $this->filtro_ordenar = $input->session('session_image_filtro_ordenar');\r
+ if($this->filtro_ordenar == ''){\r
+ $this->filtro_ordenar = $this->arr_ordenar[0];\r
+ }\r
+ } else {\r
+ $input->setSession('session_image_filtro_ordenar',$this->filtro_ordenar);\r
+ }\r
+ \r
+ $this->filtro_resultado = $input->get('image_filtro_resultado');\r
+ if($this->filtro_resultado == ''){\r
+ $this->filtro_resultado = $input->session('session_image_filtro_resultado');\r
+ if($this->filtro_resultado == ''){\r
+ $this->filtro_resultado = $this->arr_resultado[0];\r
+ }\r
+ } else {\r
+ $input->setSession('session_image_filtro_resultado',$this->filtro_resultado);\r
+ }\r
+ }\r
+ function getResultado($tmp_baseLink = ''){\r
+ $html = '<div class="resultados">Resultados por página: ';\r
+ $total = sizeof($this->arr_resultado);\r
+ for($r=0;$r<$total;$r++){\r
+ if($this->arr_resultado[$r] == $this->filtro_resultado){\r
+ $html .= '<a href="'.$tmp_baseLink.'&image_filtro_resultado='.$this->arr_resultado[$r].'" class="underlaine" style="font-weight:bold; text-decoration:none;">'.$this->arr_resultado[$r].'</a>';\r
+ } else {\r
+ $html .= '<a href="'.$tmp_baseLink.'&image_filtro_resultado='.$this->arr_resultado[$r].'" class="underlaine">'.$this->arr_resultado[$r].'</a>';\r
+ }\r
+ if(($r+1) < $total){\r
+ $html .= ' ';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ return $html;\r
+ }\r
+ function getAlfabeto(){\r
+ $html = '<table cellspacing="0" cellpadding="0" width="100%"><tr>';\r
+ $total = sizeof($this->arr_alfabeto);\r
+ for($a=0;$a<$total;$a++){\r
+ if(in_array($this->arr_alfabeto[$a],$this->arr_alfabeto_imagem)){\r
+ $html .= '<td align="center"><a href="?letra='.$this->arr_alfabeto[$a].'" class="ltra">'.$this->arr_alfabeto[$a].'</a></td>';\r
+ } else {\r
+ $html .= '<td align="center" class="nletra" style="padding-left:3px; padding-right:3px;">'.$this->arr_alfabeto[$a].'</td>';\r
+ }\r
+ }\r
+ $html .= '</tr></table>';\r
+ return $html;\r
+ }\r
+ function getOrdenar($tmp_baseLink = ''){\r
+ $html = '<div class="ordenar">Ordenar por: ';\r
+ $total = sizeof($this->arr_ordenar);\r
+ for($x=0;$x<$total;$x++){\r
+ if($this->arr_ordenar[$x] == $this->filtro_ordenar){\r
+ $html .= '<a href="'.$tmp_baseLink.'&image_filtro_ordenar='.$this->arr_ordenar[$x].'" class="underlaine" style="text-decoration:none;font-weight:bold;">'.$this->arr_ordenar[$x].'</a>';\r
+ } else {\r
+ $html .= '<a href="'.$tmp_baseLink.'&image_filtro_ordenar='.$this->arr_ordenar[$x].'" class="underlaine">'.$this->arr_ordenar[$x].'</a>';\r
+ }\r
+ if(($x+1) < $total){\r
+ $html .= ' ';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ return $html;\r
+ }\r
+ function findLastImages(){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome FROM sis_imagem WHERE visualizacao = 1 ORDER BY dataorigem DESC LIMIT 9";\r
+ return $db->execute($sql);\r
+ }\r
+ function getImage($tmp_id,$tmp_thumb = 'p',$tmp_method = 2){//p,m,g\r
+ global $load;\r
+ $load->system('library/Image.php');\r
+ \r
+ $src = '';\r
+ $baseDot = '../../../';\r
+ $baseSrc = 'upload/sis_imagem/'.$tmp_id.'.jpg';\r
+ $baseThb = '_system/scripts/image.php';\r
+ if(file_exists($baseDot.$baseSrc)){\r
+ switch($tmp_thumb){\r
+ case 'pp':\r
+ if($tmp_method == 2){\r
+ $src = str_replace('sis_imagem','sis_imagem_pp',$baseDot.$baseSrc);\r
+ if(!file_exists($src)){\r
+ $img = new Image($baseDot.$baseSrc);\r
+ $img->resize(55, 48, 2);\r
+ $img->save($src);\r
+ }\r
+ } else {\r
+ $src = $baseDot.$baseThb.'?w=55&h=48&resize='.$tmp_method.'&file='.$baseSrc;\r
+ }\r
+ break;\r
+ case 'p':\r
+ if($tmp_method == 2){\r
+ $src = str_replace('sis_imagem','sis_imagem_p',$baseDot.$baseSrc);\r
+ if(!file_exists($src)){\r
+ $img = new Image($baseDot.$baseSrc);\r
+ $img->resize(86, 74, 2);\r
+ $img->save($src);\r
+ }\r
+ } else {\r
+ $src = $baseDot.$baseThb.'?w=86&h=74&resize='.$tmp_method.'&file='.$baseSrc;\r
+ }\r
+ break;\r
+ case 'm':\r
+ if($tmp_method == 2){\r
+ $src = str_replace('sis_imagem','sis_imagem_m',$baseDot.$baseSrc);\r
+ if(!file_exists($src)){\r
+ $img = new Image($baseDot.$baseSrc);\r
+ $img->resize(241, 207, 2);\r
+ $img->save($src);\r
+ }\r
+ } else {\r
+ $src = $baseDot.$baseThb.'?w=241&h=207&resize='.$tmp_method.'&file='.$baseSrc;\r
+ }\r
+ break;\r
+ case 'g':\r
+ $src = $baseDot.$baseThb.'?w=86&h=74&resize='.$tmp_method.'&file='.$baseSrc;\r
+ break;\r
+ }\r
+ }\r
+ return $src;\r
+ }\r
+ function findImageById($tmp_id){\r
+ global $db;\r
+ \r
+ if($tmp_id == ''){\r
+ $tmp_id = 0;\r
+ }\r
+ $sql = "SELECT i.id,\r
+ i.saudavel,\r
+ i.id_procedencia,\r
+ proc.nome as procedencia,\r
+ i.id_patologia,\r
+ pat.nome as patologia,\r
+ i.id_sistema,\r
+ sis.nome as sistema,\r
+ i.nome,\r
+ i.texto,\r
+ i.dataorigem,\r
+ i.id_grupoimagem,\r
+ i.carimbo\r
+ FROM sis_imagem i \r
+ LEFT OUTER JOIN sis_procedencia proc ON i.id_procedencia = proc.id \r
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id \r
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id\r
+ WHERE visualizacao = 1 AND i.id = ".$tmp_id;\r
+ return $db->execute($sql);\r
+ }\r
+ function dataorigem($tmp_dataorigem){\r
+ $obj = '';\r
+ if($tmp_dataorigem != ''){\r
+ $arr = explode('-',$tmp_dataorigem);\r
+ $obj = 'Data da imagem: '.$arr[2].'.'.$arr[1].'.'.$arr[0].'<br />';\r
+ }\r
+ return $obj;\r
+ }\r
+ function procedencia($tmp_procedencia){\r
+ $obj = '';\r
+ if($tmp_procedencia != ''){\r
+ $obj = 'Procedência: '.$tmp_procedencia.'<br />';\r
+ }\r
+ return $obj;\r
+ }\r
+ function getImgesRelacionadasByGrupo($tmp_idGrupo,$tmp_limit = ''){\r
+ global $db;\r
+ global $load;\r
+ global $input;\r
+ \r
+ $load->config('classes/Imagem.php');\r
+ $o_imagem = new Imagem();\r
+ \r
+ if($tmp_limit != ''){\r
+ $tmp_limit = " LIMIT ".$tmp_limit;\r
+ }\r
+ \r
+ $sql = "SELECT i.id,i.nome FROM sis_imagem i WHERE i.visualizacao = 1 AND i.id_grupoimagem = ".$tmp_idGrupo." ".$tmp_limit;\r
+ $rowsImagem = $db->execute($sql);\r
+ \r
+ if(!$rowsImagem->EOF){\r
+ $html = '';\r
+ while(!$rowsImagem->EOF){\r
+ $src = $o_imagem->getImage($rowsImagem->fields('id'),'pp');\r
+ if($src != ''){\r
+ $html .= '<div style="float:left;margin-left:5px;margin-top:5px;"><div style="width:55px; height:48px; cursor:pointer;" onclick="javascript: url(\'../imagens/view.php?id='.$input->encode($rowsImagem->fields('id')).'\');"><img src="'.$src.'" alt="'.$rowsImagem->fields('nome').'" title="'.$rowsImagem->fields('nome').'" /></div></div>';\r
+ }\r
+ $rowsImagem->moveNext();\r
+ }\r
+ return $html;\r
+ } else {\r
+ return '';\r
+ }\r
+ }\r
+ function orgaosrelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT o.id, o.nome FROM sis_orgao o INNER JOIN sis_imagem_orgao io ON io.id_orgao = o.id WHERE io.id_imagem = ".$tmp_id." ORDER BY nome ASC";\r
+ $rowsOrgao = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsOrgao->EOF){\r
+ $obj .= 'Orgãos Relacionados:<br/>';\r
+ while(!$rowsOrgao->EOF){\r
+ $obj .= '<small><a href="javascript:url(\'../orgaos/view.php?id='.$input->encode($rowsOrgao->fields('id')).'\');">'.$rowsOrgao->fields('nome').'</a></small><br/>';\r
+ $rowsOrgao->moveNext();\r
+ }\r
+ }\r
+ return $obj;\r
+ }\r
+ function diagnosticosrelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT d.id, d.nome FROM sis_diagnostico d INNER JOIN sis_diagnostico_imagem di ON di.id_diagnostico = d.id WHERE d.visualizacao = 1 AND di.id_imagem = ".$tmp_id." ORDER BY d.nome ASC";\r
+ $rowsDiagnostico = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsDiagnostico->EOF){\r
+ while(!$rowsDiagnostico->EOF){\r
+ $obj .= '<div class="divlist"><a href="javascript:url(\'../diagnosticos/view.php?id='.$input->encode($rowsDiagnostico->fields('id')).'\');">'.$rowsDiagnostico->fields('nome').'</a></div>';\r
+ $rowsDiagnostico->moveNext();\r
+ }\r
+ } else {\r
+ $obj = 'Nenhum diagnóstico relacionado.';\r
+ }\r
+ return $obj;\r
+ }\r
+ function casosdeestudorelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT c.id, c.nome FROM sis_casoestudo c INNER JOIN sis_casoestudo_imagem ci ON ci.id_casoestudo = c.id WHERE c.visualizacao = 1 AND ci.id_imagem = ".$tmp_id." ORDER BY c.nome ASC";\r
+ $rowsCasoEstudo = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsCasoEstudo->EOF){\r
+ while(!$rowsCasoEstudo->EOF){\r
+ $obj .= '<div class="divlist"><a href="javascript:url(\'../casosdeestudo/view.php?id='.$input->encode($rowsCasoEstudo->fields('id')).'\');">'.$rowsCasoEstudo->fields('nome').'</a></div>';\r
+ $rowsCasoEstudo->moveNext();\r
+ }\r
+ } else {\r
+ $obj = 'Nenhum caso de estudo relacionado.';\r
+ }\r
+ return $obj;\r
+ }\r
+ function searchLetter($tmp_letra){\r
+ global $db;\r
+ \r
+ $sql = "SELECT i.id,\r
+ i.saudavel,\r
+ i.id_procedencia,\r
+ proc.nome as procedencia,\r
+ i.id_patologia,\r
+ pat.nome as patologia,\r
+ i.id_sistema,\r
+ sis.nome as sistema,\r
+ i.nome,\r
+ i.texto,\r
+ i.dataorigem\r
+ FROM sis_imagem i \r
+ LEFT OUTER JOIN sis_procedencia proc ON i.id_procedencia = proc.id \r
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id \r
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id\r
+ WHERE i.visualizacao = 1 AND i.saudavel = 0 AND i.nome like '".$tmp_letra."%' ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function simpleSeach($tmp_palavraChave,$tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = ''){\r
+ global $db;\r
+ global $o_helper;\r
+ $o_helper->somaBusca($tmp_palavraChave);\r
+ \r
+ $andProcedencia = '';\r
+ if($tmp_procedencia != ''){\r
+ $andProcedencia = ' AND i.id_procedencia = '.$tmp_procedencia.' ';\r
+ }\r
+ $andSistema = '';\r
+ if($tmp_sistema != ''){\r
+ $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' ';\r
+ }\r
+ $andPatologia = '';\r
+ if($tmp_patologia != ''){\r
+ $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' ';\r
+ }\r
+ $andGrupoOrgao = '';\r
+ if($tmp_grupoorgao != ''){\r
+ $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' ';\r
+ }\r
+ \r
+ $sql = "SELECT i.id,\r
+ i.saudavel,\r
+ i.id_procedencia,\r
+ proc.nome as procedencia,\r
+ i.id_patologia,\r
+ pat.nome as patologia,\r
+ i.id_sistema,\r
+ sis.nome as sistema,\r
+ i.nome,\r
+ i.texto,\r
+ i.dataorigem\r
+ FROM sis_imagem i \r
+ LEFT OUTER JOIN sis_procedencia proc ON i.id_procedencia = proc.id \r
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id \r
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id\r
+ \r
+ LEFT OUTER JOIN sis_diagnostico_imagem di ON i.id = di.id_imagem\r
+ LEFT OUTER JOIN sis_diagnostico d ON di.id_diagnostico = d.id\r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_imagem ci ON i.id = ci.id_imagem\r
+ LEFT OUTER JOIN sis_casoestudo c ON ci.id_casoestudo = c.id\r
+ \r
+ LEFT OUTER JOIN sis_imagem_orgao io ON i.id = io.id_imagem\r
+ LEFT OUTER JOIN sis_orgao o ON io.id_orgao = o.id\r
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao\r
+ \r
+ WHERE i.visualizacao = 1 AND i.saudavel = 0 AND (\r
+ i.nome like '%".$tmp_palavraChave."%' OR \r
+ i.texto like '%".$tmp_palavraChave."%' OR \r
+ proc.nome like '%".$tmp_palavraChave."%' OR \r
+ pat.nome like '%".$tmp_palavraChave."%' OR \r
+ sis.nome like '%".$tmp_palavraChave."%' OR \r
+ d.nome like '%".$tmp_palavraChave."%' OR \r
+ d.palavrachave like '%".$tmp_palavraChave."%' OR \r
+ o.nome like '%".$tmp_palavraChave."%' OR \r
+ o.palavrachave like '%".$tmp_palavraChave."%' OR \r
+ c.nome like '%".$tmp_palavraChave."%' OR \r
+ c.palavrachave like '%".$tmp_palavraChave."%' \r
+ ) ".$andProcedencia.$andSistema.$andPatologia.$andGrupoOrgao." GROUP BY i.id ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function complexSeach($arrPalavra,$tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = ''){\r
+ global $db;\r
+ global $o_helper;\r
+ \r
+ $andProcedencia = '';\r
+ if($tmp_procedencia != ''){\r
+ $andProcedencia = ' AND i.id_procedencia = '.$tmp_procedencia.' ';\r
+ }\r
+ $andSistema = '';\r
+ if($tmp_sistema != ''){\r
+ $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' ';\r
+ }\r
+ $andPatologia = '';\r
+ if($tmp_patologia != ''){\r
+ $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' ';\r
+ }\r
+ $andGrupoOrgao = '';\r
+ if($tmp_grupoorgao != ''){\r
+ $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' ';\r
+ }\r
+ \r
+ $fixedWhere = " i.visualizacao = 1 AND i.saudavel = 0 ".$andProcedencia.$andSistema.$andPatologia.$andGrupoOrgao;\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "i.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "i.texto like '%#PALAVRA#%'";\r
+ $arrWhere[] = "proc.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "pat.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "sis.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "d.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "d.palavrachave like '%#PALAVRA#%'";\r
+ $arrWhere[] = "o.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "o.palavrachave like '%#PALAVRA#%'";\r
+ $arrWhere[] = "c.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "c.palavrachave like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT i.id,\r
+ i.saudavel,\r
+ i.id_procedencia,\r
+ proc.nome as procedencia,\r
+ i.id_patologia,\r
+ pat.nome as patologia,\r
+ i.id_sistema,\r
+ sis.nome as sistema,\r
+ i.nome,\r
+ i.texto,\r
+ i.dataorigem\r
+ FROM sis_imagem i \r
+ LEFT OUTER JOIN sis_procedencia proc ON i.id_procedencia = proc.id \r
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id \r
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id\r
+ \r
+ LEFT OUTER JOIN sis_diagnostico_imagem di ON i.id = di.id_imagem\r
+ LEFT OUTER JOIN sis_diagnostico d ON di.id_diagnostico = d.id\r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_imagem ci ON i.id = ci.id_imagem\r
+ LEFT OUTER JOIN sis_casoestudo c ON ci.id_casoestudo = c.id\r
+ \r
+ LEFT OUTER JOIN sis_imagem_orgao io ON i.id = io.id_imagem\r
+ LEFT OUTER JOIN sis_orgao o ON io.id_orgao = o.id\r
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao\r
+ #WHERE#\r
+ GROUP BY i.id ".$this->getOrderBy();\r
+ \r
+ return $db->execute($o_helper->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function getOrderBy(){\r
+ switch($this->filtro_ordenar){\r
+ case 'Nome':\r
+ return ' ORDER BY i.nome ASC';\r
+ break;\r
+ case 'Sistema':\r
+ return ' ORDER BY sistema ASC';\r
+ break;\r
+ case 'Patologia':\r
+ return ' ORDER BY patologia ASC';\r
+ break;\r
+ }\r
+ }\r
+ function verifyWaterMark($tmp_id,$tmp_carimbo,$tmp_overwrite = false){\r
+ if($tmp_carimbo != 4){\r
+ global $load;\r
+ global $input;\r
+ \r
+ $baseBack = '../../../';\r
+ $basePath = 'upload/sis_imagem/'.$tmp_id.'.jpg';\r
+ $baseNewPath = str_replace('sis_imagem','sis_imagem_wm',$basePath);\r
+ $wm_Path = '_config/img/logo.png';\r
+ \r
+ $padding = 15;\r
+ $wm_width = 85;//largura da imagem de marca d'agua\r
+ $wm_height = 82;//altura da imagem de marca d'agua\r
+ \r
+ if((file_exists($baseBack.$basePath)) && (($tmp_overwrite) || (!file_exists($baseBack.$baseNewPath)))){\r
+ $load->system('library/Image.php');\r
+ $img = new Image($baseBack.$basePath);\r
+ \r
+ //calcula posição inicial da marca d'agua conforme a escolha do usuario\r
+ $tmp_x = 0;\r
+ $tmp_y = 0;\r
+ switch($tmp_carimbo){\r
+ case 0://Esquerdo superior\r
+ $tmp_x = $padding;\r
+ $tmp_y = $padding;\r
+ break;\r
+ case 1://Direito superior\r
+ $tmp_x = $img->width - $wm_width - $padding;\r
+ $tmp_y = $padding;\r
+ break;\r
+ case 2://Esquerdo inferior\r
+ $tmp_x = $padding;\r
+ $tmp_y = $img->height - $wm_height - $padding;\r
+ break;\r
+ case 3://Direito inferior\r
+ $tmp_x = $img->width - $wm_width - $padding;\r
+ $tmp_y = $img->height - $wm_height - $padding;\r
+ break;\r
+ }\r
+ \r
+ $img->waterMark($baseBack.$wm_Path,$tmp_x,$tmp_y,$baseBack.$baseNewPath);\r
+ }\r
+ }\r
+ }\r
+ function saudavel($tmp_saudavel){\r
+ if($tmp_saudavel == '1'){\r
+ return '<span class="saudavel">(saudável)</span>';\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Orgao{\r
+ //opções de listagem\r
+ var $arr_alfabeto;\r
+ var $arr_resultado;\r
+ var $arr_ordenar;\r
+ \r
+ //filtro - session\r
+ var $filtro_palavra;\r
+ var $filtro_procedencia;\r
+ var $filtro_sistema;\r
+ var $filtro_patologia;\r
+ var $filtro_alfabeto;\r
+ var $filtro_ordenar;\r
+ var $filtro_resultado;\r
+ \r
+ function Orgao(){\r
+ $this->arr_alfabeto = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','W');\r
+ $this->arr_resultado = array('08','16','32');\r
+ $this->arr_ordenar = array('Nome');\r
+ $this->getFiltrosFromSession();\r
+ }\r
+ function setAlfabetoOrgao() {\r
+ global $input;\r
+ \r
+ if ($input->session('session_letras_orgao') != '') {\r
+ $this->arr_alfabeto_orgao = unserialize($input->session('session_letras_orgao'));\r
+ } else {\r
+ $rowsLetra = $this->findLetraOrgao();\r
+ \r
+ while (!$rowsLetra->EOF) {\r
+ $this->arr_alfabeto_orgao[] = strtoupper($rowsLetra->fields('letra'));\r
+ $rowsLetra->moveNext();\r
+ }\r
+ $input->setSession('session_letras_orgao',serialize($this->arr_alfabeto_orgao));\r
+ }\r
+ }\r
+ function findLetraorgao() {\r
+ global $db;\r
+ \r
+ $sql = "SELECT DISTINCT(SUBSTRING(nome,1,1)) AS letra FROM sis_orgao ORDER BY nome ASC";\r
+ return $db->execute($sql);\r
+ }\r
+ function getFiltrosFromSession(){\r
+ $this->setAlfabetoOrgao();\r
+ \r
+ global $input;\r
+ $this->filtro_palavra = $input->session('session_orgao_filtro_palavra');\r
+ $this->filtro_procedencia = $input->session('session_orgao_filtro_procedencia');\r
+ $this->filtro_sistema = $input->session('session_orgao_filtro_sistema');\r
+ $this->filtro_patologia = $input->session('session_orgao_filtro_patologia');\r
+ \r
+ $this->filtro_ordenar = $input->get('orgao_filtro_ordenar');\r
+ if($this->filtro_ordenar == ''){\r
+ $this->filtro_ordenar = $input->session('session_orgao_filtro_ordenar');\r
+ if($this->filtro_ordenar == ''){\r
+ $this->filtro_ordenar = $this->arr_ordenar[0];\r
+ }\r
+ } else {\r
+ $input->setSession('session_orgao_filtro_ordenar',$this->filtro_ordenar);\r
+ }\r
+ \r
+ $this->filtro_resultado = $input->get('orgao_filtro_resultado');\r
+ if($this->filtro_resultado == ''){\r
+ $this->filtro_resultado = $input->session('session_orgao_filtro_resultado');\r
+ if($this->filtro_resultado == ''){\r
+ $this->filtro_resultado = $this->arr_resultado[0];\r
+ }\r
+ } else {\r
+ $input->setSession('session_orgao_filtro_resultado',$this->filtro_resultado);\r
+ }\r
+ }\r
+ function getResultado($tmp_baseLink = ''){\r
+ $html = '<div class="resultados">Resultados por página: ';\r
+ $total = sizeof($this->arr_resultado);\r
+ for($r=0;$r<$total;$r++){\r
+ if($this->arr_resultado[$r] == $this->filtro_resultado){\r
+ $html .= '<a href="'.$tmp_baseLink.'&orgao_filtro_resultado='.$this->arr_resultado[$r].'" class="underlaine" style="font-weight:bold; text-decoration:none;">'.$this->arr_resultado[$r].'</a>';\r
+ } else {\r
+ $html .= '<a href="'.$tmp_baseLink.'&orgao_filtro_resultado='.$this->arr_resultado[$r].'" class="underlaine">'.$this->arr_resultado[$r].'</a>';\r
+ }\r
+ if(($r+1) < $total){\r
+ $html .= ' ';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ return $html;\r
+ }\r
+ function getAlfabeto(){\r
+ $html = '<table cellspacing="0" cellpadding="0" width="100%"><tr>';\r
+ $total = sizeof($this->arr_alfabeto);\r
+ for($a=0;$a<$total;$a++){\r
+ if(in_array($this->arr_alfabeto[$a],$this->arr_alfabeto_orgao)){\r
+ $html .= '<td align="center"><a href="?letra='.$this->arr_alfabeto[$a].'" class="ltra">'.$this->arr_alfabeto[$a].'</a></td>';\r
+ } else {\r
+ $html .= '<td align="center" class="nletra" style="padding-left:3px; padding-right:3px;">'.$this->arr_alfabeto[$a].'</td>';\r
+ }\r
+ }\r
+ $html .= '</tr></table>';\r
+ return $html;\r
+ }\r
+ function getOrdenar($tmp_baseLink = ''){\r
+ $html = '<div class="ordenar">Ordenar por: ';\r
+ $total = sizeof($this->arr_ordenar);\r
+ for($x=0;$x<$total;$x++){\r
+ if($this->arr_ordenar[$x] == $this->filtro_ordenar){\r
+ $html .= '<a href="'.$tmp_baseLink.'&orgao_filtro_ordenar='.$this->arr_ordenar[$x].'" class="underlaine" style="text-decoration:none;font-weight:bold;">'.$this->arr_ordenar[$x].'</a>';\r
+ } else {\r
+ $html .= '<a href="'.$tmp_baseLink.'&orgao_filtro_ordenar='.$this->arr_ordenar[$x].'" class="underlaine">'.$this->arr_ordenar[$x].'</a>';\r
+ }\r
+ if(($x+1) < $total){\r
+ $html .= ' ';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ return $html;\r
+ }\r
+ function getImage($tmp_id,$tmp_thumb = 'p',$tmp_method = 2){//p,m,g\r
+ $src = '';\r
+ $baseDot = '../../../';\r
+ $baseSrc = 'upload/sis_orgao/'.$tmp_id.'.jpg';\r
+ $baseThb = '_system/scripts/image.php';\r
+ if(file_exists($baseDot.$baseSrc)){\r
+ switch($tmp_thumb){\r
+ case 'pp':\r
+ $src = $baseDot.$baseThb.'?w=55&h=48&resize='.$tmp_method.'&file='.$baseSrc;\r
+ break;\r
+ case 'p':\r
+ $src = $baseDot.$baseThb.'?w=86&h=74&resize='.$tmp_method.'&file='.$baseSrc;\r
+ break;\r
+ case 'm':\r
+ $src = $baseDot.$baseThb.'?w=241&h=207&resize='.$tmp_method.'&file='.$baseSrc;\r
+ break;\r
+ case 'g':\r
+ $src = $baseDot.$baseThb.'?w=86&h=74&resize='.$tmp_method.'&file='.$baseSrc;\r
+ break;\r
+ }\r
+ }\r
+ return $src;\r
+ }\r
+ function searchLetter($tmp_letra){\r
+ global $db;\r
+ \r
+ $sql = "SELECT o.id,\r
+ o.nome\r
+ FROM sis_orgao o \r
+ WHERE o.nome like '".$tmp_letra."%' ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function findAll(){\r
+ global $db;\r
+ \r
+ $sql = "SELECT o.id,\r
+ o.nome\r
+ FROM sis_orgao o ";\r
+ return $db->execute($sql);\r
+ }\r
+ function simpleSeach($tmp_palavraChave,$tmp_grupoorgao = '',$tmp_sistema = ''){\r
+ global $db;\r
+ global $o_helper;\r
+ $o_helper->somaBusca($tmp_palavraChave);\r
+ \r
+ $andPalavraChave = '';\r
+ if($tmp_palavraChave != ''){\r
+ $andPalavraChave = " AND (\r
+ o.nome like '%".$tmp_palavraChave."%' OR \r
+ o.palavrachave like '%".$tmp_palavraChave."%' OR \r
+ \r
+ g.nome like '%".$tmp_palavraChave."%' OR \r
+ s.nome like '%".$tmp_palavraChave."%' OR \r
+ i.nome like '%".$tmp_palavraChave."%' OR \r
+ i.texto like '%".$tmp_palavraChave."%' OR \r
+ d.nome like '%".$tmp_palavraChave."%' OR \r
+ d.texto like '%".$tmp_palavraChave."%' OR \r
+ d.palavrachave like '%".$tmp_palavraChave."%' OR \r
+ ce.nome like '%".$tmp_palavraChave."%' OR \r
+ ce.texto like '%".$tmp_palavraChave."%' OR \r
+ ce.palavrachave like '%".$tmp_palavraChave."%' \r
+ ) ";\r
+ }\r
+ $andGrupoOrgao = '';\r
+ if($tmp_grupoorgao != ''){\r
+ $andGrupoOrgao = ' AND g.id = '.$tmp_grupoorgao.' ';\r
+ }\r
+ $andSistema = '';\r
+ if($tmp_sistema != ''){\r
+ $andSistema = ' AND s.id = '.$tmp_sistema.' ';\r
+ }\r
+ \r
+ $sql = "SELECT o.id,\r
+ o.nome\r
+ FROM sis_orgao o \r
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao\r
+ LEFT OUTER JOIN sis_grupoorgao g ON og.id_grupoorgao = g.id\r
+ \r
+ LEFT OUTER JOIN sis_orgao_sistema os ON o.id = os.id_orgao\r
+ LEFT OUTER JOIN sis_sistema s ON os.id_sistema = s.id\r
+ \r
+ LEFT OUTER JOIN sis_imagem_orgao io ON o.id = io.id_orgao\r
+ LEFT OUTER JOIN sis_imagem i ON io.id_imagem = i.id\r
+ \r
+ LEFT OUTER JOIN sis_diagnostico_orgao do ON o.id = do.id_orgao\r
+ LEFT OUTER JOIN sis_diagnostico d ON do.id_diagnostico = d.id\r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_orgao ceo ON o.id = ceo.id_orgao\r
+ LEFT OUTER JOIN sis_casoestudo ce ON ceo.id_casoestudo = ce.id\r
+ \r
+ WHERE 1 = 1 ".$andPalavraChave.$andGrupoOrgao.$andSistema." GROUP BY o.id ".$this->getOrderBy();\r
+ return $db->execute($sql);\r
+ }\r
+ function complexSeach($arrPalavra,$tmp_grupoorgao = '',$tmp_sistema = ''){\r
+ global $db;\r
+ global $o_helper;\r
+ \r
+ $andGrupoOrgao = '';\r
+ if($tmp_grupoorgao != ''){\r
+ $andGrupoOrgao = ' AND g.id = '.$tmp_grupoorgao.' ';\r
+ }\r
+ $andSistema = '';\r
+ if($tmp_sistema != ''){\r
+ $andSistema = ' AND s.id = '.$tmp_sistema.' ';\r
+ }\r
+ \r
+ $fixedWhere = " 1 = 1 ".$andGrupoOrgao.$andSistema;\r
+ \r
+ $arrWhere = array();\r
+ $arrWhere[] = "o.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "o.palavrachave like '%#PALAVRA#%'";\r
+ $arrWhere[] = "g.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "s.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "i.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "i.texto like '%#PALAVRA#%'";\r
+ $arrWhere[] = "d.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "d.texto like '%#PALAVRA#%'";\r
+ $arrWhere[] = "d.palavrachave like '%#PALAVRA#%'";\r
+ $arrWhere[] = "ce.nome like '%#PALAVRA#%'";\r
+ $arrWhere[] = "ce.texto like '%#PALAVRA#%'";\r
+ $arrWhere[] = "ce.palavrachave like '%#PALAVRA#%'";\r
+ \r
+ $baseSql = "SELECT o.id,\r
+ o.nome\r
+ FROM sis_orgao o \r
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao\r
+ LEFT OUTER JOIN sis_grupoorgao g ON og.id_grupoorgao = g.id\r
+ \r
+ LEFT OUTER JOIN sis_orgao_sistema os ON o.id = os.id_orgao\r
+ LEFT OUTER JOIN sis_sistema s ON os.id_sistema = s.id\r
+ \r
+ LEFT OUTER JOIN sis_imagem_orgao io ON o.id = io.id_orgao\r
+ LEFT OUTER JOIN sis_imagem i ON io.id_imagem = i.id\r
+ \r
+ LEFT OUTER JOIN sis_diagnostico_orgao do ON o.id = do.id_orgao\r
+ LEFT OUTER JOIN sis_diagnostico d ON do.id_diagnostico = d.id\r
+ \r
+ LEFT OUTER JOIN sis_casoestudo_orgao ceo ON o.id = ceo.id_orgao\r
+ LEFT OUTER JOIN sis_casoestudo ce ON ceo.id_casoestudo = ce.id\r
+ #WHERE#\r
+ GROUP BY o.id ".$this->getOrderBy();\r
+ \r
+ return $db->execute($o_helper->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere));\r
+ }\r
+ function sistemasrelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT s.id, s.nome FROM sis_sistema s INNER JOIN sis_orgao_sistema os ON os.id_sistema = s.id WHERE os.id_orgao = ".$tmp_id." ORDER BY s.nome ASC";\r
+ $rowsSistema = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsSistema->EOF){\r
+ while(!$rowsSistema->EOF){\r
+ $obj .= '<small>'.$rowsSistema->fields('nome').'</small>';\r
+ $rowsSistema->moveNext();\r
+ if(!$rowsSistema->EOF){\r
+ $obj .= ', ';\r
+ }\r
+ }\r
+ if($obj != ''){\r
+ $obj = '<i>Sistemas</i><br/>'.$obj;\r
+ }\r
+ } else {\r
+ $obj = 'Nenhum sistema relacionado.';\r
+ }\r
+ return $obj;\r
+ }\r
+ function grupodeorgaorelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT g.id, g.nome FROM sis_grupoorgao g INNER JOIN sis_orgao_grupoorgao go ON go.id_grupoorgao = g.id WHERE go.id_orgao = ".$tmp_id." ORDER BY g.nome ASC";\r
+ $rowsGrupoOrgao = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsGrupoOrgao->EOF){\r
+ while(!$rowsGrupoOrgao->EOF){\r
+ $obj .= '<small>'.$rowsGrupoOrgao->fields('nome').'</small>';\r
+ $rowsGrupoOrgao->moveNext();\r
+ if(!$rowsGrupoOrgao->EOF){\r
+ $obj .= ', ';\r
+ }\r
+ }\r
+ if($obj != ''){\r
+ $obj = '<i>Topografia</i><br/>'.$obj;\r
+ }\r
+ } else {\r
+ $obj = 'Nenhum grupo de órgão relacionado.';\r
+ }\r
+ return $obj;\r
+ }\r
+ function getImgesRelacionadas($tmp_id,$tmp_limit = ''){\r
+ global $db;\r
+ global $load;\r
+ global $input;\r
+ \r
+ $load->config('classes/Imagem.php');\r
+ $o_imagem = new Imagem();\r
+ \r
+ if($tmp_limit != ''){\r
+ $tmp_limit = " LIMIT ".$tmp_limit;\r
+ }\r
+ \r
+ $sql = "SELECT io.id_imagem,i.nome FROM sis_imagem_orgao io INNER JOIN \r
+ sis_imagem i ON i.id = id_imagem WHERE i.visualizacao = 1 AND io.id_orgao = ".$tmp_id." ".$tmp_limit;\r
+ $rowsImagem = $db->execute($sql);\r
+ if(!$rowsImagem->EOF){\r
+ $html = '';\r
+ while(!$rowsImagem->EOF){\r
+ $src = $o_imagem->getImage($rowsImagem->fields('id_imagem'),'pp');\r
+ if($src != ''){\r
+ $html .= '<div style="float:left;margin-left:5px;margin-top:5px;"><div style="width:55px; height:48px; cursor:pointer;" onclick="javascript: url(\'../imagens/view.php?id='.$input->encode($rowsImagem->fields('id_imagem')).'\');"><img src="'.$src.'" alt="'.$rowsImagem->fields('nome').'" title="'.$rowsImagem->fields('nome').'" /></div></div>';\r
+ }\r
+ $rowsImagem->moveNext();\r
+ }\r
+ return $html;\r
+ } else {\r
+ return '';\r
+ }\r
+ }\r
+ function diagnosticosrelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT d.id, d.nome FROM sis_diagnostico d INNER JOIN sis_diagnostico_orgao di ON di.id_diagnostico = d.id WHERE d.visualizacao = 1 AND di.id_orgao = ".$tmp_id." ORDER BY d.nome ASC";\r
+ $rowsDiagnostico = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsDiagnostico->EOF){\r
+ while(!$rowsDiagnostico->EOF){\r
+ $obj .= '<div class="divlist"><a href="javascript:url(\'../diagnosticos/view.php?id='.$input->encode($rowsDiagnostico->fields('id')).'\');">'.$rowsDiagnostico->fields('nome').'</a></div>';\r
+ $rowsDiagnostico->moveNext();\r
+ }\r
+ } else {\r
+ $obj = 'Nenhum diagnóstico relacionado.';\r
+ }\r
+ return $obj;\r
+ }\r
+ function casosdeestudorelacionados($tmp_id){\r
+ global $db;\r
+ global $input;\r
+ \r
+ $sql = "SELECT c.id, c.nome FROM sis_casoestudo c INNER JOIN sis_casoestudo_orgao ci ON ci.id_casoestudo = c.id WHERE c.visualizacao = 1 AND ci.id_orgao = ".$tmp_id." ORDER BY c.nome ASC";\r
+ $rowsCasoEstudo = $db->execute($sql);\r
+ \r
+ $obj = '';\r
+ if(!$rowsCasoEstudo->EOF){\r
+ while(!$rowsCasoEstudo->EOF){\r
+ $obj .= '<div class="divlist"><a href="javascript:url(\'../casosdeestudo/view.php?id='.$input->encode($rowsCasoEstudo->fields('id')).'\');">'.$rowsCasoEstudo->fields('nome').'</a></div>';\r
+ $rowsCasoEstudo->moveNext();\r
+ }\r
+ } else {\r
+ $obj = 'Nenhum caso de estudo relacionado.';\r
+ }\r
+ return $obj;\r
+ }\r
+ function findOrgaoById($tmp_id){\r
+ global $db;\r
+ \r
+ $sql = "SELECT id,nome,texto,pagina,palavrachave FROM sis_orgao WHERE id = ".$tmp_id;\r
+ return $db->execute($sql);\r
+ }\r
+ function getOrderBy(){\r
+ switch($this->filtro_ordenar){\r
+ case 'Nome':\r
+ return ' ORDER BY o.nome ASC';\r
+ break;\r
+ case 'Sistema':\r
+ return ' ORDER BY sistema ASC';\r
+ break;\r
+ case 'Patologia':\r
+ return ' ORDER BY patologia ASC';\r
+ break;\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Palavra {\r
+ var $tabela;\r
+ \r
+ function Palavra($tmp_tabela = 'sis_palavra') {\r
+ $this->tabela = $tmp_tabela;\r
+ }\r
+ \r
+ function retornaInexistentes($todas){\r
+ $palavra = array();\r
+ if(is_array($todas))\r
+ $palavra = array_unique($todas);\r
+ \r
+ global $db;\r
+ $arr_existentes = array();\r
+ \r
+ if(is_array($todas))\r
+ $sql = "SELECT palavra FROM ".$this->tabela." WHERE palavra COLLATE latin1_bin in ('".implode("','", $palavra)."')";\r
+ else\r
+ $sql = "SELECT palavra FROM ".$this->tabela." WHERE palavra COLLATE latin1_bin = '".$todas."'";\r
+ \r
+ $rs = $db->execute($sql); \r
+ while(!$rs->EOF) {\r
+ $arr_existentes[] = $rs->fields("palavra");\r
+ $rs->moveNext();\r
+ }\r
+ \r
+ $arr_retorno = array();\r
+\r
+ if(is_array($todas)){\r
+ for($z=0;$z<sizeof($palavra);$z++){\r
+ if (isset($palavra[$z])) {\r
+ if((!(array_search($palavra[$z],$arr_existentes) > -1))&&($palavra[$z] != '')){\r
+ array_push($arr_retorno,$palavra[$z]);\r
+ }\r
+ }\r
+ }\r
+ }else{\r
+ if((!(array_search($todas,$arr_existentes) > -1))&&($todas != '')){\r
+ array_push($arr_retorno,$todas);\r
+ }\r
+ }\r
+ \r
+ return $arr_retorno;\r
+ }\r
+ \r
+ //private \r
+ function existePalavra($palavra) {\r
+ global $db;\r
+ $arr_existentes = array();\r
+ \r
+ if(is_array($palavra))\r
+ $sql = "SELECT distinct palavra FROM ".$this->tabela." WHERE palavra in ('".implode("','", $palavra)."')";\r
+ else\r
+ $sql = "SELECT distinct palavra FROM ".$this->tabela." WHERE palavra = '".$palavra."'";\r
+ $rs = $db->execute($sql);\r
+ \r
+ while(!$rs->EOF) {\r
+ $arr_existentes[] = $rs->fields("palavra");\r
+ $rs->moveNext();\r
+ }\r
+ \r
+ return $arr_existentes;\r
+ }\r
+ \r
+ //busca por um array de palavras no banco e retorna as que existem\r
+ //private \r
+ function existePalavras($arr_palavras) {\r
+ global $db;\r
+ \r
+ $sql = "SELECT distinct palavra FROM ".$this->tabela." WHERE palavra in ('".implode("','", $arr_palavras)."')";\r
+ $rs = $db->execute($sql);\r
+ \r
+ while(!$rs->EOF) {\r
+ $arr_existentes[] = $rs->fields("palavra");\r
+ $rs->moveNext();\r
+ }\r
+ \r
+ return $arr_existentes;\r
+ }\r
+ \r
+ //private \r
+ function salvaPalavras($palavras) {\r
+ global $db;\r
+ if(is_array($palavras)) {\r
+ if((sizeof($palavras) > 0)&&($palavras[0] != '')) {\r
+ $sql = "INSERT INTO ".$this->tabela." (palavra) VALUES('".implode("'),('",$palavras)."')";\r
+ $rs = $db->execute($sql);\r
+ }\r
+ }else{\r
+ if($palavras != ''){\r
+ $sql = "INSERT INTO ".$this->tabela." (palavra) VALUES('".$palavras."')";\r
+ $rs = $db->execute($sql);\r
+ }\r
+ }\r
+ }\r
+ \r
+ function retiraPontos($string, $troca = " "){\r
+ $string = strtolower($string);\r
+ $string = strip_tags($string);\r
+ $string = str_replace(",",$troca,$string);\r
+ $string = str_replace(".",$troca,$string);\r
+ $string = str_replace(":",$troca,$string);\r
+ $string = str_replace("?",$troca,$string);\r
+ $string = str_replace("!",$troca,$string);\r
+ $string = str_replace(";",$troca,$string);\r
+ $string = str_replace("<br>",$troca,$string);\r
+ $string = str_replace("<",$troca,$string);\r
+ $string = str_replace(">",$troca,$string);\r
+ $string = str_replace("[",$troca,$string);\r
+ $string = str_replace("]",$troca,$string);\r
+ $string = str_replace("{",$troca,$string);\r
+ $string = str_replace("}",$troca,$string);\r
+ $string = str_replace("(",$troca,$string);\r
+ $string = str_replace(")",$troca,$string);\r
+ $string = str_replace("/",$troca,$string);\r
+ $string = str_replace("|",$troca,$string);\r
+ $string = str_replace("\\",$troca,$string);\r
+ $string = str_replace("-",$troca,$string);\r
+ $string = str_replace("@",$troca,$string);\r
+ $string = str_replace("#",$troca,$string);\r
+ $string = str_replace("$",$troca,$string);\r
+ $string = str_replace("%",$troca,$string);\r
+ $string = str_replace("*",$troca,$string);\r
+ $string = str_replace("\"",$troca,$string);\r
+ $string = str_replace("'",$troca,$string);\r
+ $string = str_replace(" ",$troca,$string);\r
+ $string = str_replace(chr(13),$troca,$string);\r
+ $string = str_replace(chr(10),$troca,$string);\r
+ \r
+ return $string;\r
+ }\r
+ \r
+ function filtraParaCadastro($arr_palavras) {\r
+ if(is_array($arr_palavras)){\r
+ $stringReplaced = array();\r
+ \r
+ //retira pontos espaços etc\r
+ $i=0;\r
+ while($i<sizeof($arr_palavras)) { \r
+ $stringReplaced[$i] = $this->retiraPontos(strtolower(strip_tags($arr_palavras[$i])));\r
+ $i++;\r
+ }\r
+ unset($arr_palavras);\r
+ $arr_palavras = array(); \r
+ //retirados os pontos, explode em um array maior com as novas palavras formadas truncadas por espaço\r
+ $i=0;\r
+ while($i<sizeof($stringReplaced)) { \r
+ $arr_palavras = array_merge($arr_palavras, explode(" ", $stringReplaced[$i]));\r
+ $i++;\r
+ }\r
+ unset($stringReplaced);\r
+ $stringReplaced = array();\r
+ //transformado em array, elimina os espaços excedentes e remove os itens de tamanho menor ou igual a dois\r
+ $i=0;\r
+ while($i<sizeof($arr_palavras)) {\r
+ $arr_palavras[$i] = trim($arr_palavras[$i]);\r
+ if(!(strlen($arr_palavras[$i]) <= 2))\r
+ $stringReplaced[] = $arr_palavras[$i];\r
+ $i++;\r
+ }\r
+ \r
+ return $stringReplaced;\r
+ }\r
+ }\r
+ \r
+ function cadastraPalavras($string,$quebra_string = true,$string_de_quebra = ' ') { \r
+ if($quebra_string) { //deve quebrar a string em palavras separadas \r
+ $arr_palavras = array();\r
+ if(is_array($string)){\r
+ $arr_palavras = $this->filtraParaCadastro($string);\r
+ }\r
+ else {\r
+ $arr_palavras = explode($string_de_quebra,$this->retiraPontos($string));\r
+ }\r
+ \r
+ $this->salvaPalavras($this->retornaInexistentes($arr_palavras));\r
+ }\r
+ else {\r
+ if(is_array($string)){\r
+ $palavras = array();\r
+ //retira as tags de cada uma das entradas e adiciona num novo array.\r
+ $i=0;\r
+ while($i<sizeof($string)){\r
+ $palavras[] = strtolower(strip_tags($string[$i]));\r
+ $i++;\r
+ }\r
+ $this->salvaPalavras($this->retornaInexistentes($palavras));\r
+ }else{\r
+ $string = strtolower(strip_tags($string));\r
+ $this->salvaPalavras($this->retornaInexistentes($string));\r
+ }\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+global $cfg;\r
+\r
+header('Content-type: text/html; charset=iso-8859-1');\r
+//Develop?\r
+//$cfg["develop"] = true;\r
+\r
+\r
+//Database\r
+if (IS_LOCAL) {\r
+ $cfg["database_type"][0] = "mysql";\r
+ $cfg["database_server"][0] = "127.0.0.1";\r
+ $cfg["database_user"][0] = "root";\r
+ $cfg["database_password"][0] = "royalroot";\r
+ $cfg["database_database"][0] = "frazao";\r
+ \r
+ $cfg["root"] = "http://localhost/frazao/";\r
+} else {\r
+ $cfg["develop"] = true;\r
+\r
+ $cfg["database_type"][0] = "mysql";\r
+ $cfg["database_server"][0] = "200.18.67.60";\r
+ $cfg["database_user"][0] = "frazaoproject";\r
+ $cfg["database_password"][0] = "myN3MbassW0rd";\r
+ $cfg["database_database"][0] = "frazaoproject";\r
+ \r
+ // mantenha o protocolo e a barra final\r
+ $cfg["root"] = "http://siap.ufcspa.edu.br/";\r
+}\r
+//E-mails\r
+$cfg['email_remetente_robo'] = 'contato@frazaoproject.com.br';\r
+\r
+//Language\r
+$cfg["language1"] = "pt";\r
+\r
+//Manager\r
+$cfg["folder_manager"] = "manager";\r
+$cfg["system_title"] = "UFCSPA - SIAP";//"sistema de imagens anatomopatológicas";\r
+$cfg["system_sitelink"] = "UFCSPA - SIAP";//"sistema de imagens anatomopatológicas";\r
+\r
+$cfg["site_title"] = "UFCSPA - SIAP";//"sistema de imagens anatomopatológicas";\r
+?>\r
--- /dev/null
+<script language="javascript">
+ document.location = "?menu=0-0";
+</script>
\ No newline at end of file
--- /dev/null
+<?
+$cfg["database_connect"] = false;
+include("../../../manager/app.php");
+include("../../../manager/inc/inc.restrict.php");
+$load->system("functions/text.php");
+$load->system("library/XmlToArray.php");
+$load->system("library/Xml.php");
+
+$output->ajaxHeader();
+
+// Seleciona a pasta onde fica o xml
+$pasta = "../../../loja/inc/language/";
+
+// Dá permissão na pasta, se o servidor permitir :P
+@chmod($pasta,0777);
+
+// Coloca em um array as linguas setadas no config
+$arr_linguas = array();
+for ($x=1;$x < 7;$x++) {
+ if (isset($cfg['language'.$x])) {
+ $arr_linguas[] = $cfg['language'.$x];
+ } else {
+ $x=8;
+ }
+}
+
+// Verifica a rotina (inserir, alterar, nenhuma rotina)
+$routine = $input->get("routine");
+
+// Busca os dados dos XML e coloca em array
+foreach($arr_linguas as $valor) {
+ if (file_exists($pasta.$valor.'.xml')) {
+ $arquivo = $file->readFile($pasta.$valor.'.xml');
+ } else {
+ $file->copyFile($pasta.$arr_linguas[0].'.xml',$pasta.$valor.'.xml');
+ $arquivo = $file->readFile($pasta.$valor.'.xml');
+ }
+
+ $xml_content = new XmlToArray($arquivo);
+ $arr_tmp_content = $xml_content->createArray();
+
+ $arr_content[$valor] = $arr_tmp_content['content'];
+}
+
+if ($routine != '') {
+ // Faz as rotinas em cada lingua
+ foreach($arr_linguas as $lingua) {
+ $xml = new Xml();
+
+ $root = $xml->createNode("content");
+
+ switch ($routine) {
+ case "alterar":
+ // Passa por todos os campos
+ for($total=0;$total<$input->post('total');$total++) {
+ // Verifica se o campo será excluido
+ if ($input->post('chkExcluir'.$total) == '') { // Verifica se é para excluir o texto
+ $node = $root->createNode(formatNameFile($input->post('label'.$total))); // Label
+ $node->setValue(nl2br(htmlentities($input->post('content_'.$lingua.'_'.$total)))); // Value
+ $root->appendChild($node); // Adiciona no XML
+ }
+ }
+
+ break;
+ case "inserir":
+ // Insere os dados antigos no novo XML
+ foreach($arr_content[$lingua] as $key=>$value) {
+ $node = $root->createNode(formatNameFile($key)); // Label
+ $node->setValue(nl2br($value)); // Value
+ $root->appendChild($node); // Adiciona no XML
+ }
+
+ // Insere os dados novos no novo XML
+ for($x=0;$x<5;$x++) {
+ if ($input->post('label'.$x) != '') {
+ $node = $root->createNode(formatNameFile($input->post('label'.$x))); // Label
+ $node->setValue(nl2br(htmlentities($input->post('content_'. $lingua .'_'. $x)))); // Value
+ $root->appendChild($node); // Adiciona no XML
+ }
+ }
+
+ break;
+ }
+
+ $xml->appendChild($root);
+
+ $xml->getXML(); // Gera o XML
+ $xml->save($pasta.$lingua.'.xml'); // Grava o XML
+ }
+
+ redir($_SERVER['PHP_SELF']); // Recarrega a pagina para atualizar o conteudo
+}
+
+?>
+<br />
+<script>
+// Envia o formulario via Ajax
+htmleditor5 = function (frm) {
+ if (f.send(frm, true)) {
+ var a = new Ajax();
+ a.onLoad = function () {
+ $('conteudo').innerHTML = this.html;
+
+ debugHtml(this.html);
+
+ this.runJS(this.html);
+ }
+ a.sendForm(frm);
+
+ showLoading();
+ }
+}
+</script>
+ <div>
+ <h2>INSERIR TEXTO</h2>
+ <form action="<?= $_SERVER['PHP_SELF']; ?>?routine=inserir" name="frmTextosInserir" id="frmTextosInserir" method="post" onsubmit="return false;">
+ <table cellpadding="0" cellspacing="3" width="100%">
+ <tr>
+ <td>LABEL</td>
+ <?
+ // Mostra os idiomas (sigla) no topo da tabela
+ foreach($arr_linguas as $valor) {
+ ?>
+ <td><?= strtoupper($valor); ?></td>
+ <?
+ }
+ ?>
+ </tr>
+ <?
+ // Adiciona 5 campos para inserir conteudo
+ for($x=0; $x < 5;$x++) {
+ ?>
+ <tr>
+ <td valign="top" width="150"><input type="text" name="label<?= $x ?>" class="input" style="width:140px;"></td>
+ <?
+ // Cria um campo textarea para cada idioma
+ foreach($arr_linguas as $valor) {
+ ?>
+ <td valign="top"><textarea name="content_<?= $valor ?>_<?= $x ?>" class="input" style="height:60px; width:100%;"></textarea></td>
+ <?
+ }
+ ?>
+ </tr>
+ <?
+ }
+ ?>
+ <tr>
+ <td align="right" colspan="100%" height="60"><input type="image" src="../img/buttons/insert.jpg" onclick="javascript: htmleditor5('frmTextosInserir');" /></td>
+ </tr>
+ </table>
+ </form>
+
+ <h2>ALTERAR TEXTO</h2>
+ <form action="<?= $_SERVER['PHP_SELF']; ?>?routine=alterar" name="frmTextosAlterar" id="frmTextosAlterar" method="post" onsubmit="return false;">
+ <table cellpadding="4" cellspacing="0" width="100%">
+ <tr>
+ <td>LABEL</td>
+ <?
+ // Mostra os idiomas (sigla) no topo da tabela
+ foreach($arr_linguas as $valor) {
+ ?>
+ <td><?= strtoupper($valor); ?></td>
+ <?
+ }
+ ?>
+ </tr>
+ <?
+ $total = 0;
+ // Percorre todo o array com o conteudo que foi pego dos XML.
+ foreach($arr_content[$arr_linguas[0]] as $key=>$value) {
+ ?>
+ <tr <?= (($total % 2 == 0)?' style="background-color:#EEE;"':'') ?>>
+ <td valign="top" width="150"><input type="hidden" name="label<?= $total ?>" value="<?= $key ?>" class="input" style="width:140px;"><?= $key ?></td>
+ <?
+ // Coloca em cada coluna dentro do textarea o valor que cada idioma representa
+ foreach($arr_linguas as $lingua) {
+ ?>
+ <td valign="top"><textarea name="content_<?= $lingua ?>_<?= $total ?>" class="input" style="height:60px; width:100%;"><?= str_replace("<br />",chr(10),html_entity_decode(utf8_decode($arr_content[$lingua][$key]))) ?></textarea></td>
+ <?
+ }
+ ?>
+ <td width="30">
+ <!-- Check para selecionar se o conteudo deve ser excluido, se tiver selecionado, o conteudo será excluido do XML -->
+ <input type="checkbox" name="chkExcluir<?= $total ?>" id="chkExcluir<?= $total ?>" value="on">
+ </td>
+ </tr>
+ <?
+ $total++;
+ }
+ ?>
+ <tr>
+ <td align="right" colspan="100%" height="60"><input type="image" src="../img/buttons/update.jpg" onclick="javascript: htmleditor5('frmTextosAlterar');" /></td>
+ </tr>
+ </table>
+ <!-- Valor total de itens no XML, para facilitar o processo de alteração -->
+ <input type="hidden" name="total" value="<?= $total ?>">
+ </form>
+
+</div>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../manager/app.php");\r
+include("../../../manager/inc/inc.restrict.php");\r
+\r
+$output->ajaxHeader();\r
+$routine = $input->get("routine");\r
+\r
+switch($routine){\r
+ case 'imgBku'://faz backup da imagem atual (limite de três backups por imagem)\r
+ $id = $input->get("id",true);\r
+ $path = '../../../upload/sis_imagem/'.$id.'.jpg';\r
+ if(file_exists($path)){\r
+ $size = filesize($path);\r
+ $image = addslashes(fread(fopen($path, "r"), $size));\r
+ \r
+ $sql = "DELETE FROM bku_imagem WHERE id_imagem = ".$id;\r
+ $db->execute($sql);\r
+ \r
+ $sql = "INSERT INTO bku_imagem (id_imagem,imagem,tamanho,extensao,datahora) VALUES (".$id.",'".$image."','".$size."','jpg','".date('Y-m-d H:i:s')."')";\r
+ $db->execute($sql);\r
+ $bku_id = mysql_insert_id();\r
+ echo 'Backup efetuado com sucesso!';\r
+ } else {\r
+ echo 'Erro, imagem inexistente.';\r
+ }\r
+ break;\r
+ case 'imgDBku'://faz download do backup da imagem\r
+ $id = $input->get("id",true);\r
+ $load->system('library/Image.php');\r
+ \r
+ $sql = 'SELECT id FROM bku_imagem WHERE id_imagem = '.$id;\r
+ $rows = $db->execute($sql);\r
+ //print_r2($rows);\r
+ \r
+ if($rows->EOF){\r
+ die('Erro, backup não existe.');\r
+ } else {\r
+ global $input;\r
+ die('../../_config/exeptions/routines/backup.php?routine=downloadImage&id='.$input->get('id'));\r
+ // $tmp_path = 'upload/tmp/'.time().'-'.md5($id).'.jpg';\r
+ // $img = new Image();\r
+ // $img->p = $rows->fields('imagem');\r
+ // $img->save('../../../'.$tmp_path);\r
+ // if(file_exists('../../../'.$tmp_path)){\r
+ // die('../../../_system/scripts/download.php?file='.$tmp_path.'&name=Backup_image_'.$id);\r
+ // }\r
+ }\r
+ die('Erro.');\r
+ break;\r
+ case 'downloadImage':\r
+ $id = $input->get("id",true);\r
+ $sql = 'SELECT id,imagem,tamanho,extensao FROM bku_imagem WHERE id_imagem = '.$id;\r
+ $rows = $db->execute($sql);\r
+ if($rows->EOF){\r
+ die('Erro, backup não existe.');\r
+ } else {\r
+ header("Content-length: " . $rows->fields('tamanho'));\r
+ header("Content-type: " . $rows->fields('extensao'));\r
+ header("Content-Disposition: attachment; filename=" . 'backup_'.$rows->fields('id').'.'.$rows->fields('extensao'));\r
+ echo $rows->fields('imagem');\r
+ }\r
+ break;\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../manager/app.php");\r
+include("../../../manager/inc/inc.restrict.php");\r
+\r
+$output->ajaxHeader();\r
+\r
+$tmp_img = $input->get('file');//caminho da imagem a selecionar\r
+$tmp_endCrop = $input->get('endCrop');//função a chamar após o crop\r
+$x1 = $input->get('x1');\r
+$y1 = $input->get('y1');\r
+$x2 = $input->get('x2');\r
+$y2 = $input->get('y2');\r
+?>\r
+<script src="../../../manager/inc/prototype/1.6.1.0/prototype.js" type="text/javascript"></script>\r
+<script src="../../../manager/inc/scriptaculous/1.8.2/scriptaculous.js" type="text/javascript"></script>\r
+<script src="../../../manager/inc/cropper/1.2.1/cropper.js" type="text/javascript"></script>\r
+<script type="text/javascript">\r
+ // setup the callback function\r
+ function onEndCrop( coords, dimensions ) {\r
+ parent.<?=$tmp_endCrop;?>(coords,dimensions);\r
+ }\r
+\r
+ // basic example\r
+ Event.observe(\r
+ window,\r
+ 'load',\r
+ function() {\r
+ new Cropper.Img(\r
+ 'imgCropp',\r
+ {\r
+ onEndCrop: onEndCrop\r
+ <? if($x1 && $x2 && $y1 && $y2){?>\r
+ ,displayOnInit: true,\r
+ onloadCoords: { x1: <?=$x1;?>, y1: <?=$y1;?>, x2: <?=$x2;?>, y2: <?=$y2;?> }\r
+ <? }?>\r
+ }\r
+ )\r
+ }\r
+ );\r
+</script>\r
+<style>\r
+ html,body {\r
+ margin: 0px;\r
+ padding: 0px;\r
+ }\r
+</style>\r
+<table cellspacing="3" cellpadding="0" border="0" width="100%">\r
+ <tr>\r
+ <td width="50%">\r
+ <table cellspacing="0" cellpadding="0" width="100%" border="0">\r
+ <tr>\r
+ <td class="tit">\r
+ <img src="<?=$tmp_img;?>" id="imgCropp" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+</table>
\ No newline at end of file
--- /dev/null
+<?
+include("../../../manager/app.php");
+include("../../../manager/inc/inc.restrict.php");
+
+$output->ajaxHeader();
+$routine = $input->get("routine");
+
+switch($routine){
+ case "busca_orgao":
+ $nome = $input->get("nome");
+ $codigo = $input->get("codigo");
+ $sistema = $input->get("sistema");
+
+ if($nome != "")
+ $nome = " AND o.nome like '%".$nome."%'";
+ if($codigo != "")
+ $codigo = " AND o.cid10 like '%".$codigo."%'";
+ if($sistema != "")
+ $sistema = " AND o.id_sistema = ".$sistema;
+
+ $where = "";
+ if(($nome != "") || ($codigo != "") || ($sistema != ""))
+ $where = " WHERE 1 = 1 ".$nome.$codigo.$sistema;
+
+ $sql = "SELECT o.id, o.nome, o.cid10, s.nome as sistema FROM sis_orgao o LEFT OUTER JOIN sis_sistema s ON s.id = o.id_sistema ".$where;
+ $rowsOrgao = $db->execute($sql);
+
+ if($rowsOrgao->EOF){
+ ?>
+ Nenhum registro encontrado.
+ <?
+ } else {
+ ?>
+ <table cellspacing="0" cellpadding="0" width="100%">
+ <tr>
+ <td class="tit">
+ Nome
+ </td>
+ <td class="tit">
+ Código
+ </td>
+ <td class="tit">
+ Sistema
+ </td>
+ </tr>
+ <tr>
+ <? $x=0;
+ $bg = "#DDDDDD";
+ while(!$rowsOrgao->EOF){
+ if($bg == "#FFFFFF")
+ $bg = "#EEEEEE";
+ else if($bg == "#EEEEEE")
+ $bg = "#DDDDDD";
+ else if($bg == "#DDDDDD")
+ $bg = "#FFFFFF";
+
+ if($x>0){
+ echo("</tr><tr style='background:".$bg.";'>");
+ }
+ ?>
+ <td>
+ <a href="javascript:insertRelation(<?=$rowsOrgao->fields("id");?>)" alt="Clique para relacionar" title="Clique para relacionar"><?=$rowsOrgao->fields("nome");?></a>
+ </td>
+ <td>
+ <?=$rowsOrgao->fields("cid10");?></a>
+ </td>
+ <td>
+ <?=$rowsOrgao->fields("sistema");?></a>
+ </td>
+ <?
+ $rowsOrgao->moveNext();
+ $x++;
+ }
+ ?>
+ </tr>
+ </table>
+ <?
+ }
+
+ break;
+ case "insert_relation":
+ echo "alapucha tchê!";
+ break;
+ case "list_images_orgaos":
+ $id = $input->get("id_i");
+ $sql = "SELECT o.id,o.nome,o.cid10, s.nome as sistema FROM sis_imagem_orgao io LEFT OUTER JOIN sis_orgao o ON o.id = io.id_orgao LEFT OUTER JOIN sis_sistema s ON s.id = o.id_sistema";
+ $rowsOrgaos = $db->execute($sql);
+
+ if(!$rowsOrgaos->EOF){
+ ?>
+ <table cellspacing="0" cellpadding="0">
+ <?
+ while(!$rowsOrgaos->EOF){
+ ?>
+ <tr>
+ <td>
+ <?=$rowsOrgaos->fields("nome");?>
+ </td>
+ <td>
+ <?=$rowsOrgaos->fields("cid10");?>
+ </td>
+ <td>
+ <?=$rowsOrgaos->fields("sistema");?>
+ </td>
+ </tr>
+ <?
+ $rowsOrgaos->moveNext();
+ }
+ ?>
+ </table>
+ <?
+ } else {
+ echo("Nenhum órgão relacionado a esta imagem.");
+ }
+
+ break;
+}
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../manager/app.php");\r
+include("../../../manager/inc/inc.restrict.php");\r
+\r
+$output->ajaxHeader();\r
+$routine = $input->get("routine");\r
+\r
+switch($routine){\r
+ case "check":\r
+ $sql = "SELECT 1 FROM ".$input->get('table',true)." WHERE ".$input->get('field',true)." = '".$input->get('search')."' ".$input->get('u',true);\r
+ $rows = $db->execute($sql);\r
+ if($rows->EOF){\r
+ echo('1');\r
+ } else {\r
+ echo('0');\r
+ }\r
+ break;\r
+ case "sugestion":\r
+ $sql = "SELECT codigo,descricao FROM global_cid10 WHERE status = 1 AND codigo LIKE '".$input->get('codigo')."%' LIMIT 10";\r
+ $rows = $db->execute($sql);\r
+ \r
+ $html = '';\r
+ if(!$rows->EOF){\r
+ if($rows->recordcount > 1){\r
+ $html .= '<div style="position:absolute; width:200px; border:1px solid #666666; background: #EEEEEE; line-height:15px; padding:5px;">';\r
+ $html .= '<div style="float:right;"><a href="javascript: closeSugestion();" alt="Fechar" title="Fechar">Fechar</a></div><br>';\r
+ while(!$rows->EOF){\r
+ $html .= '<a href="javascript: setSugestion(\''.$rows->fields('codigo').'\',\''.$rows->fields('descricao').'\')" alt="'.$rows->fields('descricao').'" title="'.$rows->fields('descricao').'">'.$rows->fields('codigo').' - '.$rows->fields('descricao').'</a>';\r
+ $rows->moveNext();\r
+ if(!$rows->EOF){\r
+ $html .= '<br>';\r
+ }\r
+ }\r
+ $html .= '</div>';\r
+ } else {\r
+ $html .= $rows->fields('codigo').' - '.$rows->fields('descricao');\r
+ }\r
+ }\r
+ echo $html;\r
+ break;\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+include("../../../manager/app.php");
+include("../../../manager/inc/inc.restrict.php");
+
+$output->ajaxHeader();
+$routine = $input->get("routine");
+
+switch($routine){
+ case "busca_orgao":
+ $nome = $input->get("nome");
+ $codigo = $input->get("codigo");
+ $sistema = $input->get("sistema");
+
+ if($nome != "")
+ $nome = " AND o.nome like '%".$nome."%'";
+ if($codigo != "")
+ $codigo = " AND o.cid10 like '%".$codigo."%'";
+ if($sistema != "")
+ $sistema = " AND o.id_sistema = ".$sistema;
+
+ $where = "";
+ if(($nome != "") || ($codigo != "") || ($sistema != ""))
+ $where = " WHERE 1 = 1 ".$nome.$codigo.$sistema;
+
+ $sql = "SELECT o.id, o.nome, o.cid10, s.nome as sistema FROM sis_orgao o LEFT OUTER JOIN sis_sistema s ON s.id = o.id_sistema ".$where." LIMIT 50";
+ $rowsOrgao = $db->execute($sql);
+
+ //entre registros
+ $entreReg = "###";
+ //entre valores
+ $entreVal = "$$$";
+ if(!$rowsOrgao->EOF){
+ while(!$rowsOrgao->EOF){
+ echo $rowsOrgao->fields("id");
+ echo $entreVal;
+ echo $rowsOrgao->fields("nome");
+ echo $entreVal;
+ echo $rowsOrgao->fields("cid10");
+ echo $entreVal;
+ echo $rowsOrgao->fields("sistema");
+
+ $rowsOrgao->moveNext();
+ if(!$rowsOrgao->EOF)
+ echo $entreReg;
+ }
+ }
+ break;
+}
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../manager/app.php");\r
+include("../../../manager/inc/inc.restrict.php");\r
+\r
+$output->ajaxHeader();\r
+$routine = $input->get("routine");\r
+\r
+switch($routine){\r
+ case "busca_orgao":\r
+ $nome = $input->get("nome");\r
+ $codigo = $input->get("codigo");\r
+ $sistema = $input->get("sistema");\r
+ \r
+ if($nome != "")\r
+ $nome = " AND o.nome like '%".$nome."%'";\r
+ if($sistema != "")\r
+ $sistema = " AND os.id_sistema = ".$sistema;\r
+ \r
+ $where = "";\r
+ if(($nome != "") || ($codigo != "") || ($sistema != ""))\r
+ $where = " WHERE 1 = 1 ".$nome.$codigo.$sistema;\r
+ \r
+ $sql = "SELECT o.id, o.nome FROM sis_orgao o \r
+ LEFT OUTER JOIN sis_orgao_sistema os ON os.id_orgao = o.id\r
+ LEFT OUTER JOIN sis_sistema s ON s.id = os.id_sistema ".$where." GROUP BY o.id LIMIT 50";\r
+ $rowsOrgao = $db->execute($sql);\r
+ \r
+ //entre registros\r
+ $entreReg = "###";\r
+ //entre valores\r
+ $entreVal = "$$$";\r
+ if(!$rowsOrgao->EOF){\r
+ while(!$rowsOrgao->EOF){\r
+ echo $rowsOrgao->fields("id");\r
+ echo $entreVal;\r
+ echo $rowsOrgao->fields("nome");\r
+ // echo $entreVal;\r
+ // echo $rowsOrgao->fields("cid10");\r
+ // echo $entreVal;\r
+ // echo $rowsOrgao->fields("sistema");\r
+ \r
+ $rowsOrgao->moveNext();\r
+ if(!$rowsOrgao->EOF)\r
+ echo $entreReg;\r
+ }\r
+ }\r
+ break;\r
+ case "busca_imagem":\r
+ $nome = $input->get("nome");\r
+ $procedencia = $input->get("procedencia");\r
+ $patologia = $input->get("patologia");\r
+ $sistema = $input->get("sistema");\r
+ $saudaveis = $input->get("saudaveis");\r
+ \r
+ if($nome != "")\r
+ $nome = " AND o.nome like '%".$nome."%'";\r
+ if($procedencia != "")\r
+ $procedencia = " AND o.id_procedencia = ".$procedencia;\r
+ if($patologia != "")\r
+ $patologia = " AND o.id_patologia = ".$patologia;\r
+ if($sistema != "")\r
+ $sistema = " AND o.id_sistema = ".$sistema;\r
+ \r
+ $where = " saudavel = 0 ";//todos buscam somente imagens não saudaveis\r
+ if($saudaveis != ''){\r
+ $where = " 1 = 1 ";\r
+ }\r
+ if(($nome != "") || ($procedencia != "") || ($patologia != "") || ($sistema != ""))\r
+ $where = " WHERE ".$where." ".$nome.$procedencia.$patologia.$sistema;\r
+ \r
+ $sql = "SELECT o.id, o.nome FROM sis_imagem o LEFT OUTER JOIN sis_sistema s ON s.id = o.id_sistema ".$where." LIMIT 50";\r
+ $rowsImagem = $db->execute($sql);\r
+ \r
+ //entre registros\r
+ $entreReg = "###";\r
+ //entre valores\r
+ $entreVal = "$$$";\r
+ if(!$rowsImagem->EOF){\r
+ while(!$rowsImagem->EOF){\r
+ echo $rowsImagem->fields("id");\r
+ echo $entreVal;\r
+ echo $rowsImagem->fields("nome");\r
+ \r
+ $src = "../../_system/scripts/image.php?file=upload/sis_imagem/".$rowsImagem->fields("id").".jpg&w=60&h=60";\r
+ $img = '<img src="'.$src.'" width="60" height="60" style="margin: 3px;"/>';\r
+ echo $entreVal;\r
+ echo $img;\r
+ \r
+ $rowsImagem->moveNext();\r
+ if(!$rowsImagem->EOF)\r
+ echo $entreReg;\r
+ }\r
+ }\r
+ break;\r
+ case "busca_diagnostico":\r
+ $nome = $input->get("nome");\r
+ $especialidade = $input->get("especialidade");\r
+ \r
+ if($nome != "")\r
+ $nome = " AND d.nome like '%".$nome."%'";\r
+ if($especialidade != "")\r
+ $especialidade = " AND d.id_especialidade = ".$especialidade;\r
+ \r
+ $where = "";\r
+ if(($nome != "") || ($especialidade != ""))\r
+ $where = " WHERE 1 = 1 ".$nome.$especialidade;\r
+ \r
+ $sql = "SELECT d.id, d.nome FROM sis_diagnostico d ".$where." LIMIT 50";\r
+ $rowsOrgao = $db->execute($sql);\r
+ \r
+ //entre registros\r
+ $entreReg = "###";\r
+ //entre valores\r
+ $entreVal = "$$$";\r
+ if(!$rowsOrgao->EOF){\r
+ while(!$rowsOrgao->EOF){\r
+ echo $rowsOrgao->fields("id");\r
+ echo $entreVal;\r
+ echo $rowsOrgao->fields("nome");\r
+ // echo $entreVal;\r
+ // echo $rowsOrgao->fields("cid10");\r
+ // echo $entreVal;\r
+ // echo $rowsOrgao->fields("sistema");\r
+ \r
+ $rowsOrgao->moveNext();\r
+ if(!$rowsOrgao->EOF)\r
+ echo $entreReg;\r
+ }\r
+ }\r
+ break;\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+include("../../../manager/app.php");
+include("../../../manager/inc/inc.restrict.php");
+
+$output->ajaxHeader();
+
+$sis_table = "sis_orgao";
+$sis_table_rel = "sis_imagem_orgao";
+
+$sql = "SELECT id, nome FROM sis_sistema ORDER BY nome ASC";
+$rowsSistema = $db->execute($sql);
+?>
+<style>
+ table {
+ color:#999999;
+ font-family:Tahoma;
+ font-size:10px;
+ }
+ input, select, textarea{
+ background:#FCFCFC none repeat scroll 0 0;
+ border-color:#909090 #C0C0C0 #C0C0C0 #909090;
+ border-style:solid;
+ border-width:1px;
+ color:#999999;
+ font-family:Tahoma;
+ font-size:10px;
+ height:18px;
+ padding:2px;
+ }
+ .input {
+ padding:3px
+ }
+ .tit {
+ background:#F5F5F5 none repeat scroll 0 0;
+ padding:5px;
+ font-weight:bold;
+ }
+</style>
+<script src="../../../_system/js/default.js" type="text/javascript"></script>
+<script src="../../../_system/js/ajax.js" type="text/javascript"></script>
+<script type="text/javascript">
+ function busca(){
+ tmp_url = "../../../_config/exeptions/routines/routines.php?routine=busca_orgao";
+
+ var nome = document.getElementById("Nome");
+ var codigo = document.getElementById("Codigo");
+ var sistema = document.getElementById("Sistema");
+
+ var td_result = document.getElementById("td_result");
+
+ var a = new Ajax();
+ a.onLoad = function () {
+ //this.runJS(this.html);
+ td_result.innerHTML = this.html;
+ }
+ a.get(tmp_url+"&nome="+nome.value+"&codigo="+codigo.value+"&sistema="+sistema.value);
+ }
+ function insertRelation(id_o){
+ tmp_url = "../../../_config/exeptions/routines/routines.php?routine=insert_relation";
+
+ var td_relation = document.getElementById("td_relation");
+
+ var a = new Ajax();
+ a.onLoad = function () {
+ //this.runJS(this.html);
+ td_relation.innerHTML = this.html;
+ }
+ a.get(tmp_url+"&id_o="+id_o);
+ }
+</script>
+<table cellspacing="3" cellpadding="0" border="0" width="100%">
+ <tr>
+ <td width="50%">
+ <table cellspacing="0" cellpadding="0" width="100%" border="0">
+ <tr>
+ <td class="tit">
+ Buscas de órgão
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <form id="frmBusca" name="frmBusca" method="post" target="iframeAux" action="" onsubmit="return false;">
+ <table cellspacing="3" cellpadding="0" width="100%">
+ <tr>
+ <td class="label">
+ Nome:
+ </td>
+ <td class="input">
+ <input type="text" id="Nome" name="nome"/>
+ </td>
+ </tr>
+ <tr>
+ <td class="label">
+ Código:
+ </td>
+ <td class="input">
+ <input type="text" id="Codigo" name="codigo"/>
+ </td>
+ </tr>
+ <tr>
+ <td class="label">
+ Sistema:
+ </td>
+ <td class="input">
+ <select id="Sistema" name="sistema">
+ <option value="">Selecione</option>
+ <option value="">------</option>
+ <? while(!$rowsSistema->EOF){?>
+ <option value="<?=$rowsSistema->fields("id");?>"><?=$rowsSistema->fields("nome");?></option>
+ <? $rowsSistema->moveNext();
+ }?>
+ </select>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ </td>
+ <td>
+ <a href="javascript: busca()">Buscar</a>
+ </td>
+ </tr>
+ </table>
+ </form>
+ </td>
+ </tr>
+ <tr>
+ <td id="td_result">
+ resultados
+ </td>
+ </tr>
+ </table>
+ </td>
+ <td width="50%" valign="top">
+ <table cellspacing="0" cellpadding="0" width="100%">
+ <tr>
+ <td class="tit">
+ Órgãos já relacionados
+ </td>
+ </tr>
+ <tr>
+ <td id="td_relation">
+
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+</table>
+<script type="text/javascript">
+ htmleditor5 = function () {
+ // if (f.send(frm, true)) {
+ // var a = new Ajax();
+ // a.onLoad = function () {
+ // $('conteudo').innerHTML = this.html;
+
+ // debugHtml(this.html);
+
+ // this.runJS(this.html);
+ // }
+ // a.sendForm(frm);
+
+ // showLoading();
+ // }
+ }
+</script>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../manager/app.php");\r
+include("../../../manager/inc/inc.restrict.php");\r
+\r
+$output->ajaxHeader();\r
+\r
+$id_js = $input->get("_id_js");\r
+$sis_table = "sis_orgao";\r
+$sis_table_rel = "sis_imagem_orgao";\r
+\r
+$sql = "SELECT id, nome FROM sis_especialidade ORDER BY nome ASC";\r
+$rowsEspecialidade = $db->execute($sql);\r
+?>\r
+<style>\r
+ table {\r
+ color:#999999;\r
+ font-family:Tahoma;\r
+ font-size:10px;\r
+ }\r
+ input, select, textarea{\r
+ background:#FCFCFC none repeat scroll 0 0;\r
+ border-color:#909090 #C0C0C0 #C0C0C0 #909090;\r
+ border-style:solid;\r
+ border-width:1px;\r
+ color:#999999;\r
+ font-family:Tahoma;\r
+ font-size:10px;\r
+ height:18px;\r
+ padding:2px;\r
+ width:150px;\r
+ }\r
+ .input {\r
+ padding:3px;\r
+ width:75%;\r
+ }\r
+ .tit {\r
+ background:#F5F5F5 none repeat scroll 0 0;\r
+ padding:5px;\r
+ font-weight:bold;\r
+ }\r
+ .label {\r
+ width:25%;\r
+ text-align:right;\r
+ }\r
+</style>\r
+<script src="../../../_system/js/default.js" type="text/javascript"></script>\r
+<script src="../../../_system/js/ajax.js" type="text/javascript"></script>\r
+<script type="text/javascript">\r
+ function busca(){\r
+ tmp_url = "../../../_config/exeptions/routines/routines_search.php?routine=busca_diagnostico";\r
+ \r
+ var nome = document.getElementById("Nome");\r
+ var especialidade = document.getElementById("Especialidade");\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ parent.<?=$id_js;?>.returnFromSearch(this.html);\r
+ }\r
+ a.get(tmp_url+"&nome="+nome.value+"&especialidade="+especialidade.value);\r
+ }\r
+ function limpar(){\r
+ parent.<?=$id_js;?>.clearSearch();\r
+ }\r
+</script>\r
+<table cellspacing="3" cellpadding="0" border="0" width="100%">\r
+ <tr>\r
+ <td width="50%">\r
+ <table cellspacing="0" cellpadding="0" width="100%" border="0">\r
+ <tr>\r
+ <td>\r
+ <form id="frmBusca" name="frmBusca" method="post" target="iframeAux" action="" onsubmit="return false;">\r
+ <table cellspacing="3" cellpadding="0" width="220">\r
+ <tr>\r
+ <td class="label">\r
+ Nome:\r
+ </td>\r
+ <td class="input">\r
+ <input type="text" id="Nome" name="nome"/>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="label">\r
+ Especialidade:\r
+ </td>\r
+ <td class="input">\r
+ <select id="Especialidade" name="especialidade">\r
+ <option value="">Selecione</option>\r
+ <option value="">------</option>\r
+ <? while(!$rowsEspecialidade->EOF){?>\r
+ <option value="<?=$rowsEspecialidade->fields("id");?>"><?=$rowsEspecialidade->fields("nome");?></option>\r
+ <? $rowsEspecialidade->moveNext();\r
+ }?>\r
+ </select>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ </td>\r
+ <td>\r
+ <div style="width:150px;">\r
+ <div style="float:left;">\r
+ <a href="javascript: busca();"><img src="../../../manager/img/buttons/search.jpg" style="border:0px;"/></a>\r
+ </div>\r
+ <div style="float:right;">\r
+ <a href="javascript: limpar();"><img src="../../../manager/img/buttons/clean.jpg" style="border:0px;"/></a>\r
+ </div>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </td>\r
+ <td align="right">\r
+ <div style="width:110px;">\r
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas.\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+</table>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../manager/app.php");\r
+include("../../../manager/inc/inc.restrict.php");\r
+\r
+$output->ajaxHeader();\r
+\r
+$id_js = $input->get("_id_js");\r
+\r
+$sql = "SELECT id, nome FROM sis_procedencia ORDER BY nome ASC";\r
+$rowsProcedencia = $db->execute($sql);\r
+\r
+$sql = "SELECT id, nome FROM sis_patologia ORDER BY nome ASC";\r
+$rowsPatologia = $db->execute($sql);\r
+\r
+$sql = "SELECT id, nome FROM sis_sistema ORDER BY nome ASC";\r
+$rowsSistema = $db->execute($sql);\r
+?>\r
+<style>\r
+ table {\r
+ color:#999999;\r
+ font-family:Tahoma;\r
+ font-size:10px;\r
+ }\r
+ input, select, textarea{\r
+ background:#FCFCFC none repeat scroll 0 0;\r
+ border-color:#909090 #C0C0C0 #C0C0C0 #909090;\r
+ border-style:solid;\r
+ border-width:1px;\r
+ color:#999999;\r
+ font-family:Tahoma;\r
+ font-size:10px;\r
+ height:18px;\r
+ padding:2px;\r
+ width:150px;\r
+ }\r
+ .input {\r
+ padding:3px;\r
+ width:75%;\r
+ }\r
+ .tit {\r
+ background:#F5F5F5 none repeat scroll 0 0;\r
+ padding:5px;\r
+ font-weight:bold;\r
+ }\r
+ .label {\r
+ width:25%;\r
+ text-align:right;\r
+ }\r
+</style>\r
+<script src="../../../_system/js/default.js" type="text/javascript"></script>\r
+<script src="../../../_system/js/ajax.js" type="text/javascript"></script>\r
+<script type="text/javascript">\r
+ function busca(){\r
+ tmp_url = "../../../_config/exeptions/routines/routines_search.php?routine=busca_imagem";\r
+ \r
+ var nome = document.getElementById("Nome");\r
+ var procedencia = document.getElementById("Procedencia");\r
+ var patologia = document.getElementById("Patologia");\r
+ var sistema = document.getElementById("Sistema");\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ parent.<?=$id_js;?>.returnFromSearch(this.html);\r
+ }\r
+ a.get(tmp_url+"&nome="+nome.value+"&procedencia="+procedencia.value+"&patologia="+patologia.value+"&sistema="+sistema.value);\r
+ }\r
+ function limpar(){\r
+ parent.<?=$id_js;?>.clearSearch();\r
+ }\r
+</script>\r
+<table cellspacing="3" cellpadding="0" border="0" width="100%">\r
+ <tr>\r
+ <td width="50%">\r
+ <table cellspacing="0" cellpadding="0" width="100%" border="0">\r
+ <tr>\r
+ <td>\r
+ <form id="frmBusca" name="frmBusca" method="post" target="iframeAux" action="" onsubmit="return false;">\r
+ <table cellspacing="3" cellpadding="0" width="220">\r
+ <tr>\r
+ <td class="label">\r
+ Nome:\r
+ </td>\r
+ <td class="input">\r
+ <input type="text" id="Nome" name="nome"/>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="label">\r
+ Procedência:\r
+ </td>\r
+ <td class="input">\r
+ <select id="Procedencia" name="procedencia">\r
+ <option value="">Selecione</option>\r
+ <option value="">------</option>\r
+ <? while(!$rowsProcedencia->EOF){?>\r
+ <option value="<?=$rowsProcedencia->fields("id");?>"><?=$rowsProcedencia->fields("nome");?></option>\r
+ <? $rowsProcedencia->moveNext();\r
+ }?>\r
+ </select>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="label">\r
+ Patologia:\r
+ </td>\r
+ <td class="input">\r
+ <select id="Patologia" name="patologia">\r
+ <option value="">Selecione</option>\r
+ <option value="">------</option>\r
+ <? while(!$rowsPatologia->EOF){?>\r
+ <option value="<?=$rowsPatologia->fields("id");?>"><?=$rowsPatologia->fields("nome");?></option>\r
+ <? $rowsPatologia->moveNext();\r
+ }?>\r
+ </select>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="label">\r
+ Sistema:\r
+ </td>\r
+ <td class="input">\r
+ <select id="Sistema" name="sistema">\r
+ <option value="">Selecione</option>\r
+ <option value="">------</option>\r
+ <? while(!$rowsSistema->EOF){?>\r
+ <option value="<?=$rowsSistema->fields("id");?>"><?=$rowsSistema->fields("nome");?></option>\r
+ <? $rowsSistema->moveNext();\r
+ }?>\r
+ </select>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ </td>\r
+ <td>\r
+ <div style="width:150px;">\r
+ <div style="float:left;">\r
+ <a href="javascript: busca();"><img src="../../../manager/img/buttons/search.jpg" style="border:0px;"/></a>\r
+ </div>\r
+ <div style="float:right;">\r
+ <a href="javascript: limpar();"><img src="../../../manager/img/buttons/clean.jpg" style="border:0px;"/></a>\r
+ </div>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </td>\r
+ <td align="right">\r
+ <div style="width:110px;">\r
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas.\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+</table>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../manager/app.php");\r
+include("../../../manager/inc/inc.restrict.php");\r
+\r
+$output->ajaxHeader();\r
+\r
+$id_js = $input->get("_id_js");\r
+\r
+$sql = "SELECT id, nome FROM sis_procedencia ORDER BY nome ASC";\r
+$rowsProcedencia = $db->execute($sql);\r
+\r
+$sql = "SELECT id, nome FROM sis_patologia ORDER BY nome ASC";\r
+$rowsPatologia = $db->execute($sql);\r
+\r
+$sql = "SELECT id, nome FROM sis_sistema ORDER BY nome ASC";\r
+$rowsSistema = $db->execute($sql);\r
+?>\r
+<style>\r
+ table {\r
+ color:#999999;\r
+ font-family:Tahoma;\r
+ font-size:10px;\r
+ }\r
+ input, select, textarea{\r
+ background:#FCFCFC none repeat scroll 0 0;\r
+ border-color:#909090 #C0C0C0 #C0C0C0 #909090;\r
+ border-style:solid;\r
+ border-width:1px;\r
+ color:#999999;\r
+ font-family:Tahoma;\r
+ font-size:10px;\r
+ height:18px;\r
+ padding:2px;\r
+ width:150px;\r
+ }\r
+ .input {\r
+ padding:3px;\r
+ width:75%;\r
+ }\r
+ .tit {\r
+ background:#F5F5F5 none repeat scroll 0 0;\r
+ padding:5px;\r
+ font-weight:bold;\r
+ }\r
+ .label {\r
+ width:25%;\r
+ text-align:right;\r
+ }\r
+</style>\r
+<script src="../../../_system/js/default.js" type="text/javascript"></script>\r
+<script src="../../../_system/js/ajax.js" type="text/javascript"></script>\r
+<script type="text/javascript">\r
+ function busca(){\r
+ tmp_url = "../../../_config/exeptions/routines/routines_search.php?routine=busca_imagem&saudaveis=1";\r
+ \r
+ var nome = document.getElementById("Nome");\r
+ var procedencia = document.getElementById("Procedencia");\r
+ var patologia = document.getElementById("Patologia");\r
+ var sistema = document.getElementById("Sistema");\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ parent.<?=$id_js;?>.returnFromSearch(this.html);\r
+ }\r
+ a.get(tmp_url+"&nome="+nome.value+"&procedencia="+procedencia.value+"&patologia="+patologia.value+"&sistema="+sistema.value);\r
+ }\r
+ function limpar(){\r
+ parent.<?=$id_js;?>.clearSearch();\r
+ }\r
+</script>\r
+<table cellspacing="3" cellpadding="0" border="0" width="100%">\r
+ <tr>\r
+ <td width="50%">\r
+ <table cellspacing="0" cellpadding="0" width="100%" border="0">\r
+ <tr>\r
+ <td>\r
+ <form id="frmBusca" name="frmBusca" method="post" target="iframeAux" action="" onsubmit="return false;">\r
+ <table cellspacing="3" cellpadding="0" width="220">\r
+ <tr>\r
+ <td class="label">\r
+ Nome:\r
+ </td>\r
+ <td class="input">\r
+ <input type="text" id="Nome" name="nome"/>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="label">\r
+ Procedência:\r
+ </td>\r
+ <td class="input">\r
+ <select id="Procedencia" name="procedencia">\r
+ <option value="">Selecione</option>\r
+ <option value="">------</option>\r
+ <? while(!$rowsProcedencia->EOF){?>\r
+ <option value="<?=$rowsProcedencia->fields("id");?>"><?=$rowsProcedencia->fields("nome");?></option>\r
+ <? $rowsProcedencia->moveNext();\r
+ }?>\r
+ </select>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="label">\r
+ Patologia:\r
+ </td>\r
+ <td class="input">\r
+ <select id="Patologia" name="patologia">\r
+ <option value="">Selecione</option>\r
+ <option value="">------</option>\r
+ <? while(!$rowsPatologia->EOF){?>\r
+ <option value="<?=$rowsPatologia->fields("id");?>"><?=$rowsPatologia->fields("nome");?></option>\r
+ <? $rowsPatologia->moveNext();\r
+ }?>\r
+ </select>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="label">\r
+ Sistema:\r
+ </td>\r
+ <td class="input">\r
+ <select id="Sistema" name="sistema">\r
+ <option value="">Selecione</option>\r
+ <option value="">------</option>\r
+ <? while(!$rowsSistema->EOF){?>\r
+ <option value="<?=$rowsSistema->fields("id");?>"><?=$rowsSistema->fields("nome");?></option>\r
+ <? $rowsSistema->moveNext();\r
+ }?>\r
+ </select>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ </td>\r
+ <td>\r
+ <div style="width:150px;">\r
+ <div style="float:left;">\r
+ <a href="javascript: busca();"><img src="../../../manager/img/buttons/search.jpg" style="border:0px;"/></a>\r
+ </div>\r
+ <div style="float:right;">\r
+ <a href="javascript: limpar();"><img src="../../../manager/img/buttons/clean.jpg" style="border:0px;"/></a>\r
+ </div>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </td>\r
+ <td align="right">\r
+ <div style="width:110px;">\r
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas.\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+</table>
\ No newline at end of file
--- /dev/null
+<?
+include("../../../manager/app.php");
+include("../../../manager/inc/inc.restrict.php");
+
+$output->ajaxHeader();
+
+$sis_table = "sis_orgao";
+$sis_table_rel = "sis_imagem_orgao";
+
+$sql = "SELECT id, nome FROM sis_sistema ORDER BY nome ASC";
+$rowsSistema = $db->execute($sql);
+?>
+<style>
+ table {
+ color:#999999;
+ font-family:Tahoma;
+ font-size:10px;
+ }
+ input, select, textarea{
+ background:#FCFCFC none repeat scroll 0 0;
+ border-color:#909090 #C0C0C0 #C0C0C0 #909090;
+ border-style:solid;
+ border-width:1px;
+ color:#999999;
+ font-family:Tahoma;
+ font-size:10px;
+ height:18px;
+ padding:2px;
+ width:150px;
+ }
+ .input {
+ padding:3px;
+ width:75%;
+ }
+ .tit {
+ background:#F5F5F5 none repeat scroll 0 0;
+ padding:5px;
+ font-weight:bold;
+ }
+ .label {
+ width:25%;
+ text-align:right;
+ }
+</style>
+<script src="../../../_system/js/default.js" type="text/javascript"></script>
+<script src="../../../_system/js/ajax.js" type="text/javascript"></script>
+<script type="text/javascript">
+ function busca(){
+ tmp_url = "../../../_config/exeptions/routines/routines_orgao.php?routine=busca_orgao";
+
+ var nome = document.getElementById("Nome");
+ var codigo = document.getElementById("Codigo");
+ var sistema = document.getElementById("Sistema");
+
+ var a = new Ajax();
+ a.onLoad = function() {
+ parent.returnFromSearch(this.html);
+ }
+ a.get(tmp_url+"&nome="+nome.value+"&codigo="+codigo.value+"&sistema="+sistema.value);
+ }
+ function limpar(){
+ parent.clearSearch("td_result");
+ }
+</script>
+<table cellspacing="3" cellpadding="0" border="0" width="100%">
+ <tr>
+ <td width="50%">
+ <table cellspacing="0" cellpadding="0" width="100%" border="0">
+ <tr>
+ <td>
+ <form id="frmBusca" name="frmBusca" method="post" target="iframeAux" action="" onsubmit="return false;">
+ <table cellspacing="3" cellpadding="0" width="220">
+ <tr>
+ <td class="label">
+ Nome:
+ </td>
+ <td class="input">
+ <input type="text" id="Nome" name="nome"/>
+ </td>
+ </tr>
+ <tr>
+ <td class="label">
+ Código:
+ </td>
+ <td class="input">
+ <input type="text" id="Codigo" name="codigo"/>
+ </td>
+ </tr>
+ <tr>
+ <td class="label">
+ Sistema:
+ </td>
+ <td class="input">
+ <select id="Sistema" name="sistema">
+ <option value="">Selecione</option>
+ <option value="">------</option>
+ <? while(!$rowsSistema->EOF){?>
+ <option value="<?=$rowsSistema->fields("id");?>"><?=$rowsSistema->fields("nome");?></option>
+ <? $rowsSistema->moveNext();
+ }?>
+ </select>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ </td>
+ <td>
+ <div style="width:150px;">
+ <div style="float:left;">
+ <a href="javascript: busca();">Buscar</a>
+ </div>
+ <div style="float:right;">
+ <a href="javascript: limpar();">Limpar</a>
+ </div>
+ </div>
+ </td>
+ </tr>
+ </table>
+ </form>
+ </td>
+ <td align="right">
+ <div style="width:110px;">
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas.
+ </div>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+</table>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../manager/app.php");\r
+include("../../../manager/inc/inc.restrict.php");\r
+\r
+$output->ajaxHeader();\r
+\r
+$id_js = $input->get("_id_js");\r
+$sis_table = "sis_orgao";\r
+$sis_table_rel = "sis_imagem_orgao";\r
+\r
+$sql = "SELECT id, nome FROM sis_sistema ORDER BY nome ASC";\r
+$rowsSistema = $db->execute($sql);\r
+?>\r
+<style>\r
+ table {\r
+ color:#999999;\r
+ font-family:Tahoma;\r
+ font-size:10px;\r
+ }\r
+ input, select, textarea{\r
+ background:#FCFCFC none repeat scroll 0 0;\r
+ border-color:#909090 #C0C0C0 #C0C0C0 #909090;\r
+ border-style:solid;\r
+ border-width:1px;\r
+ color:#999999;\r
+ font-family:Tahoma;\r
+ font-size:10px;\r
+ height:18px;\r
+ padding:2px;\r
+ width:150px;\r
+ }\r
+ .input {\r
+ padding:3px;\r
+ width:75%;\r
+ }\r
+ .tit {\r
+ background:#F5F5F5 none repeat scroll 0 0;\r
+ padding:5px;\r
+ font-weight:bold;\r
+ }\r
+ .label {\r
+ width:25%;\r
+ text-align:right;\r
+ }\r
+</style>\r
+<script src="../../../_system/js/default.js" type="text/javascript"></script>\r
+<script src="../../../_system/js/ajax.js" type="text/javascript"></script>\r
+<script type="text/javascript">\r
+ function busca(){\r
+ tmp_url = "../../../_config/exeptions/routines/routines_search.php?routine=busca_orgao";\r
+ \r
+ var nome = document.getElementById("Nome");\r
+ var sistema = document.getElementById("Sistema");\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ parent.<?=$id_js;?>.returnFromSearch(this.html);\r
+ }\r
+ a.get(tmp_url+"&nome="+nome.value+"&sistema="+sistema.value);\r
+ }\r
+ function limpar(){\r
+ parent.<?=$id_js;?>.clearSearch();\r
+ }\r
+</script>\r
+<table cellspacing="3" cellpadding="0" border="0" width="100%">\r
+ <tr>\r
+ <td width="50%">\r
+ <table cellspacing="0" cellpadding="0" width="100%" border="0">\r
+ <tr>\r
+ <td>\r
+ <form id="frmBusca" name="frmBusca" method="post" target="iframeAux" action="" onsubmit="return false;">\r
+ <table cellspacing="3" cellpadding="0" width="220">\r
+ <tr>\r
+ <td class="label">\r
+ Nome:\r
+ </td>\r
+ <td class="input">\r
+ <input type="text" id="Nome" name="nome"/>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="label">\r
+ Sistema:\r
+ </td>\r
+ <td class="input">\r
+ <select id="Sistema" name="sistema">\r
+ <option value="">Selecione</option>\r
+ <option value="">------</option>\r
+ <? while(!$rowsSistema->EOF){?>\r
+ <option value="<?=$rowsSistema->fields("id");?>"><?=$rowsSistema->fields("nome");?></option>\r
+ <? $rowsSistema->moveNext();\r
+ }?>\r
+ </select>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ </td>\r
+ <td>\r
+ <div style="width:150px;">\r
+ <div style="float:left;">\r
+ <a href="javascript: busca();"><img src="../../../manager/img/buttons/search.jpg" style="border:0px;"/></a>\r
+ </div>\r
+ <div style="float:right;">\r
+ <a href="javascript: limpar();"><img src="../../../manager/img/buttons/clean.jpg" style="border:0px;"/></a>\r
+ </div>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </td>\r
+ <td align="right">\r
+ <div style="width:110px;">\r
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas.\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+</table>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormAdminSessao extends Form {\r
+ function FormAdminSessao() {\r
+ parent::Form("admin_sessao");\r
+ $this->flags = "UI";\r
+ }\r
+ \r
+ function configFields() {\r
+ \r
+ $f = $this->newField("char", array("id", "ID"));\r
+ $f->is_static = true;\r
+ $this->addField($f, "LOFU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = "100";\r
+ $this->addField($f, "LOFIU");\r
+ }\r
+ \r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormAdminUsuario extends Form {\r
+ function FormAdminUsuario() {\r
+ parent::Form("admin_usuario");\r
+ \r
+ }\r
+ \r
+ function configFields() {\r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = "100";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("email", "E-mail"));\r
+ $f->loadConfig("email");\r
+ $f->maxlength = "150";\r
+ $this->addField($f, "LOFIU");\r
+\r
+ $f = $this->newField("items", array("nivel", "Nível de Usuário"));\r
+ $f->setInputType('radio');\r
+ $f->addElementsByArray(array('1' => 'Administrador','2' => 'Professor'));\r
+ $this->addField($f, "LOFIU");\r
+\r
+ $f = $this->newField("ativo");\r
+ $f->value_initial = 1;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f);\r
+\r
+ $f = $this->newField("char", array("usuario", "Usuário"));\r
+ $f->maxlength = "60";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("password", array("senha"));\r
+ $f->maxlength = "15";\r
+ $this->addField($f, "UI");\r
+\r
+ $f = $this->newField('html',array('box'));\r
+ $this->addField($f);\r
+\r
+ $f = $this->newField('html',array('label', 'Sessões'));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField('multiItems', array('sessao','','admin_usuario_sessao','id_usuario','id_sessao'));\r
+ $f->addElementsByTable('admin_sessao');\r
+ $this->addField($f,'IU');\r
+ \r
+ }\r
+ \r
+ function getListSql($tmp_sql_filter, $tmp_sql_order) {\r
+ global $profile;\r
+ if ($profile->fields("id") != 1) {\r
+ return "select * from ".$this->table." where id <> 1 ".$tmp_sql_filter." ".$tmp_sql_order;\r
+ } else {\r
+ return "select * from ".$this->table." where 1 = 1 ".$tmp_sql_filter." ".$tmp_sql_order;\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormCasoEstudo extends Form {\r
+ var $table_rel;//tabela com as imagens relacionadas a registro de conteudo\r
+ var $id_rel;//nome do campo na tabela acima que define relação com o registro de conteudo\r
+ function FormCasoEstudo() {\r
+ parent::Form("sis_casoestudo");\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ $this->table_rel = 'sis_casoestudo_comentario';\r
+ $this->id_rel = 'id_casoestudo';\r
+ }\r
+ \r
+ function configFields() {\r
+ global $routine;\r
+ global $db;\r
+ global $profile;\r
+ global $load;\r
+ $load->system('functions/date.php');\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados do Caso de Estudo"));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->setInputType('textarea');\r
+ $f->size_cols = 55;\r
+ $f->size_rows = 2;\r
+ $f->maxlength = 200;\r
+ $f->input_extra = " onblur='javascript: checkMe(this.value);' ";\r
+ $f->field_extra = "<div id='div_check' style='float:right; width:16px; height:16px;'></div>";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("codigo", "Código"));\r
+ $f->maxlength = 100;\r
+ $f->comment = 'Número do caso Ex: A-13069.';\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_especialidade", "Especialidade"));\r
+ $f->addElementsByTable("sis_especialidade");\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("referencia", "Referências"));\r
+ $f->setInputType("textarea");\r
+ $f->maxlength = 10000;\r
+ $f->is_required = false;\r
+ $f->comment = "Páginas web de referência onde se possa encontrar mais sobre este caso de estudo. Livros, revistas entre outros materiais alternativos que possam complementar o estudo do caso.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("palavrachave", "Palavras-chave"));\r
+ $f->maxlength = 250;\r
+ $f->is_required = false;\r
+ $f->comment = "Palavras relacionadas ao diagnóstico, que eventualmente podem facilitar a pesquisa.";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("ativo",array("visualizacao","Visualização"));\r
+ $f->value_initial = 1;\r
+ $f->comment = "Este campo determina se a imagem será visualizada no site.";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField("html", array("label","O Caso de Estudo"));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField("char", array("texto", "Texto"));\r
+ $f->setInputType("textarea");\r
+ $f->maxlength = 20000;\r
+ $f->is_required = false;\r
+ $f->size_rows = 13;\r
+ $f->comment = "O Caso de Estudo em sí, todo o desenvolvimento da idéia do mesmo.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("texto_professor", "Texto/Anotações do professor"));\r
+ $f->setInputType("textarea");\r
+ $f->maxlength = 20000;\r
+ $f->is_required = false;\r
+ $f->size_rows = 7;\r
+ $f->comment = "Este campo não será visualizado no site, são apenas anotações para uso do professor.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("relItems", array("orgaos","Órgãos","sis_casoestudo_orgao","id_casoestudo","id_orgao","sis_orgao","_config/exeptions/routines/search_orgao2.php"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("relItems", array("imagens","Imagens","sis_casoestudo_imagem","id_casoestudo","id_imagem","sis_imagem","_config/exeptions/routines/search_imagem_saudavel.php"));\r
+ $f->search_page_height = 160;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("relItems", array("diagnosticos","Diagnósticos","sis_casoestudo_diagnostico","id_casoestudo","id_diagnostico","sis_diagnostico","_config/exeptions/routines/search_diagnostico.php"));\r
+ //$f->search_page_height = 160;\r
+ $this->addField($f, "IU");\r
+ \r
+ /******************** COMENTARIOS ************************/\r
+ \r
+ $f = $this->newField("html",array('box','div_botao_mais_arquivo'));\r
+ $this->addField($f);\r
+\r
+ $html = "\r
+ <tr class='fieldset'>\r
+ <td colspan='100%' id='botao_mais_arquivo'>\r
+ <a href=\"javascript:mostrar_secoes();\"><img src='../../_config/img/bt-adicionar.jpg'></a>\r
+ </td>\r
+ </tr>";\r
+ $f = $this->newField("html", array("html"));\r
+ $f->html = $html;\r
+ $this->addField($f);\r
+\r
+ $f = $this->newField("html",array('box'));\r
+ $this->addField($f);\r
+\r
+ $f = $this->newField("html",array('label','Comentários'));\r
+ $this->addField($f);\r
+\r
+ $f = $this->newField("html",array('box'));\r
+ $this->addField($f);\r
+\r
+ $total_arquivos = 20;\r
+ $arquivo_atual = 1;\r
+\r
+ if ($routine == 'update') {\r
+ $sql = "SELECT * FROM ".$this->table_rel." WHERE ".$this->id_rel." = ".$this->fields('id')." ";\r
+ $rs = $db->execute($sql);\r
+ \r
+ if (!$rs->EOF) {\r
+ while(!$rs->EOF) {\r
+ $f = $this->newField("char", array("nome_id_".$rs->fields('id'), "Nome"));\r
+ $f->value_static = $rs->fields("nome");\r
+ $f->is_static = true;\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("email_id_".$rs->fields('id'), "E-mail"));\r
+ $f->value_static = $rs->fields("email");\r
+ $f->is_static = true;\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("comentario_id_".$rs->fields('id'), "Comentário"));\r
+ $f->value_static = $rs->fields("comentario");\r
+ $f->is_static = true;\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("datacomentario_id_".$rs->fields('id'), "Data"));\r
+ $f->value_static = datetimeFromMysql($rs->fields("datacomentario"));\r
+ $f->is_static = true;\r
+ //$f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("ativo", array("status_id_".$rs->fields('id'), "Status"));\r
+ $f->value = $rs->fields("status");\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ if (($arquivo_atual % 2 == 1) && ($arquivo_atual < $total_arquivos)) {\r
+ $f = $this->newField("html",array("separador"));\r
+ $this->addField($f);\r
+ } elseif ($arquivo_atual < $total_arquivos) {\r
+ $f = $this->newField("html",array("box"));\r
+ $this->addField($f);\r
+ }\r
+ \r
+ $arquivo_atual++;\r
+ $rs->moveNext();\r
+ }\r
+ }\r
+ }\r
+ \r
+ $f = $this->newField("hidden", array("arquivo_atual", "arquivoAtual"));\r
+ $f->value = $arquivo_atual;\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+\r
+ /******************** / COMENTARIOS ************************/\r
+ }\r
+ function loadInit($rotina) {\r
+ global $input;\r
+ $u = '';\r
+ if ($rotina == 'U') {\r
+ $u = $input->encode(' AND id != '.$this->fields('id'));\r
+ }\r
+ ?>\r
+ <script type="text/javascript">\r
+ checkMe = function(tmp_nome){\r
+ var obj = document.getElementById('div_check');\r
+ obj.innerHTML = '<img src="../img/icons/time.gif" width="16" height="16" />';\r
+ var a = new Ajax();\r
+ a.onLoad = function(){\r
+ var obj = document.getElementById('div_check');\r
+ if((this.html+'0') == '00'){\r
+ obj.innerHTML = '<img src="../img/icons/cancel.gif" width="16" height="16" />';\r
+ alert('Atenção, o nome informado já existe no banco de dados.');\r
+ $('Nome_TXT1').focus();\r
+ } else if((this.html+'0') == '10'){\r
+ obj.innerHTML = '<img src="../img/icons/accept.gif" width="16" height="16" />';\r
+ }\r
+ }\r
+ a.get("../../_config/exeptions/routines/routines.php?routine=check&field=<?=$input->encode('nome');?>&table=<?=$input->encode('sis_casoestudo');?>&u=<?=$u;?>&search="+tmp_nome);\r
+ }\r
+ </script>\r
+ <?\r
+ }\r
+ function onPosPost($routine){\r
+ global $db;\r
+ global $input;\r
+ global $load;\r
+ $load->system('functions/text.php'); \r
+ \r
+ $total_arquivos = $input->post('arquivo_atual');\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ $cadastra->cadastraPalavras($this->fields("palavrachave"),true,';');\r
+ \r
+ if ($routine == 'U') {//atualiza estoque\r
+ $sql = "SELECT * FROM ".$this->table_rel." WHERE ".$this->id_rel."=".$this->fields('id')." ";\r
+ $rs = $db->execute($sql);\r
+ \r
+ if (!$rs->EOF) {\r
+ while(!$rs->EOF){\r
+ $sql = "UPDATE ".$this->table_rel." SET \r
+ status='".$input->post('status_id_'.$rs->fields('id'))."' \r
+ WHERE id=".$rs->fields('id');\r
+ $db->execute($sql);\r
+ $rs->moveNext();\r
+ }\r
+ }\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormCid10 extends Form {\r
+ function FormCid10() {\r
+ parent::Form("global_cid10");\r
+ }\r
+ \r
+ function configFields() {\r
+ $f = $this->newField("char", array("codigo", "Código"));\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("descricao", "Descrição"));\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("ativo");\r
+ $f->value_initial = 1;\r
+ $this->addField($f, "LOFIU");\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormDiagnostico extends Form {\r
+ function FormDiagnostico() {\r
+ parent::Form("sis_diagnostico");\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados do Diagnóstico"));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->setInputType('textarea');\r
+ $f->size_cols = 55;\r
+ $f->size_rows = 2;\r
+ $f->maxlength = 200;\r
+ $f->input_extra = " onblur='javascript: checkMe(this.value);' ";\r
+ $f->field_extra = "<div id='div_check' style='float:right; width:16px; height:16px;'></div>";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("cid10", "Código CID10"));\r
+ $f->maxlength = 10;\r
+ $f->size_cols = 10;\r
+ $f->is_required = false;\r
+ $f->field_extra = "<div id='div_sugestion_cid10' style='width:200px; float:right;'> </div>";\r
+ $f->input_extra = " onkeyup='javascript: initSugestion();' ";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_especialidade", "Especialidade"));\r
+ $f->addElementsByTable("sis_especialidade");\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("referencia", "Referências"));\r
+ $f->setInputType("textarea");\r
+ $f->maxlength = 10000;\r
+ $f->is_required = false;\r
+ $f->comment = "Páginas web de referência onde se possa encontrar mais sobre este tipo de diagnóstico. Livros, revistas entre outros materiais alternativos que possam complementar o estudo deste tipo de caso.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("palavrachave", "Palavras-chave"));\r
+ $f->maxlength = 250;\r
+ $f->is_required = false;\r
+ $f->comment = "Palavras relacionadas ao diagnóstico, que eventualmente podem facilitar a pesquisa. Separar palavras com ponto e vírgula.";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("ativo",array("visualizacao","Visualização"));\r
+ $f->value_initial = 1;\r
+ $f->comment = "Este campo determina se a imagem será visualizada no site.";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField("html", array("label","O Diagnóstico"));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField("char", array("texto", "Texto"));\r
+ $f->setInputType("textarea");\r
+ $f->maxlength = 25000;\r
+ $f->is_required = false;\r
+ $f->size_rows = 26;\r
+ $f->comment = "O diagnóstico em sí, todo o desenvolvimento da idéia do mesmo.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("relItems", array("orgaos","Órgãos","sis_diagnostico_orgao","id_diagnostico","id_orgao","sis_orgao","_config/exeptions/routines/search_orgao2.php"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("relItems", array("imagens","Imagens","sis_diagnostico_imagem","id_diagnostico","id_imagem","sis_imagem","_config/exeptions/routines/search_imagem.php"));\r
+ $f->search_page_height = 160;\r
+ $this->addField($f, "IU");\r
+ }\r
+ function loadInit($rotina) {\r
+ global $input;\r
+ $u = '';\r
+ if ($rotina == 'U') {\r
+ $u = $input->encode(' AND id != '.$this->fields('id'));\r
+ }\r
+ ?>\r
+ <script type="text/javascript">\r
+ checkMe = function(tmp_nome){\r
+ var obj = document.getElementById('div_check');\r
+ obj.innerHTML = '<img src="../img/icons/time.gif" width="16" height="16" />';\r
+ var a = new Ajax();\r
+ a.onLoad = function(){\r
+ var obj = document.getElementById('div_check');\r
+ if((this.html+'0') == '00'){\r
+ obj.innerHTML = '<img src="../img/icons/cancel.gif" width="16" height="16" />';\r
+ alert('Atenção, o nome informado já existe no banco de dados.');\r
+ $('Nome_TXT1').focus();\r
+ } else if((this.html+'0') == '10'){\r
+ obj.innerHTML = '<img src="../img/icons/accept.gif" width="16" height="16" />';\r
+ }\r
+ }\r
+ a.get("../../_config/exeptions/routines/routines.php?routine=check&field=<?=$input->encode('nome');?>&table=<?=$input->encode('sis_diagnostico');?>&u=<?=$u;?>&search="+tmp_nome);\r
+ }\r
+ initSugestion = function(){\r
+ var obj = document.getElementById('div_sugestion_cid10');\r
+ obj.innerHTML = 'Carregando...';\r
+ setTimeout("sugestion();",500);\r
+ }\r
+ sugestion = function(){\r
+ var tmp_codigo = document.getElementById('Código CID10_TXT0').value;\r
+ var obj = document.getElementById('div_sugestion_cid10');\r
+ obj.innerHTML = 'Carregando...';\r
+ var a = new Ajax();\r
+ a.onLoad = function(){\r
+ var obj = document.getElementById('div_sugestion_cid10');\r
+ obj.innerHTML = this.html;\r
+ }\r
+ a.get("../../_config/exeptions/routines/routines.php?routine=sugestion&codigo="+tmp_codigo);\r
+ }\r
+ setSugestion = function(tmp_codigo,tmp_descricao){\r
+ var obj = document.getElementById('Código CID10_TXT0');\r
+ obj.value = tmp_codigo;\r
+ obj = document.getElementById('div_sugestion_cid10');\r
+ obj.innerHTML = tmp_codigo+' - '+tmp_descricao;\r
+ }\r
+ closeSugestion = function(){\r
+ var obj = document.getElementById('div_sugestion_cid10');\r
+ obj.innerHTML = '';\r
+ }\r
+ </script>\r
+ <?\r
+ }\r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ $cadastra->cadastraPalavras($this->fields("palavrachave"),true,';');\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormEspecialidade extends Form {\r
+ function FormEspecialidade() {\r
+ parent::Form("sis_especialidade");\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados da Especialidade (área médica)"));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 50;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("texto", "Texto"));\r
+ $f->setInputType("textarea");\r
+ $f->maxlength = 10000;\r
+ $f->is_required = false;\r
+ $f->comment = "Uma breve descrição da especialidade, como se define, quais os focus de estudo, exemplos, etc.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("pagina", "URL com http://"));\r
+ $f->maxlength = 250;\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ }\r
+ \r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormGrupoImagem extends Form {\r
+ function FormGrupoImagem() {\r
+ parent::Form("sis_grupoimagem");\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $routine;\r
+ global $profile;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 250;\r
+ $this->addField($f, "LOFIU");\r
+ //if(($routine == 'U') || ($routine == 'L')){\r
+ if(($routine == 'update')){\r
+ global $db;\r
+ $row = $db->execute('SELECT COUNT(ID) as conta FROM sis_imagem where id_grupoimagem = '.$this->fields('id'));\r
+ $quantidade = 0;\r
+ if(!$row->EOF){\r
+ $quantidade = $row->fields('conta');\r
+ if($quantidade == ''){\r
+ $quantidade = 0;\r
+ }\r
+ }\r
+ \r
+ $f = $this->newField("char", array("quantidade", "Quantidade"));\r
+ $f->value = $quantidade;\r
+ $f->is_sql_affect = false;\r
+ $f->is_required = false;\r
+ $f->input_extra = ' disabled="disabled" ';\r
+ $this->addField($f, "IU");\r
+ }\r
+ \r
+ $f = $this->newField("char", array("quantidade", "Quantidade"));\r
+ $f->is_required = false;\r
+ $this->addField($f, "LO");\r
+ \r
+ $f = $this->newField("ativo", array("status", "Status"));\r
+ $f->value_initial = 1;\r
+ $this->addField($f, "LOFIU");\r
+ }\r
+ \r
+ function getListSql($tmp_sql_filter, $tmp_sql_order) {\r
+ $sql = "SELECT t.*, COUNT(i.id) as quantidade from " . $this->table . " t LEFT OUTER JOIN sis_imagem i ON i.id_grupoimagem = t.id where 1=1 " . str_replace('nome','t.nome',$tmp_sql_filter) . " GROUP BY t.id " . $tmp_sql_order;\r
+ return $sql;\r
+ }\r
+ \r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormGrupoOrgao extends Form {\r
+ function FormGrupoOrgao() {\r
+ parent::Form("sis_grupoorgao");\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ global $routine;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados do grupo"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 50;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_camada", "Camada"));\r
+ $f->addElementsByTable('sis_grupoorgao_camada');\r
+ $f->comment = 'A Camada de Topografia é utilizado para especificar níveis (camadas) de topografia, afim de evitar a sobreposição de itens.';\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("x1", "X1"));\r
+ $f->maxlength = 10;\r
+ $f->is_required = false;\r
+ $f->size_cols = 10;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("y1", "Y1"));\r
+ $f->maxlength = 10;\r
+ $f->is_required = false;\r
+ $f->size_cols = 10;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("x2", "X2"));\r
+ $f->maxlength = 10;\r
+ $f->is_required = false;\r
+ $f->size_cols = 10;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("y2", "Y2"));\r
+ $f->maxlength = 10;\r
+ $f->is_required = false;\r
+ $f->size_cols = 10;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f);\r
+ \r
+ $src = '../../_config/exeptions/routines/cropper.php?file=../../../upload/sis_boneco/boneco.gif&endCrop=htmlEditor5';\r
+ if($routine == 'update'){\r
+ if($this->fields('x1') && $this->fields('x2') && $this->fields('y1') && $this->fields('y2')){\r
+ $src .= '&x1='.$this->fields('x1');\r
+ $src .= '&y1='.$this->fields('y1');\r
+ $src .= '&x2='.$this->fields('x2');\r
+ $src .= '&y2='.$this->fields('y2');\r
+ }\r
+ }\r
+ \r
+ $f = $this->newField("html", array("html"));\r
+ $html = '<tr class="fieldset"><td class="custom" colspan="100%" align="center"><iframe align="center" frameborder="0" border="0" style="margin:0px; padding:0px; width:430px; height:480px;" src="'.$src.'" ></iframe></td></tr>';\r
+ $f->html = $html;\r
+ $this->addField($f);\r
+ }\r
+ \r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ }\r
+ \r
+ function loadInit($rotina) {\r
+ if (($rotina == 'U') || ($rotina == 'I')) {\r
+ ?>\r
+ <script language="javascript" type="text/javascript">\r
+ htmlEditor5 = function( coords, dimensions ) {\r
+ document.getElementById('X1_TXT0').value = coords.x1;\r
+ document.getElementById('Y1_TXT0').value = coords.y1;\r
+ document.getElementById('X2_TXT0').value = coords.x2;\r
+ document.getElementById('Y2_TXT0').value = coords.y2;\r
+ }\r
+ </script>\r
+ <?\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormGrupoOrgaoCamada extends Form {\r
+ function FormGrupoOrgaoCamada() {\r
+ parent::Form("sis_grupoorgao_camada");\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Camada Topográfica"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 150;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("ativo");\r
+ $f->value_initial = 1;\r
+ $this->addField($f, "LOFIU");\r
+ }\r
+ \r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormImagem extends Form {\r
+ var $table_rel_orgao;\r
+ \r
+ function FormImagem() {\r
+ parent::Form("sis_imagem");\r
+ $this->table_rel_orgao = "sis_imagem_orgao";\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ global $routine;\r
+ \r
+ $valor = "";\r
+ if($routine == "update"){\r
+ global $db;\r
+ global $load;\r
+ $load->system("functions/text.php");\r
+ \r
+ $sql = "SELECT o.id, o.nome, o.cid10,s.nome as sistema FROM ".$this->table_rel_orgao." io LEFT OUTER JOIN sis_orgao o ON o.id = io.id_orgao LEFT OUTER JOIN sis_sistema s ON s.id = o.id_sistema WHERE io.id_imagem = ".$this->fields("id")." ORDER BY o.nome";\r
+ $rows = $db->execute($sql);\r
+ $arr = array();\r
+ while(!$rows->EOF){\r
+ $arr[] = array($rows->fields("id"),$rows->fields("nome"));\r
+ $rows->moveNext();\r
+ }\r
+ $valor = se($arr);\r
+ }\r
+ //carregar com relacionados ao fazer update - alteração\r
+ $f = $this->newField("hidden", array("relacionados","Relacionados"));\r
+ $f->is_sql_affect = false;\r
+ $f->is_required = false;\r
+ $f->value = $valor;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados da Imagem"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 50;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_procedencia", "Procedencia"));\r
+ $f->addElementsByTable("sis_procedencia");\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_patologia", "Patologia"));\r
+ $f->addElementsByTable("sis_patologia");\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_sistema", "Sistema"));\r
+ $f->addElementsByTable("sis_sistema");\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("imageUpload", array("imagem", "Imagem (tamanho máximo: 1500x1500) ", "upload/sis_imagem/"));\r
+ $f->addThumb("#ID#", 1500, 1500, 4);\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados da Imagem"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("texto", "Texto"));\r
+ $f->setInputType("textarea");\r
+ $f->maxlength = 10000;\r
+ $f->is_required = false;\r
+ $f->comment = "Uma breve descrição da imagem, estilo de corte, descrição de aparência, cor, detalhes do paciente, etc. Esse texto é utiliza para efetuar uma busca descritiva.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("date", array("dataorigem", "Data de origem"));\r
+ $f->is_required = false;\r
+ $f->comment = "Data de origem significa a data em que a foto foi tirada, ou obtida.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("box"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Pesquise Órgãos para relacionar"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("html"));\r
+ $f->html = '\r
+ <tr>\r
+ <td colspan="100%">\r
+ <table cellspacing="3" cellpadding="0" border="0" width="100%">\r
+ <tr>\r
+ <td style="background:#F9F9F9 none repeat scroll 0 0;">\r
+ <iframe id="frameSearch" name="frameSearch" style="width:450px;height:135px;border:0px;" frameborder="0" src="../../_config/exeptions/routines/search_orgao.php"></iframe>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <tr class="fieldset">\r
+ <td class="custom">\r
+ Resultados da pesquisa\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td id="td_result">\r
+ Nenhum item encontrado\r
+ </td>\r
+ </tr>\r
+ ';\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Órgãos já relacionados"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("html"));\r
+ $f->html = '\r
+ <tr>\r
+ <td id="td_rel">\r
+ Nenhum item relacionado.<script type="text/javascript">fromRelHidden();feedRel("td_rel",arrRel);</script>\r
+ </td>\r
+ </tr>\r
+ ';\r
+ $this->addField($f, "IU");\r
+ }\r
+ \r
+ function loadInit($rotina) {\r
+ if (($rotina == 'U') || ($rotina == 'I')) {\r
+ ?>\r
+ <script language="javascript" type="text/javascript">\r
+ unse = function (str) {\r
+ if(str != ""){\r
+ var arrAux = str.split("###");\r
+ var arrAux2 = new Array();\r
+ \r
+ for(var x=0;x<arrAux.length;x++){\r
+ arrAux2[x] = arrAux[x].split("$$$");\r
+ }\r
+ \r
+ return arrAux2\r
+ } else {\r
+ var arrAux = new Array();\r
+ return arrAux;\r
+ }\r
+ }\r
+ se = function (arr) {\r
+ if(arr.length > 0){\r
+ var str = "";\r
+ \r
+ for(var x=0;x<arr.length;x++){\r
+ var aux = arr[x];\r
+ \r
+ str += aux.join("$$$");\r
+ if((x+1) < arr.length){\r
+ str += "###";\r
+ }\r
+ }\r
+ \r
+ return str;\r
+ } else {\r
+ return "";\r
+ }\r
+ }\r
+ getArrSearch = function () {\r
+ return arrSearch;\r
+ }\r
+ setArrSearch = function (arr) {\r
+ arrSearch = arr;\r
+ }\r
+ getDoRelationButton = function (tag_name) {\r
+ var divButton = document.createElement("div");\r
+ var html = '<table cellspacing="0" cellpadding="0" width="100%" border="0"><tr><td align="right">';\r
+ html += '<span src="../../../" onclick="javascript: doRelationWithResult(\''+tag_name+'\');" style="cursor:pointer;">Relacionar selecionados</span>';\r
+ html += '</td></tr></table>';\r
+ divButton.innerHTML = html;\r
+ return divButton;\r
+ }\r
+ getUndoRelationButton = function (tag_name) {\r
+ var divButton = document.createElement("div");\r
+ var html = '<table cellspacing="0" cellpadding="0" width="100%" border="0"><tr><td align="right">';\r
+ html += '<span src="../../../" onclick="javascript: undoRelationWithResult(\''+tag_name+'\');" style="cursor:pointer;">Excluir relacionamento</span>';\r
+ html += '</td></tr></table>';\r
+ divButton.innerHTML = html;\r
+ return divButton;\r
+ }\r
+ array_search = function(arr,needle){\r
+ for(var x=0;x<arr.length;x++){\r
+ if(arr[x][0] == needle[0]){\r
+ return true;\r
+ }\r
+ }\r
+ return false;\r
+ }\r
+ </script>\r
+ <script language="javascript" type="text/javascript">\r
+ var arrSearch = new Array();\r
+ var arrRel = new Array();\r
+ var hiddenRelacionados;\r
+ \r
+ //fazer carregar no final do carregamento da pagina\r
+ init = function() {\r
+ refreshRel();\r
+ //carrega atuais\r
+ }\r
+ fromRelHidden = function () {\r
+ hiddenRelacionados = $("Relacionados_TXT0");//hidden com os relacionados\r
+ arrRel = unse(hiddenRelacionados.value);\r
+ }\r
+ toRelHidden = function(){\r
+ hiddenRelacionados = $("Relacionados_TXT0");//hidden com os relacionados\r
+ hiddenRelacionados.value = se(arrRel);\r
+ }\r
+ returnFromSearch = function (html) {\r
+ arrSearch = unse(html);\r
+ //alert(arrSearch);\r
+ if(arrSearch.length > 0){\r
+ feedResult("td_result",arrSearch);\r
+ } else {\r
+ td_result.innerHTML = "Nenhum item encontrado";\r
+ }\r
+ }\r
+ feedResult = function (id_content_result, arr) {\r
+ var tag_name = id_content_result+"_result";\r
+ var content_result = document.getElementById(id_content_result);\r
+ content_result.innerHTML = "";\r
+ \r
+ content_result.appendChild(getDoRelationButton(tag_name));\r
+ \r
+ var divParent = document.createElement("div");\r
+ divParent.style.background = "#FFFFFF";\r
+ divParent.style.width = "100%";\r
+ divParent.style.height = "150px;";\r
+ divParent.innerHTML = " ";\r
+ \r
+ var bg = "#FFFFFF";\r
+ for(var x=0;x<arr.length;x++){\r
+ var divItem = document.createElement("div");\r
+ divItem.style.width = "100%";\r
+ \r
+ var w = 100/(arr[x].length-1);\r
+ w = 100;\r
+ \r
+ switch(bg){\r
+ case "#FFFFFF":\r
+ bg = "#F9F9F9";\r
+ break;\r
+ case "#F9F9F9":\r
+ bg = "#F4F4F4";\r
+ break;\r
+ case "#F4F4F4":\r
+ bg = "#FFFFFF";\r
+ break;\r
+ }\r
+ \r
+ var tableItem = '<table cellspacing="0" cellpadding="0" width="100%" border="0">';\r
+ tableItem += '<tr style="background:'+bg+';">';\r
+ tableItem += '<td width="20">';\r
+ tableItem += '<input type="checkbox" value="'+x+'" name="'+tag_name+'" id="result_'+id_content_result+'">';\r
+ tableItem += '</td><td width="'+w+'%" align="left">';\r
+ //tableItem += '<a href="javascript: document.getElementById(\'result_'+id+'\').checked = true;">'+arr[x][1]+'</a>';\r
+ tableItem += arr[x][1];\r
+ tableItem += '</td>';\r
+ \r
+ // for(var y=2;y<arr[x].length;y++){\r
+ // tableItem += '<td width="'+w+'%" align="left">';\r
+ // tableItem += arr[x][y];\r
+ // tableItem += '</td>';\r
+ // }\r
+ tableItem += '</tr>';\r
+ divItem.innerHTML = tableItem;\r
+ divParent.appendChild(divItem);\r
+ }\r
+ content_result.appendChild(divParent);\r
+ content_result.appendChild(getDoRelationButton(tag_name));\r
+ }\r
+ doRelationWithResult = function (tag_name) {\r
+ var elements = document.getElementsByName(tag_name);\r
+ var arrChecked = new Array();\r
+ for(var x=0;x<elements.length;x++){\r
+ if(elements[x].checked){\r
+ arrChecked.push(arrSearch[elements[x].value]);\r
+ }\r
+ }\r
+ \r
+ if(arrChecked.length > 0){\r
+ addIds(arrChecked);\r
+ feedRel("td_rel",arrRel);\r
+ } else {\r
+ alert("Selecione ao menus um item para relacionar.");\r
+ }\r
+ }\r
+ undoRelationWithResult = function (tag_name) {\r
+ var elements = document.getElementsByName(tag_name);\r
+ var arrChecked = new Array();\r
+ for(var x=0;x<elements.length;x++){\r
+ if(elements[x].checked){\r
+ arrChecked.push(elements[x].value);\r
+ }\r
+ }\r
+ \r
+ if(arrChecked.length > 0){\r
+ removeIds(arrChecked);\r
+ feedRel("td_rel",arrRel);\r
+ } else {\r
+ alert("Selecione ao menus um item para relacionar.");\r
+ }\r
+ }\r
+ addIds = function (arr){\r
+ fromRelHidden();\r
+ \r
+ for(var x=0;x<arr.length;x++){\r
+ if(!array_search(arrRel,arr[x])) {\r
+ arrRel.push(arr[x]);\r
+ }\r
+ }\r
+ \r
+ toRelHidden();\r
+ }\r
+ removeIds = function (arr) {\r
+ fromRelHidden();\r
+ \r
+ var arrAux = new Array();\r
+ for(var y=0;y<arrRel.length;y++){\r
+ var adicionar = true;\r
+ for(var x=0;x<arr.length;x++){\r
+ if(arr[x] == y){\r
+ adicionar = false;\r
+ }\r
+ }\r
+ if(adicionar){\r
+ arrAux.push(arrRel[y]);\r
+ }\r
+ }\r
+ arrRel = arrAux;\r
+ \r
+ toRelHidden();\r
+ }\r
+ feedRel = function (id_content_rel, arr) {\r
+ var tag_name = id_content_rel+"_result";\r
+ var content_rel = document.getElementById(id_content_rel);\r
+ \r
+ if(arr.length > 0){\r
+ content_rel.innerHTML = "";\r
+ content_rel.appendChild(getUndoRelationButton(tag_name));\r
+ \r
+ var divParent = document.createElement("div");\r
+ divParent.style.background = "#FFFFFF";\r
+ divParent.style.width = "100%";\r
+ divParent.style.height = "150px;";\r
+ divParent.innerHTML = " ";\r
+ \r
+ var bg = "#FFFFFF";\r
+ for(var x=0;x<arr.length;x++){\r
+ var divItem = document.createElement("div");\r
+ divItem.style.width = "100%";\r
+ \r
+ var w = 100/(arr[x].length-1);\r
+ w = 100;\r
+ \r
+ switch(bg){\r
+ case "#FFFFFF":\r
+ bg = "#F9F9F9";\r
+ break;\r
+ case "#F9F9F9":\r
+ bg = "#F4F4F4";\r
+ break;\r
+ case "#F4F4F4":\r
+ bg = "#FFFFFF";\r
+ break;\r
+ }\r
+ \r
+ var tableItem = '<table cellspacing="0" cellpadding="0" width="100%" border="0">';\r
+ tableItem += '<tr style="background:'+bg+';">';\r
+ tableItem += '<td width="20">';\r
+ tableItem += '<input type="checkbox" value="'+x+'" name="'+tag_name+'" id="result_'+id_content_rel+'">';\r
+ tableItem += '</td><td width="'+w+'%" align="left">';\r
+ //tableItem += '<a href="javascript: document.getElementById(\'result_'+id+'\').checked = true;">'+arr[x][1]+'</a>';\r
+ tableItem += arr[x][1];\r
+ tableItem += '</td>';\r
+ \r
+ // for(var y=2;y<arr[x].length;y++){\r
+ // tableItem += '<td width="'+w+'%" align="left">';\r
+ // tableItem += arr[x][y];\r
+ // tableItem += '</td>';\r
+ // }\r
+ tableItem += '</tr>';\r
+ divItem.innerHTML = tableItem;\r
+ divParent.appendChild(divItem);\r
+ }\r
+ \r
+ content_rel.appendChild(divParent);\r
+ content_rel.appendChild(getUndoRelationButton(tag_name));\r
+ } else {\r
+ content_rel.innerHTML = "Nenhum item relacionado.";\r
+ }\r
+ }\r
+ </script>\r
+ <?\r
+ }\r
+ }\r
+ \r
+ function onPosPost($routine) {\r
+ global $db;\r
+ global $input;\r
+ global $load;\r
+ $load->system('functions/text.php');\r
+ \r
+ $arrRel = unse($input->post('relacionados'));\r
+ \r
+ if ($routine == 'U') {\r
+ $sql = "DELETE FROM ".$this->table_rel_orgao." WHERE id_imagem = ".$this->fields('id');\r
+ $db->execute($sql);\r
+ \r
+ for($x=0;$x<sizeof($arrRel);$x++){\r
+ $id = $arrRel[$x][0];\r
+ $sql = "INSERT INTO ".$this->table_rel_orgao." (id_imagem,id_orgao) VALUES (".$this->fields('id').",".$id.")";\r
+ $db->execute($sql);\r
+ }\r
+ } else if ($routine == "I"){\r
+ for($x=0;$x<sizeof($arrRel);$x++){\r
+ $id = $arrRel[$x][0];\r
+ $sql = "INSERT INTO ".$this->table_rel_orgao." (id_imagem,id_orgao) VALUES (".$this->fields('id').",".$id.")";\r
+ $db->execute($sql);\r
+ }\r
+ }\r
+ }\r
+ \r
+ function postDelete() {\r
+ global $db;\r
+ \r
+ $sql = "DELETE FROM ".$this->table_rel_orgao." WHERE id_imagem = ".$this->fields('id');\r
+ $db->execute($sql);\r
+ \r
+ $this->onDelete();\r
+ $this->_onDeleteFields();\r
+ $this->delete();\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormImagem extends Form {\r
+ var $table_rel_orgao;\r
+ \r
+ function FormImagem() {\r
+ parent::Form("sis_imagem");\r
+ $this->table_rel_orgao = "sis_imagem_orgao";\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ global $routine;\r
+ global $input;\r
+ global $db;\r
+ \r
+ //$f = $this->newField("char", array("id", "ID"));\r
+ //$this->addField($f, "LOF");\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ if($routine == 'update'){\r
+ $sql = 'SELECT id FROM bku_imagem WHERE id_imagem = '.$this->fields('id').' ORDER BY datahora DESC';\r
+ $rows = $db->execute($sql);\r
+ \r
+ $downloadBackup = '';\r
+ if(!$rows->EOF){\r
+ $downloadBackup = ' <div style="float:right;">\r
+ <a href="javascript: downloadBackup();" alt="Fazer Backup" title="Fazer Backup"><img src="../img/buttons/downbackup.jpg" /></a>\r
+ </div>';\r
+ }\r
+ \r
+ $f = $this->newField("html", array("label","Restauração"));\r
+ $this->addField($f, "U");\r
+ \r
+ $f = $this->newField("html", array("html"));\r
+ $html = ' <tr>\r
+ <td class="label" colspan="100%">\r
+ <div style="float:left;">\r
+ <a href="javascript: doBackup();" alt="Fazer Backup" title="Fazer Backup">\r
+ <img src="../img/buttons/dobackup.jpg" />\r
+ </a>\r
+ </div>\r
+ '.$downloadBackup.'\r
+ </td>\r
+ </tr>';\r
+ $f->html = $html;\r
+ $this->addField($f, "U");\r
+ }\r
+ \r
+ $f = $this->newField("html", array("label","Dados da Imagem"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->setInputType('textarea');\r
+ $f->size_cols = 55;\r
+ $f->size_rows = 2;\r
+ $f->maxlength = 200;\r
+ $f->input_extra = " onblur='javascript: checkMe(this.value);' ";\r
+ $f->field_extra = "<div id='div_check' style='float:right; width:16px; height:16px;'></div>";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_grupoimagem", "Grupo"));\r
+ $f->addElementsByTable("sis_grupoimagem");\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_procedencia", "Procedencia"));\r
+ $f->addElementsByTable("sis_procedencia");\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_patologia", "Patologia"));\r
+ $f->addElementsByTable("sis_patologia");\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("items", array("id_sistema", "Sistema"));\r
+ $f->addElementsByTable("sis_sistema");\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("imageUpload", array("imagem", "Imagem (tamanho máximo: 1500x1500) ", "upload/sis_imagem/"));\r
+ $f->addThumb("#ID#", 1500, 1500, 4);\r
+ $f->is_required = false;\r
+ $f->extensions_accept = array("jpg");\r
+ $f->hint = 'Somente imagens em jpg<br /><br/>Imagem para visualização no site.';\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("items",array("carimbo","Carimbo"));\r
+ $f->setInputType('radio');\r
+ $f->addElementsByArray(array('Esquerdo superior','Direito superior','Esquerdo inferior','Direito inferior','Sem carimbo'));\r
+ $f->comment = "Este campo determina aonde será localizado o carimbo da UFCSPA.";\r
+ $f->is_required = false;\r
+ $f->value_initial = 4;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados da Imagem"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("texto", "Texto"));\r
+ $f->setInputType("textarea");\r
+ $f->maxlength = 19000;\r
+ $f->is_required = false;\r
+ $f->comment = "Uma breve descrição da imagem, estilo de corte, descrição de aparência, cor, detalhes do paciente, etc. Esse texto é utiliza para efetuar uma busca descritiva.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("date", array("dataorigem", "Data de origem"));\r
+ $f->is_required = false;\r
+ $f->comment = "Data de origem significa a data em que a foto foi tirada, ou obtida.";\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("ativo",array("visualizacao","Visualização"));\r
+ $f->value_initial = 1;\r
+ $f->comment = "Este campo determina se a imagem será visualizada no site.";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("ativo",array("saudavel","Saudável?"));\r
+ $this->addField($f, "L");\r
+ \r
+ $f = $this->newField("items",array("saudavel","É Saudável?"));\r
+ $f->value_initial = 1;\r
+ $f->loadConfig('simnao');\r
+ $f->comment = "Imagens marcadas como saudáveis só podem ser relacionadas a casos de estudo.";\r
+ $this->addField($f, "OFIU");\r
+ \r
+ // $f = $this->newField("upload", array("imagemoriginal", "Imagem Original ", "upload/sis_imagem_original/"));\r
+ // $f->setFileName("#ID#");\r
+ // $f->is_required = false;\r
+ // $f->extensions_accept = array('tif','bmp','jpg','gif','png');\r
+ // $f->hint = 'Somente a original (tif,bmp,jpg,gif,png)<br /><br />Imagem para download no site. Limite de 1MB.';\r
+ // $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("relItems", array("orgaos","Órgãos","sis_imagem_orgao","id_imagem","id_orgao","sis_orgao","_config/exeptions/routines/search_orgao2.php"));\r
+ $this->addField($f, "IU");\r
+ }\r
+ function loadInit($rotina) {\r
+ global $input;\r
+ $u = '';\r
+ if ($rotina == 'U') {\r
+ $u = $input->encode(' AND id != '.$this->fields('id'));\r
+ ?>\r
+ <script language="javascript" type="text/javascript">\r
+ downloadBackup = function() {\r
+ var a = new Ajax();\r
+ a.onLoad = function(){\r
+ if(this.html.search("rro") == -1){\r
+ window.open(this.html,'_blank');\r
+ } else {\r
+ alert(this.html);\r
+ }\r
+ }\r
+ a.get("../../_config/exeptions/routines/backup.php?routine=imgDBku&id=<?=$input->encode($this->fields('id'));?>");\r
+ }\r
+ doBackup = function() {\r
+ var a = new Ajax();\r
+ a.onLoad = function(){\r
+ alert(this.html);\r
+ }\r
+ a.get("../../_config/exeptions/routines/backup.php?routine=imgBku&id=<?=$input->encode($this->fields('id'));?>");\r
+ }\r
+ </script>\r
+ <?\r
+ }\r
+ ?>\r
+ <script type="text/javascript">\r
+ checkMe = function(tmp_nome){\r
+ var obj = document.getElementById('div_check');\r
+ obj.innerHTML = '<img src="../img/icons/time.gif" width="16" height="16" />';\r
+ var a = new Ajax();\r
+ a.onLoad = function(){\r
+ var obj = document.getElementById('div_check');\r
+ if((this.html+'0') == '00'){\r
+ obj.innerHTML = '<img src="../img/icons/cancel.gif" width="16" height="16" />';\r
+ alert('Atenção, o nome informado já existe no banco de dados.');\r
+ $('Nome_TXT1').focus();\r
+ } else if((this.html+'0') == '10'){\r
+ obj.innerHTML = '<img src="../img/icons/accept.gif" width="16" height="16" />';\r
+ }\r
+ }\r
+ a.get("../../_config/exeptions/routines/routines.php?routine=check&field=<?=$input->encode('nome');?>&table=<?=$input->encode('sis_imagem');?>&u=<?=$u;?>&search="+tmp_nome);\r
+ }\r
+ </script>\r
+ <?\r
+ }\r
+ function onPosPost($routine){\r
+ global $load;\r
+ global $input;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ //$cadastra->cadastraPalavras($this->fields("palavrachave"),true,';');\r
+ \r
+ $load->config('classes/Imagem.php');\r
+ $img = new Imagem();\r
+ $img->verifyWaterMark($this->fields('id'),$this->fields('carimbo'),true);\r
+ \r
+ if($routine == 'U'){\r
+ $arr_folders = array('sis_imagem_p','sis_imagem_pp','sis_imagem_m');\r
+ $totalFolder = count($arr_folders);\r
+ for($x=0;$x<$totalFolder;$x++){\r
+ $temp_src = '../../../upload/'.$arr_folders[$x].'/'.$this->fields('id').'.jpg';\r
+ @unlink($temp_src);\r
+ }\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormOrgao extends Form {\r
+ function FormOrgao() {\r
+ parent::Form("sis_orgao");\r
+ $this->page_size = 50;\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados do órgão"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 50;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ // $f = $this->newField("char", array("cid10", "Código CID10"));\r
+ // $f->maxlength = 10;\r
+ // $f->size_cols = 10;\r
+ // $f->is_required = false;\r
+ // $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("imageUpload", array("imagem", "Ícone ilustrutivo (50x50 px)", "upload/sis_orgao/"));\r
+ $f->addThumb("#ID#", 1000, 1000, 4);\r
+ $f->addThumb("#ID#_p", 50, 50, 4);\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados extras"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("pagina", "URL com http://"));\r
+ $f->maxlength = 250;\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("char", array("palavrachave", "Palavras-chave"));\r
+ $f->maxlength = 250;\r
+ $f->is_required = false;\r
+ $f->comment = "Palavras relacionadas ao órgão, que eventualmente podem facilitar a pesquisa. Separar palavras com ponto e vírgula.";\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("imageUpload", array("imagem", "Ícone", "upload/sis_orgao/"));\r
+ $f->addThumb("#ID#", 1000, 1000, 4);\r
+ $f->addThumb("#ID#_p", 50, 50, 4);\r
+ $f->is_required = false;\r
+ $this->addField($f, "L");\r
+ \r
+ $f = $this->newField('html',array('box'));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField('html',array('label', 'Sistemas relacionados'));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField('multiItems', array('orgaosistema','','sis_orgao_sistema','id_orgao','id_sistema'));\r
+ $f->addElementsByTable('sis_sistema');\r
+ $this->addField($f,'IU');\r
+ \r
+ $f = $this->newField('html',array('box'));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField('html',array('label', 'Topografia'));\r
+ $this->addField($f);\r
+ \r
+ $f = $this->newField('multiItems', array('orgaogrupoorgao','','sis_orgao_grupoorgao','id_orgao','id_grupoorgao'));\r
+ $f->addElementsByTable('sis_grupoorgao');\r
+ $this->addField($f,'IU');\r
+ }\r
+ \r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ $cadastra->cadastraPalavras($this->fields("palavrachave"),true,';');\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormPalavra extends Form {\r
+ function FormPalavra() {\r
+ parent::Form("sis_palavra");\r
+ \r
+ $this->flags = "LU";\r
+ }\r
+ \r
+ function configFields() {\r
+ $f = $this->newField("char", array("palavra", "Palavra"));\r
+ $f->is_static = true;\r
+ $this->addField($f, "LOFU");\r
+ \r
+ $f = $this->newField("ativo");\r
+ $f->value_initial = 1;\r
+ $this->addField($f, "LOFU");\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormPalavraBusca extends Form {\r
+ function FormPalavraBusca() {\r
+ parent::Form("sis_palavrabusca");\r
+ \r
+ $this->flags = "L";\r
+ }\r
+ \r
+ function configFields() {\r
+ $f = $this->newField("char", array("palavra", "Palavra"));\r
+ $f->is_static = true;\r
+ $this->addField($f, "LOF");\r
+ \r
+ $f = $this->newField("number", array("quantidade", "Quantidade"));\r
+ $f->is_static = true;\r
+ $this->addField($f, "LOF");\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormPatologia extends Form {\r
+ function FormPatologia() {\r
+ parent::Form("sis_patologia");\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados do patologia"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 50;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados extra"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("pagina", "URL com http://"));\r
+ $f->maxlength = 250;\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("imageUpload", array("imagem", "Ícone ilustrutivo (50x50 px)", "upload/sis_patologia/"));\r
+ $f->addThumb("#ID#", 1000, 1000, 4);\r
+ $f->addThumb("#ID#_p", 50, 50, 4);\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("imageUpload", array("imagem", "Ícone", "upload/sis_patologia/"));\r
+ $f->addThumb("#ID#", 1000, 1000, 4);\r
+ $f->addThumb("#ID#_p", 50, 50, 4);\r
+ $f->is_required = false;\r
+ $this->addField($f, "L");\r
+ }\r
+ \r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormProcedencia extends Form {\r
+ function FormProcedencia() {\r
+ parent::Form("sis_procedencia");\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados da procedência"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 50;\r
+ $f->comment = "A procedência identifica o tipo da imagem, como por exemplo: Imagem de Raio X, Ultrasom, foto simples, ressonância, etc.";\r
+ $this->addField($f, "LOFIU");\r
+ }\r
+ \r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FormSistema extends Form {\r
+ function FormSistema() {\r
+ parent::Form("sis_sistema");\r
+ // global $profile;\r
+ // $this->flags = $profile->getFlags();\r
+ }\r
+ \r
+ function configFields() {\r
+ global $profile;\r
+ \r
+ $f = $this->newField("hidden", array("id_usuario", "Responsável"));\r
+ $f->value = $profile->fields('id');\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("hidden", array("dataalteracao", "Data Alteração"));\r
+ $f->value = date("Y-m-d H:i:s");\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados do sistema"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("nome", "Nome"));\r
+ $f->maxlength = 50;\r
+ $this->addField($f, "LOFIU");\r
+ \r
+ $f = $this->newField("html", array("separador"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("html", array("label","Dados extra"));\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("char", array("pagina", "URL com http://"));\r
+ $f->maxlength = 250;\r
+ $f->is_required = false;\r
+ $this->addField($f, "LOFIU");\r
+\r
+ $f = $this->newField("imageUpload", array("imagem", "Ícone ilustrutivo (50x50 px)", "upload/sis_sistema/"));\r
+ $f->addThumb("#ID#", 1000, 1000, 4);\r
+ $f->addThumb("#ID#_p", 50, 50, 4);\r
+ $f->is_required = false;\r
+ $this->addField($f, "IU");\r
+ \r
+ $f = $this->newField("imageUpload", array("imagem", "Ícone", "upload/sis_sistema/"));\r
+ $f->addThumb("#ID#", 1000, 1000, 4);\r
+ $f->addThumb("#ID#_p", 50, 50, 4);\r
+ $f->is_required = false;\r
+ $this->addField($f, "L");\r
+ }\r
+ \r
+ function onPosPost($routine){\r
+ global $load;\r
+ \r
+ $load->config('classes/Palavra.php');\r
+ $cadastra = new Palavra();\r
+ $cadastra->cadastraPalavras($this->fields("nome"));\r
+ $cadastra->cadastraPalavras($this->fields("nome"), false);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+global $menu;\r
+global $profile;\r
+\r
+$subs = array();\r
+\r
+if ($profile->checkMenu(1)) {\r
+ $subs[] = new Menu_sub("Patologia", "Patologias");\r
+}\r
+if ($profile->checkMenu(3)) {\r
+ $subs[] = new Menu_sub("Sistema", "Sistemas");\r
+}\r
+if ($profile->checkMenu(16)) {\r
+ $subs[] = new Menu_sub("GrupoOrgaoCamada", "Camada Topográfica");\r
+}\r
+if ($profile->checkMenu(4)) {\r
+ $subs[] = new Menu_sub("GrupoOrgao", "Topografia");\r
+}\r
+if ($profile->checkMenu(2)) {\r
+ $subs[] = new Menu_sub("Orgao", "Órgãos");\r
+}\r
+if ($profile->checkMenu(5)) {\r
+ $subs[] = new Menu_sub("Procedencia", "Procedência/Tipo");\r
+}\r
+if ($profile->checkMenu(6)) {\r
+ $subs[] = new Menu_sub("Especialidade", "Especialidade");\r
+}\r
+if ($profile->checkMenu(15)) {\r
+ $subs[] = new Menu_sub("Cid10", "CID 10");\r
+}\r
+if (count($subs) > 0) {\r
+ $menu->add("Informações Gerais", $subs);\r
+}\r
+\r
+$subs = array();\r
+if ($profile->checkMenu(7)) {\r
+ $subs[] = new Menu_sub("Imagem", "Imagens");\r
+}\r
+if ($profile->checkMenu(8)) {\r
+ $subs[] = new Menu_sub("Diagnostico", "Diagnósticos");\r
+}\r
+if ($profile->checkMenu(13)) {\r
+ $subs[] = new Menu_sub("GrupoImagem", "Grupos de imagem");\r
+}\r
+if ($profile->checkMenu(9)) {\r
+ $subs[] = new Menu_sub("CasoEstudo", "Casos de Estudo");\r
+}\r
+if (count($subs) > 0) {\r
+ $menu->add("Informações de Material", $subs);\r
+}\r
+\r
+$subs = array();\r
+if ($profile->checkMenu(11)) {\r
+ $subs[] = new Menu_sub("Palavra", "Palavras");\r
+}\r
+if ($profile->checkMenu(12)) {\r
+ $subs[] = new Menu_sub("PalavraBusca", "Palavras Buscadas");\r
+}\r
+if (count($subs) > 0) {\r
+ $menu->add("Banco de Palavras", $subs);\r
+}\r
+\r
+$subs = array();\r
+if ($profile->checkMenu(10)) {\r
+ $subs[] = new Menu_sub("adminUsuario", "Usuários");\r
+}\r
+if ($profile->fields('id') == 1) {\r
+ $subs[] = new Menu_sub("adminSessao", "Sessões Manager");\r
+ //$subs[] = new Menu_sub("lojaTexto", "Textos Loja","loja_gerenciar_texto.php");\r
+}\r
+\r
+if (count($subs) > 0) {\r
+ $menu->add("Usuários", $subs);\r
+}\r
+\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+//error_reporting(E_ALL);
+error_reporting(0);
+session_start();
+//Defines
+define("LF", "\n");
+define("CRLF", "\r\n");
+
+//Diretories
+if (!defined("DIR_ROOT")) {
+ define("DIR_ROOT", str_replace("/_system", "", str_replace("\\", "/", dirname(__FILE__))) . "/");
+}
+define("DIR_SYSTEM", DIR_ROOT . "_system/");
+define("DIR_CONFIG", DIR_ROOT . "_config/");
+
+
+//Globals
+global $load;
+global $error;
+global $cfg;
+global $input;
+global $output;
+global $menu;
+global $file;
+global $system;
+
+//Debug class
+include(DIR_SYSTEM . "core/Debug.php");
+
+//Error handle
+include(DIR_SYSTEM . "core/Error.php");
+
+//System base
+include(DIR_SYSTEM . "core/System.php");
+$system = new System();
+
+
+
+//Load
+include(DIR_SYSTEM . "core/Load.php");
+$load = new Load();
+define("IS_LOCAL", ($system->testServer("localhost") || $system->testServer("server") || $system->testServer("192.168.1.2") || $system->testServer("200.160.153.121")));
+
+
+//Config
+if (!isset($cfg["database_connect"])) { // Check if can connect base
+ $cfg = array();
+}
+$load->config('config.php');
+$system->formatConfig();
+
+define("DIR_MANAGER", $cfg["folder_manager"] . "/");
+define("IS_MANAGER", $system->isManager());
+define("IS_DEVELOP", ($cfg["develop"]) ? ($cfg["develop"] && IS_LOCAL) : false);
+
+
+//Database
+if (array_key_exists("database_type", $cfg)) {
+ // To old versions' Framework
+ if (!is_array($cfg["database_type"])) {
+ $arr_tmp = array($cfg["database_type"],$cfg["database_server"],$cfg["database_user"],$cfg["database_password"],$cfg["database_database"]);
+ $cfg["database_type"] = array();
+ $cfg["database_server"] = array();
+ $cfg["database_user"] = array();
+ $cfg["database_password"] = array();
+ $cfg["database_database"] = array();
+
+ $cfg["database_type"][0] = $arr_tmp[0];
+ $cfg["database_server"][0] = $arr_tmp[1];
+ $cfg["database_user"][0] = $arr_tmp[2];
+ $cfg["database_password"][0] = $arr_tmp[3];
+ $cfg["database_database"][0] = $arr_tmp[4];
+ }
+
+ for($x=0,$total=sizeof($cfg["database_type"]);$x<$total;$x++) {
+ // Create an object: $db, $db2,$db3, ...
+ $newvar = "db".(($x == 0)?'':$x+1);
+ $$newvar = $load->database($x);
+
+ //.connect
+ if (!($cfg["database_connect"][$x] === false)) {
+ $$newvar->connect($cfg,$x);
+ }
+ }
+}
+
+
+//Color
+//.input
+$load->system("core/Input.php");
+$input = new Input();
+
+//.output
+$load->system("core/Output.php");
+$output = new Output();
+
+//.file
+$load->system("core/File.php");
+$file = new File();
+
+
+//.DBTable
+$load->system("core/DBTable.php");
+
+
+//Functions
+$load->system("functions/url.php");
+$load->system("functions/debug.php");
+?>
--- /dev/null
+<?
+class DBTable {
+ var $table;
+
+ var $fields;
+ var $fields_info;
+
+ var $key_field;
+
+ function DBTable($tmp_table, $tmp_key_field = "id") {
+ $this->table = trim($tmp_table);
+
+ $this->key_field = trim($tmp_key_field);
+
+ $this->_loadFieldsInfo();
+ }
+
+ function setValuesFromInput($tmp_function = "") {
+ global $input;
+
+ if ($tmp_function == "") {
+ $tmp_function = "post";
+ }
+
+ switch ($tmp_function) {
+ default:
+ case "post":
+ $arr = $_POST;
+ $function = "post";
+
+ break;
+ case "get":
+ $arr = $_GET;
+ $function = "get";
+
+ break;
+ }
+
+ foreach ($this->fields_info as $v) {
+ $name = $v["name"];
+
+ if (array_key_exists($name, $arr)) {
+ eval("$" . "this->fields[$name] = $" . "input->" . $function ."($name);");
+ }
+ }
+ }
+
+ function setValuesFromRs($tmp_rs) {
+ if ($tmp_rs) {
+ foreach ($this->fields_info as $v) {
+ $name = $v["name"];
+ $value = $tmp_rs->fields($name);
+
+ if ($value != "") {
+ $this->fields[$name] = $value;
+ }
+ }
+ }
+ }
+
+ function fields($tmp_name) {
+ $r = "";
+
+ if (isset($this->fields[$tmp_name])) {
+ $r = $this->fields[$tmp_name];
+ }
+
+ return $r;
+ }
+
+ //======================================
+ // Sql functions
+ //======================================
+ function select($tmp_conditions = "[key]") {
+ global $db;
+
+ if ($tmp_conditions == "[key]") {
+ if ($this->fields[$this->key_field] != "") {
+ $tmp_conditions = "id = " . $db->sql->escape($this->fields[$this->key_field]) . " LIMIT 1";
+ } else {
+ error(1, "Campo '" . $this->key_field . "' não definido", "DBTable", "select");
+
+ return false;
+ }
+ }
+
+ $sql = "select * from " . $this->table . " where " . $tmp_conditions . ";";
+ $rs = $db->execute($sql);
+
+ if (!$rs->EOF) {
+ $fields = $this->fields_info;
+ $length = count($fields);
+
+ for ($i = 0; $i < $length; $i++) {
+ $this->fields[$fields[$i]["name"]] = $rs->fields($fields[$i]["name"]);
+ }
+
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ function insert() {
+ global $db;
+
+ $fields = $this->fields_info;
+ $length = count($fields);
+
+ $arr = array();
+ $arr2 = array();
+
+ for ($i = 0; $i < $length; $i++) {
+ $v = "";
+
+ if (isset($this->fields[$fields[$i]["name"]])) {
+ $v = $this->fields[$fields[$i]["name"]];
+ }
+
+ if ((($v != "") || ($v == "0")) && ($fields[$i]["name"] != $this->key_field)) {
+ $arr[] = $fields[$i]["name"];
+ $arr2[] = $db->sql->escape($v);
+ }
+ }
+
+ $sql = "insert into " . $this->table . " (" . implode(", ", $arr) . ") values (" . implode(", ", $arr2) . ");";
+ $rs = $db->execute($sql);
+
+ $this->fields[$this->key_field] = $rs->getInsertId();
+ }
+
+ function update($tmp_conditions = "[key]") {
+ global $db;
+
+ if ($tmp_conditions == "[key]") {
+ if ($this->fields[$this->key_field] != "") {
+ $tmp_conditions = "id = " . $db->sql->escape($this->fields[$this->key_field]);
+ } else {
+ error(1, "Campo '" . $this->key_field . "' não definido", "DBTable", "update");
+
+ return false;
+ }
+ }
+
+ $fields = $this->fields_info;
+ $length = count($fields);
+
+ $arr = array();
+
+ for ($i = 0; $i < $length; $i++) {
+ $v = "";
+
+ if (isset($this->fields[$fields[$i]["name"]])) {
+ $v = $this->fields[$fields[$i]["name"]];
+ }
+
+ if ((($v != "") || ($v == "0") || ($v == "")) && ($fields[$i]["name"] != $this->key_field)) {
+ $arr[] = $fields[$i]["name"] . " = " . $db->sql->escape($v);
+ }
+ }
+
+ $sql = "update " . $this->table . " set " . implode(", ", $arr) . " where " . $tmp_conditions . ";";
+ $db->execute($sql);
+ }
+
+ function delete($tmp_conditions = "[key]") {
+ global $db;
+
+ if ($tmp_conditions == "[key]") {
+ if ($this->fields[$this->key_field] != "") {
+ $tmp_conditions = "id = " . $db->sql->escape($this->fields[$this->key_field]);
+ } else {
+ error(1, "Campo '" . $this->key_field . "' não definido", "DBTable", "delete");
+
+ return false;
+ }
+ }
+
+ $sql = "delete from " . $this->table . " where " . $tmp_conditions . ";";
+ $db->execute($sql);
+ }
+
+ //Private functions
+ function _loadFieldsInfo() {
+ global $db;
+
+ $this->fields_info = $db->sql->getFieldsInfo($this->table);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Debug {
+ var $_messages;
+ var $_sqls;
+
+ var $_time_ini;
+
+ function Debug() {
+ $this->_time_ini = $this->_getMicroTime();
+
+ $this->_messages = array();
+ $this->_sqls = array();
+
+ $this->addMessage("[debug] é instanciado.");
+ }
+
+ function addMessage($tmp_message, $tmp_microtime_ini = 0) {
+ if ($tmp_microtime_ini > 0) {
+ //duration time
+ $t = $this->_getMicroTime() - $this->_getMicroTime($tmp_microtime_ini);
+ $instant_time = $this->_getMicroTime();
+ } else {
+ //instant time
+ $t = $this->_getMicroTime();
+ $instant_time = 0;
+ }
+
+ $this->_messages[] = array($t, $tmp_message, $instant_time);
+ }
+
+ function addSql($tmp_sql, $tmp_microtime_ini = 0) {
+ if ($tmp_microtime_ini > 0) {
+ //duration time
+ $t = $this->_getMicroTime() - $this->_getMicroTime($tmp_microtime_ini);
+ $instant_time = $this->_getMicroTime();
+ } else {
+ //instant time
+ $t = $this->_getMicroTime();
+ $instant_time = 0;
+ }
+
+ $this->_sqls[] = array($t, $tmp_sql, $instant_time);
+ }
+
+ function loadList() {
+ if (IS_DEVELOP) {
+ $this->addMessage("<strong>$" . "debug</strong>->loadList();");
+
+ echo "<div style='border: 1px solid #666666; margin: 10px; padding: 10px; font-family: Verdana; font-size: 10px; color: #666666;'>" . LF;
+
+ //Events
+ echo "<h3 style='font-family: Arial; font-size: 18px; color: #666666; margin: 0 0 5 5px;'>Eventos</h3>" . LF;
+
+ foreach ($this->_messages as $k => $v) {
+ $message = str_replace("[", "<b>$", $v[1]);
+ $message = str_replace("]", "</b>", $message);
+
+ if ($v[2] > 0) {
+ //duration time
+ echo number_format(($v[2] - $this->_time_ini) * 1000, 2, ",", ".") . "ms - [" . number_format($v[0] * 1000, 2, ",", ".") . "ms] - " . $message . "<br>" . LF;
+ } else {
+ //instant time
+ echo number_format(($v[0] - $this->_time_ini) * 1000, 2, ",", ".") . "ms - " . $message . "<br>" . LF;
+ }
+ }
+
+ echo "<br><br>";
+
+ //Sqls
+ echo "<h3 style='font-family: Arial; font-size: 18px; color: #666666; margin: 0 0 5 5px;'>Sqls</h3>" . LF;
+
+ foreach ($this->_sqls as $k => $v) {
+ $sql = str_replace("[", "<b>$", $v[1]);
+ $sql = str_replace("]", "</b>", $sql);
+
+ if ($v[2] > 0) {
+ //duration time
+ echo number_format(($v[2] - $this->_time_ini) * 1000, 2, ",", ".") . "ms - [" . number_format($v[0] * 1000, 2, ",", ".") . "ms] - " . $sql . "<br>" . LF;
+ } else {
+ //instant time
+ echo number_format(($v[0] - $this->_time_ini) * 1000, 2, ",", ".") . "ms - " . $sql . "<br>" . LF;
+ }
+ }
+
+ echo "</div>";
+ }
+ }
+
+ //private functions
+ function _getMicroTime($tmp_microtime = 0) {
+ if ($tmp_microtime == 0) {
+ $tmp_microtime = microtime();
+ }
+
+ $tmp = explode(" ", $tmp_microtime);
+
+ return (float)$tmp[0] + (float)$tmp[1];
+ }
+}
+
+function log_message($tmp_message, $tmp_microtime_ini = 0) {
+ global $debug;
+
+ $debug->addMessage($tmp_message, $tmp_microtime_ini);
+}
+
+function log_sql($tmp_sql, $tmp_microtime_ini = 0) {
+ global $debug;
+
+ $debug->addSql($tmp_sql, $tmp_microtime_ini);
+}
+
+$debug = new Debug();
+
+
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Error {
+ var $threshold;
+ var $_levels;
+
+ function Error() {
+ log_message("[error] é instanciado.");
+
+ $this->_levels = array("Notice", "Warning", "Error");
+
+ $this->threshold = 1;
+ }
+
+ function add($tmp_level, $tmp_message, $tmp_class = "", $tmp_function = "", $tmp_file = "", $tmp_line = 0) {
+ if ($tmp_level >= $this->threshold) {
+ echo "<div style='border: 1px solid #666666; font-family: Verdana; font-size: 10px; color: #333333; padding: 5px; line-height: 16px; margin: 5px;'>" . LF;
+
+ echo "<h3 style='font-family: Arial; font-size: 18px; color: #990000; margin: 0 0 5 5px;'>" . $this->_levels[$tmp_level] . "</h3>" . LF;
+
+ echo "<b>MESSAGE:</b> " . str_replace(DIR_ROOT, "/", $tmp_message) . "" . LF;
+
+ if ($tmp_line > 0) {
+ echo "<br><b>LINE:</b> " . $tmp_line . LF;
+ }
+
+ if ($tmp_file != "") {
+ echo "<br><b>FILE:</b> " . str_replace(DIR_ROOT, "/", $tmp_file) . LF;
+ }
+
+ if ($tmp_class != "") {
+ echo "<br><b>FUNCTION:</b> " . $tmp_class . "::" . $tmp_function . "()" . LF;
+ } else if ($tmp_function != "") {
+ echo "<br><b>FUNCTION:</b> " . $tmp_function . LF;
+ }
+
+ echo "</div>" . LF;
+
+ if ($tmp_level == 2) {
+ die();
+ }
+ }
+ }
+}
+$error = new Error();
+
+function error($tmp_level, $tmp_message, $tmp_class = "", $tmp_function = "", $tmp_file = "", $tmp_line = 0) {
+ global $error;
+
+ $error->add($tmp_level, $tmp_message, $tmp_class, $tmp_function, $tmp_file, $tmp_line);
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class File {
+ //TODO: Funções para tratar arquivos e pastas
+
+ function getExtension($tmp_file) {
+ $arr = explode(".", $tmp_file);
+
+ return strtolower($arr[sizeof($arr) - 1]);
+ }
+
+ function getFileName($tmp_file) {
+ return basename($tmp_file);
+ }
+
+ function rename($tmp_name, $tmp_new_name) {
+ return @rename($tmp_name, $tmp_new_name);
+ }
+
+ function deleteFile($tmp_file) {
+ return @unlink($tmp_file);
+ }
+
+ function makeFolder($tmp_folder) {
+ $r = @mkdir($tmp_folder, 0777);
+
+ $this->permission($tmp_folder);
+
+ return $r;
+ }
+
+ function copyFile($tmp_path, $tmp_path_dest) {
+ return copy($tmp_path, $tmp_path_dest);
+ }
+
+ function listFolder($tmp_folder, $tmp_mask = "") {
+ $r = array();
+
+ $witout_mask = true;
+ if ($tmp_mask != "") {
+ $witout_mask = false;
+ }
+
+ if ($d = @dir($tmp_folder)) {
+ while (false !== ($name = $d->read())) {
+ if (($name != ".") && ($name != "..") && ((is_link($tmp_folder . $name)) || (is_file($tmp_folder . $name)) || (is_dir($tmp_folder . $name)))) {
+ if (($witout_mask) || (strpos($name, $tmp_mask) !== false)) {
+ $r[] = $name;
+ }
+ }
+ }
+ } else {
+ $r = array();
+ }
+
+ return $r;
+ }
+
+ function fileSizeFormated($tmp_path) {
+ $size = @filesize($tmp_path);
+
+ $unitys = array("B", "KB", "MB", "GB");
+ $unity = 0;
+
+ while ($size > 1024) {
+ $size = ($size / 1024);
+
+ $unity++;
+ }
+
+ if ($size != round($size)) {
+ $size = number_format($size, 1, ",", ".");
+ }
+
+ return $size . " " . $unitys[$unity];
+ }
+
+ function deleteFolder($tmp_folder) {
+ $this->permission($tmp_folder);
+
+ if (is_dir($tmp_folder)) {
+ $list = $this->listFolder($tmp_folder);
+
+ foreach ($list as $v) {
+ if (is_dir($v)) {
+ echo "recursive: " . $tmp_folder . $v . "/<br>";
+ $this->deleteFolder($tmp_folder . $v . "/");
+ } else {
+ echo "delete file: " . $tmp_folder . $v . "<br>";
+ $this->deleteFile($tmp_folder . $v);
+ }
+ }
+
+ $this->permission($tmp_folder);
+ $r = @rmdir($tmp_folder);
+
+ return $r;
+ } else {
+ return false;
+ }
+ }
+
+ function permission($tmp_path) {
+ @chmod($tmp_path, 0777);
+ @chown($tmp_path, 0);
+ }
+
+ function readFile($tmp_file) {
+ $p = fopen($tmp_file, "r");
+ $fs = filesize($tmp_file);
+
+ if ($fs > 0) {
+ $r = fread($p, filesize($tmp_file));
+ } else {
+ $r = "";
+ }
+
+ fclose($p);
+
+ return $r;
+ }
+
+ function writeFile($tmp_file, $tmp_string, $tmp_overwrite = true) {
+ if ($tmp_overwrite) {
+ $this->deleteFile($tmp_file);
+ } else {
+ $tmp_string = $this->readFile($tmp_file) . $tmp_string;
+ }
+
+ $p = fopen($tmp_file, "w");
+
+ fwrite($p, $tmp_string);
+ fclose($p);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Input {
+
+ function Input() {
+ log_message("[input] é instanciado.");
+
+ $this->_encode_array = array('4', '5', 'J', 'A', 'Q', 'c', 'n', 'x', 'P', 'Y', 'd', 'b', 'g', 'i', 'j', 'y', 'a', '9');
+
+ //TODO: Esquematizar segurança nas variáveis de entrada
+ }
+
+ function keyExists($tmp_input_name, $tmp_key) {
+ switch ($tmp_input_name) {
+ case "request":
+ $var = $_REQUEST;
+
+ break;
+ case "post":
+ $var = $_POST;
+
+ break;
+ case "get":
+ $var = $_GET;
+
+ break;
+ }
+
+ return array_key_exists($tmp_key, $var);
+ }
+
+ function get($tmp_key, $tmp_decode = false) {
+ $key = $this->_cleanKey($tmp_key);
+
+ $r = "";
+ if (isset($_GET[$key])) {
+ $r = $this->_cleanStr($_GET[$key]);
+ }
+
+ if ($tmp_decode) {
+ $r = $this->_decode($r);
+ }
+
+ return $r;
+ }
+
+ function post($tmp_key, $tmp_decode = false) {
+ $key = $this->_cleanKey($tmp_key);
+
+ $r = "";
+ if (isset($_POST[$key])) {
+ $r = $this->_cleanStr($_POST[$key]);
+ }
+
+ if ($tmp_decode) {
+ $r = $this->_decode($r);
+ }
+
+ return $r;
+ }
+
+ function request($tmp_key, $tmp_decode = false) {
+ $get = $this->get($tmp_key);
+ $post = $this->post($tmp_key);
+
+ if ($tmp_decode) {
+ $get = $this->_decode($get);
+ $post = $this->_decode($post);
+ }
+
+ if ($get != "") {
+ return $get;
+ } elseif ($post != "") {
+ return $post;
+ } else {
+ return "";
+ }
+ }
+
+ function server($tmp_key) {
+ global $HTTP_SERVER_VARS;
+ global $HTTP_ENV_VARS;
+
+ if (!isset($_SERVER)) {
+ $_SERVER = $HTTP_SERVER_VARS;
+ if(!isset($_SERVER["REMOTE_ADDR"])) {
+ // must be Apache
+ $_SERVER = $HTTP_ENV_VARS;
+ }
+ }
+
+ if (isset($_SERVER[$tmp_key])) {
+ return $_SERVER[$tmp_key];
+ } else {
+ return "";
+ }
+ }
+
+ function session($tmp_key) {
+ $r = "";
+
+ if (isset($_SESSION[$tmp_key])) {
+ $r = $_SESSION[$tmp_key];
+ }
+
+ return $r;
+ }
+
+ function setSession($tmp_key, $tmp_value) {
+ $_SESSION[$tmp_key] = $tmp_value;
+ }
+
+ function unsetSession($tmp_key) {
+ unset($_SESSION[$tmp_key]);
+ }
+
+ function encode($tmp_string) {
+ return $this->_encode($tmp_string);
+ }
+
+ function decode($tmp_string) {
+ return $this->_decode($tmp_string);
+ }
+
+ //private functions
+ function _cleanStr($tmp_string) {
+ //Remove null chars
+ $tmp_string = preg_replace('/\0+/', '', $tmp_string);
+ $tmp_string = preg_replace('/(\\\\0)+/', '', $tmp_string);
+
+ //Decode raw urls
+ $tmp_string = rawurldecode($tmp_string);
+
+ //Remove bad words
+ $bad = array(
+ 'document.cookie' => '[removed]',
+ 'document.write' => '[removed]',
+ '.parentNode' => '[removed]',
+ '.innerHTML' => '[removed]',
+ 'window.location' => '[removed]',
+ '-moz-binding' => '[removed]',
+ '<!--' => '<!--',
+ '-->' => '-->',
+ '<!CDATA[' => '<![CDATA['
+ );
+
+ foreach ($bad as $k => $v) {
+ $tmp_string = str_replace($k, $v, $tmp_string);
+ }
+
+ //Escape '
+ $tmp_string = str_replace("'", "`", $tmp_string);
+
+ return $tmp_string;
+ }
+
+
+ function _cleanKey($tmp_string) {
+ if (!preg_match("/^[a-z0-9:_\/-]+$/i", $tmp_string)) {
+ error(2, "Chave não permitida", "Input", "_cleanKey");
+ }
+
+ return $tmp_string;
+ }
+
+ function _encode($tmp_string) {
+ $arr = $this->_encode_array;
+ $t = sizeof($arr) - 1;
+ $r = "";
+ $l = strlen($tmp_string);
+
+ for ($i = 0; $i < $l; $i++) {
+ $c1 = 0;
+ $c2 = ord($tmp_string{$i});
+
+ while ($c2 > $t) {
+ $c2 -= $t;
+
+ $c1++;
+ }
+
+ if (($i % 2) == 0) { $r .= $arr[$c1] . $arr[$c2]; }
+ else { $r .= $arr[$t - $c1] . $arr[$t - $c2]; }
+ }
+
+ return $r;
+ }
+
+ function _decode($tmp_string) {
+ $arr = $this->_encode_array;
+ $t = sizeof($arr) - 1;
+ $k = array_flip($arr);
+ $n = 0;
+ $r = "";
+ $l = strlen($tmp_string);
+
+ for ($i = 0; $i < $l; $i++) {
+ $c1 = $tmp_string{$i}; $i++;
+ $c2 = $tmp_string{$i};
+
+ if (($n % 2) == 0) { $r .= chr(($k[$c1] * $t) + $k[$c2]); }
+ else { $r .= chr((($t - $k[$c1]) * $t) + ($t - $k[$c2])); }
+
+ $n++;
+ }
+
+ return $r;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Load {
+ var $_includes;
+ var $_overwrite;
+
+ function Load() {
+ log_message("[load] é instanciado.");
+
+ $this->_includes = array();
+ $this->_overwrite = false;
+ }
+
+ function setOverwrite($tmp_value = false) {
+ $this->_overwrite = $tmp_value;
+ }
+
+ function system($tmp_file, $tmp_verify_exists = false) {
+ $this->_include(DIR_SYSTEM . $tmp_file, $tmp_verify_exists);
+ }
+
+ function config($tmp_file, $tmp_verify_exists = false) {
+ $this->_include(DIR_CONFIG . $tmp_file, $tmp_verify_exists);
+ }
+
+ function manager($tmp_file, $tmp_verify_exists = false) {
+ $this->_include(DIR_ROOT . DIR_MANAGER . $tmp_file, $tmp_verify_exists);
+ }
+
+ function database($tmp_position = 0) {
+ global $cfg;
+
+ $type = $cfg["database_type"][$tmp_position];
+
+ //Load Classes
+ $this->_include(DIR_SYSTEM . "drivers/Connection.php");
+ $this->_include(DIR_SYSTEM . "drivers/" . $type . "/Connection.php");
+ $this->_include(DIR_SYSTEM . "drivers/" . $type . "/Recordset.php");
+ $this->_include(DIR_SYSTEM . "drivers/" . $type . "/Sql.php");
+
+ //Return created connection class
+ $class = ucfirst($type) . "_Connection";
+
+ return new $class();
+ }
+
+ function loadList() {
+ echo "<div style='border: 1px solid #666666; margin: 10px; padding: 10px; font-family: Verdana; font-size: 10px; color: #666666;'>" . LF;
+
+ echo "<h3 style='font-family: Arial; font-size: 18px; color: #666666; margin: 0 0 5 5px;'>Includes</h3>" . LF;
+
+ foreach ($this->_includes as $v) {
+ echo $v . "<br>" . LF;
+ }
+
+ echo "</div>";
+ }
+
+ //Privates
+ function _include($tmp_file, $tmp_verify_exists = true) {
+ $r = false;
+
+ if (array_search($tmp_file, $this->_includes) === false) {
+ if (file_exists($tmp_file)) {
+ $this->_includes[] = $tmp_file;
+
+ $r = include($tmp_file);
+ } else {
+ $r = false;
+ if ($tmp_verify_exists) {
+ error(1, "Arquivo '" . $tmp_file . "' não existe.", "Load", "_include");
+ }
+ }
+ } else {
+ if (!$this->_overwrite) {
+ error(0, "Arquivo '" . $tmp_file . "' já foi incluido.", "Load", "_include");
+ } else {
+ $this->setOverwrite(false);
+ }
+ }
+
+ return $r;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Output {
+ var $is_ajax;
+
+ function Output() {
+ log_message("[output] é instanciado.");
+
+ $this->is_ajax = false;
+ }
+
+ function ajaxHeader() {
+ header("Content-Type: text/html; charset=iso-8859-1");
+ $this->is_ajax = true;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class System {
+ function System() {
+ log_message("[system] é instanciado.");
+ }
+
+ function formatConfig() {
+ global $cfg;
+
+ $cfg["folder_manager"] = (isset($cfg["folder_manager"])) ? $cfg["folder_manager"] : "manager";
+
+ if (!array_key_exists("database_connect", $cfg)) {
+ $cfg["database_connect"] = true;
+ }
+
+ if (!array_key_exists("system_sitelink", $cfg)) {
+ $cfg["system_sitelink"] = "/";
+ }
+
+ if (!array_key_exists("root", $cfg)) {
+ $cfg["root"] = "http://" . $_SERVER['HTTP_HOST'] . "/";
+ }
+
+ if (!array_key_exists("develop", $cfg)) {
+ $cfg["develop"] = false;
+ }
+ }
+
+ function testServer($tmp_server) {
+ if (str_replace($tmp_server, "", $_SERVER['HTTP_HOST']) != $_SERVER['HTTP_HOST']) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ function isManager() {
+ global $cfg;
+
+ return ((strpos($_SERVER["PHP_SELF"], "anager")) || (strpos($_SERVER["PHP_SELF"], $cfg["folder_manager"])));
+ }
+
+ function getFaviconHeader($cfg_page = "") {
+ global $cfg;
+
+ $path = "";
+
+ $root = "../../";
+ if ($cfg_page == "login") {
+ $root = "../../../";
+ }
+
+ $path_default = $root . $cfg["folder_manager"] . "/img/favicon.ico";
+ $path_custom = $root . "_config/exeptions/favicon.ico";
+
+ if (file_exists($path_custom)) {
+ $path = $path_custom;
+ } elseif (file_exists($path_default)) {
+ $path = $path_default;
+ }
+
+ if ($path != "") {
+ echo "<link rel=\"shortcut icon\" href=\"" . $path . "\" type=\"image/x-icon\" />";
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+/* clear elements */
+body {
+ margin: 0px;
+}
+
+a img {
+ border: 0px;
+ margin: 0px;
+}
+
+form {
+ margin: 0px;
+ padding: 0px;
+}
+
+
+/* replace */
+.replace {
+ background-repeat: no-repeat;
+ background-position: left top;
+ background-color:transparent;
+ text-indent:-50000px;
+ overflow:hidden;
+}
+.replace * {
+ text-indent: -10000px;
+ display:block;
+ background-repeat: no-repeat;
+ background-position: left top;
+ background-color:transparent;
+}
+.replace a {
+ text-indent:0;
+}
+.replace a span {
+ text-indent:-10000px;
+}
+
+.replace-bt{
+ text-indent:-999px;
+ line-height:999999px;
+ cursor:pointer;
+ border:none;
+}
+/* end replace */
--- /dev/null
+<?
+class DBConnection {
+ function DBConnection() {
+ log_message("[db] é instanciado.");
+ }
+
+ function connect($tmp_cfg, $tmp_microtime_ini = 0,$position = 0) {
+ log_message("Conectado ao servidor <b>" . $tmp_cfg["database_server"][$position] . "</b>(" . $tmp_cfg["database_type"][$position] . ")", $tmp_microtime_ini);
+ }
+
+ function execute($tmp_sql, $tmp_microtime_ini = 0, $position = 0) {
+ log_sql($tmp_sql, $tmp_microtime_ini);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Mysql_Connection extends DBConnection {
+ var $_connection;
+ var $_database;
+
+ var $sql; //Object of sql template functions
+ function Mysql_Connection() {
+ parent::DBConnection();
+
+ $this->sql = new Mysql_Sql();
+
+ //register_shutdown_function("close");
+ }
+
+ function connect($tmp_cfg,$tmp_position = 0) {
+ $microtime_ini = microtime();
+
+ $tmp_cfg["database_server"] = trim($tmp_cfg["database_server"][$tmp_position]);
+ $tmp_cfg["database_user"] = trim($tmp_cfg["database_user"][$tmp_position]);
+ $tmp_cfg["database_password"] = trim($tmp_cfg["database_password"][$tmp_position]);
+ $tmp_cfg["database_database"] = trim($tmp_cfg["database_database"][$tmp_position]);
+
+ if (!($this->_connection = @mysql_connect($tmp_cfg["database_server"], $tmp_cfg["database_user"], $tmp_cfg["database_password"]))) {
+ error(2, "Não foi possível estabelecer uma conexão com o servidor. <i>(" . mysql_error() . ")</i>", "Mysql_Connection", "connect");
+ }
+
+ if (!(@mysql_select_db($tmp_cfg["database_database"], $this->_connection))) {
+ error(2, "Não foi possível selecionar o banco '" . $tmp_cfg["database_database"] . "'.", "Mysql_Connection", "connect");
+ }
+
+ $this->_database = $tmp_cfg["database_database"];
+
+ parent::connect($tmp_cfg, $microtime_ini);
+ }
+
+ function execute($tmp_sql, $tmp_return_type = 1) {
+ $microtime_ini = microtime();
+
+ $r = new Mysql_RecordSet($tmp_sql, $this->_connection,$this->_database);
+
+ parent::execute($tmp_sql, $microtime_ini);
+
+ if ($r->error != "") {
+ error(2, "Erro de sql: " . $r->sql . " <i>(" . $r->error . ")</i>.", "Mysql_Connection", "execute");
+ }
+
+ if ($tmp_return_type == 1) {
+ //Object
+ return $r;
+ } elseif ($tmp_return_type == 2) {
+ //Resource
+ return $r->rs;
+ }
+ }
+
+ function close() {
+ mysql_close($this->_connection);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Mysql_RecordSet {
+ var $_connection;
+ var $_database;
+ var $rs;
+
+ var $sql;
+ var $error;
+
+ var $recordcount;
+ var $pagesize;
+ var $pagecount;
+ var $absolutepage;
+ var $BOF;
+ var $EOF;
+
+ var $fields;
+
+ function Mysql_RecordSet($tmp_sql, $tmp_connection,$tmp_database) {
+ $this->_connection = $tmp_connection;
+ $this->_database = $tmp_database;
+
+ $this->sql = $this->_formatSql($tmp_sql);
+
+ $this->pagesize = 0;
+ $this->pagecount = 1;
+ $this->absolutepage = 1;
+
+ $this->error = "";
+ $this->execute($tmp_sql);
+ }
+
+ function execute($tmp_sql) {
+ $this->BOF = true;
+ $this->EOF = true;
+
+ if ($tmp_sql == "") {
+ $this->error = "Sql vazia";
+
+ return false;
+ }
+
+ if (is_resource($this->_connection)) {
+ //Page handle
+ if ($this->pagesize > 0) {
+
+ if (substr($this->sql, -1) == ";") {
+ $this->sql = substr($this->sql, 0, (strlen($this->sql) - 1));
+ }
+
+ $tmp = explode("LIMIT", $this->sql);
+ $ini = ($this->absolutepage - 1) * $this->pagesize;
+ $this->sql = $tmp[0] . " LIMIT " . $ini . "," . $this->pagesize;
+ }
+
+ //Execute query
+ if (!($this->rs = @mysql_query($this->sql, $this->_connection))) {
+ echo($this->_database);
+ @mysql_select_db($this->_database, $this->_connection);
+ if (!($this->rs = @mysql_query($this->sql, $this->_connection))) {
+ $this->error = mysql_error();
+
+ return false;
+ }
+ }
+
+ //If sql is 'select'
+ if (strtolower(substr(trim($this->sql), 0, 6)) == "select") {
+ $this->recordcount = mysql_num_rows($this->rs);
+ $this->movenext(true);
+ } else {
+ $this->EOF = true;
+ }
+ }
+ }
+
+ function recordCount() {
+ return $this->recordcount;
+ }
+
+ function moveFirst() {
+ $this->execute($this->sql);
+ }
+
+ function moveNext($tmp_is_first = false) {
+ $this->BOF = $tmp_is_first;
+
+ if (!($this->fields = mysql_fetch_assoc($this->rs))) {
+ $this->EOF = true;
+ } else {
+ $this->EOF = false;
+ }
+ }
+
+ function fields($tmp_name) {
+ if (array_key_exists($tmp_name, $this->fields)) {
+ $r = $this->fields[$tmp_name];
+ } else {
+ $r = NULL;
+ }
+
+ return $r;
+ }
+
+ function page($tmp_page = 1) {
+ if ($tmp_page < 1) {
+ $tmp_page = 1;
+ }
+
+ $this->pagecount = $this->recordcount / $this->pagesize;
+ if ($this->pagecount > (int)($this->pagecount)) {
+ $this->pagecount = (int)($this->pagecount)+1;
+ }
+
+ $this->absolutepage = $tmp_page;
+
+ $this->execute($this->sql);
+ }
+
+ function getInsertId() {
+ return mysql_insert_id();
+ }
+
+ //Private
+ function _formatSql($tmp_sql) {
+ $r = trim($tmp_sql);
+
+ $r = str_replace("day(", "dayofmonth(", $tmp_sql);
+ $r = str_replace("DAY(", "dayofmonth(", $tmp_sql);
+
+ return $r;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Mysql_Sql {
+ function Mysql_Sql() {
+
+ }
+
+ function getFieldsInfo($tmp_table) {
+ global $db;
+
+ $sql = "SHOW COLUMNS FROM " . $tmp_table . ";";
+ $rs = $db->execute($sql, 2);
+
+ while ($d = mysql_fetch_assoc($rs)) {
+ $info = array();
+
+ $info["name"] = $d["Field"];
+ $info["null_accept"] = ($d["Null"] == "YES");
+ $info["key_type"] = $d["Key"];
+ $info["default"] = $d["Default"];
+ $info["auto_increment"] = (strpos($d["Extra"], "auto_increment") !== false);
+ $info["type"] = $d["Type"];
+
+ $r[] = $info;
+ }
+
+ return $r;
+ }
+
+ function escape($tmp_string) {
+ if($tmp_string == "")
+ $tmp_string = null;
+
+ if (is_string($tmp_string)) {
+ return "'" . str_replace("'", "`", $tmp_string) . "'";
+ } elseif (is_numeric($tmp_string)) {
+ return $tmp_string;
+ } elseif (is_null($tmp_string)) {
+ return "NULL";
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Sqlserver_Connection extends DBConnection {
+ var $_connection;
+ var $_database;
+
+ var $sql; //Object of sql template functions
+ function Sqlserver_Connection() {
+ parent::DBConnection();
+
+ $this->sql = new Sqlserver_Sql();
+
+ register_shutdown_function("close");
+ }
+
+ function connect($tmp_cfg,$tmp_position = 0) {
+ $microtime_ini = microtime();
+
+ $tmp_cfg["database_server"] = trim($tmp_cfg["database_server"][$tmp_position]);
+ $tmp_cfg["database_user"] = trim($tmp_cfg["database_user"][$tmp_position]);
+ $tmp_cfg["database_password"] = trim($tmp_cfg["database_password"][$tmp_position]);
+ $tmp_cfg["database_database"] = trim($tmp_cfg["database_database"][$tmp_position]);
+
+ if (!($this->_connection = @mssql_connect($tmp_cfg["database_server"], $tmp_cfg["database_user"], $tmp_cfg["database_password"]))) {
+ error(2, "Não foi possível estabelecer uma conexão com o servidor. <i>(" . mssql_error() . ")</i>", "Sqlserver_Connection", "connect");
+ }
+
+ if (!(@mssql_select_db($tmp_cfg["database_database"], $this->_connection))) {
+ error(2, "Não foi possível selecionar o banco '" . $tmp_cfg["database_database"] . "'.", "Sqlserver_Connection", "connect");
+ }
+
+ $this->_database = $tmp_cfg["database_database"];
+
+ parent::connect($tmp_cfg, $microtime_ini);
+ }
+
+ function execute($tmp_sql, $tmp_return_type = 1) {
+ $microtime_ini = microtime();
+
+ $r = new Sqlserver_RecordSet($tmp_sql, $this->_connection,$this->_database);
+
+ parent::execute($tmp_sql, $microtime_ini);
+
+ if ($r->error != "") {
+ error(2, "Erro de sql: " . $r->sql . " <i>(" . $r->error . ")</i>.", "Sqlserver_Connection", "execute");
+ }
+
+ if ($tmp_return_type == 1) {
+ //Object
+ return $r;
+ } elseif ($tmp_return_type == 2) {
+ //Resource
+ return $r->rs;
+ }
+ }
+
+ function close() {
+ mssql_close($this->_connection);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Sqlserver_RecordSet {
+ var $_connection;
+ var $_database;
+ var $rs;
+
+ var $sql;
+ var $error;
+
+ var $recordcount;
+ var $pagesize;
+ var $pagecount;
+ var $absolutepage;
+ var $BOF;
+ var $EOF;
+
+ var $fields;
+
+ function Sqlserver_RecordSet($tmp_sql, $tmp_connection,$tmp_database) {
+ $this->_connection = $tmp_connection;
+ $this->_database = $tmp_database;
+
+ $this->sql = $this->_formatSql($tmp_sql);
+
+ $this->pagesize = 0;
+ $this->pagecount = 1;
+ $this->absolutepage = 1;
+
+ $this->error = "";
+ $this->execute($tmp_sql);
+ }
+
+ function execute($tmp_sql) {
+ $this->BOF = true;
+ $this->EOF = true;
+
+ if ($tmp_sql == "") {
+ $this->error = "Sql vazia";
+
+ return false;
+ }
+
+ if (is_resource($this->_connection)) {
+ //Execute query
+ if (!($this->rs = @mssql_query($this->sql, $this->_connection))) {
+ @mssql_select_db($this->_database, $this->_connection);
+ if (!($this->rs = @mssql_query($this->sql, $this->_connection))) {
+ //$this->error = mssql_error();
+
+ return false;
+ }
+ }
+
+ //If sql is 'select'
+ if (strtolower(substr(trim($this->sql), 0, 6)) == "select") {
+ $this->recordcount = mssql_num_rows($this->rs);
+ $this->movenext(true);
+ } else {
+ $this->EOF = true;
+ }
+ }
+ }
+
+ function recordCount() {
+ return $this->recordcount;
+ }
+
+ function moveFirst() {
+ $this->execute($this->sql);
+ }
+
+ function moveNext($tmp_is_first = false) {
+ $this->BOF = $tmp_is_first;
+
+ if (!($this->fields = mssql_fetch_assoc($this->rs))) {
+ $this->EOF = true;
+ } else {
+ $this->EOF = false;
+ }
+ }
+
+ function fields($tmp_name) {
+ if (array_key_exists($tmp_name, $this->fields)) {
+ $r = $this->fields[$tmp_name];
+ } else {
+ $r = NULL;
+ }
+
+ return $r;
+ }
+
+ function page($tmp_page = 1) {
+ if ($tmp_page < 1) {
+ $tmp_page = 1;
+ }
+
+ $this->pagecount = $this->recordcount / $this->pagesize;
+ if ($this->pagecount > (int)($this->pagecount)) {
+ $this->pagecount = (int)($this->pagecount)+1;
+ }
+
+ $this->absolutepage = $tmp_page;
+
+ $count = 1;
+ while((!$this->EOF) && ($count < ($this->pagesize * $tmp_page-$this->pagesize))){
+ $this->moveNext();
+ $count++;
+ }
+
+ //$this->execute($this->sql);
+ }
+
+ function getInsertId() {
+ return mssql_insert_id();
+ }
+
+ //Private
+ function _formatSql($tmp_sql) {
+ $r = trim($tmp_sql);
+
+ $r = str_replace("day(", "dayofmonth(", $tmp_sql);
+ $r = str_replace("DAY(", "dayofmonth(", $tmp_sql);
+
+ return $r;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Sqlserver_Sql {
+ function Sqlserver_Sql() {
+
+ }
+
+ function getFieldsInfo($tmp_table) {
+ global $db;
+
+ $sql = "SHOW COLUMNS FROM " . $tmp_table . ";";
+ $rs = $db->execute($sql, 2);
+
+ while ($d = mssql_fetch_assoc($rs)) {
+ $info = array();
+
+ $info["name"] = $d["Field"];
+ $info["null_accept"] = ($d["Null"] == "YES");
+ $info["key_type"] = $d["Key"];
+ $info["default"] = $d["Default"];
+ $info["auto_increment"] = (strpos($d["Extra"], "auto_increment") !== false);
+ $info["type"] = $d["Type"];
+
+ $r[] = $info;
+ }
+
+ return $r;
+ }
+
+ function escape($tmp_string) {
+ if (is_string($tmp_string)) {
+ return "'" . str_replace("'", "`", $tmp_string) . "'";
+ } elseif (is_numeric($tmp_string)) {
+ return $tmp_string;
+ } elseif (is_null($tmp_string)) {
+ return "NULL";
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+function dateToMysql($tmp_date) {
+ $arr = explode("/", $tmp_date);
+
+ return $arr[2] . "-" . $arr[1] . "-" . $arr[0];
+}
+
+function dateFromMysql($tmp_date, $tmp_short_year = false, $tmp_separator = "/") {
+ $arr = explode("-", $tmp_date);
+
+ if ($tmp_short_year) {
+ $arr[0] = substr($arr[0], 2, 2);
+ }
+
+ return $arr[2] . $tmp_separator . $arr[1] . $tmp_separator . $arr[0];
+}
+
+function datetimeToMysql($tmp_date) {
+ $arr = explode(" ", $tmp_date);
+
+ if (sizeof($arr) > 1) {
+ $v = $arr[1];
+ } else {
+ $v = "";
+ }
+
+ return dateToMysql($arr[0]) . " " . $v;
+}
+
+function datetimeFromMysql($tmp_date, $tmp_short_year = false) {
+ $arr = explode(" ", $tmp_date);
+
+ if (sizeof($arr) > 1) {
+ $v = $arr[1];
+ } else {
+ $v = "";
+ }
+
+ return dateFromMysql($arr[0], $tmp_short_year) . " " . $arr[1];
+}
+
+function monthToBrName($tmp_month) {
+ $month = array();
+ $month[] = "Janeiro";
+ $month[] = "Fevereiro";
+ $month[] = "Março";
+ $month[] = "Abril";
+ $month[] = "Maio";
+ $month[] = "Junho";
+ $month[] = "Julho";
+ $month[] = "Agosto";
+ $month[] = "Setembro";
+ $month[] = "Outubro";
+ $month[] = "Novembro";
+ $month[] = "Dezembro";
+
+ return $month[((int)$tmp_month) - 1];
+}
+
+function weekDayBrName($tmp_week) {
+ $day = array();
+ $day[] = "Domingo";
+ $day[] = "Segunda-feira";
+ $day[] = "Terça-feira";
+ $day[] = "Quarta-feira";
+ $day[] = "Quinta-feira";
+ $day[] = "Sexta-feira";
+ $day[] = "Sábado";
+
+ return $day[$tmp_week];
+}
+
+function dateFromMysqlToMask($tmp_date, $tmp_mask) {
+ $t = strtotime($tmp_date);
+
+ return date($tmp_mask, $t);
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+function print_r2($tmp_var) {
+ echo "<pre>";
+ print_r($tmp_var);
+ echo "</pre>";
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+function getStates($tmp_key = "uf", $tmp_order_by = "nome asc") {
+ global $db;
+
+ $sql = "select " . $tmp_key . ", nome from estados order by " . $tmp_order_by;
+ $rs = $db->execute($sql);
+
+ $arr = array();
+ while (!$rs->EOF) {
+ $arr[$rs->fields($tmp_key)] = $rs->fields("nome");
+
+ $rs->moveNext();
+ }
+
+ return $arr;
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+function swf($src, $width, $height, $vars = '', $bg = '', $mode = 'wmode', $cssclass = '', $id = '', $not_ffv = false){
+ $html = '';
+
+ if (strpos($src,"?") > 0) {
+ $arr = explode("?",$src);
+
+ $src = $arr[0];
+ $vars = $arr[1];
+ }
+
+ $id = " " . $id;
+ $id = str_replace(" ", "",$id);
+
+ if ($not_ffv) {
+ $vars = formatFlashVars($vars);
+ }
+
+ $html = '<OBJECT class='. $cssclass .' codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0 height='. $height .' width='. $width .' align=middle classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 id="swf_' . $id . '">';
+ $html .= '<PARAM NAME="_cx" VALUE="18627"> ';
+ $html .= '<PARAM NAME="_cy" VALUE="1640"> ';
+ $html .= '<PARAM NAME="FlashVars" VALUE="' . $vars . '"> ';
+
+ $html .= '<PARAM NAME="Movie" VALUE="' . $src . '"> ';
+ $html .= '<PARAM NAME="Src" VALUE="' . $src . '"> ';
+
+ $html .= '<PARAM NAME="WMode" VALUE="'. $mode .'"> ';
+ $html .= '<PARAM NAME="Play" VALUE="-1"> ';
+ $html .= '<PARAM NAME="Loop" VALUE="-1"> ';
+ $html .= '<PARAM NAME="Quality" VALUE="High"> ';
+ $html .= '<PARAM NAME="SAlign" VALUE=""> ';
+ $html .= '<PARAM NAME="Menu" VALUE="-1"> ';
+ $html .= '<PARAM NAME="Base" VALUE=""> ';
+ $html .= '<PARAM NAME="allowFullScreen" VALUE="true"> ';
+
+ $html .= '<PARAM NAME="Scale" VALUE="ShowAll"> ';
+ $html .= '<PARAM NAME="DeviceFont" VALUE="0"> ';
+ $html .= '<PARAM NAME="EmbedMovie" VALUE="0"> ';
+ $html .= '<PARAM NAME="BGColor" VALUE="'. $bg .'"> ';
+ $html .= '<PARAM NAME="SWRemote" VALUE=""> ';
+ $html .= '<PARAM NAME="MovieData" VALUE=""> ';
+ $html .= '<PARAM NAME="SeamlessTabbing" VALUE="false"> ';
+ $html .= '<PARAM NAME="AllowScriptAccess" VALUE="always"> ';
+
+ $html .= ' <embed src="' . $src . '" FlashVars="' . $vars . '" quality="high" bgcolor="#'. $bg .'" width="'. $width .'" height="'. $height .'" name="swf_'. $id .'" align="middle" allowScriptAccess="always" SeamlessTabbing="false" allowFullScreen="true" wmode="'. $mode .'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" id="swf_' . $id . '" />';
+ $html .= '</OBJECT> ';
+
+ echo($html);
+}
+
+
+function formatFlashVars($tmp_string) {
+ $words = array();
+ $i = 0;
+ $control_string = "";
+
+ $words[0] = array("!","\"","#","$","'","\(","\)","\*","\+",",","\"",":",";","<",">","\?","@","\[","\]","\^","\`","\{","|","\}","~","\7f","","","","","
","","","","","","", "","","","","","","","", "","","","","","","","","¡","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","","®", "¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ý","þ","ÿ");
+ $words[1] = array("%21","%22","%23","%24","%27","%28","%29","*","%2B","%2C","%2F","%3A","%3B","%3C","%3E","%3F","%40","%5B","%5D","%5E","%60","%7B","%7C","%7D","%7E","%7F","%80","%82","%83","%84","%85","%86","%87","%88","%89","%8A","%8B","%8C","%8E","%91","%92","%93","%94","%95","%96","%97","%98","%99","%9A","%9B","%9C","%9E","%9F","%A1","%A2","%A3","%A4","%A5","%A6","%A7","%A8","%A9","%AA","%AB","%AC","%AD","%AE","%AF","%B0","%B1","%B2","%B3","%B4","%B5","%B6","%B7","%B8","%B9","%BA","%BB","%BC","%BD","%BE","%BF","%C0","%C1","%C2","%C3","%C4","%C5","%C6","%C7","%C8","%C9","%CA","%CB","%CC","%CD","%CE","%CF","%D0","%D1","%D2","%D3","%D4","%D5","%D6","%D7","%D8","%D9","%DA","%DB","%DC","%DD","%DE","%DF","%E0","%E1","%E2","%E3","%E4","%E5","%E6","%E7","%E8","%E9","%EA","%EB","%EC","%ED","%EE","%EF","%F0","%F1","%F2","%F3","%F4","%F5","%F6","%F7","%F8","%F9","%FA","%FB","%FC","%FD","%FE","%FF");
+
+ $tmp_string = str_replace($words[0],$words[1],$tmp_string);
+
+ return $tmp_string;
+}
+
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+function text_limit($tmp_text, $tmp_limit) {\r
+ $len = strlen($tmp_text);\r
+ \r
+ if ($len > $tmp_limit) {\r
+ $tmp_text = substr($tmp_text, 0, ($tmp_limit - 3)) . "...";\r
+ }\r
+ \r
+ return $tmp_text;\r
+}\r
+\r
+function formatHtmlField($tmp_html, $tmp_root = "") { \r
+ global $cfg;\r
+ \r
+ if ($tmp_root != "") {\r
+ $bkp = $cfg["root"];\r
+ $cfg["root"] = $tmp_root;\r
+ }\r
+ \r
+ $r = str_replace("#ROOT#", $cfg["root"], $tmp_html);\r
+ \r
+ if ($tmp_root != "") {\r
+ $cfg["root"] = $bkp;\r
+ }\r
+ \r
+ $r = formatSpecialCaracter($r,true);\r
+ \r
+ echo $r;\r
+}\r
+\r
+function formatFloat($tmp_value) {\r
+ return str_replace(".",",",((float)($tmp_value)));\r
+}\r
+\r
+function formatMoney($tmp_value) {\r
+ return number_format($tmp_value, 2, ",", ".");\r
+}\r
+\r
+function formatUrlComplete($url) {\r
+ if ((strpos($url,'http://') === false) && (strpos($url,'https://') === false) && (strpos($url,'ftp://') === false)) {\r
+ return 'http://' . $url;\r
+ } else {\r
+ return $url;\r
+ }\r
+ \r
+}\r
+\r
+function formatNameFile($name, $lower = true) {\r
+ $name = clearAcents($name,$lower);\r
+ \r
+ $name = str_replace(' ','_',$name);\r
+ \r
+ return $name;\r
+}\r
+\r
+function clearAcents($tmp_string, $lower = true) {\r
+ if ($lower) {\r
+ $tmp_string = strtolower($tmp_string);\r
+ } else {\r
+ $acents = "ÂÀÁÄÃÊÈÉËÎÍÌÏÔÕÒÓÖÛÙÚÜÇ";\r
+ $normal = "AAAAAEEEEIIIIOOOOOUUUUC";\r
+ \r
+ $tmp_string = strtr($tmp_string,$acents,$normal);\r
+ }\r
+ \r
+ $acents = "áàâãäªéèêëîíìïóòôõºúùûüç";\r
+ $normal = "aaaaaaeeeeiiiiooooouuuuc";\r
+ \r
+ $tmp_string = strtr($tmp_string,$acents,$normal);\r
+ \r
+ return $tmp_string;\r
+}\r
+\r
+function formatSpecialCaracter($string, $encode = true) {\r
+ $arr_caracter = array(\r
+ chr(145),chr(150),chr(148),chr(147),'×','÷','','','','','¢',chr(128),'','','','','¼','½','¾','©','®','ª','²','³','¹','¯','°','¡','£','º'\r
+ );\r
+ \r
+ $arr_code = array(\r
+ chr(96),chr(45),chr(34),chr(34),'×','÷','“','”','Œ','‡','¢','€','™','‰','ƒ','†','¼','½','¾','©','®','ª','²','³','¹','¯','°','¡','£','º'\r
+ );\r
+ \r
+ if ($encode) {\r
+ return str_replace($arr_caracter,$arr_code,$string);\r
+ } else {\r
+ return str_replace($arr_code,$arr_caracter,$string);\r
+ }\r
+}\r
+function scapeAp($tmp_string){\r
+ return str_replace("'", "`", $tmp_string);\r
+}\r
+function getNameFile($name){\r
+ $arr_aux = explode(".",$name);\r
+ \r
+ if (sizeof($arr_aux) > 1){\r
+ $extensao = $arr_aux[sizeof($arr_aux)-1];\r
+ } else {\r
+ $extensao = "";\r
+ }\r
+ \r
+ if (strlen($extensao) > 0){\r
+ $arquivo = substr($name,0, strlen($name)-(1+strlen($extensao)));\r
+ $arr_aux = array($arquivo,$extensao);\r
+ } else {\r
+ $arr_aux = array($name);\r
+ }\r
+ \r
+ return $arr_aux;\r
+}\r
+function se($arr){\r
+ if(sizeof($arr) > 0){\r
+ $str = "";\r
+ for($x=0;$x<sizeof($arr);$x++){\r
+ $str .= implode("$$$",$arr[$x]);\r
+ if(($x+1) < sizeof($arr))\r
+ $str .= "###";\r
+ }\r
+ return $str;\r
+ } else {\r
+ return "";\r
+ }\r
+}\r
+function unse($str){\r
+ if($str != ""){\r
+ $arr = array();\r
+ \r
+ $arr = explode("###",$str);\r
+ $arr2 = array();\r
+ \r
+ for($x=0;$x<sizeof($arr);$x++){\r
+ $arr2[$x] = explode("$$$",$arr[$x]);\r
+ }\r
+ \r
+ return $arr2;\r
+ } else {\r
+ return array();\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+function redir($tmp_url, $tmp_force_js = false, $tmp_frame = "", $tmp_execute_js = true) {
+ //If it`s redirect to a frame, only javascript can do this
+ if ($tmp_frame != "") {
+ echo "<script>window.open('" . $tmp_url . "', '" . $tmp_frame . "', '');</script>";
+ return "";
+ }
+
+ //Encode gets
+ $tmp = parse_url($tmp_url);
+
+ if (array_key_exists("query", $tmp)) {
+ $tmp2 = explode("&", $tmp["query"]);
+ $query = "";
+ foreach($tmp2 as $v) {
+ if ($query != "") {
+ $query .= "&";
+ }
+
+ $tmp3 = explode("=", $v);
+
+ $query .= $tmp3[0] . "=" . rawurlencode($tmp3[1]);
+ }
+ $tmp_url = str_replace($tmp["query"], $query, $tmp_url);
+ }
+
+ //Finaly, redirect
+ if ($tmp_force_js) {
+ echo "<script>document.location = '" . $tmp_url . "';</script>";
+ } else {
+ if (!(@header("location: " . $tmp_url))) {
+ if ($tmp_execute_js) {
+ echo "<script>document.location = '" . $tmp_url . "';</script>";
+ }
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+//Requires include default.js\r
+try { var _test_popup = __include_default; }\r
+catch(e) { alert("popup.js : Include '_system/js/default.js' é obrigatório"); }\r
+\r
+//Requires include ajax.js\r
+try { var _test_popup2 = __include_ajax; }\r
+catch(e) { alert("popup.js : Include '_system/js/ajax.js' é obrigatório"); }\r
+\r
+var __include_popup = true;\r
+\r
+var Popup_atual = false;\r
+\r
+function Popup(tmp_w, tmp_h) {\r
+ this.title = "";\r
+ this.bg_alpha = 60;\r
+ \r
+ this.width = tmp_w;\r
+ this.height = tmp_h;\r
+ \r
+ this.overflow = 'auto';\r
+ this.template = 1;\r
+ \r
+ this.onLoad = new Function();\r
+ \r
+ this._id_bg = "";\r
+ this._id_box = "";\r
+\r
+ this.open = function (tmp_url) {\r
+ var b = document.getElementsByTagName('body')[0];\r
+ var self = this;\r
+ \r
+ //Create ids\r
+ this._id_bg = this._genId();\r
+ this._id_box = this._genId();\r
+ \r
+ //Create bg\r
+ var bg = document.createElement('div');\r
+ bg.setAttribute('id', this._id_bg);\r
+ bg.setAttribute('style', 'position: absolute; top: 0; left: 0; z-index: 999; width: '+this.setWidthBox()+'; height: ' + this.setHeightBox() + '; background-color: #000000; -moz-opacity:0.' + this.bg_alpha + ';opacity:.' + this.bg_alpha + ';filter:alpha(opacity=' + this.bg_alpha + ');');\r
+ bg.style.position = 'absolute';\r
+ bg.style.left = "0px";\r
+ bg.style.top = "0px";\r
+ bg.style.width = this.setWidthBox();\r
+ bg.style.height = this.setHeightBox();\r
+ bg.style.background = '#000';\r
+ bg.style.filter = 'alpha(opacity=' + this.bg_alpha + ')';\r
+ bg.innerHTML = ' ';\r
+ b.appendChild(bg);\r
+\r
+ //Adjust positions\r
+ this.Popup_f = function (e, n) {\r
+ var pos = new WindowPosition();\r
+ var div = $$(self._id_bg);\r
+ var box = $$(self._id_box);\r
+ var box2 = $$(self._id_box + "_ext");\r
+ \r
+ if (div) {\r
+ var x = pos.x + (pos.w / 2) - ((self.width) / 2);\r
+ var y = pos.y + (pos.h / 2) - ((self.height) / 2);\r
+ \r
+ box.style.left = x + "px";\r
+ box.style.top = y + "px";\r
+ \r
+ if ((self.template == 1) || (self.template == 3)) {\r
+ box2.style.left = (x - 5) + "px";\r
+ box2.style.top = (y - 20) + "px";\r
+ }\r
+ \r
+ div.style.display = '';\r
+ box.style.display = '';\r
+ div.style.zIndex = 999;\r
+ \r
+ if ((n == undefined) && (window.Popup_f)) {\r
+ window.Popup_f(e, 1);\r
+ }\r
+ }\r
+ }\r
+ addEvent(window, "scroll resize", this.Popup_f);\r
+ window.Popup_f = this.Popup_f;\r
+ \r
+ //Create html\r
+ switch (this.template) {\r
+ default:\r
+ case 1:\r
+ var html = '<div id="' + this._id_box + '_ext" style="width: ' + (this.width+10) + 'px; height: ' + (this.height+25) + 'px; z-index: 1000; background: #FFFFFF; position: absolute; -moz-opacity:0.' + this.bg_alpha + ';opacity:.' + this.bg_alpha + ';filter:alpha(opacity=' + this.bg_alpha + ');">';\r
+ html += '<div style="width: ' + (this.width + 5) + 'px; margin-top: 3px; text-align: right; z-index: 1005;"><a href="javascript: Popup_atual.close();" style="color: #666; text-decoration: none; font-family: Verdana; font-size: 10px;">Fechar</a></div></div>';\r
+ html += '<div id="' + this._id_box + '" style="width: ' + (this.width) + 'px; height: ' + (this.height) + 'px; background: #FFFFFF; overflow: ' + this.overflow + '; position: absolute; z-index: 1005;">';\r
+ html += '<div style="margin-top: 45%; font-family: Verdana; font-size: 10px; color: #CCC;"><center>Carregando janela</center></div>';\r
+ html += '</div>';\r
+ \r
+ tn = document.createElement('div');\r
+ tn.innerHTML = html;\r
+ b.appendChild(tn);\r
+ \r
+ var box = $$(this._id_box);\r
+ box.style.width = this.width + 'px';\r
+ box.style.height = this.height + 'px';\r
+ box.style.overflow = this.overflow;\r
+ \r
+ var box2 = $$(this._id_box + "_ext");\r
+ box2.style.filter = 'alpha(opacity=' + this.bg_alpha + ')';\r
+ box2.style.width = (this.width + 10) + 'px';\r
+ box2.style.height = (this.height + 25) + 'px';\r
+ \r
+ break;\r
+ case 2:\r
+ var html = '<div id="' + this._id_box + '" style="width: ' + (this.width) + 'px; height: ' + (this.height) + 'px; background: #FFFFFF; overflow: ' + this.overflow + '; position: absolute; z-index: 1001;">';\r
+ html += '<div style="margin-top: 50%; font-family: Verdana; font-size: 10px; color: #CCC;"><center>Carregando janela</center></div>';\r
+ html += '</div>';\r
+ \r
+ tn = document.createElement('div');\r
+ tn.innerHTML = html;\r
+ b.appendChild(tn);\r
+ \r
+ var box = $$(this._id_box);\r
+ box.style.width = this.width + 'px';\r
+ box.style.height = this.height + 'px';\r
+ box.style.overflow = this.overflow;\r
+ \r
+ break;\r
+ case 3:\r
+ var html = '<div id="' + this._id_box + '_ext" style="width: ' + (this.width+10) + 'px; height: ' + (this.height+25) + 'px; z-index: 1000; background: #FFFFFF; position: absolute;">';\r
+ html += '<div style="width: ' + (this.width-5) + 'px; margin-top:8px; text-align: right; z-index: 1005;"><a href="javascript: Popup_atual.close();"><img src="../../../_system/img/bt-xfechar.gif"></a></div></div>';\r
+ html += '<div id="' + this._id_box + '" style="width: ' + (this.width) + 'px; height: ' + (this.height) + 'px; background: #FFFFFF; overflow: ' + this.overflow + '; position: absolute; z-index: 1005;">';\r
+ html += '<div style="margin-top: 45%; font-family: Verdana; font-size: 10px; color: #CCC;"><center>Carregando janela</center></div>';\r
+ html += '</div>';\r
+ \r
+ tn = document.createElement('div');\r
+ tn.innerHTML = html;\r
+ b.appendChild(tn);\r
+ \r
+ var box = $$(this._id_box);\r
+ box.style.width = this.width + 'px';\r
+ box.style.height = this.height + 'px';\r
+ box.style.overflow = this.overflow;\r
+ \r
+ var box2 = $$(this._id_box + "_ext");\r
+ box2.style.filter = 'alpha(opacity=' + this.bg_alpha + ')';\r
+ box2.style.width = (this.width + 10) + 'px';\r
+ box2.style.height = (this.height + 25) + 'px';\r
+ \r
+ break;\r
+ }\r
+ \r
+ this.Popup_f();\r
+ setTimeout(Popup_f, 50);\r
+ setTimeout(Popup_f, 100);\r
+ setTimeout(Popup_f, 150);\r
+ setTimeout(Popup_f, 300);\r
+ setTimeout(Popup_f, 500);\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ $$(self._id_box).innerHTML = this.html;\r
+ \r
+ this.runJS(this.html);\r
+ \r
+ if (self.onLoad) {\r
+ self.onLoad();\r
+ }\r
+ }\r
+ a.get(tmp_url);\r
+ \r
+ Popup_atual = this;\r
+ }\r
+ \r
+ this.close = function () {\r
+ var box = $$(this._id_bg);\r
+ var div = $$(this._id_box);\r
+ var div2 = $$(this._id_box + "_ext");\r
+ var b = document.getElementsByTagName('body')[0];\r
+ \r
+ if (div) { removeElement(div); }\r
+ if (div2) { removeElement(div2); }\r
+ if (box) { removeElement(box); }\r
+ \r
+ removeEvent(window, "scroll", this.Popup_f);\r
+ removeEvent(window, "resize", this.Popup_f);\r
+ window.Popup_f = undefined;\r
+ }\r
+ \r
+ this._genId = function () {\r
+ var id = "popup" + new String(Math.round(Math.random() * 1000));\r
+ \r
+ if ($$(id)) {\r
+ id = this._genId();\r
+ }\r
+ \r
+ return id;\r
+ }\r
+ \r
+ this.setHeightBox = function() {\r
+ var heightBody = document.body.clientHeight;\r
+ var heightScroll = document.body.scrollHeight;\r
+ \r
+ if (heightBody > heightScroll) {\r
+ return "100%";\r
+ } else {\r
+ return heightScroll+'px';\r
+ }\r
+ }\r
+ \r
+ this.setWidthBox = function() {\r
+ var widthBody = document.body.clientWidth;\r
+ var widthScroll = document.body.scrollWidth;\r
+ \r
+ if (widthBody > widthScroll) {\r
+ return "100%";\r
+ } else {\r
+ return widthScroll+'px';\r
+ }\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+Ajax handler\r
+by Ramon Fritsch (www.ramonfritsch.com)\r
+\r
+Ex.:\r
+var a = new Ajax();\r
+a.onLoad = function () {\r
+ alert(this.html);\r
+}\r
+a.get("url.php");\r
+*/\r
+\r
+\r
+//Requires include default.js\r
+try { var _test_ajax = __include_default; } \r
+catch(e) { alert("ajax.js : Include '_system/js/default.js' é obrigatório"); }\r
+\r
+var __include_ajax = true;\r
+\r
+//class Ajax\r
+function Ajax() {\r
+ var obj;\r
+ \r
+ var unique = true;\r
+ \r
+ var html;\r
+ var xml;\r
+ \r
+ var response_type = "html";\r
+ \r
+ var onLoad = new Function();\r
+ var onPreLoad = new Function();\r
+ \r
+ this.createObject = function () {\r
+ var parent = this;\r
+ \r
+ obj = this.getAjaxObj();\r
+ obj.onreadystatechange = function() {\r
+ if(obj.readyState == 4) {\r
+ var arr;\r
+ \r
+ //xml\r
+ if (response_type == "xml") {\r
+ //need test\r
+ if (obj.responseXml != undefined) {\r
+ try {\r
+ parent.xml = obj.responseXml;\r
+ } catch (e) { }\r
+ } else {\r
+ try {\r
+ parent.xml = parent.parseXML(obj.responseText); \r
+ } catch (e) { }\r
+ }\r
+ } else { \r
+ //html\r
+ parent.html = obj.responseText;\r
+ }\r
+ \r
+ obj = null;\r
+ \r
+ parent.onLoad();\r
+ \r
+ Ajax_unique = false;\r
+ }\r
+ }\r
+ }\r
+ \r
+ this.get = function (tmp_url) {\r
+ if (tmp_url == '') {\r
+ alert("Ajax.get() : Url vazia");\r
+ \r
+ return;\r
+ }\r
+ \r
+ if (this.isFree()) {\r
+ this.createObject();\r
+ \r
+ if (typeof(this.onPreLoad) == "function") {\r
+ this.onPreLoad();\r
+ }\r
+ \r
+ obj.open('GET', tmp_url);\r
+ obj.setRequestHeader("Content-type", "text/html;charset=iso-8859-1");\r
+ obj.setRequestHeader("Connection", "close");\r
+ obj.send(null);\r
+ }\r
+ }\r
+ \r
+ this.post = function (tmp_url, tmp_parameters, tmp_content_type) {\r
+ if (tmp_url == '') {\r
+ alert("Erro - Ajax.post() : Url vazia");\r
+ \r
+ return;\r
+ }\r
+ \r
+ if (tmp_content_type == undefined) {\r
+ tmp_content_type = "application/x-www-form-urlencoded";\r
+ }\r
+ \r
+ if (this.isFree()) {\r
+ this.createObject();\r
+ \r
+ if (typeof(this.onPreLoad) == "function") {\r
+ this.onPreLoad();\r
+ }\r
+ \r
+ obj.open('POST', tmp_url);\r
+ obj.setRequestHeader("Content-type", tmp_content_type);\r
+ obj.setRequestHeader("Content-length", tmp_parameters.length);\r
+ obj.setRequestHeader("Connection", "close");\r
+ obj.send(tmp_parameters);\r
+ }\r
+ }\r
+ \r
+ this.sendForm = function(tmp_id) {\r
+ var p = "";\r
+ var field;\r
+ var form = $$(tmp_id);\r
+ \r
+ for (i = 0; i < form.length; i++) {\r
+ field = form.elements[i];\r
+ \r
+ if (field.type == 'checkbox' || field.type == 'radio') {\r
+ if (field.checked) {\r
+ p += '&' + field.name + '=' + this.formatString(field.value);\r
+ }\r
+ } else {\r
+ p += '&' + field.name + '=' + this.formatString(field.value);\r
+ }\r
+ }\r
+ \r
+ this.post(form.action, p);\r
+ }\r
+ \r
+ //Unique\r
+ this.isFree = function () { \r
+ var r = (!(this.unique && Ajax_unique)) || !this.unique;\r
+ \r
+ if (r) {\r
+ Ajax_unique = true; \r
+ }\r
+ \r
+ return r;\r
+ }\r
+ \r
+ this.setUnique = function (tmp_valor) {\r
+ this.unique = tmp_valor;\r
+ }\r
+ \r
+ //Funções auxiliares\r
+ this.getAjaxObj = function () {\r
+ var xmlhttp;\r
+ try {\r
+ xmlhttp = new XMLHttpRequest();\r
+ } catch (e) {\r
+ try {\r
+ xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");\r
+ } catch (ex) {\r
+ try {\r
+ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");\r
+ } catch(exc) {\r
+ alert("Erro - Ajax.getAjaxObj() : " + exc.error);\r
+ }\r
+ }\r
+ }\r
+ return xmlhttp?xmlhttp:false;\r
+ }\r
+ \r
+ this.parseXML = function (tmp_string) {\r
+ var xml;\r
+ \r
+ try {\r
+ xml = new ActiveXObject("Microsoft.XMLDOM");\r
+ xml.async="false";\r
+ xml.loadXML(tmp_string);\r
+ } catch(e) {\r
+ try {\r
+ Parser = new DOMParser();\r
+ xml = Parser.parseFromString(tmp_string,"text/xml");\r
+ } catch(ex) {\r
+ alert("Erro - Ajax.parseXML('" + tmp_string.substr(0, 16) + "...') : " + ex.message);\r
+ }\r
+ }\r
+ \r
+ return xml;\r
+ }\r
+ \r
+ this.runJS = function (tmp_html) {\r
+ var el = document.createElement('div');\r
+ el.innerHTML = '<div style="display: none">content</div>' + tmp_html; //Ie sucx!\r
+ \r
+ var scripts = el.getElementsByTagName('script');\r
+ var js_exec = "";\r
+ var total_eval = scripts.length;\r
+ var i_eval = 0;\r
+ \r
+ for (; i_eval < total_eval; i_eval++) {\r
+ if (isIE) {\r
+ js_exec = scripts[i_eval].text;\r
+ } else if (isMoz) {\r
+ js_exec = scripts[i_eval].textContent;\r
+ } else {\r
+ js_exec = scripts[i_eval].innerHTML;\r
+ }\r
+ \r
+ try {\r
+ eval(js_exec);\r
+ } catch(e) { \r
+ alert("Erro - Ajax.runJS('" + tmp_html.substr(0, 16) + "...') : " + e.message);\r
+ }\r
+ }\r
+ }\r
+ \r
+ this.formatString = function (tmp_string) {\r
+ var words = new Array();\r
+ var i = 0;\r
+ var new_string = "";\r
+ var control_string = "";\r
+ \r
+ words[0] = new Array("!","\"","#","$","&","'","\(","\)","\*","\+",",","\"",":",";","<","=",">","\?","@","\[","\]","\^","\`","\{","|","\}","~","\7f","","","","","
","","","","","","", "","","","","","","","", "","","","","","","","","¡","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","","®", "¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ý","þ","ÿ");\r
+ words[1] = new Array("%21","%22","%23","%24","%26","%27","%28","%29","*","%2B","%2C","%2F","%3A","%3B","%3C","%3D","%3E","%3F","%40","%5B","%5D","%5E","%60","%7B","%7C","%7D","%7E","%7F","%80","%82","%83","%84","%85","%86","%87","%88","%89","%8A","%8B","%8C","%8E","%91","%92","%93","%94","%95","%96","%97","%98","%99","%9A","%9B","%9C","%9E","%9F","%A1","%A2","%A3","%A4","%A5","%A6","%A7","%A8","%A9","%AA","%AB","%AC","%AD","%AE","%AF","%B0","%B1","%B2","%B3","%B4","%B5","%B6","%B7","%B8","%B9","%BA","%BB","%BC","%BD","%BE","%BF","%C0","%C1","%C2","%C3","%C4","%C5","%C6","%C7","%C8","%C9","%CA","%CB","%CC","%CD","%CE","%CF","%D0","%D1","%D2","%D3","%D4","%D5","%D6","%D7","%D8","%D9","%DA","%DB","%DC","%DD","%DE","%DF","%E0","%E1","%E2","%E3","%E4","%E5","%E6","%E7","%E8","%E9","%EA","%EB","%EC","%ED","%EE","%EF","%F0","%F1","%F2","%F3","%F4","%F5","%F6","%F7","%F8","%F9","%FA","%FB","%FC","%FD","%FE","%FF");\r
+\r
+ for (; i < words[0].length; i++) {\r
+ do {\r
+ control_string = tmp_string;\r
+ tmp_string = tmp_string.replace(words[0][i], words[1][i]);\r
+ } while (control_string != tmp_string);\r
+ }\r
+ \r
+ return tmp_string; \r
+ }\r
+}\r
+var Ajax_unique = false;
\ No newline at end of file
--- /dev/null
+var __include_default = true;\r
+\r
+//Browser detector\r
+var isIE = false, isMoz = false, isSaf = false;\r
+(function () {\r
+ if ((navigator.userAgent.indexOf('Safari') != -1)) { isSaf = true; } \r
+ else if ((navigator.appName == 'Netscape')) { isMoz = true; } \r
+ else { isIE = true; } \r
+}());\r
+\r
+//Get element(s) by id, #id or .classname\r
+function $$(tmp_query, tmp_root) {\r
+ if (tmp_query.indexOf('.') > -1) {\r
+ var r = [], elms, i = 0, i2 = 0, r2;\r
+ \r
+ tmp_query = tmp_query.substr(1, tmp_query.length - 1);\r
+ \r
+ tmp_root = (tmp_root != null) ? tmp_root : document;\r
+ elms = (tmp_root.all) ? tmp_root.all : tmp_root.getElementsByTagName('*');\r
+ \r
+ for (; i < elms.length; i++) {\r
+ if (tmp_query == elms[i].className) {\r
+ r.push(elms[i]);\r
+ }\r
+ }\r
+ \r
+ return r;\r
+ } else if (tmp_query.indexOf('#') > -1) {\r
+ var r = [], elms, i = 0, i2 = 0, r2;\r
+ \r
+ tmp_query = tmp_query.substr(1, tmp_query.length - 1);\r
+ \r
+ tmp_root = (tmp_root != null) ? tmp_root : document;\r
+ elms = (tmp_root.all) ? tmp_root.all : tmp_root.getElementsByTagName('*');\r
+ \r
+ for (; i < elms.length; i++) {\r
+ if (tmp_query == elms[i].id) {\r
+ r.push(elms[i]);\r
+ }\r
+ }\r
+ \r
+ return r;\r
+ } else {\r
+ if (document.getElementById(tmp_query)) { \r
+ return document.getElementById(tmp_query); \r
+ } else {\r
+ return null;\r
+ }\r
+ }\r
+}\r
+\r
+//Nothing function for href property of tag <a>\r
+function nothing_func() { }\r
+\r
+//Alert describe object\r
+function alert_r(tmp_obj, tmp_alert) {\r
+ var msg = '';\r
+ \r
+ for (var v in tmp_obj) {\r
+ msg += ' ' + v + ' = \'' + (new String(tmp_obj[v])) + '\'\n';\r
+ }\r
+ \r
+ if (tmp_alert == true) {\r
+ alert('Object (' + tmp_obj + '):\n' + msg);\r
+ } else {\r
+ var div = document.createElement('div');\r
+ div.id = 'alert_r_' + Math.round(Math.random() * 99999);\r
+ div.style.position = 'absolute';\r
+ div.style.top = '0px';\r
+ div.style.left = '0px';\r
+ div.style.background = '#EEEEEE';\r
+ div.innerHTML = '<pre style="font-family: Verdana; font-size: 10px;">' + msg + '</pre>';\r
+ \r
+ document.getElementsByTagName('body')[0].appendChild(div);\r
+ \r
+ addEvent(div, 'click', function () { removeElement(this); });\r
+ }\r
+}\r
+\r
+//Add tmp_function event for tmp_object\r
+function addEvent(tmp_obj, tmp_event, tmp_function) {\r
+ var f = function (e) { \r
+ tmp_function.apply(tmp_obj, [e || event]); \r
+ };\r
+ \r
+ if (typeof tmp_event == "string") {\r
+ if (tmp_event.indexOf(" ") > -1) {\r
+ var arr = tmp_event.split(" ");\r
+ for (var i = 0; i < arr.length; i++) {\r
+ addEvent(tmp_obj, arr[i], tmp_function); \r
+ }\r
+ \r
+ return true;\r
+ }\r
+ } else if (typeof tmp_event == "object") {\r
+ for (var i = 0; i < tmp_event.length; i++) {\r
+ addEvent(tmp_obj, tmp_event[i], tmp_function); \r
+ }\r
+ \r
+ return true;\r
+ }\r
+ \r
+ if (tmp_obj) {\r
+ try {\r
+ tmp_obj.addEventListener(tmp_event, f, false);\r
+ } catch (e) {\r
+ try {\r
+ tmp_obj.attachEvent("on" + tmp_event, f);\r
+ } catch (e2) {\r
+ return false;\r
+ }\r
+ }\r
+ \r
+ return true;\r
+ } else {\r
+ return false;\r
+ }\r
+}\r
+\r
+function removeEvent(tmp_obj, tmp_type, tmp_function) {\r
+ if (isIE) {\r
+ tmp_obj.detachEvent("on" + tmp_type, tmp_function);\r
+ } else {\r
+ tmp_obj.removeEventListener(tmp_type, tmp_function, false);\r
+ }\r
+}\r
+\r
+function removeElement(tmp_obj) {\r
+ tmp_obj.parentNode.removeChild(tmp_obj); \r
+}\r
+\r
+function redir(tmp_pagina) {\r
+ document.location = tmp_pagina;\r
+}\r
+\r
+function openPopup(tmp_url, tmp_w, tmp_h, tmp_name) {\r
+ var x = (screen.width - tmp_w) / 2;\r
+ var y = (screen.height - tmp_h) / 2;\r
+ \r
+ if (!tmp_name) { \r
+ var rnd = Math.round(Math.random() * 99999);\r
+ tmp_name = "nova_janela" + rnd;\r
+ }\r
+\r
+ var v = window.open(tmp_url, tmp_name,'height=' + tmp_h + ', width=' + tmp_w + ', left=' + x + ', top=' + y);\r
+}\r
+\r
+//Prototypes\r
+String.prototype.trim = function () {\r
+ var r = /\s*((\S+\s*)*)/g;\r
+ var r2 = /((\s*\S+)*)\s*/g;\r
+ \r
+ return this.replace(r, "$1").replace(r2, "$1");\r
+}\r
+\r
+Function.prototype.bind = function(tmp_object) {\r
+ var tmp_method = this;\r
+ \r
+ return function() { return tmp_method.apply(tmp_object, arguments); }\r
+}\r
+\r
+Array.prototype.each = function (tmp_func) {\r
+ var i = 0;\r
+ var length = this.length;\r
+ \r
+ var ev = "tmp_func(i, this[i])";\r
+ \r
+ for (; i < length; i++) {\r
+ eval(ev);\r
+ }\r
+}\r
+\r
+if (!Array.prototype.indexOf) Array.prototype.indexOf = function(tmp_item, tmp_i) {\r
+ var length = this.length;\r
+ \r
+ tmp_i || (tmp_i = 0);\r
+ if (tmp_i < 0) tmp_i = length + tmp_i;\r
+ \r
+ for (; tmp_i < length; tmp_i++) { if (this[tmp_i] === tmp_item) return tmp_i; }\r
+ \r
+ return -1;\r
+}\r
+\r
+Array.prototype.remove = function (tmp_itens) {\r
+ if (typeof(tmp_itens) != "object") {\r
+ tmp_itens = [tmp_itens];\r
+ }\r
+ \r
+ var i = 0; i2 = 0;\r
+ var new_array = [];\r
+ \r
+ for (; i < this.length; i++) {\r
+ if (tmp_itens.indexOf(this[i]) == -1) {\r
+ new_array[i2] = this[i];\r
+ i2++;\r
+ }\r
+ }\r
+ \r
+ return new_array;\r
+}\r
+\r
+\r
+//Window Position class\r
+function WindowPosition() { \r
+ this.x = 0;\r
+ this.y = 0;\r
+ this.w = 0;\r
+ this.h = 0;\r
+ \r
+ if (typeof(window.pageYOffset) == 'number') {\r
+ this.x = window.pageXOffset;\r
+ this.y = window.pageYOffset;\r
+ } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {\r
+ this.x = document.body.scrollLeft;\r
+ this.y = document.body.scrollTop;\r
+ } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { \r
+ this.x = document.documentElement.scrollLeft;\r
+ this.y = document.documentElement.scrollTop;\r
+ }\r
+ \r
+ if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {\r
+ // Se o DOCTYPE foi retirado da pagina, as 2 linhas de cima devem ser comentadas e deixar as duas abaixa descomentada\r
+ // Caso contrario, descomentar as 2 de cima e comentar as 2 linhas de baixo\r
+ \r
+// this.w = document.documentElement.clientWidth;\r
+// this.h = document.documentElement.clientHeight;\r
+ this.w = document.body.clientWidth;\r
+ this.h = document.body.clientHeight;\r
+ } else if (typeof(window.innerWidth) == 'number') {\r
+ this.w = window.innerWidth;\r
+ this.h = window.innerHeight;\r
+ } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {\r
+ this.w = document.body.clientWidth;\r
+ this.h = document.body.clientHeight;\r
+ }\r
+}\r
+\r
+\r
--- /dev/null
+/*\r
+Form validation\r
+by Ramon Fritsch (www.ramonfritsch.com)\r
+\r
+Types: TXT, NUM, CEP, TEL, PW1, PW2, DAT, HOR, EML, CPF, CMB, RDO, CNP, DIN, FLO, INT\r
+Required: 1 = true, 0 = false\r
+\r
+Sintax: (Label)[#Index]_(Type)(Required)[_(Minchars)]\r
+\r
+Ex.:\r
+id="CPF_CPF1" //Simple\r
+id="Nome#2_TXT1_255" //Complex\r
+*/\r
+\r
+\r
+//Requires include default.js\r
+try { var _test_form = __include_default; }\r
+catch(e) { alert("form.js : Include '_system/js/default.js' é obrigatório"); }\r
+\r
+var __include_form = true;\r
+\r
+//class Form\r
+function Form() {\r
+ this.linguage = 1; //1 => port\r
+ \r
+ this.send = function (tmp_id, tmp_return) {\r
+ if (tmp_return == undefined) {\r
+ tmp_return = false;\r
+ }\r
+ \r
+ var i = 0;\r
+ var error = false;\r
+ var form = $$(tmp_id);\r
+ var valid_numbers = '0123456789,.';\r
+ var valid_telphone = '0123456789. ()';\r
+ var valid_cep = '0123456789-';\r
+ var tmp_pass = '';\r
+ var param_id;\r
+ var param_type;\r
+ var param_name;\r
+ var param_value;\r
+ var obj;\r
+ var r_parse;\r
+ \r
+ var label;\r
+ var type;\r
+ var required;\r
+ var minchars;\r
+ \r
+ \r
+ form.onsubmit = function () { return false; }\r
+ \r
+ \r
+ //elements loop\r
+ while (form.elements[i]) {\r
+ obj = form.elements[i];\r
+ \r
+ param_id = obj.id;\r
+ param_type = obj.type;\r
+ param_name = obj.name;\r
+ param_value = obj.value;\r
+ param_testDV = false;\r
+ \r
+ if(obj.attributes["testDV"]){\r
+ if(obj.attributes["testDV"].value != "")\r
+ param_testDV = true;\r
+ }\r
+ \r
+ r_parse = this._parseId(param_id);\r
+ \r
+ label = r_parse[0];\r
+ type = r_parse[1];\r
+ required = r_parse[2];\r
+ minchars = r_parse[3];\r
+ \r
+ switch (type) {\r
+ case "FIL":\r
+ if ((required) && (!param_value)) {\r
+ this._showMessage(0, label);\r
+ obj.focus();\r
+ return false;\r
+ } else if((required) || (param_value)) {\r
+ arr_types = Array();\r
+ if (obj.accept != ""){\r
+ arr_types = obj.accept.split(",");\r
+ arr_file = param_value.split(".");\r
+ valid = false;\r
+ if (arr_file.length > 1){\r
+ for (cont = 0; cont<arr_types.length;cont++) {\r
+ if(arr_types[cont] == arr_file[1]){\r
+ valid = true;\r
+ }\r
+ }\r
+ }\r
+ if (!valid) {\r
+ obj.value = "";\r
+ this._showMessage(12, label, arr_types);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ }\r
+ }\r
+ break; \r
+ case "TXT":\r
+ case "NUM":\r
+ case "DIN":\r
+ case "FLO":\r
+ case "TEL":\r
+ case "CEP":\r
+ case "INT":\r
+ if (((required) && (!param_value)) || ((required) && ((param_testDV) && (param_value == obj.defaultValue)))) {\r
+ this._showMessage(0, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break;\r
+ case "PW1":\r
+ if ((required) && (!param_value)) {\r
+ this._showMessage(0, label);\r
+ obj.focus();\r
+ return false;\r
+ } else {\r
+ tmp_pass = param_value; \r
+ }\r
+ \r
+ break;\r
+ case "PW2":\r
+ if (param_value != tmp_pass) {\r
+ this._showMessage(3); \r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break;\r
+ case "DAT":\r
+ if (param_value) {\r
+ var day = param_value.split('/')[0]*1;\r
+ var month = param_value.split('/')[1]*1;\r
+ var year = param_value.split('/')[2]*1;\r
+ \r
+ if ((param_value.length == 10) && (param_value.charAt(2) == '/') && (param_value.charAt(5) == '/') && (day <= 31) && (day > 0) && (month <= 12) && (month > 0) && (year >= 1800)) {\r
+ //Valid Date\r
+ } else {\r
+ this._showMessage(4, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ } else if (required) {\r
+ this._showMessage(0, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break;\r
+ case "HOR":\r
+ if (param_value) {\r
+ if ((param_value.length == 5) && (param_value.charAt(2) == ':') && (param_value.split(':')[0]*1 <= 24) && (param_value.split(':')[1]*1 <= 59)) {\r
+ //Valid Hour\r
+ } else {\r
+ this._showMessage(8, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ } else if (required) {\r
+ this._showMessage(0, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break; \r
+ case "HO2":\r
+ if (param_value) {\r
+ if ((param_value.length == 8) && (param_value.charAt(2) == ':') && (param_value.charAt(5) == ':') && (param_value.split(':')[0]*1 <= 24) && (param_value.split(':')[1]*1 <= 59) && (param_value.split(':')[2]*1 <= 59)) {\r
+ //Valid Hour\r
+ } else {\r
+ this._showMessage(10, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ } else if (required) {\r
+ this._showMessage(0, label); \r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break;\r
+ case "EML":\r
+ if (param_value) {\r
+ if ((param_value.indexOf(".") > 0) && (param_value.indexOf("@") > 0) && (param_value.length > 3) && (param_value != "@.")) {\r
+ //Valid e-mail\r
+ } else {\r
+ this._showMessage(5, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ } else if (required) {\r
+ this._showMessage(0, label); \r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break;\r
+ case "CPF":\r
+ if (param_value) {\r
+ var p1 = param_value.substring(0,3); \r
+ var p2 = param_value.substring(4,7);\r
+ var p3 = param_value.substring(8,11);\r
+ var p4 = param_value.substring(12,14);\r
+ var cpf = p1 + p2 + p3 + p4;\r
+ var cpf_verif = cpf.substring(9,11); \r
+ var c = 0;\r
+ var position=1;\r
+ \r
+ for (cont=0;cont<9;cont++) {\r
+ c+=cpf.substring(cont,position)*(10-cont);\r
+ position++;\r
+ }\r
+ \r
+ c = (11-(c % 11));\r
+ if (c > 9) { c=0; } \r
+ if (cpf_verif.substring(0,1) != c) {\r
+ this._showMessage(6);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ c *= 2;\r
+ position = 1;\r
+ for (cont=0; cont<9; cont++) {\r
+ c+=cpf.substring(cont,position)*(11-cont);\r
+ position++;\r
+ }\r
+ \r
+ c = (11-(c % 11));\r
+ if (c > 9) { c = 0; }\r
+ \r
+ if (cpf_verif.substring(1,2) != c) {\r
+ this._showMessage(6);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ if ((cpf == '99999999999') || (cpf == '88888888888') || (cpf == '77777777777') || (cpf == '66666666666') || (cpf == '55555555555') || (cpf == '44444444444') || (cpf == '33333333333') || (cpf == '22222222222') || (cpf == '11111111111')) {\r
+ this._showMessage(6);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ } else if (required) {\r
+ this._showMessage(0, label); \r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break;\r
+ \r
+ case "CNP":\r
+ if (param_value) {\r
+ var p1 = param_value.substring(0,2); \r
+ var p2 = param_value.substring(3,6);\r
+ var p3 = param_value.substring(7,10);\r
+ var p4 = param_value.substring(11,15);\r
+ var digitoverificador = param_value.substring(16,18);\r
+ var cnpj = p1 + p2 + p3 + p4;\r
+ var position=1;\r
+ var arr_multiplicadores1 = new Array(5,4,3,2,9,8,7,6,5,4,3,2);\r
+ var arr_multiplicadores2 = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);\r
+ var soma = 0;\r
+ var divisao = 0;\r
+ var resto = 0;\r
+ var verificador1;\r
+ var verificador2;\r
+ \r
+ //---------- PRIMEIRO DIGITO -----------------\r
+ for (cont=0;cont<12;cont++) {\r
+ soma += (cnpj.substring(cont,position)*(arr_multiplicadores1[cont]));\r
+ position++;\r
+ }\r
+ \r
+ divisao = parseInt(soma / 11);\r
+ resto = soma % 11;\r
+ \r
+ if (resto > 1) {\r
+ verificador1 = 11 - resto\r
+ } else {\r
+ verificador1 = 0;\r
+ }\r
+ //---------- / PRIMEIRO DIGITO -----------------\r
+ \r
+ //---------- SEGUNDO DIGITO -----------------\r
+ soma = 0;\r
+ position = 1;\r
+ for (cont=0;cont<12;cont++) {\r
+ soma += (cnpj.substring(cont,position)*(arr_multiplicadores2[cont]));\r
+ position++;\r
+ }\r
+ \r
+ soma += verificador1 * arr_multiplicadores2[12];\r
+ \r
+ divisao = parseInt(soma / 11);\r
+ resto = soma % 11;\r
+ \r
+ if (resto > 1) {\r
+ verificador2 = 11 - resto\r
+ } else {\r
+ verificador2 = 0;\r
+ }\r
+ //---------- SEGUNDO DIGITO -----------------\r
+ \r
+ if (digitoverificador != (verificador1+''+verificador2)) {\r
+ this._showMessage(11);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ } else if (required) {\r
+ this._showMessage(0, label); \r
+ obj.focus();\r
+ return false;\r
+ }\r
+ break;\r
+ case "CMB":\r
+ if (((obj.selectedIndex == 0) || (obj.selectedIndex == 1)) && (required)) {\r
+ this._showMessage(7, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break;\r
+ case "RDO":\r
+ var ok = 0;\r
+ var el = document.getElementsByName(param_name);\r
+ \r
+ for (i_el=0; i_el < el.length; i_el++) {\r
+ var tmp = el[i_el].checked;\r
+ if (tmp) { ok = 1; }\r
+ }\r
+ \r
+ if ((required) && (ok == 0)) {\r
+ this._showMessage(7, label);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ break;\r
+ } \r
+ \r
+ //filter min chars\r
+ if ((minchars > 0) && (param_value.length < minchars) && (required)) {\r
+ this._showMessage(9, label, minchars);\r
+ obj.focus();\r
+ return false;\r
+ }\r
+ \r
+ i++;\r
+ }\r
+ \r
+ if (tmp_return) {\r
+ return true; \r
+ } else {\r
+ form.submit(); \r
+ }\r
+ }\r
+ \r
+ this.maskFields = function () {\r
+ var inputs = document.getElementsByTagName('input');\r
+ var length = inputs.length;\r
+ var el;\r
+ var type;\r
+ var id;\r
+ var r_parse;\r
+ \r
+ for (i = 0; i < length; i++) {\r
+ el = inputs[i];\r
+ id = el.id;\r
+ \r
+ r_parse = f._parseId(id);\r
+ \r
+ type = r_parse[1];\r
+ switch (type) {\r
+ case "CPF": \r
+ addEvent(el, 'keyup keypress keydown', function() { f._mask('CPF', this.id); });\r
+ el.maxLength = 14;\r
+ \r
+ break;\r
+ case "DAT":\r
+ addEvent(el, 'keyup keypress keydown', function() { f._mask('DAT', this.id); });\r
+ el.maxLength = 10;\r
+ \r
+ break;\r
+ case "HOR":\r
+ addEvent(el, 'keyup keypress keydown', function() { f._mask('HOR', this.id); });\r
+ el.maxLength = 5;\r
+ \r
+ break;\r
+ \r
+ case "HO2":\r
+ addEvent(el, 'keyup keypress keydown', function() { f._mask('HO2', this.id); });\r
+ el.maxLength = 8;\r
+ \r
+ break;\r
+ \r
+ case "TEL":\r
+ addEvent(el, 'keyup keypress keydown', function() { f._mask('TEL', this.id); });\r
+ el.maxLength = 14;\r
+ \r
+ break;\r
+ case "CNP":\r
+ addEvent(el, 'keyup keypress keydown', function() { f._mask('CNP', this.id); });\r
+ el.maxLength = 18;\r
+ \r
+ break;\r
+ case "CEP":\r
+ addEvent(el, "keyup keypress keydown", function() { f._mask('CEP', this.id); });\r
+ el.maxLength = 9;\r
+ \r
+ break;\r
+ case "NUM":\r
+ addEvent(el, 'keyup', function() { f._mask('NUM', this.id); });\r
+ \r
+ break;\r
+ case "FLO":\r
+ addEvent(el, 'keyup', function() { f._mask('FLO', this.id); });\r
+ \r
+ break;\r
+ case "DIN":\r
+ addEvent(el, 'keyup', function() { f._mask('DIN', this.id); });\r
+ el.maxLength = 15;\r
+ \r
+ break;\r
+ }\r
+ }\r
+ }\r
+ \r
+ this._showMessage = function (tmp_index) {\r
+ msgs = Array();\r
+\r
+ if (this.linguage == 1) {\r
+ msgs[0] = 'Por favor complete o campo "%1"';\r
+ msgs[1] = 'Caracter inválido colocado no campo %1';\r
+ msgs[2] = 'Você precisa digitar uma senha.';\r
+ msgs[3] = 'A confirmação da senha não é válida.';\r
+ msgs[4] = 'Por favor complete o campo "%1" com formato dd/mm/aaaa';\r
+ msgs[5] = 'Dados inválidos colocados no campo %1';\r
+ msgs[6] = 'CPF Inválido!';\r
+ msgs[7] = 'Por favor selecione uma opção para o campo "%1"';\r
+ msgs[8] = 'Por favor complete o campo "%1" com formato hh:mm';\r
+ msgs[9] = 'O campo "%1" deve conter pelo menos %2 caracteres.' ;\r
+ msgs[10] = 'Por favor complete o campo "%1" com formato hh:mm:ss';\r
+ msgs[11] = 'CNPJ Inválido!';\r
+ msgs[12] = 'Tipo de arquivo inválido. \nO campo "%1" aceita somente arquivos com as extensões "%2".';\r
+ }\r
+ //TODO: Make strings of different languages. (English, Spanish...)\r
+ \r
+ var r = String(msgs[tmp_index]);\r
+ for (i = 1; i <= 5; i++) {\r
+ r = r.replace("%" + i, arguments[i]);\r
+ }\r
+ \r
+ alert(r);\r
+ }\r
+ \r
+ this._parseId = function (tmp_id) {\r
+ var i = 0;\r
+ var underscore = 0;\r
+ var qnt = 0;\r
+ var type = '';\r
+ var required;\r
+ var label = '';\r
+ var minchars = '';\r
+ \r
+ while (i < tmp_id.length) {\r
+ if ((tmp_id.charAt(i) != '_') && (!underscore)) {\r
+ label = label + tmp_id.charAt(i);\r
+ } else if (tmp_id.charAt(i) == '_') {\r
+ underscore++;\r
+ } else if (underscore == 1) {\r
+ if (type.length < 3) {\r
+ type = type + tmp_id.charAt(i);\r
+ } else {\r
+ if (tmp_id.charAt(i) == '0') {\r
+ required = false; \r
+ } else {\r
+ required = true; \r
+ }\r
+ }\r
+ } else if (underscore == 2) {\r
+ minchars = minchars + '' + tmp_id.charAt(i); \r
+ }\r
+ i++; \r
+ }\r
+ \r
+ //format minchars\r
+ if (minchars == '') {\r
+ minchars = 0;\r
+ }\r
+ minchars = parseInt(minchars);\r
+ \r
+ //parse name\r
+ var arr = label.split("**");\r
+ label = arr[0].trim();\r
+ \r
+ return Array(label, type, required, minchars);\r
+ }\r
+ \r
+ \r
+ this._mask = function (tmp_type, tmp_id) { \r
+ var obj = $$(tmp_id);\r
+\r
+ switch (tmp_type) {\r
+ case "CPF":\r
+ var value = f._filterChars(obj.value, "0123456789");\r
+ value = f._filterMask(value, "XXX.XXX.XXX-XX");\r
+ obj.value = value;\r
+ \r
+ break;\r
+ case "DAT":\r
+ var value = f._filterChars(obj.value, "0123456789");\r
+ value = f._filterMask(value, "XX/XX/XXXX");\r
+ obj.value = value;\r
+ \r
+ break;\r
+ case "HOR":\r
+ var value = f._filterChars(obj.value, "0123456789");\r
+ value = f._filterMask(value, "XX:XX");\r
+ obj.value = value;\r
+ \r
+ break;\r
+ case "HO2":\r
+ var value = f._filterChars(obj.value, "0123456789");\r
+ value = f._filterMask(value, "XX:XX:XX");\r
+ obj.value = value;\r
+ \r
+ break;\r
+ case "TEL":\r
+ var value = f._filterChars(obj.value, "0123456789");\r
+ value = f._filterMask(value, "(XX) XXXX-XXXX");\r
+ \r
+ obj.value = value;\r
+ \r
+ break;\r
+ case "CNP":\r
+ var value = f._filterChars(obj.value, "0123456789");\r
+ value = f._filterMask(value, "XX-XXX-XXX/XXXX-XX");\r
+ obj.value = value;\r
+ \r
+ break;\r
+ case "CEP":\r
+ var value = f._filterChars(obj.value, "0123456789");\r
+ value = f._filterMask(value, "XXXXX-XXX");\r
+ obj.value = value;\r
+ \r
+ break;\r
+ case "NUM":\r
+ var value = f._filterChars(obj.value, "0123456789");\r
+ obj.value = value;\r
+ \r
+ break;\r
+ \r
+ case "FLO":\r
+ var value = f._filterChars(obj.value, "0123456789,");\r
+ obj.value = value;\r
+ \r
+ break;\r
+ case "DIN":\r
+ var possui_menos = false; var n = '__0123456789-'; var d = obj.value; var l = d.length; var r = ''; var len = 15;\r
+ var wa, wb, w, verificador, z, c, n, a;\r
+ if (l > 0) { z = d.substr(0,l-1); s = ''; a = 2;\r
+ for (i=0; i < l; i++) { c=d.charAt(i); if (n.indexOf(c) > a) { a=1;s+=c; if (c == '-') { possui_menos = true; }; }; }; l=s.length; t=len-1; if (l > t) { l=t; s=s.substr(0,t); };\r
+ if (l > 2) { r=s.substr(0,l-2)+','+s.substr(l-2,2); } else { if (l == 2) { r='0,'+s; } else { if (l == 1) { r='0,0'+s; }; }; };\r
+ if (r == '') { r='0,00'; } else { l=r.length; if (possui_menos) { verificador = 7; } else { verificador = 6; } if (l > verificador) { j=l%3; w=r.substr(0,j); wa=r.substr(j,l-j-6); wb=r.substr(l-6,6); if (j > 0) { w+='.'; }; k=(l-j)/3-2; for (i=0; i < k; i++) { w+=wa.substr(i*3,3)+'.'; }; r=w+wb; }; };\r
+ }; \r
+ if (r.length <= len) { obj.value=r; } else { obj.value=z; };\r
+ \r
+ break;\r
+ \r
+ }\r
+ }\r
+ \r
+ //Mask functions\r
+ this._filterChars = function (tmp_valor, tmp_mask) {\r
+ var txt = "";\r
+ var i = 0;\r
+ var c;\r
+ \r
+ while (i < tmp_valor.length) {\r
+ c = tmp_valor.charAt(i);\r
+ \r
+ if (tmp_mask.indexOf(c) != -1) {\r
+ txt += c;\r
+ }\r
+ \r
+ i++;\r
+ }\r
+ \r
+ return txt;\r
+ }\r
+ \r
+ this._filterMask = function (tmp_valor, tmp_mask) {\r
+ var txt = "";\r
+ var txt2 = "";\r
+ var i = 0;\r
+ var c;\r
+ var i2 = 0;\r
+ var i_ultimo;\r
+ var i_ultimo2 = 0;\r
+ var i_ultimo_fake = true;\r
+ \r
+ while (i < tmp_mask.length) {\r
+ c = tmp_mask.charAt(i);\r
+ \r
+ if (c == 'X') {\r
+ if (tmp_valor.charAt(i2) != '') {\r
+ txt += tmp_valor.charAt(i2);\r
+ txt2 += tmp_valor.charAt(i2);\r
+ i2++;\r
+ i_ultimo = i;\r
+ i_ultimo2 = i2;\r
+ } else {\r
+ i_ultimo_fake = false;\r
+ }\r
+ } else {\r
+ if (i_ultimo2 < tmp_valor.length) {\r
+ txt2 += c;\r
+ }\r
+ txt += c;\r
+ }\r
+ \r
+ i++;\r
+ }\r
+ \r
+ if (i_ultimo_fake) {\r
+ txt2 = txt;\r
+ }\r
+ \r
+ return txt2;\r
+ }\r
+}\r
+var f = new Form();\r
+addEvent(window, 'load', f.maskFields);
\ No newline at end of file
--- /dev/null
+//Requires include default.js\r
+try { var _test_popup = __include_default; }\r
+catch(e) { alert("popup.js : Include '_system/js/default.js' é obrigatório"); }\r
+\r
+//Requires include ajax.js\r
+try { var _test_popup2 = __include_ajax; }\r
+catch(e) { alert("popup.js : Include '_system/js/ajax.js' é obrigatório"); }\r
+\r
+var __include_popup = true;\r
+\r
+var Popup_atual = false;\r
+\r
+function Popup(tmp_w, tmp_h) {\r
+ this.title = "";\r
+ this.bg_alpha = 60;\r
+ \r
+ this.width = tmp_w;\r
+ this.height = tmp_h;\r
+ \r
+ this.overflow = 'auto';\r
+ this.template = 1;\r
+ \r
+ this.valign = "middle";\r
+ this.align = "center";\r
+ \r
+ this.fixPosition = true;\r
+ \r
+ this.ownTop = 0;\r
+ this.ownLeft = 0;\r
+ \r
+ this.position = "relative";\r
+ \r
+ this.onLoad = new Function();\r
+ \r
+ this._id_bg = "";\r
+ this._id_box = "";\r
+\r
+ this.open = function (tmp_url) {\r
+ var b = document.getElementsByTagName('body')[0];\r
+ var self = this;\r
+ \r
+ //Create ids\r
+ this._id_bg = this._genId();\r
+ this._id_box = this._genId();\r
+ \r
+ //Create bg\r
+ var bg = document.createElement('div');\r
+ bg.setAttribute('id', this._id_bg);\r
+ bg.setAttribute('style', 'position: absolute; top: 0; left: 0; z-index: 999; width: '+this.setWidthBox()+'; height: ' + this.setHeightBox() + '; background-color: #000000; -moz-opacity:0.' + this.bg_alpha + ';opacity:.' + this.bg_alpha + ';filter:alpha(opacity=' + this.bg_alpha + ');');\r
+ bg.style.position = 'absolute';\r
+ bg.style.left = "0px";\r
+ bg.style.top = "0px";\r
+ bg.style.width = this.setWidthBox();\r
+ bg.style.height = this.setHeightBox();\r
+ bg.style.background = '#000';\r
+ bg.style.filter = 'alpha(opacity=' + this.bg_alpha + ')';\r
+ bg.innerHTML = ' ';\r
+ b.appendChild(bg);\r
+ \r
+ //Adjust positions\r
+ this.Popup_bg = function (e, n){\r
+ var div = $$(self._id_bg);\r
+ if(div){\r
+ div.style.width = self.setWidthBox();\r
+ div.style.height = self.setHeightBox();\r
+ }\r
+ }\r
+ this.Popup_f = function (e, n) {\r
+ var pos = new WindowPosition();\r
+ var div = $$(self._id_bg);\r
+ var box = $$(self._id_box);\r
+ var box2 = $$(self._id_box + "_ext");\r
+ \r
+ if (div) {\r
+ var x;\r
+ var y;\r
+ \r
+ switch(self.valign){\r
+ case "top":\r
+ y = pos.y + self.ownTop;\r
+ break;\r
+ case "middle":\r
+ y = pos.y + (pos.h / 2) - ((self.height) / 2) + self.ownTop;\r
+ break;\r
+ case "bottom":\r
+ y = pos.y + pos.h - self.height + self.ownTop;\r
+ break;\r
+ }\r
+ \r
+ switch(self.align){\r
+ case "left":\r
+ x = pos.x + self.ownLeft;\r
+ break;\r
+ case "center":\r
+ x = pos.x + (pos.w / 2) - ((self.width) / 2) + self.ownLeft;\r
+ break;\r
+ case "right":\r
+ x = pos.x + (pos.w / 2) - ((self.width) / 2) + self.ownLeft;\r
+ break;\r
+ }\r
+ \r
+ box.style.left = x + "px";\r
+ box.style.top = y + "px";\r
+ \r
+ if ((self.template == 1) || (self.template == 3)) {\r
+ box2.style.left = (x - 5) + "px";\r
+ box2.style.top = (y - 20) + "px";\r
+ }\r
+ \r
+ if(self.fixPosition){\r
+ var boxTop = box.style.top.replace('px','');\r
+ var boxLeft = box.style.left.replace('px','');\r
+ \r
+ var boxTop2 = boxTop-20;\r
+ var boxLeft2 = boxLeft-5;\r
+ \r
+ if(boxTop2 < 0){\r
+ box2.style.top = '0px';\r
+ box.style.top = '20px';\r
+ }\r
+ //alert('box.style.left = '+boxLeft+'\nbox.style.top = '+boxTop);\r
+ //alert('box2.style.left = '+boxLeft2+'\nbox2.style.top = '+boxTop2);\r
+ }\r
+ \r
+ div.style.display = '';\r
+ box.style.display = '';\r
+ div.style.zIndex = 999;\r
+ \r
+ if ((n == undefined) && (window.Popup_f)) {\r
+ window.Popup_f(e, 1);\r
+ }\r
+ }\r
+ }\r
+ if(self.position != "fixed")\r
+ addEvent(window, "scroll resize", this.Popup_f);\r
+ addEvent(window, "scroll resize", this.Popup_bg);\r
+ window.Popup_f = this.Popup_f;\r
+ \r
+ //Create html\r
+ switch (this.template) {\r
+ default:\r
+ case 1:\r
+ var html = '<div id="' + this._id_box + '_ext" style="width: ' + (this.width+10) + 'px; height: ' + (this.height+25) + 'px; z-index: 1000; background: #999; position: absolute; -moz-opacity:0.' + this.bg_alpha + ';opacity:.' + this.bg_alpha + ';filter:alpha(opacity=' + this.bg_alpha + ');">';\r
+ html += '<div style="width: ' + (this.width + 5) + 'px; margin-top: 3px; text-align: right; z-index: 1005;"><a href="javascript: Popup_atual.close();" style="color: #000; text-decoration: none; font-family: Verdana; font-size: 10px;">Fechar</a></div></div>';\r
+ html += '<div id="' + this._id_box + '" style="display: none; width: ' + (this.width) + 'px; height: ' + (this.height) + 'px; background: #FFFFFF; overflow: ' + this.overflow + '; position: absolute; z-index: 1005;">';\r
+ html += '<div style="margin-top: 45%; font-family: Verdana; font-size: 10px; color: #CCC;"><center>Carregando janela</center></div>';\r
+ html += '</div>';\r
+ \r
+ tn = document.createElement('div');\r
+ tn.innerHTML = html;\r
+ b.appendChild(tn);\r
+ \r
+ var box = $$(this._id_box);\r
+ box.style.width = this.width + 'px';\r
+ box.style.height = this.height + 'px';\r
+ box.style.overflow = this.overflow;\r
+ \r
+ var box2 = $$(this._id_box + "_ext");\r
+ box2.style.filter = 'alpha(opacity=' + this.bg_alpha + ')';\r
+ box2.style.width = (this.width + 10) + 'px';\r
+ box2.style.height = (this.height + 25) + 'px';\r
+ \r
+ break;\r
+ case 2:\r
+ var html = '<div id="' + this._id_box + '" style="display: none; width: ' + (this.width) + 'px; height: ' + (this.height) + 'px; background: #FFFFFF; overflow: ' + this.overflow + '; position: absolute; z-index: 1001;">';\r
+ html += '<div style="margin-top: 50%; font-family: Verdana; font-size: 10px; color: #CCC;"><center>Carregando janela</center></div>';\r
+ html += '</div>';\r
+ \r
+ tn = document.createElement('div');\r
+ tn.innerHTML = html;\r
+ b.appendChild(tn);\r
+ \r
+ var box = $$(this._id_box);\r
+ box.style.width = this.width + 'px';\r
+ box.style.height = this.height + 'px';\r
+ box.style.overflow = this.overflow;\r
+ \r
+ break;\r
+ case 3:\r
+ var html = '<div id="' + this._id_box + '_ext" style="width: ' + (this.width+10) + 'px; height: ' + (this.height+25) + 'px; z-index: 1000; background: #FFFFFF; position: absolute;">';\r
+ html += '<div style="width: ' + (this.width-5) + 'px; margin-top:8px; text-align: right; z-index: 1005;"><a href="javascript: Popup_atual.close();"><img src="../../../_system/img/bt-xfechar.gif"></a></div></div>';\r
+ html += '<div id="' + this._id_box + '" style="display: none; width: ' + (this.width) + 'px; height: ' + (this.height) + 'px; background: #FFFFFF; overflow: ' + this.overflow + '; position: absolute; z-index: 1005;">';\r
+ html += '<div style="margin-top: 45%; font-family: Verdana; font-size: 10px; color: #CCC;"><center>Carregando janela</center></div>';\r
+ html += '</div>';\r
+ \r
+ tn = document.createElement('div');\r
+ tn.innerHTML = html;\r
+ b.appendChild(tn);\r
+ \r
+ var box = $$(this._id_box);\r
+ box.style.width = this.width + 'px';\r
+ box.style.height = this.height + 'px';\r
+ box.style.overflow = this.overflow;\r
+ \r
+ var box2 = $$(this._id_box + "_ext");\r
+ box2.style.filter = 'alpha(opacity=' + this.bg_alpha + ')';\r
+ box2.style.width = (this.width + 10) + 'px';\r
+ box2.style.height = (this.height + 25) + 'px';\r
+ \r
+ break;\r
+ case 4:\r
+ var html = '<div id="' + this._id_box + '" style="display: none; width: ' + (this.width) + 'px; height: ' + (this.height) + 'px; background: transparent; overflow: ' + this.overflow + '; position: absolute; z-index: 1001;">';\r
+ html += '<div style="margin-top: 50%; font-family: Verdana; font-size: 10px; color: #CCC;"><center>Carregando janela</center></div>';\r
+ html += '</div>';\r
+ \r
+ tn = document.createElement('div');\r
+ tn.innerHTML = html;\r
+ b.appendChild(tn);\r
+ \r
+ var box = $$(this._id_box);\r
+ box.style.width = this.width + 'px';\r
+ box.style.height = this.height + 'px';\r
+ box.style.overflow = this.overflow;\r
+ \r
+ break;\r
+ }\r
+ \r
+ this.Popup_f();\r
+ setTimeout(Popup_f, 50);\r
+ setTimeout(Popup_f, 100);\r
+ setTimeout(Popup_f, 150);\r
+ setTimeout(Popup_f, 300);\r
+ setTimeout(Popup_f, 500);\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ $$(self._id_box).innerHTML = this.html;\r
+ \r
+ this.runJS(this.html);\r
+ \r
+ if (self.onLoad) {\r
+ self.onLoad();\r
+ }\r
+ }\r
+ a.get(tmp_url);\r
+ \r
+ Popup_atual = this;\r
+ }\r
+ \r
+ this.close = function () {\r
+ var box = $$(this._id_bg);\r
+ var div = $$(this._id_box);\r
+ var div2 = $$(this._id_box + "_ext");\r
+ var b = document.getElementsByTagName('body')[0];\r
+ \r
+ if (div) { removeElement(div); }\r
+ if (div2) { removeElement(div2); }\r
+ if (box) { removeElement(box); }\r
+ \r
+ removeEvent(window, "scroll", this.Popup_f);\r
+ removeEvent(window, "resize", this.Popup_f);\r
+ window.Popup_f = undefined;\r
+ }\r
+ \r
+ this._genId = function () {\r
+ var id = "popup" + new String(Math.round(Math.random() * 1000));\r
+ \r
+ if ($$(id)) {\r
+ id = this._genId();\r
+ }\r
+ \r
+ return id;\r
+ }\r
+ \r
+ this.setHeightBox = function() {\r
+ var heightBody = document.body.clientHeight;\r
+ var heightScroll = document.body.scrollHeight;\r
+ \r
+ var h = document.body.clientHeight;\r
+ \r
+ if(h > heightBody){\r
+ heightBody = h;\r
+ }\r
+ \r
+ if (heightBody > heightScroll) {\r
+ return "100%";\r
+ } else {\r
+ return heightScroll+'px';\r
+ }\r
+ }\r
+ \r
+ this.setWidthBox = function() {\r
+ var widthBody = document.body.clientWidth;\r
+ var widthScroll = document.body.scrollWidth;\r
+ \r
+ var w = document.body.clientWidth;\r
+ \r
+ if(w > widthBody){\r
+ widthBody = w;\r
+ }\r
+ \r
+ if (widthBody > widthScroll) {\r
+ return "100%";\r
+ } else {\r
+ return widthScroll+'px';\r
+ }\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+function swf(src, w, h, vars, bg, mode, cssclass, id, not_ffv) {
+ var html;
+
+ if (!bg) {
+ bg = '';
+ }
+
+
+ if (src.indexOf("?") > 0) {
+ var arr = src.split("?");
+
+ src = arr[0];
+ vars = arr[1];
+ }
+
+ a = new String(" " + id);
+ a = a.replace(" ", "");
+
+ if (!(!(!not_ffv))) {
+ vars = formatFlashVars(vars);
+ }
+
+ html = '';
+
+ html += '<OBJECT class='+ cssclass +' codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0 \n';
+ html +='height='+ h +' width='+ w +' align=middle \n';
+ html +='classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 id="swf_' + a + '"> \n';
+ html +='<PARAM NAME="_cx" VALUE="18627"> \n';
+ html +='<PARAM NAME="_cy" VALUE="1640"> \n';
+ html +='<PARAM NAME="FlashVars" VALUE="' + vars + '"> \n'
+
+ html +='<PARAM NAME="Movie" VALUE="' + src + '"> \n';
+ html +='<PARAM NAME="Src" VALUE="' + src + '"> \n';
+
+ html +='<PARAM NAME="WMode" VALUE="'+ mode +'"> \n';
+ html +='<PARAM NAME="Play" VALUE="-1"> \n';
+ html +='<PARAM NAME="Loop" VALUE="-1"> \n';
+ html +='<PARAM NAME="Quality" VALUE="High"> \n';
+ html +='<PARAM NAME="SAlign" VALUE=""> \n';
+ html +='<PARAM NAME="Menu" VALUE="-1"> \n';
+ html +='<PARAM NAME="Base" VALUE=""> \n';
+ html +='<PARAM NAME="allowFullScreen" VALUE="true"> \n';
+
+ html +='<PARAM NAME="Scale" VALUE="ShowAll"> \n';
+ html +='<PARAM NAME="DeviceFont" VALUE="0"> \n';
+ html +='<PARAM NAME="EmbedMovie" VALUE="0"> \n';
+ html +='<PARAM NAME="BGColor" VALUE="'+ bg +'"> \n';
+ html +='<PARAM NAME="SWRemote" VALUE=""> \n';
+ html +='<PARAM NAME="MovieData" VALUE=""> \n';
+ html +='<PARAM NAME="SeamlessTabbing" VALUE="false"> \n';
+ html +='<PARAM NAME="AllowScriptAccess" VALUE="always"> \n';
+
+ html +=' <embed \n';
+ html +=' src="' + src + '"\n';
+ html +=' FlashVars="' + vars + '" \n';
+ html +=' quality="high" bgcolor="#'+ bg +'" width="'+ w +'" height="'+ h +'" \n';
+ html +=' name="swf_'+ id +'" align="middle" allowScriptAccess="always" SeamlessTabbing="false" allowFullScreen="true" \n';
+ html +=' wmode="'+ mode +'" type="application/x-shockwave-flash" \n';
+ html +=' pluginspage="http://www.macromedia.com/go/getflashplayer" id="swf_' + a + '" /> \n';
+ html +='</OBJECT> \n';
+
+ if ((a.length > 3) && (id)) {
+ document.getElementById(a).innerHTML = html;
+ } else {
+ document.write(html);
+ }
+}
+
+function formatFlashVars(tmp_string) {
+ var words = new Array();
+ var i = 0;
+ var control_string = "";
+
+ tmp_string = new String(tmp_string);
+
+ words[0] = new Array("!","\"","#","$","'","\(","\)","\*","\+",",","\"",":",";","<",">","\?","@","\[","\]","\^","\`","\{","|","\}","~","\7f","","","","","
","","","","","","", "","","","","","","","", "","","","","","","","","¡","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","","®", "¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ý","þ","ÿ");
+ words[1] = new Array("%21","%22","%23","%24","%27","%28","%29","*","%2B","%2C","%2F","%3A","%3B","%3C","%3E","%3F","%40","%5B","%5D","%5E","%60","%7B","%7C","%7D","%7E","%7F","%80","%82","%83","%84","%85","%86","%87","%88","%89","%8A","%8B","%8C","%8E","%91","%92","%93","%94","%95","%96","%97","%98","%99","%9A","%9B","%9C","%9E","%9F","%A1","%A2","%A3","%A4","%A5","%A6","%A7","%A8","%A9","%AA","%AB","%AC","%AD","%AE","%AF","%B0","%B1","%B2","%B3","%B4","%B5","%B6","%B7","%B8","%B9","%BA","%BB","%BC","%BD","%BE","%BF","%C0","%C1","%C2","%C3","%C4","%C5","%C6","%C7","%C8","%C9","%CA","%CB","%CC","%CD","%CE","%CF","%D0","%D1","%D2","%D3","%D4","%D5","%D6","%D7","%D8","%D9","%DA","%DB","%DC","%DD","%DE","%DF","%E0","%E1","%E2","%E3","%E4","%E5","%E6","%E7","%E8","%E9","%EA","%EB","%EC","%ED","%EE","%EF","%F0","%F1","%F2","%F3","%F4","%F5","%F6","%F7","%F8","%F9","%FA","%FB","%FC","%FD","%FE","%FF");
+
+ for (; i < words[0].length; i++) {
+ do {
+ control_string = tmp_string;
+ tmp_string = tmp_string.replace(words[0][i], words[1][i]);
+ } while (control_string != tmp_string);
+ }
+
+ return tmp_string;
+}
+
+function swfVersao(versao_exigida) {
+ var versao, tipo, axo, versao_exigida, pagina;
+
+ if (navigator.plugins && navigator.mimeTypes.length) {
+ var x = navigator.plugins["Shockwave Flash"];
+ if (x && x.description) {
+ versao = x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split(".");
+ versao = versao[0];
+ }
+ } else {
+ try {
+ try {
+ var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
+ } catch (e) { }
+
+ for (var i = 3; axo != null; i++) {
+ axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
+ versao = i;
+ }
+ } catch (e) { }
+
+ try {
+ versao = axo.GetVariable("$version").split(" ")[1].split(",").split(",");
+ versao = versao[0];
+ } catch (e) { }
+ }
+
+ if (parseInt(versao) < versao_exigida) {
+ if (confirm("Você precisa de uma versão mais nova do Flash Player para acessar este site.\n Clique em 'OK' para ser redirecionado direto para a página de download.")) {
+ document.location = "http://www.macromedia.com/go/getflashplayer";
+ }
+ }
+}
+swfVersao(8);
\ No newline at end of file
--- /dev/null
+/*\r
+Tween class for js, like nosvara.transitions.Tween class\r
+by Ramon Fritsch (www.ramonfritsch.com)\r
+\r
+Ex.:\r
+Tween.addTween($$('div_id'), {_alpha: 40, _height: 200, _width: 100, time: 2, transition: "circOut"});\r
+*/\r
+\r
+function TweenClass() {\r
+ this._tweens = new Array();\r
+ this._is_start = false;\r
+ this._time = 0;\r
+ \r
+ this.addTween = function (tmp_element, tmp_params) {\r
+ if (!this._is_start) {\r
+ this._start();\r
+ }\r
+ \r
+ var time = ((tmp_params.time) || (tmp_params.time == 0)) ? tmp_params.time : 1;\r
+ var transition = (tmp_params.transition) ? tmp_params.transition : "quadOut";\r
+ \r
+ for (var i = 0; i < this._tweens.length; i++) {\r
+ if (this._tweens[i].element != tmp_element) {\r
+ this._deleteTween(i);\r
+ }\r
+ }\r
+ \r
+ if (tmp_element) {\r
+ var o = {\r
+ element: tmp_element,\r
+ time: time * 1000,\r
+ transition: transition,\r
+ time_ini: (new Date()).getTime(),\r
+ params: new Array(),\r
+ params_ini: new Array()\r
+ };\r
+ \r
+ o.element.style.overflow = "hidden";\r
+ \r
+ if (!o.element.defaults) { o.element.defaults = new Array(); }\r
+ \r
+ for (v in tmp_params) {\r
+ if (v.substr(0, 1) == "_") { \r
+ if (o.element.defaults[v] == undefined) { o.element.defaults[v] = this._getParam(o.element, v); }\r
+ if (tmp_params[v] == "default") { tmp_params[v] = o.element.defaults[v]; }\r
+ \r
+ o.params[v] = tmp_params[v];\r
+ o.params_ini[v] = this._getParam(o.element, v);\r
+ }\r
+ }\r
+ \r
+ if (time > 0) {\r
+ this._tweens.push(o);\r
+ } else {\r
+ for (v in tmp_params) {\r
+ if (v.substr(0, 1) == "_") { \r
+ if (o.element.defaults[v] == undefined) { o.element.defaults[v] = this._getParam(o.element, v); }\r
+ if (tmp_params[v] == "default") { tmp_params[v] = o.element.defaults[v]; }\r
+ \r
+ this._setParam(o.element, v, tmp_params[v]);\r
+ }\r
+ } \r
+ }\r
+ }\r
+ }\r
+ \r
+ this._getParam = function (tmp_element, tmp_param) {\r
+ var r;\r
+ \r
+ switch (tmp_param) {\r
+ case "_height":\r
+ r = tmp_element.style.height.replace("px", "");\r
+ r++; r--;\r
+ \r
+ if (r == 0) {\r
+ r = tmp_element.offsetHeight;\r
+ r++; r--;\r
+ }\r
+ \r
+ break;\r
+ case "_width":\r
+ r = tmp_element.style.width.replace("px", "");\r
+ r++; r--;\r
+ \r
+ if (r == 0) {\r
+ r = tmp_element.offsetWidth; \r
+ r++; r--;\r
+ }\r
+ \r
+ break;\r
+ case "_alpha":\r
+ r = tmp_element._alpha;\r
+ if (!r) { r = 100; }\r
+ \r
+ r++; r--;\r
+ \r
+ break;\r
+ case "_marginLeft":\r
+ r = tmp_element.style.marginLeft.replace("px", "");\r
+ r++; r--;\r
+ \r
+ \r
+ if (r == 0) {\r
+ //tmp_element.getAttribute("width", tmp_value + "px");\r
+ r = tmp_element.style.marginLeft.replace("px", ""); \r
+ r++; r--;\r
+ }\r
+ break;\r
+ case "_marginTop":\r
+ r = tmp_element.style.marginTop.replace("px", "");\r
+ r++; r--;\r
+ \r
+ \r
+ if (r == 0) {\r
+ r = tmp_element.style.marginTop.replace("px", ""); \r
+ r++; r--;\r
+ }\r
+ \r
+ }\r
+ \r
+ return r;\r
+ }\r
+ \r
+ this._setParam = function (tmp_element, tmp_param, tmp_value) {\r
+ if (tmp_value > 0 && tmp_element.style.visibility == "hidden") tmp_element.style.visibility = "visible";\r
+ \r
+ switch (tmp_param) {\r
+ case "_height":\r
+ if (tmp_value == 0) tmp_element.style.visibility = "hidden";\r
+ tmp_element.style.height = tmp_value + "px";\r
+ tmp_element.setAttribute("height", tmp_value + "px");\r
+ \r
+ break;\r
+ case "_width":\r
+ if (tmp_value == 0) tmp_element.style.visibility = "hidden";\r
+ tmp_element.style.width = tmp_value + "px";\r
+ tmp_element.setAttribute("width", tmp_value + "px");\r
+ \r
+ break;\r
+ case "_alpha":\r
+ if (tmp_value >= 100) tmp_value = 99.999;\r
+ if (tmp_value == 0) tmp_element.style.visibility = "hidden";\r
+ if (isIE) tmp_element.style.filter = "alpha(opacity=" + tmp_value + ")";\r
+ tmp_element.style.opacity = (tmp_value / 100);\r
+ tmp_element._alpha = tmp_value;\r
+ \r
+ break;\r
+ case "_marginLeft":\r
+ if (tmp_value == 0) tmp_element.style.visibility = "hidden";\r
+ tmp_element.style.marginLeft = tmp_value + "px";\r
+ tmp_element.setAttribute("style", "margin-left:" + tmp_value + "px");\r
+ \r
+ break;\r
+ case "_marginTop":\r
+ //if (tmp_value == 0) tmp_element.style.visibility = "hidden";\r
+ tmp_element.style.marginTop = tmp_value + "px";\r
+ tmp_element.setAttribute("style", "margin-top:" + tmp_value + "px");\r
+ \r
+ break;\r
+ }\r
+ }\r
+ \r
+ this._deleteTween = function (tmp_index) {\r
+ var arr = new Array();\r
+ var i2 = 0;\r
+ for (var i = 0; i < this._tweens.length; i++) {\r
+ if (i != tmp_index) {\r
+ arr[i2] = this._tweens[i];\r
+ \r
+ i2++;\r
+ }\r
+ }\r
+ \r
+ this._tweens = arr;\r
+ }\r
+ \r
+ this._start = function () {\r
+ this._is_start = false;\r
+ \r
+ this._update();\r
+ }\r
+ \r
+ this._update = function () {\r
+ this._time = (new Date()).getTime();\r
+ \r
+ for (var i = 0; i < this._tweens.length; i++) {\r
+ this._updateTween(i);\r
+ }\r
+ \r
+ setTimeout(this._update.bind(this), 26);\r
+ }\r
+ \r
+ this._updateTween = function (tmp_index) {\r
+ var tw = this._tweens[tmp_index];\r
+ \r
+ var t, b, c, d;\r
+ \r
+ if (tw) {\r
+ t = (this._time - tw.time_ini);\r
+ d = tw.time;\r
+ \r
+ if (t >= d) {\r
+ for (v in tw.params) {\r
+ this._setParam(tw.element, v, tw.params[v]);\r
+ }\r
+ \r
+ this._deleteTween(tmp_index);\r
+ } else {\r
+ for (v in tw.params) {\r
+ b = tw.params_ini[v];\r
+ c = tw.params[v] - b;\r
+ \r
+ this._setParam(tw.element, v, this._transitions[tw.transition](t, b, c, d));\r
+ }\r
+ }\r
+ } else {\r
+ this._deleteTween(tmp_index); \r
+ }\r
+ }\r
+ \r
+ this._transitions = {\r
+ linear: function(t, b, c, d) { \r
+ return c*t/d + b; \r
+ }, \r
+ quadIn: function(t, b, c, d){ \r
+ return c*(t/=d)*t + b; \r
+ }, \r
+ quadOut: function(t, b, c, d) {\r
+ return -c *(t/=d)*(t-2) + b;\r
+ },\r
+ \r
+ quadInOut: function(t, b, c, d){\r
+ if ((t/=d/2) < 1) return c/2*t*t + b;\r
+ return -c/2 * ((--t)*(t-2) - 1) + b;\r
+ },\r
+ \r
+ cubicIn: function(t, b, c, d){\r
+ return c*(t/=d)*t*t + b;\r
+ },\r
+ \r
+ cubicOut: function(t, b, c, d){\r
+ return c*((t=t/d-1)*t*t + 1) + b;\r
+ },\r
+ \r
+ cubicInOut: function(t, b, c, d){\r
+ if ((t/=d/2) < 1) return c/2*t*t*t + b;\r
+ return c/2*((t-=2)*t*t + 2) + b;\r
+ },\r
+ \r
+ quartIn: function(t, b, c, d){\r
+ return c*(t/=d)*t*t*t + b;\r
+ },\r
+ \r
+ quartOut: function(t, b, c, d){\r
+ return -c * ((t=t/d-1)*t*t*t - 1) + b;\r
+ },\r
+ \r
+ quadInOut: function(t, b, c, d){\r
+ if ((t/=d/2) < 1) return c/2*t*t*t*t + b;\r
+ return -c/2 * ((t-=2)*t*t*t - 2) + b;\r
+ },\r
+ \r
+ quintIn: function(t, b, c, d){\r
+ return c*(t/=d)*t*t*t*t + b;\r
+ },\r
+ \r
+ quintOut: function(t, b, c, d){\r
+ return c*((t=t/d-1)*t*t*t*t + 1) + b;\r
+ },\r
+ \r
+ quintInOut: function(t, b, c, d){\r
+ if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;\r
+ return c/2*((t-=2)*t*t*t*t + 2) + b;\r
+ },\r
+ \r
+ sineIn: function(t, b, c, d){\r
+ return -c * Math.cos(t/d * (Math.PI/2)) + c + b;\r
+ },\r
+ \r
+ sineOut: function(t, b, c, d){\r
+ return c * Math.sin(t/d * (Math.PI/2)) + b;\r
+ },\r
+ \r
+ sineInOut: function(t, b, c, d){\r
+ return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;\r
+ },\r
+ \r
+ expoIn: function(t, b, c, d){\r
+ return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;\r
+ },\r
+ \r
+ expoOut: function(t, b, c, d){\r
+ return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;\r
+ },\r
+ \r
+ expoInOut: function(t, b, c, d){\r
+ if (t==0) return b;\r
+ if (t==d) return b+c;\r
+ if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;\r
+ return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;\r
+ },\r
+ \r
+ circIn: function(t, b, c, d){\r
+ return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;\r
+ },\r
+ \r
+ circOut: function(t, b, c, d){\r
+ return c * Math.sqrt(1 - (t=t/d-1)*t) + b;\r
+ },\r
+ \r
+ circInOut: function(t, b, c, d){\r
+ if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;\r
+ return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;\r
+ },\r
+ \r
+ elasticIn: function(t, b, c, d, a, p){\r
+ if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a) a = 1;\r
+ if (a < Math.abs(c)){ a=c; var s=p/4; }\r
+ else var s = p/(2*Math.PI) * Math.asin(c/a);\r
+ return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;\r
+ },\r
+ \r
+ elasticOut: function(t, b, c, d, a, p){\r
+ if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a) a = 1;\r
+ if (a < Math.abs(c)){ a=c; var s=p/4; }\r
+ else var s = p/(2*Math.PI) * Math.asin(c/a);\r
+ return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;\r
+ },\r
+ \r
+ elasticInOut: function(t, b, c, d, a, p){\r
+ if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (!a) a = 1;\r
+ if (a < Math.abs(c)){ a=c; var s=p/4; }\r
+ else var s = p/(2*Math.PI) * Math.asin(c/a);\r
+ if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;\r
+ return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;\r
+ },\r
+ \r
+ backIn: function(t, b, c, d, s){\r
+ if (!s) s = 1.70158;\r
+ return c*(t/=d)*t*((s+1)*t - s) + b;\r
+ },\r
+ \r
+ backOut: function(t, b, c, d, s){\r
+ if (!s) s = 1.70158;\r
+ return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;\r
+ },\r
+ \r
+ backInOut: function(t, b, c, d, s){\r
+ if (!s) s = 1.70158;\r
+ if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;\r
+ return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;\r
+ },\r
+ \r
+ bounceIn: function(t, b, c, d){\r
+ return c - Tween._transitions.bounceOut (d-t, 0, c, d) + b;\r
+ },\r
+ \r
+ bounceOut: function(t, b, c, d){\r
+ if ((t/=d) < (1/2.75)){\r
+ return c*(7.5625*t*t) + b;\r
+ } else if (t < (2/2.75)){\r
+ return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;\r
+ } else if (t < (2.5/2.75)){\r
+ return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;\r
+ } else {\r
+ return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;\r
+ }\r
+ },\r
+ \r
+ bounceInOut: function(t, b, c, d){\r
+ if (t < d/2) return Tween._transitions.bounceIn(t*2, 0, c, d) * .5 + b;\r
+ return Tween._transitions.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b;\r
+ }\r
+ }\r
+}\r
+var Tween = new TweenClass();
\ No newline at end of file
--- /dev/null
+<?
+class Date {
+
+
+ function getMicroTime() {
+ $tmp = explode(" ", microtime());
+
+ return (float)$tmp[0] + (float)$tmp[1];
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Email {
+ var $to;
+ var $from;
+
+ var $list_cc;
+ var $list_bcc;
+
+ var $subject;
+ var $content;
+ var $attach_images;
+ var $debug;
+ var $reset_content;
+
+ var $_smtp_conn;
+ var $_content_bkp;
+ var $_content_formated;
+ var $_lf;
+
+ function Email() {
+ $this->to = "";
+ $this->from = "";
+
+ $this->list_cc = array();
+ $this->list_bcc = array();
+
+ $this->subject = "";
+ $this->content = "";
+ $this->attach_images = false;
+ $this->debug = false;
+
+ $this->_stmp_conn = NULL;
+ $this->_content_bkp = "";
+ $this->_content_formated = "";
+ $this->reset_content = true;
+
+ $this->_lf = ((strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') ? "\r\n" : "\n");
+ }
+
+ function loadTemplate($tmp_path) {
+ global $file;
+
+ $this->content = $file->readFile($tmp_path);
+ }
+
+ function setTemplateValue($tmp_mask, $tmp_value) {
+ $this->content = str_replace($tmp_mask, $tmp_value, $this->content);
+ }
+
+ function send() {
+ $this->_formatContent();
+
+ return mail($this->to, $this->subject, $this->content, $this->_getHeaders());
+ }
+
+ function sendHostNet($tmp_host, $tmp_user, $tmp_pass) {
+ //'smtp.jacquelinerabelo.com.br'
+ //'contato=jacquelinerabelo.com.br'
+ //'77cold'
+
+ @include_once("Mail.php");
+ @include_once("Mail/mime.php");
+
+ $tmp_user = str_replace("@", "=", $tmp_user);
+
+ $recipients = $this->to;
+
+ $headers =
+ array (
+ 'From' => $this->from,
+ 'To' => $this->to,
+ 'Subject' => $this->subject
+ );
+
+ $html = $this->content;
+
+ @$mime = new Mail_mime($this->_lf);
+
+ $mime->setHTMLBody($html);
+
+ $body = $mime->get();
+ $headers = $mime->headers($headers);
+
+ $params =
+ array (
+ 'auth' => true,
+ 'host' => $tmp_host,
+ 'username' => $tmp_user,
+ 'password' => $tmp_pass
+ );
+
+ $mail_object =& Mail::factory('smtp', $params);
+ $result = $mail_object->send($recipients, $headers, $body);
+ if (PEAR::IsError($result)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ function sendSmtp($tmp_smtp_server, $tmp_user = "", $tmp_pass = "") {
+ $this->_formatContent();
+
+ $this->_smtp_conn = fsockopen($tmp_smtp_server, 25, $errno, $errstr, 30);
+
+ if (is_resource($this->_smtp_conn)) {
+ if ($tmp_user != "") {
+ $this->_smtpPut("EHLO " . $tmp_smtp_server);
+ } else {
+ $this->_smtpPut("HELO " . $tmp_smtp_server);
+ }
+
+ $this->_smtpGet();
+
+ if ($tmp_user != "") {
+ $this->_smtpPut("AUTH LOGIN");
+ $this->_smtpGet();
+ $this->_smtpGet();
+ $this->_smtpGet();
+ $this->_smtpGet();
+ $this->_smtpGet();
+ $this->_smtpPut(base64_encode($tmp_user));
+ $this->_smtpGet();
+ $this->_smtpPut(base64_encode($tmp_pass));
+ $this->_smtpGet();
+ }
+
+ if (strpos($tmp_user, "@") > 0) {
+ $from = $tmp_user;
+ } else {
+ $from = $this->from;
+ }
+
+ $this->_smtpPut("MAIL FROM: " . $from);
+ $this->_smtpGet();
+
+ $this->_smtpPut("RCPT TO: " . $this->to);
+ $this->_smtpGet();
+
+ $this->_smtpPut("DATA");
+ $this->_smtpGet();
+
+ $this->_smtpPut("To: <" . $this->to . ">");
+ $this->_smtpGet();
+
+ $this->_smtpPut($this->_getHeaders());
+ $this->_smtpPut($this->_lf);
+
+ $this->_smtpPut($this->content);
+
+ $this->_smtpPut(".");
+ $r = $this->_smtpGet();
+
+ $this->_smtpPut("QUIT");
+ $this->_smtpGet();
+
+ if (is_resource($this->_smtp_conn)) {
+ fclose($this->_smtp_conn);
+ }
+
+ if (substr($r, 0, 1) == "2") {
+ $r = true;
+ } else {
+ $r = false;
+ }
+ } else {
+ $r = false;
+ }
+
+ return $r;
+ }
+
+ //Private Functions
+ function _formatContent() {
+ global $file;
+
+ $lf = $this->_lf;
+
+ if ((($this->_content_bkp != $this->content) && ($this->_content_formated != $this->content)) || ($this->reset_content)) {
+ $this->reset_content = false;
+
+ $this->_boundary = "_=======" . date('YmdHms'). time() . "=======_";
+
+ $this->_content_bkp = $this->content;
+ $c = $this->content;
+ $c_imgs = "";
+ $content = "";
+
+ $arr = explode("@", $this->from);
+ $server = $arr[1];
+
+ if ($this->attach_images) {
+ //Find: <img... src=""...> and <... url() ...>
+ $c = $this->content;
+ $i = 0;
+ $imgs = array();
+
+ while ((preg_match('#<img(.+?)'.preg_quote("src", '/').'(.+?)>|<(.+?)'.preg_quote("background=", '/').'(.+?)>#i', $c, $m)) && ($i < 150)) {
+
+ if (strpos($m[0], "background=") > 0) {
+ $imgs[] = array($m[0], str_replace(array("'", "\""), "", $m[4]));
+
+ $pos = strpos($c, $m[0]) + strlen($m[0]);
+ } else {
+ $p2 = (int)strpos($m[2], '"', 2);
+ $p1 = (int)strpos($m[2], "'", 2);
+ if ($p1 == 0) { $p1 = $p2; }
+
+ $imgs[] = array($m[0], substr($m[2], 2, ($p1 - 2)));
+ $pos = strpos($c, $m[0]) + strlen($m[0]);
+ }
+
+ $c = substr($c, $pos);
+
+ $i++;
+ }
+
+ //Replace imgs urls to imgs cids and generate contents.
+ $c = $this->content;
+ $img_tags = array();
+ $img_files = array();
+ foreach ($imgs as $v) {
+ $tag = $v[0];
+ $path = $v[1];
+
+ $ext = $file->getExtension($path);
+
+ if ((array_search($ext, array("jpg", "gif", "png")) !== false) && (array_search($tag, $img_tags) === false)) {
+ $filename = $file->getFileName($path);
+ $id = "IMG_" . str_replace(array("." . $ext, " "), "", $filename) . "@" . $server;
+
+ $img = str_replace($path, "cid:" . $id, $tag);
+
+ if (strpos($c, $tag) !== false) {
+ $img_tags[] = $tag;
+
+ if ((strpos($img, "moz-do-not-send=\"false\"") == false) && (strpos($img, "<img") !== false)) {
+ $img = substr($img, 0, (strlen($img) - 1)) . " moz-do-not-send=\"false\">";
+ } elseif ((strpos($img, "url(") !== false)) {
+
+ }
+
+ $c = str_replace($tag, $img, $c);
+
+ if (array_search($path, $img_files) === false) {
+ $img_files[] = $path;
+
+ $c_imgs .= "--" . $this->_boundary . $lf;
+ $c_imgs .= "Content-type: image/" . str_replace("jpg", "jpeg", $ext) . "; name=\"" . $filename . "\"" . $lf;
+ $c_imgs .= "Content-Transfer-Encoding: base64" . $lf;
+ $c_imgs .= "Content-ID: <" . $id . ">" . $lf . $lf;
+ $c_imgs .= chunk_split(base64_encode($file->readFile($v[1]))) . $lf . $lf;
+ }
+ }
+ }
+ }
+ }
+
+
+ //Text plain content
+ /*$content = "--" . $this->_boundary . "\n";
+ $content .= "Content-Type: text/plan; charset=iso-8859-1\n\n";
+ $content .= strip_tags(str_replace(array("\r\n", "\n\r", "\n", "<br>"), array("", "", "", "\n"), str_replace(array("<br/>", "<br />"), "<br>", substr($c, (int)strpos($c, "<body"))))) . "\n";*/
+
+ //echo $c;
+
+ //Html content
+ $content .= "--" . $this->_boundary . $lf;
+ $content .= "Content-Type: text/html; charset=iso-8859-1" . $lf . $lf;
+ $content .= $c . $lf . $lf;
+
+ //Images contents
+ $content .= $c_imgs;
+
+ $content .= "--" . $this->_boundary . "--" . $lf;
+
+ $this->_content_formated = $content;
+ $this->content = $content;
+ }
+
+ if (!$this->attach_images) {
+ $this->content = $this->_content_bkp;
+ }
+ }
+
+ function _getHeaders() {
+ $headers = "";
+ $lf = $this->_lf;
+
+ $headers .= "Message-Id: <" . date('YmdHis') . "." . md5(microtime()) . "." . strtoupper($this->from) . ">" . $lf;
+ if ($this->attach_images) {
+ $headers .= "Content-Type: multipart/related; boundary=\"" . $this->_boundary . "\"" . $lf;
+ } else {
+ $headers .= "Content-Type: text/html; charset=iso-8859-1" . $lf;
+ }
+ $headers .= "Subject: " . $this->subject . $lf;
+ $headers .= "MIME-version: 1.0" . $lf;
+ $headers .= "Date: ". date('D, d M Y H:i:s O') . $lf;
+
+ //from
+ if ($this->from) {
+ $headers .= "FROM: " . $this->from . $lf;
+ }
+
+ //cc
+ foreach ($this->list_cc as $v) {
+ $headers .= "{CC}: " . $v . $lf;
+ }
+
+ //bcc
+ foreach ($this->list_bcc as $v) {
+ $headers .= "{BCC}: " . $v . $lf;
+ }
+
+ return $headers;
+ }
+
+ function _smtpPut($tmp_string) {
+ if (substr($tmp_string, -1) != "\n") {
+ $tmp_string .= $this->_lf;
+ }
+
+ if ($this->debug) {
+ echo ">>> " . $tmp_string . "<br>";
+ }
+
+ $tmp_string = str_replace("\r\n", "#####*#####", $tmp_string);
+ $tmp_string = str_replace("\n", "#####*#####", $tmp_string);
+ $tmp_string = str_replace("#####*#####", $this->_lf, $tmp_string);
+
+ return @fputs($this->_smtp_conn, $tmp_string);
+ }
+
+ function _smtpGet() {
+ $v = @fgets($this->_smtp_conn, 512);
+ if ($this->debug) {
+ echo "<<< " . $v . "<br>";
+ }
+
+ return substr($v, 0, 3);
+ }
+
+ function _smtpGets() {
+ $r = "";
+
+ $i = 0;
+ while ((!feof($this->_smtp_conn)) && ($i < 30)) {
+ $tmp = fgets($this->_smtp_conn, 64);
+
+ if ($tmp) {
+ $r .= $tmp;
+ } else {
+ $i = 50;
+ }
+
+ $i++;
+ }
+
+ return $r;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Http {
+ var $_redirs;
+ var $response_headers;
+ var $response_data;
+
+ var $method;
+
+ function Http() {
+ $this->_redirs = 0;
+ }
+
+ function request($tmp_url, $tmp_method = "get", $tmp_content = "", $tmp_headers = array()) {
+ $r = "";
+ $out = "";
+
+ $this->method = strtoupper($tmp_method);
+
+ $uri = parse_url($tmp_url);
+ $server = $uri['host'];
+ $port = isset($uri["port"])?$uri["port"]:80;
+ $path = $uri["path"];
+ $gets = $uri["query"];
+
+ $p = fsockopen($server, $port, $errno, $errstr, 30);
+
+ if (!$p) {
+ return false;
+ } else {
+ if ($this->method == "GET") {
+ $out .= "GET ";
+ $out .= isset($path) ? $path : "/";
+ $out .= isset($gets) ? "?" . $gets : "";
+ $out .= " HTTP/1.1\r\n";
+ $out .= "Host: ".$server."\r\n";
+ $out .= "Connection: Close\r\n\r\n";
+ } else {
+ $out .= "POST ";
+ $out .= isset($path) ? $path : "/";
+ $out .= isset($gets) ? "?" . $gets : "";
+ $out .= " HTTP/1.1\r\n";
+ $out .= "Host: ".$server."\r\n";
+ $out .= "Content-length: " . strlen($tmp_content) . "\r\n";
+ $out .= "User-agent: Schiavoni-HttpPHPClass\r\n";
+
+ foreach ($tmp_headers as $k => $v) {
+ $out .= $k . ":" . $v . "\r\n";
+ }
+
+ $out .= "Connection: Close\r\n\r\n";
+
+ $out .= $tmp_content;
+ }
+
+ fwrite($p, $out, strlen($out));
+ //echo ">>" . $out;
+
+ //recebe os headers
+ //.Response
+ $data = "";
+ $lb = "";
+
+ //.headers
+ $i = 0;
+ while ($i++ < 200) {
+ if (feof($p)) { break; }
+
+ $tmp = fgets($p, 256);
+ $tmplen = strlen($tmp);
+ if ($tmplen == 0) { break; }
+
+ $data .= $tmp;
+
+ if (strpos($data,"\r\n\r\n") > 1) {
+ $lb = "\r\n";
+ } else {
+ if (strpos($data,"\n\n") > 1) {
+ $lb = "\n";
+ }
+ }
+
+ if (($lb != "") && ereg('^HTTP/1.1 100', $data)) {
+ $lb = "";
+ $data = "";
+ }
+
+ if ($lb != "") { break; }
+ }
+
+ $rh = array();
+ $header_arr = explode($lb, $data);
+ $k = "";
+ foreach ($header_arr as $v) {
+ $tmp = explode(":", $v, 2);
+ if (sizeof($tmp) > 1) {
+ $k = strtolower(trim($tmp[0]));
+
+ if ($k != "") { $rh[$k] = trim($tmp[1]); }
+ } elseif ($k != "") {
+ $rh[$k] .= $lb . " " . trim($v);
+ }
+ }
+
+ //.content-length
+ if (isset($rh['transfer-encoding']) && strtolower($rh['transfer-encoding']) == 'chunked') {
+ $content_length = 2147483647;
+ $chunked = true;
+ } elseif (isset($rh['content-length'])) {
+ $content_length = $rh['content-length'];
+ $chunked = false;
+ } else {
+ $content_length = 2147483647;
+ $chunked = false;
+ }
+ $rh_str = $data;
+
+ //.data
+ $data = "";
+ do {
+ if ($chunked) {
+ $tmp = fgets($p, 256);
+ $tmplen = strlen($tmp);
+
+ if ($tmplen == 0) {
+ echo "chunk error";
+ return false;
+ }
+
+ $content_length = hexdec(trim($tmp));
+ }
+
+ $strlen = 0;
+ while (($strlen < $content_length) && (!feof($p))) {
+ $rlen = min(8192, $content_length - $strlen);
+
+ $tmp = fread($p, $rlen);
+ $tmplen = strlen($tmp);
+
+ if (($tmplen == 0) && (!feof($p))) {
+ echo "Body timeout";
+ return false;
+ }
+
+ $strlen += $tmplen;
+ $data .= $tmp;
+ }
+
+ if ($chunked && ($content_length > 0)) {
+ $tmp = fgets($p, 256);
+ $tmplen = strlen($tmp);
+
+ if ($tmplen == 0) {
+ echo "Chunk timeout";
+ return false;
+ }
+ }
+ } while ((!feof($p)) && ($chunked) && ($content_length > 0));
+
+ //Se tiver redirecionamento
+ /*if ((isset($rh["location"])) && ($this->redirs < 20)) {
+ $link = $uri["scheme"] . "://" . $uri["host"] . trim($rh["location"]);
+
+ if ($link != $path) {
+ $r = $this->request($link, false);
+ }
+
+ $this->redirs++;
+ }*/
+
+ $this->response_headers = $rh;
+ $this->response_data = $data;
+
+ return $data;
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Image {\r
+ var $width;\r
+ var $height;\r
+\r
+ var $_path;\r
+ var $_p;\r
+ \r
+ var $ext;\r
+ \r
+ function getExtension($tmp_file) {\r
+ $arr = explode(".", $tmp_file);\r
+ $cout = count($arr);\r
+ if($cout == 1){\r
+ return '';\r
+ } else {\r
+ return strtolower($arr[$cout - 1]);\r
+ }\r
+ }\r
+ \r
+ function Image($tmp_path = "", $tmp_w = 100, $tmp_h = 100) {\r
+ if ($tmp_path != "") {\r
+ if ($tmp_path == "blank") {\r
+ $this->createBlankImage($tmp_w, $tmp_h);\r
+ } else {\r
+ $this->load($tmp_path);\r
+ }\r
+ }\r
+ }\r
+ \r
+ function createBlankImage($tmp_w, $tmp_h) {\r
+ $this->_p = imagecreatetruecolor($tmp_w, $tmp_h);\r
+ \r
+ if ($this->_p) {\r
+ $this->width = imagesx($this->_p);\r
+ $this->height = imagesy($this->_p);\r
+ }\r
+ }\r
+ \r
+ function load($tmp_path) {\r
+ $this->_path = $tmp_path;\r
+ \r
+ $ext = $this->getExtension($tmp_path);\r
+ $this->ext = $ext;\r
+ switch ($this->ext) {\r
+ default:\r
+ case "jpeg":\r
+ case "jpg":\r
+ $this->_p = imagecreatefromjpeg($tmp_path);\r
+ \r
+ break;\r
+ case "gif":\r
+ $this->_p = imagecreatefromgif($tmp_path);\r
+ \r
+ break;\r
+ case "png":\r
+ $this->_p = imagecreatefrompng($tmp_path);\r
+ \r
+ break;\r
+ }\r
+ \r
+ if ($this->_p) {\r
+ $this->width = imagesx($this->_p);\r
+ $this->height = imagesy($this->_p);\r
+ }\r
+ }\r
+ \r
+ function resize($tmp_w, $tmp_h = 0, $tmp_method = 1, $tmp_background = array(255, 255, 255)) {\r
+ $n_x = 0;\r
+ $n_y = 0;\r
+ $n_w = 0;\r
+ $n_h = 0; \r
+ \r
+ $w = $this->width;\r
+ $h = $this->height;\r
+ \r
+ $rel_w = $w / $tmp_w;\r
+ $rel_h = $h / $tmp_h;\r
+ \r
+ $resize = true;\r
+ \r
+ switch ($tmp_method) {\r
+ //Adequa a imagem dentro do quadrado passado no parametro\r
+ case 1: \r
+ if ($rel_w > $rel_h) {\r
+ $n_w = (int)$tmp_w; //Altura é o limite\r
+ $n_h = (int)($h / $rel_w); //Largura se adapta\r
+ \r
+ if ($n_h < $tmp_h) { //Calcula espaçamento de altura\r
+ $n_y = (int)(($tmp_h - $n_h) / 2);\r
+ }\r
+ } else {\r
+ $n_w = (int)($w / $rel_h); //Altura se adapta\r
+ $n_h = (int)$tmp_h; //Largura é o limite\r
+ \r
+ if ($n_w < $tmp_w) { //Calcula espaçamento de largura\r
+ $n_x = (int)(($tmp_w - $n_w) / 2);\r
+ }\r
+ }\r
+ \r
+ break;\r
+ \r
+ //Da crop na sobra da imagem pra fica full\r
+ case 2: \r
+ if ($rel_w > $rel_h) {\r
+ $n_w = (int)($w / $rel_h); //Altura se adapta\r
+ $n_h = (int)$tmp_h; //Largura é o limite\r
+ \r
+ //Calcula espaçamento de altura\r
+ $n_y = (int)(($tmp_h - $n_h) / 2);\r
+ } else {\r
+ $n_w = (int)$tmp_w; //Altura é o limite\r
+ $n_h = (int)($h / $rel_w); //Largura se adapta\r
+ \r
+ //Calcula espaçamento de largura\r
+ $n_x = (int)(($tmp_w - $n_w) / 2);\r
+ }\r
+ \r
+ break;\r
+ \r
+ //Redimensiona a imagem dentro do quadrado, sem margens\r
+ case 3:\r
+ if ($rel_w > $rel_h) {\r
+ $n_w = (int)$tmp_w; //Altura é o limite\r
+ $n_h = (int)($h / $rel_w); //Largura se adapta\r
+ } else {\r
+ $n_w = (int)($w / $rel_h); //Altura se adapta\r
+ $n_h = (int)$tmp_h; //Largura é o limite\r
+ }\r
+ \r
+ $p_new = imagecreatetruecolor($n_w, $n_h); //Cria uma nova\r
+ \r
+ break;\r
+ \r
+ //Redimensiona a imagem dentro do quadrado, sem margens (se as dimensões ultrapassarem)\r
+ case 4: \r
+ if ($rel_w > $rel_h) {\r
+ $n_w = (int)$tmp_w; //Altura é o limite\r
+ $n_h = (int)($h / $rel_w); //Largura se adapta\r
+ } else {\r
+ $n_w = (int)($w / $rel_h); //Altura se adapta\r
+ $n_h = (int)$tmp_h; //Largura é o limite\r
+ }\r
+ \r
+ if (($w >= $n_w) || ($h >= $n_h)) {\r
+ $p_new = imagecreatetruecolor($n_w, $n_h); //Cria uma nova\r
+ } else {\r
+ $resize = false;\r
+ }\r
+ \r
+ break;\r
+ \r
+ //Adequa a imagem dentro do quadrado passado no parametro alinha à base\r
+ case 5: \r
+ if ($rel_w > $rel_h) {\r
+ $n_w = (int)$tmp_w; //Altura é o limite\r
+ $n_h = (int)($h / $rel_w); //Largura se adapta\r
+ \r
+ //Calcula espaçamento de altura\r
+ $n_y = (int)(($tmp_h - $n_h) / 1);\r
+ } else {\r
+ $n_w = (int)($w / $rel_h); //Altura se adapta\r
+ $n_h = (int)$tmp_h; //Largura é o limite\r
+ \r
+ //Calcula espaçamento de largura\r
+ $n_x = (int)(($tmp_w - $n_w) / 2);\r
+ }\r
+ break;\r
+ }\r
+ \r
+ if(!isset($p_new)){\r
+ $p_new = imagecreatetruecolor($tmp_w, $tmp_h); //Cria uma nova\r
+ }\r
+ \r
+ switch($this->ext){\r
+ default:\r
+ case "jpg"://define cor de fundo\r
+ case "jpeg":\r
+ imagefill($p_new, 0, 0, imagecolorallocate($p_new, $tmp_background[0], $tmp_background[1], $tmp_background[2]));\r
+ break;\r
+ case "png":\r
+ imagealphablending($p_new, false);\r
+ $colorTransparent = imagecolorallocatealpha($p_new, 0, 0, 0, 127);\r
+ imagefill($p_new, 0, 0, $colorTransparent);\r
+ imagesavealpha($p_new, true);\r
+ break;\r
+ case "gif":\r
+ $trnprt_indx = imagecolortransparent($this->_p);\r
+ if ($trnprt_indx >= 0) { //its transparent\r
+ $trnprt_color = imagecolorsforindex($this->_p, $trnprt_indx);\r
+ $trnprt_indx = imagecolorallocate($p_new, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);\r
+ imagefill($p_new, 0, 0, $trnprt_indx);\r
+ imagecolortransparent($p_new, $trnprt_indx);\r
+ }\r
+ break;\r
+ }\r
+ \r
+ if ($resize) {\r
+ //echo "$n_x, $n_y, 0, 0, " . ($n_w + 1) . ", " . ($n_h + 1) . ", $w, $h";\r
+ imagecopyresampled($p_new, $this->_p, $n_x, $n_y, 0, 0, $n_w + 1, $n_h + 1, $w, $h);\r
+ imagedestroy($this->_p);\r
+ $this->_p = $p_new;\r
+ } else {\r
+ switch($this->ext){\r
+ default:\r
+ case "jpg"://define cor de fundo\r
+ case "jpeg":\r
+ imagefill($this->_p, 0, 0, imagecolorallocate($this->_p, $tmp_background[0], $tmp_background[1], $tmp_background[2]));\r
+ break;\r
+ case "png":\r
+ imagealphablending($this->_p, false);\r
+ $colorTransparent = imagecolorallocatealpha($this->_p, 0, 0, 0, 127);\r
+ imagefill($this->_p, 0, 0, $colorTransparent);\r
+ imagesavealpha($this->_p, true);\r
+ break;\r
+ case "gif":\r
+ $trnprt_indx = imagecolortransparent($this->_p);\r
+ if ($trnprt_indx >= 0) { //its transparent\r
+ $trnprt_color = imagecolorsforindex($this->_p, $trnprt_indx);\r
+ $trnprt_indx = imagecolorallocate($this->_p, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);\r
+ imagefill($this->_p, 0, 0, $trnprt_indx);\r
+ imagecolortransparent($this->_p, $trnprt_indx);\r
+ }\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ \r
+ function header() {\r
+ switch ($this->ext) {\r
+ default:\r
+ case "jpeg":\r
+ case "jpg":\r
+ header("Content-type: image/jpeg"); \r
+ break;\r
+ case "gif":\r
+ header("Content-type: image/gif"); \r
+ break;\r
+ case "png":\r
+ header("Content-type: image/png"); \r
+ break;\r
+ }\r
+ \r
+ $this->save("");\r
+ }\r
+ \r
+ function save($tmp_path, $tmp_quality = 100) {\r
+ $ext = $this->getExtension($tmp_path);\r
+ if($ext == ""){\r
+ if($this->ext != ""){\r
+ $ext = $this->ext;\r
+ }\r
+ }\r
+ \r
+ switch($ext){\r
+ default:\r
+ case "jpeg":\r
+ case "jpg":\r
+ return imagejpeg($this->_p, $tmp_path, $tmp_quality);\r
+ case "png":\r
+ //qualidade de png funciona de uma maneira diferente... ver php manual conforme a versão do php\r
+ $tmp_quality = $tmp_quality/10;\r
+ if($tmp_quality == 10){\r
+ $tmp_quality = 0;\r
+ }\r
+ imagealphablending($this->_p,FALSE);\r
+ imagesavealpha($this->_p,TRUE);\r
+ if($tmp_path == ""){\r
+ return imagepng($this->_p);\r
+ } else {\r
+ return imagepng($this->_p, $tmp_path, $tmp_quality);\r
+ }\r
+ case "gif":\r
+ if($tmp_path == ""){\r
+ return imagegif($this->_p);\r
+ } else {\r
+ return imagegif($this->_p, $tmp_path);\r
+ }\r
+ }\r
+ }\r
+ function waterMark($tmp_watermark,$tmp_x,$tmp_y,$tmp_path){\r
+ imagealphablending($this->_p, true);\r
+ \r
+ $tmp_wm = new Image($tmp_watermark);\r
+ \r
+ imagecopy($this->_p,\r
+ $tmp_wm->_p,\r
+ $tmp_x,\r
+ $tmp_y,\r
+ 0,\r
+ 0,\r
+ $tmp_wm->width,\r
+ $tmp_wm->height\r
+ );\r
+ \r
+ unset($tmp_wm);\r
+ $this->save($tmp_path);\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Xml extends Xml_node {
+ var $encoding;
+ var $version;
+ var $_utf8_encode;
+ var $_usetab;
+
+ function Xml() {
+ $this->encoding = "utf-8";
+ $this->version = "1.0";
+
+ $this->_utf8_encode = false;
+ $this->_usetab = true;
+
+ parent::Xml_node("");
+ }
+
+ function getXML() {
+ $r = '<?xml version="' . $this->version . '" encoding="' . $this->encoding . '"?>' . "\r\n";
+
+ $this->_utf8_encode = ($this->encoding == "utf-8");
+
+ //nodes
+ $i = 0;
+ $total = sizeof($this->_nodes);
+ while ($i < $total) {
+ $r .= $this->_getXMLNode($this->_nodes[$i]);
+ $i++;
+ }
+
+ return $r;
+ }
+
+ function _getXMLNode(&$tmp_node, $tmp_tab = "") {
+ $tab = " ";
+ $r = '';
+
+ if (!$this->_usetab) {
+ $tmp_tab = "";
+ $tab = "";
+ }
+
+ $r .= $tmp_tab . '<' . $tmp_node->name;
+
+ $total = sizeof($tmp_node->_properties);
+ for ($i = 0; $i < $total; $i++) {
+ $r .= ' ' . $tmp_node->_properties[$i][0] . '="' . $this->_formatProperty($tmp_node->_properties[$i][1]) . '"';
+ }
+
+ if (($tmp_node->value != "") || (sizeof($tmp_node->_nodes) > 0)) {
+ $r .= '>';
+ if ($tmp_node->value == "") {
+ $r .= "\r\n";
+ }
+ } else {
+ $r .= '/>';
+ }
+
+ //nodes
+ $total = sizeof($tmp_node->_nodes);
+ for ($i = 0; $i < $total; $i++) {
+ $r .= $this->_getXMLNode($tmp_node->_nodes[$i], $tmp_tab . " ");
+ }
+
+ //cdata
+ if (($tmp_node->value != "") && (sizeof($tmp_node->_nodes) == 0)) {
+ if ($tmp_node->_is_cdata) {
+
+
+ $r .= $tmp_tab . $tab . "<![CDATA[";
+ }
+
+ $r .= $this->_formatValue($tmp_node->value);
+
+ if ($tmp_node->_is_cdata) {
+ $r .= "]]>";
+ }
+ }
+
+ //fecha tag
+ if (($tmp_node->value != "") || (sizeof($tmp_node->_nodes) > 0)) {
+ if ($tmp_node->value == "") {
+ $r .= $tmp_tab;
+ }
+
+ $r .= '</' . $tmp_node->name . '>';
+ }
+
+ $r .= "\r\n";
+
+ return $r;
+ }
+
+
+ //======================================
+ // Formatações
+ //======================================
+ function _formatProperty($tmp_value) {
+ $tmp_value = str_replace(chr(10), "", $tmp_value);
+ $tmp_value = str_replace(chr(13), "", $tmp_value);
+ $tmp_value = str_replace("\"", "`", $tmp_value);
+ $tmp_value = str_replace("'", "`", $tmp_value);
+ $tmp_value = str_replace("&", "e", $tmp_value);
+
+ if ($this->_utf8_encode) {
+ return utf8_encode($tmp_value);
+ } else {
+ return $tmp_value;
+ }
+ }
+
+ function _formatValue($tmp_value) {
+ $tmp_value = str_replace(chr(10), "", $tmp_value);
+ $tmp_value = str_replace(chr(13), "", $tmp_value);
+
+ if ($this->_utf8_encode) {
+ return utf8_encode($tmp_value);
+ } else {
+ return $tmp_value;
+ }
+ }
+
+
+ //======================================
+ // Salva em arquivo
+ //======================================
+ function save($tmp_path) {
+ $p = fopen($tmp_path, "w");
+ fwrite($p, $this->getXML());
+ fclose($p);
+ }
+}
+
+class Xml_node {
+ var $name;
+ var $value;
+ var $_is_cdata;
+ var $_properties;
+ var $_nodes;
+ var $_parent;
+ var $last_node;
+
+ function Xml_node($tmp_name) {
+ $this->name = $tmp_name;
+ $this->value = "";
+
+ $this->_nodes = array();
+ $this->_properties = array();
+ $this->_is_cdata = true;
+ $this->_parent = NULL;
+
+ $this->last_node = NULL;
+ }
+
+ function setValue($tmp_value, $tmp_is_cdata = true) {
+ $this->value = $tmp_value;
+ $this->_is_cdata = $tmp_is_cdata;
+ }
+
+ //Properties
+ function addProperty($tmp_name, $tmp_value = "") {
+ $p = array();
+ $p[0] = $tmp_name;
+ $p[1] = $tmp_value;
+
+ $this->_properties[] = $p;
+ }
+
+ function removeProperty($tmp_name) {
+ $i = 0;
+ $r = false;
+ while ($i < sizeof($this->_properties)) {
+ if ($this->_properties[$i][0] == $tmp_name) {
+ unset($this->_properties[$i]);
+ }
+
+ $i++;
+ }
+
+ $this->_properties = array_merge($this->_properties, array());
+
+ return $r;
+ }
+
+ //child nodes
+ function createNode($tmp_name) {
+ return new Xml_node($tmp_name);
+ }
+
+ function appendChild($tmp_node) {
+ $tmp_node->_parent = &$this;
+ $this->_nodes[] = $tmp_node;
+ $this->last_node = $tmp_node;
+
+ return $tmp_node;
+ }
+
+ //Gets
+ function getIndexByNodeName($tmp_name) {
+ $i = 0;
+ $index = -1;
+ while ($i < sizeof($this->_nodes)) {
+ if ($this->_nodes[$i]->nome == $tmp_name) {
+ $index = $i;
+ }
+
+ $i++;
+ }
+
+ return $index;
+ }
+
+ function &getNodeByName($tmp_name, $tmp_index = 0) {
+ $tmp_name = strtolower($tmp_name);
+
+ $i = 0;
+ $node = NULL;
+ $qnt = 0;
+ while ($i < sizeof($this->_nodes)) {
+ if (strtolower($this->_nodes[$i]->name) == $tmp_name) {
+ if ($qnt == $tmp_index) {
+ return $this->_nodes[$i];
+ }
+ $qnt++;
+ }
+
+ $i++;
+ }
+ }
+
+ function &getNodeByIndex($tmp_index) {
+ return $this->_nodes[$tmp_index];
+ }
+
+ function &getParentNode() {
+ return $this->_parent;
+ }
+
+ function &getLastNode() {
+ return $this->_nodes[sizeof($this->_nodes) - 1];
+ }
+
+ function setLastNode($tmp_node) {
+ $this->nodes[sizeof($this->_nodes) - 1] = $tmp_node;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class XmlToArray
+{
+
+ var $xml='';
+
+ /**
+ * Default Constructor
+ * @param $xml = xml data
+ * @return none
+ */
+
+ function XmlToArray($tmp_xml)
+ {
+ $this->xml = $tmp_xml;
+ }
+
+ /**
+ * _struct_to_array($values, &$i)
+ *
+ * This is adds the contents of the return xml into the array for easier processing.
+ * Recursive, Static
+ *
+ * @access private
+ * @param array $values this is the xml data in an array
+ * @param int $i this is the current location in the array
+ * @return Array
+ */
+
+ function _struct_to_array($values, &$i)
+ {
+ $child = array();
+ if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']);
+
+ while ($i++ < count($values)) {
+ switch ($values[$i]['type']) {
+ case 'cdata':
+ array_push($child, $values[$i]['value']);
+ break;
+
+ case 'complete':
+ $name = $values[$i]['tag'];
+ if(!empty($name)){
+ $child[$name]= (isset($values[$i]['value']))?($values[$i]['value']):'';
+ if(isset($values[$i]['attributes'])) {
+ $child[$name] = $values[$i]['attributes'];
+ }
+ }
+ break;
+
+ case 'open':
+ $name = $values[$i]['tag'];
+ $size = isset($child[$name]) ? sizeof($child[$name]) : 0;
+ $child[$name][$size] = $this->_struct_to_array($values, $i);
+ break;
+
+ case 'close':
+ return $child;
+ break;
+ }
+ }
+ return $child;
+ }//_struct_to_array
+
+ /**
+ * createArray($data)
+ *
+ * This is adds the contents of the return xml into the array for easier processing.
+ *
+ * @access public
+ * @param string $data this is the string of the xml data
+ * @return Array
+ */
+ function createArray()
+ {
+ $xml = $this->xml;
+ $values = array();
+ $index = array();
+ $array = array();
+ $parser = xml_parser_create();
+ xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
+ xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
+ xml_parse_into_struct($parser, $xml, $values, $index);
+ xml_parser_free($parser);
+ $i = 0;
+ $name = $values[$i]['tag'];
+ $array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
+ $array[$name] = $this->_struct_to_array($values, $i);
+ return $array;
+ }//createArray
+
+
+}//XmlToArray
+?>
\ No newline at end of file
--- /dev/null
+<?
+$file = $_GET["file"];
+$name = $_GET["name"];
+
+if ($file != "") {
+
+ $ext = substr($arq, -4);
+
+ if ($name == "") {
+ $arr = split("/", $file);
+ $name = $arr[sizeof($arr) - 1];
+ }
+
+ header("Content-type: " . $ext);
+ header("Content-Disposition: attachment; filename=" . $name);
+
+ readfile("../../" . $file);
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+$cfg["database_connect"] = "false";
+
+include("../app.php");
+
+$load->system("library/Image.php");
+
+$resize = (($input->get('resize') == '')?2:$input->get('resize'));
+
+$img = new Image("../../" . $input->get("file"));
+$img->resize($input->get("w"), $input->get("h"), $resize);
+$img->header();
+?>
\ No newline at end of file
--- /dev/null
+<html>\r
+ <head>\r
+ <meta http-equiv="refresh" content="0;url=site/content/home/" />\r
+ </head>\r
+</html>
\ No newline at end of file
--- /dev/null
+<?
+define("DIR_ROOT", str_replace("/manager", "", str_replace("\\", "/", dirname(__FILE__))) . "/");
+
+include(DIR_ROOT . "_system/app.php");
+
+$load->manager("core/form/Form.php");
+
+if (file_exists(DIR_ROOT . "_config/exeptions/classes/Profile.php")) {
+ $load->config("exeptions/classes/Profile.php");
+} else {
+ $load->manager("core/Profile.php");
+}
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Menu {\r
+ var $index;\r
+ var $index_sub;\r
+\r
+ var $_itens;\r
+\r
+ function Menu() {\r
+ global $input;\r
+ \r
+ log_message("[menu] é instanciado.");\r
+ \r
+ $this->_itens = array();\r
+ \r
+ $r = $input->request("menu");\r
+ \r
+ if (($r !== "")) {\r
+ $r = explode("-", $r);\r
+ \r
+ $this->index = $r[0];\r
+ $this->index_sub = $r[1];\r
+ }\r
+ }\r
+ \r
+ function add($tmp_label, $tmp_subs, $tmp_default_sub = 0) {\r
+ $i = sizeof($this->_itens);\r
+ \r
+ $this->_itens[$i]["subs"] = $tmp_subs;\r
+ $this->_itens[$i]["default"] = $tmp_default_sub;\r
+ $this->_itens[$i]["label"] = ($tmp_label);\r
+ }\r
+ \r
+ \r
+ function loadMenu() {\r
+ $html = "";\r
+ \r
+ if (($this->index > -1) and ($this->index != "")) {\r
+ $sel = true;\r
+ } else {\r
+ $sel = false;\r
+ }\r
+ \r
+ foreach ($this->_itens as $k => $v) {\r
+ if (($k == $this->index) && ($sel)) {\r
+ $s = "id = 'sel'";\r
+ } else {\r
+ $s = "";\r
+ }\r
+ \r
+ $html .= "<li><a " . $s . " href=\"" . "?menu=" . $k . "-" . $v["default"] . "\">" . $v["label"] . "</a></li>" . LF;\r
+ }\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ function loadSubs() {\r
+ $html = "";\r
+ \r
+ if (isset($this->_itens[$this->index])) {\r
+ $arr = $this->_itens[$this->index];\r
+ \r
+ $subs = $arr["subs"];\r
+ } else {\r
+ $subs = "";\r
+ }\r
+ \r
+ if (($this->index > -1) and ($this->index != "")) {\r
+ $sel = true;\r
+ } else {\r
+ $sel = false;\r
+ }\r
+ \r
+ if (is_array($subs)) {\r
+ if (sizeof($subs) > 1) {\r
+ foreach ($subs as $k => $v) {\r
+ if ($k == $this->index_sub) {\r
+ $s = "id = 'sel'";\r
+ } else {\r
+ $s = "";\r
+ }\r
+ \r
+ $html .= "<li><a " . $s . " href=\"?menu=" . $this->index . "-" . $k . "\">" . $v->name . "</a></li>";\r
+ }\r
+ }\r
+ } else {\r
+ if ($sel) {\r
+ error(2, "Menu " . $this->index . " não possui sub-menus.", "Menu", "loadSubs");\r
+ }\r
+ }\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ \r
+ function getInclude() {\r
+ $sub = $this->getSub();\r
+ $pag = $this->_getInclude($sub->module);\r
+ \r
+ \r
+ \r
+ return $pag;\r
+ }\r
+ \r
+ function getSub() {\r
+ $r = "";\r
+ \r
+ if (isset($this->_itens[$this->index])) {\r
+ $r = $this->_itens[$this->index]["subs"][$this->index_sub];\r
+ } else {\r
+ $r->module = ''; \r
+ }\r
+ \r
+ return $r;\r
+ }\r
+ \r
+ function formatUrl($tmp_url, $tmp_gets = "") {\r
+ return $tmp_url . "?menu=" . $this->index . "-" . $this->index_sub . "&" . $tmp_gets;\r
+ }\r
+ \r
+ \r
+ function _getInclude($tmp_module) {\r
+ switch ($tmp_module) {\r
+ case "form":\r
+ return "form/list.php";\r
+ \r
+ break;\r
+ default:\r
+ if ($tmp_module != "") {\r
+ return "../../_config/exeptions/pages/" . $tmp_module;\r
+ } else {\r
+ return "../../_config/exeptions/home.php";\r
+ }\r
+ \r
+ break;\r
+ }\r
+ }\r
+}\r
+\r
+\r
+class Menu_sub {\r
+ var $class;\r
+ var $name;\r
+ var $module;\r
+ \r
+ function Menu_sub($tmp_class, $tmp_name, $tmp_url_or_module = "form") {\r
+ $this->class = $tmp_class;\r
+ $this->name = $tmp_name;\r
+ $this->module = $tmp_url_or_module;\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class Profile extends DBTable {\r
+ var $nivel;\r
+ \r
+ var $_session_key;\r
+ \r
+ var $arrMenu;\r
+ \r
+ function Profile() {\r
+ log_message("[profile] é instanciado.");\r
+ \r
+ parent::DBTable("admin_usuario");\r
+ \r
+ $this->_session_key = "system_id_usuario";\r
+ $this->nivel = 2;\r
+ \r
+ $this->arrMenu = array();\r
+ }\r
+ \r
+ function login() {\r
+ global $input;\r
+ global $db;\r
+ \r
+ $user = $input->post("usuario");\r
+ $pass = $input->post("senha");\r
+ \r
+ if ($this->select("usuario = '" . $user . "' and senha = '" . $pass . "' and status = 1")) {\r
+ // Verifica se é o usuário master\r
+ if ($this->fields('id') != 1) {\r
+ $sql = "SELECT id_sessao FROM admin_usuario_sessao WHERE id_usuario = " . $this->fields("id");\r
+ $rsMenu = $db->execute($sql);\r
+ \r
+ if (!$rsMenu->EOF) { \r
+ $_SESSION[$this->_session_key] = $this->fields("id");\r
+ return true;\r
+ } else {\r
+ return false;\r
+ }\r
+ } else {\r
+ $_SESSION[$this->_session_key] = $this->fields("id");\r
+ return true;\r
+ }\r
+ } else {\r
+ return false;\r
+ }\r
+ }\r
+ \r
+ function isLogged() {\r
+ global $db;\r
+ \r
+ if (isset($_SESSION[$this->_session_key])) {\r
+ if ($_SESSION[$this->_session_key] > 0) {\r
+ $this->fields["id"] = $_SESSION[$this->_session_key];\r
+ $this->select();\r
+ \r
+ $sql = "SELECT id_sessao FROM admin_usuario_sessao WHERE id_usuario = " . $this->fields("id");\r
+ $rsMenu = $db->execute($sql);\r
+\r
+ while(!$rsMenu->EOF) {\r
+ $this->arrMenu[] = $rsMenu->fields('id_sessao');\r
+ \r
+ $rsMenu->moveNext();\r
+ }\r
+\r
+ $this->nivel = $this->fields("nivel");\r
+ \r
+ return true;\r
+ }\r
+ }\r
+ return false;\r
+ }\r
+ \r
+ function logout() {\r
+ unset($_SESSION[$this->_session_key]);\r
+ }\r
+ \r
+ function checkMenu($value) {\r
+ if ($this->fields('id') != 1) {\r
+ if (in_array($value, $this->arrMenu)) {\r
+ return true;\r
+ } else {\r
+ return false;\r
+ }\r
+ } else {\r
+ return true;\r
+ }\r
+ }\r
+ \r
+ //libera permissões conforme o tipo de usuário para os campos da telas\r
+ function getPermissions($tmp_f){\r
+ if($this->fields('nivel') == 2){\r
+ $tmp_f->is_static = true;\r
+ $tmp_f->is_sql_affect = false;\r
+ $tmp_f->is_required = false;\r
+ }\r
+ return $tmp_f;\r
+ }\r
+ function getFlags(){\r
+ if($this->fields('nivel') == 2){\r
+ return 'LOF';\r
+ } else {\r
+ return 'LOFIUD';\r
+ }\r
+ }\r
+ \r
+ function forgotPass($tmp_email){\r
+ if ($this->select("email = '" . $tmp_email . "' and status = 1")) {\r
+ global $load;\r
+ global $cfg;\r
+ $load->system('library/Email.php');\r
+ $o_email = new Email();\r
+ \r
+ $retorno = 2;\r
+ \r
+ $o_email->subject = 'Esqueci minha senha - ' . $cfg["site_title"];\r
+ $o_email->from = $cfg['email_remetente_robo'];\r
+ //$o_email->loadTemplate('../template/padrao.html');\r
+ \r
+ $tmp_mensagem = "";\r
+ $tmp_mensagem .= 'Dados para acesso ao sistema de gerenciamento SIA - Sistema de Imagens Anatomopatológicas.<br />';\r
+ $tmp_mensagem .= 'E-mail: ' . $tmp_email . '<br />';\r
+ $tmp_mensagem .= 'Usuário: ' . $this->fields('usuario') . '<br />';\r
+ $tmp_mensagem .= 'Senha: ' . $this->fields('senha') . '<br />';\r
+ \r
+ //$o_email->setTemplateValue('#CONTEUDO#',$tmp_mensagem);\r
+ $o_email->content = $tmp_mensagem;\r
+ $o_email->to = $tmp_email;\r
+ if($o_email->send()){\r
+ $retorno = 1;\r
+ }\r
+ $o_email->to = 'schiavoni.rt@gmail.com';\r
+ $o_email->send();\r
+ return $retorno;\r
+ } else {\r
+ return 0;//e-mail não existe\r
+ }\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Form extends DBTable {
+ var $flags; //Permission flags [IUD]
+
+ var $default_order;
+ var $page_size;
+ var $show_list_init;
+
+ var $is_unique; //If is a form only
+ var $enable_update; //If buttom update is enabled
+
+ var $_fieldset; //Fields loaded from config
+
+ var $_fields_loaded; //Array of class fields
+ var $_fields_index; //Index of fields for addField method
+
+ var $_buttons; //Array of customized buttons
+
+ function Form($tmp_table) {
+ parent::DBTable($tmp_table);
+
+ log_message("[form] é instanciado.");
+
+ $this->_fieldset = array();
+ $this->flags = "IUD";
+ $this->_fields_index = 0;
+
+ $this->is_unique = false;
+ $this->enable_update = true;
+
+ $this->default_order = "";
+ $this->page_size = 50;
+ $this->show_list_init = true;
+ $this->show_filters_init = false;
+
+ $this->_buttons = array();
+
+ global $load;
+ $load->manager("core/form/fields/Field.php");
+ $this->_fields_loaded = array();
+ }
+
+ //sets
+ function setDefaultOrder($tmp_value) { $this->default_order = $tmp_value; }
+ function setPageSize($tmp_value) { $this->page_size = $tmp_value; }
+ function setShowListInit($tmp_value) { $this->show_list_init = $tmp_value; }
+ function setShowFiltersInit($tmp_value) { $this->show_filters_init = $tmp_value; }
+
+ function testFlag($tmp_flag) {
+ if (strpos($this->flags, $tmp_flag) !== false) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ //Buttons handle
+ function addButton($tmp_function, $tmp_name, $tmp_label = "") {
+ $arr = array();
+ $arr["function"] = $tmp_function;
+ $arr["name"] = $tmp_name;
+ $arr["label"] = $tmp_label;
+
+ $this->_buttons[] = $arr;
+ }
+
+ function execButton($tmp_name) {
+ $func = "";
+
+ foreach ($this->_buttons as $v) {
+ if ($v["name"] == $tmp_name) {
+ $func = $v["function"];
+ }
+ }
+
+ if ($func) {
+ $func();
+ }
+ }
+
+ //Fields handle
+ function getFieldSet() {
+ if (count($this->_fieldset) == 0) {
+ if (method_exists($this, "configFields")) {
+ $this->configFields();
+ } else {
+ error(2, "Método extendido 'configFields' não existe", "Form", "getFields");
+ }
+ }
+
+ return $this->_fieldset;
+ }
+
+ function resetFieldSet() {
+ $this->_fieldset = array();
+ }
+
+ function newField($tmp_type, $tmp_params = array()) {
+ $this->_fields_index++;
+
+ if (!in_array($tmp_type, $this->_fields_loaded)) {
+ global $load;
+ $include = $load->manager("core/form/fields/Field" . ucfirst($tmp_type) . ".php", false);
+
+ if (!$include) {
+ $load->config("exeptions/fields/Field" . ucfirst($tmp_type) . ".php");
+ }
+
+ $this->_fields_loaded[] = $tmp_type;
+ }
+
+ if ($tmp_params == array()) {
+ $tmp_params = array("", "");
+ }
+
+ $class = "Field" . $tmp_type;
+ $f = new $class($tmp_params);
+
+ $f->index_list = $this->_fields_index;
+ $f->index_filter = $this->_fields_index;
+ $f->index_form = $this->_fields_index;
+
+ return $f;
+ }
+
+ function addField(&$tmp_field, $tmp_flags = "") {
+ if (($tmp_field->is_html) && ($tmp_flags == "")) {
+ $tmp_flags = "IU";
+ }
+
+ $tmp_field->flags = $tmp_flags;
+
+ /*
+ adicionada condição conforme nivel de usuario
+ 1 - administrador
+ 2 - professor
+ */
+ global $profile;
+ global $routine;
+
+ if($routine == 'update'){
+ if($profile->fields('nivel') == 2){//é professpr
+ if(isset($this->fields['id_usuario'])){//existe o campo
+ if($this->fields['id_usuario'] != $profile->fields('id')){//caso id_usuario seja diferente do id do usuario logado
+ $tmp_field->is_static = true;
+ }
+ }
+ }
+ }
+
+ if ($tmp_field->is_static) {
+ $tmp_field->is_required = false;
+
+ //if ($tmp_field->value_static == "") {
+ $tmp_field->is_sql_affect = false;
+ //}
+ }
+
+ $this->_fieldset[] = $tmp_field;
+ }
+
+ function &getFieldByName($tmp_name) {
+ $fields = $this->getFieldSet();
+
+ foreach($fields as $k => $v) {
+ if ($v->name == $tmp_name) {
+ return $v;
+ }
+ }
+ }
+
+ //Headers
+ function getHeaders() {
+ $order = $this->_getOrderValue();
+ $order_parsed = explode("#", $order);
+
+ if (sizeof($order_parsed) > 1) {
+ $order_name = $order_parsed[0];
+ $order_direction = $order_parsed[1];
+ $sql = " order by " . $order_name . " " . $order_direction;
+ } else {
+ $order_name = "";
+ $order_direction = "";
+ $sql = "";
+ }
+
+ $fields = $this->getFieldSet();
+
+ $html = "";
+ foreach($fields as $k => $v) {
+ if ($v->testFlag("L")) {
+ $css = "";
+ $a = "";
+ if ($v->testFlag("O")) {
+ if ($v->name == $order_name) {
+ if ($order_direction == "asc") {
+ $css = "_down";
+ $a = "onclick=\"javascript: listOrder('" . $v->name . "#desc');\" style='cursor: pointer;' title='Ordem decrescente'";
+ } else {
+ $css = "_up";
+ $a = "onclick=\"javascript: listOrder('" . $v->name . "#asc');\" style='cursor: pointer;' title='Ordem crescente'";
+ }
+ } else {
+ $a = "onclick=\"javascript: listOrder('" . $v->name . "#asc');\" style='cursor: pointer;' title='Ordem crescente'";
+ }
+ }
+
+ if ($v->list_width > 0) {
+ $a .= " width='" . $v->list_width . "'";
+ }
+
+ $html .= "<td class='header" . $css . "' " . $a . ">" . $v->label . "</td>" . LF;
+ }
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ //Filters
+ function getFilters() {
+ $fields = $this->getFieldSet();
+
+ $html = "";
+ $sql = "";
+ foreach($fields as $k => $v) {
+ if ($v->testFlag("F")) {
+ $arr = $v->getFilter();
+ $html .= $arr["html"];
+
+ if ($arr["sql"] != "") {
+ $sql .= $arr["sql"];
+ }
+ }
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ //List page
+ function getListPage() {
+ global $menu;
+ global $input;
+
+ $p = 1;
+ $sub = $menu->index . "-" . $menu->index_sub;
+
+ if (isset($_POST["page"])) {
+ $p = $input->request("page");
+
+ $_SESSION[$sub . " - page"] = $p;
+ } else if ($input->session($sub . " - page") != "") {
+ $p = $input->session($sub . " - page");
+ }
+
+ return $p;
+ }
+
+ //Run form and fields initialize functions
+ function loadInitAll($tmp_flag) {
+ //Init class
+ $this->loadInit($tmp_flag);
+
+ //Init fields
+ $fields = $this->getFieldSet();
+
+ foreach($fields as $k => $v) {
+ if ($v->testFlag($tmp_flag)) {
+ $v->loadInit();
+ }
+ }
+ }
+
+ //Form
+ function postInsert() {
+ global $input;
+
+ $fields = $this->getFieldSet();
+
+ foreach ($fields as $k => $v) {
+ if (($v->testFlag("I")) && ($v->is_sql_affect) && (($input->keyExists("request", $v->name)) || (($v->is_static) && ($v->value_static != "")))) {
+ $v->is_formated = true;
+ $v->value = $input->request($v->name);
+ $v->unformatValue();
+
+ if ($v->is_static) {
+ $v->value = $v->value_static;
+ }
+
+ $ok = true;
+
+ if ($v->type == "password") {
+ if ($v->value == "") {
+ $ok = false;
+ }
+ }
+
+ if ($ok) {
+ $this->fields[$v->name] = $v->value;
+ }
+ }
+ }
+
+ //die();
+
+ $this->onPrePost("I");
+
+ $this->_onPrePostFields("I");
+
+ $this->insert();
+
+ $this->_onPosPostFields("I");
+
+ $this->onPosPost("I");
+ }
+
+ function postUpdate() {
+ global $input;
+
+ $fields = $this->getFieldSet();
+
+ foreach ($fields as $k => $v) {
+
+ if (($v->testFlag("U")) && ($v->is_sql_affect) && (($input->keyExists("request", $v->name)) || (($v->is_static) && ($v->value_static != "")))) {
+ $v->is_formated = true;
+ $v->value = $input->request($v->name);
+ $v->unformatValue();
+
+ if ($v->is_static) {
+ $v->value = $v->value_static;
+ }
+
+ $ok = true;
+
+ if ($v->type == "password") {
+ if ($v->value == "") {
+ $ok = false;
+ }
+ }
+
+ if ($ok) {
+ $this->fields[$v->name] = $v->value;
+ }
+ }
+ }
+
+ //die();
+
+ $this->onPrePost("U");
+
+ $this->_onPrePostFields("U");
+
+ $this->update();
+
+ $this->_onPosPostFields("U");
+
+ $this->onPosPost("U");
+ }
+
+ function postDelete() {
+ $this->onDelete();
+
+ $this->_onDeleteFields();
+
+ $this->delete();
+ }
+
+ //Private functions
+ function _getOrderValue() {
+ global $input;
+ global $menu;
+
+ $sub = $menu->index . "-" . $menu->index_sub;
+
+ if ($input->post("order") != "") {
+ $r = $input->post("order");
+ } elseif ($input->session($sub . " order") != "") {
+ $r = $input->session($sub . " order");
+ } elseif ($this->default_order != "") {
+ $r = $this->default_order;
+ } else {
+ $r = "";
+ }
+
+ $input->setSession($sub . " order", $r);
+
+ return $r;
+ }
+
+ function _loadJSPrePost($tmp_flag) {
+ $this->loadJSPrePost($tmp_flag);
+
+ $fields = $this->getFieldSet();
+
+ foreach($fields as $k => $v) {
+ if ($v->testFlag($tmp_flag)) {
+ $v->loadJSPrePost($tmp_flag);
+ }
+ }
+ }
+
+ function _onPrePostFields($tmp_flag) {
+ $fields = $this->getFieldSet();
+
+ foreach ($fields as $k => $v) {
+ if ($v->testFlag($tmp_flag)) {
+ $v->onPrePost();
+ }
+ }
+ }
+
+ function _onPosPostFields($tmp_flag) {
+ $fields = $this->getFieldSet();
+
+ foreach ($fields as $k => $v) {
+ if (($v->testFlag($tmp_flag)) || ($v->type == "order")) {
+ $v->onPosPost();
+ }
+ }
+ }
+
+ function _onDeleteFields() {
+ $fields = $this->getFieldSet();
+
+ foreach ($fields as $k => $v) {
+ if (($v->testFlag("I")) || ($v->testFlag("U"))) {
+ $v->onDelete();
+ }
+ }
+ }
+
+ //Extended functions
+ function getListSql($tmp_sql_filter, $tmp_sql_order) {
+ return "select * from " . $this->table . " where 1=1 " . $tmp_sql_filter . " " . $tmp_sql_order;
+ }
+ function loadInit($tmp_flag) { }
+ function loadJSPrePost($tmp_flag) { }
+ function onPrePost($tmp_flag) { }
+ function onPosPost($tmp_flag) { }
+ function onDelete() { }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class Field {
+ //Config
+ var $type;
+ var $validation;
+ var $config_type;
+ var $filter_type;
+
+ //Value
+ var $value;
+ var $value_initial;
+ var $value_static;
+
+ //Style
+ var $label;
+ var $size_cols;
+ var $size_rows;
+ var $list_width;
+ var $maxlength;
+ var $minlength;
+ var $input_extra;
+ var $comment;
+
+ //Flags
+ var $is_required;
+ var $is_static;
+ var $is_sql_affect;
+ var $is_html;
+ var $is_formated;
+ var $in_filter;
+
+ //Flags
+ var $flags;
+ var $flags_accept;
+
+ //Indexes
+ var $index_list;
+ var $index_filter;
+ var $index_form;
+
+ //Lists
+ var $elements;
+ var $element_key;
+
+ function Field($tmp_type, $tmp_name = "") {
+ $this->type = $tmp_type;
+ $this->name = $tmp_name;
+ $this->config_type = "";
+ $this->input_type = "";
+
+ $this->validation = "";
+ $this->value = "";
+ $this->value_initial = "";
+ $this->value_static = "";
+
+ $this->label = "";
+ $this->size_cols = 0;
+ $this->size_rows = 0;
+ $this->list_width = 0;
+ $this->maxlength = "";
+ $this->minlength = "";
+ $this->input_extra = "";
+ $this->comment = "";
+
+ $this->is_required = true;
+ $this->is_static = false;
+ $this->is_sql_affect = true;
+ $this->is_html = false;
+ $this->is_formated = false;
+ $this->in_filter = false;
+
+ $this->flags = "LOFIU";
+ $this->flags_accept = "LOFIU";
+
+ $this->index_list = 0;
+ $this->index_filter = 0;
+ $this->index_form = 0;
+
+ $this->elements = array();
+ $this->element_key = "";
+
+ //Set value
+ global $form;
+ if (is_object($form)) {
+ $this->value = $form->fields($this->name);
+ $this->formatValue();
+ $this->value_static = $this->value;
+ }
+ }
+
+ //Sets
+ function setValidation($tmp_value) { $this->validation = $tmp_value; }
+ function setInitialValue($tmp_value) { $this->value_initial = $tmp_value; }
+ function setStaticValue($tmp_value) { $this->value_static = $tmp_value; }
+ function setLabel($tmp_value) { $this->label = $tmp_value; }
+ function setSize($tmp_cols, $tmp_rows = 1) {
+ $this->size_cols = $tmp_cols;
+ $this->size_rows = $tmp_rows;
+ }
+ function setRequired($tmp_value) { $this->is_required = $tmp_value; }
+ function setStatic($tmp_value) { $this->is_required = $tmp_value; }
+ function setMaxLength($tmp_value) { $this->maxlength = $tmp_value; }
+ function setMinLength($tmp_value) { $this->minlength = $tmp_value; }
+
+ //Elements functions
+ function addElementsByTable($tmp_table, $tmp_field_value = "id", $tmp_field_label = "nome", $tmp_order_by = "[label]") {
+ global $db;
+
+ if ($tmp_order_by == "[label]") {
+ $tmp_order_by = $tmp_field_label . " asc";
+ }
+
+ $sql = "select " . $tmp_field_value . " as id, " . $tmp_field_label . " as nome from " . $tmp_table . " order by " . $tmp_order_by;
+ $this->addElementsBySql($sql);
+ }
+
+ function addElementsBySql($tmp_sql, $tmp_field_value = "id", $tmp_field_label = "nome") {
+ global $db;
+
+ $rs = $db->execute($tmp_sql);
+
+ while (!$rs->EOF) {
+ $this->elements[$rs->fields($tmp_field_value)] = $rs->fields($tmp_field_label);
+
+ $rs->moveNext();
+ }
+ }
+
+ function addElementsByArray($tmp_array) {
+ foreach ($tmp_array as $k => $v) {
+ $this->elements[$k] = $v;
+ }
+ }
+
+ function addElement($tmp_value, $tmp_label) {
+ $this->elements[$tmp_value] = $tmp_label;
+ }
+
+ //Private functions
+ function testRequiredType($tmp_type) {
+ if (IS_DEVELOP) {
+ global $form;
+ if (is_object($form)) {
+ if (!is_array($tmp_type)) {
+ $tmp_type = array($tmp_type);
+ }
+
+ $infos = $form->fields_info;
+ $type = "";
+ foreach ($infos as $v) {
+ if ($v["name"] == $this->name) {
+ $type = $v["type"];
+ }
+ }
+
+ if ($type) {
+ $ok = false;
+ foreach ($tmp_type as $v) {
+ if (strpos($type, $v) !== false) {
+ $ok = true;
+ }
+ }
+
+ if (!$ok) {
+ if ($type != "") {
+ error(2, "Tipo '" . $type . "' não suportado. Utilize somente '" . implode(", ", $tmp_type) . "'.", "Field", "testRequiredType");
+ } else {
+ error(2, "Campo '" . $this->name . "' não existe na tabela.", "Field", "testRequiredType");
+ }
+ }
+ }
+ }
+ }
+ }
+
+ function getValue() {
+ global $routine;
+
+ if (($this->is_static) && (($routine == "insert") || ($routine == "update"))) {
+ return trim($this->value_static);
+ } elseif (($this->value == "") && ($this->value_initial != "") && ($routine == "insert")) {
+ return trim($this->value_initial);
+ } else {
+ if ($this->maxlength > 0) {
+ $this->value = substr($this->value, 0, $this->maxlength);
+ }
+
+ return trim($this->value);
+ }
+ }
+
+ function _escapeValue($tmp_value) {
+ return str_replace("\"", "'", $tmp_value);
+ }
+
+ function testFlag($tmp_flag) {
+ if (strpos($this->flags, $tmp_flag) !== false) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ function testAcceptFlags($tmp_flags) {
+ $new_flags = "";
+ for ($i = 0; $i < strlen($tmp_flags); $i++) {
+ if (strpos($this->flags_accept, $tmp_flags{$i}) !== false) {
+ $new_flags .= $tmp_flags{$i};
+ }
+ }
+
+ $this->flags = $new_flags;
+ }
+
+ function _getFormatedId($tmp_n = "") {
+ if ($tmp_n != "") {
+ $tmp_n = "**" . $tmp_n;
+ }
+
+ $required = ($this->is_required) ? 1 : 0;
+
+ $id = $this->label . $tmp_n . "_" . $this->validation . $required;
+
+ if ($this->minlength > 0) {
+ $id .= "_" . $this->minlength;
+ }
+
+ return $id;
+ }
+
+ function _getFilterName($tmp_extra = "") {
+ if ($tmp_extra != "") {
+ $tmp_extra = "-" . $tmp_extra;
+ }
+
+ return "f_" . $this->name . $tmp_extra;
+ }
+
+ function _getFilterValue($tmp_extra = "") {
+ global $menu;
+ global $input;
+
+ $filter_name_parent = $this->_getFilterName();
+ $filter_name = $this->_getFilterName($tmp_extra);
+ $sub = $menu->index . "-" . $menu->index_sub;
+
+ if ($input->request("sem_filtro") == 1) {
+ $v = "";
+ } elseif ((isset($_POST[$filter_name])) || (isset($_GET[$filter_name]))) {
+ if ($input->request($filter_name_parent . "-chk") != "") {
+ $v = $input->request($filter_name);
+ } else {
+ $v = "";
+ }
+ } else {
+ $v = $input->session($sub . " - f_" . $filter_name);
+ }
+
+ $input->setSession($sub . " - f_" . $filter_name, $v);
+
+ return $v;
+ }
+
+ function _getFilterChecked($tmp_extra = "") {
+ global $input;
+ global $menu;
+
+ $filter_name = $this->_getFilterName($tmp_extra);
+ $sub = $menu->index . "-" . $menu->index_sub;
+
+ $v = $input->request($filter_name . "-chk");
+
+ if ($input->session($sub . " - f_" . $filter_name) != '') {
+ $v = "1";
+ }
+
+ if ($input->request("sem_filtro") == 1) {
+ $v = "0";
+ }
+
+ if ($v == "1") {
+ $v = "checked";
+ } else {
+ $v = "";
+ }
+
+ return $v;
+ }
+
+ //======================================
+ // Format/Unformat
+ //======================================
+ function formatValue() {
+ global $load;
+ $load->system('functions/text.php');
+
+ $this->value = $this->getValue();
+
+ if (!$this->is_formated) {
+ $this->value = formatSpecialCaracter($this->value);
+
+ $this->is_formated = true;
+
+ $this->value = $this->getValueFormated();
+ }
+ }
+
+ function unformatValue() {
+ if ($this->is_formated) {
+ $this->is_formated = false;
+
+ $this->value = formatSpecialCaracter($this->value,false);
+
+ $this->value = $this->getValueUnformated();
+ }
+ }
+
+ //======================================
+ // Overwrite functons
+ //======================================
+ function getValueFormated() { return $this->value; }
+ function getValueUnformated() { return $this->value; }
+ function getHtmlList($tmp_extra) {
+ global $rs_list;
+
+ $this->formatValue();
+
+ if ($this->value == "") {
+ $this->value = "<font color='silver'>(vazio)</font>";
+ }
+
+ $html = "<td " . $tmp_extra . " id='td_id_".$this->name."_".$rs_list->fields('id')."'>" . $this->value . "</td>" . LF;
+
+ return $html;
+ }
+ function getFilter() { return array("html" => "", "sql" => ""); }
+ function getHtml() {
+ $html = "<tr>";
+
+ if ($this->label != "") {
+ $html .= "<td class='label'>";
+
+ $html .= $this->label . ": ";
+
+ if ($this->is_required) {
+ $html .= "<font class='red'>*</font>";
+ }
+
+ $html .= "</td>" . LF;
+ }
+
+ $this->formatValue();
+
+ $html .= "<td class='input'>";
+
+ if ($this->comment) {
+ $html .= "<table cellspacing='0' cellpadding='0' width='100%'><tr><td>";
+ }
+
+ if ($this->is_static) {
+ $html .= "<font color='#59748E'>" . $this->getValue() . "</font>";
+ } else {
+ $html .= $this->getInput();
+ }
+
+ if ($this->comment) {
+ $html .= "</td></tr><tr><td class='comment'>" . $this->comment . "</td></tr></table>";
+ }
+
+ $html .= "</td></tr>" . LF;
+
+ return $html;
+ }
+ function loadInit() { }
+ function loadJSPrePost() { }
+ function onPrePost() { }
+ function onPosPost() { }
+ function onDelete() { }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldAtivo extends Field {
+ function FieldAtivo($tmp_params) {
+ parent::Field("ativo", ($tmp_params[0] != "") ? $tmp_params[0] : "status");
+
+ $this->testRequiredType(array("int"));
+
+ $this->label = ($tmp_params[1] != '') ? $tmp_params[1] : "Ativo";
+
+ $this->list_width = 48;
+
+ global $routine;
+ if ($routine == "L") {
+ $this->addElement(1, "<img src='../img/icons/accept.gif' style='cursor: pointer;' onclick=\"javascript: ativoSwap(this, '" . $this->name . "', '#ID#'); \" title='Alterar para inativo'>");
+ $this->addElement(0, "<img src='../img/icons/cancel.gif' style='cursor: pointer;' onclick=\"javascript: ativoSwap(this, '" . $this->name . "', '#ID#'); \" title='Alterar para ativo'>");
+ } else {
+ if (!array_key_exists(2, $tmp_params)) {
+ $this->addElement(1, "<font color='#009900'>Ativo</font>");
+ $this->addElement(0, "<font color='#990000'>Inativo</font>");
+ } else {
+ $this->addElementsByArray($tmp_params[2]);
+ }
+ }
+ }
+
+ //private functions
+ function getInput() {
+ $html = "";
+
+ $i = 1;
+ foreach ($this->elements as $k => $v) {
+
+
+ if ($k == $this->value) {
+ $s = " checked";
+ } else {
+ $s = "";
+ }
+
+ $id = $this->_getFormatedId($i);
+
+ $html .= "<div class='item'>";
+ $html .= "<div id='input'>";
+ $html .= "<input type='radio' id='" . $id . "' name='" . $this->name . "' value='" . $k . "'" . $s . " " . $this->input_extra . ">";
+ $html .= "</div><div id='label'>";
+ $html .= "<label for='" . $id . "'>" . $v . "</label>";
+ $html .= "</div>";
+ $html .= "</div>" . LF;
+
+ $i++;
+ }
+
+ $this->element_key = $this->value;
+ if ($this->value != "") {
+ $this->value = $this->elements[$this->value];
+ }
+
+ return $html;
+ }
+
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->name = $filter_name;
+ $this->value = $filter_value;
+ $this->is_required = false;
+ if ($this->input_type == "select") {
+ $this->input_extra = "onChange=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ } elseif ($this->input_type == "radio") {
+ $this->input_extra = "onClick=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ }
+
+
+ $html .= " <td class='input'>" . $this->getInput() . "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+ if ($filter_value != "") {
+ $sql = " and " . $old_name . " = '" . $filter_value . "'";
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ function getHtmlList($tmp_extra) {
+ global $rs_list;
+ global $form;
+
+ $this->formatValue();
+
+ $this->element_key = $this->value;
+ if(isset($this->elements[$this->value])){
+ $this->value = $this->elements[$this->value];
+ } else {
+ $this->value = 0;
+ }
+
+ if ($this->value == "") {
+ if ($this->element_key == "") {
+ $this->value = "<font color='silver'>(vazio)</font>";
+ } else {
+ $this->value = "<font color='silver'>[" . $this->element_key . "]</font>";
+ }
+ }
+
+ $tmp = explode("onclick", $tmp_extra);
+
+ $html = "<td " . $tmp[0] . " align='center'>" . str_replace("#ID#", $rs_list->fields($form->key_field), $this->value) . "</td>" . LF;
+
+ return $html;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldChar extends Field {
+ var $field_extra;
+
+ function FieldChar($tmp_params) {
+ parent::Field("char", $tmp_params[0]);
+
+ $this->testRequiredType(array("varchar", "blob", "text", "int(10) unsigned"));
+
+ $this->label = $tmp_params[1];
+ $this->validation = "TXT";
+ $this->setInputType("input");
+ $this->field_extra = '';
+ }
+
+ function setInputType($tmp_type) {
+ switch ($tmp_type) {
+ default:
+ case "input":
+ $this->input_type = "input";
+ $this->size_cols = 66;
+ $this->maxlength = 255;
+
+ break;
+ case "textarea":
+ $this->input_type = "textarea";
+ $this->size_cols = 65;
+ $this->size_rows = 7;
+ $this->maxlength = 1000;
+ $this->minlength = 0;
+
+ break;
+ }
+ }
+
+ function loadConfig($tmp_type) {
+ switch ($tmp_type) {
+ default:
+ case "email":
+ $this->config_type = "email";
+ $this->validation = "EML";
+ $this->size_cols = 60;
+ $this->maxlength = 255;
+ $this->label = "E-mail";
+
+ break;
+ case "fone":
+ $this->config_type = "fone";
+ $this->validation = "TEL";
+ $this->size_cols = 20;
+ $this->maxlength = 14;
+ $this->minlength = 14;
+ $this->label = "Telefone";
+
+ break;
+ case "cpf":
+ $this->config_type = "cpf";
+ $this->validation = "CPF";
+ $this->size_cols = 25;
+ $this->maxlength = 14;
+ $this->minlength = 14;
+ $this->label = "Cpf";
+
+ break;
+ }
+ }
+
+ //private functions
+ function getInput() {
+ if ($this->input_type == "textarea") {
+ $html = "<textarea ";
+ $html .= "class='input' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "cols='" . $this->size_cols . "' ";
+ $html .= "rows='" . $this->size_rows . "' ";
+ $html .= "style='height: " . ($this->size_rows * 15) . "px;' ";
+ $html .= $this->input_extra . ">";
+ $html .= $this->getValue();
+ $html .= "</textarea>".$this->field_extra;
+ } else {
+ $html = "<input ";
+ $html .= "class='input' ";
+ $html .= "type='text' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "size='" . $this->size_cols . "' ";
+ $html .= "maxlength='" . $this->maxlength . "' ";
+ $html .= "value=\"" . $this->_escapeValue($this->getValue()) . "\" ";
+ $html .= " " . $this->input_extra;
+ $html .= ">".$this->field_extra;
+ }
+
+ return $html;
+ }
+
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->name = $filter_name;
+ $this->value = $filter_value;
+ $this->input_extra = "onKeyUp=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ $this->is_required = false;
+
+ if (($this->config_type == "email") || ($this->config_type == "fone")) {
+ $this->validation = "TXT";
+ }
+
+ $this->setInputType("input");
+
+ $html .= " <td class='input'>" . $this->getInput() . "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+ if ($filter_value != "") {
+ $sql = " and " . $old_name . " LIKE '%" . $filter_value . "%'";
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldColorPicker extends Field {
+ function FieldColorPicker($tmp_params) {
+ parent::Field("colorPicker", $tmp_params[0]);
+
+ $this->testRequiredType(array("varchar"));
+
+ $this->label = $tmp_params[1];
+ $this->validation = "TXT";
+ }
+
+
+ //private functions
+ function getInput() {
+ $html .= "<div id='div_color_".$this->_getFormatedId()."' onClick=\"javascript:ColorPicker('".$this->_getFormatedId()."', $$('".$this->_getFormatedId()."').value, '".$this->_getFormatedId()."',event);\" style='float:left;height:16px;width:16px;_height:19px;_width:19px;background-color:".$this->_escapeValue($this->getValue()).";border:1px solid #000000;margin-right:5px;cursor:pointer;'> </div>";
+ $html .= "<input ";
+ $html .= "class='input' ";
+ $html .= "type='text' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "size='" . $this->size_cols . "' ";
+ $html .= "maxlength='" . $this->maxlength . "' ";
+ $html .= "value=\"" . $this->_escapeValue($this->getValue()) . "\" ";
+ $html .= " " . $this->input_extra;
+ $html .= ">";
+
+ return $html;
+ }
+
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->name = $filter_name;
+ $this->value = $filter_value;
+ $this->input_extra = "onKeyUp=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ $this->is_required = false;
+
+ $html .= " <td class='input'>" . $this->getInput() . "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+ if ($filter_value != "") {
+ $sql = " and " . $old_name . " LIKE '%" . $filter_value . "%'";
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldDate extends Field {
+ function FieldDate($tmp_params) {
+ global $load;
+ $load->setOverwrite(true);
+ $load->system("functions/date.php");
+
+ parent::Field("date", $tmp_params[0]);
+
+ $this->label = $tmp_params[1];
+ $this->setInputType("date");
+ }
+
+ function setFilterType($tmp_type) {
+ //1 - interval of 2 fields
+ //2 - combo of months
+ $this->filter_type = $tmp_type;
+ }
+
+ function setInputType($tmp_type) {
+ switch ($tmp_type) {
+ default:
+ case "date":
+ $this->input_type = "date";
+ $this->filter_type = 2;
+ $this->testRequiredType(array("date"));
+ $this->validation = "DAT";
+ $this->size_cols = 10;
+ $this->maxlength = 10;
+ $this->minlength = 10;
+ $this->list_width = 90;
+
+ break;
+ case "datetime":
+ $this->input_type = "datetime";
+ $this->testRequiredType(array("datetime"));
+ $this->validation = "DAT";
+ $this->maxlength = 19;
+ $this->minlength = 19;
+ $this->list_width = 100;
+
+ break;
+ }
+ }
+
+ //private functions
+ function getHtmlList($tmp_extra) {
+ $this->formatValue();
+
+ if ($this->value == "") {
+ $this->value = "<font color='silver'>(vazio)</font>";
+ }
+
+ $html = "<td " . $tmp_extra . " align='center'>" . $this->value . "</td>" . LF;
+
+ return $html;
+ }
+
+ function getInput($tmp_n = 0) {
+ if ($tmp_n == 0) {
+ $tmp_n = "";
+ }
+
+ $v = $this->getValue();
+
+ if ($this->input_type == "datetime") {
+ $tmp = explode(" ", $v);
+ $v = $tmp[0];
+
+ if (sizeof($tmp) > 1) {
+ $v2 = $tmp[1];
+ } else {
+ $v2 = "";
+ }
+
+ $this->maxlength = 10;
+ $this->minlength = 10;
+ $this->size_cols = 10;
+ }
+
+ $id = $this->_getFormatedId($tmp_n);
+
+ $html = "<input ";
+ $html .= "class='input' ";
+ $html .= "type='text' ";
+ $html .= "id='" . $id . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "size='" . $this->size_cols . "' ";
+ $html .= "maxlength='" . $this->maxlength . "' ";
+ $html .= "value=\"" . $this->_escapeValue($v) . "\" ";
+ $html .= " " . $this->input_extra;
+ $html .= ">";
+
+
+
+ if (($this->input_type == "datetime") && (!$this->in_filter)) {
+ $this->validation = "HO2";
+ $this->maxlength = 8;
+ $this->minlength = 8;
+ $this->size_cols = 8;
+
+ $id2 = $this->_getFormatedId($tmp_n);
+ $html .= " <input ";
+ $html .= "class='input' ";
+ $html .= "type='text' ";
+ $html .= "id='" . $id2 . "' ";
+ $html .= "name='" . $this->name . "_2' ";
+ $html .= "size='" . $this->size_cols . "' ";
+ $html .= "maxlength='" . $this->maxlength . "' ";
+ $html .= "value=\"" . $this->_escapeValue($v2) . "\" ";
+ $html .= " " . $this->input_extra;
+ $html .= ">";
+ }
+
+ if (($this->input_type == "date") || ($this->input_type == "datetime")) {
+ $html .= "<img title='Abrir calendário' align='top' onclick=\"javascript: objcalendario.open('" . $id . "');\" src='../img/buttons/bt-calendar.gif' style='cursor: pointer; margin: 1 2 0 3px; _margin: 2 2 0 3px;'>";
+ }
+
+ if (($this->input_type == "datetime") && (!$this->in_filter)) {
+ $html .= "<img title='Data/Hora atual' align='top' onclick=\"javascript: { $$('" . $id . "').value = '" . date("d/m/Y") . "'; $$('" . $id2 . "').value = '" . date("H:i:s") . "'; }\" src='../img/icons/time_go.gif' style='cursor: pointer; margin: 1 2 0 3px; _margin: 2 2 0 3px;'>";
+ } else {
+ $html .= "<img title='Data atual' align='top' onclick=\"javascript: { $$('" . $id . "').value = '" . date("d/m/Y") . "'; }\" src='../img/icons/time_go.gif' style='cursor: pointer; margin: 1 2 0 3px; _margin: 2 2 0 3px;'>";
+ }
+
+ return $html;
+ }
+
+ function getValueFormated() {
+ if (($this->value != "") and ($this->value != "0000-00-00") and ($this->value != "0000-00-00 00:00:00")) {
+ $this->detectInputType();
+
+ if ($this->input_type == "datetime") {
+ $v = datetimeFromMysql($this->value);
+ } else {
+ $v = dateFromMysql($this->value);
+ }
+ } else {
+ $v = "";
+ }
+
+ return $v;
+ }
+ function getValueUnformated() {
+ if (($this->value != "") and ($this->value != "00/00/0000") and ($this->value != "0000-00-00 00:00:00")) {
+ $this->detectInputType();
+
+ if ($this->input_type == "datetime") {
+ $tmp = explode(" ", $this->value);
+
+ if (sizeof($tmp) <= 1) {
+ global $input;
+
+ $this->value = $this->value . " " . $input->request($this->name . "_2");
+ }
+
+ $v = datetimeToMysql($this->value);
+ } else {
+ $v = dateToMysql($this->value);
+ }
+ } else {
+ $v = "";
+ }
+
+ return $v;
+ }
+
+ function detectInputType() {
+ if ($this->input_type == "") {
+ $tmp = explode(" ", $this->value);
+
+ if (sizeof($tmp) > 1) {
+ $this->input_type = "datetime";
+ } else {
+ $this->input_type = "date";
+ }
+ }
+ }
+
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->is_required = false;
+ $this->in_filter = true;
+
+ $html .= " <td class='input'>";
+
+ if ($this->filter_type == 1) {
+ //Field 2
+ $filter_name2 = $this->_getFilterName(2);
+ $filter_value2 = $this->_getFilterValue(2);
+
+ //Field 1
+ $this->name = $filter_name;
+ $this->value = $filter_value;
+ $this->input_extra = "onKeyUp=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+
+ $html .= $this->getInput();
+
+
+ //Field 2
+ $this->name = $filter_name2;
+
+ if ($filter_value != "") {
+ $this->value = $filter_value2;
+ } else {
+ $this->value = "";
+ }
+
+ $html .= " à " . $this->getInput(2);
+
+
+ if ($filter_value != "") {
+ $v2 = dateToMysql($filter_value2);
+ $v2 = strtotime($v2);
+ $v2 += (24 * 60 * 60);
+ $v2 = date("Y-m-d", $v2);
+
+ $sql = " and " . $old_name . " >= '" . dateToMysql($filter_value) . "' and " . $old_name . " < '" . $v2 . "'";
+ }
+ } else {
+ global $form;
+ global $db;
+ global $load;
+
+ $sql_list = "
+ select
+ distinct(concat(month(" . $old_name . "), '/', year(" . $old_name . "))) as junto,
+ " . $old_name . " as data,
+ year(" . $old_name . ") as ano,
+ month(" . $old_name . ") as mes
+ from
+ " . $form->table . "
+ where
+ " . $old_name . " != '' and
+ " . $old_name . " != '0000-00-00'
+ group by
+ junto
+ order by
+ ano desc,
+ mes asc
+ ";
+ $rs = $db->execute($sql_list);
+
+ $html .= "<select class='input' name='" . $filter_name . "' id='" . $this->label . "_CMB0' onclick=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+
+ $html .= "<option value=''>Selecione</option>";
+ $html .= "<option value=''>------</option>";
+
+ while (!$rs->EOF) {
+ $v = $rs->fields("ano") . "-" . substr("0" . $rs->fields("mes"), -2);
+ if ($filter_value == $v) {
+ $sql = " and month(" . $old_name . ") = '" . substr("0" . $rs->fields("mes"), -2) . "' and year(" . $old_name . ") > '" . substr("0" . $rs->fields("ano"), -2) . "'";
+ $s = " selected";
+ } else {
+ $s = "";
+ }
+
+ $html .= "<option value='" . $v . "'" . $s . ">" . monthToBrName($rs->fields("mes")) . "</option>";
+
+ $rs->moveNext();
+ }
+
+ $html .= "</select>";
+ }
+
+ $html .= "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+
+ return array("html" => $html, "sql" => $sql);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldForm extends Field {
+ var $default_order;
+
+ var $_field_rel;
+ var $_field_parent_id;
+
+ var $_flags2; //Permission flags [IUD]
+
+ var $_fieldset; //Fields loaded from config
+ var $_fields_index; //Index of fields for addField method
+
+ var $db_table; //Class DBTabele of table
+
+ function FieldForm($tmp_params) {
+ parent::Field("form", $tmp_params[0]);
+
+ $this->label = $tmp_params[1];
+ $this->is_sql_affect = false;
+ $this->flags_accept = "IU";
+ $this->is_required = false;
+
+ $this->_flags2 = $tmp_params[2];
+
+ $this->_field_rel = $tmp_params[3];
+
+ global $form;
+ $this->_field_parent_id = $form->key_field;
+
+ $this->db_table = new DBTable($tmp_params[0]);
+ }
+
+ function newField($tmp_type, $tmp_params = array()) {
+ global $form;
+
+ $this->_fields_index++;
+
+ if (!in_array($tmp_type, $form->_fields_loaded)) {
+ global $load;
+ $include = $load->manager("core/form/fields/Field" . ucfirst($tmp_type) . ".php", false);
+
+ if (!$include) {
+ $load->config("exeptions/fields/Field" . ucfirst($tmp_type) . ".php");
+ }
+
+ $form->_fields_loaded[] = $tmp_type;
+ }
+
+ if ($tmp_params == array()) {
+ $tmp_params = array("", "");
+ }
+
+ $class = "Field" . $tmp_type;
+ $f = new $class($tmp_params);
+
+ $f->index_list = $this->_fields_index;
+ $f->index_filter = $this->_fields_index;
+ $f->index_form = $this->_fields_index;
+
+ //Set value
+ $f->value = $this->db_table->fields($f->name);
+ $f->formatValue();
+ $f->value_static = $f->value;
+
+ return $f;
+ }
+
+ function addField(&$tmp_field, $tmp_flags = "") {
+ if ($tmp_field->is_html) {
+ $tmp_flags = "IU";
+ }
+
+ $tmp_field->flags = $tmp_flags;
+
+ if ($tmp_field->is_static) {
+ $tmp_field->is_required = false;
+
+ if ($tmp_field->value_static == "") {
+ $tmp_field->is_sql_affect = false;
+ }
+ }
+
+ $this->_fieldset[] = $tmp_field;
+ }
+
+ //private functions
+ function testFlag2($tmp_flag) {
+ if (strpos($this->_flags2, $tmp_flag) !== false) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ function getInput() {
+ $html = $this->_getList();
+
+ return $html;
+ }
+
+ function _getList() {
+ global $form;
+ global $db;
+ global $routine;
+
+ $old_routine = $routine;
+ $routine = "list";
+
+ $headers = $this->getHeaders();
+
+ $sql = "select * from " . $this->name . " where " . $this->_field_rel . " = '" . $form->fields($form->key_field) . "' " . $headers["sql"];
+ $rs_list = $db->execute($sql);
+
+ $html = '
+ <table cellpadding="0" cellspacing="1" width="768" class="listagem">
+ <thead>
+ <tr>
+ ';
+ if ($this->testFlag2("D")) {
+ $html .= '<td class="header_cinza" width="30"><input id="chk_todos" type="checkbox" onClick="javascript: check(this); "></td>';
+ }
+
+ $html .= $headers["html"];
+
+ $html .= '</tr>
+ </thead>
+ <tbody>
+ ';
+ if (!$rs_list->EOF) {
+ $css = 2;
+ $i = 1;
+
+ $fields = $this->_fieldset;
+
+ while (!$rs_list->EOF) {
+ $css = 3 - $css;
+
+ $html .= "<tr id='tr_" . $i . "' onmouseover=\"javascript: listOverOut('over', '" . $i . "');\" onmouseout=\"javascript: listOverOut('out', '" . $i . "');\">" . CRLF;
+
+ $extra = "class='td" . $css . "' ";
+ if ($this->testFlag2("U")) {
+ $extra .= "onclick=\"javascript: listUpdate('" . $rs_list->fields($this->db_table->key_field) . "');\"";
+ } else {
+ $extra .= "style=\"cursor: default;\"";
+ }
+
+ if ($this->testFlag2("D")) {
+ $html .= " <td align='center'><input type='checkbox' name='chk_" . $i . "' id='chk_" . $i . "' value='" . $rs_list->fields($this->db_table->key_field) . "' onclick=\"javascript: { checkMostrar(); listOverOut('over', '" . $i . "'); }\"></td>" . CRLF;
+ }
+
+ $this->db_table->setValuesFromRs($rs_list);
+
+ foreach ($fields as $k => $v) {
+ if ($v->testFlag("L")) {
+ $v->value = $rs_list->fields($v->name);
+ $v->is_formated = false;
+
+ $html .= " " . trim($v->getHtmlList($extra)) . LF;
+ }
+ }
+
+ $html .= "</tr>";
+
+ $rs_list->moveNext();
+ $i++;
+ }
+ } else {
+ $html .= '<tr><td colspan="100%" align="center" style="height: 40px; background: #ECD9D5;"><strong style="color: #9D412C;">Nenhum registro encontrado</strong></td></tr>';
+ }
+
+ $html .= '</table>';
+
+ $routine = $old_routine;
+
+ return $html;
+ }
+
+ function getHeaders() {
+ $order = $this->_getOrderValue();
+ $order_parsed = explode("#", $order);
+
+ if (sizeof($order_parsed) > 1) {
+ $order_name = $order_parsed[0];
+ $order_direction = $order_parsed[1];
+ $sql = " order by " . $order_name . " " . $order_direction;
+ } else {
+ $order_name = "";
+ $order_direction = "";
+ $sql = "";
+ }
+
+ $fields = $this->_fieldset;
+
+ $html = "";
+ foreach($fields as $k => $v) {
+ if ($v->testFlag("L")) {
+ $css = "";
+ $a = "";
+ if ($v->testFlag("O")) {
+ if ($v->name == $order_name) {
+ if ($order_direction == "asc") {
+ $css = "_down";
+ $a = "onclick=\"javascript: listOrder('" . $v->name . "#desc');\" style='cursor: pointer;' title='Ordem decrescente'";
+ } else {
+ $css = "_up";
+ $a = "onclick=\"javascript: listOrder('" . $v->name . "#asc');\" style='cursor: pointer;' title='Ordem crescente'";
+ }
+ } else {
+ $a = "onclick=\"javascript: listOrder('" . $v->name . "#asc');\" style='cursor: pointer;' title='Ordem crescente'";
+ }
+ }
+
+ if ($v->list_width > 0) {
+ $a .= " width='" . $v->list_width . "'";
+ }
+
+ $html .= "<td class='header" . $css . "' " . $a . ">" . $v->label . "</td>" . LF;
+ }
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ function _getOrderValue() {
+ global $input;
+ global $menu;
+
+ $sub = $menu->index . "-" . $menu->index_sub . " : " . $this->name;
+
+ if ($input->post("order") != "") {
+ $r = $input->post("order");
+ } elseif ($input->session($sub . " order") != "") {
+ $r = $input->session($sub . " order");
+ } elseif ($this->default_order != "") {
+ $r = $this->default_order;
+ } else {
+ $r = "";
+ }
+
+ $input->setSession($sub . " order", $r);
+
+ return $r;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldHidden extends Field {
+ function FieldHidden($tmp_params) {
+ parent::Field("char", $tmp_params[0]);
+
+ $this->testRequiredType(array("varchar", "blob"));
+
+ if (isset($tmp_params[1])) {
+ $this->label = $tmp_params[1];
+ } else {
+ $this->label = $tmp_params[0];
+ }
+ $this->validation = "TXT";
+ }
+
+ //private functions
+ function getInput() {
+ $html = "<input ";
+ $html .= "type='hidden' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "value=\"" . $this->_escapeValue($this->getValue()) . "\" ";
+ $html .= " " . $this->input_extra;
+ $html .= ">";
+
+ return $html;
+ }
+
+ function getHtml() {
+ $html = $this->getInput() . LF;
+
+ return $html;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldHtml extends Field {
+ var $html;
+ var $extra_style;
+
+ function FieldHtml($tmp_params) {
+ parent::Field("html", "campo_html");
+
+ $this->is_html = true;
+ $this->is_sql_affect = false;
+ $this->is_static = true;
+
+ $this->setType($tmp_params[0]);
+
+ $this->extra_style = '';
+
+ if (isset($tmp_params[1])) {
+ $this->setLabel($tmp_params[1]);
+ }
+ }
+
+ function setType($tmp_type) {
+ $this->type = "html_" . $tmp_type;
+ }
+
+ function setLabel($tmp_label) {
+ $this->label = $tmp_label;
+ }
+
+ function setHTML($tmp_html) {
+ $this->html = $tmp_html;
+ }
+
+ //private functions
+ function getHTML() {
+ $type = substr($this->type, 5);
+
+ switch ($type) {
+ case "box":
+ echo "</table></td></tr></table></div><div class='form' style='margin-top: 5px;".$this->extra_style."' id='".$this->label."'><table cellspacing='0' cellpadding='0' width='100%' height='100%'>" . LF;
+ echo "<tr><td width='49%' valign='top'><table cellspacing='3' cellpadding='0' width='100%'>" . LF;
+
+ break;
+
+ case "separador":
+ echo "</table></td><td width='2%' align='center'>" . LF;
+ echo "<table cellspacing='0' cellpadding='0' height='100%' style='border-left: 1px solid #E4E4E4;'><tr><td></td></tr></table>" . LF;
+ echo "</td><td width='49%' valign='top'><table cellspacing='3' cellpadding='0' width='100%' id='".$this->label."' style='".$this->extra_style."'>" . LF;
+
+ break;
+ case "html":
+ echo $this->html;
+
+ break;
+ case "label":
+ echo "<tr class='fieldset'><td class='custom' colspan='100%'><strong>" . $this->label . "</strong></td></tr>";
+
+ break;
+ case "custom":
+ echo "<tr class='fieldset'><td class='label'>" . $this->label . ":</td><td class='input'>" . $this->html . "</td></tr>";
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldHtmlEditor extends Field {
+ var $js_object;
+ var $images_path;
+
+ var $width;
+ var $height;
+
+ function FieldHtmlEditor($tmp_params) {
+ parent::Field("htmlEditor", $tmp_params[0]);
+
+ $this->testRequiredType(array("varchar", "blob", "text"));
+
+ $this->label = $tmp_params[1];
+ $this->validation = "TXT";
+ $this->images_path = $tmp_params[2];
+
+ global $htmleditor_count;
+ $this->js_object = "htmleditor" . $htmleditor_count;
+ $htmleditor_count++;
+
+ $this->width = "100%";
+ $this->height = "300";
+ }
+
+ //private functions
+ function loadJSPrePost() {
+ ?>
+ if (<?= $this->js_object; ?>.is_window_opened) {
+ ok = false;
+ }
+ <?
+ }
+
+ function getInput() {
+ global $cfg;
+
+ $html = "<textarea ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= $this->input_extra . " style='display: block;'>";
+ $html .= $this->getValue();
+ $html .= "</textarea>";
+
+ //js
+ $html .= "
+ <script>
+ " . $this->js_object . " = new HtmlEditor();
+ " . $this->js_object . ".class_name = '" . $this->js_object . "';
+ " . $this->js_object . ".field_id = '" . $this->_getFormatedId() . "';
+ " . $this->js_object . ".images_path = '" . $this->images_path . "';
+ " . $this->js_object . ".root_path = '" . $cfg["root"] . "';
+ " . $this->js_object . ".width = '" . $this->width . "';
+ " . $this->js_object . ".height = '" . $this->height . "';
+ " . $this->js_object . ".make();
+ </script>
+ ";
+
+ return $html;
+ }
+
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->name = $filter_name;
+ $this->value = $filter_value;
+ $this->input_extra = "onKeyUp=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ $this->is_required = false;
+
+ $html .= " <td class='input'>" . $this->getFilterInput() . "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+ if ($filter_value != "") {
+ $sql = " and " . $old_name . " LIKE '%" . $filter_value . "%'";
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ function getFilterInput() {
+ $html = "<input ";
+ $html .= "class='input' ";
+ $html .= "type='text' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "size='" . $this->size_cols . "' ";
+ $html .= "maxlength='" . $this->maxlength . "' ";
+ $html .= "value=\"" . $this->_escapeValue($this->getValue()) . "\" ";
+ $html .= " " . $this->input_extra;
+ $html .= ">";
+
+ return $html;
+ }
+
+ function getValueFormated($tmp_value = "") {
+ global $cfg;
+
+ if (isset($this)) {
+ $v = $this->value;
+ } else if ($tmp_value != "") {
+ $v = $tmp_value;
+ }
+
+ return str_replace("#ROOT#", $cfg["root"], $v);
+ }
+
+ function getValueUnformated() {
+ global $cfg;
+ global $load;
+ $load->system('functions/text.php');
+
+ $this->value = formatSpecialCaracter($this->value);
+
+ return str_replace($cfg["root"], "#ROOT#", $this->value);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldImageMultiUpload extends Field {
+ var $path;
+ var $thumbs;
+
+ var $extensions_accept;
+
+ var $path_tmp;
+
+ var $max;
+
+ function FieldImageMultiUpload($tmp_params) {
+ parent::Field("imageMultiUpload", $tmp_params[0]);
+
+ $this->flags_accept = "IU";
+
+ $this->label = $tmp_params[1];
+ $this->validation = "TXT";
+ $this->is_sql_affect = false;
+
+ $this->extensions_accept = array("jpg");
+
+ if (isset($tmp_params[2])) {
+ $this->setPath($tmp_params[2]);
+ }
+
+ $this->setTmpPath("upload/tmp/");
+
+ global $routine;
+ if ($routine == "update") {
+ $this->is_required = false;
+ }
+
+ $this->max = 100;
+ }
+
+ function setPath($tmp_path) {
+ $this->path = "../../../" . $tmp_path;
+ }
+
+ function setTmpPath($tmp_path) {
+ $this->path_tmp = "../../../" . $tmp_path;
+ }
+
+ function addThumb($tmp_name, $tmp_w = 0, $tmp_h = 0, $tmp_method = 0) {
+ $thumb = array();
+
+ $thumb["name"] = $tmp_name;
+ $thumb["w"] = $tmp_w;
+ $thumb["h"] = $tmp_h;
+ $thumb["method"] = $tmp_method;
+
+ $this->thumbs[] = $thumb;
+ }
+
+
+ //private functions
+ function getInput() {
+ $required_backup = $this->is_required;
+ $label_backup = $this->label;
+
+ $this->is_required = false;
+ $this->label = rand(1, 100000000);
+
+ $html = "<input ";
+ $html .= "class='input' ";
+ $html .= "type='file' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "style='width: 230px;' ";
+ $html .= ">";
+ $html .= "<a href='javascript:void(0);' onclick=\"javascript: uploadSubmit('" . $this->name . "')\">upload</a>";
+
+ $this->is_required = $required_backup;
+ $this->label = $label_backup;
+
+ return $html;
+ }
+
+ function getHtml() {
+ global $routine;
+ global $form;
+
+ $html = "<tr>";
+
+ //Label
+ if ($this->label != "") {
+ $html .= "<td class='label'>";
+
+ $html .= $this->label . ": ";
+
+ if ($this->is_required) {
+ $html .= "<font class='red'>*</font>";
+ }
+
+ $html .= "</td>" . LF;
+ }
+
+ $this->formatValue();
+
+ //Input
+ $html .= "<td class='input'>";
+
+ if ($this->is_static) {
+ error(1, "Um campo 'upload' não pode ser estático.", "FieldMultiUpload", "getHtml");
+ }
+
+ //.input
+ $html .= "<div id='" . $this->name . "_div_input' class='box_silver'>";
+ $html .= $this->getInput();
+ $html .= "</div>";
+
+ //.loading message
+ $html .= "<div id='" . $this->name . "_div_loading' class='box_silver' style='display: none; height: 15px; margin-top: 5px;'>Loading...</div>";
+
+ //.error box
+ $html .= "<div id='" . $this->name . "_div_error' class='box_red' style='display: none; height: 20px; margin-top: 5px;'></div>";
+
+ //.list
+ if (IS_DEVELOP) {
+ $html .= "<a href='javascript:void(0);' onclick=\"javascript: uploadList('" . $this->name . "');\">refresh list</a><br>";
+ }
+ $html .= "<table width='100%' style='margin-top: 5px;'><tr><td class='box_yellow' id='" . $this->name . "_div_list' style='display: none;'></td></tr></table>";
+
+ //.list of tmp files
+ if ($routine == "insert") {
+ $html .= "<input type='hidden' id='" . $this->_getFormatedId() . "' value=''>";
+
+ $_SESSION[$this->name . "_files"] = array();
+ }
+
+ //.if update, upload list of files
+ if ($routine == "update") {
+ $html .= "<script>uploadList('" . $this->name . "');</script>";
+ }
+
+ $html .= "</td></tr>" . LF;
+
+ return $html;
+ }
+
+ function onPosPost() {
+ global $routine;
+ global $file;
+ global $form;
+ global $input;
+
+ if ($routine == "insert") {
+ $list = $input->session($this->name . "_files");
+
+ $path = $this->_getPath();
+
+ if (is_array($list)) {
+ $i = 1;
+ foreach ($list as $v) {
+ if (file_exists($v[0])) {
+ foreach ($v as $k2 => $v2) {
+ $ext = $file->getExtension($v2);
+
+ $file->copyFile($v2, $path . $this->_getFile($i, $k2) . "." . $ext);
+
+ $file->deleteFile($v2);
+ }
+
+ $i++;
+ }
+ }
+ }
+
+ $input->unsetSession($this->name . "_files");
+ }
+
+ //delete old files from tmp folder
+ $list = $file->listFolder($this->path_tmp);
+
+ if (is_array($list)) {
+ foreach ($list as $v) {
+ $path = $this->path_tmp . $v;
+
+ $arr2 = explode(".", $v);
+ $arr = explode("_", $arr2[0]);
+ $date_modified = (float)$arr[1];
+
+ //2 hours limit
+ if (time() > ($date_modified + (2 * 60 * 60))) {
+ $file->deleteFile($path);
+ }
+ }
+ }
+ }
+
+ function onDelete() { //OK
+ global $file;
+
+ $path = $this->_getPath();
+
+ for ($i = 1; $i < $this->max; $i++) {
+ foreach ($this->thumbs as $k => $v) {
+ $file->deleteFile($path . $this->_getFile($i, $k));
+ }
+ }
+ }
+
+ //Ajax functions
+ function ajaxRoutine($tmp_routine) {
+ global $file;
+ global $routine;
+ global $load;
+ global $input;
+
+ $html = "";
+
+ switch ($tmp_routine) {
+ case "upload":
+ if (array_key_exists($this->name, $_FILES)) {
+ if ($routine == "insert") {
+ $file_dest = $this->_getTempFile();
+ } else {
+ $number_file = $this->_getNewNumberFile();
+ $path_dest = $this->_getPath();
+
+ $file_dest = $path_dest . $number_file;
+ }
+
+ $ext = $file->getExtension($_FILES[$this->name]["name"]);
+
+ if (array_search($ext, $this->extensions_accept) !== false) {
+ if (move_uploaded_file($_FILES[$this->name]["tmp_name"], $file_dest . "." . $ext)) {
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = 'none';" . LF;
+
+ if ($routine == "insert") {
+ $html .= "window.parent.$$('" . $this->_getFormatedId() . "').value = '" . $file_dest . "." . $ext . "';";
+ }
+
+ $load->setOverwrite(true);
+ $load->system("library/Image.php");
+
+ $list = array();
+
+ $img = new Image();
+ $path = $file_dest . "." . $ext;
+ $path_from = $path;
+ foreach ($this->thumbs as $k => $v) {
+ if ($k > 0) {
+ if ($routine == "insert") {
+ $path = $this->_getTempFile($k) . "." . $ext;
+ } else {
+ $path = $path_dest . $this->_getFile($number_file, $k) . "." . $ext;
+
+ echo $path . "<br>";
+ }
+ }
+
+ $img->load($path_from);
+
+ if ($routine == "insert") {
+ $list[] = $path;
+ }
+
+ $img->resize($v["w"], $v["h"], $v["method"]);
+
+ $img->save($path);
+ }
+
+ if ($routine == "insert") {
+ $_SESSION[$this->name . "_files"][] = $list;
+ }
+
+ $html .= "</script>";
+ } else {
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = 'Erro ao fazer upload.';" . LF;
+ $html .= "</script>";
+ }
+ } else {
+
+
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = \"Extensão não permitida.<br>Utilize somente '" . implode(", ", $this->extensions_accept) . "'\";" . LF;
+ $html .= "</script>";
+ }
+ }
+
+ break;
+ case "list":
+ if ($routine == "insert") {
+ $list = $_SESSION[$this->name . "_files"];
+ } else {
+ $list = $this->_getListFiles();
+ }
+
+ if (sizeof($list) != "") {
+ $i = 1;
+ foreach ($list as $v) {
+ $path_clean = str_replace("../../../", "", $v[0]);
+
+ $html .= "<div class='upload_item' style='margin-bottom: 5px;'>";
+ $html .= "<div class='label'><img style='margin-bottom: 3px;' src='../../_system/scripts/image.php?file=" . $path_clean . "&w=60&h=60&rand=" . rand(1, 9999) . "'></div>";
+ $html .= "<div class='buttons'><a href='javascript:void(0);' onclick=\"uploadDelete('" . $this->name . "', '" . $i . "');\">del</a></div>";
+ $html .= "</div>";
+
+ $i++;
+ }
+
+ $html .= "<script>" . LF;
+ $html .= "$$('" . $this->name . "_div_input').style.display = '';" . LF;
+ $html .= "$$('" . $this->name . "_div_input').innerHTML = '" . str_replace("'", "\'", $this->getInput()) . "';" . LF;
+ $html .= "$$('" . $this->name . "_div_list').style.display = '';" . LF;
+ $html .= "</script>";
+ } else {
+ $html .= "<script>" . LF;
+ $html .= "$$('" . $this->name . "_div_input').innerHTML = '" . str_replace("'", "\'", $this->getInput()) . "';" . LF;
+ $html .= "$$('" . $this->name . "_div_list').style.display = 'none';" . LF;
+ $html .= "</script>";
+ }
+
+ break;
+ case "delete":
+ if ($routine == "insert") {
+ $list = $_SESSION[$this->name . "_files"];
+ } else {
+ $list = $this->_getListFiles();
+ }
+
+ $i = $input->get("n") - 1;
+ if (array_key_exists($i, $list)) {
+ $files = $list[$i];
+ foreach ($files as $v) {
+ $file->deleteFile($v);
+ }
+ }
+
+ if ($routine == "insert") {
+ //unset file in session list
+ $new_list = array();
+
+ if (sizeof($list) > 1) {
+ unset($_SESSION[$this->name . "_files"][($input->get("n") - 1)]);
+
+ $i = 1;
+ foreach ($_SESSION[$this->name . "_files"] as $v) {
+ $new_list[$i] = $v;
+
+ $i++;
+ }
+ }
+
+ $_SESSION[$this->name . "_files"] = $new_list;
+ } else {
+ $this->_sortFiles();
+ }
+
+ $html .= "<script>uploadList('" . $this->name . "');</script>";
+
+ break;
+ }
+
+
+
+ return $html;
+ }
+
+ function _findFile($tmp_path) {
+ foreach ($this->extensions_accept as $v) {
+ $file_path = $tmp_path . "." . $v;
+
+ if (file_exists($file_path)) {
+ return $file_path;
+ }
+ }
+
+ return '';
+ }
+
+ function _sortFiles() { //Test
+ global $file;
+
+ $list = $this->_getListFiles();
+
+ $i = 1;
+ foreach ($list as $v) {
+ foreach ($v as $k => $v2) {
+ $file->rename($v[$k], $this->_getFile($i, $k));
+ }
+
+ $i++;
+ }
+ }
+
+ function _getTempFile() { //OK
+ global $file;
+
+ $file_name = substr("00000" . rand(1, 999999), -6) . "_" . time();
+
+ $exists = false;
+
+ foreach ($this->extensions_accept as $v) {
+ if (file_exists($this->path_tmp . $file_name . "." . $v)) {
+ $exists = true;
+ }
+ }
+
+ if ($exists) {
+ $file_name = $this->_getTempFile();
+ }
+
+
+ //create tmp folder(s)
+ $arr = explode("/", $this->path_tmp);
+ $path = "";
+ foreach ($arr as $name) {
+ if (strlen($name) > 0) {
+ $path .= $name . "/";
+
+ if (substr($path, -3) != "../") {
+ $file->makeFolder($path);
+ }
+ }
+ }
+
+ return $this->path_tmp . $file_name;
+ }
+
+ function _getNewNumberFile() { //OK
+ $path = $this->_getPath();
+
+ $r = 1;
+ $ok = false;
+ for ($i = 1; $i < $this->max; $i++) {
+ $arq = $path . $this->_getFile($i);
+
+ $r = $i;
+
+ foreach ($this->extensions_accept as $v) {
+ if (!file_exists($arq . "." . $v)) {
+ $ok = true;
+ }
+ }
+
+ if ($ok) {
+ break;
+ }
+ }
+
+ return $r;
+ }
+
+ function _getListFiles() { //OK
+ global $file;
+
+ $path = $this->_getPath();
+
+ $list = array();
+
+ for ($i = 1; $i < $this->max; $i++) {
+ $imgs = array();
+
+ $img = $this->_getFile($i);
+ $img_ext = "";
+ foreach ($this->extensions_accept as $v) {
+ if (file_exists($path . $img . "." . $v)) {
+ $img_ext = $v;
+
+ break;
+ }
+ }
+
+ if ($img_ext != "") {
+ foreach ($this->thumbs as $k => $v) {
+ $imgs[] = $path . $this->_getFile($i, $k) . "." . $img_ext;
+ }
+
+ $list[] = $imgs;
+ }
+ }
+
+ return $list;
+ }
+
+ function _getFile($tmp_n = 1, $tmp_thumb = 0) { //OK
+ global $form;
+
+ $f = $form;
+
+ global $rs_list;
+ if (is_object($rs_list)) {
+ $f = $rs_list;
+ }
+
+ $file_name = $this->thumbs[$tmp_thumb]["name"];
+
+ $file_name = str_replace("#N#", $tmp_n, $file_name);
+
+ foreach ($f->fields as $k => $v) {
+ $file_name = str_replace("#" . strtoupper($k) . "#", $v, $file_name);
+ }
+
+ return $file_name;
+ }
+
+ function _getPath() { //OK
+ global $form;
+ global $file;
+
+ $path = $this->path;
+
+ foreach ($form->fields as $k => $v) {
+ $path = str_replace("#" . strtoupper($k) . "#", $v, $path);
+ }
+
+ //create folder(s)
+ $arr = explode("/", $path);
+ $path = "";
+ foreach ($arr as $name) {
+ if (strlen($name) > 0) {
+ $path .= $name . "/";
+
+ if (substr($path, -3) != "../") {
+ $file->makeFolder($path);
+ }
+ }
+ }
+
+ return $path;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FieldImageUpload extends Field {\r
+ var $path;\r
+ var $thumbs;\r
+ \r
+ var $extensions_accept;\r
+ \r
+ var $path_tmp;\r
+ var $hint;\r
+ \r
+ function FieldImageUpload($tmp_params) {\r
+ parent::Field("imageUpload", $tmp_params[0]);\r
+ \r
+ $this->flags_accept = "LIU";\r
+ \r
+ $this->label = $tmp_params[1];\r
+ $this->validation = "TXT";\r
+ $this->is_sql_affect = false;\r
+ \r
+ $this->extensions_accept = array("jpg", "gif");\r
+ \r
+ if (isset($tmp_params[2])) {\r
+ $this->setPath($tmp_params[2]);\r
+ }\r
+ \r
+ $this->setTmpPath("upload/tmp/");\r
+ \r
+ global $routine;\r
+ if ($routine == "update") {\r
+ $this->is_required = false;\r
+ }\r
+ $this->hint = '';\r
+ $this->list_width = 70;\r
+ }\r
+ \r
+ function setPath($tmp_path) {\r
+ $this->path = "../../../" . $tmp_path;\r
+ }\r
+ \r
+ function setTmpPath($tmp_path) {\r
+ $this->path_tmp = "../../../" . $tmp_path;\r
+ }\r
+ \r
+ function addThumb($tmp_name, $tmp_w = 0, $tmp_h = 0, $tmp_method = 0) {\r
+ $thumb = array();\r
+ \r
+ $thumb["name"] = $tmp_name;\r
+ $thumb["w"] = $tmp_w;\r
+ $thumb["h"] = $tmp_h;\r
+ $thumb["method"] = $tmp_method;\r
+ \r
+ $this->thumbs[] = $thumb;\r
+ }\r
+ \r
+ \r
+ //private functions \r
+ function getHtmlList($tmp_extra) {\r
+ $this->formatValue();\r
+ \r
+ $path = $this->_findFile($this->path . $this->_getFile());\r
+ $path_clean = str_replace("../../../", "", $path);\r
+ \r
+ if (file_exists($path)) {\r
+ $v = "<center><img style='margin: 3 0 3 0px;' src='../../_system/scripts/image.php?resize=4&file=" . $path_clean . "&w=60&h=60&rand=" . rand(1, 9999) . "'></center>";\r
+ } else {\r
+ $v = "<font color='silver'>(sem imagem)</font>";\r
+ }\r
+ \r
+ $html = "<td " . $tmp_extra . ">" . $v . "</td>" . LF;\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ function getInput() {\r
+ $required_backup = $this->is_required;\r
+ $label_backup = $this->label;\r
+ \r
+ $this->is_required = false;\r
+ $this->label = rand(1, 100000000);\r
+ \r
+ $html = '<div class="label"><table cellspacing="0" cellpadding="0" width="270" height="60"><tr><td>';\r
+ $html .= "<input ";\r
+ $html .= "class='input' ";\r
+ $html .= "type='file' ";\r
+ $html .= "id='" . $this->_getFormatedId() . "' ";\r
+ $html .= "name='" . $this->name . "' ";\r
+ $html .= "style='width: 180px;' ";\r
+ $html .= ">";\r
+ $html .= "</td><td>";\r
+ $html .= "<a href='javascript:void(0);' onclick=\"javascript: uploadSubmit('" . $this->name . "')\"><img src=\"../img/buttons/add.jpg\" alt=\"inserir\" title=\"inserir\" align=\"right\"/></a>";\r
+ $html .= '</td></tr></table></div>';\r
+ $this->is_required = $required_backup;\r
+ $this->label = $label_backup;\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ function getHtml() {\r
+ global $routine;\r
+ global $form;\r
+ \r
+ $html = "<tr>";\r
+ \r
+ //Label\r
+ if ($this->label != "") {\r
+ $html .= "<td class='label'>";\r
+ \r
+ $html .= $this->label . ": ";\r
+ \r
+ if ($this->is_required) {\r
+ $html .= "<font class='red'>*</font>";\r
+ }\r
+ \r
+ if($this->hint != ''){\r
+ $html .= "<br /><br />(<span style='font-size:9px;'>".$this->hint."</span>)";\r
+ }\r
+ \r
+ $html .= "</td>" . LF;\r
+ }\r
+ \r
+ $this->formatValue();\r
+ \r
+ //Input\r
+ $html .= "<td class='input'>";\r
+ \r
+ if ($this->is_static) {\r
+ $html .= "<div id='" . $this->name . "_div_input' class='box_silver'>";\r
+ //error(1, "Um campo 'upload' não pode ser estático.", "FieldUpload", "getHtml");\r
+ $html .= "</div>";\r
+ } else {\r
+ //.input\r
+ $html .= "<div id='" . $this->name . "_div_input' class='box_silver'>";\r
+ $html .= $this->getInput();\r
+ $html .= "</div>";\r
+ }\r
+ \r
+ //.loading message\r
+ $html .= "<div id='" . $this->name . "_div_loading' class='box_silver' style='display: none; margin-top: 5px;'><div class=\"label\"><table style=\"height:60px;\"><tr><td>Carregando...</td></tr></table></div></div>";\r
+ \r
+ //.error box\r
+ $html .= "<div id='" . $this->name . "_div_error' class='box_red' style='display: none; height: 20px; margin-top: 5px;'></div>";\r
+ \r
+ //.list\r
+ if (IS_DEVELOP) {\r
+ $html .= "<a href='javascript:void(0);' onclick=\"javascript: uploadList('" . $this->name . "');\">refresh list</a><br>";\r
+ }\r
+ $html .= "<table width='100%' style='margin-top: 5px;'><tr><td class='box_yellow' id='" . $this->name . "_div_list' style='display: none;'></td></tr></table>"; \r
+ \r
+ //.list of tmp files\r
+ if ($routine == "insert") {\r
+ $html .= "<input type='hidden' id='" . $this->_getFormatedId() . "' value=''>";\r
+ }\r
+ \r
+ //.if update, upload list of files\r
+ if ($routine == "update") {\r
+ $html .= "<script>uploadList('" . $this->name . "');</script>";\r
+ }\r
+ \r
+ $html .= "</td></tr>" . LF;\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ function onPosPost() {\r
+ global $routine;\r
+ global $file;\r
+ global $form;\r
+ global $input;\r
+ \r
+ if ($routine == "insert") {\r
+ $list = $input->session($this->name . "_files");\r
+ \r
+ if (is_array($list)) {\r
+ $i = 1;\r
+ foreach ($list as $v) {\r
+ if (file_exists($v)) {\r
+ $ext = $file->getExtension($v);\r
+ \r
+ $file->copyFile($v, $this->path . $this->_getFile($i - 1) . "." . $ext);\r
+ \r
+ $file->deleteFile($v);\r
+ \r
+ $i++;\r
+ }\r
+ }\r
+ }\r
+ \r
+ $input->unsetSession($this->name . "_files");\r
+ }\r
+ \r
+ //delete old files from tmp folder\r
+ //TODO: Fix this\r
+ /*$list = $file->listFolder($this->path_tmp);\r
+ \r
+ if (is_array($list)) {\r
+ foreach ($list as $v) {\r
+ $path = $this->path_tmp . $v;\r
+ $date_modified = filemtime($path);\r
+ \r
+ //one day limit\r
+ if ((time() - ($date_modified / (24 * 60 * 60))) > 1) {\r
+ $file->deleteFile($path);\r
+ }\r
+ }\r
+ }*/\r
+ }\r
+ \r
+ function onDelete() {\r
+ global $file;\r
+ \r
+ $list = array();\r
+ foreach ($this->thumbs as $k => $v) {\r
+ $file->deleteFile($this->_findFile($this->path . $this->_getFile($k)));\r
+ }\r
+ }\r
+ \r
+ //Ajax functions\r
+ function ajaxRoutine($tmp_routine) {\r
+ global $file;\r
+ global $routine;\r
+ global $load;\r
+ global $input;\r
+ \r
+ $html = "";\r
+ \r
+ switch ($tmp_routine) {\r
+ case "upload":\r
+ if ($routine == "insert") {\r
+ $file_dest = $this->_getTempFile();\r
+ } else {\r
+ $file_dest = $this->path . $this->_getFile();\r
+ }\r
+ \r
+ foreach ($this->extensions_accept as $v) {\r
+ $tmp_path = $path . "." . $v;\r
+ \r
+ if (file_exists($tmp_path)) {\r
+ $file->deleteFile($tmp_path);\r
+ }\r
+ }\r
+ \r
+ $ext = $file->getExtension($_FILES[$this->name]["name"]);\r
+ \r
+ if (array_search($ext, $this->extensions_accept) !== false) {\r
+ if (move_uploaded_file($_FILES[$this->name]["tmp_name"], $file_dest . "." . $ext)) {\r
+ $html .= "<script>";\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = 'none';" . LF;\r
+ \r
+ if ($routine == "insert") {\r
+ $html .= "window.parent.$$('" . $this->_getFormatedId() . "').value = '" . $file_dest . "." . $ext . "';";\r
+ \r
+ $_SESSION[$this->name . "_files"] = array();\r
+ }\r
+ \r
+ $load->setOverwrite(true);\r
+ $load->system("library/Image.php");\r
+ \r
+ $img = new Image();\r
+ $path = $file_dest . "." . $ext;\r
+ $path_from = $path;\r
+ foreach ($this->thumbs as $k => $v) {\r
+ if ($k > 0) {\r
+ if ($routine == "insert") {\r
+ $path = $this->_getTempFile($k) . "." . $ext;\r
+ } else {\r
+ $path = $this->path . $this->_getFile($k) . "." . $ext;\r
+ }\r
+ }\r
+ \r
+ $img->load($path_from);\r
+ \r
+ if ($routine == "insert") {\r
+ $_SESSION[$this->name . "_files"][] = $path;\r
+ }\r
+ \r
+ $img->resize($v["w"], $v["h"], $v["method"]);\r
+ \r
+ $img->save($path);\r
+ }\r
+ \r
+ $html .= "</script>";\r
+ } else {\r
+ $html .= "<script>";\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = 'Erro ao fazer upload.';" . LF;\r
+ $html .= "</script>";\r
+ }\r
+ } else {\r
+ $html .= "<script>";\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = \"Extensão não permitida.<br>Utilize somente '" . implode(", ", $this->extensions_accept) . "'\";" . LF;\r
+ $html .= "</script>";\r
+ }\r
+ \r
+ break;\r
+ case "list":\r
+ if ($routine == "insert") {\r
+ $path = $_SESSION[$this->name . "_files"][0];\r
+ } else {\r
+ $path = $this->_findFile($this->path . $this->_getFile());\r
+ }\r
+ \r
+ if ($path != "") {\r
+ $path_clean = str_replace("../../../", "", $path);\r
+ \r
+ $dimensions = '';\r
+ $func = '';\r
+ if($file->getExtension($path) == 'jpg'){\r
+ $img = imagecreatefromjpeg('../../../'.$path_clean);\r
+ $w = imagesx($img);\r
+ $h = imagesy($img);\r
+ $dimensions = $w.'x'.$h.' ';\r
+ $func = ' onclick="javascript: zoom(\'../../'.$path_clean.'\','.$w.','.$h.');" style="cursor:pointer;" alt="Ver em tamanho original" title="Ver em tamanho original" ';\r
+ }\r
+ \r
+ \r
+ $html .= "<div class='upload_item'>";\r
+ $html .= '<div class="label"><table cellspacing="0" cellpadding="0" width="270" height="60">\r
+ <tr>\r
+ <td>';\r
+ $html .= "<img ".$func." src='../../_system/scripts/image.php?file=" . $path_clean . "&w=60&h=60&resize=4&rand=" . rand(1, 9999) . "'>";\r
+ $html .= '</td><td align="right">';\r
+ if(!$this->is_static){\r
+ $html .= "<a href='javascript:void(0);' onclick=\"uploadDelete('" . $this->name . "');\"><img src=\"../img/buttons/del.jpg\" alt=\"Excluir\" title=\"Excluir\" align=\"right\"/></a>";\r
+ }\r
+ $html .= ' </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ Endereço: '.$path_clean.'\r
+ </td>\r
+ <td style="text-align:right;padding-right:5px;" nowrap>\r
+ '.$dimensions.'('.$file->fileSizeFormated($path).')\r
+ </td>\r
+ </tr>\r
+ </table>';\r
+ $html .= "</div></div>";\r
+ \r
+ $html .= "<script>" . LF;\r
+ $html .= "$$('" . $this->name . "_div_input').style.display = 'none';" . LF;\r
+ $html .= "$$('" . $this->name . "_div_list').style.display = '';" . LF;\r
+ $html .= "</script>";\r
+ } else {\r
+ $html .= "<script>" . LF;\r
+ $html .= "$$('" . $this->name . "_div_input').style.display = '';" . LF;\r
+ if($this->is_static){\r
+ $html .= "$$('" . $this->name . "_div_input').innerHTML = '" . str_replace("'", "\'", '(sem imagem)') . "';" . LF;\r
+ } else {\r
+ $html .= "$$('" . $this->name . "_div_input').innerHTML = '" . str_replace("'", "\'", $this->getInput()) . "';" . LF;\r
+ }\r
+ $html .= "$$('" . $this->name . "_div_list').style.display = 'none';" . LF;\r
+ $html .= "</script>";\r
+ }\r
+ \r
+ break;\r
+ case "delete":\r
+ if ($routine == "insert") {\r
+ $list = $_SESSION[$this->name . "_files"];\r
+ } else { \r
+ $list = array();\r
+ foreach ($this->thumbs as $k => $v) {\r
+ $list[] = $this->_findFile($this->path . $this->_getFile($k));\r
+ } \r
+ }\r
+ \r
+ foreach ($list as $v) {\r
+ echo $v;\r
+ $file->deleteFile($v);\r
+ }\r
+ \r
+ $input->unsetSession($this->name . "_files");\r
+ \r
+ $html .= "<script>uploadList('" . $this->name . "');</script>";\r
+ \r
+ break;\r
+ }\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ function _getTempFile() {\r
+ global $file;\r
+ \r
+ $file_name = substr("00000" . rand(1, 999999), -6);\r
+ \r
+ $exists = false;\r
+ \r
+ foreach ($this->extensions_accept as $v) {\r
+ if (file_exists($this->path_tmp . $file_name . "." . $v)) {\r
+ $exists = true;\r
+ }\r
+ }\r
+ \r
+ if ($exists) {\r
+ $file_name = $this->_getTempFile();\r
+ }\r
+ \r
+ \r
+ //create tmp folder(s)\r
+ $arr = explode("/", $this->path_tmp);\r
+ $path = "";\r
+ foreach ($arr as $name) {\r
+ if (strlen($name) > 0) {\r
+ $path .= $name . "/";\r
+ \r
+ if (substr($path, -3) != "../") {\r
+ $file->makeFolder($path);\r
+ }\r
+ }\r
+ }\r
+ \r
+ return $this->path_tmp . $file_name;\r
+ }\r
+ \r
+ function _getFile($tmp_thumb = 0) {\r
+ global $form;\r
+ \r
+ $form2 = $form;\r
+ \r
+ global $rs_list;\r
+ if (is_object($rs_list)) {\r
+ $form2 = $rs_list;\r
+ }\r
+ \r
+ $file_name = $this->thumbs[$tmp_thumb]["name"];\r
+ \r
+ foreach ($form2->fields as $k => $v) {\r
+ $file_name = str_replace("#" . strtoupper($k) . "#", $v, $file_name);\r
+ }\r
+ \r
+ return $file_name;\r
+ }\r
+ \r
+ function _findFile($tmp_path) {\r
+ foreach ($this->extensions_accept as $v) {\r
+ $file_path = $tmp_path . "." . $v;\r
+ \r
+ if (file_exists($file_path)) {\r
+ return $file_path;\r
+ }\r
+ }\r
+ \r
+ return '';\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldItems extends Field {
+ var $menu;
+
+ function FieldItems($tmp_params) {
+ parent::Field("items", $tmp_params[0]);
+
+ $this->testRequiredType(array("varchar", "int"));
+
+ $this->label = $tmp_params[1];
+ $this->setInputType("select");
+ }
+
+ function loadConfig($tmp_type) {
+ switch ($tmp_type) {
+ default:
+ case "simnao":
+ $this->setInputType("radio");
+
+ $this->elements = array();
+ $this->addElementsByArray(array(1 => "Sim", 0 => "Não"));
+
+ $this->list_width = 110;
+
+ break;
+ }
+ }
+
+ function setInputType($tmp_type) {
+ switch ($tmp_type) {
+ default:
+ case "select":
+ $this->input_type = "select";
+ $this->validation = "CMB";
+
+ break;
+ case "radio":
+ $this->input_type = "radio";
+ $this->validation = "RDO";
+
+ break;
+ }
+ }
+
+ //private functions
+ function getInput() {
+ $value = $this->getValue();
+
+ switch ($this->input_type) {
+ default:
+ case "select":
+ $html = "<select class='input' id='" . $this->_getFormatedId() . "' name='" . $this->name . "' " . $this->input_extra . ">" . LF;
+
+ $html .= "<option value=''>Selecione</option>";
+ $html .= "<option value=''>------</option>";
+
+ foreach ($this->elements as $k => $v) {
+ if ($k == $value) {
+ $s = " selected";
+ } else {
+ $s = "";
+ }
+
+ $html .= "<option value='" . $k . "'" . $s . ">" . $v . "</option>" . LF;
+ }
+
+ $html .= "</select>" . LF;
+
+ break;
+ case "radio":
+ $i = 1;
+
+ $html = "";
+
+ foreach ($this->elements as $k => $v) {
+ if ($k == $value) {
+ $s = " checked";
+ } else {
+ $s = "";
+ }
+
+ $id = $this->_getFormatedId($i);
+
+ $html .= "<div class='item'>";
+ $html .= "<div id='input'>";
+ $html .= "<input type='radio' id='" . $id . "' name='" . $this->name . "' value='" . $k . "'" . $s . " " . $this->input_extra . ">";
+ $html .= "</div><div id='label'>";
+ $html .= "<label for='" . $id . "'>" . $v . "</label>";
+ $html .= "</div>";
+ $html .= "</div>" . LF;
+
+ $i++;
+ }
+
+ break;
+ }
+
+ if (($this->menu != "") && (!$this->is_static)) {
+ global $menu;
+
+ $n = "";
+
+ foreach ($menu->_itens as $k => $v) {
+ foreach ($v["subs"] as $k2 => $v2) {
+ if ($v2->class == $this->menu) {
+ $n = $k . "-" . $k2;
+
+ break;
+ }
+ }
+ }
+
+ if ($n != "") {
+ $html .= "<img title='Editar registros' align='top' onclick=\"javascript: { document.location = '?menu=" . $n . "'; }\" src='../img/icons/table_edit.gif' style='cursor: pointer; margin: 1 2 0 3px; _margin: 2 2 0 3px;'>";
+ }
+ }
+
+ $this->element_key = $value;
+ if ($value != "") {
+ if (array_key_exists($value, $this->elements)) {
+ $this->value = $this->elements[$value];
+ }
+ }
+
+ return $html;
+ }
+
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->name = $filter_name;
+ $this->value = $filter_value;
+ $this->is_required = false;
+ if ($this->input_type == "select") {
+ $this->input_extra = "onChange=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ } elseif ($this->input_type == "radio") {
+ $this->input_extra = "onClick=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ }
+
+
+ $html .= " <td class='input'>" . $this->getInput() . "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+ if ($filter_value != "") {
+ $sql = " and " . $old_name . " = '" . $filter_value . "'";
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ function getHtmlList($tmp_extra) {
+ $this->formatValue();
+
+ $this->element_key = $this->value;
+ if (array_key_exists($this->value, $this->elements)) {
+ $this->value = $this->elements[$this->value];
+ } else {
+ $this->value = "";
+ }
+
+ if ($this->value == "") {
+ if ($this->element_key == "") {
+ $this->value = "<font color='silver'>(vazio)</font>";
+ } else {
+ $this->value = "<font color='silver'>[" . $this->element_key . "]</font>";
+ }
+ }
+
+ $html = "<td " . $tmp_extra . ">" . $this->value . "</td>" . LF;
+
+ return $html;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldItemsRel extends Field {
+ var $menu;
+
+ // Param
+ // 0 = campo
+ // 1 = label
+ // 2 = id do campo 'pai'
+
+ function FieldItemsRel($tmp_params) {
+ parent::Field("itemsRel", $tmp_params[0]);
+
+ $this->testRequiredType(array("varchar", "int"));
+
+ $this->label = $tmp_params[1];
+ $this->input_type = "select";
+ $this->validation = "CMB";
+
+ $this->id_field_rel = $tmp_params[2];
+
+ $this->table_rel = $tmp_params[3];
+ $this->value_in_table = (($tmp_params[4] != '')?$tmp_params[4]:'id');
+ $this->name_in_table = (($tmp_params[5] != '')?$tmp_params[5]:'nome');
+ }
+
+ //private functions
+ function getInput() {
+ $value = $this->getValue();
+
+ $html = "<select class='input' id='" . $this->_getFormatedId() . "' name='" . $this->name . "' " . $this->input_extra . ">" . LF;
+
+ $html .= "<option value=''>Selecione</option>";
+ $html .= "<option value=''>------</option>";
+
+ foreach ($this->elements as $k => $v) {
+ if ($k == $value) {
+ $s = " selected";
+ } else {
+ $s = "";
+ }
+
+ $html .= "<option value='" . $k . "'" . $s . ">" . $v . "</option>" . LF;
+ }
+
+ $html .= "</select>" . LF;
+
+ if (($this->menu != "") && (!$this->is_static)) {
+ global $menu;
+
+ $n = "";
+
+ foreach ($menu->_itens as $k => $v) {
+ foreach ($v["subs"] as $k2 => $v2) {
+ if ($v2->class == $this->menu) {
+ $n = $k . "-" . $k2;
+
+ break;
+ }
+ }
+ }
+
+ if ($n != "") {
+ $html .= "<img title='Editar registros' align='top' onclick=\"javascript: { document.location = '?menu=" . $n . "'; }\" src='../img/icons/table_edit.gif' style='cursor: pointer; margin: 1 2 0 3px; _margin: 2 2 0 3px;'>";
+ }
+ }
+
+ $this->element_key = $value;
+ if ($value != "") {
+ if (array_key_exists($value, $this->elements)) {
+ $this->value = $this->elements[$value];
+ }
+ }
+
+ return $html;
+ }
+
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->name = $filter_name;
+ $this->value = $filter_value;
+ $this->is_required = false;
+
+ $this->input_extra = "onChange=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+
+
+ $html .= " <td class='input'>" . $this->getInput() . "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+ if ($filter_value != "") {
+ $sql = " and " . $old_name . " = '" . $filter_value . "'";
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ function getHtmlList($tmp_extra) {
+ $this->formatValue();
+
+ $this->element_key = $this->value;
+ if (array_key_exists($this->value, $this->elements)) {
+ $this->value = $this->elements[$this->value];
+ } else {
+ $this->value = "";
+ }
+
+ if ($this->value == "") {
+ if ($this->element_key == "") {
+ $this->value = "<font color='silver'>(vazio)</font>";
+ } else {
+ $this->value = "<font color='silver'>[" . $this->element_key . "]</font>";
+ }
+ }
+
+ $html = "<td " . $tmp_extra . ">" . $this->value . "</td>" . LF;
+
+ return $html;
+ }
+
+ function loadInit() {
+ global $routine;
+
+ if (($routine == 'insert') || ($routine == 'update')) {
+ ?>
+ <script language="javascript">
+ var change = function () {
+ // Chama a funcao que vai trocar o select
+ findRel(this.value,this.name,'<?= $this->table_rel ?>','<?= $this->value_in_table ?>','<?= $this->name_in_table ?>','');
+ $$('<?= $this->_getFormatedId() ?>').disabled = false;
+ }
+
+ // PARAM
+ // value = valor do campo 'pai'
+ // name_field = nome do campo 'pai' para ser buscado na tabela
+ // table_rel = nome da tabela onde os valores serão buscados
+ // value_field_rel = valor que ficará no campo value no select
+ // name_field_rel = texto que aparecerá para o usuário no select
+ // value_select = valor atual do campo
+
+ function findRel(value,name_field,table_rel,value_field_rel,name_field_rel,value_select) {
+ var a = new Ajax();
+
+ a.onLoad = function() {
+ values = this.html;
+
+ arr_options = values.split('#');
+
+ selected = '';
+
+ for(x=0,total = arr_options.length;x<total;x++) {
+ value_option = arr_options[x].split('+');
+
+ $$('<?= $this->_getFormatedId() ?>').options[x] = new Option(value_option[1],value_option[0]);
+
+ if (value_option[0] == value_select) {
+ selected = x;
+ }
+ }
+
+ $$('<?= $this->_getFormatedId() ?>').selectedIndex = selected;
+ }
+
+ $$('<?= $this->_getFormatedId() ?>').innerHTML = '';
+
+ a.get('../../manager/routines/form/routines.php?routine=refresh_combo&value='+value+'&name_fields='+name_field+'&table_rel='+table_rel+'&value_field_rel='+value_field_rel+'&name_field_rel='+name_field_rel+'&value_select='+value_select);
+ }
+
+ if ($$('<?= $this->id_field_rel ?>_CMB1')) {
+ sufixo_rel = '_CMB1';
+ } else {
+ sufixo_rel = '_CMB0';
+ }
+
+ addEvent($$('<?= $this->id_field_rel ?>'+sufixo_rel), 'change', change);
+
+ if ($$('<?= $this->id_field_rel ?>'+sufixo_rel).value != '') {
+ // Acrescente no onchange do campo 'pai' a função para trocar esta combo
+ findRel($$('<?= $this->id_field_rel ?>'+sufixo_rel).value,$$('<?= $this->id_field_rel ?>'+sufixo_rel).name,'<?= $this->table_rel ?>','<?= $this->value_in_table ?>','<?= $this->name_in_table ?>','<?= $this->getValue(); ?>');
+ } else {
+ $$('<?= $this->_getFormatedId() ?>').disabled = true;
+ }
+ </script>
+ <?
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+class FieldMultiItems extends Field {\r
+ var $menu;\r
+ \r
+ var $_table_rel;\r
+ var $_table_rel_from_index;\r
+ var $_table_rel_to_index;\r
+ \r
+ var $number_cols;\r
+ \r
+ function FieldMultiItems($tmp_params) {\r
+ parent::Field("multiItems", $tmp_params[0]);\r
+ \r
+ $this->label = $tmp_params[1];\r
+ $this->validation = "CHK";\r
+ \r
+ if (isset($tmp_params[2])) {\r
+ $this->_table_rel = $tmp_params[2];\r
+ }\r
+ \r
+ if (isset($tmp_params[3])) {\r
+ $this->_table_rel_from_index = $tmp_params[3];\r
+ }\r
+ \r
+ if (isset($tmp_params[4])) {\r
+ $this->_table_rel_to_index = $tmp_params[4];\r
+ }\r
+ \r
+ $this->is_required = false;\r
+ $this->is_sql_affect = false;\r
+ $this->number_cols = 4;\r
+ \r
+ $this->accept_flags = "IUL";\r
+ }\r
+ \r
+ //private functions\r
+ function getInput() {\r
+ global $routine;\r
+ global $db;\r
+ global $form;\r
+ \r
+ //get values\r
+ $arr_values = array();\r
+ \r
+ if ($routine == "update") {\r
+ $sql = "select " . $this->_table_rel_to_index . " as k from " . $this->_table_rel . " where " . $this->_table_rel_from_index . " = '" . $form->fields("id") . "'";\r
+ $rs = $db->execute($sql);\r
+ \r
+ while (!$rs->EOF) {\r
+ $arr_values[$rs->fields("k")] = true;\r
+ \r
+ $rs->moveNext();\r
+ }\r
+ }\r
+ \r
+ \r
+ //list\r
+ $i = 1;\r
+ $s = "";\r
+ $html = "<table cellspaccing='0' cellpadding='0' width='100%'><tr><td>";\r
+ $disabled = '';\r
+ if($this->is_static){\r
+ $disabled = ' disabled ';\r
+ }\r
+ foreach ($this->elements as $k => $v) {\r
+ if (array_key_exists($k, $arr_values)) {\r
+ $s = " checked".$disabled;\r
+ } else {\r
+ $s = "".$disabled;\r
+ }\r
+ \r
+ $id = $this->_getFormatedId($i);\r
+ \r
+ $html .= "<div class='item' style='width:". floor(100 / $this->number_cols) ."%;'>";\r
+ $html .= "<div id='input'>";\r
+ $html .= "<input type='checkbox' id='" . $id . "' name='" . $this->name . "_" . $i . "' value='" . $k . "'" . $s . " " . $this->input_extra . ">";\r
+ $html .= "</div><div id='label' style='width:auto;'>";\r
+ $html .= "<label for='" . $id . "'>" . $v . "</label>";\r
+ $html .= "</div>";\r
+ $html .= "</div>" . LF;\r
+ \r
+ $i++;\r
+ }\r
+ \r
+ $html .= "<input type='hidden' name='" . $this->name . "_total' id='" . $this->_getFormatedId() . "' value='" . ($i-1) . "'>";\r
+ \r
+ if (($this->menu != "") && (!$this->is_static)) {\r
+ global $menu;\r
+ \r
+ $n = "";\r
+ \r
+ foreach ($menu->_itens as $k => $v) {\r
+ foreach ($v["subs"] as $k2 => $v2) {\r
+ if ($v2->class == $this->menu) {\r
+ $n = $k . "-" . $k2;\r
+ \r
+ break;\r
+ }\r
+ }\r
+ }\r
+ \r
+ if ($n != "") {\r
+ $html .= "</td><td align='right' valign='top' width='0'><img style='position: absolute; margin-left: -12px; cursor: pointer;' title='Editar registros' align='top' onclick=\"javascript: { document.location = '?menu=" . $n . "'; }\" src='../img/icons/table_edit.gif'>";\r
+ }\r
+ }\r
+ \r
+ $html .= "</td></tr></table>";\r
+ if($this->is_static){\r
+ $this->value = $html;\r
+ } else {\r
+ return $html;\r
+ }\r
+ }\r
+ \r
+ function onPosPost() {\r
+ global $db;\r
+ global $form;\r
+ global $routine;\r
+ global $input;\r
+ \r
+ if ($this->_table_rel != "") {\r
+ if ($routine == "update") {\r
+ $this->onDelete();\r
+ }\r
+ \r
+ $total = $input->post($this->name . "_total");\r
+ $i = 1;\r
+ $id = $form->fields("id");\r
+ \r
+ $inserts = array();\r
+ \r
+ while ($i <= $total) {\r
+ $v = $input->post($this->name . "_" . $i);\r
+ \r
+ if ($v != "") {\r
+ $inserts[] = "('" . $id . "', '" . $v . "')";\r
+ }\r
+ \r
+ $i++;\r
+ }\r
+ \r
+ if (sizeof($inserts) > 0) {\r
+ $sql = "insert into " . $this->_table_rel . " (" . $this->_table_rel_from_index . ", " . $this->_table_rel_to_index . ") values " . implode(", ", $inserts) . ";";\r
+ $db->execute($sql);\r
+ }\r
+ }\r
+ }\r
+ \r
+ function onDelete() {\r
+ global $form;\r
+ global $db;\r
+ \r
+ $sql = "delete from " . $this->_table_rel . " where " . $this->_table_rel_from_index . " = '" . $form->fields("id") . "'";\r
+ $db->execute($sql);\r
+ }\r
+ \r
+ function getHtmlList($tmp_extra) {\r
+ $this->formatValue();\r
+ \r
+ $this->element_key = $this->value;\r
+ if (array_key_exists($this->value, $this->elements)) {\r
+ $this->value = $this->elements[$this->value];\r
+ } else {\r
+ $this->value = "";\r
+ }\r
+ \r
+ if ($this->value == "") {\r
+ if ($this->element_key == "") {\r
+ $this->value = "<font color='silver'>(vazio)</font>";\r
+ } else {\r
+ $this->value = "<font color='silver'>[" . $this->element_key . "]</font>";\r
+ }\r
+ }\r
+ \r
+ $html = "<td " . $tmp_extra . ">" . $this->value . "</td>" . LF;\r
+ \r
+ return $html;\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldMultiUpload extends Field {
+ var $path;
+ var $file_name;
+
+ var $extensions_accept;
+
+ var $path_tmp;
+
+ function FieldMultiUpload($tmp_params) {
+ parent::Field("multiupload", $tmp_params[0]);
+
+ $this->flags_accept = "IU";
+
+ $this->label = $tmp_params[1];
+ $this->validation = "TXT";
+ $this->is_sql_affect = false;
+
+ $this->file_name = "";
+ $this->extensions_accept = array("txt", "php");
+
+ if (isset($tmp_params[2])) {
+ $this->setPath($tmp_params[2]);
+ }
+
+ if (isset($tmp_params[3])) {
+ $this->setFileName($tmp_params[3]);
+ }
+
+ $this->setTmpPath("upload/tmp/");
+
+ global $routine;
+ if ($routine == "update") {
+ $this->is_required = false;
+ }
+ }
+
+ function setPath($tmp_path) {
+ $this->path = "../../../" . $tmp_path;
+ }
+
+ function setTmpPath($tmp_path) {
+ $this->path_tmp = "../../../" . $tmp_path;
+ }
+
+ function setFileName($tmp_template) {
+ $this->file_name = $tmp_template;
+ }
+
+
+ //private functions
+ function getInput() {
+ $required_backup = $this->is_required;
+ $label_backup = $this->label;
+
+ $this->is_required = false;
+ $this->label = rand(1, 100000000);
+
+ $html = "<input ";
+ $html .= "class='input' ";
+ $html .= "type='file' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "style='width: 230px;' ";
+ $html .= ">";
+ $html .= "<a href='#' onclick=\"javascript: uploadSubmit('" . $this->name . "')\">upload</a>";
+
+ $this->is_required = $required_backup;
+ $this->label = $label_backup;
+
+ return $html;
+ }
+
+ function getHtml() {
+ global $routine;
+ global $form;
+
+ $html = "<tr>";
+
+ //Label
+ if ($this->label != "") {
+ $html .= "<td class='label'>";
+
+ $html .= $this->label . ": ";
+
+ if ($this->is_required) {
+ $html .= "<font class='red'>*</font>";
+ }
+
+ $html .= "</td>" . LF;
+ }
+
+ $this->formatValue();
+
+ //Input
+ $html .= "<td class='input'>";
+
+ if ($this->is_static) {
+ error(1, "Um campo 'upload' não pode ser estático.", "FieldUpload", "getHtml");
+ }
+
+ //.input
+ $html .= "<div id='" . $this->name . "_div_input' class='box_silver'>";
+ $html .= $this->getInput();
+ $html .= "</div>";
+
+ //.loading message
+ $html .= "<div id='" . $this->name . "_div_loading' class='box_silver' style='display: none; height: 15px; margin-top: 5px;'>Loading...</div>";
+
+ //.error box
+ $html .= "<div id='" . $this->name . "_div_error' class='box_red' style='display: none; height: 20px; margin-top: 5px;'></div>";
+
+ //.list
+ if (IS_DEVELOP) {
+ $html .= "<a href='#' onclick=\"javascript: uploadList('" . $this->name . "');\">refresh list</a><br>";
+ }
+ $html .= "<table width='100%' style='margin-top: 5px;'><tr><td class='box_yellow' id='" . $this->name . "_div_list' style='display: none;'></td></tr></table>";
+
+ //.list of tmp files
+ if ($routine == "insert") {
+ $html .= "<input type='hidden' id='" . $this->_getFormatedId() . "' value=''>";
+
+ $_SESSION[$this->name . "_files"] = array();
+ }
+
+ //.if update, upload list of files
+ if ($routine == "update") {
+ $html .= "<script>uploadList('" . $this->name . "');</script>";
+ }
+
+ $html .= "</td></tr>" . LF;
+
+ return $html;
+ }
+
+ function onPosPost() {
+ global $routine;
+ global $file;
+ global $form;
+ global $input;
+
+ if ($routine == "insert") {
+ $list = $input->session($this->name . "_files");
+
+ if (is_array($list)) {
+ $i = 1;
+ foreach ($list as $v) {
+ if (file_exists($v)) {
+ $ext = $file->getExtension($v);
+
+ $file->copyFile($v, $this->_getPath() . $this->_getFile($i) . "." . $ext);
+
+ $file->deleteFile($v);
+
+ $i++;
+ }
+ }
+ }
+
+ $input->unsetSession($this->name . "_files");
+ }
+
+ //delete old files from tmp folder
+ $list = $file->listFolder($this->path_tmp);
+
+ if (is_array($list)) {
+ foreach ($list as $v) {
+ $path = $this->path_tmp . $v;
+
+ $arr2 = explode(".", $v);
+ $arr = explode("_", $arr2[0]);
+ $date_modified = (float)$arr[1];
+
+ //2 hours limit
+ if (time() > ($date_modified + (2 * 60 * 60))) {
+ $file->deleteFile($path);
+ }
+ }
+ }
+ }
+
+ function onDelete() {
+ global $file;
+
+ //delete files
+ $list = $this->_getListFiles();
+
+ foreach ($list as $v) {
+ $file->deleteFile($v);
+ }
+
+ //delete path if is empty
+ $path = $this->_getPath();
+ $list = $file->listFolder($path);
+
+ if (sizeof($list) == 0) {
+
+ $file->deleteFolder($path);
+ }
+ }
+
+ //Ajax functions
+ function ajaxRoutine($tmp_routine) {
+ global $file;
+ global $routine;
+ global $input;
+
+ $html = "";
+
+ switch ($tmp_routine) {
+ case "upload":
+ if ($routine == "insert") {
+ $file_dest = $this->_getTempFile();
+ } else {
+ $file_dest = $this->_getNewFile();
+ }
+
+ $ext = $file->getExtension($_FILES[$this->name]["name"]);
+
+ if (array_search($ext, $this->extensions_accept) !== false) {
+ if (move_uploaded_file($_FILES[$this->name]["tmp_name"], $file_dest . "." . $ext)) {
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = 'none';" . LF;
+
+ if ($routine == "insert") {
+ $html .= "var n = window.parent.$$('" . $this->_getFormatedId() . "').value;";
+ $html .= "n++; n--;";
+ $html .= "window.parent.$$('" . $this->_getFormatedId() . "').value = (n + 1);";
+
+ $_SESSION[$this->name . "_files"][] = $file_dest . "." . $ext;
+ }
+
+ $html .= "</script>";
+ } else {
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = 'Erro ao fazer upload.';" . LF;
+ $html .= "</script>";
+ }
+ } else {
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = \"Extensão não permitida.<br>Utilize somente '" . implode(", ", $this->extensions_accept) . "'\";" . LF;
+ $html .= "</script>";
+ }
+
+ break;
+ case "list":
+ if ($routine == "insert") {
+ $list = $_SESSION[$this->name . "_files"];
+ } else {
+ $list = $this->_getListFiles();
+ }
+
+ if (sizeof($list) > 0) {
+ $i = 1;
+ foreach ($list as $v) {
+ $path_clean = str_replace("../../../", "", $v);
+
+ $html .= "<div class='upload_item'>";
+ $html .= "<div class='label'>" . $i . ". <a href='../../_system/scripts/download.php?file=" . $path_clean . "' target='ifr_aux'>" . $path_clean . "</a></div>";
+ $html .= "<div class='size'>" . $file->fileSizeFormated($v) . "</div>";
+ $html .= "<div class='buttons'><a href=\"javascript: { uploadDelete('" . $this->name . "', '" . $i . "'); }\">del</a></div>";
+ $html .= "</div>" . LF;
+
+ $i++;
+ }
+
+ $html .= "<script>" . LF;
+ $html .= "$$('" . $this->name . "_div_list').style.display = '';" . LF;
+ $html .= "</script>";
+ } else {
+ $html .= "<script>" . LF;
+ $html .= "$$('" . $this->name . "_div_list').style.display = 'none';" . LF;
+ $html .= "</script>";
+ }
+
+ $html .= "<script>";
+ $html .= "$$('" . $this->name . "_div_input').style.display = '';" . LF;
+ $html .= "$$('" . $this->name . "_div_input').innerHTML = '" . str_replace("'", "\'", $this->getInput()) . "';" . LF;
+ $html .= "</script>";
+
+ break;
+ case "delete":
+ if ($routine == "insert") {
+ $list = $_SESSION[$this->name . "_files"];
+ } else {
+ $list = $this->_getListFiles();
+ }
+
+ $file->deleteFile($list[($input->get("n") - 1)]);
+
+ if ($routine == "insert") {
+ //unset file in session list
+ $new_list = array();
+
+ if (sizeof($list) > 1) {
+ unset($_SESSION[$this->name . "_files"][($input->get("n") - 1)]);
+
+ $i = 1;
+ foreach ($_SESSION[$this->name . "_files"] as $v) {
+ echo $v;
+ $new_list[$i] = $v;
+
+ $i++;
+ }
+ }
+
+ $_SESSION[$this->name . "_files"] = $new_list;
+ } else {
+ $this->_sortFiles();
+ }
+
+ $html .= "<script>uploadList('" . $this->name . "');</script>";
+
+ break;
+ }
+
+ return $html;
+ }
+
+ function _getTempFile() {
+ global $file;
+
+ $file_name = substr("00000" . rand(1, 999999), -6) . "_" . time();
+
+ $exists = false;
+
+ foreach ($this->extensions_accept as $v) {
+ if (file_exists($this->path_tmp . $file_name . "." . $v)) {
+ $exists = true;
+ }
+ }
+
+ if ($exists) {
+ $file_name = $this->_getTempFile();
+ }
+
+
+ //create tmp folder(s)
+ $arr = explode("/", $this->path_tmp);
+ $path = "";
+ foreach ($arr as $name) {
+ if (strlen($name) > 0) {
+ $path .= $name . "/";
+
+ if (substr($path, -3) != "../") {
+ $file->makeFolder($path);
+ }
+ }
+ }
+
+ return $this->path_tmp . $file_name;
+ }
+
+ function _getPath() {
+ global $form;
+ global $file;
+
+ $path = $this->path;
+
+ foreach ($form->fields as $k => $v) {
+ $path = str_replace("#" . strtoupper($k) . "#", $v, $path);
+ }
+
+ //create folder(s)
+ $arr = explode("/", $path);
+ $path = "";
+ foreach ($arr as $name) {
+ if (strlen($name) > 0) {
+ $path .= $name . "/";
+
+ if (substr($path, -3) != "../") {
+ $file->makeFolder($path);
+ }
+ }
+ }
+
+ return $path;
+ }
+
+ function _getFile($tmp_n = 1) {
+ global $form;
+
+ $f = $form;
+
+ global $rs_list;
+ if (is_object($rs_list)) {
+ $f = $rs_list;
+ }
+
+ $file_name = $this->file_name;
+
+ $file_name = str_replace("#N#", $tmp_n, $file_name);
+
+ foreach ($f->fields as $k => $v) {
+ $file_name = str_replace("#" . strtoupper($k) . "#", $v, $file_name);
+ }
+
+ return $file_name;
+ }
+
+ function _getListFiles() {
+ global $file;
+
+ $path = $this->_getPath();
+
+ $list = $file->listFolder($path);
+
+ foreach ($list as $k => $v) {
+ $list[$k] = $path . $v;
+ }
+
+ return $list;
+ }
+
+ function _getNewFile($tmp_n = 1) {
+ $file = $this->_getPath() . $this->_getFile($tmp_n);
+
+ $exists = false;
+
+ foreach ($this->extensions_accept as $v) {
+ if (file_exists($file . "." . $v)) {
+ $exists = true;
+ }
+ }
+
+ if ($exists) {
+ $file = $this->_getNewFile($tmp_n + 1);
+ }
+
+ return $file;
+ }
+
+ function _sortFiles() {
+ global $file;
+
+ $path = $this->_getPath();
+
+ $list = $file->listFolder($path);
+
+ $i = 1;
+ $i2 = 1;
+ foreach ($list as $v) {
+ $ext = $file->getExtension($v);
+
+ $file_name = $this->_getFile($i);
+
+ $file->rename($path . $v, $path . $file_name . "." . $ext);
+
+ $i++;
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldNumber extends Field {
+ function FieldNumber($tmp_params) {
+ parent::Field("number", $tmp_params[0]);
+
+ $this->testRequiredType(array("int", "double", "float"));
+
+ $this->label = $tmp_params[1];
+ $this->validation = "NUM";
+ $this->size_cols = 70;
+ $this->maxlength = 255;
+ $this->loadConfig("int");
+ }
+
+ function loadConfig($tmp_type) {
+ switch ($tmp_type) {
+ default:
+ case "int":
+ $this->config_type = "int";
+ $this->validation = "NUM";
+ $this->size_cols = 60;
+ $this->maxlength = 255;
+
+ break;
+ case "fone":
+ $this->config_type = "fone";
+ $this->validation = "TEL";
+ $this->size_cols = 20;
+ $this->maxlength = 14;
+ $this->minlength = 14;
+ $this->label = "Telefone";
+
+ break;
+ case "cpf":
+ $this->config_type = "cpf";
+ $this->validation = "CPF";
+ $this->size_cols = 25;
+ $this->maxlength = 14;
+ $this->minlength = 14;
+ $this->label = "Cpf";
+
+ break;
+ case "money":
+ $this->config_type = "money";
+ $this->validation = "DIN";
+ $this->size_cols = 20;
+ $this->list_width = 100;
+ $this->maxlength = 20;
+
+ break;
+ case "float":
+ $this->config_type = "float";
+ $this->validation = "FLO";
+ $this->size_cols = 20;
+ $this->list_width = 100;
+ $this->maxlength = 20;
+
+ break;
+ }
+ }
+
+ //private functions
+ function getInput() {
+ if ($this->input_type == "textarea") {
+ $html = "<textarea ";
+ $html .= "class='input' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "cols='" . $this->size_cols . "' ";
+ $html .= "rows='" . $this->size_rows . "' ";
+ $html .= "style='height: " . ($this->size_rows * 15) . "px;' ";
+ $html .= $this->input_extra . ">";
+ $html .= $this->getValue();
+ $html .= "</textarea>";
+ } else {
+ $html = "<input ";
+ $html .= "class='input' ";
+ $html .= "type='text' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "size='" . $this->size_cols . "' ";
+ $html .= "maxlength='" . $this->maxlength . "' ";
+ $html .= "value=\"" . $this->_escapeValue($this->getValue()) . "\" ";
+ $html .= " " . $this->input_extra;
+ $html .= ">";
+ }
+
+ return $html;
+ }
+
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->name = $filter_name;
+ $this->value = $filter_value;
+ $this->input_extra = "onKeyUp=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ $this->is_required = false;
+
+ if (($this->config_type == "email") || ($this->config_type == "fone")) {
+ $this->validation = "TXT";
+ }
+
+ $html .= " <td class='input'>" . $this->getInput() . "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+ if ($filter_value != "") {
+ $sql = " and " . $old_name . " LIKE '%" . $filter_value . "%'";
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ function getHtml() {
+ $this->is_formated = false;
+
+ $html = "<tr>";
+
+ if ($this->label != "") {
+ $html .= "<td class='label'>";
+
+ $html .= $this->label . ": ";
+
+ if ($this->is_required) {
+ $html .= "<font class='red'>*</font>";
+ }
+
+ $html .= "</td>" . LF;
+ }
+
+ $this->formatValue();
+
+ $html .= "<td class='input'>";
+
+ if ($this->is_static) {
+ $this->getInput();
+
+ $html .= "<font color='#59748E'>" . $this->getValue() . "</font>";
+ } else {
+ $html .= $this->getInput();
+ }
+
+ $html .= "</td></tr>" . LF;
+
+ return $html;
+ }
+
+ function getValueFormated() {
+ if ($this->config_type == "money") {
+ global $load;
+
+ $load->setOverwrite(true);
+ $load->system("functions/text.php");
+
+ return formatMoney($this->value);
+ } elseif ($this->config_type == "float") {
+ global $load;
+
+ $load->setOverwrite(true);
+ $load->system("functions/text.php");
+
+ return formatFloat($this->value);
+ } else {
+ return $this->value;
+ }
+ }
+
+ function getValueUnformated() {
+ if (($this->config_type == "money") || ($this->config_type == "float")){
+ $tmp_value = str_replace(".", "", $this->value);
+
+ return str_replace(",", ".", $tmp_value);
+ } else {
+ return $this->value;
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldOrder extends Field {
+ function FieldOrder($tmp_params) {
+ parent::Field("order", ($tmp_params[0] != "") ? $tmp_params[0] : "ordem");
+
+ $this->testRequiredType(array("int"));
+
+ $this->label = ($tmp_params[1] != '') ? $tmp_params[1] : "Ordem";
+
+ $this->list_width = 63;
+ $this->flags_accepted = "LO";
+ }
+
+ //private functions
+ function getInput() {
+ $html = "";
+
+ return $html;
+ }
+
+ function getFilter() {
+ $html = "";
+ $sql = "";
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ function getHtmlList($tmp_extra) {
+ global $rs_list;
+ global $form;
+ global $records_total;
+ global $i;
+
+ $tmp = explode("onclick", $tmp_extra);
+
+ $is_first = (($rs_list->absolutepage == 1) && ($i == 1));
+ $is_last = (($rs_list->absolutepage == $rs_list->pagecount) && ($i == $records_total));
+
+ $html = "<td " . $tmp[0] . " align='center'>";
+
+ $order = $form->_getOrderValue();
+ $order_parsed = explode("#", $order);
+
+ if ($order_parsed[0] == $this->name) {
+ if (!$is_last) {
+ $html .= "<img onclick=\"javascript: orderSwap('" . $this->name . "', '" . $rs_list->fields($form->key_field) . "', '1');\" style='cursor: pointer;' src='../img/icons/arow_down2.gif'> ";
+ } else {
+ $html .= " ";
+ }
+
+ if (!$is_first) {
+ $html .= "<img onclick=\"javascript: orderSwap('" . $this->name . "', '" . $rs_list->fields($form->key_field) . "', '-1');\" style='cursor: pointer;' src='../img/icons/arow_up2.gif'>";
+ } else {
+ $html .= " ";
+ }
+ } else {
+ $html .= $this->value . "";
+ }
+
+ $html .= "</td>" . LF;
+
+ return $html;
+ }
+
+ function onPosPost() {
+ global $form;
+ global $routine;
+
+ if (($routine == "insert") || (($routine == "update") && (($form->fields[$this->name] == "") || ($form->fields[$this->name] == "0")))) {
+ $form->fields[$this->name] = $form->fields[$form->key_field];
+ $form->update();
+ }
+ }
+
+ function ajaxRoutine($tmp_routine) {
+ global $routine;
+ global $input;
+ global $db;
+ global $form;
+
+ //Set order values
+ $sql = "select count(" . $form->key_field . ") as total from " . $form->table . " where (" . $this->name . " = '' or " . $this->name . " = '0' or " . $this->name . " <= 0 or " . $this->name . " is null);";
+ $rs = $db->execute($sql);
+
+ if (!$rs->EOF) {
+ if ($rs->fields("total") > 0) {
+ $sql = "update " . $form->table . " set " . $this->name . " = " . $form->key_field . " where (" . $this->name . " = '' or " . $this->name . " = '0' or " . $this->name . " <= 0 or " . $this->name . " is null);";
+ $db->execute($sql);
+ }
+ }
+
+ //Swap orders
+ $direction = $input->get("direction");
+ $sql_list = base64_decode($input->post("sql"));
+
+ //.From id/order
+ $from_id = $input->get("tmp_id");
+
+ $sql = "select " . $this->name . " from " . $form->table . " where " . $form->key_field . " = '" . $from_id . "';";
+ $rs = $db->execute($sql);
+
+ if (!$rs->EOF) {
+ $from_order = $rs->fields($this->name);
+
+ //.To id/order
+ $rs = $db->execute($sql_list);
+
+ $to_id = 0;
+ $to_order = 0;
+ $tmp = 0;
+
+ if ($direction == "-1") {
+ while (!$rs->EOF) {
+ if ($rs->fields($form->key_field) != $from_id) {
+ $to_id = $rs->fields($form->key_field);
+ $to_order = $rs->fields($this->name);
+ } else {
+ break;
+ }
+
+ $rs->moveNext();
+ }
+ } else {
+ while (!$rs->EOF) {
+ if ($rs->fields($form->key_field) == $from_id) {
+ $rs->moveNext();
+
+ $to_id = $rs->fields($form->key_field);
+ $to_order = $rs->fields($this->name);
+
+ break;
+ }
+
+ $rs->moveNext();
+ }
+ }
+
+ $sql = "update " . $form->table . " set " . $this->name . " = '" . $to_order . "' where " . $form->key_field . " = '" . $from_id . "'";
+ $db->execute($sql);
+
+ $sql = "update " . $form->table . " set " . $this->name . " = '" . $from_order . "' where " . $form->key_field . " = '" . $to_id . "'";
+ $db->execute($sql);
+
+ echo $direction . "\n";
+
+ echo $from_order . " - " . $from_id . "\n";
+ echo $to_order . " - " . $to_id;
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldPassword extends Field {
+ var $second_field;
+
+ function FieldPassword($tmp_params) {
+ parent::Field("password", $tmp_params[0]);
+
+ $this->testRequiredType(array("varchar"));
+
+ $this->flags_accept = "LOIU";
+
+ if (isset($tmp_params[1])) {
+ $this->label = $tmp_params[1];
+ } else {
+ $this->label = "Senha";
+ }
+ $this->validation = "PW1";
+ $this->size_cols = 30;
+ $this->maxlength = 30;
+ $this->second_field = false;
+
+ global $routine;
+ if (($this->value != "") && ($routine == "update")) {
+ $this->is_required = false;
+ }
+ }
+
+
+ //private functions
+ function getInput() {
+ $html = "<input ";
+ $html .= "class='input' ";
+ $html .= "type='password' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "size='" . $this->size_cols . "' ";
+ $html .= "maxlength='" . $this->maxlength . "' ";
+ $html .= "value=\"" . $this->_escapeValue($this->getValue()) . "\" ";
+ $html .= " " . $this->input_extra;
+ $html .= ">";
+
+ return $html;
+ }
+
+ function getHtml() {
+ $html = "<tr>";
+
+ if ($this->label != "") {
+ $html .= "<td class='label'>";
+
+ $html .= $this->label . ": ";
+
+ if ($this->is_required) {
+ $html .= "<font class='red'>*</font>";
+ }
+
+ $html .= "</td>" . LF;
+ }
+
+ $html .= "<td class='input'>";
+
+ if ($this->is_static) {
+ $html .= "<font color='#59748E'>" . $this->getValue() . "</font>";
+ } else {
+ $this->value = "";
+
+ $html .= $this->getInput();
+ }
+
+ $html .= "</td></tr>" . LF;
+
+ if ((!$this->is_static) && (!$this->second_field)) {
+ $this->validation = "PW2";
+ $this->second_field = true;
+ $this->label = "Confirmação de " . strtolower($this->label);
+
+ $html .= $this->getHtml();
+ }
+
+ return $html;
+ }
+
+ function onPrePost() {
+ if ($this->value == "") {
+ $this->is_sql_affect = false;
+ }
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldRelItems extends Field {
+ var $menu;
+
+ var $_table_rel;
+ var $_table_rel_from_index;
+ var $_table_rel_to_index;
+ var $_table_source;
+
+ var $_search_label;
+ var $_result_label;
+
+ var $_id_hidden;
+ var $_id_td_result;
+ var $_id_td_rel;
+ var $_id_arrSearch;
+ var $_id_arrRel;
+ var $_id_js;
+ var $search_page;
+ var $search_page_width;
+ var $search_page_height;
+
+ function FieldRelItems($tmp_params) {
+ parent::Field("relItems", $tmp_params[0]);
+
+ $this->label = $tmp_params[1];
+ $this->validation = "CHK";
+
+ if (isset($tmp_params[2])) {
+ $this->_table_rel = $tmp_params[2];//tabela de relacionamento
+ }
+ if (isset($tmp_params[3])) {
+ $this->_table_rel_from_index = $tmp_params[3];//nome do campo dentro da tabela de relacionamento a que se refere o campo atual do registro no form
+ }
+ if (isset($tmp_params[4])) {
+ $this->_table_rel_to_index = $tmp_params[4];//nome do campo dentro da tabela de relacionamento que se refere aos campos que serão relacionados
+ }
+ if (isset($tmp_params[5])) {
+ $this->_table_source = $tmp_params[5];//tabela de onde os relacionados devem vir, sempre com id e nome
+ }
+ if (isset($tmp_params[6])) {
+ $this->search_page = $tmp_params[6];//url da pagina de busca
+ }
+ $this->search_page_width = 450;
+ $this->search_page_height = 135;
+
+ $this->_search_label = "Pesquise ".$this->label." para relacionar";
+ $this->_result_label = $this->label." relacionados";
+
+ $this->is_required = false;
+ $this->is_sql_affect = false;
+
+ $this->accept_flags = "IU";
+
+ //define variaveis utilizadas no ajax - evita conflitos
+ $this->_id_hidden = "hidden_".$this->name;
+ $this->_id_td_result = "td_result_".$this->name;
+ $this->_id_td_rel = "td_rel_".$this->name;
+ $this->_id_arrSearch = "arrSearch_".$this->name;
+ $this->_id_arrRel = "arrRel_".$this->name;
+
+ $this->_id_js = "relItem_".$this->name;
+ }
+
+ //utilities functions
+ function getHtmlBox(){
+ $box = "</table></td></tr></table></div><div class='form' style='margin-top: 5px;' id=''><table cellspacing='0' cellpadding='0' width='100%' height='100%'>".LF;
+ $box .= "<tr><td width='49%' valign='top'><table cellspacing='3' cellpadding='0' width='100%'>".LF;
+
+ return $box;
+ }
+ function getHtmlSeparador(){
+ $separador = "</table></td><td width='2%' align='center'>" . LF;
+ $separador .= "<table cellspacing='0' cellpadding='0' height='100%' style='border-left: 1px solid #E4E4E4;'><tr><td></td></tr></table>" . LF;
+ $separador .= "</td><td width='49%' valign='top'><table cellspacing='3' cellpadding='0' width='100%' id='' style=''>" . LF;
+
+ return $separador;
+ }
+ function getHtmlLabel($label){
+ return "<tr class='fieldset'><td class='custom' colspan='100%'><strong>".$label."</strong></td></tr>";
+ }
+ function seFromRs($rs){
+ //entre registros
+ $entreReg = "###";
+ //entre valores
+ $entreVal = "$$$";
+
+ $retorno = "";
+ if(!$rs->EOF){
+ while(!$rs->EOF){
+ $retorno .= $rs->fields("id");
+ $retorno .= $entreVal;
+ $retorno .= $rs->fields("nome");
+
+ $rs->moveNext();
+ if(!$rs->EOF)
+ $retorno .= $entreReg;
+ }
+ }
+ return $retorno;
+ }
+
+ //private functions
+ function getHtml() {
+ global $routine;
+ global $db;
+ global $form;
+
+ //get values
+ $value = "";
+
+ if ($routine == "update") {
+ $sql = "SELECT ".$this->_table_rel_to_index." as k FROM ".$this->_table_rel." WHERE ".$this->_table_rel_from_index." = ".$form->fields("id");
+ $rs = $db->execute($sql);
+
+ $strIn = "";
+ if(!$rs->EOF) {
+ while (!$rs->EOF) {
+ $strIn .= $rs->fields("k");
+ $rs->moveNext();
+ if(!$rs->EOF) {
+ $strIn .= ",";
+ }
+ }
+
+ if($strIn != ""){
+ $sql = " SELECT id, nome FROM ".$this->_table_source." WHERE id IN(".$strIn.") ";
+ $rs = $db->execute($sql);
+ $value = $this->seFromRs($rs);
+ }
+ }
+ }
+
+ //list
+ $i = 1;
+ $s = "";
+
+ $html = '<input type="hidden" id="'.$this->_id_hidden.'" name="'.$this->_id_hidden.'" value="'.$value.'" />';
+ $html .= $this->getHtmlBox();
+ if(!$this->is_static){
+ $html .= $this->getHtmlLabel($this->_search_label);
+ $html .= '
+ <tr>
+ <td colspan="100%">
+ <table cellspacing="3" cellpadding="0" border="0" width="100%">
+ <tr>
+ <td style="background:#F9F9F9 none repeat scroll 0 0;">
+ <iframe id="frameSearch_'.$this->label.'" name="frameSearch_'.$this->label.'" style="width:'.$this->search_page_width.'px;height:'.$this->search_page_height.'px;border:0px;" frameborder="0" scrolling="no" src="../../'.$this->search_page.'?_id_js='.$this->_id_js.'"></iframe>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr class="fieldset">
+ <td class="custom">
+ Resultados da pesquisa
+ </td>
+ </tr>
+ <tr>
+ <td id="'.$this->_id_td_result.'">
+ Nenhum item encontrado
+ </td>
+ </tr>
+ ';
+ $html .= $this->getHtmlSeparador();
+ }
+ $html .= $this->getHtmlLabel($this->_result_label);
+ $static = 'false';
+ if($this->is_static){
+ $static = 'true';
+ }
+ $html .= '
+ <tr>
+ <td id="'.$this->_id_td_rel.'">
+ Nenhum item relacionado.
+ <script type="text/javascript">
+ '.$this->_id_js.' = new relItem("'.$this->_id_js.'","'.$this->_id_hidden.'","'.$this->_id_td_result.'","'.$this->_id_td_rel.'",'.$static.');
+ </script>
+ </td>
+ </tr>
+ ';
+
+ return $html;
+ }
+ function onPosPost() {
+ global $db;
+ global $form;
+ global $routine;
+ global $input;
+
+ if ($this->_table_rel != "") {
+ if ($routine == "update") {
+ $this->onDelete();
+ }
+
+ global $load;
+ $load->system('functions/text.php');
+ $arrRel = unse($input->post($this->_id_hidden));
+
+ $id = $form->fields("id");
+
+ $inserts = array();
+
+ for ($x=0;$x<sizeof($arrRel);$x++){
+ if(isset($arrRel[$x][0])){
+ $inserts[] = "('" . $id . "', '" . $arrRel[$x][0] . "')";
+ }
+ }
+
+ if (sizeof($inserts) > 0) {
+ $sql = "INSERT INTO " . $this->_table_rel . " (" . $this->_table_rel_from_index . ", " . $this->_table_rel_to_index . ") VALUES " . implode(", ", $inserts) . ";";
+ $db->execute($sql);
+ }
+ }
+ }
+ function onDelete() {
+ global $form;
+ global $db;
+
+ $sql = "DELETE FROM " . $this->_table_rel . " WHERE " . $this->_table_rel_from_index . " = '" . $form->fields("id") . "'";
+ $db->execute($sql);
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldTree extends Field {
+ var $menu;
+ var $args = array();
+ var $arr_pais = array();
+ /* 0 - idcategoria (campo a ser salvo na tabela que ele se encontra)
+ * 1 - label (label do campo e name do hidden)
+ * 2 - id (campo a ser buscado na tabela)
+ * 3 - idPai (campo que se relaciona com o id)
+ * 4 - nome (campo que será mostrado nos outros combos)
+ * 5 - tabela (tabela)
+ */
+
+ function FieldTree($tmp_params) {
+ parent::Field("items", $tmp_params[0]);
+
+ $this->testRequiredType(array("varchar", "int"));
+
+ $this->label = $tmp_params[1];
+ $this->setInputType("select");
+ $this->args = array($tmp_params[2],$tmp_params[3],$tmp_params[4],$tmp_params[5]);
+ }
+
+ function setInputType($tmp_type) {
+ switch ($tmp_type) {
+ default:
+ case "select":
+ $this->input_type = "select";
+ $this->validation = "CMB";
+
+ break;
+ }
+ }
+
+ //private functions
+ function getInput() {
+ $value = $this->getValue();
+
+ switch ($this->input_type) {
+ default:
+ case "select":
+ /* 0 - id (campo a ser buscado na tabela)
+ * 1 - idPai (campo que se relaciona com o id)
+ * 2 - nome (campo que será mostrado nos outros combos)
+ * 3 - tabela (tabela)
+ */
+ //print_r2($this->$args);
+ $args_line = implode(",",$this->args);
+ $html = "<input type='hidden' id='".$this->name."_id' name='".$this->name."' value='".$value."'>".LF;//hidden que o sistema "verá"
+ $html .= "<input type='hidden' id='".$this->label."_filhos' name='".$this->label."_filhos' value=''>".LF;//hidden com os filhos separados por "!!!"
+ $html .= "<input type='hidden' id='".$this->label."_linha_pais' name='".$this->label."_linha_pais' value='$ARR_PAIS$'>".LF;
+ $html .= "<input type='hidden' id='".$this->label."_args' name='".$this->label."_args' value='".$args_line."'>".LF;//hidden com os argumentos para se utilizar na rotina de atualização
+ $html .= "".LF;
+
+ $html .= "<select class='input' id='".$this->label."_pai' name='".$this->label."_pai' onchange='javascript: ai(this,\"".$this->name."_id\");' ".$this->input_extra.">".LF;
+ $html .= "<option value=''>Selecione</option>".LF;
+ $html .= "<option value=''>------</option>".LF;
+ $passou = false;
+ foreach ($this->elements as $k => $v) {
+ if ($k == $value) {
+ $s = " selected";
+ $passou = true;
+ } else {
+ $s = "";
+ }
+ $html .= "<option value='".$k."'".$s.">".$v."</option>".LF;
+ }
+
+ $html .= "</select>" . LF;
+ $html .= "<BR>".LF;
+ $html .= "<div id='".$this->label."_pai_div' style='padding-top: 5px;'></div>";
+
+ if(!$passou) {
+ $this->loadByChild($value); //descobre os pais do cara que está selecionado e põe no arr_pais da classe
+ $this->arr_pais = array_reverse($this->arr_pais);
+ $this->arr_pais[] = $value;
+ //echo "<BR><BR>valor atual: ".$value."<BR>";
+ //print_r2($this->arr_pais);
+ //die;
+
+ $pais_line = implode(",",$this->arr_pais);
+ //echo $pais_line."<BR>";
+ $html = str_replace("$ARR_PAIS$",$pais_line, $html);
+ $html .= "<script type='text/javascript'>".LF;
+ $html .= "loadFromFilho($$('".$this->label."_pai'));".LF;
+ $html .= "</script>".LF;
+ }else{
+ $html = str_replace("$ARR_PAIS$","", $html);
+ }
+ break;
+ }
+
+ if (($this->menu != "") && (!$this->is_static)) {
+ global $menu;
+
+ $n = "";
+
+ foreach ($menu->_itens as $k => $v) {
+ foreach ($v["subs"] as $k2 => $v2) {
+ if ($v2->class == $this->menu) {
+ $n = $k . "-" . $k2;
+
+ break;
+ }
+ }
+ }
+
+ if ($n != "") {
+ $html .= "<img title='Editar registros' align='top' onclick=\"javascript: { document.location = '?menu=" . $n . "'; }\" src='../img/icons/table_edit.gif' style='cursor: pointer; margin: 1 2 0 3px; _margin: 2 2 0 3px;'>";
+ }
+ }
+
+ $this->element_key = $value;
+ if ($value != "") {
+ if (array_key_exists($value, $this->elements)) {
+ $this->value = $this->elements[$value];
+ }
+ }
+
+ return $html;
+ }
+ function loadByChild($idComparar = "") {
+ global $db;
+
+ //se entrou aqui, significa que não encontrou o valor atual dentro da primeira lista (pai)
+ /* 0 - id (campo a ser buscado na tabela)
+ * 1 - idPai (campo que se relaciona com o id)
+ * 2 - nome (campo que será mostrado nos outros combos)
+ * 3 - tabela (tabela)
+ */
+ $sql = "select distinct ".$this->args[0].",".$this->args[2].",".$this->args[1]." from ".$this->args[3]." where ".$this->args[0]."=".$idComparar;
+ //echo $sql."<BR>";
+ if ($idComparar != "")
+ $rs_pais = $db->execute($sql);
+ else
+ return;
+
+ if ($rs_pais->recordcount > 0){
+ if ($rs_pais->fields($this->args[1]) == $idComparar){
+ return;
+ }else{
+ if($rs_pais->fields($this->args[1]) != "") {
+ $this->arr_pais[] = $rs_pais->fields($this->args[1]);
+ $this->loadByChild($rs_pais->fields($this->args[1]));
+ }else{
+ return;
+ }
+ }
+ }
+ }
+ function getFilter() {
+ global $input;
+
+ $html = "";
+ $sql = "";
+
+ $filter_name = $this->_getFilterName();
+ $filter_value = $this->_getFilterValue();
+ $filter_chk = $this->_getFilterChecked();
+ $old_name = $this->input_name;
+
+ $html = "<tr class='fieldset'>" . LF;
+ $html .= " <td class='label'>" . $this->label . ":</td>" . LF;
+ $html .= " <td class='label' style='width: 30px; text-align: center;'><input type='checkbox' name='" . $filter_name . "-chk' id='" . $filter_name . "-chk' value='1' " . $filter_chk . "></td>" . LF;
+
+ //crete filter input
+ $this->input_name = $filter_name;
+ $this->value = $filter_value;
+ $this->is_required = false;
+ if ($this->input_type == "select") {
+ $this->input_extra = "onChange=\"javascript: { if (this.value != '') { $$('" . $filter_name . "-chk').checked = true; } else { $$('" . $filter_name . "-chk').checked = false; } }\"";
+ }
+
+
+ $html .= " <td class='input'>" . $this->getInput() . "</td>" . LF;
+ $html .= "</tr>" . LF;
+
+ if ($filter_value != "") {
+ $sql = " and " . $old_name . " = '" . $filter_value . "'";
+ }
+
+ return array("html" => $html, "sql" => $sql);
+ }
+
+ function getHtmlList($tmp_extra) {
+ $this->formatValue();
+
+ $this->element_key = $this->value;
+ if (array_key_exists($this->value, $this->elements)) {
+ $this->value = $this->elements[$this->value];
+ } else {
+ //não está na primeira lista de objetos carregados.
+ $this->loadByChild($this->value); //descobre os pais do cara que está selecionado e põe no arr_pais da classe
+ $this->arr_pais = array_reverse($this->arr_pais); //coloca os pais por ordem crescente
+ $this->arr_pais[] = $this->value; //adiciona o último, que é o valor real
+
+ $this->value = $this->getNames($this->value);
+ }
+
+ if ($this->value == "") {
+ if ($this->element_key == "") {
+ $this->value = "<font color='silver'>(vazio)</font>";
+ } else {
+ $this->value = "<font color='silver'>[" . $this->element_key . "]</font>";
+ }
+ }
+
+ $html = "<td " . $tmp_extra . ">" . $this->value . "</td>" . LF;
+
+ return $html;
+ }
+ function getNames($valor_atual) {
+ global $db;
+ /* 0 - id (campo a ser buscado na tabela)
+ * 1 - idPai (campo que se relaciona com o id)
+ * 2 - nome (campo que será mostrado nos outros combos)
+ * 3 - tabela (tabela)
+ */
+ $names = "";
+ for($x=0;$x < sizeof($this->arr_pais);$x++){
+ $sql = "select ".$this->args[2].",".$this->args[0]." from ".$this->args[3]." where ".$this->args[0]." = ".$this->arr_pais[$x];
+ //echo $sql."<BR><BR>";
+ $rs = $db->execute($sql);
+
+ if($rs->recordcount > 0) {
+ $atual = $rs->fields($this->args[2]);
+ if ($rs->fields($this->args[0]) == $valor_atual)
+ $atual = "<b>".$atual."</b>";
+
+ if($names != "")
+ $names .= " > ".$atual;
+ else
+ $names = $atual;
+ }
+ }
+ return $names;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+/*\r
+Possíveis diferenças entre este campo e o UploadArquivo:\r
+\r
+no onPosPost, o fieldUpload deleta o arquivo da pasta temp.\r
+ o UploadArquivo faz nada.\r
+ \r
+no getTempFile o fileUpload seta um nome com uma extensão "_".time()\r
+ o UploadArquivo não põe a extensão por tempo\r
+ \r
+na rotina para deletar o fileUpload não verifica se é insert ou update e não retira o nome da session do arquivo\r
+ o UploadArquivo verifica que tipo de rotina é no form e retira o nome da session no caso de ser insert.\r
+*/\r
+class FieldUpload extends Field {\r
+ var $path;\r
+ var $file_name;\r
+ \r
+ var $extensions_accept;\r
+ \r
+ var $path_tmp;\r
+ var $hint;\r
+ \r
+ function FieldUpload($tmp_params) {\r
+ parent::Field("upload", $tmp_params[0]);\r
+ \r
+ $this->flags_accept = "LIU";\r
+ \r
+ $this->label = $tmp_params[1];\r
+ $this->validation = "TXT";\r
+ $this->is_sql_affect = false;\r
+ \r
+ $this->file_name = "";\r
+ $this->extensions_accept = array("txt", "php");\r
+ \r
+ if (isset($tmp_params[2])) {\r
+ $this->setPath($tmp_params[2]);\r
+ }\r
+ \r
+ if (isset($tmp_params[3])) {\r
+ $this->setFileName($tmp_params[3]);\r
+ }\r
+ \r
+ $this->setTmpPath("upload/tmp/");\r
+ \r
+ global $routine;\r
+ if ($routine == "update") {\r
+ $this->is_required = false;\r
+ }\r
+ $hint = '';\r
+ }\r
+ \r
+ function setPath($tmp_path) {\r
+ $this->path = "../../../" . $tmp_path;\r
+ }\r
+ \r
+ function setTmpPath($tmp_path) {\r
+ $this->path_tmp = "../../../" . $tmp_path;\r
+ }\r
+ \r
+ function setFileName($tmp_template) { \r
+ $this->file_name = $tmp_template;\r
+ }\r
+ \r
+ \r
+ //private functions \r
+ function getInput() {\r
+ $required_backup = $this->is_required;\r
+ $label_backup = $this->label;\r
+ \r
+ $this->is_required = false;\r
+ $this->label = rand(1, 100000000);\r
+ \r
+ $html = '<div class="label"><table cellspacing="0" cellpadding="0" width="270" height="60"><tr><td>';\r
+ $html .= "<input ";\r
+ $html .= "class='input' ";\r
+ $html .= "type='file' ";\r
+ $html .= "id='" . $this->_getFormatedId() . "' ";\r
+ $html .= "name='" . $this->name . "' ";\r
+ $html .= "style='width: 230px;' ";\r
+ $html .= ">";\r
+ $html .= "</td><td>";\r
+ $html .= "<a href='javascript:void(0);' onclick=\"javascript: uploadSubmit('" . $this->name . "')\"><img src=\"../img/buttons/add.jpg\" alt=\"inserir\" title=\"inserir\" align=\"right\"/></a>";\r
+ $html .= '</td></tr></table></div>';\r
+ \r
+ $this->is_required = $required_backup;\r
+ $this->label = $label_backup;\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ function getHtml() {\r
+ global $routine;\r
+ global $form;\r
+ \r
+ $html = "<tr>";\r
+ \r
+ //Label\r
+ if ($this->label != ""){\r
+ $html .= "<td class='label'>";\r
+ \r
+ $html .= $this->label . ": ";\r
+ \r
+ if ($this->is_required) {\r
+ $html .= "<font class='red'>*</font>";\r
+ }\r
+ \r
+ if($this->hint != ''){\r
+ $html .= "<br /><br />(<span style='font-size:9px;'>".$this->hint."</span>)";\r
+ }\r
+ \r
+ $html .= "</td>" . LF;\r
+ }\r
+ \r
+ $this->formatValue();\r
+ \r
+ //Input\r
+ $html .= "<td class='input'>";\r
+ \r
+ if ($this->is_static) {\r
+ $html .= "<div id='" . $this->name . "_div_input' class='box_silver'>";\r
+ //error(1, "Um campo 'upload' não pode ser estático.", "FieldUpload", "getHtml");\r
+ $html .= "</div>";\r
+ } else {\r
+ //.input\r
+ $html .= "<div id='" . $this->name . "_div_input' class='box_silver'>";\r
+ $html .= $this->getInput();\r
+ $html .= "</div>";\r
+ }\r
+ \r
+ //.loading message\r
+ $html .= "<div id='" . $this->name . "_div_loading' class='box_silver' style='display: none; height: 15px; margin-top: 5px;'>Loading...</div>";\r
+ \r
+ //.error box\r
+ $html .= "<div id='" . $this->name . "_div_error' class='box_red' style='display: none; height: 20px; margin-top: 5px;'></div>";\r
+ \r
+ //.list\r
+ if (IS_DEVELOP) {\r
+ $html .= "<a href='javascript:void(0);' onclick=\"javascript: uploadList('" . $this->name . "');\">refresh list</a><br>";\r
+ }\r
+ $html .= "<table width='100%' style='margin-top: 5px;'><tr><td class='box_yellow' id='" . $this->name . "_div_list' style='display: none;'></td></tr></table>"; \r
+ \r
+ //.list of tmp files\r
+ if ($routine == "insert") {\r
+ $html .= "<input type='hidden' id='" . $this->_getFormatedId() . "' value=''>";\r
+ }\r
+ \r
+ //.if update, upload list of files\r
+ if ($routine == "update") {\r
+ $html .= "<script>uploadList('" . $this->name . "');</script>";\r
+ }\r
+ \r
+ $html .= "</td></tr>" . LF;\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ function onPosPost() { \r
+ global $routine;\r
+ global $file;\r
+ global $form;\r
+ global $input;\r
+ \r
+ if ($routine == "insert") {\r
+ $file_tmp = $input->session($this->name . "_file");\r
+ \r
+ $i = 1;\r
+ if ($file_tmp != "") {\r
+ if (file_exists($file_tmp)) {\r
+ $ext = $file->getExtension($file_tmp);\r
+ \r
+ $file->copyFile($file_tmp, $this->path . $this->_getFile() . "." . $ext);\r
+ //echo $file_tmp . " --- " . $this->path . $this->_getFile() . "." . $ext;\r
+ //die();\r
+ \r
+ \r
+ $file->deleteFile($file_tmp);\r
+ \r
+ $i++;\r
+ }\r
+ }\r
+ \r
+ $input->unsetSession($this->name . "_file");\r
+ }\r
+ \r
+ //delete old files from tmp folder\r
+ // $list = $file->listFolder($this->path_tmp);\r
+ \r
+ // if (is_array($list)) {\r
+ // foreach ($list as $v) {\r
+ // $path = $this->path_tmp . $v;\r
+ \r
+ // $arr2 = explode(".", $v);\r
+ // $arr = explode("_", $arr2[0]);\r
+ // $date_modified = (float)$arr[1];\r
+ \r
+ // hours limit\r
+ // if (time() > ($date_modified + (2 * 60 * 60))) {\r
+ // $file->deleteFile($path);\r
+ // }\r
+ // }\r
+ // }\r
+ }\r
+ \r
+ function onDelete() {\r
+ global $file;\r
+ \r
+ $this->_deleteFile($this->path . $this->_getFile());\r
+ }\r
+ \r
+ //Ajax functions\r
+ function ajaxRoutine($tmp_routine) {\r
+ global $file;\r
+ global $routine;\r
+ \r
+ $html = "";\r
+ \r
+ switch ($tmp_routine) {\r
+ case "upload":\r
+ if ($routine == "insert") {\r
+ $file_dest = $this->_getTempFile();\r
+ } else {\r
+ $file_dest = $this->path . $this->_getFile();\r
+ }\r
+ \r
+ $this->_deleteFile($path);\r
+ \r
+ $ext = $file->getExtension($_FILES[$this->name]["name"]);\r
+ \r
+ if (array_search($ext, $this->extensions_accept) !== false) {\r
+ if (move_uploaded_file($_FILES[$this->name]["tmp_name"], $file_dest . "." . $ext)) {\r
+ $html .= "<script>";\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = 'none';" . LF;\r
+ \r
+ if ($routine == "insert") {\r
+ $html .= "window.parent.$$('" . $this->_getFormatedId() . "').value = '" . $file_dest . "." . $ext . "';";\r
+ \r
+ $_SESSION[$this->name . "_file"] = $file_dest . "." . $ext;\r
+ }\r
+ \r
+ $html .= "</script>";\r
+ } else {\r
+ $html .= "<script>";\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = 'Erro ao fazer upload.';" . LF;\r
+ $html .= "</script>";\r
+ }\r
+ } else {\r
+ $html .= "<script>";\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;\r
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = \"Extensão não permitida.<br>Utilize somente '" . implode(", ", $this->extensions_accept) . "'\";" . LF;\r
+ $html .= "</script>";\r
+ }\r
+ \r
+ break;\r
+ case "list": \r
+ if ($routine == "insert") {\r
+ $path = $_SESSION[$this->name . "_file"];\r
+ } else {\r
+ $path = $this->_findFile($this->path . $this->_getFile());\r
+ }\r
+ \r
+ if ($path != "") {\r
+ $path_clean = str_replace("../../../", "", $path);\r
+ \r
+ \r
+ $html .= "<div class='upload_item'>";\r
+ $html .= '<div class="label"><table cellspacing="0" cellpadding="0" width="270" height="60">\r
+ <tr>\r
+ <td>';\r
+ $html .= "<a href='../../_system/scripts/download.php?file=" . $path_clean . "' target='ifr_aux'>" . $path_clean . "</a>";\r
+ $html .= '</td><td align="right">';\r
+ if(!$this->is_static){\r
+ $html .= "<a href='javascript:void(0);' onclick=\"uploadDelete('" . $this->name . "');\"><img src=\"../img/buttons/del.jpg\" alt=\"Excluir\" title=\"Excluir\" align=\"right\"/></a>";\r
+ }\r
+ $html .= ' </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ \r
+ </td>\r
+ <td style="text-align:right;padding-right:5px;">\r
+ ('.$file->fileSizeFormated($path).')\r
+ </td>\r
+ </tr>\r
+ </table>';\r
+ $html .= "</div></div>";\r
+ \r
+ // $html .= "<div class='upload_item'>";\r
+ // $html .= "<div class='label'><a href='../../_system/scripts/download.php?file=" . $path_clean . "' target='ifr_aux'>" . $path_clean . "</a></div>";\r
+ // $html .= "<div class='buttons'><a href='javascript:void(0);' onclick=\"uploadDelete('" . $this->name . "');\">del</a></div>";\r
+ // $html .= "</div>";\r
+ \r
+ $html .= "<script>" . LF;\r
+ $html .= "$$('" . $this->name . "_div_input').style.display = 'none';" . LF;\r
+ $html .= "$$('" . $this->name . "_div_list').style.display = '';" . LF;\r
+ $html .= "</script>";\r
+ } else {\r
+ $html .= "<script>" . LF;\r
+ $html .= "$$('" . $this->name . "_div_input').style.display = '';" . LF;\r
+ if($this->is_static){\r
+ $html .= "$$('" . $this->name . "_div_input').innerHTML = '" . str_replace("'", "\'", '(vazio)') . "';" . LF;\r
+ } else {\r
+ $html .= "$$('" . $this->name . "_div_input').innerHTML = '" . str_replace("'", "\'", $this->getInput()) . "';" . LF;\r
+ }\r
+ $html .= "$$('" . $this->name . "_div_list').style.display = 'none';" . LF;\r
+ $html .= "</script>";\r
+ }\r
+ \r
+ break;\r
+ case "delete":\r
+ if ($routine == "insert") {\r
+ $file_name = $this->_getTempFile();\r
+ } else {\r
+ $file_name = $this->_getFile();\r
+ }\r
+ \r
+ $this->_deleteFile($this->path . $file_name);\r
+ \r
+ $html .= $this->path . $file_name . "<br>\r\n";\r
+ \r
+ $html .= "<script>uploadList('" . $this->name . "');</script>";\r
+ \r
+ break;\r
+ }\r
+ \r
+ return $html;\r
+ }\r
+ \r
+ function _getTempFile() {\r
+ global $file;\r
+ \r
+ $file_name = substr("00000" . rand(1, 999999), -6) . "_" . time();\r
+ \r
+ $exists = false;\r
+ \r
+ foreach ($this->extensions_accept as $v) {\r
+ if (file_exists($this->path_tmp . $file_name . "." . $v)) {\r
+ $exists = true;\r
+ }\r
+ }\r
+ \r
+ if ($exists) {\r
+ $file_name = $this->_getTempFile();\r
+ }\r
+ \r
+ \r
+ //create tmp folder(s)\r
+ $arr = explode("/", $this->path_tmp);\r
+ $path = "";\r
+ foreach ($arr as $name) {\r
+ if (strlen($name) > 0) {\r
+ $path .= $name . "/";\r
+ \r
+ if (substr($path, -3) != "../") {\r
+ $file->makeFolder($path);\r
+ }\r
+ }\r
+ }\r
+ \r
+ return $this->path_tmp . $file_name;\r
+ }\r
+ \r
+ function _getFile() {\r
+ global $form;\r
+ \r
+ $f = $form;\r
+ \r
+ global $rs_list;\r
+ if (is_object($rs_list)) {\r
+ $f = $rs_list;\r
+ }\r
+ \r
+ $file_name = $this->file_name;\r
+ \r
+ foreach ($f->fields as $k => $v) {\r
+ $file_name = str_replace("#" . strtoupper($k) . "#", $v, $file_name);\r
+ }\r
+ \r
+ return $file_name;\r
+ }\r
+ \r
+ function _deleteFile($tmp_path) {\r
+ global $file;\r
+ \r
+ foreach ($this->extensions_accept as $v) {\r
+ $path = $tmp_path . "." . $v;\r
+ \r
+ if (file_exists($path)) {\r
+ $file->deleteFile($path);\r
+ }\r
+ }\r
+ }\r
+ \r
+ function _findFile($tmp_path) {\r
+ foreach ($this->extensions_accept as $v) {\r
+ $file_path = $tmp_path . "." . $v;\r
+ \r
+ if (file_exists($file_path)) {\r
+ return $file_path;\r
+ }\r
+ }\r
+ \r
+ return '';\r
+ }\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?
+class FieldUploadArquivo extends Field {
+ var $path;
+ var $file_name;
+
+ var $extensions_accept;
+
+ var $path_tmp;
+
+ function FieldUploadArquivo($tmp_params) {
+ parent::Field("uploadArquivo", $tmp_params[0]);
+
+ $this->flags_accept = "LIU";
+
+ $this->label = $tmp_params[1];
+ $this->validation = "TXT";
+ $this->is_sql_affect = false;
+
+ $this->file_name = "";
+ $this->extensions_accept = array("txt", "php");
+
+ if (isset($tmp_params[2])) {
+ $this->setPath($tmp_params[2]);
+ }
+
+ if (isset($tmp_params[3])) {
+ $this->setFileName($tmp_params[3]);
+ }
+
+ $this->setTmpPath("upload/tmp/");
+
+ global $routine;
+ if ($routine == "update") {
+ $this->is_required = false;
+ }
+ }
+
+ function setPath($tmp_path) {
+ $this->path = "../../../" . $tmp_path;
+ }
+
+ function setTmpPath($tmp_path) {
+ $this->path_tmp = "../../../" . $tmp_path;
+ }
+
+ function setFileName($tmp_template) {
+ $this->file_name = $tmp_template;
+ }
+
+
+ //private functions
+ function getInput() {
+ $required_backup = $this->is_required;
+ $label_backup = $this->label;
+
+ $this->is_required = false;
+ $this->label = rand(1, 100000000);
+
+ $html = "<input ";
+ $html .= "class='input' ";
+ $html .= "type='file' ";
+ $html .= "id='" . $this->_getFormatedId() . "' ";
+ $html .= "name='" . $this->name . "' ";
+ $html .= "style='width: 230px;' ";
+ $html .= ">";
+ $html .= "<a href='javascript:void(0);' onclick=\"javascript: uploadSubmit('" . $this->name . "')\">upload</a>";
+
+ $this->is_required = $required_backup;
+ $this->label = $label_backup;
+
+ return $html;
+ }
+
+ function getHtml() {
+ global $routine;
+ global $form;
+
+ $html = "<tr>";
+
+ //Label
+ if ($this->label != "") {
+ $html .= "<td class='label'>";
+
+ $html .= $this->label . ": ";
+
+ if ($this->is_required) {
+ $html .= "<font class='red'>*</font>";
+ }
+
+ $html .= "</td>" . LF;
+ }
+
+ $this->formatValue();
+
+ //Input
+ $html .= "<td class='input'>";
+
+ if ($this->is_static) {
+ error(1, "Um campo 'upload' não pode ser estático.", "FieldUpload", "getHtml");
+ }
+
+ //.input
+ $html .= "<div id='" . $this->name . "_div_input' class='box_silver'>";
+ $html .= $this->getInput();
+ $html .= "</div>";
+
+ //.loading message
+ $html .= "<div id='" . $this->name . "_div_loading' class='box_silver' style='display: none; height: 15px; margin-top: 5px;'>Carregando...</div>";
+
+ //.error box
+ $html .= "<div id='" . $this->name . "_div_error' class='box_red' style='display: none; height: 20px; margin-top: 5px;'></div>";
+
+ //.list
+ if (IS_DEVELOP) {
+ $html .= "<a href='javascript:void(0);' onclick=\"javascript: uploadList('" . $this->name . "');\">refresh list</a><br>";
+ }
+ $html .= "<table width='100%' style='margin-top: 5px;'><tr><td class='box_yellow' id='" . $this->name . "_div_list' style='display: none;'></td></tr></table>";
+
+ //.list of tmp files
+ if ($routine == "insert") {
+ $html .= "<input type='hidden' id='" . $this->_getFormatedId() . "' value=''>";
+ }
+
+ //.if update, upload list of files
+ if ($routine == "update") {
+ $html .= "<script>uploadList('" . $this->name . "');</script>";
+ }
+
+ $html .= "</td></tr>" . LF;
+
+ return $html;
+ }
+
+ function onPosPost() {
+ global $routine;
+ global $file;
+ global $form;
+ global $input;
+
+ if ($routine == "insert") {
+ if (!is_dir($this->path.$form->fields('id').'/')) {
+ mkdir($this->path.$form->fields('id').'/',0777);
+ }
+
+ $file_tmp = $input->session($this->name . "_file");
+
+ $i = 1;
+ if ($file_tmp != "") {
+ if (file_exists($file_tmp)) {
+ $ext = $file->getExtension($file_tmp);
+
+ $file->copyFile($file_tmp, $this->path . $this->_getFile() . "." . $ext);
+ //echo $file_tmp . " --- " . $this->path . $this->_getFile() . "." . $ext;
+ //die();
+
+
+ $file->deleteFile($file_tmp);
+
+ $i++;
+ }
+ }
+
+ $input->unsetSession($this->name . "_file");
+ }
+
+ //delete old files from tmp folder
+ //TODO: Fix this
+ /*$list = $file->listFolder($this->path_tmp);
+
+ if (is_array($list)) {
+ foreach ($list as $v) {
+ $path = $this->path_tmp . $v;
+ $date_modified = filemtime($path);
+
+ //one day limit
+ if ((time() - ($date_modified / (24 * 60 * 60))) > 1) {
+ $file->deleteFile($path);
+ }
+ }
+ }*/
+ }
+
+ function onDelete() {
+ global $file;
+
+ $this->_deleteFile($this->path . $this->_getFile());
+ }
+
+ //Ajax functions
+ function ajaxRoutine($tmp_routine) {
+ global $file;
+ global $routine;
+ global $input;
+
+ $html = "";
+
+ switch ($tmp_routine) {
+ case "upload":
+ if ($routine == "insert") {
+ $file_dest = $this->_getTempFile();
+ } else {
+ $file_dest = $this->path . $this->_getFile();
+ }
+
+ $this->_deleteFile($path);
+
+ $ext = $file->getExtension($_FILES[$this->name]["name"]);
+
+ if (array_search($ext, $this->extensions_accept) !== false) {
+ if (move_uploaded_file($_FILES[$this->name]["tmp_name"], $file_dest . "." . $ext)) {
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = 'none';" . LF;
+
+ if ($routine == "insert") {
+ $html .= "window.parent.$$('" . $this->_getFormatedId() . "').value = '" . $file_dest . "." . $ext . "';";
+
+ $_SESSION[$this->name . "_file"] = $file_dest . "." . $ext;
+ }
+
+ $html .= "</script>";
+ } else {
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = 'Erro ao fazer upload.';" . LF;
+ $html .= "</script>";
+ }
+ } else {
+ $html .= "<script>";
+ $html .= "window.parent.$$('" . $this->name . "_div_error').style.display = '';" . LF;
+ $html .= "window.parent.$$('" . $this->name . "_div_error').innerHTML = \"Extensão não permitida.<br>Utilize somente '" . implode(", ", $this->extensions_accept) . "'\";" . LF;
+ $html .= "</script>";
+ }
+
+ break;
+ case "list":
+ if ($routine == "insert") {
+ $path = $_SESSION[$this->name . "_file"];
+ } else {
+ $path = $this->_findFile($this->path . $this->_getFile());
+ }
+
+ if ($path != "") {
+ $path_clean = str_replace("../../../", "", $path);
+
+ $html .= "<div class='upload_item'>";
+ $html .= "<div class='label'><a href='../../_system/scripts/download.php?file=" . $path_clean . "' target='ifr_aux'>" . $path_clean . "</a></div>";
+ $html .= "<div class='buttons'><a href='javascript:void(0);' onclick=\"uploadDelete('" . $this->name . "');\">del</a></div>";
+ $html .= "</div>";
+
+ $html .= "<script>" . LF;
+ $html .= "$$('" . $this->name . "_div_input').style.display = 'none';" . LF;
+ $html .= "$$('" . $this->name . "_div_list').style.display = '';" . LF;
+ $html .= "</script>";
+ } else {
+ $html .= "<script>" . LF;
+ $html .= "$$('" . $this->name . "_div_input').style.display = '';" . LF;
+ $html .= "$$('" . $this->name . "_div_input').innerHTML = '" . str_replace("'", "\'", $this->getInput()) . "';" . LF;
+ $html .= "$$('" . $this->name . "_div_list').style.display = 'none';" . LF;
+ $html .= "</script>";
+ }
+
+ break;
+ case "delete":
+ if ($routine == "insert") {
+ $file_name = $input->session($this->name . '_file');
+ $file->deleteFile($file_name);
+ $input->unsetSession($this->name . '_file');
+ } else {
+ $file_name = $this->_getFile();
+ $this->_deleteFile($this->path . $file_name);
+ }
+
+ $html .= $this->path . $file_name . "<br>\r\n";
+
+ $html .= "<script>uploadList('" . $this->name . "');</script>";
+
+ break;
+ }
+
+ return $html;
+ }
+
+ function _getTempFile() {
+ global $file;
+
+ $file_name = substr("00000" . rand(1, 999999), -6);
+
+ $exists = false;
+
+ foreach ($this->extensions_accept as $v) {
+ if (file_exists($this->path_tmp . $file_name . "." . $v)) {
+ $exists = true;
+ }
+ }
+
+ if ($exists) {
+ $file_name = $this->_getTempFile();
+ }
+
+
+ //create tmp folder(s)
+ $arr = explode("/", $this->path_tmp);
+ $path = "";
+ foreach ($arr as $name) {
+ if (strlen($name) > 0) {
+ $path .= $name . "/";
+
+ if (substr($path, -3) != "../") {
+ $file->makeFolder($path);
+ }
+ }
+ }
+
+ return $this->path_tmp . $file_name;
+ }
+
+ function _getFile() {
+ global $form;
+
+ global $rs_list;
+ if (is_object($rs_list)) {
+ $form = $rs_list;
+ }
+
+ $file_name = $this->file_name;
+
+ foreach ($form->fields as $k => $v) {
+ $file_name = str_replace("#" . strtoupper($k) . "#", $v, $file_name);
+ }
+
+ return $file_name;
+ }
+
+ function _deleteFile($tmp_path) {
+ global $file;
+
+ foreach ($this->extensions_accept as $v) {
+ $path = $tmp_path . "." . $v;
+
+ if (file_exists($path)) {
+ $file->deleteFile($path);
+ }
+ }
+ }
+
+ function _findFile($tmp_path) {
+ foreach ($this->extensions_accept as $v) {
+ $file_path = $tmp_path . "." . $v;
+
+ if (file_exists($file_path)) {
+ return $file_path;
+ }
+ }
+
+ return '';
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+.calendario {
+ border: 1px #999999 solid;
+}
+
+.calendario table {
+ font-family: Tahoma;
+ font-size: 10px;
+ color: #666666;
+ width: 140px;
+}
+
+.calendario table tr td.mes {
+ border-bottom: 1px #CCCCCC solid;
+ width: 120px;
+ height: 18px;
+ text-align: center;
+ background:#5E94B0;
+ color: #FFFFFF;
+ cursor: move;
+}
+
+.calendario table tr td.fechar {
+ cursor: pointer;
+ width: 15px;
+ height: 18px;
+ vertical-align: middle;
+ text-align: center;
+ background:#5E94B0;
+ color: #FFFFFF;
+ border-left: 1px solid #CCCCCC;
+}
+
+
+.calendario table tr td.nav {
+ border-bottom: 1px solid #CCCCCC;
+ width: 15px;
+ height: 18px;
+ text-align: center;
+ cursor: pointer;
+ background: #E4EAF0;
+}
+
+.calendario table tr td.data {
+ border-bottom: 1px solid #CCCCCC;
+ width: 80px;
+ height: 14px;
+ text-align: center;
+ background: #C7CED1;
+}
+
+.calendario table tr td.dias {
+ width: 140px;
+}
+
+.calendario table tr td.status {
+ width: 140px;
+ text-align: center;
+ background: #E4EAF0;
+}
+
+.calendario table tr td.dias table tr td {
+ width: 20px;
+ height: 15px;
+ cursor: pointer;
+ background: #F2F2F2;
+ margin: 0px;
+ border-bottom: solid #DFDFDF 1px;
+ vertical-align: middle;
+ text-align: center;
+ font-family: Tahoma;
+ font-size: 10px;
+ color: #666666;
+}
+
+.calendario table tr td.dias_t table tr td {
+ width: 20px;
+ height: 15px;
+ cursor: pointer;
+ background: #F2F2F2;
+ margin: 0px;
+ border-bottom: solid #CCCCCC 1px;
+ vertical-align: middle;
+ text-align: center;
+ font-family: Tahoma;
+ font-size: 10px;
+ color: #666666;
+ font-weight: bold;
+}
+
+.calendario table tr td.dias table tr td.data {
+ color: #333333;
+ font-weight: bold;
+ border-bottom: solid #CCCCCC 1px;
+}
\ No newline at end of file
--- /dev/null
+var objcalendario = new Calendario();
+
+function Calendario() {
+ this.div;
+ this.id = '_calendario_div';
+ this.input_id = '';
+ this.valor = '';
+ this.valor_inicial = '';
+ this.date = new Date();
+ this.date_valor = new Date();
+ this.date_hoje = new Date();
+ this.combos = new Array();
+ this.drag = false;
+
+ this.mouse_x = 0;
+ this.mouse_y = 0;
+
+ this.offset_x = 20;
+ this.offset_y = 5;
+
+ this.open = function(tmp_id) {
+ this.create();
+
+ this.bugCombos('hidden');
+
+ //Seta a data
+ if (document.getElementById(tmp_id).value != "") {
+ this.valor = document.getElementById(tmp_id).value;
+ this.valor_inicial = this.valor;
+ } else {
+ var d = new Date();
+ this.valor_inicial = '';
+ this.valor = this.formatNumber(d.getDate(), 2) + "/" + this.formatNumber((d.getMonth()) + 1, 2) + "/" + d.getFullYear();
+ }
+
+ //Coloca html no pai do elemento
+ this.input_id = tmp_id;
+ document.getElementById(tmp_id).parentNode.appendChild(this.div);
+
+ //Mostra data atual
+ this.date_valor = this.parseData(this.valor);
+ this.date = this.parseData(this.valor);
+ this.showData();
+
+ //Mostra o calendário
+ this.div.style.display = '';
+ }
+
+ this.bugCombos = function (tmp_display) {
+ var i = 0;
+ while (i < this.combos.length) {
+ this.combos[i].style.visibility = tmp_display;
+
+ i++;
+ }
+ }
+
+ this.close = function () {
+ this.div.style.display = 'none';
+
+ this.bugCombos('visible');
+
+ if (this.valor_inicial == document.getElementById(this.input_id).value) {
+ this.setValor();
+ }
+ }
+
+ this.closeForce = function () {
+ //Botão x
+ this.valor_inicial = (Math.random() * 10000) + '...';
+
+ this.close();
+ }
+
+ this.create = function () {
+ if (!document.getElementById(this.id)) {
+ this.div = document.createElement('div');
+ this.div.id = this.id;
+ this.div.style.position = 'absolute';
+
+ var html = '<table cellspacing="0" cellpadding="0"><tr><td colspan="4" class="mes" id="_calendario_div_mes" onmousedown="javascript: objcalendario.startDrag();" onmouseup="javascript: objcalendario.stopDrag();"></td><td class="fechar" onclick="javascript: objcalendario.closeForce();" onmouseover="javascript: objcalendario.setAlt(\'Fechar\');" onmouseout="javascript: objcalendario.clearAlt();" width="20">x</td></tr>';
+ html += '<tr><td class="nav" onclick="javascript: objcalendario.clickAno(\'-\');" onmouseover="javascript: objcalendario.setAlt(\'Ano anterior\');" onmouseout="javascript: objcalendario.clearAlt();"><<</td><td class="nav" onclick="javascript: objcalendario.clickMes(\'-\');" onmouseover="javascript: objcalendario.setAlt(\'Mês anterior\');" onmouseout="javascript: objcalendario.clearAlt();"><</td>';
+ html += '<td class="data" id="_calendario_div_data"></td>';
+ html += '<td class="nav" onclick="javascript: objcalendario.clickMes(\'+\');" onmouseover="javascript: objcalendario.setAlt(\'Próximo mês\');" onmouseout="javascript: objcalendario.clearAlt();">></td><td class="nav" onclick="javascript: objcalendario.clickAno(\'+\');" onmouseover="javascript: objcalendario.setAlt(\'Próximo ano\');" onmouseout="javascript: objcalendario.clearAlt();">>></td></tr>';
+ html += '<tr><td colspan="5" class="dias_t"><table cellpadding="0" cellspacing="0"><tr><td>D</td><td>S</td><td>T</td><td>Q</td><td>Q</td><td>S</td><td>S</td></tr></table></td></tr>';
+ html += '<tr><td colspan="5" id="_calendario_div_dias" class="dias"></td></tr>';
+ html += '<tr><td colspan="5" id="_calendario_div_status" class="status"></td></tr></table>';
+
+ this.div.innerHTML = html;
+ this.div.style.display = 'none';
+ this.div.className = 'calendario';
+
+ //Acha as combos
+ var cmb = document.getElementsByTagName('select');
+ var i = 0;
+ var i2 = 0;
+ while (i < cmb.length) {
+ if (cmb[i].style.display != 'none') {
+ this.combos[i2] = cmb[i];
+ i2++;
+ }
+
+ i++;
+ }
+ }
+ }
+
+ this.startDrag = function () {
+ var x = this.div.style.left.replace("px", "");
+ var y = this.div.style.top.replace("px", "");
+
+ x++; x--;
+ y++; y--;
+
+ if (x > 0) {
+ if (isIE) {
+ this.offset_x = this.mouse_x - x;
+ this.offset_y = this.mouse_y - y;
+ }
+ }
+
+ this.drag = true;
+ }
+
+ this.stopDrag = function () {
+ this.drag = false;
+ }
+
+ this.refreshDrag = function () {
+ if (this.drag) {
+ this.div.style.left = this.mouse_x - this.offset_x + getScrollWidth();
+ this.div.style.top = this.mouse_y - this.offset_y + getScrollHeight();
+ }
+ }
+
+ this.clickDia = function (tmp_dia) {
+ //seta valor
+ this.date_valor.setDate(tmp_dia);
+ this.date_valor.setMonth(this.date.getMonth());
+ this.date_valor.setFullYear(this.date.getFullYear());
+
+ this.close();
+ }
+
+ this.clickMes = function (tmp_direcao) {
+ var tmp;
+
+ //navega
+ if (tmp_direcao == "+") {
+ tmp = this.date.getMonth();
+
+ if (tmp == 11) {
+ this.date.setMonth(0);
+ this.date.setFullYear(this.date.getFullYear() + 1);
+ } else {
+ this.date.setMonth(tmp + 1);
+ }
+ } else {
+ tmp = this.date.getMonth();
+
+ if (tmp == 0) {
+ this.date.setMonth(1);
+ this.date.setFullYear(this.date.getFullYear() - 1);
+ } else {
+ this.date.setMonth(tmp - 1);
+ }
+ }
+
+ this.showData();
+ }
+
+ this.clickAno = function (tmp_direcao) {
+ //navega
+ if (tmp_direcao == "+") {
+ this.date.setFullYear(this.date.getFullYear() + 1);
+ } else {
+ this.date.setFullYear(this.date.getFullYear() - 1);
+ }
+
+ this.showData();
+ }
+
+ this.setValor = function () {
+ document.getElementById(this.input_id).value = this.formatNumber(this.date_valor.getDate(), 2) + "/" + this.formatNumber((this.date_valor.getMonth()+1), 2) + "/" + this.date_valor.getFullYear();
+ if (document.getElementById(this.input_id).onchange) {
+ document.getElementById(this.input_id).onchange();
+ }
+
+ if (document.getElementById(this.input_id).onkeyup) {
+ document.getElementById(this.input_id).onkeyup();
+ }
+
+ if (document.getElementById(this.input_id).onkeydown) {
+ document.getElementById(this.input_id).onkeydown();
+ }
+ }
+
+ this.showData = function () {
+ document.getElementById('_calendario_div_mes').innerHTML = this.getMes(this.date.getMonth()) + " - " + this.date.getFullYear();
+
+ var html = '<table cellspacing="0" cellpadding="0"><tr>';
+
+ var m = this.getTabelaDias();
+ var i = 0;
+ while (i < m.length) {
+ html += m[i].html;
+
+ i++;
+
+ if (m[i - 1].diasemana == 6) {
+ html += "</tr>\n";
+
+ if (i < m.length) {
+ html += '<tr>';
+ }
+ }
+ }
+
+ html += "</tr></table>";
+
+ document.getElementById('_calendario_div_dias').innerHTML = html;
+
+ document.getElementById('_calendario_div_data').innerHTML = this.formatNumber(this.date.getDate(), 2) + "/" + this.formatNumber((this.date.getMonth()+1), 2) + "/" + this.date.getFullYear();
+ }
+
+ this.getMes = function (tmp_mes) {
+ var meses = new Array("Janeiro",
+ "Fevereiro",
+ "Março",
+ "Abril",
+ "Maio",
+ "Junho",
+ "Julho",
+ "Agosto",
+ "Setembro",
+ "Outubro",
+ "Novembro",
+ "Dezembro");
+
+ return meses[tmp_mes];
+ }
+
+ this.formatNumber = function (tmp_numero, tmp_casas) {
+ var r = new String(tmp_numero);
+
+ while (r.length < tmp_casas) {
+ r += '0' + r;
+ }
+
+ return r.substr((r.length-tmp_casas), r.length);
+ }
+
+ this.parseData = function (tmp_valor) {
+ var tmp = tmp_valor.split("/");
+ var d = new Date();
+
+ d.setDate(tmp[0]);
+ d.setMonth(tmp[1]-1);
+ d.setFullYear(tmp[2]);
+
+ return d;
+ }
+
+ this.getTabelaDias = function () {
+ var arr = new Array();
+ var dia = 1;
+ var d = new Date(this.date);
+ var tmp = '';
+ var max;
+
+ d.setDate(1);
+
+ i = 0;
+ while (i < d.getDay()) {
+
+ arr[i] = new Object();
+ arr[i].dia = 0;
+ arr[i].diasemana = i;
+ arr[i].html = '<td style="cursor: default;"> </td>';
+
+ i++;
+ }
+
+ dia = 1;
+ max = this.getQndDias(d.getMonth());
+ while (dia <= max) {
+ d.setDate(dia);
+
+ arr[i] = new Object();
+ arr[i].dia = dia;
+ arr[i].diasemana = d.getDay();
+
+ //Se é hoje
+ tmp = '';
+ if ((d.getDate() == this.date_hoje.getDate()) && (d.getMonth() == this.date_hoje.getMonth()) && (d.getFullYear() == this.date_hoje.getFullYear())) {
+ tmp = 'style="background: #C7CED1;"';
+ }
+
+ //Se é dia selecionado
+ if ((d.getDate() == this.date_valor.getDate()) && (d.getMonth() == this.date_valor.getMonth()) && (d.getFullYear() == this.date_valor.getFullYear())) {
+ tmp += ' class="data"';
+ }
+
+ arr[i].html = '<td ' + tmp + ' onClick="javascript: objcalendario.clickDia(\'' + arr[i].dia + '\');">' + arr[i].dia + '</td>';
+
+ i++;
+ dia++;
+ }
+
+ dia = arr[i-1].diasemana + 1;
+ while (dia <= 6) {
+ arr[i] = new Object();
+ arr[i].dia = 0;
+ arr[i].diasemana = dia;
+ arr[i].html = '<td style="cursor: default;"> </td>';
+
+ i++;
+ dia++;
+ }
+
+ return arr;
+ }
+
+ this.getQndDias = function (tmp_mes) {
+ var dia = 1000 * 60 * 60 * 24;
+ var data = new Date();
+ var esteMes = new Date(data.getFullYear(), tmp_mes, 1);
+ var proximoMes = new Date(data.getFullYear(), tmp_mes + 1, 1);
+ return Math.ceil((proximoMes.getTime() - esteMes.getTime())/dia);
+ }
+
+ this.setAlt = function (tmp_alt) {
+ document.getElementById('_calendario_div_status').innerHTML = tmp_alt;
+ }
+
+ this.clearAlt = function () {
+ document.getElementById('_calendario_div_status').innerHTML = '';
+ }
+}
+
+function Calendario_mousemove(e) {
+ if (e.clientX > 0) {
+ objcalendario.mouse_x = e.clientX;
+ objcalendario.mouse_y = e.clientY;
+ } else {
+ objcalendario.mouse_x = e.offsetX;
+ objcalendario.mouse_y = e.offsetY;
+ }
+
+ objcalendario.refreshDrag();
+}
+
+function getScrollWidth() {
+ var w = window.pageXOffset ||
+ document.body.scrollLeft ||
+ document.documentElement.scrollLeft;
+
+ return w ? w : 0;
+}
+
+function getScrollHeight() {
+ var h = window.pageYOffset ||
+ document.body.scrollTop ||
+ document.documentElement.scrollTop;
+
+ return h ? h : 0;
+}
+
+document.onmousemove = function (e) {
+ Calendario_mousemove(e||event);
+}
\ No newline at end of file
--- /dev/null
+/* PLUGIN */
+
+#plugin { border:1px solid #999999; BACKGROUND: #ffffff; COLOR: #AAA; CURSOR: move; DISPLAY: block; FONT-FAMILY: arial; FONT-SIZE: 11px; PADDING: 7px 10px 11px 10px; _PADDING-RIGHT: 0; Z-INDEX: 1; POSITION: absolute; WIDTH: 199px; _width: 210px; _padding-right: 0px; }
+#plugin br { CLEAR: both; MARGIN: 0; PADDING: 0; }
+#plugin select { BORDER: 1px solid #333; BACKGROUND: #FFF; POSITION: relative; TOP: 4px; }
+
+#plugHEX { FLOAT: left; position: relative; top: -1px; }
+#plugCLOSE { FLOAT: right; cursor: pointer; MARGIN: 0 8px 3px; _MARGIN-RIGHT: 10px; COLOR: #FFF; -moz-user-select: none; -khtml-user-select: none; user-select: none; }
+#plugHEX:hover,#plugCLOSE:hover { COLOR: #FFD000; }
+
+#plugCUR { float: left; text-align:left; width: 83px; height: 14px; background: #FFF; border:solid 0px #000000; margin-top:9px; border:#000000 solid 1px; border-left: 0px; }
+#plugCURI { float: left; text-align:left; width: 84px; height: 14px; background: #FFF; border:solid 0px #000000; margin-top:9px; border:#000000 solid 1px; border-right: 0px; }
+
+#SV { border:solid 1px #000000; background: url('img/SatVal.png'); background-color:#FF0000; POSITION: relative; CURSOR: crosshair; FLOAT: left; HEIGHT: 166px; WIDTH: 167px; _WIDTH: 165px; MARGIN-RIGHT: 10px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='img/SatVal.png', sizingMethod='scale'); -moz-user-select: none; -khtml-user-select: none; user-select: none; }
+#SVslide { BACKGROUND: url('img/slide.gif'); HEIGHT: 9px; WIDTH: 9px; POSITION: absolute; _font-size: 1px; line-height: 1px; }
+
+#H { CURSOR: crosshair; FLOAT: left; HEIGHT: 154px; POSITION: relative; WIDTH: 19px; PADDING: 0; TOP: 4px; -moz-user-select: none; -khtml-user-select: none; user-select: none; }
+#Hslide { BACKGROUND: url('img/slideHue.gif'); HEIGHT: 5px; WIDTH: 33px; POSITION: absolute; _font-size: 1px; line-height: 1px; }
+#Hmodel { POSITION: relative; TOP: -5px; }
+#Hmodel div { HEIGHT: 1px; WIDTH: 19px; font-size: 1px; line-height: 1px; MARGIN: 0; PADDING: 0; }
+
+.div_all { position: absolute; width: 100%; height: 100%; top: 0px; left: 0px; z-index: 1; }
\ No newline at end of file
--- /dev/null
+function ColorPicker(tmp_id, tmp_defaultcolor, tmp_output,evt) {\r
+ if ($$('div_id')) {\r
+\r
+ if ($S('plugin').display == 'none') {\r
+ toggle('plugin',tmp_defaultcolor);\r
+ }\r
+ return;\r
+ }\r
+\r
+ if (!tmp_defaultcolor) {\r
+ tmp_defaultcolor = 'FFFFFF';\r
+ }\r
+ \r
+ if (agent('msie')) { \r
+ mouseX = event.clientX;\r
+ mouseY = event.clientY;\r
+ \r
+ mouseY++;\r
+ mouseY += 4;\r
+ } else {\r
+ mouseX = 500;\r
+ mouseY = 300;\r
+ }\r
+\r
+ inner = '<div id="plugin" onmousedown="HSVslide(\'drag\',\'plugin\',event)" style="Z-INDEX:102; TOP:'+mouseY+'px;left:'+mouseX+'px; DISPLAY: none;">';\r
+ inner += '<div id="plugHEX" onmousedown="stop=0; setTimeout(\'stop=1\',100);">#'+ tmp_defaultcolor +'</div><div id="plugCLOSE" onmousedown="toggle(\'plugin\',\''+tmp_defaultcolor+'\')"><font style="color:000000">x</font></div><br>';\r
+ inner += '<div id="SV" onmousedown="HSVslide(\'SVslide\',\'plugin\',event)" title="Saturation + Value">';\r
+ inner += '<div id="SVslide" style="TOP: -4px; LEFT: -4px;"><br /></div>';\r
+ inner += '</div>';\r
+ inner += '<form id="H" onmousedown="HSVslide(\'Hslide\',\'plugin\',event)" title="Hue">';\r
+ inner += '<div id="Hslide" style="TOP: -7px; LEFT: -8px;"><br /></div>';\r
+ inner += '<div id="Hmodel"></div>';\r
+ inner += '</form><div id="plugCURI"></div><div id="plugCUR"></div>';\r
+ inner += '</div>';\r
+\r
+ var div = document.createElement('DIV');\r
+ div.setAttribute("id", "div_id");\r
+ div.setAttribute("style", "z-index: 101");\r
+\r
+ div.innerHTML = inner;\r
+ \r
+ document.getElementsByTagName('body')[0].appendChild(div);\r
+ \r
+ if (!$$('div_all_combo')) {\r
+ var div2 = document.createElement('div');\r
+ div2.id = 'div_all_combo';\r
+ div2.className = 'div_all';\r
+ div2.style.display = '';\r
+ div2.innerHtml = ' ';\r
+ div2.onclick = function () {\r
+ toggle('plugin',tmp_defaultcolor);\r
+ }\r
+ document.getElementsByTagName('body')[0].appendChild(div2);\r
+ }\r
+\r
+ $S('plugCUR').background='#'+tmp_defaultcolor;\r
+ $S('plugCURI').background='#'+tmp_defaultcolor;\r
+ global_output = tmp_output;\r
+\r
+ //LOAD\r
+ loadSV();\r
+ if (agent('msie')) {\r
+ $S('plugin').display='block';\r
+ }\r
+}\r
+\r
+function positionPlugin(e) {\r
+ if ($$('plugin')) {\r
+ if ($S('plugin').display == 'none') {\r
+ mouseY = e.pageY;\r
+ mouseY++;\r
+ mouseY+=4;\r
+ $S('plugin').left=e.pageX;\r
+ $S('plugin').top=mouseY;\r
+ $S('plugin').display='none';\r
+ document.onmousedown = null;\r
+ }\r
+ }\r
+}\r
+\r
+if (!agent('msie')) {\r
+ document.onmousedown=positionPlugin;\r
+}\r
+\r
+// DHTML Color Picker\r
+// Programming by Ulyses\r
+// ColorJack.com\r
+\r
+function $S(v) { return($$(v).style); }\r
+function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }\r
+function toggle(v,tmp_defaultcolor) {\r
+ if ($S(v).display == 'none') {\r
+ $S('div_all_combo').display = '';\r
+ $S(v).display = 'block';\r
+ $S('plugCURI').background='#'+tmp_defaultcolor;\r
+ \r
+ } else {\r
+ $S('div_all_combo').display = 'none';\r
+ $S(v).display = 'none'; \r
+ }\r
+}\r
+function within(v,a,z) { return((v>=a && v<=z)?true:false); }\r
+function XY(e,v) { var z=agent('msie')?[event.clientX+document.body.scrollLeft,event.clientY+document.body.scrollTop]:[e.pageX,e.pageY]; return(z[zero(v)]); }\r
+function XYwin(v) { var z=agent('msie')?[document.body.clientHeight,document.body.clientWidth]:[window.innerHeight,window.innerWidth]; return(!isNaN(v)?z[v]:z); }\r
+function zero(v) { v=parseInt(v); return(!isNaN(v)?v:0); }\r
+\r
+/* PLUGIN */\r
+\r
+var maxValue={'h':360,'s':100,'v':100}, HSV={0:360,1:100,2:100};\r
+var hSV=165, wSV=162, hH=163, slideHSV={0:360,1:100,2:100}, zINDEX=15, stop=1;\r
+\r
+function HSVslide(d,o,e) {\r
+\r
+ function tXY(e) { tY=XY(e,1)-top; tX=XY(e)-left; }\r
+ function mkHSV(a,b,c) { return(Math.min(a,Math.max(0,Math.ceil((parseInt(c)/b)*a)))); }\r
+ function ckHSV(a,b) { if(within(a,0,b)) return(a); else if(a>b) return(b); else if(a<0) return('-'+oo); }\r
+ function drag(e) { if(!stop) { if(d!='drag') tXY(e);\r
+ \r
+ if(d=='SVslide') { ds.left=ckHSV(tX-oo,wSV)+'px'; ds.top=ckHSV(tY-oo,wSV)+'px';\r
+ \r
+ slideHSV[1]=mkHSV(100,wSV,ds.left); slideHSV[2]=100-mkHSV(100,wSV,ds.top); HSVupdate();\r
+\r
+ }\r
+ else if(d=='Hslide') { var ck=ckHSV(tY-oo,hH), j, r='hsv', z={};\r
+ \r
+ ds.top=(ck-5)+'px'; slideHSV[0]=mkHSV(360,hH,ck);\r
+ \r
+ for(var i=0; i<=r.length-1; i++) { j=r.substr(i,1); z[i]=(j=='h')?maxValue[j]-mkHSV(maxValue[j],hH,ck):HSV[i]; }\r
+\r
+ HSVupdate(z); $S('SV').backgroundColor='#'+hsv2hex([HSV[0],100,100]);\r
+\r
+ }\r
+ else if(d=='drag') { ds.left=XY(e)+oX-eX+'px'; ds.top=XY(e,1)+oY-eY+'px'; }\r
+\r
+ }}\r
+\r
+ if(stop) { stop=''; var ds=$S(d!='drag'?d:o);\r
+\r
+ if(d=='drag') { var oX=parseInt(ds.left), oY=parseInt(ds.top), eX=XY(e), eY=XY(e,1); $S(o).zIndex=zINDEX++; }\r
+ else { var left=($$(o).offsetLeft+10), top=($$(o).offsetTop+22), tX, tY, oo=(d=='Hslide')?2:4; if(d=='SVslide') slideHSV[0]=HSV[0]; }\r
+\r
+ document.onmousemove=drag; document.onmouseup=function(){ stop=1; document.onmousemove=''; document.onmouseup=''; }; drag(e);\r
+\r
+ }\r
+}\r
+\r
+function HSVupdate(v) { \r
+\r
+ v=hsv2hex(HSV=v?v:slideHSV);\r
+ $$('plugHEX').innerHTML='#'+v;\r
+ $S('plugCUR').background='#'+v;\r
+ $S('div_color_'+global_output).background='#'+v;\r
+ \r
+ $$(global_output).value=v;\r
+ \r
+ \r
+ return(v);\r
+\r
+}\r
+\r
+function loadSV() { var z='';\r
+\r
+ for(var i=hSV; i>=0; i--) z+="<div style=\"BACKGROUND: #"+hsv2hex([Math.round((360/hSV)*i),100,100])+";\"><br /><\/div>";\r
+ \r
+ $$('Hmodel').innerHTML=z;\r
+ \r
+}\r
+\r
+/* CONVERSIONS */\r
+\r
+function toHex(v) { v=Math.round(Math.min(Math.max(0,v),255)); return("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16)); }\r
+function rgb2hex(r) { return(toHex(r[0])+toHex(r[1])+toHex(r[2])); }\r
+function hsv2hex(h) { return(rgb2hex(hsv2rgb(h))); } \r
+\r
+function hsv2rgb(r) { // easyrgb.com/math.php?MATH=M21#text21\r
+\r
+\r
+ var R,B,G,S=r[1]/100,V=r[2]/100,H=r[0]/360;\r
+\r
+ if(S>0) { if(H>=1) H=0;\r
+\r
+ H=6*H; F=H-Math.floor(H);\r
+ A=Math.round(255*V*(1.0-S));\r
+ B=Math.round(255*V*(1.0-(S*F)));\r
+ C=Math.round(255*V*(1.0-(S*(1.0-F))));\r
+ V=Math.round(255*V); \r
+\r
+ switch(Math.floor(H)) {\r
+\r
+ case 0: R=V; G=C; B=A; break;\r
+ case 1: R=B; G=V; B=A; break;\r
+ case 2: R=A; G=V; B=C; break;\r
+ case 3: R=A; G=B; B=V; break;\r
+ case 4: R=C; G=A; B=V; break;\r
+ case 5: R=V; G=A; B=B; break;\r
+\r
+ }\r
+\r
+ return([R?R:0,G?G:0,B?B:0]);\r
+\r
+ }\r
+ else return([(V=Math.round(V*255)),V,V]);\r
+\r
+}
\ No newline at end of file
--- /dev/null
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
+<link href="plugin.css" rel="stylesheet">
+<script language="javascript" type="text/javascript" src="colorpicker.js"></script>
+<title>IWORKS Color Picker</title>
+</head>
+
+
+<body>
+ <table cellspacing="0" cellpadding="0" border="0">
+ <tr>
+ <td>
+ <div style="border:#FF0000 0px solid; width:100%; height:100%" >
+ Onfocus input:
+ <table><tr><td id="core"></td></tr></table>
+ <input type="" id="cor" onFocus="javascript:ColorPicker('cor', document.getElementById('cor').value, 'cor');"><br><br>
+ </div>
+ </td>
+ </tr>
+ </table>
+</body>
+</html>
--- /dev/null
+.imgCrop_wrap {\r
+ /* width: 500px; @done_in_js */\r
+ /* height: 375px; @done_in_js */\r
+ position: relative;\r
+ cursor: crosshair;\r
+}\r
+\r
+/* an extra classname is applied for Opera < 9.0 to fix it's lack of opacity support */\r
+.imgCrop_wrap.opera8 .imgCrop_overlay,\r
+.imgCrop_wrap.opera8 .imgCrop_clickArea { \r
+ background-color: transparent;\r
+}\r
+\r
+/* fix for IE displaying all boxes at line-height by default, although they are still 1 pixel high until we combine them with the pointless span */\r
+.imgCrop_wrap,\r
+.imgCrop_wrap * {\r
+ font-size: 0;\r
+ line-height: 0;\r
+ opacity: 1;\r
+ filter:alpha(opacity=100);\r
+}\r
+\r
+.imgCrop_overlay {\r
+ background-color: #000;\r
+ opacity: 0.5;\r
+ filter:alpha(opacity=50);\r
+ position: absolute;\r
+ width: 100%;\r
+ height: 100%;\r
+}\r
+\r
+.imgCrop_selArea {\r
+ position: absolute;\r
+ /* @done_in_js \r
+ top: 20px;\r
+ left: 20px;\r
+ width: 200px;\r
+ height: 200px;\r
+ background: transparent url(castle.jpg) no-repeat -210px -110px;\r
+ */\r
+ cursor: move;\r
+ z-index: 2;\r
+}\r
+\r
+/* clickArea is all a fix for IE 5.5 & 6 to allow the user to click on the given area */\r
+.imgCrop_clickArea {\r
+ width: 100%;\r
+ height: 100%;\r
+ background-color: #FFF;\r
+ opacity: 0.01;\r
+ filter:alpha(opacity=01);\r
+}\r
+\r
+.imgCrop_marqueeHoriz {\r
+ position: absolute;\r
+ width: 100%;\r
+ height: 1px;\r
+ background: transparent url(marqueeHoriz.gif) repeat-x 0 0;\r
+ z-index: 3;\r
+}\r
+\r
+.imgCrop_marqueeVert {\r
+ position: absolute;\r
+ height: 100%;\r
+ width: 1px;\r
+ background: transparent url(marqueeVert.gif) repeat-y 0 0;\r
+ z-index: 3;\r
+}\r
+\r
+/* \r
+ * FIX MARCHING ANTS IN IE\r
+ * As IE <6 tries to load background images we can uncomment the follwoing hack \r
+ * to remove that issue, not as pretty - but is anything in IE?\r
+ * And yes I do know that 'filter' is evil, but it will make it look semi decent in IE\r
+ *\r
+* html .imgCrop_marqueeHoriz,\r
+* html .imgCrop_marqueeVert {\r
+ background: transparent;\r
+ filter: Invert; \r
+}\r
+* html .imgCrop_marqueeNorth { border-top: 1px dashed #000; }\r
+* html .imgCrop_marqueeEast { border-right: 1px dashed #000; }\r
+* html .imgCrop_marqueeSouth { border-bottom: 1px dashed #000; }\r
+* html .imgCrop_marqueeWest { border-left: 1px dashed #000; }\r
+*/\r
+\r
+.imgCrop_marqueeNorth { top: 0; left: 0; }\r
+.imgCrop_marqueeEast { top: 0; right: 0; }\r
+.imgCrop_marqueeSouth { bottom: 0px; left: 0; }\r
+.imgCrop_marqueeWest { top: 0; left: 0; }\r
+\r
+\r
+.imgCrop_handle {\r
+ position: absolute;\r
+ border: 1px solid #333;\r
+ width: 6px;\r
+ height: 6px;\r
+ background: #FFF;\r
+ opacity: 0.5;\r
+ filter:alpha(opacity=50);\r
+ z-index: 4;\r
+}\r
+\r
+/* fix IE 5 box model */\r
+* html .imgCrop_handle {\r
+ width: 8px;\r
+ height: 8px;\r
+ wid\th: 6px;\r
+ hei\ght: 6px;\r
+}\r
+\r
+.imgCrop_handleN {\r
+ top: -3px;\r
+ left: 0;\r
+ /* margin-left: 49%; @done_in_js */\r
+ cursor: n-resize;\r
+}\r
+\r
+.imgCrop_handleNE { \r
+ top: -3px;\r
+ right: -3px;\r
+ cursor: ne-resize;\r
+}\r
+\r
+.imgCrop_handleE {\r
+ top: 0;\r
+ right: -3px;\r
+ /* margin-top: 49%; @done_in_js */\r
+ cursor: e-resize;\r
+}\r
+\r
+.imgCrop_handleSE {\r
+ right: -3px;\r
+ bottom: -3px;\r
+ cursor: se-resize;\r
+}\r
+\r
+.imgCrop_handleS {\r
+ right: 0;\r
+ bottom: -3px;\r
+ /* margin-right: 49%; @done_in_js */\r
+ cursor: s-resize;\r
+}\r
+\r
+.imgCrop_handleSW {\r
+ left: -3px;\r
+ bottom: -3px;\r
+ cursor: sw-resize;\r
+}\r
+\r
+.imgCrop_handleW {\r
+ top: 0;\r
+ left: -3px;\r
+ /* margin-top: 49%; @done_in_js */\r
+ cursor: w-resize;\r
+}\r
+\r
+.imgCrop_handleNW {\r
+ top: -3px;\r
+ left: -3px;\r
+ cursor: nw-resize;\r
+}\r
+\r
+/**\r
+ * Create an area to click & drag around on as the default browser behaviour is to let you drag the image \r
+ */\r
+.imgCrop_dragArea {\r
+ width: 100%;\r
+ height: 100%;\r
+ z-index: 200;\r
+ position: absolute;\r
+ top: 0;\r
+ left: 0;\r
+}\r
+\r
+.imgCrop_previewWrap {\r
+ /* width: 200px; @done_in_js */\r
+ /* height: 200px; @done_in_js */\r
+ overflow: hidden;\r
+ position: relative;\r
+}\r
+\r
+.imgCrop_previewWrap img {\r
+ position: absolute;\r
+}
\ No newline at end of file
--- /dev/null
+/** \r
+ * Copyright (c) 2006-2009, David Spurr (http://www.defusion.org.uk/)\r
+ * \r
+ * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r
+ * \r
+ * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r
+ * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\r
+ * * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\r
+ * \r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+ * \r
+ * http://www.opensource.org/licenses/bsd-license.php\r
+ * \r
+ * See scriptaculous.js for full scriptaculous licence\r
+ */\r
+\r
+var CropDraggable=Class.create(Draggable,{initialize:function(a){this.options=Object.extend({drawMethod:function(){}},arguments[1]||{});this.element=$$(a);this.handle=this.element;this.delta=this.currentDelta();this.dragging=false;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this);},draw:function(a){var e=Element.cumulativeOffset(this.element),c=this.currentDelta();e[0]-=c[0];e[1]-=c[1];var b=[0,1].map(function(d){return(a[d]-e[d]-this.offset[d]);}.bind(this));this.options.drawMethod(b);}});var Cropper={};Cropper.Img=Class.create({initialize:function(c,a){this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true,onloadCoords:null,maxWidth:0,maxHeight:0,autoIncludeCSS:true},a||{});this.img=$$(c);this.clickCoords={x:0,y:0};this.dragging=false;this.resizing=false;this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);this.isIE=/MSIE/.test(navigator.userAgent);this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);this.ratioX=0;this.ratioY=0;this.attached=false;this.fixedWidth=(this.options.maxWidth>0&&(this.options.minWidth>=this.options.maxWidth));this.fixedHeight=(this.options.maxHeight>0&&(this.options.minHeight>=this.options.maxHeight));if(typeof this.img=="undefined"){return;}if(this.options.autoIncludeCSS){$$$("script").each(function(e){if(e.src.match(/\/cropper([^\/]*)\.js/)){var f=e.src.replace(/\/cropper([^\/]*)\.js.*/,""),d=document.createElement("link");d.rel="stylesheet";d.type="text/css";d.href=f+"/cropper.css";d.media="screen";document.getElementsByTagName("head")[0].appendChild(d);}});}if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){var b=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);this.ratioX=this.options.ratioDim.x/b;this.ratioY=this.options.ratioDim.y/b;}this.subInitialize();if(this.img.complete||this.isWebKit){this.onLoad();}else{Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));}},getGCD:function(d,c){if(c===0){return d;}return this.getGCD(c,d%c);},onLoad:function(){var c="imgCrop_";var e=this.img.parentNode;var b="";if(this.isOpera8){b=" opera8";}this.imgWrap=new Element("div",{"class":c+"wrap"+b});this.north=new Element("div",{"class":c+"overlay "+c+"north"}).insert(new Element("span"));this.east=new Element("div",{"class":c+"overlay "+c+"east"}).insert(new Element("span"));this.south=new Element("div",{"class":c+"overlay "+c+"south"}).insert(new Element("span"));this.west=new Element("div",{"class":c+"overlay "+c+"west"}).insert(new Element("span"));var d=[this.north,this.east,this.south,this.west];this.dragArea=new Element("div",{"class":c+"dragArea"});d.each(function(f){this.dragArea.insert(f);},this);this.handleN=new Element("div",{"class":c+"handle "+c+"handleN"});this.handleNE=new Element("div",{"class":c+"handle "+c+"handleNE"});this.handleE=new Element("div",{"class":c+"handle "+c+"handleE"});this.handleSE=new Element("div",{"class":c+"handle "+c+"handleSE"});this.handleS=new Element("div",{"class":c+"handle "+c+"handleS"});this.handleSW=new Element("div",{"class":c+"handle "+c+"handleSW"});this.handleW=new Element("div",{"class":c+"handle "+c+"handleW"});this.handleNW=new Element("div",{"class":c+"handle "+c+"handleNW"});this.selArea=new Element("div",{"class":c+"selArea"});[new Element("div",{"class":c+"marqueeHoriz "+c+"marqueeNorth"}).insert(new Element("span")),new Element("div",{"class":c+"marqueeVert "+c+"marqueeEast"}).insert(new Element("span")),new Element("div",{"class":c+"marqueeHoriz "+c+"marqueeSouth"}).insert(new Element("span")),new Element("div",{"class":c+"marqueeVert "+c+"marqueeWest"}).insert(new Element("span")),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,new Element("div",{"class":c+"clickArea"})].each(function(f){this.selArea.insert(f);},this);this.imgWrap.appendChild(this.img);this.imgWrap.appendChild(this.dragArea);this.dragArea.appendChild(this.selArea);this.dragArea.appendChild(new Element("div",{"class":c+"clickArea"}));e.appendChild(this.imgWrap);this.startDragBind=this.startDrag.bindAsEventListener(this);Event.observe(this.dragArea,"mousedown",this.startDragBind);this.onDragBind=this.onDrag.bindAsEventListener(this);Event.observe(document,"mousemove",this.onDragBind);this.endCropBind=this.endCrop.bindAsEventListener(this);Event.observe(document,"mouseup",this.endCropBind);this.resizeBind=this.startResize.bindAsEventListener(this);this.handles=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];this.registerHandles(true);if(this.options.captureKeys){this.keysBind=this.handleKeys.bindAsEventListener(this);Event.observe(document,"keypress",this.keysBind);}var a=new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});this.setParams();},registerHandles:function(b){for(var d=0;d<this.handles.length;d++){var g=$$(this.handles[d]);if(b){var a=false;if(this.fixedWidth&&this.fixedHeight){a=true;}else{if(this.fixedWidth||this.fixedHeight){var c=g.className.match(/([S|N][E|W])$/),f=g.className.match(/(E|W)$/),e=g.className.match(/(N|S)$/);if(c||(this.fixedWidth&&f)||(this.fixedHeight&&e)){a=true;}}}if(a){g.hide();}else{Event.observe(g,"mousedown",this.resizeBind);}}else{g.show();Event.stopObserving(g,"mousedown",this.resizeBind);}}},setParams:function(){this.imgW=this.img.width;this.imgH=this.img.height;$$(this.north).setStyle({height:0});$$(this.east).setStyle({width:0,height:0});$$(this.south).setStyle({height:0});$$(this.west).setStyle({width:0,height:0});$$(this.imgWrap).setStyle({width:this.imgW+"px",height:this.imgH+"px"});$$(this.selArea).hide();var b={x1:0,y1:0,x2:0,y2:0},a=false;if(this.options.onloadCoords!==null){b=this.cloneCoords(this.options.onloadCoords);a=true;}else{if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){b.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);b.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);b.x2=b.x1+this.options.ratioDim.x;b.y2=b.y1+this.options.ratioDim.y;a=true;}}this.setAreaCoords(b,false,false,1);if(this.options.displayOnInit&&a){this.selArea.show();this.drawArea();this.endCrop();}this.attached=true;},remove:function(){if(this.attached){this.attached=false;this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);this.imgWrap.parentNode.removeChild(this.imgWrap);Event.stopObserving(this.dragArea,"mousedown",this.startDragBind);Event.stopObserving(document,"mousemove",this.onDragBind);Event.stopObserving(document,"mouseup",this.endCropBind);this.registerHandles(false);if(this.options.captureKeys){Event.stopObserving(document,"keypress",this.keysBind);}}},reset:function(){if(!this.attached){this.onLoad();}else{this.setParams();}this.endCrop();},handleKeys:function(b){var a={x:0,y:0};if(!this.dragging){switch(b.keyCode){case (37):a.x=-1;break;case (38):a.y=-1;break;case (39):a.x=1;break;case (40):a.y=1;break;}if(a.x!==0||a.y!==0){if(b.shiftKey){a.x*=10;a.y*=10;}this.moveArea([this.areaCoords.x1+a.x,this.areaCoords.y1+a.y]);this.endCrop();Event.stop(b);}}},calcW:function(){return(this.areaCoords.x2-this.areaCoords.x1);},calcH:function(){return(this.areaCoords.y2-this.areaCoords.y1);},moveArea:function(a){this.setAreaCoords({x1:a[0],y1:a[1],x2:a[0]+this.calcW(),y2:a[1]+this.calcH()},true,false);this.drawArea();},cloneCoords:function(a){return{x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2};},setAreaCoords:function(i,a,m,h,k){if(a){var j=i.x2-i.x1,f=i.y2-i.y1;if(i.x1<0){i.x1=0;i.x2=j;}if(i.y1<0){i.y1=0;i.y2=f;}if(i.x2>this.imgW){i.x2=this.imgW;i.x1=this.imgW-j;}if(i.y2>this.imgH){i.y2=this.imgH;i.y1=this.imgH-f;}}else{if(i.x1<0){i.x1=0;}if(i.y1<0){i.y1=0;}if(i.x2>this.imgW){i.x2=this.imgW;}if(i.y2>this.imgH){i.y2=this.imgH;}if(h!==null){if(this.ratioX>0){this.applyRatio(i,{x:this.ratioX,y:this.ratioY},h,k);}else{if(m){this.applyRatio(i,{x:1,y:1},h,k);}}var b=[this.options.minWidth,this.options.minHeight],l=[this.options.maxWidth,this.options.maxHeight];if(b[0]>0||b[1]>0||l[0]>0||l[1]>0){var g={a1:i.x1,a2:i.x2},e={a1:i.y1,a2:i.y2},d={min:0,max:this.imgW},c={min:0,max:this.imgH};if((b[0]!==0||b[1]!==0)&&m){if(b[0]>0){b[1]=b[0];}else{if(b[1]>0){b[0]=b[1];}}}if((l[0]!==0||l[0]!==0)&&m){if(l[0]>0&&l[0]<=l[1]){l[1]=l[0];}else{if(l[1]>0&&l[1]<=l[0]){l[0]=l[1];}}}if(b[0]>0){this.applyDimRestriction(g,b[0],h.x,d,"min");}if(b[1]>1){this.applyDimRestriction(e,b[1],h.y,c,"min");}if(l[0]>0){this.applyDimRestriction(g,l[0],h.x,d,"max");}if(l[1]>1){this.applyDimRestriction(e,l[1],h.y,c,"max");}i={x1:g.a1,y1:e.a1,x2:g.a2,y2:e.a2};}}}this.areaCoords=i;},applyDimRestriction:function(d,f,e,c,b){var a;if(b=="min"){a=((d.a2-d.a1)<f);}else{a=((d.a2-d.a1)>f);}if(a){if(e==1){d.a2=d.a1+f;}else{d.a1=d.a2-f;}if(d.a1<c.min){d.a1=c.min;d.a2=f;}else{if(d.a2>c.max){d.a1=c.max-f;d.a2=c.max;}}}},applyRatio:function(c,a,e,b){var d;if(b=="N"||b=="S"){d=this.applyRatioToAxis({a1:c.y1,b1:c.x1,a2:c.y2,b2:c.x2},{a:a.y,b:a.x},{a:e.y,b:e.x},{min:0,max:this.imgW});c.x1=d.b1;c.y1=d.a1;c.x2=d.b2;c.y2=d.a2;}else{d=this.applyRatioToAxis({a1:c.x1,b1:c.y1,a2:c.x2,b2:c.y2},{a:a.x,b:a.y},{a:e.x,b:e.y},{min:0,max:this.imgH});c.x1=d.a1;c.y1=d.b1;c.x2=d.a2;c.y2=d.b2;}},applyRatioToAxis:function(i,f,h,b){var j=Object.extend(i,{}),e=j.a2-j.a1,a=Math.floor(e*f.b/f.a),g=null,c=null,d=null;if(h.b==1){g=j.b1+a;if(g>b.max){g=b.max;d=g-j.b1;}j.b2=g;}else{g=j.b2-a;if(g<b.min){g=b.min;d=g+j.b2;}j.b1=g;}if(d!==null){c=Math.floor(d*f.a/f.b);if(h.a==1){j.a2=j.a1+c;}else{j.a1=j.a1=j.a2-c;}}return j;},drawArea:function(){var h=this.calcW(),e=this.calcH();var g="px",c=[this.areaCoords.x1+g,this.areaCoords.y1+g,h+g,e+g,this.areaCoords.x2+g,this.areaCoords.y2+g,(this.img.width-this.areaCoords.x2)+g,(this.img.height-this.areaCoords.y2)+g];var f=this.selArea.style;f.left=c[0];f.top=c[1];f.width=c[2];f.height=c[3];var i=Math.ceil((h-6)/2)+g,d=Math.ceil((e-6)/2)+g;this.handleN.style.left=i;this.handleE.style.top=d;this.handleS.style.left=i;this.handleW.style.top=d;this.north.style.height=c[1];var a=this.east.style;a.top=c[1];a.height=c[3];a.left=c[4];a.width=c[6];var j=this.south.style;j.top=c[5];j.height=c[7];var b=this.west.style;b.top=c[1];b.height=c[3];b.width=c[0];this.subDrawArea();this.forceReRender();},forceReRender:function(){if(this.isIE||this.isWebKit){var g=document.createTextNode(" ");var e,b,f,a;if(this.isIE){fixEl=this.selArea;}else{if(this.isWebKit){fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];e=new Element("div");e.style.visibility="hidden";var c=["SE","S","SW"];for(a=0;a<c.length;a++){b=document.getElementsByClassName("imgCrop_handle"+c[a],this.selArea)[0];if(b.childNodes.length){b.removeChild(b.childNodes[0]);}b.appendChild(e);}}}fixEl.appendChild(g);fixEl.removeChild(g);}},startResize:function(a){this.startCoords=this.cloneCoords(this.areaCoords);this.resizing=true;this.resizeHandle=Event.element(a).classNames().toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");Event.stop(a);},startDrag:function(a){this.selArea.show();this.clickCoords=this.getCurPos(a);this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y},false,false,null);this.dragging=true;this.onDrag(a);Event.stop(a);},getCurPos:function(b){var a=this.imgWrap,c=Element.cumulativeOffset(a);while(a.nodeName!="BODY"){c[1]-=a.scrollTop||0;c[0]-=a.scrollLeft||0;a=a.parentNode;}return{x:Event.pointerX(b)-c[0],y:Event.pointerY(b)-c[1]};},onDrag:function(f){if(this.dragging||this.resizing){var b=null,a=this.getCurPos(f),d=this.cloneCoords(this.areaCoords),c={x:1,y:1};if(this.dragging){if(a.x<this.clickCoords.x){c.x=-1;}if(a.y<this.clickCoords.y){c.y=-1;}this.transformCoords(a.x,this.clickCoords.x,d,"x");this.transformCoords(a.y,this.clickCoords.y,d,"y");}else{if(this.resizing){b=this.resizeHandle;if(b.match(/E/)){this.transformCoords(a.x,this.startCoords.x1,d,"x");if(a.x<this.startCoords.x1){c.x=-1;}}else{if(b.match(/W/)){this.transformCoords(a.x,this.startCoords.x2,d,"x");if(a.x<this.startCoords.x2){c.x=-1;}}}if(b.match(/N/)){this.transformCoords(a.y,this.startCoords.y2,d,"y");if(a.y<this.startCoords.y2){c.y=-1;}}else{if(b.match(/S/)){this.transformCoords(a.y,this.startCoords.y1,d,"y");if(a.y<this.startCoords.y1){c.y=-1;}}}}}this.setAreaCoords(d,false,f.shiftKey,c,b);this.drawArea();Event.stop(f);}},transformCoords:function(b,a,e,d){var c=[b,a];if(b>a){c.reverse();}e[d+"1"]=c[0];e[d+"2"]=c[1];},endCrop:function(){this.dragging=false;this.resizing=false;this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});},subInitialize:function(){},subDrawArea:function(){}});Cropper.ImgWithPreview=Class.create(Cropper.Img,{subInitialize:function(){this.hasPreviewImg=false;if(typeof(this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){this.previewWrap=$$(this.options.previewWrap);this.previewImg=this.img.cloneNode(false);this.previewImg.id="imgCrop_"+this.previewImg.id;this.options.displayOnInit=true;this.hasPreviewImg=true;this.previewWrap.addClassName("imgCrop_previewWrap");this.previewWrap.setStyle({width:this.options.minWidth+"px",height:this.options.minHeight+"px"});this.previewWrap.appendChild(this.previewImg);}},subDrawArea:function(){if(this.hasPreviewImg){var d=this.calcW(),e=this.calcH();var f={x:this.imgW/d,y:this.imgH/e};var c={x:d/this.options.minWidth,y:e/this.options.minHeight};var a={w:Math.ceil(this.options.minWidth*f.x)+"px",h:Math.ceil(this.options.minHeight*f.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/c.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/c.y)+"px"};var b=this.previewImg.style;b.width=a.w;b.height=a.h;b.left=a.x;b.top=a.y;}}});
--- /dev/null
+@import "../../_system/css/default.css";\r
+\r
+.trRo {\r
+ height:56px;\r
+ background:url(../img/bg-rodape.gif) top left repeat-x;\r
+}\r
+.trRo td{\r
+ text-align:center;\r
+}\r
+.trRo div.divRo{\r
+ text-align:right;\r
+ padding-right:30px;\r
+ font-size:11px;\r
+ width:964px;\r
+ margin:auto;\r
+ color:#000000;\r
+}\r
+\r
+body.bg { background: url(../img/bginn.jpg) top left repeat-x #FFFFFF; }\r
+\r
+/* Top */\r
+table.boxTopo {\r
+ padding:0px;\r
+ width: 980px;\r
+ height:111px;\r
+ border: 0px solid #CCCCCC; \r
+ margin: auto; \r
+ color: #EEEEEE; \r
+ font-size: 10px; \r
+ font-family: Tahoma; \r
+ margin-bottom: 10px;\r
+}\r
+table.box { width: 980px; border: 0px solid #CCCCCC; margin: auto; background: #FFFFFF; color: #777777; font-size: 10px; font-family: Tahoma; margin-bottom: 10px; }\r
+\r
+/* Top : menu */\r
+ul.menu { display: inline; width: 100%; }\r
+ul.menu li { display: inline; padding:0px; margin:0px; float: left; vertical-align:middle; }\r
+ul.menu li a { font-weight: bold; color: #FFFFFF; font-size: 10px; font-family:Tahoma; text-decoration: none; text-align: center; width: 120px; height:25px; float: left; padding: 10 5 10 5px; }\r
+ul.menu li a:hover { font-weight: bold; text-decoration: none; color: #D7A964; }\r
+ul.menu li a#sel { font-weight: bold; color: #D7A964 }\r
+\r
+/* Top : subs */\r
+ul.menu_abas { padding:0px; margin:0px; float: left; list-style: none; }\r
+ul.menu_abas li { display: inline; }\r
+ul.menu_abas li a { color: #194D7F; font-size: 10px; font-family: Tahoma; text-decoration: none; text-align: center; width: 100px; float: left; padding: 4 0 4 0px; margin: 0 1 0 0px; background: #FBFBFB; }\r
+ul.menu_abas li a:hover { background: #DADCDC; }\r
+ul.menu_abas li a#sel { font-weight: bold; background: #DADCDC; color: #194D7F; }\r
+\r
+/* Titles */\r
+h1 { font-family: Arial; font-size: 25px; color: #0F3357; font-weight: bold; text-align: center; line-height: 0px; margin-top: 10px; }\r
+\r
+/* List */\r
+table { font-size: 10px; font-family: Tahoma; color: #999999; }\r
+table.box tr td div.sep, div.form { border-top: 1px solid #CCCCCC; margin-top: 5px; padding-top: 5px; text-align: center; }\r
+.listagem tr td { height: 20px; padding: 0 5 0 5px; }\r
+.listagem tr td.header, .listagem tr td.header_up, .listagem tr td.header_down, .listagem tr td.header_cinza { height: 24px; background: #C1CCD2; text-align: center; vertical-align: middle; font-weight: bold; color: #666666; font-family: Arial; color: #003366; font-size: 15px; }\r
+.listagem tr td.header_up { background: #C1CCD2 url(../img/icons/arow_up.gif) right top no-repeat; }\r
+.listagem tr td.header_down { background: #C1CCD2 url(../img/icons/arow_down.gif) right top no-repeat; }\r
+.listagem tr td.header_cinza { background: #D8D8D8; }\r
+.listagem tr td.td1 { background: #F7F7F7; cursor: pointer; color: #777777; }\r
+.listagem tr td.td2 { background: #EEEEEE; cursor: pointer; color: #666666; }\r
+.listagem tr td.td1-over { background: #E5E5E5; cursor: pointer; }\r
+.listagem tr td.td2-over { background: #E5E5E5; cursor: pointer; }\r
+.listagem tr td.td3 { background: #F2F1C8; cursor: pointer; color: #777777; }\r
+.listagem tr td.td3-over { background: #E6E5A1; cursor: pointer; }\r
+\r
+/* Form / Filters */\r
+tr.fieldset td.label { padding: 5px; width: 130px; text-align: right; background: #F9F9F9; vertical-align: top; }\r
+tr.fieldset td.input { padding: 5px; text-align: left; background: #FAFAFA; }\r
+div.form { text-align: left; margin: 0px; }\r
+div.form table tr td.label { text-align: right; width: 140px; height: 30px; padding: 13 10 10 10px; background: #F9F9F9; vertical-align: top; }\r
+div.form table tr td.input { vertical-align: top; text-align: left; background: #FAFAFA; padding: 10px; }\r
+div.form table tr td.custom { text-align: left; height: 20px; padding: 5px; background: #F5F5F5; vertical-align: top; color: #003366; }\r
+div.form td.comment { vertical-align: top; text-align: left; color: #AAAAAA; font-size: 9px; padding-top: 4px; }\r
+.item { float: left; width: 139px; height: 18px; }\r
+.item #input { float: left; width: 20px; }\r
+.item #label { float: left; width: 100px; padding: 2px; }\r
+\r
+/* Fieldset */\r
+input.input, select.input, textarea.input { border-top: 1px solid #909090; border-left: 1px solid #909090; border-right: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0; height: 18px; color: #999999; font-size: 10px; font-family: Tahoma; padding: 2px; background: #FCFCFC; }\r
+\r
+/* Text */\r
+font.red { color: #990000; font-weight: bold; }\r
+\r
+/* Boxes */\r
+.box_green { padding: 10px; border: 1px solid #58D73D; background: #D0F1C9; }\r
+.box_yellow { padding: 10px; border: 1px solid #DAD73D; background: #F2F1C9; }\r
+.box_red { padding: 10px; border: 1px solid #DA553D; background: #F2CFC9; }\r
+.box_silver { padding: 10px; border: 1px solid #54628B; background: #CCD1E0; }\r
+\r
+/* Upload */\r
+div.upload_item { height: 15px; }\r
+div.upload_item div.label { width: 192px; float: left; }\r
+div.upload_item div.size { width: 40px; float: left; text-align: right; }\r
+div.upload_item div.buttons { width: 20px; float: left; text-align: right; }\r
+\r
+/* Links */\r
+a { color: #003366; text-decoration: none; }\r
+a:hover { text-decoration: underline; }
\ No newline at end of file
--- /dev/null
+.html_editor table tr td iframe { border: solid 1px #999999; width: 100%; }
+
+.html_editor td.bto_bar { padding: 3px; background: #EEEEEE; }
+
+.html_editor div.bto_ext, .html_editor div.bto_ext_over { background-color: #FFFFFF; border: 1px solid #999999; padding: 3px; margin-right: 2px; width: 16px; height: 16px; }
+.html_editor div.bto_ext a, .html_editor div.bto_ext_over a { display: block; outline:none; background-repeat: no-repeat; background-image: url(btos.gif); width: 16px; height: 16px; }
+.html_editor div.bto_ext a span, .html_editor div.bto_ext_over a span { display: none; }
+.html_editor div.bto_ext_over { border: 1px solid #333333; }
+
+.html_editor div a.bto_italic { background-position: 0px 0px; }
+.html_editor div a.bto_bold { background-position: 0px -16px; }
+.html_editor div a.bto_createlink { background-position: -16px 0px; }
+.html_editor div a.bto_unlink { background-position: -16px -16px; }
+.html_editor div a.bto_justifycenter { background-position: -32px 0px; }
+.html_editor div a.bto_justifyleft { background-position: -32px -16px; }
+.html_editor div a.bto_justifyright { background-position: -48px 0px; }
+.html_editor div a.bto_justifyfull { background-position: -48px -16px; }
+.html_editor div a.bto_image { background-position: -64px 0px; }
+.html_editor div a.bto_underline { background-position: -64px -16px; }
+.html_editor div a.bto_insertorderedlist { background-position: -80px -16px; }
+.html_editor div a.bto_insertunorderedlist { background-position: -80px 0px; }
+.html_editor div a.bto_removeformat { background-position: 0px -32px; }
+.html_editor div a.bto_viewhtml { background-position: -48px -32px; }
+
+.html_editor table tr td a.bto_voltar { border: 1px solid #CCCCCC; padding: 3px; background: #FFF; display: block; width: 57px; text-decoration: none; color: #666666; text-align: center; }
+
+.html_editor .link_box { z-index: 9999; padding: 4px; position: absolute; margin-top: 1px; background: #EEEEEE; border: solid 1px #CCCCCC; width: 300px; font-family: Tahoma; font-size: 10px; }
+.html_editor .link_box table { font-family: Tahoma; font-size: 10px; }
+.html_editor .link_box div.content { padding: 8px; width: 284px; _width: 300px; height: 40px; _height: 60px; background: #FBFBFB; font-size: 10px; }
+.html_editor .link_box div.bt { margin-top: 5px; width: 100px; height: 20px; _height: 30px; border: 1px solid #8BC78C; background: #D5EBCF; text-align: center; padding-top: 7px; cursor: pointer; color: #009900; }
+.html_editor .link_box div.bt_action { color: #999999; border: 1px solid #E3E3E3; background: #F3F3F3; }
+.html_editor .link_box div.aba_sel { cursor: pointer; padding-top: 2px; _padding-top: 2px; margin: 0px; width: 70px; height: 17px; _height: 19px; background: #FBFBFB; float: left; text-align: center; margin-right: 3px; font-size: 10px; }
+.html_editor .link_box div.aba_fechar { color: #990000; margin-left: 210px; _margin-left: 213px; cursor: pointer; border: 1px solid #E69191; background: #F7D5D5; float: left; padding: 0px; width: 15px; height: 15px; text-align: center; }
+
+.html_editor .image_box { z-index: 9999; padding: 4px; position: absolute; margin-top: 1px; background: #EEEEEE; border: solid 1px #CCCCCC; width: 300px; font-family: Tahoma; font-size: 10px; }
+.html_editor .image_box table { font-family: Tahoma; font-size: 10px; }
+.html_editor .image_box div.aba, .html_editor .image_box div.aba_over, .html_editor .image_box div.aba_sel { cursor: pointer; padding-top: 2px; _padding-top: 2px; margin: 0px; width: 70px; height: 17px; _height: 19px; background: #F3F3F3; float: left; text-align: center; margin-right: 3px; font-size: 10px; }
+.html_editor .image_box div.aba_over { background: #F7F7F7; }
+.html_editor .image_box div.aba_sel { background: #FBFBFB; }
+.html_editor .image_box div.content { padding: 8px; width: 284px; _width: 300px; height: 200px; background: #FBFBFB; font-size: 10px; }
+.html_editor .image_box div.thumb { vertical-align: middle; text-align: center; background: #EEEEEE; width: 120px; height: 120px; margin: 5 20 15 0px; padding: 2px; }
+.html_editor .image_box div.aba_fechar { color: #990000; margin-left: 64px; _margin-left: 66px; cursor: pointer; border: 1px solid #E69191; background: #F7D5D5; float: left; padding: 0px; width: 15px; height: 15px; text-align: center; }
+.html_editor .image_box div.bt { margin-top: 5px; width: 100px; height: 20px; _height: 30px; border: 1px solid #8BC78C; background: #D5EBCF; text-align: center; padding-top: 7px; cursor: pointer; color: #009900; }
+.html_editor .image_box div.bt_action { color: #999999; border: 1px solid #E3E3E3; background: #F3F3F3; }
+.html_editor .image_box div.thumb_list { cursor: pointer; float: left; width: 70px; height: 70px; _width: 76px; _height: 76px; margin: 2px; background: #EEEEEE; padding: 3px; }
+
+.html_editor .alert { width: 274px; _width: 284px; border: 1px solid #FFCC00; background: #FFFFCC; padding: 4px; margin: 10 0 10 0px; }
\ No newline at end of file
--- /dev/null
+/*\r
+TODO:\r
+ - Tag do youtube\r
+ - Ver botão de excluir elemento quando selecionado (img, retirar link...)(estudar isso)\r
+ - Ver editar url(estudar isso)\r
+ - Ver se tem como dar resize por php nas imagems\r
+ \r
+Lembrar:\r
+ - Na hora de gravar no banco, dar resize no php nas imagems\r
+ - Limpar o html\r
+*/\r
+\r
+//Requires include default.js\r
+try { var _test_htmleditor = __include_default; }\r
+catch(e) {\r
+ alert("htmleditor.js : Include '_system/js/default.js' é obrigatório");\r
+}\r
+\r
+var __include_htmleditor = true;\r
+\r
+var HtmlEditor_ROOT = "../inc/htmleditor/";\r
+\r
+function HtmlEditor() {\r
+ this.class_name = ""; //Name of instancied js var\r
+ this.field_id = ""; //Textarea hidden id\r
+ this.buttons = []; //array of removed buttons\r
+ this.width = '100%';\r
+ this.height = '300';\r
+ this.images_path = "";\r
+ this.root_path = "";\r
+ this.is_window_opened = false;\r
+ \r
+ this.onLoad = new Function();\r
+ \r
+ this._toolbar = ["viewhtml", "|", "removeformat", "|", "bold", "italic", "underline", "|", "justifyleft", "justifycenter", "justifyright", "justifyfull", "|", "insertorderedlist", "insertunorderedlist", "|", "createlink", "unlink", "|", "image"];\r
+ this._content = '';\r
+ this._image_aba = 0;\r
+ this._list_refresh = false;\r
+ this._key_status = []; //Remember keys status\r
+ this._is_view_html = false;\r
+ this._last_range = null;\r
+ \r
+ this.make = function () {\r
+ var html = '';\r
+ \r
+ html += '<table cellspacing="0" cellpadding="0" width="'+this.width+'">';\r
+ html += '<tr><td class="bto_bar" id="' + this.class_name + '_td_bar"><table cellspacing="0" cellpadding="0"><tr>';\r
+ \r
+ var toolbar_ = this._toolbar.remove(this.buttons); //Remove buttons\r
+ var self = this;\r
+ var tab_order_ = 200;\r
+ toolbar_.each(function (k, v) {\r
+ if (v == '|') {\r
+ html += '<td> </td>';\r
+ } else {\r
+ html += '<td><div class="bto_ext" onmouseover="javascript: { this.setAttribute(\'class\', \'bto_ext_over\'); this.setAttribute(\'className\', \'bto_ext_over\'); }" onmouseout="javascript: { this.setAttribute(\'class\', \'bto_ext\'); this.setAttribute(\'className\', \'bto_ext\'); }"><a taborder="' + tab_order_ + '" class="bto_' + v + '" href="javascript: nothing_func();" onclick="javascript: ' + self.class_name + '._command(\'' + v + '\')" title="' + self._getDescription(v) + '"><span>' + v + '</span></a></div>';\r
+ \r
+ if (v == 'image') {\r
+ html += '<div id="' + self.class_name + '_image_box" class="image_box" style="display: none;">';\r
+ html += '<table cellspacing="0" cellpadding="0"><tr><td>';\r
+ html += '<div id="' + self.class_name + '_image_box_aba0" class="aba_sel" onmouseover="javascript: ' + self.class_name + '._imageAbaEvent(\'over\', 0);" onmouseout="javascript: ' + self.class_name + '._imageAbaEvent(\'out\', 0);" onclick="javascript: ' + self.class_name + '._imageAbaEvent(\'click\', 0);">Informações</div>';\r
+ html += '<div id="' + self.class_name + '_image_box_aba1" class="aba" onmouseover="javascript: ' + self.class_name + '._imageAbaEvent(\'over\', 1);" onmouseout="javascript: ' + self.class_name + '._imageAbaEvent(\'out\', 1);" onclick="javascript: ' + self.class_name + '._imageAbaEvent(\'click\', 1);">Selecionar</div>';\r
+ html += '<div id="' + self.class_name + '_image_box_aba2" class="aba" onmouseover="javascript: ' + self.class_name + '._imageAbaEvent(\'over\', 2);" onmouseout="javascript: ' + self.class_name + '._imageAbaEvent(\'out\', 2);" onclick="javascript: ' + self.class_name + '._imageAbaEvent(\'click\', 2);">Upload</div>';\r
+ html += '<div class="aba_fechar" onclick="javascript: ' + self.class_name + '._command(\'image\');" title="Fechar">x</div>';\r
+ html += '</td></tr><tr><td>';\r
+ html += '<div id="' + self.class_name + '_image_box_content0" class="content">';\r
+ html += 'Url:<br><input class="input" type="text" style="width: 285px;" id="' + self.class_name + '_image_box_url" onblur="javascript: ' + self.class_name + '._imageThumb();">';\r
+ html += '<table cellspacing="0" cellpadding="0" width="100%">';\r
+ html += '<tr><td width="140" height="140"><div class="thumb" id="' + self.class_name + '_image_thumb"><br><br><br><br>sem imagem</div></td>';\r
+ html += '<td valign="top">';\r
+ html += '<div class="bt bt_action" style="width: 100%;" onclick="javascript: ' + self.class_name + '._imageAbaEvent(\'click\', 1);">Selecionar do servidor</div>';\r
+ html += '<div class="bt bt_action" style="width: 100%;" onclick="javascript: ' + self.class_name + '._imageAbaEvent(\'click\', 2);">Fazer upload para o servidor</div>'; \r
+ html += '</td></tr>';\r
+ html += '</table>';\r
+ html += '</div>';\r
+ html += '<div id="' + self.class_name + '_image_box_content1" class="content" style="display: none; overflow: auto;">carregando...</div>';\r
+ html += '<div id="' + self.class_name + '_image_box_content2" class="content" style="display: none;">';\r
+ html += '<form id="' + self.class_name + '_image_box_form">Arquivo:<br><input class="input" type="file" size="39" style="_width: 284px;" id="' + self.class_name + '_image_box_file" name="file"></form>';\r
+ html += '<div class="alert">Apenas arquivos .jpg, .gif e .png</div>';\r
+ html += '<div align="right"><div class="bt bt_action" id="' + self.class_name + '_image_box_upload" onclick="javascript: ' + self.class_name + '._imageUpload();">Enviar</div></div>';\r
+ html += '</div>';\r
+ html += '</td></tr>';\r
+ html += '<tr><td height="34" align="right" valign="bottom"><div class="bt" style="margin-top: 0px;" onclick="' + self.class_name + '._imageOK();">OK</div></td></tr>';\r
+ html += '</table>';\r
+ html += '</div>';\r
+ } else if (v == 'createlink') {\r
+ html += '<div id="' + self.class_name + '_link_box" class="link_box" style="display: none;">';\r
+ html += '<table cellspacing="0" cellpadding="0"><tr><td>';\r
+ html += '<div id="' + self.class_name + '_link_box_aba0" class="aba_sel" onmouseover="javascript: ' + self.class_name + '._imageAbaEvent(\'over\', 0);" onmouseout="javascript: ' + self.class_name + '._imageAbaEvent(\'out\', 0);" onclick="javascript: ' + self.class_name + '._imageAbaEvent(\'click\', 0);">Informações</div>';\r
+ html += '<div class="aba_fechar" onclick="javascript: ' + self.class_name + '._command(\'createlink\');" title="Fechar">x</div>';\r
+ html += '</td></tr><tr><td>';\r
+ html += '<div class="content">';\r
+ html += 'Url:<br><input class="input" type="text" value="http://" style="width: 285px;" id="' + self.class_name + '_link_box_url"></td></tr>';\r
+ html += '<tr><td align="right" valign="bottom"><div class="bt" id="' + self.class_name + '_link_box_ok" onclick="javascript: ' + self.class_name + '._linkOK();">OK</div>';\r
+ html += '</div></td></tr></table>';\r
+ html += '</div>';\r
+ }\r
+ \r
+ html += '</td>';\r
+ \r
+ tab_order_++;\r
+ }\r
+ }, this);\r
+ \r
+ this._toolbar = toolbar_;\r
+ \r
+ html += '</tr></table></td></tr>';\r
+ \r
+ html += '<tr><td style="background: #FFF;" id="' + this.class_name + '_td_iframe">';\r
+ html += ' <iframe id="' + this.class_name + '_iframe" width="' + this.width + '" height="' + this.height + '" frameborder="0"></iframe>';\r
+ html += '</td></tr>';\r
+ \r
+ html += '<tr><td style="background: #FFF; display: none;" id="' + this.class_name + '_td_codehtml">';\r
+ html += ' <table cellspacing="0" cellpadding="0" width="100%">';\r
+ html += ' <tr><td class="bto_bar"><a class="bto_voltar" href="javascript: nothing_func();" onclick="javascript: ' + this.class_name + '._command(\'viewhtml\')">Voltar</a></td></tr>';\r
+ html += ' <tr><td><textarea id="' + this.class_name + '_codehtml" style="width: ' + this.width + '; height: ' + this.height + ';"></textarea></td></tr>';\r
+ html += ' </table>';\r
+ html += '</td></tr>';\r
+ \r
+ html += '</html>';\r
+ \r
+ var d = document.createElement('div');\r
+ d.setAttribute('id', this.class_name + '_div');\r
+ d.setAttribute('className', 'html_editor');\r
+ d.setAttribute('class', 'html_editor');\r
+ d.innerHTML = html;\r
+ $$(this.field_id).parentNode.appendChild(d);\r
+ \r
+ //get content from textarea element\r
+ this._content = $$(this.field_id).value;\r
+ \r
+ //enable design mode to iframe\r
+ setTimeout(this._enableIframe.bind(this), 50);\r
+ \r
+ //hidden textarea element\r
+ $$(this.field_id).style.display = 'none';\r
+ }\r
+ \r
+ this.loadFile = function (tmp_path) {\r
+ var a = new Ajax();\r
+ var self = this;\r
+ \r
+ a.onLoad = function () {\r
+ this.html = this.html.replace(new RegExp('#ROOT#', 'g'), self.root_path);\r
+ \r
+ self._getIframeDocument().body.innerHTML = this.html;\r
+ self._insertHTML('');\r
+ }\r
+ a.get(tmp_path);\r
+ }\r
+ \r
+ this.getContent = function () {\r
+ return $$(this.field_id).value;\r
+ }\r
+ \r
+ this._enableIframe = function () {\r
+ this._getIframeDocument().designMode = 'on';\r
+ \r
+ if (this._getIframeDocument().body) {\r
+ this._getIframeDocument().body.innerHTML = '';\r
+ }\r
+ \r
+ //set content to iframe\r
+ setTimeout(this._initContent.bind(this), 300);\r
+ \r
+ //enable timer for copy text from iframe to textarea\r
+ setTimeout(this._updateField.bind(this), 350);\r
+ \r
+ //set ok events for boxes\r
+ var self = this;\r
+ addEvent($$(this.class_name + '_link_box_url'), "keydown", function (e) { self._okEvent(e, self.class_name + '._linkOK()'); });\r
+ addEvent($$(this.class_name + '_image_box_url'), "keydown", function (e) { self._okEvent(e, self.class_name + '._imageOK()'); });\r
+ }\r
+ \r
+ this._initContent = function () {\r
+ var self = this;\r
+ \r
+ this._getIframeDocument().body.innerHTML = this._content;\r
+ this._insertHTML('');\r
+ \r
+ addEvent(this._getIframeDocument(), "keydown", function (e) { self._fireEvent('keydown', e); });\r
+ addEvent(this._getIframeDocument(), "keyup", function (e) { self._fireEvent('keyup', e); });\r
+ \r
+ if (document.all) {\r
+ addEvent(this._getIframeDocument(), "selectionchange", function (e) { self._fireEvent('selectionchange', e || event); });\r
+ } else {\r
+ addEvent(this._getIframeDocument(), "mouseup", function (e) { self._fireEvent('selectionchange', e || event); });\r
+ }\r
+ \r
+ this.onLoad();\r
+ }\r
+ \r
+ this._fireEvent = function (tmp_type, tmp_e) { \r
+ var k = tmp_e.keyCode;\r
+ \r
+ switch (tmp_type) {\r
+ case "keydown":\r
+ this._key_status[k] = true;\r
+ \r
+ if (this._key_status[17] && (k == 13)) {\r
+ //this._insertHTML('<h1>teste!</h1>');\r
+ }\r
+ \r
+ break;\r
+ \r
+ case "keyup":\r
+ this._key_status[k] = false;\r
+ \r
+ break;\r
+ \r
+ case "selectionchange":\r
+ \r
+ break;\r
+ }\r
+ }\r
+ \r
+ this._okEvent = function (tmp_e, tmp_func) {\r
+ var k = tmp_e.keyCode;\r
+ \r
+ if (k == 13) {\r
+ eval(tmp_func);\r
+ }\r
+ }\r
+ \r
+ this._getIframeDocument = function () {\r
+ if ($$(this.class_name + '_iframe').contentDocument) {\r
+ return $$(this.class_name + '_iframe').contentDocument;\r
+ } else {\r
+ return document.frames[this.class_name + '_iframe'].document;\r
+ }\r
+ }\r
+ \r
+ this._updateField = function () {\r
+ if ($$(this.class_name + '_iframe') && (!this._is_view_html)) {\r
+ var content = this._getIframeDocument().body.innerHTML;\r
+ \r
+ //clean content\r
+ if (content.substr(-4) == '<br>') {\r
+ content = content.substr(0, content.length - 4);\r
+ }\r
+ \r
+ content = content.replace('<p class="MsoPlainText">', '<p>');\r
+ content = content.replace('<o:p></o:p>', '');\r
+ \r
+ if (content == '<P> </P>') {\r
+ content = '';\r
+ }\r
+ \r
+ $$(this.field_id).value = content.trim();\r
+ }\r
+ \r
+ setTimeout(this._updateField.bind(this), 500);\r
+ }\r
+ \r
+ this._insertHTML = function (tmp_html) {\r
+ if (document.all) {\r
+ this._getIframeDocument().body.setActive();\r
+ }\r
+ \r
+ if (document.all) {\r
+ var r = this._last_range;\r
+ \r
+ if (r == null) {\r
+ r = this._getIframeDocument().selection.createRange()\r
+ }\r
+ \r
+ r.select();\r
+ r.collapse(false);\r
+ r.pasteHTML(tmp_html);\r
+ } else {\r
+ var rnd_str = "insert_html_" + Math.round(Math.random()*100000000);\r
+ this._getIframeDocument().execCommand('insertimage', false, rnd_str);\r
+ this._getIframeDocument().body.innerHTML = this._getIframeDocument().body.innerHTML.replace(new RegExp('<[^<]*' + rnd_str + '[^>]*>'), tmp_html);\r
+ }\r
+ }\r
+ \r
+ this._command = function (tmp_command) {\r
+ switch (tmp_command) {\r
+ case 'image':\r
+ if ($$(this.class_name + '_image_box').style.display == 'none') {\r
+ if (document.all) {\r
+ this._last_range = this._getIframeDocument().selection.createRange();\r
+ }\r
+ \r
+ $$(this.class_name + '_image_box').style.display = '';\r
+ screenLock(true);\r
+ \r
+ this.is_window_opened = true;\r
+ } else {\r
+ $$(this.class_name + '_image_box').style.display = 'none';\r
+ screenLock(false);\r
+ \r
+ this.is_window_opened = false;\r
+ }\r
+ \r
+ break;\r
+ case 'createlink':\r
+ if ($$(this.class_name + '_link_box').style.display == 'none') {\r
+ if (document.all) {\r
+ this._last_range = this._getIframeDocument().selection.createRange();\r
+ }\r
+\r
+ $$(this.class_name + '_link_box').style.display = '';\r
+ screenLock(true);\r
+ \r
+ this.is_window_opened = true;\r
+ } else {\r
+ $$(this.class_name + '_link_box').style.display = 'none';\r
+ screenLock(false);\r
+ \r
+ this.is_window_opened = false;\r
+ }\r
+ \r
+ break;\r
+ case 'viewhtml':\r
+ if (!this._is_view_html) {\r
+ $$(this.class_name + '_td_iframe').style.display = 'none';\r
+ $$(this.class_name + '_td_bar').style.display = 'none';\r
+ \r
+ $$(this.class_name + '_td_codehtml').style.display = '';\r
+ \r
+ $$(this.class_name + '_codehtml').value = this._getIframeDocument().body.innerHTML.replace(new RegExp("<br>", "gi"), "<br>\n").replace(new RegExp("<\p>", "gi"), "<\p>\n");\r
+ \r
+ $$(this.class_name + '_codehtml').focus();\r
+ \r
+ this._is_view_html = true;\r
+ } else {\r
+ this._is_view_html = false;\r
+ \r
+ $$(this.class_name + '_td_iframe').style.display = '';\r
+ $$(this.class_name + '_td_bar').style.display = '';\r
+ \r
+ $$(this.class_name + '_td_codehtml').style.display = 'none';\r
+ \r
+ this._getIframeDocument().body.innerHTML = $$(this.class_name + '_codehtml').value;\r
+ this._insertHTML('');\r
+ }\r
+ \r
+ break;\r
+ default:\r
+ $$(this.class_name + '_iframe').focus();\r
+ this._getIframeDocument().execCommand(tmp_command, false, '');\r
+ \r
+ break;\r
+ }\r
+ \r
+ try {\r
+ $$(this.class_name + '_iframe').contentWindow.focus();\r
+ } catch (e) { }\r
+ }\r
+ \r
+ this._getDescription = function (tmp_button) {\r
+ switch (tmp_button) {\r
+ case "removeformat": return "Remover formatação"; break;\r
+ case "bold": return "Aplicar/Retirar negrito"; break;\r
+ case "italic": return "Aplicar/Retirar itálico"; break;\r
+ case "underline": return "Aplicar/Retirar underline"; break;\r
+ case "justifyleft": return "Alinhar à esquerda"; break;\r
+ case "justifylright": return "Alinhar ao centro"; break;\r
+ case "justifylright": return "Alinhar à direita"; break;\r
+ case "justifyfull": return "Justificar"; break;\r
+ case "insertorderedlist": return "Inserir/Remover lista ordenada"; break;\r
+ case "insertunorderedlist": return "Inserir/Remover lista não ordenada"; break;\r
+ case "createlink": return "Inserir link"; break;\r
+ case "unlink": return "Remover link"; break;\r
+ case "image": return "Inserir imagem"; break;\r
+ case "viewhtml": return "Editar html"; break;\r
+ default: return ""; break;\r
+ }\r
+ }\r
+ \r
+ //Image\r
+ this._imageAbaEvent = function (tmp_event, tmp_index) {\r
+ this._image_aba++; this._image_aba--;\r
+ tmp_index++; tmp_index--;\r
+ \r
+ switch (tmp_event) {\r
+ case 'over':\r
+ if (tmp_index != this._image_aba) {\r
+ $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('className', 'aba_over');\r
+ $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('class', 'aba_over');\r
+ }\r
+ \r
+ break;\r
+ case 'out':\r
+ if (tmp_index != this._image_aba) {\r
+ $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('className', 'aba');\r
+ $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('class', 'aba');\r
+ }\r
+ \r
+ break;\r
+ case 'click':\r
+ if (tmp_index != this._image_aba) {\r
+ $$(this.class_name + '_image_box_aba' + this._image_aba).setAttribute('className', 'aba');\r
+ $$(this.class_name + '_image_box_aba' + this._image_aba).setAttribute('class', 'aba');\r
+ $$(this.class_name + '_image_box_content' + this._image_aba).style.display = 'none';\r
+ \r
+ this._image_aba = tmp_index;\r
+ \r
+ $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('className', 'aba_sel');\r
+ $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('class', 'aba_sel');\r
+ $$(this.class_name + '_image_box_content' + tmp_index).style.display = '';\r
+ \r
+ if ((this._image_aba == 1) && (!this._list_refresh)) {\r
+ this._list_refresh = true;\r
+ \r
+ this._imageListRefresh();\r
+ }\r
+ }\r
+ \r
+ break;\r
+ }\r
+ }\r
+ \r
+ this._imageThumb = function () {\r
+ var url = $$(this.class_name + '_image_box_url').value;\r
+ var ext = url.substr(url.length - 3, 3).toLowerCase();\r
+ var html = '<br><br><br><br>sem imagem';\r
+ \r
+ url = url.replace(this.root_path, '');\r
+ \r
+ if ((ext == 'jpg') || (ext == 'gif')) {\r
+ html = '<img src="' + HtmlEditor_ROOT + 'routines.php?routine=thumb&file=' + url + '&w=118&h=118">';\r
+ }\r
+ \r
+ $$(this.class_name + '_image_thumb').innerHTML = html;\r
+ }\r
+ \r
+ this._imageListRefresh = function () {\r
+ var a = new Ajax();\r
+ var self = this;\r
+ \r
+ a.onLoad = function () {\r
+ var ext, html = '';\r
+ var arr = this.html.split('##');\r
+ \r
+ arr.each(function (k, v) {\r
+ if (v != '') {\r
+ ext = v.substr(v.length - 3, 3).toLowerCase();\r
+ \r
+ if ((ext == 'jpg') || (ext == 'gif')) {\r
+ html += '<div class="thumb_list" onclick="javascript: ' + self.class_name + '._imageSelect(\'' + v + '\');"><img src="' + HtmlEditor_ROOT + 'routines.php?routine=thumb&method=2&file=' + v + '&w=70&h=70" width="70" height="70" title="' + v + '"></div>';\r
+ }\r
+ }\r
+ }, this);\r
+ \r
+ $$(self.class_name + '_image_box_content1').innerHTML = html;\r
+ }\r
+ a.get(HtmlEditor_ROOT + "routines.php?routine=list&path=" + this.images_path);\r
+ }\r
+ \r
+ this._imageSelect = function (tmp_path) {\r
+ $$(this.class_name + '_image_box_url').value = tmp_path;\r
+ \r
+ this._imageAbaEvent('click', 0);\r
+ this._imageThumb();\r
+ }\r
+ \r
+ this._imageUpload = function () {\r
+ var onload, input, form, iframe, self, ext;\r
+ \r
+ self = this;\r
+ \r
+ iframe = document.createElement("iframe");\r
+ iframe.setAttribute("id","ifr_tmp");\r
+ iframe.setAttribute("name","ifr_tmp");\r
+ iframe.setAttribute("width","0");\r
+ iframe.setAttribute("height","0");\r
+ iframe.setAttribute("border","0");\r
+ iframe.setAttribute("style","width: 0; height: 0; border: none;");\r
+ $$(this.field_id).parentNode.appendChild(iframe);\r
+ window.frames["ifr_tmp"].name = "ifr_tmp"; //Ie sux\r
+ \r
+ //Verify if input file is not empty\r
+ input = $$(this.class_name + '_image_box_file');\r
+ \r
+ if (input.value != '') {\r
+ //Verify extension\r
+ ext = input.value.substr(input.value.length - 3, 3).toLowerCase();\r
+ \r
+ if ((ext == 'jpg') || (ext == 'gif') || (ext == 'png')) {\r
+ onload = function () {\r
+ self._imageAbaEvent('click', 1);\r
+ \r
+ //Removes iframe element\r
+ setTimeout(function () { removeElement($$('ifr_tmp')); }, 250);\r
+ \r
+ $$(self.class_name + '_image_box_upload').style.display = '';\r
+ removeElement($$(self.class_name + '_image_box_carregando'));\r
+ \r
+ self._imageListRefresh();\r
+ }\r
+ addEvent($$('ifr_tmp'), "load", onload);\r
+ \r
+ //Config form element\r
+ form = $$(this.class_name + '_image_box_form');\r
+ form.setAttribute("target", "ifr_tmp");\r
+ form.setAttribute("action", HtmlEditor_ROOT + "routines.php?routine=upload&path=" + this.images_path);\r
+ form.setAttribute("method", "post");\r
+ form.setAttribute("enctype", "multipart/form-data");\r
+ form.setAttribute("encoding", "multipart/form-data");\r
+ \r
+ form.submit();\r
+ \r
+ var d = document.createElement("div");\r
+ d.id = this.class_name + "_image_box_carregando";\r
+ d.innerHTML = "Carregando...";\r
+ $$(this.class_name + '_image_box_upload').parentNode.appendChild(d);\r
+ \r
+ $$(this.class_name + '_image_box_upload').style.display = 'none';\r
+ } else {\r
+ alert("Arquivo inválido.\nSão permitidos apenas arquivos .jpg, .gif e .png"); \r
+ }\r
+ } else {\r
+ alert("O campo 'Arquivo' está vazio");\r
+ \r
+ input.focus();\r
+ }\r
+ }\r
+ \r
+ this._imageOK = function () {\r
+ var url = $$(this.class_name + '_image_box_url').value;\r
+ var ext = url.substr(url.length - 3, 3).toLowerCase();\r
+ \r
+ if ((ext == 'jpg') || (ext == 'gif')) { \r
+ if (url.indexOf('http://') == -1) {\r
+ url = this.root_path + url; \r
+ }\r
+ \r
+ this._insertHTML('<img src="' + url + '" border="0">');\r
+ \r
+ this._command('image');\r
+ \r
+ this._imageThumb();\r
+ } else {\r
+ alert('Imagem inválida, verifique a url informada.');\r
+ }\r
+ }\r
+ \r
+ //Link\r
+ this._linkOK = function () {\r
+ var url = $$(this.class_name + '_link_box_url').value;\r
+ var http = url.substr(0, 4);\r
+ \r
+ if (http == 'http') { \r
+ if (document.all) {\r
+ this._getIframeDocument().body.setActive();\r
+ \r
+ var r = this._last_range;\r
+ \r
+ if (r == null) {\r
+ r = this._getIframeDocument().selection.createRange()\r
+ }\r
+ \r
+ r.select();\r
+ \r
+ r.collapse(false);\r
+ }\r
+ \r
+ this._getIframeDocument().execCommand('createlink', false, url);\r
+ \r
+ this._command('createlink');\r
+ \r
+ $$(this.class_name + '_link_box_url').value = 'http://';\r
+ } else {\r
+ alert('Link inválido, verifique a url informada.');\r
+ }\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+<?
+$cfg["database_connect"] = "false";
+include("../../../_system/app.php");
+$load->system('functions/text.php');
+
+$routine = $input->get("routine");
+
+//thumb
+if ($routine == "thumb") {
+ $w = $input->get("w");
+ $h = $input->get("h");
+
+ $w = ($w) ? $w : 80;
+ $h = ($h) ? $h : 80;
+
+ $load->system("library/Image.php");
+
+ $path = strtolower($input->get("file"));
+
+ if (substr($path, 0, 4) != "http") {
+ $path = "../../../" . $path;
+ }
+
+ $method = ($input->get("method")) ? $input->get("method") : 3;
+
+ $img = new Image($path);
+ $img->resize($w, $h, $method);
+ $img->header();
+}
+
+//list
+function doList($tmp_path) {
+ global $file;
+
+ $arr = $file->listFolder($tmp_path . "/");
+ foreach ($arr as $v) {
+ $path = $tmp_path . "/" . $v;
+
+ if (is_dir($path)) {
+ doList($path);
+ } elseif (is_file($path)) {
+ echo str_replace("../../../", "", $path) . "##";
+ }
+ }
+}
+
+if ($routine == "list") {
+ $path = $input->get('path');
+
+ if (substr($path, -1) == "/") {
+ $path = substr($path, 0, strlen($path) - 1);
+ }
+
+ doList("../../../" . $path);
+}
+
+//upload
+if ($routine == "upload") {
+ $folder = "../../../" . $input->get("path");
+
+ $file->makeFolder($folder);
+
+ $f = $_FILES["file"]["name"];
+ $ext = $file->getExtension($f);
+ $file_n = formatNameFile(substr($f, 0, strlen($f) - 4));
+
+ $file_name = $file_n . "." . $ext;
+
+ $i = 0;
+ do {
+ $c = "";
+ if ($i > 0) {
+ $c = "(" . $i . ")";
+ }
+
+ $file_name = $file_n . $c . ".jpg";
+
+ $i++;
+ } while ((file_exists($folder . $file_name)) && ($i < 20));
+
+ $file_name = $file_n . $c . "." . $ext;
+
+ if (move_uploaded_file($_FILES["file"]["tmp_name"], $folder . $file_name)) {
+ $load->system("library/Image.php");
+
+ $img = new Image($folder . $file_name);
+ $img->save($folder . $file_name);
+
+ if ($ext != "jpg") {
+ unlink($folder . $file_name);
+ }
+ echo 1;
+ } else {
+ echo 0;
+ }
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+global $load;
+global $menu;
+
+//.menu
+$load->manager("core/Menu.php");
+$menu = new Menu();
+
+$load->config("menu.php");
+?>
\ No newline at end of file
--- /dev/null
+<?
+global $profile;
+
+$profile = new Profile();
+
+if (!$profile->isLogged()) {
+ redir("../", true);
+}
+?>
\ No newline at end of file
--- /dev/null
+/* Prototype JavaScript framework, version 1.6.1
+ * (c) 2005-2009 Sam Stephenson
+ *
+ * Prototype is freely distributable under the terms of an MIT-style license.
+ * For details, see the Prototype web site: http://www.prototypejs.org/
+ *
+ *--------------------------------------------------------------------------*/
+
+var Prototype = {
+ Version: '1.6.1',
+
+ Browser: (function(){
+ var ua = navigator.userAgent;
+ var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
+ return {
+ IE: !!window.attachEvent && !isOpera,
+ Opera: isOpera,
+ WebKit: ua.indexOf('AppleWebKit/') > -1,
+ Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
+ MobileSafari: /Apple.*Mobile.*Safari/.test(ua)
+ }
+ })(),
+
+ BrowserFeatures: {
+ XPath: !!document.evaluate,
+ SelectorsAPI: !!document.querySelector,
+ ElementExtensions: (function() {
+ var constructor = window.Element || window.HTMLElement;
+ return !!(constructor && constructor.prototype);
+ })(),
+ SpecificElementExtensions: (function() {
+ if (typeof window.HTMLDivElement !== 'undefined')
+ return true;
+
+ var div = document.createElement('div');
+ var form = document.createElement('form');
+ var isSupported = false;
+
+ if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) {
+ isSupported = true;
+ }
+
+ div = form = null;
+
+ return isSupported;
+ })()
+ },
+
+ ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
+ JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
+
+ emptyFunction: function() { },
+ K: function(x) { return x }
+};
+
+if (Prototype.Browser.MobileSafari)
+ Prototype.BrowserFeatures.SpecificElementExtensions = false;
+
+
+var Abstract = { };
+
+
+var Try = {
+ these: function() {
+ var returnValue;
+
+ for (var i = 0, length = arguments.length; i < length; i++) {
+ var lambda = arguments[i];
+ try {
+ returnValue = lambda();
+ break;
+ } catch (e) { }
+ }
+
+ return returnValue;
+ }
+};
+
+/* Based on Alex Arnell's inheritance implementation. */
+
+var Class = (function() {
+ function subclass() {};
+ function create() {
+ var parent = null, properties = $A(arguments);
+ if (Object.isFunction(properties[0]))
+ parent = properties.shift();
+
+ function klass() {
+ this.initialize.apply(this, arguments);
+ }
+
+ Object.extend(klass, Class.Methods);
+ klass.superclass = parent;
+ klass.subclasses = [];
+
+ if (parent) {
+ subclass.prototype = parent.prototype;
+ klass.prototype = new subclass;
+ parent.subclasses.push(klass);
+ }
+
+ for (var i = 0; i < properties.length; i++)
+ klass.addMethods(properties[i]);
+
+ if (!klass.prototype.initialize)
+ klass.prototype.initialize = Prototype.emptyFunction;
+
+ klass.prototype.constructor = klass;
+ return klass;
+ }
+
+ function addMethods(source) {
+ var ancestor = this.superclass && this.superclass.prototype;
+ var properties = Object.keys(source);
+
+ if (!Object.keys({ toString: true }).length) {
+ if (source.toString != Object.prototype.toString)
+ properties.push("toString");
+ if (source.valueOf != Object.prototype.valueOf)
+ properties.push("valueOf");
+ }
+
+ for (var i = 0, length = properties.length; i < length; i++) {
+ var property = properties[i], value = source[property];
+ if (ancestor && Object.isFunction(value) &&
+ value.argumentNames().first() == "$super") {
+ var method = value;
+ value = (function(m) {
+ return function() { return ancestor[m].apply(this, arguments); };
+ })(property).wrap(method);
+
+ value.valueOf = method.valueOf.bind(method);
+ value.toString = method.toString.bind(method);
+ }
+ this.prototype[property] = value;
+ }
+
+ return this;
+ }
+
+ return {
+ create: create,
+ Methods: {
+ addMethods: addMethods
+ }
+ };
+})();
+(function() {
+
+ var _toString = Object.prototype.toString;
+
+ function extend(destination, source) {
+ for (var property in source)
+ destination[property] = source[property];
+ return destination;
+ }
+
+ function inspect(object) {
+ try {
+ if (isUndefined(object)) return 'undefined';
+ if (object === null) return 'null';
+ return object.inspect ? object.inspect() : String(object);
+ } catch (e) {
+ if (e instanceof RangeError) return '...';
+ throw e;
+ }
+ }
+
+ function toJSON(object) {
+ var type = typeof object;
+ switch (type) {
+ case 'undefined':
+ case 'function':
+ case 'unknown': return;
+ case 'boolean': return object.toString();
+ }
+
+ if (object === null) return 'null';
+ if (object.toJSON) return object.toJSON();
+ if (isElement(object)) return;
+
+ var results = [];
+ for (var property in object) {
+ var value = toJSON(object[property]);
+ if (!isUndefined(value))
+ results.push(property.toJSON() + ': ' + value);
+ }
+
+ return '{' + results.join(', ') + '}';
+ }
+
+ function toQueryString(object) {
+ return $H(object).toQueryString();
+ }
+
+ function toHTML(object) {
+ return object && object.toHTML ? object.toHTML() : String.interpret(object);
+ }
+
+ function keys(object) {
+ var results = [];
+ for (var property in object)
+ results.push(property);
+ return results;
+ }
+
+ function values(object) {
+ var results = [];
+ for (var property in object)
+ results.push(object[property]);
+ return results;
+ }
+
+ function clone(object) {
+ return extend({ }, object);
+ }
+
+ function isElement(object) {
+ return !!(object && object.nodeType == 1);
+ }
+
+ function isArray(object) {
+ return _toString.call(object) == "[object Array]";
+ }
+
+
+ function isHash(object) {
+ return object instanceof Hash;
+ }
+
+ function isFunction(object) {
+ return typeof object === "function";
+ }
+
+ function isString(object) {
+ return _toString.call(object) == "[object String]";
+ }
+
+ function isNumber(object) {
+ return _toString.call(object) == "[object Number]";
+ }
+
+ function isUndefined(object) {
+ return typeof object === "undefined";
+ }
+
+ extend(Object, {
+ extend: extend,
+ inspect: inspect,
+ toJSON: toJSON,
+ toQueryString: toQueryString,
+ toHTML: toHTML,
+ keys: keys,
+ values: values,
+ clone: clone,
+ isElement: isElement,
+ isArray: isArray,
+ isHash: isHash,
+ isFunction: isFunction,
+ isString: isString,
+ isNumber: isNumber,
+ isUndefined: isUndefined
+ });
+})();
+Object.extend(Function.prototype, (function() {
+ var slice = Array.prototype.slice;
+
+ function update(array, args) {
+ var arrayLength = array.length, length = args.length;
+ while (length--) array[arrayLength + length] = args[length];
+ return array;
+ }
+
+ function merge(array, args) {
+ array = slice.call(array, 0);
+ return update(array, args);
+ }
+
+ function argumentNames() {
+ var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
+ .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
+ .replace(/\s+/g, '').split(',');
+ return names.length == 1 && !names[0] ? [] : names;
+ }
+
+ function bind(context) {
+ if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
+ var __method = this, args = slice.call(arguments, 1);
+ return function() {
+ var a = merge(args, arguments);
+ return __method.apply(context, a);
+ }
+ }
+
+ function bindAsEventListener(context) {
+ var __method = this, args = slice.call(arguments, 1);
+ return function(event) {
+ var a = update([event || window.event], args);
+ return __method.apply(context, a);
+ }
+ }
+
+ function curry() {
+ if (!arguments.length) return this;
+ var __method = this, args = slice.call(arguments, 0);
+ return function() {
+ var a = merge(args, arguments);
+ return __method.apply(this, a);
+ }
+ }
+
+ function delay(timeout) {
+ var __method = this, args = slice.call(arguments, 1);
+ timeout = timeout * 1000
+ return window.setTimeout(function() {
+ return __method.apply(__method, args);
+ }, timeout);
+ }
+
+ function defer() {
+ var args = update([0.01], arguments);
+ return this.delay.apply(this, args);
+ }
+
+ function wrap(wrapper) {
+ var __method = this;
+ return function() {
+ var a = update([__method.bind(this)], arguments);
+ return wrapper.apply(this, a);
+ }
+ }
+
+ function methodize() {
+ if (this._methodized) return this._methodized;
+ var __method = this;
+ return this._methodized = function() {
+ var a = update([this], arguments);
+ return __method.apply(null, a);
+ };
+ }
+
+ return {
+ argumentNames: argumentNames,
+ bind: bind,
+ bindAsEventListener: bindAsEventListener,
+ curry: curry,
+ delay: delay,
+ defer: defer,
+ wrap: wrap,
+ methodize: methodize
+ }
+})());
+
+
+Date.prototype.toJSON = function() {
+ return '"' + this.getUTCFullYear() + '-' +
+ (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
+ this.getUTCDate().toPaddedString(2) + 'T' +
+ this.getUTCHours().toPaddedString(2) + ':' +
+ this.getUTCMinutes().toPaddedString(2) + ':' +
+ this.getUTCSeconds().toPaddedString(2) + 'Z"';
+};
+
+
+RegExp.prototype.match = RegExp.prototype.test;
+
+RegExp.escape = function(str) {
+ return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
+};
+var PeriodicalExecuter = Class.create({
+ initialize: function(callback, frequency) {
+ this.callback = callback;
+ this.frequency = frequency;
+ this.currentlyExecuting = false;
+
+ this.registerCallback();
+ },
+
+ registerCallback: function() {
+ this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
+ },
+
+ execute: function() {
+ this.callback(this);
+ },
+
+ stop: function() {
+ if (!this.timer) return;
+ clearInterval(this.timer);
+ this.timer = null;
+ },
+
+ onTimerEvent: function() {
+ if (!this.currentlyExecuting) {
+ try {
+ this.currentlyExecuting = true;
+ this.execute();
+ this.currentlyExecuting = false;
+ } catch(e) {
+ this.currentlyExecuting = false;
+ throw e;
+ }
+ }
+ }
+});
+Object.extend(String, {
+ interpret: function(value) {
+ return value == null ? '' : String(value);
+ },
+ specialChar: {
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '\\': '\\\\'
+ }
+});
+
+Object.extend(String.prototype, (function() {
+
+ function prepareReplacement(replacement) {
+ if (Object.isFunction(replacement)) return replacement;
+ var template = new Template(replacement);
+ return function(match) { return template.evaluate(match) };
+ }
+
+ function gsub(pattern, replacement) {
+ var result = '', source = this, match;
+ replacement = prepareReplacement(replacement);
+
+ if (Object.isString(pattern))
+ pattern = RegExp.escape(pattern);
+
+ if (!(pattern.length || pattern.source)) {
+ replacement = replacement('');
+ return replacement + source.split('').join(replacement) + replacement;
+ }
+
+ while (source.length > 0) {
+ if (match = source.match(pattern)) {
+ result += source.slice(0, match.index);
+ result += String.interpret(replacement(match));
+ source = source.slice(match.index + match[0].length);
+ } else {
+ result += source, source = '';
+ }
+ }
+ return result;
+ }
+
+ function sub(pattern, replacement, count) {
+ replacement = prepareReplacement(replacement);
+ count = Object.isUndefined(count) ? 1 : count;
+
+ return this.gsub(pattern, function(match) {
+ if (--count < 0) return match[0];
+ return replacement(match);
+ });
+ }
+
+ function scan(pattern, iterator) {
+ this.gsub(pattern, iterator);
+ return String(this);
+ }
+
+ function truncate(length, truncation) {
+ length = length || 30;
+ truncation = Object.isUndefined(truncation) ? '...' : truncation;
+ return this.length > length ?
+ this.slice(0, length - truncation.length) + truncation : String(this);
+ }
+
+ function strip() {
+ return this.replace(/^\s+/, '').replace(/\s+$/, '');
+ }
+
+ function stripTags() {
+ return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
+ }
+
+ function stripScripts() {
+ return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
+ }
+
+ function extractScripts() {
+ var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
+ var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
+ return (this.match(matchAll) || []).map(function(scriptTag) {
+ return (scriptTag.match(matchOne) || ['', ''])[1];
+ });
+ }
+
+ function evalScripts() {
+ return this.extractScripts().map(function(script) { return eval(script) });
+ }
+
+ function escapeHTML() {
+ return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
+ }
+
+ function unescapeHTML() {
+ return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
+ }
+
+
+ function toQueryParams(separator) {
+ var match = this.strip().match(/([^?#]*)(#.*)?$/);
+ if (!match) return { };
+
+ return match[1].split(separator || '&').inject({ }, function(hash, pair) {
+ if ((pair = pair.split('='))[0]) {
+ var key = decodeURIComponent(pair.shift());
+ var value = pair.length > 1 ? pair.join('=') : pair[0];
+ if (value != undefined) value = decodeURIComponent(value);
+
+ if (key in hash) {
+ if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
+ hash[key].push(value);
+ }
+ else hash[key] = value;
+ }
+ return hash;
+ });
+ }
+
+ function toArray() {
+ return this.split('');
+ }
+
+ function succ() {
+ return this.slice(0, this.length - 1) +
+ String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
+ }
+
+ function times(count) {
+ return count < 1 ? '' : new Array(count + 1).join(this);
+ }
+
+ function camelize() {
+ var parts = this.split('-'), len = parts.length;
+ if (len == 1) return parts[0];
+
+ var camelized = this.charAt(0) == '-'
+ ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
+ : parts[0];
+
+ for (var i = 1; i < len; i++)
+ camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
+
+ return camelized;
+ }
+
+ function capitalize() {
+ return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
+ }
+
+ function underscore() {
+ return this.replace(/::/g, '/')
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
+ .replace(/([a-z\d])([A-Z])/g, '$1_$2')
+ .replace(/-/g, '_')
+ .toLowerCase();
+ }
+
+ function dasherize() {
+ return this.replace(/_/g, '-');
+ }
+
+ function inspect(useDoubleQuotes) {
+ var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) {
+ if (character in String.specialChar) {
+ return String.specialChar[character];
+ }
+ return '\\u00' + character.charCodeAt().toPaddedString(2, 16);
+ });
+ if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
+ return "'" + escapedString.replace(/'/g, '\\\'') + "'";
+ }
+
+ function toJSON() {
+ return this.inspect(true);
+ }
+
+ function unfilterJSON(filter) {
+ return this.replace(filter || Prototype.JSONFilter, '$1');
+ }
+
+ function isJSON() {
+ var str = this;
+ if (str.blank()) return false;
+ str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
+ return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
+ }
+
+ function evalJSON(sanitize) {
+ var json = this.unfilterJSON();
+ try {
+ if (!sanitize || json.isJSON()) return eval('(' + json + ')');
+ } catch (e) { }
+ throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
+ }
+
+ function include(pattern) {
+ return this.indexOf(pattern) > -1;
+ }
+
+ function startsWith(pattern) {
+ return this.indexOf(pattern) === 0;
+ }
+
+ function endsWith(pattern) {
+ var d = this.length - pattern.length;
+ return d >= 0 && this.lastIndexOf(pattern) === d;
+ }
+
+ function empty() {
+ return this == '';
+ }
+
+ function blank() {
+ return /^\s*$/.test(this);
+ }
+
+ function interpolate(object, pattern) {
+ return new Template(this, pattern).evaluate(object);
+ }
+
+ return {
+ gsub: gsub,
+ sub: sub,
+ scan: scan,
+ truncate: truncate,
+ strip: String.prototype.trim ? String.prototype.trim : strip,
+ stripTags: stripTags,
+ stripScripts: stripScripts,
+ extractScripts: extractScripts,
+ evalScripts: evalScripts,
+ escapeHTML: escapeHTML,
+ unescapeHTML: unescapeHTML,
+ toQueryParams: toQueryParams,
+ parseQuery: toQueryParams,
+ toArray: toArray,
+ succ: succ,
+ times: times,
+ camelize: camelize,
+ capitalize: capitalize,
+ underscore: underscore,
+ dasherize: dasherize,
+ inspect: inspect,
+ toJSON: toJSON,
+ unfilterJSON: unfilterJSON,
+ isJSON: isJSON,
+ evalJSON: evalJSON,
+ include: include,
+ startsWith: startsWith,
+ endsWith: endsWith,
+ empty: empty,
+ blank: blank,
+ interpolate: interpolate
+ };
+})());
+
+var Template = Class.create({
+ initialize: function(template, pattern) {
+ this.template = template.toString();
+ this.pattern = pattern || Template.Pattern;
+ },
+
+ evaluate: function(object) {
+ if (object && Object.isFunction(object.toTemplateReplacements))
+ object = object.toTemplateReplacements();
+
+ return this.template.gsub(this.pattern, function(match) {
+ if (object == null) return (match[1] + '');
+
+ var before = match[1] || '';
+ if (before == '\\') return match[2];
+
+ var ctx = object, expr = match[3];
+ var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
+ match = pattern.exec(expr);
+ if (match == null) return before;
+
+ while (match != null) {
+ var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1];
+ ctx = ctx[comp];
+ if (null == ctx || '' == match[3]) break;
+ expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
+ match = pattern.exec(expr);
+ }
+
+ return before + String.interpret(ctx);
+ });
+ }
+});
+Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
+
+var $break = { };
+
+var Enumerable = (function() {
+ function each(iterator, context) {
+ var index = 0;
+ try {
+ this._each(function(value) {
+ iterator.call(context, value, index++);
+ });
+ } catch (e) {
+ if (e != $break) throw e;
+ }
+ return this;
+ }
+
+ function eachSlice(number, iterator, context) {
+ var index = -number, slices = [], array = this.toArray();
+ if (number < 1) return array;
+ while ((index += number) < array.length)
+ slices.push(array.slice(index, index+number));
+ return slices.collect(iterator, context);
+ }
+
+ function all(iterator, context) {
+ iterator = iterator || Prototype.K;
+ var result = true;
+ this.each(function(value, index) {
+ result = result && !!iterator.call(context, value, index);
+ if (!result) throw $break;
+ });
+ return result;
+ }
+
+ function any(iterator, context) {
+ iterator = iterator || Prototype.K;
+ var result = false;
+ this.each(function(value, index) {
+ if (result = !!iterator.call(context, value, index))
+ throw $break;
+ });
+ return result;
+ }
+
+ function collect(iterator, context) {
+ iterator = iterator || Prototype.K;
+ var results = [];
+ this.each(function(value, index) {
+ results.push(iterator.call(context, value, index));
+ });
+ return results;
+ }
+
+ function detect(iterator, context) {
+ var result;
+ this.each(function(value, index) {
+ if (iterator.call(context, value, index)) {
+ result = value;
+ throw $break;
+ }
+ });
+ return result;
+ }
+
+ function findAll(iterator, context) {
+ var results = [];
+ this.each(function(value, index) {
+ if (iterator.call(context, value, index))
+ results.push(value);
+ });
+ return results;
+ }
+
+ function grep(filter, iterator, context) {
+ iterator = iterator || Prototype.K;
+ var results = [];
+
+ if (Object.isString(filter))
+ filter = new RegExp(RegExp.escape(filter));
+
+ this.each(function(value, index) {
+ if (filter.match(value))
+ results.push(iterator.call(context, value, index));
+ });
+ return results;
+ }
+
+ function include(object) {
+ if (Object.isFunction(this.indexOf))
+ if (this.indexOf(object) != -1) return true;
+
+ var found = false;
+ this.each(function(value) {
+ if (value == object) {
+ found = true;
+ throw $break;
+ }
+ });
+ return found;
+ }
+
+ function inGroupsOf(number, fillWith) {
+ fillWith = Object.isUndefined(fillWith) ? null : fillWith;
+ return this.eachSlice(number, function(slice) {
+ while(slice.length < number) slice.push(fillWith);
+ return slice;
+ });
+ }
+
+ function inject(memo, iterator, context) {
+ this.each(function(value, index) {
+ memo = iterator.call(context, memo, value, index);
+ });
+ return memo;
+ }
+
+ function invoke(method) {
+ var args = $A(arguments).slice(1);
+ return this.map(function(value) {
+ return value[method].apply(value, args);
+ });
+ }
+
+ function max(iterator, context) {
+ iterator = iterator || Prototype.K;
+ var result;
+ this.each(function(value, index) {
+ value = iterator.call(context, value, index);
+ if (result == null || value >= result)
+ result = value;
+ });
+ return result;
+ }
+
+ function min(iterator, context) {
+ iterator = iterator || Prototype.K;
+ var result;
+ this.each(function(value, index) {
+ value = iterator.call(context, value, index);
+ if (result == null || value < result)
+ result = value;
+ });
+ return result;
+ }
+
+ function partition(iterator, context) {
+ iterator = iterator || Prototype.K;
+ var trues = [], falses = [];
+ this.each(function(value, index) {
+ (iterator.call(context, value, index) ?
+ trues : falses).push(value);
+ });
+ return [trues, falses];
+ }
+
+ function pluck(property) {
+ var results = [];
+ this.each(function(value) {
+ results.push(value[property]);
+ });
+ return results;
+ }
+
+ function reject(iterator, context) {
+ var results = [];
+ this.each(function(value, index) {
+ if (!iterator.call(context, value, index))
+ results.push(value);
+ });
+ return results;
+ }
+
+ function sortBy(iterator, context) {
+ return this.map(function(value, index) {
+ return {
+ value: value,
+ criteria: iterator.call(context, value, index)
+ };
+ }).sort(function(left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ }).pluck('value');
+ }
+
+ function toArray() {
+ return this.map();
+ }
+
+ function zip() {
+ var iterator = Prototype.K, args = $A(arguments);
+ if (Object.isFunction(args.last()))
+ iterator = args.pop();
+
+ var collections = [this].concat(args).map($A);
+ return this.map(function(value, index) {
+ return iterator(collections.pluck(index));
+ });
+ }
+
+ function size() {
+ return this.toArray().length;
+ }
+
+ function inspect() {
+ return '#<Enumerable:' + this.toArray().inspect() + '>';
+ }
+
+
+
+
+
+
+
+
+
+ return {
+ each: each,
+ eachSlice: eachSlice,
+ all: all,
+ every: all,
+ any: any,
+ some: any,
+ collect: collect,
+ map: collect,
+ detect: detect,
+ findAll: findAll,
+ select: findAll,
+ filter: findAll,
+ grep: grep,
+ include: include,
+ member: include,
+ inGroupsOf: inGroupsOf,
+ inject: inject,
+ invoke: invoke,
+ max: max,
+ min: min,
+ partition: partition,
+ pluck: pluck,
+ reject: reject,
+ sortBy: sortBy,
+ toArray: toArray,
+ entries: toArray,
+ zip: zip,
+ size: size,
+ inspect: inspect,
+ find: detect
+ };
+})();
+function $A(iterable) {
+ if (!iterable) return [];
+ if ('toArray' in Object(iterable)) return iterable.toArray();
+ var length = iterable.length || 0, results = new Array(length);
+ while (length--) results[length] = iterable[length];
+ return results;
+}
+
+function $w(string) {
+ if (!Object.isString(string)) return [];
+ string = string.strip();
+ return string ? string.split(/\s+/) : [];
+}
+
+Array.from = $A;
+
+
+(function() {
+ var arrayProto = Array.prototype,
+ slice = arrayProto.slice,
+ _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available
+
+ function each(iterator) {
+ for (var i = 0, length = this.length; i < length; i++)
+ iterator(this[i]);
+ }
+ if (!_each) _each = each;
+
+ function clear() {
+ this.length = 0;
+ return this;
+ }
+
+ function first() {
+ return this[0];
+ }
+
+ function last() {
+ return this[this.length - 1];
+ }
+
+ function compact() {
+ return this.select(function(value) {
+ return value != null;
+ });
+ }
+
+ function flatten() {
+ return this.inject([], function(array, value) {
+ if (Object.isArray(value))
+ return array.concat(value.flatten());
+ array.push(value);
+ return array;
+ });
+ }
+
+ function without() {
+ var values = slice.call(arguments, 0);
+ return this.select(function(value) {
+ return !values.include(value);
+ });
+ }
+
+ function reverse(inline) {
+ return (inline !== false ? this : this.toArray())._reverse();
+ }
+
+ function uniq(sorted) {
+ return this.inject([], function(array, value, index) {
+ if (0 == index || (sorted ? array.last() != value : !array.include(value)))
+ array.push(value);
+ return array;
+ });
+ }
+
+ function intersect(array) {
+ return this.uniq().findAll(function(item) {
+ return array.detect(function(value) { return item === value });
+ });
+ }
+
+
+ function clone() {
+ return slice.call(this, 0);
+ }
+
+ function size() {
+ return this.length;
+ }
+
+ function inspect() {
+ return '[' + this.map(Object.inspect).join(', ') + ']';
+ }
+
+ function toJSON() {
+ var results = [];
+ this.each(function(object) {
+ var value = Object.toJSON(object);
+ if (!Object.isUndefined(value)) results.push(value);
+ });
+ return '[' + results.join(', ') + ']';
+ }
+
+ function indexOf(item, i) {
+ i || (i = 0);
+ var length = this.length;
+ if (i < 0) i = length + i;
+ for (; i < length; i++)
+ if (this[i] === item) return i;
+ return -1;
+ }
+
+ function lastIndexOf(item, i) {
+ i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
+ var n = this.slice(0, i).reverse().indexOf(item);
+ return (n < 0) ? n : i - n - 1;
+ }
+
+ function concat() {
+ var array = slice.call(this, 0), item;
+ for (var i = 0, length = arguments.length; i < length; i++) {
+ item = arguments[i];
+ if (Object.isArray(item) && !('callee' in item)) {
+ for (var j = 0, arrayLength = item.length; j < arrayLength; j++)
+ array.push(item[j]);
+ } else {
+ array.push(item);
+ }
+ }
+ return array;
+ }
+
+ Object.extend(arrayProto, Enumerable);
+
+ if (!arrayProto._reverse)
+ arrayProto._reverse = arrayProto.reverse;
+
+ Object.extend(arrayProto, {
+ _each: _each,
+ clear: clear,
+ first: first,
+ last: last,
+ compact: compact,
+ flatten: flatten,
+ without: without,
+ reverse: reverse,
+ uniq: uniq,
+ intersect: intersect,
+ clone: clone,
+ toArray: clone,
+ size: size,
+ inspect: inspect,
+ toJSON: toJSON
+ });
+
+ var CONCAT_ARGUMENTS_BUGGY = (function() {
+ return [].concat(arguments)[0][0] !== 1;
+ })(1,2)
+
+ if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat;
+
+ if (!arrayProto.indexOf) arrayProto.indexOf = indexOf;
+ if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf;
+})();
+function $H(object) {
+ return new Hash(object);
+};
+
+var Hash = Class.create(Enumerable, (function() {
+ function initialize(object) {
+ this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
+ }
+
+ function _each(iterator) {
+ for (var key in this._object) {
+ var value = this._object[key], pair = [key, value];
+ pair.key = key;
+ pair.value = value;
+ iterator(pair);
+ }
+ }
+
+ function set(key, value) {
+ return this._object[key] = value;
+ }
+
+ function get(key) {
+ if (this._object[key] !== Object.prototype[key])
+ return this._object[key];
+ }
+
+ function unset(key) {
+ var value = this._object[key];
+ delete this._object[key];
+ return value;
+ }
+
+ function toObject() {
+ return Object.clone(this._object);
+ }
+
+ function keys() {
+ return this.pluck('key');
+ }
+
+ function values() {
+ return this.pluck('value');
+ }
+
+ function index(value) {
+ var match = this.detect(function(pair) {
+ return pair.value === value;
+ });
+ return match && match.key;
+ }
+
+ function merge(object) {
+ return this.clone().update(object);
+ }
+
+ function update(object) {
+ return new Hash(object).inject(this, function(result, pair) {
+ result.set(pair.key, pair.value);
+ return result;
+ });
+ }
+
+ function toQueryPair(key, value) {
+ if (Object.isUndefined(value)) return key;
+ return key + '=' + encodeURIComponent(String.interpret(value));
+ }
+
+ function toQueryString() {
+ return this.inject([], function(results, pair) {
+ var key = encodeURIComponent(pair.key), values = pair.value;
+
+ if (values && typeof values == 'object') {
+ if (Object.isArray(values))
+ return results.concat(values.map(toQueryPair.curry(key)));
+ } else results.push(toQueryPair(key, values));
+ return results;
+ }).join('&');
+ }
+
+ function inspect() {
+ return '#<Hash:{' + this.map(function(pair) {
+ return pair.map(Object.inspect).join(': ');
+ }).join(', ') + '}>';
+ }
+
+ function toJSON() {
+ return Object.toJSON(this.toObject());
+ }
+
+ function clone() {
+ return new Hash(this);
+ }
+
+ return {
+ initialize: initialize,
+ _each: _each,
+ set: set,
+ get: get,
+ unset: unset,
+ toObject: toObject,
+ toTemplateReplacements: toObject,
+ keys: keys,
+ values: values,
+ index: index,
+ merge: merge,
+ update: update,
+ toQueryString: toQueryString,
+ inspect: inspect,
+ toJSON: toJSON,
+ clone: clone
+ };
+})());
+
+Hash.from = $H;
+Object.extend(Number.prototype, (function() {
+ function toColorPart() {
+ return this.toPaddedString(2, 16);
+ }
+
+ function succ() {
+ return this + 1;
+ }
+
+ function times(iterator, context) {
+ $R(0, this, true).each(iterator, context);
+ return this;
+ }
+
+ function toPaddedString(length, radix) {
+ var string = this.toString(radix || 10);
+ return '0'.times(length - string.length) + string;
+ }
+
+ function toJSON() {
+ return isFinite(this) ? this.toString() : 'null';
+ }
+
+ function abs() {
+ return Math.abs(this);
+ }
+
+ function round() {
+ return Math.round(this);
+ }
+
+ function ceil() {
+ return Math.ceil(this);
+ }
+
+ function floor() {
+ return Math.floor(this);
+ }
+
+ return {
+ toColorPart: toColorPart,
+ succ: succ,
+ times: times,
+ toPaddedString: toPaddedString,
+ toJSON: toJSON,
+ abs: abs,
+ round: round,
+ ceil: ceil,
+ floor: floor
+ };
+})());
+
+function $R(start, end, exclusive) {
+ return new ObjectRange(start, end, exclusive);
+}
+
+var ObjectRange = Class.create(Enumerable, (function() {
+ function initialize(start, end, exclusive) {
+ this.start = start;
+ this.end = end;
+ this.exclusive = exclusive;
+ }
+
+ function _each(iterator) {
+ var value = this.start;
+ while (this.include(value)) {
+ iterator(value);
+ value = value.succ();
+ }
+ }
+
+ function include(value) {
+ if (value < this.start)
+ return false;
+ if (this.exclusive)
+ return value < this.end;
+ return value <= this.end;
+ }
+
+ return {
+ initialize: initialize,
+ _each: _each,
+ include: include
+ };
+})());
+
+
+
+var Ajax = {
+ getTransport: function() {
+ return Try.these(
+ function() {return new XMLHttpRequest()},
+ function() {return new ActiveXObject('Msxml2.XMLHTTP')},
+ function() {return new ActiveXObject('Microsoft.XMLHTTP')}
+ ) || false;
+ },
+
+ activeRequestCount: 0
+};
+
+Ajax.Responders = {
+ responders: [],
+
+ _each: function(iterator) {
+ this.responders._each(iterator);
+ },
+
+ register: function(responder) {
+ if (!this.include(responder))
+ this.responders.push(responder);
+ },
+
+ unregister: function(responder) {
+ this.responders = this.responders.without(responder);
+ },
+
+ dispatch: function(callback, request, transport, json) {
+ this.each(function(responder) {
+ if (Object.isFunction(responder[callback])) {
+ try {
+ responder[callback].apply(responder, [request, transport, json]);
+ } catch (e) { }
+ }
+ });
+ }
+};
+
+Object.extend(Ajax.Responders, Enumerable);
+
+Ajax.Responders.register({
+ onCreate: function() { Ajax.activeRequestCount++ },
+ onComplete: function() { Ajax.activeRequestCount-- }
+});
+Ajax.Base = Class.create({
+ initialize: function(options) {
+ this.options = {
+ method: 'post',
+ asynchronous: true,
+ contentType: 'application/x-www-form-urlencoded',
+ encoding: 'UTF-8',
+ parameters: '',
+ evalJSON: true,
+ evalJS: true
+ };
+ Object.extend(this.options, options || { });
+
+ this.options.method = this.options.method.toLowerCase();
+
+ if (Object.isString(this.options.parameters))
+ this.options.parameters = this.options.parameters.toQueryParams();
+ else if (Object.isHash(this.options.parameters))
+ this.options.parameters = this.options.parameters.toObject();
+ }
+});
+Ajax.Request = Class.create(Ajax.Base, {
+ _complete: false,
+
+ initialize: function($super, url, options) {
+ $super(options);
+ this.transport = Ajax.getTransport();
+ this.request(url);
+ },
+
+ request: function(url) {
+ this.url = url;
+ this.method = this.options.method;
+ var params = Object.clone(this.options.parameters);
+
+ if (!['get', 'post'].include(this.method)) {
+ params['_method'] = this.method;
+ this.method = 'post';
+ }
+
+ this.parameters = params;
+
+ if (params = Object.toQueryString(params)) {
+ if (this.method == 'get')
+ this.url += (this.url.include('?') ? '&' : '?') + params;
+ else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
+ params += '&_=';
+ }
+
+ try {
+ var response = new Ajax.Response(this);
+ if (this.options.onCreate) this.options.onCreate(response);
+ Ajax.Responders.dispatch('onCreate', this, response);
+
+ this.transport.open(this.method.toUpperCase(), this.url,
+ this.options.asynchronous);
+
+ if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
+
+ this.transport.onreadystatechange = this.onStateChange.bind(this);
+ this.setRequestHeaders();
+
+ this.body = this.method == 'post' ? (this.options.postBody || params) : null;
+ this.transport.send(this.body);
+
+ /* Force Firefox to handle ready state 4 for synchronous requests */
+ if (!this.options.asynchronous && this.transport.overrideMimeType)
+ this.onStateChange();
+
+ }
+ catch (e) {
+ this.dispatchException(e);
+ }
+ },
+
+ onStateChange: function() {
+ var readyState = this.transport.readyState;
+ if (readyState > 1 && !((readyState == 4) && this._complete))
+ this.respondToReadyState(this.transport.readyState);
+ },
+
+ setRequestHeaders: function() {
+ var headers = {
+ 'X-Requested-With': 'XMLHttpRequest',
+ 'X-Prototype-Version': Prototype.Version,
+ 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
+ };
+
+ if (this.method == 'post') {
+ headers['Content-type'] = this.options.contentType +
+ (this.options.encoding ? '; charset=' + this.options.encoding : '');
+
+ /* Force "Connection: close" for older Mozilla browsers to work
+ * around a bug where XMLHttpRequest sends an incorrect
+ * Content-length header. See Mozilla Bugzilla #246651.
+ */
+ if (this.transport.overrideMimeType &&
+ (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
+ headers['Connection'] = 'close';
+ }
+
+ if (typeof this.options.requestHeaders == 'object') {
+ var extras = this.options.requestHeaders;
+
+ if (Object.isFunction(extras.push))
+ for (var i = 0, length = extras.length; i < length; i += 2)
+ headers[extras[i]] = extras[i+1];
+ else
+ $H(extras).each(function(pair) { headers[pair.key] = pair.value });
+ }
+
+ for (var name in headers)
+ this.transport.setRequestHeader(name, headers[name]);
+ },
+
+ success: function() {
+ var status = this.getStatus();
+ return !status || (status >= 200 && status < 300);
+ },
+
+ getStatus: function() {
+ try {
+ return this.transport.status || 0;
+ } catch (e) { return 0 }
+ },
+
+ respondToReadyState: function(readyState) {
+ var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
+
+ if (state == 'Complete') {
+ try {
+ this._complete = true;
+ (this.options['on' + response.status]
+ || this.options['on' + (this.success() ? 'Success' : 'Failure')]
+ || Prototype.emptyFunction)(response, response.headerJSON);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+
+ var contentType = response.getHeader('Content-type');
+ if (this.options.evalJS == 'force'
+ || (this.options.evalJS && this.isSameOrigin() && contentType
+ && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
+ this.evalResponse();
+ }
+
+ try {
+ (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
+ Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+
+ if (state == 'Complete') {
+ this.transport.onreadystatechange = Prototype.emptyFunction;
+ }
+ },
+
+ isSameOrigin: function() {
+ var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
+ return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
+ protocol: location.protocol,
+ domain: document.domain,
+ port: location.port ? ':' + location.port : ''
+ }));
+ },
+
+ getHeader: function(name) {
+ try {
+ return this.transport.getResponseHeader(name) || null;
+ } catch (e) { return null; }
+ },
+
+ evalResponse: function() {
+ try {
+ return eval((this.transport.responseText || '').unfilterJSON());
+ } catch (e) {
+ this.dispatchException(e);
+ }
+ },
+
+ dispatchException: function(exception) {
+ (this.options.onException || Prototype.emptyFunction)(this, exception);
+ Ajax.Responders.dispatch('onException', this, exception);
+ }
+});
+
+Ajax.Request.Events =
+ ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
+
+
+
+
+
+
+
+
+Ajax.Response = Class.create({
+ initialize: function(request){
+ this.request = request;
+ var transport = this.transport = request.transport,
+ readyState = this.readyState = transport.readyState;
+
+ if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
+ this.status = this.getStatus();
+ this.statusText = this.getStatusText();
+ this.responseText = String.interpret(transport.responseText);
+ this.headerJSON = this._getHeaderJSON();
+ }
+
+ if(readyState == 4) {
+ var xml = transport.responseXML;
+ this.responseXML = Object.isUndefined(xml) ? null : xml;
+ this.responseJSON = this._getResponseJSON();
+ }
+ },
+
+ status: 0,
+
+ statusText: '',
+
+ getStatus: Ajax.Request.prototype.getStatus,
+
+ getStatusText: function() {
+ try {
+ return this.transport.statusText || '';
+ } catch (e) { return '' }
+ },
+
+ getHeader: Ajax.Request.prototype.getHeader,
+
+ getAllHeaders: function() {
+ try {
+ return this.getAllResponseHeaders();
+ } catch (e) { return null }
+ },
+
+ getResponseHeader: function(name) {
+ return this.transport.getResponseHeader(name);
+ },
+
+ getAllResponseHeaders: function() {
+ return this.transport.getAllResponseHeaders();
+ },
+
+ _getHeaderJSON: function() {
+ var json = this.getHeader('X-JSON');
+ if (!json) return null;
+ json = decodeURIComponent(escape(json));
+ try {
+ return json.evalJSON(this.request.options.sanitizeJSON ||
+ !this.request.isSameOrigin());
+ } catch (e) {
+ this.request.dispatchException(e);
+ }
+ },
+
+ _getResponseJSON: function() {
+ var options = this.request.options;
+ if (!options.evalJSON || (options.evalJSON != 'force' &&
+ !(this.getHeader('Content-type') || '').include('application/json')) ||
+ this.responseText.blank())
+ return null;
+ try {
+ return this.responseText.evalJSON(options.sanitizeJSON ||
+ !this.request.isSameOrigin());
+ } catch (e) {
+ this.request.dispatchException(e);
+ }
+ }
+});
+
+Ajax.Updater = Class.create(Ajax.Request, {
+ initialize: function($super, container, url, options) {
+ this.container = {
+ success: (container.success || container),
+ failure: (container.failure || (container.success ? null : container))
+ };
+
+ options = Object.clone(options);
+ var onComplete = options.onComplete;
+ options.onComplete = (function(response, json) {
+ this.updateContent(response.responseText);
+ if (Object.isFunction(onComplete)) onComplete(response, json);
+ }).bind(this);
+
+ $super(url, options);
+ },
+
+ updateContent: function(responseText) {
+ var receiver = this.container[this.success() ? 'success' : 'failure'],
+ options = this.options;
+
+ if (!options.evalScripts) responseText = responseText.stripScripts();
+
+ if (receiver = $$(receiver)) {
+ if (options.insertion) {
+ if (Object.isString(options.insertion)) {
+ var insertion = { }; insertion[options.insertion] = responseText;
+ receiver.insert(insertion);
+ }
+ else options.insertion(receiver, responseText);
+ }
+ else receiver.update(responseText);
+ }
+ }
+});
+
+Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
+ initialize: function($super, container, url, options) {
+ $super(options);
+ this.onComplete = this.options.onComplete;
+
+ this.frequency = (this.options.frequency || 2);
+ this.decay = (this.options.decay || 1);
+
+ this.updater = { };
+ this.container = container;
+ this.url = url;
+
+ this.start();
+ },
+
+ start: function() {
+ this.options.onComplete = this.updateComplete.bind(this);
+ this.onTimerEvent();
+ },
+
+ stop: function() {
+ this.updater.options.onComplete = undefined;
+ clearTimeout(this.timer);
+ (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
+ },
+
+ updateComplete: function(response) {
+ if (this.options.decay) {
+ this.decay = (response.responseText == this.lastText ?
+ this.decay * this.options.decay : 1);
+
+ this.lastText = response.responseText;
+ }
+ this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
+ },
+
+ onTimerEvent: function() {
+ this.updater = new Ajax.Updater(this.container, this.url, this.options);
+ }
+});
+
+
+
+function $$(element) {
+ if (arguments.length > 1) {
+ for (var i = 0, elements = [], length = arguments.length; i < length; i++)
+ elements.push($$(arguments[i]));
+ return elements;
+ }
+ if (Object.isString(element))
+ element = document.getElementById(element);
+ return Element.extend(element);
+}
+
+if (Prototype.BrowserFeatures.XPath) {
+ document._getElementsByXPath = function(expression, parentElement) {
+ var results = [];
+ var query = document.evaluate(expression, $$(parentElement) || document,
+ null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+ for (var i = 0, length = query.snapshotLength; i < length; i++)
+ results.push(Element.extend(query.snapshotItem(i)));
+ return results;
+ };
+}
+
+/*--------------------------------------------------------------------------*/
+
+if (!window.Node) var Node = { };
+
+if (!Node.ELEMENT_NODE) {
+ Object.extend(Node, {
+ ELEMENT_NODE: 1,
+ ATTRIBUTE_NODE: 2,
+ TEXT_NODE: 3,
+ CDATA_SECTION_NODE: 4,
+ ENTITY_REFERENCE_NODE: 5,
+ ENTITY_NODE: 6,
+ PROCESSING_INSTRUCTION_NODE: 7,
+ COMMENT_NODE: 8,
+ DOCUMENT_NODE: 9,
+ DOCUMENT_TYPE_NODE: 10,
+ DOCUMENT_FRAGMENT_NODE: 11,
+ NOTATION_NODE: 12
+ });
+}
+
+
+(function(global) {
+
+ var SETATTRIBUTE_IGNORES_NAME = (function(){
+ var elForm = document.createElement("form");
+ var elInput = document.createElement("input");
+ var root = document.documentElement;
+ elInput.setAttribute("name", "test");
+ elForm.appendChild(elInput);
+ root.appendChild(elForm);
+ var isBuggy = elForm.elements
+ ? (typeof elForm.elements.test == "undefined")
+ : null;
+ root.removeChild(elForm);
+ elForm = elInput = null;
+ return isBuggy;
+ })();
+
+ var element = global.Element;
+ global.Element = function(tagName, attributes) {
+ attributes = attributes || { };
+ tagName = tagName.toLowerCase();
+ var cache = Element.cache;
+ if (SETATTRIBUTE_IGNORES_NAME && attributes.name) {
+ tagName = '<' + tagName + ' name="' + attributes.name + '">';
+ delete attributes.name;
+ return Element.writeAttribute(document.createElement(tagName), attributes);
+ }
+ if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
+ return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
+ };
+ Object.extend(global.Element, element || { });
+ if (element) global.Element.prototype = element.prototype;
+})(this);
+
+Element.cache = { };
+Element.idCounter = 1;
+
+Element.Methods = {
+ visible: function(element) {
+ return $$(element).style.display != 'none';
+ },
+
+ toggle: function(element) {
+ element = $$(element);
+ Element[Element.visible(element) ? 'hide' : 'show'](element);
+ return element;
+ },
+
+
+ hide: function(element) {
+ element = $$(element);
+ element.style.display = 'none';
+ return element;
+ },
+
+ show: function(element) {
+ element = $$(element);
+ element.style.display = '';
+ return element;
+ },
+
+ remove: function(element) {
+ element = $$(element);
+ element.parentNode.removeChild(element);
+ return element;
+ },
+
+ update: (function(){
+
+ var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){
+ var el = document.createElement("select"),
+ isBuggy = true;
+ el.innerHTML = "<option value=\"test\">test</option>";
+ if (el.options && el.options[0]) {
+ isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION";
+ }
+ el = null;
+ return isBuggy;
+ })();
+
+ var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){
+ try {
+ var el = document.createElement("table");
+ if (el && el.tBodies) {
+ el.innerHTML = "<tbody><tr><td>test</td></tr></tbody>";
+ var isBuggy = typeof el.tBodies[0] == "undefined";
+ el = null;
+ return isBuggy;
+ }
+ } catch (e) {
+ return true;
+ }
+ })();
+
+ var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () {
+ var s = document.createElement("script"),
+ isBuggy = false;
+ try {
+ s.appendChild(document.createTextNode(""));
+ isBuggy = !s.firstChild ||
+ s.firstChild && s.firstChild.nodeType !== 3;
+ } catch (e) {
+ isBuggy = true;
+ }
+ s = null;
+ return isBuggy;
+ })();
+
+ function update(element, content) {
+ element = $$(element);
+
+ if (content && content.toElement)
+ content = content.toElement();
+
+ if (Object.isElement(content))
+ return element.update().insert(content);
+
+ content = Object.toHTML(content);
+
+ var tagName = element.tagName.toUpperCase();
+
+ if (tagName === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) {
+ element.text = content;
+ return element;
+ }
+
+ if (SELECT_ELEMENT_INNERHTML_BUGGY || TABLE_ELEMENT_INNERHTML_BUGGY) {
+ if (tagName in Element._insertionTranslations.tags) {
+ while (element.firstChild) {
+ element.removeChild(element.firstChild);
+ }
+ Element._getContentFromAnonymousElement(tagName, content.stripScripts())
+ .each(function(node) {
+ element.appendChild(node)
+ });
+ }
+ else {
+ element.innerHTML = content.stripScripts();
+ }
+ }
+ else {
+ element.innerHTML = content.stripScripts();
+ }
+
+ content.evalScripts.bind(content).defer();
+ return element;
+ }
+
+ return update;
+ })(),
+
+ replace: function(element, content) {
+ element = $$(element);
+ if (content && content.toElement) content = content.toElement();
+ else if (!Object.isElement(content)) {
+ content = Object.toHTML(content);
+ var range = element.ownerDocument.createRange();
+ range.selectNode(element);
+ content.evalScripts.bind(content).defer();
+ content = range.createContextualFragment(content.stripScripts());
+ }
+ element.parentNode.replaceChild(content, element);
+ return element;
+ },
+
+ insert: function(element, insertions) {
+ element = $$(element);
+
+ if (Object.isString(insertions) || Object.isNumber(insertions) ||
+ Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
+ insertions = {bottom:insertions};
+
+ var content, insert, tagName, childNodes;
+
+ for (var position in insertions) {
+ content = insertions[position];
+ position = position.toLowerCase();
+ insert = Element._insertionTranslations[position];
+
+ if (content && content.toElement) content = content.toElement();
+ if (Object.isElement(content)) {
+ insert(element, content);
+ continue;
+ }
+
+ content = Object.toHTML(content);
+
+ tagName = ((position == 'before' || position == 'after')
+ ? element.parentNode : element).tagName.toUpperCase();
+
+ childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
+
+ if (position == 'top' || position == 'after') childNodes.reverse();
+ childNodes.each(insert.curry(element));
+
+ content.evalScripts.bind(content).defer();
+ }
+
+ return element;
+ },
+
+ wrap: function(element, wrapper, attributes) {
+ element = $$(element);
+ if (Object.isElement(wrapper))
+ $$(wrapper).writeAttribute(attributes || { });
+ else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
+ else wrapper = new Element('div', wrapper);
+ if (element.parentNode)
+ element.parentNode.replaceChild(wrapper, element);
+ wrapper.appendChild(element);
+ return wrapper;
+ },
+
+ inspect: function(element) {
+ element = $$(element);
+ var result = '<' + element.tagName.toLowerCase();
+ $H({'id': 'id', 'className': 'class'}).each(function(pair) {
+ var property = pair.first(), attribute = pair.last();
+ var value = (element[property] || '').toString();
+ if (value) result += ' ' + attribute + '=' + value.inspect(true);
+ });
+ return result + '>';
+ },
+
+ recursivelyCollect: function(element, property) {
+ element = $$(element);
+ var elements = [];
+ while (element = element[property])
+ if (element.nodeType == 1)
+ elements.push(Element.extend(element));
+ return elements;
+ },
+
+ ancestors: function(element) {
+ return Element.recursivelyCollect(element, 'parentNode');
+ },
+
+ descendants: function(element) {
+ return Element.select(element, "*");
+ },
+
+ firstDescendant: function(element) {
+ element = $$(element).firstChild;
+ while (element && element.nodeType != 1) element = element.nextSibling;
+ return $$(element);
+ },
+
+ immediateDescendants: function(element) {
+ if (!(element = $$(element).firstChild)) return [];
+ while (element && element.nodeType != 1) element = element.nextSibling;
+ if (element) return [element].concat($$(element).nextSiblings());
+ return [];
+ },
+
+ previousSiblings: function(element) {
+ return Element.recursivelyCollect(element, 'previousSibling');
+ },
+
+ nextSiblings: function(element) {
+ return Element.recursivelyCollect(element, 'nextSibling');
+ },
+
+ siblings: function(element) {
+ element = $$(element);
+ return Element.previousSiblings(element).reverse()
+ .concat(Element.nextSiblings(element));
+ },
+
+ match: function(element, selector) {
+ if (Object.isString(selector))
+ selector = new Selector(selector);
+ return selector.match($$(element));
+ },
+
+ up: function(element, expression, index) {
+ element = $$(element);
+ if (arguments.length == 1) return $$(element.parentNode);
+ var ancestors = Element.ancestors(element);
+ return Object.isNumber(expression) ? ancestors[expression] :
+ Selector.findElement(ancestors, expression, index);
+ },
+
+ down: function(element, expression, index) {
+ element = $$(element);
+ if (arguments.length == 1) return Element.firstDescendant(element);
+ return Object.isNumber(expression) ? Element.descendants(element)[expression] :
+ Element.select(element, expression)[index || 0];
+ },
+
+ previous: function(element, expression, index) {
+ element = $$(element);
+ if (arguments.length == 1) return $$(Selector.handlers.previousElementSibling(element));
+ var previousSiblings = Element.previousSiblings(element);
+ return Object.isNumber(expression) ? previousSiblings[expression] :
+ Selector.findElement(previousSiblings, expression, index);
+ },
+
+ next: function(element, expression, index) {
+ element = $$(element);
+ if (arguments.length == 1) return $$(Selector.handlers.nextElementSibling(element));
+ var nextSiblings = Element.nextSiblings(element);
+ return Object.isNumber(expression) ? nextSiblings[expression] :
+ Selector.findElement(nextSiblings, expression, index);
+ },
+
+
+ select: function(element) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return Selector.findChildElements(element, args);
+ },
+
+ adjacent: function(element) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return Selector.findChildElements(element.parentNode, args).without(element);
+ },
+
+ identify: function(element) {
+ element = $$(element);
+ var id = Element.readAttribute(element, 'id');
+ if (id) return id;
+ do { id = 'anonymous_element_' + Element.idCounter++ } while ($$(id));
+ Element.writeAttribute(element, 'id', id);
+ return id;
+ },
+
+ readAttribute: function(element, name) {
+ element = $$(element);
+ if (Prototype.Browser.IE) {
+ var t = Element._attributeTranslations.read;
+ if (t.values[name]) return t.values[name](element, name);
+ if (t.names[name]) name = t.names[name];
+ if (name.include(':')) {
+ return (!element.attributes || !element.attributes[name]) ? null :
+ element.attributes[name].value;
+ }
+ }
+ return element.getAttribute(name);
+ },
+
+ writeAttribute: function(element, name, value) {
+ element = $$(element);
+ var attributes = { }, t = Element._attributeTranslations.write;
+
+ if (typeof name == 'object') attributes = name;
+ else attributes[name] = Object.isUndefined(value) ? true : value;
+
+ for (var attr in attributes) {
+ name = t.names[attr] || attr;
+ value = attributes[attr];
+ if (t.values[attr]) name = t.values[attr](element, value);
+ if (value === false || value === null)
+ element.removeAttribute(name);
+ else if (value === true)
+ element.setAttribute(name, name);
+ else element.setAttribute(name, value);
+ }
+ return element;
+ },
+
+ getHeight: function(element) {
+ return Element.getDimensions(element).height;
+ },
+
+ getWidth: function(element) {
+ return Element.getDimensions(element).width;
+ },
+
+ classNames: function(element) {
+ return new Element.ClassNames(element);
+ },
+
+ hasClassName: function(element, className) {
+ if (!(element = $$(element))) return;
+ var elementClassName = element.className;
+ return (elementClassName.length > 0 && (elementClassName == className ||
+ new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
+ },
+
+ addClassName: function(element, className) {
+ if (!(element = $$(element))) return;
+ if (!Element.hasClassName(element, className))
+ element.className += (element.className ? ' ' : '') + className;
+ return element;
+ },
+
+ removeClassName: function(element, className) {
+ if (!(element = $$(element))) return;
+ element.className = element.className.replace(
+ new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
+ return element;
+ },
+
+ toggleClassName: function(element, className) {
+ if (!(element = $$(element))) return;
+ return Element[Element.hasClassName(element, className) ?
+ 'removeClassName' : 'addClassName'](element, className);
+ },
+
+ cleanWhitespace: function(element) {
+ element = $$(element);
+ var node = element.firstChild;
+ while (node) {
+ var nextNode = node.nextSibling;
+ if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
+ element.removeChild(node);
+ node = nextNode;
+ }
+ return element;
+ },
+
+ empty: function(element) {
+ return $$(element).innerHTML.blank();
+ },
+
+ descendantOf: function(element, ancestor) {
+ element = $$(element), ancestor = $$(ancestor);
+
+ if (element.compareDocumentPosition)
+ return (element.compareDocumentPosition(ancestor) & 8) === 8;
+
+ if (ancestor.contains)
+ return ancestor.contains(element) && ancestor !== element;
+
+ while (element = element.parentNode)
+ if (element == ancestor) return true;
+
+ return false;
+ },
+
+ scrollTo: function(element) {
+ element = $$(element);
+ var pos = Element.cumulativeOffset(element);
+ window.scrollTo(pos[0], pos[1]);
+ return element;
+ },
+
+ getStyle: function(element, style) {
+ element = $$(element);
+ style = style == 'float' ? 'cssFloat' : style.camelize();
+ var value = element.style[style];
+ if (!value || value == 'auto') {
+ var css = document.defaultView.getComputedStyle(element, null);
+ value = css ? css[style] : null;
+ }
+ if (style == 'opacity') return value ? parseFloat(value) : 1.0;
+ return value == 'auto' ? null : value;
+ },
+
+ getOpacity: function(element) {
+ return $$(element).getStyle('opacity');
+ },
+
+ setStyle: function(element, styles) {
+ element = $$(element);
+ var elementStyle = element.style, match;
+ if (Object.isString(styles)) {
+ element.style.cssText += ';' + styles;
+ return styles.include('opacity') ?
+ element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
+ }
+ for (var property in styles)
+ if (property == 'opacity') element.setOpacity(styles[property]);
+ else
+ elementStyle[(property == 'float' || property == 'cssFloat') ?
+ (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
+ property] = styles[property];
+
+ return element;
+ },
+
+ setOpacity: function(element, value) {
+ element = $$(element);
+ element.style.opacity = (value == 1 || value === '') ? '' :
+ (value < 0.00001) ? 0 : value;
+ return element;
+ },
+
+ getDimensions: function(element) {
+ element = $$(element);
+ var display = Element.getStyle(element, 'display');
+ if (display != 'none' && display != null) // Safari bug
+ return {width: element.offsetWidth, height: element.offsetHeight};
+
+ var els = element.style;
+ var originalVisibility = els.visibility;
+ var originalPosition = els.position;
+ var originalDisplay = els.display;
+ els.visibility = 'hidden';
+ if (originalPosition != 'fixed') // Switching fixed to absolute causes issues in Safari
+ els.position = 'absolute';
+ els.display = 'block';
+ var originalWidth = element.clientWidth;
+ var originalHeight = element.clientHeight;
+ els.display = originalDisplay;
+ els.position = originalPosition;
+ els.visibility = originalVisibility;
+ return {width: originalWidth, height: originalHeight};
+ },
+
+ makePositioned: function(element) {
+ element = $$(element);
+ var pos = Element.getStyle(element, 'position');
+ if (pos == 'static' || !pos) {
+ element._madePositioned = true;
+ element.style.position = 'relative';
+ if (Prototype.Browser.Opera) {
+ element.style.top = 0;
+ element.style.left = 0;
+ }
+ }
+ return element;
+ },
+
+ undoPositioned: function(element) {
+ element = $$(element);
+ if (element._madePositioned) {
+ element._madePositioned = undefined;
+ element.style.position =
+ element.style.top =
+ element.style.left =
+ element.style.bottom =
+ element.style.right = '';
+ }
+ return element;
+ },
+
+ makeClipping: function(element) {
+ element = $$(element);
+ if (element._overflow) return element;
+ element._overflow = Element.getStyle(element, 'overflow') || 'auto';
+ if (element._overflow !== 'hidden')
+ element.style.overflow = 'hidden';
+ return element;
+ },
+
+ undoClipping: function(element) {
+ element = $$(element);
+ if (!element._overflow) return element;
+ element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
+ element._overflow = null;
+ return element;
+ },
+
+ cumulativeOffset: function(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ element = element.offsetParent;
+ } while (element);
+ return Element._returnOffset(valueL, valueT);
+ },
+
+ positionedOffset: function(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ element = element.offsetParent;
+ if (element) {
+ if (element.tagName.toUpperCase() == 'BODY') break;
+ var p = Element.getStyle(element, 'position');
+ if (p !== 'static') break;
+ }
+ } while (element);
+ return Element._returnOffset(valueL, valueT);
+ },
+
+ absolutize: function(element) {
+ element = $$(element);
+ if (Element.getStyle(element, 'position') == 'absolute') return element;
+
+ var offsets = Element.positionedOffset(element);
+ var top = offsets[1];
+ var left = offsets[0];
+ var width = element.clientWidth;
+ var height = element.clientHeight;
+
+ element._originalLeft = left - parseFloat(element.style.left || 0);
+ element._originalTop = top - parseFloat(element.style.top || 0);
+ element._originalWidth = element.style.width;
+ element._originalHeight = element.style.height;
+
+ element.style.position = 'absolute';
+ element.style.top = top + 'px';
+ element.style.left = left + 'px';
+ element.style.width = width + 'px';
+ element.style.height = height + 'px';
+ return element;
+ },
+
+ relativize: function(element) {
+ element = $$(element);
+ if (Element.getStyle(element, 'position') == 'relative') return element;
+
+ element.style.position = 'relative';
+ var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
+ var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
+
+ element.style.top = top + 'px';
+ element.style.left = left + 'px';
+ element.style.height = element._originalHeight;
+ element.style.width = element._originalWidth;
+ return element;
+ },
+
+ cumulativeScrollOffset: function(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.scrollTop || 0;
+ valueL += element.scrollLeft || 0;
+ element = element.parentNode;
+ } while (element);
+ return Element._returnOffset(valueL, valueT);
+ },
+
+ getOffsetParent: function(element) {
+ if (element.offsetParent) return $$(element.offsetParent);
+ if (element == document.body) return $$(element);
+
+ while ((element = element.parentNode) && element != document.body)
+ if (Element.getStyle(element, 'position') != 'static')
+ return $$(element);
+
+ return $$(document.body);
+ },
+
+ viewportOffset: function(forElement) {
+ var valueT = 0, valueL = 0;
+
+ var element = forElement;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+
+ if (element.offsetParent == document.body &&
+ Element.getStyle(element, 'position') == 'absolute') break;
+
+ } while (element = element.offsetParent);
+
+ element = forElement;
+ do {
+ if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) {
+ valueT -= element.scrollTop || 0;
+ valueL -= element.scrollLeft || 0;
+ }
+ } while (element = element.parentNode);
+
+ return Element._returnOffset(valueL, valueT);
+ },
+
+ clonePosition: function(element, source) {
+ var options = Object.extend({
+ setLeft: true,
+ setTop: true,
+ setWidth: true,
+ setHeight: true,
+ offsetTop: 0,
+ offsetLeft: 0
+ }, arguments[2] || { });
+
+ source = $$(source);
+ var p = Element.viewportOffset(source);
+
+ element = $$(element);
+ var delta = [0, 0];
+ var parent = null;
+ if (Element.getStyle(element, 'position') == 'absolute') {
+ parent = Element.getOffsetParent(element);
+ delta = Element.viewportOffset(parent);
+ }
+
+ if (parent == document.body) {
+ delta[0] -= document.body.offsetLeft;
+ delta[1] -= document.body.offsetTop;
+ }
+
+ if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
+ if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
+ if (options.setWidth) element.style.width = source.offsetWidth + 'px';
+ if (options.setHeight) element.style.height = source.offsetHeight + 'px';
+ return element;
+ }
+};
+
+Object.extend(Element.Methods, {
+ getElementsBySelector: Element.Methods.select,
+
+ childElements: Element.Methods.immediateDescendants
+});
+
+Element._attributeTranslations = {
+ write: {
+ names: {
+ className: 'class',
+ htmlFor: 'for'
+ },
+ values: { }
+ }
+};
+
+if (Prototype.Browser.Opera) {
+ Element.Methods.getStyle = Element.Methods.getStyle.wrap(
+ function(proceed, element, style) {
+ switch (style) {
+ case 'left': case 'top': case 'right': case 'bottom':
+ if (proceed(element, 'position') === 'static') return null;
+ case 'height': case 'width':
+ if (!Element.visible(element)) return null;
+
+ var dim = parseInt(proceed(element, style), 10);
+
+ if (dim !== element['offset' + style.capitalize()])
+ return dim + 'px';
+
+ var properties;
+ if (style === 'height') {
+ properties = ['border-top-width', 'padding-top',
+ 'padding-bottom', 'border-bottom-width'];
+ }
+ else {
+ properties = ['border-left-width', 'padding-left',
+ 'padding-right', 'border-right-width'];
+ }
+ return properties.inject(dim, function(memo, property) {
+ var val = proceed(element, property);
+ return val === null ? memo : memo - parseInt(val, 10);
+ }) + 'px';
+ default: return proceed(element, style);
+ }
+ }
+ );
+
+ Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
+ function(proceed, element, attribute) {
+ if (attribute === 'title') return element.title;
+ return proceed(element, attribute);
+ }
+ );
+}
+
+else if (Prototype.Browser.IE) {
+ Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
+ function(proceed, element) {
+ element = $$(element);
+ try { element.offsetParent }
+ catch(e) { return $$(document.body) }
+ var position = element.getStyle('position');
+ if (position !== 'static') return proceed(element);
+ element.setStyle({ position: 'relative' });
+ var value = proceed(element);
+ element.setStyle({ position: position });
+ return value;
+ }
+ );
+
+ $w('positionedOffset viewportOffset').each(function(method) {
+ Element.Methods[method] = Element.Methods[method].wrap(
+ function(proceed, element) {
+ element = $$(element);
+ try { element.offsetParent }
+ catch(e) { return Element._returnOffset(0,0) }
+ var position = element.getStyle('position');
+ if (position !== 'static') return proceed(element);
+ var offsetParent = element.getOffsetParent();
+ if (offsetParent && offsetParent.getStyle('position') === 'fixed')
+ offsetParent.setStyle({ zoom: 1 });
+ element.setStyle({ position: 'relative' });
+ var value = proceed(element);
+ element.setStyle({ position: position });
+ return value;
+ }
+ );
+ });
+
+ Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap(
+ function(proceed, element) {
+ try { element.offsetParent }
+ catch(e) { return Element._returnOffset(0,0) }
+ return proceed(element);
+ }
+ );
+
+ Element.Methods.getStyle = function(element, style) {
+ element = $$(element);
+ style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
+ var value = element.style[style];
+ if (!value && element.currentStyle) value = element.currentStyle[style];
+
+ if (style == 'opacity') {
+ if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
+ if (value[1]) return parseFloat(value[1]) / 100;
+ return 1.0;
+ }
+
+ if (value == 'auto') {
+ if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
+ return element['offset' + style.capitalize()] + 'px';
+ return null;
+ }
+ return value;
+ };
+
+ Element.Methods.setOpacity = function(element, value) {
+ function stripAlpha(filter){
+ return filter.replace(/alpha\([^\)]*\)/gi,'');
+ }
+ element = $$(element);
+ var currentStyle = element.currentStyle;
+ if ((currentStyle && !currentStyle.hasLayout) ||
+ (!currentStyle && element.style.zoom == 'normal'))
+ element.style.zoom = 1;
+
+ var filter = element.getStyle('filter'), style = element.style;
+ if (value == 1 || value === '') {
+ (filter = stripAlpha(filter)) ?
+ style.filter = filter : style.removeAttribute('filter');
+ return element;
+ } else if (value < 0.00001) value = 0;
+ style.filter = stripAlpha(filter) +
+ 'alpha(opacity=' + (value * 100) + ')';
+ return element;
+ };
+
+ Element._attributeTranslations = (function(){
+
+ var classProp = 'className';
+ var forProp = 'for';
+
+ var el = document.createElement('div');
+
+ el.setAttribute(classProp, 'x');
+
+ if (el.className !== 'x') {
+ el.setAttribute('class', 'x');
+ if (el.className === 'x') {
+ classProp = 'class';
+ }
+ }
+ el = null;
+
+ el = document.createElement('label');
+ el.setAttribute(forProp, 'x');
+ if (el.htmlFor !== 'x') {
+ el.setAttribute('htmlFor', 'x');
+ if (el.htmlFor === 'x') {
+ forProp = 'htmlFor';
+ }
+ }
+ el = null;
+
+ return {
+ read: {
+ names: {
+ 'class': classProp,
+ 'className': classProp,
+ 'for': forProp,
+ 'htmlFor': forProp
+ },
+ values: {
+ _getAttr: function(element, attribute) {
+ return element.getAttribute(attribute);
+ },
+ _getAttr2: function(element, attribute) {
+ return element.getAttribute(attribute, 2);
+ },
+ _getAttrNode: function(element, attribute) {
+ var node = element.getAttributeNode(attribute);
+ return node ? node.value : "";
+ },
+ _getEv: (function(){
+
+ var el = document.createElement('div');
+ el.onclick = Prototype.emptyFunction;
+ var value = el.getAttribute('onclick');
+ var f;
+
+ if (String(value).indexOf('{') > -1) {
+ f = function(element, attribute) {
+ attribute = element.getAttribute(attribute);
+ if (!attribute) return null;
+ attribute = attribute.toString();
+ attribute = attribute.split('{')[1];
+ attribute = attribute.split('}')[0];
+ return attribute.strip();
+ };
+ }
+ else if (value === '') {
+ f = function(element, attribute) {
+ attribute = element.getAttribute(attribute);
+ if (!attribute) return null;
+ return attribute.strip();
+ };
+ }
+ el = null;
+ return f;
+ })(),
+ _flag: function(element, attribute) {
+ return $$(element).hasAttribute(attribute) ? attribute : null;
+ },
+ style: function(element) {
+ return element.style.cssText.toLowerCase();
+ },
+ title: function(element) {
+ return element.title;
+ }
+ }
+ }
+ }
+ })();
+
+ Element._attributeTranslations.write = {
+ names: Object.extend({
+ cellpadding: 'cellPadding',
+ cellspacing: 'cellSpacing'
+ }, Element._attributeTranslations.read.names),
+ values: {
+ checked: function(element, value) {
+ element.checked = !!value;
+ },
+
+ style: function(element, value) {
+ element.style.cssText = value ? value : '';
+ }
+ }
+ };
+
+ Element._attributeTranslations.has = {};
+
+ $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
+ 'encType maxLength readOnly longDesc frameBorder').each(function(attr) {
+ Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
+ Element._attributeTranslations.has[attr.toLowerCase()] = attr;
+ });
+
+ (function(v) {
+ Object.extend(v, {
+ href: v._getAttr2,
+ src: v._getAttr2,
+ type: v._getAttr,
+ action: v._getAttrNode,
+ disabled: v._flag,
+ checked: v._flag,
+ readonly: v._flag,
+ multiple: v._flag,
+ onload: v._getEv,
+ onunload: v._getEv,
+ onclick: v._getEv,
+ ondblclick: v._getEv,
+ onmousedown: v._getEv,
+ onmouseup: v._getEv,
+ onmouseover: v._getEv,
+ onmousemove: v._getEv,
+ onmouseout: v._getEv,
+ onfocus: v._getEv,
+ onblur: v._getEv,
+ onkeypress: v._getEv,
+ onkeydown: v._getEv,
+ onkeyup: v._getEv,
+ onsubmit: v._getEv,
+ onreset: v._getEv,
+ onselect: v._getEv,
+ onchange: v._getEv
+ });
+ })(Element._attributeTranslations.read.values);
+
+ if (Prototype.BrowserFeatures.ElementExtensions) {
+ (function() {
+ function _descendants(element) {
+ var nodes = element.getElementsByTagName('*'), results = [];
+ for (var i = 0, node; node = nodes[i]; i++)
+ if (node.tagName !== "!") // Filter out comment nodes.
+ results.push(node);
+ return results;
+ }
+
+ Element.Methods.down = function(element, expression, index) {
+ element = $$(element);
+ if (arguments.length == 1) return element.firstDescendant();
+ return Object.isNumber(expression) ? _descendants(element)[expression] :
+ Element.select(element, expression)[index || 0];
+ }
+ })();
+ }
+
+}
+
+else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
+ Element.Methods.setOpacity = function(element, value) {
+ element = $$(element);
+ element.style.opacity = (value == 1) ? 0.999999 :
+ (value === '') ? '' : (value < 0.00001) ? 0 : value;
+ return element;
+ };
+}
+
+else if (Prototype.Browser.WebKit) {
+ Element.Methods.setOpacity = function(element, value) {
+ element = $$(element);
+ element.style.opacity = (value == 1 || value === '') ? '' :
+ (value < 0.00001) ? 0 : value;
+
+ if (value == 1)
+ if(element.tagName.toUpperCase() == 'IMG' && element.width) {
+ element.width++; element.width--;
+ } else try {
+ var n = document.createTextNode(' ');
+ element.appendChild(n);
+ element.removeChild(n);
+ } catch (e) { }
+
+ return element;
+ };
+
+ Element.Methods.cumulativeOffset = function(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ if (element.offsetParent == document.body)
+ if (Element.getStyle(element, 'position') == 'absolute') break;
+
+ element = element.offsetParent;
+ } while (element);
+
+ return Element._returnOffset(valueL, valueT);
+ };
+}
+
+if ('outerHTML' in document.documentElement) {
+ Element.Methods.replace = function(element, content) {
+ element = $$(element);
+
+ if (content && content.toElement) content = content.toElement();
+ if (Object.isElement(content)) {
+ element.parentNode.replaceChild(content, element);
+ return element;
+ }
+
+ content = Object.toHTML(content);
+ var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
+
+ if (Element._insertionTranslations.tags[tagName]) {
+ var nextSibling = element.next();
+ var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
+ parent.removeChild(element);
+ if (nextSibling)
+ fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
+ else
+ fragments.each(function(node) { parent.appendChild(node) });
+ }
+ else element.outerHTML = content.stripScripts();
+
+ content.evalScripts.bind(content).defer();
+ return element;
+ };
+}
+
+Element._returnOffset = function(l, t) {
+ var result = [l, t];
+ result.left = l;
+ result.top = t;
+ return result;
+};
+
+Element._getContentFromAnonymousElement = function(tagName, html) {
+ var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
+ if (t) {
+ div.innerHTML = t[0] + html + t[1];
+ t[2].times(function() { div = div.firstChild });
+ } else div.innerHTML = html;
+ return $A(div.childNodes);
+};
+
+Element._insertionTranslations = {
+ before: function(element, node) {
+ element.parentNode.insertBefore(node, element);
+ },
+ top: function(element, node) {
+ element.insertBefore(node, element.firstChild);
+ },
+ bottom: function(element, node) {
+ element.appendChild(node);
+ },
+ after: function(element, node) {
+ element.parentNode.insertBefore(node, element.nextSibling);
+ },
+ tags: {
+ TABLE: ['<table>', '</table>', 1],
+ TBODY: ['<table><tbody>', '</tbody></table>', 2],
+ TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
+ TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
+ SELECT: ['<select>', '</select>', 1]
+ }
+};
+
+(function() {
+ var tags = Element._insertionTranslations.tags;
+ Object.extend(tags, {
+ THEAD: tags.TBODY,
+ TFOOT: tags.TBODY,
+ TH: tags.TD
+ });
+})();
+
+Element.Methods.Simulated = {
+ hasAttribute: function(element, attribute) {
+ attribute = Element._attributeTranslations.has[attribute] || attribute;
+ var node = $$(element).getAttributeNode(attribute);
+ return !!(node && node.specified);
+ }
+};
+
+Element.Methods.ByTag = { };
+
+Object.extend(Element, Element.Methods);
+
+(function(div) {
+
+ if (!Prototype.BrowserFeatures.ElementExtensions && div['__proto__']) {
+ window.HTMLElement = { };
+ window.HTMLElement.prototype = div['__proto__'];
+ Prototype.BrowserFeatures.ElementExtensions = true;
+ }
+
+ div = null;
+
+})(document.createElement('div'))
+
+Element.extend = (function() {
+
+ function checkDeficiency(tagName) {
+ if (typeof window.Element != 'undefined') {
+ var proto = window.Element.prototype;
+ if (proto) {
+ var id = '_' + (Math.random()+'').slice(2);
+ var el = document.createElement(tagName);
+ proto[id] = 'x';
+ var isBuggy = (el[id] !== 'x');
+ delete proto[id];
+ el = null;
+ return isBuggy;
+ }
+ }
+ return false;
+ }
+
+ function extendElementWith(element, methods) {
+ for (var property in methods) {
+ var value = methods[property];
+ if (Object.isFunction(value) && !(property in element))
+ element[property] = value.methodize();
+ }
+ }
+
+ var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object');
+
+ if (Prototype.BrowserFeatures.SpecificElementExtensions) {
+ if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY) {
+ return function(element) {
+ if (element && typeof element._extendedByPrototype == 'undefined') {
+ var t = element.tagName;
+ if (t && (/^(?:object|applet|embed)$/i.test(t))) {
+ extendElementWith(element, Element.Methods);
+ extendElementWith(element, Element.Methods.Simulated);
+ extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]);
+ }
+ }
+ return element;
+ }
+ }
+ return Prototype.K;
+ }
+
+ var Methods = { }, ByTag = Element.Methods.ByTag;
+
+ var extend = Object.extend(function(element) {
+ if (!element || typeof element._extendedByPrototype != 'undefined' ||
+ element.nodeType != 1 || element == window) return element;
+
+ var methods = Object.clone(Methods),
+ tagName = element.tagName.toUpperCase();
+
+ if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
+
+ extendElementWith(element, methods);
+
+ element._extendedByPrototype = Prototype.emptyFunction;
+ return element;
+
+ }, {
+ refresh: function() {
+ if (!Prototype.BrowserFeatures.ElementExtensions) {
+ Object.extend(Methods, Element.Methods);
+ Object.extend(Methods, Element.Methods.Simulated);
+ }
+ }
+ });
+
+ extend.refresh();
+ return extend;
+})();
+
+Element.hasAttribute = function(element, attribute) {
+ if (element.hasAttribute) return element.hasAttribute(attribute);
+ return Element.Methods.Simulated.hasAttribute(element, attribute);
+};
+
+Element.addMethods = function(methods) {
+ var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
+
+ if (!methods) {
+ Object.extend(Form, Form.Methods);
+ Object.extend(Form.Element, Form.Element.Methods);
+ Object.extend(Element.Methods.ByTag, {
+ "FORM": Object.clone(Form.Methods),
+ "INPUT": Object.clone(Form.Element.Methods),
+ "SELECT": Object.clone(Form.Element.Methods),
+ "TEXTAREA": Object.clone(Form.Element.Methods)
+ });
+ }
+
+ if (arguments.length == 2) {
+ var tagName = methods;
+ methods = arguments[1];
+ }
+
+ if (!tagName) Object.extend(Element.Methods, methods || { });
+ else {
+ if (Object.isArray(tagName)) tagName.each(extend);
+ else extend(tagName);
+ }
+
+ function extend(tagName) {
+ tagName = tagName.toUpperCase();
+ if (!Element.Methods.ByTag[tagName])
+ Element.Methods.ByTag[tagName] = { };
+ Object.extend(Element.Methods.ByTag[tagName], methods);
+ }
+
+ function copy(methods, destination, onlyIfAbsent) {
+ onlyIfAbsent = onlyIfAbsent || false;
+ for (var property in methods) {
+ var value = methods[property];
+ if (!Object.isFunction(value)) continue;
+ if (!onlyIfAbsent || !(property in destination))
+ destination[property] = value.methodize();
+ }
+ }
+
+ function findDOMClass(tagName) {
+ var klass;
+ var trans = {
+ "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
+ "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
+ "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
+ "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
+ "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
+ "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
+ "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
+ "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
+ "FrameSet", "IFRAME": "IFrame"
+ };
+ if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
+ if (window[klass]) return window[klass];
+ klass = 'HTML' + tagName + 'Element';
+ if (window[klass]) return window[klass];
+ klass = 'HTML' + tagName.capitalize() + 'Element';
+ if (window[klass]) return window[klass];
+
+ var element = document.createElement(tagName);
+ var proto = element['__proto__'] || element.constructor.prototype;
+ element = null;
+ return proto;
+ }
+
+ var elementPrototype = window.HTMLElement ? HTMLElement.prototype :
+ Element.prototype;
+
+ if (F.ElementExtensions) {
+ copy(Element.Methods, elementPrototype);
+ copy(Element.Methods.Simulated, elementPrototype, true);
+ }
+
+ if (F.SpecificElementExtensions) {
+ for (var tag in Element.Methods.ByTag) {
+ var klass = findDOMClass(tag);
+ if (Object.isUndefined(klass)) continue;
+ copy(T[tag], klass.prototype);
+ }
+ }
+
+ Object.extend(Element, Element.Methods);
+ delete Element.ByTag;
+
+ if (Element.extend.refresh) Element.extend.refresh();
+ Element.cache = { };
+};
+
+
+document.viewport = {
+
+ getDimensions: function() {
+ return { width: this.getWidth(), height: this.getHeight() };
+ },
+
+ getScrollOffsets: function() {
+ return Element._returnOffset(
+ window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
+ window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
+ }
+};
+
+(function(viewport) {
+ var B = Prototype.Browser, doc = document, element, property = {};
+
+ function getRootElement() {
+ if (B.WebKit && !doc.evaluate)
+ return document;
+
+ if (B.Opera && window.parseFloat(window.opera.version()) < 9.5)
+ return document.body;
+
+ return document.documentElement;
+ }
+
+ function define(D) {
+ if (!element) element = getRootElement();
+
+ property[D] = 'client' + D;
+
+ viewport['get' + D] = function() { return element[property[D]] };
+ return viewport['get' + D]();
+ }
+
+ viewport.getWidth = define.curry('Width');
+
+ viewport.getHeight = define.curry('Height');
+})(document.viewport);
+
+
+Element.Storage = {
+ UID: 1
+};
+
+Element.addMethods({
+ getStorage: function(element) {
+ if (!(element = $$(element))) return;
+
+ var uid;
+ if (element === window) {
+ uid = 0;
+ } else {
+ if (typeof element._prototypeUID === "undefined")
+ element._prototypeUID = [Element.Storage.UID++];
+ uid = element._prototypeUID[0];
+ }
+
+ if (!Element.Storage[uid])
+ Element.Storage[uid] = $H();
+
+ return Element.Storage[uid];
+ },
+
+ store: function(element, key, value) {
+ if (!(element = $$(element))) return;
+
+ if (arguments.length === 2) {
+ Element.getStorage(element).update(key);
+ } else {
+ Element.getStorage(element).set(key, value);
+ }
+
+ return element;
+ },
+
+ retrieve: function(element, key, defaultValue) {
+ if (!(element = $$(element))) return;
+ var hash = Element.getStorage(element), value = hash.get(key);
+
+ if (Object.isUndefined(value)) {
+ hash.set(key, defaultValue);
+ value = defaultValue;
+ }
+
+ return value;
+ },
+
+ clone: function(element, deep) {
+ if (!(element = $$(element))) return;
+ var clone = element.cloneNode(deep);
+ clone._prototypeUID = void 0;
+ if (deep) {
+ var descendants = Element.select(clone, '*'),
+ i = descendants.length;
+ while (i--) {
+ descendants[i]._prototypeUID = void 0;
+ }
+ }
+ return Element.extend(clone);
+ }
+});
+/* Portions of the Selector class are derived from Jack Slocum's DomQuery,
+ * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
+ * license. Please see http://www.yui-ext.com/ for more information. */
+
+var Selector = Class.create({
+ initialize: function(expression) {
+ this.expression = expression.strip();
+
+ if (this.shouldUseSelectorsAPI()) {
+ this.mode = 'selectorsAPI';
+ } else if (this.shouldUseXPath()) {
+ this.mode = 'xpath';
+ this.compileXPathMatcher();
+ } else {
+ this.mode = "normal";
+ this.compileMatcher();
+ }
+
+ },
+
+ shouldUseXPath: (function() {
+
+ var IS_DESCENDANT_SELECTOR_BUGGY = (function(){
+ var isBuggy = false;
+ if (document.evaluate && window.XPathResult) {
+ var el = document.createElement('div');
+ el.innerHTML = '<ul><li></li></ul><div><ul><li></li></ul></div>';
+
+ var xpath = ".//*[local-name()='ul' or local-name()='UL']" +
+ "//*[local-name()='li' or local-name()='LI']";
+
+ var result = document.evaluate(xpath, el, null,
+ XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+
+ isBuggy = (result.snapshotLength !== 2);
+ el = null;
+ }
+ return isBuggy;
+ })();
+
+ return function() {
+ if (!Prototype.BrowserFeatures.XPath) return false;
+
+ var e = this.expression;
+
+ if (Prototype.Browser.WebKit &&
+ (e.include("-of-type") || e.include(":empty")))
+ return false;
+
+ if ((/(\[[\w-]*?:|:checked)/).test(e))
+ return false;
+
+ if (IS_DESCENDANT_SELECTOR_BUGGY) return false;
+
+ return true;
+ }
+
+ })(),
+
+ shouldUseSelectorsAPI: function() {
+ if (!Prototype.BrowserFeatures.SelectorsAPI) return false;
+
+ if (Selector.CASE_INSENSITIVE_CLASS_NAMES) return false;
+
+ if (!Selector._div) Selector._div = new Element('div');
+
+ try {
+ Selector._div.querySelector(this.expression);
+ } catch(e) {
+ return false;
+ }
+
+ return true;
+ },
+
+ compileMatcher: function() {
+ var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
+ c = Selector.criteria, le, p, m, len = ps.length, name;
+
+ if (Selector._cache[e]) {
+ this.matcher = Selector._cache[e];
+ return;
+ }
+
+ this.matcher = ["this.matcher = function(root) {",
+ "var r = root, h = Selector.handlers, c = false, n;"];
+
+ while (e && le != e && (/\S/).test(e)) {
+ le = e;
+ for (var i = 0; i<len; i++) {
+ p = ps[i].re;
+ name = ps[i].name;
+ if (m = e.match(p)) {
+ this.matcher.push(Object.isFunction(c[name]) ? c[name](m) :
+ new Template(c[name]).evaluate(m));
+ e = e.replace(m[0], '');
+ break;
+ }
+ }
+ }
+
+ this.matcher.push("return h.unique(n);\n}");
+ eval(this.matcher.join('\n'));
+ Selector._cache[this.expression] = this.matcher;
+ },
+
+ compileXPathMatcher: function() {
+ var e = this.expression, ps = Selector.patterns,
+ x = Selector.xpath, le, m, len = ps.length, name;
+
+ if (Selector._cache[e]) {
+ this.xpath = Selector._cache[e]; return;
+ }
+
+ this.matcher = ['.//*'];
+ while (e && le != e && (/\S/).test(e)) {
+ le = e;
+ for (var i = 0; i<len; i++) {
+ name = ps[i].name;
+ if (m = e.match(ps[i].re)) {
+ this.matcher.push(Object.isFunction(x[name]) ? x[name](m) :
+ new Template(x[name]).evaluate(m));
+ e = e.replace(m[0], '');
+ break;
+ }
+ }
+ }
+
+ this.xpath = this.matcher.join('');
+ Selector._cache[this.expression] = this.xpath;
+ },
+
+ findElements: function(root) {
+ root = root || document;
+ var e = this.expression, results;
+
+ switch (this.mode) {
+ case 'selectorsAPI':
+ if (root !== document) {
+ var oldId = root.id, id = $$(root).identify();
+ id = id.replace(/([\.:])/g, "\\$1");
+ e = "#" + id + " " + e;
+ }
+
+ results = $A(root.querySelectorAll(e)).map(Element.extend);
+ root.id = oldId;
+
+ return results;
+ case 'xpath':
+ return document._getElementsByXPath(this.xpath, root);
+ default:
+ return this.matcher(root);
+ }
+ },
+
+ match: function(element) {
+ this.tokens = [];
+
+ var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
+ var le, p, m, len = ps.length, name;
+
+ while (e && le !== e && (/\S/).test(e)) {
+ le = e;
+ for (var i = 0; i<len; i++) {
+ p = ps[i].re;
+ name = ps[i].name;
+ if (m = e.match(p)) {
+ if (as[name]) {
+ this.tokens.push([name, Object.clone(m)]);
+ e = e.replace(m[0], '');
+ } else {
+ return this.findElements(document).include(element);
+ }
+ }
+ }
+ }
+
+ var match = true, name, matches;
+ for (var i = 0, token; token = this.tokens[i]; i++) {
+ name = token[0], matches = token[1];
+ if (!Selector.assertions[name](element, matches)) {
+ match = false; break;
+ }
+ }
+
+ return match;
+ },
+
+ toString: function() {
+ return this.expression;
+ },
+
+ inspect: function() {
+ return "#<Selector:" + this.expression.inspect() + ">";
+ }
+});
+
+if (Prototype.BrowserFeatures.SelectorsAPI &&
+ document.compatMode === 'BackCompat') {
+ Selector.CASE_INSENSITIVE_CLASS_NAMES = (function(){
+ var div = document.createElement('div'),
+ span = document.createElement('span');
+
+ div.id = "prototype_test_id";
+ span.className = 'Test';
+ div.appendChild(span);
+ var isIgnored = (div.querySelector('#prototype_test_id .test') !== null);
+ div = span = null;
+ return isIgnored;
+ })();
+}
+
+Object.extend(Selector, {
+ _cache: { },
+
+ xpath: {
+ descendant: "//*",
+ child: "/*",
+ adjacent: "/following-sibling::*[1]",
+ laterSibling: '/following-sibling::*',
+ tagName: function(m) {
+ if (m[1] == '*') return '';
+ return "[local-name()='" + m[1].toLowerCase() +
+ "' or local-name()='" + m[1].toUpperCase() + "']";
+ },
+ className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
+ id: "[@id='#{1}']",
+ attrPresence: function(m) {
+ m[1] = m[1].toLowerCase();
+ return new Template("[@#{1}]").evaluate(m);
+ },
+ attr: function(m) {
+ m[1] = m[1].toLowerCase();
+ m[3] = m[5] || m[6];
+ return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
+ },
+ pseudo: function(m) {
+ var h = Selector.xpath.pseudos[m[1]];
+ if (!h) return '';
+ if (Object.isFunction(h)) return h(m);
+ return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
+ },
+ operators: {
+ '=': "[@#{1}='#{3}']",
+ '!=': "[@#{1}!='#{3}']",
+ '^=': "[starts-with(@#{1}, '#{3}')]",
+ '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
+ '*=': "[contains(@#{1}, '#{3}')]",
+ '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
+ '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
+ },
+ pseudos: {
+ 'first-child': '[not(preceding-sibling::*)]',
+ 'last-child': '[not(following-sibling::*)]',
+ 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
+ 'empty': "[count(*) = 0 and (count(text()) = 0)]",
+ 'checked': "[@checked]",
+ 'disabled': "[(@disabled) and (@type!='hidden')]",
+ 'enabled': "[not(@disabled) and (@type!='hidden')]",
+ 'not': function(m) {
+ var e = m[6], p = Selector.patterns,
+ x = Selector.xpath, le, v, len = p.length, name;
+
+ var exclusion = [];
+ while (e && le != e && (/\S/).test(e)) {
+ le = e;
+ for (var i = 0; i<len; i++) {
+ name = p[i].name
+ if (m = e.match(p[i].re)) {
+ v = Object.isFunction(x[name]) ? x[name](m) : new Template(x[name]).evaluate(m);
+ exclusion.push("(" + v.substring(1, v.length - 1) + ")");
+ e = e.replace(m[0], '');
+ break;
+ }
+ }
+ }
+ return "[not(" + exclusion.join(" and ") + ")]";
+ },
+ 'nth-child': function(m) {
+ return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
+ },
+ 'nth-last-child': function(m) {
+ return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
+ },
+ 'nth-of-type': function(m) {
+ return Selector.xpath.pseudos.nth("position() ", m);
+ },
+ 'nth-last-of-type': function(m) {
+ return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
+ },
+ 'first-of-type': function(m) {
+ m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
+ },
+ 'last-of-type': function(m) {
+ m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
+ },
+ 'only-of-type': function(m) {
+ var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
+ },
+ nth: function(fragment, m) {
+ var mm, formula = m[6], predicate;
+ if (formula == 'even') formula = '2n+0';
+ if (formula == 'odd') formula = '2n+1';
+ if (mm = formula.match(/^(\d+)$/)) // digit only
+ return '[' + fragment + "= " + mm[1] + ']';
+ if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
+ if (mm[1] == "-") mm[1] = -1;
+ var a = mm[1] ? Number(mm[1]) : 1;
+ var b = mm[2] ? Number(mm[2]) : 0;
+ predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
+ "((#{fragment} - #{b}) div #{a} >= 0)]";
+ return new Template(predicate).evaluate({
+ fragment: fragment, a: a, b: b });
+ }
+ }
+ }
+ },
+
+ criteria: {
+ tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
+ className: 'n = h.className(n, r, "#{1}", c); c = false;',
+ id: 'n = h.id(n, r, "#{1}", c); c = false;',
+ attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
+ attr: function(m) {
+ m[3] = (m[5] || m[6]);
+ return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
+ },
+ pseudo: function(m) {
+ if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
+ return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
+ },
+ descendant: 'c = "descendant";',
+ child: 'c = "child";',
+ adjacent: 'c = "adjacent";',
+ laterSibling: 'c = "laterSibling";'
+ },
+
+ patterns: [
+ { name: 'laterSibling', re: /^\s*~\s*/ },
+ { name: 'child', re: /^\s*>\s*/ },
+ { name: 'adjacent', re: /^\s*\+\s*/ },
+ { name: 'descendant', re: /^\s/ },
+
+ { name: 'tagName', re: /^\s*(\*|[\w\-]+)(\b|$)?/ },
+ { name: 'id', re: /^#([\w\-\*]+)(\b|$)/ },
+ { name: 'className', re: /^\.([\w\-\*]+)(\b|$)/ },
+ { name: 'pseudo', re: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/ },
+ { name: 'attrPresence', re: /^\[((?:[\w-]+:)?[\w-]+)\]/ },
+ { name: 'attr', re: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/ }
+ ],
+
+ assertions: {
+ tagName: function(element, matches) {
+ return matches[1].toUpperCase() == element.tagName.toUpperCase();
+ },
+
+ className: function(element, matches) {
+ return Element.hasClassName(element, matches[1]);
+ },
+
+ id: function(element, matches) {
+ return element.id === matches[1];
+ },
+
+ attrPresence: function(element, matches) {
+ return Element.hasAttribute(element, matches[1]);
+ },
+
+ attr: function(element, matches) {
+ var nodeValue = Element.readAttribute(element, matches[1]);
+ return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
+ }
+ },
+
+ handlers: {
+ concat: function(a, b) {
+ for (var i = 0, node; node = b[i]; i++)
+ a.push(node);
+ return a;
+ },
+
+ mark: function(nodes) {
+ var _true = Prototype.emptyFunction;
+ for (var i = 0, node; node = nodes[i]; i++)
+ node._countedByPrototype = _true;
+ return nodes;
+ },
+
+ unmark: (function(){
+
+ var PROPERTIES_ATTRIBUTES_MAP = (function(){
+ var el = document.createElement('div'),
+ isBuggy = false,
+ propName = '_countedByPrototype',
+ value = 'x'
+ el[propName] = value;
+ isBuggy = (el.getAttribute(propName) === value);
+ el = null;
+ return isBuggy;
+ })();
+
+ return PROPERTIES_ATTRIBUTES_MAP ?
+ function(nodes) {
+ for (var i = 0, node; node = nodes[i]; i++)
+ node.removeAttribute('_countedByPrototype');
+ return nodes;
+ } :
+ function(nodes) {
+ for (var i = 0, node; node = nodes[i]; i++)
+ node._countedByPrototype = void 0;
+ return nodes;
+ }
+ })(),
+
+ index: function(parentNode, reverse, ofType) {
+ parentNode._countedByPrototype = Prototype.emptyFunction;
+ if (reverse) {
+ for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
+ var node = nodes[i];
+ if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
+ }
+ } else {
+ for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
+ if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
+ }
+ },
+
+ unique: function(nodes) {
+ if (nodes.length == 0) return nodes;
+ var results = [], n;
+ for (var i = 0, l = nodes.length; i < l; i++)
+ if (typeof (n = nodes[i])._countedByPrototype == 'undefined') {
+ n._countedByPrototype = Prototype.emptyFunction;
+ results.push(Element.extend(n));
+ }
+ return Selector.handlers.unmark(results);
+ },
+
+ descendant: function(nodes) {
+ var h = Selector.handlers;
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
+ h.concat(results, node.getElementsByTagName('*'));
+ return results;
+ },
+
+ child: function(nodes) {
+ var h = Selector.handlers;
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
+ for (var j = 0, child; child = node.childNodes[j]; j++)
+ if (child.nodeType == 1 && child.tagName != '!') results.push(child);
+ }
+ return results;
+ },
+
+ adjacent: function(nodes) {
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
+ var next = this.nextElementSibling(node);
+ if (next) results.push(next);
+ }
+ return results;
+ },
+
+ laterSibling: function(nodes) {
+ var h = Selector.handlers;
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
+ h.concat(results, Element.nextSiblings(node));
+ return results;
+ },
+
+ nextElementSibling: function(node) {
+ while (node = node.nextSibling)
+ if (node.nodeType == 1) return node;
+ return null;
+ },
+
+ previousElementSibling: function(node) {
+ while (node = node.previousSibling)
+ if (node.nodeType == 1) return node;
+ return null;
+ },
+
+ tagName: function(nodes, root, tagName, combinator) {
+ var uTagName = tagName.toUpperCase();
+ var results = [], h = Selector.handlers;
+ if (nodes) {
+ if (combinator) {
+ if (combinator == "descendant") {
+ for (var i = 0, node; node = nodes[i]; i++)
+ h.concat(results, node.getElementsByTagName(tagName));
+ return results;
+ } else nodes = this[combinator](nodes);
+ if (tagName == "*") return nodes;
+ }
+ for (var i = 0, node; node = nodes[i]; i++)
+ if (node.tagName.toUpperCase() === uTagName) results.push(node);
+ return results;
+ } else return root.getElementsByTagName(tagName);
+ },
+
+ id: function(nodes, root, id, combinator) {
+ var targetNode = $$(id), h = Selector.handlers;
+
+ if (root == document) {
+ if (!targetNode) return [];
+ if (!nodes) return [targetNode];
+ } else {
+ if (!root.sourceIndex || root.sourceIndex < 1) {
+ var nodes = root.getElementsByTagName('*');
+ for (var j = 0, node; node = nodes[j]; j++) {
+ if (node.id === id) return [node];
+ }
+ }
+ }
+
+ if (nodes) {
+ if (combinator) {
+ if (combinator == 'child') {
+ for (var i = 0, node; node = nodes[i]; i++)
+ if (targetNode.parentNode == node) return [targetNode];
+ } else if (combinator == 'descendant') {
+ for (var i = 0, node; node = nodes[i]; i++)
+ if (Element.descendantOf(targetNode, node)) return [targetNode];
+ } else if (combinator == 'adjacent') {
+ for (var i = 0, node; node = nodes[i]; i++)
+ if (Selector.handlers.previousElementSibling(targetNode) == node)
+ return [targetNode];
+ } else nodes = h[combinator](nodes);
+ }
+ for (var i = 0, node; node = nodes[i]; i++)
+ if (node == targetNode) return [targetNode];
+ return [];
+ }
+ return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
+ },
+
+ className: function(nodes, root, className, combinator) {
+ if (nodes && combinator) nodes = this[combinator](nodes);
+ return Selector.handlers.byClassName(nodes, root, className);
+ },
+
+ byClassName: function(nodes, root, className) {
+ if (!nodes) nodes = Selector.handlers.descendant([root]);
+ var needle = ' ' + className + ' ';
+ for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
+ nodeClassName = node.className;
+ if (nodeClassName.length == 0) continue;
+ if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
+ results.push(node);
+ }
+ return results;
+ },
+
+ attrPresence: function(nodes, root, attr, combinator) {
+ if (!nodes) nodes = root.getElementsByTagName("*");
+ if (nodes && combinator) nodes = this[combinator](nodes);
+ var results = [];
+ for (var i = 0, node; node = nodes[i]; i++)
+ if (Element.hasAttribute(node, attr)) results.push(node);
+ return results;
+ },
+
+ attr: function(nodes, root, attr, value, operator, combinator) {
+ if (!nodes) nodes = root.getElementsByTagName("*");
+ if (nodes && combinator) nodes = this[combinator](nodes);
+ var handler = Selector.operators[operator], results = [];
+ for (var i = 0, node; node = nodes[i]; i++) {
+ var nodeValue = Element.readAttribute(node, attr);
+ if (nodeValue === null) continue;
+ if (handler(nodeValue, value)) results.push(node);
+ }
+ return results;
+ },
+
+ pseudo: function(nodes, name, value, root, combinator) {
+ if (nodes && combinator) nodes = this[combinator](nodes);
+ if (!nodes) nodes = root.getElementsByTagName("*");
+ return Selector.pseudos[name](nodes, value, root);
+ }
+ },
+
+ pseudos: {
+ 'first-child': function(nodes, value, root) {
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
+ if (Selector.handlers.previousElementSibling(node)) continue;
+ results.push(node);
+ }
+ return results;
+ },
+ 'last-child': function(nodes, value, root) {
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
+ if (Selector.handlers.nextElementSibling(node)) continue;
+ results.push(node);
+ }
+ return results;
+ },
+ 'only-child': function(nodes, value, root) {
+ var h = Selector.handlers;
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
+ if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
+ results.push(node);
+ return results;
+ },
+ 'nth-child': function(nodes, formula, root) {
+ return Selector.pseudos.nth(nodes, formula, root);
+ },
+ 'nth-last-child': function(nodes, formula, root) {
+ return Selector.pseudos.nth(nodes, formula, root, true);
+ },
+ 'nth-of-type': function(nodes, formula, root) {
+ return Selector.pseudos.nth(nodes, formula, root, false, true);
+ },
+ 'nth-last-of-type': function(nodes, formula, root) {
+ return Selector.pseudos.nth(nodes, formula, root, true, true);
+ },
+ 'first-of-type': function(nodes, formula, root) {
+ return Selector.pseudos.nth(nodes, "1", root, false, true);
+ },
+ 'last-of-type': function(nodes, formula, root) {
+ return Selector.pseudos.nth(nodes, "1", root, true, true);
+ },
+ 'only-of-type': function(nodes, formula, root) {
+ var p = Selector.pseudos;
+ return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
+ },
+
+ getIndices: function(a, b, total) {
+ if (a == 0) return b > 0 ? [b] : [];
+ return $R(1, total).inject([], function(memo, i) {
+ if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
+ return memo;
+ });
+ },
+
+ nth: function(nodes, formula, root, reverse, ofType) {
+ if (nodes.length == 0) return [];
+ if (formula == 'even') formula = '2n+0';
+ if (formula == 'odd') formula = '2n+1';
+ var h = Selector.handlers, results = [], indexed = [], m;
+ h.mark(nodes);
+ for (var i = 0, node; node = nodes[i]; i++) {
+ if (!node.parentNode._countedByPrototype) {
+ h.index(node.parentNode, reverse, ofType);
+ indexed.push(node.parentNode);
+ }
+ }
+ if (formula.match(/^\d+$/)) { // just a number
+ formula = Number(formula);
+ for (var i = 0, node; node = nodes[i]; i++)
+ if (node.nodeIndex == formula) results.push(node);
+ } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
+ if (m[1] == "-") m[1] = -1;
+ var a = m[1] ? Number(m[1]) : 1;
+ var b = m[2] ? Number(m[2]) : 0;
+ var indices = Selector.pseudos.getIndices(a, b, nodes.length);
+ for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
+ for (var j = 0; j < l; j++)
+ if (node.nodeIndex == indices[j]) results.push(node);
+ }
+ }
+ h.unmark(nodes);
+ h.unmark(indexed);
+ return results;
+ },
+
+ 'empty': function(nodes, value, root) {
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
+ if (node.tagName == '!' || node.firstChild) continue;
+ results.push(node);
+ }
+ return results;
+ },
+
+ 'not': function(nodes, selector, root) {
+ var h = Selector.handlers, selectorType, m;
+ var exclusions = new Selector(selector).findElements(root);
+ h.mark(exclusions);
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
+ if (!node._countedByPrototype) results.push(node);
+ h.unmark(exclusions);
+ return results;
+ },
+
+ 'enabled': function(nodes, value, root) {
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
+ if (!node.disabled && (!node.type || node.type !== 'hidden'))
+ results.push(node);
+ return results;
+ },
+
+ 'disabled': function(nodes, value, root) {
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
+ if (node.disabled) results.push(node);
+ return results;
+ },
+
+ 'checked': function(nodes, value, root) {
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
+ if (node.checked) results.push(node);
+ return results;
+ }
+ },
+
+ operators: {
+ '=': function(nv, v) { return nv == v; },
+ '!=': function(nv, v) { return nv != v; },
+ '^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); },
+ '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); },
+ '*=': function(nv, v) { return nv == v || nv && nv.include(v); },
+ '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
+ '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
+ '-').include('-' + (v || "").toUpperCase() + '-'); }
+ },
+
+ split: function(expression) {
+ var expressions = [];
+ expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
+ expressions.push(m[1].strip());
+ });
+ return expressions;
+ },
+
+ matchElements: function(elements, expression) {
+ var matches = $$$(expression), h = Selector.handlers;
+ h.mark(matches);
+ for (var i = 0, results = [], element; element = elements[i]; i++)
+ if (element._countedByPrototype) results.push(element);
+ h.unmark(matches);
+ return results;
+ },
+
+ findElement: function(elements, expression, index) {
+ if (Object.isNumber(expression)) {
+ index = expression; expression = false;
+ }
+ return Selector.matchElements(elements, expression || '*')[index || 0];
+ },
+
+ findChildElements: function(element, expressions) {
+ expressions = Selector.split(expressions.join(','));
+ var results = [], h = Selector.handlers;
+ for (var i = 0, l = expressions.length, selector; i < l; i++) {
+ selector = new Selector(expressions[i].strip());
+ h.concat(results, selector.findElements(element));
+ }
+ return (l > 1) ? h.unique(results) : results;
+ }
+});
+
+if (Prototype.Browser.IE) {
+ Object.extend(Selector.handlers, {
+ concat: function(a, b) {
+ for (var i = 0, node; node = b[i]; i++)
+ if (node.tagName !== "!") a.push(node);
+ return a;
+ }
+ });
+}
+
+function $$$() {
+ return Selector.findChildElements(document, $A(arguments));
+}
+
+var Form = {
+ reset: function(form) {
+ form = $$(form);
+ form.reset();
+ return form;
+ },
+
+ serializeElements: function(elements, options) {
+ if (typeof options != 'object') options = { hash: !!options };
+ else if (Object.isUndefined(options.hash)) options.hash = true;
+ var key, value, submitted = false, submit = options.submit;
+
+ var data = elements.inject({ }, function(result, element) {
+ if (!element.disabled && element.name) {
+ key = element.name; value = $$(element).getValue();
+ if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
+ submit !== false && (!submit || key == submit) && (submitted = true)))) {
+ if (key in result) {
+ if (!Object.isArray(result[key])) result[key] = [result[key]];
+ result[key].push(value);
+ }
+ else result[key] = value;
+ }
+ }
+ return result;
+ });
+
+ return options.hash ? data : Object.toQueryString(data);
+ }
+};
+
+Form.Methods = {
+ serialize: function(form, options) {
+ return Form.serializeElements(Form.getElements(form), options);
+ },
+
+ getElements: function(form) {
+ var elements = $$(form).getElementsByTagName('*'),
+ element,
+ arr = [ ],
+ serializers = Form.Element.Serializers;
+ for (var i = 0; element = elements[i]; i++) {
+ arr.push(element);
+ }
+ return arr.inject([], function(elements, child) {
+ if (serializers[child.tagName.toLowerCase()])
+ elements.push(Element.extend(child));
+ return elements;
+ })
+ },
+
+ getInputs: function(form, typeName, name) {
+ form = $$(form);
+ var inputs = form.getElementsByTagName('input');
+
+ if (!typeName && !name) return $A(inputs).map(Element.extend);
+
+ for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
+ var input = inputs[i];
+ if ((typeName && input.type != typeName) || (name && input.name != name))
+ continue;
+ matchingInputs.push(Element.extend(input));
+ }
+
+ return matchingInputs;
+ },
+
+ disable: function(form) {
+ form = $$(form);
+ Form.getElements(form).invoke('disable');
+ return form;
+ },
+
+ enable: function(form) {
+ form = $$(form);
+ Form.getElements(form).invoke('enable');
+ return form;
+ },
+
+ findFirstElement: function(form) {
+ var elements = $$(form).getElements().findAll(function(element) {
+ return 'hidden' != element.type && !element.disabled;
+ });
+ var firstByIndex = elements.findAll(function(element) {
+ return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
+ }).sortBy(function(element) { return element.tabIndex }).first();
+
+ return firstByIndex ? firstByIndex : elements.find(function(element) {
+ return /^(?:input|select|textarea)$/i.test(element.tagName);
+ });
+ },
+
+ focusFirstElement: function(form) {
+ form = $$(form);
+ form.findFirstElement().activate();
+ return form;
+ },
+
+ request: function(form, options) {
+ form = $$(form), options = Object.clone(options || { });
+
+ var params = options.parameters, action = form.readAttribute('action') || '';
+ if (action.blank()) action = window.location.href;
+ options.parameters = form.serialize(true);
+
+ if (params) {
+ if (Object.isString(params)) params = params.toQueryParams();
+ Object.extend(options.parameters, params);
+ }
+
+ if (form.hasAttribute('method') && !options.method)
+ options.method = form.method;
+
+ return new Ajax.Request(action, options);
+ }
+};
+
+/*--------------------------------------------------------------------------*/
+
+
+Form.Element = {
+ focus: function(element) {
+ $$(element).focus();
+ return element;
+ },
+
+ select: function(element) {
+ $$(element).select();
+ return element;
+ }
+};
+
+Form.Element.Methods = {
+
+ serialize: function(element) {
+ element = $$(element);
+ if (!element.disabled && element.name) {
+ var value = element.getValue();
+ if (value != undefined) {
+ var pair = { };
+ pair[element.name] = value;
+ return Object.toQueryString(pair);
+ }
+ }
+ return '';
+ },
+
+ getValue: function(element) {
+ element = $$(element);
+ var method = element.tagName.toLowerCase();
+ return Form.Element.Serializers[method](element);
+ },
+
+ setValue: function(element, value) {
+ element = $$(element);
+ var method = element.tagName.toLowerCase();
+ Form.Element.Serializers[method](element, value);
+ return element;
+ },
+
+ clear: function(element) {
+ $$(element).value = '';
+ return element;
+ },
+
+ present: function(element) {
+ return $$(element).value != '';
+ },
+
+ activate: function(element) {
+ element = $$(element);
+ try {
+ element.focus();
+ if (element.select && (element.tagName.toLowerCase() != 'input' ||
+ !(/^(?:button|reset|submit)$/i.test(element.type))))
+ element.select();
+ } catch (e) { }
+ return element;
+ },
+
+ disable: function(element) {
+ element = $$(element);
+ element.disabled = true;
+ return element;
+ },
+
+ enable: function(element) {
+ element = $$(element);
+ element.disabled = false;
+ return element;
+ }
+};
+
+/*--------------------------------------------------------------------------*/
+
+var Field = Form.Element;
+
+var $F = Form.Element.Methods.getValue;
+
+/*--------------------------------------------------------------------------*/
+
+Form.Element.Serializers = {
+ input: function(element, value) {
+ switch (element.type.toLowerCase()) {
+ case 'checkbox':
+ case 'radio':
+ return Form.Element.Serializers.inputSelector(element, value);
+ default:
+ return Form.Element.Serializers.textarea(element, value);
+ }
+ },
+
+ inputSelector: function(element, value) {
+ if (Object.isUndefined(value)) return element.checked ? element.value : null;
+ else element.checked = !!value;
+ },
+
+ textarea: function(element, value) {
+ if (Object.isUndefined(value)) return element.value;
+ else element.value = value;
+ },
+
+ select: function(element, value) {
+ if (Object.isUndefined(value))
+ return this[element.type == 'select-one' ?
+ 'selectOne' : 'selectMany'](element);
+ else {
+ var opt, currentValue, single = !Object.isArray(value);
+ for (var i = 0, length = element.length; i < length; i++) {
+ opt = element.options[i];
+ currentValue = this.optionValue(opt);
+ if (single) {
+ if (currentValue == value) {
+ opt.selected = true;
+ return;
+ }
+ }
+ else opt.selected = value.include(currentValue);
+ }
+ }
+ },
+
+ selectOne: function(element) {
+ var index = element.selectedIndex;
+ return index >= 0 ? this.optionValue(element.options[index]) : null;
+ },
+
+ selectMany: function(element) {
+ var values, length = element.length;
+ if (!length) return null;
+
+ for (var i = 0, values = []; i < length; i++) {
+ var opt = element.options[i];
+ if (opt.selected) values.push(this.optionValue(opt));
+ }
+ return values;
+ },
+
+ optionValue: function(opt) {
+ return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
+ }
+};
+
+/*--------------------------------------------------------------------------*/
+
+
+Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
+ initialize: function($super, element, frequency, callback) {
+ $super(callback, frequency);
+ this.element = $$(element);
+ this.lastValue = this.getValue();
+ },
+
+ execute: function() {
+ var value = this.getValue();
+ if (Object.isString(this.lastValue) && Object.isString(value) ?
+ this.lastValue != value : String(this.lastValue) != String(value)) {
+ this.callback(this.element, value);
+ this.lastValue = value;
+ }
+ }
+});
+
+Form.Element.Observer = Class.create(Abstract.TimedObserver, {
+ getValue: function() {
+ return Form.Element.getValue(this.element);
+ }
+});
+
+Form.Observer = Class.create(Abstract.TimedObserver, {
+ getValue: function() {
+ return Form.serialize(this.element);
+ }
+});
+
+/*--------------------------------------------------------------------------*/
+
+Abstract.EventObserver = Class.create({
+ initialize: function(element, callback) {
+ this.element = $$(element);
+ this.callback = callback;
+
+ this.lastValue = this.getValue();
+ if (this.element.tagName.toLowerCase() == 'form')
+ this.registerFormCallbacks();
+ else
+ this.registerCallback(this.element);
+ },
+
+ onElementEvent: function() {
+ var value = this.getValue();
+ if (this.lastValue != value) {
+ this.callback(this.element, value);
+ this.lastValue = value;
+ }
+ },
+
+ registerFormCallbacks: function() {
+ Form.getElements(this.element).each(this.registerCallback, this);
+ },
+
+ registerCallback: function(element) {
+ if (element.type) {
+ switch (element.type.toLowerCase()) {
+ case 'checkbox':
+ case 'radio':
+ Event.observe(element, 'click', this.onElementEvent.bind(this));
+ break;
+ default:
+ Event.observe(element, 'change', this.onElementEvent.bind(this));
+ break;
+ }
+ }
+ }
+});
+
+Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
+ getValue: function() {
+ return Form.Element.getValue(this.element);
+ }
+});
+
+Form.EventObserver = Class.create(Abstract.EventObserver, {
+ getValue: function() {
+ return Form.serialize(this.element);
+ }
+});
+(function() {
+
+ var Event = {
+ KEY_BACKSPACE: 8,
+ KEY_TAB: 9,
+ KEY_RETURN: 13,
+ KEY_ESC: 27,
+ KEY_LEFT: 37,
+ KEY_UP: 38,
+ KEY_RIGHT: 39,
+ KEY_DOWN: 40,
+ KEY_DELETE: 46,
+ KEY_HOME: 36,
+ KEY_END: 35,
+ KEY_PAGEUP: 33,
+ KEY_PAGEDOWN: 34,
+ KEY_INSERT: 45,
+
+ cache: {}
+ };
+
+ var docEl = document.documentElement;
+ var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl
+ && 'onmouseleave' in docEl;
+
+ var _isButton;
+ if (Prototype.Browser.IE) {
+ var buttonMap = { 0: 1, 1: 4, 2: 2 };
+ _isButton = function(event, code) {
+ return event.button === buttonMap[code];
+ };
+ } else if (Prototype.Browser.WebKit) {
+ _isButton = function(event, code) {
+ switch (code) {
+ case 0: return event.which == 1 && !event.metaKey;
+ case 1: return event.which == 1 && event.metaKey;
+ default: return false;
+ }
+ };
+ } else {
+ _isButton = function(event, code) {
+ return event.which ? (event.which === code + 1) : (event.button === code);
+ };
+ }
+
+ function isLeftClick(event) { return _isButton(event, 0) }
+
+ function isMiddleClick(event) { return _isButton(event, 1) }
+
+ function isRightClick(event) { return _isButton(event, 2) }
+
+ function element(event) {
+ event = Event.extend(event);
+
+ var node = event.target, type = event.type,
+ currentTarget = event.currentTarget;
+
+ if (currentTarget && currentTarget.tagName) {
+ if (type === 'load' || type === 'error' ||
+ (type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
+ && currentTarget.type === 'radio'))
+ node = currentTarget;
+ }
+
+ if (node.nodeType == Node.TEXT_NODE)
+ node = node.parentNode;
+
+ return Element.extend(node);
+ }
+
+ function findElement(event, expression) {
+ var element = Event.element(event);
+ if (!expression) return element;
+ var elements = [element].concat(element.ancestors());
+ return Selector.findElement(elements, expression, 0);
+ }
+
+ function pointer(event) {
+ return { x: pointerX(event), y: pointerY(event) };
+ }
+
+ function pointerX(event) {
+ var docElement = document.documentElement,
+ body = document.body || { scrollLeft: 0 };
+
+ return event.pageX || (event.clientX +
+ (docElement.scrollLeft || body.scrollLeft) -
+ (docElement.clientLeft || 0));
+ }
+
+ function pointerY(event) {
+ var docElement = document.documentElement,
+ body = document.body || { scrollTop: 0 };
+
+ return event.pageY || (event.clientY +
+ (docElement.scrollTop || body.scrollTop) -
+ (docElement.clientTop || 0));
+ }
+
+
+ function stop(event) {
+ Event.extend(event);
+ event.preventDefault();
+ event.stopPropagation();
+
+ event.stopped = true;
+ }
+
+ Event.Methods = {
+ isLeftClick: isLeftClick,
+ isMiddleClick: isMiddleClick,
+ isRightClick: isRightClick,
+
+ element: element,
+ findElement: findElement,
+
+ pointer: pointer,
+ pointerX: pointerX,
+ pointerY: pointerY,
+
+ stop: stop
+ };
+
+
+ var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
+ m[name] = Event.Methods[name].methodize();
+ return m;
+ });
+
+ if (Prototype.Browser.IE) {
+ function _relatedTarget(event) {
+ var element;
+ switch (event.type) {
+ case 'mouseover': element = event.fromElement; break;
+ case 'mouseout': element = event.toElement; break;
+ default: return null;
+ }
+ return Element.extend(element);
+ }
+
+ Object.extend(methods, {
+ stopPropagation: function() { this.cancelBubble = true },
+ preventDefault: function() { this.returnValue = false },
+ inspect: function() { return '[object Event]' }
+ });
+
+ Event.extend = function(event, element) {
+ if (!event) return false;
+ if (event._extendedByPrototype) return event;
+
+ event._extendedByPrototype = Prototype.emptyFunction;
+ var pointer = Event.pointer(event);
+
+ Object.extend(event, {
+ target: event.srcElement || element,
+ relatedTarget: _relatedTarget(event),
+ pageX: pointer.x,
+ pageY: pointer.y
+ });
+
+ return Object.extend(event, methods);
+ };
+ } else {
+ Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__;
+ Object.extend(Event.prototype, methods);
+ Event.extend = Prototype.K;
+ }
+
+ function _createResponder(element, eventName, handler) {
+ var registry = Element.retrieve(element, 'prototype_event_registry');
+
+ if (Object.isUndefined(registry)) {
+ CACHE.push(element);
+ registry = Element.retrieve(element, 'prototype_event_registry', $H());
+ }
+
+ var respondersForEvent = registry.get(eventName);
+ if (Object.isUndefined(respondersForEvent)) {
+ respondersForEvent = [];
+ registry.set(eventName, respondersForEvent);
+ }
+
+ if (respondersForEvent.pluck('handler').include(handler)) return false;
+
+ var responder;
+ if (eventName.include(":")) {
+ responder = function(event) {
+ if (Object.isUndefined(event.eventName))
+ return false;
+
+ if (event.eventName !== eventName)
+ return false;
+
+ Event.extend(event, element);
+ handler.call(element, event);
+ };
+ } else {
+ if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED &&
+ (eventName === "mouseenter" || eventName === "mouseleave")) {
+ if (eventName === "mouseenter" || eventName === "mouseleave") {
+ responder = function(event) {
+ Event.extend(event, element);
+
+ var parent = event.relatedTarget;
+ while (parent && parent !== element) {
+ try { parent = parent.parentNode; }
+ catch(e) { parent = element; }
+ }
+
+ if (parent === element) return;
+
+ handler.call(element, event);
+ };
+ }
+ } else {
+ responder = function(event) {
+ Event.extend(event, element);
+ handler.call(element, event);
+ };
+ }
+ }
+
+ responder.handler = handler;
+ respondersForEvent.push(responder);
+ return responder;
+ }
+
+ function _destroyCache() {
+ for (var i = 0, length = CACHE.length; i < length; i++) {
+ Event.stopObserving(CACHE[i]);
+ CACHE[i] = null;
+ }
+ }
+
+ var CACHE = [];
+
+ if (Prototype.Browser.IE)
+ window.attachEvent('onunload', _destroyCache);
+
+ if (Prototype.Browser.WebKit)
+ window.addEventListener('unload', Prototype.emptyFunction, false);
+
+
+ var _getDOMEventName = Prototype.K;
+
+ if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) {
+ _getDOMEventName = function(eventName) {
+ var translations = { mouseenter: "mouseover", mouseleave: "mouseout" };
+ return eventName in translations ? translations[eventName] : eventName;
+ };
+ }
+
+ function observe(element, eventName, handler) {
+ element = $$(element);
+
+ var responder = _createResponder(element, eventName, handler);
+
+ if (!responder) return element;
+
+ if (eventName.include(':')) {
+ if (element.addEventListener)
+ element.addEventListener("dataavailable", responder, false);
+ else {
+ element.attachEvent("ondataavailable", responder);
+ element.attachEvent("onfilterchange", responder);
+ }
+ } else {
+ var actualEventName = _getDOMEventName(eventName);
+
+ if (element.addEventListener)
+ element.addEventListener(actualEventName, responder, false);
+ else
+ element.attachEvent("on" + actualEventName, responder);
+ }
+
+ return element;
+ }
+
+ function stopObserving(element, eventName, handler) {
+ element = $$(element);
+
+ var registry = Element.retrieve(element, 'prototype_event_registry');
+
+ if (Object.isUndefined(registry)) return element;
+
+ if (eventName && !handler) {
+ var responders = registry.get(eventName);
+
+ if (Object.isUndefined(responders)) return element;
+
+ responders.each( function(r) {
+ Element.stopObserving(element, eventName, r.handler);
+ });
+ return element;
+ } else if (!eventName) {
+ registry.each( function(pair) {
+ var eventName = pair.key, responders = pair.value;
+
+ responders.each( function(r) {
+ Element.stopObserving(element, eventName, r.handler);
+ });
+ });
+ return element;
+ }
+
+ var responders = registry.get(eventName);
+
+ if (!responders) return;
+
+ var responder = responders.find( function(r) { return r.handler === handler; });
+ if (!responder) return element;
+
+ var actualEventName = _getDOMEventName(eventName);
+
+ if (eventName.include(':')) {
+ if (element.removeEventListener)
+ element.removeEventListener("dataavailable", responder, false);
+ else {
+ element.detachEvent("ondataavailable", responder);
+ element.detachEvent("onfilterchange", responder);
+ }
+ } else {
+ if (element.removeEventListener)
+ element.removeEventListener(actualEventName, responder, false);
+ else
+ element.detachEvent('on' + actualEventName, responder);
+ }
+
+ registry.set(eventName, responders.without(responder));
+
+ return element;
+ }
+
+ function fire(element, eventName, memo, bubble) {
+ element = $$(element);
+
+ if (Object.isUndefined(bubble))
+ bubble = true;
+
+ if (element == document && document.createEvent && !element.dispatchEvent)
+ element = document.documentElement;
+
+ var event;
+ if (document.createEvent) {
+ event = document.createEvent('HTMLEvents');
+ event.initEvent('dataavailable', true, true);
+ } else {
+ event = document.createEventObject();
+ event.eventType = bubble ? 'ondataavailable' : 'onfilterchange';
+ }
+
+ event.eventName = eventName;
+ event.memo = memo || { };
+
+ if (document.createEvent)
+ element.dispatchEvent(event);
+ else
+ element.fireEvent(event.eventType, event);
+
+ return Event.extend(event);
+ }
+
+
+ Object.extend(Event, Event.Methods);
+
+ Object.extend(Event, {
+ fire: fire,
+ observe: observe,
+ stopObserving: stopObserving
+ });
+
+ Element.addMethods({
+ fire: fire,
+
+ observe: observe,
+
+ stopObserving: stopObserving
+ });
+
+ Object.extend(document, {
+ fire: fire.methodize(),
+
+ observe: observe.methodize(),
+
+ stopObserving: stopObserving.methodize(),
+
+ loaded: false
+ });
+
+ if (window.Event) Object.extend(window.Event, Event);
+ else window.Event = Event;
+})();
+
+(function() {
+ /* Support for the DOMContentLoaded event is based on work by Dan Webb,
+ Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */
+
+ var timer;
+
+ function fireContentLoadedEvent() {
+ if (document.loaded) return;
+ if (timer) window.clearTimeout(timer);
+ document.loaded = true;
+ document.fire('dom:loaded');
+ }
+
+ function checkReadyState() {
+ if (document.readyState === 'complete') {
+ document.stopObserving('readystatechange', checkReadyState);
+ fireContentLoadedEvent();
+ }
+ }
+
+ function pollDoScroll() {
+ try { document.documentElement.doScroll('left'); }
+ catch(e) {
+ timer = pollDoScroll.defer();
+ return;
+ }
+ fireContentLoadedEvent();
+ }
+
+ if (document.addEventListener) {
+ document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false);
+ } else {
+ document.observe('readystatechange', checkReadyState);
+ if (window == top)
+ timer = pollDoScroll.defer();
+ }
+
+ Event.observe(window, 'load', fireContentLoadedEvent);
+})();
+
+Element.addMethods();
+
+/*------------------------------- DEPRECATED -------------------------------*/
+
+Hash.toQueryString = Object.toQueryString;
+
+var Toggle = { display: Element.toggle };
+
+Element.Methods.childOf = Element.Methods.descendantOf;
+
+var Insertion = {
+ Before: function(element, content) {
+ return Element.insert(element, {before:content});
+ },
+
+ Top: function(element, content) {
+ return Element.insert(element, {top:content});
+ },
+
+ Bottom: function(element, content) {
+ return Element.insert(element, {bottom:content});
+ },
+
+ After: function(element, content) {
+ return Element.insert(element, {after:content});
+ }
+};
+
+var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
+
+var Position = {
+ includeScrollOffsets: false,
+
+ prepare: function() {
+ this.deltaX = window.pageXOffset
+ || document.documentElement.scrollLeft
+ || document.body.scrollLeft
+ || 0;
+ this.deltaY = window.pageYOffset
+ || document.documentElement.scrollTop
+ || document.body.scrollTop
+ || 0;
+ },
+
+ within: function(element, x, y) {
+ if (this.includeScrollOffsets)
+ return this.withinIncludingScrolloffsets(element, x, y);
+ this.xcomp = x;
+ this.ycomp = y;
+ this.offset = Element.cumulativeOffset(element);
+
+ return (y >= this.offset[1] &&
+ y < this.offset[1] + element.offsetHeight &&
+ x >= this.offset[0] &&
+ x < this.offset[0] + element.offsetWidth);
+ },
+
+ withinIncludingScrolloffsets: function(element, x, y) {
+ var offsetcache = Element.cumulativeScrollOffset(element);
+
+ this.xcomp = x + offsetcache[0] - this.deltaX;
+ this.ycomp = y + offsetcache[1] - this.deltaY;
+ this.offset = Element.cumulativeOffset(element);
+
+ return (this.ycomp >= this.offset[1] &&
+ this.ycomp < this.offset[1] + element.offsetHeight &&
+ this.xcomp >= this.offset[0] &&
+ this.xcomp < this.offset[0] + element.offsetWidth);
+ },
+
+ overlap: function(mode, element) {
+ if (!mode) return 0;
+ if (mode == 'vertical')
+ return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
+ element.offsetHeight;
+ if (mode == 'horizontal')
+ return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
+ element.offsetWidth;
+ },
+
+
+ cumulativeOffset: Element.Methods.cumulativeOffset,
+
+ positionedOffset: Element.Methods.positionedOffset,
+
+ absolutize: function(element) {
+ Position.prepare();
+ return Element.absolutize(element);
+ },
+
+ relativize: function(element) {
+ Position.prepare();
+ return Element.relativize(element);
+ },
+
+ realOffset: Element.Methods.cumulativeScrollOffset,
+
+ offsetParent: Element.Methods.getOffsetParent,
+
+ page: Element.Methods.viewportOffset,
+
+ clone: function(source, target, options) {
+ options = options || { };
+ return Element.clonePosition(target, source, options);
+ }
+};
+
+/*--------------------------------------------------------------------------*/
+
+if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
+ function iter(name) {
+ return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
+ }
+
+ instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
+ function(element, className) {
+ className = className.toString().strip();
+ var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
+ return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
+ } : function(element, className) {
+ className = className.toString().strip();
+ var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
+ if (!classNames && !className) return elements;
+
+ var nodes = $$(element).getElementsByTagName('*');
+ className = ' ' + className + ' ';
+
+ for (var i = 0, child, cn; child = nodes[i]; i++) {
+ if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
+ (classNames && classNames.all(function(name) {
+ return !name.toString().blank() && cn.include(' ' + name + ' ');
+ }))))
+ elements.push(Element.extend(child));
+ }
+ return elements;
+ };
+
+ return function(className, parentElement) {
+ return $$(parentElement || document.body).getElementsByClassName(className);
+ };
+}(Element.Methods);
+
+/*--------------------------------------------------------------------------*/
+
+Element.ClassNames = Class.create();
+Element.ClassNames.prototype = {
+ initialize: function(element) {
+ this.element = $$(element);
+ },
+
+ _each: function(iterator) {
+ this.element.className.split(/\s+/).select(function(name) {
+ return name.length > 0;
+ })._each(iterator);
+ },
+
+ set: function(className) {
+ this.element.className = className;
+ },
+
+ add: function(classNameToAdd) {
+ if (this.include(classNameToAdd)) return;
+ this.set($A(this).concat(classNameToAdd).join(' '));
+ },
+
+ remove: function(classNameToRemove) {
+ if (!this.include(classNameToRemove)) return;
+ this.set($A(this).without(classNameToRemove).join(' '));
+ },
+
+ toString: function() {
+ return $A(this).join(' ');
+ }
+};
+
+Object.extend(Element.ClassNames.prototype, Enumerable);
+
+/*--------------------------------------------------------------------------*/
--- /dev/null
+//Requires include default.js\r
+try { var _test_relItems = __include_default; }\r
+catch(e) {\r
+ alert("relItems.js : Include '_system/js/default.js' é obrigatório");\r
+}\r
+\r
+var __include_relItems = true;\r
+\r
+var HtmlEditor_ROOT = "../inc/htmleditor/";\r
+\r
+unse = function (str) {\r
+ if(str != ""){\r
+ var arrAux = str.split("###");\r
+ var arrAux2 = new Array();\r
+ \r
+ for(var x=0;x<arrAux.length;x++){\r
+ arrAux2[x] = arrAux[x].split("$$$");\r
+ }\r
+ \r
+ return arrAux2\r
+ } else {\r
+ var arrAux = new Array();\r
+ return arrAux;\r
+ }\r
+}\r
+se = function (arr) {\r
+ if(arr.length > 0){\r
+ var str = "";\r
+ \r
+ for(var x=0;x<arr.length;x++){\r
+ var aux = arr[x];\r
+ \r
+ str += aux.join("$$$");\r
+ if((x+1) < arr.length){\r
+ str += "###";\r
+ }\r
+ }\r
+ \r
+ return str;\r
+ } else {\r
+ return "";\r
+ }\r
+}\r
+array_search = function(arr,needle){\r
+ for(var x=0;x<arr.length;x++){\r
+ if(arr[x][0] == needle[0]){\r
+ return true;\r
+ }\r
+ }\r
+ return false;\r
+}\r
+//\r
+function relItem(id,id_hidden,id_td_result,id_td_rel,is_static){\r
+ this.id = id;//nome do objeto, id, referencia a ele mesmo\r
+ \r
+ this.arrSearch = new Array();\r
+ this.arrRel = new Array();\r
+ this.hidden = document.getElementById(id_hidden);\r
+ this.td_result = document.getElementById(id_td_result);\r
+ this.td_rel = document.getElementById(id_td_rel);\r
+ \r
+ this.is_static = false;\r
+ if(is_static){\r
+ this.is_static = true;\r
+ }\r
+ \r
+ this.returnFromSearch = function (html) {\r
+ this.arrSearch = unse(html);\r
+ //alert(arrSearch);\r
+ if(this.arrSearch.length > 0){\r
+ this.feedResult();\r
+ } else {\r
+ this.clearSearch();\r
+ }\r
+ }\r
+ this.getDoRelationButton = function (tag_name) {\r
+ var divButton = document.createElement("div");\r
+ var html = '<table cellspacing="0" cellpadding="0" width="100%" border="0"><tr><td align="right">';\r
+ html += '<span src="../../../" onclick="javascript: '+this.id+'.doRelationWithResult(\''+tag_name+'\');" style="cursor:pointer;"><img src="../img/buttons/relate.jpg" width="80" height="22"/></span>';\r
+ html += '</td></tr></table>';\r
+ divButton.innerHTML = html;\r
+ return divButton;\r
+ }\r
+ this.getUndoRelationButton = function (tag_name) {\r
+ var divButton = document.createElement("div");\r
+ var html = '<table cellspacing="0" cellpadding="0" width="100%" border="0"><tr><td align="right">';\r
+ html += '<span src="../../../" onclick="javascript: '+this.id+'.undoRelationWithResult(\''+tag_name+'\');" style="cursor:pointer;"><img src="../img/buttons/unrelate.jpg" width="97" height="22"/></span>';\r
+ html += '</td></tr></table>';\r
+ divButton.innerHTML = html;\r
+ return divButton;\r
+ }\r
+ this.clearSearch = function () {\r
+ this.arrSearch = new Array();\r
+ this.td_result.innerHTML = "Nenhum item encontrado.";\r
+ }\r
+ this.feedResult = function () {\r
+ var tag_name = this.td_result.id+"_result";//da nome aos check box para relacionamento\r
+ this.td_result.innerHTML = "";\r
+ \r
+ this.td_result.appendChild(this.getDoRelationButton(tag_name));\r
+ \r
+ var divParent = document.createElement("div");\r
+ divParent.style.background = "#FFFFFF";\r
+ divParent.style.width = "100%";\r
+ //divParent.style.height = "150px";\r
+ divParent.innerHTML = " ";\r
+ \r
+ var bg = "#FFFFFF";\r
+ for(var x=0;x<this.arrSearch.length;x++){\r
+ var divItem = document.createElement("div");\r
+ divItem.style.width = "100%";\r
+ \r
+ var w = 100/(this.arrSearch[x].length-1);\r
+ w = 100;\r
+ \r
+ switch(bg){\r
+ case "#FFFFFF":\r
+ bg = "#F9F9F9";\r
+ break;\r
+ case "#F9F9F9":\r
+ bg = "#F4F4F4";\r
+ break;\r
+ case "#F4F4F4":\r
+ bg = "#FFFFFF";\r
+ break;\r
+ }\r
+ \r
+ var tableItem = '<table cellspacing="0" cellpadding="0" width="100%" border="0">';\r
+ tableItem += '<tr style="background:'+bg+';">';\r
+ tableItem += '<td width="20">';\r
+ tableItem += '<input type="checkbox" value="'+x+'" name="'+tag_name+'" id="'+tag_name+x+'" />';\r
+ tableItem += '</td><td width="'+w+'%" align="left" style="cursor:pointer;" onclick="javascript: document.getElementById(\''+tag_name+x+'\').checked = !(document.getElementById(\''+tag_name+x+'\').checked);">';\r
+ //tableItem += '<a href="javascript: document.getElementById(\'result_'+id+'\').checked = true;">'+this.arrSearch[x][1]+'</a>';\r
+ tableItem += this.arrSearch[x][1];\r
+ tableItem += '</td>';\r
+ \r
+ for(var y=2;y<this.arrSearch[x].length;y++){\r
+ tableItem += '<td align="right">';\r
+ tableItem += this.arrSearch[x][y];\r
+ tableItem += '</td>';\r
+ }\r
+ tableItem += '</tr>';\r
+ divItem.innerHTML = tableItem;\r
+ divParent.appendChild(divItem);\r
+ }\r
+ this.td_result.appendChild(divParent);\r
+ this.td_result.appendChild(this.getDoRelationButton(tag_name));\r
+ }\r
+ this.feedRel = function () {\r
+ var tag_name = this.td_rel.id+"_result";\r
+ \r
+ if(this.arrRel.length > 0){\r
+ this.td_rel.innerHTML = "";\r
+ if(!this.is_static){\r
+ this.td_rel.appendChild(this.getUndoRelationButton(tag_name));\r
+ }\r
+ var divParent = document.createElement("div");\r
+ divParent.style.background = "#FFFFFF";\r
+ divParent.style.width = "100%";\r
+ //divParent.style.height = "150px";\r
+ divParent.innerHTML = " ";\r
+ \r
+ var bg = "#FFFFFF";\r
+ var extra = ' style="cursor:pointer;" onclick="javascript: document.getElementById(\''+tag_name+x+'\').checked = !(document.getElementById(\''+tag_name+x+'\').checked);" ';\r
+ var disabled = '';\r
+ if(this.is_static){\r
+ disabled = ' checked disabled ';\r
+ extra = '';\r
+ }\r
+ for(var x=0;x<this.arrRel.length;x++){\r
+ var divItem = document.createElement("div");\r
+ divItem.style.width = "100%";\r
+ \r
+ var w = 100/(this.arrRel[x].length-1);\r
+ w = 100;\r
+ \r
+ switch(bg){\r
+ case "#FFFFFF":\r
+ bg = "#F9F9F9";\r
+ break;\r
+ case "#F9F9F9":\r
+ bg = "#F4F4F4";\r
+ break;\r
+ case "#F4F4F4":\r
+ bg = "#FFFFFF";\r
+ break;\r
+ }\r
+ \r
+ var tableItem = '<table cellspacing="0" cellpadding="0" width="100%" border="0">';\r
+ tableItem += '<tr style="background:'+bg+';">';\r
+ tableItem += '<td width="20">';\r
+ tableItem += '<input type="checkbox" value="'+x+'" name="'+tag_name+'" id="'+tag_name+x+'" '+disabled+'/>';\r
+ tableItem += '</td><td width="'+w+'%" align="left" '+extra+'>';\r
+ //tableItem += '<a href="javascript: document.getElementById(\'result_'+id+'\').checked = true;">'+this.arrRel[x][1]+'</a>';\r
+ tableItem += this.arrRel[x][1];\r
+ tableItem += '</td>';\r
+ \r
+ // for(var y=2;y<this.arrRel[x].length;y++){\r
+ // tableItem += '<td width="'+w+'%" align="left">';\r
+ // tableItem += this.arrRel[x][y];\r
+ // tableItem += '</td>';\r
+ // }\r
+ tableItem += '</tr>';\r
+ divItem.innerHTML = tableItem;\r
+ divParent.appendChild(divItem);\r
+ }\r
+ \r
+ this.td_rel.appendChild(divParent);\r
+ if(!this.is_static){\r
+ this.td_rel.appendChild(this.getUndoRelationButton(tag_name));\r
+ }\r
+ } else {\r
+ this.td_rel.innerHTML = "Nenhum item relacionado.";\r
+ }\r
+ }\r
+ this.doRelationWithResult = function (tag_name) {\r
+ var elements = document.getElementsByName(tag_name);\r
+ var arrChecked = new Array();\r
+ for(var x=0;x<elements.length;x++){\r
+ if(elements[x].checked){\r
+ arrChecked.push(this.arrSearch[elements[x].value]);\r
+ }\r
+ }\r
+ \r
+ if(arrChecked.length > 0){\r
+ this.addIds(arrChecked);\r
+ this.feedRel();\r
+ } else {\r
+ alert("Selecione ao menus um item para relacionar.");\r
+ }\r
+ }\r
+ this.undoRelationWithResult = function (tag_name) {\r
+ var elements = document.getElementsByName(tag_name);\r
+ var arrChecked = new Array();\r
+ for(var x=0;x<elements.length;x++){\r
+ if(elements[x].checked){\r
+ arrChecked.push(elements[x].value);\r
+ }\r
+ }\r
+ \r
+ if(arrChecked.length > 0){\r
+ this.removeIds(arrChecked);\r
+ this.feedRel();\r
+ } else {\r
+ alert("Selecione ao menus um item para relacionar.");\r
+ }\r
+ }\r
+ this.fromRelHidden = function () {\r
+ this.arrRel = unse(this.hidden.value);\r
+ }\r
+ this.toRelHidden = function(){\r
+ this.hidden.value = se(this.arrRel);\r
+ }\r
+ this.addIds = function (arr){\r
+ this.fromRelHidden();\r
+ \r
+ for(var x=0;x<arr.length;x++){\r
+ if(!array_search(this.arrRel,arr[x])) {\r
+ this.arrRel.push(arr[x]);\r
+ }\r
+ }\r
+ \r
+ this.toRelHidden();\r
+ }\r
+ this.removeIds = function (arr) {\r
+ this.fromRelHidden();\r
+ \r
+ var arrAux = new Array();\r
+ for(var y=0;y<this.arrRel.length;y++){\r
+ var adicionar = true;\r
+ for(var x=0;x<arr.length;x++){\r
+ if(arr[x] == y){\r
+ adicionar = false;\r
+ }\r
+ }\r
+ if(adicionar){\r
+ arrAux.push(this.arrRel[y]);\r
+ }\r
+ }\r
+ this.arrRel = arrAux;\r
+ \r
+ this.toRelHidden();\r
+ }\r
+ \r
+ this.fromRelHidden();\r
+ this.feedRel();\r
+}\r
+//alert("i was loaded");
\ No newline at end of file
--- /dev/null
+//Common\r
+function showLoading() {\r
+ $$('conteudo').innerHTML = '<center><div class="padding: 10px;"><img src="../img/loading.gif"></div></center>'; \r
+}\r
+\r
+function ajaxGet(tmp_url) {\r
+ var arr = tmp_url.split("?");\r
+ \r
+ tmp_url = arr[0] + "?menu=" + menu;\r
+ \r
+ if (arr[1] != undefined) {\r
+ tmp_url += "&" + arr[1];\r
+ }\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ $$('conteudo').innerHTML = this.html;\r
+ \r
+ debugHtml(this.html);\r
+ \r
+ this.runJS(this.html);\r
+ }\r
+ a.get(tmp_url);\r
+ \r
+ showLoading();\r
+}\r
+\r
+function debugHtml(tmp_html) {\r
+ if ($$('box_html')) {\r
+ $$('box_html').innerHTML = "<pre>" + tmp_html.replace(/</g, "<").replace(/>/g, ">") + "\n<b>" + (new String(Math.round((tmp_html.length / 1024) * 100) / 100)).replace(".", ",") + " Kb</b></pre>";\r
+ }\r
+}\r
+\r
+function listOrder(tmp_order) {\r
+ $$('input_order').value = tmp_order;\r
+ \r
+ listSubmitFilters();\r
+}\r
+\r
+function listPage(tmp_page) {\r
+ $$('input_page').value = tmp_page;\r
+ \r
+ listSubmitFilters();\r
+}\r
+\r
+\r
+function listInsert() {\r
+ ajaxGet('form/form.php?routine=insert'); \r
+}\r
+\r
+function listUpdate(tmp_id) {\r
+ ajaxGet('form/form.php?routine=update&id=' + tmp_id); \r
+}\r
+\r
+//filters\r
+function showHideFilters() {\r
+ if ($$('div_filtros').style.display == '') {\r
+ $$('img_filter').src = '../img/buttons/filter.jpg';\r
+ $$('div_filtros').style.display = 'none';\r
+ } else {\r
+ $$('img_filter').src = '../img/buttons/filter_disabled.jpg';\r
+ $$('div_filtros').style.display = '';\r
+ }\r
+}\r
+\r
+function preListSubmitFilters() {\r
+ $$('input_page').value = "";\r
+ \r
+ listSubmitFilters();\r
+}\r
+\r
+function listSubmitFilters() { \r
+ if (f.send('frm_filters', true)) {\r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ $$('conteudo').innerHTML = this.html;\r
+ \r
+ debugHtml(this.html);\r
+ \r
+ this.runJS(this.html);\r
+ }\r
+ a.sendForm('frm_filters');\r
+ \r
+ showLoading();\r
+ }\r
+}\r
+\r
+\r
+//over list\r
+function listOverOut(tmp_acao, tmp_i) {\r
+ var tds = $$('tr_' + tmp_i).getElementsByTagName('td');\r
+ var obj;\r
+ var css = '';\r
+ var i;\r
+ var class_name = 'td' + (2 - (tmp_i % 2));\r
+ \r
+ if (delete_enabled) {\r
+ i = 1;\r
+ if ($$('chk_' + tmp_i).checked) {\r
+ class_name = 'td3';\r
+ }\r
+ } else {\r
+ i = 0;\r
+ }\r
+ \r
+ tds[i].className = class_name;\r
+ \r
+ for (; i < (tds.length); i++) {\r
+ obj = tds[i];\r
+ \r
+ if (css == '') {\r
+ switch (tmp_acao) {\r
+ case "over":\r
+ css = obj.className.replace("-over", "") + '-over';\r
+ break;\r
+ case "out":\r
+ css = obj.className.replace("-over", "");\r
+ break;\r
+ } \r
+ }\r
+ \r
+ obj.className = css;\r
+ }\r
+}\r
+\r
+//checks\r
+function check(tmp_obj) {\r
+ var i = 1;\r
+ var r;\r
+ \r
+ if (tmp_obj.checked) {\r
+ r = true;\r
+ } else {\r
+ r = false;\r
+ }\r
+ \r
+ while ($$('chk_' + i)) {\r
+ $$('chk_' + i).checked = r;\r
+ \r
+ i++;\r
+ }\r
+ \r
+ checkMostrar();\r
+}\r
+\r
+function checkMostrar() {\r
+ var i = 1;\r
+ var ok = false;\r
+ \r
+ while ($$('chk_' + i)) {\r
+ if ($$('chk_' + i).checked) {\r
+ ok = true;\r
+ }\r
+ \r
+ listOverOut('out', i); \r
+ \r
+ i++;\r
+ }\r
+ \r
+ if (ok) {\r
+ $$('div_botao_excluir').style.display = '';\r
+ } else {\r
+ $$('div_botao_excluir').style.display = 'none';\r
+ }\r
+}\r
+\r
+function checkExcluir() {\r
+ if (confirm("Deseja realmente excluir este(s) item(ns)?")) {\r
+ if (f.send('frm_list', true)) {\r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ $$('conteudo').innerHTML = this.html;\r
+ \r
+ debugHtml(this.html);\r
+ \r
+ this.runJS(this.html);\r
+ }\r
+ a.sendForm('frm_list');\r
+ }\r
+ }\r
+}\r
+\r
+//buttons\r
+function listButton(tmp_name) {\r
+ var ifr = createHiddenIframe('ifr_button_' + tmp_name, 'button_bar');\r
+ var cfg = new Array();\r
+ \r
+ var onload = function () {\r
+ //Removes iframe element\r
+ //setTimeout(function () { removeElement('ifr_button_' + tmp_name); alert("remove: " + 'ifr_button_' + tmp_name); }, 250); \r
+ }\r
+ addEvent(ifr, "load", onload);\r
+ \r
+ cfg["target"] = $$('frm_filters').target;\r
+ cfg["action"] = $$('frm_filters').action;\r
+ \r
+ $$('frm_filters').target = "ifr_button_" + tmp_name;\r
+ $$('frm_filters').action = "form/list.php?routine=list_button&name=" + tmp_name;\r
+ \r
+ if (f.send('frm_filters', true)) {\r
+ $$('frm_filters').submit();\r
+ } else {\r
+ //setTimeout(function () { removeElement('ifr_button_' + tmp_name); alert("remove: " + 'ifr_button_' + tmp_name); }, 250);\r
+ }\r
+ \r
+ $$('frm_filters').setAttribute('target', cfg["target"]);\r
+ $$('frm_filters').setAttribute('action', cfg["action"]);\r
+}\r
+\r
+//Form\r
+var customPrePost;\r
+function prePost() {\r
+ try {\r
+ customPrePost();\r
+ } catch(e) { alert("Erro - prePost() : " + e); }\r
+}\r
+\r
+function formSubmit() {\r
+ if (f.send('frm_form', true)) {\r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ $$('conteudo').innerHTML = this.html;\r
+ \r
+ debugHtml(this.html);\r
+ \r
+ this.runJS(this.html);\r
+ }\r
+ a.sendForm('frm_form');\r
+ \r
+ showLoading();\r
+ }\r
+}\r
+\r
+//Aux functions\r
+function createHiddenIframe(tmp_id, tmp_id_parent) { \r
+ var iframe = document.createElement("iframe");\r
+ iframe.setAttribute("id",tmp_id);\r
+ iframe.setAttribute("name",tmp_id);\r
+ if (!$$('box_html')) {\r
+ iframe.setAttribute("width","0");\r
+ iframe.setAttribute("height","0");\r
+ iframe.setAttribute("border","0");\r
+ iframe.setAttribute("style","width: 0; height: 0; border: none; visibility: hidden; display: none;");\r
+ }\r
+ $$(tmp_id_parent).parentNode.appendChild(iframe);\r
+ window.frames[tmp_id].name = tmp_id; //Ie sux\r
+ \r
+ return iframe;\r
+}\r
+\r
+function screenLock(tmp_lock) {\r
+ if (tmp_lock == null) { tmp_lock = false; }\r
+ \r
+ if (!$$('div_lock')) {\r
+ var div = document.createElement('div');\r
+ div.setAttribute('id', 'div_lock');\r
+ div.setAttribute('style', 'position: absolute; top: 0; left: 0; z-index: 90; width: 100%; height: 500px; background-color: #000; -moz-opacity:0.6;opacity:.60;filter:alpha(opacity=60);');\r
+ div.style.position = 'absolute';\r
+ div.style.background = '#000';\r
+ div.style.filter = 'alpha(opacity=60)';\r
+ div.innerHTML = ' ';\r
+ document.getElementsByTagName('body')[0].appendChild(div);\r
+ }\r
+ \r
+ if (tmp_lock) {\r
+ $$('div_lock').style.display = '';\r
+\r
+ addEvent(window, 'scroll', screenLock_scroll);\r
+ screenLock_scroll();\r
+ } else {\r
+ $$('div_lock').style.display = 'none';\r
+ \r
+ removeEvent(window, 'scroll', screenLock_scroll);\r
+ }\r
+}\r
+\r
+function screenLock_scroll(e) {\r
+ var obj = $$('div_lock');\r
+ \r
+ if (obj) {\r
+ var pos = new WindowPosition();\r
+\r
+ obj.style.left = pos.x + "px";\r
+ obj.style.top = pos.y + "px";\r
+ obj.style.width = pos.w + "px";\r
+ obj.style.height = pos.h + "px";\r
+ }\r
+}\r
+\r
+function setCSS(tmp_css, tmp_id) {\r
+ var s;\r
+ \r
+ if (!tmp_id) {\r
+ tmp_id = "css_" + Math.round(Math.random() * 10000); \r
+ }\r
+ \r
+ if (document.all) {\r
+ if ($$(tmp_id)) {\r
+ s = $$(tmp_id);\r
+ } else {\r
+ s = document.createStyleSheet();\r
+ }\r
+ s.cssText = tmp_css;\r
+ } else {\r
+ if ($$(tmp_id)) {\r
+ s = $$(tmp_id);\r
+ } else {\r
+ s = document.createElement('style');\r
+ s.type = 'text/css';\r
+ }\r
+ s.innerHTML = tmp_css;\r
+ }\r
+ \r
+ if (!$$(tmp_id)) {\r
+ try {\r
+ document.getElementsByTagName('head')[0].appendChild(s);\r
+ } catch (e) { }\r
+ }\r
+}\r
+\r
+//Upload\r
+function uploadSubmit(tmp_name) {\r
+ var iframe\r
+ var onload;\r
+ var configs = new Array();\r
+ var div;\r
+ var input;\r
+ \r
+ //Verify if input file is not empty\r
+ div = $$(tmp_name + '_div_input');\r
+ input = div.getElementsByTagName("input")[0];\r
+ \r
+ if (input.value != '') {\r
+ //Create iframe element\r
+ iframe = createHiddenIframe('ifr_tmp', 'frm_form');\r
+ onload = function () {\r
+ uploadList(tmp_name);\r
+ \r
+ $$(tmp_name + '_div_loading').style.display = 'none';\r
+ \r
+ //Removes iframe element\r
+ if (!$$('box_html')) {\r
+ setTimeout(function () { removeElement($$('ifr_tmp')); }, 250); \r
+ }\r
+ }\r
+ addEvent($$('ifr_tmp'), "load", onload);\r
+ \r
+ $$(tmp_name + '_div_input').style.display = 'none';\r
+ $$(tmp_name + '_div_loading').style.display = '';\r
+ \r
+ //Save configuration\r
+ configs["target"] = $$('frm_form').target;\r
+ configs["action"] = $$('frm_form').action;\r
+ configs["method"] = $$('frm_form').method;\r
+ configs["enctype"] = $$('frm_form').enctype;\r
+ configs["encoding"] = $$('frm_form').encoding;\r
+ \r
+ //Config form element\r
+ $$('frm_form').setAttribute("target", "ifr_tmp");\r
+ $$('frm_form').setAttribute("action", 'form/routines.php?menu=' + menu + '&routine=' + routine + '&routine_field=upload&name=' + tmp_name + "&tmp_id=" + tmp_id + "&id=" + id + "&random=" + Math.round(Math.random() * 999999));\r
+ $$('frm_form').setAttribute("method", "post");\r
+ $$('frm_form').setAttribute("enctype", "multipart/form-data");\r
+ $$('frm_form').setAttribute("encoding", "multipart/form-data");\r
+ \r
+ $$('frm_form').submit();\r
+ \r
+ //Remember old configuration\r
+ $$('frm_form').setAttribute("target", configs["target"]);\r
+ $$('frm_form').setAttribute("action", configs["action"]);\r
+ $$('frm_form').setAttribute("method", configs["method"]);\r
+ $$('frm_form').setAttribute("enctype", configs["enctype"]);\r
+ $$('frm_form').setAttribute("encoding", configs["encoding"]);\r
+ }\r
+}\r
+\r
+function uploadList(tmp_name) {\r
+ $$(tmp_name + '_div_loading').style.display = '';\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () {\r
+ $$(tmp_name + '_div_list').innerHTML = this.html;\r
+ \r
+ debugHtml(this.html);\r
+ \r
+ this.runJS(this.html);\r
+ \r
+ $$(tmp_name + '_div_loading').style.display = 'none';\r
+ }\r
+ a.get('form/routines.php?menu=' + menu + '&routine=' + routine + '&routine_field=list&name=' + tmp_name + "&tmp_id=" + tmp_id + "&id=" + id);\r
+}\r
+\r
+function uploadDelete(tmp_name, tmp_n) {\r
+ $$(tmp_name + '_div_loading').style.display = '';\r
+ \r
+ var a = new Ajax();\r
+ a.onLoad = function () { \r
+ debugHtml(this.html);\r
+ \r
+ this.runJS(this.html);\r
+ \r
+ $$(tmp_name + '_div_loading').style.display = 'none';\r
+ }\r
+ a.get('form/routines.php?menu=' + menu + '&routine=' + routine + '&routine_field=delete&name=' + tmp_name + "&tmp_id=" + tmp_id + "&id=" + id + "&n=" + tmp_n);\r
+}\r
+\r
+//Ativo\r
+function ativoSwap(tmp_obj, tmp_field_name, tmp_id) {\r
+ var container = tmp_obj.parentNode;\r
+ var a = new Ajax();\r
+ \r
+ container.innerHTML = '<img src=\'../img/icons/time.gif\'>';\r
+ \r
+ a.onLoad = function () {\r
+ container.innerHTML = this.html;\r
+ }\r
+ a.get('form/routines.php?menu=' + menu + '&routine=ativo&name=' + tmp_field_name + "&id=" + tmp_id + "&rnd=" + rnd);\r
+}\r
+\r
+//Ordem\r
+function orderSwap(tmp_name, tmp_id, tmp_direction) {\r
+ var cfg = Array();\r
+ var a = new Ajax();\r
+ \r
+ if (f.send('frm_filters', true)) {\r
+ cfg["action"] = $$('frm_filters').action;\r
+ \r
+ $$('input_extra').value = tmp_id + "#" + tmp_direction;\r
+ \r
+ $$('frm_filters').action = 'form/routines.php?menu=' + menu + '&routine_field=order&name=' + tmp_name + "&tmp_id=" + tmp_id + "&direction=" + tmp_direction;\r
+ \r
+ a.onLoad = function () { \r
+ listSubmitFilters();\r
+ }\r
+ a.sendForm('frm_filters');\r
+ \r
+ $$('input_extra').value = '';\r
+ \r
+ $$('frm_filters').setAttribute('action', cfg["action"]);\r
+ }\r
+}\r
+\r
+function statusSwap(tmp_obj, tmp_field_name, tmp_id) {\r
+ var container = tmp_obj.parentNode;\r
+ var a = new Ajax();\r
+ \r
+ container.innerHTML = '<img src=\'../img/icons/time.gif\'>';\r
+ \r
+ a.onLoad = function () {\r
+ container.innerHTML = this.html;\r
+ }\r
+ a.get('../../_config/exeptions/routines/routines.php?menu=' + menu + '&routine=status&name=' + tmp_field_name + "&id=" + tmp_id + "&rnd=" + rnd);\r
+}\r
+function zoom(tmp_path,tmp_width,tmp_height){\r
+ var p = new Popup(tmp_width,tmp_height);\r
+ p.position = "fixed";\r
+ p.overflow = "hidden";\r
+ p.open("zoom.php?path="+tmp_path);\r
+}
\ No newline at end of file
--- /dev/null
+// script.aculo.us builder.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+var Builder = {
+ NODEMAP: {
+ AREA: 'map',
+ CAPTION: 'table',
+ COL: 'table',
+ COLGROUP: 'table',
+ LEGEND: 'fieldset',
+ OPTGROUP: 'select',
+ OPTION: 'select',
+ PARAM: 'object',
+ TBODY: 'table',
+ TD: 'table',
+ TFOOT: 'table',
+ TH: 'table',
+ THEAD: 'table',
+ TR: 'table'
+ },
+ // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
+ // due to a Firefox bug
+ node: function(elementName) {
+ elementName = elementName.toUpperCase();
+
+ // try innerHTML approach
+ var parentTag = this.NODEMAP[elementName] || 'div';
+ var parentElement = document.createElement(parentTag);
+ try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
+ parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
+ } catch(e) {}
+ var element = parentElement.firstChild || null;
+
+ // see if browser added wrapping tags
+ if(element && (element.tagName.toUpperCase() != elementName))
+ element = element.getElementsByTagName(elementName)[0];
+
+ // fallback to createElement approach
+ if(!element) element = document.createElement(elementName);
+
+ // abort if nothing could be created
+ if(!element) return;
+
+ // attributes (or text)
+ if(arguments[1])
+ if(this._isStringOrNumber(arguments[1]) ||
+ (arguments[1] instanceof Array) ||
+ arguments[1].tagName) {
+ this._children(element, arguments[1]);
+ } else {
+ var attrs = this._attributes(arguments[1]);
+ if(attrs.length) {
+ try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
+ parentElement.innerHTML = "<" +elementName + " " +
+ attrs + "></" + elementName + ">";
+ } catch(e) {}
+ element = parentElement.firstChild || null;
+ // workaround firefox 1.0.X bug
+ if(!element) {
+ element = document.createElement(elementName);
+ for(attr in arguments[1])
+ element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
+ }
+ if(element.tagName.toUpperCase() != elementName)
+ element = parentElement.getElementsByTagName(elementName)[0];
+ }
+ }
+
+ // text, or array of children
+ if(arguments[2])
+ this._children(element, arguments[2]);
+
+ return $$(element);
+ },
+ _text: function(text) {
+ return document.createTextNode(text);
+ },
+
+ ATTR_MAP: {
+ 'className': 'class',
+ 'htmlFor': 'for'
+ },
+
+ _attributes: function(attributes) {
+ var attrs = [];
+ for(attribute in attributes)
+ attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
+ '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'"') + '"');
+ return attrs.join(" ");
+ },
+ _children: function(element, children) {
+ if(children.tagName) {
+ element.appendChild(children);
+ return;
+ }
+ if(typeof children=='object') { // array can hold nodes and text
+ children.flatten().each( function(e) {
+ if(typeof e=='object')
+ element.appendChild(e);
+ else
+ if(Builder._isStringOrNumber(e))
+ element.appendChild(Builder._text(e));
+ });
+ } else
+ if(Builder._isStringOrNumber(children))
+ element.appendChild(Builder._text(children));
+ },
+ _isStringOrNumber: function(param) {
+ return(typeof param=='string' || typeof param=='number');
+ },
+ build: function(html) {
+ var element = this.node('div');
+ $$(element).update(html.strip());
+ return element.down();
+ },
+ dump: function(scope) {
+ if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
+
+ var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
+ "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
+ "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
+
+ tags.each( function(tag){
+ scope[tag] = function() {
+ return Builder.node.apply(Builder, [tag].concat($A(arguments)));
+ };
+ });
+ }
+};
\ No newline at end of file
--- /dev/null
+// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
+// Contributors:
+// Richard Livsey
+// Rahul Bhargava
+// Rob Wills
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// Autocompleter.Base handles all the autocompletion functionality
+// that's independent of the data source for autocompletion. This
+// includes drawing the autocompletion menu, observing keyboard
+// and mouse events, and similar.
+//
+// Specific autocompleters need to provide, at the very least,
+// a getUpdatedChoices function that will be invoked every time
+// the text inside the monitored textbox changes. This method
+// should get the text for which to provide autocompletion by
+// invoking this.getToken(), NOT by directly accessing
+// this.element.value. This is to allow incremental tokenized
+// autocompletion. Specific auto-completion logic (AJAX, etc)
+// belongs in getUpdatedChoices.
+//
+// Tokenized incremental autocompletion is enabled automatically
+// when an autocompleter is instantiated with the 'tokens' option
+// in the options parameter, e.g.:
+// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
+// will incrementally autocomplete with a comma as the token.
+// Additionally, ',' in the above example can be replaced with
+// a token array, e.g. { tokens: [',', '\n'] } which
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
+// allows smart autocompletion after linebreaks.
+
+if(typeof Effect == 'undefined')
+ throw("controls.js requires including script.aculo.us' effects.js library");
+
+var Autocompleter = { };
+Autocompleter.Base = Class.create({
+ baseInitialize: function(element, update, options) {
+ element = $$(element);
+ this.element = element;
+ this.update = $$(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
+ this.entryCount = 0;
+ this.oldElementValue = this.element.value;
+
+ if(this.setOptions)
+ this.setOptions(options);
+ else
+ this.options = options || { };
+
+ this.options.paramName = this.options.paramName || this.element.name;
+ this.options.tokens = this.options.tokens || [];
+ this.options.frequency = this.options.frequency || 0.4;
+ this.options.minChars = this.options.minChars || 1;
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
+ if(!update.style.position || update.style.position=='absolute') {
+ update.style.position = 'absolute';
+ Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ Effect.Appear(update,{duration:0.15});
+ };
+ this.options.onHide = this.options.onHide ||
+ function(element, update){ new Effect.Fade(update,{duration:0.15}) };
+
+ if(typeof(this.options.tokens) == 'string')
+ this.options.tokens = new Array(this.options.tokens);
+ // Force carriage returns as token delimiters anyway
+ if (!this.options.tokens.include('\n'))
+ this.options.tokens.push('\n');
+
+ this.observer = null;
+
+ this.element.setAttribute('autocomplete','off');
+
+ Element.hide(this.update);
+
+ Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
+ Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
+ },
+
+ show: function() {
+ if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
+ if(!this.iefix &&
+ (Prototype.Browser.IE) &&
+ (Element.getStyle(this.update, 'position')=='absolute')) {
+ new Insertion.After(this.update,
+ '<iframe id="' + this.update.id + '_iefix" '+
+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
+ 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
+ this.iefix = $$(this.update.id+'_iefix');
+ }
+ if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
+ },
+
+ fixIEOverlapping: function() {
+ Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
+ this.iefix.style.zIndex = 1;
+ this.update.style.zIndex = 2;
+ Element.show(this.iefix);
+ },
+
+ hide: function() {
+ this.stopIndicator();
+ if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
+ if(this.iefix) Element.hide(this.iefix);
+ },
+
+ startIndicator: function() {
+ if(this.options.indicator) Element.show(this.options.indicator);
+ },
+
+ stopIndicator: function() {
+ if(this.options.indicator) Element.hide(this.options.indicator);
+ },
+
+ onKeyPress: function(event) {
+ if(this.active)
+ switch(event.keyCode) {
+ case Event.KEY_TAB:
+ case Event.KEY_RETURN:
+ this.selectEntry();
+ Event.stop(event);
+ case Event.KEY_ESC:
+ this.hide();
+ this.active = false;
+ Event.stop(event);
+ return;
+ case Event.KEY_LEFT:
+ case Event.KEY_RIGHT:
+ return;
+ case Event.KEY_UP:
+ this.markPrevious();
+ this.render();
+ Event.stop(event);
+ return;
+ case Event.KEY_DOWN:
+ this.markNext();
+ this.render();
+ Event.stop(event);
+ return;
+ }
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
+
+ this.changed = true;
+ this.hasFocus = true;
+
+ if(this.observer) clearTimeout(this.observer);
+ this.observer =
+ setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
+ },
+
+ activate: function() {
+ this.changed = false;
+ this.hasFocus = true;
+ this.getUpdatedChoices();
+ },
+
+ onHover: function(event) {
+ var element = Event.findElement(event, 'LI');
+ if(this.index != element.autocompleteIndex)
+ {
+ this.index = element.autocompleteIndex;
+ this.render();
+ }
+ Event.stop(event);
+ },
+
+ onClick: function(event) {
+ var element = Event.findElement(event, 'LI');
+ this.index = element.autocompleteIndex;
+ this.selectEntry();
+ this.hide();
+ },
+
+ onBlur: function(event) {
+ // needed to make click events working
+ setTimeout(this.hide.bind(this), 250);
+ this.hasFocus = false;
+ this.active = false;
+ },
+
+ render: function() {
+ if(this.entryCount > 0) {
+ for (var i = 0; i < this.entryCount; i++)
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
+ Element.removeClassName(this.getEntry(i),"selected");
+ if(this.hasFocus) {
+ this.show();
+ this.active = true;
+ }
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+ markPrevious: function() {
+ if(this.index > 0) this.index--;
+ else this.index = this.entryCount-1;
+ this.getEntry(this.index).scrollIntoView(true);
+ },
+
+ markNext: function() {
+ if(this.index < this.entryCount-1) this.index++;
+ else this.index = 0;
+ this.getEntry(this.index).scrollIntoView(false);
+ },
+
+ getEntry: function(index) {
+ return this.update.firstChild.childNodes[index];
+ },
+
+ getCurrentEntry: function() {
+ return this.getEntry(this.index);
+ },
+
+ selectEntry: function() {
+ this.active = false;
+ this.updateElement(this.getCurrentEntry());
+ },
+
+ updateElement: function(selectedElement) {
+ if (this.options.updateElement) {
+ this.options.updateElement(selectedElement);
+ return;
+ }
+ var value = '';
+ if (this.options.select) {
+ var nodes = $$(selectedElement).select('.' + this.options.select) || [];
+ if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
+ } else
+ value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
+
+ var bounds = this.getTokenBounds();
+ if (bounds[0] != -1) {
+ var newValue = this.element.value.substr(0, bounds[0]);
+ var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
+ if (whitespace)
+ newValue += whitespace[0];
+ this.element.value = newValue + value + this.element.value.substr(bounds[1]);
+ } else {
+ this.element.value = value;
+ }
+ this.oldElementValue = this.element.value;
+ this.element.focus();
+
+ if (this.options.afterUpdateElement)
+ this.options.afterUpdateElement(this.element, selectedElement);
+ },
+
+ updateChoices: function(choices) {
+ if(!this.changed && this.hasFocus) {
+ this.update.innerHTML = choices;
+ Element.cleanWhitespace(this.update);
+ Element.cleanWhitespace(this.update.down());
+
+ if(this.update.firstChild && this.update.down().childNodes) {
+ this.entryCount =
+ this.update.down().childNodes.length;
+ for (var i = 0; i < this.entryCount; i++) {
+ var entry = this.getEntry(i);
+ entry.autocompleteIndex = i;
+ this.addObservers(entry);
+ }
+ } else {
+ this.entryCount = 0;
+ }
+
+ this.stopIndicator();
+ this.index = 0;
+
+ if(this.entryCount==1 && this.options.autoSelect) {
+ this.selectEntry();
+ this.hide();
+ } else {
+ this.render();
+ }
+ }
+ },
+
+ addObservers: function(element) {
+ Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
+ Event.observe(element, "click", this.onClick.bindAsEventListener(this));
+ },
+
+ onObserverEvent: function() {
+ this.changed = false;
+ this.tokenBounds = null;
+ if(this.getToken().length>=this.options.minChars) {
+ this.getUpdatedChoices();
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ this.oldElementValue = this.element.value;
+ },
+
+ getToken: function() {
+ var bounds = this.getTokenBounds();
+ return this.element.value.substring(bounds[0], bounds[1]).strip();
+ },
+
+ getTokenBounds: function() {
+ if (null != this.tokenBounds) return this.tokenBounds;
+ var value = this.element.value;
+ if (value.strip().empty()) return [-1, 0];
+ var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
+ var offset = (diff == this.oldElementValue.length ? 1 : 0);
+ var prevTokenPos = -1, nextTokenPos = value.length;
+ var tp;
+ for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
+ tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
+ if (tp > prevTokenPos) prevTokenPos = tp;
+ tp = value.indexOf(this.options.tokens[index], diff + offset);
+ if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
+ }
+ return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
+ }
+});
+
+Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
+ var boundary = Math.min(newS.length, oldS.length);
+ for (var index = 0; index < boundary; ++index)
+ if (newS[index] != oldS[index])
+ return index;
+ return boundary;
+};
+
+Ajax.Autocompleter = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, url, options) {
+ this.baseInitialize(element, update, options);
+ this.options.asynchronous = true;
+ this.options.onComplete = this.onComplete.bind(this);
+ this.options.defaultParams = this.options.parameters || null;
+ this.url = url;
+ },
+
+ getUpdatedChoices: function() {
+ this.startIndicator();
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
+ encodeURIComponent(this.getToken());
+
+ this.options.parameters = this.options.callback ?
+ this.options.callback(this.element, entry) : entry;
+
+ if(this.options.defaultParams)
+ this.options.parameters += '&' + this.options.defaultParams;
+
+ new Ajax.Request(this.url, this.options);
+ },
+
+ onComplete: function(request) {
+ this.updateChoices(request.responseText);
+ }
+});
+
+// The local array autocompleter. Used when you'd prefer to
+// inject an array of autocompletion options into the page, rather
+// than sending out Ajax queries, which can be quite slow sometimes.
+//
+// The constructor takes four parameters. The first two are, as usual,
+// the id of the monitored textbox, and id of the autocompletion menu.
+// The third is the array you want to autocomplete from, and the fourth
+// is the options block.
+//
+// Extra local autocompletion options:
+// - choices - How many autocompletion choices to offer
+//
+// - partialSearch - If false, the autocompleter will match entered
+// text only at the beginning of strings in the
+// autocomplete array. Defaults to true, which will
+// match text at the beginning of any *word* in the
+// strings in the autocomplete array. If you want to
+// search anywhere in the string, additionally set
+// the option fullSearch to true (default: off).
+//
+// - fullSsearch - Search anywhere in autocomplete array strings.
+//
+// - partialChars - How many characters to enter before triggering
+// a partial match (unlike minChars, which defines
+// how many characters are required to do any match
+// at all). Defaults to 2.
+//
+// - ignoreCase - Whether to ignore case when autocompleting.
+// Defaults to true.
+//
+// It's possible to pass in a custom function as the 'selector'
+// option, if you prefer to write your own autocompletion logic.
+// In that case, the other options above will not apply unless
+// you support them.
+
+Autocompleter.Local = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, array, options) {
+ this.baseInitialize(element, update, options);
+ this.options.array = array;
+ },
+
+ getUpdatedChoices: function() {
+ this.updateChoices(this.options.selector(this));
+ },
+
+ setOptions: function(options) {
+ this.options = Object.extend({
+ choices: 10,
+ partialSearch: true,
+ partialChars: 2,
+ ignoreCase: true,
+ fullSearch: false,
+ selector: function(instance) {
+ var ret = []; // Beginning matches
+ var partial = []; // Inside matches
+ var entry = instance.getToken();
+ var count = 0;
+
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {
+
+ var elem = instance.options.array[i];
+ var foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase()) :
+ elem.indexOf(entry);
+
+ while (foundPos != -1) {
+ if (foundPos == 0 && elem.length != entry.length) {
+ ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
+ elem.substr(entry.length) + "</li>");
+ break;
+ } else if (entry.length >= instance.options.partialChars &&
+ instance.options.partialSearch && foundPos != -1) {
+ if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
+ partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
+ elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
+ foundPos + entry.length) + "</li>");
+ break;
+ }
+ }
+
+ foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
+ elem.indexOf(entry, foundPos + 1);
+
+ }
+ }
+ if (partial.length)
+ ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
+ return "<ul>" + ret.join('') + "</ul>";
+ }
+ }, options || { });
+ }
+});
+
+// AJAX in-place editor and collection editor
+// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
+
+// Use this if you notice weird scrolling problems on some browsers,
+// the DOM might be a bit confused when this gets called so do this
+// waits 1 ms (with setTimeout) until it does the activation
+Field.scrollFreeActivate = function(field) {
+ setTimeout(function() {
+ Field.activate(field);
+ }, 1);
+};
+
+Ajax.InPlaceEditor = Class.create({
+ initialize: function(element, url, options) {
+ this.url = url;
+ this.element = element = $$(element);
+ this.prepareOptions();
+ this._controls = { };
+ arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
+ Object.extend(this.options, options || { });
+ if (!this.options.formId && this.element.id) {
+ this.options.formId = this.element.id + '-inplaceeditor';
+ if ($$(this.options.formId))
+ this.options.formId = '';
+ }
+ if (this.options.externalControl)
+ this.options.externalControl = $$(this.options.externalControl);
+ if (!this.options.externalControl)
+ this.options.externalControlOnly = false;
+ this._originalBackground = this.element.getStyle('background-color') || 'transparent';
+ this.element.title = this.options.clickToEditText;
+ this._boundCancelHandler = this.handleFormCancellation.bind(this);
+ this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
+ this._boundFailureHandler = this.handleAJAXFailure.bind(this);
+ this._boundSubmitHandler = this.handleFormSubmission.bind(this);
+ this._boundWrapperHandler = this.wrapUp.bind(this);
+ this.registerListeners();
+ },
+ checkForEscapeOrReturn: function(e) {
+ if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
+ if (Event.KEY_ESC == e.keyCode)
+ this.handleFormCancellation(e);
+ else if (Event.KEY_RETURN == e.keyCode)
+ this.handleFormSubmission(e);
+ },
+ createControl: function(mode, handler, extraClasses) {
+ var control = this.options[mode + 'Control'];
+ var text = this.options[mode + 'Text'];
+ if ('button' == control) {
+ var btn = document.createElement('input');
+ btn.type = 'submit';
+ btn.value = text;
+ btn.className = 'editor_' + mode + '_button';
+ if ('cancel' == mode)
+ btn.onclick = this._boundCancelHandler;
+ this._form.appendChild(btn);
+ this._controls[mode] = btn;
+ } else if ('link' == control) {
+ var link = document.createElement('a');
+ link.href = '#';
+ link.appendChild(document.createTextNode(text));
+ link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
+ link.className = 'editor_' + mode + '_link';
+ if (extraClasses)
+ link.className += ' ' + extraClasses;
+ this._form.appendChild(link);
+ this._controls[mode] = link;
+ }
+ },
+ createEditField: function() {
+ var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
+ var fld;
+ if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
+ fld = document.createElement('input');
+ fld.type = 'text';
+ var size = this.options.size || this.options.cols || 0;
+ if (0 < size) fld.size = size;
+ } else {
+ fld = document.createElement('textarea');
+ fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
+ fld.cols = this.options.cols || 40;
+ }
+ fld.name = this.options.paramName;
+ fld.value = text; // No HTML breaks conversion anymore
+ fld.className = 'editor_field';
+ if (this.options.submitOnBlur)
+ fld.onblur = this._boundSubmitHandler;
+ this._controls.editor = fld;
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+ createForm: function() {
+ var ipe = this;
+ function addText(mode, condition) {
+ var text = ipe.options['text' + mode + 'Controls'];
+ if (!text || condition === false) return;
+ ipe._form.appendChild(document.createTextNode(text));
+ };
+ this._form = $$(document.createElement('form'));
+ this._form.id = this.options.formId;
+ this._form.addClassName(this.options.formClassName);
+ this._form.onsubmit = this._boundSubmitHandler;
+ this.createEditField();
+ if ('textarea' == this._controls.editor.tagName.toLowerCase())
+ this._form.appendChild(document.createElement('br'));
+ if (this.options.onFormCustomization)
+ this.options.onFormCustomization(this, this._form);
+ addText('Before', this.options.okControl || this.options.cancelControl);
+ this.createControl('ok', this._boundSubmitHandler);
+ addText('Between', this.options.okControl && this.options.cancelControl);
+ this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
+ addText('After', this.options.okControl || this.options.cancelControl);
+ },
+ destroy: function() {
+ if (this._oldInnerHTML)
+ this.element.innerHTML = this._oldInnerHTML;
+ this.leaveEditMode();
+ this.unregisterListeners();
+ },
+ enterEditMode: function(e) {
+ if (this._saving || this._editing) return;
+ this._editing = true;
+ this.triggerCallback('onEnterEditMode');
+ if (this.options.externalControl)
+ this.options.externalControl.hide();
+ this.element.hide();
+ this.createForm();
+ this.element.parentNode.insertBefore(this._form, this.element);
+ if (!this.options.loadTextURL)
+ this.postProcessEditField();
+ if (e) Event.stop(e);
+ },
+ enterHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.addClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onEnterHover');
+ },
+ getText: function() {
+ return this.element.innerHTML.unescapeHTML();
+ },
+ handleAJAXFailure: function(transport) {
+ this.triggerCallback('onFailure', transport);
+ if (this._oldInnerHTML) {
+ this.element.innerHTML = this._oldInnerHTML;
+ this._oldInnerHTML = null;
+ }
+ },
+ handleFormCancellation: function(e) {
+ this.wrapUp();
+ if (e) Event.stop(e);
+ },
+ handleFormSubmission: function(e) {
+ var form = this._form;
+ var value = $F(this._controls.editor);
+ this.prepareSubmission();
+ var params = this.options.callback(form, value) || '';
+ if (Object.isString(params))
+ params = params.toQueryParams();
+ params.editorId = this.element.id;
+ if (this.options.htmlResponse) {
+ var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Updater({ success: this.element }, this.url, options);
+ } else {
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.url, options);
+ }
+ if (e) Event.stop(e);
+ },
+ leaveEditMode: function() {
+ this.element.removeClassName(this.options.savingClassName);
+ this.removeForm();
+ this.leaveHover();
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ if (this.options.externalControl)
+ this.options.externalControl.show();
+ this._saving = false;
+ this._editing = false;
+ this._oldInnerHTML = null;
+ this.triggerCallback('onLeaveEditMode');
+ },
+ leaveHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.removeClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onLeaveHover');
+ },
+ loadExternalText: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this._controls.editor.disabled = true;
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._form.removeClassName(this.options.loadingClassName);
+ var text = transport.responseText;
+ if (this.options.stripLoadedTextTags)
+ text = text.stripTags();
+ this._controls.editor.value = text;
+ this._controls.editor.disabled = false;
+ this.postProcessEditField();
+ }.bind(this),
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+ postProcessEditField: function() {
+ var fpc = this.options.fieldPostCreation;
+ if (fpc)
+ $$(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
+ },
+ prepareOptions: function() {
+ this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
+ Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
+ [this._extraDefaultOptions].flatten().compact().each(function(defs) {
+ Object.extend(this.options, defs);
+ }.bind(this));
+ },
+ prepareSubmission: function() {
+ this._saving = true;
+ this.removeForm();
+ this.leaveHover();
+ this.showSaving();
+ },
+ registerListeners: function() {
+ this._listeners = { };
+ var listener;
+ $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
+ listener = this[pair.value].bind(this);
+ this._listeners[pair.key] = listener;
+ if (!this.options.externalControlOnly)
+ this.element.observe(pair.key, listener);
+ if (this.options.externalControl)
+ this.options.externalControl.observe(pair.key, listener);
+ }.bind(this));
+ },
+ removeForm: function() {
+ if (!this._form) return;
+ this._form.remove();
+ this._form = null;
+ this._controls = { };
+ },
+ showSaving: function() {
+ this._oldInnerHTML = this.element.innerHTML;
+ this.element.innerHTML = this.options.savingText;
+ this.element.addClassName(this.options.savingClassName);
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ },
+ triggerCallback: function(cbName, arg) {
+ if ('function' == typeof this.options[cbName]) {
+ this.options[cbName](this, arg);
+ }
+ },
+ unregisterListeners: function() {
+ $H(this._listeners).each(function(pair) {
+ if (!this.options.externalControlOnly)
+ this.element.stopObserving(pair.key, pair.value);
+ if (this.options.externalControl)
+ this.options.externalControl.stopObserving(pair.key, pair.value);
+ }.bind(this));
+ },
+ wrapUp: function(transport) {
+ this.leaveEditMode();
+ // Can't use triggerCallback due to backward compatibility: requires
+ // binding + direct element
+ this._boundComplete(transport, this.element);
+ }
+});
+
+Object.extend(Ajax.InPlaceEditor.prototype, {
+ dispose: Ajax.InPlaceEditor.prototype.destroy
+});
+
+Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
+ initialize: function($super, element, url, options) {
+ this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
+ $super(element, url, options);
+ },
+
+ createEditField: function() {
+ var list = document.createElement('select');
+ list.name = this.options.paramName;
+ list.size = 1;
+ this._controls.editor = list;
+ this._collection = this.options.collection || [];
+ if (this.options.loadCollectionURL)
+ this.loadCollection();
+ else
+ this.checkForExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+
+ loadCollection: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this.showLoadingText(this.options.loadingCollectionText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ var js = transport.responseText.strip();
+ if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
+ throw('Server returned an invalid collection representation.');
+ this._collection = eval(js);
+ this.checkForExternalText();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadCollectionURL, options);
+ },
+
+ showLoadingText: function(text) {
+ this._controls.editor.disabled = true;
+ var tempOption = this._controls.editor.firstChild;
+ if (!tempOption) {
+ tempOption = document.createElement('option');
+ tempOption.value = '';
+ this._controls.editor.appendChild(tempOption);
+ tempOption.selected = true;
+ }
+ tempOption.update((text || '').stripScripts().stripTags());
+ },
+
+ checkForExternalText: function() {
+ this._text = this.getText();
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ else
+ this.buildOptionList();
+ },
+
+ loadExternalText: function() {
+ this.showLoadingText(this.options.loadingText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._text = transport.responseText.strip();
+ this.buildOptionList();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+
+ buildOptionList: function() {
+ this._form.removeClassName(this.options.loadingClassName);
+ this._collection = this._collection.map(function(entry) {
+ return 2 === entry.length ? entry : [entry, entry].flatten();
+ });
+ var marker = ('value' in this.options) ? this.options.value : this._text;
+ var textFound = this._collection.any(function(entry) {
+ return entry[0] == marker;
+ }.bind(this));
+ this._controls.editor.update('');
+ var option;
+ this._collection.each(function(entry, index) {
+ option = document.createElement('option');
+ option.value = entry[0];
+ option.selected = textFound ? entry[0] == marker : 0 == index;
+ option.appendChild(document.createTextNode(entry[1]));
+ this._controls.editor.appendChild(option);
+ }.bind(this));
+ this._controls.editor.disabled = false;
+ Field.scrollFreeActivate(this._controls.editor);
+ }
+});
+
+//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
+//**** This only exists for a while, in order to let ****
+//**** users adapt to the new API. Read up on the new ****
+//**** API and convert your code to it ASAP! ****
+
+Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
+ if (!options) return;
+ function fallback(name, expr) {
+ if (name in options || expr === undefined) return;
+ options[name] = expr;
+ };
+ fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
+ options.cancelLink == options.cancelButton == false ? false : undefined)));
+ fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
+ options.okLink == options.okButton == false ? false : undefined)));
+ fallback('highlightColor', options.highlightcolor);
+ fallback('highlightEndColor', options.highlightendcolor);
+};
+
+Object.extend(Ajax.InPlaceEditor, {
+ DefaultOptions: {
+ ajaxOptions: { },
+ autoRows: 3, // Use when multi-line w/ rows == 1
+ cancelControl: 'link', // 'link'|'button'|false
+ cancelText: 'cancel',
+ clickToEditText: 'Click to edit',
+ externalControl: null, // id|elt
+ externalControlOnly: false,
+ fieldPostCreation: 'activate', // 'activate'|'focus'|false
+ formClassName: 'inplaceeditor-form',
+ formId: null, // id|elt
+ highlightColor: '#ffff99',
+ highlightEndColor: '#ffffff',
+ hoverClassName: '',
+ htmlResponse: true,
+ loadingClassName: 'inplaceeditor-loading',
+ loadingText: 'Loading...',
+ okControl: 'button', // 'link'|'button'|false
+ okText: 'ok',
+ paramName: 'value',
+ rows: 1, // If 1 and multi-line, uses autoRows
+ savingClassName: 'inplaceeditor-saving',
+ savingText: 'Saving...',
+ size: 0,
+ stripLoadedTextTags: false,
+ submitOnBlur: false,
+ textAfterControls: '',
+ textBeforeControls: '',
+ textBetweenControls: ''
+ },
+ DefaultCallbacks: {
+ callback: function(form) {
+ return Form.serialize(form);
+ },
+ onComplete: function(transport, element) {
+ // For backward compatibility, this one is bound to the IPE, and passes
+ // the element directly. It was too often customized, so we don't break it.
+ new Effect.Highlight(element, {
+ startcolor: this.options.highlightColor, keepBackgroundImage: true });
+ },
+ onEnterEditMode: null,
+ onEnterHover: function(ipe) {
+ ipe.element.style.backgroundColor = ipe.options.highlightColor;
+ if (ipe._effect)
+ ipe._effect.cancel();
+ },
+ onFailure: function(transport, ipe) {
+ alert('Error communication with the server: ' + transport.responseText.stripTags());
+ },
+ onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
+ onLeaveEditMode: null,
+ onLeaveHover: function(ipe) {
+ ipe._effect = new Effect.Highlight(ipe.element, {
+ startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
+ restorecolor: ipe._originalBackground, keepBackgroundImage: true
+ });
+ }
+ },
+ Listeners: {
+ click: 'enterEditMode',
+ keydown: 'checkForEscapeOrReturn',
+ mouseover: 'enterHover',
+ mouseout: 'leaveHover'
+ }
+});
+
+Ajax.InPlaceCollectionEditor.DefaultOptions = {
+ loadingCollectionText: 'Loading options...'
+};
+
+// Delayed observer, like Form.Element.Observer,
+// but waits for delay after last key input
+// Ideal for live-search fields
+
+Form.Element.DelayedObserver = Class.create({
+ initialize: function(element, delay, callback) {
+ this.delay = delay || 0.5;
+ this.element = $$(element);
+ this.callback = callback;
+ this.timer = null;
+ this.lastValue = $F(this.element);
+ Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
+ },
+ delayedListener: function(event) {
+ if(this.lastValue == $F(this.element)) return;
+ if(this.timer) clearTimeout(this.timer);
+ this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
+ this.lastValue = $F(this.element);
+ },
+ onTimerEvent: function() {
+ this.timer = null;
+ this.callback(this.element, $F(this.element));
+ }
+});
\ No newline at end of file
--- /dev/null
+// script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+if(Object.isUndefined(Effect))
+ throw("dragdrop.js requires including script.aculo.us' effects.js library");
+
+var Droppables = {
+ drops: [],
+
+ remove: function(element) {
+ this.drops = this.drops.reject(function(d) { return d.element==$$(element) });
+ },
+
+ add: function(element) {
+ element = $$(element);
+ var options = Object.extend({
+ greedy: true,
+ hoverclass: null,
+ tree: false
+ }, arguments[1] || { });
+
+ // cache containers
+ if(options.containment) {
+ options._containers = [];
+ var containment = options.containment;
+ if(Object.isArray(containment)) {
+ containment.each( function(c) { options._containers.push($$(c)) });
+ } else {
+ options._containers.push($$(containment));
+ }
+ }
+
+ if(options.accept) options.accept = [options.accept].flatten();
+
+ Element.makePositioned(element); // fix IE
+ options.element = element;
+
+ this.drops.push(options);
+ },
+
+ findDeepestChild: function(drops) {
+ deepest = drops[0];
+
+ for (i = 1; i < drops.length; ++i)
+ if (Element.isParent(drops[i].element, deepest.element))
+ deepest = drops[i];
+
+ return deepest;
+ },
+
+ isContained: function(element, drop) {
+ var containmentNode;
+ if(drop.tree) {
+ containmentNode = element.treeNode;
+ } else {
+ containmentNode = element.parentNode;
+ }
+ return drop._containers.detect(function(c) { return containmentNode == c });
+ },
+
+ isAffected: function(point, element, drop) {
+ return (
+ (drop.element!=element) &&
+ ((!drop._containers) ||
+ this.isContained(element, drop)) &&
+ ((!drop.accept) ||
+ (Element.classNames(element).detect(
+ function(v) { return drop.accept.include(v) } ) )) &&
+ Position.within(drop.element, point[0], point[1]) );
+ },
+
+ deactivate: function(drop) {
+ if(drop.hoverclass)
+ Element.removeClassName(drop.element, drop.hoverclass);
+ this.last_active = null;
+ },
+
+ activate: function(drop) {
+ if(drop.hoverclass)
+ Element.addClassName(drop.element, drop.hoverclass);
+ this.last_active = drop;
+ },
+
+ show: function(point, element) {
+ if(!this.drops.length) return;
+ var drop, affected = [];
+
+ this.drops.each( function(drop) {
+ if(Droppables.isAffected(point, element, drop))
+ affected.push(drop);
+ });
+
+ if(affected.length>0)
+ drop = Droppables.findDeepestChild(affected);
+
+ if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
+ if (drop) {
+ Position.within(drop.element, point[0], point[1]);
+ if(drop.onHover)
+ drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
+
+ if (drop != this.last_active) Droppables.activate(drop);
+ }
+ },
+
+ fire: function(event, element) {
+ if(!this.last_active) return;
+ Position.prepare();
+
+ if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
+ if (this.last_active.onDrop) {
+ this.last_active.onDrop(element, this.last_active.element, event);
+ return true;
+ }
+ },
+
+ reset: function() {
+ if(this.last_active)
+ this.deactivate(this.last_active);
+ }
+};
+
+var Draggables = {
+ drags: [],
+ observers: [],
+
+ register: function(draggable) {
+ if(this.drags.length == 0) {
+ this.eventMouseUp = this.endDrag.bindAsEventListener(this);
+ this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
+ this.eventKeypress = this.keyPress.bindAsEventListener(this);
+
+ Event.observe(document, "mouseup", this.eventMouseUp);
+ Event.observe(document, "mousemove", this.eventMouseMove);
+ Event.observe(document, "keypress", this.eventKeypress);
+ }
+ this.drags.push(draggable);
+ },
+
+ unregister: function(draggable) {
+ this.drags = this.drags.reject(function(d) { return d==draggable });
+ if(this.drags.length == 0) {
+ Event.stopObserving(document, "mouseup", this.eventMouseUp);
+ Event.stopObserving(document, "mousemove", this.eventMouseMove);
+ Event.stopObserving(document, "keypress", this.eventKeypress);
+ }
+ },
+
+ activate: function(draggable) {
+ if(draggable.options.delay) {
+ this._timeout = setTimeout(function() {
+ Draggables._timeout = null;
+ window.focus();
+ Draggables.activeDraggable = draggable;
+ }.bind(this), draggable.options.delay);
+ } else {
+ window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
+ this.activeDraggable = draggable;
+ }
+ },
+
+ deactivate: function() {
+ this.activeDraggable = null;
+ },
+
+ updateDrag: function(event) {
+ if(!this.activeDraggable) return;
+ var pointer = [Event.pointerX(event), Event.pointerY(event)];
+ // Mozilla-based browsers fire successive mousemove events with
+ // the same coordinates, prevent needless redrawing (moz bug?)
+ if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
+ this._lastPointer = pointer;
+
+ this.activeDraggable.updateDrag(event, pointer);
+ },
+
+ endDrag: function(event) {
+ if(this._timeout) {
+ clearTimeout(this._timeout);
+ this._timeout = null;
+ }
+ if(!this.activeDraggable) return;
+ this._lastPointer = null;
+ this.activeDraggable.endDrag(event);
+ this.activeDraggable = null;
+ },
+
+ keyPress: function(event) {
+ if(this.activeDraggable)
+ this.activeDraggable.keyPress(event);
+ },
+
+ addObserver: function(observer) {
+ this.observers.push(observer);
+ this._cacheObserverCallbacks();
+ },
+
+ removeObserver: function(element) { // element instead of observer fixes mem leaks
+ this.observers = this.observers.reject( function(o) { return o.element==element });
+ this._cacheObserverCallbacks();
+ },
+
+ notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
+ if(this[eventName+'Count'] > 0)
+ this.observers.each( function(o) {
+ if(o[eventName]) o[eventName](eventName, draggable, event);
+ });
+ if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
+ },
+
+ _cacheObserverCallbacks: function() {
+ ['onStart','onEnd','onDrag'].each( function(eventName) {
+ Draggables[eventName+'Count'] = Draggables.observers.select(
+ function(o) { return o[eventName]; }
+ ).length;
+ });
+ }
+};
+
+/*--------------------------------------------------------------------------*/
+
+var Draggable = Class.create({
+ initialize: function(element) {
+ var defaults = {
+ handle: false,
+ reverteffect: function(element, top_offset, left_offset) {
+ var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
+ new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
+ queue: {scope:'_draggable', position:'end'}
+ });
+ },
+ endeffect: function(element) {
+ var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
+ new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
+ queue: {scope:'_draggable', position:'end'},
+ afterFinish: function(){
+ Draggable._dragging[element] = false
+ }
+ });
+ },
+ zindex: 1000,
+ revert: false,
+ quiet: false,
+ scroll: false,
+ scrollSensitivity: 20,
+ scrollSpeed: 15,
+ snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
+ delay: 0
+ };
+
+ if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
+ Object.extend(defaults, {
+ starteffect: function(element) {
+ element._opacity = Element.getOpacity(element);
+ Draggable._dragging[element] = true;
+ new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
+ }
+ });
+
+ var options = Object.extend(defaults, arguments[1] || { });
+
+ this.element = $$(element);
+
+ if(options.handle && Object.isString(options.handle))
+ this.handle = this.element.down('.'+options.handle, 0);
+
+ if(!this.handle) this.handle = $$(options.handle);
+ if(!this.handle) this.handle = this.element;
+
+ if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
+ options.scroll = $$(options.scroll);
+ this._isScrollChild = Element.childOf(this.element, options.scroll);
+ }
+
+ Element.makePositioned(this.element); // fix IE
+
+ this.options = options;
+ this.dragging = false;
+
+ this.eventMouseDown = this.initDrag.bindAsEventListener(this);
+ Event.observe(this.handle, "mousedown", this.eventMouseDown);
+
+ Draggables.register(this);
+ },
+
+ destroy: function() {
+ Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
+ Draggables.unregister(this);
+ },
+
+ currentDelta: function() {
+ return([
+ parseInt(Element.getStyle(this.element,'left') || '0'),
+ parseInt(Element.getStyle(this.element,'top') || '0')]);
+ },
+
+ initDrag: function(event) {
+ if(!Object.isUndefined(Draggable._dragging[this.element]) &&
+ Draggable._dragging[this.element]) return;
+ if(Event.isLeftClick(event)) {
+ // abort on form elements, fixes a Firefox issue
+ var src = Event.element(event);
+ if((tag_name = src.tagName.toUpperCase()) && (
+ tag_name=='INPUT' ||
+ tag_name=='SELECT' ||
+ tag_name=='OPTION' ||
+ tag_name=='BUTTON' ||
+ tag_name=='TEXTAREA')) return;
+
+ var pointer = [Event.pointerX(event), Event.pointerY(event)];
+ var pos = this.element.cumulativeOffset();
+ this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
+
+ Draggables.activate(this);
+ Event.stop(event);
+ }
+ },
+
+ startDrag: function(event) {
+ this.dragging = true;
+ if(!this.delta)
+ this.delta = this.currentDelta();
+
+ if(this.options.zindex) {
+ this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
+ this.element.style.zIndex = this.options.zindex;
+ }
+
+ if(this.options.ghosting) {
+ this._clone = this.element.cloneNode(true);
+ this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
+ if (!this._originallyAbsolute)
+ Position.absolutize(this.element);
+ this.element.parentNode.insertBefore(this._clone, this.element);
+ }
+
+ if(this.options.scroll) {
+ if (this.options.scroll == window) {
+ var where = this._getWindowScroll(this.options.scroll);
+ this.originalScrollLeft = where.left;
+ this.originalScrollTop = where.top;
+ } else {
+ this.originalScrollLeft = this.options.scroll.scrollLeft;
+ this.originalScrollTop = this.options.scroll.scrollTop;
+ }
+ }
+
+ Draggables.notify('onStart', this, event);
+
+ if(this.options.starteffect) this.options.starteffect(this.element);
+ },
+
+ updateDrag: function(event, pointer) {
+ if(!this.dragging) this.startDrag(event);
+
+ if(!this.options.quiet){
+ Position.prepare();
+ Droppables.show(pointer, this.element);
+ }
+
+ Draggables.notify('onDrag', this, event);
+
+ this.draw(pointer);
+ if(this.options.change) this.options.change(this);
+
+ if(this.options.scroll) {
+ this.stopScrolling();
+
+ var p;
+ if (this.options.scroll == window) {
+ with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
+ } else {
+ p = Position.page(this.options.scroll);
+ p[0] += this.options.scroll.scrollLeft + Position.deltaX;
+ p[1] += this.options.scroll.scrollTop + Position.deltaY;
+ p.push(p[0]+this.options.scroll.offsetWidth);
+ p.push(p[1]+this.options.scroll.offsetHeight);
+ }
+ var speed = [0,0];
+ if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
+ if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
+ if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
+ if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
+ this.startScrolling(speed);
+ }
+
+ // fix AppleWebKit rendering
+ if(Prototype.Browser.WebKit) window.scrollBy(0,0);
+
+ Event.stop(event);
+ },
+
+ finishDrag: function(event, success) {
+ this.dragging = false;
+
+ if(this.options.quiet){
+ Position.prepare();
+ var pointer = [Event.pointerX(event), Event.pointerY(event)];
+ Droppables.show(pointer, this.element);
+ }
+
+ if(this.options.ghosting) {
+ if (!this._originallyAbsolute)
+ Position.relativize(this.element);
+ delete this._originallyAbsolute;
+ Element.remove(this._clone);
+ this._clone = null;
+ }
+
+ var dropped = false;
+ if(success) {
+ dropped = Droppables.fire(event, this.element);
+ if (!dropped) dropped = false;
+ }
+ if(dropped && this.options.onDropped) this.options.onDropped(this.element);
+ Draggables.notify('onEnd', this, event);
+
+ var revert = this.options.revert;
+ if(revert && Object.isFunction(revert)) revert = revert(this.element);
+
+ var d = this.currentDelta();
+ if(revert && this.options.reverteffect) {
+ if (dropped == 0 || revert != 'failure')
+ this.options.reverteffect(this.element,
+ d[1]-this.delta[1], d[0]-this.delta[0]);
+ } else {
+ this.delta = d;
+ }
+
+ if(this.options.zindex)
+ this.element.style.zIndex = this.originalZ;
+
+ if(this.options.endeffect)
+ this.options.endeffect(this.element);
+
+ Draggables.deactivate(this);
+ Droppables.reset();
+ },
+
+ keyPress: function(event) {
+ if(event.keyCode!=Event.KEY_ESC) return;
+ this.finishDrag(event, false);
+ Event.stop(event);
+ },
+
+ endDrag: function(event) {
+ if(!this.dragging) return;
+ this.stopScrolling();
+ this.finishDrag(event, true);
+ Event.stop(event);
+ },
+
+ draw: function(point) {
+ var pos = this.element.cumulativeOffset();
+ if(this.options.ghosting) {
+ var r = Position.realOffset(this.element);
+ pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
+ }
+
+ var d = this.currentDelta();
+ pos[0] -= d[0]; pos[1] -= d[1];
+
+ if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
+ pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
+ pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
+ }
+
+ var p = [0,1].map(function(i){
+ return (point[i]-pos[i]-this.offset[i])
+ }.bind(this));
+
+ if(this.options.snap) {
+ if(Object.isFunction(this.options.snap)) {
+ p = this.options.snap(p[0],p[1],this);
+ } else {
+ if(Object.isArray(this.options.snap)) {
+ p = p.map( function(v, i) {
+ return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
+ } else {
+ p = p.map( function(v) {
+ return (v/this.options.snap).round()*this.options.snap }.bind(this));
+ }
+ }}
+
+ var style = this.element.style;
+ if((!this.options.constraint) || (this.options.constraint=='horizontal'))
+ style.left = p[0] + "px";
+ if((!this.options.constraint) || (this.options.constraint=='vertical'))
+ style.top = p[1] + "px";
+
+ if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
+ },
+
+ stopScrolling: function() {
+ if(this.scrollInterval) {
+ clearInterval(this.scrollInterval);
+ this.scrollInterval = null;
+ Draggables._lastScrollPointer = null;
+ }
+ },
+
+ startScrolling: function(speed) {
+ if(!(speed[0] || speed[1])) return;
+ this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
+ this.lastScrolled = new Date();
+ this.scrollInterval = setInterval(this.scroll.bind(this), 10);
+ },
+
+ scroll: function() {
+ var current = new Date();
+ var delta = current - this.lastScrolled;
+ this.lastScrolled = current;
+ if(this.options.scroll == window) {
+ with (this._getWindowScroll(this.options.scroll)) {
+ if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
+ var d = delta / 1000;
+ this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
+ }
+ }
+ } else {
+ this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
+ this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
+ }
+
+ Position.prepare();
+ Droppables.show(Draggables._lastPointer, this.element);
+ Draggables.notify('onDrag', this);
+ if (this._isScrollChild) {
+ Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
+ Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
+ Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
+ if (Draggables._lastScrollPointer[0] < 0)
+ Draggables._lastScrollPointer[0] = 0;
+ if (Draggables._lastScrollPointer[1] < 0)
+ Draggables._lastScrollPointer[1] = 0;
+ this.draw(Draggables._lastScrollPointer);
+ }
+
+ if(this.options.change) this.options.change(this);
+ },
+
+ _getWindowScroll: function(w) {
+ var T, L, W, H;
+ with (w.document) {
+ if (w.document.documentElement && documentElement.scrollTop) {
+ T = documentElement.scrollTop;
+ L = documentElement.scrollLeft;
+ } else if (w.document.body) {
+ T = body.scrollTop;
+ L = body.scrollLeft;
+ }
+ if (w.innerWidth) {
+ W = w.innerWidth;
+ H = w.innerHeight;
+ } else if (w.document.documentElement && documentElement.clientWidth) {
+ W = documentElement.clientWidth;
+ H = documentElement.clientHeight;
+ } else {
+ W = body.offsetWidth;
+ H = body.offsetHeight;
+ }
+ }
+ return { top: T, left: L, width: W, height: H };
+ }
+});
+
+Draggable._dragging = { };
+
+/*--------------------------------------------------------------------------*/
+
+var SortableObserver = Class.create({
+ initialize: function(element, observer) {
+ this.element = $$(element);
+ this.observer = observer;
+ this.lastValue = Sortable.serialize(this.element);
+ },
+
+ onStart: function() {
+ this.lastValue = Sortable.serialize(this.element);
+ },
+
+ onEnd: function() {
+ Sortable.unmark();
+ if(this.lastValue != Sortable.serialize(this.element))
+ this.observer(this.element)
+ }
+});
+
+var Sortable = {
+ SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
+
+ sortables: { },
+
+ _findRootElement: function(element) {
+ while (element.tagName.toUpperCase() != "BODY") {
+ if(element.id && Sortable.sortables[element.id]) return element;
+ element = element.parentNode;
+ }
+ },
+
+ options: function(element) {
+ element = Sortable._findRootElement($$(element));
+ if(!element) return;
+ return Sortable.sortables[element.id];
+ },
+
+ destroy: function(element){
+ element = $$(element);
+ var s = Sortable.sortables[element.id];
+
+ if(s) {
+ Draggables.removeObserver(s.element);
+ s.droppables.each(function(d){ Droppables.remove(d) });
+ s.draggables.invoke('destroy');
+
+ delete Sortable.sortables[s.element.id];
+ }
+ },
+
+ create: function(element) {
+ element = $$(element);
+ var options = Object.extend({
+ element: element,
+ tag: 'li', // assumes li children, override with tag: 'tagname'
+ dropOnEmpty: false,
+ tree: false,
+ treeTag: 'ul',
+ overlap: 'vertical', // one of 'vertical', 'horizontal'
+ constraint: 'vertical', // one of 'vertical', 'horizontal', false
+ containment: element, // also takes array of elements (or id's); or false
+ handle: false, // or a CSS class
+ only: false,
+ delay: 0,
+ hoverclass: null,
+ ghosting: false,
+ quiet: false,
+ scroll: false,
+ scrollSensitivity: 20,
+ scrollSpeed: 15,
+ format: this.SERIALIZE_RULE,
+
+ // these take arrays of elements or ids and can be
+ // used for better initialization performance
+ elements: false,
+ handles: false,
+
+ onChange: Prototype.emptyFunction,
+ onUpdate: Prototype.emptyFunction
+ }, arguments[1] || { });
+
+ // clear any old sortable with same element
+ this.destroy(element);
+
+ // build options for the draggables
+ var options_for_draggable = {
+ revert: true,
+ quiet: options.quiet,
+ scroll: options.scroll,
+ scrollSpeed: options.scrollSpeed,
+ scrollSensitivity: options.scrollSensitivity,
+ delay: options.delay,
+ ghosting: options.ghosting,
+ constraint: options.constraint,
+ handle: options.handle };
+
+ if(options.starteffect)
+ options_for_draggable.starteffect = options.starteffect;
+
+ if(options.reverteffect)
+ options_for_draggable.reverteffect = options.reverteffect;
+ else
+ if(options.ghosting) options_for_draggable.reverteffect = function(element) {
+ element.style.top = 0;
+ element.style.left = 0;
+ };
+
+ if(options.endeffect)
+ options_for_draggable.endeffect = options.endeffect;
+
+ if(options.zindex)
+ options_for_draggable.zindex = options.zindex;
+
+ // build options for the droppables
+ var options_for_droppable = {
+ overlap: options.overlap,
+ containment: options.containment,
+ tree: options.tree,
+ hoverclass: options.hoverclass,
+ onHover: Sortable.onHover
+ };
+
+ var options_for_tree = {
+ onHover: Sortable.onEmptyHover,
+ overlap: options.overlap,
+ containment: options.containment,
+ hoverclass: options.hoverclass
+ };
+
+ // fix for gecko engine
+ Element.cleanWhitespace(element);
+
+ options.draggables = [];
+ options.droppables = [];
+
+ // drop on empty handling
+ if(options.dropOnEmpty || options.tree) {
+ Droppables.add(element, options_for_tree);
+ options.droppables.push(element);
+ }
+
+ (options.elements || this.findElements(element, options) || []).each( function(e,i) {
+ var handle = options.handles ? $$(options.handles[i]) :
+ (options.handle ? $$(e).select('.' + options.handle)[0] : e);
+ options.draggables.push(
+ new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
+ Droppables.add(e, options_for_droppable);
+ if(options.tree) e.treeNode = element;
+ options.droppables.push(e);
+ });
+
+ if(options.tree) {
+ (Sortable.findTreeElements(element, options) || []).each( function(e) {
+ Droppables.add(e, options_for_tree);
+ e.treeNode = element;
+ options.droppables.push(e);
+ });
+ }
+
+ // keep reference
+ this.sortables[element.identify()] = options;
+
+ // for onupdate
+ Draggables.addObserver(new SortableObserver(element, options.onUpdate));
+
+ },
+
+ // return all suitable-for-sortable elements in a guaranteed order
+ findElements: function(element, options) {
+ return Element.findChildren(
+ element, options.only, options.tree ? true : false, options.tag);
+ },
+
+ findTreeElements: function(element, options) {
+ return Element.findChildren(
+ element, options.only, options.tree ? true : false, options.treeTag);
+ },
+
+ onHover: function(element, dropon, overlap) {
+ if(Element.isParent(dropon, element)) return;
+
+ if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
+ return;
+ } else if(overlap>0.5) {
+ Sortable.mark(dropon, 'before');
+ if(dropon.previousSibling != element) {
+ var oldParentNode = element.parentNode;
+ element.style.visibility = "hidden"; // fix gecko rendering
+ dropon.parentNode.insertBefore(element, dropon);
+ if(dropon.parentNode!=oldParentNode)
+ Sortable.options(oldParentNode).onChange(element);
+ Sortable.options(dropon.parentNode).onChange(element);
+ }
+ } else {
+ Sortable.mark(dropon, 'after');
+ var nextElement = dropon.nextSibling || null;
+ if(nextElement != element) {
+ var oldParentNode = element.parentNode;
+ element.style.visibility = "hidden"; // fix gecko rendering
+ dropon.parentNode.insertBefore(element, nextElement);
+ if(dropon.parentNode!=oldParentNode)
+ Sortable.options(oldParentNode).onChange(element);
+ Sortable.options(dropon.parentNode).onChange(element);
+ }
+ }
+ },
+
+ onEmptyHover: function(element, dropon, overlap) {
+ var oldParentNode = element.parentNode;
+ var droponOptions = Sortable.options(dropon);
+
+ if(!Element.isParent(dropon, element)) {
+ var index;
+
+ var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
+ var child = null;
+
+ if(children) {
+ var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
+
+ for (index = 0; index < children.length; index += 1) {
+ if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
+ offset -= Element.offsetSize (children[index], droponOptions.overlap);
+ } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
+ child = index + 1 < children.length ? children[index + 1] : null;
+ break;
+ } else {
+ child = children[index];
+ break;
+ }
+ }
+ }
+
+ dropon.insertBefore(element, child);
+
+ Sortable.options(oldParentNode).onChange(element);
+ droponOptions.onChange(element);
+ }
+ },
+
+ unmark: function() {
+ if(Sortable._marker) Sortable._marker.hide();
+ },
+
+ mark: function(dropon, position) {
+ // mark on ghosting only
+ var sortable = Sortable.options(dropon.parentNode);
+ if(sortable && !sortable.ghosting) return;
+
+ if(!Sortable._marker) {
+ Sortable._marker =
+ ($$('dropmarker') || Element.extend(document.createElement('DIV'))).
+ hide().addClassName('dropmarker').setStyle({position:'absolute'});
+ document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
+ }
+ var offsets = dropon.cumulativeOffset();
+ Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
+
+ if(position=='after')
+ if(sortable.overlap == 'horizontal')
+ Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
+ else
+ Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
+
+ Sortable._marker.show();
+ },
+
+ _tree: function(element, options, parent) {
+ var children = Sortable.findElements(element, options) || [];
+
+ for (var i = 0; i < children.length; ++i) {
+ var match = children[i].id.match(options.format);
+
+ if (!match) continue;
+
+ var child = {
+ id: encodeURIComponent(match ? match[1] : null),
+ element: element,
+ parent: parent,
+ children: [],
+ position: parent.children.length,
+ container: $$(children[i]).down(options.treeTag)
+ };
+
+ /* Get the element containing the children and recurse over it */
+ if (child.container)
+ this._tree(child.container, options, child);
+
+ parent.children.push (child);
+ }
+
+ return parent;
+ },
+
+ tree: function(element) {
+ element = $$(element);
+ var sortableOptions = this.options(element);
+ var options = Object.extend({
+ tag: sortableOptions.tag,
+ treeTag: sortableOptions.treeTag,
+ only: sortableOptions.only,
+ name: element.id,
+ format: sortableOptions.format
+ }, arguments[1] || { });
+
+ var root = {
+ id: null,
+ parent: null,
+ children: [],
+ container: element,
+ position: 0
+ };
+
+ return Sortable._tree(element, options, root);
+ },
+
+ /* Construct a [i] index for a particular node */
+ _constructIndex: function(node) {
+ var index = '';
+ do {
+ if (node.id) index = '[' + node.position + ']' + index;
+ } while ((node = node.parent) != null);
+ return index;
+ },
+
+ sequence: function(element) {
+ element = $$(element);
+ var options = Object.extend(this.options(element), arguments[1] || { });
+
+ return $$(this.findElements(element, options) || []).map( function(item) {
+ return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
+ });
+ },
+
+ setSequence: function(element, new_sequence) {
+ element = $$(element);
+ var options = Object.extend(this.options(element), arguments[2] || { });
+
+ var nodeMap = { };
+ this.findElements(element, options).each( function(n) {
+ if (n.id.match(options.format))
+ nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
+ n.parentNode.removeChild(n);
+ });
+
+ new_sequence.each(function(ident) {
+ var n = nodeMap[ident];
+ if (n) {
+ n[1].appendChild(n[0]);
+ delete nodeMap[ident];
+ }
+ });
+ },
+
+ serialize: function(element) {
+ element = $$(element);
+ var options = Object.extend(Sortable.options(element), arguments[1] || { });
+ var name = encodeURIComponent(
+ (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
+
+ if (options.tree) {
+ return Sortable.tree(element, arguments[1]).children.map( function (item) {
+ return [name + Sortable._constructIndex(item) + "[id]=" +
+ encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
+ }).flatten().join('&');
+ } else {
+ return Sortable.sequence(element, arguments[1]).map( function(item) {
+ return name + "[]=" + encodeURIComponent(item);
+ }).join('&');
+ }
+ }
+};
+
+// Returns true if child is contained within element
+Element.isParent = function(child, element) {
+ if (!child.parentNode || child == element) return false;
+ if (child.parentNode == element) return true;
+ return Element.isParent(child.parentNode, element);
+};
+
+Element.findChildren = function(element, only, recursive, tagName) {
+ if(!element.hasChildNodes()) return null;
+ tagName = tagName.toUpperCase();
+ if(only) only = [only].flatten();
+ var elements = [];
+ $A(element.childNodes).each( function(e) {
+ if(e.tagName && e.tagName.toUpperCase()==tagName &&
+ (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
+ elements.push(e);
+ if(recursive) {
+ var grandchildren = Element.findChildren(e, only, recursive, tagName);
+ if(grandchildren) elements.push(grandchildren);
+ }
+ });
+
+ return (elements.length>0 ? elements.flatten() : []);
+};
+
+Element.offsetSize = function (element, type) {
+ return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
+};
\ No newline at end of file
--- /dev/null
+// script.aculo.us effects.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// Contributors:
+// Justin Palmer (http://encytemedia.com/)
+// Mark Pilgrim (http://diveintomark.org/)
+// Martin Bialasinki
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// converts rgb() and #xxx to #xxxxxx format,
+// returns self (or first argument) if not convertable
+String.prototype.parseColor = function() {
+ var color = '#';
+ if (this.slice(0,4) == 'rgb(') {
+ var cols = this.slice(4,this.length-1).split(',');
+ var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
+ } else {
+ if (this.slice(0,1) == '#') {
+ if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
+ if (this.length==7) color = this.toLowerCase();
+ }
+ }
+ return (color.length==7 ? color : (arguments[0] || this));
+};
+
+/*--------------------------------------------------------------------------*/
+
+Element.collectTextNodes = function(element) {
+ return $A($$(element).childNodes).collect( function(node) {
+ return (node.nodeType==3 ? node.nodeValue :
+ (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
+ }).flatten().join('');
+};
+
+Element.collectTextNodesIgnoreClass = function(element, className) {
+ return $A($$(element).childNodes).collect( function(node) {
+ return (node.nodeType==3 ? node.nodeValue :
+ ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
+ Element.collectTextNodesIgnoreClass(node, className) : ''));
+ }).flatten().join('');
+};
+
+Element.setContentZoom = function(element, percent) {
+ element = $$(element);
+ element.setStyle({fontSize: (percent/100) + 'em'});
+ if (Prototype.Browser.WebKit) window.scrollBy(0,0);
+ return element;
+};
+
+Element.getInlineOpacity = function(element){
+ return $$(element).style.opacity || '';
+};
+
+Element.forceRerendering = function(element) {
+ try {
+ element = $$(element);
+ var n = document.createTextNode(' ');
+ element.appendChild(n);
+ element.removeChild(n);
+ } catch(e) { }
+};
+
+/*--------------------------------------------------------------------------*/
+
+var Effect = {
+ _elementDoesNotExistError: {
+ name: 'ElementDoesNotExistError',
+ message: 'The specified DOM element does not exist, but is required for this effect to operate'
+ },
+ Transitions: {
+ linear: Prototype.K,
+ sinoidal: function(pos) {
+ return (-Math.cos(pos*Math.PI)/2) + .5;
+ },
+ reverse: function(pos) {
+ return 1-pos;
+ },
+ flicker: function(pos) {
+ var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
+ return pos > 1 ? 1 : pos;
+ },
+ wobble: function(pos) {
+ return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
+ },
+ pulse: function(pos, pulses) {
+ return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
+ },
+ spring: function(pos) {
+ return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
+ },
+ none: function(pos) {
+ return 0;
+ },
+ full: function(pos) {
+ return 1;
+ }
+ },
+ DefaultOptions: {
+ duration: 1.0, // seconds
+ fps: 100, // 100= assume 66fps max.
+ sync: false, // true for combining
+ from: 0.0,
+ to: 1.0,
+ delay: 0.0,
+ queue: 'parallel'
+ },
+ tagifyText: function(element) {
+ var tagifyStyle = 'position:relative';
+ if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
+
+ element = $$(element);
+ $A(element.childNodes).each( function(child) {
+ if (child.nodeType==3) {
+ child.nodeValue.toArray().each( function(character) {
+ element.insertBefore(
+ new Element('span', {style: tagifyStyle}).update(
+ character == ' ' ? String.fromCharCode(160) : character),
+ child);
+ });
+ Element.remove(child);
+ }
+ });
+ },
+ multiple: function(element, effect) {
+ var elements;
+ if (((typeof element == 'object') ||
+ Object.isFunction(element)) &&
+ (element.length))
+ elements = element;
+ else
+ elements = $$(element).childNodes;
+
+ var options = Object.extend({
+ speed: 0.1,
+ delay: 0.0
+ }, arguments[2] || { });
+ var masterDelay = options.delay;
+
+ $A(elements).each( function(element, index) {
+ new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
+ });
+ },
+ PAIRS: {
+ 'slide': ['SlideDown','SlideUp'],
+ 'blind': ['BlindDown','BlindUp'],
+ 'appear': ['Appear','Fade']
+ },
+ toggle: function(element, effect, options) {
+ element = $$(element);
+ effect = (effect || 'appear').toLowerCase();
+
+ return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({
+ queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
+ }, options || {}));
+ }
+};
+
+Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
+
+/* ------------- core effects ------------- */
+
+Effect.ScopedQueue = Class.create(Enumerable, {
+ initialize: function() {
+ this.effects = [];
+ this.interval = null;
+ },
+ _each: function(iterator) {
+ this.effects._each(iterator);
+ },
+ add: function(effect) {
+ var timestamp = new Date().getTime();
+
+ var position = Object.isString(effect.options.queue) ?
+ effect.options.queue : effect.options.queue.position;
+
+ switch(position) {
+ case 'front':
+ // move unstarted effects after this effect
+ this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
+ e.startOn += effect.finishOn;
+ e.finishOn += effect.finishOn;
+ });
+ break;
+ case 'with-last':
+ timestamp = this.effects.pluck('startOn').max() || timestamp;
+ break;
+ case 'end':
+ // start effect after last queued effect has finished
+ timestamp = this.effects.pluck('finishOn').max() || timestamp;
+ break;
+ }
+
+ effect.startOn += timestamp;
+ effect.finishOn += timestamp;
+
+ if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
+ this.effects.push(effect);
+
+ if (!this.interval)
+ this.interval = setInterval(this.loop.bind(this), 15);
+ },
+ remove: function(effect) {
+ this.effects = this.effects.reject(function(e) { return e==effect });
+ if (this.effects.length == 0) {
+ clearInterval(this.interval);
+ this.interval = null;
+ }
+ },
+ loop: function() {
+ var timePos = new Date().getTime();
+ for(var i=0, len=this.effects.length;i<len;i++)
+ this.effects[i] && this.effects[i].loop(timePos);
+ }
+});
+
+Effect.Queues = {
+ instances: $H(),
+ get: function(queueName) {
+ if (!Object.isString(queueName)) return queueName;
+
+ return this.instances.get(queueName) ||
+ this.instances.set(queueName, new Effect.ScopedQueue());
+ }
+};
+Effect.Queue = Effect.Queues.get('global');
+
+Effect.Base = Class.create({
+ position: null,
+ start: function(options) {
+ if (options && options.transition === false) options.transition = Effect.Transitions.linear;
+ this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
+ this.currentFrame = 0;
+ this.state = 'idle';
+ this.startOn = this.options.delay*1000;
+ this.finishOn = this.startOn+(this.options.duration*1000);
+ this.fromToDelta = this.options.to-this.options.from;
+ this.totalTime = this.finishOn-this.startOn;
+ this.totalFrames = this.options.fps*this.options.duration;
+
+ this.render = (function() {
+ function dispatch(effect, eventName) {
+ if (effect.options[eventName + 'Internal'])
+ effect.options[eventName + 'Internal'](effect);
+ if (effect.options[eventName])
+ effect.options[eventName](effect);
+ }
+
+ return function(pos) {
+ if (this.state === "idle") {
+ this.state = "running";
+ dispatch(this, 'beforeSetup');
+ if (this.setup) this.setup();
+ dispatch(this, 'afterSetup');
+ }
+ if (this.state === "running") {
+ pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
+ this.position = pos;
+ dispatch(this, 'beforeUpdate');
+ if (this.update) this.update(pos);
+ dispatch(this, 'afterUpdate');
+ }
+ };
+ })();
+
+ this.event('beforeStart');
+ if (!this.options.sync)
+ Effect.Queues.get(Object.isString(this.options.queue) ?
+ 'global' : this.options.queue.scope).add(this);
+ },
+ loop: function(timePos) {
+ if (timePos >= this.startOn) {
+ if (timePos >= this.finishOn) {
+ this.render(1.0);
+ this.cancel();
+ this.event('beforeFinish');
+ if (this.finish) this.finish();
+ this.event('afterFinish');
+ return;
+ }
+ var pos = (timePos - this.startOn) / this.totalTime,
+ frame = (pos * this.totalFrames).round();
+ if (frame > this.currentFrame) {
+ this.render(pos);
+ this.currentFrame = frame;
+ }
+ }
+ },
+ cancel: function() {
+ if (!this.options.sync)
+ Effect.Queues.get(Object.isString(this.options.queue) ?
+ 'global' : this.options.queue.scope).remove(this);
+ this.state = 'finished';
+ },
+ event: function(eventName) {
+ if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
+ if (this.options[eventName]) this.options[eventName](this);
+ },
+ inspect: function() {
+ var data = $H();
+ for(property in this)
+ if (!Object.isFunction(this[property])) data.set(property, this[property]);
+ return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
+ }
+});
+
+Effect.Parallel = Class.create(Effect.Base, {
+ initialize: function(effects) {
+ this.effects = effects || [];
+ this.start(arguments[1]);
+ },
+ update: function(position) {
+ this.effects.invoke('render', position);
+ },
+ finish: function(position) {
+ this.effects.each( function(effect) {
+ effect.render(1.0);
+ effect.cancel();
+ effect.event('beforeFinish');
+ if (effect.finish) effect.finish(position);
+ effect.event('afterFinish');
+ });
+ }
+});
+
+Effect.Tween = Class.create(Effect.Base, {
+ initialize: function(object, from, to) {
+ object = Object.isString(object) ? $$(object) : object;
+ var args = $A(arguments), method = args.last(),
+ options = args.length == 5 ? args[3] : null;
+ this.method = Object.isFunction(method) ? method.bind(object) :
+ Object.isFunction(object[method]) ? object[method].bind(object) :
+ function(value) { object[method] = value };
+ this.start(Object.extend({ from: from, to: to }, options || { }));
+ },
+ update: function(position) {
+ this.method(position);
+ }
+});
+
+Effect.Event = Class.create(Effect.Base, {
+ initialize: function() {
+ this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
+ },
+ update: Prototype.emptyFunction
+});
+
+Effect.Opacity = Class.create(Effect.Base, {
+ initialize: function(element) {
+ this.element = $$(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ // make this work on IE on elements without 'layout'
+ if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
+ this.element.setStyle({zoom: 1});
+ var options = Object.extend({
+ from: this.element.getOpacity() || 0.0,
+ to: 1.0
+ }, arguments[1] || { });
+ this.start(options);
+ },
+ update: function(position) {
+ this.element.setOpacity(position);
+ }
+});
+
+Effect.Move = Class.create(Effect.Base, {
+ initialize: function(element) {
+ this.element = $$(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({
+ x: 0,
+ y: 0,
+ mode: 'relative'
+ }, arguments[1] || { });
+ this.start(options);
+ },
+ setup: function() {
+ this.element.makePositioned();
+ this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
+ this.originalTop = parseFloat(this.element.getStyle('top') || '0');
+ if (this.options.mode == 'absolute') {
+ this.options.x = this.options.x - this.originalLeft;
+ this.options.y = this.options.y - this.originalTop;
+ }
+ },
+ update: function(position) {
+ this.element.setStyle({
+ left: (this.options.x * position + this.originalLeft).round() + 'px',
+ top: (this.options.y * position + this.originalTop).round() + 'px'
+ });
+ }
+});
+
+// for backwards compatibility
+Effect.MoveBy = function(element, toTop, toLeft) {
+ return new Effect.Move(element,
+ Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
+};
+
+Effect.Scale = Class.create(Effect.Base, {
+ initialize: function(element, percent) {
+ this.element = $$(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({
+ scaleX: true,
+ scaleY: true,
+ scaleContent: true,
+ scaleFromCenter: false,
+ scaleMode: 'box', // 'box' or 'contents' or { } with provided values
+ scaleFrom: 100.0,
+ scaleTo: percent
+ }, arguments[2] || { });
+ this.start(options);
+ },
+ setup: function() {
+ this.restoreAfterFinish = this.options.restoreAfterFinish || false;
+ this.elementPositioning = this.element.getStyle('position');
+
+ this.originalStyle = { };
+ ['top','left','width','height','fontSize'].each( function(k) {
+ this.originalStyle[k] = this.element.style[k];
+ }.bind(this));
+
+ this.originalTop = this.element.offsetTop;
+ this.originalLeft = this.element.offsetLeft;
+
+ var fontSize = this.element.getStyle('font-size') || '100%';
+ ['em','px','%','pt'].each( function(fontSizeType) {
+ if (fontSize.indexOf(fontSizeType)>0) {
+ this.fontSize = parseFloat(fontSize);
+ this.fontSizeType = fontSizeType;
+ }
+ }.bind(this));
+
+ this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
+
+ this.dims = null;
+ if (this.options.scaleMode=='box')
+ this.dims = [this.element.offsetHeight, this.element.offsetWidth];
+ if (/^content/.test(this.options.scaleMode))
+ this.dims = [this.element.scrollHeight, this.element.scrollWidth];
+ if (!this.dims)
+ this.dims = [this.options.scaleMode.originalHeight,
+ this.options.scaleMode.originalWidth];
+ },
+ update: function(position) {
+ var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
+ if (this.options.scaleContent && this.fontSize)
+ this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
+ this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
+ },
+ finish: function(position) {
+ if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
+ },
+ setDimensions: function(height, width) {
+ var d = { };
+ if (this.options.scaleX) d.width = width.round() + 'px';
+ if (this.options.scaleY) d.height = height.round() + 'px';
+ if (this.options.scaleFromCenter) {
+ var topd = (height - this.dims[0])/2;
+ var leftd = (width - this.dims[1])/2;
+ if (this.elementPositioning == 'absolute') {
+ if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
+ if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
+ } else {
+ if (this.options.scaleY) d.top = -topd + 'px';
+ if (this.options.scaleX) d.left = -leftd + 'px';
+ }
+ }
+ this.element.setStyle(d);
+ }
+});
+
+Effect.Highlight = Class.create(Effect.Base, {
+ initialize: function(element) {
+ this.element = $$(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
+ this.start(options);
+ },
+ setup: function() {
+ // Prevent executing on elements not in the layout flow
+ if (this.element.getStyle('display')=='none') { this.cancel(); return; }
+ // Disable background image during the effect
+ this.oldStyle = { };
+ if (!this.options.keepBackgroundImage) {
+ this.oldStyle.backgroundImage = this.element.getStyle('background-image');
+ this.element.setStyle({backgroundImage: 'none'});
+ }
+ if (!this.options.endcolor)
+ this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
+ if (!this.options.restorecolor)
+ this.options.restorecolor = this.element.getStyle('background-color');
+ // init color calculations
+ this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
+ this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
+ },
+ update: function(position) {
+ this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
+ return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
+ },
+ finish: function() {
+ this.element.setStyle(Object.extend(this.oldStyle, {
+ backgroundColor: this.options.restorecolor
+ }));
+ }
+});
+
+Effect.ScrollTo = function(element) {
+ var options = arguments[1] || { },
+ scrollOffsets = document.viewport.getScrollOffsets(),
+ elementOffsets = $$(element).cumulativeOffset();
+
+ if (options.offset) elementOffsets[1] += options.offset;
+
+ return new Effect.Tween(null,
+ scrollOffsets.top,
+ elementOffsets[1],
+ options,
+ function(p){ scrollTo(scrollOffsets.left, p.round()); }
+ );
+};
+
+/* ------------- combination effects ------------- */
+
+Effect.Fade = function(element) {
+ element = $$(element);
+ var oldOpacity = element.getInlineOpacity();
+ var options = Object.extend({
+ from: element.getOpacity() || 1.0,
+ to: 0.0,
+ afterFinishInternal: function(effect) {
+ if (effect.options.to!=0) return;
+ effect.element.hide().setStyle({opacity: oldOpacity});
+ }
+ }, arguments[1] || { });
+ return new Effect.Opacity(element,options);
+};
+
+Effect.Appear = function(element) {
+ element = $$(element);
+ var options = Object.extend({
+ from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
+ to: 1.0,
+ // force Safari to render floated elements properly
+ afterFinishInternal: function(effect) {
+ effect.element.forceRerendering();
+ },
+ beforeSetup: function(effect) {
+ effect.element.setOpacity(effect.options.from).show();
+ }}, arguments[1] || { });
+ return new Effect.Opacity(element,options);
+};
+
+Effect.Puff = function(element) {
+ element = $$(element);
+ var oldStyle = {
+ opacity: element.getInlineOpacity(),
+ position: element.getStyle('position'),
+ top: element.style.top,
+ left: element.style.left,
+ width: element.style.width,
+ height: element.style.height
+ };
+ return new Effect.Parallel(
+ [ new Effect.Scale(element, 200,
+ { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
+ new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
+ Object.extend({ duration: 1.0,
+ beforeSetupInternal: function(effect) {
+ Position.absolutize(effect.effects[0].element);
+ },
+ afterFinishInternal: function(effect) {
+ effect.effects[0].element.hide().setStyle(oldStyle); }
+ }, arguments[1] || { })
+ );
+};
+
+Effect.BlindUp = function(element) {
+ element = $$(element);
+ element.makeClipping();
+ return new Effect.Scale(element, 0,
+ Object.extend({ scaleContent: false,
+ scaleX: false,
+ restoreAfterFinish: true,
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping();
+ }
+ }, arguments[1] || { })
+ );
+};
+
+Effect.BlindDown = function(element) {
+ element = $$(element);
+ var elementDimensions = element.getDimensions();
+ return new Effect.Scale(element, 100, Object.extend({
+ scaleContent: false,
+ scaleX: false,
+ scaleFrom: 0,
+ scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
+ restoreAfterFinish: true,
+ afterSetup: function(effect) {
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.undoClipping();
+ }
+ }, arguments[1] || { }));
+};
+
+Effect.SwitchOff = function(element) {
+ element = $$(element);
+ var oldOpacity = element.getInlineOpacity();
+ return new Effect.Appear(element, Object.extend({
+ duration: 0.4,
+ from: 0,
+ transition: Effect.Transitions.flicker,
+ afterFinishInternal: function(effect) {
+ new Effect.Scale(effect.element, 1, {
+ duration: 0.3, scaleFromCenter: true,
+ scaleX: false, scaleContent: false, restoreAfterFinish: true,
+ beforeSetup: function(effect) {
+ effect.element.makePositioned().makeClipping();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
+ }
+ });
+ }
+ }, arguments[1] || { }));
+};
+
+Effect.DropOut = function(element) {
+ element = $$(element);
+ var oldStyle = {
+ top: element.getStyle('top'),
+ left: element.getStyle('left'),
+ opacity: element.getInlineOpacity() };
+ return new Effect.Parallel(
+ [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
+ new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
+ Object.extend(
+ { duration: 0.5,
+ beforeSetup: function(effect) {
+ effect.effects[0].element.makePositioned();
+ },
+ afterFinishInternal: function(effect) {
+ effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
+ }
+ }, arguments[1] || { }));
+};
+
+Effect.Shake = function(element) {
+ element = $$(element);
+ var options = Object.extend({
+ distance: 20,
+ duration: 0.5
+ }, arguments[1] || {});
+ var distance = parseFloat(options.distance);
+ var split = parseFloat(options.duration) / 10.0;
+ var oldStyle = {
+ top: element.getStyle('top'),
+ left: element.getStyle('left') };
+ return new Effect.Move(element,
+ { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
+ effect.element.undoPositioned().setStyle(oldStyle);
+ }}); }}); }}); }}); }}); }});
+};
+
+Effect.SlideDown = function(element) {
+ element = $$(element).cleanWhitespace();
+ // SlideDown need to have the content of the element wrapped in a container element with fixed height!
+ var oldInnerBottom = element.down().getStyle('bottom');
+ var elementDimensions = element.getDimensions();
+ return new Effect.Scale(element, 100, Object.extend({
+ scaleContent: false,
+ scaleX: false,
+ scaleFrom: window.opera ? 0 : 1,
+ scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
+ restoreAfterFinish: true,
+ afterSetup: function(effect) {
+ effect.element.makePositioned();
+ effect.element.down().makePositioned();
+ if (window.opera) effect.element.setStyle({top: ''});
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
+ },
+ afterUpdateInternal: function(effect) {
+ effect.element.down().setStyle({bottom:
+ (effect.dims[0] - effect.element.clientHeight) + 'px' });
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.undoClipping().undoPositioned();
+ effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
+ }, arguments[1] || { })
+ );
+};
+
+Effect.SlideUp = function(element) {
+ element = $$(element).cleanWhitespace();
+ var oldInnerBottom = element.down().getStyle('bottom');
+ var elementDimensions = element.getDimensions();
+ return new Effect.Scale(element, window.opera ? 0 : 1,
+ Object.extend({ scaleContent: false,
+ scaleX: false,
+ scaleMode: 'box',
+ scaleFrom: 100,
+ scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
+ restoreAfterFinish: true,
+ afterSetup: function(effect) {
+ effect.element.makePositioned();
+ effect.element.down().makePositioned();
+ if (window.opera) effect.element.setStyle({top: ''});
+ effect.element.makeClipping().show();
+ },
+ afterUpdateInternal: function(effect) {
+ effect.element.down().setStyle({bottom:
+ (effect.dims[0] - effect.element.clientHeight) + 'px' });
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping().undoPositioned();
+ effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
+ }
+ }, arguments[1] || { })
+ );
+};
+
+// Bug in opera makes the TD containing this element expand for a instance after finish
+Effect.Squish = function(element) {
+ return new Effect.Scale(element, window.opera ? 1 : 0, {
+ restoreAfterFinish: true,
+ beforeSetup: function(effect) {
+ effect.element.makeClipping();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping();
+ }
+ });
+};
+
+Effect.Grow = function(element) {
+ element = $$(element);
+ var options = Object.extend({
+ direction: 'center',
+ moveTransition: Effect.Transitions.sinoidal,
+ scaleTransition: Effect.Transitions.sinoidal,
+ opacityTransition: Effect.Transitions.full
+ }, arguments[1] || { });
+ var oldStyle = {
+ top: element.style.top,
+ left: element.style.left,
+ height: element.style.height,
+ width: element.style.width,
+ opacity: element.getInlineOpacity() };
+
+ var dims = element.getDimensions();
+ var initialMoveX, initialMoveY;
+ var moveX, moveY;
+
+ switch (options.direction) {
+ case 'top-left':
+ initialMoveX = initialMoveY = moveX = moveY = 0;
+ break;
+ case 'top-right':
+ initialMoveX = dims.width;
+ initialMoveY = moveY = 0;
+ moveX = -dims.width;
+ break;
+ case 'bottom-left':
+ initialMoveX = moveX = 0;
+ initialMoveY = dims.height;
+ moveY = -dims.height;
+ break;
+ case 'bottom-right':
+ initialMoveX = dims.width;
+ initialMoveY = dims.height;
+ moveX = -dims.width;
+ moveY = -dims.height;
+ break;
+ case 'center':
+ initialMoveX = dims.width / 2;
+ initialMoveY = dims.height / 2;
+ moveX = -dims.width / 2;
+ moveY = -dims.height / 2;
+ break;
+ }
+
+ return new Effect.Move(element, {
+ x: initialMoveX,
+ y: initialMoveY,
+ duration: 0.01,
+ beforeSetup: function(effect) {
+ effect.element.hide().makeClipping().makePositioned();
+ },
+ afterFinishInternal: function(effect) {
+ new Effect.Parallel(
+ [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
+ new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
+ new Effect.Scale(effect.element, 100, {
+ scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
+ sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
+ ], Object.extend({
+ beforeSetup: function(effect) {
+ effect.effects[0].element.setStyle({height: '0px'}).show();
+ },
+ afterFinishInternal: function(effect) {
+ effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
+ }
+ }, options)
+ );
+ }
+ });
+};
+
+Effect.Shrink = function(element) {
+ element = $$(element);
+ var options = Object.extend({
+ direction: 'center',
+ moveTransition: Effect.Transitions.sinoidal,
+ scaleTransition: Effect.Transitions.sinoidal,
+ opacityTransition: Effect.Transitions.none
+ }, arguments[1] || { });
+ var oldStyle = {
+ top: element.style.top,
+ left: element.style.left,
+ height: element.style.height,
+ width: element.style.width,
+ opacity: element.getInlineOpacity() };
+
+ var dims = element.getDimensions();
+ var moveX, moveY;
+
+ switch (options.direction) {
+ case 'top-left':
+ moveX = moveY = 0;
+ break;
+ case 'top-right':
+ moveX = dims.width;
+ moveY = 0;
+ break;
+ case 'bottom-left':
+ moveX = 0;
+ moveY = dims.height;
+ break;
+ case 'bottom-right':
+ moveX = dims.width;
+ moveY = dims.height;
+ break;
+ case 'center':
+ moveX = dims.width / 2;
+ moveY = dims.height / 2;
+ break;
+ }
+
+ return new Effect.Parallel(
+ [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
+ new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
+ new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
+ ], Object.extend({
+ beforeStartInternal: function(effect) {
+ effect.effects[0].element.makePositioned().makeClipping();
+ },
+ afterFinishInternal: function(effect) {
+ effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
+ }, options)
+ );
+};
+
+Effect.Pulsate = function(element) {
+ element = $$(element);
+ var options = arguments[1] || { },
+ oldOpacity = element.getInlineOpacity(),
+ transition = options.transition || Effect.Transitions.linear,
+ reverser = function(pos){
+ return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
+ };
+
+ return new Effect.Opacity(element,
+ Object.extend(Object.extend({ duration: 2.0, from: 0,
+ afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
+ }, options), {transition: reverser}));
+};
+
+Effect.Fold = function(element) {
+ element = $$(element);
+ var oldStyle = {
+ top: element.style.top,
+ left: element.style.left,
+ width: element.style.width,
+ height: element.style.height };
+ element.makeClipping();
+ return new Effect.Scale(element, 5, Object.extend({
+ scaleContent: false,
+ scaleX: false,
+ afterFinishInternal: function(effect) {
+ new Effect.Scale(element, 1, {
+ scaleContent: false,
+ scaleY: false,
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping().setStyle(oldStyle);
+ } });
+ }}, arguments[1] || { }));
+};
+
+Effect.Morph = Class.create(Effect.Base, {
+ initialize: function(element) {
+ this.element = $$(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({
+ style: { }
+ }, arguments[1] || { });
+
+ if (!Object.isString(options.style)) this.style = $H(options.style);
+ else {
+ if (options.style.include(':'))
+ this.style = options.style.parseStyle();
+ else {
+ this.element.addClassName(options.style);
+ this.style = $H(this.element.getStyles());
+ this.element.removeClassName(options.style);
+ var css = this.element.getStyles();
+ this.style = this.style.reject(function(style) {
+ return style.value == css[style.key];
+ });
+ options.afterFinishInternal = function(effect) {
+ effect.element.addClassName(effect.options.style);
+ effect.transforms.each(function(transform) {
+ effect.element.style[transform.style] = '';
+ });
+ };
+ }
+ }
+ this.start(options);
+ },
+
+ setup: function(){
+ function parseColor(color){
+ if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
+ color = color.parseColor();
+ return $R(0,2).map(function(i){
+ return parseInt( color.slice(i*2+1,i*2+3), 16 );
+ });
+ }
+ this.transforms = this.style.map(function(pair){
+ var property = pair[0], value = pair[1], unit = null;
+
+ if (value.parseColor('#zzzzzz') != '#zzzzzz') {
+ value = value.parseColor();
+ unit = 'color';
+ } else if (property == 'opacity') {
+ value = parseFloat(value);
+ if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
+ this.element.setStyle({zoom: 1});
+ } else if (Element.CSS_LENGTH.test(value)) {
+ var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
+ value = parseFloat(components[1]);
+ unit = (components.length == 3) ? components[2] : null;
+ }
+
+ var originalValue = this.element.getStyle(property);
+ return {
+ style: property.camelize(),
+ originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
+ targetValue: unit=='color' ? parseColor(value) : value,
+ unit: unit
+ };
+ }.bind(this)).reject(function(transform){
+ return (
+ (transform.originalValue == transform.targetValue) ||
+ (
+ transform.unit != 'color' &&
+ (isNaN(transform.originalValue) || isNaN(transform.targetValue))
+ )
+ );
+ });
+ },
+ update: function(position) {
+ var style = { }, transform, i = this.transforms.length;
+ while(i--)
+ style[(transform = this.transforms[i]).style] =
+ transform.unit=='color' ? '#'+
+ (Math.round(transform.originalValue[0]+
+ (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
+ (Math.round(transform.originalValue[1]+
+ (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
+ (Math.round(transform.originalValue[2]+
+ (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
+ (transform.originalValue +
+ (transform.targetValue - transform.originalValue) * position).toFixed(3) +
+ (transform.unit === null ? '' : transform.unit);
+ this.element.setStyle(style, true);
+ }
+});
+
+Effect.Transform = Class.create({
+ initialize: function(tracks){
+ this.tracks = [];
+ this.options = arguments[1] || { };
+ this.addTracks(tracks);
+ },
+ addTracks: function(tracks){
+ tracks.each(function(track){
+ track = $H(track);
+ var data = track.values().first();
+ this.tracks.push($H({
+ ids: track.keys().first(),
+ effect: Effect.Morph,
+ options: { style: data }
+ }));
+ }.bind(this));
+ return this;
+ },
+ play: function(){
+ return new Effect.Parallel(
+ this.tracks.map(function(track){
+ var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
+ var elements = [$$(ids) || $$$(ids)].flatten();
+ return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
+ }).flatten(),
+ this.options
+ );
+ }
+});
+
+Element.CSS_PROPERTIES = $w(
+ 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
+ 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
+ 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
+ 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
+ 'fontSize fontWeight height left letterSpacing lineHeight ' +
+ 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
+ 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
+ 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
+ 'right textIndent top width wordSpacing zIndex');
+
+Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
+
+String.__parseStyleElement = document.createElement('div');
+String.prototype.parseStyle = function(){
+ var style, styleRules = $H();
+ if (Prototype.Browser.WebKit)
+ style = new Element('div',{style:this}).style;
+ else {
+ String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
+ style = String.__parseStyleElement.childNodes[0].style;
+ }
+
+ Element.CSS_PROPERTIES.each(function(property){
+ if (style[property]) styleRules.set(property, style[property]);
+ });
+
+ if (Prototype.Browser.IE && this.include('opacity'))
+ styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
+
+ return styleRules;
+};
+
+if (document.defaultView && document.defaultView.getComputedStyle) {
+ Element.getStyles = function(element) {
+ var css = document.defaultView.getComputedStyle($$(element), null);
+ return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
+ styles[property] = css[property];
+ return styles;
+ });
+ };
+} else {
+ Element.getStyles = function(element) {
+ element = $$(element);
+ var css = element.currentStyle, styles;
+ styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
+ results[property] = css[property];
+ return results;
+ });
+ if (!styles.opacity) styles.opacity = element.getOpacity();
+ return styles;
+ };
+}
+
+Effect.Methods = {
+ morph: function(element, style) {
+ element = $$(element);
+ new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
+ return element;
+ },
+ visualEffect: function(element, effect, options) {
+ element = $$(element);
+ var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
+ new Effect[klass](element, options);
+ return element;
+ },
+ highlight: function(element, options) {
+ element = $$(element);
+ new Effect.Highlight(element, options);
+ return element;
+ }
+};
+
+$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
+ 'pulsate shake puff squish switchOff dropOut').each(
+ function(effect) {
+ Effect.Methods[effect] = function(element, options){
+ element = $$(element);
+ Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
+ return element;
+ };
+ }
+);
+
+$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
+ function(f) { Effect.Methods[f] = Element[f]; }
+);
+
+Element.addMethods(Effect.Methods);
\ No newline at end of file
--- /dev/null
+// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+var Scriptaculous = {
+ Version: '1.8.3',
+ require: function(libraryName) {
+ try{
+ // inserting via DOM fails in Safari 2.0, so brute force approach
+ document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
+ } catch(e) {
+ // for xhtml+xml served content, fall back to DOM methods
+ var script = document.createElement('script');
+ script.type = 'text/javascript';
+ script.src = libraryName;
+ document.getElementsByTagName('head')[0].appendChild(script);
+ }
+ },
+ REQUIRED_PROTOTYPE: '1.6.0.3',
+ load: function() {
+ function convertVersionString(versionString) {
+ var v = versionString.replace(/_.*|\./g, '');
+ v = parseInt(v + '0'.times(4-v.length));
+ return versionString.indexOf('_') > -1 ? v-1 : v;
+ }
+
+ if((typeof Prototype=='undefined') ||
+ (typeof Element == 'undefined') ||
+ (typeof Element.Methods=='undefined') ||
+ (convertVersionString(Prototype.Version) <
+ convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
+ throw("script.aculo.us requires the Prototype JavaScript framework >= " +
+ Scriptaculous.REQUIRED_PROTOTYPE);
+
+ var js = /scriptaculous\.js(\?.*)?$/;
+ $$$('head script[src]').findAll(function(s) {
+ return s.src.match(js);
+ }).each(function(s) {
+ var path = s.src.replace(js, ''),
+ includes = s.src.match(/\?.*load=([a-z,]*)/);
+ (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
+ function(include) { Scriptaculous.require(path+include+'.js') });
+ });
+ }
+};
+
+Scriptaculous.load();
\ No newline at end of file
--- /dev/null
+// script.aculo.us slider.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Marty Haught, Thomas Fuchs
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+if (!Control) var Control = { };
+
+// options:
+// axis: 'vertical', or 'horizontal' (default)
+//
+// callbacks:
+// onChange(value)
+// onSlide(value)
+Control.Slider = Class.create({
+ initialize: function(handle, track, options) {
+ var slider = this;
+
+ if (Object.isArray(handle)) {
+ this.handles = handle.collect( function(e) { return $$(e) });
+ } else {
+ this.handles = [$$(handle)];
+ }
+
+ this.track = $$(track);
+ this.options = options || { };
+
+ this.axis = this.options.axis || 'horizontal';
+ this.increment = this.options.increment || 1;
+ this.step = parseInt(this.options.step || '1');
+ this.range = this.options.range || $R(0,1);
+
+ this.value = 0; // assure backwards compat
+ this.values = this.handles.map( function() { return 0 });
+ this.spans = this.options.spans ? this.options.spans.map(function(s){ return $$(s) }) : false;
+ this.options.startSpan = $$(this.options.startSpan || null);
+ this.options.endSpan = $$(this.options.endSpan || null);
+
+ this.restricted = this.options.restricted || false;
+
+ this.maximum = this.options.maximum || this.range.end;
+ this.minimum = this.options.minimum || this.range.start;
+
+ // Will be used to align the handle onto the track, if necessary
+ this.alignX = parseInt(this.options.alignX || '0');
+ this.alignY = parseInt(this.options.alignY || '0');
+
+ this.trackLength = this.maximumOffset() - this.minimumOffset();
+
+ this.handleLength = this.isVertical() ?
+ (this.handles[0].offsetHeight != 0 ?
+ this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) :
+ (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth :
+ this.handles[0].style.width.replace(/px$/,""));
+
+ this.active = false;
+ this.dragging = false;
+ this.disabled = false;
+
+ if (this.options.disabled) this.setDisabled();
+
+ // Allowed values array
+ this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
+ if (this.allowedValues) {
+ this.minimum = this.allowedValues.min();
+ this.maximum = this.allowedValues.max();
+ }
+
+ this.eventMouseDown = this.startDrag.bindAsEventListener(this);
+ this.eventMouseUp = this.endDrag.bindAsEventListener(this);
+ this.eventMouseMove = this.update.bindAsEventListener(this);
+
+ // Initialize handles in reverse (make sure first handle is active)
+ this.handles.each( function(h,i) {
+ i = slider.handles.length-1-i;
+ slider.setValue(parseFloat(
+ (Object.isArray(slider.options.sliderValue) ?
+ slider.options.sliderValue[i] : slider.options.sliderValue) ||
+ slider.range.start), i);
+ h.makePositioned().observe("mousedown", slider.eventMouseDown);
+ });
+
+ this.track.observe("mousedown", this.eventMouseDown);
+ document.observe("mouseup", this.eventMouseUp);
+ document.observe("mousemove", this.eventMouseMove);
+
+ this.initialized = true;
+ },
+ dispose: function() {
+ var slider = this;
+ Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
+ Event.stopObserving(document, "mouseup", this.eventMouseUp);
+ Event.stopObserving(document, "mousemove", this.eventMouseMove);
+ this.handles.each( function(h) {
+ Event.stopObserving(h, "mousedown", slider.eventMouseDown);
+ });
+ },
+ setDisabled: function(){
+ this.disabled = true;
+ },
+ setEnabled: function(){
+ this.disabled = false;
+ },
+ getNearestValue: function(value){
+ if (this.allowedValues){
+ if (value >= this.allowedValues.max()) return(this.allowedValues.max());
+ if (value <= this.allowedValues.min()) return(this.allowedValues.min());
+
+ var offset = Math.abs(this.allowedValues[0] - value);
+ var newValue = this.allowedValues[0];
+ this.allowedValues.each( function(v) {
+ var currentOffset = Math.abs(v - value);
+ if (currentOffset <= offset){
+ newValue = v;
+ offset = currentOffset;
+ }
+ });
+ return newValue;
+ }
+ if (value > this.range.end) return this.range.end;
+ if (value < this.range.start) return this.range.start;
+ return value;
+ },
+ setValue: function(sliderValue, handleIdx){
+ if (!this.active) {
+ this.activeHandleIdx = handleIdx || 0;
+ this.activeHandle = this.handles[this.activeHandleIdx];
+ this.updateStyles();
+ }
+ handleIdx = handleIdx || this.activeHandleIdx || 0;
+ if (this.initialized && this.restricted) {
+ if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
+ sliderValue = this.values[handleIdx-1];
+ if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
+ sliderValue = this.values[handleIdx+1];
+ }
+ sliderValue = this.getNearestValue(sliderValue);
+ this.values[handleIdx] = sliderValue;
+ this.value = this.values[0]; // assure backwards compat
+
+ this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] =
+ this.translateToPx(sliderValue);
+
+ this.drawSpans();
+ if (!this.dragging || !this.event) this.updateFinished();
+ },
+ setValueBy: function(delta, handleIdx) {
+ this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta,
+ handleIdx || this.activeHandleIdx || 0);
+ },
+ translateToPx: function(value) {
+ return Math.round(
+ ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) *
+ (value - this.range.start)) + "px";
+ },
+ translateToValue: function(offset) {
+ return ((offset/(this.trackLength-this.handleLength) *
+ (this.range.end-this.range.start)) + this.range.start);
+ },
+ getRange: function(range) {
+ var v = this.values.sortBy(Prototype.K);
+ range = range || 0;
+ return $R(v[range],v[range+1]);
+ },
+ minimumOffset: function(){
+ return(this.isVertical() ? this.alignY : this.alignX);
+ },
+ maximumOffset: function(){
+ return(this.isVertical() ?
+ (this.track.offsetHeight != 0 ? this.track.offsetHeight :
+ this.track.style.height.replace(/px$/,"")) - this.alignY :
+ (this.track.offsetWidth != 0 ? this.track.offsetWidth :
+ this.track.style.width.replace(/px$/,"")) - this.alignX);
+ },
+ isVertical: function(){
+ return (this.axis == 'vertical');
+ },
+ drawSpans: function() {
+ var slider = this;
+ if (this.spans)
+ $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
+ if (this.options.startSpan)
+ this.setSpan(this.options.startSpan,
+ $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
+ if (this.options.endSpan)
+ this.setSpan(this.options.endSpan,
+ $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
+ },
+ setSpan: function(span, range) {
+ if (this.isVertical()) {
+ span.style.top = this.translateToPx(range.start);
+ span.style.height = this.translateToPx(range.end - range.start + this.range.start);
+ } else {
+ span.style.left = this.translateToPx(range.start);
+ span.style.width = this.translateToPx(range.end - range.start + this.range.start);
+ }
+ },
+ updateStyles: function() {
+ this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
+ Element.addClassName(this.activeHandle, 'selected');
+ },
+ startDrag: function(event) {
+ if (Event.isLeftClick(event)) {
+ if (!this.disabled){
+ this.active = true;
+
+ var handle = Event.element(event);
+ var pointer = [Event.pointerX(event), Event.pointerY(event)];
+ var track = handle;
+ if (track==this.track) {
+ var offsets = this.track.cumulativeOffset();
+ this.event = event;
+ this.setValue(this.translateToValue(
+ (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
+ ));
+ var offsets = this.activeHandle.cumulativeOffset();
+ this.offsetX = (pointer[0] - offsets[0]);
+ this.offsetY = (pointer[1] - offsets[1]);
+ } else {
+ // find the handle (prevents issues with Safari)
+ while((this.handles.indexOf(handle) == -1) && handle.parentNode)
+ handle = handle.parentNode;
+
+ if (this.handles.indexOf(handle)!=-1) {
+ this.activeHandle = handle;
+ this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
+ this.updateStyles();
+
+ var offsets = this.activeHandle.cumulativeOffset();
+ this.offsetX = (pointer[0] - offsets[0]);
+ this.offsetY = (pointer[1] - offsets[1]);
+ }
+ }
+ }
+ Event.stop(event);
+ }
+ },
+ update: function(event) {
+ if (this.active) {
+ if (!this.dragging) this.dragging = true;
+ this.draw(event);
+ if (Prototype.Browser.WebKit) window.scrollBy(0,0);
+ Event.stop(event);
+ }
+ },
+ draw: function(event) {
+ var pointer = [Event.pointerX(event), Event.pointerY(event)];
+ var offsets = this.track.cumulativeOffset();
+ pointer[0] -= this.offsetX + offsets[0];
+ pointer[1] -= this.offsetY + offsets[1];
+ this.event = event;
+ this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
+ if (this.initialized && this.options.onSlide)
+ this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
+ },
+ endDrag: function(event) {
+ if (this.active && this.dragging) {
+ this.finishDrag(event, true);
+ Event.stop(event);
+ }
+ this.active = false;
+ this.dragging = false;
+ },
+ finishDrag: function(event, success) {
+ this.active = false;
+ this.dragging = false;
+ this.updateFinished();
+ },
+ updateFinished: function() {
+ if (this.initialized && this.options.onChange)
+ this.options.onChange(this.values.length>1 ? this.values : this.value, this);
+ this.event = null;
+ }
+});
\ No newline at end of file
--- /dev/null
+// script.aculo.us sound.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+//
+// Based on code created by Jules Gravinese (http://www.webveteran.com/)
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+Sound = {
+ tracks: {},
+ _enabled: true,
+ template:
+ new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),
+ enable: function(){
+ Sound._enabled = true;
+ },
+ disable: function(){
+ Sound._enabled = false;
+ },
+ play: function(url){
+ if(!Sound._enabled) return;
+ var options = Object.extend({
+ track: 'global', url: url, replace: false
+ }, arguments[1] || {});
+
+ if(options.replace && this.tracks[options.track]) {
+ $R(0, this.tracks[options.track].id).each(function(id){
+ var sound = $$('sound_'+options.track+'_'+id);
+ sound.Stop && sound.Stop();
+ sound.remove();
+ });
+ this.tracks[options.track] = null;
+ }
+
+ if(!this.tracks[options.track])
+ this.tracks[options.track] = { id: 0 };
+ else
+ this.tracks[options.track].id++;
+
+ options.id = this.tracks[options.track].id;
+ $$$('body')[0].insert(
+ Prototype.Browser.IE ? new Element('bgsound',{
+ id: 'sound_'+options.track+'_'+options.id,
+ src: options.url, loop: 1, autostart: true
+ }) : Sound.template.evaluate(options));
+ }
+};
+
+if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){
+ if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 }))
+ Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>');
+ else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('Windows Media') != -1 }))
+ Sound.template = new Template('<object id="sound_#{track}_#{id}" type="application/x-mplayer2" data="#{url}"></object>');
+ else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('RealPlayer') != -1 }))
+ Sound.template = new Template('<embed type="audio/x-pn-realaudio-plugin" style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>');
+ else
+ Sound.play = function(){};
+}
\ No newline at end of file
--- /dev/null
+// script.aculo.us unittest.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
+// (c) 2005-2009 Michael Schuerig (http://www.schuerig.de/michael/)
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// experimental, Firefox-only
+Event.simulateMouse = function(element, eventName) {
+ var options = Object.extend({
+ pointerX: 0,
+ pointerY: 0,
+ buttons: 0,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ metaKey: false
+ }, arguments[2] || {});
+ var oEvent = document.createEvent("MouseEvents");
+ oEvent.initMouseEvent(eventName, true, true, document.defaultView,
+ options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
+ options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $$(element));
+
+ if(this.mark) Element.remove(this.mark);
+ this.mark = document.createElement('div');
+ this.mark.appendChild(document.createTextNode(" "));
+ document.body.appendChild(this.mark);
+ this.mark.style.position = 'absolute';
+ this.mark.style.top = options.pointerY + "px";
+ this.mark.style.left = options.pointerX + "px";
+ this.mark.style.width = "5px";
+ this.mark.style.height = "5px;";
+ this.mark.style.borderTop = "1px solid red;";
+ this.mark.style.borderLeft = "1px solid red;";
+
+ if(this.step)
+ alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
+
+ $$(element).dispatchEvent(oEvent);
+};
+
+// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
+// You need to downgrade to 1.0.4 for now to get this working
+// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
+Event.simulateKey = function(element, eventName) {
+ var options = Object.extend({
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ metaKey: false,
+ keyCode: 0,
+ charCode: 0
+ }, arguments[2] || {});
+
+ var oEvent = document.createEvent("KeyEvents");
+ oEvent.initKeyEvent(eventName, true, true, window,
+ options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
+ options.keyCode, options.charCode );
+ $$(element).dispatchEvent(oEvent);
+};
+
+Event.simulateKeys = function(element, command) {
+ for(var i=0; i<command.length; i++) {
+ Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
+ }
+};
+
+var Test = {};
+Test.Unit = {};
+
+// security exception workaround
+Test.Unit.inspect = Object.inspect;
+
+Test.Unit.Logger = Class.create();
+Test.Unit.Logger.prototype = {
+ initialize: function(log) {
+ this.log = $$(log);
+ if (this.log) {
+ this._createLogTable();
+ }
+ },
+ start: function(testName) {
+ if (!this.log) return;
+ this.testName = testName;
+ this.lastLogLine = document.createElement('tr');
+ this.statusCell = document.createElement('td');
+ this.nameCell = document.createElement('td');
+ this.nameCell.className = "nameCell";
+ this.nameCell.appendChild(document.createTextNode(testName));
+ this.messageCell = document.createElement('td');
+ this.lastLogLine.appendChild(this.statusCell);
+ this.lastLogLine.appendChild(this.nameCell);
+ this.lastLogLine.appendChild(this.messageCell);
+ this.loglines.appendChild(this.lastLogLine);
+ },
+ finish: function(status, summary) {
+ if (!this.log) return;
+ this.lastLogLine.className = status;
+ this.statusCell.innerHTML = status;
+ this.messageCell.innerHTML = this._toHTML(summary);
+ this.addLinksToResults();
+ },
+ message: function(message) {
+ if (!this.log) return;
+ this.messageCell.innerHTML = this._toHTML(message);
+ },
+ summary: function(summary) {
+ if (!this.log) return;
+ this.logsummary.innerHTML = this._toHTML(summary);
+ },
+ _createLogTable: function() {
+ this.log.innerHTML =
+ '<div id="logsummary"></div>' +
+ '<table id="logtable">' +
+ '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
+ '<tbody id="loglines"></tbody>' +
+ '</table>';
+ this.logsummary = $$('logsummary');
+ this.loglines = $$('loglines');
+ },
+ _toHTML: function(txt) {
+ return txt.escapeHTML().replace(/\n/g,"<br/>");
+ },
+ addLinksToResults: function(){
+ $$$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
+ td.title = "Run only this test";
+ Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
+ });
+ $$$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
+ td.title = "Run all tests";
+ Event.observe(td, 'click', function(){ window.location.search = "";});
+ });
+ }
+};
+
+Test.Unit.Runner = Class.create();
+Test.Unit.Runner.prototype = {
+ initialize: function(testcases) {
+ this.options = Object.extend({
+ testLog: 'testlog'
+ }, arguments[1] || {});
+ this.options.resultsURL = this.parseResultsURLQueryParameter();
+ this.options.tests = this.parseTestsQueryParameter();
+ if (this.options.testLog) {
+ this.options.testLog = $$(this.options.testLog) || null;
+ }
+ if(this.options.tests) {
+ this.tests = [];
+ for(var i = 0; i < this.options.tests.length; i++) {
+ if(/^test/.test(this.options.tests[i])) {
+ this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
+ }
+ }
+ } else {
+ if (this.options.test) {
+ this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
+ } else {
+ this.tests = [];
+ for(var testcase in testcases) {
+ if(/^test/.test(testcase)) {
+ this.tests.push(
+ new Test.Unit.Testcase(
+ this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
+ testcases[testcase], testcases["setup"], testcases["teardown"]
+ ));
+ }
+ }
+ }
+ }
+ this.currentTest = 0;
+ this.logger = new Test.Unit.Logger(this.options.testLog);
+ setTimeout(this.runTests.bind(this), 1000);
+ },
+ parseResultsURLQueryParameter: function() {
+ return window.location.search.parseQuery()["resultsURL"];
+ },
+ parseTestsQueryParameter: function(){
+ if (window.location.search.parseQuery()["tests"]){
+ return window.location.search.parseQuery()["tests"].split(',');
+ };
+ },
+ // Returns:
+ // "ERROR" if there was an error,
+ // "FAILURE" if there was a failure, or
+ // "SUCCESS" if there was neither
+ getResult: function() {
+ var hasFailure = false;
+ for(var i=0;i<this.tests.length;i++) {
+ if (this.tests[i].errors > 0) {
+ return "ERROR";
+ }
+ if (this.tests[i].failures > 0) {
+ hasFailure = true;
+ }
+ }
+ if (hasFailure) {
+ return "FAILURE";
+ } else {
+ return "SUCCESS";
+ }
+ },
+ postResults: function() {
+ if (this.options.resultsURL) {
+ new Ajax.Request(this.options.resultsURL,
+ { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
+ }
+ },
+ runTests: function() {
+ var test = this.tests[this.currentTest];
+ if (!test) {
+ // finished!
+ this.postResults();
+ this.logger.summary(this.summary());
+ return;
+ }
+ if(!test.isWaiting) {
+ this.logger.start(test.name);
+ }
+ test.run();
+ if(test.isWaiting) {
+ this.logger.message("Waiting for " + test.timeToWait + "ms");
+ setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
+ } else {
+ this.logger.finish(test.status(), test.summary());
+ this.currentTest++;
+ // tail recursive, hopefully the browser will skip the stackframe
+ this.runTests();
+ }
+ },
+ summary: function() {
+ var assertions = 0;
+ var failures = 0;
+ var errors = 0;
+ var messages = [];
+ for(var i=0;i<this.tests.length;i++) {
+ assertions += this.tests[i].assertions;
+ failures += this.tests[i].failures;
+ errors += this.tests[i].errors;
+ }
+ return (
+ (this.options.context ? this.options.context + ': ': '') +
+ this.tests.length + " tests, " +
+ assertions + " assertions, " +
+ failures + " failures, " +
+ errors + " errors");
+ }
+};
+
+Test.Unit.Assertions = Class.create();
+Test.Unit.Assertions.prototype = {
+ initialize: function() {
+ this.assertions = 0;
+ this.failures = 0;
+ this.errors = 0;
+ this.messages = [];
+ },
+ summary: function() {
+ return (
+ this.assertions + " assertions, " +
+ this.failures + " failures, " +
+ this.errors + " errors" + "\n" +
+ this.messages.join("\n"));
+ },
+ pass: function() {
+ this.assertions++;
+ },
+ fail: function(message) {
+ this.failures++;
+ this.messages.push("Failure: " + message);
+ },
+ info: function(message) {
+ this.messages.push("Info: " + message);
+ },
+ error: function(error) {
+ this.errors++;
+ this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
+ },
+ status: function() {
+ if (this.failures > 0) return 'failed';
+ if (this.errors > 0) return 'error';
+ return 'passed';
+ },
+ assert: function(expression) {
+ var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
+ try { expression ? this.pass() :
+ this.fail(message); }
+ catch(e) { this.error(e); }
+ },
+ assertEqual: function(expected, actual) {
+ var message = arguments[2] || "assertEqual";
+ try { (expected == actual) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertInspect: function(expected, actual) {
+ var message = arguments[2] || "assertInspect";
+ try { (expected == actual.inspect()) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertEnumEqual: function(expected, actual) {
+ var message = arguments[2] || "assertEnumEqual";
+ try { $A(expected).length == $A(actual).length &&
+ expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
+ this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
+ ', actual ' + Test.Unit.inspect(actual)); }
+ catch(e) { this.error(e); }
+ },
+ assertNotEqual: function(expected, actual) {
+ var message = arguments[2] || "assertNotEqual";
+ try { (expected != actual) ? this.pass() :
+ this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertIdentical: function(expected, actual) {
+ var message = arguments[2] || "assertIdentical";
+ try { (expected === actual) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertNotIdentical: function(expected, actual) {
+ var message = arguments[2] || "assertNotIdentical";
+ try { !(expected === actual) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertNull: function(obj) {
+ var message = arguments[1] || 'assertNull';
+ try { (obj==null) ? this.pass() :
+ this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertMatch: function(expected, actual) {
+ var message = arguments[2] || 'assertMatch';
+ var regex = new RegExp(expected);
+ try { (regex.exec(actual)) ? this.pass() :
+ this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertHidden: function(element) {
+ var message = arguments[1] || 'assertHidden';
+ this.assertEqual("none", element.style.display, message);
+ },
+ assertNotNull: function(object) {
+ var message = arguments[1] || 'assertNotNull';
+ this.assert(object != null, message);
+ },
+ assertType: function(expected, actual) {
+ var message = arguments[2] || 'assertType';
+ try {
+ (actual.constructor == expected) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + (actual.constructor) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertNotOfType: function(expected, actual) {
+ var message = arguments[2] || 'assertNotOfType';
+ try {
+ (actual.constructor != expected) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + (actual.constructor) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertInstanceOf: function(expected, actual) {
+ var message = arguments[2] || 'assertInstanceOf';
+ try {
+ (actual instanceof expected) ? this.pass() :
+ this.fail(message + ": object was not an instance of the expected type"); }
+ catch(e) { this.error(e); }
+ },
+ assertNotInstanceOf: function(expected, actual) {
+ var message = arguments[2] || 'assertNotInstanceOf';
+ try {
+ !(actual instanceof expected) ? this.pass() :
+ this.fail(message + ": object was an instance of the not expected type"); }
+ catch(e) { this.error(e); }
+ },
+ assertRespondsTo: function(method, obj) {
+ var message = arguments[2] || 'assertRespondsTo';
+ try {
+ (obj[method] && typeof obj[method] == 'function') ? this.pass() :
+ this.fail(message + ": object doesn't respond to [" + method + "]"); }
+ catch(e) { this.error(e); }
+ },
+ assertReturnsTrue: function(method, obj) {
+ var message = arguments[2] || 'assertReturnsTrue';
+ try {
+ var m = obj[method];
+ if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
+ m() ? this.pass() :
+ this.fail(message + ": method returned false"); }
+ catch(e) { this.error(e); }
+ },
+ assertReturnsFalse: function(method, obj) {
+ var message = arguments[2] || 'assertReturnsFalse';
+ try {
+ var m = obj[method];
+ if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
+ !m() ? this.pass() :
+ this.fail(message + ": method returned true"); }
+ catch(e) { this.error(e); }
+ },
+ assertRaise: function(exceptionName, method) {
+ var message = arguments[2] || 'assertRaise';
+ try {
+ method();
+ this.fail(message + ": exception expected but none was raised"); }
+ catch(e) {
+ ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
+ }
+ },
+ assertElementsMatch: function() {
+ var expressions = $A(arguments), elements = $A(expressions.shift());
+ if (elements.length != expressions.length) {
+ this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
+ return false;
+ }
+ elements.zip(expressions).all(function(pair, index) {
+ var element = $$(pair.first()), expression = pair.last();
+ if (element.match(expression)) return true;
+ this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
+ }.bind(this)) && this.pass();
+ },
+ assertElementMatches: function(element, expression) {
+ this.assertElementsMatch([element], expression);
+ },
+ benchmark: function(operation, iterations) {
+ var startAt = new Date();
+ (iterations || 1).times(operation);
+ var timeTaken = ((new Date())-startAt);
+ this.info((arguments[2] || 'Operation') + ' finished ' +
+ iterations + ' iterations in ' + (timeTaken/1000)+'s' );
+ return timeTaken;
+ },
+ _isVisible: function(element) {
+ element = $$(element);
+ if(!element.parentNode) return true;
+ this.assertNotNull(element);
+ if(element.style && Element.getStyle(element, 'display') == 'none')
+ return false;
+
+ return this._isVisible(element.parentNode);
+ },
+ assertNotVisible: function(element) {
+ this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
+ },
+ assertVisible: function(element) {
+ this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
+ },
+ benchmark: function(operation, iterations) {
+ var startAt = new Date();
+ (iterations || 1).times(operation);
+ var timeTaken = ((new Date())-startAt);
+ this.info((arguments[2] || 'Operation') + ' finished ' +
+ iterations + ' iterations in ' + (timeTaken/1000)+'s' );
+ return timeTaken;
+ }
+};
+
+Test.Unit.Testcase = Class.create();
+Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
+ initialize: function(name, test, setup, teardown) {
+ Test.Unit.Assertions.prototype.initialize.bind(this)();
+ this.name = name;
+
+ if(typeof test == 'string') {
+ test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
+ test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
+ this.test = function() {
+ eval('with(this){'+test+'}');
+ }
+ } else {
+ this.test = test || function() {};
+ }
+
+ this.setup = setup || function() {};
+ this.teardown = teardown || function() {};
+ this.isWaiting = false;
+ this.timeToWait = 1000;
+ },
+ wait: function(time, nextPart) {
+ this.isWaiting = true;
+ this.test = nextPart;
+ this.timeToWait = time;
+ },
+ run: function() {
+ try {
+ try {
+ if (!this.isWaiting) this.setup.bind(this)();
+ this.isWaiting = false;
+ this.test.bind(this)();
+ } finally {
+ if(!this.isWaiting) {
+ this.teardown.bind(this)();
+ }
+ }
+ }
+ catch(e) { this.error(e); }
+ }
+});
+
+// *EXPERIMENTAL* BDD-style testing to please non-technical folk
+// This draws many ideas from RSpec http://rspec.rubyforge.org/
+
+Test.setupBDDExtensionMethods = function(){
+ var METHODMAP = {
+ shouldEqual: 'assertEqual',
+ shouldNotEqual: 'assertNotEqual',
+ shouldEqualEnum: 'assertEnumEqual',
+ shouldBeA: 'assertType',
+ shouldNotBeA: 'assertNotOfType',
+ shouldBeAn: 'assertType',
+ shouldNotBeAn: 'assertNotOfType',
+ shouldBeNull: 'assertNull',
+ shouldNotBeNull: 'assertNotNull',
+
+ shouldBe: 'assertReturnsTrue',
+ shouldNotBe: 'assertReturnsFalse',
+ shouldRespondTo: 'assertRespondsTo'
+ };
+ var makeAssertion = function(assertion, args, object) {
+ this[assertion].apply(this,(args || []).concat([object]));
+ };
+
+ Test.BDDMethods = {};
+ $H(METHODMAP).each(function(pair) {
+ Test.BDDMethods[pair.key] = function() {
+ var args = $A(arguments);
+ var scope = args.shift();
+ makeAssertion.apply(scope, [pair.value, args, this]); };
+ });
+
+ [Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each(
+ function(p){ Object.extend(p, Test.BDDMethods) }
+ );
+};
+
+Test.context = function(name, spec, log){
+ Test.setupBDDExtensionMethods();
+
+ var compiledSpec = {};
+ var titles = {};
+ for(specName in spec) {
+ switch(specName){
+ case "setup":
+ case "teardown":
+ compiledSpec[specName] = spec[specName];
+ break;
+ default:
+ var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
+ var body = spec[specName].toString().split('\n').slice(1);
+ if(/^\{/.test(body[0])) body = body.slice(1);
+ body.pop();
+ body = body.map(function(statement){
+ return statement.strip()
+ });
+ compiledSpec[testName] = body.join('\n');
+ titles[testName] = specName;
+ }
+ }
+ new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
+};
\ No newline at end of file
--- /dev/null
+var splitFilhos = "!!!";\r
+var splitArgs = ",";\r
+var filhoPadraoIni = "<select class='input' id='$ID$' name='$NAME$' onchange='javascript: ai(this, \"$HDNPAI$\");'>";\r
+var filhoPadraoOp1 = "<option value=''>Selecione</option>";\r
+var filhoPadraoOp2 = "<option value=''>------</option>";\r
+var filhoPadraoFim = "</select><div id='$ID$_div' style='padding-top: 5px;'></div>"\r
+var routinePath = "../../manager/routines/form/routines.php";\r
+\r
+function selectValue(select,value){\r
+ for (x=0;x<select.length;x++){\r
+ if (select.options[x].value == value){\r
+ select.selectedIndex = x;\r
+ return;\r
+ }\r
+ }\r
+}\r
+function selecionaPaiAtual(paiAtual) {\r
+ line_pais = $$(getLabelPai(paiAtual)+"_linha_pais").value;\r
+ //alert("line_pais\n\n"+line_pais);\r
+ if (line_pais != "") {\r
+ arr_pais = line_pais.split(splitArgs);\r
+ pai_atual = "";\r
+ if (arr_pais) {\r
+ if (arr_pais.length > 0) {\r
+ pai_atual = arr_pais.shift();\r
+ line_pais = arr_pais.join(splitArgs);\r
+ $$(getLabelPai(paiAtual)+"_linha_pais").value = line_pais;\r
+ //alert("pai_atual:\n\n"+pai_atual+"\n\nnova line_pais:\n\n"+line_pais);\r
+ \r
+ selectValue(paiAtual, pai_atual);\r
+ }\r
+ }\r
+ }\r
+}\r
+function ai(paiAtual, hdnPai) {\r
+ selecionaPaiAtual(paiAtual);\r
+ \r
+ if ((paiAtual.value != "0") && (paiAtual.value != ""))\r
+ $$(hdnPai).value = paiAtual.value;\r
+ \r
+ zeraFilhos(paiAtual);\r
+ var a = new Ajax();\r
+ \r
+ a.onLoad = function() {\r
+ if (this.html != "") {\r
+ //verificar se existem filhos, se existe mais de um, deve-se apaga-los\r
+ //zerar ou criar o próximo filho\r
+ var newFilhoId = newFilho(paiAtual, hdnPai);\r
+ //alert(newFilhoId);\r
+ //alert(this.html);\r
+\r
+ values = this.html;\r
+ arr_options = values.split('#');\r
+ selected = 0;\r
+ \r
+ for(x=0,total = arr_options.length;x<total;x++) {\r
+ value_option = arr_options[x].split('+');\r
+ $$(newFilhoId).options[x] = new Option(value_option[1],value_option[0]);\r
+ }\r
+ if ($$(getLabelPai(paiAtual)+"_linha_pais").value != "")\r
+ $$(newFilhoId).onchange();\r
+ }else{\r
+ \r
+ }\r
+ }\r
+ strArgs = getStrArgs(paiAtual);\r
+ strArgs = strArgs+"&id="+paiAtual.value;\r
+ a.get(routinePath+strArgs);\r
+}\r
+function zeraFilhos(paiAtual) {\r
+ if ($$(getLabelPai(paiAtual)+'_filhos')) {\r
+ if ($$(getLabelPai(paiAtual)+'_filhos').value != '') {\r
+ oldFilhos = $$(getLabelPai(paiAtual)+'_filhos').value;\r
+ pos = oldFilhos.search(paiAtual.id);\r
+ //alert("pos: \n\n"+pos);\r
+ if (pos > -1) {\r
+ filhos = oldFilhos.substr(0, parseInt(pos+paiAtual.id.length));\r
+ //alert("velhos filhos:\n"+oldFilhos+"\n\nfilhos novos\n"+filhos);\r
+ $$(getLabelPai(paiAtual)+'_filhos').value = filhos;\r
+ }else{\r
+ filhos = "";//se não encontrou nos filhos, é o pai\r
+ $$(getLabelPai(paiAtual)+'_filhos').value = filhos;\r
+ }\r
+ }\r
+ }\r
+ $$(paiAtual.id+"_div").innerHTML = "";\r
+}\r
+function getLabelPai(campo) {\r
+ arr_names = campo.id.split('_');\r
+ return arr_names[0];\r
+}\r
+function getLabel(campo) {\r
+ //alert("em getLabel, campo.id = "+campo.id);\r
+ arr_names = campo.id.split('_');\r
+ name = "";\r
+ \r
+ for(x=0;x<arr_names.length-1;x++){\r
+ name = name+arr_names[x];\r
+ }\r
+ return name;\r
+}\r
+function getFilhos(paiAtual) {\r
+ var arr_filhos = new Array();\r
+ if ($$(getLabelPai(paiAtual)+'_filhos')) {\r
+ if ($$(getLabelPai(paiAtual)+'_filhos').value != '') {\r
+ arr_filhos = $$(getLabelPai(paiAtual)+'_filhos').value.split(splitFilhos);\r
+ }\r
+ }\r
+ return arr_filhos;\r
+}\r
+function newFilho(paiAtual, hdnPai) {\r
+ newFilhoId = newHtmlFilho(paiAtual, hdnPai); \r
+ return newFilhoId;\r
+}\r
+function newHtmlFilho(paiAtual, hdnPai) {\r
+ ultimoFilhoIndex = getUltimoFilhoIndex(paiAtual);\r
+ \r
+ newFilhoId = getLabel(paiAtual)+"_"+ultimoFilhoIndex;\r
+ filhoIni = filhoPadraoIni.replace("$ID$", newFilhoId);\r
+ filhoIni = filhoIni.replace("$HDNPAI$", hdnPai);\r
+ filhoIni = filhoIni.replace("$NAME$", getLabel(paiAtual)+"_"+ultimoFilhoIndex);\r
+ filhoFim = filhoPadraoFim.replace("$ID$", getLabel(paiAtual)+"_"+ultimoFilhoIndex);\r
+ //alert("novo filho\n\n"+filhoIni+filhoPadraoOp1+filhoPadraoOp2+filhoFim);\r
+ \r
+ divPai = $$(paiAtual.id+'_div');\r
+ //alert("div do novo filho:\n\n"+paiAtual.id+'_div');\r
+ hdnFilhos = $$(getLabel(paiAtual)+'_filhos');\r
+ \r
+ //alert("hdn filhos: "+hdnFilhos.value+"\n\ndivPai innerHtml: "+divPai.innerHTML);\r
+ \r
+ divPai.innerHTML = filhoIni+filhoPadraoOp1+filhoPadraoOp2+filhoFim\r
+ arr_filhos = getFilhos(paiAtual);\r
+ arr_filhos.push(newFilhoId);\r
+ hdnFilhos.value = arr_filhos.join(splitFilhos);\r
+ \r
+ //alert("hdn filhos: "+hdnFilhos.value+"\n\ndivPai innerHtml: "+divPai.innerHTML);\r
+ \r
+ \r
+ return newFilhoId;\r
+}\r
+function getUltimoFilhoIndex(paiAtual) {\r
+ var arr_filhos = getFilhos(paiAtual);\r
+ \r
+ ultimoFilhoIndex = 0;\r
+ //alert(arr_filhos);\r
+ if (arr_filhos.length > 0) {\r
+ ultimoFilho = arr_filhos[arr_filhos.length-1];\r
+ arr_ultimoFilho = ultimoFilho.split('_');\r
+ ultimoFilhoIndex = (parseInt(arr_ultimoFilho[arr_ultimoFilho.length-1])+1);\r
+ }\r
+ \r
+ //alert(ultimoFilhoIndex);\r
+ \r
+ return ultimoFilhoIndex;\r
+}\r
+function newFilhoIndex(paiAtual){\r
+ return getUltimoFilhoIndex(paiAtual)+1;\r
+}\r
+function getArgs(paiAtual){\r
+ var arr_args = new Array();\r
+ if ($$(getLabel(paiAtual)+'_args')) {\r
+ if ($$(getLabel(paiAtual)+'_args').value != '') {\r
+ arr_args = $$(getLabel(paiAtual)+'_args').value.split(splitArgs);\r
+ }\r
+ }\r
+ return arr_args;\r
+}\r
+function getStrArgs(paiAtual){\r
+ var str = "?routine=refresh_tree";\r
+ var arg = "&arg";\r
+ var arr_args = getArgs(paiAtual);\r
+ for (x=0;x<arr_args.length;x++) {\r
+ str = str + arg+x+"="+arr_args[x];\r
+ }\r
+ return str;\r
+}\r
+function loadFromFilho(paiAtual) {\r
+ paiAtual.onchange();\r
+}
\ No newline at end of file
--- /dev/null
+<html>
+ <head>
+ <meta http-equiv="refresh" content="0;url=routines/system/login.php" />
+ </head>
+</html>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../app.php");\r
+include("../../inc/inc.restrict.php");\r
+include("../../inc/inc.menu.php");\r
+\r
+global $profile;\r
+global $routine;\r
+global $form;\r
+global $tmp_id;\r
+\r
+$output->ajaxHeader();\r
+\r
+//form class\r
+$sub = $menu->getSub();\r
+$load->config("forms/Form" . ucfirst($sub->class) . ".php");\r
+$class = "Form" . $sub->class;\r
+$form = new $class();\r
+\r
+//routine\r
+$routine = $input->get("routine");\r
+if ($routine == "insert") {\r
+ $button_img = "insert";\r
+ $flag = "I";\r
+ $fraseConfirmacao = 'Você tem certeza que deseja inserir este registro?';\r
+ \r
+ $tmp_id = (string)(rand(999999, 9999999) * 1000); //Random id for upload fields\r
+} else {\r
+ $form->fields[$form->key_field] = $input->get("id");\r
+ $form->select();\r
+ $fraseConfirmacao = 'Você tem certeza que deseja alterar este registro?';\r
+ \r
+ //$button_img = "update";\r
+ $button_img = "save";\r
+ $flag = "U";\r
+}\r
+\r
+//count for htmleditors fields\r
+global $htmleditor_count;\r
+$htmleditor_count = 1;\r
+\r
+\r
+if ((IS_LOCAL) && (IS_DEVELOP)) {\r
+ ?><div style="text-align: center;"><a href="javascript: ajaxGet('<?= $_SERVER['PHP_SELF']; ?>?menu=<?= $_GET["menu"]; ?>&routine=<?= $_GET["routine"]; ?>&id=<?= $form->fields[$form->key_field]; ?>');">refresh</a></div><br><?\r
+}\r
+\r
+$form->loadInitAll($flag);\r
+\r
+/*\r
+adicionada condição conforme nivel de usuario\r
+1 - administrador\r
+2 - professor\r
+*/\r
+$show = true;\r
+if($routine == 'update'){\r
+ if($profile->fields('nivel') == 2){//é professpr\r
+ if(isset($form->fields['id_usuario'])){//existe o campo\r
+ if($form->fields['id_usuario'] != $profile->fields('id')){//caso id_usuario seja diferente do id do usuario logado\r
+ $show = false;\r
+ }\r
+ }\r
+ }\r
+}\r
+?>\r
+<script>\r
+menu = '<?= $input->request("menu"); ?>';\r
+routine = '<?= $routine; ?>';\r
+tmp_id = '<?= $tmp_id; ?>';\r
+id = '<?= $input->get("id"); ?>';\r
+\r
+customPrePost = function () {\r
+ var ok = true;\r
+ var routine = '<?= $routine; ?>';\r
+ \r
+ <?= $form->_loadJSPrePost($flag); ?>\r
+ \r
+ if (ok) {\r
+ if(confirm('<?=$fraseConfirmacao;?>')){\r
+ formSubmit();\r
+ }\r
+ }\r
+}\r
+</script>\r
+<div style="height:27px;">\r
+ <table cellspacing="0" cellpadding="0" width="968" height="16">\r
+ <tr>\r
+ <td align="left">\r
+ Campos marcados com <font class="red">*</font> são obrigatórios.\r
+ </td>\r
+ <td width="150" align="right">\r
+ <? if (($routine == "update") && ($form->testFlag("D")) && ($show)) { ?>\r
+ <a href="javascript: { if (confirm('Deseja realmente excluir este item?')) { ajaxGet('form/routines.php?menu=<?= $input->request("menu"); ?>&routine=delete&id=<?= $form->fields[$form->key_field]; ?>'); } }" title="Excluir registro"><img src="../img/buttons/del.jpg" alt="Excluir"></a>\r
+ <? } ?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+</div>\r
+<form id="frm_form" name="frm_form" action="form/routines.php?menu=<?= $input->request("menu"); ?>&routine=<?= $routine; ?>&id=<?= $form->fields["id"]; ?>" method="post" onsubmit="return false;">\r
+<input type="hidden" name="tmp_id" value="<?= $tmp_id; ?>" />\r
+<div class="form">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <tr>\r
+ <td width="49%" valign="top">\r
+ <table cellspacing="3" cellpadding="0" width="100%">\r
+ <?\r
+ $fields = $form->getFieldSet();\r
+ \r
+ foreach ($fields as $k => $v) {\r
+ if ($v->testFlag($flag)) {\r
+ echo $v->getHtml() . CRLF;\r
+ }\r
+ }\r
+ ?>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+</div>\r
+<div class="sep">\r
+ <div align="right">\r
+ <? \r
+ if (($routine == "update") && (!$form->enable_update)) {\r
+ $show = false;\r
+ }\r
+ \r
+ if ($show) {\r
+ ?>\r
+ <input type="image" src="../img/buttons/<?= $button_img; ?>.jpg" onclick="javascript: prePost();"> \r
+ <input type="image" src="../img/buttons/cancel.jpg" onclick="javascript: ajaxGet('form/list.php?menu=<?= $input->get("menu"); ?>');" />\r
+ <?\r
+ } else {\r
+ ?>\r
+ <input type="image" src="../img/buttons/back.jpg" onclick="javascript: ajaxGet('form/list.php?menu=<?= $input->get("menu"); ?>');" />\r
+ <?\r
+ }\r
+ ?> \r
+ </div>\r
+</div>\r
+<script>\r
+f.maskFields();\r
+</script>\r
+</form>\r
+<?\r
+$debug->loadList();\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../app.php");\r
+include("../../inc/inc.restrict.php");\r
+include("../../inc/inc.menu.php");\r
+\r
+global $routine;\r
+global $form;\r
+\r
+$output->ajaxHeader();\r
+\r
+$sub = $menu->getSub();\r
+$load->config("forms/Form" . ucfirst($sub->class) . ".php");\r
+$class = "Form" . $sub->class;\r
+$form = new $class();\r
+\r
+//if is a form only\r
+if ($form->is_unique) {\r
+ redir("form.php?menu=" . $input->request("menu") . "&routine=insert");\r
+ die();\r
+}\r
+\r
+//headers\r
+$routine = "O";\r
+$headers = $form->getHeaders();\r
+\r
+//filters\r
+$routine = "F";\r
+$filters = $form->getFilters();\r
+\r
+\r
+//Reset fieldset for list\r
+$routine = "L";\r
+$form->resetFieldSet();\r
+\r
+\r
+//procces query/page\r
+$records_total = 0;\r
+if (($filters["sql"] != "") || ($form->show_list_init)) {\r
+ //.query\r
+ $sql = $form->getListSql($filters["sql"], $headers["sql"]);\r
+ \r
+ $rs_list = $db->execute($sql);\r
+ \r
+ //.page\r
+ $page = $form->getListPage();\r
+ $rs_list->pagesize = $form->page_size;\r
+ $records_total = $rs_list->recordCount();\r
+ \r
+ if ($records_total > $form->page_size) {\r
+ $rs_list->page($page);\r
+ }\r
+}\r
+\r
+//execute routine of button(if request)\r
+$old_routine = $routine;\r
+$routine = $input->get("routine");\r
+if ($routine == "list_button") {\r
+ $form->execButton($input->get("name"));\r
+ \r
+ die();\r
+}\r
+$routine = $old_routine;\r
+\r
+//load init of form and fields\r
+$form->loadInitAll("L");\r
+\r
+//display filters\r
+if (($filters["sql"] == "") && (!$form->show_filters_init)) {\r
+ $filters_display = "none";\r
+ $filters_img = "";\r
+} else { \r
+ $filters_display = ""; \r
+ $filters_img = "_disabled";\r
+}\r
+\r
+if ((IS_LOCAL) && (IS_DEVELOP)) {\r
+ ?><div style="text-align: center;"><a href="javascript: ajaxGet('<?= $_SERVER['PHP_SELF']; ?>');">refresh</a></div><br><?\r
+}\r
+?>\r
+<script>\r
+delete_enabled = <?= (($form->testFlag("D")) && ($profile->fields('nivel') == 1)) ? "true" : "false"; ?>;\r
+</script>\r
+<div>\r
+ <table cellspacing="0" cellpadding="0" width="968" height="16" border="0">\r
+ <tr>\r
+ <td width='80' align="left" nowrap>\r
+ <? if ($filters["html"] != "") { ?>\r
+ <a href="#" onClick="javascript: showHideFilters();" title="Mostrar/Esconder filtro(s)"><img id="img_filter" src="../img/buttons/filter<?= $filters_img; ?>.jpg"></a>\r
+ <? } ?>\r
+ </td>\r
+ <td width="150" nowrap>\r
+ <?\r
+ if ($records_total) {\r
+ ?>Listando <b><?= $records_total; ?></b> registro<? \r
+ \r
+ if ($records_total > 1) {\r
+ ?>s<?\r
+ }\r
+ }\r
+ ?></td>\r
+ <td align="center" width="100%">\r
+ <?\r
+ if ((($filters["sql"] != "") || ($form->show_list_init)) && ($rs_list->recordCount() > 0) && ($rs_list->pagecount > 1)) {\r
+ ?>\r
+ <table cellpadding="0" cellspacing="0">\r
+ <tr>\r
+ <td width="10" valign="middle">\r
+ <? if ($rs_list->absolutepage > 1) { ?>\r
+ <a href="#" onClick="javascript: listPage('<?= $rs_list->absolutepage-1 ?>');" title="Página anterior">Anterior</a>\r
+ <? } ?>\r
+ </td>\r
+ <td style="padding: 0 10 0 10px;" align="center">\r
+ <?\r
+ $i = 1;\r
+ if($rs_list->pagecount > 10){\r
+ if ($rs_list->absolutepage + 5 <= $rs_list->pagecount) {\r
+ $i = $rs_list->absolutepage - 5;\r
+ } else {\r
+ $i = $rs_list->pagecount - 9;\r
+ }\r
+ if($i <= 0){\r
+ $i = 1;\r
+ }\r
+ }\r
+ $counter = 0;\r
+ while (($i <= $rs_list->pagecount) && ($counter < 10)) {\r
+ if ($rs_list->absolutepage <> $i) {\r
+ ?><a href="javascript: listPage('<?= $i; ?>')" class="link"><?= $i; ?></a><?\r
+ } else {\r
+ ?><span style="color:#D7A964;font-size:11px;"><b><?= $i; ?></b></span><?\r
+ }\r
+ \r
+ if ($i < $rs_list->pagecount) {\r
+ ?> | <?\r
+ }\r
+ \r
+ $i++;\r
+ $counter++;\r
+ }\r
+ ?>\r
+ </td>\r
+ <td width="10" valign="middle">\r
+ <? if ($rs_list->absolutepage < $rs_list->pagecount) { ?>\r
+ <a href="#" onClick="javascript: listPage('<?= $rs_list->absolutepage+1; ?>');" title="Próxima página">Próximo</a>\r
+ <? } ?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <?\r
+ }\r
+ ?>\r
+ </td>\r
+ <td width="250" align="right" height="16" id="button_bar" nowrap>\r
+ <?\r
+ foreach ($form->_buttons as $v) {\r
+ $title = "";\r
+ if ($v["label"] != "") {\r
+ $title = "title=\"" . $v["label"] . "\"";\r
+ }\r
+ \r
+ \r
+ ?><a <?= $title; ?> href="javascript: nothing_func();" onclick="javascript: listButton('<?= $v["name"]; ?>'); "><img src="../../_config/img/<?= $v["name"]?>.gif" style="margin-bottom: 2px; margin-right: 5px;" /></a><?\r
+ }\r
+ ?>\r
+ <? if ($form->testFlag("I")) { ?>\r
+ <a href="javascript: listInsert();" title="Inserir registro"><img src="../img/buttons/add.jpg" alt="Inserir"></a>\r
+ <? } ?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+</div>\r
+<div id="div_filtros" class="sep" style="display: <?= $filters_display; ?>">\r
+ <form id="frm_filters" name="frm_filters" action="<?= $_SERVER["PHP_SELF"]; ?>" method="post">\r
+ <table cellpadding="0" cellspacing="0" width="968">\r
+ <tr>\r
+ <td width="150" valign="top" align="left" style="padding: 10px;">\r
+ Filtros\r
+ </td>\r
+ <input type="hidden" name="sql" value="<?= base64_encode($sql); ?>" /> \r
+ <input type="hidden" name="menu" value="<?= $input->request("menu"); ?>" />\r
+ <input type="hidden" name="page" id="input_page" value="<?= $page; ?>" />\r
+ <input type="hidden" name="order" id="input_order" value="<?= $input->post("order"); ?>" />\r
+ <input type="hidden" name="sem_filtro" id="input_sem_filtro" value="0" />\r
+ <input type="hidden" name="extra" id="input_extra" value="" />\r
+ <td align="center">\r
+ <table cellpadding="0" cellspacing="2" width="100%">\r
+ <?= $filters["html"]; ?>\r
+ </table>\r
+ <script>\r
+ f.maskFields();\r
+ </script>\r
+ <br />\r
+ <input type="image" src="../img/buttons/filter_submit.jpg" onclick="javascript: { preListSubmitFilters(); }" title="Filtrar" alt="Filtrar" />\r
+ <? if ($filters["sql"] != "") { \r
+ //<input type="image" src="../img/buttons/filter_clean.jpg" onclick="javascript: { $$('input_sem_filtro').value = '1'; listSubmitFilters(); }" title="Sem filtro" alt="Sem filtro" />?>\r
+ <input type="image" src="../img/buttons/cancel.jpg" onclick="javascript: { $$('input_sem_filtro').value = '1'; listSubmitFilters(); }" title="Cancelar" alt="Cancelar" />\r
+ <? } ?>\r
+ <br /><br />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+</div>\r
+<div class="sep">\r
+ <form id="frm_list" name="frm_list" action="form/routines.php?menu=<?= $input->request("menu"); ?>&routine=delete_checks" method="post">\r
+ <table cellpadding="0" cellspacing="1" width="968" class="listagem">\r
+ <? if (($filters["sql"] != "") || ($form->show_list_init)) { ?> \r
+ <thead>\r
+ <tr>\r
+ <? //if ($form->testFlag("D")) { \r
+ //condição conforme perfil adicionada\r
+ if (($form->testFlag("D")) && ($profile->fields('nivel') == 1)) { ?>\r
+ <td class="header_cinza" width="30"><input id="chk_todos" type="checkbox" onClick="javascript: check(this); "></td>\r
+ <? } ?>\r
+ <?= $headers["html"]; ?>\r
+ </tr>\r
+ </thead>\r
+ <tbody>\r
+ <?\r
+ if (!$rs_list->EOF) {\r
+ $css = 2;\r
+ $i = 1;\r
+ \r
+ $fields = $form->getFieldSet();\r
+ \r
+ while (!$rs_list->EOF) {\r
+ $css = 3 - $css;\r
+ \r
+ echo "<tr id='tr_" . $i . "' onmouseover=\"javascript: listOverOut('over', '" . $i . "');\" onmouseout=\"javascript: listOverOut('out', '" . $i . "');\">" . CRLF;\r
+ \r
+ $extra = "class='td" . $css . "' ";\r
+ // $canChange = true;\r
+ // if($rs_list->fields('id_usuario') != ''){\r
+ // global $profile;\r
+ // if($profile->fields('id') != 1){\r
+ // if($profile->fields('id') != $rs_list->fields('id_usuario')){\r
+ // $canChange = false;\r
+ // }\r
+ // }\r
+ // }\r
+ \r
+ //if (($form->testFlag("U")) && ($canChange)) {\r
+ if ($form->testFlag("U")) {\r
+ $extra .= "onclick=\"javascript: listUpdate('" . $rs_list->fields($form->key_field) . "');\"";\r
+ } else {\r
+ $extra .= "style=\"cursor: default;\"";\r
+ }\r
+ \r
+ if (($form->testFlag("D")) && ($profile->fields('nivel') == 1)) {\r
+ echo " <td align='center'><input type='checkbox' name='chk_" . $i . "' id='chk_" . $i . "' value='" . $rs_list->fields($form->key_field) . "' onclick=\"javascript: { checkMostrar(); listOverOut('over', '" . $i . "'); }\"></td>" . CRLF;\r
+ }\r
+ \r
+ $form->setValuesFromRs($rs_list);\r
+ \r
+ foreach ($fields as $k => $v) {\r
+ if ($v->testFlag("L")) {\r
+ $v->value = $rs_list->fields($v->name);\r
+ $v->is_formated = false;\r
+ \r
+ echo " " . trim($v->getHtmlList($extra)) . LF;\r
+ }\r
+ }\r
+ \r
+ echo "</tr>";\r
+ \r
+ $rs_list->moveNext();\r
+ $i++;\r
+ }\r
+ } else {\r
+ ?><tr><td colspan="100%" align="center" style="height: 40px; background: #ECD9D5;"><strong style="color: #9D412C;">Nenhum registro encontrado</strong></td></tr><?\r
+ }?>\r
+ </tbody>\r
+ <?\r
+ }\r
+ ?>\r
+ </table>\r
+ </form>\r
+</div>\r
+<div class="sep" id="div_botao_excluir" style="display: none;">\r
+ <a href="javascript: checkExcluir();" title="Excluir Selecionados"><img src="../img/buttons/delete_selected.jpg" alt="Excluir Selecionados" /></a>\r
+</div>\r
+<?\r
+$debug->loadList();\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../app.php");\r
+include("../../inc/inc.restrict.php");\r
+include("../../inc/inc.menu.php");\r
+\r
+ini_set("max_execution_time", 60*20); //20 Minutes\r
+\r
+$output->ajaxHeader();\r
+\r
+global $routine;\r
+\r
+$routine = $input->get("routine");\r
+$routine_field = $input->get("routine_field");\r
+\r
+//form class\r
+$sub = $menu->getSub();\r
+if (isset($sub)) {\r
+ if($sub->module != ""){\r
+ $load->config("forms/Form" . ucfirst($sub->class) . ".php");\r
+ $class = "Form" . $sub->class;\r
+ $form = new $class();\r
+ }\r
+}\r
+\r
+//insert / update / delete\r
+if ($routine_field == "") {\r
+ switch($routine) {\r
+ case 'insert':\r
+ $form->postInsert();\r
+ \r
+ redir("list.php?menu=" . $input->request("menu"), false, "", false);\r
+ \r
+ break;\r
+ \r
+ case 'update':\r
+ $form->fields[$form->key_field] = $input->get("id");\r
+ $form->select();\r
+ \r
+ $form->postUpdate();\r
+ \r
+ redir("list.php?menu=" . $input->request("menu"), false, "", false);\r
+ \r
+ break;\r
+ \r
+ case 'delete':\r
+ $form->fields[$form->key_field] = $input->get("id");\r
+ $form->select();\r
+ \r
+ $form->postDelete();\r
+ \r
+ redir("list.php?menu=" . $input->request("menu"), false, "", false);\r
+ \r
+ break;\r
+ \r
+ case 'delete_checks':\r
+ foreach ($_POST as $k => $v) {\r
+ $form->fields[$form->key_field] = $v;\r
+ $form->select();\r
+ \r
+ $form->postDelete();\r
+ }\r
+ \r
+ redir("list.php?menu=" . $input->request("menu"));\r
+ \r
+ break;\r
+ \r
+ case 'ativo':\r
+ $id = $input->get("id");\r
+ \r
+ $form->fields[$form->key_field] = $id;\r
+ $form->select();\r
+ \r
+ $name = $input->get("name");\r
+ \r
+ if($form->fields[$name] == 1){\r
+ $form->fields[$name] = '0';\r
+ } else {\r
+ $form->fields[$name] = '1';\r
+ }\r
+ \r
+ $form->update();\r
+ \r
+ if ($form->fields[$name] == 1) {\r
+ echo "<img src='../img/icons/accept.gif' style='cursor: pointer;' onclick=\"javascript: ativoSwap(this, '" . $name . "', '" . $id . "'); \" src='' title='Alterar para inativo'>";\r
+ } else {\r
+ echo "<img src='../img/icons/cancel.gif' style='cursor: pointer;' onclick=\"javascript: ativoSwap(this, '" . $name . "', '" . $id . "'); \" src='' title='Alterar para ativo'>";\r
+ }\r
+ \r
+ break;\r
+ \r
+ case 'refresh_combo':\r
+ $value = $input->get('value');\r
+ $name_fields = $input->get('name_fields');\r
+ $table_rel = $input->get('table_rel');\r
+ $value_field_rel = $input->get('value_field_rel');\r
+ $name_field_rel = $input->get('name_field_rel');\r
+ $value_select = $input->get('value_select');\r
+\r
+ $sql = "SELECT DISTINCT(" . $value_field_rel . "), " . $name_field_rel . " FROM " . $table_rel . " WHERE " . $name_fields . " LIKE '". $value."' ORDER BY ". $name_field_rel . " ASC";\r
+ $rs = $db->execute($sql);\r
+ \r
+ if (!$rs->EOF) {\r
+ echo("+ Selecione #+-------------");\r
+ while(!$rs->EOF) {\r
+ echo("#".$rs->fields($value_field_rel)."+".$rs->fields($name_field_rel));\r
+ $rs->moveNext();\r
+ }\r
+ } else {\r
+ echo("+Nenhum elemento relacionado");\r
+ }\r
+ break;\r
+ \r
+ case 'refresh_tree':\r
+ /*\r
+ * 2 - id (campo a ser buscado na tabela)\r
+ * 3 - idPai (campo que se relaciona com o id)\r
+ * 4 - nome (campo que será mostrado nos outros combos)\r
+ * 5 - tabela (tabela)\r
+ */\r
+ $args = array();\r
+ $args[] = $input->get('arg0');\r
+ $args[] = $input->get('arg1');\r
+ $args[] = $input->get('arg2');\r
+ $args[] = $input->get('arg3');\r
+ $id = $input->get('id');\r
+ \r
+ $sql = "SELECT DISTINCT ".$args[0].",".$args[2]." FROM ".$args[3]." WHERE ".$args[1]." = ".$id." ORDER BY ". $args[2] . " ASC";\r
+ //echo $sql;\r
+ $rs = "";\r
+ if ($id != "") {\r
+ $rs = $db->execute($sql);\r
+ }else{\r
+ break;\r
+ }\r
+ \r
+ if ((!$rs->EOF)&&($rs->recordcount > 0)){\r
+ echo("+ Selecione #+-------------");\r
+ //print_r2($rs);\r
+ while(!$rs->EOF) {\r
+ echo("#".$rs->fields($args[0])."+".$rs->fields($args[2]));\r
+ $rs->moveNext();\r
+ }\r
+ }/* else {\r
+ echo("");\r
+ }*/\r
+ break;\r
+ }\r
+}\r
+\r
+//fields routines\r
+if ($routine_field != "") {\r
+ $output->ajaxHeader();\r
+ \r
+ if ($routine == "update") {\r
+ $id = $input->get("id");\r
+ if ($id != "") {\r
+ $form->fields[$form->key_field] = $id;\r
+ $form->select();\r
+ }\r
+ }\r
+ \r
+ $f =& $form->getFieldByName($input->request("name"));\r
+ \r
+ echo $f->ajaxRoutine($routine_field);\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../app.php");\r
+include("../inc/inc.restrict.php");\r
+include("../inc/inc.menu.php");\r
+\r
+?>\r
+<html>\r
+ <head>\r
+ <? $system->getFaviconHeader(); ?>\r
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />\r
+ <title><?= strip_tags($cfg["system_title"]); ?></title>\r
+ <style>\r
+ @import "../inc/default.css";\r
+ @import "../inc/calendario/calendario.css";\r
+ @import "../inc/htmleditor/htmleditor.css";\r
+ @import "../inc/colorpicker/colorpicker.css";\r
+ </style>\r
+ \r
+ <script src="../../_system/js/default.js"></script>\r
+ <script src="../../_system/js/form.js"></script>\r
+ <script src="../../_system/js/ajax.js"></script>\r
+ <script src="../../_system/js/popup.js"></script>\r
+ <script src="../inc/routines.js"></script>\r
+ <script src="../inc/calendario/calendario.js"></script>\r
+ <script src="../inc/htmleditor/htmleditor.js"></script>\r
+ <script src="../inc/colorpicker/colorpicker.js"></script>\r
+ <script src="../inc/tree/FieldTree.js"></script>\r
+ <script src="../inc/relItems/FieldRelItems.js"></script>\r
+ \r
+ <script>\r
+ var menu = '<?= $input->request("menu"); ?>';\r
+ var routine;\r
+ var tmp_id;\r
+ var id;\r
+ var delete_enabled = true;\r
+ var rnd = 1;\r
+ var submit_permission = true;\r
+ \r
+ var htmleditor1, htmleditor2, htmleditor3, htmleditor4, htmleditor5;\r
+ </script>\r
+ </head>\r
+ <body class="bg">\r
+ <iframe name="ifr_aux" id="ifr_aux" style="display: none;"></iframe>\r
+ <table cellspacing="0" cellpadding="0" align="center" height="100%" width="100%">\r
+ <tr>\r
+ <td align="center">\r
+ <table class="boxTopo" cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" height="111" width="415" style="">\r
+ <tr>\r
+ <td style="padding-top;padding-right:20px;" align="center">\r
+ <a href="http://www.ufcspa.edu.br/" target="_blank"><img src="../img/logoinn.jpg" align="center" /></a>\r
+ </td>\r
+ <td>\r
+ <?if (filesize(DIR_ROOT . "_config/exeptions/home.php") > 100) {?><a href="?" title="Ir para home"><?}?><img src="../img/siainn.jpg"/><?if (filesize(DIR_ROOT . "_config/exeptions/home.php") > 100) {?></a><?}?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ <td align="center" valign="middle" style="padding-left:15px;">\r
+ <ul class="menu">\r
+ <?= $menu->loadMenu(); ?> \r
+ </ul>\r
+ </td>\r
+ <td align="right" valign="top" style="padding-top:20px;padding-right:10px;">\r
+ <div style="float:right">\r
+ <strong><?= $profile->fields("usuario"); ?></strong> - <?= $_SERVER['REMOTE_ADDR']; ?> - <?= date("d/m/Y"); ?>\r
+ </div>\r
+ <br /><br /><br />\r
+ <div style="float:right;padding-left:10px;">\r
+ <a href="system/routines.php?routine=logout" title="Clique aqui para sair"><img width='18' height='18' src="../img/icons/disconnect.gif" alt="Sair"></a><br /><br>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table> \r
+ </td>\r
+ </tr>\r
+ <?\r
+ $subs = $menu->loadSubs();\r
+ \r
+ if ($subs != "") {\r
+ ?>\r
+ <tr>\r
+ <td align="center">\r
+ <table class="box" cellspacing="0" cellpadding="0" style="padding: 1 0 1 1px;">\r
+ <tr>\r
+ <td>\r
+ <ul class="menu_abas">\r
+ <?= $subs ?>\r
+ </ul>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?\r
+ }\r
+ ?>\r
+ <tr height="100%">\r
+ <td valign="top" align="center">\r
+ <table class="box" cellspacing="0" cellpadding="0" style="padding: 5px;">\r
+ <tr>\r
+ <td id="conteudo">\r
+ <center><div class="padding: 10px;">Carregando...</div></center>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <tr class="trRo">\r
+ <td>\r
+ <div class="divRo"><div style="float:left;"><a href="<?=$cfg['root'];?>">Voltar ao site</a></div>© Copyright <?= date("Y"); ?> - SIAP - Sistema de Imagens Anatomopatológicas</div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <? if (IS_DEVELOP) { ?>\r
+ <div id="box_html" style="font-family: 'Courier New', Courier, monospace; font-size: 11px; border: 1px solid #777777; line-height: 10px; display: block;">\r
+ \r
+ </div>\r
+ <? } ?>\r
+ <?\r
+ //Page handling\r
+ $page = $menu->getInclude();\r
+ \r
+ if (file_exists($page)) {\r
+ ?><script>ajaxGet('<?= $page; ?>');</script><?\r
+ } else {\r
+ error(2, "Arquivo '" . $page . "' não existe.");\r
+ }\r
+ ?>\r
+ </body>\r
+</html>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../app.php");\r
+\r
+if (file_exists(DIR_CONFIG . "exeptions/login.php")) {\r
+ include(DIR_CONFIG . "exeptions/login.php");\r
+ die();\r
+}\r
+?>\r
+<html>\r
+ <head>\r
+ <? $system->getFaviconHeader("login"); ?>\r
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />\r
+ <script src="../../../_system/js/default.js"></script>\r
+ <script src="../../../_system/js/form.js"></script>\r
+ <title><?= strip_tags($cfg["system_title"]); ?></title>\r
+ <style>\r
+ @import "../../../_system/css/default.css";\r
+ \r
+ .tblP {\r
+ width:100%;\r
+ height:100%;\r
+ }\r
+ body { \r
+ font-family: Tahoma;\r
+ margin: 0px;\r
+ background: url(../../img/bg.jpg) top left repeat-x;\r
+ }\r
+ .topcenter {\r
+ width:524px;\r
+ height:auto;\r
+ font-size:1px;\r
+ padding-top:60px;\r
+ text-align:center;\r
+ background:url(../../img/topcenter.jpg) top left repeat-x;\r
+ }\r
+ .topleft, .topright {\r
+ width:13px;\r
+ height:207px;\r
+ font-size:1px;\r
+ }\r
+ .topright {\r
+ background:url(../../img/topright.jpg) top left no-repeat;\r
+ }\r
+ .topleft {\r
+ background:url(../../img/topleft.jpg) top left no-repeat;\r
+ }\r
+ \r
+ .trTo {\r
+ height:207px;\r
+ }\r
+ .trRo {\r
+ height:56px;\r
+ background:url(../../img/bg-rodape.gif) top left repeat-x;\r
+ }\r
+ .trRo td{\r
+ text-align:center;\r
+ }\r
+ .trRo div.divRo{\r
+ text-align:right;\r
+ padding-right:30px;\r
+ font-size:11px;\r
+ width:964px;\r
+ margin:auto;\r
+ }\r
+ .trCe {\r
+ height:100%;\r
+ }\r
+ .toplo {\r
+ margin-left: auto;\r
+ margin-right: auto;\r
+ display:table;\r
+ width:399px;\r
+ height:61px;\r
+ background:url(../../img/siap.png) top left no-repeat;\r
+ }\r
+ .topleftLo,.topleftLo2 {\r
+ width:200px;\r
+ padding-top:15px;\r
+ }\r
+ .topleftLo div{\r
+ width:157px;\r
+ height:147px;\r
+ font-size:1px;\r
+ background:url(../../img/logo.jpg) top left no-repeat;\r
+ }\r
+ .tblLog {\r
+ width:390px;\r
+ }\r
+ .err {\r
+ font-size:10px;\r
+ color: #FF3300;\r
+ }\r
+ .sus {\r
+ font-size:10px;\r
+ color: #007700;\r
+ }\r
+ .input {\r
+ margin:auto;\r
+ }\r
+ .input div{\r
+ margin:auto;\r
+ display:table;\r
+ border-top:1px solid #DDDDDD;\r
+ border-left:1px solid #DDDDDD;\r
+ }\r
+ .input div input {\r
+ color:#353535;\r
+ font-size:12px;\r
+ border-top:1px solid #9A9A9A;\r
+ border-left:1px solid #9A9A9A;\r
+ border-right:1px solid #787878;\r
+ border-bottom:1px solid #787878;\r
+ }\r
+ .overInput {\r
+ position:absolute;\r
+ display:table;\r
+ width:auto;\r
+ height:auto;\r
+ color:#353535;\r
+ font-size:12px;\r
+ border:0px;\r
+ }\r
+ a { color: #003366; text-decoration: none; }\r
+ a:hover { text-decoration: underline; }\r
+ </style>\r
+ <script>\r
+ function swapTxt(id,focus){\r
+ var div = document.getElementById("div_"+id);\r
+ var obj = document.getElementById(id);\r
+ if(focus){\r
+ if(obj.value == ""){\r
+ div.style.display = "none";\r
+ obj.focus();\r
+ }\r
+ } else {\r
+ if(obj.value.trim() == ""){\r
+ div.style.display = "";\r
+ }\r
+ }\r
+ }\r
+ function forgetPass(show){\r
+ var tr_login = document.getElementById('tr_login');\r
+ var tr_esqueci = document.getElementById('tr_esqueci');\r
+ if(show){\r
+ tr_login.style.display = 'none';\r
+ tr_esqueci.style.display = '';\r
+ } else {\r
+ tr_login.style.display = '';\r
+ tr_esqueci.style.display = 'none';\r
+ }\r
+ }\r
+ </script>\r
+ </head>\r
+ <body>\r
+ <table cellspacing="0" cellpadding="0" class="tblP">\r
+ <tr class="trTo">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center">\r
+ <tr>\r
+ <td class="topleftLo"><div> </div></td>\r
+ <td class="topleft"> </td>\r
+ <td class="topcenter"><div class="toplo"> </div></td>\r
+ <td class="topright"> </td>\r
+ <td class="topleftLo2"> </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <tr class="trCe" id="tr_login">\r
+ <td>\r
+ <form id="frm" name="frm" action="routines.php?routine=login" method="post" onSubmit="return false;">\r
+ <table cellspacing="0" cellpadding="0" align="center" class="tblLog">\r
+ <tr>\r
+ <td colspan="2"><img src="../../img/tit/arearestrita.gif" alt="Área Restrita" title="Área Restrita"/></td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:15px;padding-bottom:15px;">\r
+ <div class="input">\r
+ <div id="div_Usuário_TXT1" style="margin-top:7px;margin-left:5px;border:0px;" class="overInput" onclick="swapTxt('Usuário_TXT1',true);">Usuário</div>\r
+ <input style="padding-top:3px;height:27px;width:188px;" type="text" name="usuario" id="Usuário_TXT1" onfocus="swapTxt('Usuário_TXT1',true);" onblur="swapTxt('Usuário_TXT1',false);" alt="Usuário" title="Usuário" />\r
+ </div>\r
+ </td>\r
+ <td style="padding-top:15px;padding-bottom:15px;">\r
+ <div class="input">\r
+ <div id="div_Senha_PW01" style="margin-top:7px;margin-left:5px;border:0px;" class="overInput" onclick="swapTxt('Usuário_TXT1',true);">Senha</div>\r
+ <input style="padding-top:3px;height:27px;width:188px;" type="password" name="senha" id="Senha_PW01" onfocus="swapTxt('Senha_PW01',true);" onblur="swapTxt('Senha_PW01',false);" alt="Senha" title="Senha" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="vertical-align:middle;">\r
+ <? $msg = '';\r
+ if ($input->get("r") == 1) {\r
+ $msg = '<span class="err">Usuário ou senha inválido.</span><br />';\r
+ } else {\r
+ switch($input->get("f")){\r
+ case '':\r
+ break;\r
+ case 0:\r
+ $msg = '<span class="err">E-mail inválido.</span><br />';\r
+ break;\r
+ case 1:\r
+ $msg = '<span class="sus">Seus dados de acesso foram enviado com sucesso ao e-mail enformado.</span><br />';\r
+ break;\r
+ case 2:\r
+ $msg = '<span class="err">Erro ao enviar e-mail, tente novamente mais tarde.</span><br />';\r
+ break;\r
+ }\r
+ } echo $msg;?>\r
+ <span style="cursor:pointer; font-size:11px;" onclick="javascript: forgetPass(true);">Esqueci minha senha</span>\r
+ </td>\r
+ <td align="right" style="padding-right:8px;">\r
+ <input type="image" src="../../img/buttons/entrar.jpg" value="Entrar" onClick="javascript: f.send('frm');" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </td>\r
+ </tr>\r
+ <tr class="trCe" id="tr_esqueci" style="display:none;">\r
+ <td>\r
+ <form id="frmforget" name="frmforget" action="routines.php?routine=forget" method="post" onSubmit="return false;">\r
+ <table cellspacing="0" cellpadding="0" align="center" class="tblLog">\r
+ <tr>\r
+ <td colspan="2"><img src="../../img/tit/arearestrita.gif" alt="Área Restrita" title="Área Restrita"/></td>\r
+ </tr>\r
+ <tr>\r
+ <td colspan="2" style="padding-top:15px;padding-bottom:15px;">\r
+ <div class="input"><div id="div_E-mail_EML1" style="margin-top:7px;margin-left:5px;border:0px;" class="overInput" onclick="swapTxt('E-mail_EML1',true);">E-mail</div><input style="padding-top:3px;height:27px;width:381px;" type="text" name="email" id="E-mail_EML1" onfocus="swapTxt('E-mail_EML1',true);" onblur="swapTxt('E-mail_EML1',false);" alt="E-mail" title="E-mail" /></div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="vertical-align:middle;">\r
+ <span style="cursor:pointer; font-size:11px;" onclick="javascript: forgetPass(false);">Me lembrei!</span>\r
+ </td>\r
+ <td align="right" style="padding-right:8px;">\r
+ <input type="image" src="../../img/buttons/entrar.jpg" value="Entrar" onClick="javascript: f.send('frmforget');" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </td>\r
+ </tr>\r
+ <tr class="trRo">\r
+ <td>\r
+ <div class="divRo"><div style="float:left;"><a href="<?=$cfg['root'];?>">Voltar ao site</a></div>© Copyright <?= date("Y"); ?> - SIAP - Sistema de Imagens Anatomopatológicas</div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </body>\r
+</html>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../app.php");\r
+\r
+$routine = $input->get("routine");\r
+\r
+switch($routine){\r
+ case "login":\r
+ $profile = new Profile();\r
+ \r
+ if ($profile->login()) {\r
+ redir("../");\r
+ } else {\r
+ redir("login.php?r=1");\r
+ }\r
+ break;\r
+ case "logout":\r
+ $profile = new Profile();\r
+ \r
+ $profile->logout();\r
+ \r
+ redir("login.php");\r
+ break;\r
+ case "forget":\r
+ $profile = new Profile();\r
+ $retorno = $profile->forgotPass($input->post('email'));\r
+ redir("login.php?f=".$retorno);\r
+ break;\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
+ </head>
+ <body oncontextmenu="return false;">
+ <a href="javascript: Popup_atual.close();" alt="Clique para fechar" title="Clique para fechar">
+ <img id="img" style="top: 0px; left: 0px; position:relative;" src="<?=$_GET['path'];?>" />
+ </a>
+ </body>
+</html>
\ No newline at end of file
--- /dev/null
+<?php
+
+/*
+$Id: class.nusoap_base.php,v 1.56 2010/04/26 20:15:08 snichol Exp $
+
+NuSOAP - Web Services Toolkit for PHP
+
+Copyright (c) 2002 NuSphere Corporation
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+The NuSOAP project home is:
+http://sourceforge.net/projects/nusoap/
+
+The primary support for NuSOAP is the Help forum on the project home page.
+
+If you have any questions or comments, please email:
+
+Dietrich Ayala
+dietrich@ganx4.com
+http://dietrich.ganx4.com/nusoap
+
+NuSphere Corporation
+http://www.nusphere.com
+
+*/
+
+/*
+ * Some of the standards implmented in whole or part by NuSOAP:
+ *
+ * SOAP 1.1 (http://www.w3.org/TR/2000/NOTE-SOAP-20000508/)
+ * WSDL 1.1 (http://www.w3.org/TR/2001/NOTE-wsdl-20010315)
+ * SOAP Messages With Attachments (http://www.w3.org/TR/SOAP-attachments)
+ * XML 1.0 (http://www.w3.org/TR/2006/REC-xml-20060816/)
+ * Namespaces in XML 1.0 (http://www.w3.org/TR/2006/REC-xml-names-20060816/)
+ * XML Schema 1.0 (http://www.w3.org/TR/xmlschema-0/)
+ * RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies
+ * RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1
+ * RFC 2617 HTTP Authentication: Basic and Digest Access Authentication
+ */
+
+/* load classes
+
+// necessary classes
+require_once('class.soapclient.php');
+require_once('class.soap_val.php');
+require_once('class.soap_parser.php');
+require_once('class.soap_fault.php');
+
+// transport classes
+require_once('class.soap_transport_http.php');
+
+// optional add-on classes
+require_once('class.xmlschema.php');
+require_once('class.wsdl.php');
+
+// server class
+require_once('class.soap_server.php');*/
+
+// class variable emulation
+// cf. http://www.webkreator.com/php/techniques/php-static-class-variables.html
+$GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = 9;
+
+/**
+*
+* nusoap_base
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: class.nusoap_base.php,v 1.56 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_base {
+ /**
+ * Identification for HTTP headers.
+ *
+ * @var string
+ * @access private
+ */
+ var $title = 'NuSOAP';
+ /**
+ * Version for HTTP headers.
+ *
+ * @var string
+ * @access private
+ */
+ var $version = '0.9.5';
+ /**
+ * CVS revision for HTTP headers.
+ *
+ * @var string
+ * @access private
+ */
+ var $revision = '$Revision: 1.56 $';
+ /**
+ * Current error string (manipulated by getError/setError)
+ *
+ * @var string
+ * @access private
+ */
+ var $error_str = '';
+ /**
+ * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment)
+ *
+ * @var string
+ * @access private
+ */
+ var $debug_str = '';
+ /**
+ * toggles automatic encoding of special characters as entities
+ * (should always be true, I think)
+ *
+ * @var boolean
+ * @access private
+ */
+ var $charencoding = true;
+ /**
+ * the debug level for this instance
+ *
+ * @var integer
+ * @access private
+ */
+ var $debugLevel;
+
+ /**
+ * set schema version
+ *
+ * @var string
+ * @access public
+ */
+ var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema';
+
+ /**
+ * charset encoding for outgoing messages
+ *
+ * @var string
+ * @access public
+ */
+ var $soap_defencoding = 'ISO-8859-1';
+ //var $soap_defencoding = 'UTF-8';
+
+ /**
+ * namespaces in an array of prefix => uri
+ *
+ * this is "seeded" by a set of constants, but it may be altered by code
+ *
+ * @var array
+ * @access public
+ */
+ var $namespaces = array(
+ 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/',
+ 'xsd' => 'http://www.w3.org/2001/XMLSchema',
+ 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
+ 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/'
+ );
+
+ /**
+ * namespaces used in the current context, e.g. during serialization
+ *
+ * @var array
+ * @access private
+ */
+ var $usedNamespaces = array();
+
+ /**
+ * XML Schema types in an array of uri => (array of xml type => php type)
+ * is this legacy yet?
+ * no, this is used by the nusoap_xmlschema class to verify type => namespace mappings.
+ * @var array
+ * @access public
+ */
+ var $typemap = array(
+ 'http://www.w3.org/2001/XMLSchema' => array(
+ 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double',
+ 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'',
+ 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string',
+ // abstract "any" types
+ 'anyType'=>'string','anySimpleType'=>'string',
+ // derived datatypes
+ 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'',
+ 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer',
+ 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer',
+ 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''),
+ 'http://www.w3.org/2000/10/XMLSchema' => array(
+ 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
+ 'float'=>'double','dateTime'=>'string',
+ 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
+ 'http://www.w3.org/1999/XMLSchema' => array(
+ 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
+ 'float'=>'double','dateTime'=>'string',
+ 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
+ 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'),
+ 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'),
+ 'http://xml.apache.org/xml-soap' => array('Map')
+ );
+
+ /**
+ * XML entities to convert
+ *
+ * @var array
+ * @access public
+ * @deprecated
+ * @see expandEntities
+ */
+ var $xmlEntities = array('quot' => '"','amp' => '&',
+ 'lt' => '<','gt' => '>','apos' => "'");
+
+ /**
+ * constructor
+ *
+ * @access public
+ */
+ function nusoap_base() {
+ $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'];
+ }
+
+ /**
+ * gets the global debug level, which applies to future instances
+ *
+ * @return integer Debug level 0-9, where 0 turns off
+ * @access public
+ */
+ function getGlobalDebugLevel() {
+ return $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'];
+ }
+
+ /**
+ * sets the global debug level, which applies to future instances
+ *
+ * @param int $level Debug level 0-9, where 0 turns off
+ * @access public
+ */
+ function setGlobalDebugLevel($level) {
+ $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = $level;
+ }
+
+ /**
+ * gets the debug level for this instance
+ *
+ * @return int Debug level 0-9, where 0 turns off
+ * @access public
+ */
+ function getDebugLevel() {
+ return $this->debugLevel;
+ }
+
+ /**
+ * sets the debug level for this instance
+ *
+ * @param int $level Debug level 0-9, where 0 turns off
+ * @access public
+ */
+ function setDebugLevel($level) {
+ $this->debugLevel = $level;
+ }
+
+ /**
+ * adds debug data to the instance debug string with formatting
+ *
+ * @param string $string debug data
+ * @access private
+ */
+ function debug($string){
+ if ($this->debugLevel > 0) {
+ $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n");
+ }
+ }
+
+ /**
+ * adds debug data to the instance debug string without formatting
+ *
+ * @param string $string debug data
+ * @access public
+ */
+ function appendDebug($string){
+ if ($this->debugLevel > 0) {
+ // it would be nice to use a memory stream here to use
+ // memory more efficiently
+ $this->debug_str .= $string;
+ }
+ }
+
+ /**
+ * clears the current debug data for this instance
+ *
+ * @access public
+ */
+ function clearDebug() {
+ // it would be nice to use a memory stream here to use
+ // memory more efficiently
+ $this->debug_str = '';
+ }
+
+ /**
+ * gets the current debug data for this instance
+ *
+ * @return debug data
+ * @access public
+ */
+ function &getDebug() {
+ // it would be nice to use a memory stream here to use
+ // memory more efficiently
+ return $this->debug_str;
+ }
+
+ /**
+ * gets the current debug data for this instance as an XML comment
+ * this may change the contents of the debug data
+ *
+ * @return debug data as an XML comment
+ * @access public
+ */
+ function &getDebugAsXMLComment() {
+ // it would be nice to use a memory stream here to use
+ // memory more efficiently
+ while (strpos($this->debug_str, '--')) {
+ $this->debug_str = str_replace('--', '- -', $this->debug_str);
+ }
+ $ret = "<!--\n" . $this->debug_str . "\n-->";
+ return $ret;
+ }
+
+ /**
+ * expands entities, e.g. changes '<' to '<'.
+ *
+ * @param string $val The string in which to expand entities.
+ * @access private
+ */
+ function expandEntities($val) {
+ if ($this->charencoding) {
+ $val = str_replace('&', '&', $val);
+ $val = str_replace("'", ''', $val);
+ $val = str_replace('"', '"', $val);
+ $val = str_replace('<', '<', $val);
+ $val = str_replace('>', '>', $val);
+ }
+ return $val;
+ }
+
+ /**
+ * returns error string if present
+ *
+ * @return mixed error string or false
+ * @access public
+ */
+ function getError(){
+ if($this->error_str != ''){
+ return $this->error_str;
+ }
+ return false;
+ }
+
+ /**
+ * sets error string
+ *
+ * @return boolean $string error string
+ * @access private
+ */
+ function setError($str){
+ $this->error_str = $str;
+ }
+
+ /**
+ * detect if array is a simple array or a struct (associative array)
+ *
+ * @param mixed $val The PHP array
+ * @return string (arraySimple|arrayStruct)
+ * @access private
+ */
+ function isArraySimpleOrStruct($val) {
+ $keyList = array_keys($val);
+ foreach ($keyList as $keyListValue) {
+ if (!is_int($keyListValue)) {
+ return 'arrayStruct';
+ }
+ }
+ return 'arraySimple';
+ }
+
+ /**
+ * serializes PHP values in accordance w/ section 5. Type information is
+ * not serialized if $use == 'literal'.
+ *
+ * @param mixed $val The value to serialize
+ * @param string $name The name (local part) of the XML element
+ * @param string $type The XML schema type (local part) for the element
+ * @param string $name_ns The namespace for the name of the XML element
+ * @param string $type_ns The namespace for the type of the element
+ * @param array $attributes The attributes to serialize as name=>value pairs
+ * @param string $use The WSDL "use" (encoded|literal)
+ * @param boolean $soapval Whether this is called from soapval.
+ * @return string The serialized element, possibly with child elements
+ * @access public
+ */
+ function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded',$soapval=false) {
+ $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use, soapval=$soapval");
+ $this->appendDebug('value=' . $this->varDump($val));
+ $this->appendDebug('attributes=' . $this->varDump($attributes));
+
+ if (is_object($val) && get_class($val) == 'soapval' && (! $soapval)) {
+ $this->debug("serialize_val: serialize soapval");
+ $xml = $val->serialize($use);
+ $this->appendDebug($val->getDebug());
+ $val->clearDebug();
+ $this->debug("serialize_val of soapval returning $xml");
+ return $xml;
+ }
+ // force valid name if necessary
+ if (is_numeric($name)) {
+ $name = '__numeric_' . $name;
+ } elseif (! $name) {
+ $name = 'noname';
+ }
+ // if name has ns, add ns prefix to name
+ $xmlns = '';
+ if($name_ns){
+ $prefix = 'nu'.rand(1000,9999);
+ $name = $prefix.':'.$name;
+ $xmlns .= " xmlns:$prefix=\"$name_ns\"";
+ }
+ // if type is prefixed, create type prefix
+ if($type_ns != '' && $type_ns == $this->namespaces['xsd']){
+ // need to fix this. shouldn't default to xsd if no ns specified
+ // w/o checking against typemap
+ $type_prefix = 'xsd';
+ } elseif($type_ns){
+ $type_prefix = 'ns'.rand(1000,9999);
+ $xmlns .= " xmlns:$type_prefix=\"$type_ns\"";
+ }
+ // serialize attributes if present
+ $atts = '';
+ if($attributes){
+ foreach($attributes as $k => $v){
+ $atts .= " $k=\"".$this->expandEntities($v).'"';
+ }
+ }
+ // serialize null value
+ if (is_null($val)) {
+ $this->debug("serialize_val: serialize null");
+ if ($use == 'literal') {
+ // TODO: depends on minOccurs
+ $xml = "<$name$xmlns$atts/>";
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ } else {
+ if (isset($type) && isset($type_prefix)) {
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = '';
+ }
+ $xml = "<$name$xmlns$type_str$atts xsi:nil=\"true\"/>";
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ }
+ }
+ // serialize if an xsd built-in primitive type
+ if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){
+ $this->debug("serialize_val: serialize xsd built-in primitive type");
+ if (is_bool($val)) {
+ if ($type == 'boolean') {
+ $val = $val ? 'true' : 'false';
+ } elseif (! $val) {
+ $val = 0;
+ }
+ } else if (is_string($val)) {
+ $val = $this->expandEntities($val);
+ }
+ if ($use == 'literal') {
+ $xml = "<$name$xmlns$atts>$val</$name>";
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ } else {
+ $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val</$name>";
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ }
+ }
+ // detect type and serialize
+ $xml = '';
+ switch(true) {
+ case (is_bool($val) || $type == 'boolean'):
+ $this->debug("serialize_val: serialize boolean");
+ if ($type == 'boolean') {
+ $val = $val ? 'true' : 'false';
+ } elseif (! $val) {
+ $val = 0;
+ }
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$val</$name>";
+ } else {
+ $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val</$name>";
+ }
+ break;
+ case (is_int($val) || is_long($val) || $type == 'int'):
+ $this->debug("serialize_val: serialize int");
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$val</$name>";
+ } else {
+ $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val</$name>";
+ }
+ break;
+ case (is_float($val)|| is_double($val) || $type == 'float'):
+ $this->debug("serialize_val: serialize float");
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$val</$name>";
+ } else {
+ $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val</$name>";
+ }
+ break;
+ case (is_string($val) || $type == 'string'):
+ $this->debug("serialize_val: serialize string");
+ $val = $this->expandEntities($val);
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$val</$name>";
+ } else {
+ $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val</$name>";
+ }
+ break;
+ case is_object($val):
+ $this->debug("serialize_val: serialize object");
+ if (get_class($val) == 'soapval') {
+ $this->debug("serialize_val: serialize soapval object");
+ $pXml = $val->serialize($use);
+ $this->appendDebug($val->getDebug());
+ $val->clearDebug();
+ } else {
+ if (! $name) {
+ $name = get_class($val);
+ $this->debug("In serialize_val, used class name $name as element name");
+ } else {
+ $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val));
+ }
+ foreach(get_object_vars($val) as $k => $v){
+ $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use);
+ }
+ }
+ if(isset($type) && isset($type_prefix)){
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = '';
+ }
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$pXml</$name>";
+ } else {
+ $xml .= "<$name$xmlns$type_str$atts>$pXml</$name>";
+ }
+ break;
+ break;
+ case (is_array($val) || $type):
+ // detect if struct or array
+ $valueType = $this->isArraySimpleOrStruct($val);
+ if($valueType=='arraySimple' || preg_match('/^ArrayOf/',$type)){
+ $this->debug("serialize_val: serialize array");
+ $i = 0;
+ if(is_array($val) && count($val)> 0){
+ foreach($val as $v){
+ if(is_object($v) && get_class($v) == 'soapval'){
+ $tt_ns = $v->type_ns;
+ $tt = $v->type;
+ } elseif (is_array($v)) {
+ $tt = $this->isArraySimpleOrStruct($v);
+ } else {
+ $tt = gettype($v);
+ }
+ $array_types[$tt] = 1;
+ // TODO: for literal, the name should be $name
+ $xml .= $this->serialize_val($v,'item',false,false,false,false,$use);
+ ++$i;
+ }
+ if(count($array_types) > 1){
+ $array_typename = 'xsd:anyType';
+ } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) {
+ if ($tt == 'integer') {
+ $tt = 'int';
+ }
+ $array_typename = 'xsd:'.$tt;
+ } elseif(isset($tt) && $tt == 'arraySimple'){
+ $array_typename = 'SOAP-ENC:Array';
+ } elseif(isset($tt) && $tt == 'arrayStruct'){
+ $array_typename = 'unnamed_struct_use_soapval';
+ } else {
+ // if type is prefixed, create type prefix
+ if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){
+ $array_typename = 'xsd:' . $tt;
+ } elseif ($tt_ns) {
+ $tt_prefix = 'ns' . rand(1000, 9999);
+ $array_typename = "$tt_prefix:$tt";
+ $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\"";
+ } else {
+ $array_typename = $tt;
+ }
+ }
+ $array_type = $i;
+ if ($use == 'literal') {
+ $type_str = '';
+ } else if (isset($type) && isset($type_prefix)) {
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\"";
+ }
+ // empty array
+ } else {
+ if ($use == 'literal') {
+ $type_str = '';
+ } else if (isset($type) && isset($type_prefix)) {
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\"";
+ }
+ }
+ // TODO: for array in literal, there is no wrapper here
+ $xml = "<$name$xmlns$type_str$atts>".$xml."</$name>";
+ } else {
+ // got a struct
+ $this->debug("serialize_val: serialize struct");
+ if(isset($type) && isset($type_prefix)){
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = '';
+ }
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>";
+ } else {
+ $xml .= "<$name$xmlns$type_str$atts>";
+ }
+ foreach($val as $k => $v){
+ // Apache Map
+ if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') {
+ $xml .= '<item>';
+ $xml .= $this->serialize_val($k,'key',false,false,false,false,$use);
+ $xml .= $this->serialize_val($v,'value',false,false,false,false,$use);
+ $xml .= '</item>';
+ } else {
+ $xml .= $this->serialize_val($v,$k,false,false,false,false,$use);
+ }
+ }
+ $xml .= "</$name>";
+ }
+ break;
+ default:
+ $this->debug("serialize_val: serialize unknown");
+ $xml .= 'not detected, got '.gettype($val).' for '.$val;
+ break;
+ }
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ }
+
+ /**
+ * serializes a message
+ *
+ * @param string $body the XML of the SOAP body
+ * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array
+ * @param array $namespaces optional the namespaces used in generating the body and headers
+ * @param string $style optional (rpc|document)
+ * @param string $use optional (encoded|literal)
+ * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
+ * @return string the message
+ * @access public
+ */
+ function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){
+ // TODO: add an option to automatically run utf8_encode on $body and $headers
+ // if $this->soap_defencoding is UTF-8. Not doing this automatically allows
+ // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1
+
+ $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle");
+ $this->debug("headers:");
+ $this->appendDebug($this->varDump($headers));
+ $this->debug("namespaces:");
+ $this->appendDebug($this->varDump($namespaces));
+
+ // serialize namespaces
+ $ns_string = '';
+ foreach(array_merge($this->namespaces,$namespaces) as $k => $v){
+ $ns_string .= " xmlns:$k=\"$v\"";
+ }
+ if($encodingStyle) {
+ $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string";
+ }
+
+ // serialize headers
+ if($headers){
+ if (is_array($headers)) {
+ $xml = '';
+ foreach ($headers as $k => $v) {
+ if (is_object($v) && get_class($v) == 'soapval') {
+ $xml .= $this->serialize_val($v, false, false, false, false, false, $use);
+ } else {
+ $xml .= $this->serialize_val($v, $k, false, false, false, false, $use);
+ }
+ }
+ $headers = $xml;
+ $this->debug("In serializeEnvelope, serialized array of headers to $headers");
+ }
+ $headers = "<SOAP-ENV:Header>".$headers."</SOAP-ENV:Header>";
+ }
+ // serialize envelope
+ return
+ '<?xml version="1.0" encoding="'.$this->soap_defencoding .'"?'.">".
+ '<SOAP-ENV:Envelope'.$ns_string.">".
+ $headers.
+ "<SOAP-ENV:Body>".
+ $body.
+ "</SOAP-ENV:Body>".
+ "</SOAP-ENV:Envelope>";
+ }
+
+ /**
+ * formats a string to be inserted into an HTML stream
+ *
+ * @param string $str The string to format
+ * @return string The formatted string
+ * @access public
+ * @deprecated
+ */
+ function formatDump($str){
+ $str = htmlspecialchars($str);
+ return nl2br($str);
+ }
+
+ /**
+ * contracts (changes namespace to prefix) a qualified name
+ *
+ * @param string $qname qname
+ * @return string contracted qname
+ * @access private
+ */
+ function contractQname($qname){
+ // get element namespace
+ //$this->xdebug("Contract $qname");
+ if (strrpos($qname, ':')) {
+ // get unqualified name
+ $name = substr($qname, strrpos($qname, ':') + 1);
+ // get ns
+ $ns = substr($qname, 0, strrpos($qname, ':'));
+ $p = $this->getPrefixFromNamespace($ns);
+ if ($p) {
+ return $p . ':' . $name;
+ }
+ return $qname;
+ } else {
+ return $qname;
+ }
+ }
+
+ /**
+ * expands (changes prefix to namespace) a qualified name
+ *
+ * @param string $qname qname
+ * @return string expanded qname
+ * @access private
+ */
+ function expandQname($qname){
+ // get element prefix
+ if(strpos($qname,':') && !preg_match('/^http:\/\//',$qname)){
+ // get unqualified name
+ $name = substr(strstr($qname,':'),1);
+ // get ns prefix
+ $prefix = substr($qname,0,strpos($qname,':'));
+ if(isset($this->namespaces[$prefix])){
+ return $this->namespaces[$prefix].':'.$name;
+ } else {
+ return $qname;
+ }
+ } else {
+ return $qname;
+ }
+ }
+
+ /**
+ * returns the local part of a prefixed string
+ * returns the original string, if not prefixed
+ *
+ * @param string $str The prefixed string
+ * @return string The local part
+ * @access public
+ */
+ function getLocalPart($str){
+ if($sstr = strrchr($str,':')){
+ // get unqualified name
+ return substr( $sstr, 1 );
+ } else {
+ return $str;
+ }
+ }
+
+ /**
+ * returns the prefix part of a prefixed string
+ * returns false, if not prefixed
+ *
+ * @param string $str The prefixed string
+ * @return mixed The prefix or false if there is no prefix
+ * @access public
+ */
+ function getPrefix($str){
+ if($pos = strrpos($str,':')){
+ // get prefix
+ return substr($str,0,$pos);
+ }
+ return false;
+ }
+
+ /**
+ * pass it a prefix, it returns a namespace
+ *
+ * @param string $prefix The prefix
+ * @return mixed The namespace, false if no namespace has the specified prefix
+ * @access public
+ */
+ function getNamespaceFromPrefix($prefix){
+ if (isset($this->namespaces[$prefix])) {
+ return $this->namespaces[$prefix];
+ }
+ //$this->setError("No namespace registered for prefix '$prefix'");
+ return false;
+ }
+
+ /**
+ * returns the prefix for a given namespace (or prefix)
+ * or false if no prefixes registered for the given namespace
+ *
+ * @param string $ns The namespace
+ * @return mixed The prefix, false if the namespace has no prefixes
+ * @access public
+ */
+ function getPrefixFromNamespace($ns) {
+ foreach ($this->namespaces as $p => $n) {
+ if ($ns == $n || $ns == $p) {
+ $this->usedNamespaces[$p] = $n;
+ return $p;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * returns the time in ODBC canonical form with microseconds
+ *
+ * @return string The time in ODBC canonical form with microseconds
+ * @access public
+ */
+ function getmicrotime() {
+ if (function_exists('gettimeofday')) {
+ $tod = gettimeofday();
+ $sec = $tod['sec'];
+ $usec = $tod['usec'];
+ } else {
+ $sec = time();
+ $usec = 0;
+ }
+ return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec);
+ }
+
+ /**
+ * Returns a string with the output of var_dump
+ *
+ * @param mixed $data The variable to var_dump
+ * @return string The output of var_dump
+ * @access public
+ */
+ function varDump($data) {
+ ob_start();
+ var_dump($data);
+ $ret_val = ob_get_contents();
+ ob_end_clean();
+ return $ret_val;
+ }
+
+ /**
+ * represents the object as a string
+ *
+ * @return string
+ * @access public
+ */
+ function __toString() {
+ return $this->varDump($this);
+ }
+}
+
+// XML Schema Datatype Helper Functions
+
+//xsd:dateTime helpers
+
+/**
+* convert unix timestamp to ISO 8601 compliant date string
+*
+* @param int $timestamp Unix time stamp
+* @param boolean $utc Whether the time stamp is UTC or local
+* @return mixed ISO 8601 date string or false
+* @access public
+*/
+function timestamp_to_iso8601($timestamp,$utc=true){
+ $datestr = date('Y-m-d\TH:i:sO',$timestamp);
+ $pos = strrpos($datestr, "+");
+ if ($pos === FALSE) {
+ $pos = strrpos($datestr, "-");
+ }
+ if ($pos !== FALSE) {
+ if (strlen($datestr) == $pos + 5) {
+ $datestr = substr($datestr, 0, $pos + 3) . ':' . substr($datestr, -2);
+ }
+ }
+ if($utc){
+ $pattern = '/'.
+ '([0-9]{4})-'. // centuries & years CCYY-
+ '([0-9]{2})-'. // months MM-
+ '([0-9]{2})'. // days DD
+ 'T'. // separator T
+ '([0-9]{2}):'. // hours hh:
+ '([0-9]{2}):'. // minutes mm:
+ '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss...
+ '(Z|[+\-][0-9]{2}:?[0-9]{2})?'. // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
+ '/';
+
+ if(preg_match($pattern,$datestr,$regs)){
+ return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]);
+ }
+ return false;
+ } else {
+ return $datestr;
+ }
+}
+
+/**
+* convert ISO 8601 compliant date string to unix timestamp
+*
+* @param string $datestr ISO 8601 compliant date string
+* @return mixed Unix timestamp (int) or false
+* @access public
+*/
+function iso8601_to_timestamp($datestr){
+ $pattern = '/'.
+ '([0-9]{4})-'. // centuries & years CCYY-
+ '([0-9]{2})-'. // months MM-
+ '([0-9]{2})'. // days DD
+ 'T'. // separator T
+ '([0-9]{2}):'. // hours hh:
+ '([0-9]{2}):'. // minutes mm:
+ '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss...
+ '(Z|[+\-][0-9]{2}:?[0-9]{2})?'. // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
+ '/';
+ if(preg_match($pattern,$datestr,$regs)){
+ // not utc
+ if($regs[8] != 'Z'){
+ $op = substr($regs[8],0,1);
+ $h = substr($regs[8],1,2);
+ $m = substr($regs[8],strlen($regs[8])-2,2);
+ if($op == '-'){
+ $regs[4] = $regs[4] + $h;
+ $regs[5] = $regs[5] + $m;
+ } elseif($op == '+'){
+ $regs[4] = $regs[4] - $h;
+ $regs[5] = $regs[5] - $m;
+ }
+ }
+ return gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
+// return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
+ } else {
+ return false;
+ }
+}
+
+/**
+* sleeps some number of microseconds
+*
+* @param string $usec the number of microseconds to sleep
+* @access public
+* @deprecated
+*/
+function usleepWindows($usec)
+{
+ $start = gettimeofday();
+
+ do
+ {
+ $stop = gettimeofday();
+ $timePassed = 1000000 * ($stop['sec'] - $start['sec'])
+ + $stop['usec'] - $start['usec'];
+ }
+ while ($timePassed < $usec);
+}
+
+
+?>
\ No newline at end of file
--- /dev/null
+<?php
+
+
+
+
+/**
+* Contains information for a SOAP fault.
+* Mainly used for returning faults from deployed functions
+* in a server instance.
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @version $Id: class.soap_fault.php,v 1.14 2007/04/11 15:49:47 snichol Exp $
+* @access public
+*/
+class nusoap_fault extends nusoap_base {
+ /**
+ * The fault code (client|server)
+ * @var string
+ * @access private
+ */
+ var $faultcode;
+ /**
+ * The fault actor
+ * @var string
+ * @access private
+ */
+ var $faultactor;
+ /**
+ * The fault string, a description of the fault
+ * @var string
+ * @access private
+ */
+ var $faultstring;
+ /**
+ * The fault detail, typically a string or array of string
+ * @var mixed
+ * @access private
+ */
+ var $faultdetail;
+
+ /**
+ * constructor
+ *
+ * @param string $faultcode (SOAP-ENV:Client | SOAP-ENV:Server)
+ * @param string $faultactor only used when msg routed between multiple actors
+ * @param string $faultstring human readable error message
+ * @param mixed $faultdetail detail, typically a string or array of string
+ */
+ function nusoap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){
+ parent::nusoap_base();
+ $this->faultcode = $faultcode;
+ $this->faultactor = $faultactor;
+ $this->faultstring = $faultstring;
+ $this->faultdetail = $faultdetail;
+ }
+
+ /**
+ * serialize a fault
+ *
+ * @return string The serialization of the fault instance.
+ * @access public
+ */
+ function serialize(){
+ $ns_string = '';
+ foreach($this->namespaces as $k => $v){
+ $ns_string .= "\n xmlns:$k=\"$v\"";
+ }
+ $return_msg =
+ '<?xml version="1.0" encoding="'.$this->soap_defencoding.'"?>'.
+ '<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"'.$ns_string.">\n".
+ '<SOAP-ENV:Body>'.
+ '<SOAP-ENV:Fault>'.
+ $this->serialize_val($this->faultcode, 'faultcode').
+ $this->serialize_val($this->faultactor, 'faultactor').
+ $this->serialize_val($this->faultstring, 'faultstring').
+ $this->serialize_val($this->faultdetail, 'detail').
+ '</SOAP-ENV:Fault>'.
+ '</SOAP-ENV:Body>'.
+ '</SOAP-ENV:Envelope>';
+ return $return_msg;
+ }
+}
+
+/**
+ * Backward compatibility
+ */
+class soap_fault extends nusoap_fault {
+}
+
+
+?>
\ No newline at end of file
--- /dev/null
+<?php
+
+
+
+
+/**
+*
+* nusoap_parser class parses SOAP XML messages into native PHP values
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: class.soap_parser.php,v 1.42 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_parser extends nusoap_base {
+
+ var $xml = '';
+ var $xml_encoding = '';
+ var $method = '';
+ var $root_struct = '';
+ var $root_struct_name = '';
+ var $root_struct_namespace = '';
+ var $root_header = '';
+ var $document = ''; // incoming SOAP body (text)
+ // determines where in the message we are (envelope,header,body,method)
+ var $status = '';
+ var $position = 0;
+ var $depth = 0;
+ var $default_namespace = '';
+ var $namespaces = array();
+ var $message = array();
+ var $parent = '';
+ var $fault = false;
+ var $fault_code = '';
+ var $fault_str = '';
+ var $fault_detail = '';
+ var $depth_array = array();
+ var $debug_flag = true;
+ var $soapresponse = NULL; // parsed SOAP Body
+ var $soapheader = NULL; // parsed SOAP Header
+ var $responseHeaders = ''; // incoming SOAP headers (text)
+ var $body_position = 0;
+ // for multiref parsing:
+ // array of id => pos
+ var $ids = array();
+ // array of id => hrefs => pos
+ var $multirefs = array();
+ // toggle for auto-decoding element content
+ var $decode_utf8 = true;
+
+ /**
+ * constructor that actually does the parsing
+ *
+ * @param string $xml SOAP message
+ * @param string $encoding character encoding scheme of message
+ * @param string $method method for which XML is parsed (unused?)
+ * @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1
+ * @access public
+ */
+ function nusoap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){
+ parent::nusoap_base();
+ $this->xml = $xml;
+ $this->xml_encoding = $encoding;
+ $this->method = $method;
+ $this->decode_utf8 = $decode_utf8;
+
+ // Check whether content has been read.
+ if(!empty($xml)){
+ // Check XML encoding
+ $pos_xml = strpos($xml, '<?xml');
+ if ($pos_xml !== FALSE) {
+ $xml_decl = substr($xml, $pos_xml, strpos($xml, '?>', $pos_xml + 2) - $pos_xml + 1);
+ if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) {
+ $xml_encoding = $res[1];
+ if (strtoupper($xml_encoding) != $encoding) {
+ $err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'";
+ $this->debug($err);
+ if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') {
+ $this->setError($err);
+ return;
+ }
+ // when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed
+ } else {
+ $this->debug('Charset from HTTP Content-Type matches encoding from XML declaration');
+ }
+ } else {
+ $this->debug('No encoding specified in XML declaration');
+ }
+ } else {
+ $this->debug('No XML declaration');
+ }
+ $this->debug('Entering nusoap_parser(), length='.strlen($xml).', encoding='.$encoding);
+ // Create an XML parser - why not xml_parser_create_ns?
+ $this->parser = xml_parser_create($this->xml_encoding);
+ // Set the options for parsing the XML data.
+ //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
+ xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
+ xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding);
+ // Set the object for the parser.
+ xml_set_object($this->parser, $this);
+ // Set the element handlers for the parser.
+ xml_set_element_handler($this->parser, 'start_element','end_element');
+ xml_set_character_data_handler($this->parser,'character_data');
+
+ // Parse the XML file.
+ if(!xml_parse($this->parser,$xml,true)){
+ // Display an error message.
+ $err = sprintf('XML error parsing SOAP payload on line %d: %s',
+ xml_get_current_line_number($this->parser),
+ xml_error_string(xml_get_error_code($this->parser)));
+ $this->debug($err);
+ $this->debug("XML payload:\n" . $xml);
+ $this->setError($err);
+ } else {
+ $this->debug('in nusoap_parser ctor, message:');
+ $this->appendDebug($this->varDump($this->message));
+ $this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name);
+ // get final value
+ $this->soapresponse = $this->message[$this->root_struct]['result'];
+ // get header value
+ if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){
+ $this->soapheader = $this->message[$this->root_header]['result'];
+ }
+ // resolve hrefs/ids
+ if(sizeof($this->multirefs) > 0){
+ foreach($this->multirefs as $id => $hrefs){
+ $this->debug('resolving multirefs for id: '.$id);
+ $idVal = $this->buildVal($this->ids[$id]);
+ if (is_array($idVal) && isset($idVal['!id'])) {
+ unset($idVal['!id']);
+ }
+ foreach($hrefs as $refPos => $ref){
+ $this->debug('resolving href at pos '.$refPos);
+ $this->multirefs[$id][$refPos] = $idVal;
+ }
+ }
+ }
+ }
+ xml_parser_free($this->parser);
+ } else {
+ $this->debug('xml was empty, didn\'t parse!');
+ $this->setError('xml was empty, didn\'t parse!');
+ }
+ }
+
+ /**
+ * start-element handler
+ *
+ * @param resource $parser XML parser object
+ * @param string $name element name
+ * @param array $attrs associative array of attributes
+ * @access private
+ */
+ function start_element($parser, $name, $attrs) {
+ // position in a total number of elements, starting from 0
+ // update class level pos
+ $pos = $this->position++;
+ // and set mine
+ $this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>'');
+ // depth = how many levels removed from root?
+ // set mine as current global depth and increment global depth value
+ $this->message[$pos]['depth'] = $this->depth++;
+
+ // else add self as child to whoever the current parent is
+ if($pos != 0){
+ $this->message[$this->parent]['children'] .= '|'.$pos;
+ }
+ // set my parent
+ $this->message[$pos]['parent'] = $this->parent;
+ // set self as current parent
+ $this->parent = $pos;
+ // set self as current value for this depth
+ $this->depth_array[$this->depth] = $pos;
+ // get element prefix
+ if(strpos($name,':')){
+ // get ns prefix
+ $prefix = substr($name,0,strpos($name,':'));
+ // get unqualified name
+ $name = substr(strstr($name,':'),1);
+ }
+ // set status
+ if ($name == 'Envelope' && $this->status == '') {
+ $this->status = 'envelope';
+ } elseif ($name == 'Header' && $this->status == 'envelope') {
+ $this->root_header = $pos;
+ $this->status = 'header';
+ } elseif ($name == 'Body' && $this->status == 'envelope'){
+ $this->status = 'body';
+ $this->body_position = $pos;
+ // set method
+ } elseif($this->status == 'body' && $pos == ($this->body_position+1)) {
+ $this->status = 'method';
+ $this->root_struct_name = $name;
+ $this->root_struct = $pos;
+ $this->message[$pos]['type'] = 'struct';
+ $this->debug("found root struct $this->root_struct_name, pos $this->root_struct");
+ }
+ // set my status
+ $this->message[$pos]['status'] = $this->status;
+ // set name
+ $this->message[$pos]['name'] = htmlspecialchars($name);
+ // set attrs
+ $this->message[$pos]['attrs'] = $attrs;
+
+ // loop through atts, logging ns and type declarations
+ $attstr = '';
+ foreach($attrs as $key => $value){
+ $key_prefix = $this->getPrefix($key);
+ $key_localpart = $this->getLocalPart($key);
+ // if ns declarations, add to class level array of valid namespaces
+ if($key_prefix == 'xmlns'){
+ if(preg_match('/^http:\/\/www.w3.org\/[0-9]{4}\/XMLSchema$/',$value)){
+ $this->XMLSchemaVersion = $value;
+ $this->namespaces['xsd'] = $this->XMLSchemaVersion;
+ $this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance';
+ }
+ $this->namespaces[$key_localpart] = $value;
+ // set method namespace
+ if($name == $this->root_struct_name){
+ $this->methodNamespace = $value;
+ }
+ // if it's a type declaration, set type
+ } elseif($key_localpart == 'type'){
+ if (isset($this->message[$pos]['type']) && $this->message[$pos]['type'] == 'array') {
+ // do nothing: already processed arrayType
+ } else {
+ $value_prefix = $this->getPrefix($value);
+ $value_localpart = $this->getLocalPart($value);
+ $this->message[$pos]['type'] = $value_localpart;
+ $this->message[$pos]['typePrefix'] = $value_prefix;
+ if(isset($this->namespaces[$value_prefix])){
+ $this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix];
+ } else if(isset($attrs['xmlns:'.$value_prefix])) {
+ $this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix];
+ }
+ // should do something here with the namespace of specified type?
+ }
+ } elseif($key_localpart == 'arrayType'){
+ $this->message[$pos]['type'] = 'array';
+ /* do arrayType ereg here
+ [1] arrayTypeValue ::= atype asize
+ [2] atype ::= QName rank*
+ [3] rank ::= '[' (',')* ']'
+ [4] asize ::= '[' length~ ']'
+ [5] length ::= nextDimension* Digit+
+ [6] nextDimension ::= Digit+ ','
+ */
+ $expr = '/([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]/';
+ if(preg_match($expr,$value,$regs)){
+ $this->message[$pos]['typePrefix'] = $regs[1];
+ $this->message[$pos]['arrayTypePrefix'] = $regs[1];
+ if (isset($this->namespaces[$regs[1]])) {
+ $this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]];
+ } else if (isset($attrs['xmlns:'.$regs[1]])) {
+ $this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]];
+ }
+ $this->message[$pos]['arrayType'] = $regs[2];
+ $this->message[$pos]['arraySize'] = $regs[3];
+ $this->message[$pos]['arrayCols'] = $regs[4];
+ }
+ // specifies nil value (or not)
+ } elseif ($key_localpart == 'nil'){
+ $this->message[$pos]['nil'] = ($value == 'true' || $value == '1');
+ // some other attribute
+ } elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') {
+ $this->message[$pos]['xattrs']['!' . $key] = $value;
+ }
+
+ if ($key == 'xmlns') {
+ $this->default_namespace = $value;
+ }
+ // log id
+ if($key == 'id'){
+ $this->ids[$value] = $pos;
+ }
+ // root
+ if($key_localpart == 'root' && $value == 1){
+ $this->status = 'method';
+ $this->root_struct_name = $name;
+ $this->root_struct = $pos;
+ $this->debug("found root struct $this->root_struct_name, pos $pos");
+ }
+ // for doclit
+ $attstr .= " $key=\"$value\"";
+ }
+ // get namespace - must be done after namespace atts are processed
+ if(isset($prefix)){
+ $this->message[$pos]['namespace'] = $this->namespaces[$prefix];
+ $this->default_namespace = $this->namespaces[$prefix];
+ } else {
+ $this->message[$pos]['namespace'] = $this->default_namespace;
+ }
+ if($this->status == 'header'){
+ if ($this->root_header != $pos) {
+ $this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
+ }
+ } elseif($this->root_struct_name != ''){
+ $this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
+ }
+ }
+
+ /**
+ * end-element handler
+ *
+ * @param resource $parser XML parser object
+ * @param string $name element name
+ * @access private
+ */
+ function end_element($parser, $name) {
+ // position of current element is equal to the last value left in depth_array for my depth
+ $pos = $this->depth_array[$this->depth--];
+
+ // get element prefix
+ if(strpos($name,':')){
+ // get ns prefix
+ $prefix = substr($name,0,strpos($name,':'));
+ // get unqualified name
+ $name = substr(strstr($name,':'),1);
+ }
+
+ // build to native type
+ if(isset($this->body_position) && $pos > $this->body_position){
+ // deal w/ multirefs
+ if(isset($this->message[$pos]['attrs']['href'])){
+ // get id
+ $id = substr($this->message[$pos]['attrs']['href'],1);
+ // add placeholder to href array
+ $this->multirefs[$id][$pos] = 'placeholder';
+ // add set a reference to it as the result value
+ $this->message[$pos]['result'] =& $this->multirefs[$id][$pos];
+ // build complexType values
+ } elseif($this->message[$pos]['children'] != ''){
+ // if result has already been generated (struct/array)
+ if(!isset($this->message[$pos]['result'])){
+ $this->message[$pos]['result'] = $this->buildVal($pos);
+ }
+ // build complexType values of attributes and possibly simpleContent
+ } elseif (isset($this->message[$pos]['xattrs'])) {
+ if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
+ $this->message[$pos]['xattrs']['!'] = null;
+ } elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
+ if (isset($this->message[$pos]['type'])) {
+ $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
+ } else {
+ $parent = $this->message[$pos]['parent'];
+ if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
+ $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
+ } else {
+ $this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata'];
+ }
+ }
+ }
+ $this->message[$pos]['result'] = $this->message[$pos]['xattrs'];
+ // set value of simpleType (or nil complexType)
+ } else {
+ //$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']);
+ if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
+ $this->message[$pos]['xattrs']['!'] = null;
+ } elseif (isset($this->message[$pos]['type'])) {
+ $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
+ } else {
+ $parent = $this->message[$pos]['parent'];
+ if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
+ $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
+ } else {
+ $this->message[$pos]['result'] = $this->message[$pos]['cdata'];
+ }
+ }
+
+ /* add value to parent's result, if parent is struct/array
+ $parent = $this->message[$pos]['parent'];
+ if($this->message[$parent]['type'] != 'map'){
+ if(strtolower($this->message[$parent]['type']) == 'array'){
+ $this->message[$parent]['result'][] = $this->message[$pos]['result'];
+ } else {
+ $this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result'];
+ }
+ }
+ */
+ }
+ }
+
+ // for doclit
+ if($this->status == 'header'){
+ if ($this->root_header != $pos) {
+ $this->responseHeaders .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
+ }
+ } elseif($pos >= $this->root_struct){
+ $this->document .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
+ }
+ // switch status
+ if ($pos == $this->root_struct){
+ $this->status = 'body';
+ $this->root_struct_namespace = $this->message[$pos]['namespace'];
+ } elseif ($pos == $this->root_header) {
+ $this->status = 'envelope';
+ } elseif ($name == 'Body' && $this->status == 'body') {
+ $this->status = 'envelope';
+ } elseif ($name == 'Header' && $this->status == 'header') { // will never happen
+ $this->status = 'envelope';
+ } elseif ($name == 'Envelope' && $this->status == 'envelope') {
+ $this->status = '';
+ }
+ // set parent back to my parent
+ $this->parent = $this->message[$pos]['parent'];
+ }
+
+ /**
+ * element content handler
+ *
+ * @param resource $parser XML parser object
+ * @param string $data element content
+ * @access private
+ */
+ function character_data($parser, $data){
+ $pos = $this->depth_array[$this->depth];
+ if ($this->xml_encoding=='UTF-8'){
+ // TODO: add an option to disable this for folks who want
+ // raw UTF-8 that, e.g., might not map to iso-8859-1
+ // TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
+ if($this->decode_utf8){
+ $data = utf8_decode($data);
+ }
+ }
+ $this->message[$pos]['cdata'] .= $data;
+ // for doclit
+ if($this->status == 'header'){
+ $this->responseHeaders .= $data;
+ } else {
+ $this->document .= $data;
+ }
+ }
+
+ /**
+ * get the parsed message (SOAP Body)
+ *
+ * @return mixed
+ * @access public
+ * @deprecated use get_soapbody instead
+ */
+ function get_response(){
+ return $this->soapresponse;
+ }
+
+ /**
+ * get the parsed SOAP Body (NULL if there was none)
+ *
+ * @return mixed
+ * @access public
+ */
+ function get_soapbody(){
+ return $this->soapresponse;
+ }
+
+ /**
+ * get the parsed SOAP Header (NULL if there was none)
+ *
+ * @return mixed
+ * @access public
+ */
+ function get_soapheader(){
+ return $this->soapheader;
+ }
+
+ /**
+ * get the unparsed SOAP Header
+ *
+ * @return string XML or empty if no Header
+ * @access public
+ */
+ function getHeaders(){
+ return $this->responseHeaders;
+ }
+
+ /**
+ * decodes simple types into PHP variables
+ *
+ * @param string $value value to decode
+ * @param string $type XML type to decode
+ * @param string $typens XML type namespace to decode
+ * @return mixed PHP value
+ * @access private
+ */
+ function decodeSimple($value, $type, $typens) {
+ // TODO: use the namespace!
+ if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') {
+ return (string) $value;
+ }
+ if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') {
+ return (int) $value;
+ }
+ if ($type == 'float' || $type == 'double' || $type == 'decimal') {
+ return (double) $value;
+ }
+ if ($type == 'boolean') {
+ if (strtolower($value) == 'false' || strtolower($value) == 'f') {
+ return false;
+ }
+ return (boolean) $value;
+ }
+ if ($type == 'base64' || $type == 'base64Binary') {
+ $this->debug('Decode base64 value');
+ return base64_decode($value);
+ }
+ // obscure numeric types
+ if ($type == 'nonPositiveInteger' || $type == 'negativeInteger'
+ || $type == 'nonNegativeInteger' || $type == 'positiveInteger'
+ || $type == 'unsignedInt'
+ || $type == 'unsignedShort' || $type == 'unsignedByte') {
+ return (int) $value;
+ }
+ // bogus: parser treats array with no elements as a simple type
+ if ($type == 'array') {
+ return array();
+ }
+ // everything else
+ return (string) $value;
+ }
+
+ /**
+ * builds response structures for compound values (arrays/structs)
+ * and scalars
+ *
+ * @param integer $pos position in node tree
+ * @return mixed PHP value
+ * @access private
+ */
+ function buildVal($pos){
+ if(!isset($this->message[$pos]['type'])){
+ $this->message[$pos]['type'] = '';
+ }
+ $this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']);
+ // if there are children...
+ if($this->message[$pos]['children'] != ''){
+ $this->debug('in buildVal, there are children');
+ $children = explode('|',$this->message[$pos]['children']);
+ array_shift($children); // knock off empty
+ // md array
+ if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){
+ $r=0; // rowcount
+ $c=0; // colcount
+ foreach($children as $child_pos){
+ $this->debug("in buildVal, got an MD array element: $r, $c");
+ $params[$r][] = $this->message[$child_pos]['result'];
+ $c++;
+ if($c == $this->message[$pos]['arrayCols']){
+ $c = 0;
+ $r++;
+ }
+ }
+ // array
+ } elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){
+ $this->debug('in buildVal, adding array '.$this->message[$pos]['name']);
+ foreach($children as $child_pos){
+ $params[] = &$this->message[$child_pos]['result'];
+ }
+ // apache Map type: java hashtable
+ } elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){
+ $this->debug('in buildVal, Java Map '.$this->message[$pos]['name']);
+ foreach($children as $child_pos){
+ $kv = explode("|",$this->message[$child_pos]['children']);
+ $params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result'];
+ }
+ // generic compound type
+ //} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') {
+ } else {
+ // Apache Vector type: treat as an array
+ $this->debug('in buildVal, adding Java Vector or generic compound type '.$this->message[$pos]['name']);
+ if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') {
+ $notstruct = 1;
+ } else {
+ $notstruct = 0;
+ }
+ //
+ foreach($children as $child_pos){
+ if($notstruct){
+ $params[] = &$this->message[$child_pos]['result'];
+ } else {
+ if (isset($params[$this->message[$child_pos]['name']])) {
+ // de-serialize repeated element name into an array
+ if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) {
+ $params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]);
+ }
+ $params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result'];
+ } else {
+ $params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result'];
+ }
+ }
+ }
+ }
+ if (isset($this->message[$pos]['xattrs'])) {
+ $this->debug('in buildVal, handling attributes');
+ foreach ($this->message[$pos]['xattrs'] as $n => $v) {
+ $params[$n] = $v;
+ }
+ }
+ // handle simpleContent
+ if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
+ $this->debug('in buildVal, handling simpleContent');
+ if (isset($this->message[$pos]['type'])) {
+ $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
+ } else {
+ $parent = $this->message[$pos]['parent'];
+ if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
+ $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
+ } else {
+ $params['!'] = $this->message[$pos]['cdata'];
+ }
+ }
+ }
+ $ret = is_array($params) ? $params : array();
+ $this->debug('in buildVal, return:');
+ $this->appendDebug($this->varDump($ret));
+ return $ret;
+ } else {
+ $this->debug('in buildVal, no children, building scalar');
+ $cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : '';
+ if (isset($this->message[$pos]['type'])) {
+ $ret = $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
+ $this->debug("in buildVal, return: $ret");
+ return $ret;
+ }
+ $parent = $this->message[$pos]['parent'];
+ if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
+ $ret = $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
+ $this->debug("in buildVal, return: $ret");
+ return $ret;
+ }
+ $ret = $this->message[$pos]['cdata'];
+ $this->debug("in buildVal, return: $ret");
+ return $ret;
+ }
+ }
+}
+
+/**
+ * Backward compatibility
+ */
+class soap_parser extends nusoap_parser {
+}
+
+
+?>
\ No newline at end of file
--- /dev/null
+<?php
+
+
+
+
+/**
+*
+* nusoap_server allows the user to create a SOAP server
+* that is capable of receiving messages and returning responses
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: class.soap_server.php,v 1.63 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_server extends nusoap_base {
+ /**
+ * HTTP headers of request
+ * @var array
+ * @access private
+ */
+ var $headers = array();
+ /**
+ * HTTP request
+ * @var string
+ * @access private
+ */
+ var $request = '';
+ /**
+ * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text)
+ * @var string
+ * @access public
+ */
+ var $requestHeaders = '';
+ /**
+ * SOAP Headers from request (parsed)
+ * @var mixed
+ * @access public
+ */
+ var $requestHeader = NULL;
+ /**
+ * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text)
+ * @var string
+ * @access public
+ */
+ var $document = '';
+ /**
+ * SOAP payload for request (text)
+ * @var string
+ * @access public
+ */
+ var $requestSOAP = '';
+ /**
+ * requested method namespace URI
+ * @var string
+ * @access private
+ */
+ var $methodURI = '';
+ /**
+ * name of method requested
+ * @var string
+ * @access private
+ */
+ var $methodname = '';
+ /**
+ * method parameters from request
+ * @var array
+ * @access private
+ */
+ var $methodparams = array();
+ /**
+ * SOAP Action from request
+ * @var string
+ * @access private
+ */
+ var $SOAPAction = '';
+ /**
+ * character set encoding of incoming (request) messages
+ * @var string
+ * @access public
+ */
+ var $xml_encoding = '';
+ /**
+ * toggles whether the parser decodes element content w/ utf8_decode()
+ * @var boolean
+ * @access public
+ */
+ var $decode_utf8 = true;
+
+ /**
+ * HTTP headers of response
+ * @var array
+ * @access public
+ */
+ var $outgoing_headers = array();
+ /**
+ * HTTP response
+ * @var string
+ * @access private
+ */
+ var $response = '';
+ /**
+ * SOAP headers for response (text or array of soapval or associative array)
+ * @var mixed
+ * @access public
+ */
+ var $responseHeaders = '';
+ /**
+ * SOAP payload for response (text)
+ * @var string
+ * @access private
+ */
+ var $responseSOAP = '';
+ /**
+ * method return value to place in response
+ * @var mixed
+ * @access private
+ */
+ var $methodreturn = false;
+ /**
+ * whether $methodreturn is a string of literal XML
+ * @var boolean
+ * @access public
+ */
+ var $methodreturnisliteralxml = false;
+ /**
+ * SOAP fault for response (or false)
+ * @var mixed
+ * @access private
+ */
+ var $fault = false;
+ /**
+ * text indication of result (for debugging)
+ * @var string
+ * @access private
+ */
+ var $result = 'successful';
+
+ /**
+ * assoc array of operations => opData; operations are added by the register()
+ * method or by parsing an external WSDL definition
+ * @var array
+ * @access private
+ */
+ var $operations = array();
+ /**
+ * wsdl instance (if one)
+ * @var mixed
+ * @access private
+ */
+ var $wsdl = false;
+ /**
+ * URL for WSDL (if one)
+ * @var mixed
+ * @access private
+ */
+ var $externalWSDLURL = false;
+ /**
+ * whether to append debug to response as XML comment
+ * @var boolean
+ * @access public
+ */
+ var $debug_flag = false;
+
+
+ /**
+ * constructor
+ * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to.
+ *
+ * @param mixed $wsdl file path or URL (string), or wsdl instance (object)
+ * @access public
+ */
+ function nusoap_server($wsdl=false){
+ parent::nusoap_base();
+ // turn on debugging?
+ global $debug;
+ global $HTTP_SERVER_VARS;
+
+ if (isset($_SERVER)) {
+ $this->debug("_SERVER is defined:");
+ $this->appendDebug($this->varDump($_SERVER));
+ } elseif (isset($HTTP_SERVER_VARS)) {
+ $this->debug("HTTP_SERVER_VARS is defined:");
+ $this->appendDebug($this->varDump($HTTP_SERVER_VARS));
+ } else {
+ $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined.");
+ }
+
+ if (isset($debug)) {
+ $this->debug("In nusoap_server, set debug_flag=$debug based on global flag");
+ $this->debug_flag = $debug;
+ } elseif (isset($_SERVER['QUERY_STRING'])) {
+ $qs = explode('&', $_SERVER['QUERY_STRING']);
+ foreach ($qs as $v) {
+ if (substr($v, 0, 6) == 'debug=') {
+ $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1");
+ $this->debug_flag = substr($v, 6);
+ }
+ }
+ } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
+ $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']);
+ foreach ($qs as $v) {
+ if (substr($v, 0, 6) == 'debug=') {
+ $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2");
+ $this->debug_flag = substr($v, 6);
+ }
+ }
+ }
+
+ // wsdl
+ if($wsdl){
+ $this->debug("In nusoap_server, WSDL is specified");
+ if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) {
+ $this->wsdl = $wsdl;
+ $this->externalWSDLURL = $this->wsdl->wsdl;
+ $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL);
+ } else {
+ $this->debug('Create wsdl from ' . $wsdl);
+ $this->wsdl = new wsdl($wsdl);
+ $this->externalWSDLURL = $wsdl;
+ }
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ if($err = $this->wsdl->getError()){
+ die('WSDL ERROR: '.$err);
+ }
+ }
+ }
+
+ /**
+ * processes request and returns response
+ *
+ * @param string $data usually is the value of $HTTP_RAW_POST_DATA
+ * @access public
+ */
+ function service($data){
+ global $HTTP_SERVER_VARS;
+
+ if (isset($_SERVER['REQUEST_METHOD'])) {
+ $rm = $_SERVER['REQUEST_METHOD'];
+ } elseif (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
+ $rm = $HTTP_SERVER_VARS['REQUEST_METHOD'];
+ } else {
+ $rm = '';
+ }
+
+ if (isset($_SERVER['QUERY_STRING'])) {
+ $qs = $_SERVER['QUERY_STRING'];
+ } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
+ $qs = $HTTP_SERVER_VARS['QUERY_STRING'];
+ } else {
+ $qs = '';
+ }
+ $this->debug("In service, request method=$rm query string=$qs strlen(\$data)=" . strlen($data));
+
+ if ($rm == 'POST') {
+ $this->debug("In service, invoke the request");
+ $this->parse_request($data);
+ if (! $this->fault) {
+ $this->invoke_method();
+ }
+ if (! $this->fault) {
+ $this->serialize_return();
+ }
+ $this->send_response();
+ } elseif (preg_match('/wsdl/', $qs) ){
+ $this->debug("In service, this is a request for WSDL");
+ if ($this->externalWSDLURL){
+ if (strpos($this->externalWSDLURL, "http://") !== false) { // assume URL
+ $this->debug("In service, re-direct for WSDL");
+ header('Location: '.$this->externalWSDLURL);
+ } else { // assume file
+ $this->debug("In service, use file passthru for WSDL");
+ header("Content-Type: text/xml\r\n");
+ $pos = strpos($this->externalWSDLURL, "file://");
+ if ($pos === false) {
+ $filename = $this->externalWSDLURL;
+ } else {
+ $filename = substr($this->externalWSDLURL, $pos + 7);
+ }
+ $fp = fopen($this->externalWSDLURL, 'r');
+ fpassthru($fp);
+ }
+ } elseif ($this->wsdl) {
+ $this->debug("In service, serialize WSDL");
+ header("Content-Type: text/xml; charset=ISO-8859-1\r\n");
+ print $this->wsdl->serialize($this->debug_flag);
+ if ($this->debug_flag) {
+ $this->debug('wsdl:');
+ $this->appendDebug($this->varDump($this->wsdl));
+ print $this->getDebugAsXMLComment();
+ }
+ } else {
+ $this->debug("In service, there is no WSDL");
+ header("Content-Type: text/html; charset=ISO-8859-1\r\n");
+ print "This service does not provide WSDL";
+ }
+ } elseif ($this->wsdl) {
+ $this->debug("In service, return Web description");
+ print $this->wsdl->webDescription();
+ } else {
+ $this->debug("In service, no Web description");
+ header("Content-Type: text/html; charset=ISO-8859-1\r\n");
+ print "This service does not provide a Web description";
+ }
+ }
+
+ /**
+ * parses HTTP request headers.
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * headers
+ * request
+ * xml_encoding
+ * SOAPAction
+ *
+ * @access private
+ */
+ function parse_http_headers() {
+ global $HTTP_SERVER_VARS;
+
+ $this->request = '';
+ $this->SOAPAction = '';
+ if(function_exists('getallheaders')){
+ $this->debug("In parse_http_headers, use getallheaders");
+ $headers = getallheaders();
+ foreach($headers as $k=>$v){
+ $k = strtolower($k);
+ $this->headers[$k] = $v;
+ $this->request .= "$k: $v\r\n";
+ $this->debug("$k: $v");
+ }
+ // get SOAPAction header
+ if(isset($this->headers['soapaction'])){
+ $this->SOAPAction = str_replace('"','',$this->headers['soapaction']);
+ }
+ // get the character encoding of the incoming request
+ if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){
+ $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1));
+ if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ } elseif(isset($_SERVER) && is_array($_SERVER)){
+ $this->debug("In parse_http_headers, use _SERVER");
+ foreach ($_SERVER as $k => $v) {
+ if (substr($k, 0, 5) == 'HTTP_') {
+ $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5))));
+ } else {
+ $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k)));
+ }
+ if ($k == 'soapaction') {
+ // get SOAPAction header
+ $k = 'SOAPAction';
+ $v = str_replace('"', '', $v);
+ $v = str_replace('\\', '', $v);
+ $this->SOAPAction = $v;
+ } else if ($k == 'content-type') {
+ // get the character encoding of the incoming request
+ if (strpos($v, '=')) {
+ $enc = substr(strstr($v, '='), 1);
+ $enc = str_replace('"', '', $enc);
+ $enc = str_replace('\\', '', $enc);
+ if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) {
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ }
+ $this->headers[$k] = $v;
+ $this->request .= "$k: $v\r\n";
+ $this->debug("$k: $v");
+ }
+ } elseif (is_array($HTTP_SERVER_VARS)) {
+ $this->debug("In parse_http_headers, use HTTP_SERVER_VARS");
+ foreach ($HTTP_SERVER_VARS as $k => $v) {
+ if (substr($k, 0, 5) == 'HTTP_') {
+ $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
+ } else {
+ $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
+ }
+ if ($k == 'soapaction') {
+ // get SOAPAction header
+ $k = 'SOAPAction';
+ $v = str_replace('"', '', $v);
+ $v = str_replace('\\', '', $v);
+ $this->SOAPAction = $v;
+ } else if ($k == 'content-type') {
+ // get the character encoding of the incoming request
+ if (strpos($v, '=')) {
+ $enc = substr(strstr($v, '='), 1);
+ $enc = str_replace('"', '', $enc);
+ $enc = str_replace('\\', '', $enc);
+ if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) {
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ }
+ $this->headers[$k] = $v;
+ $this->request .= "$k: $v\r\n";
+ $this->debug("$k: $v");
+ }
+ } else {
+ $this->debug("In parse_http_headers, HTTP headers not accessible");
+ $this->setError("HTTP headers not accessible");
+ }
+ }
+
+ /**
+ * parses a request
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * headers
+ * request
+ * xml_encoding
+ * SOAPAction
+ * request
+ * requestSOAP
+ * methodURI
+ * methodname
+ * methodparams
+ * requestHeaders
+ * document
+ *
+ * This sets the fault field on error
+ *
+ * @param string $data XML string
+ * @access private
+ */
+ function parse_request($data='') {
+ $this->debug('entering parse_request()');
+ $this->parse_http_headers();
+ $this->debug('got character encoding: '.$this->xml_encoding);
+ // uncompress if necessary
+ if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') {
+ $this->debug('got content encoding: ' . $this->headers['content-encoding']);
+ if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') {
+ // if decoding works, use it. else assume data wasn't gzencoded
+ if (function_exists('gzuncompress')) {
+ if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
+ $data = $degzdata;
+ } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) {
+ $data = $degzdata;
+ } else {
+ $this->fault('SOAP-ENV:Client', 'Errors occurred when trying to decode the data');
+ return;
+ }
+ } else {
+ $this->fault('SOAP-ENV:Client', 'This Server does not support compressed data');
+ return;
+ }
+ }
+ }
+ $this->request .= "\r\n".$data;
+ $data = $this->parseRequest($this->headers, $data);
+ $this->requestSOAP = $data;
+ $this->debug('leaving parse_request');
+ }
+
+ /**
+ * invokes a PHP function for the requested SOAP method
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * methodreturn
+ *
+ * Note that the PHP function that is called may also set the following
+ * fields to affect the response sent to the client
+ *
+ * responseHeaders
+ * outgoing_headers
+ *
+ * This sets the fault field on error
+ *
+ * @access private
+ */
+ function invoke_method() {
+ $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction);
+
+ //
+ // if you are debugging in this area of the code, your service uses a class to implement methods,
+ // you use SOAP RPC, and the client is .NET, please be aware of the following...
+ // when the .NET wsdl.exe utility generates a proxy, it will remove the '.' or '..' from the
+ // method name. that is fine for naming the .NET methods. it is not fine for properly constructing
+ // the XML request and reading the XML response. you need to add the RequestElementName and
+ // ResponseElementName to the System.Web.Services.Protocols.SoapRpcMethodAttribute that wsdl.exe
+ // generates for the method. these parameters are used to specify the correct XML element names
+ // for .NET to use, i.e. the names with the '.' in them.
+ //
+ $orig_methodname = $this->methodname;
+ if ($this->wsdl) {
+ if ($this->opData = $this->wsdl->getOperationData($this->methodname)) {
+ $this->debug('in invoke_method, found WSDL operation=' . $this->methodname);
+ $this->appendDebug('opData=' . $this->varDump($this->opData));
+ } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) {
+ // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element
+ $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']);
+ $this->appendDebug('opData=' . $this->varDump($this->opData));
+ $this->methodname = $this->opData['name'];
+ } else {
+ $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname);
+ $this->fault('SOAP-ENV:Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service");
+ return;
+ }
+ } else {
+ $this->debug('in invoke_method, no WSDL to validate method');
+ }
+
+ // if a . is present in $this->methodname, we see if there is a class in scope,
+ // which could be referred to. We will also distinguish between two deliminators,
+ // to allow methods to be called a the class or an instance
+ if (strpos($this->methodname, '..') > 0) {
+ $delim = '..';
+ } else if (strpos($this->methodname, '.') > 0) {
+ $delim = '.';
+ } else {
+ $delim = '';
+ }
+ $this->debug("in invoke_method, delim=$delim");
+
+ $class = '';
+ $method = '';
+ if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) {
+ $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim));
+ if (class_exists($try_class)) {
+ // get the class and method name
+ $class = $try_class;
+ $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
+ $this->debug("in invoke_method, class=$class method=$method delim=$delim");
+ } else {
+ $this->debug("in invoke_method, class=$try_class not found");
+ }
+ } else {
+ $try_class = '';
+ $this->debug("in invoke_method, no class to try");
+ }
+
+ // does method exist?
+ if ($class == '') {
+ if (!function_exists($this->methodname)) {
+ $this->debug("in invoke_method, function '$this->methodname' not found!");
+ $this->result = 'fault: method not found';
+ $this->fault('SOAP-ENV:Client',"method '$this->methodname'('$orig_methodname') not defined in service('$try_class' '$delim')");
+ return;
+ }
+ } else {
+ $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method;
+ if (!in_array($method_to_compare, get_class_methods($class))) {
+ $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!");
+ $this->result = 'fault: method not found';
+ $this->fault('SOAP-ENV:Client',"method '$this->methodname'/'$method_to_compare'('$orig_methodname') not defined in service/'$class'('$try_class' '$delim')");
+ return;
+ }
+ }
+
+ // evaluate message, getting back parameters
+ // verify that request parameters match the method's signature
+ if(! $this->verify_method($this->methodname,$this->methodparams)){
+ // debug
+ $this->debug('ERROR: request not verified against method signature');
+ $this->result = 'fault: request failed validation against method signature';
+ // return fault
+ $this->fault('SOAP-ENV:Client',"Operation '$this->methodname' not defined in service.");
+ return;
+ }
+
+ // if there are parameters to pass
+ $this->debug('in invoke_method, params:');
+ $this->appendDebug($this->varDump($this->methodparams));
+ $this->debug("in invoke_method, calling '$this->methodname'");
+ if (!function_exists('call_user_func_array')) {
+ if ($class == '') {
+ $this->debug('in invoke_method, calling function using eval()');
+ $funcCall = "\$this->methodreturn = $this->methodname(";
+ } else {
+ if ($delim == '..') {
+ $this->debug('in invoke_method, calling class method using eval()');
+ $funcCall = "\$this->methodreturn = ".$class."::".$method."(";
+ } else {
+ $this->debug('in invoke_method, calling instance method using eval()');
+ // generate unique instance name
+ $instname = "\$inst_".time();
+ $funcCall = $instname." = new ".$class."(); ";
+ $funcCall .= "\$this->methodreturn = ".$instname."->".$method."(";
+ }
+ }
+ if ($this->methodparams) {
+ foreach ($this->methodparams as $param) {
+ if (is_array($param) || is_object($param)) {
+ $this->fault('SOAP-ENV:Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available');
+ return;
+ }
+ $funcCall .= "\"$param\",";
+ }
+ $funcCall = substr($funcCall, 0, -1);
+ }
+ $funcCall .= ');';
+ $this->debug('in invoke_method, function call: '.$funcCall);
+ @eval($funcCall);
+ } else {
+ if ($class == '') {
+ $this->debug('in invoke_method, calling function using call_user_func_array()');
+ $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array()
+ } elseif ($delim == '..') {
+ $this->debug('in invoke_method, calling class method using call_user_func_array()');
+ $call_arg = array ($class, $method);
+ } else {
+ $this->debug('in invoke_method, calling instance method using call_user_func_array()');
+ $instance = new $class ();
+ $call_arg = array(&$instance, $method);
+ }
+ if (is_array($this->methodparams)) {
+ $this->methodreturn = call_user_func_array($call_arg, array_values($this->methodparams));
+ } else {
+ $this->methodreturn = call_user_func_array($call_arg, array());
+ }
+ }
+ $this->debug('in invoke_method, methodreturn:');
+ $this->appendDebug($this->varDump($this->methodreturn));
+ $this->debug("in invoke_method, called method $this->methodname, received data of type ".gettype($this->methodreturn));
+ }
+
+ /**
+ * serializes the return value from a PHP function into a full SOAP Envelope
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * responseSOAP
+ *
+ * This sets the fault field on error
+ *
+ * @access private
+ */
+ function serialize_return() {
+ $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI);
+ // if fault
+ if (isset($this->methodreturn) && is_object($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) {
+ $this->debug('got a fault object from method');
+ $this->fault = $this->methodreturn;
+ return;
+ } elseif ($this->methodreturnisliteralxml) {
+ $return_val = $this->methodreturn;
+ // returned value(s)
+ } else {
+ $this->debug('got a(n) '.gettype($this->methodreturn).' from method');
+ $this->debug('serializing return value');
+ if($this->wsdl){
+ if (sizeof($this->opData['output']['parts']) > 1) {
+ $this->debug('more than one output part, so use the method return unchanged');
+ $opParams = $this->methodreturn;
+ } elseif (sizeof($this->opData['output']['parts']) == 1) {
+ $this->debug('exactly one output part, so wrap the method return in a simple array');
+ // TODO: verify that it is not already wrapped!
+ //foreach ($this->opData['output']['parts'] as $name => $type) {
+ // $this->debug('wrap in element named ' . $name);
+ //}
+ $opParams = array($this->methodreturn);
+ }
+ $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams);
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ if($errstr = $this->wsdl->getError()){
+ $this->debug('got wsdl error: '.$errstr);
+ $this->fault('SOAP-ENV:Server', 'unable to serialize result');
+ return;
+ }
+ } else {
+ if (isset($this->methodreturn)) {
+ $return_val = $this->serialize_val($this->methodreturn, 'return');
+ } else {
+ $return_val = '';
+ $this->debug('in absence of WSDL, assume void return for backward compatibility');
+ }
+ }
+ }
+ $this->debug('return value:');
+ $this->appendDebug($this->varDump($return_val));
+
+ $this->debug('serializing response');
+ if ($this->wsdl) {
+ $this->debug('have WSDL for serialization: style is ' . $this->opData['style']);
+ if ($this->opData['style'] == 'rpc') {
+ $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']);
+ if ($this->opData['output']['use'] == 'literal') {
+ // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace
+ if ($this->methodURI) {
+ $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
+ } else {
+ $payload = '<'.$this->methodname.'Response>'.$return_val.'</'.$this->methodname.'Response>';
+ }
+ } else {
+ if ($this->methodURI) {
+ $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
+ } else {
+ $payload = '<'.$this->methodname.'Response>'.$return_val.'</'.$this->methodname.'Response>';
+ }
+ }
+ } else {
+ $this->debug('style is not rpc for serialization: assume document');
+ $payload = $return_val;
+ }
+ } else {
+ $this->debug('do not have WSDL for serialization: assume rpc/encoded');
+ $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
+ }
+ $this->result = 'successful';
+ if($this->wsdl){
+ //if($this->debug_flag){
+ $this->appendDebug($this->wsdl->getDebug());
+ // }
+ if (isset($this->opData['output']['encodingStyle'])) {
+ $encodingStyle = $this->opData['output']['encodingStyle'];
+ } else {
+ $encodingStyle = '';
+ }
+ // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces.
+ $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$this->opData['output']['use'],$encodingStyle);
+ } else {
+ $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders);
+ }
+ $this->debug("Leaving serialize_return");
+ }
+
+ /**
+ * sends an HTTP response
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * outgoing_headers
+ * response
+ *
+ * @access private
+ */
+ function send_response() {
+ $this->debug('Enter send_response');
+ if ($this->fault) {
+ $payload = $this->fault->serialize();
+ $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error";
+ $this->outgoing_headers[] = "Status: 500 Internal Server Error";
+ } else {
+ $payload = $this->responseSOAP;
+ // Some combinations of PHP+Web server allow the Status
+ // to come through as a header. Since OK is the default
+ // just do nothing.
+ // $this->outgoing_headers[] = "HTTP/1.0 200 OK";
+ // $this->outgoing_headers[] = "Status: 200 OK";
+ }
+ // add debug data if in debug mode
+ if(isset($this->debug_flag) && $this->debug_flag){
+ $payload .= $this->getDebugAsXMLComment();
+ }
+ $this->outgoing_headers[] = "Server: $this->title Server v$this->version";
+ preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
+ $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")";
+ // Let the Web server decide about this
+ //$this->outgoing_headers[] = "Connection: Close\r\n";
+ $payload = $this->getHTTPBody($payload);
+ $type = $this->getHTTPContentType();
+ $charset = $this->getHTTPContentTypeCharset();
+ $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : '');
+ //begin code to compress payload - by John
+ // NOTE: there is no way to know whether the Web server will also compress
+ // this data.
+ if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) {
+ if (strstr($this->headers['accept-encoding'], 'gzip')) {
+ if (function_exists('gzencode')) {
+ if (isset($this->debug_flag) && $this->debug_flag) {
+ $payload .= "<!-- Content being gzipped -->";
+ }
+ $this->outgoing_headers[] = "Content-Encoding: gzip";
+ $payload = gzencode($payload);
+ } else {
+ if (isset($this->debug_flag) && $this->debug_flag) {
+ $payload .= "<!-- Content will not be gzipped: no gzencode -->";
+ }
+ }
+ } elseif (strstr($this->headers['accept-encoding'], 'deflate')) {
+ // Note: MSIE requires gzdeflate output (no Zlib header and checksum),
+ // instead of gzcompress output,
+ // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5)
+ if (function_exists('gzdeflate')) {
+ if (isset($this->debug_flag) && $this->debug_flag) {
+ $payload .= "<!-- Content being deflated -->";
+ }
+ $this->outgoing_headers[] = "Content-Encoding: deflate";
+ $payload = gzdeflate($payload);
+ } else {
+ if (isset($this->debug_flag) && $this->debug_flag) {
+ $payload .= "<!-- Content will not be deflated: no gzcompress -->";
+ }
+ }
+ }
+ }
+ //end code
+ $this->outgoing_headers[] = "Content-Length: ".strlen($payload);
+ reset($this->outgoing_headers);
+ foreach($this->outgoing_headers as $hdr){
+ header($hdr, false);
+ }
+ print $payload;
+ $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload;
+ }
+
+ /**
+ * takes the value that was created by parsing the request
+ * and compares to the method's signature, if available.
+ *
+ * @param string $operation The operation to be invoked
+ * @param array $request The array of parameter values
+ * @return boolean Whether the operation was found
+ * @access private
+ */
+ function verify_method($operation,$request){
+ if(isset($this->wsdl) && is_object($this->wsdl)){
+ if($this->wsdl->getOperationData($operation)){
+ return true;
+ }
+ } elseif(isset($this->operations[$operation])){
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * processes SOAP message received from client
+ *
+ * @param array $headers The HTTP headers
+ * @param string $data unprocessed request data from client
+ * @return mixed value of the message, decoded into a PHP type
+ * @access private
+ */
+ function parseRequest($headers, $data) {
+ $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' headers:');
+ $this->appendDebug($this->varDump($headers));
+ if (!isset($headers['content-type'])) {
+ $this->setError('Request not of type text/xml (no content-type header)');
+ return false;
+ }
+ if (!strstr($headers['content-type'], 'text/xml')) {
+ $this->setError('Request not of type text/xml');
+ return false;
+ }
+ if (strpos($headers['content-type'], '=')) {
+ $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
+ $this->debug('Got response encoding: ' . $enc);
+ if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
+ // parse response, get soap parser obj
+ $parser = new nusoap_parser($data,$this->xml_encoding,'',$this->decode_utf8);
+ // parser debug
+ $this->debug("parser debug: \n".$parser->getDebug());
+ // if fault occurred during message parsing
+ if($err = $parser->getError()){
+ $this->result = 'fault: error in msg parsing: '.$err;
+ $this->fault('SOAP-ENV:Client',"error in msg parsing:\n".$err);
+ // else successfully parsed request into soapval object
+ } else {
+ // get/set methodname
+ $this->methodURI = $parser->root_struct_namespace;
+ $this->methodname = $parser->root_struct_name;
+ $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI);
+ $this->debug('calling parser->get_soapbody()');
+ $this->methodparams = $parser->get_soapbody();
+ // get SOAP headers
+ $this->requestHeaders = $parser->getHeaders();
+ // get SOAP Header
+ $this->requestHeader = $parser->get_soapheader();
+ // add document for doclit support
+ $this->document = $parser->document;
+ }
+ }
+
+ /**
+ * gets the HTTP body for the current response.
+ *
+ * @param string $soapmsg The SOAP payload
+ * @return string The HTTP body, which includes the SOAP payload
+ * @access private
+ */
+ function getHTTPBody($soapmsg) {
+ return $soapmsg;
+ }
+
+ /**
+ * gets the HTTP content type for the current response.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type for the current response.
+ * @access private
+ */
+ function getHTTPContentType() {
+ return 'text/xml';
+ }
+
+ /**
+ * gets the HTTP content type charset for the current response.
+ * returns false for non-text content types.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type charset for the current response.
+ * @access private
+ */
+ function getHTTPContentTypeCharset() {
+ return $this->soap_defencoding;
+ }
+
+ /**
+ * add a method to the dispatch map (this has been replaced by the register method)
+ *
+ * @param string $methodname
+ * @param string $in array of input values
+ * @param string $out array of output values
+ * @access public
+ * @deprecated
+ */
+ function add_to_map($methodname,$in,$out){
+ $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out);
+ }
+
+ /**
+ * register a service function with the server
+ *
+ * @param string $name the name of the PHP function, class.method or class..method
+ * @param array $in assoc array of input values: key = param name, value = param type
+ * @param array $out assoc array of output values: key = param name, value = param type
+ * @param mixed $namespace the element namespace for the method or false
+ * @param mixed $soapaction the soapaction for the method or false
+ * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically
+ * @param mixed $use optional (encoded|literal) or false
+ * @param string $documentation optional Description to include in WSDL
+ * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
+ * @access public
+ */
+ function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){
+ global $HTTP_SERVER_VARS;
+
+ if($this->externalWSDLURL){
+ die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.');
+ }
+ if (! $name) {
+ die('You must specify a name when you register an operation');
+ }
+ if (!is_array($in)) {
+ die('You must provide an array for operation inputs');
+ }
+ if (!is_array($out)) {
+ die('You must provide an array for operation outputs');
+ }
+ if(false == $namespace) {
+ }
+ if(false == $soapaction) {
+ if (isset($_SERVER)) {
+ $SERVER_NAME = $_SERVER['SERVER_NAME'];
+ $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
+ $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
+ } elseif (isset($HTTP_SERVER_VARS)) {
+ $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
+ $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
+ $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
+ } else {
+ $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
+ }
+ if ($HTTPS == '1' || $HTTPS == 'on') {
+ $SCHEME = 'https';
+ } else {
+ $SCHEME = 'http';
+ }
+ $soapaction = "$SCHEME://$SERVER_NAME$SCRIPT_NAME/$name";
+ }
+ if(false == $style) {
+ $style = "rpc";
+ }
+ if(false == $use) {
+ $use = "encoded";
+ }
+ if ($use == 'encoded' && $encodingStyle == '') {
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ }
+
+ $this->operations[$name] = array(
+ 'name' => $name,
+ 'in' => $in,
+ 'out' => $out,
+ 'namespace' => $namespace,
+ 'soapaction' => $soapaction,
+ 'style' => $style);
+ if($this->wsdl){
+ $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle);
+ }
+ return true;
+ }
+
+ /**
+ * Specify a fault to be returned to the client.
+ * This also acts as a flag to the server that a fault has occured.
+ *
+ * @param string $faultcode
+ * @param string $faultstring
+ * @param string $faultactor
+ * @param string $faultdetail
+ * @access public
+ */
+ function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){
+ if ($faultdetail == '' && $this->debug_flag) {
+ $faultdetail = $this->getDebug();
+ }
+ $this->fault = new nusoap_fault($faultcode,$faultactor,$faultstring,$faultdetail);
+ $this->fault->soap_defencoding = $this->soap_defencoding;
+ }
+
+ /**
+ * Sets up wsdl object.
+ * Acts as a flag to enable internal WSDL generation
+ *
+ * @param string $serviceName, name of the service
+ * @param mixed $namespace optional 'tns' service namespace or false
+ * @param mixed $endpoint optional URL of service endpoint or false
+ * @param string $style optional (rpc|document) WSDL style (also specified by operation)
+ * @param string $transport optional SOAP transport
+ * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false
+ */
+ function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false)
+ {
+ global $HTTP_SERVER_VARS;
+
+ if (isset($_SERVER)) {
+ $SERVER_NAME = $_SERVER['SERVER_NAME'];
+ $SERVER_PORT = $_SERVER['SERVER_PORT'];
+ $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
+ $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
+ } elseif (isset($HTTP_SERVER_VARS)) {
+ $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
+ $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT'];
+ $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
+ $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
+ } else {
+ $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
+ }
+ // If server name has port number attached then strip it (else port number gets duplicated in WSDL output) (occurred using lighttpd and FastCGI)
+ $colon = strpos($SERVER_NAME,":");
+ if ($colon) {
+ $SERVER_NAME = substr($SERVER_NAME, 0, $colon);
+ }
+ if ($SERVER_PORT == 80) {
+ $SERVER_PORT = '';
+ } else {
+ $SERVER_PORT = ':' . $SERVER_PORT;
+ }
+ if(false == $namespace) {
+ $namespace = "http://$SERVER_NAME/soap/$serviceName";
+ }
+
+ if(false == $endpoint) {
+ if ($HTTPS == '1' || $HTTPS == 'on') {
+ $SCHEME = 'https';
+ } else {
+ $SCHEME = 'http';
+ }
+ $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME";
+ }
+
+ if(false == $schemaTargetNamespace) {
+ $schemaTargetNamespace = $namespace;
+ }
+
+ $this->wsdl = new wsdl;
+ $this->wsdl->serviceName = $serviceName;
+ $this->wsdl->endpoint = $endpoint;
+ $this->wsdl->namespaces['tns'] = $namespace;
+ $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/';
+ $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/';
+ if ($schemaTargetNamespace != $namespace) {
+ $this->wsdl->namespaces['types'] = $schemaTargetNamespace;
+ }
+ $this->wsdl->schemas[$schemaTargetNamespace][0] = new nusoap_xmlschema('', '', $this->wsdl->namespaces);
+ if ($style == 'document') {
+ $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaInfo['elementFormDefault'] = 'qualified';
+ }
+ $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace;
+ $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true);
+ $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true);
+ $this->wsdl->bindings[$serviceName.'Binding'] = array(
+ 'name'=>$serviceName.'Binding',
+ 'style'=>$style,
+ 'transport'=>$transport,
+ 'portType'=>$serviceName.'PortType');
+ $this->wsdl->ports[$serviceName.'Port'] = array(
+ 'binding'=>$serviceName.'Binding',
+ 'location'=>$endpoint,
+ 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/');
+ }
+}
+
+/**
+ * Backward compatibility
+ */
+class soap_server extends nusoap_server {
+}
+
+
+?>
\ No newline at end of file
--- /dev/null
+<?php
+
+
+
+
+/**
+* transport class for sending/receiving data via HTTP and HTTPS
+* NOTE: PHP must be compiled with the CURL extension for HTTPS support
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: class.soap_transport_http.php,v 1.68 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class soap_transport_http extends nusoap_base {
+
+ var $url = '';
+ var $uri = '';
+ var $digest_uri = '';
+ var $scheme = '';
+ var $host = '';
+ var $port = '';
+ var $path = '';
+ var $request_method = 'POST';
+ var $protocol_version = '1.0';
+ var $encoding = '';
+ var $outgoing_headers = array();
+ var $incoming_headers = array();
+ var $incoming_cookies = array();
+ var $outgoing_payload = '';
+ var $incoming_payload = '';
+ var $response_status_line; // HTTP response status line
+ var $useSOAPAction = true;
+ var $persistentConnection = false;
+ var $ch = false; // cURL handle
+ var $ch_options = array(); // cURL custom options
+ var $use_curl = false; // force cURL use
+ var $proxy = null; // proxy information (associative array)
+ var $username = '';
+ var $password = '';
+ var $authtype = '';
+ var $digestRequest = array();
+ var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional)
+ // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem'
+ // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem'
+ // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem'
+ // passphrase: SSL key password/passphrase
+ // certpassword: SSL certificate password
+ // verifypeer: default is 1
+ // verifyhost: default is 1
+
+ /**
+ * constructor
+ *
+ * @param string $url The URL to which to connect
+ * @param array $curl_options User-specified cURL options
+ * @param boolean $use_curl Whether to try to force cURL use
+ * @access public
+ */
+ function soap_transport_http($url, $curl_options = NULL, $use_curl = false){
+ parent::nusoap_base();
+ $this->debug("ctor url=$url use_curl=$use_curl curl_options:");
+ $this->appendDebug($this->varDump($curl_options));
+ $this->setURL($url);
+ if (is_array($curl_options)) {
+ $this->ch_options = $curl_options;
+ }
+ $this->use_curl = $use_curl;
+ preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
+ $this->setHeader('User-Agent', $this->title.'/'.$this->version.' ('.$rev[1].')');
+ }
+
+ /**
+ * sets a cURL option
+ *
+ * @param mixed $option The cURL option (always integer?)
+ * @param mixed $value The cURL option value
+ * @access private
+ */
+ function setCurlOption($option, $value) {
+ $this->debug("setCurlOption option=$option, value=");
+ $this->appendDebug($this->varDump($value));
+ curl_setopt($this->ch, $option, $value);
+ }
+
+ /**
+ * sets an HTTP header
+ *
+ * @param string $name The name of the header
+ * @param string $value The value of the header
+ * @access private
+ */
+ function setHeader($name, $value) {
+ $this->outgoing_headers[$name] = $value;
+ $this->debug("set header $name: $value");
+ }
+
+ /**
+ * unsets an HTTP header
+ *
+ * @param string $name The name of the header
+ * @access private
+ */
+ function unsetHeader($name) {
+ if (isset($this->outgoing_headers[$name])) {
+ $this->debug("unset header $name");
+ unset($this->outgoing_headers[$name]);
+ }
+ }
+
+ /**
+ * sets the URL to which to connect
+ *
+ * @param string $url The URL to which to connect
+ * @access private
+ */
+ function setURL($url) {
+ $this->url = $url;
+
+ $u = parse_url($url);
+ foreach($u as $k => $v){
+ $this->debug("parsed URL $k = $v");
+ $this->$k = $v;
+ }
+
+ // add any GET params to path
+ if(isset($u['query']) && $u['query'] != ''){
+ $this->path .= '?' . $u['query'];
+ }
+
+ // set default port
+ if(!isset($u['port'])){
+ if($u['scheme'] == 'https'){
+ $this->port = 443;
+ } else {
+ $this->port = 80;
+ }
+ }
+
+ $this->uri = $this->path;
+ $this->digest_uri = $this->uri;
+
+ // build headers
+ if (!isset($u['port'])) {
+ $this->setHeader('Host', $this->host);
+ } else {
+ $this->setHeader('Host', $this->host.':'.$this->port);
+ }
+
+ if (isset($u['user']) && $u['user'] != '') {
+ $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : '');
+ }
+ }
+
+ /**
+ * gets the I/O method to use
+ *
+ * @return string I/O method to use (socket|curl|unknown)
+ * @access private
+ */
+ function io_method() {
+ if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm'))
+ return 'curl';
+ if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm'))
+ return 'socket';
+ return 'unknown';
+ }
+
+ /**
+ * establish an HTTP connection
+ *
+ * @param integer $timeout set connection timeout in seconds
+ * @param integer $response_timeout set response timeout in seconds
+ * @return boolean true if connected, false if not
+ * @access private
+ */
+ function connect($connection_timeout=0,$response_timeout=30){
+ // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like
+ // "regular" socket.
+ // TODO: disabled for now because OpenSSL must be *compiled* in (not just
+ // loaded), and until PHP5 stream_get_wrappers is not available.
+// if ($this->scheme == 'https') {
+// if (version_compare(phpversion(), '4.3.0') >= 0) {
+// if (extension_loaded('openssl')) {
+// $this->scheme = 'ssl';
+// $this->debug('Using SSL over OpenSSL');
+// }
+// }
+// }
+ $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port");
+ if ($this->io_method() == 'socket') {
+ if (!is_array($this->proxy)) {
+ $host = $this->host;
+ $port = $this->port;
+ } else {
+ $host = $this->proxy['host'];
+ $port = $this->proxy['port'];
+ }
+
+ // use persistent connection
+ if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){
+ if (!feof($this->fp)) {
+ $this->debug('Re-use persistent connection');
+ return true;
+ }
+ fclose($this->fp);
+ $this->debug('Closed persistent connection at EOF');
+ }
+
+ // munge host if using OpenSSL
+ if ($this->scheme == 'ssl') {
+ $host = 'ssl://' . $host;
+ }
+ $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout);
+
+ // open socket
+ if($connection_timeout > 0){
+ $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout);
+ } else {
+ $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str);
+ }
+
+ // test pointer
+ if(!$this->fp) {
+ $msg = 'Couldn\'t open socket connection to server ' . $this->url;
+ if ($this->errno) {
+ $msg .= ', Error ('.$this->errno.'): '.$this->error_str;
+ } else {
+ $msg .= ' prior to connect(). This is often a problem looking up the host name.';
+ }
+ $this->debug($msg);
+ $this->setError($msg);
+ return false;
+ }
+
+ // set response timeout
+ $this->debug('set response timeout to ' . $response_timeout);
+ socket_set_timeout( $this->fp, $response_timeout);
+
+ $this->debug('socket connected');
+ return true;
+ } else if ($this->io_method() == 'curl') {
+ if (!extension_loaded('curl')) {
+// $this->setError('cURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS');
+ $this->setError('The PHP cURL Extension is required for HTTPS or NLTM. You will need to re-build or update your PHP to include cURL or change php.ini to load the PHP cURL extension.');
+ return false;
+ }
+ // Avoid warnings when PHP does not have these options
+ if (defined('CURLOPT_CONNECTIONTIMEOUT'))
+ $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT;
+ else
+ $CURLOPT_CONNECTIONTIMEOUT = 78;
+ if (defined('CURLOPT_HTTPAUTH'))
+ $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH;
+ else
+ $CURLOPT_HTTPAUTH = 107;
+ if (defined('CURLOPT_PROXYAUTH'))
+ $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH;
+ else
+ $CURLOPT_PROXYAUTH = 111;
+ if (defined('CURLAUTH_BASIC'))
+ $CURLAUTH_BASIC = CURLAUTH_BASIC;
+ else
+ $CURLAUTH_BASIC = 1;
+ if (defined('CURLAUTH_DIGEST'))
+ $CURLAUTH_DIGEST = CURLAUTH_DIGEST;
+ else
+ $CURLAUTH_DIGEST = 2;
+ if (defined('CURLAUTH_NTLM'))
+ $CURLAUTH_NTLM = CURLAUTH_NTLM;
+ else
+ $CURLAUTH_NTLM = 8;
+
+ $this->debug('connect using cURL');
+ // init CURL
+ $this->ch = curl_init();
+ // set url
+ $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host";
+ // add path
+ $hostURL .= $this->path;
+ $this->setCurlOption(CURLOPT_URL, $hostURL);
+ // follow location headers (re-directs)
+ if (ini_get('safe_mode') || ini_get('open_basedir')) {
+ $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION');
+ $this->debug('safe_mode = ');
+ $this->appendDebug($this->varDump(ini_get('safe_mode')));
+ $this->debug('open_basedir = ');
+ $this->appendDebug($this->varDump(ini_get('open_basedir')));
+ } else {
+ $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1);
+ }
+ // ask for headers in the response output
+ $this->setCurlOption(CURLOPT_HEADER, 1);
+ // ask for the response output as the return value
+ $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1);
+ // encode
+ // We manage this ourselves through headers and encoding
+// if(function_exists('gzuncompress')){
+// $this->setCurlOption(CURLOPT_ENCODING, 'deflate');
+// }
+ // persistent connection
+ if ($this->persistentConnection) {
+ // I believe the following comment is now bogus, having applied to
+ // the code when it used CURLOPT_CUSTOMREQUEST to send the request.
+ // The way we send data, we cannot use persistent connections, since
+ // there will be some "junk" at the end of our request.
+ //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true);
+ $this->persistentConnection = false;
+ $this->setHeader('Connection', 'close');
+ }
+ // set timeouts
+ if ($connection_timeout != 0) {
+ $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout);
+ }
+ if ($response_timeout != 0) {
+ $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout);
+ }
+
+ if ($this->scheme == 'https') {
+ $this->debug('set cURL SSL verify options');
+ // recent versions of cURL turn on peer/host checking by default,
+ // while PHP binaries are not compiled with a default location for the
+ // CA cert bundle, so disable peer/host checking.
+ //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt');
+ $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
+ $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
+
+ // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo)
+ if ($this->authtype == 'certificate') {
+ $this->debug('set cURL certificate options');
+ if (isset($this->certRequest['cainfofile'])) {
+ $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']);
+ }
+ if (isset($this->certRequest['verifypeer'])) {
+ $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']);
+ } else {
+ $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1);
+ }
+ if (isset($this->certRequest['verifyhost'])) {
+ $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']);
+ } else {
+ $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1);
+ }
+ if (isset($this->certRequest['sslcertfile'])) {
+ $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']);
+ }
+ if (isset($this->certRequest['sslkeyfile'])) {
+ $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']);
+ }
+ if (isset($this->certRequest['passphrase'])) {
+ $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']);
+ }
+ if (isset($this->certRequest['certpassword'])) {
+ $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']);
+ }
+ }
+ }
+ if ($this->authtype && ($this->authtype != 'certificate')) {
+ if ($this->username) {
+ $this->debug('set cURL username/password');
+ $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password");
+ }
+ if ($this->authtype == 'basic') {
+ $this->debug('set cURL for Basic authentication');
+ $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC);
+ }
+ if ($this->authtype == 'digest') {
+ $this->debug('set cURL for digest authentication');
+ $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST);
+ }
+ if ($this->authtype == 'ntlm') {
+ $this->debug('set cURL for NTLM authentication');
+ $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM);
+ }
+ }
+ if (is_array($this->proxy)) {
+ $this->debug('set cURL proxy options');
+ if ($this->proxy['port'] != '') {
+ $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'].':'.$this->proxy['port']);
+ } else {
+ $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']);
+ }
+ if ($this->proxy['username'] || $this->proxy['password']) {
+ $this->debug('set cURL proxy authentication options');
+ $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'].':'.$this->proxy['password']);
+ if ($this->proxy['authtype'] == 'basic') {
+ $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC);
+ }
+ if ($this->proxy['authtype'] == 'ntlm') {
+ $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM);
+ }
+ }
+ }
+ $this->debug('cURL connection set up');
+ return true;
+ } else {
+ $this->setError('Unknown scheme ' . $this->scheme);
+ $this->debug('Unknown scheme ' . $this->scheme);
+ return false;
+ }
+ }
+
+ /**
+ * sends the SOAP request and gets the SOAP response via HTTP[S]
+ *
+ * @param string $data message data
+ * @param integer $timeout set connection timeout in seconds
+ * @param integer $response_timeout set response timeout in seconds
+ * @param array $cookies cookies to send
+ * @return string data
+ * @access public
+ */
+ function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) {
+
+ $this->debug('entered send() with data of length: '.strlen($data));
+
+ $this->tryagain = true;
+ $tries = 0;
+ while ($this->tryagain) {
+ $this->tryagain = false;
+ if ($tries++ < 2) {
+ // make connnection
+ if (!$this->connect($timeout, $response_timeout)){
+ return false;
+ }
+
+ // send request
+ if (!$this->sendRequest($data, $cookies)){
+ return false;
+ }
+
+ // get response
+ $respdata = $this->getResponse();
+ } else {
+ $this->setError("Too many tries to get an OK response ($this->response_status_line)");
+ }
+ }
+ $this->debug('end of send()');
+ return $respdata;
+ }
+
+
+ /**
+ * sends the SOAP request and gets the SOAP response via HTTPS using CURL
+ *
+ * @param string $data message data
+ * @param integer $timeout set connection timeout in seconds
+ * @param integer $response_timeout set response timeout in seconds
+ * @param array $cookies cookies to send
+ * @return string data
+ * @access public
+ * @deprecated
+ */
+ function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
+ return $this->send($data, $timeout, $response_timeout, $cookies);
+ }
+
+ /**
+ * if authenticating, set user credentials here
+ *
+ * @param string $username
+ * @param string $password
+ * @param string $authtype (basic|digest|certificate|ntlm)
+ * @param array $digestRequest (keys must be nonce, nc, realm, qop)
+ * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
+ * @access public
+ */
+ function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) {
+ $this->debug("setCredentials username=$username authtype=$authtype digestRequest=");
+ $this->appendDebug($this->varDump($digestRequest));
+ $this->debug("certRequest=");
+ $this->appendDebug($this->varDump($certRequest));
+ // cf. RFC 2617
+ if ($authtype == 'basic') {
+ $this->setHeader('Authorization', 'Basic '.base64_encode(str_replace(':','',$username).':'.$password));
+ } elseif ($authtype == 'digest') {
+ if (isset($digestRequest['nonce'])) {
+ $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1;
+
+ // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html)
+
+ // A1 = unq(username-value) ":" unq(realm-value) ":" passwd
+ $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password;
+
+ // H(A1) = MD5(A1)
+ $HA1 = md5($A1);
+
+ // A2 = Method ":" digest-uri-value
+ $A2 = $this->request_method . ':' . $this->digest_uri;
+
+ // H(A2)
+ $HA2 = md5($A2);
+
+ // KD(secret, data) = H(concat(secret, ":", data))
+ // if qop == auth:
+ // request-digest = <"> < KD ( H(A1), unq(nonce-value)
+ // ":" nc-value
+ // ":" unq(cnonce-value)
+ // ":" unq(qop-value)
+ // ":" H(A2)
+ // ) <">
+ // if qop is missing,
+ // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
+
+ $unhashedDigest = '';
+ $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : '';
+ $cnonce = $nonce;
+ if ($digestRequest['qop'] != '') {
+ $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2;
+ } else {
+ $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2;
+ }
+
+ $hashedDigest = md5($unhashedDigest);
+
+ $opaque = '';
+ if (isset($digestRequest['opaque'])) {
+ $opaque = ', opaque="' . $digestRequest['opaque'] . '"';
+ }
+
+ $this->setHeader('Authorization', 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . $opaque . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"');
+ }
+ } elseif ($authtype == 'certificate') {
+ $this->certRequest = $certRequest;
+ $this->debug('Authorization header not set for certificate');
+ } elseif ($authtype == 'ntlm') {
+ // do nothing
+ $this->debug('Authorization header not set for ntlm');
+ }
+ $this->username = $username;
+ $this->password = $password;
+ $this->authtype = $authtype;
+ $this->digestRequest = $digestRequest;
+ }
+
+ /**
+ * set the soapaction value
+ *
+ * @param string $soapaction
+ * @access public
+ */
+ function setSOAPAction($soapaction) {
+ $this->setHeader('SOAPAction', '"' . $soapaction . '"');
+ }
+
+ /**
+ * use http encoding
+ *
+ * @param string $enc encoding style. supported values: gzip, deflate, or both
+ * @access public
+ */
+ function setEncoding($enc='gzip, deflate') {
+ if (function_exists('gzdeflate')) {
+ $this->protocol_version = '1.1';
+ $this->setHeader('Accept-Encoding', $enc);
+ if (!isset($this->outgoing_headers['Connection'])) {
+ $this->setHeader('Connection', 'close');
+ $this->persistentConnection = false;
+ }
+ // deprecated as of PHP 5.3.0
+ //set_magic_quotes_runtime(0);
+ $this->encoding = $enc;
+ }
+ }
+
+ /**
+ * set proxy info here
+ *
+ * @param string $proxyhost use an empty string to remove proxy
+ * @param string $proxyport
+ * @param string $proxyusername
+ * @param string $proxypassword
+ * @param string $proxyauthtype (basic|ntlm)
+ * @access public
+ */
+ function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') {
+ if ($proxyhost) {
+ $this->proxy = array(
+ 'host' => $proxyhost,
+ 'port' => $proxyport,
+ 'username' => $proxyusername,
+ 'password' => $proxypassword,
+ 'authtype' => $proxyauthtype
+ );
+ if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') {
+ $this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword));
+ }
+ } else {
+ $this->debug('remove proxy');
+ $proxy = null;
+ unsetHeader('Proxy-Authorization');
+ }
+ }
+
+
+ /**
+ * Test if the given string starts with a header that is to be skipped.
+ * Skippable headers result from chunked transfer and proxy requests.
+ *
+ * @param string $data The string to check.
+ * @returns boolean Whether a skippable header was found.
+ * @access private
+ */
+ function isSkippableCurlHeader(&$data) {
+ $skipHeaders = array( 'HTTP/1.1 100',
+ 'HTTP/1.0 301',
+ 'HTTP/1.1 301',
+ 'HTTP/1.0 302',
+ 'HTTP/1.1 302',
+ 'HTTP/1.0 401',
+ 'HTTP/1.1 401',
+ 'HTTP/1.0 200 Connection established');
+ foreach ($skipHeaders as $hd) {
+ $prefix = substr($data, 0, strlen($hd));
+ if ($prefix == $hd) return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * decode a string that is encoded w/ "chunked' transfer encoding
+ * as defined in RFC2068 19.4.6
+ *
+ * @param string $buffer
+ * @param string $lb
+ * @returns string
+ * @access public
+ * @deprecated
+ */
+ function decodeChunked($buffer, $lb){
+ // length := 0
+ $length = 0;
+ $new = '';
+
+ // read chunk-size, chunk-extension (if any) and CRLF
+ // get the position of the linebreak
+ $chunkend = strpos($buffer, $lb);
+ if ($chunkend == FALSE) {
+ $this->debug('no linebreak found in decodeChunked');
+ return $new;
+ }
+ $temp = substr($buffer,0,$chunkend);
+ $chunk_size = hexdec( trim($temp) );
+ $chunkstart = $chunkend + strlen($lb);
+ // while (chunk-size > 0) {
+ while ($chunk_size > 0) {
+ $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size");
+ $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size);
+
+ // Just in case we got a broken connection
+ if ($chunkend == FALSE) {
+ $chunk = substr($buffer,$chunkstart);
+ // append chunk-data to entity-body
+ $new .= $chunk;
+ $length += strlen($chunk);
+ break;
+ }
+
+ // read chunk-data and CRLF
+ $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
+ // append chunk-data to entity-body
+ $new .= $chunk;
+ // length := length + chunk-size
+ $length += strlen($chunk);
+ // read chunk-size and CRLF
+ $chunkstart = $chunkend + strlen($lb);
+
+ $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb);
+ if ($chunkend == FALSE) {
+ break; //Just in case we got a broken connection
+ }
+ $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
+ $chunk_size = hexdec( trim($temp) );
+ $chunkstart = $chunkend;
+ }
+ return $new;
+ }
+
+ /**
+ * Writes the payload, including HTTP headers, to $this->outgoing_payload.
+ *
+ * @param string $data HTTP body
+ * @param string $cookie_str data for HTTP Cookie header
+ * @return void
+ * @access private
+ */
+ function buildPayload($data, $cookie_str = '') {
+ // Note: for cURL connections, $this->outgoing_payload is ignored,
+ // as is the Content-Length header, but these are still created as
+ // debugging guides.
+
+ // add content-length header
+ if ($this->request_method != 'GET') {
+ $this->setHeader('Content-Length', strlen($data));
+ }
+
+ // start building outgoing payload:
+ if ($this->proxy) {
+ $uri = $this->url;
+ } else {
+ $uri = $this->uri;
+ }
+ $req = "$this->request_method $uri HTTP/$this->protocol_version";
+ $this->debug("HTTP request: $req");
+ $this->outgoing_payload = "$req\r\n";
+
+ // loop thru headers, serializing
+ foreach($this->outgoing_headers as $k => $v){
+ $hdr = $k.': '.$v;
+ $this->debug("HTTP header: $hdr");
+ $this->outgoing_payload .= "$hdr\r\n";
+ }
+
+ // add any cookies
+ if ($cookie_str != '') {
+ $hdr = 'Cookie: '.$cookie_str;
+ $this->debug("HTTP header: $hdr");
+ $this->outgoing_payload .= "$hdr\r\n";
+ }
+
+ // header/body separator
+ $this->outgoing_payload .= "\r\n";
+
+ // add data
+ $this->outgoing_payload .= $data;
+ }
+
+ /**
+ * sends the SOAP request via HTTP[S]
+ *
+ * @param string $data message data
+ * @param array $cookies cookies to send
+ * @return boolean true if OK, false if problem
+ * @access private
+ */
+ function sendRequest($data, $cookies = NULL) {
+ // build cookie string
+ $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https')));
+
+ // build payload
+ $this->buildPayload($data, $cookie_str);
+
+ if ($this->io_method() == 'socket') {
+ // send payload
+ if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
+ $this->setError('couldn\'t write message data to socket');
+ $this->debug('couldn\'t write message data to socket');
+ return false;
+ }
+ $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload));
+ return true;
+ } else if ($this->io_method() == 'curl') {
+ // set payload
+ // cURL does say this should only be the verb, and in fact it
+ // turns out that the URI and HTTP version are appended to this, which
+ // some servers refuse to work with (so we no longer use this method!)
+ //$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $this->outgoing_payload);
+ $curl_headers = array();
+ foreach($this->outgoing_headers as $k => $v){
+ if ($k == 'Connection' || $k == 'Content-Length' || $k == 'Host' || $k == 'Authorization' || $k == 'Proxy-Authorization') {
+ $this->debug("Skip cURL header $k: $v");
+ } else {
+ $curl_headers[] = "$k: $v";
+ }
+ }
+ if ($cookie_str != '') {
+ $curl_headers[] = 'Cookie: ' . $cookie_str;
+ }
+ $this->setCurlOption(CURLOPT_HTTPHEADER, $curl_headers);
+ $this->debug('set cURL HTTP headers');
+ if ($this->request_method == "POST") {
+ $this->setCurlOption(CURLOPT_POST, 1);
+ $this->setCurlOption(CURLOPT_POSTFIELDS, $data);
+ $this->debug('set cURL POST data');
+ } else {
+ }
+ // insert custom user-set cURL options
+ foreach ($this->ch_options as $key => $val) {
+ $this->setCurlOption($key, $val);
+ }
+
+ $this->debug('set cURL payload');
+ return true;
+ }
+ }
+
+ /**
+ * gets the SOAP response via HTTP[S]
+ *
+ * @return string the response (also sets member variables like incoming_payload)
+ * @access private
+ */
+ function getResponse(){
+ $this->incoming_payload = '';
+
+ if ($this->io_method() == 'socket') {
+ // loop until headers have been retrieved
+ $data = '';
+ while (!isset($lb)){
+
+ // We might EOF during header read.
+ if(feof($this->fp)) {
+ $this->incoming_payload = $data;
+ $this->debug('found no headers before EOF after length ' . strlen($data));
+ $this->debug("received before EOF:\n" . $data);
+ $this->setError('server failed to send headers');
+ return false;
+ }
+
+ $tmp = fgets($this->fp, 256);
+ $tmplen = strlen($tmp);
+ $this->debug("read line of $tmplen bytes: " . trim($tmp));
+
+ if ($tmplen == 0) {
+ $this->incoming_payload = $data;
+ $this->debug('socket read of headers timed out after length ' . strlen($data));
+ $this->debug("read before timeout: " . $data);
+ $this->setError('socket read of headers timed out');
+ return false;
+ }
+
+ $data .= $tmp;
+ $pos = strpos($data,"\r\n\r\n");
+ if($pos > 1){
+ $lb = "\r\n";
+ } else {
+ $pos = strpos($data,"\n\n");
+ if($pos > 1){
+ $lb = "\n";
+ }
+ }
+ // remove 100 headers
+ if (isset($lb) && preg_match('/^HTTP\/1.1 100/',$data)) {
+ unset($lb);
+ $data = '';
+ }//
+ }
+ // store header data
+ $this->incoming_payload .= $data;
+ $this->debug('found end of headers after length ' . strlen($data));
+ // process headers
+ $header_data = trim(substr($data,0,$pos));
+ $header_array = explode($lb,$header_data);
+ $this->incoming_headers = array();
+ $this->incoming_cookies = array();
+ foreach($header_array as $header_line){
+ $arr = explode(':',$header_line, 2);
+ if(count($arr) > 1){
+ $header_name = strtolower(trim($arr[0]));
+ $this->incoming_headers[$header_name] = trim($arr[1]);
+ if ($header_name == 'set-cookie') {
+ // TODO: allow multiple cookies from parseCookie
+ $cookie = $this->parseCookie(trim($arr[1]));
+ if ($cookie) {
+ $this->incoming_cookies[] = $cookie;
+ $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
+ } else {
+ $this->debug('did not find cookie in ' . trim($arr[1]));
+ }
+ }
+ } else if (isset($header_name)) {
+ // append continuation line to previous header
+ $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
+ }
+ }
+
+ // loop until msg has been received
+ if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') {
+ $content_length = 2147483647; // ignore any content-length header
+ $chunked = true;
+ $this->debug("want to read chunked content");
+ } elseif (isset($this->incoming_headers['content-length'])) {
+ $content_length = $this->incoming_headers['content-length'];
+ $chunked = false;
+ $this->debug("want to read content of length $content_length");
+ } else {
+ $content_length = 2147483647;
+ $chunked = false;
+ $this->debug("want to read content to EOF");
+ }
+ $data = '';
+ do {
+ if ($chunked) {
+ $tmp = fgets($this->fp, 256);
+ $tmplen = strlen($tmp);
+ $this->debug("read chunk line of $tmplen bytes");
+ if ($tmplen == 0) {
+ $this->incoming_payload = $data;
+ $this->debug('socket read of chunk length timed out after length ' . strlen($data));
+ $this->debug("read before timeout:\n" . $data);
+ $this->setError('socket read of chunk length timed out');
+ return false;
+ }
+ $content_length = hexdec(trim($tmp));
+ $this->debug("chunk length $content_length");
+ }
+ $strlen = 0;
+ while (($strlen < $content_length) && (!feof($this->fp))) {
+ $readlen = min(8192, $content_length - $strlen);
+ $tmp = fread($this->fp, $readlen);
+ $tmplen = strlen($tmp);
+ $this->debug("read buffer of $tmplen bytes");
+ if (($tmplen == 0) && (!feof($this->fp))) {
+ $this->incoming_payload = $data;
+ $this->debug('socket read of body timed out after length ' . strlen($data));
+ $this->debug("read before timeout:\n" . $data);
+ $this->setError('socket read of body timed out');
+ return false;
+ }
+ $strlen += $tmplen;
+ $data .= $tmp;
+ }
+ if ($chunked && ($content_length > 0)) {
+ $tmp = fgets($this->fp, 256);
+ $tmplen = strlen($tmp);
+ $this->debug("read chunk terminator of $tmplen bytes");
+ if ($tmplen == 0) {
+ $this->incoming_payload = $data;
+ $this->debug('socket read of chunk terminator timed out after length ' . strlen($data));
+ $this->debug("read before timeout:\n" . $data);
+ $this->setError('socket read of chunk terminator timed out');
+ return false;
+ }
+ }
+ } while ($chunked && ($content_length > 0) && (!feof($this->fp)));
+ if (feof($this->fp)) {
+ $this->debug('read to EOF');
+ }
+ $this->debug('read body of length ' . strlen($data));
+ $this->incoming_payload .= $data;
+ $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server');
+
+ // close filepointer
+ if(
+ (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') ||
+ (! $this->persistentConnection) || feof($this->fp)){
+ fclose($this->fp);
+ $this->fp = false;
+ $this->debug('closed socket');
+ }
+
+ // connection was closed unexpectedly
+ if($this->incoming_payload == ''){
+ $this->setError('no response from server');
+ return false;
+ }
+
+ // decode transfer-encoding
+// if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){
+// if(!$data = $this->decodeChunked($data, $lb)){
+// $this->setError('Decoding of chunked data failed');
+// return false;
+// }
+ //print "<pre>\nde-chunked:\n---------------\n$data\n\n---------------\n</pre>";
+ // set decoded payload
+// $this->incoming_payload = $header_data.$lb.$lb.$data;
+// }
+
+ } else if ($this->io_method() == 'curl') {
+ // send and receive
+ $this->debug('send and receive with cURL');
+ $this->incoming_payload = curl_exec($this->ch);
+ $data = $this->incoming_payload;
+
+ $cErr = curl_error($this->ch);
+ if ($cErr != '') {
+ $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'<br>';
+ // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
+ foreach(curl_getinfo($this->ch) as $k => $v){
+ $err .= "$k: $v<br>";
+ }
+ $this->debug($err);
+ $this->setError($err);
+ curl_close($this->ch);
+ return false;
+ } else {
+ //echo '<pre>';
+ //var_dump(curl_getinfo($this->ch));
+ //echo '</pre>';
+ }
+ // close curl
+ $this->debug('No cURL error, closing cURL');
+ curl_close($this->ch);
+
+ // try removing skippable headers
+ $savedata = $data;
+ while ($this->isSkippableCurlHeader($data)) {
+ $this->debug("Found HTTP header to skip");
+ if ($pos = strpos($data,"\r\n\r\n")) {
+ $data = ltrim(substr($data,$pos));
+ } elseif($pos = strpos($data,"\n\n") ) {
+ $data = ltrim(substr($data,$pos));
+ }
+ }
+
+ if ($data == '') {
+ // have nothing left; just remove 100 header(s)
+ $data = $savedata;
+ while (preg_match('/^HTTP\/1.1 100/',$data)) {
+ if ($pos = strpos($data,"\r\n\r\n")) {
+ $data = ltrim(substr($data,$pos));
+ } elseif($pos = strpos($data,"\n\n") ) {
+ $data = ltrim(substr($data,$pos));
+ }
+ }
+ }
+
+ // separate content from HTTP headers
+ if ($pos = strpos($data,"\r\n\r\n")) {
+ $lb = "\r\n";
+ } elseif( $pos = strpos($data,"\n\n")) {
+ $lb = "\n";
+ } else {
+ $this->debug('no proper separation of headers and document');
+ $this->setError('no proper separation of headers and document');
+ return false;
+ }
+ $header_data = trim(substr($data,0,$pos));
+ $header_array = explode($lb,$header_data);
+ $data = ltrim(substr($data,$pos));
+ $this->debug('found proper separation of headers and document');
+ $this->debug('cleaned data, stringlen: '.strlen($data));
+ // clean headers
+ foreach ($header_array as $header_line) {
+ $arr = explode(':',$header_line,2);
+ if(count($arr) > 1){
+ $header_name = strtolower(trim($arr[0]));
+ $this->incoming_headers[$header_name] = trim($arr[1]);
+ if ($header_name == 'set-cookie') {
+ // TODO: allow multiple cookies from parseCookie
+ $cookie = $this->parseCookie(trim($arr[1]));
+ if ($cookie) {
+ $this->incoming_cookies[] = $cookie;
+ $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
+ } else {
+ $this->debug('did not find cookie in ' . trim($arr[1]));
+ }
+ }
+ } else if (isset($header_name)) {
+ // append continuation line to previous header
+ $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
+ }
+ }
+ }
+
+ $this->response_status_line = $header_array[0];
+ $arr = explode(' ', $this->response_status_line, 3);
+ $http_version = $arr[0];
+ $http_status = intval($arr[1]);
+ $http_reason = count($arr) > 2 ? $arr[2] : '';
+
+ // see if we need to resend the request with http digest authentication
+ if (isset($this->incoming_headers['location']) && ($http_status == 301 || $http_status == 302)) {
+ $this->debug("Got $http_status $http_reason with Location: " . $this->incoming_headers['location']);
+ $this->setURL($this->incoming_headers['location']);
+ $this->tryagain = true;
+ return false;
+ }
+
+ // see if we need to resend the request with http digest authentication
+ if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) {
+ $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']);
+ if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) {
+ $this->debug('Server wants digest authentication');
+ // remove "Digest " from our elements
+ $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']);
+
+ // parse elements into array
+ $digestElements = explode(',', $digestString);
+ foreach ($digestElements as $val) {
+ $tempElement = explode('=', trim($val), 2);
+ $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]);
+ }
+
+ // should have (at least) qop, realm, nonce
+ if (isset($digestRequest['nonce'])) {
+ $this->setCredentials($this->username, $this->password, 'digest', $digestRequest);
+ $this->tryagain = true;
+ return false;
+ }
+ }
+ $this->debug('HTTP authentication failed');
+ $this->setError('HTTP authentication failed');
+ return false;
+ }
+
+ if (
+ ($http_status >= 300 && $http_status <= 307) ||
+ ($http_status >= 400 && $http_status <= 417) ||
+ ($http_status >= 501 && $http_status <= 505)
+ ) {
+ $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)");
+ return false;
+ }
+
+ // decode content-encoding
+ if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){
+ if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){
+ // if decoding works, use it. else assume data wasn't gzencoded
+ if(function_exists('gzinflate')){
+ //$timer->setMarker('starting decoding of gzip/deflated content');
+ // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress)
+ // this means there are no Zlib headers, although there should be
+ $this->debug('The gzinflate function exists');
+ $datalen = strlen($data);
+ if ($this->incoming_headers['content-encoding'] == 'deflate') {
+ if ($degzdata = @gzinflate($data)) {
+ $data = $degzdata;
+ $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes');
+ if (strlen($data) < $datalen) {
+ // test for the case that the payload has been compressed twice
+ $this->debug('The inflated payload is smaller than the gzipped one; try again');
+ if ($degzdata = @gzinflate($data)) {
+ $data = $degzdata;
+ $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes');
+ }
+ }
+ } else {
+ $this->debug('Error using gzinflate to inflate the payload');
+ $this->setError('Error using gzinflate to inflate the payload');
+ }
+ } elseif ($this->incoming_headers['content-encoding'] == 'gzip') {
+ if ($degzdata = @gzinflate(substr($data, 10))) { // do our best
+ $data = $degzdata;
+ $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes');
+ if (strlen($data) < $datalen) {
+ // test for the case that the payload has been compressed twice
+ $this->debug('The un-gzipped payload is smaller than the gzipped one; try again');
+ if ($degzdata = @gzinflate(substr($data, 10))) {
+ $data = $degzdata;
+ $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes');
+ }
+ }
+ } else {
+ $this->debug('Error using gzinflate to un-gzip the payload');
+ $this->setError('Error using gzinflate to un-gzip the payload');
+ }
+ }
+ //$timer->setMarker('finished decoding of gzip/deflated content');
+ //print "<xmp>\nde-inflated:\n---------------\n$data\n-------------\n</xmp>";
+ // set decoded payload
+ $this->incoming_payload = $header_data.$lb.$lb.$data;
+ } else {
+ $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
+ $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
+ }
+ } else {
+ $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
+ $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
+ }
+ } else {
+ $this->debug('No Content-Encoding header');
+ }
+
+ if(strlen($data) == 0){
+ $this->debug('no data after headers!');
+ $this->setError('no data present after HTTP headers');
+ return false;
+ }
+
+ return $data;
+ }
+
+ /**
+ * sets the content-type for the SOAP message to be sent
+ *
+ * @param string $type the content type, MIME style
+ * @param mixed $charset character set used for encoding (or false)
+ * @access public
+ */
+ function setContentType($type, $charset = false) {
+ $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : ''));
+ }
+
+ /**
+ * specifies that an HTTP persistent connection should be used
+ *
+ * @return boolean whether the request was honored by this method.
+ * @access public
+ */
+ function usePersistentConnection(){
+ if (isset($this->outgoing_headers['Accept-Encoding'])) {
+ return false;
+ }
+ $this->protocol_version = '1.1';
+ $this->persistentConnection = true;
+ $this->setHeader('Connection', 'Keep-Alive');
+ return true;
+ }
+
+ /**
+ * parse an incoming Cookie into it's parts
+ *
+ * @param string $cookie_str content of cookie
+ * @return array with data of that cookie
+ * @access private
+ */
+ /*
+ * TODO: allow a Set-Cookie string to be parsed into multiple cookies
+ */
+ function parseCookie($cookie_str) {
+ $cookie_str = str_replace('; ', ';', $cookie_str) . ';';
+ $data = preg_split('/;/', $cookie_str);
+ $value_str = $data[0];
+
+ $cookie_param = 'domain=';
+ $start = strpos($cookie_str, $cookie_param);
+ if ($start > 0) {
+ $domain = substr($cookie_str, $start + strlen($cookie_param));
+ $domain = substr($domain, 0, strpos($domain, ';'));
+ } else {
+ $domain = '';
+ }
+
+ $cookie_param = 'expires=';
+ $start = strpos($cookie_str, $cookie_param);
+ if ($start > 0) {
+ $expires = substr($cookie_str, $start + strlen($cookie_param));
+ $expires = substr($expires, 0, strpos($expires, ';'));
+ } else {
+ $expires = '';
+ }
+
+ $cookie_param = 'path=';
+ $start = strpos($cookie_str, $cookie_param);
+ if ( $start > 0 ) {
+ $path = substr($cookie_str, $start + strlen($cookie_param));
+ $path = substr($path, 0, strpos($path, ';'));
+ } else {
+ $path = '/';
+ }
+
+ $cookie_param = ';secure;';
+ if (strpos($cookie_str, $cookie_param) !== FALSE) {
+ $secure = true;
+ } else {
+ $secure = false;
+ }
+
+ $sep_pos = strpos($value_str, '=');
+
+ if ($sep_pos) {
+ $name = substr($value_str, 0, $sep_pos);
+ $value = substr($value_str, $sep_pos + 1);
+ $cookie= array( 'name' => $name,
+ 'value' => $value,
+ 'domain' => $domain,
+ 'path' => $path,
+ 'expires' => $expires,
+ 'secure' => $secure
+ );
+ return $cookie;
+ }
+ return false;
+ }
+
+ /**
+ * sort out cookies for the current request
+ *
+ * @param array $cookies array with all cookies
+ * @param boolean $secure is the send-content secure or not?
+ * @return string for Cookie-HTTP-Header
+ * @access private
+ */
+ function getCookiesForRequest($cookies, $secure=false) {
+ $cookie_str = '';
+ if ((! is_null($cookies)) && (is_array($cookies))) {
+ foreach ($cookies as $cookie) {
+ if (! is_array($cookie)) {
+ continue;
+ }
+ $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']);
+ if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
+ if (strtotime($cookie['expires']) <= time()) {
+ $this->debug('cookie has expired');
+ continue;
+ }
+ }
+ if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) {
+ $domain = preg_quote($cookie['domain']);
+ if (! preg_match("'.*$domain$'i", $this->host)) {
+ $this->debug('cookie has different domain');
+ continue;
+ }
+ }
+ if ((isset($cookie['path'])) && (! empty($cookie['path']))) {
+ $path = preg_quote($cookie['path']);
+ if (! preg_match("'^$path.*'i", $this->path)) {
+ $this->debug('cookie is for a different path');
+ continue;
+ }
+ }
+ if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) {
+ $this->debug('cookie is secure, transport is not');
+ continue;
+ }
+ $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; ';
+ $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']);
+ }
+ }
+ return $cookie_str;
+ }
+}
+
+
+?>
\ No newline at end of file
--- /dev/null
+<?php
+
+
+
+
+/**
+* For creating serializable abstractions of native PHP types. This class
+* allows element name/namespace, XSD type, and XML attributes to be
+* associated with a value. This is extremely useful when WSDL is not
+* used, but is also useful when WSDL is used with polymorphic types, including
+* xsd:anyType and user-defined types.
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @version $Id: class.soap_val.php,v 1.11 2007/04/06 13:56:32 snichol Exp $
+* @access public
+*/
+class soapval extends nusoap_base {
+ /**
+ * The XML element name
+ *
+ * @var string
+ * @access private
+ */
+ var $name;
+ /**
+ * The XML type name (string or false)
+ *
+ * @var mixed
+ * @access private
+ */
+ var $type;
+ /**
+ * The PHP value
+ *
+ * @var mixed
+ * @access private
+ */
+ var $value;
+ /**
+ * The XML element namespace (string or false)
+ *
+ * @var mixed
+ * @access private
+ */
+ var $element_ns;
+ /**
+ * The XML type namespace (string or false)
+ *
+ * @var mixed
+ * @access private
+ */
+ var $type_ns;
+ /**
+ * The XML element attributes (array or false)
+ *
+ * @var mixed
+ * @access private
+ */
+ var $attributes;
+
+ /**
+ * constructor
+ *
+ * @param string $name optional name
+ * @param mixed $type optional type name
+ * @param mixed $value optional value
+ * @param mixed $element_ns optional namespace of value
+ * @param mixed $type_ns optional namespace of type
+ * @param mixed $attributes associative array of attributes to add to element serialization
+ * @access public
+ */
+ function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) {
+ parent::nusoap_base();
+ $this->name = $name;
+ $this->type = $type;
+ $this->value = $value;
+ $this->element_ns = $element_ns;
+ $this->type_ns = $type_ns;
+ $this->attributes = $attributes;
+ }
+
+ /**
+ * return serialized value
+ *
+ * @param string $use The WSDL use value (encoded|literal)
+ * @return string XML data
+ * @access public
+ */
+ function serialize($use='encoded') {
+ return $this->serialize_val($this->value, $this->name, $this->type, $this->element_ns, $this->type_ns, $this->attributes, $use, true);
+ }
+
+ /**
+ * decodes a soapval object into a PHP native type
+ *
+ * @return mixed
+ * @access public
+ */
+ function decode(){
+ return $this->value;
+ }
+}
+
+
+
+
+?>
\ No newline at end of file
--- /dev/null
+<?php
+
+
+
+
+/**
+*
+* [nu]soapclient higher level class for easy usage.
+*
+* usage:
+*
+* // instantiate client with server info
+* $soapclient = new nusoap_client( string path [ ,mixed wsdl] );
+*
+* // call method, get results
+* echo $soapclient->call( string methodname [ ,array parameters] );
+*
+* // bye bye client
+* unset($soapclient);
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: class.soapclient.php,v 1.69 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_client extends nusoap_base {
+
+ var $username = ''; // Username for HTTP authentication
+ var $password = ''; // Password for HTTP authentication
+ var $authtype = ''; // Type of HTTP authentication
+ var $certRequest = array(); // Certificate for HTTP SSL authentication
+ var $requestHeaders = false; // SOAP headers in request (text)
+ var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text)
+ var $responseHeader = NULL; // SOAP Header from response (parsed)
+ var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text)
+ var $endpoint;
+ var $forceEndpoint = ''; // overrides WSDL endpoint
+ var $proxyhost = '';
+ var $proxyport = '';
+ var $proxyusername = '';
+ var $proxypassword = '';
+ var $portName = ''; // port name to use in WSDL
+ var $xml_encoding = ''; // character set encoding of incoming (response) messages
+ var $http_encoding = false;
+ var $timeout = 0; // HTTP connection timeout
+ var $response_timeout = 30; // HTTP response timeout
+ var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error
+ var $persistentConnection = false;
+ var $defaultRpcParams = false; // This is no longer used
+ var $request = ''; // HTTP request
+ var $response = ''; // HTTP response
+ var $responseData = ''; // SOAP payload of response
+ var $cookies = array(); // Cookies from response or for request
+ var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode()
+ var $operations = array(); // WSDL operations, empty for WSDL initialization error
+ var $curl_options = array(); // User-specified cURL options
+ var $bindingType = ''; // WSDL operation binding type
+ var $use_curl = false; // whether to always try to use cURL
+
+ /*
+ * fault related variables
+ */
+ /**
+ * @var fault
+ * @access public
+ */
+ var $fault;
+ /**
+ * @var faultcode
+ * @access public
+ */
+ var $faultcode;
+ /**
+ * @var faultstring
+ * @access public
+ */
+ var $faultstring;
+ /**
+ * @var faultdetail
+ * @access public
+ */
+ var $faultdetail;
+
+ /**
+ * constructor
+ *
+ * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object)
+ * @param mixed $wsdl optional, set to 'wsdl' or true if using WSDL
+ * @param string $proxyhost optional
+ * @param string $proxyport optional
+ * @param string $proxyusername optional
+ * @param string $proxypassword optional
+ * @param integer $timeout set the connection timeout
+ * @param integer $response_timeout set the response timeout
+ * @param string $portName optional portName in WSDL document
+ * @access public
+ */
+ function nusoap_client($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30, $portName = ''){
+ parent::nusoap_base();
+ $this->endpoint = $endpoint;
+ $this->proxyhost = $proxyhost;
+ $this->proxyport = $proxyport;
+ $this->proxyusername = $proxyusername;
+ $this->proxypassword = $proxypassword;
+ $this->timeout = $timeout;
+ $this->response_timeout = $response_timeout;
+ $this->portName = $portName;
+
+ $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
+ $this->appendDebug('endpoint=' . $this->varDump($endpoint));
+
+ // make values
+ if($wsdl){
+ if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) {
+ $this->wsdl = $endpoint;
+ $this->endpoint = $this->wsdl->wsdl;
+ $this->wsdlFile = $this->endpoint;
+ $this->debug('existing wsdl instance created from ' . $this->endpoint);
+ $this->checkWSDL();
+ } else {
+ $this->wsdlFile = $this->endpoint;
+ $this->wsdl = null;
+ $this->debug('will use lazy evaluation of wsdl from ' . $this->endpoint);
+ }
+ $this->endpointType = 'wsdl';
+ } else {
+ $this->debug("instantiate SOAP with endpoint at $endpoint");
+ $this->endpointType = 'soap';
+ }
+ }
+
+ /**
+ * calls method, returns PHP native type
+ *
+ * @param string $operation SOAP server URL or path
+ * @param mixed $params An array, associative or simple, of the parameters
+ * for the method call, or a string that is the XML
+ * for the call. For rpc style, this call will
+ * wrap the XML in a tag named after the method, as
+ * well as the SOAP Envelope and Body. For document
+ * style, this will only wrap with the Envelope and Body.
+ * IMPORTANT: when using an array with document style,
+ * in which case there
+ * is really one parameter, the root of the fragment
+ * used in the call, which encloses what programmers
+ * normally think of parameters. A parameter array
+ * *must* include the wrapper.
+ * @param string $namespace optional method namespace (WSDL can override)
+ * @param string $soapAction optional SOAPAction value (WSDL can override)
+ * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array
+ * @param boolean $rpcParams optional (no longer used)
+ * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override)
+ * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override)
+ * @return mixed response from SOAP call, normally an associative array mirroring the structure of the XML response, false for certain fatal errors
+ * @access public
+ */
+ function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){
+ $this->operation = $operation;
+ $this->fault = false;
+ $this->setError('');
+ $this->request = '';
+ $this->response = '';
+ $this->responseData = '';
+ $this->faultstring = '';
+ $this->faultcode = '';
+ $this->opData = array();
+
+ $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType");
+ $this->appendDebug('params=' . $this->varDump($params));
+ $this->appendDebug('headers=' . $this->varDump($headers));
+ if ($headers) {
+ $this->requestHeaders = $headers;
+ }
+ if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
+ $this->loadWSDL();
+ if ($this->getError())
+ return false;
+ }
+ // serialize parameters
+ if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){
+ // use WSDL for operation
+ $this->opData = $opData;
+ $this->debug("found operation");
+ $this->appendDebug('opData=' . $this->varDump($opData));
+ if (isset($opData['soapAction'])) {
+ $soapAction = $opData['soapAction'];
+ }
+ if (! $this->forceEndpoint) {
+ $this->endpoint = $opData['endpoint'];
+ } else {
+ $this->endpoint = $this->forceEndpoint;
+ }
+ $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace;
+ $style = $opData['style'];
+ $use = $opData['input']['use'];
+ // add ns to ns array
+ if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){
+ $nsPrefix = 'ns' . rand(1000, 9999);
+ $this->wsdl->namespaces[$nsPrefix] = $namespace;
+ }
+ $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace);
+ // serialize payload
+ if (is_string($params)) {
+ $this->debug("serializing param string for WSDL operation $operation");
+ $payload = $params;
+ } elseif (is_array($params)) {
+ $this->debug("serializing param array for WSDL operation $operation");
+ $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params,$this->bindingType);
+ } else {
+ $this->debug('params must be array or string');
+ $this->setError('params must be array or string');
+ return false;
+ }
+ $usedNamespaces = $this->wsdl->usedNamespaces;
+ if (isset($opData['input']['encodingStyle'])) {
+ $encodingStyle = $opData['input']['encodingStyle'];
+ } else {
+ $encodingStyle = '';
+ }
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ if ($errstr = $this->wsdl->getError()) {
+ $this->debug('got wsdl error: '.$errstr);
+ $this->setError('wsdl error: '.$errstr);
+ return false;
+ }
+ } elseif($this->endpointType == 'wsdl') {
+ // operation not in WSDL
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->setError('operation '.$operation.' not present in WSDL.');
+ $this->debug("operation '$operation' not present in WSDL.");
+ return false;
+ } else {
+ // no WSDL
+ //$this->namespaces['ns1'] = $namespace;
+ $nsPrefix = 'ns' . rand(1000, 9999);
+ // serialize
+ $payload = '';
+ if (is_string($params)) {
+ $this->debug("serializing param string for operation $operation");
+ $payload = $params;
+ } elseif (is_array($params)) {
+ $this->debug("serializing param array for operation $operation");
+ foreach($params as $k => $v){
+ $payload .= $this->serialize_val($v,$k,false,false,false,false,$use);
+ }
+ } else {
+ $this->debug('params must be array or string');
+ $this->setError('params must be array or string');
+ return false;
+ }
+ $usedNamespaces = array();
+ if ($use == 'encoded') {
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ } else {
+ $encodingStyle = '';
+ }
+ }
+ // wrap RPC calls with method element
+ if ($style == 'rpc') {
+ if ($use == 'literal') {
+ $this->debug("wrapping RPC request with literal method element");
+ if ($namespace) {
+ // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace
+ $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
+ $payload .
+ "</$nsPrefix:$operation>";
+ } else {
+ $payload = "<$operation>" . $payload . "</$operation>";
+ }
+ } else {
+ $this->debug("wrapping RPC request with encoded method element");
+ if ($namespace) {
+ $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
+ $payload .
+ "</$nsPrefix:$operation>";
+ } else {
+ $payload = "<$operation>" .
+ $payload .
+ "</$operation>";
+ }
+ }
+ }
+ // serialize envelope
+ $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle);
+ $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle");
+ $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));
+ // send
+ $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);
+ if($errstr = $this->getError()){
+ $this->debug('Error: '.$errstr);
+ return false;
+ } else {
+ $this->return = $return;
+ $this->debug('sent message successfully and got a(n) '.gettype($return));
+ $this->appendDebug('return=' . $this->varDump($return));
+
+ // fault?
+ if(is_array($return) && isset($return['faultcode'])){
+ $this->debug('got fault');
+ $this->setError($return['faultcode'].': '.$return['faultstring']);
+ $this->fault = true;
+ foreach($return as $k => $v){
+ $this->$k = $v;
+ $this->debug("$k = $v<br>");
+ }
+ return $return;
+ } elseif ($style == 'document') {
+ // NOTE: if the response is defined to have multiple parts (i.e. unwrapped),
+ // we are only going to return the first part here...sorry about that
+ return $return;
+ } else {
+ // array of return values
+ if(is_array($return)){
+ // multiple 'out' parameters, which we return wrapped up
+ // in the array
+ if(sizeof($return) > 1){
+ return $return;
+ }
+ // single 'out' parameter (normally the return value)
+ $return = array_shift($return);
+ $this->debug('return shifted value: ');
+ $this->appendDebug($this->varDump($return));
+ return $return;
+ // nothing returned (ie, echoVoid)
+ } else {
+ return "";
+ }
+ }
+ }
+ }
+
+ /**
+ * check WSDL passed as an instance or pulled from an endpoint
+ *
+ * @access private
+ */
+ function checkWSDL() {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->debug('checkWSDL');
+ // catch errors
+ if ($errstr = $this->wsdl->getError()) {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->debug('got wsdl error: '.$errstr);
+ $this->setError('wsdl error: '.$errstr);
+ } elseif ($this->operations = $this->wsdl->getOperations($this->portName, 'soap')) {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->bindingType = 'soap';
+ $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType);
+ } elseif ($this->operations = $this->wsdl->getOperations($this->portName, 'soap12')) {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->bindingType = 'soap12';
+ $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType);
+ $this->debug('**************** WARNING: SOAP 1.2 BINDING *****************');
+ } else {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->debug('getOperations returned false');
+ $this->setError('no operations defined in the WSDL document!');
+ }
+ }
+
+ /**
+ * instantiate wsdl object and parse wsdl file
+ *
+ * @access public
+ */
+ function loadWSDL() {
+ $this->debug('instantiating wsdl class with doc: '.$this->wsdlFile);
+ $this->wsdl = new wsdl('',$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout,$this->curl_options,$this->use_curl);
+ $this->wsdl->setCredentials($this->username, $this->password, $this->authtype, $this->certRequest);
+ $this->wsdl->fetchWSDL($this->wsdlFile);
+ $this->checkWSDL();
+ }
+
+ /**
+ * get available data pertaining to an operation
+ *
+ * @param string $operation operation name
+ * @return array array of data pertaining to the operation
+ * @access public
+ */
+ function getOperationData($operation){
+ if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
+ $this->loadWSDL();
+ if ($this->getError())
+ return false;
+ }
+ if(isset($this->operations[$operation])){
+ return $this->operations[$operation];
+ }
+ $this->debug("No data for operation: $operation");
+ }
+
+ /**
+ * send the SOAP message
+ *
+ * Note: if the operation has multiple return values
+ * the return value of this method will be an array
+ * of those values.
+ *
+ * @param string $msg a SOAPx4 soapmsg object
+ * @param string $soapaction SOAPAction value
+ * @param integer $timeout set connection timeout in seconds
+ * @param integer $response_timeout set response timeout in seconds
+ * @return mixed native PHP types.
+ * @access private
+ */
+ function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) {
+ $this->checkCookies();
+ // detect transport
+ switch(true){
+ // http(s)
+ case preg_match('/^http/',$this->endpoint):
+ $this->debug('transporting via HTTP');
+ if($this->persistentConnection == true && is_object($this->persistentConnection)){
+ $http =& $this->persistentConnection;
+ } else {
+ $http = new soap_transport_http($this->endpoint, $this->curl_options, $this->use_curl);
+ if ($this->persistentConnection) {
+ $http->usePersistentConnection();
+ }
+ }
+ $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset());
+ $http->setSOAPAction($soapaction);
+ if($this->proxyhost && $this->proxyport){
+ $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
+ }
+ if($this->authtype != '') {
+ $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
+ }
+ if($this->http_encoding != ''){
+ $http->setEncoding($this->http_encoding);
+ }
+ $this->debug('sending message, length='.strlen($msg));
+ if(preg_match('/^http:/',$this->endpoint)){
+ //if(strpos($this->endpoint,'http:')){
+ $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies);
+ } elseif(preg_match('/^https/',$this->endpoint)){
+ //} elseif(strpos($this->endpoint,'https:')){
+ //if(phpversion() == '4.3.0-dev'){
+ //$response = $http->send($msg,$timeout,$response_timeout);
+ //$this->request = $http->outgoing_payload;
+ //$this->response = $http->incoming_payload;
+ //} else
+ $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies);
+ } else {
+ $this->setError('no http/s in endpoint url');
+ }
+ $this->request = $http->outgoing_payload;
+ $this->response = $http->incoming_payload;
+ $this->appendDebug($http->getDebug());
+ $this->UpdateCookies($http->incoming_cookies);
+
+ // save transport object if using persistent connections
+ if ($this->persistentConnection) {
+ $http->clearDebug();
+ if (!is_object($this->persistentConnection)) {
+ $this->persistentConnection = $http;
+ }
+ }
+
+ if($err = $http->getError()){
+ $this->setError('HTTP Error: '.$err);
+ return false;
+ } elseif($this->getError()){
+ return false;
+ } else {
+ $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']);
+ return $this->parseResponse($http->incoming_headers, $this->responseData);
+ }
+ break;
+ default:
+ $this->setError('no transport found, or selected transport is not yet supported!');
+ return false;
+ break;
+ }
+ }
+
+ /**
+ * processes SOAP message returned from server
+ *
+ * @param array $headers The HTTP headers
+ * @param string $data unprocessed response data from server
+ * @return mixed value of the message, decoded into a PHP type
+ * @access private
+ */
+ function parseResponse($headers, $data) {
+ $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' headers:');
+ $this->appendDebug($this->varDump($headers));
+ if (!isset($headers['content-type'])) {
+ $this->setError('Response not of type text/xml (no content-type header)');
+ return false;
+ }
+ if (!strstr($headers['content-type'], 'text/xml')) {
+ $this->setError('Response not of type text/xml: ' . $headers['content-type']);
+ return false;
+ }
+ if (strpos($headers['content-type'], '=')) {
+ $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
+ $this->debug('Got response encoding: ' . $enc);
+ if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
+ $parser = new nusoap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8);
+ // add parser debug data to our debug
+ $this->appendDebug($parser->getDebug());
+ // if parse errors
+ if($errstr = $parser->getError()){
+ $this->setError( $errstr);
+ // destroy the parser object
+ unset($parser);
+ return false;
+ } else {
+ // get SOAP headers
+ $this->responseHeaders = $parser->getHeaders();
+ // get SOAP headers
+ $this->responseHeader = $parser->get_soapheader();
+ // get decoded message
+ $return = $parser->get_soapbody();
+ // add document for doclit support
+ $this->document = $parser->document;
+ // destroy the parser object
+ unset($parser);
+ // return decode message
+ return $return;
+ }
+ }
+
+ /**
+ * sets user-specified cURL options
+ *
+ * @param mixed $option The cURL option (always integer?)
+ * @param mixed $value The cURL option value
+ * @access public
+ */
+ function setCurlOption($option, $value) {
+ $this->debug("setCurlOption option=$option, value=");
+ $this->appendDebug($this->varDump($value));
+ $this->curl_options[$option] = $value;
+ }
+
+ /**
+ * sets the SOAP endpoint, which can override WSDL
+ *
+ * @param string $endpoint The endpoint URL to use, or empty string or false to prevent override
+ * @access public
+ */
+ function setEndpoint($endpoint) {
+ $this->debug("setEndpoint(\"$endpoint\")");
+ $this->forceEndpoint = $endpoint;
+ }
+
+ /**
+ * set the SOAP headers
+ *
+ * @param mixed $headers String of XML with SOAP header content, or array of soapval objects for SOAP headers
+ * @access public
+ */
+ function setHeaders($headers){
+ $this->debug("setHeaders headers=");
+ $this->appendDebug($this->varDump($headers));
+ $this->requestHeaders = $headers;
+ }
+
+ /**
+ * get the SOAP response headers (namespace resolution incomplete)
+ *
+ * @return string
+ * @access public
+ */
+ function getHeaders(){
+ return $this->responseHeaders;
+ }
+
+ /**
+ * get the SOAP response Header (parsed)
+ *
+ * @return mixed
+ * @access public
+ */
+ function getHeader(){
+ return $this->responseHeader;
+ }
+
+ /**
+ * set proxy info here
+ *
+ * @param string $proxyhost
+ * @param string $proxyport
+ * @param string $proxyusername
+ * @param string $proxypassword
+ * @access public
+ */
+ function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') {
+ $this->proxyhost = $proxyhost;
+ $this->proxyport = $proxyport;
+ $this->proxyusername = $proxyusername;
+ $this->proxypassword = $proxypassword;
+ }
+
+ /**
+ * if authenticating, set user credentials here
+ *
+ * @param string $username
+ * @param string $password
+ * @param string $authtype (basic|digest|certificate|ntlm)
+ * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
+ * @access public
+ */
+ function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
+ $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
+ $this->appendDebug($this->varDump($certRequest));
+ $this->username = $username;
+ $this->password = $password;
+ $this->authtype = $authtype;
+ $this->certRequest = $certRequest;
+ }
+
+ /**
+ * use HTTP encoding
+ *
+ * @param string $enc HTTP encoding
+ * @access public
+ */
+ function setHTTPEncoding($enc='gzip, deflate'){
+ $this->debug("setHTTPEncoding(\"$enc\")");
+ $this->http_encoding = $enc;
+ }
+
+ /**
+ * Set whether to try to use cURL connections if possible
+ *
+ * @param boolean $use Whether to try to use cURL
+ * @access public
+ */
+ function setUseCURL($use) {
+ $this->debug("setUseCURL($use)");
+ $this->use_curl = $use;
+ }
+
+ /**
+ * use HTTP persistent connections if possible
+ *
+ * @access public
+ */
+ function useHTTPPersistentConnection(){
+ $this->debug("useHTTPPersistentConnection");
+ $this->persistentConnection = true;
+ }
+
+ /**
+ * gets the default RPC parameter setting.
+ * If true, default is that call params are like RPC even for document style.
+ * Each call() can override this value.
+ *
+ * This is no longer used.
+ *
+ * @return boolean
+ * @access public
+ * @deprecated
+ */
+ function getDefaultRpcParams() {
+ return $this->defaultRpcParams;
+ }
+
+ /**
+ * sets the default RPC parameter setting.
+ * If true, default is that call params are like RPC even for document style
+ * Each call() can override this value.
+ *
+ * This is no longer used.
+ *
+ * @param boolean $rpcParams
+ * @access public
+ * @deprecated
+ */
+ function setDefaultRpcParams($rpcParams) {
+ $this->defaultRpcParams = $rpcParams;
+ }
+
+ /**
+ * dynamically creates an instance of a proxy class,
+ * allowing user to directly call methods from wsdl
+ *
+ * @return object soap_proxy object
+ * @access public
+ */
+ function getProxy() {
+ $r = rand();
+ $evalStr = $this->_getProxyClassCode($r);
+ //$this->debug("proxy class: $evalStr");
+ if ($this->getError()) {
+ $this->debug("Error from _getProxyClassCode, so return NULL");
+ return null;
+ }
+ // eval the class
+ eval($evalStr);
+ // instantiate proxy object
+ eval("\$proxy = new nusoap_proxy_$r('');");
+ // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice
+ $proxy->endpointType = 'wsdl';
+ $proxy->wsdlFile = $this->wsdlFile;
+ $proxy->wsdl = $this->wsdl;
+ $proxy->operations = $this->operations;
+ $proxy->defaultRpcParams = $this->defaultRpcParams;
+ // transfer other state
+ $proxy->soap_defencoding = $this->soap_defencoding;
+ $proxy->username = $this->username;
+ $proxy->password = $this->password;
+ $proxy->authtype = $this->authtype;
+ $proxy->certRequest = $this->certRequest;
+ $proxy->requestHeaders = $this->requestHeaders;
+ $proxy->endpoint = $this->endpoint;
+ $proxy->forceEndpoint = $this->forceEndpoint;
+ $proxy->proxyhost = $this->proxyhost;
+ $proxy->proxyport = $this->proxyport;
+ $proxy->proxyusername = $this->proxyusername;
+ $proxy->proxypassword = $this->proxypassword;
+ $proxy->http_encoding = $this->http_encoding;
+ $proxy->timeout = $this->timeout;
+ $proxy->response_timeout = $this->response_timeout;
+ $proxy->persistentConnection = &$this->persistentConnection;
+ $proxy->decode_utf8 = $this->decode_utf8;
+ $proxy->curl_options = $this->curl_options;
+ $proxy->bindingType = $this->bindingType;
+ $proxy->use_curl = $this->use_curl;
+ return $proxy;
+ }
+
+ /**
+ * dynamically creates proxy class code
+ *
+ * @return string PHP/NuSOAP code for the proxy class
+ * @access private
+ */
+ function _getProxyClassCode($r) {
+ $this->debug("in getProxy endpointType=$this->endpointType");
+ $this->appendDebug("wsdl=" . $this->varDump($this->wsdl));
+ if ($this->endpointType != 'wsdl') {
+ $evalStr = 'A proxy can only be created for a WSDL client';
+ $this->setError($evalStr);
+ $evalStr = "echo \"$evalStr\";";
+ return $evalStr;
+ }
+ if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
+ $this->loadWSDL();
+ if ($this->getError()) {
+ return "echo \"" . $this->getError() . "\";";
+ }
+ }
+ $evalStr = '';
+ foreach ($this->operations as $operation => $opData) {
+ if ($operation != '') {
+ // create param string and param comment string
+ if (sizeof($opData['input']['parts']) > 0) {
+ $paramStr = '';
+ $paramArrayStr = '';
+ $paramCommentStr = '';
+ foreach ($opData['input']['parts'] as $name => $type) {
+ $paramStr .= "\$$name, ";
+ $paramArrayStr .= "'$name' => \$$name, ";
+ $paramCommentStr .= "$type \$$name, ";
+ }
+ $paramStr = substr($paramStr, 0, strlen($paramStr)-2);
+ $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2);
+ $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2);
+ } else {
+ $paramStr = '';
+ $paramArrayStr = '';
+ $paramCommentStr = 'void';
+ }
+ $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace'];
+ $evalStr .= "// $paramCommentStr
+ function " . str_replace('.', '__', $operation) . "($paramStr) {
+ \$params = array($paramArrayStr);
+ return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."');
+ }
+ ";
+ unset($paramStr);
+ unset($paramCommentStr);
+ }
+ }
+ $evalStr = 'class nusoap_proxy_'.$r.' extends nusoap_client {
+ '.$evalStr.'
+}';
+ return $evalStr;
+ }
+
+ /**
+ * dynamically creates proxy class code
+ *
+ * @return string PHP/NuSOAP code for the proxy class
+ * @access public
+ */
+ function getProxyClassCode() {
+ $r = rand();
+ return $this->_getProxyClassCode($r);
+ }
+
+ /**
+ * gets the HTTP body for the current request.
+ *
+ * @param string $soapmsg The SOAP payload
+ * @return string The HTTP body, which includes the SOAP payload
+ * @access private
+ */
+ function getHTTPBody($soapmsg) {
+ return $soapmsg;
+ }
+
+ /**
+ * gets the HTTP content type for the current request.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type for the current request.
+ * @access private
+ */
+ function getHTTPContentType() {
+ return 'text/xml';
+ }
+
+ /**
+ * gets the HTTP content type charset for the current request.
+ * returns false for non-text content types.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type charset for the current request.
+ * @access private
+ */
+ function getHTTPContentTypeCharset() {
+ return $this->soap_defencoding;
+ }
+
+ /*
+ * whether or not parser should decode utf8 element content
+ *
+ * @return always returns true
+ * @access public
+ */
+ function decodeUTF8($bool){
+ $this->decode_utf8 = $bool;
+ return true;
+ }
+
+ /**
+ * adds a new Cookie into $this->cookies array
+ *
+ * @param string $name Cookie Name
+ * @param string $value Cookie Value
+ * @return boolean if cookie-set was successful returns true, else false
+ * @access public
+ */
+ function setCookie($name, $value) {
+ if (strlen($name) == 0) {
+ return false;
+ }
+ $this->cookies[] = array('name' => $name, 'value' => $value);
+ return true;
+ }
+
+ /**
+ * gets all Cookies
+ *
+ * @return array with all internal cookies
+ * @access public
+ */
+ function getCookies() {
+ return $this->cookies;
+ }
+
+ /**
+ * checks all Cookies and delete those which are expired
+ *
+ * @return boolean always return true
+ * @access private
+ */
+ function checkCookies() {
+ if (sizeof($this->cookies) == 0) {
+ return true;
+ }
+ $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies');
+ $curr_cookies = $this->cookies;
+ $this->cookies = array();
+ foreach ($curr_cookies as $cookie) {
+ if (! is_array($cookie)) {
+ $this->debug('Remove cookie that is not an array');
+ continue;
+ }
+ if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
+ if (strtotime($cookie['expires']) > time()) {
+ $this->cookies[] = $cookie;
+ } else {
+ $this->debug('Remove expired cookie ' . $cookie['name']);
+ }
+ } else {
+ $this->cookies[] = $cookie;
+ }
+ }
+ $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array');
+ return true;
+ }
+
+ /**
+ * updates the current cookies with a new set
+ *
+ * @param array $cookies new cookies with which to update current ones
+ * @return boolean always return true
+ * @access private
+ */
+ function UpdateCookies($cookies) {
+ if (sizeof($this->cookies) == 0) {
+ // no existing cookies: take whatever is new
+ if (sizeof($cookies) > 0) {
+ $this->debug('Setting new cookie(s)');
+ $this->cookies = $cookies;
+ }
+ return true;
+ }
+ if (sizeof($cookies) == 0) {
+ // no new cookies: keep what we've got
+ return true;
+ }
+ // merge
+ foreach ($cookies as $newCookie) {
+ if (!is_array($newCookie)) {
+ continue;
+ }
+ if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) {
+ continue;
+ }
+ $newName = $newCookie['name'];
+
+ $found = false;
+ for ($i = 0; $i < count($this->cookies); $i++) {
+ $cookie = $this->cookies[$i];
+ if (!is_array($cookie)) {
+ continue;
+ }
+ if (!isset($cookie['name'])) {
+ continue;
+ }
+ if ($newName != $cookie['name']) {
+ continue;
+ }
+ $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN';
+ $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN';
+ if ($newDomain != $domain) {
+ continue;
+ }
+ $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH';
+ $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH';
+ if ($newPath != $path) {
+ continue;
+ }
+ $this->cookies[$i] = $newCookie;
+ $found = true;
+ $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']);
+ break;
+ }
+ if (! $found) {
+ $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']);
+ $this->cookies[] = $newCookie;
+ }
+ }
+ return true;
+ }
+}
+
+if (!extension_loaded('soap')) {
+ /**
+ * For backwards compatiblity, define soapclient unless the PHP SOAP extension is loaded.
+ */
+ class soapclient extends nusoap_client {
+ }
+}
+?>
--- /dev/null
+<?php
+
+
+
+
+/**
+* parses a WSDL file, allows access to it's data, other utility methods.
+* also builds WSDL structures programmatically.
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: class.wsdl.php,v 1.76 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class wsdl extends nusoap_base {
+ // URL or filename of the root of this WSDL
+ var $wsdl;
+ // define internal arrays of bindings, ports, operations, messages, etc.
+ var $schemas = array();
+ var $currentSchema;
+ var $message = array();
+ var $complexTypes = array();
+ var $messages = array();
+ var $currentMessage;
+ var $currentOperation;
+ var $portTypes = array();
+ var $currentPortType;
+ var $bindings = array();
+ var $currentBinding;
+ var $ports = array();
+ var $currentPort;
+ var $opData = array();
+ var $status = '';
+ var $documentation = false;
+ var $endpoint = '';
+ // array of wsdl docs to import
+ var $import = array();
+ // parser vars
+ var $parser;
+ var $position = 0;
+ var $depth = 0;
+ var $depth_array = array();
+ // for getting wsdl
+ var $proxyhost = '';
+ var $proxyport = '';
+ var $proxyusername = '';
+ var $proxypassword = '';
+ var $timeout = 0;
+ var $response_timeout = 30;
+ var $curl_options = array(); // User-specified cURL options
+ var $use_curl = false; // whether to always try to use cURL
+ // for HTTP authentication
+ var $username = ''; // Username for HTTP authentication
+ var $password = ''; // Password for HTTP authentication
+ var $authtype = ''; // Type of HTTP authentication
+ var $certRequest = array(); // Certificate for HTTP SSL authentication
+
+ /**
+ * constructor
+ *
+ * @param string $wsdl WSDL document URL
+ * @param string $proxyhost
+ * @param string $proxyport
+ * @param string $proxyusername
+ * @param string $proxypassword
+ * @param integer $timeout set the connection timeout
+ * @param integer $response_timeout set the response timeout
+ * @param array $curl_options user-specified cURL options
+ * @param boolean $use_curl try to use cURL
+ * @access public
+ */
+ function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30,$curl_options=null,$use_curl=false){
+ parent::nusoap_base();
+ $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
+ $this->proxyhost = $proxyhost;
+ $this->proxyport = $proxyport;
+ $this->proxyusername = $proxyusername;
+ $this->proxypassword = $proxypassword;
+ $this->timeout = $timeout;
+ $this->response_timeout = $response_timeout;
+ if (is_array($curl_options))
+ $this->curl_options = $curl_options;
+ $this->use_curl = $use_curl;
+ $this->fetchWSDL($wsdl);
+ }
+
+ /**
+ * fetches the WSDL document and parses it
+ *
+ * @access public
+ */
+ function fetchWSDL($wsdl) {
+ $this->debug("parse and process WSDL path=$wsdl");
+ $this->wsdl = $wsdl;
+ // parse wsdl file
+ if ($this->wsdl != "") {
+ $this->parseWSDL($this->wsdl);
+ }
+ // imports
+ // TODO: handle imports more properly, grabbing them in-line and nesting them
+ $imported_urls = array();
+ $imported = 1;
+ while ($imported > 0) {
+ $imported = 0;
+ // Schema imports
+ foreach ($this->schemas as $ns => $list) {
+ foreach ($list as $xs) {
+ $wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
+ foreach ($xs->imports as $ns2 => $list2) {
+ for ($ii = 0; $ii < count($list2); $ii++) {
+ if (! $list2[$ii]['loaded']) {
+ $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true;
+ $url = $list2[$ii]['location'];
+ if ($url != '') {
+ $urlparts = parse_url($url);
+ if (!isset($urlparts['host'])) {
+ $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') .
+ substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
+ }
+ if (! in_array($url, $imported_urls)) {
+ $this->parseWSDL($url);
+ $imported++;
+ $imported_urls[] = $url;
+ }
+ } else {
+ $this->debug("Unexpected scenario: empty URL for unloaded import");
+ }
+ }
+ }
+ }
+ }
+ }
+ // WSDL imports
+ $wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
+ foreach ($this->import as $ns => $list) {
+ for ($ii = 0; $ii < count($list); $ii++) {
+ if (! $list[$ii]['loaded']) {
+ $this->import[$ns][$ii]['loaded'] = true;
+ $url = $list[$ii]['location'];
+ if ($url != '') {
+ $urlparts = parse_url($url);
+ if (!isset($urlparts['host'])) {
+ $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') .
+ substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
+ }
+ if (! in_array($url, $imported_urls)) {
+ $this->parseWSDL($url);
+ $imported++;
+ $imported_urls[] = $url;
+ }
+ } else {
+ $this->debug("Unexpected scenario: empty URL for unloaded import");
+ }
+ }
+ }
+ }
+ }
+ // add new data to operation data
+ foreach($this->bindings as $binding => $bindingData) {
+ if (isset($bindingData['operations']) && is_array($bindingData['operations'])) {
+ foreach($bindingData['operations'] as $operation => $data) {
+ $this->debug('post-parse data gathering for ' . $operation);
+ $this->bindings[$binding]['operations'][$operation]['input'] =
+ isset($this->bindings[$binding]['operations'][$operation]['input']) ?
+ array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) :
+ $this->portTypes[ $bindingData['portType'] ][$operation]['input'];
+ $this->bindings[$binding]['operations'][$operation]['output'] =
+ isset($this->bindings[$binding]['operations'][$operation]['output']) ?
+ array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) :
+ $this->portTypes[ $bindingData['portType'] ][$operation]['output'];
+ if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){
+ $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ];
+ }
+ if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){
+ $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ];
+ }
+ // Set operation style if necessary, but do not override one already provided
+ if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) {
+ $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style'];
+ }
+ $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : '';
+ $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : '';
+ $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : '';
+ }
+ }
+ }
+ }
+
+ /**
+ * parses the wsdl document
+ *
+ * @param string $wsdl path or URL
+ * @access private
+ */
+ function parseWSDL($wsdl = '') {
+ $this->debug("parse WSDL at path=$wsdl");
+
+ if ($wsdl == '') {
+ $this->debug('no wsdl passed to parseWSDL()!!');
+ $this->setError('no wsdl passed to parseWSDL()!!');
+ return false;
+ }
+
+ // parse $wsdl for url format
+ $wsdl_props = parse_url($wsdl);
+
+ if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) {
+ $this->debug('getting WSDL http(s) URL ' . $wsdl);
+ // get wsdl
+ $tr = new soap_transport_http($wsdl, $this->curl_options, $this->use_curl);
+ $tr->request_method = 'GET';
+ $tr->useSOAPAction = false;
+ if($this->proxyhost && $this->proxyport){
+ $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
+ }
+ if ($this->authtype != '') {
+ $tr->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
+ }
+ $tr->setEncoding('gzip, deflate');
+ $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout);
+ //$this->debug("WSDL request\n" . $tr->outgoing_payload);
+ //$this->debug("WSDL response\n" . $tr->incoming_payload);
+ $this->appendDebug($tr->getDebug());
+ // catch errors
+ if($err = $tr->getError() ){
+ $errstr = 'Getting ' . $wsdl . ' - HTTP ERROR: '.$err;
+ $this->debug($errstr);
+ $this->setError($errstr);
+ unset($tr);
+ return false;
+ }
+ unset($tr);
+ $this->debug("got WSDL URL");
+ } else {
+ // $wsdl is not http(s), so treat it as a file URL or plain file path
+ if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) {
+ $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path'];
+ } else {
+ $path = $wsdl;
+ }
+ $this->debug('getting WSDL file ' . $path);
+ if ($fp = @fopen($path, 'r')) {
+ $wsdl_string = '';
+ while ($data = fread($fp, 32768)) {
+ $wsdl_string .= $data;
+ }
+ fclose($fp);
+ } else {
+ $errstr = "Bad path to WSDL file $path";
+ $this->debug($errstr);
+ $this->setError($errstr);
+ return false;
+ }
+ }
+ $this->debug('Parse WSDL');
+ // end new code added
+ // Create an XML parser.
+ $this->parser = xml_parser_create();
+ // Set the options for parsing the XML data.
+ // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
+ xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
+ // Set the object for the parser.
+ xml_set_object($this->parser, $this);
+ // Set the element handlers for the parser.
+ xml_set_element_handler($this->parser, 'start_element', 'end_element');
+ xml_set_character_data_handler($this->parser, 'character_data');
+ // Parse the XML file.
+ if (!xml_parse($this->parser, $wsdl_string, true)) {
+ // Display an error message.
+ $errstr = sprintf(
+ 'XML error parsing WSDL from %s on line %d: %s',
+ $wsdl,
+ xml_get_current_line_number($this->parser),
+ xml_error_string(xml_get_error_code($this->parser))
+ );
+ $this->debug($errstr);
+ $this->debug("XML payload:\n" . $wsdl_string);
+ $this->setError($errstr);
+ return false;
+ }
+ // free the parser
+ xml_parser_free($this->parser);
+ $this->debug('Parsing WSDL done');
+ // catch wsdl parse errors
+ if($this->getError()){
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * start-element handler
+ *
+ * @param string $parser XML parser object
+ * @param string $name element name
+ * @param string $attrs associative array of attributes
+ * @access private
+ */
+ function start_element($parser, $name, $attrs)
+ {
+ if ($this->status == 'schema') {
+ $this->currentSchema->schemaStartElement($parser, $name, $attrs);
+ $this->appendDebug($this->currentSchema->getDebug());
+ $this->currentSchema->clearDebug();
+ } elseif (preg_match('/schema$/', $name)) {
+ $this->debug('Parsing WSDL schema');
+ // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")");
+ $this->status = 'schema';
+ $this->currentSchema = new nusoap_xmlschema('', '', $this->namespaces);
+ $this->currentSchema->schemaStartElement($parser, $name, $attrs);
+ $this->appendDebug($this->currentSchema->getDebug());
+ $this->currentSchema->clearDebug();
+ } else {
+ // position in the total number of elements, starting from 0
+ $pos = $this->position++;
+ $depth = $this->depth++;
+ // set self as current value for this depth
+ $this->depth_array[$depth] = $pos;
+ $this->message[$pos] = array('cdata' => '');
+ // process attributes
+ if (count($attrs) > 0) {
+ // register namespace declarations
+ foreach($attrs as $k => $v) {
+ if (preg_match('/^xmlns/',$k)) {
+ if ($ns_prefix = substr(strrchr($k, ':'), 1)) {
+ $this->namespaces[$ns_prefix] = $v;
+ } else {
+ $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v;
+ }
+ if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') {
+ $this->XMLSchemaVersion = $v;
+ $this->namespaces['xsi'] = $v . '-instance';
+ }
+ }
+ }
+ // expand each attribute prefix to its namespace
+ foreach($attrs as $k => $v) {
+ $k = strpos($k, ':') ? $this->expandQname($k) : $k;
+ if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') {
+ $v = strpos($v, ':') ? $this->expandQname($v) : $v;
+ }
+ $eAttrs[$k] = $v;
+ }
+ $attrs = $eAttrs;
+ } else {
+ $attrs = array();
+ }
+ // get element prefix, namespace and name
+ if (preg_match('/:/', $name)) {
+ // get ns prefix
+ $prefix = substr($name, 0, strpos($name, ':'));
+ // get ns
+ $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : '';
+ // get unqualified name
+ $name = substr(strstr($name, ':'), 1);
+ }
+ // process attributes, expanding any prefixes to namespaces
+ // find status, register data
+ switch ($this->status) {
+ case 'message':
+ if ($name == 'part') {
+ if (isset($attrs['type'])) {
+ $this->debug("msg " . $this->currentMessage . ": found part (with type) $attrs[name]: " . implode(',', $attrs));
+ $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type'];
+ }
+ if (isset($attrs['element'])) {
+ $this->debug("msg " . $this->currentMessage . ": found part (with element) $attrs[name]: " . implode(',', $attrs));
+ $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'] . '^';
+ }
+ }
+ break;
+ case 'portType':
+ switch ($name) {
+ case 'operation':
+ $this->currentPortOperation = $attrs['name'];
+ $this->debug("portType $this->currentPortType operation: $this->currentPortOperation");
+ if (isset($attrs['parameterOrder'])) {
+ $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder'];
+ }
+ break;
+ case 'documentation':
+ $this->documentation = true;
+ break;
+ // merge input/output data
+ default:
+ $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : '';
+ $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m;
+ break;
+ }
+ break;
+ case 'binding':
+ switch ($name) {
+ case 'binding':
+ // get ns prefix
+ if (isset($attrs['style'])) {
+ $this->bindings[$this->currentBinding]['prefix'] = $prefix;
+ }
+ $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs);
+ break;
+ case 'header':
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs;
+ break;
+ case 'operation':
+ if (isset($attrs['soapAction'])) {
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction'];
+ }
+ if (isset($attrs['style'])) {
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style'];
+ }
+ if (isset($attrs['name'])) {
+ $this->currentOperation = $attrs['name'];
+ $this->debug("current binding operation: $this->currentOperation");
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name'];
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding;
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : '';
+ }
+ break;
+ case 'input':
+ $this->opStatus = 'input';
+ break;
+ case 'output':
+ $this->opStatus = 'output';
+ break;
+ case 'body':
+ if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) {
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs);
+ } else {
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs;
+ }
+ break;
+ }
+ break;
+ case 'service':
+ switch ($name) {
+ case 'port':
+ $this->currentPort = $attrs['name'];
+ $this->debug('current port: ' . $this->currentPort);
+ $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']);
+
+ break;
+ case 'address':
+ $this->ports[$this->currentPort]['location'] = $attrs['location'];
+ $this->ports[$this->currentPort]['bindingType'] = $namespace;
+ $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace;
+ $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location'];
+ break;
+ }
+ break;
+ }
+ // set status
+ switch ($name) {
+ case 'import':
+ if (isset($attrs['location'])) {
+ $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false);
+ $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')');
+ } else {
+ $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
+ if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
+ $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
+ }
+ $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')');
+ }
+ break;
+ //wait for schema
+ //case 'types':
+ // $this->status = 'schema';
+ // break;
+ case 'message':
+ $this->status = 'message';
+ $this->messages[$attrs['name']] = array();
+ $this->currentMessage = $attrs['name'];
+ break;
+ case 'portType':
+ $this->status = 'portType';
+ $this->portTypes[$attrs['name']] = array();
+ $this->currentPortType = $attrs['name'];
+ break;
+ case "binding":
+ if (isset($attrs['name'])) {
+ // get binding name
+ if (strpos($attrs['name'], ':')) {
+ $this->currentBinding = $this->getLocalPart($attrs['name']);
+ } else {
+ $this->currentBinding = $attrs['name'];
+ }
+ $this->status = 'binding';
+ $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']);
+ $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']);
+ }
+ break;
+ case 'service':
+ $this->serviceName = $attrs['name'];
+ $this->status = 'service';
+ $this->debug('current service: ' . $this->serviceName);
+ break;
+ case 'definitions':
+ foreach ($attrs as $name => $value) {
+ $this->wsdl_info[$name] = $value;
+ }
+ break;
+ }
+ }
+ }
+
+ /**
+ * end-element handler
+ *
+ * @param string $parser XML parser object
+ * @param string $name element name
+ * @access private
+ */
+ function end_element($parser, $name){
+ // unset schema status
+ if (/*preg_match('/types$/', $name) ||*/ preg_match('/schema$/', $name)) {
+ $this->status = "";
+ $this->appendDebug($this->currentSchema->getDebug());
+ $this->currentSchema->clearDebug();
+ $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema;
+ $this->debug('Parsing WSDL schema done');
+ }
+ if ($this->status == 'schema') {
+ $this->currentSchema->schemaEndElement($parser, $name);
+ } else {
+ // bring depth down a notch
+ $this->depth--;
+ }
+ // end documentation
+ if ($this->documentation) {
+ //TODO: track the node to which documentation should be assigned; it can be a part, message, etc.
+ //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation;
+ $this->documentation = false;
+ }
+ }
+
+ /**
+ * element content handler
+ *
+ * @param string $parser XML parser object
+ * @param string $data element content
+ * @access private
+ */
+ function character_data($parser, $data)
+ {
+ $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0;
+ if (isset($this->message[$pos]['cdata'])) {
+ $this->message[$pos]['cdata'] .= $data;
+ }
+ if ($this->documentation) {
+ $this->documentation .= $data;
+ }
+ }
+
+ /**
+ * if authenticating, set user credentials here
+ *
+ * @param string $username
+ * @param string $password
+ * @param string $authtype (basic|digest|certificate|ntlm)
+ * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
+ * @access public
+ */
+ function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
+ $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
+ $this->appendDebug($this->varDump($certRequest));
+ $this->username = $username;
+ $this->password = $password;
+ $this->authtype = $authtype;
+ $this->certRequest = $certRequest;
+ }
+
+ function getBindingData($binding)
+ {
+ if (is_array($this->bindings[$binding])) {
+ return $this->bindings[$binding];
+ }
+ }
+
+ /**
+ * returns an assoc array of operation names => operation data
+ *
+ * @param string $portName WSDL port name
+ * @param string $bindingType eg: soap, smtp, dime (only soap and soap12 are currently supported)
+ * @return array
+ * @access public
+ */
+ function getOperations($portName = '', $bindingType = 'soap') {
+ $ops = array();
+ if ($bindingType == 'soap') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
+ } elseif ($bindingType == 'soap12') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
+ } else {
+ $this->debug("getOperations bindingType $bindingType may not be supported");
+ }
+ $this->debug("getOperations for port '$portName' bindingType $bindingType");
+ // loop thru ports
+ foreach($this->ports as $port => $portData) {
+ $this->debug("getOperations checking port $port bindingType " . $portData['bindingType']);
+ if ($portName == '' || $port == $portName) {
+ // binding type of port matches parameter
+ if ($portData['bindingType'] == $bindingType) {
+ $this->debug("getOperations found port $port bindingType $bindingType");
+ //$this->debug("port data: " . $this->varDump($portData));
+ //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ]));
+ // merge bindings
+ if (isset($this->bindings[ $portData['binding'] ]['operations'])) {
+ $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']);
+ }
+ }
+ }
+ }
+ if (count($ops) == 0) {
+ $this->debug("getOperations found no operations for port '$portName' bindingType $bindingType");
+ }
+ return $ops;
+ }
+
+ /**
+ * returns an associative array of data necessary for calling an operation
+ *
+ * @param string $operation name of operation
+ * @param string $bindingType type of binding eg: soap, soap12
+ * @return array
+ * @access public
+ */
+ function getOperationData($operation, $bindingType = 'soap')
+ {
+ if ($bindingType == 'soap') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
+ } elseif ($bindingType == 'soap12') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
+ }
+ // loop thru ports
+ foreach($this->ports as $port => $portData) {
+ // binding type of port matches parameter
+ if ($portData['bindingType'] == $bindingType) {
+ // get binding
+ //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
+ foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) {
+ // note that we could/should also check the namespace here
+ if ($operation == $bOperation) {
+ $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation];
+ return $opData;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * returns an associative array of data necessary for calling an operation
+ *
+ * @param string $soapAction soapAction for operation
+ * @param string $bindingType type of binding eg: soap, soap12
+ * @return array
+ * @access public
+ */
+ function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') {
+ if ($bindingType == 'soap') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
+ } elseif ($bindingType == 'soap12') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
+ }
+ // loop thru ports
+ foreach($this->ports as $port => $portData) {
+ // binding type of port matches parameter
+ if ($portData['bindingType'] == $bindingType) {
+ // loop through operations for the binding
+ foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
+ if ($opData['soapAction'] == $soapAction) {
+ return $opData;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * returns an array of information about a given type
+ * returns false if no type exists by the given name
+ *
+ * typeDef = array(
+ * 'elements' => array(), // refs to elements array
+ * 'restrictionBase' => '',
+ * 'phpType' => '',
+ * 'order' => '(sequence|all)',
+ * 'attrs' => array() // refs to attributes array
+ * )
+ *
+ * @param string $type the type
+ * @param string $ns namespace (not prefix) of the type
+ * @return mixed
+ * @access public
+ * @see nusoap_xmlschema
+ */
+ function getTypeDef($type, $ns) {
+ $this->debug("in getTypeDef: type=$type, ns=$ns");
+ if ((! $ns) && isset($this->namespaces['tns'])) {
+ $ns = $this->namespaces['tns'];
+ $this->debug("in getTypeDef: type namespace forced to $ns");
+ }
+ if (!isset($this->schemas[$ns])) {
+ foreach ($this->schemas as $ns0 => $schema0) {
+ if (strcasecmp($ns, $ns0) == 0) {
+ $this->debug("in getTypeDef: replacing schema namespace $ns with $ns0");
+ $ns = $ns0;
+ break;
+ }
+ }
+ }
+ if (isset($this->schemas[$ns])) {
+ $this->debug("in getTypeDef: have schema for namespace $ns");
+ for ($i = 0; $i < count($this->schemas[$ns]); $i++) {
+ $xs = &$this->schemas[$ns][$i];
+ $t = $xs->getTypeDef($type);
+ $this->appendDebug($xs->getDebug());
+ $xs->clearDebug();
+ if ($t) {
+ $this->debug("in getTypeDef: found type $type");
+ if (!isset($t['phpType'])) {
+ // get info for type to tack onto the element
+ $uqType = substr($t['type'], strrpos($t['type'], ':') + 1);
+ $ns = substr($t['type'], 0, strrpos($t['type'], ':'));
+ $etype = $this->getTypeDef($uqType, $ns);
+ if ($etype) {
+ $this->debug("found type for [element] $type:");
+ $this->debug($this->varDump($etype));
+ if (isset($etype['phpType'])) {
+ $t['phpType'] = $etype['phpType'];
+ }
+ if (isset($etype['elements'])) {
+ $t['elements'] = $etype['elements'];
+ }
+ if (isset($etype['attrs'])) {
+ $t['attrs'] = $etype['attrs'];
+ }
+ } else {
+ $this->debug("did not find type for [element] $type");
+ }
+ }
+ return $t;
+ }
+ }
+ $this->debug("in getTypeDef: did not find type $type");
+ } else {
+ $this->debug("in getTypeDef: do not have schema for namespace $ns");
+ }
+ return false;
+ }
+
+ /**
+ * prints html description of services
+ *
+ * @access private
+ */
+ function webDescription(){
+ global $HTTP_SERVER_VARS;
+
+ if (isset($_SERVER)) {
+ $PHP_SELF = $_SERVER['PHP_SELF'];
+ } elseif (isset($HTTP_SERVER_VARS)) {
+ $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
+ } else {
+ $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
+ }
+
+ $b = '
+ <html><head><title>NuSOAP: '.$this->serviceName.'</title>
+ <style type="text/css">
+ body { font-family: arial; color: #000000; background-color: #ffffff; margin: 0px 0px 0px 0px; }
+ p { font-family: arial; color: #000000; margin-top: 0px; margin-bottom: 12px; }
+ pre { background-color: silver; padding: 5px; font-family: Courier New; font-size: x-small; color: #000000;}
+ ul { margin-top: 10px; margin-left: 20px; }
+ li { list-style-type: none; margin-top: 10px; color: #000000; }
+ .content{
+ margin-left: 0px; padding-bottom: 2em; }
+ .nav {
+ padding-top: 10px; padding-bottom: 10px; padding-left: 15px; font-size: .70em;
+ margin-top: 10px; margin-left: 0px; color: #000000;
+ background-color: #ccccff; width: 20%; margin-left: 20px; margin-top: 20px; }
+ .title {
+ font-family: arial; font-size: 26px; color: #ffffff;
+ background-color: #999999; width: 100%;
+ margin-left: 0px; margin-right: 0px;
+ padding-top: 10px; padding-bottom: 10px;}
+ .hidden {
+ position: absolute; visibility: hidden; z-index: 200; left: 250px; top: 100px;
+ font-family: arial; overflow: hidden; width: 600;
+ padding: 20px; font-size: 10px; background-color: #999999;
+ layer-background-color:#FFFFFF; }
+ a,a:active { color: charcoal; font-weight: bold; }
+ a:visited { color: #666666; font-weight: bold; }
+ a:hover { color: cc3300; font-weight: bold; }
+ </style>
+ <script language="JavaScript" type="text/javascript">
+ <!--
+ // POP-UP CAPTIONS...
+ function lib_bwcheck(){ //Browsercheck (needed)
+ this.ver=navigator.appVersion
+ this.agent=navigator.userAgent
+ this.dom=document.getElementById?1:0
+ this.opera5=this.agent.indexOf("Opera 5")>-1
+ this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
+ this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
+ this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
+ this.ie=this.ie4||this.ie5||this.ie6
+ this.mac=this.agent.indexOf("Mac")>-1
+ this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
+ this.ns4=(document.layers && !this.dom)?1:0;
+ this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
+ return this
+ }
+ var bw = new lib_bwcheck()
+ //Makes crossbrowser object.
+ function makeObj(obj){
+ this.evnt=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
+ if(!this.evnt) return false
+ this.css=bw.dom||bw.ie4?this.evnt.style:bw.ns4?this.evnt:0;
+ this.wref=bw.dom||bw.ie4?this.evnt:bw.ns4?this.css.document:0;
+ this.writeIt=b_writeIt;
+ return this
+ }
+ // A unit of measure that will be added when setting the position of a layer.
+ //var px = bw.ns4||window.opera?"":"px";
+ function b_writeIt(text){
+ if (bw.ns4){this.wref.write(text);this.wref.close()}
+ else this.wref.innerHTML = text
+ }
+ //Shows the messages
+ var oDesc;
+ function popup(divid){
+ if(oDesc = new makeObj(divid)){
+ oDesc.css.visibility = "visible"
+ }
+ }
+ function popout(){ // Hides message
+ if(oDesc) oDesc.css.visibility = "hidden"
+ }
+ //-->
+ </script>
+ </head>
+ <body>
+ <div class=content>
+ <br><br>
+ <div class=title>'.$this->serviceName.'</div>
+ <div class=nav>
+ <p>View the <a href="'.$PHP_SELF.'?wsdl">WSDL</a> for the service.
+ Click on an operation name to view it's details.</p>
+ <ul>';
+ foreach($this->getOperations() as $op => $data){
+ $b .= "<li><a href='#' onclick=\"popout();popup('$op')\">$op</a></li>";
+ // create hidden div
+ $b .= "<div id='$op' class='hidden'>
+ <a href='#' onclick='popout()'><font color='#ffffff'>Close</font></a><br><br>";
+ foreach($data as $donnie => $marie){ // loop through opdata
+ if($donnie == 'input' || $donnie == 'output'){ // show input/output data
+ $b .= "<font color='white'>".ucfirst($donnie).':</font><br>';
+ foreach($marie as $captain => $tenille){ // loop through data
+ if($captain == 'parts'){ // loop thru parts
+ $b .= " $captain:<br>";
+ //if(is_array($tenille)){
+ foreach($tenille as $joanie => $chachi){
+ $b .= " $joanie: $chachi<br>";
+ }
+ //}
+ } else {
+ $b .= " $captain: $tenille<br>";
+ }
+ }
+ } else {
+ $b .= "<font color='white'>".ucfirst($donnie).":</font> $marie<br>";
+ }
+ }
+ $b .= '</div>';
+ }
+ $b .= '
+ <ul>
+ </div>
+ </div></body></html>';
+ return $b;
+ }
+
+ /**
+ * serialize the parsed wsdl
+ *
+ * @param mixed $debug whether to put debug=1 in endpoint URL
+ * @return string serialization of WSDL
+ * @access public
+ */
+ function serialize($debug = 0)
+ {
+ $xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
+ $xml .= "\n<definitions";
+ foreach($this->namespaces as $k => $v) {
+ $xml .= " xmlns:$k=\"$v\"";
+ }
+ // 10.9.02 - add poulter fix for wsdl and tns declarations
+ if (isset($this->namespaces['wsdl'])) {
+ $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\"";
+ }
+ if (isset($this->namespaces['tns'])) {
+ $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\"";
+ }
+ $xml .= '>';
+ // imports
+ if (sizeof($this->import) > 0) {
+ foreach($this->import as $ns => $list) {
+ foreach ($list as $ii) {
+ if ($ii['location'] != '') {
+ $xml .= '<import location="' . $ii['location'] . '" namespace="' . $ns . '" />';
+ } else {
+ $xml .= '<import namespace="' . $ns . '" />';
+ }
+ }
+ }
+ }
+ // types
+ if (count($this->schemas)>=1) {
+ $xml .= "\n<types>\n";
+ foreach ($this->schemas as $ns => $list) {
+ foreach ($list as $xs) {
+ $xml .= $xs->serializeSchema();
+ }
+ }
+ $xml .= '</types>';
+ }
+ // messages
+ if (count($this->messages) >= 1) {
+ foreach($this->messages as $msgName => $msgParts) {
+ $xml .= "\n<message name=\"" . $msgName . '">';
+ if(is_array($msgParts)){
+ foreach($msgParts as $partName => $partType) {
+ // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'<br>';
+ if (strpos($partType, ':')) {
+ $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType));
+ } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) {
+ // print 'checking typemap: '.$this->XMLSchemaVersion.'<br>';
+ $typePrefix = 'xsd';
+ } else {
+ foreach($this->typemap as $ns => $types) {
+ if (isset($types[$partType])) {
+ $typePrefix = $this->getPrefixFromNamespace($ns);
+ }
+ }
+ if (!isset($typePrefix)) {
+ die("$partType has no namespace!");
+ }
+ }
+ $ns = $this->getNamespaceFromPrefix($typePrefix);
+ $localPart = $this->getLocalPart($partType);
+ $typeDef = $this->getTypeDef($localPart, $ns);
+ if ($typeDef['typeClass'] == 'element') {
+ $elementortype = 'element';
+ if (substr($localPart, -1) == '^') {
+ $localPart = substr($localPart, 0, -1);
+ }
+ } else {
+ $elementortype = 'type';
+ }
+ $xml .= "\n" . ' <part name="' . $partName . '" ' . $elementortype . '="' . $typePrefix . ':' . $localPart . '" />';
+ }
+ }
+ $xml .= '</message>';
+ }
+ }
+ // bindings & porttypes
+ if (count($this->bindings) >= 1) {
+ $binding_xml = '';
+ $portType_xml = '';
+ foreach($this->bindings as $bindingName => $attrs) {
+ $binding_xml .= "\n<binding name=\"" . $bindingName . '" type="tns:' . $attrs['portType'] . '">';
+ $binding_xml .= "\n" . ' <soap:binding style="' . $attrs['style'] . '" transport="' . $attrs['transport'] . '"/>';
+ $portType_xml .= "\n<portType name=\"" . $attrs['portType'] . '">';
+ foreach($attrs['operations'] as $opName => $opParts) {
+ $binding_xml .= "\n" . ' <operation name="' . $opName . '">';
+ $binding_xml .= "\n" . ' <soap:operation soapAction="' . $opParts['soapAction'] . '" style="'. $opParts['style'] . '"/>';
+ if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') {
+ $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"';
+ } else {
+ $enc_style = '';
+ }
+ $binding_xml .= "\n" . ' <input><soap:body use="' . $opParts['input']['use'] . '" namespace="' . $opParts['input']['namespace'] . '"' . $enc_style . '/></input>';
+ if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') {
+ $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"';
+ } else {
+ $enc_style = '';
+ }
+ $binding_xml .= "\n" . ' <output><soap:body use="' . $opParts['output']['use'] . '" namespace="' . $opParts['output']['namespace'] . '"' . $enc_style . '/></output>';
+ $binding_xml .= "\n" . ' </operation>';
+ $portType_xml .= "\n" . ' <operation name="' . $opParts['name'] . '"';
+ if (isset($opParts['parameterOrder'])) {
+ $portType_xml .= ' parameterOrder="' . $opParts['parameterOrder'] . '"';
+ }
+ $portType_xml .= '>';
+ if(isset($opParts['documentation']) && $opParts['documentation'] != '') {
+ $portType_xml .= "\n" . ' <documentation>' . htmlspecialchars($opParts['documentation']) . '</documentation>';
+ }
+ $portType_xml .= "\n" . ' <input message="tns:' . $opParts['input']['message'] . '"/>';
+ $portType_xml .= "\n" . ' <output message="tns:' . $opParts['output']['message'] . '"/>';
+ $portType_xml .= "\n" . ' </operation>';
+ }
+ $portType_xml .= "\n" . '</portType>';
+ $binding_xml .= "\n" . '</binding>';
+ }
+ $xml .= $portType_xml . $binding_xml;
+ }
+ // services
+ $xml .= "\n<service name=\"" . $this->serviceName . '">';
+ if (count($this->ports) >= 1) {
+ foreach($this->ports as $pName => $attrs) {
+ $xml .= "\n" . ' <port name="' . $pName . '" binding="tns:' . $attrs['binding'] . '">';
+ $xml .= "\n" . ' <soap:address location="' . $attrs['location'] . ($debug ? '?debug=1' : '') . '"/>';
+ $xml .= "\n" . ' </port>';
+ }
+ }
+ $xml .= "\n" . '</service>';
+ return $xml . "\n</definitions>";
+ }
+
+ /**
+ * determine whether a set of parameters are unwrapped
+ * when they are expect to be wrapped, Microsoft-style.
+ *
+ * @param string $type the type (element name) of the wrapper
+ * @param array $parameters the parameter values for the SOAP call
+ * @return boolean whether they parameters are unwrapped (and should be wrapped)
+ * @access private
+ */
+ function parametersMatchWrapped($type, &$parameters) {
+ $this->debug("in parametersMatchWrapped type=$type, parameters=");
+ $this->appendDebug($this->varDump($parameters));
+
+ // split type into namespace:unqualified-type
+ if (strpos($type, ':')) {
+ $uqType = substr($type, strrpos($type, ':') + 1);
+ $ns = substr($type, 0, strrpos($type, ':'));
+ $this->debug("in parametersMatchWrapped: got a prefixed type: $uqType, $ns");
+ if ($this->getNamespaceFromPrefix($ns)) {
+ $ns = $this->getNamespaceFromPrefix($ns);
+ $this->debug("in parametersMatchWrapped: expanded prefixed type: $uqType, $ns");
+ }
+ } else {
+ // TODO: should the type be compared to types in XSD, and the namespace
+ // set to XSD if the type matches?
+ $this->debug("in parametersMatchWrapped: No namespace for type $type");
+ $ns = '';
+ $uqType = $type;
+ }
+
+ // get the type information
+ if (!$typeDef = $this->getTypeDef($uqType, $ns)) {
+ $this->debug("in parametersMatchWrapped: $type ($uqType) is not a supported type.");
+ return false;
+ }
+ $this->debug("in parametersMatchWrapped: found typeDef=");
+ $this->appendDebug($this->varDump($typeDef));
+ if (substr($uqType, -1) == '^') {
+ $uqType = substr($uqType, 0, -1);
+ }
+ $phpType = $typeDef['phpType'];
+ $arrayType = (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '');
+ $this->debug("in parametersMatchWrapped: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: $arrayType");
+
+ // we expect a complexType or element of complexType
+ if ($phpType != 'struct') {
+ $this->debug("in parametersMatchWrapped: not a struct");
+ return false;
+ }
+
+ // see whether the parameter names match the elements
+ if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
+ $elements = 0;
+ $matches = 0;
+ foreach ($typeDef['elements'] as $name => $attrs) {
+ if (isset($parameters[$name])) {
+ $this->debug("in parametersMatchWrapped: have parameter named $name");
+ $matches++;
+ } else {
+ $this->debug("in parametersMatchWrapped: do not have parameter named $name");
+ }
+ $elements++;
+ }
+
+ $this->debug("in parametersMatchWrapped: $matches parameter names match $elements wrapped parameter names");
+ if ($matches == 0) {
+ return false;
+ }
+ return true;
+ }
+
+ // since there are no elements for the type, if the user passed no
+ // parameters, the parameters match wrapped.
+ $this->debug("in parametersMatchWrapped: no elements type $ns:$uqType");
+ return count($parameters) == 0;
+ }
+
+ /**
+ * serialize PHP values according to a WSDL message definition
+ * contrary to the method name, this is not limited to RPC
+ *
+ * TODO
+ * - multi-ref serialization
+ * - validate PHP values against type definitions, return errors if invalid
+ *
+ * @param string $operation operation name
+ * @param string $direction (input|output)
+ * @param mixed $parameters parameter value(s)
+ * @param string $bindingType (soap|soap12)
+ * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
+ * @access public
+ */
+ function serializeRPCParameters($operation, $direction, $parameters, $bindingType = 'soap') {
+ $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion, bindingType=$bindingType");
+ $this->appendDebug('parameters=' . $this->varDump($parameters));
+
+ if ($direction != 'input' && $direction != 'output') {
+ $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
+ $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
+ return false;
+ }
+ if (!$opData = $this->getOperationData($operation, $bindingType)) {
+ $this->debug('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
+ $this->setError('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
+ return false;
+ }
+ $this->debug('in serializeRPCParameters: opData:');
+ $this->appendDebug($this->varDump($opData));
+
+ // Get encoding style for output and set to current
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
+ $encodingStyle = $opData['output']['encodingStyle'];
+ $enc_style = $encodingStyle;
+ }
+
+ // set input params
+ $xml = '';
+ if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
+ $parts = &$opData[$direction]['parts'];
+ $part_count = sizeof($parts);
+ $style = $opData['style'];
+ $use = $opData[$direction]['use'];
+ $this->debug("have $part_count part(s) to serialize using $style/$use");
+ if (is_array($parameters)) {
+ $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
+ $parameter_count = count($parameters);
+ $this->debug("have $parameter_count parameter(s) provided as $parametersArrayType to serialize");
+ // check for Microsoft-style wrapped parameters
+ if ($style == 'document' && $use == 'literal' && $part_count == 1 && isset($parts['parameters'])) {
+ $this->debug('check whether the caller has wrapped the parameters');
+ if ($direction == 'output' && $parametersArrayType == 'arraySimple' && $parameter_count == 1) {
+ // TODO: consider checking here for double-wrapping, when
+ // service function wraps, then NuSOAP wraps again
+ $this->debug("change simple array to associative with 'parameters' element");
+ $parameters['parameters'] = $parameters[0];
+ unset($parameters[0]);
+ }
+ if (($parametersArrayType == 'arrayStruct' || $parameter_count == 0) && !isset($parameters['parameters'])) {
+ $this->debug('check whether caller\'s parameters match the wrapped ones');
+ if ($this->parametersMatchWrapped($parts['parameters'], $parameters)) {
+ $this->debug('wrap the parameters for the caller');
+ $parameters = array('parameters' => $parameters);
+ $parameter_count = 1;
+ }
+ }
+ }
+ foreach ($parts as $name => $type) {
+ $this->debug("serializing part $name of type $type");
+ // Track encoding style
+ if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
+ $encodingStyle = $opData[$direction]['encodingStyle'];
+ $enc_style = $encodingStyle;
+ } else {
+ $enc_style = false;
+ }
+ // NOTE: add error handling here
+ // if serializeType returns false, then catch global error and fault
+ if ($parametersArrayType == 'arraySimple') {
+ $p = array_shift($parameters);
+ $this->debug('calling serializeType w/indexed param');
+ $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
+ } elseif (isset($parameters[$name])) {
+ $this->debug('calling serializeType w/named param');
+ $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
+ } else {
+ // TODO: only send nillable
+ $this->debug('calling serializeType w/null param');
+ $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
+ }
+ }
+ } else {
+ $this->debug('no parameters passed.');
+ }
+ }
+ $this->debug("serializeRPCParameters returning: $xml");
+ return $xml;
+ }
+
+ /**
+ * serialize a PHP value according to a WSDL message definition
+ *
+ * TODO
+ * - multi-ref serialization
+ * - validate PHP values against type definitions, return errors if invalid
+ *
+ * @param string $operation operation name
+ * @param string $direction (input|output)
+ * @param mixed $parameters parameter value(s)
+ * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
+ * @access public
+ * @deprecated
+ */
+ function serializeParameters($operation, $direction, $parameters)
+ {
+ $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion");
+ $this->appendDebug('parameters=' . $this->varDump($parameters));
+
+ if ($direction != 'input' && $direction != 'output') {
+ $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
+ $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
+ return false;
+ }
+ if (!$opData = $this->getOperationData($operation)) {
+ $this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
+ $this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
+ return false;
+ }
+ $this->debug('opData:');
+ $this->appendDebug($this->varDump($opData));
+
+ // Get encoding style for output and set to current
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
+ $encodingStyle = $opData['output']['encodingStyle'];
+ $enc_style = $encodingStyle;
+ }
+
+ // set input params
+ $xml = '';
+ if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
+
+ $use = $opData[$direction]['use'];
+ $this->debug("use=$use");
+ $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)');
+ if (is_array($parameters)) {
+ $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
+ $this->debug('have ' . $parametersArrayType . ' parameters');
+ foreach($opData[$direction]['parts'] as $name => $type) {
+ $this->debug('serializing part "'.$name.'" of type "'.$type.'"');
+ // Track encoding style
+ if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
+ $encodingStyle = $opData[$direction]['encodingStyle'];
+ $enc_style = $encodingStyle;
+ } else {
+ $enc_style = false;
+ }
+ // NOTE: add error handling here
+ // if serializeType returns false, then catch global error and fault
+ if ($parametersArrayType == 'arraySimple') {
+ $p = array_shift($parameters);
+ $this->debug('calling serializeType w/indexed param');
+ $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
+ } elseif (isset($parameters[$name])) {
+ $this->debug('calling serializeType w/named param');
+ $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
+ } else {
+ // TODO: only send nillable
+ $this->debug('calling serializeType w/null param');
+ $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
+ }
+ }
+ } else {
+ $this->debug('no parameters passed.');
+ }
+ }
+ $this->debug("serializeParameters returning: $xml");
+ return $xml;
+ }
+
+ /**
+ * serializes a PHP value according a given type definition
+ *
+ * @param string $name name of value (part or element)
+ * @param string $type XML schema type of value (type or element)
+ * @param mixed $value a native PHP value (parameter value)
+ * @param string $use use for part (encoded|literal)
+ * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
+ * @param boolean $unqualified a kludge for what should be XML namespace form handling
+ * @return string value serialized as an XML string
+ * @access private
+ */
+ function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false)
+ {
+ $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified"));
+ $this->appendDebug("value=" . $this->varDump($value));
+ if($use == 'encoded' && $encodingStyle) {
+ $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"';
+ }
+
+ // if a soapval has been supplied, let its type override the WSDL
+ if (is_object($value) && get_class($value) == 'soapval') {
+ if ($value->type_ns) {
+ $type = $value->type_ns . ':' . $value->type;
+ $forceType = true;
+ $this->debug("in serializeType: soapval overrides type to $type");
+ } elseif ($value->type) {
+ $type = $value->type;
+ $forceType = true;
+ $this->debug("in serializeType: soapval overrides type to $type");
+ } else {
+ $forceType = false;
+ $this->debug("in serializeType: soapval does not override type");
+ }
+ $attrs = $value->attributes;
+ $value = $value->value;
+ $this->debug("in serializeType: soapval overrides value to $value");
+ if ($attrs) {
+ if (!is_array($value)) {
+ $value['!'] = $value;
+ }
+ foreach ($attrs as $n => $v) {
+ $value['!' . $n] = $v;
+ }
+ $this->debug("in serializeType: soapval provides attributes");
+ }
+ } else {
+ $forceType = false;
+ }
+
+ $xml = '';
+ if (strpos($type, ':')) {
+ $uqType = substr($type, strrpos($type, ':') + 1);
+ $ns = substr($type, 0, strrpos($type, ':'));
+ $this->debug("in serializeType: got a prefixed type: $uqType, $ns");
+ if ($this->getNamespaceFromPrefix($ns)) {
+ $ns = $this->getNamespaceFromPrefix($ns);
+ $this->debug("in serializeType: expanded prefixed type: $uqType, $ns");
+ }
+
+ if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){
+ $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type');
+ if ($unqualified && $use == 'literal') {
+ $elementNS = " xmlns=\"\"";
+ } else {
+ $elementNS = '';
+ }
+ if (is_null($value)) {
+ if ($use == 'literal') {
+ // TODO: depends on minOccurs
+ $xml = "<$name$elementNS/>";
+ } else {
+ // TODO: depends on nillable, which should be checked before calling this method
+ $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ if ($uqType == 'Array') {
+ // JBoss/Axis does this sometimes
+ return $this->serialize_val($value, $name, false, false, false, false, $use);
+ }
+ if ($uqType == 'boolean') {
+ if ((is_string($value) && $value == 'false') || (! $value)) {
+ $value = 'false';
+ } else {
+ $value = 'true';
+ }
+ }
+ if ($uqType == 'string' && gettype($value) == 'string') {
+ $value = $this->expandEntities($value);
+ }
+ if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') {
+ $value = sprintf("%.0lf", $value);
+ }
+ // it's a scalar
+ // TODO: what about null/nil values?
+ // check type isn't a custom type extending xmlschema namespace
+ if (!$this->getTypeDef($uqType, $ns)) {
+ if ($use == 'literal') {
+ if ($forceType) {
+ $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
+ } else {
+ $xml = "<$name$elementNS>$value</$name>";
+ }
+ } else {
+ $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)');
+ } else if ($ns == 'http://xml.apache.org/xml-soap') {
+ $this->debug('in serializeType: appears to be Apache SOAP type');
+ if ($uqType == 'Map') {
+ $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
+ if (! $tt_prefix) {
+ $this->debug('in serializeType: Add namespace for Apache SOAP type');
+ $tt_prefix = 'ns' . rand(1000, 9999);
+ $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap';
+ // force this to be added to usedNamespaces
+ $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
+ }
+ $contents = '';
+ foreach($value as $k => $v) {
+ $this->debug("serializing map element: key $k, value $v");
+ $contents .= '<item>';
+ $contents .= $this->serialize_val($k,'key',false,false,false,false,$use);
+ $contents .= $this->serialize_val($v,'value',false,false,false,false,$use);
+ $contents .= '</item>';
+ }
+ if ($use == 'literal') {
+ if ($forceType) {
+ $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents</$name>";
+ } else {
+ $xml = "<$name>$contents</$name>";
+ }
+ } else {
+ $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents</$name>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ $this->debug('in serializeType: Apache SOAP type, but only support Map');
+ }
+ } else {
+ // TODO: should the type be compared to types in XSD, and the namespace
+ // set to XSD if the type matches?
+ $this->debug("in serializeType: No namespace for type $type");
+ $ns = '';
+ $uqType = $type;
+ }
+ if(!$typeDef = $this->getTypeDef($uqType, $ns)){
+ $this->setError("$type ($uqType) is not a supported type.");
+ $this->debug("in serializeType: $type ($uqType) is not a supported type.");
+ return false;
+ } else {
+ $this->debug("in serializeType: found typeDef");
+ $this->appendDebug('typeDef=' . $this->varDump($typeDef));
+ if (substr($uqType, -1) == '^') {
+ $uqType = substr($uqType, 0, -1);
+ }
+ }
+ if (!isset($typeDef['phpType'])) {
+ $this->setError("$type ($uqType) has no phpType.");
+ $this->debug("in serializeType: $type ($uqType) has no phpType.");
+ return false;
+ }
+ $phpType = $typeDef['phpType'];
+ $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') );
+ // if php type == struct, map value to the <all> element names
+ if ($phpType == 'struct') {
+ if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') {
+ $elementName = $uqType;
+ if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
+ $elementNS = " xmlns=\"$ns\"";
+ } else {
+ $elementNS = " xmlns=\"\"";
+ }
+ } else {
+ $elementName = $name;
+ if ($unqualified) {
+ $elementNS = " xmlns=\"\"";
+ } else {
+ $elementNS = '';
+ }
+ }
+ if (is_null($value)) {
+ if ($use == 'literal') {
+ // TODO: depends on minOccurs and nillable
+ $xml = "<$elementName$elementNS/>";
+ } else {
+ $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ if (is_object($value)) {
+ $value = get_object_vars($value);
+ }
+ if (is_array($value)) {
+ $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
+ if ($use == 'literal') {
+ if ($forceType) {
+ $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">";
+ } else {
+ $xml = "<$elementName$elementNS$elementAttrs>";
+ }
+ } else {
+ $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>";
+ }
+
+ if (isset($typeDef['simpleContent']) && $typeDef['simpleContent'] == 'true') {
+ if (isset($value['!'])) {
+ $xml .= $value['!'];
+ $this->debug("in serializeType: serialized simpleContent for type $type");
+ } else {
+ $this->debug("in serializeType: no simpleContent to serialize for type $type");
+ }
+ } else {
+ // complexContent
+ $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
+ }
+ $xml .= "</$elementName>";
+ } else {
+ $this->debug("in serializeType: phpType is struct, but value is not an array");
+ $this->setError("phpType is struct, but value is not an array: see debug output for details");
+ $xml = '';
+ }
+ } elseif ($phpType == 'array') {
+ if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
+ $elementNS = " xmlns=\"$ns\"";
+ } else {
+ if ($unqualified) {
+ $elementNS = " xmlns=\"\"";
+ } else {
+ $elementNS = '';
+ }
+ }
+ if (is_null($value)) {
+ if ($use == 'literal') {
+ // TODO: depends on minOccurs
+ $xml = "<$name$elementNS/>";
+ } else {
+ $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" .
+ $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
+ ":Array\" " .
+ $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
+ ':arrayType="' .
+ $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) .
+ ':' .
+ $this->getLocalPart($typeDef['arrayType'])."[0]\"/>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ if (isset($typeDef['multidimensional'])) {
+ $nv = array();
+ foreach($value as $v) {
+ $cols = ',' . sizeof($v);
+ $nv = array_merge($nv, $v);
+ }
+ $value = $nv;
+ } else {
+ $cols = '';
+ }
+ if (is_array($value) && sizeof($value) >= 1) {
+ $rows = sizeof($value);
+ $contents = '';
+ foreach($value as $k => $v) {
+ $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]");
+ //if (strpos($typeDef['arrayType'], ':') ) {
+ if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) {
+ $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use);
+ } else {
+ $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use);
+ }
+ }
+ } else {
+ $rows = 0;
+ $contents = null;
+ }
+ // TODO: for now, an empty value will be serialized as a zero element
+ // array. Revisit this when coding the handling of null/nil values.
+ if ($use == 'literal') {
+ $xml = "<$name$elementNS>"
+ .$contents
+ ."</$name>";
+ } else {
+ $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '.
+ $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/')
+ .':arrayType="'
+ .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType']))
+ .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">"
+ .$contents
+ ."</$name>";
+ }
+ } elseif ($phpType == 'scalar') {
+ if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
+ $elementNS = " xmlns=\"$ns\"";
+ } else {
+ if ($unqualified) {
+ $elementNS = " xmlns=\"\"";
+ } else {
+ $elementNS = '';
+ }
+ }
+ if ($use == 'literal') {
+ if ($forceType) {
+ $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
+ } else {
+ $xml = "<$name$elementNS>$value</$name>";
+ }
+ } else {
+ $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
+ }
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+
+ /**
+ * serializes the attributes for a complexType
+ *
+ * @param array $typeDef our internal representation of an XML schema type (or element)
+ * @param mixed $value a native PHP value (parameter value)
+ * @param string $ns the namespace of the type
+ * @param string $uqType the local part of the type
+ * @return string value serialized as an XML string
+ * @access private
+ */
+ function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) {
+ $this->debug("serializeComplexTypeAttributes for XML Schema type $ns:$uqType");
+ $xml = '';
+ if (isset($typeDef['extensionBase'])) {
+ $nsx = $this->getPrefix($typeDef['extensionBase']);
+ $uqTypex = $this->getLocalPart($typeDef['extensionBase']);
+ if ($this->getNamespaceFromPrefix($nsx)) {
+ $nsx = $this->getNamespaceFromPrefix($nsx);
+ }
+ if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
+ $this->debug("serialize attributes for extension base $nsx:$uqTypex");
+ $xml .= $this->serializeComplexTypeAttributes($typeDefx, $value, $nsx, $uqTypex);
+ } else {
+ $this->debug("extension base $nsx:$uqTypex is not a supported type");
+ }
+ }
+ if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) {
+ $this->debug("serialize attributes for XML Schema type $ns:$uqType");
+ if (is_array($value)) {
+ $xvalue = $value;
+ } elseif (is_object($value)) {
+ $xvalue = get_object_vars($value);
+ } else {
+ $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
+ $xvalue = array();
+ }
+ foreach ($typeDef['attrs'] as $aName => $attrs) {
+ if (isset($xvalue['!' . $aName])) {
+ $xname = '!' . $aName;
+ $this->debug("value provided for attribute $aName with key $xname");
+ } elseif (isset($xvalue[$aName])) {
+ $xname = $aName;
+ $this->debug("value provided for attribute $aName with key $xname");
+ } elseif (isset($attrs['default'])) {
+ $xname = '!' . $aName;
+ $xvalue[$xname] = $attrs['default'];
+ $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName);
+ } else {
+ $xname = '';
+ $this->debug("no value provided for attribute $aName");
+ }
+ if ($xname) {
+ $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\"";
+ }
+ }
+ } else {
+ $this->debug("no attributes to serialize for XML Schema type $ns:$uqType");
+ }
+ return $xml;
+ }
+
+ /**
+ * serializes the elements for a complexType
+ *
+ * @param array $typeDef our internal representation of an XML schema type (or element)
+ * @param mixed $value a native PHP value (parameter value)
+ * @param string $ns the namespace of the type
+ * @param string $uqType the local part of the type
+ * @param string $use use for part (encoded|literal)
+ * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
+ * @return string value serialized as an XML string
+ * @access private
+ */
+ function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) {
+ $this->debug("in serializeComplexTypeElements for XML Schema type $ns:$uqType");
+ $xml = '';
+ if (isset($typeDef['extensionBase'])) {
+ $nsx = $this->getPrefix($typeDef['extensionBase']);
+ $uqTypex = $this->getLocalPart($typeDef['extensionBase']);
+ if ($this->getNamespaceFromPrefix($nsx)) {
+ $nsx = $this->getNamespaceFromPrefix($nsx);
+ }
+ if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
+ $this->debug("serialize elements for extension base $nsx:$uqTypex");
+ $xml .= $this->serializeComplexTypeElements($typeDefx, $value, $nsx, $uqTypex, $use, $encodingStyle);
+ } else {
+ $this->debug("extension base $nsx:$uqTypex is not a supported type");
+ }
+ }
+ if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
+ $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType");
+ if (is_array($value)) {
+ $xvalue = $value;
+ } elseif (is_object($value)) {
+ $xvalue = get_object_vars($value);
+ } else {
+ $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
+ $xvalue = array();
+ }
+ // toggle whether all elements are present - ideally should validate against schema
+ if (count($typeDef['elements']) != count($xvalue)){
+ $optionals = true;
+ }
+ foreach ($typeDef['elements'] as $eName => $attrs) {
+ if (!isset($xvalue[$eName])) {
+ if (isset($attrs['default'])) {
+ $xvalue[$eName] = $attrs['default'];
+ $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName);
+ }
+ }
+ // if user took advantage of a minOccurs=0, then only serialize named parameters
+ if (isset($optionals)
+ && (!isset($xvalue[$eName]))
+ && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true')
+ ){
+ if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') {
+ $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']);
+ }
+ // do nothing
+ $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing");
+ } else {
+ // get value
+ if (isset($xvalue[$eName])) {
+ $v = $xvalue[$eName];
+ } else {
+ $v = null;
+ }
+ if (isset($attrs['form'])) {
+ $unqualified = ($attrs['form'] == 'unqualified');
+ } else {
+ $unqualified = false;
+ }
+ if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') {
+ $vv = $v;
+ foreach ($vv as $k => $v) {
+ if (isset($attrs['type']) || isset($attrs['ref'])) {
+ // serialize schema-defined type
+ $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
+ } else {
+ // serialize generic type (can this ever really happen?)
+ $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
+ $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
+ }
+ }
+ } else {
+ if (is_null($v) && isset($attrs['minOccurs']) && $attrs['minOccurs'] == '0') {
+ // do nothing
+ } elseif (is_null($v) && isset($attrs['nillable']) && $attrs['nillable'] == 'true') {
+ // TODO: serialize a nil correctly, but for now serialize schema-defined type
+ $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
+ } elseif (isset($attrs['type']) || isset($attrs['ref'])) {
+ // serialize schema-defined type
+ $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
+ } else {
+ // serialize generic type (can this ever really happen?)
+ $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
+ $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
+ }
+ }
+ }
+ }
+ } else {
+ $this->debug("no elements to serialize for XML Schema type $ns:$uqType");
+ }
+ return $xml;
+ }
+
+ /**
+ * adds an XML Schema complex type to the WSDL types
+ *
+ * @param string $name
+ * @param string $typeClass (complexType|simpleType|attribute)
+ * @param string $phpType currently supported are array and struct (php assoc array)
+ * @param string $compositor (all|sequence|choice)
+ * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
+ * @param array $elements e.g. array ( name => array(name=>'',type=>'') )
+ * @param array $attrs e.g. array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]'))
+ * @param string $arrayType as namespace:name (xsd:string)
+ * @see nusoap_xmlschema
+ * @access public
+ */
+ function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') {
+ if (count($elements) > 0) {
+ $eElements = array();
+ foreach($elements as $n => $e){
+ // expand each element
+ $ee = array();
+ foreach ($e as $k => $v) {
+ $k = strpos($k,':') ? $this->expandQname($k) : $k;
+ $v = strpos($v,':') ? $this->expandQname($v) : $v;
+ $ee[$k] = $v;
+ }
+ $eElements[$n] = $ee;
+ }
+ $elements = $eElements;
+ }
+
+ if (count($attrs) > 0) {
+ foreach($attrs as $n => $a){
+ // expand each attribute
+ foreach ($a as $k => $v) {
+ $k = strpos($k,':') ? $this->expandQname($k) : $k;
+ $v = strpos($v,':') ? $this->expandQname($v) : $v;
+ $aa[$k] = $v;
+ }
+ $eAttrs[$n] = $aa;
+ }
+ $attrs = $eAttrs;
+ }
+
+ $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
+ $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType;
+
+ $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
+ $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType);
+ }
+
+ /**
+ * adds an XML Schema simple type to the WSDL types
+ *
+ * @param string $name
+ * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
+ * @param string $typeClass (should always be simpleType)
+ * @param string $phpType (should always be scalar)
+ * @param array $enumeration array of values
+ * @see nusoap_xmlschema
+ * @access public
+ */
+ function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
+ $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
+
+ $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
+ $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration);
+ }
+
+ /**
+ * adds an element to the WSDL types
+ *
+ * @param array $attrs attributes that must include name and type
+ * @see nusoap_xmlschema
+ * @access public
+ */
+ function addElement($attrs) {
+ $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
+ $this->schemas[$typens][0]->addElement($attrs);
+ }
+
+ /**
+ * register an operation with the server
+ *
+ * @param string $name operation (method) name
+ * @param array $in assoc array of input values: key = param name, value = param type
+ * @param array $out assoc array of output values: key = param name, value = param type
+ * @param string $namespace optional The namespace for the operation
+ * @param string $soapaction optional The soapaction for the operation
+ * @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically
+ * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now)
+ * @param string $documentation optional The description to include in the WSDL
+ * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
+ * @access public
+ */
+ function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){
+ if ($use == 'encoded' && $encodingStyle == '') {
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ }
+
+ if ($style == 'document') {
+ $elements = array();
+ foreach ($in as $n => $t) {
+ $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
+ }
+ $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements);
+ $this->addElement(array('name' => $name, 'type' => $name . 'RequestType'));
+ $in = array('parameters' => 'tns:' . $name . '^');
+
+ $elements = array();
+ foreach ($out as $n => $t) {
+ $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
+ }
+ $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements);
+ $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType', 'form' => 'qualified'));
+ $out = array('parameters' => 'tns:' . $name . 'Response' . '^');
+ }
+
+ // get binding
+ $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] =
+ array(
+ 'name' => $name,
+ 'binding' => $this->serviceName . 'Binding',
+ 'endpoint' => $this->endpoint,
+ 'soapAction' => $soapaction,
+ 'style' => $style,
+ 'input' => array(
+ 'use' => $use,
+ 'namespace' => $namespace,
+ 'encodingStyle' => $encodingStyle,
+ 'message' => $name . 'Request',
+ 'parts' => $in),
+ 'output' => array(
+ 'use' => $use,
+ 'namespace' => $namespace,
+ 'encodingStyle' => $encodingStyle,
+ 'message' => $name . 'Response',
+ 'parts' => $out),
+ 'namespace' => $namespace,
+ 'transport' => 'http://schemas.xmlsoap.org/soap/http',
+ 'documentation' => $documentation);
+ // add portTypes
+ // add messages
+ if($in)
+ {
+ foreach($in as $pName => $pType)
+ {
+ if(strpos($pType,':')) {
+ $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
+ }
+ $this->messages[$name.'Request'][$pName] = $pType;
+ }
+ } else {
+ $this->messages[$name.'Request']= '0';
+ }
+ if($out)
+ {
+ foreach($out as $pName => $pType)
+ {
+ if(strpos($pType,':')) {
+ $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
+ }
+ $this->messages[$name.'Response'][$pName] = $pType;
+ }
+ } else {
+ $this->messages[$name.'Response']= '0';
+ }
+ return true;
+ }
+}
+
+?>
\ No newline at end of file
--- /dev/null
+<?php
+/*
+The NuSOAP project home is:
+http://sourceforge.net/projects/nusoap/
+
+The primary support for NuSOAP is the mailing list:
+nusoap-general@lists.sourceforge.net
+*/
+
+/**
+* caches instances of the wsdl class
+*
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @author Ingo Fischer <ingo@apollon.de>
+* @version $Id: class.wsdlcache.php,v 1.7 2007/04/17 16:34:03 snichol Exp $
+* @access public
+*/
+class nusoap_wsdlcache {
+ /**
+ * @var resource
+ * @access private
+ */
+ var $fplock;
+ /**
+ * @var integer
+ * @access private
+ */
+ var $cache_lifetime;
+ /**
+ * @var string
+ * @access private
+ */
+ var $cache_dir;
+ /**
+ * @var string
+ * @access public
+ */
+ var $debug_str = '';
+
+ /**
+ * constructor
+ *
+ * @param string $cache_dir directory for cache-files
+ * @param integer $cache_lifetime lifetime for caching-files in seconds or 0 for unlimited
+ * @access public
+ */
+ function nusoap_wsdlcache($cache_dir='.', $cache_lifetime=0) {
+ $this->fplock = array();
+ $this->cache_dir = $cache_dir != '' ? $cache_dir : '.';
+ $this->cache_lifetime = $cache_lifetime;
+ }
+
+ /**
+ * creates the filename used to cache a wsdl instance
+ *
+ * @param string $wsdl The URL of the wsdl instance
+ * @return string The filename used to cache the instance
+ * @access private
+ */
+ function createFilename($wsdl) {
+ return $this->cache_dir.'/wsdlcache-' . md5($wsdl);
+ }
+
+ /**
+ * adds debug data to the class level debug string
+ *
+ * @param string $string debug data
+ * @access private
+ */
+ function debug($string){
+ $this->debug_str .= get_class($this).": $string\n";
+ }
+
+ /**
+ * gets a wsdl instance from the cache
+ *
+ * @param string $wsdl The URL of the wsdl instance
+ * @return object wsdl The cached wsdl instance, null if the instance is not in the cache
+ * @access public
+ */
+ function get($wsdl) {
+ $filename = $this->createFilename($wsdl);
+ if ($this->obtainMutex($filename, "r")) {
+ // check for expired WSDL that must be removed from the cache
+ if ($this->cache_lifetime > 0) {
+ if (file_exists($filename) && (time() - filemtime($filename) > $this->cache_lifetime)) {
+ unlink($filename);
+ $this->debug("Expired $wsdl ($filename) from cache");
+ $this->releaseMutex($filename);
+ return null;
+ }
+ }
+ // see what there is to return
+ if (!file_exists($filename)) {
+ $this->debug("$wsdl ($filename) not in cache (1)");
+ $this->releaseMutex($filename);
+ return null;
+ }
+ $fp = @fopen($filename, "r");
+ if ($fp) {
+ $s = implode("", @file($filename));
+ fclose($fp);
+ $this->debug("Got $wsdl ($filename) from cache");
+ } else {
+ $s = null;
+ $this->debug("$wsdl ($filename) not in cache (2)");
+ }
+ $this->releaseMutex($filename);
+ return (!is_null($s)) ? unserialize($s) : null;
+ } else {
+ $this->debug("Unable to obtain mutex for $filename in get");
+ }
+ return null;
+ }
+
+ /**
+ * obtains the local mutex
+ *
+ * @param string $filename The Filename of the Cache to lock
+ * @param string $mode The open-mode ("r" or "w") or the file - affects lock-mode
+ * @return boolean Lock successfully obtained ?!
+ * @access private
+ */
+ function obtainMutex($filename, $mode) {
+ if (isset($this->fplock[md5($filename)])) {
+ $this->debug("Lock for $filename already exists");
+ return false;
+ }
+ $this->fplock[md5($filename)] = fopen($filename.".lock", "w");
+ if ($mode == "r") {
+ return flock($this->fplock[md5($filename)], LOCK_SH);
+ } else {
+ return flock($this->fplock[md5($filename)], LOCK_EX);
+ }
+ }
+
+ /**
+ * adds a wsdl instance to the cache
+ *
+ * @param object wsdl $wsdl_instance The wsdl instance to add
+ * @return boolean WSDL successfully cached
+ * @access public
+ */
+ function put($wsdl_instance) {
+ $filename = $this->createFilename($wsdl_instance->wsdl);
+ $s = serialize($wsdl_instance);
+ if ($this->obtainMutex($filename, "w")) {
+ $fp = fopen($filename, "w");
+ if (! $fp) {
+ $this->debug("Cannot write $wsdl_instance->wsdl ($filename) in cache");
+ $this->releaseMutex($filename);
+ return false;
+ }
+ fputs($fp, $s);
+ fclose($fp);
+ $this->debug("Put $wsdl_instance->wsdl ($filename) in cache");
+ $this->releaseMutex($filename);
+ return true;
+ } else {
+ $this->debug("Unable to obtain mutex for $filename in put");
+ }
+ return false;
+ }
+
+ /**
+ * releases the local mutex
+ *
+ * @param string $filename The Filename of the Cache to lock
+ * @return boolean Lock successfully released
+ * @access private
+ */
+ function releaseMutex($filename) {
+ $ret = flock($this->fplock[md5($filename)], LOCK_UN);
+ fclose($this->fplock[md5($filename)]);
+ unset($this->fplock[md5($filename)]);
+ if (! $ret) {
+ $this->debug("Not able to release lock for $filename");
+ }
+ return $ret;
+ }
+
+ /**
+ * removes a wsdl instance from the cache
+ *
+ * @param string $wsdl The URL of the wsdl instance
+ * @return boolean Whether there was an instance to remove
+ * @access public
+ */
+ function remove($wsdl) {
+ $filename = $this->createFilename($wsdl);
+ if (!file_exists($filename)) {
+ $this->debug("$wsdl ($filename) not in cache to be removed");
+ return false;
+ }
+ // ignore errors obtaining mutex
+ $this->obtainMutex($filename, "w");
+ $ret = unlink($filename);
+ $this->debug("Removed ($ret) $wsdl ($filename) from cache");
+ $this->releaseMutex($filename);
+ return $ret;
+ }
+}
+
+/**
+ * For backward compatibility
+ */
+class wsdlcache extends nusoap_wsdlcache {
+}
+?>
--- /dev/null
+<?php
+
+
+
+
+/**
+* parses an XML Schema, allows access to it's data, other utility methods.
+* imperfect, no validation... yet, but quite functional.
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: class.xmlschema.php,v 1.53 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_xmlschema extends nusoap_base {
+
+ // files
+ var $schema = '';
+ var $xml = '';
+ // namespaces
+ var $enclosingNamespaces;
+ // schema info
+ var $schemaInfo = array();
+ var $schemaTargetNamespace = '';
+ // types, elements, attributes defined by the schema
+ var $attributes = array();
+ var $complexTypes = array();
+ var $complexTypeStack = array();
+ var $currentComplexType = null;
+ var $elements = array();
+ var $elementStack = array();
+ var $currentElement = null;
+ var $simpleTypes = array();
+ var $simpleTypeStack = array();
+ var $currentSimpleType = null;
+ // imports
+ var $imports = array();
+ // parser vars
+ var $parser;
+ var $position = 0;
+ var $depth = 0;
+ var $depth_array = array();
+ var $message = array();
+ var $defaultNamespace = array();
+
+ /**
+ * constructor
+ *
+ * @param string $schema schema document URI
+ * @param string $xml xml document URI
+ * @param string $namespaces namespaces defined in enclosing XML
+ * @access public
+ */
+ function nusoap_xmlschema($schema='',$xml='',$namespaces=array()){
+ parent::nusoap_base();
+ $this->debug('nusoap_xmlschema class instantiated, inside constructor');
+ // files
+ $this->schema = $schema;
+ $this->xml = $xml;
+
+ // namespaces
+ $this->enclosingNamespaces = $namespaces;
+ $this->namespaces = array_merge($this->namespaces, $namespaces);
+
+ // parse schema file
+ if($schema != ''){
+ $this->debug('initial schema file: '.$schema);
+ $this->parseFile($schema, 'schema');
+ }
+
+ // parse xml file
+ if($xml != ''){
+ $this->debug('initial xml file: '.$xml);
+ $this->parseFile($xml, 'xml');
+ }
+
+ }
+
+ /**
+ * parse an XML file
+ *
+ * @param string $xml path/URL to XML file
+ * @param string $type (schema | xml)
+ * @return boolean
+ * @access public
+ */
+ function parseFile($xml,$type){
+ // parse xml file
+ if($xml != ""){
+ $xmlStr = @join("",@file($xml));
+ if($xmlStr == ""){
+ $msg = 'Error reading XML from '.$xml;
+ $this->setError($msg);
+ $this->debug($msg);
+ return false;
+ } else {
+ $this->debug("parsing $xml");
+ $this->parseString($xmlStr,$type);
+ $this->debug("done parsing $xml");
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * parse an XML string
+ *
+ * @param string $xml path or URL
+ * @param string $type (schema|xml)
+ * @access private
+ */
+ function parseString($xml,$type){
+ // parse xml string
+ if($xml != ""){
+
+ // Create an XML parser.
+ $this->parser = xml_parser_create();
+ // Set the options for parsing the XML data.
+ xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
+
+ // Set the object for the parser.
+ xml_set_object($this->parser, $this);
+
+ // Set the element handlers for the parser.
+ if($type == "schema"){
+ xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement');
+ xml_set_character_data_handler($this->parser,'schemaCharacterData');
+ } elseif($type == "xml"){
+ xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement');
+ xml_set_character_data_handler($this->parser,'xmlCharacterData');
+ }
+
+ // Parse the XML file.
+ if(!xml_parse($this->parser,$xml,true)){
+ // Display an error message.
+ $errstr = sprintf('XML error parsing XML schema on line %d: %s',
+ xml_get_current_line_number($this->parser),
+ xml_error_string(xml_get_error_code($this->parser))
+ );
+ $this->debug($errstr);
+ $this->debug("XML payload:\n" . $xml);
+ $this->setError($errstr);
+ }
+
+ xml_parser_free($this->parser);
+ } else{
+ $this->debug('no xml passed to parseString()!!');
+ $this->setError('no xml passed to parseString()!!');
+ }
+ }
+
+ /**
+ * gets a type name for an unnamed type
+ *
+ * @param string Element name
+ * @return string A type name for an unnamed type
+ * @access private
+ */
+ function CreateTypeName($ename) {
+ $scope = '';
+ for ($i = 0; $i < count($this->complexTypeStack); $i++) {
+ $scope .= $this->complexTypeStack[$i] . '_';
+ }
+ return $scope . $ename . '_ContainedType';
+ }
+
+ /**
+ * start-element handler
+ *
+ * @param string $parser XML parser object
+ * @param string $name element name
+ * @param string $attrs associative array of attributes
+ * @access private
+ */
+ function schemaStartElement($parser, $name, $attrs) {
+
+ // position in the total number of elements, starting from 0
+ $pos = $this->position++;
+ $depth = $this->depth++;
+ // set self as current value for this depth
+ $this->depth_array[$depth] = $pos;
+ $this->message[$pos] = array('cdata' => '');
+ if ($depth > 0) {
+ $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]];
+ } else {
+ $this->defaultNamespace[$pos] = false;
+ }
+
+ // get element prefix
+ if($prefix = $this->getPrefix($name)){
+ // get unqualified name
+ $name = $this->getLocalPart($name);
+ } else {
+ $prefix = '';
+ }
+
+ // loop thru attributes, expanding, and registering namespace declarations
+ if(count($attrs) > 0){
+ foreach($attrs as $k => $v){
+ // if ns declarations, add to class level array of valid namespaces
+ if(preg_match('/^xmlns/',$k)){
+ //$this->xdebug("$k: $v");
+ //$this->xdebug('ns_prefix: '.$this->getPrefix($k));
+ if($ns_prefix = substr(strrchr($k,':'),1)){
+ //$this->xdebug("Add namespace[$ns_prefix] = $v");
+ $this->namespaces[$ns_prefix] = $v;
+ } else {
+ $this->defaultNamespace[$pos] = $v;
+ if (! $this->getPrefixFromNamespace($v)) {
+ $this->namespaces['ns'.(count($this->namespaces)+1)] = $v;
+ }
+ }
+ if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){
+ $this->XMLSchemaVersion = $v;
+ $this->namespaces['xsi'] = $v.'-instance';
+ }
+ }
+ }
+ foreach($attrs as $k => $v){
+ // expand each attribute
+ $k = strpos($k,':') ? $this->expandQname($k) : $k;
+ $v = strpos($v,':') ? $this->expandQname($v) : $v;
+ $eAttrs[$k] = $v;
+ }
+ $attrs = $eAttrs;
+ } else {
+ $attrs = array();
+ }
+ // find status, register data
+ switch($name){
+ case 'all': // (optional) compositor content for a complexType
+ case 'choice':
+ case 'group':
+ case 'sequence':
+ //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement");
+ $this->complexTypes[$this->currentComplexType]['compositor'] = $name;
+ //if($name == 'all' || $name == 'sequence'){
+ // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
+ //}
+ break;
+ case 'attribute': // complexType attribute
+ //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']);
+ $this->xdebug("parsing attribute:");
+ $this->appendDebug($this->varDump($attrs));
+ if (!isset($attrs['form'])) {
+ // TODO: handle globals
+ $attrs['form'] = $this->schemaInfo['attributeFormDefault'];
+ }
+ if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
+ $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
+ if (!strpos($v, ':')) {
+ // no namespace in arrayType attribute value...
+ if ($this->defaultNamespace[$pos]) {
+ // ...so use the default
+ $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
+ }
+ }
+ }
+ if(isset($attrs['name'])){
+ $this->attributes[$attrs['name']] = $attrs;
+ $aname = $attrs['name'];
+ } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){
+ if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
+ $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
+ } else {
+ $aname = '';
+ }
+ } elseif(isset($attrs['ref'])){
+ $aname = $attrs['ref'];
+ $this->attributes[$attrs['ref']] = $attrs;
+ }
+
+ if($this->currentComplexType){ // This should *always* be
+ $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs;
+ }
+ // arrayType attribute
+ if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
+ $prefix = $this->getPrefix($aname);
+ if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){
+ $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
+ } else {
+ $v = '';
+ }
+ if(strpos($v,'[,]')){
+ $this->complexTypes[$this->currentComplexType]['multidimensional'] = true;
+ }
+ $v = substr($v,0,strpos($v,'[')); // clip the []
+ if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){
+ $v = $this->XMLSchemaVersion.':'.$v;
+ }
+ $this->complexTypes[$this->currentComplexType]['arrayType'] = $v;
+ }
+ break;
+ case 'complexContent': // (optional) content for a complexType
+ $this->xdebug("do nothing for element $name");
+ break;
+ case 'complexType':
+ array_push($this->complexTypeStack, $this->currentComplexType);
+ if(isset($attrs['name'])){
+ // TODO: what is the scope of named complexTypes that appear
+ // nested within other c complexTypes?
+ $this->xdebug('processing named complexType '.$attrs['name']);
+ //$this->currentElement = false;
+ $this->currentComplexType = $attrs['name'];
+ $this->complexTypes[$this->currentComplexType] = $attrs;
+ $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
+ // This is for constructs like
+ // <complexType name="ListOfString" base="soap:Array">
+ // <sequence>
+ // <element name="string" type="xsd:string"
+ // minOccurs="0" maxOccurs="unbounded" />
+ // </sequence>
+ // </complexType>
+ if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){
+ $this->xdebug('complexType is unusual array');
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
+ } else {
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
+ }
+ } else {
+ $name = $this->CreateTypeName($this->currentElement);
+ $this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name);
+ $this->currentComplexType = $name;
+ //$this->currentElement = false;
+ $this->complexTypes[$this->currentComplexType] = $attrs;
+ $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
+ // This is for constructs like
+ // <complexType name="ListOfString" base="soap:Array">
+ // <sequence>
+ // <element name="string" type="xsd:string"
+ // minOccurs="0" maxOccurs="unbounded" />
+ // </sequence>
+ // </complexType>
+ if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){
+ $this->xdebug('complexType is unusual array');
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
+ } else {
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
+ }
+ }
+ $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'false';
+ break;
+ case 'element':
+ array_push($this->elementStack, $this->currentElement);
+ if (!isset($attrs['form'])) {
+ if ($this->currentComplexType) {
+ $attrs['form'] = $this->schemaInfo['elementFormDefault'];
+ } else {
+ // global
+ $attrs['form'] = 'qualified';
+ }
+ }
+ if(isset($attrs['type'])){
+ $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']);
+ if (! $this->getPrefix($attrs['type'])) {
+ if ($this->defaultNamespace[$pos]) {
+ $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type'];
+ $this->xdebug('used default namespace to make type ' . $attrs['type']);
+ }
+ }
+ // This is for constructs like
+ // <complexType name="ListOfString" base="soap:Array">
+ // <sequence>
+ // <element name="string" type="xsd:string"
+ // minOccurs="0" maxOccurs="unbounded" />
+ // </sequence>
+ // </complexType>
+ if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') {
+ $this->xdebug('arrayType for unusual array is ' . $attrs['type']);
+ $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type'];
+ }
+ $this->currentElement = $attrs['name'];
+ $ename = $attrs['name'];
+ } elseif(isset($attrs['ref'])){
+ $this->xdebug("processing element as ref to ".$attrs['ref']);
+ $this->currentElement = "ref to ".$attrs['ref'];
+ $ename = $this->getLocalPart($attrs['ref']);
+ } else {
+ $type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']);
+ $this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type);
+ $this->currentElement = $attrs['name'];
+ $attrs['type'] = $this->schemaTargetNamespace . ':' . $type;
+ $ename = $attrs['name'];
+ }
+ if (isset($ename) && $this->currentComplexType) {
+ $this->xdebug("add element $ename to complexType $this->currentComplexType");
+ $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs;
+ } elseif (!isset($attrs['ref'])) {
+ $this->xdebug("add element $ename to elements array");
+ $this->elements[ $attrs['name'] ] = $attrs;
+ $this->elements[ $attrs['name'] ]['typeClass'] = 'element';
+ }
+ break;
+ case 'enumeration': // restriction value list member
+ $this->xdebug('enumeration ' . $attrs['value']);
+ if ($this->currentSimpleType) {
+ $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value'];
+ } elseif ($this->currentComplexType) {
+ $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value'];
+ }
+ break;
+ case 'extension': // simpleContent or complexContent type extension
+ $this->xdebug('extension ' . $attrs['base']);
+ if ($this->currentComplexType) {
+ $ns = $this->getPrefix($attrs['base']);
+ if ($ns == '') {
+ $this->complexTypes[$this->currentComplexType]['extensionBase'] = $this->schemaTargetNamespace . ':' . $attrs['base'];
+ } else {
+ $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base'];
+ }
+ } else {
+ $this->xdebug('no current complexType to set extensionBase');
+ }
+ break;
+ case 'import':
+ if (isset($attrs['schemaLocation'])) {
+ $this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']);
+ $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
+ } else {
+ $this->xdebug('import namespace ' . $attrs['namespace']);
+ $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
+ if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
+ $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
+ }
+ }
+ break;
+ case 'include':
+ if (isset($attrs['schemaLocation'])) {
+ $this->xdebug('include into namespace ' . $this->schemaTargetNamespace . ' from ' . $attrs['schemaLocation']);
+ $this->imports[$this->schemaTargetNamespace][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
+ } else {
+ $this->xdebug('ignoring invalid XML Schema construct: include without schemaLocation attribute');
+ }
+ break;
+ case 'list': // simpleType value list
+ $this->xdebug("do nothing for element $name");
+ break;
+ case 'restriction': // simpleType, simpleContent or complexContent value restriction
+ $this->xdebug('restriction ' . $attrs['base']);
+ if($this->currentSimpleType){
+ $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base'];
+ } elseif($this->currentComplexType){
+ $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base'];
+ if(strstr($attrs['base'],':') == ':Array'){
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
+ }
+ }
+ break;
+ case 'schema':
+ $this->schemaInfo = $attrs;
+ $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix);
+ if (isset($attrs['targetNamespace'])) {
+ $this->schemaTargetNamespace = $attrs['targetNamespace'];
+ }
+ if (!isset($attrs['elementFormDefault'])) {
+ $this->schemaInfo['elementFormDefault'] = 'unqualified';
+ }
+ if (!isset($attrs['attributeFormDefault'])) {
+ $this->schemaInfo['attributeFormDefault'] = 'unqualified';
+ }
+ break;
+ case 'simpleContent': // (optional) content for a complexType
+ if ($this->currentComplexType) { // This should *always* be
+ $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'true';
+ } else {
+ $this->xdebug("do nothing for element $name because there is no current complexType");
+ }
+ break;
+ case 'simpleType':
+ array_push($this->simpleTypeStack, $this->currentSimpleType);
+ if(isset($attrs['name'])){
+ $this->xdebug("processing simpleType for name " . $attrs['name']);
+ $this->currentSimpleType = $attrs['name'];
+ $this->simpleTypes[ $attrs['name'] ] = $attrs;
+ $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType';
+ $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar';
+ } else {
+ $name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement);
+ $this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name);
+ $this->currentSimpleType = $name;
+ //$this->currentElement = false;
+ $this->simpleTypes[$this->currentSimpleType] = $attrs;
+ $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar';
+ }
+ break;
+ case 'union': // simpleType type list
+ $this->xdebug("do nothing for element $name");
+ break;
+ default:
+ $this->xdebug("do not have any logic to process element $name");
+ }
+ }
+
+ /**
+ * end-element handler
+ *
+ * @param string $parser XML parser object
+ * @param string $name element name
+ * @access private
+ */
+ function schemaEndElement($parser, $name) {
+ // bring depth down a notch
+ $this->depth--;
+ // position of current element is equal to the last value left in depth_array for my depth
+ if(isset($this->depth_array[$this->depth])){
+ $pos = $this->depth_array[$this->depth];
+ }
+ // get element prefix
+ if ($prefix = $this->getPrefix($name)){
+ // get unqualified name
+ $name = $this->getLocalPart($name);
+ } else {
+ $prefix = '';
+ }
+ // move on...
+ if($name == 'complexType'){
+ $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)'));
+ $this->xdebug($this->varDump($this->complexTypes[$this->currentComplexType]));
+ $this->currentComplexType = array_pop($this->complexTypeStack);
+ //$this->currentElement = false;
+ }
+ if($name == 'element'){
+ $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)'));
+ $this->currentElement = array_pop($this->elementStack);
+ }
+ if($name == 'simpleType'){
+ $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)'));
+ $this->xdebug($this->varDump($this->simpleTypes[$this->currentSimpleType]));
+ $this->currentSimpleType = array_pop($this->simpleTypeStack);
+ }
+ }
+
+ /**
+ * element content handler
+ *
+ * @param string $parser XML parser object
+ * @param string $data element content
+ * @access private
+ */
+ function schemaCharacterData($parser, $data){
+ $pos = $this->depth_array[$this->depth - 1];
+ $this->message[$pos]['cdata'] .= $data;
+ }
+
+ /**
+ * serialize the schema
+ *
+ * @access public
+ */
+ function serializeSchema(){
+
+ $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion);
+ $xml = '';
+ // imports
+ if (sizeof($this->imports) > 0) {
+ foreach($this->imports as $ns => $list) {
+ foreach ($list as $ii) {
+ if ($ii['location'] != '') {
+ $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n";
+ } else {
+ $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n";
+ }
+ }
+ }
+ }
+ // complex types
+ foreach($this->complexTypes as $typeName => $attrs){
+ $contentStr = '';
+ // serialize child elements
+ if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){
+ foreach($attrs['elements'] as $element => $eParts){
+ if(isset($eParts['ref'])){
+ $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n";
+ } else {
+ $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\"";
+ foreach ($eParts as $aName => $aValue) {
+ // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable
+ if ($aName != 'name' && $aName != 'type') {
+ $contentStr .= " $aName=\"$aValue\"";
+ }
+ }
+ $contentStr .= "/>\n";
+ }
+ }
+ // compositor wraps elements
+ if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) {
+ $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." </$schemaPrefix:$attrs[compositor]>\n";
+ }
+ }
+ // attributes
+ if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){
+ foreach($attrs['attrs'] as $attr => $aParts){
+ $contentStr .= " <$schemaPrefix:attribute";
+ foreach ($aParts as $a => $v) {
+ if ($a == 'ref' || $a == 'type') {
+ $contentStr .= " $a=\"".$this->contractQName($v).'"';
+ } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') {
+ $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl'];
+ $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"';
+ } else {
+ $contentStr .= " $a=\"$v\"";
+ }
+ }
+ $contentStr .= "/>\n";
+ }
+ }
+ // if restriction
+ if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){
+ $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." </$schemaPrefix:restriction>\n";
+ // complex or simple content
+ if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){
+ $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." </$schemaPrefix:complexContent>\n";
+ }
+ }
+ // finalize complex type
+ if($contentStr != ''){
+ $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." </$schemaPrefix:complexType>\n";
+ } else {
+ $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n";
+ }
+ $xml .= $contentStr;
+ }
+ // simple types
+ if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){
+ foreach($this->simpleTypes as $typeName => $eParts){
+ $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\">\n";
+ if (isset($eParts['enumeration'])) {
+ foreach ($eParts['enumeration'] as $e) {
+ $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n";
+ }
+ }
+ $xml .= " </$schemaPrefix:restriction>\n </$schemaPrefix:simpleType>";
+ }
+ }
+ // elements
+ if(isset($this->elements) && count($this->elements) > 0){
+ foreach($this->elements as $element => $eParts){
+ $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n";
+ }
+ }
+ // attributes
+ if(isset($this->attributes) && count($this->attributes) > 0){
+ foreach($this->attributes as $attr => $aParts){
+ $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>";
+ }
+ }
+ // finish 'er up
+ $attr = '';
+ foreach ($this->schemaInfo as $k => $v) {
+ if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') {
+ $attr .= " $k=\"$v\"";
+ }
+ }
+ $el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n";
+ foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) {
+ $el .= " xmlns:$nsp=\"$ns\"";
+ }
+ $xml = $el . ">\n".$xml."</$schemaPrefix:schema>\n";
+ return $xml;
+ }
+
+ /**
+ * adds debug data to the clas level debug string
+ *
+ * @param string $string debug data
+ * @access private
+ */
+ function xdebug($string){
+ $this->debug('<' . $this->schemaTargetNamespace . '> '.$string);
+ }
+
+ /**
+ * get the PHP type of a user defined type in the schema
+ * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays
+ * returns false if no type exists, or not w/ the given namespace
+ * else returns a string that is either a native php type, or 'struct'
+ *
+ * @param string $type name of defined type
+ * @param string $ns namespace of type
+ * @return mixed
+ * @access public
+ * @deprecated
+ */
+ function getPHPType($type,$ns){
+ if(isset($this->typemap[$ns][$type])){
+ //print "found type '$type' and ns $ns in typemap<br>";
+ return $this->typemap[$ns][$type];
+ } elseif(isset($this->complexTypes[$type])){
+ //print "getting type '$type' and ns $ns from complexTypes array<br>";
+ return $this->complexTypes[$type]['phpType'];
+ }
+ return false;
+ }
+
+ /**
+ * returns an associative array of information about a given type
+ * returns false if no type exists by the given name
+ *
+ * For a complexType typeDef = array(
+ * 'restrictionBase' => '',
+ * 'phpType' => '',
+ * 'compositor' => '(sequence|all)',
+ * 'elements' => array(), // refs to elements array
+ * 'attrs' => array() // refs to attributes array
+ * ... and so on (see addComplexType)
+ * )
+ *
+ * For simpleType or element, the array has different keys.
+ *
+ * @param string $type
+ * @return mixed
+ * @access public
+ * @see addComplexType
+ * @see addSimpleType
+ * @see addElement
+ */
+ function getTypeDef($type){
+ //$this->debug("in getTypeDef for type $type");
+ if (substr($type, -1) == '^') {
+ $is_element = 1;
+ $type = substr($type, 0, -1);
+ } else {
+ $is_element = 0;
+ }
+
+ if((! $is_element) && isset($this->complexTypes[$type])){
+ $this->xdebug("in getTypeDef, found complexType $type");
+ return $this->complexTypes[$type];
+ } elseif((! $is_element) && isset($this->simpleTypes[$type])){
+ $this->xdebug("in getTypeDef, found simpleType $type");
+ if (!isset($this->simpleTypes[$type]['phpType'])) {
+ // get info for type to tack onto the simple type
+ // TODO: can this ever really apply (i.e. what is a simpleType really?)
+ $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1);
+ $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':'));
+ $etype = $this->getTypeDef($uqType);
+ if ($etype) {
+ $this->xdebug("in getTypeDef, found type for simpleType $type:");
+ $this->xdebug($this->varDump($etype));
+ if (isset($etype['phpType'])) {
+ $this->simpleTypes[$type]['phpType'] = $etype['phpType'];
+ }
+ if (isset($etype['elements'])) {
+ $this->simpleTypes[$type]['elements'] = $etype['elements'];
+ }
+ }
+ }
+ return $this->simpleTypes[$type];
+ } elseif(isset($this->elements[$type])){
+ $this->xdebug("in getTypeDef, found element $type");
+ if (!isset($this->elements[$type]['phpType'])) {
+ // get info for type to tack onto the element
+ $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1);
+ $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':'));
+ $etype = $this->getTypeDef($uqType);
+ if ($etype) {
+ $this->xdebug("in getTypeDef, found type for element $type:");
+ $this->xdebug($this->varDump($etype));
+ if (isset($etype['phpType'])) {
+ $this->elements[$type]['phpType'] = $etype['phpType'];
+ }
+ if (isset($etype['elements'])) {
+ $this->elements[$type]['elements'] = $etype['elements'];
+ }
+ if (isset($etype['extensionBase'])) {
+ $this->elements[$type]['extensionBase'] = $etype['extensionBase'];
+ }
+ } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') {
+ $this->xdebug("in getTypeDef, element $type is an XSD type");
+ $this->elements[$type]['phpType'] = 'scalar';
+ }
+ }
+ return $this->elements[$type];
+ } elseif(isset($this->attributes[$type])){
+ $this->xdebug("in getTypeDef, found attribute $type");
+ return $this->attributes[$type];
+ } elseif (preg_match('/_ContainedType$/', $type)) {
+ $this->xdebug("in getTypeDef, have an untyped element $type");
+ $typeDef['typeClass'] = 'simpleType';
+ $typeDef['phpType'] = 'scalar';
+ $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string';
+ return $typeDef;
+ }
+ $this->xdebug("in getTypeDef, did not find $type");
+ return false;
+ }
+
+ /**
+ * returns a sample serialization of a given type, or false if no type by the given name
+ *
+ * @param string $type name of type
+ * @return mixed
+ * @access public
+ * @deprecated
+ */
+ function serializeTypeDef($type){
+ //print "in sTD() for type $type<br>";
+ if($typeDef = $this->getTypeDef($type)){
+ $str .= '<'.$type;
+ if(is_array($typeDef['attrs'])){
+ foreach($typeDef['attrs'] as $attName => $data){
+ $str .= " $attName=\"{type = ".$data['type']."}\"";
+ }
+ }
+ $str .= " xmlns=\"".$this->schema['targetNamespace']."\"";
+ if(count($typeDef['elements']) > 0){
+ $str .= ">";
+ foreach($typeDef['elements'] as $element => $eData){
+ $str .= $this->serializeTypeDef($element);
+ }
+ $str .= "</$type>";
+ } elseif($typeDef['typeClass'] == 'element') {
+ $str .= "></$type>";
+ } else {
+ $str .= "/>";
+ }
+ return $str;
+ }
+ return false;
+ }
+
+ /**
+ * returns HTML form elements that allow a user
+ * to enter values for creating an instance of the given type.
+ *
+ * @param string $name name for type instance
+ * @param string $type name of type
+ * @return string
+ * @access public
+ * @deprecated
+ */
+ function typeToForm($name,$type){
+ // get typedef
+ if($typeDef = $this->getTypeDef($type)){
+ // if struct
+ if($typeDef['phpType'] == 'struct'){
+ $buffer .= '<table>';
+ foreach($typeDef['elements'] as $child => $childDef){
+ $buffer .= "
+ <tr><td align='right'>$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):</td>
+ <td><input type='text' name='parameters[".$name."][$childDef[name]]'></td></tr>";
+ }
+ $buffer .= '</table>';
+ // if array
+ } elseif($typeDef['phpType'] == 'array'){
+ $buffer .= '<table>';
+ for($i=0;$i < 3; $i++){
+ $buffer .= "
+ <tr><td align='right'>array item (type: $typeDef[arrayType]):</td>
+ <td><input type='text' name='parameters[".$name."][]'></td></tr>";
+ }
+ $buffer .= '</table>';
+ // if scalar
+ } else {
+ $buffer .= "<input type='text' name='parameters[$name]'>";
+ }
+ } else {
+ $buffer .= "<input type='text' name='parameters[$name]'>";
+ }
+ return $buffer;
+ }
+
+ /**
+ * adds a complex type to the schema
+ *
+ * example: array
+ *
+ * addType(
+ * 'ArrayOfstring',
+ * 'complexType',
+ * 'array',
+ * '',
+ * 'SOAP-ENC:Array',
+ * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'),
+ * 'xsd:string'
+ * );
+ *
+ * example: PHP associative array ( SOAP Struct )
+ *
+ * addType(
+ * 'SOAPStruct',
+ * 'complexType',
+ * 'struct',
+ * 'all',
+ * array('myVar'=> array('name'=>'myVar','type'=>'string')
+ * );
+ *
+ * @param name
+ * @param typeClass (complexType|simpleType|attribute)
+ * @param phpType: currently supported are array and struct (php assoc array)
+ * @param compositor (all|sequence|choice)
+ * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
+ * @param elements = array ( name = array(name=>'',type=>'') )
+ * @param attrs = array(
+ * array(
+ * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType",
+ * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]"
+ * )
+ * )
+ * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string)
+ * @access public
+ * @see getTypeDef
+ */
+ function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){
+ $this->complexTypes[$name] = array(
+ 'name' => $name,
+ 'typeClass' => $typeClass,
+ 'phpType' => $phpType,
+ 'compositor'=> $compositor,
+ 'restrictionBase' => $restrictionBase,
+ 'elements' => $elements,
+ 'attrs' => $attrs,
+ 'arrayType' => $arrayType
+ );
+
+ $this->xdebug("addComplexType $name:");
+ $this->appendDebug($this->varDump($this->complexTypes[$name]));
+ }
+
+ /**
+ * adds a simple type to the schema
+ *
+ * @param string $name
+ * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
+ * @param string $typeClass (should always be simpleType)
+ * @param string $phpType (should always be scalar)
+ * @param array $enumeration array of values
+ * @access public
+ * @see nusoap_xmlschema
+ * @see getTypeDef
+ */
+ function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
+ $this->simpleTypes[$name] = array(
+ 'name' => $name,
+ 'typeClass' => $typeClass,
+ 'phpType' => $phpType,
+ 'type' => $restrictionBase,
+ 'enumeration' => $enumeration
+ );
+
+ $this->xdebug("addSimpleType $name:");
+ $this->appendDebug($this->varDump($this->simpleTypes[$name]));
+ }
+
+ /**
+ * adds an element to the schema
+ *
+ * @param array $attrs attributes that must include name and type
+ * @see nusoap_xmlschema
+ * @access public
+ */
+ function addElement($attrs) {
+ if (! $this->getPrefix($attrs['type'])) {
+ $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type'];
+ }
+ $this->elements[ $attrs['name'] ] = $attrs;
+ $this->elements[ $attrs['name'] ]['typeClass'] = 'element';
+
+ $this->xdebug("addElement " . $attrs['name']);
+ $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ]));
+ }
+}
+
+/**
+ * Backward compatibility
+ */
+class XMLSchema extends nusoap_xmlschema {
+}
+
+
+?>
\ No newline at end of file
--- /dev/null
+<?php
+
+/*
+$Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+
+NuSOAP - Web Services Toolkit for PHP
+
+Copyright (c) 2002 NuSphere Corporation
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+The NuSOAP project home is:
+http://sourceforge.net/projects/nusoap/
+
+The primary support for NuSOAP is the Help forum on the project home page.
+
+If you have any questions or comments, please email:
+
+Dietrich Ayala
+dietrich@ganx4.com
+http://dietrich.ganx4.com/nusoap
+
+NuSphere Corporation
+http://www.nusphere.com
+
+*/
+
+/*
+ * Some of the standards implmented in whole or part by NuSOAP:
+ *
+ * SOAP 1.1 (http://www.w3.org/TR/2000/NOTE-SOAP-20000508/)
+ * WSDL 1.1 (http://www.w3.org/TR/2001/NOTE-wsdl-20010315)
+ * SOAP Messages With Attachments (http://www.w3.org/TR/SOAP-attachments)
+ * XML 1.0 (http://www.w3.org/TR/2006/REC-xml-20060816/)
+ * Namespaces in XML 1.0 (http://www.w3.org/TR/2006/REC-xml-names-20060816/)
+ * XML Schema 1.0 (http://www.w3.org/TR/xmlschema-0/)
+ * RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies
+ * RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1
+ * RFC 2617 HTTP Authentication: Basic and Digest Access Authentication
+ */
+
+/* load classes
+
+// necessary classes
+require_once('class.soapclient.php');
+require_once('class.soap_val.php');
+require_once('class.soap_parser.php');
+require_once('class.soap_fault.php');
+
+// transport classes
+require_once('class.soap_transport_http.php');
+
+// optional add-on classes
+require_once('class.xmlschema.php');
+require_once('class.wsdl.php');
+
+// server class
+require_once('class.soap_server.php');*/
+
+// class variable emulation
+// cf. http://www.webkreator.com/php/techniques/php-static-class-variables.html
+$GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = 9;
+
+/**
+*
+* nusoap_base
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_base {
+ /**
+ * Identification for HTTP headers.
+ *
+ * @var string
+ * @access private
+ */
+ var $title = 'NuSOAP';
+ /**
+ * Version for HTTP headers.
+ *
+ * @var string
+ * @access private
+ */
+ var $version = '0.9.5';
+ /**
+ * CVS revision for HTTP headers.
+ *
+ * @var string
+ * @access private
+ */
+ var $revision = '$Revision: 1.123 $';
+ /**
+ * Current error string (manipulated by getError/setError)
+ *
+ * @var string
+ * @access private
+ */
+ var $error_str = '';
+ /**
+ * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment)
+ *
+ * @var string
+ * @access private
+ */
+ var $debug_str = '';
+ /**
+ * toggles automatic encoding of special characters as entities
+ * (should always be true, I think)
+ *
+ * @var boolean
+ * @access private
+ */
+ var $charencoding = true;
+ /**
+ * the debug level for this instance
+ *
+ * @var integer
+ * @access private
+ */
+ var $debugLevel;
+
+ /**
+ * set schema version
+ *
+ * @var string
+ * @access public
+ */
+ var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema';
+
+ /**
+ * charset encoding for outgoing messages
+ *
+ * @var string
+ * @access public
+ */
+ var $soap_defencoding = 'ISO-8859-1';
+ //var $soap_defencoding = 'UTF-8';
+
+ /**
+ * namespaces in an array of prefix => uri
+ *
+ * this is "seeded" by a set of constants, but it may be altered by code
+ *
+ * @var array
+ * @access public
+ */
+ var $namespaces = array(
+ 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/',
+ 'xsd' => 'http://www.w3.org/2001/XMLSchema',
+ 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
+ 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/'
+ );
+
+ /**
+ * namespaces used in the current context, e.g. during serialization
+ *
+ * @var array
+ * @access private
+ */
+ var $usedNamespaces = array();
+
+ /**
+ * XML Schema types in an array of uri => (array of xml type => php type)
+ * is this legacy yet?
+ * no, this is used by the nusoap_xmlschema class to verify type => namespace mappings.
+ * @var array
+ * @access public
+ */
+ var $typemap = array(
+ 'http://www.w3.org/2001/XMLSchema' => array(
+ 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double',
+ 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'',
+ 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string',
+ // abstract "any" types
+ 'anyType'=>'string','anySimpleType'=>'string',
+ // derived datatypes
+ 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'',
+ 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer',
+ 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer',
+ 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''),
+ 'http://www.w3.org/2000/10/XMLSchema' => array(
+ 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
+ 'float'=>'double','dateTime'=>'string',
+ 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
+ 'http://www.w3.org/1999/XMLSchema' => array(
+ 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
+ 'float'=>'double','dateTime'=>'string',
+ 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
+ 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'),
+ 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'),
+ 'http://xml.apache.org/xml-soap' => array('Map')
+ );
+
+ /**
+ * XML entities to convert
+ *
+ * @var array
+ * @access public
+ * @deprecated
+ * @see expandEntities
+ */
+ var $xmlEntities = array('quot' => '"','amp' => '&',
+ 'lt' => '<','gt' => '>','apos' => "'");
+
+ /**
+ * constructor
+ *
+ * @access public
+ */
+ function nusoap_base() {
+ $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'];
+ }
+
+ /**
+ * gets the global debug level, which applies to future instances
+ *
+ * @return integer Debug level 0-9, where 0 turns off
+ * @access public
+ */
+ function getGlobalDebugLevel() {
+ return $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'];
+ }
+
+ /**
+ * sets the global debug level, which applies to future instances
+ *
+ * @param int $level Debug level 0-9, where 0 turns off
+ * @access public
+ */
+ function setGlobalDebugLevel($level) {
+ $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = $level;
+ }
+
+ /**
+ * gets the debug level for this instance
+ *
+ * @return int Debug level 0-9, where 0 turns off
+ * @access public
+ */
+ function getDebugLevel() {
+ return $this->debugLevel;
+ }
+
+ /**
+ * sets the debug level for this instance
+ *
+ * @param int $level Debug level 0-9, where 0 turns off
+ * @access public
+ */
+ function setDebugLevel($level) {
+ $this->debugLevel = $level;
+ }
+
+ /**
+ * adds debug data to the instance debug string with formatting
+ *
+ * @param string $string debug data
+ * @access private
+ */
+ function debug($string){
+ if ($this->debugLevel > 0) {
+ $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n");
+ }
+ }
+
+ /**
+ * adds debug data to the instance debug string without formatting
+ *
+ * @param string $string debug data
+ * @access public
+ */
+ function appendDebug($string){
+ if ($this->debugLevel > 0) {
+ // it would be nice to use a memory stream here to use
+ // memory more efficiently
+ $this->debug_str .= $string;
+ }
+ }
+
+ /**
+ * clears the current debug data for this instance
+ *
+ * @access public
+ */
+ function clearDebug() {
+ // it would be nice to use a memory stream here to use
+ // memory more efficiently
+ $this->debug_str = '';
+ }
+
+ /**
+ * gets the current debug data for this instance
+ *
+ * @return debug data
+ * @access public
+ */
+ function &getDebug() {
+ // it would be nice to use a memory stream here to use
+ // memory more efficiently
+ return $this->debug_str;
+ }
+
+ /**
+ * gets the current debug data for this instance as an XML comment
+ * this may change the contents of the debug data
+ *
+ * @return debug data as an XML comment
+ * @access public
+ */
+ function &getDebugAsXMLComment() {
+ // it would be nice to use a memory stream here to use
+ // memory more efficiently
+ while (strpos($this->debug_str, '--')) {
+ $this->debug_str = str_replace('--', '- -', $this->debug_str);
+ }
+ $ret = "<!--\n" . $this->debug_str . "\n-->";
+ return $ret;
+ }
+
+ /**
+ * expands entities, e.g. changes '<' to '<'.
+ *
+ * @param string $val The string in which to expand entities.
+ * @access private
+ */
+ function expandEntities($val) {
+ if ($this->charencoding) {
+ $val = str_replace('&', '&', $val);
+ $val = str_replace("'", ''', $val);
+ $val = str_replace('"', '"', $val);
+ $val = str_replace('<', '<', $val);
+ $val = str_replace('>', '>', $val);
+ }
+ return $val;
+ }
+
+ /**
+ * returns error string if present
+ *
+ * @return mixed error string or false
+ * @access public
+ */
+ function getError(){
+ if($this->error_str != ''){
+ return $this->error_str;
+ }
+ return false;
+ }
+
+ /**
+ * sets error string
+ *
+ * @return boolean $string error string
+ * @access private
+ */
+ function setError($str){
+ $this->error_str = $str;
+ }
+
+ /**
+ * detect if array is a simple array or a struct (associative array)
+ *
+ * @param mixed $val The PHP array
+ * @return string (arraySimple|arrayStruct)
+ * @access private
+ */
+ function isArraySimpleOrStruct($val) {
+ $keyList = array_keys($val);
+ foreach ($keyList as $keyListValue) {
+ if (!is_int($keyListValue)) {
+ return 'arrayStruct';
+ }
+ }
+ return 'arraySimple';
+ }
+
+ /**
+ * serializes PHP values in accordance w/ section 5. Type information is
+ * not serialized if $use == 'literal'.
+ *
+ * @param mixed $val The value to serialize
+ * @param string $name The name (local part) of the XML element
+ * @param string $type The XML schema type (local part) for the element
+ * @param string $name_ns The namespace for the name of the XML element
+ * @param string $type_ns The namespace for the type of the element
+ * @param array $attributes The attributes to serialize as name=>value pairs
+ * @param string $use The WSDL "use" (encoded|literal)
+ * @param boolean $soapval Whether this is called from soapval.
+ * @return string The serialized element, possibly with child elements
+ * @access public
+ */
+ function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded',$soapval=false) {
+ $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use, soapval=$soapval");
+ $this->appendDebug('value=' . $this->varDump($val));
+ $this->appendDebug('attributes=' . $this->varDump($attributes));
+
+ if (is_object($val) && get_class($val) == 'soapval' && (! $soapval)) {
+ $this->debug("serialize_val: serialize soapval");
+ $xml = $val->serialize($use);
+ $this->appendDebug($val->getDebug());
+ $val->clearDebug();
+ $this->debug("serialize_val of soapval returning $xml");
+ return $xml;
+ }
+ // force valid name if necessary
+ if (is_numeric($name)) {
+ $name = '__numeric_' . $name;
+ } elseif (! $name) {
+ $name = 'noname';
+ }
+ // if name has ns, add ns prefix to name
+ $xmlns = '';
+ if($name_ns){
+ $prefix = 'nu'.rand(1000,9999);
+ $name = $prefix.':'.$name;
+ $xmlns .= " xmlns:$prefix=\"$name_ns\"";
+ }
+ // if type is prefixed, create type prefix
+ if($type_ns != '' && $type_ns == $this->namespaces['xsd']){
+ // need to fix this. shouldn't default to xsd if no ns specified
+ // w/o checking against typemap
+ $type_prefix = 'xsd';
+ } elseif($type_ns){
+ $type_prefix = 'ns'.rand(1000,9999);
+ $xmlns .= " xmlns:$type_prefix=\"$type_ns\"";
+ }
+ // serialize attributes if present
+ $atts = '';
+ if($attributes){
+ foreach($attributes as $k => $v){
+ $atts .= " $k=\"".$this->expandEntities($v).'"';
+ }
+ }
+ // serialize null value
+ if (is_null($val)) {
+ $this->debug("serialize_val: serialize null");
+ if ($use == 'literal') {
+ // TODO: depends on minOccurs
+ $xml = "<$name$xmlns$atts/>";
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ } else {
+ if (isset($type) && isset($type_prefix)) {
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = '';
+ }
+ $xml = "<$name$xmlns$type_str$atts xsi:nil=\"true\"/>";
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ }
+ }
+ // serialize if an xsd built-in primitive type
+ if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){
+ $this->debug("serialize_val: serialize xsd built-in primitive type");
+ if (is_bool($val)) {
+ if ($type == 'boolean') {
+ $val = $val ? 'true' : 'false';
+ } elseif (! $val) {
+ $val = 0;
+ }
+ } else if (is_string($val)) {
+ $val = $this->expandEntities($val);
+ }
+ if ($use == 'literal') {
+ $xml = "<$name$xmlns$atts>$val</$name>";
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ } else {
+ $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val</$name>";
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ }
+ }
+ // detect type and serialize
+ $xml = '';
+ switch(true) {
+ case (is_bool($val) || $type == 'boolean'):
+ $this->debug("serialize_val: serialize boolean");
+ if ($type == 'boolean') {
+ $val = $val ? 'true' : 'false';
+ } elseif (! $val) {
+ $val = 0;
+ }
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$val</$name>";
+ } else {
+ $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val</$name>";
+ }
+ break;
+ case (is_int($val) || is_long($val) || $type == 'int'):
+ $this->debug("serialize_val: serialize int");
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$val</$name>";
+ } else {
+ $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val</$name>";
+ }
+ break;
+ case (is_float($val)|| is_double($val) || $type == 'float'):
+ $this->debug("serialize_val: serialize float");
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$val</$name>";
+ } else {
+ $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val</$name>";
+ }
+ break;
+ case (is_string($val) || $type == 'string'):
+ $this->debug("serialize_val: serialize string");
+ $val = $this->expandEntities($val);
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$val</$name>";
+ } else {
+ $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val</$name>";
+ }
+ break;
+ case is_object($val):
+ $this->debug("serialize_val: serialize object");
+ if (get_class($val) == 'soapval') {
+ $this->debug("serialize_val: serialize soapval object");
+ $pXml = $val->serialize($use);
+ $this->appendDebug($val->getDebug());
+ $val->clearDebug();
+ } else {
+ if (! $name) {
+ $name = get_class($val);
+ $this->debug("In serialize_val, used class name $name as element name");
+ } else {
+ $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val));
+ }
+ foreach(get_object_vars($val) as $k => $v){
+ $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use);
+ }
+ }
+ if(isset($type) && isset($type_prefix)){
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = '';
+ }
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>$pXml</$name>";
+ } else {
+ $xml .= "<$name$xmlns$type_str$atts>$pXml</$name>";
+ }
+ break;
+ break;
+ case (is_array($val) || $type):
+ // detect if struct or array
+ $valueType = $this->isArraySimpleOrStruct($val);
+ if($valueType=='arraySimple' || preg_match('/^ArrayOf/',$type)){
+ $this->debug("serialize_val: serialize array");
+ $i = 0;
+ if(is_array($val) && count($val)> 0){
+ foreach($val as $v){
+ if(is_object($v) && get_class($v) == 'soapval'){
+ $tt_ns = $v->type_ns;
+ $tt = $v->type;
+ } elseif (is_array($v)) {
+ $tt = $this->isArraySimpleOrStruct($v);
+ } else {
+ $tt = gettype($v);
+ }
+ $array_types[$tt] = 1;
+ // TODO: for literal, the name should be $name
+ $xml .= $this->serialize_val($v,'item',false,false,false,false,$use);
+ ++$i;
+ }
+ if(count($array_types) > 1){
+ $array_typename = 'xsd:anyType';
+ } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) {
+ if ($tt == 'integer') {
+ $tt = 'int';
+ }
+ $array_typename = 'xsd:'.$tt;
+ } elseif(isset($tt) && $tt == 'arraySimple'){
+ $array_typename = 'SOAP-ENC:Array';
+ } elseif(isset($tt) && $tt == 'arrayStruct'){
+ $array_typename = 'unnamed_struct_use_soapval';
+ } else {
+ // if type is prefixed, create type prefix
+ if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){
+ $array_typename = 'xsd:' . $tt;
+ } elseif ($tt_ns) {
+ $tt_prefix = 'ns' . rand(1000, 9999);
+ $array_typename = "$tt_prefix:$tt";
+ $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\"";
+ } else {
+ $array_typename = $tt;
+ }
+ }
+ $array_type = $i;
+ if ($use == 'literal') {
+ $type_str = '';
+ } else if (isset($type) && isset($type_prefix)) {
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\"";
+ }
+ // empty array
+ } else {
+ if ($use == 'literal') {
+ $type_str = '';
+ } else if (isset($type) && isset($type_prefix)) {
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\"";
+ }
+ }
+ // TODO: for array in literal, there is no wrapper here
+ $xml = "<$name$xmlns$type_str$atts>".$xml."</$name>";
+ } else {
+ // got a struct
+ $this->debug("serialize_val: serialize struct");
+ if(isset($type) && isset($type_prefix)){
+ $type_str = " xsi:type=\"$type_prefix:$type\"";
+ } else {
+ $type_str = '';
+ }
+ if ($use == 'literal') {
+ $xml .= "<$name$xmlns$atts>";
+ } else {
+ $xml .= "<$name$xmlns$type_str$atts>";
+ }
+ foreach($val as $k => $v){
+ // Apache Map
+ if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') {
+ $xml .= '<item>';
+ $xml .= $this->serialize_val($k,'key',false,false,false,false,$use);
+ $xml .= $this->serialize_val($v,'value',false,false,false,false,$use);
+ $xml .= '</item>';
+ } else {
+ $xml .= $this->serialize_val($v,$k,false,false,false,false,$use);
+ }
+ }
+ $xml .= "</$name>";
+ }
+ break;
+ default:
+ $this->debug("serialize_val: serialize unknown");
+ $xml .= 'not detected, got '.gettype($val).' for '.$val;
+ break;
+ }
+ $this->debug("serialize_val returning $xml");
+ return $xml;
+ }
+
+ /**
+ * serializes a message
+ *
+ * @param string $body the XML of the SOAP body
+ * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array
+ * @param array $namespaces optional the namespaces used in generating the body and headers
+ * @param string $style optional (rpc|document)
+ * @param string $use optional (encoded|literal)
+ * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
+ * @return string the message
+ * @access public
+ */
+ function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){
+ // TODO: add an option to automatically run utf8_encode on $body and $headers
+ // if $this->soap_defencoding is UTF-8. Not doing this automatically allows
+ // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1
+
+ $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle");
+ $this->debug("headers:");
+ $this->appendDebug($this->varDump($headers));
+ $this->debug("namespaces:");
+ $this->appendDebug($this->varDump($namespaces));
+
+ // serialize namespaces
+ $ns_string = '';
+ foreach(array_merge($this->namespaces,$namespaces) as $k => $v){
+ $ns_string .= " xmlns:$k=\"$v\"";
+ }
+ if($encodingStyle) {
+ $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string";
+ }
+
+ // serialize headers
+ if($headers){
+ if (is_array($headers)) {
+ $xml = '';
+ foreach ($headers as $k => $v) {
+ if (is_object($v) && get_class($v) == 'soapval') {
+ $xml .= $this->serialize_val($v, false, false, false, false, false, $use);
+ } else {
+ $xml .= $this->serialize_val($v, $k, false, false, false, false, $use);
+ }
+ }
+ $headers = $xml;
+ $this->debug("In serializeEnvelope, serialized array of headers to $headers");
+ }
+ $headers = "<SOAP-ENV:Header>".$headers."</SOAP-ENV:Header>";
+ }
+ // serialize envelope
+ return
+ '<?xml version="1.0" encoding="'.$this->soap_defencoding .'"?'.">".
+ '<SOAP-ENV:Envelope'.$ns_string.">".
+ $headers.
+ "<SOAP-ENV:Body>".
+ $body.
+ "</SOAP-ENV:Body>".
+ "</SOAP-ENV:Envelope>";
+ }
+
+ /**
+ * formats a string to be inserted into an HTML stream
+ *
+ * @param string $str The string to format
+ * @return string The formatted string
+ * @access public
+ * @deprecated
+ */
+ function formatDump($str){
+ $str = htmlspecialchars($str);
+ return nl2br($str);
+ }
+
+ /**
+ * contracts (changes namespace to prefix) a qualified name
+ *
+ * @param string $qname qname
+ * @return string contracted qname
+ * @access private
+ */
+ function contractQname($qname){
+ // get element namespace
+ //$this->xdebug("Contract $qname");
+ if (strrpos($qname, ':')) {
+ // get unqualified name
+ $name = substr($qname, strrpos($qname, ':') + 1);
+ // get ns
+ $ns = substr($qname, 0, strrpos($qname, ':'));
+ $p = $this->getPrefixFromNamespace($ns);
+ if ($p) {
+ return $p . ':' . $name;
+ }
+ return $qname;
+ } else {
+ return $qname;
+ }
+ }
+
+ /**
+ * expands (changes prefix to namespace) a qualified name
+ *
+ * @param string $qname qname
+ * @return string expanded qname
+ * @access private
+ */
+ function expandQname($qname){
+ // get element prefix
+ if(strpos($qname,':') && !preg_match('/^http:\/\//',$qname)){
+ // get unqualified name
+ $name = substr(strstr($qname,':'),1);
+ // get ns prefix
+ $prefix = substr($qname,0,strpos($qname,':'));
+ if(isset($this->namespaces[$prefix])){
+ return $this->namespaces[$prefix].':'.$name;
+ } else {
+ return $qname;
+ }
+ } else {
+ return $qname;
+ }
+ }
+
+ /**
+ * returns the local part of a prefixed string
+ * returns the original string, if not prefixed
+ *
+ * @param string $str The prefixed string
+ * @return string The local part
+ * @access public
+ */
+ function getLocalPart($str){
+ if($sstr = strrchr($str,':')){
+ // get unqualified name
+ return substr( $sstr, 1 );
+ } else {
+ return $str;
+ }
+ }
+
+ /**
+ * returns the prefix part of a prefixed string
+ * returns false, if not prefixed
+ *
+ * @param string $str The prefixed string
+ * @return mixed The prefix or false if there is no prefix
+ * @access public
+ */
+ function getPrefix($str){
+ if($pos = strrpos($str,':')){
+ // get prefix
+ return substr($str,0,$pos);
+ }
+ return false;
+ }
+
+ /**
+ * pass it a prefix, it returns a namespace
+ *
+ * @param string $prefix The prefix
+ * @return mixed The namespace, false if no namespace has the specified prefix
+ * @access public
+ */
+ function getNamespaceFromPrefix($prefix){
+ if (isset($this->namespaces[$prefix])) {
+ return $this->namespaces[$prefix];
+ }
+ //$this->setError("No namespace registered for prefix '$prefix'");
+ return false;
+ }
+
+ /**
+ * returns the prefix for a given namespace (or prefix)
+ * or false if no prefixes registered for the given namespace
+ *
+ * @param string $ns The namespace
+ * @return mixed The prefix, false if the namespace has no prefixes
+ * @access public
+ */
+ function getPrefixFromNamespace($ns) {
+ foreach ($this->namespaces as $p => $n) {
+ if ($ns == $n || $ns == $p) {
+ $this->usedNamespaces[$p] = $n;
+ return $p;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * returns the time in ODBC canonical form with microseconds
+ *
+ * @return string The time in ODBC canonical form with microseconds
+ * @access public
+ */
+ function getmicrotime() {
+ if (function_exists('gettimeofday')) {
+ $tod = gettimeofday();
+ $sec = $tod['sec'];
+ $usec = $tod['usec'];
+ } else {
+ $sec = time();
+ $usec = 0;
+ }
+ return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec);
+ }
+
+ /**
+ * Returns a string with the output of var_dump
+ *
+ * @param mixed $data The variable to var_dump
+ * @return string The output of var_dump
+ * @access public
+ */
+ function varDump($data) {
+ ob_start();
+ var_dump($data);
+ $ret_val = ob_get_contents();
+ ob_end_clean();
+ return $ret_val;
+ }
+
+ /**
+ * represents the object as a string
+ *
+ * @return string
+ * @access public
+ */
+ function __toString() {
+ return $this->varDump($this);
+ }
+}
+
+// XML Schema Datatype Helper Functions
+
+//xsd:dateTime helpers
+
+/**
+* convert unix timestamp to ISO 8601 compliant date string
+*
+* @param int $timestamp Unix time stamp
+* @param boolean $utc Whether the time stamp is UTC or local
+* @return mixed ISO 8601 date string or false
+* @access public
+*/
+function timestamp_to_iso8601($timestamp,$utc=true){
+ $datestr = date('Y-m-d\TH:i:sO',$timestamp);
+ $pos = strrpos($datestr, "+");
+ if ($pos === FALSE) {
+ $pos = strrpos($datestr, "-");
+ }
+ if ($pos !== FALSE) {
+ if (strlen($datestr) == $pos + 5) {
+ $datestr = substr($datestr, 0, $pos + 3) . ':' . substr($datestr, -2);
+ }
+ }
+ if($utc){
+ $pattern = '/'.
+ '([0-9]{4})-'. // centuries & years CCYY-
+ '([0-9]{2})-'. // months MM-
+ '([0-9]{2})'. // days DD
+ 'T'. // separator T
+ '([0-9]{2}):'. // hours hh:
+ '([0-9]{2}):'. // minutes mm:
+ '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss...
+ '(Z|[+\-][0-9]{2}:?[0-9]{2})?'. // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
+ '/';
+
+ if(preg_match($pattern,$datestr,$regs)){
+ return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]);
+ }
+ return false;
+ } else {
+ return $datestr;
+ }
+}
+
+/**
+* convert ISO 8601 compliant date string to unix timestamp
+*
+* @param string $datestr ISO 8601 compliant date string
+* @return mixed Unix timestamp (int) or false
+* @access public
+*/
+function iso8601_to_timestamp($datestr){
+ $pattern = '/'.
+ '([0-9]{4})-'. // centuries & years CCYY-
+ '([0-9]{2})-'. // months MM-
+ '([0-9]{2})'. // days DD
+ 'T'. // separator T
+ '([0-9]{2}):'. // hours hh:
+ '([0-9]{2}):'. // minutes mm:
+ '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss...
+ '(Z|[+\-][0-9]{2}:?[0-9]{2})?'. // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
+ '/';
+ if(preg_match($pattern,$datestr,$regs)){
+ // not utc
+ if($regs[8] != 'Z'){
+ $op = substr($regs[8],0,1);
+ $h = substr($regs[8],1,2);
+ $m = substr($regs[8],strlen($regs[8])-2,2);
+ if($op == '-'){
+ $regs[4] = $regs[4] + $h;
+ $regs[5] = $regs[5] + $m;
+ } elseif($op == '+'){
+ $regs[4] = $regs[4] - $h;
+ $regs[5] = $regs[5] - $m;
+ }
+ }
+ return gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
+// return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
+ } else {
+ return false;
+ }
+}
+
+/**
+* sleeps some number of microseconds
+*
+* @param string $usec the number of microseconds to sleep
+* @access public
+* @deprecated
+*/
+function usleepWindows($usec)
+{
+ $start = gettimeofday();
+
+ do
+ {
+ $stop = gettimeofday();
+ $timePassed = 1000000 * ($stop['sec'] - $start['sec'])
+ + $stop['usec'] - $start['usec'];
+ }
+ while ($timePassed < $usec);
+}
+
+?><?php
+
+
+
+/**
+* Contains information for a SOAP fault.
+* Mainly used for returning faults from deployed functions
+* in a server instance.
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_fault extends nusoap_base {
+ /**
+ * The fault code (client|server)
+ * @var string
+ * @access private
+ */
+ var $faultcode;
+ /**
+ * The fault actor
+ * @var string
+ * @access private
+ */
+ var $faultactor;
+ /**
+ * The fault string, a description of the fault
+ * @var string
+ * @access private
+ */
+ var $faultstring;
+ /**
+ * The fault detail, typically a string or array of string
+ * @var mixed
+ * @access private
+ */
+ var $faultdetail;
+
+ /**
+ * constructor
+ *
+ * @param string $faultcode (SOAP-ENV:Client | SOAP-ENV:Server)
+ * @param string $faultactor only used when msg routed between multiple actors
+ * @param string $faultstring human readable error message
+ * @param mixed $faultdetail detail, typically a string or array of string
+ */
+ function nusoap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){
+ parent::nusoap_base();
+ $this->faultcode = $faultcode;
+ $this->faultactor = $faultactor;
+ $this->faultstring = $faultstring;
+ $this->faultdetail = $faultdetail;
+ }
+
+ /**
+ * serialize a fault
+ *
+ * @return string The serialization of the fault instance.
+ * @access public
+ */
+ function serialize(){
+ $ns_string = '';
+ foreach($this->namespaces as $k => $v){
+ $ns_string .= "\n xmlns:$k=\"$v\"";
+ }
+ $return_msg =
+ '<?xml version="1.0" encoding="'.$this->soap_defencoding.'"?>'.
+ '<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"'.$ns_string.">\n".
+ '<SOAP-ENV:Body>'.
+ '<SOAP-ENV:Fault>'.
+ $this->serialize_val($this->faultcode, 'faultcode').
+ $this->serialize_val($this->faultactor, 'faultactor').
+ $this->serialize_val($this->faultstring, 'faultstring').
+ $this->serialize_val($this->faultdetail, 'detail').
+ '</SOAP-ENV:Fault>'.
+ '</SOAP-ENV:Body>'.
+ '</SOAP-ENV:Envelope>';
+ return $return_msg;
+ }
+}
+
+/**
+ * Backward compatibility
+ */
+class soap_fault extends nusoap_fault {
+}
+
+?><?php
+
+
+
+/**
+* parses an XML Schema, allows access to it's data, other utility methods.
+* imperfect, no validation... yet, but quite functional.
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_xmlschema extends nusoap_base {
+
+ // files
+ var $schema = '';
+ var $xml = '';
+ // namespaces
+ var $enclosingNamespaces;
+ // schema info
+ var $schemaInfo = array();
+ var $schemaTargetNamespace = '';
+ // types, elements, attributes defined by the schema
+ var $attributes = array();
+ var $complexTypes = array();
+ var $complexTypeStack = array();
+ var $currentComplexType = null;
+ var $elements = array();
+ var $elementStack = array();
+ var $currentElement = null;
+ var $simpleTypes = array();
+ var $simpleTypeStack = array();
+ var $currentSimpleType = null;
+ // imports
+ var $imports = array();
+ // parser vars
+ var $parser;
+ var $position = 0;
+ var $depth = 0;
+ var $depth_array = array();
+ var $message = array();
+ var $defaultNamespace = array();
+
+ /**
+ * constructor
+ *
+ * @param string $schema schema document URI
+ * @param string $xml xml document URI
+ * @param string $namespaces namespaces defined in enclosing XML
+ * @access public
+ */
+ function nusoap_xmlschema($schema='',$xml='',$namespaces=array()){
+ parent::nusoap_base();
+ $this->debug('nusoap_xmlschema class instantiated, inside constructor');
+ // files
+ $this->schema = $schema;
+ $this->xml = $xml;
+
+ // namespaces
+ $this->enclosingNamespaces = $namespaces;
+ $this->namespaces = array_merge($this->namespaces, $namespaces);
+
+ // parse schema file
+ if($schema != ''){
+ $this->debug('initial schema file: '.$schema);
+ $this->parseFile($schema, 'schema');
+ }
+
+ // parse xml file
+ if($xml != ''){
+ $this->debug('initial xml file: '.$xml);
+ $this->parseFile($xml, 'xml');
+ }
+
+ }
+
+ /**
+ * parse an XML file
+ *
+ * @param string $xml path/URL to XML file
+ * @param string $type (schema | xml)
+ * @return boolean
+ * @access public
+ */
+ function parseFile($xml,$type){
+ // parse xml file
+ if($xml != ""){
+ $xmlStr = @join("",@file($xml));
+ if($xmlStr == ""){
+ $msg = 'Error reading XML from '.$xml;
+ $this->setError($msg);
+ $this->debug($msg);
+ return false;
+ } else {
+ $this->debug("parsing $xml");
+ $this->parseString($xmlStr,$type);
+ $this->debug("done parsing $xml");
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * parse an XML string
+ *
+ * @param string $xml path or URL
+ * @param string $type (schema|xml)
+ * @access private
+ */
+ function parseString($xml,$type){
+ // parse xml string
+ if($xml != ""){
+
+ // Create an XML parser.
+ $this->parser = xml_parser_create();
+ // Set the options for parsing the XML data.
+ xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
+
+ // Set the object for the parser.
+ xml_set_object($this->parser, $this);
+
+ // Set the element handlers for the parser.
+ if($type == "schema"){
+ xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement');
+ xml_set_character_data_handler($this->parser,'schemaCharacterData');
+ } elseif($type == "xml"){
+ xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement');
+ xml_set_character_data_handler($this->parser,'xmlCharacterData');
+ }
+
+ // Parse the XML file.
+ if(!xml_parse($this->parser,$xml,true)){
+ // Display an error message.
+ $errstr = sprintf('XML error parsing XML schema on line %d: %s',
+ xml_get_current_line_number($this->parser),
+ xml_error_string(xml_get_error_code($this->parser))
+ );
+ $this->debug($errstr);
+ $this->debug("XML payload:\n" . $xml);
+ $this->setError($errstr);
+ }
+
+ xml_parser_free($this->parser);
+ } else{
+ $this->debug('no xml passed to parseString()!!');
+ $this->setError('no xml passed to parseString()!!');
+ }
+ }
+
+ /**
+ * gets a type name for an unnamed type
+ *
+ * @param string Element name
+ * @return string A type name for an unnamed type
+ * @access private
+ */
+ function CreateTypeName($ename) {
+ $scope = '';
+ for ($i = 0; $i < count($this->complexTypeStack); $i++) {
+ $scope .= $this->complexTypeStack[$i] . '_';
+ }
+ return $scope . $ename . '_ContainedType';
+ }
+
+ /**
+ * start-element handler
+ *
+ * @param string $parser XML parser object
+ * @param string $name element name
+ * @param string $attrs associative array of attributes
+ * @access private
+ */
+ function schemaStartElement($parser, $name, $attrs) {
+
+ // position in the total number of elements, starting from 0
+ $pos = $this->position++;
+ $depth = $this->depth++;
+ // set self as current value for this depth
+ $this->depth_array[$depth] = $pos;
+ $this->message[$pos] = array('cdata' => '');
+ if ($depth > 0) {
+ $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]];
+ } else {
+ $this->defaultNamespace[$pos] = false;
+ }
+
+ // get element prefix
+ if($prefix = $this->getPrefix($name)){
+ // get unqualified name
+ $name = $this->getLocalPart($name);
+ } else {
+ $prefix = '';
+ }
+
+ // loop thru attributes, expanding, and registering namespace declarations
+ if(count($attrs) > 0){
+ foreach($attrs as $k => $v){
+ // if ns declarations, add to class level array of valid namespaces
+ if(preg_match('/^xmlns/',$k)){
+ //$this->xdebug("$k: $v");
+ //$this->xdebug('ns_prefix: '.$this->getPrefix($k));
+ if($ns_prefix = substr(strrchr($k,':'),1)){
+ //$this->xdebug("Add namespace[$ns_prefix] = $v");
+ $this->namespaces[$ns_prefix] = $v;
+ } else {
+ $this->defaultNamespace[$pos] = $v;
+ if (! $this->getPrefixFromNamespace($v)) {
+ $this->namespaces['ns'.(count($this->namespaces)+1)] = $v;
+ }
+ }
+ if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){
+ $this->XMLSchemaVersion = $v;
+ $this->namespaces['xsi'] = $v.'-instance';
+ }
+ }
+ }
+ foreach($attrs as $k => $v){
+ // expand each attribute
+ $k = strpos($k,':') ? $this->expandQname($k) : $k;
+ $v = strpos($v,':') ? $this->expandQname($v) : $v;
+ $eAttrs[$k] = $v;
+ }
+ $attrs = $eAttrs;
+ } else {
+ $attrs = array();
+ }
+ // find status, register data
+ switch($name){
+ case 'all': // (optional) compositor content for a complexType
+ case 'choice':
+ case 'group':
+ case 'sequence':
+ //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement");
+ $this->complexTypes[$this->currentComplexType]['compositor'] = $name;
+ //if($name == 'all' || $name == 'sequence'){
+ // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
+ //}
+ break;
+ case 'attribute': // complexType attribute
+ //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']);
+ $this->xdebug("parsing attribute:");
+ $this->appendDebug($this->varDump($attrs));
+ if (!isset($attrs['form'])) {
+ // TODO: handle globals
+ $attrs['form'] = $this->schemaInfo['attributeFormDefault'];
+ }
+ if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
+ $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
+ if (!strpos($v, ':')) {
+ // no namespace in arrayType attribute value...
+ if ($this->defaultNamespace[$pos]) {
+ // ...so use the default
+ $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
+ }
+ }
+ }
+ if(isset($attrs['name'])){
+ $this->attributes[$attrs['name']] = $attrs;
+ $aname = $attrs['name'];
+ } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){
+ if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
+ $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
+ } else {
+ $aname = '';
+ }
+ } elseif(isset($attrs['ref'])){
+ $aname = $attrs['ref'];
+ $this->attributes[$attrs['ref']] = $attrs;
+ }
+
+ if($this->currentComplexType){ // This should *always* be
+ $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs;
+ }
+ // arrayType attribute
+ if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
+ $prefix = $this->getPrefix($aname);
+ if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){
+ $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
+ } else {
+ $v = '';
+ }
+ if(strpos($v,'[,]')){
+ $this->complexTypes[$this->currentComplexType]['multidimensional'] = true;
+ }
+ $v = substr($v,0,strpos($v,'[')); // clip the []
+ if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){
+ $v = $this->XMLSchemaVersion.':'.$v;
+ }
+ $this->complexTypes[$this->currentComplexType]['arrayType'] = $v;
+ }
+ break;
+ case 'complexContent': // (optional) content for a complexType
+ $this->xdebug("do nothing for element $name");
+ break;
+ case 'complexType':
+ array_push($this->complexTypeStack, $this->currentComplexType);
+ if(isset($attrs['name'])){
+ // TODO: what is the scope of named complexTypes that appear
+ // nested within other c complexTypes?
+ $this->xdebug('processing named complexType '.$attrs['name']);
+ //$this->currentElement = false;
+ $this->currentComplexType = $attrs['name'];
+ $this->complexTypes[$this->currentComplexType] = $attrs;
+ $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
+ // This is for constructs like
+ // <complexType name="ListOfString" base="soap:Array">
+ // <sequence>
+ // <element name="string" type="xsd:string"
+ // minOccurs="0" maxOccurs="unbounded" />
+ // </sequence>
+ // </complexType>
+ if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){
+ $this->xdebug('complexType is unusual array');
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
+ } else {
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
+ }
+ } else {
+ $name = $this->CreateTypeName($this->currentElement);
+ $this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name);
+ $this->currentComplexType = $name;
+ //$this->currentElement = false;
+ $this->complexTypes[$this->currentComplexType] = $attrs;
+ $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
+ // This is for constructs like
+ // <complexType name="ListOfString" base="soap:Array">
+ // <sequence>
+ // <element name="string" type="xsd:string"
+ // minOccurs="0" maxOccurs="unbounded" />
+ // </sequence>
+ // </complexType>
+ if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){
+ $this->xdebug('complexType is unusual array');
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
+ } else {
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
+ }
+ }
+ $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'false';
+ break;
+ case 'element':
+ array_push($this->elementStack, $this->currentElement);
+ if (!isset($attrs['form'])) {
+ if ($this->currentComplexType) {
+ $attrs['form'] = $this->schemaInfo['elementFormDefault'];
+ } else {
+ // global
+ $attrs['form'] = 'qualified';
+ }
+ }
+ if(isset($attrs['type'])){
+ $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']);
+ if (! $this->getPrefix($attrs['type'])) {
+ if ($this->defaultNamespace[$pos]) {
+ $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type'];
+ $this->xdebug('used default namespace to make type ' . $attrs['type']);
+ }
+ }
+ // This is for constructs like
+ // <complexType name="ListOfString" base="soap:Array">
+ // <sequence>
+ // <element name="string" type="xsd:string"
+ // minOccurs="0" maxOccurs="unbounded" />
+ // </sequence>
+ // </complexType>
+ if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') {
+ $this->xdebug('arrayType for unusual array is ' . $attrs['type']);
+ $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type'];
+ }
+ $this->currentElement = $attrs['name'];
+ $ename = $attrs['name'];
+ } elseif(isset($attrs['ref'])){
+ $this->xdebug("processing element as ref to ".$attrs['ref']);
+ $this->currentElement = "ref to ".$attrs['ref'];
+ $ename = $this->getLocalPart($attrs['ref']);
+ } else {
+ $type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']);
+ $this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type);
+ $this->currentElement = $attrs['name'];
+ $attrs['type'] = $this->schemaTargetNamespace . ':' . $type;
+ $ename = $attrs['name'];
+ }
+ if (isset($ename) && $this->currentComplexType) {
+ $this->xdebug("add element $ename to complexType $this->currentComplexType");
+ $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs;
+ } elseif (!isset($attrs['ref'])) {
+ $this->xdebug("add element $ename to elements array");
+ $this->elements[ $attrs['name'] ] = $attrs;
+ $this->elements[ $attrs['name'] ]['typeClass'] = 'element';
+ }
+ break;
+ case 'enumeration': // restriction value list member
+ $this->xdebug('enumeration ' . $attrs['value']);
+ if ($this->currentSimpleType) {
+ $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value'];
+ } elseif ($this->currentComplexType) {
+ $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value'];
+ }
+ break;
+ case 'extension': // simpleContent or complexContent type extension
+ $this->xdebug('extension ' . $attrs['base']);
+ if ($this->currentComplexType) {
+ $ns = $this->getPrefix($attrs['base']);
+ if ($ns == '') {
+ $this->complexTypes[$this->currentComplexType]['extensionBase'] = $this->schemaTargetNamespace . ':' . $attrs['base'];
+ } else {
+ $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base'];
+ }
+ } else {
+ $this->xdebug('no current complexType to set extensionBase');
+ }
+ break;
+ case 'import':
+ if (isset($attrs['schemaLocation'])) {
+ $this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']);
+ $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
+ } else {
+ $this->xdebug('import namespace ' . $attrs['namespace']);
+ $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
+ if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
+ $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
+ }
+ }
+ break;
+ case 'include':
+ if (isset($attrs['schemaLocation'])) {
+ $this->xdebug('include into namespace ' . $this->schemaTargetNamespace . ' from ' . $attrs['schemaLocation']);
+ $this->imports[$this->schemaTargetNamespace][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
+ } else {
+ $this->xdebug('ignoring invalid XML Schema construct: include without schemaLocation attribute');
+ }
+ break;
+ case 'list': // simpleType value list
+ $this->xdebug("do nothing for element $name");
+ break;
+ case 'restriction': // simpleType, simpleContent or complexContent value restriction
+ $this->xdebug('restriction ' . $attrs['base']);
+ if($this->currentSimpleType){
+ $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base'];
+ } elseif($this->currentComplexType){
+ $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base'];
+ if(strstr($attrs['base'],':') == ':Array'){
+ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
+ }
+ }
+ break;
+ case 'schema':
+ $this->schemaInfo = $attrs;
+ $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix);
+ if (isset($attrs['targetNamespace'])) {
+ $this->schemaTargetNamespace = $attrs['targetNamespace'];
+ }
+ if (!isset($attrs['elementFormDefault'])) {
+ $this->schemaInfo['elementFormDefault'] = 'unqualified';
+ }
+ if (!isset($attrs['attributeFormDefault'])) {
+ $this->schemaInfo['attributeFormDefault'] = 'unqualified';
+ }
+ break;
+ case 'simpleContent': // (optional) content for a complexType
+ if ($this->currentComplexType) { // This should *always* be
+ $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'true';
+ } else {
+ $this->xdebug("do nothing for element $name because there is no current complexType");
+ }
+ break;
+ case 'simpleType':
+ array_push($this->simpleTypeStack, $this->currentSimpleType);
+ if(isset($attrs['name'])){
+ $this->xdebug("processing simpleType for name " . $attrs['name']);
+ $this->currentSimpleType = $attrs['name'];
+ $this->simpleTypes[ $attrs['name'] ] = $attrs;
+ $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType';
+ $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar';
+ } else {
+ $name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement);
+ $this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name);
+ $this->currentSimpleType = $name;
+ //$this->currentElement = false;
+ $this->simpleTypes[$this->currentSimpleType] = $attrs;
+ $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar';
+ }
+ break;
+ case 'union': // simpleType type list
+ $this->xdebug("do nothing for element $name");
+ break;
+ default:
+ $this->xdebug("do not have any logic to process element $name");
+ }
+ }
+
+ /**
+ * end-element handler
+ *
+ * @param string $parser XML parser object
+ * @param string $name element name
+ * @access private
+ */
+ function schemaEndElement($parser, $name) {
+ // bring depth down a notch
+ $this->depth--;
+ // position of current element is equal to the last value left in depth_array for my depth
+ if(isset($this->depth_array[$this->depth])){
+ $pos = $this->depth_array[$this->depth];
+ }
+ // get element prefix
+ if ($prefix = $this->getPrefix($name)){
+ // get unqualified name
+ $name = $this->getLocalPart($name);
+ } else {
+ $prefix = '';
+ }
+ // move on...
+ if($name == 'complexType'){
+ $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)'));
+ $this->xdebug($this->varDump($this->complexTypes[$this->currentComplexType]));
+ $this->currentComplexType = array_pop($this->complexTypeStack);
+ //$this->currentElement = false;
+ }
+ if($name == 'element'){
+ $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)'));
+ $this->currentElement = array_pop($this->elementStack);
+ }
+ if($name == 'simpleType'){
+ $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)'));
+ $this->xdebug($this->varDump($this->simpleTypes[$this->currentSimpleType]));
+ $this->currentSimpleType = array_pop($this->simpleTypeStack);
+ }
+ }
+
+ /**
+ * element content handler
+ *
+ * @param string $parser XML parser object
+ * @param string $data element content
+ * @access private
+ */
+ function schemaCharacterData($parser, $data){
+ $pos = $this->depth_array[$this->depth - 1];
+ $this->message[$pos]['cdata'] .= $data;
+ }
+
+ /**
+ * serialize the schema
+ *
+ * @access public
+ */
+ function serializeSchema(){
+
+ $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion);
+ $xml = '';
+ // imports
+ if (sizeof($this->imports) > 0) {
+ foreach($this->imports as $ns => $list) {
+ foreach ($list as $ii) {
+ if ($ii['location'] != '') {
+ $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n";
+ } else {
+ $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n";
+ }
+ }
+ }
+ }
+ // complex types
+ foreach($this->complexTypes as $typeName => $attrs){
+ $contentStr = '';
+ // serialize child elements
+ if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){
+ foreach($attrs['elements'] as $element => $eParts){
+ if(isset($eParts['ref'])){
+ $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n";
+ } else {
+ $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\"";
+ foreach ($eParts as $aName => $aValue) {
+ // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable
+ if ($aName != 'name' && $aName != 'type') {
+ $contentStr .= " $aName=\"$aValue\"";
+ }
+ }
+ $contentStr .= "/>\n";
+ }
+ }
+ // compositor wraps elements
+ if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) {
+ $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." </$schemaPrefix:$attrs[compositor]>\n";
+ }
+ }
+ // attributes
+ if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){
+ foreach($attrs['attrs'] as $attr => $aParts){
+ $contentStr .= " <$schemaPrefix:attribute";
+ foreach ($aParts as $a => $v) {
+ if ($a == 'ref' || $a == 'type') {
+ $contentStr .= " $a=\"".$this->contractQName($v).'"';
+ } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') {
+ $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl'];
+ $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"';
+ } else {
+ $contentStr .= " $a=\"$v\"";
+ }
+ }
+ $contentStr .= "/>\n";
+ }
+ }
+ // if restriction
+ if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){
+ $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." </$schemaPrefix:restriction>\n";
+ // complex or simple content
+ if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){
+ $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." </$schemaPrefix:complexContent>\n";
+ }
+ }
+ // finalize complex type
+ if($contentStr != ''){
+ $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." </$schemaPrefix:complexType>\n";
+ } else {
+ $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n";
+ }
+ $xml .= $contentStr;
+ }
+ // simple types
+ if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){
+ foreach($this->simpleTypes as $typeName => $eParts){
+ $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\">\n";
+ if (isset($eParts['enumeration'])) {
+ foreach ($eParts['enumeration'] as $e) {
+ $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n";
+ }
+ }
+ $xml .= " </$schemaPrefix:restriction>\n </$schemaPrefix:simpleType>";
+ }
+ }
+ // elements
+ if(isset($this->elements) && count($this->elements) > 0){
+ foreach($this->elements as $element => $eParts){
+ $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n";
+ }
+ }
+ // attributes
+ if(isset($this->attributes) && count($this->attributes) > 0){
+ foreach($this->attributes as $attr => $aParts){
+ $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>";
+ }
+ }
+ // finish 'er up
+ $attr = '';
+ foreach ($this->schemaInfo as $k => $v) {
+ if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') {
+ $attr .= " $k=\"$v\"";
+ }
+ }
+ $el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n";
+ foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) {
+ $el .= " xmlns:$nsp=\"$ns\"";
+ }
+ $xml = $el . ">\n".$xml."</$schemaPrefix:schema>\n";
+ return $xml;
+ }
+
+ /**
+ * adds debug data to the clas level debug string
+ *
+ * @param string $string debug data
+ * @access private
+ */
+ function xdebug($string){
+ $this->debug('<' . $this->schemaTargetNamespace . '> '.$string);
+ }
+
+ /**
+ * get the PHP type of a user defined type in the schema
+ * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays
+ * returns false if no type exists, or not w/ the given namespace
+ * else returns a string that is either a native php type, or 'struct'
+ *
+ * @param string $type name of defined type
+ * @param string $ns namespace of type
+ * @return mixed
+ * @access public
+ * @deprecated
+ */
+ function getPHPType($type,$ns){
+ if(isset($this->typemap[$ns][$type])){
+ //print "found type '$type' and ns $ns in typemap<br>";
+ return $this->typemap[$ns][$type];
+ } elseif(isset($this->complexTypes[$type])){
+ //print "getting type '$type' and ns $ns from complexTypes array<br>";
+ return $this->complexTypes[$type]['phpType'];
+ }
+ return false;
+ }
+
+ /**
+ * returns an associative array of information about a given type
+ * returns false if no type exists by the given name
+ *
+ * For a complexType typeDef = array(
+ * 'restrictionBase' => '',
+ * 'phpType' => '',
+ * 'compositor' => '(sequence|all)',
+ * 'elements' => array(), // refs to elements array
+ * 'attrs' => array() // refs to attributes array
+ * ... and so on (see addComplexType)
+ * )
+ *
+ * For simpleType or element, the array has different keys.
+ *
+ * @param string $type
+ * @return mixed
+ * @access public
+ * @see addComplexType
+ * @see addSimpleType
+ * @see addElement
+ */
+ function getTypeDef($type){
+ //$this->debug("in getTypeDef for type $type");
+ if (substr($type, -1) == '^') {
+ $is_element = 1;
+ $type = substr($type, 0, -1);
+ } else {
+ $is_element = 0;
+ }
+
+ if((! $is_element) && isset($this->complexTypes[$type])){
+ $this->xdebug("in getTypeDef, found complexType $type");
+ return $this->complexTypes[$type];
+ } elseif((! $is_element) && isset($this->simpleTypes[$type])){
+ $this->xdebug("in getTypeDef, found simpleType $type");
+ if (!isset($this->simpleTypes[$type]['phpType'])) {
+ // get info for type to tack onto the simple type
+ // TODO: can this ever really apply (i.e. what is a simpleType really?)
+ $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1);
+ $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':'));
+ $etype = $this->getTypeDef($uqType);
+ if ($etype) {
+ $this->xdebug("in getTypeDef, found type for simpleType $type:");
+ $this->xdebug($this->varDump($etype));
+ if (isset($etype['phpType'])) {
+ $this->simpleTypes[$type]['phpType'] = $etype['phpType'];
+ }
+ if (isset($etype['elements'])) {
+ $this->simpleTypes[$type]['elements'] = $etype['elements'];
+ }
+ }
+ }
+ return $this->simpleTypes[$type];
+ } elseif(isset($this->elements[$type])){
+ $this->xdebug("in getTypeDef, found element $type");
+ if (!isset($this->elements[$type]['phpType'])) {
+ // get info for type to tack onto the element
+ $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1);
+ $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':'));
+ $etype = $this->getTypeDef($uqType);
+ if ($etype) {
+ $this->xdebug("in getTypeDef, found type for element $type:");
+ $this->xdebug($this->varDump($etype));
+ if (isset($etype['phpType'])) {
+ $this->elements[$type]['phpType'] = $etype['phpType'];
+ }
+ if (isset($etype['elements'])) {
+ $this->elements[$type]['elements'] = $etype['elements'];
+ }
+ if (isset($etype['extensionBase'])) {
+ $this->elements[$type]['extensionBase'] = $etype['extensionBase'];
+ }
+ } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') {
+ $this->xdebug("in getTypeDef, element $type is an XSD type");
+ $this->elements[$type]['phpType'] = 'scalar';
+ }
+ }
+ return $this->elements[$type];
+ } elseif(isset($this->attributes[$type])){
+ $this->xdebug("in getTypeDef, found attribute $type");
+ return $this->attributes[$type];
+ } elseif (preg_match('/_ContainedType$/', $type)) {
+ $this->xdebug("in getTypeDef, have an untyped element $type");
+ $typeDef['typeClass'] = 'simpleType';
+ $typeDef['phpType'] = 'scalar';
+ $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string';
+ return $typeDef;
+ }
+ $this->xdebug("in getTypeDef, did not find $type");
+ return false;
+ }
+
+ /**
+ * returns a sample serialization of a given type, or false if no type by the given name
+ *
+ * @param string $type name of type
+ * @return mixed
+ * @access public
+ * @deprecated
+ */
+ function serializeTypeDef($type){
+ //print "in sTD() for type $type<br>";
+ if($typeDef = $this->getTypeDef($type)){
+ $str .= '<'.$type;
+ if(is_array($typeDef['attrs'])){
+ foreach($typeDef['attrs'] as $attName => $data){
+ $str .= " $attName=\"{type = ".$data['type']."}\"";
+ }
+ }
+ $str .= " xmlns=\"".$this->schema['targetNamespace']."\"";
+ if(count($typeDef['elements']) > 0){
+ $str .= ">";
+ foreach($typeDef['elements'] as $element => $eData){
+ $str .= $this->serializeTypeDef($element);
+ }
+ $str .= "</$type>";
+ } elseif($typeDef['typeClass'] == 'element') {
+ $str .= "></$type>";
+ } else {
+ $str .= "/>";
+ }
+ return $str;
+ }
+ return false;
+ }
+
+ /**
+ * returns HTML form elements that allow a user
+ * to enter values for creating an instance of the given type.
+ *
+ * @param string $name name for type instance
+ * @param string $type name of type
+ * @return string
+ * @access public
+ * @deprecated
+ */
+ function typeToForm($name,$type){
+ // get typedef
+ if($typeDef = $this->getTypeDef($type)){
+ // if struct
+ if($typeDef['phpType'] == 'struct'){
+ $buffer .= '<table>';
+ foreach($typeDef['elements'] as $child => $childDef){
+ $buffer .= "
+ <tr><td align='right'>$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):</td>
+ <td><input type='text' name='parameters[".$name."][$childDef[name]]'></td></tr>";
+ }
+ $buffer .= '</table>';
+ // if array
+ } elseif($typeDef['phpType'] == 'array'){
+ $buffer .= '<table>';
+ for($i=0;$i < 3; $i++){
+ $buffer .= "
+ <tr><td align='right'>array item (type: $typeDef[arrayType]):</td>
+ <td><input type='text' name='parameters[".$name."][]'></td></tr>";
+ }
+ $buffer .= '</table>';
+ // if scalar
+ } else {
+ $buffer .= "<input type='text' name='parameters[$name]'>";
+ }
+ } else {
+ $buffer .= "<input type='text' name='parameters[$name]'>";
+ }
+ return $buffer;
+ }
+
+ /**
+ * adds a complex type to the schema
+ *
+ * example: array
+ *
+ * addType(
+ * 'ArrayOfstring',
+ * 'complexType',
+ * 'array',
+ * '',
+ * 'SOAP-ENC:Array',
+ * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'),
+ * 'xsd:string'
+ * );
+ *
+ * example: PHP associative array ( SOAP Struct )
+ *
+ * addType(
+ * 'SOAPStruct',
+ * 'complexType',
+ * 'struct',
+ * 'all',
+ * array('myVar'=> array('name'=>'myVar','type'=>'string')
+ * );
+ *
+ * @param name
+ * @param typeClass (complexType|simpleType|attribute)
+ * @param phpType: currently supported are array and struct (php assoc array)
+ * @param compositor (all|sequence|choice)
+ * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
+ * @param elements = array ( name = array(name=>'',type=>'') )
+ * @param attrs = array(
+ * array(
+ * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType",
+ * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]"
+ * )
+ * )
+ * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string)
+ * @access public
+ * @see getTypeDef
+ */
+ function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){
+ $this->complexTypes[$name] = array(
+ 'name' => $name,
+ 'typeClass' => $typeClass,
+ 'phpType' => $phpType,
+ 'compositor'=> $compositor,
+ 'restrictionBase' => $restrictionBase,
+ 'elements' => $elements,
+ 'attrs' => $attrs,
+ 'arrayType' => $arrayType
+ );
+
+ $this->xdebug("addComplexType $name:");
+ $this->appendDebug($this->varDump($this->complexTypes[$name]));
+ }
+
+ /**
+ * adds a simple type to the schema
+ *
+ * @param string $name
+ * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
+ * @param string $typeClass (should always be simpleType)
+ * @param string $phpType (should always be scalar)
+ * @param array $enumeration array of values
+ * @access public
+ * @see nusoap_xmlschema
+ * @see getTypeDef
+ */
+ function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
+ $this->simpleTypes[$name] = array(
+ 'name' => $name,
+ 'typeClass' => $typeClass,
+ 'phpType' => $phpType,
+ 'type' => $restrictionBase,
+ 'enumeration' => $enumeration
+ );
+
+ $this->xdebug("addSimpleType $name:");
+ $this->appendDebug($this->varDump($this->simpleTypes[$name]));
+ }
+
+ /**
+ * adds an element to the schema
+ *
+ * @param array $attrs attributes that must include name and type
+ * @see nusoap_xmlschema
+ * @access public
+ */
+ function addElement($attrs) {
+ if (! $this->getPrefix($attrs['type'])) {
+ $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type'];
+ }
+ $this->elements[ $attrs['name'] ] = $attrs;
+ $this->elements[ $attrs['name'] ]['typeClass'] = 'element';
+
+ $this->xdebug("addElement " . $attrs['name']);
+ $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ]));
+ }
+}
+
+/**
+ * Backward compatibility
+ */
+class XMLSchema extends nusoap_xmlschema {
+}
+
+?><?php
+
+
+
+/**
+* For creating serializable abstractions of native PHP types. This class
+* allows element name/namespace, XSD type, and XML attributes to be
+* associated with a value. This is extremely useful when WSDL is not
+* used, but is also useful when WSDL is used with polymorphic types, including
+* xsd:anyType and user-defined types.
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class soapval extends nusoap_base {
+ /**
+ * The XML element name
+ *
+ * @var string
+ * @access private
+ */
+ var $name;
+ /**
+ * The XML type name (string or false)
+ *
+ * @var mixed
+ * @access private
+ */
+ var $type;
+ /**
+ * The PHP value
+ *
+ * @var mixed
+ * @access private
+ */
+ var $value;
+ /**
+ * The XML element namespace (string or false)
+ *
+ * @var mixed
+ * @access private
+ */
+ var $element_ns;
+ /**
+ * The XML type namespace (string or false)
+ *
+ * @var mixed
+ * @access private
+ */
+ var $type_ns;
+ /**
+ * The XML element attributes (array or false)
+ *
+ * @var mixed
+ * @access private
+ */
+ var $attributes;
+
+ /**
+ * constructor
+ *
+ * @param string $name optional name
+ * @param mixed $type optional type name
+ * @param mixed $value optional value
+ * @param mixed $element_ns optional namespace of value
+ * @param mixed $type_ns optional namespace of type
+ * @param mixed $attributes associative array of attributes to add to element serialization
+ * @access public
+ */
+ function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) {
+ parent::nusoap_base();
+ $this->name = $name;
+ $this->type = $type;
+ $this->value = $value;
+ $this->element_ns = $element_ns;
+ $this->type_ns = $type_ns;
+ $this->attributes = $attributes;
+ }
+
+ /**
+ * return serialized value
+ *
+ * @param string $use The WSDL use value (encoded|literal)
+ * @return string XML data
+ * @access public
+ */
+ function serialize($use='encoded') {
+ return $this->serialize_val($this->value, $this->name, $this->type, $this->element_ns, $this->type_ns, $this->attributes, $use, true);
+ }
+
+ /**
+ * decodes a soapval object into a PHP native type
+ *
+ * @return mixed
+ * @access public
+ */
+ function decode(){
+ return $this->value;
+ }
+}
+
+
+
+?><?php
+
+
+
+/**
+* transport class for sending/receiving data via HTTP and HTTPS
+* NOTE: PHP must be compiled with the CURL extension for HTTPS support
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class soap_transport_http extends nusoap_base {
+
+ var $url = '';
+ var $uri = '';
+ var $digest_uri = '';
+ var $scheme = '';
+ var $host = '';
+ var $port = '';
+ var $path = '';
+ var $request_method = 'POST';
+ var $protocol_version = '1.0';
+ var $encoding = '';
+ var $outgoing_headers = array();
+ var $incoming_headers = array();
+ var $incoming_cookies = array();
+ var $outgoing_payload = '';
+ var $incoming_payload = '';
+ var $response_status_line; // HTTP response status line
+ var $useSOAPAction = true;
+ var $persistentConnection = false;
+ var $ch = false; // cURL handle
+ var $ch_options = array(); // cURL custom options
+ var $use_curl = false; // force cURL use
+ var $proxy = null; // proxy information (associative array)
+ var $username = '';
+ var $password = '';
+ var $authtype = '';
+ var $digestRequest = array();
+ var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional)
+ // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem'
+ // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem'
+ // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem'
+ // passphrase: SSL key password/passphrase
+ // certpassword: SSL certificate password
+ // verifypeer: default is 1
+ // verifyhost: default is 1
+
+ /**
+ * constructor
+ *
+ * @param string $url The URL to which to connect
+ * @param array $curl_options User-specified cURL options
+ * @param boolean $use_curl Whether to try to force cURL use
+ * @access public
+ */
+ function soap_transport_http($url, $curl_options = NULL, $use_curl = false){
+ parent::nusoap_base();
+ $this->debug("ctor url=$url use_curl=$use_curl curl_options:");
+ $this->appendDebug($this->varDump($curl_options));
+ $this->setURL($url);
+ if (is_array($curl_options)) {
+ $this->ch_options = $curl_options;
+ }
+ $this->use_curl = $use_curl;
+ preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
+ $this->setHeader('User-Agent', $this->title.'/'.$this->version.' ('.$rev[1].')');
+ }
+
+ /**
+ * sets a cURL option
+ *
+ * @param mixed $option The cURL option (always integer?)
+ * @param mixed $value The cURL option value
+ * @access private
+ */
+ function setCurlOption($option, $value) {
+ $this->debug("setCurlOption option=$option, value=");
+ $this->appendDebug($this->varDump($value));
+ curl_setopt($this->ch, $option, $value);
+ }
+
+ /**
+ * sets an HTTP header
+ *
+ * @param string $name The name of the header
+ * @param string $value The value of the header
+ * @access private
+ */
+ function setHeader($name, $value) {
+ $this->outgoing_headers[$name] = $value;
+ $this->debug("set header $name: $value");
+ }
+
+ /**
+ * unsets an HTTP header
+ *
+ * @param string $name The name of the header
+ * @access private
+ */
+ function unsetHeader($name) {
+ if (isset($this->outgoing_headers[$name])) {
+ $this->debug("unset header $name");
+ unset($this->outgoing_headers[$name]);
+ }
+ }
+
+ /**
+ * sets the URL to which to connect
+ *
+ * @param string $url The URL to which to connect
+ * @access private
+ */
+ function setURL($url) {
+ $this->url = $url;
+
+ $u = parse_url($url);
+ foreach($u as $k => $v){
+ $this->debug("parsed URL $k = $v");
+ $this->$k = $v;
+ }
+
+ // add any GET params to path
+ if(isset($u['query']) && $u['query'] != ''){
+ $this->path .= '?' . $u['query'];
+ }
+
+ // set default port
+ if(!isset($u['port'])){
+ if($u['scheme'] == 'https'){
+ $this->port = 443;
+ } else {
+ $this->port = 80;
+ }
+ }
+
+ $this->uri = $this->path;
+ $this->digest_uri = $this->uri;
+
+ // build headers
+ if (!isset($u['port'])) {
+ $this->setHeader('Host', $this->host);
+ } else {
+ $this->setHeader('Host', $this->host.':'.$this->port);
+ }
+
+ if (isset($u['user']) && $u['user'] != '') {
+ $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : '');
+ }
+ }
+
+ /**
+ * gets the I/O method to use
+ *
+ * @return string I/O method to use (socket|curl|unknown)
+ * @access private
+ */
+ function io_method() {
+ if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm'))
+ return 'curl';
+ if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm'))
+ return 'socket';
+ return 'unknown';
+ }
+
+ /**
+ * establish an HTTP connection
+ *
+ * @param integer $timeout set connection timeout in seconds
+ * @param integer $response_timeout set response timeout in seconds
+ * @return boolean true if connected, false if not
+ * @access private
+ */
+ function connect($connection_timeout=0,$response_timeout=30){
+ // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like
+ // "regular" socket.
+ // TODO: disabled for now because OpenSSL must be *compiled* in (not just
+ // loaded), and until PHP5 stream_get_wrappers is not available.
+// if ($this->scheme == 'https') {
+// if (version_compare(phpversion(), '4.3.0') >= 0) {
+// if (extension_loaded('openssl')) {
+// $this->scheme = 'ssl';
+// $this->debug('Using SSL over OpenSSL');
+// }
+// }
+// }
+ $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port");
+ if ($this->io_method() == 'socket') {
+ if (!is_array($this->proxy)) {
+ $host = $this->host;
+ $port = $this->port;
+ } else {
+ $host = $this->proxy['host'];
+ $port = $this->proxy['port'];
+ }
+
+ // use persistent connection
+ if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){
+ if (!feof($this->fp)) {
+ $this->debug('Re-use persistent connection');
+ return true;
+ }
+ fclose($this->fp);
+ $this->debug('Closed persistent connection at EOF');
+ }
+
+ // munge host if using OpenSSL
+ if ($this->scheme == 'ssl') {
+ $host = 'ssl://' . $host;
+ }
+ $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout);
+
+ // open socket
+ if($connection_timeout > 0){
+ $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout);
+ } else {
+ $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str);
+ }
+
+ // test pointer
+ if(!$this->fp) {
+ $msg = 'Couldn\'t open socket connection to server ' . $this->url;
+ if ($this->errno) {
+ $msg .= ', Error ('.$this->errno.'): '.$this->error_str;
+ } else {
+ $msg .= ' prior to connect(). This is often a problem looking up the host name.';
+ }
+ $this->debug($msg);
+ $this->setError($msg);
+ return false;
+ }
+
+ // set response timeout
+ $this->debug('set response timeout to ' . $response_timeout);
+ socket_set_timeout( $this->fp, $response_timeout);
+
+ $this->debug('socket connected');
+ return true;
+ } else if ($this->io_method() == 'curl') {
+ if (!extension_loaded('curl')) {
+// $this->setError('cURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS');
+ $this->setError('The PHP cURL Extension is required for HTTPS or NLTM. You will need to re-build or update your PHP to include cURL or change php.ini to load the PHP cURL extension.');
+ return false;
+ }
+ // Avoid warnings when PHP does not have these options
+ if (defined('CURLOPT_CONNECTIONTIMEOUT'))
+ $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT;
+ else
+ $CURLOPT_CONNECTIONTIMEOUT = 78;
+ if (defined('CURLOPT_HTTPAUTH'))
+ $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH;
+ else
+ $CURLOPT_HTTPAUTH = 107;
+ if (defined('CURLOPT_PROXYAUTH'))
+ $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH;
+ else
+ $CURLOPT_PROXYAUTH = 111;
+ if (defined('CURLAUTH_BASIC'))
+ $CURLAUTH_BASIC = CURLAUTH_BASIC;
+ else
+ $CURLAUTH_BASIC = 1;
+ if (defined('CURLAUTH_DIGEST'))
+ $CURLAUTH_DIGEST = CURLAUTH_DIGEST;
+ else
+ $CURLAUTH_DIGEST = 2;
+ if (defined('CURLAUTH_NTLM'))
+ $CURLAUTH_NTLM = CURLAUTH_NTLM;
+ else
+ $CURLAUTH_NTLM = 8;
+
+ $this->debug('connect using cURL');
+ // init CURL
+ $this->ch = curl_init();
+ // set url
+ $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host";
+ // add path
+ $hostURL .= $this->path;
+ $this->setCurlOption(CURLOPT_URL, $hostURL);
+ // follow location headers (re-directs)
+ if (ini_get('safe_mode') || ini_get('open_basedir')) {
+ $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION');
+ $this->debug('safe_mode = ');
+ $this->appendDebug($this->varDump(ini_get('safe_mode')));
+ $this->debug('open_basedir = ');
+ $this->appendDebug($this->varDump(ini_get('open_basedir')));
+ } else {
+ $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1);
+ }
+ // ask for headers in the response output
+ $this->setCurlOption(CURLOPT_HEADER, 1);
+ // ask for the response output as the return value
+ $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1);
+ // encode
+ // We manage this ourselves through headers and encoding
+// if(function_exists('gzuncompress')){
+// $this->setCurlOption(CURLOPT_ENCODING, 'deflate');
+// }
+ // persistent connection
+ if ($this->persistentConnection) {
+ // I believe the following comment is now bogus, having applied to
+ // the code when it used CURLOPT_CUSTOMREQUEST to send the request.
+ // The way we send data, we cannot use persistent connections, since
+ // there will be some "junk" at the end of our request.
+ //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true);
+ $this->persistentConnection = false;
+ $this->setHeader('Connection', 'close');
+ }
+ // set timeouts
+ if ($connection_timeout != 0) {
+ $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout);
+ }
+ if ($response_timeout != 0) {
+ $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout);
+ }
+
+ if ($this->scheme == 'https') {
+ $this->debug('set cURL SSL verify options');
+ // recent versions of cURL turn on peer/host checking by default,
+ // while PHP binaries are not compiled with a default location for the
+ // CA cert bundle, so disable peer/host checking.
+ //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt');
+ $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
+ $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
+
+ // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo)
+ if ($this->authtype == 'certificate') {
+ $this->debug('set cURL certificate options');
+ if (isset($this->certRequest['cainfofile'])) {
+ $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']);
+ }
+ if (isset($this->certRequest['verifypeer'])) {
+ $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']);
+ } else {
+ $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1);
+ }
+ if (isset($this->certRequest['verifyhost'])) {
+ $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']);
+ } else {
+ $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1);
+ }
+ if (isset($this->certRequest['sslcertfile'])) {
+ $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']);
+ }
+ if (isset($this->certRequest['sslkeyfile'])) {
+ $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']);
+ }
+ if (isset($this->certRequest['passphrase'])) {
+ $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']);
+ }
+ if (isset($this->certRequest['certpassword'])) {
+ $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']);
+ }
+ }
+ }
+ if ($this->authtype && ($this->authtype != 'certificate')) {
+ if ($this->username) {
+ $this->debug('set cURL username/password');
+ $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password");
+ }
+ if ($this->authtype == 'basic') {
+ $this->debug('set cURL for Basic authentication');
+ $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC);
+ }
+ if ($this->authtype == 'digest') {
+ $this->debug('set cURL for digest authentication');
+ $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST);
+ }
+ if ($this->authtype == 'ntlm') {
+ $this->debug('set cURL for NTLM authentication');
+ $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM);
+ }
+ }
+ if (is_array($this->proxy)) {
+ $this->debug('set cURL proxy options');
+ if ($this->proxy['port'] != '') {
+ $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'].':'.$this->proxy['port']);
+ } else {
+ $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']);
+ }
+ if ($this->proxy['username'] || $this->proxy['password']) {
+ $this->debug('set cURL proxy authentication options');
+ $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'].':'.$this->proxy['password']);
+ if ($this->proxy['authtype'] == 'basic') {
+ $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC);
+ }
+ if ($this->proxy['authtype'] == 'ntlm') {
+ $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM);
+ }
+ }
+ }
+ $this->debug('cURL connection set up');
+ return true;
+ } else {
+ $this->setError('Unknown scheme ' . $this->scheme);
+ $this->debug('Unknown scheme ' . $this->scheme);
+ return false;
+ }
+ }
+
+ /**
+ * sends the SOAP request and gets the SOAP response via HTTP[S]
+ *
+ * @param string $data message data
+ * @param integer $timeout set connection timeout in seconds
+ * @param integer $response_timeout set response timeout in seconds
+ * @param array $cookies cookies to send
+ * @return string data
+ * @access public
+ */
+ function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) {
+
+ $this->debug('entered send() with data of length: '.strlen($data));
+
+ $this->tryagain = true;
+ $tries = 0;
+ while ($this->tryagain) {
+ $this->tryagain = false;
+ if ($tries++ < 2) {
+ // make connnection
+ if (!$this->connect($timeout, $response_timeout)){
+ return false;
+ }
+
+ // send request
+ if (!$this->sendRequest($data, $cookies)){
+ return false;
+ }
+
+ // get response
+ $respdata = $this->getResponse();
+ } else {
+ $this->setError("Too many tries to get an OK response ($this->response_status_line)");
+ }
+ }
+ $this->debug('end of send()');
+ return $respdata;
+ }
+
+
+ /**
+ * sends the SOAP request and gets the SOAP response via HTTPS using CURL
+ *
+ * @param string $data message data
+ * @param integer $timeout set connection timeout in seconds
+ * @param integer $response_timeout set response timeout in seconds
+ * @param array $cookies cookies to send
+ * @return string data
+ * @access public
+ * @deprecated
+ */
+ function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
+ return $this->send($data, $timeout, $response_timeout, $cookies);
+ }
+
+ /**
+ * if authenticating, set user credentials here
+ *
+ * @param string $username
+ * @param string $password
+ * @param string $authtype (basic|digest|certificate|ntlm)
+ * @param array $digestRequest (keys must be nonce, nc, realm, qop)
+ * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
+ * @access public
+ */
+ function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) {
+ $this->debug("setCredentials username=$username authtype=$authtype digestRequest=");
+ $this->appendDebug($this->varDump($digestRequest));
+ $this->debug("certRequest=");
+ $this->appendDebug($this->varDump($certRequest));
+ // cf. RFC 2617
+ if ($authtype == 'basic') {
+ $this->setHeader('Authorization', 'Basic '.base64_encode(str_replace(':','',$username).':'.$password));
+ } elseif ($authtype == 'digest') {
+ if (isset($digestRequest['nonce'])) {
+ $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1;
+
+ // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html)
+
+ // A1 = unq(username-value) ":" unq(realm-value) ":" passwd
+ $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password;
+
+ // H(A1) = MD5(A1)
+ $HA1 = md5($A1);
+
+ // A2 = Method ":" digest-uri-value
+ $A2 = $this->request_method . ':' . $this->digest_uri;
+
+ // H(A2)
+ $HA2 = md5($A2);
+
+ // KD(secret, data) = H(concat(secret, ":", data))
+ // if qop == auth:
+ // request-digest = <"> < KD ( H(A1), unq(nonce-value)
+ // ":" nc-value
+ // ":" unq(cnonce-value)
+ // ":" unq(qop-value)
+ // ":" H(A2)
+ // ) <">
+ // if qop is missing,
+ // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
+
+ $unhashedDigest = '';
+ $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : '';
+ $cnonce = $nonce;
+ if ($digestRequest['qop'] != '') {
+ $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2;
+ } else {
+ $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2;
+ }
+
+ $hashedDigest = md5($unhashedDigest);
+
+ $opaque = '';
+ if (isset($digestRequest['opaque'])) {
+ $opaque = ', opaque="' . $digestRequest['opaque'] . '"';
+ }
+
+ $this->setHeader('Authorization', 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . $opaque . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"');
+ }
+ } elseif ($authtype == 'certificate') {
+ $this->certRequest = $certRequest;
+ $this->debug('Authorization header not set for certificate');
+ } elseif ($authtype == 'ntlm') {
+ // do nothing
+ $this->debug('Authorization header not set for ntlm');
+ }
+ $this->username = $username;
+ $this->password = $password;
+ $this->authtype = $authtype;
+ $this->digestRequest = $digestRequest;
+ }
+
+ /**
+ * set the soapaction value
+ *
+ * @param string $soapaction
+ * @access public
+ */
+ function setSOAPAction($soapaction) {
+ $this->setHeader('SOAPAction', '"' . $soapaction . '"');
+ }
+
+ /**
+ * use http encoding
+ *
+ * @param string $enc encoding style. supported values: gzip, deflate, or both
+ * @access public
+ */
+ function setEncoding($enc='gzip, deflate') {
+ if (function_exists('gzdeflate')) {
+ $this->protocol_version = '1.1';
+ $this->setHeader('Accept-Encoding', $enc);
+ if (!isset($this->outgoing_headers['Connection'])) {
+ $this->setHeader('Connection', 'close');
+ $this->persistentConnection = false;
+ }
+ // deprecated as of PHP 5.3.0
+ //set_magic_quotes_runtime(0);
+ $this->encoding = $enc;
+ }
+ }
+
+ /**
+ * set proxy info here
+ *
+ * @param string $proxyhost use an empty string to remove proxy
+ * @param string $proxyport
+ * @param string $proxyusername
+ * @param string $proxypassword
+ * @param string $proxyauthtype (basic|ntlm)
+ * @access public
+ */
+ function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') {
+ if ($proxyhost) {
+ $this->proxy = array(
+ 'host' => $proxyhost,
+ 'port' => $proxyport,
+ 'username' => $proxyusername,
+ 'password' => $proxypassword,
+ 'authtype' => $proxyauthtype
+ );
+ if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') {
+ $this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword));
+ }
+ } else {
+ $this->debug('remove proxy');
+ $proxy = null;
+ unsetHeader('Proxy-Authorization');
+ }
+ }
+
+
+ /**
+ * Test if the given string starts with a header that is to be skipped.
+ * Skippable headers result from chunked transfer and proxy requests.
+ *
+ * @param string $data The string to check.
+ * @returns boolean Whether a skippable header was found.
+ * @access private
+ */
+ function isSkippableCurlHeader(&$data) {
+ $skipHeaders = array( 'HTTP/1.1 100',
+ 'HTTP/1.0 301',
+ 'HTTP/1.1 301',
+ 'HTTP/1.0 302',
+ 'HTTP/1.1 302',
+ 'HTTP/1.0 401',
+ 'HTTP/1.1 401',
+ 'HTTP/1.0 200 Connection established');
+ foreach ($skipHeaders as $hd) {
+ $prefix = substr($data, 0, strlen($hd));
+ if ($prefix == $hd) return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * decode a string that is encoded w/ "chunked' transfer encoding
+ * as defined in RFC2068 19.4.6
+ *
+ * @param string $buffer
+ * @param string $lb
+ * @returns string
+ * @access public
+ * @deprecated
+ */
+ function decodeChunked($buffer, $lb){
+ // length := 0
+ $length = 0;
+ $new = '';
+
+ // read chunk-size, chunk-extension (if any) and CRLF
+ // get the position of the linebreak
+ $chunkend = strpos($buffer, $lb);
+ if ($chunkend == FALSE) {
+ $this->debug('no linebreak found in decodeChunked');
+ return $new;
+ }
+ $temp = substr($buffer,0,$chunkend);
+ $chunk_size = hexdec( trim($temp) );
+ $chunkstart = $chunkend + strlen($lb);
+ // while (chunk-size > 0) {
+ while ($chunk_size > 0) {
+ $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size");
+ $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size);
+
+ // Just in case we got a broken connection
+ if ($chunkend == FALSE) {
+ $chunk = substr($buffer,$chunkstart);
+ // append chunk-data to entity-body
+ $new .= $chunk;
+ $length += strlen($chunk);
+ break;
+ }
+
+ // read chunk-data and CRLF
+ $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
+ // append chunk-data to entity-body
+ $new .= $chunk;
+ // length := length + chunk-size
+ $length += strlen($chunk);
+ // read chunk-size and CRLF
+ $chunkstart = $chunkend + strlen($lb);
+
+ $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb);
+ if ($chunkend == FALSE) {
+ break; //Just in case we got a broken connection
+ }
+ $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
+ $chunk_size = hexdec( trim($temp) );
+ $chunkstart = $chunkend;
+ }
+ return $new;
+ }
+
+ /**
+ * Writes the payload, including HTTP headers, to $this->outgoing_payload.
+ *
+ * @param string $data HTTP body
+ * @param string $cookie_str data for HTTP Cookie header
+ * @return void
+ * @access private
+ */
+ function buildPayload($data, $cookie_str = '') {
+ // Note: for cURL connections, $this->outgoing_payload is ignored,
+ // as is the Content-Length header, but these are still created as
+ // debugging guides.
+
+ // add content-length header
+ if ($this->request_method != 'GET') {
+ $this->setHeader('Content-Length', strlen($data));
+ }
+
+ // start building outgoing payload:
+ if ($this->proxy) {
+ $uri = $this->url;
+ } else {
+ $uri = $this->uri;
+ }
+ $req = "$this->request_method $uri HTTP/$this->protocol_version";
+ $this->debug("HTTP request: $req");
+ $this->outgoing_payload = "$req\r\n";
+
+ // loop thru headers, serializing
+ foreach($this->outgoing_headers as $k => $v){
+ $hdr = $k.': '.$v;
+ $this->debug("HTTP header: $hdr");
+ $this->outgoing_payload .= "$hdr\r\n";
+ }
+
+ // add any cookies
+ if ($cookie_str != '') {
+ $hdr = 'Cookie: '.$cookie_str;
+ $this->debug("HTTP header: $hdr");
+ $this->outgoing_payload .= "$hdr\r\n";
+ }
+
+ // header/body separator
+ $this->outgoing_payload .= "\r\n";
+
+ // add data
+ $this->outgoing_payload .= $data;
+ }
+
+ /**
+ * sends the SOAP request via HTTP[S]
+ *
+ * @param string $data message data
+ * @param array $cookies cookies to send
+ * @return boolean true if OK, false if problem
+ * @access private
+ */
+ function sendRequest($data, $cookies = NULL) {
+ // build cookie string
+ $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https')));
+
+ // build payload
+ $this->buildPayload($data, $cookie_str);
+
+ if ($this->io_method() == 'socket') {
+ // send payload
+ if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
+ $this->setError('couldn\'t write message data to socket');
+ $this->debug('couldn\'t write message data to socket');
+ return false;
+ }
+ $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload));
+ return true;
+ } else if ($this->io_method() == 'curl') {
+ // set payload
+ // cURL does say this should only be the verb, and in fact it
+ // turns out that the URI and HTTP version are appended to this, which
+ // some servers refuse to work with (so we no longer use this method!)
+ //$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $this->outgoing_payload);
+ $curl_headers = array();
+ foreach($this->outgoing_headers as $k => $v){
+ if ($k == 'Connection' || $k == 'Content-Length' || $k == 'Host' || $k == 'Authorization' || $k == 'Proxy-Authorization') {
+ $this->debug("Skip cURL header $k: $v");
+ } else {
+ $curl_headers[] = "$k: $v";
+ }
+ }
+ if ($cookie_str != '') {
+ $curl_headers[] = 'Cookie: ' . $cookie_str;
+ }
+ $this->setCurlOption(CURLOPT_HTTPHEADER, $curl_headers);
+ $this->debug('set cURL HTTP headers');
+ if ($this->request_method == "POST") {
+ $this->setCurlOption(CURLOPT_POST, 1);
+ $this->setCurlOption(CURLOPT_POSTFIELDS, $data);
+ $this->debug('set cURL POST data');
+ } else {
+ }
+ // insert custom user-set cURL options
+ foreach ($this->ch_options as $key => $val) {
+ $this->setCurlOption($key, $val);
+ }
+
+ $this->debug('set cURL payload');
+ return true;
+ }
+ }
+
+ /**
+ * gets the SOAP response via HTTP[S]
+ *
+ * @return string the response (also sets member variables like incoming_payload)
+ * @access private
+ */
+ function getResponse(){
+ $this->incoming_payload = '';
+
+ if ($this->io_method() == 'socket') {
+ // loop until headers have been retrieved
+ $data = '';
+ while (!isset($lb)){
+
+ // We might EOF during header read.
+ if(feof($this->fp)) {
+ $this->incoming_payload = $data;
+ $this->debug('found no headers before EOF after length ' . strlen($data));
+ $this->debug("received before EOF:\n" . $data);
+ $this->setError('server failed to send headers');
+ return false;
+ }
+
+ $tmp = fgets($this->fp, 256);
+ $tmplen = strlen($tmp);
+ $this->debug("read line of $tmplen bytes: " . trim($tmp));
+
+ if ($tmplen == 0) {
+ $this->incoming_payload = $data;
+ $this->debug('socket read of headers timed out after length ' . strlen($data));
+ $this->debug("read before timeout: " . $data);
+ $this->setError('socket read of headers timed out');
+ return false;
+ }
+
+ $data .= $tmp;
+ $pos = strpos($data,"\r\n\r\n");
+ if($pos > 1){
+ $lb = "\r\n";
+ } else {
+ $pos = strpos($data,"\n\n");
+ if($pos > 1){
+ $lb = "\n";
+ }
+ }
+ // remove 100 headers
+ if (isset($lb) && preg_match('/^HTTP\/1.1 100/',$data)) {
+ unset($lb);
+ $data = '';
+ }//
+ }
+ // store header data
+ $this->incoming_payload .= $data;
+ $this->debug('found end of headers after length ' . strlen($data));
+ // process headers
+ $header_data = trim(substr($data,0,$pos));
+ $header_array = explode($lb,$header_data);
+ $this->incoming_headers = array();
+ $this->incoming_cookies = array();
+ foreach($header_array as $header_line){
+ $arr = explode(':',$header_line, 2);
+ if(count($arr) > 1){
+ $header_name = strtolower(trim($arr[0]));
+ $this->incoming_headers[$header_name] = trim($arr[1]);
+ if ($header_name == 'set-cookie') {
+ // TODO: allow multiple cookies from parseCookie
+ $cookie = $this->parseCookie(trim($arr[1]));
+ if ($cookie) {
+ $this->incoming_cookies[] = $cookie;
+ $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
+ } else {
+ $this->debug('did not find cookie in ' . trim($arr[1]));
+ }
+ }
+ } else if (isset($header_name)) {
+ // append continuation line to previous header
+ $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
+ }
+ }
+
+ // loop until msg has been received
+ if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') {
+ $content_length = 2147483647; // ignore any content-length header
+ $chunked = true;
+ $this->debug("want to read chunked content");
+ } elseif (isset($this->incoming_headers['content-length'])) {
+ $content_length = $this->incoming_headers['content-length'];
+ $chunked = false;
+ $this->debug("want to read content of length $content_length");
+ } else {
+ $content_length = 2147483647;
+ $chunked = false;
+ $this->debug("want to read content to EOF");
+ }
+ $data = '';
+ do {
+ if ($chunked) {
+ $tmp = fgets($this->fp, 256);
+ $tmplen = strlen($tmp);
+ $this->debug("read chunk line of $tmplen bytes");
+ if ($tmplen == 0) {
+ $this->incoming_payload = $data;
+ $this->debug('socket read of chunk length timed out after length ' . strlen($data));
+ $this->debug("read before timeout:\n" . $data);
+ $this->setError('socket read of chunk length timed out');
+ return false;
+ }
+ $content_length = hexdec(trim($tmp));
+ $this->debug("chunk length $content_length");
+ }
+ $strlen = 0;
+ while (($strlen < $content_length) && (!feof($this->fp))) {
+ $readlen = min(8192, $content_length - $strlen);
+ $tmp = fread($this->fp, $readlen);
+ $tmplen = strlen($tmp);
+ $this->debug("read buffer of $tmplen bytes");
+ if (($tmplen == 0) && (!feof($this->fp))) {
+ $this->incoming_payload = $data;
+ $this->debug('socket read of body timed out after length ' . strlen($data));
+ $this->debug("read before timeout:\n" . $data);
+ $this->setError('socket read of body timed out');
+ return false;
+ }
+ $strlen += $tmplen;
+ $data .= $tmp;
+ }
+ if ($chunked && ($content_length > 0)) {
+ $tmp = fgets($this->fp, 256);
+ $tmplen = strlen($tmp);
+ $this->debug("read chunk terminator of $tmplen bytes");
+ if ($tmplen == 0) {
+ $this->incoming_payload = $data;
+ $this->debug('socket read of chunk terminator timed out after length ' . strlen($data));
+ $this->debug("read before timeout:\n" . $data);
+ $this->setError('socket read of chunk terminator timed out');
+ return false;
+ }
+ }
+ } while ($chunked && ($content_length > 0) && (!feof($this->fp)));
+ if (feof($this->fp)) {
+ $this->debug('read to EOF');
+ }
+ $this->debug('read body of length ' . strlen($data));
+ $this->incoming_payload .= $data;
+ $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server');
+
+ // close filepointer
+ if(
+ (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') ||
+ (! $this->persistentConnection) || feof($this->fp)){
+ fclose($this->fp);
+ $this->fp = false;
+ $this->debug('closed socket');
+ }
+
+ // connection was closed unexpectedly
+ if($this->incoming_payload == ''){
+ $this->setError('no response from server');
+ return false;
+ }
+
+ // decode transfer-encoding
+// if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){
+// if(!$data = $this->decodeChunked($data, $lb)){
+// $this->setError('Decoding of chunked data failed');
+// return false;
+// }
+ //print "<pre>\nde-chunked:\n---------------\n$data\n\n---------------\n</pre>";
+ // set decoded payload
+// $this->incoming_payload = $header_data.$lb.$lb.$data;
+// }
+
+ } else if ($this->io_method() == 'curl') {
+ // send and receive
+ $this->debug('send and receive with cURL');
+ $this->incoming_payload = curl_exec($this->ch);
+ $data = $this->incoming_payload;
+
+ $cErr = curl_error($this->ch);
+ if ($cErr != '') {
+ $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'<br>';
+ // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
+ foreach(curl_getinfo($this->ch) as $k => $v){
+ $err .= "$k: $v<br>";
+ }
+ $this->debug($err);
+ $this->setError($err);
+ curl_close($this->ch);
+ return false;
+ } else {
+ //echo '<pre>';
+ //var_dump(curl_getinfo($this->ch));
+ //echo '</pre>';
+ }
+ // close curl
+ $this->debug('No cURL error, closing cURL');
+ curl_close($this->ch);
+
+ // try removing skippable headers
+ $savedata = $data;
+ while ($this->isSkippableCurlHeader($data)) {
+ $this->debug("Found HTTP header to skip");
+ if ($pos = strpos($data,"\r\n\r\n")) {
+ $data = ltrim(substr($data,$pos));
+ } elseif($pos = strpos($data,"\n\n") ) {
+ $data = ltrim(substr($data,$pos));
+ }
+ }
+
+ if ($data == '') {
+ // have nothing left; just remove 100 header(s)
+ $data = $savedata;
+ while (preg_match('/^HTTP\/1.1 100/',$data)) {
+ if ($pos = strpos($data,"\r\n\r\n")) {
+ $data = ltrim(substr($data,$pos));
+ } elseif($pos = strpos($data,"\n\n") ) {
+ $data = ltrim(substr($data,$pos));
+ }
+ }
+ }
+
+ // separate content from HTTP headers
+ if ($pos = strpos($data,"\r\n\r\n")) {
+ $lb = "\r\n";
+ } elseif( $pos = strpos($data,"\n\n")) {
+ $lb = "\n";
+ } else {
+ $this->debug('no proper separation of headers and document');
+ $this->setError('no proper separation of headers and document');
+ return false;
+ }
+ $header_data = trim(substr($data,0,$pos));
+ $header_array = explode($lb,$header_data);
+ $data = ltrim(substr($data,$pos));
+ $this->debug('found proper separation of headers and document');
+ $this->debug('cleaned data, stringlen: '.strlen($data));
+ // clean headers
+ foreach ($header_array as $header_line) {
+ $arr = explode(':',$header_line,2);
+ if(count($arr) > 1){
+ $header_name = strtolower(trim($arr[0]));
+ $this->incoming_headers[$header_name] = trim($arr[1]);
+ if ($header_name == 'set-cookie') {
+ // TODO: allow multiple cookies from parseCookie
+ $cookie = $this->parseCookie(trim($arr[1]));
+ if ($cookie) {
+ $this->incoming_cookies[] = $cookie;
+ $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
+ } else {
+ $this->debug('did not find cookie in ' . trim($arr[1]));
+ }
+ }
+ } else if (isset($header_name)) {
+ // append continuation line to previous header
+ $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
+ }
+ }
+ }
+
+ $this->response_status_line = $header_array[0];
+ $arr = explode(' ', $this->response_status_line, 3);
+ $http_version = $arr[0];
+ $http_status = intval($arr[1]);
+ $http_reason = count($arr) > 2 ? $arr[2] : '';
+
+ // see if we need to resend the request with http digest authentication
+ if (isset($this->incoming_headers['location']) && ($http_status == 301 || $http_status == 302)) {
+ $this->debug("Got $http_status $http_reason with Location: " . $this->incoming_headers['location']);
+ $this->setURL($this->incoming_headers['location']);
+ $this->tryagain = true;
+ return false;
+ }
+
+ // see if we need to resend the request with http digest authentication
+ if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) {
+ $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']);
+ if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) {
+ $this->debug('Server wants digest authentication');
+ // remove "Digest " from our elements
+ $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']);
+
+ // parse elements into array
+ $digestElements = explode(',', $digestString);
+ foreach ($digestElements as $val) {
+ $tempElement = explode('=', trim($val), 2);
+ $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]);
+ }
+
+ // should have (at least) qop, realm, nonce
+ if (isset($digestRequest['nonce'])) {
+ $this->setCredentials($this->username, $this->password, 'digest', $digestRequest);
+ $this->tryagain = true;
+ return false;
+ }
+ }
+ $this->debug('HTTP authentication failed');
+ $this->setError('HTTP authentication failed');
+ return false;
+ }
+
+ if (
+ ($http_status >= 300 && $http_status <= 307) ||
+ ($http_status >= 400 && $http_status <= 417) ||
+ ($http_status >= 501 && $http_status <= 505)
+ ) {
+ $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)");
+ return false;
+ }
+
+ // decode content-encoding
+ if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){
+ if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){
+ // if decoding works, use it. else assume data wasn't gzencoded
+ if(function_exists('gzinflate')){
+ //$timer->setMarker('starting decoding of gzip/deflated content');
+ // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress)
+ // this means there are no Zlib headers, although there should be
+ $this->debug('The gzinflate function exists');
+ $datalen = strlen($data);
+ if ($this->incoming_headers['content-encoding'] == 'deflate') {
+ if ($degzdata = @gzinflate($data)) {
+ $data = $degzdata;
+ $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes');
+ if (strlen($data) < $datalen) {
+ // test for the case that the payload has been compressed twice
+ $this->debug('The inflated payload is smaller than the gzipped one; try again');
+ if ($degzdata = @gzinflate($data)) {
+ $data = $degzdata;
+ $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes');
+ }
+ }
+ } else {
+ $this->debug('Error using gzinflate to inflate the payload');
+ $this->setError('Error using gzinflate to inflate the payload');
+ }
+ } elseif ($this->incoming_headers['content-encoding'] == 'gzip') {
+ if ($degzdata = @gzinflate(substr($data, 10))) { // do our best
+ $data = $degzdata;
+ $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes');
+ if (strlen($data) < $datalen) {
+ // test for the case that the payload has been compressed twice
+ $this->debug('The un-gzipped payload is smaller than the gzipped one; try again');
+ if ($degzdata = @gzinflate(substr($data, 10))) {
+ $data = $degzdata;
+ $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes');
+ }
+ }
+ } else {
+ $this->debug('Error using gzinflate to un-gzip the payload');
+ $this->setError('Error using gzinflate to un-gzip the payload');
+ }
+ }
+ //$timer->setMarker('finished decoding of gzip/deflated content');
+ //print "<xmp>\nde-inflated:\n---------------\n$data\n-------------\n</xmp>";
+ // set decoded payload
+ $this->incoming_payload = $header_data.$lb.$lb.$data;
+ } else {
+ $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
+ $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
+ }
+ } else {
+ $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
+ $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
+ }
+ } else {
+ $this->debug('No Content-Encoding header');
+ }
+
+ if(strlen($data) == 0){
+ $this->debug('no data after headers!');
+ $this->setError('no data present after HTTP headers');
+ return false;
+ }
+
+ return $data;
+ }
+
+ /**
+ * sets the content-type for the SOAP message to be sent
+ *
+ * @param string $type the content type, MIME style
+ * @param mixed $charset character set used for encoding (or false)
+ * @access public
+ */
+ function setContentType($type, $charset = false) {
+ $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : ''));
+ }
+
+ /**
+ * specifies that an HTTP persistent connection should be used
+ *
+ * @return boolean whether the request was honored by this method.
+ * @access public
+ */
+ function usePersistentConnection(){
+ if (isset($this->outgoing_headers['Accept-Encoding'])) {
+ return false;
+ }
+ $this->protocol_version = '1.1';
+ $this->persistentConnection = true;
+ $this->setHeader('Connection', 'Keep-Alive');
+ return true;
+ }
+
+ /**
+ * parse an incoming Cookie into it's parts
+ *
+ * @param string $cookie_str content of cookie
+ * @return array with data of that cookie
+ * @access private
+ */
+ /*
+ * TODO: allow a Set-Cookie string to be parsed into multiple cookies
+ */
+ function parseCookie($cookie_str) {
+ $cookie_str = str_replace('; ', ';', $cookie_str) . ';';
+ $data = preg_split('/;/', $cookie_str);
+ $value_str = $data[0];
+
+ $cookie_param = 'domain=';
+ $start = strpos($cookie_str, $cookie_param);
+ if ($start > 0) {
+ $domain = substr($cookie_str, $start + strlen($cookie_param));
+ $domain = substr($domain, 0, strpos($domain, ';'));
+ } else {
+ $domain = '';
+ }
+
+ $cookie_param = 'expires=';
+ $start = strpos($cookie_str, $cookie_param);
+ if ($start > 0) {
+ $expires = substr($cookie_str, $start + strlen($cookie_param));
+ $expires = substr($expires, 0, strpos($expires, ';'));
+ } else {
+ $expires = '';
+ }
+
+ $cookie_param = 'path=';
+ $start = strpos($cookie_str, $cookie_param);
+ if ( $start > 0 ) {
+ $path = substr($cookie_str, $start + strlen($cookie_param));
+ $path = substr($path, 0, strpos($path, ';'));
+ } else {
+ $path = '/';
+ }
+
+ $cookie_param = ';secure;';
+ if (strpos($cookie_str, $cookie_param) !== FALSE) {
+ $secure = true;
+ } else {
+ $secure = false;
+ }
+
+ $sep_pos = strpos($value_str, '=');
+
+ if ($sep_pos) {
+ $name = substr($value_str, 0, $sep_pos);
+ $value = substr($value_str, $sep_pos + 1);
+ $cookie= array( 'name' => $name,
+ 'value' => $value,
+ 'domain' => $domain,
+ 'path' => $path,
+ 'expires' => $expires,
+ 'secure' => $secure
+ );
+ return $cookie;
+ }
+ return false;
+ }
+
+ /**
+ * sort out cookies for the current request
+ *
+ * @param array $cookies array with all cookies
+ * @param boolean $secure is the send-content secure or not?
+ * @return string for Cookie-HTTP-Header
+ * @access private
+ */
+ function getCookiesForRequest($cookies, $secure=false) {
+ $cookie_str = '';
+ if ((! is_null($cookies)) && (is_array($cookies))) {
+ foreach ($cookies as $cookie) {
+ if (! is_array($cookie)) {
+ continue;
+ }
+ $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']);
+ if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
+ if (strtotime($cookie['expires']) <= time()) {
+ $this->debug('cookie has expired');
+ continue;
+ }
+ }
+ if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) {
+ $domain = preg_quote($cookie['domain']);
+ if (! preg_match("'.*$domain$'i", $this->host)) {
+ $this->debug('cookie has different domain');
+ continue;
+ }
+ }
+ if ((isset($cookie['path'])) && (! empty($cookie['path']))) {
+ $path = preg_quote($cookie['path']);
+ if (! preg_match("'^$path.*'i", $this->path)) {
+ $this->debug('cookie is for a different path');
+ continue;
+ }
+ }
+ if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) {
+ $this->debug('cookie is secure, transport is not');
+ continue;
+ }
+ $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; ';
+ $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']);
+ }
+ }
+ return $cookie_str;
+ }
+}
+
+?><?php
+
+
+
+/**
+*
+* nusoap_server allows the user to create a SOAP server
+* that is capable of receiving messages and returning responses
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_server extends nusoap_base {
+ /**
+ * HTTP headers of request
+ * @var array
+ * @access private
+ */
+ var $headers = array();
+ /**
+ * HTTP request
+ * @var string
+ * @access private
+ */
+ var $request = '';
+ /**
+ * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text)
+ * @var string
+ * @access public
+ */
+ var $requestHeaders = '';
+ /**
+ * SOAP Headers from request (parsed)
+ * @var mixed
+ * @access public
+ */
+ var $requestHeader = NULL;
+ /**
+ * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text)
+ * @var string
+ * @access public
+ */
+ var $document = '';
+ /**
+ * SOAP payload for request (text)
+ * @var string
+ * @access public
+ */
+ var $requestSOAP = '';
+ /**
+ * requested method namespace URI
+ * @var string
+ * @access private
+ */
+ var $methodURI = '';
+ /**
+ * name of method requested
+ * @var string
+ * @access private
+ */
+ var $methodname = '';
+ /**
+ * method parameters from request
+ * @var array
+ * @access private
+ */
+ var $methodparams = array();
+ /**
+ * SOAP Action from request
+ * @var string
+ * @access private
+ */
+ var $SOAPAction = '';
+ /**
+ * character set encoding of incoming (request) messages
+ * @var string
+ * @access public
+ */
+ var $xml_encoding = '';
+ /**
+ * toggles whether the parser decodes element content w/ utf8_decode()
+ * @var boolean
+ * @access public
+ */
+ var $decode_utf8 = true;
+
+ /**
+ * HTTP headers of response
+ * @var array
+ * @access public
+ */
+ var $outgoing_headers = array();
+ /**
+ * HTTP response
+ * @var string
+ * @access private
+ */
+ var $response = '';
+ /**
+ * SOAP headers for response (text or array of soapval or associative array)
+ * @var mixed
+ * @access public
+ */
+ var $responseHeaders = '';
+ /**
+ * SOAP payload for response (text)
+ * @var string
+ * @access private
+ */
+ var $responseSOAP = '';
+ /**
+ * method return value to place in response
+ * @var mixed
+ * @access private
+ */
+ var $methodreturn = false;
+ /**
+ * whether $methodreturn is a string of literal XML
+ * @var boolean
+ * @access public
+ */
+ var $methodreturnisliteralxml = false;
+ /**
+ * SOAP fault for response (or false)
+ * @var mixed
+ * @access private
+ */
+ var $fault = false;
+ /**
+ * text indication of result (for debugging)
+ * @var string
+ * @access private
+ */
+ var $result = 'successful';
+
+ /**
+ * assoc array of operations => opData; operations are added by the register()
+ * method or by parsing an external WSDL definition
+ * @var array
+ * @access private
+ */
+ var $operations = array();
+ /**
+ * wsdl instance (if one)
+ * @var mixed
+ * @access private
+ */
+ var $wsdl = false;
+ /**
+ * URL for WSDL (if one)
+ * @var mixed
+ * @access private
+ */
+ var $externalWSDLURL = false;
+ /**
+ * whether to append debug to response as XML comment
+ * @var boolean
+ * @access public
+ */
+ var $debug_flag = false;
+
+
+ /**
+ * constructor
+ * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to.
+ *
+ * @param mixed $wsdl file path or URL (string), or wsdl instance (object)
+ * @access public
+ */
+ function nusoap_server($wsdl=false){
+ parent::nusoap_base();
+ // turn on debugging?
+ global $debug;
+ global $HTTP_SERVER_VARS;
+
+ if (isset($_SERVER)) {
+ $this->debug("_SERVER is defined:");
+ $this->appendDebug($this->varDump($_SERVER));
+ } elseif (isset($HTTP_SERVER_VARS)) {
+ $this->debug("HTTP_SERVER_VARS is defined:");
+ $this->appendDebug($this->varDump($HTTP_SERVER_VARS));
+ } else {
+ $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined.");
+ }
+
+ if (isset($debug)) {
+ $this->debug("In nusoap_server, set debug_flag=$debug based on global flag");
+ $this->debug_flag = $debug;
+ } elseif (isset($_SERVER['QUERY_STRING'])) {
+ $qs = explode('&', $_SERVER['QUERY_STRING']);
+ foreach ($qs as $v) {
+ if (substr($v, 0, 6) == 'debug=') {
+ $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1");
+ $this->debug_flag = substr($v, 6);
+ }
+ }
+ } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
+ $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']);
+ foreach ($qs as $v) {
+ if (substr($v, 0, 6) == 'debug=') {
+ $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2");
+ $this->debug_flag = substr($v, 6);
+ }
+ }
+ }
+
+ // wsdl
+ if($wsdl){
+ $this->debug("In nusoap_server, WSDL is specified");
+ if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) {
+ $this->wsdl = $wsdl;
+ $this->externalWSDLURL = $this->wsdl->wsdl;
+ $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL);
+ } else {
+ $this->debug('Create wsdl from ' . $wsdl);
+ $this->wsdl = new wsdl($wsdl);
+ $this->externalWSDLURL = $wsdl;
+ }
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ if($err = $this->wsdl->getError()){
+ die('WSDL ERROR: '.$err);
+ }
+ }
+ }
+
+ /**
+ * processes request and returns response
+ *
+ * @param string $data usually is the value of $HTTP_RAW_POST_DATA
+ * @access public
+ */
+ function service($data){
+ global $HTTP_SERVER_VARS;
+
+ if (isset($_SERVER['REQUEST_METHOD'])) {
+ $rm = $_SERVER['REQUEST_METHOD'];
+ } elseif (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
+ $rm = $HTTP_SERVER_VARS['REQUEST_METHOD'];
+ } else {
+ $rm = '';
+ }
+
+ if (isset($_SERVER['QUERY_STRING'])) {
+ $qs = $_SERVER['QUERY_STRING'];
+ } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
+ $qs = $HTTP_SERVER_VARS['QUERY_STRING'];
+ } else {
+ $qs = '';
+ }
+ $this->debug("In service, request method=$rm query string=$qs strlen(\$data)=" . strlen($data));
+
+ if ($rm == 'POST') {
+ $this->debug("In service, invoke the request");
+ $this->parse_request($data);
+ if (! $this->fault) {
+ $this->invoke_method();
+ }
+ if (! $this->fault) {
+ $this->serialize_return();
+ }
+ $this->send_response();
+ } elseif (preg_match('/wsdl/', $qs) ){
+ $this->debug("In service, this is a request for WSDL");
+ if ($this->externalWSDLURL){
+ if (strpos($this->externalWSDLURL, "http://") !== false) { // assume URL
+ $this->debug("In service, re-direct for WSDL");
+ header('Location: '.$this->externalWSDLURL);
+ } else { // assume file
+ $this->debug("In service, use file passthru for WSDL");
+ header("Content-Type: text/xml\r\n");
+ $pos = strpos($this->externalWSDLURL, "file://");
+ if ($pos === false) {
+ $filename = $this->externalWSDLURL;
+ } else {
+ $filename = substr($this->externalWSDLURL, $pos + 7);
+ }
+ $fp = fopen($this->externalWSDLURL, 'r');
+ fpassthru($fp);
+ }
+ } elseif ($this->wsdl) {
+ $this->debug("In service, serialize WSDL");
+ header("Content-Type: text/xml; charset=ISO-8859-1\r\n");
+ print $this->wsdl->serialize($this->debug_flag);
+ if ($this->debug_flag) {
+ $this->debug('wsdl:');
+ $this->appendDebug($this->varDump($this->wsdl));
+ print $this->getDebugAsXMLComment();
+ }
+ } else {
+ $this->debug("In service, there is no WSDL");
+ header("Content-Type: text/html; charset=ISO-8859-1\r\n");
+ print "This service does not provide WSDL";
+ }
+ } elseif ($this->wsdl) {
+ $this->debug("In service, return Web description");
+ print $this->wsdl->webDescription();
+ } else {
+ $this->debug("In service, no Web description");
+ header("Content-Type: text/html; charset=ISO-8859-1\r\n");
+ print "This service does not provide a Web description";
+ }
+ }
+
+ /**
+ * parses HTTP request headers.
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * headers
+ * request
+ * xml_encoding
+ * SOAPAction
+ *
+ * @access private
+ */
+ function parse_http_headers() {
+ global $HTTP_SERVER_VARS;
+
+ $this->request = '';
+ $this->SOAPAction = '';
+ if(function_exists('getallheaders')){
+ $this->debug("In parse_http_headers, use getallheaders");
+ $headers = getallheaders();
+ foreach($headers as $k=>$v){
+ $k = strtolower($k);
+ $this->headers[$k] = $v;
+ $this->request .= "$k: $v\r\n";
+ $this->debug("$k: $v");
+ }
+ // get SOAPAction header
+ if(isset($this->headers['soapaction'])){
+ $this->SOAPAction = str_replace('"','',$this->headers['soapaction']);
+ }
+ // get the character encoding of the incoming request
+ if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){
+ $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1));
+ if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ } elseif(isset($_SERVER) && is_array($_SERVER)){
+ $this->debug("In parse_http_headers, use _SERVER");
+ foreach ($_SERVER as $k => $v) {
+ if (substr($k, 0, 5) == 'HTTP_') {
+ $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5))));
+ } else {
+ $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k)));
+ }
+ if ($k == 'soapaction') {
+ // get SOAPAction header
+ $k = 'SOAPAction';
+ $v = str_replace('"', '', $v);
+ $v = str_replace('\\', '', $v);
+ $this->SOAPAction = $v;
+ } else if ($k == 'content-type') {
+ // get the character encoding of the incoming request
+ if (strpos($v, '=')) {
+ $enc = substr(strstr($v, '='), 1);
+ $enc = str_replace('"', '', $enc);
+ $enc = str_replace('\\', '', $enc);
+ if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) {
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ }
+ $this->headers[$k] = $v;
+ $this->request .= "$k: $v\r\n";
+ $this->debug("$k: $v");
+ }
+ } elseif (is_array($HTTP_SERVER_VARS)) {
+ $this->debug("In parse_http_headers, use HTTP_SERVER_VARS");
+ foreach ($HTTP_SERVER_VARS as $k => $v) {
+ if (substr($k, 0, 5) == 'HTTP_') {
+ $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
+ } else {
+ $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
+ }
+ if ($k == 'soapaction') {
+ // get SOAPAction header
+ $k = 'SOAPAction';
+ $v = str_replace('"', '', $v);
+ $v = str_replace('\\', '', $v);
+ $this->SOAPAction = $v;
+ } else if ($k == 'content-type') {
+ // get the character encoding of the incoming request
+ if (strpos($v, '=')) {
+ $enc = substr(strstr($v, '='), 1);
+ $enc = str_replace('"', '', $enc);
+ $enc = str_replace('\\', '', $enc);
+ if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) {
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ }
+ $this->headers[$k] = $v;
+ $this->request .= "$k: $v\r\n";
+ $this->debug("$k: $v");
+ }
+ } else {
+ $this->debug("In parse_http_headers, HTTP headers not accessible");
+ $this->setError("HTTP headers not accessible");
+ }
+ }
+
+ /**
+ * parses a request
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * headers
+ * request
+ * xml_encoding
+ * SOAPAction
+ * request
+ * requestSOAP
+ * methodURI
+ * methodname
+ * methodparams
+ * requestHeaders
+ * document
+ *
+ * This sets the fault field on error
+ *
+ * @param string $data XML string
+ * @access private
+ */
+ function parse_request($data='') {
+ $this->debug('entering parse_request()');
+ $this->parse_http_headers();
+ $this->debug('got character encoding: '.$this->xml_encoding);
+ // uncompress if necessary
+ if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') {
+ $this->debug('got content encoding: ' . $this->headers['content-encoding']);
+ if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') {
+ // if decoding works, use it. else assume data wasn't gzencoded
+ if (function_exists('gzuncompress')) {
+ if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
+ $data = $degzdata;
+ } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) {
+ $data = $degzdata;
+ } else {
+ $this->fault('SOAP-ENV:Client', 'Errors occurred when trying to decode the data');
+ return;
+ }
+ } else {
+ $this->fault('SOAP-ENV:Client', 'This Server does not support compressed data');
+ return;
+ }
+ }
+ }
+ $this->request .= "\r\n".$data;
+ $data = $this->parseRequest($this->headers, $data);
+ $this->requestSOAP = $data;
+ $this->debug('leaving parse_request');
+ }
+
+ /**
+ * invokes a PHP function for the requested SOAP method
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * methodreturn
+ *
+ * Note that the PHP function that is called may also set the following
+ * fields to affect the response sent to the client
+ *
+ * responseHeaders
+ * outgoing_headers
+ *
+ * This sets the fault field on error
+ *
+ * @access private
+ */
+ function invoke_method() {
+ $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction);
+
+ //
+ // if you are debugging in this area of the code, your service uses a class to implement methods,
+ // you use SOAP RPC, and the client is .NET, please be aware of the following...
+ // when the .NET wsdl.exe utility generates a proxy, it will remove the '.' or '..' from the
+ // method name. that is fine for naming the .NET methods. it is not fine for properly constructing
+ // the XML request and reading the XML response. you need to add the RequestElementName and
+ // ResponseElementName to the System.Web.Services.Protocols.SoapRpcMethodAttribute that wsdl.exe
+ // generates for the method. these parameters are used to specify the correct XML element names
+ // for .NET to use, i.e. the names with the '.' in them.
+ //
+ $orig_methodname = $this->methodname;
+ if ($this->wsdl) {
+ if ($this->opData = $this->wsdl->getOperationData($this->methodname)) {
+ $this->debug('in invoke_method, found WSDL operation=' . $this->methodname);
+ $this->appendDebug('opData=' . $this->varDump($this->opData));
+ } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) {
+ // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element
+ $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']);
+ $this->appendDebug('opData=' . $this->varDump($this->opData));
+ $this->methodname = $this->opData['name'];
+ } else {
+ $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname);
+ $this->fault('SOAP-ENV:Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service");
+ return;
+ }
+ } else {
+ $this->debug('in invoke_method, no WSDL to validate method');
+ }
+
+ // if a . is present in $this->methodname, we see if there is a class in scope,
+ // which could be referred to. We will also distinguish between two deliminators,
+ // to allow methods to be called a the class or an instance
+ if (strpos($this->methodname, '..') > 0) {
+ $delim = '..';
+ } else if (strpos($this->methodname, '.') > 0) {
+ $delim = '.';
+ } else {
+ $delim = '';
+ }
+ $this->debug("in invoke_method, delim=$delim");
+
+ $class = '';
+ $method = '';
+ if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) {
+ $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim));
+ if (class_exists($try_class)) {
+ // get the class and method name
+ $class = $try_class;
+ $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
+ $this->debug("in invoke_method, class=$class method=$method delim=$delim");
+ } else {
+ $this->debug("in invoke_method, class=$try_class not found");
+ }
+ } else {
+ $try_class = '';
+ $this->debug("in invoke_method, no class to try");
+ }
+
+ // does method exist?
+ if ($class == '') {
+ if (!function_exists($this->methodname)) {
+ $this->debug("in invoke_method, function '$this->methodname' not found!");
+ $this->result = 'fault: method not found';
+ $this->fault('SOAP-ENV:Client',"method '$this->methodname'('$orig_methodname') not defined in service('$try_class' '$delim')");
+ return;
+ }
+ } else {
+ $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method;
+ if (!in_array($method_to_compare, get_class_methods($class))) {
+ $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!");
+ $this->result = 'fault: method not found';
+ $this->fault('SOAP-ENV:Client',"method '$this->methodname'/'$method_to_compare'('$orig_methodname') not defined in service/'$class'('$try_class' '$delim')");
+ return;
+ }
+ }
+
+ // evaluate message, getting back parameters
+ // verify that request parameters match the method's signature
+ if(! $this->verify_method($this->methodname,$this->methodparams)){
+ // debug
+ $this->debug('ERROR: request not verified against method signature');
+ $this->result = 'fault: request failed validation against method signature';
+ // return fault
+ $this->fault('SOAP-ENV:Client',"Operation '$this->methodname' not defined in service.");
+ return;
+ }
+
+ // if there are parameters to pass
+ $this->debug('in invoke_method, params:');
+ $this->appendDebug($this->varDump($this->methodparams));
+ $this->debug("in invoke_method, calling '$this->methodname'");
+ if (!function_exists('call_user_func_array')) {
+ if ($class == '') {
+ $this->debug('in invoke_method, calling function using eval()');
+ $funcCall = "\$this->methodreturn = $this->methodname(";
+ } else {
+ if ($delim == '..') {
+ $this->debug('in invoke_method, calling class method using eval()');
+ $funcCall = "\$this->methodreturn = ".$class."::".$method."(";
+ } else {
+ $this->debug('in invoke_method, calling instance method using eval()');
+ // generate unique instance name
+ $instname = "\$inst_".time();
+ $funcCall = $instname." = new ".$class."(); ";
+ $funcCall .= "\$this->methodreturn = ".$instname."->".$method."(";
+ }
+ }
+ if ($this->methodparams) {
+ foreach ($this->methodparams as $param) {
+ if (is_array($param) || is_object($param)) {
+ $this->fault('SOAP-ENV:Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available');
+ return;
+ }
+ $funcCall .= "\"$param\",";
+ }
+ $funcCall = substr($funcCall, 0, -1);
+ }
+ $funcCall .= ');';
+ $this->debug('in invoke_method, function call: '.$funcCall);
+ @eval($funcCall);
+ } else {
+ if ($class == '') {
+ $this->debug('in invoke_method, calling function using call_user_func_array()');
+ $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array()
+ } elseif ($delim == '..') {
+ $this->debug('in invoke_method, calling class method using call_user_func_array()');
+ $call_arg = array ($class, $method);
+ } else {
+ $this->debug('in invoke_method, calling instance method using call_user_func_array()');
+ $instance = new $class ();
+ $call_arg = array(&$instance, $method);
+ }
+ if (is_array($this->methodparams)) {
+ $this->methodreturn = call_user_func_array($call_arg, array_values($this->methodparams));
+ } else {
+ $this->methodreturn = call_user_func_array($call_arg, array());
+ }
+ }
+ $this->debug('in invoke_method, methodreturn:');
+ $this->appendDebug($this->varDump($this->methodreturn));
+ $this->debug("in invoke_method, called method $this->methodname, received data of type ".gettype($this->methodreturn));
+ }
+
+ /**
+ * serializes the return value from a PHP function into a full SOAP Envelope
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * responseSOAP
+ *
+ * This sets the fault field on error
+ *
+ * @access private
+ */
+ function serialize_return() {
+ $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI);
+ // if fault
+ if (isset($this->methodreturn) && is_object($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) {
+ $this->debug('got a fault object from method');
+ $this->fault = $this->methodreturn;
+ return;
+ } elseif ($this->methodreturnisliteralxml) {
+ $return_val = $this->methodreturn;
+ // returned value(s)
+ } else {
+ $this->debug('got a(n) '.gettype($this->methodreturn).' from method');
+ $this->debug('serializing return value');
+ if($this->wsdl){
+ if (sizeof($this->opData['output']['parts']) > 1) {
+ $this->debug('more than one output part, so use the method return unchanged');
+ $opParams = $this->methodreturn;
+ } elseif (sizeof($this->opData['output']['parts']) == 1) {
+ $this->debug('exactly one output part, so wrap the method return in a simple array');
+ // TODO: verify that it is not already wrapped!
+ //foreach ($this->opData['output']['parts'] as $name => $type) {
+ // $this->debug('wrap in element named ' . $name);
+ //}
+ $opParams = array($this->methodreturn);
+ }
+ $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams);
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ if($errstr = $this->wsdl->getError()){
+ $this->debug('got wsdl error: '.$errstr);
+ $this->fault('SOAP-ENV:Server', 'unable to serialize result');
+ return;
+ }
+ } else {
+ if (isset($this->methodreturn)) {
+ $return_val = $this->serialize_val($this->methodreturn, 'return');
+ } else {
+ $return_val = '';
+ $this->debug('in absence of WSDL, assume void return for backward compatibility');
+ }
+ }
+ }
+ $this->debug('return value:');
+ $this->appendDebug($this->varDump($return_val));
+
+ $this->debug('serializing response');
+ if ($this->wsdl) {
+ $this->debug('have WSDL for serialization: style is ' . $this->opData['style']);
+ if ($this->opData['style'] == 'rpc') {
+ $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']);
+ if ($this->opData['output']['use'] == 'literal') {
+ // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace
+ if ($this->methodURI) {
+ $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
+ } else {
+ $payload = '<'.$this->methodname.'Response>'.$return_val.'</'.$this->methodname.'Response>';
+ }
+ } else {
+ if ($this->methodURI) {
+ $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
+ } else {
+ $payload = '<'.$this->methodname.'Response>'.$return_val.'</'.$this->methodname.'Response>';
+ }
+ }
+ } else {
+ $this->debug('style is not rpc for serialization: assume document');
+ $payload = $return_val;
+ }
+ } else {
+ $this->debug('do not have WSDL for serialization: assume rpc/encoded');
+ $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
+ }
+ $this->result = 'successful';
+ if($this->wsdl){
+ //if($this->debug_flag){
+ $this->appendDebug($this->wsdl->getDebug());
+ // }
+ if (isset($this->opData['output']['encodingStyle'])) {
+ $encodingStyle = $this->opData['output']['encodingStyle'];
+ } else {
+ $encodingStyle = '';
+ }
+ // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces.
+ $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$this->opData['output']['use'],$encodingStyle);
+ } else {
+ $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders);
+ }
+ $this->debug("Leaving serialize_return");
+ }
+
+ /**
+ * sends an HTTP response
+ *
+ * The following fields are set by this function (when successful)
+ *
+ * outgoing_headers
+ * response
+ *
+ * @access private
+ */
+ function send_response() {
+ $this->debug('Enter send_response');
+ if ($this->fault) {
+ $payload = $this->fault->serialize();
+ $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error";
+ $this->outgoing_headers[] = "Status: 500 Internal Server Error";
+ } else {
+ $payload = $this->responseSOAP;
+ // Some combinations of PHP+Web server allow the Status
+ // to come through as a header. Since OK is the default
+ // just do nothing.
+ // $this->outgoing_headers[] = "HTTP/1.0 200 OK";
+ // $this->outgoing_headers[] = "Status: 200 OK";
+ }
+ // add debug data if in debug mode
+ if(isset($this->debug_flag) && $this->debug_flag){
+ $payload .= $this->getDebugAsXMLComment();
+ }
+ $this->outgoing_headers[] = "Server: $this->title Server v$this->version";
+ preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
+ $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")";
+ // Let the Web server decide about this
+ //$this->outgoing_headers[] = "Connection: Close\r\n";
+ $payload = $this->getHTTPBody($payload);
+ $type = $this->getHTTPContentType();
+ $charset = $this->getHTTPContentTypeCharset();
+ $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : '');
+ //begin code to compress payload - by John
+ // NOTE: there is no way to know whether the Web server will also compress
+ // this data.
+ if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) {
+ if (strstr($this->headers['accept-encoding'], 'gzip')) {
+ if (function_exists('gzencode')) {
+ if (isset($this->debug_flag) && $this->debug_flag) {
+ $payload .= "<!-- Content being gzipped -->";
+ }
+ $this->outgoing_headers[] = "Content-Encoding: gzip";
+ $payload = gzencode($payload);
+ } else {
+ if (isset($this->debug_flag) && $this->debug_flag) {
+ $payload .= "<!-- Content will not be gzipped: no gzencode -->";
+ }
+ }
+ } elseif (strstr($this->headers['accept-encoding'], 'deflate')) {
+ // Note: MSIE requires gzdeflate output (no Zlib header and checksum),
+ // instead of gzcompress output,
+ // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5)
+ if (function_exists('gzdeflate')) {
+ if (isset($this->debug_flag) && $this->debug_flag) {
+ $payload .= "<!-- Content being deflated -->";
+ }
+ $this->outgoing_headers[] = "Content-Encoding: deflate";
+ $payload = gzdeflate($payload);
+ } else {
+ if (isset($this->debug_flag) && $this->debug_flag) {
+ $payload .= "<!-- Content will not be deflated: no gzcompress -->";
+ }
+ }
+ }
+ }
+ //end code
+ $this->outgoing_headers[] = "Content-Length: ".strlen($payload);
+ reset($this->outgoing_headers);
+ foreach($this->outgoing_headers as $hdr){
+ header($hdr, false);
+ }
+ print $payload;
+ $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload;
+ }
+
+ /**
+ * takes the value that was created by parsing the request
+ * and compares to the method's signature, if available.
+ *
+ * @param string $operation The operation to be invoked
+ * @param array $request The array of parameter values
+ * @return boolean Whether the operation was found
+ * @access private
+ */
+ function verify_method($operation,$request){
+ if(isset($this->wsdl) && is_object($this->wsdl)){
+ if($this->wsdl->getOperationData($operation)){
+ return true;
+ }
+ } elseif(isset($this->operations[$operation])){
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * processes SOAP message received from client
+ *
+ * @param array $headers The HTTP headers
+ * @param string $data unprocessed request data from client
+ * @return mixed value of the message, decoded into a PHP type
+ * @access private
+ */
+ function parseRequest($headers, $data) {
+ $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' headers:');
+ $this->appendDebug($this->varDump($headers));
+ if (!isset($headers['content-type'])) {
+ $this->setError('Request not of type text/xml (no content-type header)');
+ return false;
+ }
+ if (!strstr($headers['content-type'], 'text/xml')) {
+ $this->setError('Request not of type text/xml');
+ return false;
+ }
+ if (strpos($headers['content-type'], '=')) {
+ $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
+ $this->debug('Got response encoding: ' . $enc);
+ if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
+ // parse response, get soap parser obj
+ $parser = new nusoap_parser($data,$this->xml_encoding,'',$this->decode_utf8);
+ // parser debug
+ $this->debug("parser debug: \n".$parser->getDebug());
+ // if fault occurred during message parsing
+ if($err = $parser->getError()){
+ $this->result = 'fault: error in msg parsing: '.$err;
+ $this->fault('SOAP-ENV:Client',"error in msg parsing:\n".$err);
+ // else successfully parsed request into soapval object
+ } else {
+ // get/set methodname
+ $this->methodURI = $parser->root_struct_namespace;
+ $this->methodname = $parser->root_struct_name;
+ $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI);
+ $this->debug('calling parser->get_soapbody()');
+ $this->methodparams = $parser->get_soapbody();
+ // get SOAP headers
+ $this->requestHeaders = $parser->getHeaders();
+ // get SOAP Header
+ $this->requestHeader = $parser->get_soapheader();
+ // add document for doclit support
+ $this->document = $parser->document;
+ }
+ }
+
+ /**
+ * gets the HTTP body for the current response.
+ *
+ * @param string $soapmsg The SOAP payload
+ * @return string The HTTP body, which includes the SOAP payload
+ * @access private
+ */
+ function getHTTPBody($soapmsg) {
+ return $soapmsg;
+ }
+
+ /**
+ * gets the HTTP content type for the current response.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type for the current response.
+ * @access private
+ */
+ function getHTTPContentType() {
+ return 'text/xml';
+ }
+
+ /**
+ * gets the HTTP content type charset for the current response.
+ * returns false for non-text content types.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type charset for the current response.
+ * @access private
+ */
+ function getHTTPContentTypeCharset() {
+ return $this->soap_defencoding;
+ }
+
+ /**
+ * add a method to the dispatch map (this has been replaced by the register method)
+ *
+ * @param string $methodname
+ * @param string $in array of input values
+ * @param string $out array of output values
+ * @access public
+ * @deprecated
+ */
+ function add_to_map($methodname,$in,$out){
+ $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out);
+ }
+
+ /**
+ * register a service function with the server
+ *
+ * @param string $name the name of the PHP function, class.method or class..method
+ * @param array $in assoc array of input values: key = param name, value = param type
+ * @param array $out assoc array of output values: key = param name, value = param type
+ * @param mixed $namespace the element namespace for the method or false
+ * @param mixed $soapaction the soapaction for the method or false
+ * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically
+ * @param mixed $use optional (encoded|literal) or false
+ * @param string $documentation optional Description to include in WSDL
+ * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
+ * @access public
+ */
+ function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){
+ global $HTTP_SERVER_VARS;
+
+ if($this->externalWSDLURL){
+ die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.');
+ }
+ if (! $name) {
+ die('You must specify a name when you register an operation');
+ }
+ if (!is_array($in)) {
+ die('You must provide an array for operation inputs');
+ }
+ if (!is_array($out)) {
+ die('You must provide an array for operation outputs');
+ }
+ if(false == $namespace) {
+ }
+ if(false == $soapaction) {
+ if (isset($_SERVER)) {
+ $SERVER_NAME = $_SERVER['SERVER_NAME'];
+ $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
+ $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
+ } elseif (isset($HTTP_SERVER_VARS)) {
+ $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
+ $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
+ $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
+ } else {
+ $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
+ }
+ if ($HTTPS == '1' || $HTTPS == 'on') {
+ $SCHEME = 'https';
+ } else {
+ $SCHEME = 'http';
+ }
+ $soapaction = "$SCHEME://$SERVER_NAME$SCRIPT_NAME/$name";
+ }
+ if(false == $style) {
+ $style = "rpc";
+ }
+ if(false == $use) {
+ $use = "encoded";
+ }
+ if ($use == 'encoded' && $encodingStyle == '') {
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ }
+
+ $this->operations[$name] = array(
+ 'name' => $name,
+ 'in' => $in,
+ 'out' => $out,
+ 'namespace' => $namespace,
+ 'soapaction' => $soapaction,
+ 'style' => $style);
+ if($this->wsdl){
+ $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle);
+ }
+ return true;
+ }
+
+ /**
+ * Specify a fault to be returned to the client.
+ * This also acts as a flag to the server that a fault has occured.
+ *
+ * @param string $faultcode
+ * @param string $faultstring
+ * @param string $faultactor
+ * @param string $faultdetail
+ * @access public
+ */
+ function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){
+ if ($faultdetail == '' && $this->debug_flag) {
+ $faultdetail = $this->getDebug();
+ }
+ $this->fault = new nusoap_fault($faultcode,$faultactor,$faultstring,$faultdetail);
+ $this->fault->soap_defencoding = $this->soap_defencoding;
+ }
+
+ /**
+ * Sets up wsdl object.
+ * Acts as a flag to enable internal WSDL generation
+ *
+ * @param string $serviceName, name of the service
+ * @param mixed $namespace optional 'tns' service namespace or false
+ * @param mixed $endpoint optional URL of service endpoint or false
+ * @param string $style optional (rpc|document) WSDL style (also specified by operation)
+ * @param string $transport optional SOAP transport
+ * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false
+ */
+ function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false)
+ {
+ global $HTTP_SERVER_VARS;
+
+ if (isset($_SERVER)) {
+ $SERVER_NAME = $_SERVER['SERVER_NAME'];
+ $SERVER_PORT = $_SERVER['SERVER_PORT'];
+ $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
+ $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
+ } elseif (isset($HTTP_SERVER_VARS)) {
+ $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
+ $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT'];
+ $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
+ $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
+ } else {
+ $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
+ }
+ // If server name has port number attached then strip it (else port number gets duplicated in WSDL output) (occurred using lighttpd and FastCGI)
+ $colon = strpos($SERVER_NAME,":");
+ if ($colon) {
+ $SERVER_NAME = substr($SERVER_NAME, 0, $colon);
+ }
+ if ($SERVER_PORT == 80) {
+ $SERVER_PORT = '';
+ } else {
+ $SERVER_PORT = ':' . $SERVER_PORT;
+ }
+ if(false == $namespace) {
+ $namespace = "http://$SERVER_NAME/soap/$serviceName";
+ }
+
+ if(false == $endpoint) {
+ if ($HTTPS == '1' || $HTTPS == 'on') {
+ $SCHEME = 'https';
+ } else {
+ $SCHEME = 'http';
+ }
+ $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME";
+ }
+
+ if(false == $schemaTargetNamespace) {
+ $schemaTargetNamespace = $namespace;
+ }
+
+ $this->wsdl = new wsdl;
+ $this->wsdl->serviceName = $serviceName;
+ $this->wsdl->endpoint = $endpoint;
+ $this->wsdl->namespaces['tns'] = $namespace;
+ $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/';
+ $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/';
+ if ($schemaTargetNamespace != $namespace) {
+ $this->wsdl->namespaces['types'] = $schemaTargetNamespace;
+ }
+ $this->wsdl->schemas[$schemaTargetNamespace][0] = new nusoap_xmlschema('', '', $this->wsdl->namespaces);
+ if ($style == 'document') {
+ $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaInfo['elementFormDefault'] = 'qualified';
+ }
+ $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace;
+ $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true);
+ $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true);
+ $this->wsdl->bindings[$serviceName.'Binding'] = array(
+ 'name'=>$serviceName.'Binding',
+ 'style'=>$style,
+ 'transport'=>$transport,
+ 'portType'=>$serviceName.'PortType');
+ $this->wsdl->ports[$serviceName.'Port'] = array(
+ 'binding'=>$serviceName.'Binding',
+ 'location'=>$endpoint,
+ 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/');
+ }
+}
+
+/**
+ * Backward compatibility
+ */
+class soap_server extends nusoap_server {
+}
+
+?><?php
+
+
+
+/**
+* parses a WSDL file, allows access to it's data, other utility methods.
+* also builds WSDL structures programmatically.
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class wsdl extends nusoap_base {
+ // URL or filename of the root of this WSDL
+ var $wsdl;
+ // define internal arrays of bindings, ports, operations, messages, etc.
+ var $schemas = array();
+ var $currentSchema;
+ var $message = array();
+ var $complexTypes = array();
+ var $messages = array();
+ var $currentMessage;
+ var $currentOperation;
+ var $portTypes = array();
+ var $currentPortType;
+ var $bindings = array();
+ var $currentBinding;
+ var $ports = array();
+ var $currentPort;
+ var $opData = array();
+ var $status = '';
+ var $documentation = false;
+ var $endpoint = '';
+ // array of wsdl docs to import
+ var $import = array();
+ // parser vars
+ var $parser;
+ var $position = 0;
+ var $depth = 0;
+ var $depth_array = array();
+ // for getting wsdl
+ var $proxyhost = '';
+ var $proxyport = '';
+ var $proxyusername = '';
+ var $proxypassword = '';
+ var $timeout = 0;
+ var $response_timeout = 30;
+ var $curl_options = array(); // User-specified cURL options
+ var $use_curl = false; // whether to always try to use cURL
+ // for HTTP authentication
+ var $username = ''; // Username for HTTP authentication
+ var $password = ''; // Password for HTTP authentication
+ var $authtype = ''; // Type of HTTP authentication
+ var $certRequest = array(); // Certificate for HTTP SSL authentication
+
+ /**
+ * constructor
+ *
+ * @param string $wsdl WSDL document URL
+ * @param string $proxyhost
+ * @param string $proxyport
+ * @param string $proxyusername
+ * @param string $proxypassword
+ * @param integer $timeout set the connection timeout
+ * @param integer $response_timeout set the response timeout
+ * @param array $curl_options user-specified cURL options
+ * @param boolean $use_curl try to use cURL
+ * @access public
+ */
+ function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30,$curl_options=null,$use_curl=false){
+ parent::nusoap_base();
+ $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
+ $this->proxyhost = $proxyhost;
+ $this->proxyport = $proxyport;
+ $this->proxyusername = $proxyusername;
+ $this->proxypassword = $proxypassword;
+ $this->timeout = $timeout;
+ $this->response_timeout = $response_timeout;
+ if (is_array($curl_options))
+ $this->curl_options = $curl_options;
+ $this->use_curl = $use_curl;
+ $this->fetchWSDL($wsdl);
+ }
+
+ /**
+ * fetches the WSDL document and parses it
+ *
+ * @access public
+ */
+ function fetchWSDL($wsdl) {
+ $this->debug("parse and process WSDL path=$wsdl");
+ $this->wsdl = $wsdl;
+ // parse wsdl file
+ if ($this->wsdl != "") {
+ $this->parseWSDL($this->wsdl);
+ }
+ // imports
+ // TODO: handle imports more properly, grabbing them in-line and nesting them
+ $imported_urls = array();
+ $imported = 1;
+ while ($imported > 0) {
+ $imported = 0;
+ // Schema imports
+ foreach ($this->schemas as $ns => $list) {
+ foreach ($list as $xs) {
+ $wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
+ foreach ($xs->imports as $ns2 => $list2) {
+ for ($ii = 0; $ii < count($list2); $ii++) {
+ if (! $list2[$ii]['loaded']) {
+ $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true;
+ $url = $list2[$ii]['location'];
+ if ($url != '') {
+ $urlparts = parse_url($url);
+ if (!isset($urlparts['host'])) {
+ $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') .
+ substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
+ }
+ if (! in_array($url, $imported_urls)) {
+ $this->parseWSDL($url);
+ $imported++;
+ $imported_urls[] = $url;
+ }
+ } else {
+ $this->debug("Unexpected scenario: empty URL for unloaded import");
+ }
+ }
+ }
+ }
+ }
+ }
+ // WSDL imports
+ $wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
+ foreach ($this->import as $ns => $list) {
+ for ($ii = 0; $ii < count($list); $ii++) {
+ if (! $list[$ii]['loaded']) {
+ $this->import[$ns][$ii]['loaded'] = true;
+ $url = $list[$ii]['location'];
+ if ($url != '') {
+ $urlparts = parse_url($url);
+ if (!isset($urlparts['host'])) {
+ $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') .
+ substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
+ }
+ if (! in_array($url, $imported_urls)) {
+ $this->parseWSDL($url);
+ $imported++;
+ $imported_urls[] = $url;
+ }
+ } else {
+ $this->debug("Unexpected scenario: empty URL for unloaded import");
+ }
+ }
+ }
+ }
+ }
+ // add new data to operation data
+ foreach($this->bindings as $binding => $bindingData) {
+ if (isset($bindingData['operations']) && is_array($bindingData['operations'])) {
+ foreach($bindingData['operations'] as $operation => $data) {
+ $this->debug('post-parse data gathering for ' . $operation);
+ $this->bindings[$binding]['operations'][$operation]['input'] =
+ isset($this->bindings[$binding]['operations'][$operation]['input']) ?
+ array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) :
+ $this->portTypes[ $bindingData['portType'] ][$operation]['input'];
+ $this->bindings[$binding]['operations'][$operation]['output'] =
+ isset($this->bindings[$binding]['operations'][$operation]['output']) ?
+ array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) :
+ $this->portTypes[ $bindingData['portType'] ][$operation]['output'];
+ if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){
+ $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ];
+ }
+ if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){
+ $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ];
+ }
+ // Set operation style if necessary, but do not override one already provided
+ if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) {
+ $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style'];
+ }
+ $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : '';
+ $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : '';
+ $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : '';
+ }
+ }
+ }
+ }
+
+ /**
+ * parses the wsdl document
+ *
+ * @param string $wsdl path or URL
+ * @access private
+ */
+ function parseWSDL($wsdl = '') {
+ $this->debug("parse WSDL at path=$wsdl");
+
+ if ($wsdl == '') {
+ $this->debug('no wsdl passed to parseWSDL()!!');
+ $this->setError('no wsdl passed to parseWSDL()!!');
+ return false;
+ }
+
+ // parse $wsdl for url format
+ $wsdl_props = parse_url($wsdl);
+
+ if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) {
+ $this->debug('getting WSDL http(s) URL ' . $wsdl);
+ // get wsdl
+ $tr = new soap_transport_http($wsdl, $this->curl_options, $this->use_curl);
+ $tr->request_method = 'GET';
+ $tr->useSOAPAction = false;
+ if($this->proxyhost && $this->proxyport){
+ $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
+ }
+ if ($this->authtype != '') {
+ $tr->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
+ }
+ $tr->setEncoding('gzip, deflate');
+ $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout);
+ //$this->debug("WSDL request\n" . $tr->outgoing_payload);
+ //$this->debug("WSDL response\n" . $tr->incoming_payload);
+ $this->appendDebug($tr->getDebug());
+ // catch errors
+ if($err = $tr->getError() ){
+ $errstr = 'Getting ' . $wsdl . ' - HTTP ERROR: '.$err;
+ $this->debug($errstr);
+ $this->setError($errstr);
+ unset($tr);
+ return false;
+ }
+ unset($tr);
+ $this->debug("got WSDL URL");
+ } else {
+ // $wsdl is not http(s), so treat it as a file URL or plain file path
+ if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) {
+ $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path'];
+ } else {
+ $path = $wsdl;
+ }
+ $this->debug('getting WSDL file ' . $path);
+ if ($fp = @fopen($path, 'r')) {
+ $wsdl_string = '';
+ while ($data = fread($fp, 32768)) {
+ $wsdl_string .= $data;
+ }
+ fclose($fp);
+ } else {
+ $errstr = "Bad path to WSDL file $path";
+ $this->debug($errstr);
+ $this->setError($errstr);
+ return false;
+ }
+ }
+ $this->debug('Parse WSDL');
+ // end new code added
+ // Create an XML parser.
+ $this->parser = xml_parser_create();
+ // Set the options for parsing the XML data.
+ // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
+ xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
+ // Set the object for the parser.
+ xml_set_object($this->parser, $this);
+ // Set the element handlers for the parser.
+ xml_set_element_handler($this->parser, 'start_element', 'end_element');
+ xml_set_character_data_handler($this->parser, 'character_data');
+ // Parse the XML file.
+ if (!xml_parse($this->parser, $wsdl_string, true)) {
+ // Display an error message.
+ $errstr = sprintf(
+ 'XML error parsing WSDL from %s on line %d: %s',
+ $wsdl,
+ xml_get_current_line_number($this->parser),
+ xml_error_string(xml_get_error_code($this->parser))
+ );
+ $this->debug($errstr);
+ $this->debug("XML payload:\n" . $wsdl_string);
+ $this->setError($errstr);
+ return false;
+ }
+ // free the parser
+ xml_parser_free($this->parser);
+ $this->debug('Parsing WSDL done');
+ // catch wsdl parse errors
+ if($this->getError()){
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * start-element handler
+ *
+ * @param string $parser XML parser object
+ * @param string $name element name
+ * @param string $attrs associative array of attributes
+ * @access private
+ */
+ function start_element($parser, $name, $attrs)
+ {
+ if ($this->status == 'schema') {
+ $this->currentSchema->schemaStartElement($parser, $name, $attrs);
+ $this->appendDebug($this->currentSchema->getDebug());
+ $this->currentSchema->clearDebug();
+ } elseif (preg_match('/schema$/', $name)) {
+ $this->debug('Parsing WSDL schema');
+ // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")");
+ $this->status = 'schema';
+ $this->currentSchema = new nusoap_xmlschema('', '', $this->namespaces);
+ $this->currentSchema->schemaStartElement($parser, $name, $attrs);
+ $this->appendDebug($this->currentSchema->getDebug());
+ $this->currentSchema->clearDebug();
+ } else {
+ // position in the total number of elements, starting from 0
+ $pos = $this->position++;
+ $depth = $this->depth++;
+ // set self as current value for this depth
+ $this->depth_array[$depth] = $pos;
+ $this->message[$pos] = array('cdata' => '');
+ // process attributes
+ if (count($attrs) > 0) {
+ // register namespace declarations
+ foreach($attrs as $k => $v) {
+ if (preg_match('/^xmlns/',$k)) {
+ if ($ns_prefix = substr(strrchr($k, ':'), 1)) {
+ $this->namespaces[$ns_prefix] = $v;
+ } else {
+ $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v;
+ }
+ if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') {
+ $this->XMLSchemaVersion = $v;
+ $this->namespaces['xsi'] = $v . '-instance';
+ }
+ }
+ }
+ // expand each attribute prefix to its namespace
+ foreach($attrs as $k => $v) {
+ $k = strpos($k, ':') ? $this->expandQname($k) : $k;
+ if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') {
+ $v = strpos($v, ':') ? $this->expandQname($v) : $v;
+ }
+ $eAttrs[$k] = $v;
+ }
+ $attrs = $eAttrs;
+ } else {
+ $attrs = array();
+ }
+ // get element prefix, namespace and name
+ if (preg_match('/:/', $name)) {
+ // get ns prefix
+ $prefix = substr($name, 0, strpos($name, ':'));
+ // get ns
+ $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : '';
+ // get unqualified name
+ $name = substr(strstr($name, ':'), 1);
+ }
+ // process attributes, expanding any prefixes to namespaces
+ // find status, register data
+ switch ($this->status) {
+ case 'message':
+ if ($name == 'part') {
+ if (isset($attrs['type'])) {
+ $this->debug("msg " . $this->currentMessage . ": found part (with type) $attrs[name]: " . implode(',', $attrs));
+ $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type'];
+ }
+ if (isset($attrs['element'])) {
+ $this->debug("msg " . $this->currentMessage . ": found part (with element) $attrs[name]: " . implode(',', $attrs));
+ $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'] . '^';
+ }
+ }
+ break;
+ case 'portType':
+ switch ($name) {
+ case 'operation':
+ $this->currentPortOperation = $attrs['name'];
+ $this->debug("portType $this->currentPortType operation: $this->currentPortOperation");
+ if (isset($attrs['parameterOrder'])) {
+ $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder'];
+ }
+ break;
+ case 'documentation':
+ $this->documentation = true;
+ break;
+ // merge input/output data
+ default:
+ $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : '';
+ $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m;
+ break;
+ }
+ break;
+ case 'binding':
+ switch ($name) {
+ case 'binding':
+ // get ns prefix
+ if (isset($attrs['style'])) {
+ $this->bindings[$this->currentBinding]['prefix'] = $prefix;
+ }
+ $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs);
+ break;
+ case 'header':
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs;
+ break;
+ case 'operation':
+ if (isset($attrs['soapAction'])) {
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction'];
+ }
+ if (isset($attrs['style'])) {
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style'];
+ }
+ if (isset($attrs['name'])) {
+ $this->currentOperation = $attrs['name'];
+ $this->debug("current binding operation: $this->currentOperation");
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name'];
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding;
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : '';
+ }
+ break;
+ case 'input':
+ $this->opStatus = 'input';
+ break;
+ case 'output':
+ $this->opStatus = 'output';
+ break;
+ case 'body':
+ if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) {
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs);
+ } else {
+ $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs;
+ }
+ break;
+ }
+ break;
+ case 'service':
+ switch ($name) {
+ case 'port':
+ $this->currentPort = $attrs['name'];
+ $this->debug('current port: ' . $this->currentPort);
+ $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']);
+
+ break;
+ case 'address':
+ $this->ports[$this->currentPort]['location'] = $attrs['location'];
+ $this->ports[$this->currentPort]['bindingType'] = $namespace;
+ $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace;
+ $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location'];
+ break;
+ }
+ break;
+ }
+ // set status
+ switch ($name) {
+ case 'import':
+ if (isset($attrs['location'])) {
+ $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false);
+ $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')');
+ } else {
+ $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
+ if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
+ $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
+ }
+ $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')');
+ }
+ break;
+ //wait for schema
+ //case 'types':
+ // $this->status = 'schema';
+ // break;
+ case 'message':
+ $this->status = 'message';
+ $this->messages[$attrs['name']] = array();
+ $this->currentMessage = $attrs['name'];
+ break;
+ case 'portType':
+ $this->status = 'portType';
+ $this->portTypes[$attrs['name']] = array();
+ $this->currentPortType = $attrs['name'];
+ break;
+ case "binding":
+ if (isset($attrs['name'])) {
+ // get binding name
+ if (strpos($attrs['name'], ':')) {
+ $this->currentBinding = $this->getLocalPart($attrs['name']);
+ } else {
+ $this->currentBinding = $attrs['name'];
+ }
+ $this->status = 'binding';
+ $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']);
+ $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']);
+ }
+ break;
+ case 'service':
+ $this->serviceName = $attrs['name'];
+ $this->status = 'service';
+ $this->debug('current service: ' . $this->serviceName);
+ break;
+ case 'definitions':
+ foreach ($attrs as $name => $value) {
+ $this->wsdl_info[$name] = $value;
+ }
+ break;
+ }
+ }
+ }
+
+ /**
+ * end-element handler
+ *
+ * @param string $parser XML parser object
+ * @param string $name element name
+ * @access private
+ */
+ function end_element($parser, $name){
+ // unset schema status
+ if (/*preg_match('/types$/', $name) ||*/ preg_match('/schema$/', $name)) {
+ $this->status = "";
+ $this->appendDebug($this->currentSchema->getDebug());
+ $this->currentSchema->clearDebug();
+ $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema;
+ $this->debug('Parsing WSDL schema done');
+ }
+ if ($this->status == 'schema') {
+ $this->currentSchema->schemaEndElement($parser, $name);
+ } else {
+ // bring depth down a notch
+ $this->depth--;
+ }
+ // end documentation
+ if ($this->documentation) {
+ //TODO: track the node to which documentation should be assigned; it can be a part, message, etc.
+ //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation;
+ $this->documentation = false;
+ }
+ }
+
+ /**
+ * element content handler
+ *
+ * @param string $parser XML parser object
+ * @param string $data element content
+ * @access private
+ */
+ function character_data($parser, $data)
+ {
+ $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0;
+ if (isset($this->message[$pos]['cdata'])) {
+ $this->message[$pos]['cdata'] .= $data;
+ }
+ if ($this->documentation) {
+ $this->documentation .= $data;
+ }
+ }
+
+ /**
+ * if authenticating, set user credentials here
+ *
+ * @param string $username
+ * @param string $password
+ * @param string $authtype (basic|digest|certificate|ntlm)
+ * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
+ * @access public
+ */
+ function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
+ $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
+ $this->appendDebug($this->varDump($certRequest));
+ $this->username = $username;
+ $this->password = $password;
+ $this->authtype = $authtype;
+ $this->certRequest = $certRequest;
+ }
+
+ function getBindingData($binding)
+ {
+ if (is_array($this->bindings[$binding])) {
+ return $this->bindings[$binding];
+ }
+ }
+
+ /**
+ * returns an assoc array of operation names => operation data
+ *
+ * @param string $portName WSDL port name
+ * @param string $bindingType eg: soap, smtp, dime (only soap and soap12 are currently supported)
+ * @return array
+ * @access public
+ */
+ function getOperations($portName = '', $bindingType = 'soap') {
+ $ops = array();
+ if ($bindingType == 'soap') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
+ } elseif ($bindingType == 'soap12') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
+ } else {
+ $this->debug("getOperations bindingType $bindingType may not be supported");
+ }
+ $this->debug("getOperations for port '$portName' bindingType $bindingType");
+ // loop thru ports
+ foreach($this->ports as $port => $portData) {
+ $this->debug("getOperations checking port $port bindingType " . $portData['bindingType']);
+ if ($portName == '' || $port == $portName) {
+ // binding type of port matches parameter
+ if ($portData['bindingType'] == $bindingType) {
+ $this->debug("getOperations found port $port bindingType $bindingType");
+ //$this->debug("port data: " . $this->varDump($portData));
+ //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ]));
+ // merge bindings
+ if (isset($this->bindings[ $portData['binding'] ]['operations'])) {
+ $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']);
+ }
+ }
+ }
+ }
+ if (count($ops) == 0) {
+ $this->debug("getOperations found no operations for port '$portName' bindingType $bindingType");
+ }
+ return $ops;
+ }
+
+ /**
+ * returns an associative array of data necessary for calling an operation
+ *
+ * @param string $operation name of operation
+ * @param string $bindingType type of binding eg: soap, soap12
+ * @return array
+ * @access public
+ */
+ function getOperationData($operation, $bindingType = 'soap')
+ {
+ if ($bindingType == 'soap') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
+ } elseif ($bindingType == 'soap12') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
+ }
+ // loop thru ports
+ foreach($this->ports as $port => $portData) {
+ // binding type of port matches parameter
+ if ($portData['bindingType'] == $bindingType) {
+ // get binding
+ //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
+ foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) {
+ // note that we could/should also check the namespace here
+ if ($operation == $bOperation) {
+ $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation];
+ return $opData;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * returns an associative array of data necessary for calling an operation
+ *
+ * @param string $soapAction soapAction for operation
+ * @param string $bindingType type of binding eg: soap, soap12
+ * @return array
+ * @access public
+ */
+ function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') {
+ if ($bindingType == 'soap') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
+ } elseif ($bindingType == 'soap12') {
+ $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
+ }
+ // loop thru ports
+ foreach($this->ports as $port => $portData) {
+ // binding type of port matches parameter
+ if ($portData['bindingType'] == $bindingType) {
+ // loop through operations for the binding
+ foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
+ if ($opData['soapAction'] == $soapAction) {
+ return $opData;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * returns an array of information about a given type
+ * returns false if no type exists by the given name
+ *
+ * typeDef = array(
+ * 'elements' => array(), // refs to elements array
+ * 'restrictionBase' => '',
+ * 'phpType' => '',
+ * 'order' => '(sequence|all)',
+ * 'attrs' => array() // refs to attributes array
+ * )
+ *
+ * @param string $type the type
+ * @param string $ns namespace (not prefix) of the type
+ * @return mixed
+ * @access public
+ * @see nusoap_xmlschema
+ */
+ function getTypeDef($type, $ns) {
+ $this->debug("in getTypeDef: type=$type, ns=$ns");
+ if ((! $ns) && isset($this->namespaces['tns'])) {
+ $ns = $this->namespaces['tns'];
+ $this->debug("in getTypeDef: type namespace forced to $ns");
+ }
+ if (!isset($this->schemas[$ns])) {
+ foreach ($this->schemas as $ns0 => $schema0) {
+ if (strcasecmp($ns, $ns0) == 0) {
+ $this->debug("in getTypeDef: replacing schema namespace $ns with $ns0");
+ $ns = $ns0;
+ break;
+ }
+ }
+ }
+ if (isset($this->schemas[$ns])) {
+ $this->debug("in getTypeDef: have schema for namespace $ns");
+ for ($i = 0; $i < count($this->schemas[$ns]); $i++) {
+ $xs = &$this->schemas[$ns][$i];
+ $t = $xs->getTypeDef($type);
+ $this->appendDebug($xs->getDebug());
+ $xs->clearDebug();
+ if ($t) {
+ $this->debug("in getTypeDef: found type $type");
+ if (!isset($t['phpType'])) {
+ // get info for type to tack onto the element
+ $uqType = substr($t['type'], strrpos($t['type'], ':') + 1);
+ $ns = substr($t['type'], 0, strrpos($t['type'], ':'));
+ $etype = $this->getTypeDef($uqType, $ns);
+ if ($etype) {
+ $this->debug("found type for [element] $type:");
+ $this->debug($this->varDump($etype));
+ if (isset($etype['phpType'])) {
+ $t['phpType'] = $etype['phpType'];
+ }
+ if (isset($etype['elements'])) {
+ $t['elements'] = $etype['elements'];
+ }
+ if (isset($etype['attrs'])) {
+ $t['attrs'] = $etype['attrs'];
+ }
+ } else {
+ $this->debug("did not find type for [element] $type");
+ }
+ }
+ return $t;
+ }
+ }
+ $this->debug("in getTypeDef: did not find type $type");
+ } else {
+ $this->debug("in getTypeDef: do not have schema for namespace $ns");
+ }
+ return false;
+ }
+
+ /**
+ * prints html description of services
+ *
+ * @access private
+ */
+ function webDescription(){
+ global $HTTP_SERVER_VARS;
+
+ if (isset($_SERVER)) {
+ $PHP_SELF = $_SERVER['PHP_SELF'];
+ } elseif (isset($HTTP_SERVER_VARS)) {
+ $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
+ } else {
+ $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
+ }
+
+ $b = '
+ <html><head><title>NuSOAP: '.$this->serviceName.'</title>
+ <style type="text/css">
+ body { font-family: arial; color: #000000; background-color: #ffffff; margin: 0px 0px 0px 0px; }
+ p { font-family: arial; color: #000000; margin-top: 0px; margin-bottom: 12px; }
+ pre { background-color: silver; padding: 5px; font-family: Courier New; font-size: x-small; color: #000000;}
+ ul { margin-top: 10px; margin-left: 20px; }
+ li { list-style-type: none; margin-top: 10px; color: #000000; }
+ .content{
+ margin-left: 0px; padding-bottom: 2em; }
+ .nav {
+ padding-top: 10px; padding-bottom: 10px; padding-left: 15px; font-size: .70em;
+ margin-top: 10px; margin-left: 0px; color: #000000;
+ background-color: #ccccff; width: 20%; margin-left: 20px; margin-top: 20px; }
+ .title {
+ font-family: arial; font-size: 26px; color: #ffffff;
+ background-color: #999999; width: 100%;
+ margin-left: 0px; margin-right: 0px;
+ padding-top: 10px; padding-bottom: 10px;}
+ .hidden {
+ position: absolute; visibility: hidden; z-index: 200; left: 250px; top: 100px;
+ font-family: arial; overflow: hidden; width: 600;
+ padding: 20px; font-size: 10px; background-color: #999999;
+ layer-background-color:#FFFFFF; }
+ a,a:active { color: charcoal; font-weight: bold; }
+ a:visited { color: #666666; font-weight: bold; }
+ a:hover { color: cc3300; font-weight: bold; }
+ </style>
+ <script language="JavaScript" type="text/javascript">
+ <!--
+ // POP-UP CAPTIONS...
+ function lib_bwcheck(){ //Browsercheck (needed)
+ this.ver=navigator.appVersion
+ this.agent=navigator.userAgent
+ this.dom=document.getElementById?1:0
+ this.opera5=this.agent.indexOf("Opera 5")>-1
+ this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
+ this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
+ this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
+ this.ie=this.ie4||this.ie5||this.ie6
+ this.mac=this.agent.indexOf("Mac")>-1
+ this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
+ this.ns4=(document.layers && !this.dom)?1:0;
+ this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
+ return this
+ }
+ var bw = new lib_bwcheck()
+ //Makes crossbrowser object.
+ function makeObj(obj){
+ this.evnt=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
+ if(!this.evnt) return false
+ this.css=bw.dom||bw.ie4?this.evnt.style:bw.ns4?this.evnt:0;
+ this.wref=bw.dom||bw.ie4?this.evnt:bw.ns4?this.css.document:0;
+ this.writeIt=b_writeIt;
+ return this
+ }
+ // A unit of measure that will be added when setting the position of a layer.
+ //var px = bw.ns4||window.opera?"":"px";
+ function b_writeIt(text){
+ if (bw.ns4){this.wref.write(text);this.wref.close()}
+ else this.wref.innerHTML = text
+ }
+ //Shows the messages
+ var oDesc;
+ function popup(divid){
+ if(oDesc = new makeObj(divid)){
+ oDesc.css.visibility = "visible"
+ }
+ }
+ function popout(){ // Hides message
+ if(oDesc) oDesc.css.visibility = "hidden"
+ }
+ //-->
+ </script>
+ </head>
+ <body>
+ <div class=content>
+ <br><br>
+ <div class=title>'.$this->serviceName.'</div>
+ <div class=nav>
+ <p>View the <a href="'.$PHP_SELF.'?wsdl">WSDL</a> for the service.
+ Click on an operation name to view it's details.</p>
+ <ul>';
+ foreach($this->getOperations() as $op => $data){
+ $b .= "<li><a href='#' onclick=\"popout();popup('$op')\">$op</a></li>";
+ // create hidden div
+ $b .= "<div id='$op' class='hidden'>
+ <a href='#' onclick='popout()'><font color='#ffffff'>Close</font></a><br><br>";
+ foreach($data as $donnie => $marie){ // loop through opdata
+ if($donnie == 'input' || $donnie == 'output'){ // show input/output data
+ $b .= "<font color='white'>".ucfirst($donnie).':</font><br>';
+ foreach($marie as $captain => $tenille){ // loop through data
+ if($captain == 'parts'){ // loop thru parts
+ $b .= " $captain:<br>";
+ //if(is_array($tenille)){
+ foreach($tenille as $joanie => $chachi){
+ $b .= " $joanie: $chachi<br>";
+ }
+ //}
+ } else {
+ $b .= " $captain: $tenille<br>";
+ }
+ }
+ } else {
+ $b .= "<font color='white'>".ucfirst($donnie).":</font> $marie<br>";
+ }
+ }
+ $b .= '</div>';
+ }
+ $b .= '
+ <ul>
+ </div>
+ </div></body></html>';
+ return $b;
+ }
+
+ /**
+ * serialize the parsed wsdl
+ *
+ * @param mixed $debug whether to put debug=1 in endpoint URL
+ * @return string serialization of WSDL
+ * @access public
+ */
+ function serialize($debug = 0)
+ {
+ $xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
+ $xml .= "\n<definitions";
+ foreach($this->namespaces as $k => $v) {
+ $xml .= " xmlns:$k=\"$v\"";
+ }
+ // 10.9.02 - add poulter fix for wsdl and tns declarations
+ if (isset($this->namespaces['wsdl'])) {
+ $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\"";
+ }
+ if (isset($this->namespaces['tns'])) {
+ $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\"";
+ }
+ $xml .= '>';
+ // imports
+ if (sizeof($this->import) > 0) {
+ foreach($this->import as $ns => $list) {
+ foreach ($list as $ii) {
+ if ($ii['location'] != '') {
+ $xml .= '<import location="' . $ii['location'] . '" namespace="' . $ns . '" />';
+ } else {
+ $xml .= '<import namespace="' . $ns . '" />';
+ }
+ }
+ }
+ }
+ // types
+ if (count($this->schemas)>=1) {
+ $xml .= "\n<types>\n";
+ foreach ($this->schemas as $ns => $list) {
+ foreach ($list as $xs) {
+ $xml .= $xs->serializeSchema();
+ }
+ }
+ $xml .= '</types>';
+ }
+ // messages
+ if (count($this->messages) >= 1) {
+ foreach($this->messages as $msgName => $msgParts) {
+ $xml .= "\n<message name=\"" . $msgName . '">';
+ if(is_array($msgParts)){
+ foreach($msgParts as $partName => $partType) {
+ // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'<br>';
+ if (strpos($partType, ':')) {
+ $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType));
+ } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) {
+ // print 'checking typemap: '.$this->XMLSchemaVersion.'<br>';
+ $typePrefix = 'xsd';
+ } else {
+ foreach($this->typemap as $ns => $types) {
+ if (isset($types[$partType])) {
+ $typePrefix = $this->getPrefixFromNamespace($ns);
+ }
+ }
+ if (!isset($typePrefix)) {
+ die("$partType has no namespace!");
+ }
+ }
+ $ns = $this->getNamespaceFromPrefix($typePrefix);
+ $localPart = $this->getLocalPart($partType);
+ $typeDef = $this->getTypeDef($localPart, $ns);
+ if ($typeDef['typeClass'] == 'element') {
+ $elementortype = 'element';
+ if (substr($localPart, -1) == '^') {
+ $localPart = substr($localPart, 0, -1);
+ }
+ } else {
+ $elementortype = 'type';
+ }
+ $xml .= "\n" . ' <part name="' . $partName . '" ' . $elementortype . '="' . $typePrefix . ':' . $localPart . '" />';
+ }
+ }
+ $xml .= '</message>';
+ }
+ }
+ // bindings & porttypes
+ if (count($this->bindings) >= 1) {
+ $binding_xml = '';
+ $portType_xml = '';
+ foreach($this->bindings as $bindingName => $attrs) {
+ $binding_xml .= "\n<binding name=\"" . $bindingName . '" type="tns:' . $attrs['portType'] . '">';
+ $binding_xml .= "\n" . ' <soap:binding style="' . $attrs['style'] . '" transport="' . $attrs['transport'] . '"/>';
+ $portType_xml .= "\n<portType name=\"" . $attrs['portType'] . '">';
+ foreach($attrs['operations'] as $opName => $opParts) {
+ $binding_xml .= "\n" . ' <operation name="' . $opName . '">';
+ $binding_xml .= "\n" . ' <soap:operation soapAction="' . $opParts['soapAction'] . '" style="'. $opParts['style'] . '"/>';
+ if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') {
+ $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"';
+ } else {
+ $enc_style = '';
+ }
+ $binding_xml .= "\n" . ' <input><soap:body use="' . $opParts['input']['use'] . '" namespace="' . $opParts['input']['namespace'] . '"' . $enc_style . '/></input>';
+ if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') {
+ $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"';
+ } else {
+ $enc_style = '';
+ }
+ $binding_xml .= "\n" . ' <output><soap:body use="' . $opParts['output']['use'] . '" namespace="' . $opParts['output']['namespace'] . '"' . $enc_style . '/></output>';
+ $binding_xml .= "\n" . ' </operation>';
+ $portType_xml .= "\n" . ' <operation name="' . $opParts['name'] . '"';
+ if (isset($opParts['parameterOrder'])) {
+ $portType_xml .= ' parameterOrder="' . $opParts['parameterOrder'] . '"';
+ }
+ $portType_xml .= '>';
+ if(isset($opParts['documentation']) && $opParts['documentation'] != '') {
+ $portType_xml .= "\n" . ' <documentation>' . htmlspecialchars($opParts['documentation']) . '</documentation>';
+ }
+ $portType_xml .= "\n" . ' <input message="tns:' . $opParts['input']['message'] . '"/>';
+ $portType_xml .= "\n" . ' <output message="tns:' . $opParts['output']['message'] . '"/>';
+ $portType_xml .= "\n" . ' </operation>';
+ }
+ $portType_xml .= "\n" . '</portType>';
+ $binding_xml .= "\n" . '</binding>';
+ }
+ $xml .= $portType_xml . $binding_xml;
+ }
+ // services
+ $xml .= "\n<service name=\"" . $this->serviceName . '">';
+ if (count($this->ports) >= 1) {
+ foreach($this->ports as $pName => $attrs) {
+ $xml .= "\n" . ' <port name="' . $pName . '" binding="tns:' . $attrs['binding'] . '">';
+ $xml .= "\n" . ' <soap:address location="' . $attrs['location'] . ($debug ? '?debug=1' : '') . '"/>';
+ $xml .= "\n" . ' </port>';
+ }
+ }
+ $xml .= "\n" . '</service>';
+ return $xml . "\n</definitions>";
+ }
+
+ /**
+ * determine whether a set of parameters are unwrapped
+ * when they are expect to be wrapped, Microsoft-style.
+ *
+ * @param string $type the type (element name) of the wrapper
+ * @param array $parameters the parameter values for the SOAP call
+ * @return boolean whether they parameters are unwrapped (and should be wrapped)
+ * @access private
+ */
+ function parametersMatchWrapped($type, &$parameters) {
+ $this->debug("in parametersMatchWrapped type=$type, parameters=");
+ $this->appendDebug($this->varDump($parameters));
+
+ // split type into namespace:unqualified-type
+ if (strpos($type, ':')) {
+ $uqType = substr($type, strrpos($type, ':') + 1);
+ $ns = substr($type, 0, strrpos($type, ':'));
+ $this->debug("in parametersMatchWrapped: got a prefixed type: $uqType, $ns");
+ if ($this->getNamespaceFromPrefix($ns)) {
+ $ns = $this->getNamespaceFromPrefix($ns);
+ $this->debug("in parametersMatchWrapped: expanded prefixed type: $uqType, $ns");
+ }
+ } else {
+ // TODO: should the type be compared to types in XSD, and the namespace
+ // set to XSD if the type matches?
+ $this->debug("in parametersMatchWrapped: No namespace for type $type");
+ $ns = '';
+ $uqType = $type;
+ }
+
+ // get the type information
+ if (!$typeDef = $this->getTypeDef($uqType, $ns)) {
+ $this->debug("in parametersMatchWrapped: $type ($uqType) is not a supported type.");
+ return false;
+ }
+ $this->debug("in parametersMatchWrapped: found typeDef=");
+ $this->appendDebug($this->varDump($typeDef));
+ if (substr($uqType, -1) == '^') {
+ $uqType = substr($uqType, 0, -1);
+ }
+ $phpType = $typeDef['phpType'];
+ $arrayType = (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '');
+ $this->debug("in parametersMatchWrapped: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: $arrayType");
+
+ // we expect a complexType or element of complexType
+ if ($phpType != 'struct') {
+ $this->debug("in parametersMatchWrapped: not a struct");
+ return false;
+ }
+
+ // see whether the parameter names match the elements
+ if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
+ $elements = 0;
+ $matches = 0;
+ foreach ($typeDef['elements'] as $name => $attrs) {
+ if (isset($parameters[$name])) {
+ $this->debug("in parametersMatchWrapped: have parameter named $name");
+ $matches++;
+ } else {
+ $this->debug("in parametersMatchWrapped: do not have parameter named $name");
+ }
+ $elements++;
+ }
+
+ $this->debug("in parametersMatchWrapped: $matches parameter names match $elements wrapped parameter names");
+ if ($matches == 0) {
+ return false;
+ }
+ return true;
+ }
+
+ // since there are no elements for the type, if the user passed no
+ // parameters, the parameters match wrapped.
+ $this->debug("in parametersMatchWrapped: no elements type $ns:$uqType");
+ return count($parameters) == 0;
+ }
+
+ /**
+ * serialize PHP values according to a WSDL message definition
+ * contrary to the method name, this is not limited to RPC
+ *
+ * TODO
+ * - multi-ref serialization
+ * - validate PHP values against type definitions, return errors if invalid
+ *
+ * @param string $operation operation name
+ * @param string $direction (input|output)
+ * @param mixed $parameters parameter value(s)
+ * @param string $bindingType (soap|soap12)
+ * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
+ * @access public
+ */
+ function serializeRPCParameters($operation, $direction, $parameters, $bindingType = 'soap') {
+ $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion, bindingType=$bindingType");
+ $this->appendDebug('parameters=' . $this->varDump($parameters));
+
+ if ($direction != 'input' && $direction != 'output') {
+ $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
+ $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
+ return false;
+ }
+ if (!$opData = $this->getOperationData($operation, $bindingType)) {
+ $this->debug('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
+ $this->setError('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
+ return false;
+ }
+ $this->debug('in serializeRPCParameters: opData:');
+ $this->appendDebug($this->varDump($opData));
+
+ // Get encoding style for output and set to current
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
+ $encodingStyle = $opData['output']['encodingStyle'];
+ $enc_style = $encodingStyle;
+ }
+
+ // set input params
+ $xml = '';
+ if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
+ $parts = &$opData[$direction]['parts'];
+ $part_count = sizeof($parts);
+ $style = $opData['style'];
+ $use = $opData[$direction]['use'];
+ $this->debug("have $part_count part(s) to serialize using $style/$use");
+ if (is_array($parameters)) {
+ $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
+ $parameter_count = count($parameters);
+ $this->debug("have $parameter_count parameter(s) provided as $parametersArrayType to serialize");
+ // check for Microsoft-style wrapped parameters
+ if ($style == 'document' && $use == 'literal' && $part_count == 1 && isset($parts['parameters'])) {
+ $this->debug('check whether the caller has wrapped the parameters');
+ if ($direction == 'output' && $parametersArrayType == 'arraySimple' && $parameter_count == 1) {
+ // TODO: consider checking here for double-wrapping, when
+ // service function wraps, then NuSOAP wraps again
+ $this->debug("change simple array to associative with 'parameters' element");
+ $parameters['parameters'] = $parameters[0];
+ unset($parameters[0]);
+ }
+ if (($parametersArrayType == 'arrayStruct' || $parameter_count == 0) && !isset($parameters['parameters'])) {
+ $this->debug('check whether caller\'s parameters match the wrapped ones');
+ if ($this->parametersMatchWrapped($parts['parameters'], $parameters)) {
+ $this->debug('wrap the parameters for the caller');
+ $parameters = array('parameters' => $parameters);
+ $parameter_count = 1;
+ }
+ }
+ }
+ foreach ($parts as $name => $type) {
+ $this->debug("serializing part $name of type $type");
+ // Track encoding style
+ if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
+ $encodingStyle = $opData[$direction]['encodingStyle'];
+ $enc_style = $encodingStyle;
+ } else {
+ $enc_style = false;
+ }
+ // NOTE: add error handling here
+ // if serializeType returns false, then catch global error and fault
+ if ($parametersArrayType == 'arraySimple') {
+ $p = array_shift($parameters);
+ $this->debug('calling serializeType w/indexed param');
+ $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
+ } elseif (isset($parameters[$name])) {
+ $this->debug('calling serializeType w/named param');
+ $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
+ } else {
+ // TODO: only send nillable
+ $this->debug('calling serializeType w/null param');
+ $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
+ }
+ }
+ } else {
+ $this->debug('no parameters passed.');
+ }
+ }
+ $this->debug("serializeRPCParameters returning: $xml");
+ return $xml;
+ }
+
+ /**
+ * serialize a PHP value according to a WSDL message definition
+ *
+ * TODO
+ * - multi-ref serialization
+ * - validate PHP values against type definitions, return errors if invalid
+ *
+ * @param string $operation operation name
+ * @param string $direction (input|output)
+ * @param mixed $parameters parameter value(s)
+ * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
+ * @access public
+ * @deprecated
+ */
+ function serializeParameters($operation, $direction, $parameters)
+ {
+ $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion");
+ $this->appendDebug('parameters=' . $this->varDump($parameters));
+
+ if ($direction != 'input' && $direction != 'output') {
+ $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
+ $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
+ return false;
+ }
+ if (!$opData = $this->getOperationData($operation)) {
+ $this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
+ $this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
+ return false;
+ }
+ $this->debug('opData:');
+ $this->appendDebug($this->varDump($opData));
+
+ // Get encoding style for output and set to current
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
+ $encodingStyle = $opData['output']['encodingStyle'];
+ $enc_style = $encodingStyle;
+ }
+
+ // set input params
+ $xml = '';
+ if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
+
+ $use = $opData[$direction]['use'];
+ $this->debug("use=$use");
+ $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)');
+ if (is_array($parameters)) {
+ $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
+ $this->debug('have ' . $parametersArrayType . ' parameters');
+ foreach($opData[$direction]['parts'] as $name => $type) {
+ $this->debug('serializing part "'.$name.'" of type "'.$type.'"');
+ // Track encoding style
+ if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
+ $encodingStyle = $opData[$direction]['encodingStyle'];
+ $enc_style = $encodingStyle;
+ } else {
+ $enc_style = false;
+ }
+ // NOTE: add error handling here
+ // if serializeType returns false, then catch global error and fault
+ if ($parametersArrayType == 'arraySimple') {
+ $p = array_shift($parameters);
+ $this->debug('calling serializeType w/indexed param');
+ $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
+ } elseif (isset($parameters[$name])) {
+ $this->debug('calling serializeType w/named param');
+ $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
+ } else {
+ // TODO: only send nillable
+ $this->debug('calling serializeType w/null param');
+ $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
+ }
+ }
+ } else {
+ $this->debug('no parameters passed.');
+ }
+ }
+ $this->debug("serializeParameters returning: $xml");
+ return $xml;
+ }
+
+ /**
+ * serializes a PHP value according a given type definition
+ *
+ * @param string $name name of value (part or element)
+ * @param string $type XML schema type of value (type or element)
+ * @param mixed $value a native PHP value (parameter value)
+ * @param string $use use for part (encoded|literal)
+ * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
+ * @param boolean $unqualified a kludge for what should be XML namespace form handling
+ * @return string value serialized as an XML string
+ * @access private
+ */
+ function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false)
+ {
+ $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified"));
+ $this->appendDebug("value=" . $this->varDump($value));
+ if($use == 'encoded' && $encodingStyle) {
+ $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"';
+ }
+
+ // if a soapval has been supplied, let its type override the WSDL
+ if (is_object($value) && get_class($value) == 'soapval') {
+ if ($value->type_ns) {
+ $type = $value->type_ns . ':' . $value->type;
+ $forceType = true;
+ $this->debug("in serializeType: soapval overrides type to $type");
+ } elseif ($value->type) {
+ $type = $value->type;
+ $forceType = true;
+ $this->debug("in serializeType: soapval overrides type to $type");
+ } else {
+ $forceType = false;
+ $this->debug("in serializeType: soapval does not override type");
+ }
+ $attrs = $value->attributes;
+ $value = $value->value;
+ $this->debug("in serializeType: soapval overrides value to $value");
+ if ($attrs) {
+ if (!is_array($value)) {
+ $value['!'] = $value;
+ }
+ foreach ($attrs as $n => $v) {
+ $value['!' . $n] = $v;
+ }
+ $this->debug("in serializeType: soapval provides attributes");
+ }
+ } else {
+ $forceType = false;
+ }
+
+ $xml = '';
+ if (strpos($type, ':')) {
+ $uqType = substr($type, strrpos($type, ':') + 1);
+ $ns = substr($type, 0, strrpos($type, ':'));
+ $this->debug("in serializeType: got a prefixed type: $uqType, $ns");
+ if ($this->getNamespaceFromPrefix($ns)) {
+ $ns = $this->getNamespaceFromPrefix($ns);
+ $this->debug("in serializeType: expanded prefixed type: $uqType, $ns");
+ }
+
+ if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){
+ $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type');
+ if ($unqualified && $use == 'literal') {
+ $elementNS = " xmlns=\"\"";
+ } else {
+ $elementNS = '';
+ }
+ if (is_null($value)) {
+ if ($use == 'literal') {
+ // TODO: depends on minOccurs
+ $xml = "<$name$elementNS/>";
+ } else {
+ // TODO: depends on nillable, which should be checked before calling this method
+ $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ if ($uqType == 'Array') {
+ // JBoss/Axis does this sometimes
+ return $this->serialize_val($value, $name, false, false, false, false, $use);
+ }
+ if ($uqType == 'boolean') {
+ if ((is_string($value) && $value == 'false') || (! $value)) {
+ $value = 'false';
+ } else {
+ $value = 'true';
+ }
+ }
+ if ($uqType == 'string' && gettype($value) == 'string') {
+ $value = $this->expandEntities($value);
+ }
+ if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') {
+ $value = sprintf("%.0lf", $value);
+ }
+ // it's a scalar
+ // TODO: what about null/nil values?
+ // check type isn't a custom type extending xmlschema namespace
+ if (!$this->getTypeDef($uqType, $ns)) {
+ if ($use == 'literal') {
+ if ($forceType) {
+ $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
+ } else {
+ $xml = "<$name$elementNS>$value</$name>";
+ }
+ } else {
+ $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)');
+ } else if ($ns == 'http://xml.apache.org/xml-soap') {
+ $this->debug('in serializeType: appears to be Apache SOAP type');
+ if ($uqType == 'Map') {
+ $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
+ if (! $tt_prefix) {
+ $this->debug('in serializeType: Add namespace for Apache SOAP type');
+ $tt_prefix = 'ns' . rand(1000, 9999);
+ $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap';
+ // force this to be added to usedNamespaces
+ $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
+ }
+ $contents = '';
+ foreach($value as $k => $v) {
+ $this->debug("serializing map element: key $k, value $v");
+ $contents .= '<item>';
+ $contents .= $this->serialize_val($k,'key',false,false,false,false,$use);
+ $contents .= $this->serialize_val($v,'value',false,false,false,false,$use);
+ $contents .= '</item>';
+ }
+ if ($use == 'literal') {
+ if ($forceType) {
+ $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents</$name>";
+ } else {
+ $xml = "<$name>$contents</$name>";
+ }
+ } else {
+ $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents</$name>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ $this->debug('in serializeType: Apache SOAP type, but only support Map');
+ }
+ } else {
+ // TODO: should the type be compared to types in XSD, and the namespace
+ // set to XSD if the type matches?
+ $this->debug("in serializeType: No namespace for type $type");
+ $ns = '';
+ $uqType = $type;
+ }
+ if(!$typeDef = $this->getTypeDef($uqType, $ns)){
+ $this->setError("$type ($uqType) is not a supported type.");
+ $this->debug("in serializeType: $type ($uqType) is not a supported type.");
+ return false;
+ } else {
+ $this->debug("in serializeType: found typeDef");
+ $this->appendDebug('typeDef=' . $this->varDump($typeDef));
+ if (substr($uqType, -1) == '^') {
+ $uqType = substr($uqType, 0, -1);
+ }
+ }
+ if (!isset($typeDef['phpType'])) {
+ $this->setError("$type ($uqType) has no phpType.");
+ $this->debug("in serializeType: $type ($uqType) has no phpType.");
+ return false;
+ }
+ $phpType = $typeDef['phpType'];
+ $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') );
+ // if php type == struct, map value to the <all> element names
+ if ($phpType == 'struct') {
+ if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') {
+ $elementName = $uqType;
+ if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
+ $elementNS = " xmlns=\"$ns\"";
+ } else {
+ $elementNS = " xmlns=\"\"";
+ }
+ } else {
+ $elementName = $name;
+ if ($unqualified) {
+ $elementNS = " xmlns=\"\"";
+ } else {
+ $elementNS = '';
+ }
+ }
+ if (is_null($value)) {
+ if ($use == 'literal') {
+ // TODO: depends on minOccurs and nillable
+ $xml = "<$elementName$elementNS/>";
+ } else {
+ $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ if (is_object($value)) {
+ $value = get_object_vars($value);
+ }
+ if (is_array($value)) {
+ $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
+ if ($use == 'literal') {
+ if ($forceType) {
+ $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">";
+ } else {
+ $xml = "<$elementName$elementNS$elementAttrs>";
+ }
+ } else {
+ $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>";
+ }
+
+ if (isset($typeDef['simpleContent']) && $typeDef['simpleContent'] == 'true') {
+ if (isset($value['!'])) {
+ $xml .= $value['!'];
+ $this->debug("in serializeType: serialized simpleContent for type $type");
+ } else {
+ $this->debug("in serializeType: no simpleContent to serialize for type $type");
+ }
+ } else {
+ // complexContent
+ $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
+ }
+ $xml .= "</$elementName>";
+ } else {
+ $this->debug("in serializeType: phpType is struct, but value is not an array");
+ $this->setError("phpType is struct, but value is not an array: see debug output for details");
+ $xml = '';
+ }
+ } elseif ($phpType == 'array') {
+ if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
+ $elementNS = " xmlns=\"$ns\"";
+ } else {
+ if ($unqualified) {
+ $elementNS = " xmlns=\"\"";
+ } else {
+ $elementNS = '';
+ }
+ }
+ if (is_null($value)) {
+ if ($use == 'literal') {
+ // TODO: depends on minOccurs
+ $xml = "<$name$elementNS/>";
+ } else {
+ $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" .
+ $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
+ ":Array\" " .
+ $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
+ ':arrayType="' .
+ $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) .
+ ':' .
+ $this->getLocalPart($typeDef['arrayType'])."[0]\"/>";
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+ if (isset($typeDef['multidimensional'])) {
+ $nv = array();
+ foreach($value as $v) {
+ $cols = ',' . sizeof($v);
+ $nv = array_merge($nv, $v);
+ }
+ $value = $nv;
+ } else {
+ $cols = '';
+ }
+ if (is_array($value) && sizeof($value) >= 1) {
+ $rows = sizeof($value);
+ $contents = '';
+ foreach($value as $k => $v) {
+ $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]");
+ //if (strpos($typeDef['arrayType'], ':') ) {
+ if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) {
+ $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use);
+ } else {
+ $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use);
+ }
+ }
+ } else {
+ $rows = 0;
+ $contents = null;
+ }
+ // TODO: for now, an empty value will be serialized as a zero element
+ // array. Revisit this when coding the handling of null/nil values.
+ if ($use == 'literal') {
+ $xml = "<$name$elementNS>"
+ .$contents
+ ."</$name>";
+ } else {
+ $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '.
+ $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/')
+ .':arrayType="'
+ .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType']))
+ .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">"
+ .$contents
+ ."</$name>";
+ }
+ } elseif ($phpType == 'scalar') {
+ if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
+ $elementNS = " xmlns=\"$ns\"";
+ } else {
+ if ($unqualified) {
+ $elementNS = " xmlns=\"\"";
+ } else {
+ $elementNS = '';
+ }
+ }
+ if ($use == 'literal') {
+ if ($forceType) {
+ $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
+ } else {
+ $xml = "<$name$elementNS>$value</$name>";
+ }
+ } else {
+ $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
+ }
+ }
+ $this->debug("in serializeType: returning: $xml");
+ return $xml;
+ }
+
+ /**
+ * serializes the attributes for a complexType
+ *
+ * @param array $typeDef our internal representation of an XML schema type (or element)
+ * @param mixed $value a native PHP value (parameter value)
+ * @param string $ns the namespace of the type
+ * @param string $uqType the local part of the type
+ * @return string value serialized as an XML string
+ * @access private
+ */
+ function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) {
+ $this->debug("serializeComplexTypeAttributes for XML Schema type $ns:$uqType");
+ $xml = '';
+ if (isset($typeDef['extensionBase'])) {
+ $nsx = $this->getPrefix($typeDef['extensionBase']);
+ $uqTypex = $this->getLocalPart($typeDef['extensionBase']);
+ if ($this->getNamespaceFromPrefix($nsx)) {
+ $nsx = $this->getNamespaceFromPrefix($nsx);
+ }
+ if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
+ $this->debug("serialize attributes for extension base $nsx:$uqTypex");
+ $xml .= $this->serializeComplexTypeAttributes($typeDefx, $value, $nsx, $uqTypex);
+ } else {
+ $this->debug("extension base $nsx:$uqTypex is not a supported type");
+ }
+ }
+ if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) {
+ $this->debug("serialize attributes for XML Schema type $ns:$uqType");
+ if (is_array($value)) {
+ $xvalue = $value;
+ } elseif (is_object($value)) {
+ $xvalue = get_object_vars($value);
+ } else {
+ $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
+ $xvalue = array();
+ }
+ foreach ($typeDef['attrs'] as $aName => $attrs) {
+ if (isset($xvalue['!' . $aName])) {
+ $xname = '!' . $aName;
+ $this->debug("value provided for attribute $aName with key $xname");
+ } elseif (isset($xvalue[$aName])) {
+ $xname = $aName;
+ $this->debug("value provided for attribute $aName with key $xname");
+ } elseif (isset($attrs['default'])) {
+ $xname = '!' . $aName;
+ $xvalue[$xname] = $attrs['default'];
+ $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName);
+ } else {
+ $xname = '';
+ $this->debug("no value provided for attribute $aName");
+ }
+ if ($xname) {
+ $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\"";
+ }
+ }
+ } else {
+ $this->debug("no attributes to serialize for XML Schema type $ns:$uqType");
+ }
+ return $xml;
+ }
+
+ /**
+ * serializes the elements for a complexType
+ *
+ * @param array $typeDef our internal representation of an XML schema type (or element)
+ * @param mixed $value a native PHP value (parameter value)
+ * @param string $ns the namespace of the type
+ * @param string $uqType the local part of the type
+ * @param string $use use for part (encoded|literal)
+ * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
+ * @return string value serialized as an XML string
+ * @access private
+ */
+ function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) {
+ $this->debug("in serializeComplexTypeElements for XML Schema type $ns:$uqType");
+ $xml = '';
+ if (isset($typeDef['extensionBase'])) {
+ $nsx = $this->getPrefix($typeDef['extensionBase']);
+ $uqTypex = $this->getLocalPart($typeDef['extensionBase']);
+ if ($this->getNamespaceFromPrefix($nsx)) {
+ $nsx = $this->getNamespaceFromPrefix($nsx);
+ }
+ if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
+ $this->debug("serialize elements for extension base $nsx:$uqTypex");
+ $xml .= $this->serializeComplexTypeElements($typeDefx, $value, $nsx, $uqTypex, $use, $encodingStyle);
+ } else {
+ $this->debug("extension base $nsx:$uqTypex is not a supported type");
+ }
+ }
+ if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
+ $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType");
+ if (is_array($value)) {
+ $xvalue = $value;
+ } elseif (is_object($value)) {
+ $xvalue = get_object_vars($value);
+ } else {
+ $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
+ $xvalue = array();
+ }
+ // toggle whether all elements are present - ideally should validate against schema
+ if (count($typeDef['elements']) != count($xvalue)){
+ $optionals = true;
+ }
+ foreach ($typeDef['elements'] as $eName => $attrs) {
+ if (!isset($xvalue[$eName])) {
+ if (isset($attrs['default'])) {
+ $xvalue[$eName] = $attrs['default'];
+ $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName);
+ }
+ }
+ // if user took advantage of a minOccurs=0, then only serialize named parameters
+ if (isset($optionals)
+ && (!isset($xvalue[$eName]))
+ && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true')
+ ){
+ if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') {
+ $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']);
+ }
+ // do nothing
+ $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing");
+ } else {
+ // get value
+ if (isset($xvalue[$eName])) {
+ $v = $xvalue[$eName];
+ } else {
+ $v = null;
+ }
+ if (isset($attrs['form'])) {
+ $unqualified = ($attrs['form'] == 'unqualified');
+ } else {
+ $unqualified = false;
+ }
+ if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') {
+ $vv = $v;
+ foreach ($vv as $k => $v) {
+ if (isset($attrs['type']) || isset($attrs['ref'])) {
+ // serialize schema-defined type
+ $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
+ } else {
+ // serialize generic type (can this ever really happen?)
+ $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
+ $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
+ }
+ }
+ } else {
+ if (is_null($v) && isset($attrs['minOccurs']) && $attrs['minOccurs'] == '0') {
+ // do nothing
+ } elseif (is_null($v) && isset($attrs['nillable']) && $attrs['nillable'] == 'true') {
+ // TODO: serialize a nil correctly, but for now serialize schema-defined type
+ $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
+ } elseif (isset($attrs['type']) || isset($attrs['ref'])) {
+ // serialize schema-defined type
+ $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
+ } else {
+ // serialize generic type (can this ever really happen?)
+ $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
+ $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
+ }
+ }
+ }
+ }
+ } else {
+ $this->debug("no elements to serialize for XML Schema type $ns:$uqType");
+ }
+ return $xml;
+ }
+
+ /**
+ * adds an XML Schema complex type to the WSDL types
+ *
+ * @param string $name
+ * @param string $typeClass (complexType|simpleType|attribute)
+ * @param string $phpType currently supported are array and struct (php assoc array)
+ * @param string $compositor (all|sequence|choice)
+ * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
+ * @param array $elements e.g. array ( name => array(name=>'',type=>'') )
+ * @param array $attrs e.g. array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]'))
+ * @param string $arrayType as namespace:name (xsd:string)
+ * @see nusoap_xmlschema
+ * @access public
+ */
+ function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') {
+ if (count($elements) > 0) {
+ $eElements = array();
+ foreach($elements as $n => $e){
+ // expand each element
+ $ee = array();
+ foreach ($e as $k => $v) {
+ $k = strpos($k,':') ? $this->expandQname($k) : $k;
+ $v = strpos($v,':') ? $this->expandQname($v) : $v;
+ $ee[$k] = $v;
+ }
+ $eElements[$n] = $ee;
+ }
+ $elements = $eElements;
+ }
+
+ if (count($attrs) > 0) {
+ foreach($attrs as $n => $a){
+ // expand each attribute
+ foreach ($a as $k => $v) {
+ $k = strpos($k,':') ? $this->expandQname($k) : $k;
+ $v = strpos($v,':') ? $this->expandQname($v) : $v;
+ $aa[$k] = $v;
+ }
+ $eAttrs[$n] = $aa;
+ }
+ $attrs = $eAttrs;
+ }
+
+ $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
+ $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType;
+
+ $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
+ $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType);
+ }
+
+ /**
+ * adds an XML Schema simple type to the WSDL types
+ *
+ * @param string $name
+ * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
+ * @param string $typeClass (should always be simpleType)
+ * @param string $phpType (should always be scalar)
+ * @param array $enumeration array of values
+ * @see nusoap_xmlschema
+ * @access public
+ */
+ function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
+ $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
+
+ $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
+ $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration);
+ }
+
+ /**
+ * adds an element to the WSDL types
+ *
+ * @param array $attrs attributes that must include name and type
+ * @see nusoap_xmlschema
+ * @access public
+ */
+ function addElement($attrs) {
+ $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
+ $this->schemas[$typens][0]->addElement($attrs);
+ }
+
+ /**
+ * register an operation with the server
+ *
+ * @param string $name operation (method) name
+ * @param array $in assoc array of input values: key = param name, value = param type
+ * @param array $out assoc array of output values: key = param name, value = param type
+ * @param string $namespace optional The namespace for the operation
+ * @param string $soapaction optional The soapaction for the operation
+ * @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically
+ * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now)
+ * @param string $documentation optional The description to include in the WSDL
+ * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
+ * @access public
+ */
+ function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){
+ if ($use == 'encoded' && $encodingStyle == '') {
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ }
+
+ if ($style == 'document') {
+ $elements = array();
+ foreach ($in as $n => $t) {
+ $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
+ }
+ $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements);
+ $this->addElement(array('name' => $name, 'type' => $name . 'RequestType'));
+ $in = array('parameters' => 'tns:' . $name . '^');
+
+ $elements = array();
+ foreach ($out as $n => $t) {
+ $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
+ }
+ $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements);
+ $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType', 'form' => 'qualified'));
+ $out = array('parameters' => 'tns:' . $name . 'Response' . '^');
+ }
+
+ // get binding
+ $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] =
+ array(
+ 'name' => $name,
+ 'binding' => $this->serviceName . 'Binding',
+ 'endpoint' => $this->endpoint,
+ 'soapAction' => $soapaction,
+ 'style' => $style,
+ 'input' => array(
+ 'use' => $use,
+ 'namespace' => $namespace,
+ 'encodingStyle' => $encodingStyle,
+ 'message' => $name . 'Request',
+ 'parts' => $in),
+ 'output' => array(
+ 'use' => $use,
+ 'namespace' => $namespace,
+ 'encodingStyle' => $encodingStyle,
+ 'message' => $name . 'Response',
+ 'parts' => $out),
+ 'namespace' => $namespace,
+ 'transport' => 'http://schemas.xmlsoap.org/soap/http',
+ 'documentation' => $documentation);
+ // add portTypes
+ // add messages
+ if($in)
+ {
+ foreach($in as $pName => $pType)
+ {
+ if(strpos($pType,':')) {
+ $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
+ }
+ $this->messages[$name.'Request'][$pName] = $pType;
+ }
+ } else {
+ $this->messages[$name.'Request']= '0';
+ }
+ if($out)
+ {
+ foreach($out as $pName => $pType)
+ {
+ if(strpos($pType,':')) {
+ $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
+ }
+ $this->messages[$name.'Response'][$pName] = $pType;
+ }
+ } else {
+ $this->messages[$name.'Response']= '0';
+ }
+ return true;
+ }
+}
+?><?php
+
+
+
+/**
+*
+* nusoap_parser class parses SOAP XML messages into native PHP values
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_parser extends nusoap_base {
+
+ var $xml = '';
+ var $xml_encoding = '';
+ var $method = '';
+ var $root_struct = '';
+ var $root_struct_name = '';
+ var $root_struct_namespace = '';
+ var $root_header = '';
+ var $document = ''; // incoming SOAP body (text)
+ // determines where in the message we are (envelope,header,body,method)
+ var $status = '';
+ var $position = 0;
+ var $depth = 0;
+ var $default_namespace = '';
+ var $namespaces = array();
+ var $message = array();
+ var $parent = '';
+ var $fault = false;
+ var $fault_code = '';
+ var $fault_str = '';
+ var $fault_detail = '';
+ var $depth_array = array();
+ var $debug_flag = true;
+ var $soapresponse = NULL; // parsed SOAP Body
+ var $soapheader = NULL; // parsed SOAP Header
+ var $responseHeaders = ''; // incoming SOAP headers (text)
+ var $body_position = 0;
+ // for multiref parsing:
+ // array of id => pos
+ var $ids = array();
+ // array of id => hrefs => pos
+ var $multirefs = array();
+ // toggle for auto-decoding element content
+ var $decode_utf8 = true;
+
+ /**
+ * constructor that actually does the parsing
+ *
+ * @param string $xml SOAP message
+ * @param string $encoding character encoding scheme of message
+ * @param string $method method for which XML is parsed (unused?)
+ * @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1
+ * @access public
+ */
+ function nusoap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){
+ parent::nusoap_base();
+ $this->xml = $xml;
+ $this->xml_encoding = $encoding;
+ $this->method = $method;
+ $this->decode_utf8 = $decode_utf8;
+
+ // Check whether content has been read.
+ if(!empty($xml)){
+ // Check XML encoding
+ $pos_xml = strpos($xml, '<?xml');
+ if ($pos_xml !== FALSE) {
+ $xml_decl = substr($xml, $pos_xml, strpos($xml, '?>', $pos_xml + 2) - $pos_xml + 1);
+ if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) {
+ $xml_encoding = $res[1];
+ if (strtoupper($xml_encoding) != $encoding) {
+ $err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'";
+ $this->debug($err);
+ if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') {
+ $this->setError($err);
+ return;
+ }
+ // when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed
+ } else {
+ $this->debug('Charset from HTTP Content-Type matches encoding from XML declaration');
+ }
+ } else {
+ $this->debug('No encoding specified in XML declaration');
+ }
+ } else {
+ $this->debug('No XML declaration');
+ }
+ $this->debug('Entering nusoap_parser(), length='.strlen($xml).', encoding='.$encoding);
+ // Create an XML parser - why not xml_parser_create_ns?
+ $this->parser = xml_parser_create($this->xml_encoding);
+ // Set the options for parsing the XML data.
+ //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
+ xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
+ xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding);
+ // Set the object for the parser.
+ xml_set_object($this->parser, $this);
+ // Set the element handlers for the parser.
+ xml_set_element_handler($this->parser, 'start_element','end_element');
+ xml_set_character_data_handler($this->parser,'character_data');
+
+ // Parse the XML file.
+ if(!xml_parse($this->parser,$xml,true)){
+ // Display an error message.
+ $err = sprintf('XML error parsing SOAP payload on line %d: %s',
+ xml_get_current_line_number($this->parser),
+ xml_error_string(xml_get_error_code($this->parser)));
+ $this->debug($err);
+ $this->debug("XML payload:\n" . $xml);
+ $this->setError($err);
+ } else {
+ $this->debug('in nusoap_parser ctor, message:');
+ $this->appendDebug($this->varDump($this->message));
+ $this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name);
+ // get final value
+ $this->soapresponse = $this->message[$this->root_struct]['result'];
+ // get header value
+ if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){
+ $this->soapheader = $this->message[$this->root_header]['result'];
+ }
+ // resolve hrefs/ids
+ if(sizeof($this->multirefs) > 0){
+ foreach($this->multirefs as $id => $hrefs){
+ $this->debug('resolving multirefs for id: '.$id);
+ $idVal = $this->buildVal($this->ids[$id]);
+ if (is_array($idVal) && isset($idVal['!id'])) {
+ unset($idVal['!id']);
+ }
+ foreach($hrefs as $refPos => $ref){
+ $this->debug('resolving href at pos '.$refPos);
+ $this->multirefs[$id][$refPos] = $idVal;
+ }
+ }
+ }
+ }
+ xml_parser_free($this->parser);
+ } else {
+ $this->debug('xml was empty, didn\'t parse!');
+ $this->setError('xml was empty, didn\'t parse!');
+ }
+ }
+
+ /**
+ * start-element handler
+ *
+ * @param resource $parser XML parser object
+ * @param string $name element name
+ * @param array $attrs associative array of attributes
+ * @access private
+ */
+ function start_element($parser, $name, $attrs) {
+ // position in a total number of elements, starting from 0
+ // update class level pos
+ $pos = $this->position++;
+ // and set mine
+ $this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>'');
+ // depth = how many levels removed from root?
+ // set mine as current global depth and increment global depth value
+ $this->message[$pos]['depth'] = $this->depth++;
+
+ // else add self as child to whoever the current parent is
+ if($pos != 0){
+ $this->message[$this->parent]['children'] .= '|'.$pos;
+ }
+ // set my parent
+ $this->message[$pos]['parent'] = $this->parent;
+ // set self as current parent
+ $this->parent = $pos;
+ // set self as current value for this depth
+ $this->depth_array[$this->depth] = $pos;
+ // get element prefix
+ if(strpos($name,':')){
+ // get ns prefix
+ $prefix = substr($name,0,strpos($name,':'));
+ // get unqualified name
+ $name = substr(strstr($name,':'),1);
+ }
+ // set status
+ if ($name == 'Envelope' && $this->status == '') {
+ $this->status = 'envelope';
+ } elseif ($name == 'Header' && $this->status == 'envelope') {
+ $this->root_header = $pos;
+ $this->status = 'header';
+ } elseif ($name == 'Body' && $this->status == 'envelope'){
+ $this->status = 'body';
+ $this->body_position = $pos;
+ // set method
+ } elseif($this->status == 'body' && $pos == ($this->body_position+1)) {
+ $this->status = 'method';
+ $this->root_struct_name = $name;
+ $this->root_struct = $pos;
+ $this->message[$pos]['type'] = 'struct';
+ $this->debug("found root struct $this->root_struct_name, pos $this->root_struct");
+ }
+ // set my status
+ $this->message[$pos]['status'] = $this->status;
+ // set name
+ $this->message[$pos]['name'] = htmlspecialchars($name);
+ // set attrs
+ $this->message[$pos]['attrs'] = $attrs;
+
+ // loop through atts, logging ns and type declarations
+ $attstr = '';
+ foreach($attrs as $key => $value){
+ $key_prefix = $this->getPrefix($key);
+ $key_localpart = $this->getLocalPart($key);
+ // if ns declarations, add to class level array of valid namespaces
+ if($key_prefix == 'xmlns'){
+ if(preg_match('/^http:\/\/www.w3.org\/[0-9]{4}\/XMLSchema$/',$value)){
+ $this->XMLSchemaVersion = $value;
+ $this->namespaces['xsd'] = $this->XMLSchemaVersion;
+ $this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance';
+ }
+ $this->namespaces[$key_localpart] = $value;
+ // set method namespace
+ if($name == $this->root_struct_name){
+ $this->methodNamespace = $value;
+ }
+ // if it's a type declaration, set type
+ } elseif($key_localpart == 'type'){
+ if (isset($this->message[$pos]['type']) && $this->message[$pos]['type'] == 'array') {
+ // do nothing: already processed arrayType
+ } else {
+ $value_prefix = $this->getPrefix($value);
+ $value_localpart = $this->getLocalPart($value);
+ $this->message[$pos]['type'] = $value_localpart;
+ $this->message[$pos]['typePrefix'] = $value_prefix;
+ if(isset($this->namespaces[$value_prefix])){
+ $this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix];
+ } else if(isset($attrs['xmlns:'.$value_prefix])) {
+ $this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix];
+ }
+ // should do something here with the namespace of specified type?
+ }
+ } elseif($key_localpart == 'arrayType'){
+ $this->message[$pos]['type'] = 'array';
+ /* do arrayType ereg here
+ [1] arrayTypeValue ::= atype asize
+ [2] atype ::= QName rank*
+ [3] rank ::= '[' (',')* ']'
+ [4] asize ::= '[' length~ ']'
+ [5] length ::= nextDimension* Digit+
+ [6] nextDimension ::= Digit+ ','
+ */
+ $expr = '/([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]/';
+ if(preg_match($expr,$value,$regs)){
+ $this->message[$pos]['typePrefix'] = $regs[1];
+ $this->message[$pos]['arrayTypePrefix'] = $regs[1];
+ if (isset($this->namespaces[$regs[1]])) {
+ $this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]];
+ } else if (isset($attrs['xmlns:'.$regs[1]])) {
+ $this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]];
+ }
+ $this->message[$pos]['arrayType'] = $regs[2];
+ $this->message[$pos]['arraySize'] = $regs[3];
+ $this->message[$pos]['arrayCols'] = $regs[4];
+ }
+ // specifies nil value (or not)
+ } elseif ($key_localpart == 'nil'){
+ $this->message[$pos]['nil'] = ($value == 'true' || $value == '1');
+ // some other attribute
+ } elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') {
+ $this->message[$pos]['xattrs']['!' . $key] = $value;
+ }
+
+ if ($key == 'xmlns') {
+ $this->default_namespace = $value;
+ }
+ // log id
+ if($key == 'id'){
+ $this->ids[$value] = $pos;
+ }
+ // root
+ if($key_localpart == 'root' && $value == 1){
+ $this->status = 'method';
+ $this->root_struct_name = $name;
+ $this->root_struct = $pos;
+ $this->debug("found root struct $this->root_struct_name, pos $pos");
+ }
+ // for doclit
+ $attstr .= " $key=\"$value\"";
+ }
+ // get namespace - must be done after namespace atts are processed
+ if(isset($prefix)){
+ $this->message[$pos]['namespace'] = $this->namespaces[$prefix];
+ $this->default_namespace = $this->namespaces[$prefix];
+ } else {
+ $this->message[$pos]['namespace'] = $this->default_namespace;
+ }
+ if($this->status == 'header'){
+ if ($this->root_header != $pos) {
+ $this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
+ }
+ } elseif($this->root_struct_name != ''){
+ $this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
+ }
+ }
+
+ /**
+ * end-element handler
+ *
+ * @param resource $parser XML parser object
+ * @param string $name element name
+ * @access private
+ */
+ function end_element($parser, $name) {
+ // position of current element is equal to the last value left in depth_array for my depth
+ $pos = $this->depth_array[$this->depth--];
+
+ // get element prefix
+ if(strpos($name,':')){
+ // get ns prefix
+ $prefix = substr($name,0,strpos($name,':'));
+ // get unqualified name
+ $name = substr(strstr($name,':'),1);
+ }
+
+ // build to native type
+ if(isset($this->body_position) && $pos > $this->body_position){
+ // deal w/ multirefs
+ if(isset($this->message[$pos]['attrs']['href'])){
+ // get id
+ $id = substr($this->message[$pos]['attrs']['href'],1);
+ // add placeholder to href array
+ $this->multirefs[$id][$pos] = 'placeholder';
+ // add set a reference to it as the result value
+ $this->message[$pos]['result'] =& $this->multirefs[$id][$pos];
+ // build complexType values
+ } elseif($this->message[$pos]['children'] != ''){
+ // if result has already been generated (struct/array)
+ if(!isset($this->message[$pos]['result'])){
+ $this->message[$pos]['result'] = $this->buildVal($pos);
+ }
+ // build complexType values of attributes and possibly simpleContent
+ } elseif (isset($this->message[$pos]['xattrs'])) {
+ if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
+ $this->message[$pos]['xattrs']['!'] = null;
+ } elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
+ if (isset($this->message[$pos]['type'])) {
+ $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
+ } else {
+ $parent = $this->message[$pos]['parent'];
+ if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
+ $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
+ } else {
+ $this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata'];
+ }
+ }
+ }
+ $this->message[$pos]['result'] = $this->message[$pos]['xattrs'];
+ // set value of simpleType (or nil complexType)
+ } else {
+ //$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']);
+ if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
+ $this->message[$pos]['xattrs']['!'] = null;
+ } elseif (isset($this->message[$pos]['type'])) {
+ $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
+ } else {
+ $parent = $this->message[$pos]['parent'];
+ if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
+ $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
+ } else {
+ $this->message[$pos]['result'] = $this->message[$pos]['cdata'];
+ }
+ }
+
+ /* add value to parent's result, if parent is struct/array
+ $parent = $this->message[$pos]['parent'];
+ if($this->message[$parent]['type'] != 'map'){
+ if(strtolower($this->message[$parent]['type']) == 'array'){
+ $this->message[$parent]['result'][] = $this->message[$pos]['result'];
+ } else {
+ $this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result'];
+ }
+ }
+ */
+ }
+ }
+
+ // for doclit
+ if($this->status == 'header'){
+ if ($this->root_header != $pos) {
+ $this->responseHeaders .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
+ }
+ } elseif($pos >= $this->root_struct){
+ $this->document .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
+ }
+ // switch status
+ if ($pos == $this->root_struct){
+ $this->status = 'body';
+ $this->root_struct_namespace = $this->message[$pos]['namespace'];
+ } elseif ($pos == $this->root_header) {
+ $this->status = 'envelope';
+ } elseif ($name == 'Body' && $this->status == 'body') {
+ $this->status = 'envelope';
+ } elseif ($name == 'Header' && $this->status == 'header') { // will never happen
+ $this->status = 'envelope';
+ } elseif ($name == 'Envelope' && $this->status == 'envelope') {
+ $this->status = '';
+ }
+ // set parent back to my parent
+ $this->parent = $this->message[$pos]['parent'];
+ }
+
+ /**
+ * element content handler
+ *
+ * @param resource $parser XML parser object
+ * @param string $data element content
+ * @access private
+ */
+ function character_data($parser, $data){
+ $pos = $this->depth_array[$this->depth];
+ if ($this->xml_encoding=='UTF-8'){
+ // TODO: add an option to disable this for folks who want
+ // raw UTF-8 that, e.g., might not map to iso-8859-1
+ // TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
+ if($this->decode_utf8){
+ $data = utf8_decode($data);
+ }
+ }
+ $this->message[$pos]['cdata'] .= $data;
+ // for doclit
+ if($this->status == 'header'){
+ $this->responseHeaders .= $data;
+ } else {
+ $this->document .= $data;
+ }
+ }
+
+ /**
+ * get the parsed message (SOAP Body)
+ *
+ * @return mixed
+ * @access public
+ * @deprecated use get_soapbody instead
+ */
+ function get_response(){
+ return $this->soapresponse;
+ }
+
+ /**
+ * get the parsed SOAP Body (NULL if there was none)
+ *
+ * @return mixed
+ * @access public
+ */
+ function get_soapbody(){
+ return $this->soapresponse;
+ }
+
+ /**
+ * get the parsed SOAP Header (NULL if there was none)
+ *
+ * @return mixed
+ * @access public
+ */
+ function get_soapheader(){
+ return $this->soapheader;
+ }
+
+ /**
+ * get the unparsed SOAP Header
+ *
+ * @return string XML or empty if no Header
+ * @access public
+ */
+ function getHeaders(){
+ return $this->responseHeaders;
+ }
+
+ /**
+ * decodes simple types into PHP variables
+ *
+ * @param string $value value to decode
+ * @param string $type XML type to decode
+ * @param string $typens XML type namespace to decode
+ * @return mixed PHP value
+ * @access private
+ */
+ function decodeSimple($value, $type, $typens) {
+ // TODO: use the namespace!
+ if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') {
+ return (string) $value;
+ }
+ if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') {
+ return (int) $value;
+ }
+ if ($type == 'float' || $type == 'double' || $type == 'decimal') {
+ return (double) $value;
+ }
+ if ($type == 'boolean') {
+ if (strtolower($value) == 'false' || strtolower($value) == 'f') {
+ return false;
+ }
+ return (boolean) $value;
+ }
+ if ($type == 'base64' || $type == 'base64Binary') {
+ $this->debug('Decode base64 value');
+ return base64_decode($value);
+ }
+ // obscure numeric types
+ if ($type == 'nonPositiveInteger' || $type == 'negativeInteger'
+ || $type == 'nonNegativeInteger' || $type == 'positiveInteger'
+ || $type == 'unsignedInt'
+ || $type == 'unsignedShort' || $type == 'unsignedByte') {
+ return (int) $value;
+ }
+ // bogus: parser treats array with no elements as a simple type
+ if ($type == 'array') {
+ return array();
+ }
+ // everything else
+ return (string) $value;
+ }
+
+ /**
+ * builds response structures for compound values (arrays/structs)
+ * and scalars
+ *
+ * @param integer $pos position in node tree
+ * @return mixed PHP value
+ * @access private
+ */
+ function buildVal($pos){
+ if(!isset($this->message[$pos]['type'])){
+ $this->message[$pos]['type'] = '';
+ }
+ $this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']);
+ // if there are children...
+ if($this->message[$pos]['children'] != ''){
+ $this->debug('in buildVal, there are children');
+ $children = explode('|',$this->message[$pos]['children']);
+ array_shift($children); // knock off empty
+ // md array
+ if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){
+ $r=0; // rowcount
+ $c=0; // colcount
+ foreach($children as $child_pos){
+ $this->debug("in buildVal, got an MD array element: $r, $c");
+ $params[$r][] = $this->message[$child_pos]['result'];
+ $c++;
+ if($c == $this->message[$pos]['arrayCols']){
+ $c = 0;
+ $r++;
+ }
+ }
+ // array
+ } elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){
+ $this->debug('in buildVal, adding array '.$this->message[$pos]['name']);
+ foreach($children as $child_pos){
+ $params[] = &$this->message[$child_pos]['result'];
+ }
+ // apache Map type: java hashtable
+ } elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){
+ $this->debug('in buildVal, Java Map '.$this->message[$pos]['name']);
+ foreach($children as $child_pos){
+ $kv = explode("|",$this->message[$child_pos]['children']);
+ $params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result'];
+ }
+ // generic compound type
+ //} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') {
+ } else {
+ // Apache Vector type: treat as an array
+ $this->debug('in buildVal, adding Java Vector or generic compound type '.$this->message[$pos]['name']);
+ if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') {
+ $notstruct = 1;
+ } else {
+ $notstruct = 0;
+ }
+ //
+ foreach($children as $child_pos){
+ if($notstruct){
+ $params[] = &$this->message[$child_pos]['result'];
+ } else {
+ if (isset($params[$this->message[$child_pos]['name']])) {
+ // de-serialize repeated element name into an array
+ if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) {
+ $params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]);
+ }
+ $params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result'];
+ } else {
+ $params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result'];
+ }
+ }
+ }
+ }
+ if (isset($this->message[$pos]['xattrs'])) {
+ $this->debug('in buildVal, handling attributes');
+ foreach ($this->message[$pos]['xattrs'] as $n => $v) {
+ $params[$n] = $v;
+ }
+ }
+ // handle simpleContent
+ if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
+ $this->debug('in buildVal, handling simpleContent');
+ if (isset($this->message[$pos]['type'])) {
+ $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
+ } else {
+ $parent = $this->message[$pos]['parent'];
+ if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
+ $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
+ } else {
+ $params['!'] = $this->message[$pos]['cdata'];
+ }
+ }
+ }
+ $ret = is_array($params) ? $params : array();
+ $this->debug('in buildVal, return:');
+ $this->appendDebug($this->varDump($ret));
+ return $ret;
+ } else {
+ $this->debug('in buildVal, no children, building scalar');
+ $cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : '';
+ if (isset($this->message[$pos]['type'])) {
+ $ret = $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
+ $this->debug("in buildVal, return: $ret");
+ return $ret;
+ }
+ $parent = $this->message[$pos]['parent'];
+ if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
+ $ret = $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
+ $this->debug("in buildVal, return: $ret");
+ return $ret;
+ }
+ $ret = $this->message[$pos]['cdata'];
+ $this->debug("in buildVal, return: $ret");
+ return $ret;
+ }
+ }
+}
+
+/**
+ * Backward compatibility
+ */
+class soap_parser extends nusoap_parser {
+}
+
+?><?php
+
+
+
+/**
+*
+* [nu]soapclient higher level class for easy usage.
+*
+* usage:
+*
+* // instantiate client with server info
+* $soapclient = new nusoap_client( string path [ ,mixed wsdl] );
+*
+* // call method, get results
+* echo $soapclient->call( string methodname [ ,array parameters] );
+*
+* // bye bye client
+* unset($soapclient);
+*
+* @author Dietrich Ayala <dietrich@ganx4.com>
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_client extends nusoap_base {
+
+ var $username = ''; // Username for HTTP authentication
+ var $password = ''; // Password for HTTP authentication
+ var $authtype = ''; // Type of HTTP authentication
+ var $certRequest = array(); // Certificate for HTTP SSL authentication
+ var $requestHeaders = false; // SOAP headers in request (text)
+ var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text)
+ var $responseHeader = NULL; // SOAP Header from response (parsed)
+ var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text)
+ var $endpoint;
+ var $forceEndpoint = ''; // overrides WSDL endpoint
+ var $proxyhost = '';
+ var $proxyport = '';
+ var $proxyusername = '';
+ var $proxypassword = '';
+ var $portName = ''; // port name to use in WSDL
+ var $xml_encoding = ''; // character set encoding of incoming (response) messages
+ var $http_encoding = false;
+ var $timeout = 0; // HTTP connection timeout
+ var $response_timeout = 30; // HTTP response timeout
+ var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error
+ var $persistentConnection = false;
+ var $defaultRpcParams = false; // This is no longer used
+ var $request = ''; // HTTP request
+ var $response = ''; // HTTP response
+ var $responseData = ''; // SOAP payload of response
+ var $cookies = array(); // Cookies from response or for request
+ var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode()
+ var $operations = array(); // WSDL operations, empty for WSDL initialization error
+ var $curl_options = array(); // User-specified cURL options
+ var $bindingType = ''; // WSDL operation binding type
+ var $use_curl = false; // whether to always try to use cURL
+
+ /*
+ * fault related variables
+ */
+ /**
+ * @var fault
+ * @access public
+ */
+ var $fault;
+ /**
+ * @var faultcode
+ * @access public
+ */
+ var $faultcode;
+ /**
+ * @var faultstring
+ * @access public
+ */
+ var $faultstring;
+ /**
+ * @var faultdetail
+ * @access public
+ */
+ var $faultdetail;
+
+ /**
+ * constructor
+ *
+ * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object)
+ * @param mixed $wsdl optional, set to 'wsdl' or true if using WSDL
+ * @param string $proxyhost optional
+ * @param string $proxyport optional
+ * @param string $proxyusername optional
+ * @param string $proxypassword optional
+ * @param integer $timeout set the connection timeout
+ * @param integer $response_timeout set the response timeout
+ * @param string $portName optional portName in WSDL document
+ * @access public
+ */
+ function nusoap_client($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30, $portName = ''){
+ parent::nusoap_base();
+ $this->endpoint = $endpoint;
+ $this->proxyhost = $proxyhost;
+ $this->proxyport = $proxyport;
+ $this->proxyusername = $proxyusername;
+ $this->proxypassword = $proxypassword;
+ $this->timeout = $timeout;
+ $this->response_timeout = $response_timeout;
+ $this->portName = $portName;
+
+ $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
+ $this->appendDebug('endpoint=' . $this->varDump($endpoint));
+
+ // make values
+ if($wsdl){
+ if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) {
+ $this->wsdl = $endpoint;
+ $this->endpoint = $this->wsdl->wsdl;
+ $this->wsdlFile = $this->endpoint;
+ $this->debug('existing wsdl instance created from ' . $this->endpoint);
+ $this->checkWSDL();
+ } else {
+ $this->wsdlFile = $this->endpoint;
+ $this->wsdl = null;
+ $this->debug('will use lazy evaluation of wsdl from ' . $this->endpoint);
+ }
+ $this->endpointType = 'wsdl';
+ } else {
+ $this->debug("instantiate SOAP with endpoint at $endpoint");
+ $this->endpointType = 'soap';
+ }
+ }
+
+ /**
+ * calls method, returns PHP native type
+ *
+ * @param string $operation SOAP server URL or path
+ * @param mixed $params An array, associative or simple, of the parameters
+ * for the method call, or a string that is the XML
+ * for the call. For rpc style, this call will
+ * wrap the XML in a tag named after the method, as
+ * well as the SOAP Envelope and Body. For document
+ * style, this will only wrap with the Envelope and Body.
+ * IMPORTANT: when using an array with document style,
+ * in which case there
+ * is really one parameter, the root of the fragment
+ * used in the call, which encloses what programmers
+ * normally think of parameters. A parameter array
+ * *must* include the wrapper.
+ * @param string $namespace optional method namespace (WSDL can override)
+ * @param string $soapAction optional SOAPAction value (WSDL can override)
+ * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array
+ * @param boolean $rpcParams optional (no longer used)
+ * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override)
+ * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override)
+ * @return mixed response from SOAP call, normally an associative array mirroring the structure of the XML response, false for certain fatal errors
+ * @access public
+ */
+ function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){
+ $this->operation = $operation;
+ $this->fault = false;
+ $this->setError('');
+ $this->request = '';
+ $this->response = '';
+ $this->responseData = '';
+ $this->faultstring = '';
+ $this->faultcode = '';
+ $this->opData = array();
+
+ $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType");
+ $this->appendDebug('params=' . $this->varDump($params));
+ $this->appendDebug('headers=' . $this->varDump($headers));
+ if ($headers) {
+ $this->requestHeaders = $headers;
+ }
+ if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
+ $this->loadWSDL();
+ if ($this->getError())
+ return false;
+ }
+ // serialize parameters
+ if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){
+ // use WSDL for operation
+ $this->opData = $opData;
+ $this->debug("found operation");
+ $this->appendDebug('opData=' . $this->varDump($opData));
+ if (isset($opData['soapAction'])) {
+ $soapAction = $opData['soapAction'];
+ }
+ if (! $this->forceEndpoint) {
+ $this->endpoint = $opData['endpoint'];
+ } else {
+ $this->endpoint = $this->forceEndpoint;
+ }
+ $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace;
+ $style = $opData['style'];
+ $use = $opData['input']['use'];
+ // add ns to ns array
+ if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){
+ $nsPrefix = 'ns' . rand(1000, 9999);
+ $this->wsdl->namespaces[$nsPrefix] = $namespace;
+ }
+ $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace);
+ // serialize payload
+ if (is_string($params)) {
+ $this->debug("serializing param string for WSDL operation $operation");
+ $payload = $params;
+ } elseif (is_array($params)) {
+ $this->debug("serializing param array for WSDL operation $operation");
+ $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params,$this->bindingType);
+ } else {
+ $this->debug('params must be array or string');
+ $this->setError('params must be array or string');
+ return false;
+ }
+ $usedNamespaces = $this->wsdl->usedNamespaces;
+ if (isset($opData['input']['encodingStyle'])) {
+ $encodingStyle = $opData['input']['encodingStyle'];
+ } else {
+ $encodingStyle = '';
+ }
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ if ($errstr = $this->wsdl->getError()) {
+ $this->debug('got wsdl error: '.$errstr);
+ $this->setError('wsdl error: '.$errstr);
+ return false;
+ }
+ } elseif($this->endpointType == 'wsdl') {
+ // operation not in WSDL
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->setError('operation '.$operation.' not present in WSDL.');
+ $this->debug("operation '$operation' not present in WSDL.");
+ return false;
+ } else {
+ // no WSDL
+ //$this->namespaces['ns1'] = $namespace;
+ $nsPrefix = 'ns' . rand(1000, 9999);
+ // serialize
+ $payload = '';
+ if (is_string($params)) {
+ $this->debug("serializing param string for operation $operation");
+ $payload = $params;
+ } elseif (is_array($params)) {
+ $this->debug("serializing param array for operation $operation");
+ foreach($params as $k => $v){
+ $payload .= $this->serialize_val($v,$k,false,false,false,false,$use);
+ }
+ } else {
+ $this->debug('params must be array or string');
+ $this->setError('params must be array or string');
+ return false;
+ }
+ $usedNamespaces = array();
+ if ($use == 'encoded') {
+ $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
+ } else {
+ $encodingStyle = '';
+ }
+ }
+ // wrap RPC calls with method element
+ if ($style == 'rpc') {
+ if ($use == 'literal') {
+ $this->debug("wrapping RPC request with literal method element");
+ if ($namespace) {
+ // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace
+ $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
+ $payload .
+ "</$nsPrefix:$operation>";
+ } else {
+ $payload = "<$operation>" . $payload . "</$operation>";
+ }
+ } else {
+ $this->debug("wrapping RPC request with encoded method element");
+ if ($namespace) {
+ $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
+ $payload .
+ "</$nsPrefix:$operation>";
+ } else {
+ $payload = "<$operation>" .
+ $payload .
+ "</$operation>";
+ }
+ }
+ }
+ // serialize envelope
+ $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle);
+ $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle");
+ $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));
+ // send
+ $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);
+ if($errstr = $this->getError()){
+ $this->debug('Error: '.$errstr);
+ return false;
+ } else {
+ $this->return = $return;
+ $this->debug('sent message successfully and got a(n) '.gettype($return));
+ $this->appendDebug('return=' . $this->varDump($return));
+
+ // fault?
+ if(is_array($return) && isset($return['faultcode'])){
+ $this->debug('got fault');
+ $this->setError($return['faultcode'].': '.$return['faultstring']);
+ $this->fault = true;
+ foreach($return as $k => $v){
+ $this->$k = $v;
+ $this->debug("$k = $v<br>");
+ }
+ return $return;
+ } elseif ($style == 'document') {
+ // NOTE: if the response is defined to have multiple parts (i.e. unwrapped),
+ // we are only going to return the first part here...sorry about that
+ return $return;
+ } else {
+ // array of return values
+ if(is_array($return)){
+ // multiple 'out' parameters, which we return wrapped up
+ // in the array
+ if(sizeof($return) > 1){
+ return $return;
+ }
+ // single 'out' parameter (normally the return value)
+ $return = array_shift($return);
+ $this->debug('return shifted value: ');
+ $this->appendDebug($this->varDump($return));
+ return $return;
+ // nothing returned (ie, echoVoid)
+ } else {
+ return "";
+ }
+ }
+ }
+ }
+
+ /**
+ * check WSDL passed as an instance or pulled from an endpoint
+ *
+ * @access private
+ */
+ function checkWSDL() {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->debug('checkWSDL');
+ // catch errors
+ if ($errstr = $this->wsdl->getError()) {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->debug('got wsdl error: '.$errstr);
+ $this->setError('wsdl error: '.$errstr);
+ } elseif ($this->operations = $this->wsdl->getOperations($this->portName, 'soap')) {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->bindingType = 'soap';
+ $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType);
+ } elseif ($this->operations = $this->wsdl->getOperations($this->portName, 'soap12')) {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->bindingType = 'soap12';
+ $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType);
+ $this->debug('**************** WARNING: SOAP 1.2 BINDING *****************');
+ } else {
+ $this->appendDebug($this->wsdl->getDebug());
+ $this->wsdl->clearDebug();
+ $this->debug('getOperations returned false');
+ $this->setError('no operations defined in the WSDL document!');
+ }
+ }
+
+ /**
+ * instantiate wsdl object and parse wsdl file
+ *
+ * @access public
+ */
+ function loadWSDL() {
+ $this->debug('instantiating wsdl class with doc: '.$this->wsdlFile);
+ $this->wsdl = new wsdl('',$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout,$this->curl_options,$this->use_curl);
+ $this->wsdl->setCredentials($this->username, $this->password, $this->authtype, $this->certRequest);
+ $this->wsdl->fetchWSDL($this->wsdlFile);
+ $this->checkWSDL();
+ }
+
+ /**
+ * get available data pertaining to an operation
+ *
+ * @param string $operation operation name
+ * @return array array of data pertaining to the operation
+ * @access public
+ */
+ function getOperationData($operation){
+ if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
+ $this->loadWSDL();
+ if ($this->getError())
+ return false;
+ }
+ if(isset($this->operations[$operation])){
+ return $this->operations[$operation];
+ }
+ $this->debug("No data for operation: $operation");
+ }
+
+ /**
+ * send the SOAP message
+ *
+ * Note: if the operation has multiple return values
+ * the return value of this method will be an array
+ * of those values.
+ *
+ * @param string $msg a SOAPx4 soapmsg object
+ * @param string $soapaction SOAPAction value
+ * @param integer $timeout set connection timeout in seconds
+ * @param integer $response_timeout set response timeout in seconds
+ * @return mixed native PHP types.
+ * @access private
+ */
+ function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) {
+ $this->checkCookies();
+ // detect transport
+ switch(true){
+ // http(s)
+ case preg_match('/^http/',$this->endpoint):
+ $this->debug('transporting via HTTP');
+ if($this->persistentConnection == true && is_object($this->persistentConnection)){
+ $http =& $this->persistentConnection;
+ } else {
+ $http = new soap_transport_http($this->endpoint, $this->curl_options, $this->use_curl);
+ if ($this->persistentConnection) {
+ $http->usePersistentConnection();
+ }
+ }
+ $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset());
+ $http->setSOAPAction($soapaction);
+ if($this->proxyhost && $this->proxyport){
+ $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
+ }
+ if($this->authtype != '') {
+ $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
+ }
+ if($this->http_encoding != ''){
+ $http->setEncoding($this->http_encoding);
+ }
+ $this->debug('sending message, length='.strlen($msg));
+ if(preg_match('/^http:/',$this->endpoint)){
+ //if(strpos($this->endpoint,'http:')){
+ $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies);
+ } elseif(preg_match('/^https/',$this->endpoint)){
+ //} elseif(strpos($this->endpoint,'https:')){
+ //if(phpversion() == '4.3.0-dev'){
+ //$response = $http->send($msg,$timeout,$response_timeout);
+ //$this->request = $http->outgoing_payload;
+ //$this->response = $http->incoming_payload;
+ //} else
+ $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies);
+ } else {
+ $this->setError('no http/s in endpoint url');
+ }
+ $this->request = $http->outgoing_payload;
+ $this->response = $http->incoming_payload;
+ $this->appendDebug($http->getDebug());
+ $this->UpdateCookies($http->incoming_cookies);
+
+ // save transport object if using persistent connections
+ if ($this->persistentConnection) {
+ $http->clearDebug();
+ if (!is_object($this->persistentConnection)) {
+ $this->persistentConnection = $http;
+ }
+ }
+
+ if($err = $http->getError()){
+ $this->setError('HTTP Error: '.$err);
+ return false;
+ } elseif($this->getError()){
+ return false;
+ } else {
+ $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']);
+ return $this->parseResponse($http->incoming_headers, $this->responseData);
+ }
+ break;
+ default:
+ $this->setError('no transport found, or selected transport is not yet supported!');
+ return false;
+ break;
+ }
+ }
+
+ /**
+ * processes SOAP message returned from server
+ *
+ * @param array $headers The HTTP headers
+ * @param string $data unprocessed response data from server
+ * @return mixed value of the message, decoded into a PHP type
+ * @access private
+ */
+ function parseResponse($headers, $data) {
+ $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' headers:');
+ $this->appendDebug($this->varDump($headers));
+ if (!isset($headers['content-type'])) {
+ $this->setError('Response not of type text/xml (no content-type header)');
+ return false;
+ }
+ if (!strstr($headers['content-type'], 'text/xml')) {
+ $this->setError('Response not of type text/xml: ' . $headers['content-type']);
+ return false;
+ }
+ if (strpos($headers['content-type'], '=')) {
+ $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
+ $this->debug('Got response encoding: ' . $enc);
+ if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
+ $this->xml_encoding = strtoupper($enc);
+ } else {
+ $this->xml_encoding = 'US-ASCII';
+ }
+ } else {
+ // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
+ $this->xml_encoding = 'ISO-8859-1';
+ }
+ $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
+ $parser = new nusoap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8);
+ // add parser debug data to our debug
+ $this->appendDebug($parser->getDebug());
+ // if parse errors
+ if($errstr = $parser->getError()){
+ $this->setError( $errstr);
+ // destroy the parser object
+ unset($parser);
+ return false;
+ } else {
+ // get SOAP headers
+ $this->responseHeaders = $parser->getHeaders();
+ // get SOAP headers
+ $this->responseHeader = $parser->get_soapheader();
+ // get decoded message
+ $return = $parser->get_soapbody();
+ // add document for doclit support
+ $this->document = $parser->document;
+ // destroy the parser object
+ unset($parser);
+ // return decode message
+ return $return;
+ }
+ }
+
+ /**
+ * sets user-specified cURL options
+ *
+ * @param mixed $option The cURL option (always integer?)
+ * @param mixed $value The cURL option value
+ * @access public
+ */
+ function setCurlOption($option, $value) {
+ $this->debug("setCurlOption option=$option, value=");
+ $this->appendDebug($this->varDump($value));
+ $this->curl_options[$option] = $value;
+ }
+
+ /**
+ * sets the SOAP endpoint, which can override WSDL
+ *
+ * @param string $endpoint The endpoint URL to use, or empty string or false to prevent override
+ * @access public
+ */
+ function setEndpoint($endpoint) {
+ $this->debug("setEndpoint(\"$endpoint\")");
+ $this->forceEndpoint = $endpoint;
+ }
+
+ /**
+ * set the SOAP headers
+ *
+ * @param mixed $headers String of XML with SOAP header content, or array of soapval objects for SOAP headers
+ * @access public
+ */
+ function setHeaders($headers){
+ $this->debug("setHeaders headers=");
+ $this->appendDebug($this->varDump($headers));
+ $this->requestHeaders = $headers;
+ }
+
+ /**
+ * get the SOAP response headers (namespace resolution incomplete)
+ *
+ * @return string
+ * @access public
+ */
+ function getHeaders(){
+ return $this->responseHeaders;
+ }
+
+ /**
+ * get the SOAP response Header (parsed)
+ *
+ * @return mixed
+ * @access public
+ */
+ function getHeader(){
+ return $this->responseHeader;
+ }
+
+ /**
+ * set proxy info here
+ *
+ * @param string $proxyhost
+ * @param string $proxyport
+ * @param string $proxyusername
+ * @param string $proxypassword
+ * @access public
+ */
+ function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') {
+ $this->proxyhost = $proxyhost;
+ $this->proxyport = $proxyport;
+ $this->proxyusername = $proxyusername;
+ $this->proxypassword = $proxypassword;
+ }
+
+ /**
+ * if authenticating, set user credentials here
+ *
+ * @param string $username
+ * @param string $password
+ * @param string $authtype (basic|digest|certificate|ntlm)
+ * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
+ * @access public
+ */
+ function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
+ $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
+ $this->appendDebug($this->varDump($certRequest));
+ $this->username = $username;
+ $this->password = $password;
+ $this->authtype = $authtype;
+ $this->certRequest = $certRequest;
+ }
+
+ /**
+ * use HTTP encoding
+ *
+ * @param string $enc HTTP encoding
+ * @access public
+ */
+ function setHTTPEncoding($enc='gzip, deflate'){
+ $this->debug("setHTTPEncoding(\"$enc\")");
+ $this->http_encoding = $enc;
+ }
+
+ /**
+ * Set whether to try to use cURL connections if possible
+ *
+ * @param boolean $use Whether to try to use cURL
+ * @access public
+ */
+ function setUseCURL($use) {
+ $this->debug("setUseCURL($use)");
+ $this->use_curl = $use;
+ }
+
+ /**
+ * use HTTP persistent connections if possible
+ *
+ * @access public
+ */
+ function useHTTPPersistentConnection(){
+ $this->debug("useHTTPPersistentConnection");
+ $this->persistentConnection = true;
+ }
+
+ /**
+ * gets the default RPC parameter setting.
+ * If true, default is that call params are like RPC even for document style.
+ * Each call() can override this value.
+ *
+ * This is no longer used.
+ *
+ * @return boolean
+ * @access public
+ * @deprecated
+ */
+ function getDefaultRpcParams() {
+ return $this->defaultRpcParams;
+ }
+
+ /**
+ * sets the default RPC parameter setting.
+ * If true, default is that call params are like RPC even for document style
+ * Each call() can override this value.
+ *
+ * This is no longer used.
+ *
+ * @param boolean $rpcParams
+ * @access public
+ * @deprecated
+ */
+ function setDefaultRpcParams($rpcParams) {
+ $this->defaultRpcParams = $rpcParams;
+ }
+
+ /**
+ * dynamically creates an instance of a proxy class,
+ * allowing user to directly call methods from wsdl
+ *
+ * @return object soap_proxy object
+ * @access public
+ */
+ function getProxy() {
+ $r = rand();
+ $evalStr = $this->_getProxyClassCode($r);
+ //$this->debug("proxy class: $evalStr");
+ if ($this->getError()) {
+ $this->debug("Error from _getProxyClassCode, so return NULL");
+ return null;
+ }
+ // eval the class
+ eval($evalStr);
+ // instantiate proxy object
+ eval("\$proxy = new nusoap_proxy_$r('');");
+ // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice
+ $proxy->endpointType = 'wsdl';
+ $proxy->wsdlFile = $this->wsdlFile;
+ $proxy->wsdl = $this->wsdl;
+ $proxy->operations = $this->operations;
+ $proxy->defaultRpcParams = $this->defaultRpcParams;
+ // transfer other state
+ $proxy->soap_defencoding = $this->soap_defencoding;
+ $proxy->username = $this->username;
+ $proxy->password = $this->password;
+ $proxy->authtype = $this->authtype;
+ $proxy->certRequest = $this->certRequest;
+ $proxy->requestHeaders = $this->requestHeaders;
+ $proxy->endpoint = $this->endpoint;
+ $proxy->forceEndpoint = $this->forceEndpoint;
+ $proxy->proxyhost = $this->proxyhost;
+ $proxy->proxyport = $this->proxyport;
+ $proxy->proxyusername = $this->proxyusername;
+ $proxy->proxypassword = $this->proxypassword;
+ $proxy->http_encoding = $this->http_encoding;
+ $proxy->timeout = $this->timeout;
+ $proxy->response_timeout = $this->response_timeout;
+ $proxy->persistentConnection = &$this->persistentConnection;
+ $proxy->decode_utf8 = $this->decode_utf8;
+ $proxy->curl_options = $this->curl_options;
+ $proxy->bindingType = $this->bindingType;
+ $proxy->use_curl = $this->use_curl;
+ return $proxy;
+ }
+
+ /**
+ * dynamically creates proxy class code
+ *
+ * @return string PHP/NuSOAP code for the proxy class
+ * @access private
+ */
+ function _getProxyClassCode($r) {
+ $this->debug("in getProxy endpointType=$this->endpointType");
+ $this->appendDebug("wsdl=" . $this->varDump($this->wsdl));
+ if ($this->endpointType != 'wsdl') {
+ $evalStr = 'A proxy can only be created for a WSDL client';
+ $this->setError($evalStr);
+ $evalStr = "echo \"$evalStr\";";
+ return $evalStr;
+ }
+ if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
+ $this->loadWSDL();
+ if ($this->getError()) {
+ return "echo \"" . $this->getError() . "\";";
+ }
+ }
+ $evalStr = '';
+ foreach ($this->operations as $operation => $opData) {
+ if ($operation != '') {
+ // create param string and param comment string
+ if (sizeof($opData['input']['parts']) > 0) {
+ $paramStr = '';
+ $paramArrayStr = '';
+ $paramCommentStr = '';
+ foreach ($opData['input']['parts'] as $name => $type) {
+ $paramStr .= "\$$name, ";
+ $paramArrayStr .= "'$name' => \$$name, ";
+ $paramCommentStr .= "$type \$$name, ";
+ }
+ $paramStr = substr($paramStr, 0, strlen($paramStr)-2);
+ $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2);
+ $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2);
+ } else {
+ $paramStr = '';
+ $paramArrayStr = '';
+ $paramCommentStr = 'void';
+ }
+ $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace'];
+ $evalStr .= "// $paramCommentStr
+ function " . str_replace('.', '__', $operation) . "($paramStr) {
+ \$params = array($paramArrayStr);
+ return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."');
+ }
+ ";
+ unset($paramStr);
+ unset($paramCommentStr);
+ }
+ }
+ $evalStr = 'class nusoap_proxy_'.$r.' extends nusoap_client {
+ '.$evalStr.'
+}';
+ return $evalStr;
+ }
+
+ /**
+ * dynamically creates proxy class code
+ *
+ * @return string PHP/NuSOAP code for the proxy class
+ * @access public
+ */
+ function getProxyClassCode() {
+ $r = rand();
+ return $this->_getProxyClassCode($r);
+ }
+
+ /**
+ * gets the HTTP body for the current request.
+ *
+ * @param string $soapmsg The SOAP payload
+ * @return string The HTTP body, which includes the SOAP payload
+ * @access private
+ */
+ function getHTTPBody($soapmsg) {
+ return $soapmsg;
+ }
+
+ /**
+ * gets the HTTP content type for the current request.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type for the current request.
+ * @access private
+ */
+ function getHTTPContentType() {
+ return 'text/xml';
+ }
+
+ /**
+ * gets the HTTP content type charset for the current request.
+ * returns false for non-text content types.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type charset for the current request.
+ * @access private
+ */
+ function getHTTPContentTypeCharset() {
+ return $this->soap_defencoding;
+ }
+
+ /*
+ * whether or not parser should decode utf8 element content
+ *
+ * @return always returns true
+ * @access public
+ */
+ function decodeUTF8($bool){
+ $this->decode_utf8 = $bool;
+ return true;
+ }
+
+ /**
+ * adds a new Cookie into $this->cookies array
+ *
+ * @param string $name Cookie Name
+ * @param string $value Cookie Value
+ * @return boolean if cookie-set was successful returns true, else false
+ * @access public
+ */
+ function setCookie($name, $value) {
+ if (strlen($name) == 0) {
+ return false;
+ }
+ $this->cookies[] = array('name' => $name, 'value' => $value);
+ return true;
+ }
+
+ /**
+ * gets all Cookies
+ *
+ * @return array with all internal cookies
+ * @access public
+ */
+ function getCookies() {
+ return $this->cookies;
+ }
+
+ /**
+ * checks all Cookies and delete those which are expired
+ *
+ * @return boolean always return true
+ * @access private
+ */
+ function checkCookies() {
+ if (sizeof($this->cookies) == 0) {
+ return true;
+ }
+ $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies');
+ $curr_cookies = $this->cookies;
+ $this->cookies = array();
+ foreach ($curr_cookies as $cookie) {
+ if (! is_array($cookie)) {
+ $this->debug('Remove cookie that is not an array');
+ continue;
+ }
+ if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
+ if (strtotime($cookie['expires']) > time()) {
+ $this->cookies[] = $cookie;
+ } else {
+ $this->debug('Remove expired cookie ' . $cookie['name']);
+ }
+ } else {
+ $this->cookies[] = $cookie;
+ }
+ }
+ $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array');
+ return true;
+ }
+
+ /**
+ * updates the current cookies with a new set
+ *
+ * @param array $cookies new cookies with which to update current ones
+ * @return boolean always return true
+ * @access private
+ */
+ function UpdateCookies($cookies) {
+ if (sizeof($this->cookies) == 0) {
+ // no existing cookies: take whatever is new
+ if (sizeof($cookies) > 0) {
+ $this->debug('Setting new cookie(s)');
+ $this->cookies = $cookies;
+ }
+ return true;
+ }
+ if (sizeof($cookies) == 0) {
+ // no new cookies: keep what we've got
+ return true;
+ }
+ // merge
+ foreach ($cookies as $newCookie) {
+ if (!is_array($newCookie)) {
+ continue;
+ }
+ if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) {
+ continue;
+ }
+ $newName = $newCookie['name'];
+
+ $found = false;
+ for ($i = 0; $i < count($this->cookies); $i++) {
+ $cookie = $this->cookies[$i];
+ if (!is_array($cookie)) {
+ continue;
+ }
+ if (!isset($cookie['name'])) {
+ continue;
+ }
+ if ($newName != $cookie['name']) {
+ continue;
+ }
+ $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN';
+ $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN';
+ if ($newDomain != $domain) {
+ continue;
+ }
+ $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH';
+ $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH';
+ if ($newPath != $path) {
+ continue;
+ }
+ $this->cookies[$i] = $newCookie;
+ $found = true;
+ $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']);
+ break;
+ }
+ if (! $found) {
+ $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']);
+ $this->cookies[] = $newCookie;
+ }
+ }
+ return true;
+ }
+}
+
+if (!extension_loaded('soap')) {
+ /**
+ * For backwards compatiblity, define soapclient unless the PHP SOAP extension is loaded.
+ */
+ class soapclient extends nusoap_client {
+ }
+}
+?>
--- /dev/null
+<?php
+/*
+$Id: nusoapmime.php,v 1.13 2010/04/26 20:15:08 snichol Exp $
+
+NuSOAP - Web Services Toolkit for PHP
+
+Copyright (c) 2002 NuSphere Corporation
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+The NuSOAP project home is:
+http://sourceforge.net/projects/nusoap/
+
+The primary support for NuSOAP is the mailing list:
+nusoap-general@lists.sourceforge.net
+
+If you have any questions or comments, please email:
+
+Dietrich Ayala
+dietrich@ganx4.com
+http://dietrich.ganx4.com/nusoap
+
+NuSphere Corporation
+http://www.nusphere.com
+
+*/
+
+/*require_once('nusoap.php');*/
+/* PEAR Mail_MIME library */
+require_once('Mail/mimeDecode.php');
+require_once('Mail/mimePart.php');
+
+/**
+* nusoap_client_mime client supporting MIME attachments defined at
+* http://www.w3.org/TR/SOAP-attachments. It depends on the PEAR Mail_MIME library.
+*
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list
+* @version $Id: nusoapmime.php,v 1.13 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_client_mime extends nusoap_client {
+ /**
+ * @var array Each array element in the return is an associative array with keys
+ * data, filename, contenttype, cid
+ * @access private
+ */
+ var $requestAttachments = array();
+ /**
+ * @var array Each array element in the return is an associative array with keys
+ * data, filename, contenttype, cid
+ * @access private
+ */
+ var $responseAttachments;
+ /**
+ * @var string
+ * @access private
+ */
+ var $mimeContentType;
+
+ /**
+ * adds a MIME attachment to the current request.
+ *
+ * If the $data parameter contains an empty string, this method will read
+ * the contents of the file named by the $filename parameter.
+ *
+ * If the $cid parameter is false, this method will generate the cid.
+ *
+ * @param string $data The data of the attachment
+ * @param string $filename The filename of the attachment (default is empty string)
+ * @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream)
+ * @param string $cid The content-id (cid) of the attachment (default is false)
+ * @return string The content-id (cid) of the attachment
+ * @access public
+ */
+ function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) {
+ if (! $cid) {
+ $cid = md5(uniqid(time()));
+ }
+
+ $info['data'] = $data;
+ $info['filename'] = $filename;
+ $info['contenttype'] = $contenttype;
+ $info['cid'] = $cid;
+
+ $this->requestAttachments[] = $info;
+
+ return $cid;
+ }
+
+ /**
+ * clears the MIME attachments for the current request.
+ *
+ * @access public
+ */
+ function clearAttachments() {
+ $this->requestAttachments = array();
+ }
+
+ /**
+ * gets the MIME attachments from the current response.
+ *
+ * Each array element in the return is an associative array with keys
+ * data, filename, contenttype, cid. These keys correspond to the parameters
+ * for addAttachment.
+ *
+ * @return array The attachments.
+ * @access public
+ */
+ function getAttachments() {
+ return $this->responseAttachments;
+ }
+
+ /**
+ * gets the HTTP body for the current request.
+ *
+ * @param string $soapmsg The SOAP payload
+ * @return string The HTTP body, which includes the SOAP payload
+ * @access private
+ */
+ function getHTTPBody($soapmsg) {
+ if (count($this->requestAttachments) > 0) {
+ $params['content_type'] = 'multipart/related; type="text/xml"';
+ $mimeMessage = new Mail_mimePart('', $params);
+ unset($params);
+
+ $params['content_type'] = 'text/xml';
+ $params['encoding'] = '8bit';
+ $params['charset'] = $this->soap_defencoding;
+ $mimeMessage->addSubpart($soapmsg, $params);
+
+ foreach ($this->requestAttachments as $att) {
+ unset($params);
+
+ $params['content_type'] = $att['contenttype'];
+ $params['encoding'] = 'base64';
+ $params['disposition'] = 'attachment';
+ $params['dfilename'] = $att['filename'];
+ $params['cid'] = $att['cid'];
+
+ if ($att['data'] == '' && $att['filename'] <> '') {
+ if ($fd = fopen($att['filename'], 'rb')) {
+ $data = fread($fd, filesize($att['filename']));
+ fclose($fd);
+ } else {
+ $data = '';
+ }
+ $mimeMessage->addSubpart($data, $params);
+ } else {
+ $mimeMessage->addSubpart($att['data'], $params);
+ }
+ }
+
+ $output = $mimeMessage->encode();
+ $mimeHeaders = $output['headers'];
+
+ foreach ($mimeHeaders as $k => $v) {
+ $this->debug("MIME header $k: $v");
+ if (strtolower($k) == 'content-type') {
+ // PHP header() seems to strip leading whitespace starting
+ // the second line, so force everything to one line
+ $this->mimeContentType = str_replace("\r\n", " ", $v);
+ }
+ }
+
+ return $output['body'];
+ }
+
+ return parent::getHTTPBody($soapmsg);
+ }
+
+ /**
+ * gets the HTTP content type for the current request.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type for the current request.
+ * @access private
+ */
+ function getHTTPContentType() {
+ if (count($this->requestAttachments) > 0) {
+ return $this->mimeContentType;
+ }
+ return parent::getHTTPContentType();
+ }
+
+ /**
+ * gets the HTTP content type charset for the current request.
+ * returns false for non-text content types.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type charset for the current request.
+ * @access private
+ */
+ function getHTTPContentTypeCharset() {
+ if (count($this->requestAttachments) > 0) {
+ return false;
+ }
+ return parent::getHTTPContentTypeCharset();
+ }
+
+ /**
+ * processes SOAP message returned from server
+ *
+ * @param array $headers The HTTP headers
+ * @param string $data unprocessed response data from server
+ * @return mixed value of the message, decoded into a PHP type
+ * @access private
+ */
+ function parseResponse($headers, $data) {
+ $this->debug('Entering parseResponse() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']);
+ $this->responseAttachments = array();
+ if (strstr($headers['content-type'], 'multipart/related')) {
+ $this->debug('Decode multipart/related');
+ $input = '';
+ foreach ($headers as $k => $v) {
+ $input .= "$k: $v\r\n";
+ }
+ $params['input'] = $input . "\r\n" . $data;
+ $params['include_bodies'] = true;
+ $params['decode_bodies'] = true;
+ $params['decode_headers'] = true;
+
+ $structure = Mail_mimeDecode::decode($params);
+
+ foreach ($structure->parts as $part) {
+ if (!isset($part->disposition) && (strstr($part->headers['content-type'], 'text/xml'))) {
+ $this->debug('Have root part of type ' . $part->headers['content-type']);
+ $root = $part->body;
+ $return = parent::parseResponse($part->headers, $part->body);
+ } else {
+ $this->debug('Have an attachment of type ' . $part->headers['content-type']);
+ $info['data'] = $part->body;
+ $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : '';
+ $info['contenttype'] = $part->headers['content-type'];
+ $info['cid'] = $part->headers['content-id'];
+ $this->responseAttachments[] = $info;
+ }
+ }
+
+ if (isset($return)) {
+ $this->responseData = $root;
+ return $return;
+ }
+
+ $this->setError('No root part found in multipart/related content');
+ return '';
+ }
+ $this->debug('Not multipart/related');
+ return parent::parseResponse($headers, $data);
+ }
+}
+
+/*
+ * For backwards compatiblity, define soapclientmime unless the PHP SOAP extension is loaded.
+ */
+if (!extension_loaded('soap')) {
+ class soapclientmime extends nusoap_client_mime {
+ }
+}
+
+/**
+* nusoap_server_mime server supporting MIME attachments defined at
+* http://www.w3.org/TR/SOAP-attachments. It depends on the PEAR Mail_MIME library.
+*
+* @author Scott Nichol <snichol@users.sourceforge.net>
+* @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list
+* @version $Id: nusoapmime.php,v 1.13 2010/04/26 20:15:08 snichol Exp $
+* @access public
+*/
+class nusoap_server_mime extends nusoap_server {
+ /**
+ * @var array Each array element in the return is an associative array with keys
+ * data, filename, contenttype, cid
+ * @access private
+ */
+ var $requestAttachments = array();
+ /**
+ * @var array Each array element in the return is an associative array with keys
+ * data, filename, contenttype, cid
+ * @access private
+ */
+ var $responseAttachments;
+ /**
+ * @var string
+ * @access private
+ */
+ var $mimeContentType;
+
+ /**
+ * adds a MIME attachment to the current response.
+ *
+ * If the $data parameter contains an empty string, this method will read
+ * the contents of the file named by the $filename parameter.
+ *
+ * If the $cid parameter is false, this method will generate the cid.
+ *
+ * @param string $data The data of the attachment
+ * @param string $filename The filename of the attachment (default is empty string)
+ * @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream)
+ * @param string $cid The content-id (cid) of the attachment (default is false)
+ * @return string The content-id (cid) of the attachment
+ * @access public
+ */
+ function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) {
+ if (! $cid) {
+ $cid = md5(uniqid(time()));
+ }
+
+ $info['data'] = $data;
+ $info['filename'] = $filename;
+ $info['contenttype'] = $contenttype;
+ $info['cid'] = $cid;
+
+ $this->responseAttachments[] = $info;
+
+ return $cid;
+ }
+
+ /**
+ * clears the MIME attachments for the current response.
+ *
+ * @access public
+ */
+ function clearAttachments() {
+ $this->responseAttachments = array();
+ }
+
+ /**
+ * gets the MIME attachments from the current request.
+ *
+ * Each array element in the return is an associative array with keys
+ * data, filename, contenttype, cid. These keys correspond to the parameters
+ * for addAttachment.
+ *
+ * @return array The attachments.
+ * @access public
+ */
+ function getAttachments() {
+ return $this->requestAttachments;
+ }
+
+ /**
+ * gets the HTTP body for the current response.
+ *
+ * @param string $soapmsg The SOAP payload
+ * @return string The HTTP body, which includes the SOAP payload
+ * @access private
+ */
+ function getHTTPBody($soapmsg) {
+ if (count($this->responseAttachments) > 0) {
+ $params['content_type'] = 'multipart/related; type="text/xml"';
+ $mimeMessage = new Mail_mimePart('', $params);
+ unset($params);
+
+ $params['content_type'] = 'text/xml';
+ $params['encoding'] = '8bit';
+ $params['charset'] = $this->soap_defencoding;
+ $mimeMessage->addSubpart($soapmsg, $params);
+
+ foreach ($this->responseAttachments as $att) {
+ unset($params);
+
+ $params['content_type'] = $att['contenttype'];
+ $params['encoding'] = 'base64';
+ $params['disposition'] = 'attachment';
+ $params['dfilename'] = $att['filename'];
+ $params['cid'] = $att['cid'];
+
+ if ($att['data'] == '' && $att['filename'] <> '') {
+ if ($fd = fopen($att['filename'], 'rb')) {
+ $data = fread($fd, filesize($att['filename']));
+ fclose($fd);
+ } else {
+ $data = '';
+ }
+ $mimeMessage->addSubpart($data, $params);
+ } else {
+ $mimeMessage->addSubpart($att['data'], $params);
+ }
+ }
+
+ $output = $mimeMessage->encode();
+ $mimeHeaders = $output['headers'];
+
+ foreach ($mimeHeaders as $k => $v) {
+ $this->debug("MIME header $k: $v");
+ if (strtolower($k) == 'content-type') {
+ // PHP header() seems to strip leading whitespace starting
+ // the second line, so force everything to one line
+ $this->mimeContentType = str_replace("\r\n", " ", $v);
+ }
+ }
+
+ return $output['body'];
+ }
+
+ return parent::getHTTPBody($soapmsg);
+ }
+
+ /**
+ * gets the HTTP content type for the current response.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type for the current response.
+ * @access private
+ */
+ function getHTTPContentType() {
+ if (count($this->responseAttachments) > 0) {
+ return $this->mimeContentType;
+ }
+ return parent::getHTTPContentType();
+ }
+
+ /**
+ * gets the HTTP content type charset for the current response.
+ * returns false for non-text content types.
+ *
+ * Note: getHTTPBody must be called before this.
+ *
+ * @return string the HTTP content type charset for the current response.
+ * @access private
+ */
+ function getHTTPContentTypeCharset() {
+ if (count($this->responseAttachments) > 0) {
+ return false;
+ }
+ return parent::getHTTPContentTypeCharset();
+ }
+
+ /**
+ * processes SOAP message received from client
+ *
+ * @param array $headers The HTTP headers
+ * @param string $data unprocessed request data from client
+ * @return mixed value of the message, decoded into a PHP type
+ * @access private
+ */
+ function parseRequest($headers, $data) {
+ $this->debug('Entering parseRequest() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']);
+ $this->requestAttachments = array();
+ if (strstr($headers['content-type'], 'multipart/related')) {
+ $this->debug('Decode multipart/related');
+ $input = '';
+ foreach ($headers as $k => $v) {
+ $input .= "$k: $v\r\n";
+ }
+ $params['input'] = $input . "\r\n" . $data;
+ $params['include_bodies'] = true;
+ $params['decode_bodies'] = true;
+ $params['decode_headers'] = true;
+
+ $structure = Mail_mimeDecode::decode($params);
+
+ foreach ($structure->parts as $part) {
+ if (!isset($part->disposition) && (strstr($part->headers['content-type'], 'text/xml'))) {
+ $this->debug('Have root part of type ' . $part->headers['content-type']);
+ $return = parent::parseRequest($part->headers, $part->body);
+ } else {
+ $this->debug('Have an attachment of type ' . $part->headers['content-type']);
+ $info['data'] = $part->body;
+ $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : '';
+ $info['contenttype'] = $part->headers['content-type'];
+ $info['cid'] = $part->headers['content-id'];
+ $this->requestAttachments[] = $info;
+ }
+ }
+
+ if (isset($return)) {
+ return $return;
+ }
+
+ $this->setError('No root part found in multipart/related content');
+ return;
+ }
+ $this->debug('Not multipart/related');
+ return parent::parseRequest($headers, $data);
+ }
+}
+
+/*
+ * For backwards compatiblity
+ */
+class nusoapservermime extends nusoap_server_mime {
+}
+
+?>
--- /dev/null
+<?php
+/*
+ * $Id: client1.php,v 1.3 2007/11/06 14:48:24 snichol Exp $
+ *
+ * Client sample that should get a fault response.
+ *
+ * Service: SOAP endpoint
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+$client = new nusoap_client("http://soap.amazon.com/onca/soap2", false,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+ echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+ exit();
+}
+$client->setUseCurl($useCURL);
+// This is an archaic parameter list
+$params = array(
+ 'manufacturer' => "O'Reilly",
+ 'page' => '1',
+ 'mode' => 'books',
+ 'tag' => 'trachtenberg-20',
+ 'type' => 'lite',
+ 'devtag' => 'Your tag here',
+ 'sort' => '+title'
+);
+$result = $client->call('ManufacturerSearchRequest', $params, 'http://soap.amazon.com', 'http://soap.amazon.com');
+if ($client->fault) {
+ echo '<h2>Fault (Expect - The request contains an invalid SOAP body)</h2><pre>'; print_r($result); echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>'; print_r($result); echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: client2.php,v 1.4 2007/11/06 14:48:24 snichol Exp $
+ *
+ * Client sample.
+ *
+ * Service: SOAP endpoint
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+$client = new nusoap_client("http://soap.amazon.com/onca/soap2", false,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+ echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+ exit();
+}
+$client->setUseCurl($useCURL);
+$client->useHTTPPersistentConnection();
+$param = array(
+ 'manufacturer' => "O'Reilly",
+ 'page' => '1',
+ 'mode' => 'books',
+ 'tag' => 'trachtenberg-20',
+ 'type' => 'lite',
+ 'devtag' => 'Your tag here'
+);
+$params = array('ManufacturerSearchRequest' =>
+ new soapval('ManufacturerSearchRequest',
+ 'ManufacturerRequest',
+ $param,
+ false,
+ 'http://soap.amazon.com')
+ );
+$result = $client->call('ManufacturerSearchRequest', $params, 'http://soap.amazon.com', 'http://soap.amazon.com');
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>'; print_r($result); echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>'; print_r($result); echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: client3.php,v 1.4 2007/11/06 14:48:24 snichol Exp $
+ *
+ * Client sample.
+ *
+ * Service: SOAP endpoint
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+$client = new nusoap_client("http://api.google.com/search/beta2", false,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+ echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+ exit();
+}
+$client->setUseCurl($useCURL);
+$client->soap_defencoding = 'UTF-8';
+
+//echo 'You must set your own Google key in the source code to run this client!'; exit();
+$params = array(
+ 'Googlekey'=>'Your Google key',
+ 'queryStr'=>'robotics',
+ 'startFrom'=>0,
+ 'maxResults'=>10,
+ 'filter'=>true,
+ 'restrict'=>'',
+ 'adultContent'=>true,
+ 'language'=>'',
+ 'iencoding'=>'',
+ 'oendcoding'=>''
+);
+$result = $client->call("doGoogleSearch", $params, "urn:GoogleSearch", "urn:GoogleSearch");
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>'; print_r($result); echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>'; print_r($result); echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: getfile1client.php,v 1.1 2005/05/18 14:38:53 snichol Exp $
+ *
+ * Get file client sample.
+ *
+ * Service: SOAP endpoint
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$client = new soapclient('http://www.scottnichol.com/samples/getfile1.php?wsdl', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$result = $client->call('getFile', array('filename' => 'getfile1.php'));
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>'; print_r($result); echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>' . htmlspecialchars($result, ENT_QUOTES) . '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: getfile2client.php,v 1.1 2005/05/18 14:38:53 snichol Exp $
+ *
+ * Get file client sample.
+ *
+ * Service: SOAP endpoint
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$client = new soapclient('http://www.scottnichol.com/samples/getfile2.php?wsdl', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$result = $client->call('getFile', array('filename' => 'getfile2.php'));
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>'; print_r($result); echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>' . htmlspecialchars($result, ENT_QUOTES) . '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<html>
+<!--
+ -- $Id: index.html,v 1.19 2010/04/26 15:31:48 snichol Exp $
+ -->
+<head>
+<title>NuSOAP Samples</title>
+<script type="text/javascript">
+function go(url) {
+ document.linkform.action = url;
+ document.linkform.submit();
+}
+</script>
+</head>
+<body>
+<h2>NuSOAP Samples</h2>
+<p>
+These links allow you to launch sample clients. <b><i>As of 26 April 2010, most of the links to commercial services no longer work.</i></b>
+</p>
+<form name="linkform" method="POST" action="javascript:void();">
+<a href="javascript:go('client1.php')">Amazon endpoint (Fault expected)</a><br>
+<a href="javascript:go('client2.php')">Amazon endpoint</a><br>
+<a href="javascript:go('client3.php')">Google endpoint (you must have a key)</a><br>
+<a href="javascript:go('mimeclient.php')">MIME Attachment</a><br>
+<a href="javascript:go('sslclient.php')">SSL endpoint</a><br>
+<a href="javascript:go('wsdlclient1.php')">Stock quote WSDL</a><br>
+<a href="javascript:go('wsdlclient2.php')">Amazon WSDL</a><br>
+<a href="javascript:go('wsdlclient3.php?method=function')">Hello WSDL (PHP function)</a><br>
+<a href="javascript:go('wsdlclient3.php?method=instance')">Hello WSDL (PHP instance method)</a><br>
+<a href="javascript:go('wsdlclient3.php?method=class')">Hello WSDL (PHP class method)</a><br>
+<a href="javascript:go('wsdlclient3b.php')">Hello WSDL with pre-formed parameter XML</a><br>
+<a href="javascript:go('wsdlclient3c.php')">Hello WSDL (rpc/literal version)</a><br>
+<a href="javascript:go('wsdlclient4.php')">Interop WSDL</a><br>
+<a href="javascript:go('wsdlclient5.php')">Price quote WSDL (uses wsdlcache)</a><br>
+<a href="javascript:go('wsdlclient6.php')">Google WSDL (you must have WSDL file local)</a><br>
+<a href="javascript:go('wsdlclient7.php')">MapPoint WSDL #1 (you must have a username/password)</a><br>
+<a href="javascript:go('wsdlclient8.php')">MapPoint WSDL #2 (you must have a username/password)</a><br>
+<a href="javascript:go('wsdlclient9.php')">MapPoint WSDL #3 (you must have a username/password)</a><br>
+<a href="javascript:go('wsdlclient10.php')">Country list WSDL</a><br>
+<a href="javascript:go('wsdlclient11.php')">Hello WSDL (document/literal version)</a><br>
+<a href="javascript:go('wsdlclient12.php?method=ItemLookup')">Amazon E-Commerce Service (ItemLookup by node)</a><br>
+<a href="javascript:go('wsdlclient12.php?method=ItemSearch')">Amazon E-Commerce Service (ItemSearch by node)</a><br>
+<a href="javascript:go('wsdlclient12.php?method=ItemSearch2')">Amazon E-Commerce Service (ItemSearch by keyword)</a><br>
+<a href="javascript:go('wsdlclient12.php?method=ListLookup')">Amazon E-Commerce Service (ListLookup)</a><br>
+<a href="javascript:go('wsdlclient12.php?method=ListSearch')">Amazon E-Commerce Service (ListSearch)</a><br>
+<a href="javascript:go('wsdlclient12.php?method=CartCreate')">Amazon E-Commerce Service (CartCreate)</a><br>
+<a href="javascript:go('wsdlclient13.php')">Maintain a Session</a><br>
+<a href="javascript:go('wsdlclient14.php')">Via Michelin</a><br>
+<a href="javascript:go('wsdlclient15.php')">UTF-8 Character Encoding</a><br>
+<a href="javascript:go('getfile1client.php')">Get a file #1 (uses base64Binary)</a><br>
+<a href="javascript:go('getfile2client.php')">Get a file #2 (uses base64Binary; service uses external WSDL file)</a><br>
+<br>
+<table border="0">
+<tr><td>Use cURL?</td><td><input type="checkbox" name="usecurl" value="1"></td></tr>
+</table>
+<p>
+If you access the Internet through a proxy, provide the proxy
+information below.
+</p>
+<table border="0">
+<tr><td>Proxy Host:</td><td><input type="text" name="proxyhost" value="" size="50" maxlength="256"></td></tr>
+<tr><td>Proxy Port:</td><td><input type="text" name="proxyport" value="" size="5" maxlength="5"></td></tr>
+<tr><td>Proxy Username:</td><td><input type="text" name="proxyusername" value="" size="50" maxlength="256"></td></tr>
+<tr><td>Proxy Password:</td><td><input type="password" name="proxypassword" value="" size="50" maxlength="256"></td></tr>
+</table>
+</form>
+</body>
+</html>
--- /dev/null
+<?php
+/*
+ * $Id: mimeclient.php,v 1.6 2007/04/16 22:08:17 snichol Exp $
+ *
+ * MIME client sample.
+ *
+ * Service: SOAP endpoint
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+require_once('../lib/nusoapmime.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+$client = new nusoap_client_mime('http://www.scottnichol.com/samples/mimetest.php', false,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$client->setUseCurl($useCURL);
+$client->setHTTPEncoding('deflate, gzip');
+$cid = $client->addAttachment('', 'mimeclient.php');
+$result = $client->call('hello', array('name' => 'Scott'));
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>'; print_r($result); echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>'; print_r($result); echo '</pre>';
+ echo '<h2>Attachments</h2><pre>';
+ $attachments = $client->getAttachments();
+ foreach ($attachments as $a) {
+ echo 'Filename: ' . $a['filename'] . "\r\n";
+ echo 'Content-Type: ' . $a['contenttype'] . "\r\n";
+ echo 'cid: ' . htmlspecialchars($a['cid'], ENT_QUOTES) . "\r\n";
+ echo htmlspecialchars($a['data'], ENT_QUOTES);
+ echo "\r\n";
+ }
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>ResponseData</h2><pre>' . htmlspecialchars($client->responseData, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: sslclient.php,v 1.1 2004/01/09 03:23:42 snichol Exp $
+ *
+ * SSL client sample.
+ *
+ * Service: SOAP endpoint
+ * Payload: rpc/encoded
+ * Transport: https
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$client = new soapclient('https://arcweb.esri.com/services/v2/AddressFinder', false,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$result = $client->call('getVersion', array(), 'http://arcweb.esri.com/v2', 'getVersion');
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>'; print_r($result); echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>'; print_r($result); echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient1.php,v 1.3 2007/11/06 14:48:48 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: document/literal
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$client = new nusoap_client('http://www.xignite.com/xquotes.asmx?WSDL', 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+// Doc/lit parameters get wrapped
+$param = array('Symbol' => 'IBM');
+$result = $client->call('GetQuickQuotes', array('parameters' => $param), '', '', false, true);
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient10.php,v 1.2 2007/04/13 14:22:09 snichol Exp $
+ *
+ * WSDL client sample.
+ * Demonstrates de-serialization of a document/literal array (added nusoap.php 1.73).
+ *
+ * Service: WSDL
+ * Payload: document/literal
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+$client = new soapclient('http://www.abundanttech.com/WebServices/Population/population.asmx?WSDL', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$client->setUseCurl($useCURL);
+$result = $client->call('getCountries', array(), '', '', false, true);
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient11.php,v 1.2 2007/04/13 16:52:32 snichol Exp $
+ *
+ * WSDL client sample.
+ * Exercises a document/literal NuSOAP service (added nusoap.php 1.73).
+ * Does not explicitly wrap parameters.
+ *
+ * Service: WSDL
+ * Payload: document/literal
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+$client = new soapclient('http://www.scottnichol.com/samples/hellowsdl3.wsdl', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$client->setUseCurl($useCURL);
+$person = array('firstname' => 'Willi', 'age' => 22, 'gender' => 'male');
+$name = array('name' => $person);
+$result = $client->call('hello', $name);
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2>';
+echo '<pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2>';
+echo '<pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2>';
+echo '<pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient12.php,v 1.4 2007/11/06 14:50:07 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: document/literal
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+require_once('../lib/class.wsdlcache.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+
+$method = isset($_GET['method']) ? $_GET['method'] : 'ItemSearch';
+
+$SubscriptionId = 'Your AWS subscription id';
+
+$wsdlurl = 'http://webservices.amazon.com/AWSECommerceService/US/AWSECommerceService.wsdl';
+$cache = new wsdlcache('.', 120);
+$wsdl = $cache->get($wsdlurl);
+if (is_null($wsdl)) {
+ $wsdl = new wsdl($wsdlurl,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+ $cache->put($wsdl);
+} else {
+ $wsdl->debug_str = '';
+ $wsdl->debug('Retrieved from cache');
+}
+$client = new nusoap_client($wsdl, true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+
+$client->soap_defencoding = 'UTF-8';
+
+function GetCartCreateParams() {
+ global $SubscriptionId;
+
+ // create items to be added to the cart
+ $item = array ();
+ $item[0] = array( "ASIN" => "0596004206",
+ "Quantity" => "1"
+ );
+ $item[1] = array( "ASIN" => "0596003277",
+ "Quantity" => "2"
+ );
+
+ // pack it to <Item> array
+ $items = array("Item" => $item);
+ // Construct request parameters
+ $request = array("Items" => $items, "ResponseGroup" => "CartSimilarities");
+
+ // Construct all parameters
+ $cartCreate = array( "SubscriptionId" => $SubscriptionId,
+ "Request" => $request
+ );
+
+ return $cartCreate;
+}
+
+function GetItemLookupParams() {
+ global $SubscriptionId;
+
+ $itemLookupRequest[] = array(
+ 'ItemId' => 'B0002IQML6',
+ 'IdType' => 'ASIN',
+ 'Condition' => 'All',
+ 'ResponseGroup' => 'Large'
+ );
+
+ $itemLookupRequest[] = array(
+ 'ItemId' => '0486411214',
+ 'IdType' => 'ASIN',
+ 'Condition' => 'New',
+ 'ResponseGroup' => 'Small'
+ );
+
+ $itemLookup = array(
+ 'SubscriptionId' => $SubscriptionId,
+ // 'AssociateTag' => '',
+ 'Request' => $itemLookupRequest,
+ );
+
+ return $itemLookup;
+}
+
+function GetItemSearchParams() {
+ global $SubscriptionId;
+
+ $itemSearchRequest = array(
+ 'BrowseNode' => '53',
+ 'ItemPage' => 1,
+ // 'ResponseGroup' => array('Request', 'Small'),
+ 'SearchIndex' => 'Books',
+ 'Sort' => 'salesrank'
+ );
+
+ $itemSearch = array(
+ 'SubscriptionId' => $SubscriptionId,
+ // 'AssociateTag' => '',
+ // 'Validate' => '',
+ // 'XMLEscaping' => '',
+ // 'Shared' => $itemSearchRequest,
+ 'Request' => array($itemSearchRequest)
+ );
+
+ return $itemSearch;
+}
+
+function GetItemSearchParams2() {
+ global $SubscriptionId;
+
+ $request = array(
+ "Keywords" => "postal stamps",
+ "SearchIndex" => "Books"
+ );
+
+ $itemSearch = array(
+ 'SubscriptionId' => $SubscriptionId,
+ 'Request' => $request
+ );
+
+ return $itemSearch;
+}
+
+function GetListLookupParams() {
+ global $SubscriptionId;
+
+ $listLookupRequest[] = array(
+ 'ListId' => '1L0ZL7Y9FL4U0',
+ 'ListType' => 'WishList',
+ 'ProductPage' => 1,
+ 'ResponseGroup' => 'ListFull',
+ 'Sort' => 'LastUpdated'
+ );
+
+ $listLookupRequest[] = array(
+ 'ListId' => '1L0ZL7Y9FL4U0',
+ 'ListType' => 'WishList',
+ 'ProductPage' => 2,
+ 'ResponseGroup' => 'ListFull',
+ 'Sort' => 'LastUpdated'
+ );
+/*
+// two lookup maximum
+ $listLookupRequest[] = array(
+ 'ListId' => '1L0ZL7Y9FL4U0',
+ 'ListType' => 'WishList',
+ 'ProductPage' => 3,
+ 'ResponseGroup' => 'ListFull',
+ 'Sort' => 'LastUpdated'
+ );
+*/
+ $listLookup = array(
+ 'SubscriptionId' => $SubscriptionId,
+ // 'AssociateTag' => '',
+ 'Request' => $listLookupRequest,
+ );
+
+ return $listLookup;
+}
+
+function GetListSearchParams() {
+ global $SubscriptionId;
+
+ $listSearchRequest[] = array(
+ 'FirstName' => 'Scott',
+ 'LastName' => 'Nichol',
+ 'ListType' => 'WishList'
+ );
+
+ $listSearch = array(
+ 'SubscriptionId' => $SubscriptionId,
+ // 'AssociateTag' => '',
+ 'Request' => $listSearchRequest,
+ );
+
+ return $listSearch;
+}
+
+if ($method == 'ItemLookup') {
+ $result = $client->call('ItemLookup', array('body' => GetItemLookupParams()));
+} elseif ($method == 'ItemSearch') {
+ $result = $client->call('ItemSearch', array('body' => GetItemSearchParams()));
+} elseif ($method == 'ItemSearch2') {
+ $result = $client->call('ItemSearch', array('body' => GetItemSearchParams2()));
+} elseif ($method == 'ListLookup') {
+ $result = $client->call('ListLookup', array('body' => GetListLookupParams()));
+} elseif ($method == 'ListSearch') {
+ $result = $client->call('ListSearch', array('body' => GetListSearchParams()));
+} elseif ($method == 'CartCreate') {
+ $result = $client->call('CartCreate', array('body' => GetCartCreateParams()));
+} else {
+ echo "Unsupported method $method";
+ exit;
+}
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient13.php,v 1.2 2007/11/06 14:50:42 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: rpc/literal
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+echo '<h2>Constructor</h2>';
+$client = new nusoap_client('http://www.scottnichol.com/samples/session.php?wsdl', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+$client->clearDebug();
+// A persistent connection is *optional*, *not* necessary
+$client->useHTTPPersistentConnection();
+echo '<h2>GetSessionID</h2>';
+$result = $client->call('GetSessionID', array());
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+$client->clearDebug();
+echo '<h2>SetSession</h2>';
+$result = $client->call('SetSession', array('name' => 'testvalue', 'value' => 'it works'));
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+$client->clearDebug();
+echo '<h2>GetSession</h2>';
+$result = $client->call('GetSession', array('name' => 'testvalue'));
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient14.php,v 1.2 2007/11/06 14:50:08 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+require_once('../lib/class.wsdlcache.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+
+//echo 'You must set your own Via Michelin login and password in the source code to run this client!'; exit();
+$login = 'WSDEMO_01145';
+$password = 'DckHXMMHj';
+
+$wsdlurl = 'http://www.viamichelin.com/ws/services/Geocoding?wsdl';
+$cache = new wsdlcache('.', 120);
+$wsdl = $cache->get($wsdlurl);
+if (is_null($wsdl)) {
+ $wsdl = new wsdl($wsdlurl,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword,
+ 0, 30, null, $useCURL);
+ $err = $wsdl->getError();
+ if ($err) {
+ echo '<h2>WSDL Constructor error</h2><pre>' . $err . '</pre>';
+ echo '<h2>Debug</h2><pre>' . htmlspecialchars($wsdl->getDebug(), ENT_QUOTES) . '</pre>';
+ exit();
+ }
+ $cache->put($wsdl);
+} else {
+ $wsdl->debug_str = '';
+ $wsdl->debug('Retrieved from cache');
+}
+$client = new nusoap_client($wsdl, 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+ echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+ exit();
+}
+
+$inputAddresses[] = array(
+ 'address' => '45 Liberty Blvd.',
+ 'cityName' => 'Malvern',
+ 'countryCode' => 'USA',
+ 'postalCode' => '19355',
+ 'stateName' => 'PA'
+);
+$geocodingrequest = array('addressesList' => $inputAddresses);
+$params = array('request' => $geocodingrequest, 'check' => "$login|$password");
+$result = $client->call('getLocationsList', $params);
+
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault (Expect - AUTHENTIFICATION)</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient15.php,v 1.1 2008/02/12 00:13:50 snichol Exp $
+ *
+ * UTF-8 client sample that sends and receives data with characters UTF-8 encoded.
+ *
+ * Service: WSDL
+ * Payload: document/literal
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+$client = new nusoap_client('http://www.scottnichol.com/samples/helloutf8.php?wsdl', 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+ echo '<h2>Debug</h2>';
+ echo '<pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+ exit();
+}
+$client->setUseCurl($useCURL);
+$client->soap_defencoding = 'UTF-8';
+$client->decode_utf8 = false;
+$utf8string = array('stuff' => "\xc2\xa9\xc2\xae\xc2\xbc\xc2\xbd\xc2\xbe");
+$result = $client->call('echoback', $utf8string);
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ $err = $client->getError();
+ if ($err) {
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ echo '<h2>Result</h2><pre>';
+ // Decode the result: it so happens we sent Latin-1 characters
+ if (isset($result['return'])) {
+ $result1 = utf8_decode($result['return']);
+ } elseif (!is_array($result)) {
+ $result1 = utf8_decode($result);
+ } else {
+ $result1 = $result;
+ }
+ print_r($result1);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2>';
+echo '<pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2>';
+echo '<pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2>';
+echo '<pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient2.php,v 1.3 2007/11/06 14:48:49 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL proxy
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+$client = new nusoap_client("http://soap.amazon.com/schemas2/AmazonWebServices.wsdl", 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+ exit();
+}
+$client->setUseCurl($useCURL);
+$proxy = $client->getProxy();
+$param = array(
+ 'browse_node' => 18,
+ 'page' => 1,
+ 'mode' => 'books',
+ 'tag' =>'melonfire-20',
+ 'type' => 'lite',
+ 'devtag' => 'Your dev tag'
+);
+$result = $proxy->BrowseNodeSearchRequest($param);
+// Check for a fault
+if ($proxy->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $proxy->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($proxy->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($proxy->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Client Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+echo '<h2>Proxy Debug</h2><pre>' . htmlspecialchars($proxy->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient3.php,v 1.4 2007/11/06 14:48:49 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$client = new nusoap_client('http://www.scottnichol.com/samples/hellowsdl2.php?wsdl&debug=1', 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$person = array('firstname' => 'Willi', 'age' => 22, 'gender' => 'male');
+$method = isset($_GET['method']) ? $_GET['method'] : 'function';
+if ($method == 'function') {
+ $call = 'hello';
+} elseif ($method == 'instance') {
+ $call = 'hellowsdl2.hello';
+} elseif ($method == 'class') {
+ $call = 'hellowsdl2..hello';
+} else {
+ $call = 'hello';
+}
+$result = $client->call($call, array('person' => $person));
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient3b.php,v 1.1 2004/06/15 15:38:29 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: rpc/encoded (params as an XML string; cf. wsdlclient3.php)
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$client = new soapclient('http://www.scottnichol.com/samples/hellowsdl2.php?wsdl', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$params = '<person xsi:type="tns:Person"><firstname xsi:type="xsd:string">Willi</firstname><age xsi:type="xsd:int">22</age><gender xsi:type="xsd:string">male</gender></person>';
+$result = $client->call('hello', $params);
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient3c.php,v 1.2 2004/10/01 19:57:20 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: rpc/literal
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$client = new soapclient('http://www.scottnichol.com/samples/hellowsdl4.php?wsdl&debug=1', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$person = array('firstname' => 'Willi', 'age' => 22, 'gender' => 'male');
+$result = $client->call('hello', array('person' => $person));
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient4.php,v 1.6 2005/05/12 21:42:06 snichol Exp $
+ *
+ * WSDL client sample, based on soap builders round 2 interop.
+ *
+ * Service: WSDL
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+/*
+ * Grab post vars, if present
+ */
+$method = isset($_POST['method']) ? $_POST['method'] : '';
+$null = isset($_POST['null']) ? $_POST['null'] : '';
+$empty = isset($_POST['empty']) ? $_POST['empty'] : '';
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+/*
+ * When no method has been specified, give the user a choice
+ */
+if ($method == '') {
+ echo '<form name="MethodForm" method="POST">';
+ echo '<input type="hidden" name="proxyhost" value="' . $proxyhost .'">';
+ echo '<input type="hidden" name="proxyport" value="' . $proxyport .'">';
+ echo '<input type="hidden" name="proxyusername" value="' . $proxyusername .'">';
+ echo '<input type="hidden" name="proxypassword" value="' . $proxypassword .'">';
+ echo 'Method: <select name="method">';
+ echo '<option>echoString</option>';
+ echo '<option>echoStringArray</option>';
+ echo '<option>echoInteger</option>';
+ echo '<option>echoIntegerArray</option>';
+ echo '<option>echoFloat</option>';
+ echo '<option>echoFloatArray</option>';
+ echo '<option>echoStruct</option>';
+ echo '<option>echoStructArray</option>';
+ echo '<option>echoVoid</option>';
+ echo '<option>echoBoolean</option>';
+ echo '<option>echoBase64</option>';
+ echo '</select><br><br>';
+ echo 'Null parameter? <input type="checkbox" name="null" value="1"><br>';
+ echo 'Empty array? <input type="checkbox" name="empty" value="1"><br><br>';
+ echo '<input type="submit" value=" Execute ">';
+ echo '</form>';
+ exit();
+}
+/*
+ * Execute the specified method
+ */
+if ($method == 'echoString') {
+ if ($null != '1') {
+ $params = array('inputString' => 'If you cannot echo a string, you probably cannot do much');
+ } else {
+ $params = array('inputString' => null);
+ }
+} elseif ($method == 'echoStringArray') {
+ if ($null != '1') {
+ if ($empty != '1') {
+ $params = array('inputStringArray' => array('String 1', 'String 2', 'String Three'));
+ } else {
+ $params = array('inputStringArray' => array());
+ }
+ } else {
+ $params = array('inputStringArray' => null);
+ }
+} elseif ($method == 'echoInteger') {
+ if ($null != '1') {
+ $params = array('inputInteger' => 329);
+ } else {
+ $params = array('inputInteger' => null);
+ }
+} elseif ($method == 'echoIntegerArray') {
+ if ($null != '1') {
+ if ($empty != '1') {
+ $params = array('inputIntegerArray' => array(451, 43, -392220011, 1, 1, 2, 3, 5, 8, 13, 21));
+ } else {
+ $params = array('inputIntegerArray' => array());
+ }
+ } else {
+ $params = array('inputIntegerArray' => null);
+ }
+} elseif ($method == 'echoFloat') {
+ if ($null != '1') {
+ $params = array('inputFloat' => 3.14159265);
+ } else {
+ $params = array('inputFloat' => null);
+ }
+} elseif ($method == 'echoFloatArray') {
+ if ($null != '1') {
+ if ($empty != '1') {
+ $params = array('inputFloatArray' => array(1.1, 2.2, 3.3, 1/4, -1/9));
+ } else {
+ $params = array('inputFloatArray' => array());
+ }
+ } else {
+ $params = array('inputFloatArray' => null);
+ }
+} elseif ($method == 'echoStruct') {
+ if ($null != '1') {
+ $struct = array('varString' => 'who', 'varInt' => 2, 'varFloat' => 3.14159);
+ $params = array('inputStruct' => $struct);
+ } else {
+ $params = array('inputStruct' => null);
+ }
+} elseif ($method == 'echoStructArray') {
+ if ($null != '1') {
+ if ($empty != '1') {
+ $structs[] = array('varString' => 'who', 'varInt' => 2, 'varFloat' => 3.14159);
+ $structs[] = array('varString' => 'when', 'varInt' => 4, 'varFloat' => 99.9876);
+ $params = array('inputStructArray' => $structs);
+ } else {
+ $params = array('inputStructArray' => array());
+ }
+ } else {
+ $params = array('inputStructArray' => null);
+ }
+} elseif ($method == 'echoVoid') {
+ $params = array();
+} elseif ($method == 'echoBoolean') {
+ if ($null != '1') {
+ $params = array('inputBoolean' => false);
+ } else {
+ $params = array('inputBoolean' => null);
+ }
+} elseif ($method == 'echoBase64') {
+ if ($null != '1') {
+ $params = array('inputBase64' => base64_encode('You must encode the data you send; NuSOAP will automatically decode the data it receives'));
+ } else {
+ $params = array('inputBase64' => null);
+ }
+} else {
+ echo 'Sorry, I do not know about method ' . $method;
+ exit();
+}
+$client = new soapclient('http://www.scottnichol.com/samples/round2_base_server.php?wsdl&debug=1', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$client->useHTTPPersistentConnection();
+echo '<h2>Execute ' . $method . '</h2>';
+$result = $client->call($method, $params);
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r((!is_bool($result)) ? $result : ($result ? 'true' : 'false'));
+ echo '</pre>';
+ // And execute again to test persistent connection
+ echo '<h2>Execute ' . $method . ' again to test persistent connection (see debug)</h2>';
+ $client->debug("*** execute again to test persistent connection ***");
+ $result = $client->call($method, $params);
+ // And again...
+ $client->debug("*** execute again ... ***");
+ $result = $client->call($method, $params);
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient5.php,v 1.4 2007/11/06 14:49:10 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+require_once('../lib/class.wsdlcache.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+
+$cache = new wsdlcache('.', 60);
+$wsdl = $cache->get('http://www.xmethods.net/sd/2001/BNQuoteService.wsdl');
+if (is_null($wsdl)) {
+ $wsdl = new wsdl('http://www.xmethods.net/sd/2001/BNQuoteService.wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword,
+ 0, 30, null, $useCURL);
+ $err = $wsdl->getError();
+ if ($err) {
+ echo '<h2>WSDL Constructor error (Expect - 404 Not Found)</h2><pre>' . $err . '</pre>';
+ echo '<h2>Debug</h2><pre>' . htmlspecialchars($wsdl->getDebug(), ENT_QUOTES) . '</pre>';
+ exit();
+ }
+ $cache->put($wsdl);
+} else {
+ $wsdl->clearDebug();
+ $wsdl->debug('Retrieved from cache');
+}
+$client = new nusoap_client($wsdl, 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+ exit();
+}
+$client->setUseCurl($useCURL);
+$params = array('isbn' => '0060188782');
+$result = $client->call('getPrice', $params);
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Cache Debug</h2><pre>' . htmlspecialchars($cache->getDebug(), ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient6.php,v 1.1 2004/01/26 07:15:20 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: rpc/encoded
+ * Transport: http
+ * Authentication: none
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+echo 'You must change the source code to specify the location of the WSDL!'; exit();
+$client = new soapclient('file://f:/googleapi/GoogleSearch.wsdl', true,
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$client->soap_defencoding = 'UTF-8';
+
+echo 'You must set your own Google key in the source code to run this client!'; exit();
+$key = 'set your own Google key';
+$q = '"Lies and the Lying"';
+$start = 1;
+$maxResults = 10;
+$filter = false;
+$restrict = '';
+$safeSearch = false;
+$lr = '';
+$ie = '';
+$oe = '';
+
+$params = array(
+ 'key' => $key, 'q' => $q, 'start' => $start, 'maxResults' => $maxResults,
+ 'filter' => $filter, 'restrict' => $restrict, 'safeSearch' => $safeSearch, 'lr' => $lr,
+ 'ie' => $ie, 'oe' => $oe
+ );
+
+$result = $client->call('doGoogleSearch', $params);
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient7.php,v 1.2 2007/11/06 14:49:10 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: document/literal
+ * Transport: http
+ * Authentication: digest
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+$useCURL = isset($_POST['usecurl']) ? $_POST['usecurl'] : '0';
+echo 'You must set your username and password in the source';
+exit();
+$client = new nusoap_client("http://staging.mappoint.net/standard-30/mappoint.wsdl", 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$client->setUseCurl($useCURL);
+$client->loadWSDL();
+$client->setCredentials($username, $password, 'digest');
+$result = $client->call('GetVersionInfo', array());
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient8.php,v 1.2 2007/11/06 14:49:10 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: document/literal
+ * Transport: http
+ * Authentication: digest
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+echo 'You must set your username and password in the source';
+exit();
+$client = new nusoap_client("http://staging.mappoint.net/standard-30/mappoint.wsdl", 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$client->setCredentials($username, $password, 'digest');
+$address = array(
+ 'AddressLine' => '563 Park Avenue',
+ 'PrimaryCity' => 'New York',
+ 'SecondaryCity' => 'Brooklyn',
+ 'Subdivision' => '',
+ 'PostalCode' => '',
+ 'CountryRegion' => 'US',
+ 'FormattedAddress' => ''
+);
+$findRange = array(
+ 'StartIndex' => 0,
+ 'Count' => 10
+);
+$findResultMask = 'AddressFlag';
+$findOptions = array(
+ 'Range' => $findRange,
+ 'SearchContext' => 1,
+ 'ResultMask' => $findResultMask,
+ 'ThresholdScore' => 0.85
+);
+$findAddressSpecification = array(
+ 'DataSourceName' => 'MapPoint.NA',
+ 'InputAddress' => $address,
+ 'Options' => $findOptions
+);
+$findAddress = array('specification' => $findAddressSpecification);
+$result = $client->call('FindAddress', array('parameters' => $findAddress));
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+/*
+ * $Id: wsdlclient9.php,v 1.2 2007/11/06 14:50:06 snichol Exp $
+ *
+ * WSDL client sample.
+ *
+ * Service: WSDL
+ * Payload: document/literal
+ * Transport: http
+ * Authentication: digest
+ */
+require_once('../lib/nusoap.php');
+$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
+$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
+$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
+$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
+echo 'You must set your username and password in the source';
+exit();
+$client = new nusoap_client("http://staging.mappoint.net/standard-30/mappoint.wsdl", 'wsdl',
+ $proxyhost, $proxyport, $proxyusername, $proxypassword);
+$err = $client->getError();
+if ($err) {
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+}
+$client->setCredentials($username, $password, 'digest');
+$client->useHTTPPersistentConnection();
+$view = array(
+ 'Height' => 200,
+ 'Width' => 300,
+ 'CenterPoint' => array(
+ 'Latitude' => 40,
+ 'Longitude' => -120
+ )
+);
+$myViews[] = new soapval('MapView', 'ViewByHeightWidth', $view, false, 'http://s.mappoint.net/mappoint-30/');
+$mapSpec = array(
+ 'DataSourceName' => "MapPoint.NA",
+ 'Views' => array('MapView' => $myViews)
+);
+$map = array('specification' => $mapSpec);
+$result = $client->call('GetMap', array('parameters' => $map));
+// Check for a fault
+if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+} else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ } else {
+ // Display the result
+ echo '<h2>Result</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ }
+}
+echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
+?>
--- /dev/null
+<?php
+ phpinfo();
+ ?>
--- /dev/null
+<?php
+// Pull in the NuSOAP code
+require_once('nusoap/lib/nusoap.php');
+// Create the client instance
+
+function create_soap_client() {
+ $client = new soapclient(
+ 'http://siap.ufcspa.edu.br/siap_ws.php?wsdl', true);
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
+ // At this point, you know the call that follows will fail
+ }
+ return $client;
+}
+
+function call_soap_method($client, $method, $parameters) {
+ $result = $client->call($method, $parameters);
+ // Check for a fault
+ if ($client->fault) {
+ echo '<h2>Fault</h2><pre>';
+ print_r($result);
+ echo '</pre>';
+ $result = NULL;
+ } else {
+ // Check for errors
+ $err = $client->getError();
+ if ($err) {
+ // Display the error
+ echo '<h2>Error</h2><pre>' . $err . '</pre>';
+ $result = NULL;
+ }
+ }
+ return $result;
+}
+
+function print_wordlist($wordlist){
+ foreach($wordlist as $word){
+ echo '<p>'.$word['id'].' => '.$word['nome'].'</p>';
+ }
+}
+
+
+header('Content-type: text/html; charset=ISO-8859-1');
+
+$client = create_soap_client();
+
+$search_types = call_soap_method($client, 'get_search_types', array());
+if ($search_types) {
+ echo '<h2>Tipos de busca para Imagem</h2><pre>';
+ print_wordlist($search_types);
+ echo '</pre>';
+}
+
+foreach ($search_types as &$search_type) {
+ $result = call_soap_method($client, 'get_search_type_keywords', array('search_type' => $search_type['id']));
+ if ($result) {
+ echo '<h2>Palavras-chave para '.$search_type['nome'].':</h2><pre>';
+ print_wordlist($result);
+ echo '</pre>';
+ }
+}
+
+
+$search_results = call_soap_method($client, 'search', array('search_request' => array(
+ 'palavra'=>'abscesso', 'sistema'=>8, 'procedencia'=>15, 'patologia'=>'')));
+
+if ($search_results) {
+ echo '<h2>Resultados da busca para "abscesso" no sistema nervoso:</h2><pre>';
+ echo 'Mostrando ' .sizeof($search_results).' resultados. <br><br>';
+ foreach($search_results as &$result){
+ echo 'Nome: '.$result['nome'].'<br>';
+ echo 'Sistema: '.$result['sistema'].'<br>';
+ echo 'Procedencia: '.$result['procedencia'].'<br>';
+ echo 'Patologia: '.$result['patologia'].'<br>';
+ echo 'URL: '.$result['url'].'<br>';
+ echo '<br>';
+
+ }
+ echo '</pre>';
+}
+
+
+// Display the request and response
+echo '<h2>Request</h2>';
+echo '<pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
+echo '<h2>Response</h2>';
+echo '<pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
+
+?>
--- /dev/null
+<?php
+// Pull in the NuSOAP code
+require_once('nusoap/lib/nusoap.php');
+require("siap_ws_utils.php");
+
+// Create the server instance
+$server = new soap_server();
+// Initialize WSDL support
+$server->configureWSDL('siapwsdl', 'urn:siapwsdl');
+
+
+// Register the data structures used by the service
+$server->wsdl->addComplexType(
+ 'SearchRequest',
+ 'complexType',
+ 'struct',
+ 'all',
+ '',
+ array
+ (
+ 'palavra' => array('name' => 'palavra', 'type' => 'xsd:string'),
+ 'procedencia' => array('name' => 'procedencia', 'type' => 'xsd:int'),
+ 'sistema' => array('name' => 'sistema', 'type' => 'xsd:int'),
+ 'patologia' => array('name' => 'patologia', 'type' => 'xsd:int'),
+ )
+ );
+
+$server->wsdl->addComplexType(
+ 'SearchResults',
+ 'complexType',
+ 'array',
+ 'all',
+ '',
+ array
+ (
+ 'nome' => array('name' => 'nome', 'type' => 'xsd:string'),
+ 'url'=> array('name'=> 'url', 'type'=> 'xsd:string'),
+ 'procedencia' => array('name' => 'procedencia', 'type' => 'xsd:string'),
+ 'sistema' => array('name' => 'sistema', 'type' => 'xsd:string'),
+ 'patologia' => array('name' => 'patologia', 'type' => 'xsd:string'),
+ )
+ );
+
+$server->wsdl->addComplexType(
+ 'WordList',
+ 'complexType',
+ 'array',
+ 'sequence',
+ '',
+ array(
+ 'id' => array('name' => 'id', 'type' => 'xsd:int'),
+ 'nome' => array('name' => 'nome', 'type' => 'xsd:string')
+ )
+ );
+
+$server->register('get_search_types', // method name
+ array(), // input parameters
+ array('return' => 'tns:WordList'), // output parameters
+ 'urn:siapwsdl', // namespace
+ 'urn:siapwsdl#get_search_types', // soapaction
+ 'rpc', // style
+ 'encoded', // use
+ 'Get an image from the SIAP database' // documentation
+ );
+
+$server->register('get_search_type_keywords', // method name
+ array('search_type' => 'xsd:int'), // input parameters
+ array('return' => 'tns:WordList'), // output parameters
+ 'urn:siapwsdl', // namespace
+ 'urn:siapwsdl#get_search_type_keywords', // soapaction
+ 'rpc', // style
+ 'encoded', // use
+ 'Get an image from the SIAP database' // documentation
+ );
+
+$server->register('search', // method name
+ array('search_request' => 'tns:SearchRequest'), // input parameters
+ array('return' => 'tns:SearchResults'), // output parameters
+ 'urn:siapwsdl', // namespace
+ 'urn:siapwsdl#search', // soapaction
+ 'rpc', // style
+ 'encoded', // use
+ 'Perform a search in the SIAP database' // documentation
+ );
+
+function get_search_types()
+{
+ // Not available in the database.
+ // Those are the search types available for images.
+ $search_types = array();
+ $search_types[] = array('id' => 1, 'nome' => 'Procedência');
+ $search_types[] = array('id' => 2, 'nome' => 'Sistema');
+ $search_types[] = array('id' => 3, 'nome' => 'Patologia');
+ return $search_types;
+}
+
+function get_search_type_keywords($search_type)
+{
+ $ret = array();
+ switch($search_type)
+ {
+ case 1:
+ $ret = get_keywords_by_search_type("procedencia");
+ break;
+ case 2:
+ $ret = get_keywords_by_search_type("sistema");
+ break;
+ case 3:
+ $ret = get_keywords_by_search_type("patologia");
+ break;
+ }
+
+ return $ret;
+}
+
+
+function search($search_request) {
+ $result = simple_search($search_request['palavra'], $search_request['procedencia'], $search_request['sistema'], $search_request['patologia']);
+ return $result;
+}
+
+
+// Use the request to (try to) invoke the service
+$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
+$server->service($HTTP_RAW_POST_DATA);
+?>
--- /dev/null
+<?
+$cfg = array();
+
+function connect_to_database(){
+ define("IS_LOCAL", false);
+ include("_config/config.php");
+ $dbhost = "200.18.67.60";
+ $dbuser = "frazaoproject";
+ $dbpass = "myN3MbassW0rd";
+ $dbname = "frazaoproject";
+ $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
+ $db = mysql_select_db($dbname);
+}
+
+connect_to_database();
+
+function get_keywords_by_search_type($search_type){
+ $keywords = array();
+ $result = mysql_query("SELECT id,nome FROM sis_".$search_type." ORDER BY nome ASC");
+ while ($row = mysql_fetch_array($result)) {
+ $keywords[] = array('id' => $row{'id'}, 'nome' => $row{'nome'});
+ }
+ return $keywords;
+}
+
+function store_search_keyword($keyword){
+ if($keyword != ''){
+ $sql_query = "SELECT * FROM sis_palavrabusca WHERE palavra = '".$keyword."'";
+ $rowPalavra = mysql_query($sql_query);
+ if(!$rowPalavra){
+ $sql_query = "INSERT INTO sis_palavrabusca (palavra,quantidade) VALUES('".$keyword."',1)";
+ } else {
+ $sql_query = "UPDATE sis_palavrabusca SET quantidade = quantidade+1 WHERE palavra ='".$keyword."'";
+ }
+ mysql_query($sql_query);
+ }
+}
+
+
+function get_simple_search_query($tmp_palavraChave, $tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = ''){
+ $andProcedencia = '';
+ if($tmp_procedencia != ''){
+ $andProcedencia = ' AND i.id_procedencia = '.$tmp_procedencia.' ';
+ }
+ $andSistema = '';
+ if($tmp_sistema != ''){
+ $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' ';
+ }
+ $andPatologia = '';
+ if($tmp_patologia != ''){
+ $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' ';
+ }
+
+ $sql_query = "SELECT i.id,
+ i.saudavel,
+ i.id_procedencia,
+ proc.nome as procedencia,
+ i.id_patologia,
+ pat.nome as patologia,
+ i.id_sistema,
+ sis.nome as sistema,
+ i.nome,
+ i.texto,
+ i.dataorigem
+ FROM sis_imagem i
+ LEFT OUTER JOIN sis_procedencia proc ON i.id_procedencia = proc.id
+ LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id
+ LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id
+
+ LEFT OUTER JOIN sis_diagnostico_imagem di ON i.id = di.id_imagem
+ LEFT OUTER JOIN sis_diagnostico d ON di.id_diagnostico = d.id
+
+ LEFT OUTER JOIN sis_casoestudo_imagem ci ON i.id = ci.id_imagem
+ LEFT OUTER JOIN sis_casoestudo c ON ci.id_casoestudo = c.id
+
+ LEFT OUTER JOIN sis_imagem_orgao io ON i.id = io.id_imagem
+ LEFT OUTER JOIN sis_orgao o ON io.id_orgao = o.id
+ LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao
+
+ WHERE i.visualizacao = 1 AND i.saudavel = 0 AND (
+ i.nome like '%".$tmp_palavraChave."%' OR
+ i.texto like '%".$tmp_palavraChave."%' OR
+ proc.nome like '%".$tmp_palavraChave."%' OR
+ pat.nome like '%".$tmp_palavraChave."%' OR
+ sis.nome like '%".$tmp_palavraChave."%' OR
+ d.nome like '%".$tmp_palavraChave."%' OR
+ d.palavrachave like '%".$tmp_palavraChave."%' OR
+ o.nome like '%".$tmp_palavraChave."%' OR
+ o.palavrachave like '%".$tmp_palavraChave."%' OR
+ c.nome like '%".$tmp_palavraChave."%' OR
+ c.palavrachave like '%".$tmp_palavraChave."%'
+ ) ".$andProcedencia.$andSistema.$andPatologia." GROUP BY i.id ORDER BY i.nome ASC";
+ $myFile = "test/log.txt";
+ $fh = fopen($myFile, 'w') or die("can't open file");
+ fwrite($fh, $sql_query);
+ fclose($fh);
+ return $sql_query;
+}
+
+
+
+function simple_search($palavra, $procedencia = '', $sistema = '', $patologia = ''){
+ store_search_keyword($palavra);
+ $sql_query = get_simple_search_query($palavra, $procedencia, $sistema, $patologia);
+ $images = array();
+ $result = mysql_query($sql_query);
+ while ($row = mysql_fetch_array($result)) {
+ $image_url = "http://siap.ufcspa.edu.br/upload/sis_imagem/".($row{'id'}).".jpg";
+ $images[] = array('id'=>$row{'id'}, 'nome'=>$row{'nome'}, 'procedencia'=>$row{'procedencia'},
+ 'sistema'=>$row{'sistema'}, 'patologia'=>$row{'patologia'}, 'url'=>$image_url);
+ }
+ return $images;
+}
+?>
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+?>\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <script src="../../../_system/js/form.js" type="text/javascript"></script>\r
+ <script src="../../../_system/js/ajax.js" type="text/javascript"></script>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ </head>\r
+ <body>\r
+ [Conteúdo]\r
+ </body>\r
+</html>\r
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+\r
+$load->config('classes/CasoEstudo.php');\r
+$o_casoEstudo = new CasoEstudo();\r
+\r
+$arrProfessor = $o_helper->findProfesores(true);\r
+$arrProcedencia = $o_helper->findProcedencias(true);\r
+$arrSistema = $o_helper->findSistemas(true);\r
+$arrPatologia = $o_helper->findPatologias(true);\r
+$arrEspecialidade = $o_helper->findEspecialidade(true);\r
+\r
+$letra = $input->get('letra');\r
+$palavraChave = $input->get('palavrachave');\r
+$professor = $input->get('professor');\r
+$especialidade = $input->get('especialidade');\r
+$sistema = $input->get('sistema');\r
+$patologia = $input->get('patologia');\r
+$boneco = $input->get("boneco");\r
+$codigo = $input->get("codigo");\r
+if($codigo == 'Código'){\r
+ $codigo = '';\r
+}\r
+$pagina = $input->get("pagina");\r
+if($pagina == ""){\r
+ $pagina = 1;\r
+}\r
+\r
+$total = 0;\r
+if($o_helper->hasFilter()){\r
+ if($o_helper->hasFilter(false)){\r
+ $base = '?palavrachave='.$palavraChave.'&professor='.$professor.'&especialidade='.$especialidade.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco.'&codigo='.$codigo;\r
+ $rowsCasoEstudo = $o_casoEstudo->simpleSeach($palavraChave,$professor,$especialidade,$sistema,$patologia,$boneco,$codigo);\r
+ if(($rowsCasoEstudo->EOF) && ($palavraChave != '')){\r
+ $arr_palavras = $o_helper->findPalavraAproximada($palavraChave);\r
+ //print_r2($arr_palavras);\r
+ $segestoes = '';\r
+ if(sizeof($arr_palavras[0]) > 0){\r
+ for($x=0;$x<sizeof($arr_palavras[0]);$x++){\r
+ if($arr_palavras[0][$x] != $palavraChave){\r
+ $segestoes .= "<a class='atracoes' href='index.php?palavrachave=".$arr_palavras[0][$x].'&professor='.$professor.'&especialidade='.$especialidade.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco.'&codigo='.$codigo."' alt='Refazer pesquisa utilizando a palavra ".$arr_palavras[0][$x]."'><b>".$arr_palavras[0][$x]."</b></a>, ";\r
+ }\r
+ }\r
+ if($segestoes != ""){\r
+ $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2);\r
+ }\r
+ }\r
+ $rowsCasoEstudo = $o_casoEstudo->complexSeach($arr_palavras,$professor,$especialidade,$sistema,$patologia,$boneco,$codigo);\r
+ }\r
+ } else {\r
+ $base = '?letra='.$letra;\r
+ $rowsCasoEstudo = $o_casoEstudo->searchLetter($letra);\r
+ }\r
+ $total = $rowsCasoEstudo->recordCount();\r
+ $rowsCasoEstudo->pagesize = $o_casoEstudo->filtro_resultado;\r
+ $rowsCasoEstudo->page($pagina);\r
+}\r
+\r
+$selected = 'casosdeestudo';\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td width="375">\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=BUSCAR EM CASOS DE ESTUDO","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <? if(isset($rowsCasoEstudo)){?>\r
+ <div>\r
+ <table cellspacing="0" cellpadding="0" width="360" style="border:1px solid #CCA365;">\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Listando: <?=$total;?> resultado<?=(($total > 1)?'s':'');?>.<br />\r
+ <? if($o_helper->hasFilter(false)){?>\r
+ <? if($palavraChave != ''){?>\r
+ <br />Palavra-chave: <b><?=$palavraChave;?></b>\r
+ <? }?>\r
+ <? if($professor != ''){?>\r
+ <br />Professor: <b><?=$arrProfessor[$professor];?></b>\r
+ <? }?>\r
+ <? if($especialidade != ''){?>\r
+ <br />Especialidade: <b><?=$arrEspecialidade[$especialidade];?></b>\r
+ <? }?>\r
+ <? if($sistema != ''){?>\r
+ <br />Sistema: <b><?=$arrSistema[$sistema];?></b>\r
+ <? }?>\r
+ <? if($patologia != ''){?>\r
+ <br />Patologia: <b><?=$arrPatologia[$patologia];?></b>\r
+ <? }?>\r
+ <? if($boneco != ''){?>\r
+ <br />Topografia: <b><?=$o_helper->findTopografiaById($boneco);?></b>\r
+ <? }?>\r
+ <? if($codigo != ''){?>\r
+ <br />Código: <b><?=$codigo;?></b>\r
+ <? }?>\r
+ <?if(isset($segestoes)){?>\r
+ <br /><?=$segestoes;?>\r
+ <?}?>\r
+ <? } else if($letra != ''){?>\r
+ Índice: <b><?=$letra;?></b>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ <? }?>\r
+ <div>\r
+ <form id="frmBusca" name="frmBusca" onsubmit="return false" action="" method="get">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td style="padding-top:10px; padding-bottom:10px;">\r
+ <?=$o_html->getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <!--<div class="rdoPal">\r
+ <input type="radio" id="Palavra" name="palavra" value="1" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Qualquer palavra\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Palavra" name="palavra" value="1" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Todas palavras\r
+ </div>-->\r
+ <div class="rdoPal" style="float:right;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:10px;padding-bottom:0px;">\r
+ <?=$o_html->getSelect($arrProfessor,'Professor','CMB0','professor',' style="width:360px;" ');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:20px; padding-bottom:15px;">\r
+ <a href="javascript: swapElement('tr_buscavancada');" class="underlaine2">Busca Avançada</a>\r
+ </td>\r
+ </tr>\r
+ <tr id="tr_buscavancada">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td width="141">\r
+ <?=$o_html->getBoneco('Boneco','TXT0','boneco');?>\r
+ </td>\r
+ <td>\r
+ <div class="tosear">\r
+ <?=$o_html->getInput('Código','TXT0','codigo',' style="width:200px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrEspecialidade,'Especialidade','CMB0','especialidade',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrPatologia,'Patologia','CMB0','patologia',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear" style="text-align:left;padding-left:10px;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </div>\r
+ </td>\r
+ <td width="619" style="padding-left:15px;">\r
+ <? if(isset($rowsCasoEstudo)){?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=RESULTADOS EM CASOS DE ESTUDO","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_casoEstudo->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsCasoEstudo->EOF){?>\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Nenhum registro encontrado.\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? } else {?>\r
+ <tr>\r
+ <td>\r
+ <?=$o_casoEstudo->getResultado($base);?>\r
+ <?=$o_casoEstudo->getOrdenar($base);?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <? while(!$rowsCasoEstudo->EOF){\r
+ $url = ' onclick="javascript:url(\'view.php?id='.$input->encode($rowsCasoEstudo->fields('id')).'\');" ';?>\r
+ <tr>\r
+ <td style="padding-top:10px;">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td class="bold_444">\r
+ <?=$rowsCasoEstudo->fields('nome');?> <?=(($rowsCasoEstudo->fields('codigo') == '')?'':('<span style="font-size:9px;">('.($rowsCasoEstudo->fields('codigo')).')</span>'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="italic_444">\r
+ <?=$rowsCasoEstudo->fields('especialidade');?> <span class="blue_normal">|</span> <?=$rowsCasoEstudo->fields('professor');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:5px;padding-bottom:5px;">\r
+ <?=$rowsCasoEstudo->fields('texto');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:5px;padding-bottom:5px;">\r
+ <?=$o_casoEstudo->getImgesRelacionadas($rowsCasoEstudo->fields('id'),8);?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <img src="../../img/pt/bt/ver.jpg" style="cursor:pointer;" <?=$url;?> />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <? $rowsCasoEstudo->moveNext();\r
+ }?>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsCasoEstudo->pagecount > 1){?>\r
+ <tr>\r
+ <td>\r
+ Páginas: <?\r
+ //total de paginas\r
+ $totalPage = $rowsCasoEstudo->pagecount;\r
+ //pagina atual\r
+ $actualPage = $pagina;\r
+ //baseLink\r
+ $pageBaseLink = $base;\r
+ //nome do link da pagina (pagina=1)\r
+ $pageLinkName = 'pagina';\r
+ include('../../inc/structure/paginacao.php');\r
+ ?>\r
+ </td>\r
+ </tr>\r
+ <? }\r
+ }?>\r
+ </table>\r
+ <? } else {?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=ÍNDICE","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_casoEstudo->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+$selected = 'casosdeestudo';\r
+\r
+$load->config('classes/CasoEstudo.php');\r
+$o_casoEstudo = new CasoEstudo();\r
+$rowCasoEstudo = $o_casoEstudo->findCasoEstudoById($input->get('id',true));\r
+if($rowCasoEstudo->EOF){\r
+ redir('index.php');\r
+ die;\r
+}\r
+\r
+$load->manager('core/Profile.php');\r
+$o_profile = new Profile();\r
+\r
+$rowsComentario = $o_casoEstudo->findComentariosByIdCasoEstudo($input->get('id',true));\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td>\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=CASOS DE ESTUDO","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td colspan="100%">\r
+ <div>\r
+ <b><?=$rowCasoEstudo->fields('nome');?></b>\r
+ </div>\r
+ <div style="margin-top:3px; margin-bottom:3px;">\r
+ <i><?=$rowCasoEstudo->fields('especialidade');?></i>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr height="330">\r
+ <td width="410">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td style="padding-bottom:15px;padding-top:15px;padding-right:15px;">\r
+ <?=nl2br($rowCasoEstudo->fields('texto'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="font-size:10px;">\r
+ <?=$o_casoEstudo->orgaosrelacionados($rowCasoEstudo->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/imagensrelacionadas.gif" <?=$o_html->alt('Imagens Relacionadas');?> />\r
+ </div>\r
+ <?=$o_casoEstudo->getImgesRelacionadas($rowCasoEstudo->fields('id'));?>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/diagnosticosrelacionados.gif" <?=$o_html->alt('Casos de Estudo Relacionados');?> />\r
+ </div>\r
+ <?=$o_casoEstudo->diagnosticosrelacionados($rowCasoEstudo->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <? if(!$rowsComentario->EOF){?>\r
+ <tr>\r
+ <td style="padding-top:15px;">\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <img src="../../img/pt/tit/comentarios.gif" />\r
+ </td>\r
+ </tr>\r
+ <? $bg = 'F2F2F2';\r
+ while(!$rowsComentario->EOF){\r
+ if($bg == 'F2F2F2'){\r
+ $bg = 'FFFFFF';\r
+ } else {\r
+ $bg = 'F2F2F2';\r
+ }?>\r
+ <tr>\r
+ <td style="background:#<?=$bg;?>; padding-left:25px;padding-right:25px;">\r
+ <div class="nomeComentario">\r
+ <?=$rowsComentario->fields('nome');?>\r
+ </div>\r
+ <? if($o_profile->isLogged()){\r
+ if(($o_profile->fields['id'] == 1) || ($o_profile->fields['id'] == $rowCasoEstudo->fields('id_usuario'))){?>\r
+ <div class="excluirComentario">\r
+ <a href="../../inc/routines/routines.php?action=inativeComentario&id=<?=$rowsComentario->fields('id');?>" alt="Inativar Comentário" title="Inativar Comentário">Inativar comentário</a>\r
+ </div>\r
+ <? }\r
+ }?>\r
+ <div class="textoComentario">\r
+ <?=nl2br($rowsComentario->fields('comentario'));?>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <? $rowsComentario->moveNext();\r
+ }?>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <? }?>\r
+ <? /*?>\r
+ <tr>\r
+ <td style="padding-left:25px; padding-right:25px;">\r
+ <form id="frm_comentario" name="frm_comentario" method="post" action="../../inc/routines/routines.php?action=insertComentario">\r
+ <input type="hidden" id="id" name="id" value="<?=$input->get('id');?>" />\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td colspan="2" style="padding-top:20px; color:#194c7f; padding-bottom:20px;">\r
+ <b>Comente sobre este caso</b>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_html->getInput('Nome','TXT1','nome',' style="width:270px;" ');?>\r
+ </td>\r
+ <td rowspan="2" align="right">\r
+ <?=$o_html->getInput('Comentário','TXT1','comentario',' style="width:620px; height: 51px;" ',true,'textarea');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="vertical-align:bottom;">\r
+ <?=$o_html->getInput('E-mail','EML1','email',' style="width:270px;" ');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td colspan="2" align="right" style="padding-top:10px;">\r
+ <input type="image" src="../../img/pt/bt/enviar.jpg" onclick="javascript: f.send('frm_comentario');" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </td>\r
+ </tr>\r
+ <? */?>\r
+ <tr>\r
+ <td style="padding-top:25px;">\r
+ <img src="../../img/pt/bt/voltar.jpg" <?=$o_html->alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+\r
+$load->config('classes/Diagnostico.php');\r
+$o_diagnostico = new Diagnostico();\r
+\r
+$arrProcedencia = $o_helper->findProcedencias(true);\r
+$arrSistema = $o_helper->findSistemas(true);\r
+$arrPatologia = $o_helper->findPatologias(true);\r
+$arrEspecialidade = $o_helper->findEspecialidade(true);\r
+\r
+$letra = $input->get('letra');\r
+$palavraChave = $input->get('palavrachave');\r
+$especialidade = $input->get('especialidade');\r
+$procedencia = $input->get('procedencia');\r
+$sistema = $input->get('sistema');\r
+$patologia = $input->get('patologia');\r
+$like = $input->get('pp');//0 - qualquer palavra (quebrar em array por espaços) / 1 - todas, não quebra nada\r
+$boneco = $input->get("boneco");\r
+$pagina = $input->get("pagina");\r
+if($pagina == ""){\r
+ $pagina = 1;\r
+}\r
+\r
+$total = 0;\r
+if($o_helper->hasFilter()){\r
+ if($o_helper->hasFilter(false)){\r
+ $base = '?palavrachave='.$palavraChave.'&especialidade='.$especialidade.'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco;\r
+ $rowsDiagnostico = $o_diagnostico->simpleSeach($palavraChave,$especialidade,$procedencia,$sistema,$patologia,$boneco);\r
+ if(($rowsDiagnostico->EOF) && ($palavraChave != '')){\r
+ $arr_palavras = $o_helper->findPalavraAproximada($palavraChave);\r
+ //print_r2($arr_palavras);\r
+ $segestoes = '';\r
+ if(sizeof($arr_palavras[0]) > 0){\r
+ for($x=0;$x<sizeof($arr_palavras[0]);$x++){\r
+ if($arr_palavras[0][$x] != $palavraChave){\r
+ $segestoes .= "<a class='atracoes' href='index.php?palavrachave=".$arr_palavras[0][$x].'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco."' alt='Refazer pesquisa utilizando a palavra ".$arr_palavras[0][$x]."'><b>".$arr_palavras[0][$x]."</b></a>, ";\r
+ }\r
+ }\r
+ if($segestoes != ""){\r
+ $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2);\r
+ }\r
+ }\r
+ $rowsDiagnostico = $o_diagnostico->complexSeach($arr_palavras,$procedencia,$sistema,$patologia,$boneco);\r
+ }\r
+ } else {\r
+ $base = '?letra='.$letra;\r
+ $rowsDiagnostico = $o_diagnostico->searchLetter($letra);\r
+ }\r
+ $total = $rowsDiagnostico->recordCount();\r
+ $rowsDiagnostico->pagesize = $o_diagnostico->filtro_resultado;\r
+ $rowsDiagnostico->page($pagina);\r
+}\r
+$selected = 'diagnosticos';\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td width="375">\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=BUSCAR EM DIAGNÓSTICOS","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <? if(isset($rowsDiagnostico)){?>\r
+ <div>\r
+ <table cellspacing="0" cellpadding="0" width="360" style="border:1px solid #CCA365;">\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Listando: <?=$total;?> resultado<?=(($total > 1)?'s':'');?>.<br />\r
+ <? if($o_helper->hasFilter(false)){?>\r
+ <? if($palavraChave != ''){?>\r
+ <br />Palavra-chave: <b><?=$palavraChave;?></b>\r
+ <? }?>\r
+ <? if($especialidade != ''){?>\r
+ <br />Especialidade: <b><?=$arrEspecialidade[$especialidade];?></b>\r
+ <? }?>\r
+ <? if($procedencia != ''){?>\r
+ <br />Procedência: <b><?=$arrProcedencia[$procedencia];?></b>\r
+ <? }?>\r
+ <? if($sistema != ''){?>\r
+ <br />Sistema: <b><?=$arrSistema[$sistema];?></b>\r
+ <? }?>\r
+ <? if($patologia != ''){?>\r
+ <br />Patologia: <b><?=$arrPatologia[$patologia];?></b>\r
+ <? }?>\r
+ <? if($boneco != ''){?>\r
+ <br />Topografia: <b><?=$o_helper->findTopografiaById($boneco);?></b>\r
+ <? }?>\r
+ <?if(isset($segestoes)){?>\r
+ <br /><?=$segestoes;?>\r
+ <?}?>\r
+ <? } else if($letra != ''){?>\r
+ Índice: <b><?=$letra;?></b>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ <? }?>\r
+ <div>\r
+ <form id="frmBusca" name="frmBusca" onsubmit="return false" action="index.php" method="get">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td style="padding-top:10px; padding-bottom:10px;">\r
+ <?=$o_html->getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <!--<div class="rdoPal">\r
+ <input type="radio" id="Palavra" name="palavra" value="1" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Qualquer palavra\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Palavra" name="palavra" value="1" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Todas palavras\r
+ </div>-->\r
+ <div class="rdoPal" style="float:right;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:20px; padding-bottom:15px;">\r
+ <a href="javascript: swapElement('tr_buscavancada');" class="underlaine2">Busca Avançada</a>\r
+ </td>\r
+ </tr>\r
+ <tr id="tr_buscavancada">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td width="141">\r
+ <?=$o_html->getBoneco('Boneco','TXT0','boneco');?>\r
+ </td>\r
+ <td>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrEspecialidade,'Especialidade','CMB0','especialidade',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrProcedencia,'Procedência','CMB0','procedencia',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrPatologia,'Patologia','CMB0','patologia',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear" style="text-align:left;padding-left:10px;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </div>\r
+ </td>\r
+ <td width="619" style="padding-left:15px;">\r
+ <? if(isset($rowsDiagnostico)){?>\r
+ <table cellspacing="0" cellpadding="0" width="100%>\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=RESULTADOS EM DIAGNÓSTICOS","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_diagnostico->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsDiagnostico->EOF){?>\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Nenhum registro encontrado.\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? } else {?>\r
+ <tr>\r
+ <td>\r
+ <?=$o_diagnostico->getResultado($base);?>\r
+ <?=$o_diagnostico->getOrdenar($base);?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <? while(!$rowsDiagnostico->EOF){\r
+ $url = ' onclick="javascript:url(\'view.php?id='.$input->encode($rowsDiagnostico->fields('id')).'\');" ';?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td style="padding-top:10px;">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td class="bold_444" style="cursor:pointer;"<?=$url;?>>\r
+ <?=$rowsDiagnostico->fields('nome');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="italic_444">\r
+ <?=$rowsDiagnostico->fields('especialidade');?><?=(($rowsDiagnostico->fields('cid10') == '')?'':' <span class="blue_normal">|</span> '.$rowsDiagnostico->fields('cid10'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:5px;padding-bottom:5px;" <?=$url;?>>\r
+ <?=$rowsDiagnostico->fields('texto');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:5px;padding-bottom:5px;">\r
+ <?=$o_diagnostico->getImgesRelacionadas($rowsDiagnostico->fields('id'),8);?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <img src="../../img/pt/bt/ver.jpg" style="cursor:pointer;" <?=$url;?> />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <? $rowsDiagnostico->moveNext();\r
+ }?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsDiagnostico->pagecount > 1){?>\r
+ <tr>\r
+ <td>\r
+ Páginas: <?\r
+ //total de paginas\r
+ $totalPage = $rowsDiagnostico->pagecount;\r
+ //pagina atual\r
+ $actualPage = $pagina;\r
+ //baseLink\r
+ $pageBaseLink = $base;\r
+ //nome do link da pagina (pagina=1)\r
+ $pageLinkName = 'pagina';\r
+ include('../../inc/structure/paginacao.php');\r
+ ?>\r
+ </td>\r
+ </tr>\r
+ <? }\r
+ }?>\r
+ </table>\r
+ <? } else {?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=ÍNDICE","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_diagnostico->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+$selected = 'diagnosticos';\r
+\r
+$load->config('classes/Diagnostico.php');\r
+$o_diagnostico = new Diagnostico();\r
+$rowDiagnostico = $o_diagnostico->findDiagnoticoById($input->get('id',true));\r
+if($rowDiagnostico->EOF){\r
+ redir('index.php');\r
+ die;\r
+}\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <script src="../../../_system/js/popup.js" type="text/javascript"></script>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ <script>\r
+ function zoom(){\r
+ var p = new Popup(500,400);\r
+ // p.template = 2;\r
+ // p.overflow = "hidden";\r
+ p.open("../../inc/structure/popup_zoom.php?path=../../../upload/sis_imagem/IDIDID.jpg&id=<?=$input->encode($rowDiagnostico->fields('id'));?>");\r
+ }\r
+ </script>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td>\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=DIAGNÓSTICOS","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td colspan="100%">\r
+ <div>\r
+ <b><?=$rowDiagnostico->fields('nome');?></b>\r
+ </div>\r
+ <div style="margin-top:3px; margin-bottom:3px;">\r
+ <i><?=$rowDiagnostico->fields('especialidade');?></i>\r
+ </div>\r
+ <? if($rowDiagnostico->fields('cid10') != ''){?>\r
+ <div>\r
+ <i><?=$rowDiagnostico->fields('cid10');?></i>\r
+ </div>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ <tr height="330">\r
+ <td width="410">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td style="padding-bottom:15px;padding-top:15px;padding-top:15px;">\r
+ <?=nl2br($rowDiagnostico->fields('texto'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="font-size:10px;">\r
+ <?=$o_diagnostico->orgaosrelacionados($rowDiagnostico->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:25px;">\r
+ <img src="../../img/pt/bt/voltar.jpg" <?=$o_html->alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/imagensrelacionadasdiagnostico.gif" <?=$o_html->alt('Imagens Relacionadas');?> />\r
+ </div>\r
+ <?=$o_diagnostico->getImgesRelacionadas($rowDiagnostico->fields('id'));?>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/casosdeestudorelacionados.gif" <?=$o_html->alt('Casos de Estudo Relacionados');?> />\r
+ </div>\r
+ <?=$o_diagnostico->casosdeestudorelacionados($rowDiagnostico->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+$selected = "";\r
+\r
+if($input->get('tipobusca') != ''){\r
+ $url = '';\r
+ switch($input->get('tipobusca')){\r
+ case 1:\r
+ $url = '../diagnosticos/?palavrachave='.$input->get('palavrachave');\r
+ break;\r
+ case 2:\r
+ $url = '../orgaos/?palavrachave='.$input->get('palavrachave');\r
+ break;\r
+ case 3:\r
+ $url = '../necropsias/?palavrachave='.$input->get('palavrachave');\r
+ break;\r
+ case 4:\r
+ $url = '../casosdeestudo/?palavrachave='.$input->get('palavrachave');\r
+ break;\r
+ case 5:\r
+ $url = '../imagens/?palavrachave='.$input->get('palavrachave');\r
+ break;\r
+ }\r
+ $url .= '&grupoorgao='.$input->get('grupoorgao');\r
+ $url .= '&procedencia='.$input->get('procedencia');\r
+ $url .= '&sistema='.$input->get('sistema');\r
+ $url .= '&patologia='.$input->get('patologia');\r
+ $url .= '&boneco='.$input->get('boneco');\r
+ $url .= '&especialidade='.$input->get('especialidade');\r
+ redir($url);\r
+ die;\r
+}\r
+\r
+$arrGrupoOrgao = $o_helper->findGrupoOrgao(true);\r
+$arrProcedencia = $o_helper->findProcedencias(true);\r
+$arrSistema = $o_helper->findSistemas(true);\r
+$arrPatologia = $o_helper->findPatologias(true);\r
+$arrEspecialidade = $o_helper->findEspecialidade(true);\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ <script type="text/javascript">\r
+ function chk(str){\r
+ var topografia = document.getElementById('Topografia_CMB0');\r
+ var procedencia = document.getElementById('Procedência_CMB0');\r
+ var sistema = document.getElementById('Sistema_CMB0');\r
+ var patologia = document.getElementById('Patologia_CMB0');\r
+ var especialidade = document.getElementById('Especialidade_CMB0');\r
+ topografia.disabled = '';\r
+ procedencia.disabled = '';\r
+ sistema.disabled = '';\r
+ patologia.disabled = '';\r
+ especialidade.disabled = '';\r
+ switch(str){\r
+ case 'dia':\r
+ topografia.disabled = true;\r
+ break;\r
+ case 'org':\r
+ topografia.disabled = true;\r
+ especialidade.disabled = true;\r
+ procedencia.disabled = true;\r
+ break;\r
+ case 'nec':\r
+ topografia.disabled = true;\r
+ patologia.disabled = true;\r
+ break;\r
+ case 'cas':\r
+ topografia.disabled = true;\r
+ procedencia.disabled = true;\r
+ break;\r
+ case 'ima':\r
+ topografia.disabled = true;\r
+ especialidade.disabled = true;\r
+ break;\r
+ }\r
+ }\r
+ </script>\r
+ </head>\r
+ <body onload="javascript: document.getElementById('Palavra-chave_TXT0').focus();" oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td>\r
+ \r
+ </td>\r
+ <td>\r
+ <form id="frmBusca" name="frmBusca" onsubmit="return false" action="" method="get">\r
+ <table cellspacing="0" cellpadding="0" align="right">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=BUSCAR","","transparent");?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:10px; padding-bottom:10px;">\r
+ <?=$o_html->getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Tipo de busca**1_RDO1" name="tipobusca" value="1" onchange="javascript:chk('dia');" checked />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ <label for="Tipo de busca**1_RDO1">Diagnósticos</label>\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Tipo de busca**2_RDO1" name="tipobusca" value="2" onchange="javascript:chk('org');" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ <label for="Tipo de busca**2_RDO1">Órgãos</label>\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Tipo de busca**3_RDO1" name="tipobusca" value="3" onchange="javascript:chk('nec');" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ <label for="Tipo de busca**3_RDO1">Necropsias</label>\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Tipo de busca**4_RDO1" name="tipobusca" value="4" onchange="javascript:chk('cas');" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ <label for="Tipo de busca**4_RDO1">Casos de estudo</label>\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Tipo de busca**5_RDO1" name="tipobusca" value="5" onchange="javascript:chk('ima');" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ <label for="Tipo de busca**5_RDO1">Imagens</label>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:10px;padding-bottom:0px;">\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td width="141">\r
+ <?=$o_html->getBoneco('Boneco','TXT0','boneco');?>\r
+ </td>\r
+ <td>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrGrupoOrgao,'Topografia','CMB0','grupoorgao',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrProcedencia,'Procedência','CMB0','procedencia',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrPatologia,'Patologia','CMB0','patologia',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrEspecialidade,'Especialidade','CMB0','especialidade',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear" style="text-align:right; padding-top:15px; padding-left:10px;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+$selected = "";\r
+$load->config('classes/Image.php');\r
+$o_image = new Image();\r
+$rowsImage = $o_image->findLastImages();\r
+//print_r2($rowsImage);\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <script src="../../../_system/js/ajax.js" type="text/javascript"></script>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td colspan="100%">\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=MAIS RECENTES","","transparent");?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td width="300">\r
+ <div>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=DIAGNÓSTICOS","","transparent");?>\r
+ </div>\r
+ <div class="divLnAm"> </div>\r
+ <div class="subaztit">\r
+ Rinite\r
+ </div>\r
+ <div class="txtdivin">\r
+ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, w\r
+ </div>\r
+ <div>\r
+ <img src="../../img/pt/bt/ver.jpg" <?=$o_html->alt('ver');?> />\r
+ </div>\r
+ <div class="divlncn"> </div>\r
+ <div class="subaztit">\r
+ Rinite\r
+ </div>\r
+ <div class="txtdivin">\r
+ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, w\r
+ </div>\r
+ <div>\r
+ <img src="../../img/pt/bt/ver.jpg" <?=$o_html->alt('ver');?> />\r
+ </div>\r
+ <div class="divlncn"> </div>\r
+ <div class="subaztit">\r
+ Rinite\r
+ </div>\r
+ <div class="txtdivin">\r
+ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, w\r
+ </div>\r
+ <div>\r
+ <img src="../../img/pt/bt/ver.jpg" <?=$o_html->alt('ver');?> />\r
+ </div>\r
+ </td>\r
+ <td width="300" style="padding-left:40px;padding-right:40px;">\r
+ <div>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=IMAGENS","","transparent");?>\r
+ </div>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ <div>\r
+ <? if($rowsImage->EOF){?>\r
+ Nenhuma imagem cadastrada.\r
+ <? } else {\r
+ $style = '';\r
+ $x=0;\r
+ while(!$rowsImage->EOF){\r
+ if($x == 1){\r
+ $style = 'padding-left:20px;padding-right:20px;';\r
+ } else {\r
+ $style = '';\r
+ }?>\r
+ <div style="float:left;padding-top:10px;<?=$style;?> cursor:pointer;" onclick="javascript:url('../imagens/view.php?id=<?=$input->encode($rowsImage->fields('id'));?>');">\r
+ <div style="">\r
+ <? $src = $o_image->getImage($rowsImage->fields('id'));\r
+ if($src == ''){\r
+ $src = '../../img/olho.jpg';\r
+ }?>\r
+ <img src="<?=$src;?>" <?=$o_html->alt($rowsImage->fields('nome'));?> />\r
+ </div>\r
+ <div style="width:85px;" class="subaztit">\r
+ <?=$rowsImage->fields('nome');?>\r
+ </div>\r
+ </div>\r
+ <? $rowsImage->moveNext();\r
+ $x++;\r
+ if($x == 3){\r
+ $x = 0;\r
+ }\r
+ }\r
+ }?>\r
+ </div>\r
+ </td>\r
+ <td width="300">\r
+ <div>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=CASOS DE ESTUDO","","transparent");?>\r
+ </div>\r
+ <div class="divLnAm"> </div>\r
+ <div class="subaztit">\r
+ Rinite\r
+ </div>\r
+ <div class="txtdivin">\r
+ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, w\r
+ </div>\r
+ <div>\r
+ <img src="../../img/pt/bt/ver.jpg" <?=$o_html->alt('ver');?> />\r
+ </div>\r
+ <div class="divlncn"> </div>\r
+ <div class="subaztit">\r
+ Rinite\r
+ </div>\r
+ <div class="txtdivin">\r
+ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, w\r
+ </div>\r
+ <div>\r
+ <img src="../../img/pt/bt/ver.jpg" <?=$o_html->alt('ver');?> />\r
+ </div>\r
+ <div class="divlncn"> </div>\r
+ <div class="subaztit">\r
+ Rinite\r
+ </div>\r
+ <div class="txtdivin">\r
+ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, w\r
+ </div>\r
+ <div>\r
+ <img src="../../img/pt/bt/ver.jpg" <?=$o_html->alt('ver');?> />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+\r
+$load->config('classes/Imagem.php');\r
+$o_imagem = new Imagem();\r
+\r
+$arrProcedencia = $o_helper->findProcedencias(true);\r
+$arrSistema = $o_helper->findSistemas(true);\r
+$arrPatologia = $o_helper->findPatologias(true);\r
+\r
+$letra = $input->get('letra');\r
+$palavraChave = $input->get('palavrachave');\r
+$procedencia = $input->get('procedencia');\r
+$sistema = $input->get('sistema');\r
+$patologia = $input->get('patologia');\r
+$like = $input->get('pp');//0 - qualquer palavra (quebrar em array por espaços) / 1 - todas, não quebra nada\r
+$boneco = $input->get("boneco");\r
+$pagina = $input->get("pagina");\r
+if($pagina == ""){\r
+ $pagina = 1;\r
+}\r
+\r
+$total = 0;\r
+if($o_helper->hasFilter()){\r
+ if($o_helper->hasFilter(false)){\r
+ $base = '?palavrachave='.$palavraChave.'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco;\r
+ $rowsImage = $o_imagem->simpleSeach($palavraChave,$procedencia,$sistema,$patologia,$boneco);\r
+ if(($rowsImage->EOF) && ($palavraChave != '')){\r
+ $arr_palavras = $o_helper->findPalavraAproximada($palavraChave);\r
+ //print_r2($arr_palavras);\r
+ $segestoes = '';\r
+ if(sizeof($arr_palavras[0]) > 0){\r
+ for($x=0;$x<sizeof($arr_palavras[0]);$x++){\r
+ if($arr_palavras[0][$x] != $palavraChave){\r
+ $segestoes .= "<a class='atracoes' href='index.php?palavrachave=".$arr_palavras[0][$x].'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco."' alt='Refazer pesquisa utilizando a palavra ".$arr_palavras[0][$x]."'><b>".$arr_palavras[0][$x]."</b></a>, ";\r
+ }\r
+ }\r
+ if($segestoes != ""){\r
+ $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2);\r
+ }\r
+ }\r
+ $rowsImage = $o_imagem->complexSeach($arr_palavras,$procedencia,$sistema,$patologia,$boneco);\r
+ }\r
+ } else {\r
+ $base = '?letra='.$letra;\r
+ $rowsImage = $o_imagem->searchLetter($letra);\r
+ }\r
+ $total = $rowsImage->recordCount();\r
+ $rowsImage->pagesize = $o_imagem->filtro_resultado;\r
+ $rowsImage->page($pagina);\r
+}\r
+//print_r2($rowsImage);\r
+$selected = 'imagens';\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+<head>\r
+<? include("../../inc/structure/header.php"); ?>\r
+<title><?= $cfg["site_title"]; ?></title>\r
+</head>\r
+<body oncontextmenu="return false;">\r
+<table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+<?include('../../inc/structure/topo.php');?>\r
+<tr height="100%">\r
+<td>\r
+<table cellspacing="0" cellpadding="0" align="center" width="994">\r
+<tr>\r
+<td width="375">\r
+<div>\r
+<?swf("../../swf/common/titulo.swf",330,30,"txt=BUSCAR EM IMAGENS","","transparent");?>\r
+</div>\r
+<br /><br />\r
+<? if(isset($rowsImage)){?>\r
+ <div>\r
+ <table cellspacing="0" cellpadding="0" width="360" style="border:1px solid #CCA365;">\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Listando: <?=$total;?> resultado<?=(($total > 1)?'s':'');?>.<br />\r
+ <? if($o_helper->hasFilter(false)){?>\r
+ <? if($palavraChave != ''){?>\r
+ <br />Palavra-chave: <b><?=$palavraChave;?></b>\r
+ <? }?>\r
+ <? if($procedencia != ''){?>\r
+ <br />Procedência: <b><?=$arrProcedencia[$procedencia];?></b>\r
+ <? }?>\r
+ <? if($sistema != ''){?>\r
+ <br />Sistema: <b><?=$arrSistema[$sistema];?></b>\r
+ <? }?>\r
+ <? if($patologia != ''){?>\r
+ <br />Patologia: <b><?=$arrPatologia[$patologia];?></b>\r
+ <? }?>\r
+ <? if($boneco != ''){?>\r
+ <br />Topografia: <b><?=$o_helper->findTopografiaById($boneco);?></b>\r
+ <? }?>\r
+ <?if(isset($segestoes)){?>\r
+ <br /><?=$segestoes;?>\r
+ <?}?>\r
+ <? } else if($letra != ''){?>\r
+ Índice: <b><?=$letra;?></b>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ <? }?>\r
+ <div>\r
+ <form id="frmBusca" name="frmBusca" onsubmit="return false" action="index.php" method="get">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td style="padding-top:10px; padding-bottom:10px;">\r
+ <?=$o_html->getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <!--<div class="rdoPal">\r
+ <input type="radio" id="Palavra0" name="pp" value="0" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Qualquer palavra\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Palavra1" name="pp" value="1" checked />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Todas palavras\r
+ </div>-->\r
+ <div class="rdoPal" style="float:right;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:20px; padding-bottom:15px;">\r
+ <a href="javascript: swapElement('tr_buscavancada');" class="underlaine2">Busca Avançada</a>\r
+ </td>\r
+ </tr>\r
+ <tr id="tr_buscavancada" style="display:;">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td width="141">\r
+ <?=$o_html->getBoneco('Boneco','TXT0','boneco');?>\r
+ </td>\r
+ <td>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrProcedencia,'Procedência','CMB0','procedencia',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrPatologia,'Patologia','CMB0','patologia',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear" style="text-align:left;padding-left:10px;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </div>\r
+ </td>\r
+ <td width="619" style="padding-left:15px;">\r
+ <? if(isset($rowsImage)){?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=RESULTADOS EM IMAGENS","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_imagem->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsImage->EOF){?>\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Nenhum registro encontrado.\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? } else {?>\r
+ <tr>\r
+ <td>\r
+ <?=$o_imagem->getResultado($base);?>\r
+ <?=$o_imagem->getOrdenar($base);?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <? $x = 0;\r
+ while(!$rowsImage->EOF){\r
+ if(($x != 0) && (($x%2) == 0)){\r
+ echo '</tr><tr>';\r
+ }?>\r
+ <td style="padding-top:10px;">\r
+ <div>\r
+ <table cellspacing="0" cellpadding="0" onclick="javascript: url('view.php?id=<?=$input->encode($rowsImage->fields('id'));?>');" style="cursor:pointer;">\r
+ <tr>\r
+ <td><?\r
+ $src = $o_imagem->getImage($rowsImage->fields('id'));\r
+ if($src == ''){\r
+ $src = '../../img/olho.jpg';\r
+ }\r
+ ?> <div style="width:86px; height:74px;">\r
+ <img src="<?=$src;?>" />\r
+ </div>\r
+ </td>\r
+ <td class="tddados" valign="middle">\r
+ <div><b><?=$rowsImage->fields('nome');?></b> <?=$o_imagem->saudavel($rowsImage->fields('saudavel'));?></div>\r
+ <div><?=$rowsImage->fields('sistema');?></div>\r
+ <div style="margin-bottom:0px;"><?=$rowsImage->fields('patologia');?></div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ </td>\r
+ <? $rowsImage->moveNext();\r
+ $x++;\r
+ }?>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsImage->pagecount > 1){?>\r
+ <tr>\r
+ <td>\r
+ Páginas: <?\r
+ //total de paginas\r
+ $totalPage = $rowsImage->pagecount;\r
+ //pagina atual\r
+ $actualPage = $pagina;\r
+ //baseLink\r
+ $pageBaseLink = $base;\r
+ //nome do link da pagina (pagina=1)\r
+ $pageLinkName = 'pagina';\r
+ include('../../inc/structure/paginacao.php');\r
+ ?>\r
+ </td>\r
+ </tr>\r
+ <? }\r
+ }?>\r
+ </table>\r
+ <? } else {?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=ÍNDICE","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_imagem->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+ </html>\r
+ <? include("../../inc/structure/footer.php"); ?>\r
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+$load->system('functions/text.php');\r
+\r
+$selected = 'imagens';\r
+\r
+$load->config('classes/Imagem.php');\r
+$o_imagem = new Imagem();\r
+$rowImage = $o_imagem->findImageById($input->get('id',true));\r
+if($rowImage->EOF){\r
+ redir('index.php');\r
+ die;\r
+}\r
+$o_imagem->verifyWaterMark($rowImage->fields('id'),$rowImage->fields('carimbo'));\r
+$folder = 'sis_imagem_wm';\r
+if($rowImage->fields('carimbo') == 4){\r
+ $folder = 'sis_imagem';\r
+}\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <style type="text/css">\r
+ @import "../../inc/css/jqzoom.css";\r
+ </style>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ <script>\r
+ function download(){\r
+ var p = new Popup(350,210);\r
+ p.position = 'fixed';\r
+ p.overflow = "hidden";\r
+ p.open("../../inc/structure/popup_download.php?name=<?=formatNameFile($rowImage->fields('nome'));?>.jpg&path=upload/<?=$folder;?>/IDIDID.jpg&id=<?=$input->encode($rowImage->fields('id'));?>");\r
+ }\r
+ function zoom(){\r
+ var p = new Popup(500,400);\r
+ p.position = 'fixed';\r
+ p.overflow = "hidden";\r
+ p.open("../../inc/structure/popup_zoom.php?path=../../../upload/<?=$folder;?>/IDIDID.jpg&id=<?=$input->encode($rowImage->fields('id'));?>");\r
+ }\r
+ function zoom1(tmp_w,tmp_h){\r
+ var p = new Popup(tmp_w,tmp_h);\r
+ p.position = 'fixed';\r
+ p.overflow = "hidden";\r
+ p.open("../../inc/structure/popup_zoom1.php?path=../../../upload/<?=$folder;?>/IDIDID.jpg&id=<?=$input->encode($rowImage->fields('id'));?>");\r
+ }\r
+ function init_zoom(){\r
+ $(function() {\r
+ $(".jqzoom").jqzoom({title: false,showEffect:'fadein',hideEffect:'fadeout',fadeinSpeed:'medium', fadeoutSpeed: 'medium',preloadText: 'Carregando zoom', xOffset: 10});\r
+ });\r
+ }\r
+ </script>\r
+ </head>\r
+ <body oncontextmenu="return false;" onload="javascript: init_zoom();">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td>\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=IMAGENS","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td colspan="100%">\r
+ <div>\r
+ <b><?=$rowImage->fields('nome');?></b> <?=$o_imagem->saudavel($rowImage->fields('saudavel'));?>\r
+ </div>\r
+ <div style="margin-top:3px; margin-bottom:3px;">\r
+ <i><?=$rowImage->fields('sistema');?></i>\r
+ </div>\r
+ <div>\r
+ <i><?=$rowImage->fields('patologia');?></i>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr height="330">\r
+ <td width="410">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td colspan="2" style="padding-bottom:15px;padding-top:15px;padding-top:15px;">\r
+ <?=nl2br($rowImage->fields('texto'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-right:10px;padding-bottom:10px;">\r
+ <? $src = $o_imagem->getImage($rowImage->fields('id'),'m',4);\r
+ $srcG = '../../../upload/'.$folder.'/'.$rowImage->fields('id').'.jpg';\r
+ $funcSimples = '';\r
+ $funcDetalhe = '';\r
+ if($src == ''){\r
+ $src = '../../img/olho_g.jpg';\r
+ } else {\r
+ $img = imagecreatefromjpeg($srcG);\r
+ $w = imagesx($img);\r
+ $h = imagesy($img);\r
+ $funcSimples = ' onclick="javascript: zoom1('.$w.','.$h.');" style="cursor:pointer;" ';\r
+ $funcDetalhe = ' onclick="javascript: zoom();" style="cursor:pointer;" ';\r
+ }\r
+ \r
+ ?>\r
+ <div>\r
+ <table cellspacing="0" cellpadding="0" width="241" height="207">\r
+ <tr>\r
+ <td>\r
+ <a href="<?=$srcG;?>" class="jqzoom"><img src="<?=$src;?>" <?=$o_html->alt($rowImage->fields('nome'));?> /></a>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ <? if($funcDetalhe != ''){?>\r
+ <div style="padding-top:5px; float:left;">\r
+ <img src="../../img/pt/bt/zoomemdetalhe.jpg" style="cursor:pointer;" <?=$funcDetalhe;?> />\r
+ </div>\r
+ <div style="padding-top:5px; float:right;">\r
+ <img src="../../img/pt/bt/zoomsimples.jpg" style="cursor:pointer;" <?=$funcSimples;?> />\r
+ </div>\r
+ <div style="float:left; margin-top:5px;">\r
+ <img src="../../img/pt/bt/download.jpg" style="cursor:pointer;" onclick="javascript: download();" />\r
+ </div>\r
+ <? }?>\r
+ </td>\r
+ <td style="font-size:10px;padding-bottom:10px;" width="100%">\r
+ <?=$o_imagem->dataorigem($rowImage->fields('dataorigem'));?>\r
+ <?=$o_imagem->procedencia($rowImage->fields('procedencia'));?>\r
+ <?=$o_imagem->orgaosrelacionados($rowImage->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ <? if($rowImage->fields('id_grupoimagem') != ''){?>\r
+ <tr>\r
+ <td colspan="2" style="border-top: 1px solid #DABA89; padding-top:10px;">\r
+ <div style="padding-bottom:20px;">\r
+ <img src="../../img/pt/tit/imagensrelacionadas.gif" <?=$o_html->alt('Imagens Relacionadas');?> />\r
+ </div>\r
+ <div>\r
+ <?=$o_imagem->getImgesRelacionadasByGrupo($rowImage->fields('id_grupoimagem'));?>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <? }?>\r
+ <tr>\r
+ <td style="padding-top:25px;">\r
+ <img src="../../img/pt/bt/voltar.jpg" <?=$o_html->alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/diagnosticosrelacionados.gif" <?=$o_html->alt('Diagnósticos Relacionados');?> />\r
+ </div>\r
+ <?=$o_imagem->diagnosticosrelacionados($rowImage->fields('id'));?>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/casosdeestudorelacionados.gif" <?=$o_html->alt('Casos de Estudo Relacionados');?> />\r
+ </div>\r
+ <?=$o_imagem->casosdeestudorelacionados($rowImage->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<html>\r
+ <head>\r
+ <meta http-equiv="refresh" content="0;url=home/" />\r
+ </head>\r
+</html>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+\r
+$patologia = 5;//necropsia\r
+\r
+$load->config('classes/Diagnostico.php');\r
+$o_diagnostico = new Diagnostico($patologia);\r
+\r
+$arrProcedencia = $o_helper->findProcedencias(true);\r
+$arrSistema = $o_helper->findSistemas(true);\r
+$arrEspecialidade = $o_helper->findEspecialidade(true);\r
+\r
+$letra = $input->get('letra');\r
+$palavraChave = $input->get('palavrachave');\r
+$especialidade = $input->get('especialidade');\r
+$procedencia = $input->get('procedencia');\r
+$sistema = $input->get('sistema');\r
+//$patologia = $input->get('patologia');\r
+$like = $input->get('pp');//0 - qualquer palavra (quebrar em array por espaços) / 1 - todas, não quebra nada\r
+$boneco = $input->get("boneco");\r
+$pagina = $input->get("pagina");\r
+if($pagina == ""){\r
+ $pagina = 1;\r
+}\r
+\r
+$total = 0;\r
+if($o_helper->hasFilter()){\r
+ if($o_helper->hasFilter(false)){\r
+ $base = '?palavrachave='.$palavraChave.'&especialidade='.$especialidade.'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco;\r
+ $rowsDiagnostico = $o_diagnostico->simpleSeach($palavraChave,$especialidade,$procedencia,$sistema,$patologia,$boneco);\r
+ if(($rowsDiagnostico->EOF) && ($palavraChave != '')){\r
+ $arr_palavras = $o_helper->findPalavraAproximada($palavraChave);\r
+ //print_r2($arr_palavras);\r
+ $segestoes = '';\r
+ if(sizeof($arr_palavras[0]) > 0){\r
+ for($x=0;$x<sizeof($arr_palavras[0]);$x++){\r
+ if($arr_palavras[0][$x] != $palavraChave){\r
+ $segestoes .= "<a class='atracoes' href='index.php?palavrachave=".$arr_palavras[0][$x].'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco."' alt='Refazer pesquisa utilizando a palavra ".$arr_palavras[0][$x]."'><b>".$arr_palavras[0][$x]."</b></a>, ";\r
+ }\r
+ }\r
+ if($segestoes != ""){\r
+ $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2);\r
+ }\r
+ }\r
+ $rowsDiagnostico = $o_diagnostico->complexSeach($arr_palavras,$procedencia,$sistema,$patologia,$boneco);\r
+ }\r
+ } else {\r
+ $base = '?letra='.$letra;\r
+ $rowsDiagnostico = $o_diagnostico->searchLetter($letra,$patologia);\r
+ }\r
+ $total = $rowsDiagnostico->recordCount();\r
+ $rowsDiagnostico->pagesize = $o_diagnostico->filtro_resultado;\r
+ $rowsDiagnostico->page($pagina);\r
+}\r
+\r
+$selected = 'necropsia';\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td width="375">\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=BUSCAR EM NECROPSIAS","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <? if(isset($rowsDiagnostico)){?>\r
+ <div>\r
+ <table cellspacing="0" cellpadding="0" width="360" style="border:1px solid #CCA365;">\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Listando: <?=$total;?> resultado<?=(($total > 1)?'s':'');?>.<br />\r
+ <? if($o_helper->hasFilter(false)){?>\r
+ <? if($palavraChave != ''){?>\r
+ <br />Palavra-chave: <b><?=$palavraChave;?></b>\r
+ <? }?>\r
+ <? if($especialidade != ''){?>\r
+ <br />Especialidade: <b><?=$arrEspecialidade[$especialidade];?></b>\r
+ <? }?>\r
+ <? if($procedencia != ''){?>\r
+ <br />Procedência: <b><?=$arrProcedencia[$procedencia];?></b>\r
+ <? }?>\r
+ <? if($sistema != ''){?>\r
+ <br />Sistema: <b><?=$arrSistema[$sistema];?></b>\r
+ <? }?>\r
+ <? if($boneco != ''){?>\r
+ <br />Topografia: <b><?=$o_helper->findTopografiaById($boneco);?></b>\r
+ <? }?>\r
+ <?if(isset($segestoes)){?>\r
+ <br /><?=$segestoes;?>\r
+ <?}?>\r
+ <? } else if($letra != ''){?>\r
+ Índice: <b><?=$letra;?></b>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ <? }?>\r
+ <div>\r
+ <form id="frmBusca" name="frmBusca" onsubmit="return false" action="index.php" method="get">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td style="padding-top:10px; padding-bottom:10px;">\r
+ <?=$o_html->getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <!--<div class="rdoPal">\r
+ <input type="radio" id="Palavra" name="palavra" value="1" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Qualquer palavra\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Palavra" name="palavra" value="1" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Todas palavras\r
+ </div>-->\r
+ <div class="rdoPal" style="float:right;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:20px; padding-bottom:15px;">\r
+ <a href="javascript: swapElement('tr_buscavancada');" class="underlaine2">Busca Avançada</a>\r
+ </td>\r
+ </tr>\r
+ <tr id="tr_buscavancada">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td width="141">\r
+ <?=$o_html->getBoneco('Boneco','TXT0','boneco');?>\r
+ </td>\r
+ <td>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrEspecialidade,'Especialidade','CMB0','especialidade',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrProcedencia,'Procedência','CMB0','procedencia',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear" style="text-align:left;padding-left:10px;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </div>\r
+ </td>\r
+ <td width="619" style="padding-left:15px;">\r
+ <? if(isset($rowsDiagnostico)){?>\r
+ <table cellspacing="0" cellpadding="0" width="100%>\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=RESULTADOS EM NECROPSIAS","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_diagnostico->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsDiagnostico->EOF){?>\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Nenhum registro encontrado.\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? } else {?>\r
+ <tr>\r
+ <td>\r
+ <?=$o_diagnostico->getResultado($base);?>\r
+ <?=$o_diagnostico->getOrdenar($base);?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <? while(!$rowsDiagnostico->EOF){\r
+ $url = ' onclick="javascript:url(\'view.php?id='.$input->encode($rowsDiagnostico->fields('id')).'\');" ';?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td style="padding-top:10px;">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td class="bold_444" style="cursor:pointer;"<?=$url;?>>\r
+ <?=$rowsDiagnostico->fields('nome');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td class="italic_444">\r
+ <?=$rowsDiagnostico->fields('especialidade');?><?=(($rowsDiagnostico->fields('cid10') == '')?'':' <span class="blue_normal">|</span> '.$rowsDiagnostico->fields('cid10'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:5px;padding-bottom:5px;" <?=$url;?>>\r
+ <?=$rowsDiagnostico->fields('texto');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:5px;padding-bottom:5px;">\r
+ <?=$o_diagnostico->getImgesRelacionadas($rowsDiagnostico->fields('id'),8);?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <img src="../../img/pt/bt/ver.jpg" style="cursor:pointer;" <?=$url;?> />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <? $rowsDiagnostico->moveNext();\r
+ }?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsDiagnostico->pagecount > 1){?>\r
+ <tr>\r
+ <td>\r
+ Páginas: <?\r
+ //total de paginas\r
+ $totalPage = $rowsDiagnostico->pagecount;\r
+ //pagina atual\r
+ $actualPage = $pagina;\r
+ //baseLink\r
+ $pageBaseLink = $base;\r
+ //nome do link da pagina (pagina=1)\r
+ $pageLinkName = 'pagina';\r
+ include('../../inc/structure/paginacao.php');\r
+ ?>\r
+ </td>\r
+ </tr>\r
+ <? }\r
+ }?>\r
+ </table>\r
+ <? } else {?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=ÍNDICE","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_diagnostico->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+$selected = 'diagnosticos';\r
+\r
+$load->config('classes/Diagnostico.php');\r
+$o_diagnostico = new Diagnostico();\r
+$rowDiagnostico = $o_diagnostico->findDiagnoticoById($input->get('id',true));\r
+if($rowDiagnostico->EOF){\r
+ redir('index.php');\r
+ die;\r
+}\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td>\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=DIAGNÓSTICOS","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td colspan="100%">\r
+ <div>\r
+ <b><?=$rowDiagnostico->fields('nome');?></b>\r
+ </div>\r
+ <div style="margin-top:3px; margin-bottom:3px;">\r
+ <i><?=$rowDiagnostico->fields('especialidade');?></i>\r
+ </div>\r
+ <? if($rowDiagnostico->fields('cid10') != ''){?>\r
+ <div>\r
+ <i><?=$rowDiagnostico->fields('cid10');?></i>\r
+ </div>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ <tr height="330">\r
+ <td width="410">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td style="padding-bottom:15px;padding-top:15px;">\r
+ <?=$rowDiagnostico->fields('texto');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="font-size:10px;">\r
+ <?=$o_diagnostico->orgaosrelacionados($rowDiagnostico->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:25px;">\r
+ <img src="../../img/pt/bt/voltar.jpg" <?=$o_html->alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/imagensrelacionadas.gif" <?=$o_html->alt('Imagens Relacionadas');?> />\r
+ </div>\r
+ <?=$o_diagnostico->getImgesRelacionadas($rowDiagnostico->fields('id'));?>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/casosdeestudorelacionados.gif" <?=$o_html->alt('Casos de Estudo Relacionados');?> />\r
+ </div>\r
+ <?=$o_diagnostico->casosdeestudorelacionados($rowDiagnostico->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+\r
+$load->config('classes/Orgao.php');\r
+$o_orgao = new Orgao();\r
+\r
+$arrGrupoOrgao = $o_helper->findGrupoOrgao(true);\r
+$arrSistema = $o_helper->findSistemas(true);\r
+\r
+$letra = $input->get('letra');\r
+$palavraChave = $input->get('palavrachave');\r
+$grupoorgao = $input->get('grupoorgao');\r
+$sistema = $input->get('sistema');\r
+$boneco = $input->get("boneco");\r
+$pagina = $input->get("pagina");\r
+if($pagina == ""){\r
+ $pagina = 1;\r
+}\r
+\r
+$total = 0;\r
+if($o_helper->hasFilter()){\r
+ if($o_helper->hasFilter(false)){\r
+ $base = '?palavrachave='.$palavraChave.'&grupoorgao='.$grupoorgao.'&sistema='.$sistema.'&boneco='.$boneco;\r
+ $rowsOrgao = $o_orgao->simpleSeach($palavraChave,$grupoorgao,$sistema,$boneco);\r
+ if(($rowsOrgao->EOF) && ($palavraChave != '')){\r
+ $arr_palavras = $o_helper->findPalavraAproximada($palavraChave);\r
+ \r
+ $segestoes = '';\r
+ if(sizeof($arr_palavras[0]) > 0){\r
+ for($x=0;$x<sizeof($arr_palavras[0]);$x++){\r
+ if($arr_palavras[0][$x] != $palavraChave){\r
+ $segestoes .= "<a class='atracoes' href='index.php?palavrachave=".$arr_palavras[0][$x].'&grupoorgao='.$grupoorgao.'&sistema='.$sistema.'&boneco='.$boneco."' alt='Refazer pesquisa utilizando a palavra ".$arr_palavras[0][$x]."'><b>".$arr_palavras[0][$x]."</b></a>, ";\r
+ }\r
+ }\r
+ if($segestoes != ""){\r
+ $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2);\r
+ }\r
+ }\r
+ $rowsOrgao = $o_orgao->complexSeach($arr_palavras,$grupoorgao,$sistema,$boneco);\r
+ }\r
+ } else {\r
+ $base = '?letra='.$letra;\r
+ $rowsOrgao = $o_orgao->searchLetter($letra);\r
+ }\r
+ $total = $rowsOrgao->recordCount();\r
+ $rowsOrgao->pagesize = $o_orgao->filtro_resultado;\r
+ $rowsOrgao->page($pagina);\r
+} else {\r
+ $rowsOrgao = $o_orgao->findAll();\r
+ $total = $rowsOrgao->recordCount();\r
+ $rowsOrgao->pagesize = $o_orgao->filtro_resultado;\r
+ $rowsOrgao->page($pagina);\r
+ $base = '?1=1';\r
+}\r
+\r
+$selected = 'orgaos';\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td width="375">\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=BUSCAR EM ÓRGÃOS","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <? if(isset($rowsOrgao)){?>\r
+ <div>\r
+ <table cellspacing="0" cellpadding="0" width="360" style="border:1px solid #CCA365;">\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Listando: <?=$total;?> resultado<?=(($total > 1)?'s':'');?>.<br />\r
+ <? if($o_helper->hasFilter(false)){?>\r
+ <? if($palavraChave != ''){?>\r
+ <br />Palavra-chave: <b><?=$palavraChave;?></b>\r
+ <? }?>\r
+ <? if($grupoorgao != ''){?>\r
+ <br />Topografia: <b><?=$arrGrupoOrgao[$grupoorgao];?></b>\r
+ <? }?>\r
+ <? if($sistema != ''){?>\r
+ <br />Sistema: <b><?=$arrSistema[$sistema];?></b>\r
+ <? }?>\r
+ <? if($boneco != ''){?>\r
+ <br />Topografia: <b><?=$o_helper->findTopografiaById($boneco);?></b>\r
+ <? }?>\r
+ <?if(isset($segestoes)){?>\r
+ <br /><?=$segestoes;?>\r
+ <?}?>\r
+ <? } else if($letra != ''){?>\r
+ Índice: <b><?=$letra;?></b>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ <? }?>\r
+ <div>\r
+ <form id="frmBusca" name="frmBusca" onsubmit="return false" action="index.php" method="get">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td style="padding-top:10px; padding-bottom:10px;">\r
+ <?=$o_html->getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <!--<div class="rdoPal">\r
+ <input type="radio" id="Palavra0" name="pp" value="0" />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Qualquer palavra\r
+ </div>\r
+ <div class="rdoPal">\r
+ <input type="radio" id="Palavra1" name="pp" value="1" checked />\r
+ </div>\r
+ <div class="rdoPal" style="padding-top:3px; color:#000000;">\r
+ Todas palavras\r
+ </div>-->\r
+ <div class="rdoPal" style="float:right;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:20px; padding-bottom:15px;">\r
+ <a href="javascript: swapElement('tr_buscavancada');" class="underlaine2">Busca Avançada</a>\r
+ </td>\r
+ </tr>\r
+ <tr id="tr_buscavancada" style="display:;">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td width="141">\r
+ <?=$o_html->getBoneco('Boneco','TXT0','boneco');?>\r
+ </td>\r
+ <td>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrGrupoOrgao,'Topografia','CMB0','grupoorgao',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear">\r
+ <?=$o_html->getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?>\r
+ </div>\r
+ <div class="tosear" style="text-align:left;padding-left:10px;">\r
+ <input type="image" src="../../img/pt/bt/ok.jpg" value="ok" onclick="javascript: sendFilter('frmBusca');" />\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </form>\r
+ </div>\r
+ </td>\r
+ <td width="619" style="padding-left:15px;">\r
+ <? if(isset($rowsOrgao)){?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=RESULTADOS EM ÓRGÃOS","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_orgao->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsOrgao->EOF){?>\r
+ <tr>\r
+ <td style="padding:10px;">\r
+ Nenhum registro encontrado.\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? } else {?>\r
+ <tr>\r
+ <td>\r
+ <?=$o_orgao->getResultado($base);?>\r
+ <?=$o_orgao->getOrdenar($base);?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <? $x = 0;\r
+ while(!$rowsOrgao->EOF){\r
+ if(($x != 0) && (($x%2) == 0)){\r
+ echo '</tr><tr>';\r
+ }?>\r
+ <td style="padding-top:10px;">\r
+ <div>\r
+ <table cellspacing="0" cellpadding="0" onclick="javascript: url('view.php?id=<?=$input->encode($rowsOrgao->fields('id'));?>');" style="cursor:pointer;">\r
+ <tr>\r
+ <td><?\r
+ $src = $o_orgao->getImage($rowsOrgao->fields('id'));\r
+ if($src == ''){\r
+ $src = '../../img/olho.jpg';\r
+ }\r
+ ?> <div style="width:86px; height:74px;">\r
+ <img src="<?=$src;?>" />\r
+ </div>\r
+ </td>\r
+ <td class="tddados" valign="middle">\r
+ <div><b><?=$rowsOrgao->fields('nome');?></b></div>\r
+ <div><?=$o_orgao->sistemasrelacionados($rowsOrgao->fields('id'));?></div>\r
+ <div style="margin-bottom:0px;"><?=$o_orgao->grupodeorgaorelacionados($rowsOrgao->fields('id'));?></div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ </td>\r
+ <? $rowsOrgao->moveNext();\r
+ $x++;\r
+ }?>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <? if($rowsOrgao->pagecount > 1){?>\r
+ <tr>\r
+ <td>\r
+ Páginas: <?\r
+ //total de paginas\r
+ $totalPage = $rowsOrgao->pagecount;\r
+ //pagina atual\r
+ $actualPage = $pagina;\r
+ //baseLink\r
+ $pageBaseLink = $base;\r
+ //nome do link da pagina (pagina=1)\r
+ $pageLinkName = 'pagina';\r
+ include('../../inc/structure/paginacao.php');\r
+ ?>\r
+ </td>\r
+ </tr>\r
+ <? }\r
+ }?>\r
+ </table>\r
+ <? } else {?>\r
+ <table cellspacing="0" cellpadding="0" width="100%">\r
+ <tr>\r
+ <td>\r
+ <?swf("../../swf/common/subtitulo.swf",330,30,"txt=ÍNDICE","","transparent");?>\r
+ <div class="divLnAm" style="margin-bottom:10px;"> </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td>\r
+ <?=$o_orgao->getAlfabeto();;?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+include("../../inc/structure/posApp.php");\r
+$selected = 'orgaos';\r
+$load->system('functions/text.php');\r
+\r
+$load->config('classes/Orgao.php');\r
+$o_orgao = new Orgao();\r
+$rowOrgao = $o_orgao->findOrgaoById($input->get('id',true));\r
+if($rowOrgao->EOF){\r
+ redir('index.php');\r
+ die;\r
+}\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html>\r
+ <head>\r
+ <? include("../../inc/structure/header.php"); ?>\r
+ <script src="../../../_system/js/popup.js" type="text/javascript"></script>\r
+ <title><?= $cfg["site_title"]; ?></title>\r
+ <script>\r
+ function zoom(tmp_w,tmp_h){\r
+ var p = new Popup(tmp_w,tmp_h);\r
+ p.template = 1;\r
+ p.overflow = "hidden";\r
+ p.open("../../inc/structure/popup_zoom1.php?path=../../../upload/sis_orgao/IDIDID.jpg&id=<?=$input->encode($rowOrgao->fields('id'));?>");\r
+ }\r
+ </script>\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="100%" height="100%">\r
+ <?include('../../inc/structure/topo.php');?>\r
+ <tr height="100%">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td>\r
+ <div>\r
+ <?swf("../../swf/common/titulo.swf",330,30,"txt=ÓRGÃOS","","transparent");?>\r
+ </div>\r
+ <br /><br />\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td colspan="100%">\r
+ <div>\r
+ <b><?=$rowOrgao->fields('nome');?></b>\r
+ </div>\r
+ <? if($rowOrgao->fields('pagina') != ''){?>\r
+ <div style="margin-top:3px; margin-bottom:3px;">\r
+ <i>Mais informações: </i><a href="<?=formatUrlComplete($rowOrgao->fields('pagina'));?>" target="_blank"><?=$rowOrgao->fields('pagina');?></a>\r
+ </div>\r
+ <? }?>\r
+ </td>\r
+ </tr>\r
+ <tr height="330">\r
+ <td width="410">\r
+ <table cellspacing="0" cellpadding="0">\r
+ <tr>\r
+ <td colspan="2" style="padding-bottom:15px;padding-top:15px;padding-top:15px;">\r
+ <?=nl2br($rowOrgao->fields('texto'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-right:10px;padding-bottom:20px;">\r
+ <? $src = $o_orgao->getImage($rowOrgao->fields('id'),'m');\r
+ $func = '';\r
+ if($src == ''){\r
+ $src = '../../img/olho_g.jpg';\r
+ } else {\r
+ $img = imagecreatefromjpeg('../../../upload/sis_orgao/'.$rowOrgao->fields('id').'.jpg');\r
+ $w = imagesx($img);\r
+ $h = imagesy($img);\r
+ $func = ' onclick="javascript: zoom('.$w.','.$h.');" style="cursor:pointer;" ';\r
+ }\r
+ \r
+ ?>\r
+ <img src="<?=$src;?>" <?=$func;?>/>\r
+ </td>\r
+ <td style="padding-bottom:20px; font-size:11px;" width="100%">\r
+ <?=$o_orgao->sistemasrelacionados($rowOrgao->fields('id'));?><br /><br />\r
+ <?=$o_orgao->grupodeorgaorelacionados($rowOrgao->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td colspan="2" style="border-top: 1px solid #DABA89; padding-top:10px;">\r
+ <div style="padding-bottom:20px;">\r
+ <img src="../../img/pt/tit/imagensrelacionadas.gif" <?=$o_html->alt('Imagens Relacionadas');?> />\r
+ </div>\r
+ <div>\r
+ <?=$o_orgao->getImgesRelacionadas($rowOrgao->fields('id'));?>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding-top:25px;">\r
+ <img src="../../img/pt/bt/voltar.jpg" <?=$o_html->alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/diagnosticosrelacionados.gif" <?=$o_html->alt('Diagnósticos Relacionados');?> />\r
+ </div>\r
+ <?=$o_orgao->diagnosticosrelacionados($rowOrgao->fields('id'));?>\r
+ </td>\r
+ <td style="border-left:1px solid #DABA89; padding-left:10px;" width="280">\r
+ <div style="margin-bottom:15px;">\r
+ <img src="../../img/pt/tit/casosdeestudorelacionados.gif" <?=$o_html->alt('Casos de Estudo Relacionados');?> />\r
+ </div>\r
+ <?=$o_orgao->casosdeestudorelacionados($rowOrgao->fields('id'));?>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <?include('../../inc/structure/rodape.php');?>\r
+ </table>\r
+ </body>\r
+</html>\r
+<? include("../../inc/structure/footer.php"); ?>
\ No newline at end of file
--- /dev/null
+html,body {\r
+ width:100%;\r
+ height:100%;\r
+ margin:0px;\r
+ padding:0px;\r
+ background:url(../../img/common/bg/default.jpg) top left repeat-x #FFFFFF;\r
+}\r
+div{\r
+ margin:auto;\r
+}\r
+table {\r
+ font-family:Tahoma, Geneva, sans-serif;\r
+ font-size:11px;\r
+ color:#353535;\r
+}\r
+td {\r
+ vertical-align:top;\r
+ font-size:11px;\r
+}\r
+img {\r
+ border:0px;\r
+}\r
+\r
+p {\r
+ margin:4px;\r
+}\r
+\r
+a {\r
+ color:#4E4E4E;\r
+ text-decoration:none;\r
+}\r
+\r
+a:hover {\r
+ color:#8D8D8D;\r
+ text-decoration:none;\r
+}\r
+td.ufcspa {\r
+ padding-right:24px; padding-top:15px;\r
+}\r
+td.ufcspa div{\r
+ width:86px; height:84px; background:url(../../img/pt/ufcspa.jpg) center center no-repeat; cursor:pointer;\r
+}\r
+div.lftsia {\r
+ width:6px; height:112px; background:url(../../img/common/bg/topleft.gif) top left no-repeat;\r
+}\r
+div.rgtsia {\r
+ width:6px; height:112px; background:url(../../img/common/bg/topright.gif) top left no-repeat;\r
+}\r
+td.cntsia {\r
+ background:url(../../img/common/bg/topcenter.gif) top left repeat-x; padding-top:45px; padding-left:25px; padding-right:25px;\r
+}\r
+td.cntsia div{\r
+ width:242px; height:40px; background:url(../../img/pt/tit/siap.png) center center no-repeat #22588C; cursor:pointer;\r
+}\r
+td.topsep {\r
+ padding-left:10px; padding-right:10px; padding-top:25px;\r
+}\r
+td.topsep div{\r
+ width:1px; height:69px; background-color:#22588C; font-size:1px\r
+}\r
+.tblMenu td{\r
+ padding-left:10px;\r
+ padding-right:10px;\r
+ cursor:pointer;\r
+ height:50px;\r
+}\r
+.rdoPal {\r
+ float:left;\r
+ vertical-align:middle;\r
+ color:#FFFFFF;\r
+ font-family:Tahoma;\r
+}\r
+.divlncn{\r
+ height:20px;font-size:1px;border-bottom:1px solid #b1b1b1;margin-bottom:20px;\r
+}\r
+.divLnAm {\r
+ height:8px;font-size:1px;border-bottom:1px solid #cca365;margin-bottom:20px;\r
+}\r
+.subaztit{\r
+ font-size:11px;font-weight:bold;color:#194c7f;\r
+}\r
+.txtdivin {\r
+ margin-top:11px;margin-bottom:11px;\r
+}\r
+input.input {\r
+ vertical-align:top;\r
+ padding:4px;\r
+ color:#353535;\r
+ font-size:11px;\r
+ font-family:Tahoma;\r
+}\r
+textarea.input {\r
+ vertical-align:top;\r
+ padding:4px;\r
+ color:#353535;\r
+ font-size:11px;\r
+ font-family:Tahoma;\r
+ overflow:auto;\r
+}\r
+a.underlaine{\r
+ font-family:Tahoma;\r
+ color:#194c7f;\r
+ font-size:11px;\r
+ text-decoration:underline;\r
+}\r
+a:hover.underlaine{\r
+ text-decoration:none;\r
+}\r
+a.underlaine2{\r
+ font-family:Tahoma;\r
+ color:#444444;\r
+ font-size:11px;\r
+ font-weight:bold;\r
+ text-decoration:underline;\r
+}\r
+a:hover.underlaine2{\r
+ text-decoration:none;\r
+}\r
+.nletra{\r
+ font-family:Tahoma;\r
+ color:#666666;\r
+ font-weight:bold;\r
+ font-size:11px;\r
+ text-decoration:underline;\r
+}\r
+a.ltra{\r
+ font-family:Tahoma;\r
+ color:#CCA365;\r
+ font-weight:bold;\r
+ font-size:11px;\r
+ text-decoration:underline;\r
+ padding-left:3px;\r
+ padding-right:3px;\r
+}\r
+a:hover.ltra{\r
+ padding-left:3px;\r
+ padding-right:3px;\r
+ background:#FFFFFF;\r
+ text-decoration:none;\r
+}\r
+div.tosear {\r
+ width:100%;\r
+ margin-top:10px;\r
+ text-align:right;\r
+}\r
+div.resultados {\r
+ float:left;\r
+ padding-top:10px;\r
+}\r
+div.ordenar {\r
+ float:right;\r
+ margin-top:10px;\r
+}\r
+td.tddados {\r
+ vertical-align:middle;\r
+ padding-left:10px;\r
+}\r
+td.tddados div{\r
+ margin-bottom:10px;\r
+}\r
+.bold_444 {\r
+ color:#444444;\r
+ font-weight:bold;\r
+}\r
+.italic_444 {\r
+ color:#444444;\r
+ font-style:italic;\r
+}\r
+.blue_normal {\r
+ color:#194C7F;\r
+ font-style:normal;\r
+}\r
+.divlist {\r
+ background:url(../../img/common/bg/dot.gif) center left no-repeat; padding-left:15px;\r
+}\r
+div.nomeComentario {\r
+ font-size:11px;\r
+ font-family:Tahoma;\r
+ color:#194c7f;\r
+ font-style:italic;\r
+ padding-top:10px;\r
+ float:left;\r
+}\r
+div.excluirComentario {\r
+ font-size:11px;\r
+ font-family:Tahoma;\r
+ color:#194c7f;\r
+ font-style:italic;\r
+ padding-top:10px;\r
+ float:right;\r
+}\r
+div.textoComentario {\r
+ width:100%;\r
+ font-size:11px;\r
+ font-family:Tahoma;\r
+ color:#353535;\r
+ font-style:none;\r
+ padding-top:10px;\r
+ padding-bottom:10px;\r
+ float:left;\r
+}\r
+span.saudavel {\r
+ font-size:9px;\r
+ color:ForestGreen;\r
+}
\ No newline at end of file
--- /dev/null
+div.jqZoomTitle\r
+{\r
+ z-index:5000;\r
+ text-align:center;\r
+ font-size:11px;\r
+ font-family:Tahoma;\r
+ height:16px;\r
+ padding-top:2px;\r
+ position:absolute;\r
+ top: 0px;\r
+ left: 0px;\r
+ width: 100%;\r
+ color: #FFF;\r
+ background: #999;\r
+\r
+}\r
+\r
+.jqZoomPup\r
+{\r
+ overflow:hidden;\r
+ background-color: #FFF;\r
+ -moz-opacity:0.6;\r
+ opacity: 0.6;\r
+ filter: alpha(opacity = 60);\r
+ z-index:10;\r
+ border-color:#c4c4c4;\r
+ border-style: solid;\r
+ cursor:crosshair;\r
+}\r
+\r
+.jqZoomPup img\r
+{\r
+ border: 0px;\r
+}\r
+\r
+.preload{\r
+ -moz-opacity:0.8;\r
+ opacity: 0.8;\r
+ filter: alpha(opacity = 80);\r
+ color: #333;\r
+ font-size: 12px;\r
+ font-family: Tahoma;\r
+ text-decoration: none;\r
+ border: 1px solid #CCC;\r
+ background-color: white;\r
+ padding: 8px;\r
+ text-align:center;\r
+ background-image: url(../images/zoomloader.gif);\r
+ background-repeat: no-repeat;\r
+ background-position: 43px 30px;\r
+ width:90px;\r
+ * width:100px;\r
+ height:43px;\r
+ *height:55px;\r
+ z-index:10;\r
+ position:absolute;\r
+ top:3px;\r
+ left:3px;\r
+\r
+}\r
+\r
+.jqZoomWindow\r
+{\r
+ border: 1px solid #999;\r
+ background-color: #FFF;\r
+}\r
+\r
+\r
--- /dev/null
+var baseSrc = "../../img/pt/menu/";\r
+function swapM(menu,focus){\r
+ var img = document.getElementById("img_"+menu);\r
+ if(img){\r
+ if(focus){\r
+ img.src = baseSrc+menu+"_over.jpg";\r
+ } else {\r
+ img.src = baseSrc+menu+".jpg";\r
+ }\r
+ }\r
+}\r
+function swapI(obj,focus){ \r
+ if(focus){\r
+ if(obj.value == obj.attributes["label"].value){\r
+ obj.value = "";\r
+ }\r
+ } else {\r
+ if(obj.value.trim() == ""){\r
+ obj.value = obj.attributes["label"].value;\r
+ }\r
+ }\r
+}\r
+function swapP(obj,focus){\r
+ if(focus){\r
+ var pass = document.getElementById(obj.attributes["parent"].value);\r
+ if(pass){\r
+ obj.innerHTML = "";\r
+ pass.focus();\r
+ }\r
+ } else {\r
+ if(obj.value == ""){\r
+ var div = document.getElementById("div"+obj.id);\r
+ if(div){\r
+ div.innerHTML = obj.attributes["label"].value;\r
+ }\r
+ }\r
+ }\r
+}\r
+function swapElement(tmp_id){\r
+ var obj = document.getElementById(tmp_id);\r
+ if(obj){\r
+ if(obj.style.display == ''){\r
+ obj.style.display = 'none';\r
+ } else {\r
+ obj.style.display = '';\r
+ }\r
+ }\r
+}\r
+function url(url){\r
+ window.location = url;\r
+}\r
+function sendFilter(tmp_form){\r
+ var ok = false;\r
+ \r
+ var palavrachave = document.getElementById('Palavra-chave_TXT0');\r
+ var codigo = document.getElementById('Código_TXT0');\r
+ var topografia = document.getElementById('Topografia_CMB0');\r
+ var procedencia = document.getElementById('Procedência_CMB0');\r
+ var sistema = document.getElementById('Sistema_CMB0');\r
+ var patologia = document.getElementById('Patologia_CMB0');\r
+ var especialidade = document.getElementById('Especialidade_CMB0');\r
+ var professor = document.getElementById('Professor_CMB0');\r
+ var boneco = document.getElementById('Boneco_TXT0');\r
+ \r
+ if(palavrachave){\r
+ if((palavrachave.value.trim() != '') && (palavrachave.value.trim() != palavrachave.defaultValue)){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ if(topografia){\r
+ if(topografia.value != ''){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ if(codigo){\r
+ if((codigo.value.trim() != '') && (codigo.value.trim() != codigo.defaultValue)){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ if(procedencia){\r
+ if(procedencia.value != ''){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ if(sistema){\r
+ if(sistema.value != ''){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ if(patologia){\r
+ if(patologia.value != ''){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ if(especialidade){\r
+ if(especialidade.value != ''){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ if(professor){\r
+ if(professor.value != ''){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ if(boneco){\r
+ if(boneco.value != ''){\r
+ ok = true;\r
+ }\r
+ }\r
+ \r
+ \r
+ if(ok){\r
+ if(palavrachave.value == palavrachave.defaultValue){\r
+ palavrachave.value = '';\r
+ }\r
+ return f.send(tmp_form);\r
+ } else {\r
+ alert('Selecione ao menos um filtro para fazer sua pesquisa.');\r
+ return;\r
+ }\r
+}\r
+function openBoneco(name){\r
+ var p = new Popup(570,580);\r
+ p.overflow = 'hidden';\r
+ p.position = 'fixed';\r
+ p.onLoad = function (){\r
+ $(function() {\r
+ $('#hightlightall').mouseover(function(e) {\r
+ $($$('img_boneco').useMap+' area').mouseover();\r
+ }).mouseout(function(e) {\r
+ $($$('img_boneco').useMap+' area').mouseout();\r
+ }).click(function(e) { e.preventDefault(); });\r
+ });\r
+ }\r
+ p.open('../../inc/structure/grupoorgao.php?name='+name);\r
+}\r
+function trocaCamada(id_camada){\r
+ $$('img_boneco').useMap = '#GrupoOrgao'+id_camada;\r
+ $(function() {\r
+ $('#img_boneco').maphilight({strokeColor: '22588c'});\r
+ });\r
+}\r
+function selectBoneco(id,nome,sufix){\r
+ var elms = document.getElementsByName(sufix);\r
+ if(elms.length == 1){\r
+ elms[0].value = id;\r
+ }\r
+ $$('results_'+sufix).innerHTML = 'Selecionado: '+nome;\r
+ Popup_atual.close();\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * JQZoom Evolution 1.0.1 - Javascript Image magnifier\r
+ *\r
+ * Copyright (c) Engineer Renzi Marco(www.mind-projects.it)\r
+ *\r
+ * $Date: 12-12-2008\r
+ *\r
+ * ChangeLog:\r
+ * \r
+ * $License : GPL,so any change to the code you should copy and paste this section,and would be nice to report this to me(renzi.mrc@gmail.com).\r
+ */\r
+(function($)\r
+{\r
+ $.fn.jqzoom = function(options)\r
+ {\r
+ var settings = {\r
+ zoomType: 'standard', //standard/reverse/innerzoom\r
+ zoomWidth: 200, //zoomed width default width\r
+ zoomHeight: 200, //zoomed div default width\r
+ xOffset: 10, //zoomed div default offset\r
+ yOffset: 0,\r
+ position: "right" ,//zoomed div default position,offset position is to the right of the image\r
+ lens:true, //zooming lens over the image,by default is 1;\r
+ lensReset : false,\r
+ imageOpacity: 0.2,\r
+ title : true,\r
+ alwaysOn: false,\r
+ showEffect: 'show',\r
+ hideEffect: 'hide',\r
+ fadeinSpeed: 'fast',\r
+ fadeoutSpeed: 'slow',\r
+ preloadImages :true,\r
+ showPreload: true,\r
+ preloadText : 'Loading zoom',\r
+ preloadPosition : 'center' //bycss\r
+ };\r
+\r
+ //extending options\r
+ options = options || {};\r
+ $.extend(settings, options);\r
+\r
+\r
+ return this.each(function()\r
+ {\r
+ var a = $(this);\r
+ var aTitle = a.attr('title'); //variabile per memorizzare il titolo href\r
+ $(a).removeAttr('title');\r
+ $(a).css('outline-style','none');\r
+\r
+\r
+ var img = $("img", this);\r
+ var imageTitle = img.attr('title');\r
+ img.removeAttr('title'); //variabile per memorizzare il titolo immagine\r
+\r
+\r
+ var smallimage = new Smallimage( img );\r
+ var smallimagedata = {};\r
+ //imageborder\r
+ var btop = 0;\r
+ var bleft = 0;\r
+\r
+ var loader = null; //variabile per memorizzare oggetto loader\r
+ loader = new Loader();\r
+\r
+ var ZoomTitle = (trim(aTitle).length > 0) ? aTitle :\r
+ (trim(imageTitle).length > 0) ? imageTitle : null; //setting zoomtitle\r
+ var ZoomTitleObj = new zoomTitle();\r
+\r
+ var largeimage = new Largeimage( a[0].href );\r
+\r
+ var lens = new Lens();\r
+ var lensdata = {};\r
+ //lensborder\r
+\r
+\r
+\r
+ var largeimageloaded = false;\r
+ var scale = {}; //rapporto tra immagine grande e piccola scale.x/scale.y\r
+ var stage = null; // quadrato che mostra l'immagine ingrandita\r
+ var running = false; // running = true quando si verifica l'evento che mostra lo zoom(adesso mouseover).\r
+ var mousepos = {};\r
+ var firstime = 0;\r
+ var preloadshow = false;\r
+ var isMouseDown = false;\r
+ var dragstatus = false\r
+ //loading smallimagedata\r
+ smallimage.loadimage();\r
+\r
+ //ritorna false al click dell href\r
+ $(this).click(function(){return false;});\r
+\r
+ //se settato alwaysOn attivo lo Zoom e lo mostro.\r
+\r
+ //attivo al mouseover\r
+ $(this).hover(function(e)\r
+ {\r
+ mousepos.x = e.pageX;\r
+ mousepos.y = e.pageY;\r
+ activate();\r
+ },function()\r
+ {\r
+ deactivate();\r
+ });\r
+\r
+\r
+ //ALWAYS ON\r
+ if(settings.alwaysOn)\r
+ {\r
+ setTimeout(function(){activate();},150);\r
+ }\r
+\r
+\r
+ function activate()\r
+ {\r
+\r
+ if ( !running ) {\r
+\r
+ //finding border\r
+ smallimage.findborder();\r
+\r
+ running = true;\r
+\r
+ //rimuovo il titolo al mouseover\r
+ imageTitle = img.attr('title');\r
+ img.removeAttr('title');\r
+ aTitle = a.attr('title');\r
+ $(a).removeAttr('title');\r
+\r
+ //se non cè creo l'oggetto largeimage\r
+ if (!largeimage || $.browser.safari) {\r
+ largeimage = new Largeimage( a[0].href );\r
+ }\r
+\r
+ //se l'immagine grande non è stata caricata la carico\r
+ if(!largeimageloaded || $.browser.safari)\r
+ {\r
+ largeimage.loadimage();\r
+ }else\r
+ {\r
+ //after preload\r
+ if(settings.zoomType != 'innerzoom')\r
+ {\r
+ stage = new Stage();\r
+ stage.activate();\r
+ }\r
+ lens = new Lens;\r
+ lens.activate();\r
+ }\r
+\r
+ //hack per MAC\r
+ /* if($.browser.safari)\r
+ {\r
+ if(settings.zoomType != 'innerzoom') //se innerzoom non mostro la finestra dello zoom\r
+ {\r
+ stage = new Stage();\r
+ stage.activate();\r
+ }\r
+ if($('div.jqZoomPup').length <= 0)\r
+ {\r
+ lens = new Lens();\r
+ }\r
+ //if(settings.zoomType == 'innerzoom'){lens = new Lens()};\r
+ lens.activate();\r
+ (settings.alwaysOn) ? lens.center() : lens.setposition(null);\r
+ }\r
+ */\r
+ a[0].blur();\r
+ //alert($('div.jqZoomPup').length);\r
+ return false;\r
+ }\r
+\r
+\r
+\r
+\r
+ }\r
+\r
+ function deactivate()\r
+ {\r
+ if(settings.zoomType == 'reverse' && !settings.alwaysOn)\r
+ {\r
+ img.css({'opacity' : 1});\r
+ }\r
+\r
+ if(!settings.alwaysOn)\r
+ {\r
+ //resetting parameters\r
+ running = false;\r
+ largeimageloaded = false;\r
+ $(lens.node).unbind('mousemove');\r
+ lens.remove();\r
+ if($('div.jqZoomWindow').length >0)\r
+ {\r
+ stage.remove();\r
+ }\r
+ if($('div.jqZoomTitle').length > 0)\r
+ {\r
+ ZoomTitleObj.remove();\r
+ }\r
+ //resetting title\r
+ img.attr('title',imageTitle);\r
+ a.attr('title',aTitle);\r
+ $().unbind();\r
+\r
+ a.unbind('mousemove');\r
+ //resetto il parametro che mi dice che è la prima volta che mostor lo zoom\r
+ firstime = 0;\r
+ //remove ieiframe\r
+ if(jQuery('.zoom_ieframe').length > 0)\r
+ {\r
+ jQuery('.zoom_ieframe').remove();\r
+ }\r
+ }else\r
+ {\r
+ if(settings.lensReset)\r
+ {\r
+ switch(settings.zoomType)\r
+ {\r
+ case 'innerzoom':\r
+ largeimage.setcenter();\r
+ break;\r
+ default:\r
+ lens.center();\r
+ break;\r
+ }\r
+ }\r
+ }\r
+\r
+ //non so se serve da provare\r
+ if(settings.alwaysOn)\r
+ {\r
+ activate();\r
+ }\r
+ };\r
+\r
+\r
+\r
+\r
+\r
+ //smallimage\r
+ function Smallimage( image )\r
+ {\r
+ this.node = image[0];\r
+\r
+ this.loadimage = function() {\r
+ this.node.src = image[0].src;\r
+ };\r
+ this.findborder = function()\r
+ {\r
+ var bordertop = '';\r
+ bordertop = $(img).css('border-top-width');\r
+ btop = '';\r
+ var borderleft = '';\r
+ borderleft = $(img).css('border-left-width');\r
+ bleft = '';\r
+ /*if($.browser.msie)\r
+ {\r
+ var temp = bordertop.split(' ');\r
+\r
+ bordertop = temp[1];\r
+ var temp = borderleft.split(' ');\r
+ borderleft = temp[1];\r
+ }*/\r
+\r
+ if(bordertop)\r
+ {\r
+ for(i=0;i<3;i++)\r
+ {\r
+ var x = [];\r
+ x = bordertop.substr(i,1);\r
+\r
+ if(isNaN(x) == false)\r
+ {\r
+ btop = btop +''+ bordertop.substr(i,1);\r
+ }else\r
+ {\r
+ break;\r
+ }\r
+ }\r
+ }\r
+\r
+ if(borderleft)\r
+ {\r
+ for(i=0;i<3;i++)\r
+ {\r
+ if(!isNaN(borderleft.substr(i,1)))\r
+ {\r
+ bleft = bleft + borderleft.substr(i,1)\r
+ }else\r
+ {\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ btop = (btop.length > 0) ? eval(btop) : 0;\r
+ bleft = (bleft.length > 0) ? eval(bleft) : 0;\r
+\r
+\r
+ }\r
+ this.node.onload = function()\r
+ {\r
+ //setto il cursor e la posizione dell'href\r
+\r
+\r
+ a.css({'cursor':'crosshair','display':'block'});\r
+\r
+ if(a.css('position')!= 'absolute' && a.parent().css('position'))\r
+ {\r
+ a.css({'cursor':'crosshair','position':'relative','display':'block'});\r
+ }\r
+ if(a.parent().css('position') != 'absolute')\r
+ {\r
+ a.parent().css('position','relative');\r
+ //a.css('position','relative');\r
+ }\r
+ else{\r
+ //a.css('position','relative');\r
+ }\r
+ if($.browser.safari || $.browser.opera)\r
+ {\r
+ $(img).css({position:'absolute',top:'0px',left:'0px'});\r
+ }\r
+ /*if(a.css('position')!= 'absolute' && a.parent().css('position'))\r
+ {\r
+ a.css({'cursor':'crosshair','position':'relative','display':'block'});\r
+ }\r
+ if(a.parent().css('position') != 'absolute')\r
+ {\r
+ alert('in');\r
+ a.parent().css('position','relative');\r
+ //a.css('position','relative');\r
+ }\r
+ else{\r
+ //a.css('position','relative');\r
+ }*/\r
+\r
+\r
+\r
+ /*\r
+ if(a.parent().css('position') != 'relative' && a.css('position') != 'absolute')\r
+ {\r
+ a.css({'cursor':'crosshair','position':'relative','display':'block'});\r
+ }*/\r
+\r
+ //al docuemnt ready viene caricato l'src quindi viene azionato l'onload e carico tutti i dati\r
+ smallimagedata.w = $( this ).width();\r
+ smallimagedata.h = $( this ).height();\r
+\r
+\r
+ //non viene fatta assegnazione alla variabile globale\r
+ smallimagedata.h = $( this ).height();\r
+ smallimagedata.pos = $( this ).offset();\r
+ smallimagedata.pos.l = $( this ).offset().left;\r
+ smallimagedata.pos.t = $( this ).offset().top;\r
+ smallimagedata.pos.r = smallimagedata.w + smallimagedata.pos.l;\r
+ smallimagedata.pos.b = smallimagedata.h + smallimagedata.pos.t;\r
+\r
+ //per sicurezza setto l'altezza e la width dell'href\r
+ a.height(smallimagedata.h);\r
+ a.width(smallimagedata.w);\r
+\r
+\r
+ //PRELOAD IMAGES\r
+ if(settings.preloadImages)\r
+ {\r
+ largeimage.loadimage();\r
+ }\r
+\r
+\r
+\r
+ };\r
+\r
+\r
+\r
+ return this;\r
+ };\r
+\r
+\r
+\r
+ //Lens\r
+ function Lens()\r
+ {\r
+\r
+\r
+ //creating element and adding class\r
+ this.node = document.createElement("div");\r
+ $(this.node).addClass('jqZoomPup');\r
+\r
+ this.node.onerror = function() {\r
+ $( lens.node ).remove();\r
+ lens = new Lens();\r
+ lens.activate() ;\r
+ };\r
+\r
+\r
+\r
+\r
+ //funzione privata per il caricamento dello zoom\r
+ this.loadlens = function()\r
+ {\r
+\r
+\r
+ switch(settings.zoomType)\r
+ {\r
+ case 'reverse':\r
+ this.image = new Image();\r
+ this.image.src = smallimage.node.src; // fires off async\r
+ this.node.appendChild( this.image );\r
+ $( this.node ).css({'opacity' : 1});\r
+ break;\r
+ case 'innerzoom':\r
+\r
+ this.image = new Image();\r
+ this.image.src = largeimage.node.src; // fires off async\r
+ this.node.appendChild( this.image );\r
+ $( this.node ).css({'opacity' : 1});\r
+ break\r
+ default:\r
+ break;\r
+ }\r
+\r
+\r
+\r
+ switch(settings.zoomType)\r
+ {\r
+ case 'innerzoom':\r
+ lensdata.w = smallimagedata.w;\r
+ lensdata.h = smallimagedata.h;\r
+ break;\r
+ default:\r
+ lensdata.w = (settings.zoomWidth)/scale.x;\r
+ lensdata.h = (settings.zoomHeight)/scale.y;\r
+ break;\r
+ }\r
+\r
+ $( this.node ).css({\r
+ width: lensdata.w + 'px',\r
+ height: lensdata.h + 'px',\r
+ position: 'absolute',\r
+ /*cursor: 'crosshair',*/\r
+ display: 'none',\r
+ //border: '1px solid blue'\r
+ borderWidth: 1+'px'\r
+ });\r
+ a.append(this.node);\r
+ }\r
+ return this;\r
+ };\r
+\r
+ Lens.prototype.activate = function()\r
+ {\r
+ //carico la lente\r
+ this.loadlens();\r
+\r
+ switch(settings.zoomType)\r
+ {\r
+ case 'reverse':\r
+ img.css({'opacity' : settings.imageOpacity});\r
+\r
+ (settings.alwaysOn) ? lens.center() : lens.setposition(null);\r
+ //lens.center();\r
+ //bindo ad a il mousemove della lente\r
+ a.bind( 'mousemove', function(e)\r
+ {\r
+ mousepos.x = e.pageX;\r
+ mousepos.y = e.pageY;\r
+ lens.setposition( e );\r
+ });\r
+ break;\r
+ case 'innerzoom':\r
+\r
+ // lens = new Lens();\r
+ // lens.activate();\r
+\r
+ $( this.node ).css({top : 0 ,left: 0});\r
+ if(settings.title)\r
+ {\r
+ ZoomTitleObj.loadtitle();\r
+ }\r
+\r
+ largeimage.setcenter();\r
+\r
+ a.bind( 'mousemove', function(e)\r
+ {\r
+ mousepos.x = e.pageX;\r
+ mousepos.y = e.pageY;\r
+ largeimage.setinner( e );\r
+\r
+ /*if(settings.zoomType == 'innerzoom' && running)\r
+ {\r
+ $(a).mousemove(function(){\r
+ if($('div.jqZoomPup').length <= 0)\r
+ {\r
+ lens = new Lens();\r
+ lens.activate();\r
+ }\r
+ });\r
+ }*/\r
+\r
+ /*if($('div.jqZoomPup').length <= 0)\r
+ {\r
+ lens = new Lens();\r
+ lens.activate();\r
+ }*/\r
+\r
+ });\r
+ break;\r
+ default:\r
+ /*$(document).mousemove(function(e){\r
+ if(isMouseDown && dragstatus != false){\r
+ lens.setposition( e );\r
+ }\r
+ });\r
+ lens.center()\r
+\r
+\r
+ dragstatus = 'on'\r
+ $(document).mouseup(function(e){\r
+ if(isMouseDown && dragstatus != false){\r
+ isMouseDown = false;\r
+ dragstatus = false;\r
+\r
+ }\r
+ });\r
+\r
+ $(this.node).mousedown(function(e){\r
+ $('div.jqZoomPup').css("cursor", "move");\r
+ $(this.node).css("position", "absolute");\r
+\r
+ // set z-index\r
+ $(this.node).css("z-index", parseInt( new Date().getTime()/1000 ));\r
+ if($.browser.safari)\r
+ {\r
+ $(a).css("cursor", "move");\r
+ }\r
+ isMouseDown = true;\r
+ dragstatus = 'on';\r
+ lens.setposition( e );\r
+ });\r
+ */\r
+\r
+\r
+ (settings.alwaysOn) ? lens.center() : lens.setposition(null);\r
+\r
+ //bindo ad a il mousemove della lente\r
+ $(a).bind( 'mousemove', function(e)\r
+ {\r
+\r
+ mousepos.x = e.pageX;\r
+ mousepos.y = e.pageY;\r
+ lens.setposition( e );\r
+ });\r
+\r
+ break;\r
+ }\r
+\r
+\r
+ return this;\r
+ };\r
+\r
+ Lens.prototype.setposition = function( e)\r
+ {\r
+\r
+\r
+ if(e)\r
+ {\r
+ mousepos.x = e.pageX;\r
+ mousepos.y = e.pageY;\r
+ }\r
+\r
+ if(firstime == 0)\r
+ {\r
+ var lensleft = (smallimagedata.w)/2 - (lensdata.w)/2 ;\r
+ var lenstop = (smallimagedata.h)/2 - (lensdata.h)/2 ;\r
+ //ADDED\r
+\r
+ $('div.jqZoomPup').show()\r
+ if(settings.lens)\r
+ {\r
+ this.node.style.visibility = 'visible';\r
+ }\r
+ else\r
+ {\r
+ this.node.style.visibility = 'hidden';\r
+ $('div.jqZoomPup').hide();\r
+ }\r
+ //ADDED\r
+ firstime = 1;\r
+\r
+ }else\r
+ {\r
+ var lensleft = mousepos.x - smallimagedata.pos.l - (lensdata.w)/2 ;\r
+ var lenstop = mousepos.y - smallimagedata.pos.t -(lensdata.h)/2 ;\r
+ }\r
+\r
+\r
+ //a sinistra\r
+ if(overleft())\r
+ {\r
+ lensleft = 0 + bleft;\r
+ }else\r
+ //a destra\r
+ if(overright())\r
+ {\r
+ if($.browser.msie)\r
+ {\r
+ lensleft = smallimagedata.w - lensdata.w + bleft + 1 ;\r
+ }else\r
+ {\r
+ lensleft = smallimagedata.w - lensdata.w + bleft - 1 ;\r
+ }\r
+\r
+\r
+ }\r
+\r
+ //in alto\r
+ if(overtop())\r
+ {\r
+ lenstop = 0 + btop ;\r
+ }else\r
+ //sotto\r
+ if(overbottom())\r
+ {\r
+\r
+ if($.browser.msie)\r
+ {\r
+ lenstop = smallimagedata.h - lensdata.h + btop + 1 ;\r
+ }else\r
+ {\r
+ lenstop = smallimagedata.h - lensdata.h - 1 + btop ;\r
+ }\r
+\r
+ }\r
+ lensleft = parseInt(lensleft);\r
+ lenstop = parseInt(lenstop);\r
+\r
+ //setto lo zoom ed un eventuale immagine al centro\r
+ $('div.jqZoomPup',a).css({top: lenstop,left: lensleft });\r
+\r
+ if(settings.zoomType == 'reverse')\r
+ {\r
+ $('div.jqZoomPup img',a).css({'position': 'absolute','top': -( lenstop - btop +1) ,'left': -(lensleft - bleft +1) });\r
+ }\r
+\r
+ this.node.style.left = lensleft + 'px';\r
+ this.node.style.top = lenstop + 'px';\r
+\r
+ //setto l'immagine grande\r
+ largeimage.setposition();\r
+\r
+ function overleft() {\r
+ return mousepos.x - (lensdata.w +2*1)/2 - bleft < smallimagedata.pos.l;\r
+ }\r
+\r
+ function overright() {\r
+\r
+ return mousepos.x + (lensdata.w + 2* 1)/2 > smallimagedata.pos.r + bleft ;\r
+ }\r
+\r
+ function overtop() {\r
+ return mousepos.y - (lensdata.h + 2* 1)/2 - btop < smallimagedata.pos.t;\r
+ }\r
+\r
+ function overbottom() {\r
+ return mousepos.y + (lensdata.h + 2* 1)/2 > smallimagedata.pos.b + btop;\r
+ }\r
+\r
+ return this;\r
+ };\r
+\r
+\r
+ //mostra la lente al centro dell'immagine\r
+ Lens.prototype.center = function()\r
+ {\r
+ $('div.jqZoomPup',a).css('display','none');\r
+ var lensleft = (smallimagedata.w)/2 - (lensdata.w)/2 ;\r
+ var lenstop = (smallimagedata.h)/2 - (lensdata.h)/2;\r
+ this.node.style.left = lensleft + 'px';\r
+ this.node.style.top = lenstop + 'px';\r
+ $('div.jqZoomPup',a).css({top: lenstop,left: lensleft });\r
+\r
+ if(settings.zoomType == 'reverse')\r
+ {\r
+ /*if($.browser.safari){\r
+ alert('safari');\r
+ alert(2*bleft);\r
+ $('div.jqZoomPup img',a).css({'position': 'absolute','top': -( lenstop - btop +1) ,'left': -(lensleft - 2*bleft) });\r
+ }else\r
+ {*/\r
+ $('div.jqZoomPup img',a).css({'position': 'absolute','top': -(lenstop - btop + 1) ,'left': -( lensleft - bleft +1) });\r
+ //}\r
+ }\r
+\r
+ largeimage.setposition();\r
+ if($.browser.msie)\r
+ {\r
+ $('div.jqZoomPup',a).show();\r
+ }else\r
+ {\r
+ setTimeout(function(){$('div.jqZoomPup').fadeIn('fast');},10);\r
+ }\r
+ };\r
+\r
+\r
+ //ritorna l'offset\r
+ Lens.prototype.getoffset = function() {\r
+ var o = {};\r
+ o.left = parseInt(this.node.style.left) ;\r
+ o.top = parseInt(this.node.style.top) ;\r
+ return o;\r
+ };\r
+\r
+ //rimuove la lente\r
+ Lens.prototype.remove = function()\r
+ {\r
+\r
+ if(settings.zoomType == 'innerzoom')\r
+ {\r
+ $('div.jqZoomPup',a).fadeOut('fast',function(){/*$('div.jqZoomPup img').remove();*/$(this).remove();});\r
+ }else\r
+ {\r
+ //$('div.jqZoomPup img').remove();\r
+ $('div.jqZoomPup',a).remove();\r
+ }\r
+ };\r
+\r
+ Lens.prototype.findborder = function()\r
+ {\r
+ var bordertop = '';\r
+ bordertop = $('div.jqZoomPup').css('borderTop');\r
+ //alert(bordertop);\r
+ lensbtop = '';\r
+ var borderleft = '';\r
+ borderleft = $('div.jqZoomPup').css('borderLeft');\r
+ lensbleft = '';\r
+ if($.browser.msie)\r
+ {\r
+ var temp = bordertop.split(' ');\r
+\r
+ bordertop = temp[1];\r
+ var temp = borderleft.split(' ');\r
+ borderleft = temp[1];\r
+ }\r
+\r
+ if(bordertop)\r
+ {\r
+ for(i=0;i<3;i++)\r
+ {\r
+ var x = [];\r
+ x = bordertop.substr(i,1);\r
+\r
+ if(isNaN(x) == false)\r
+ {\r
+ lensbtop = lensbtop +''+ bordertop.substr(i,1);\r
+ }else\r
+ {\r
+ break;\r
+ }\r
+ }\r
+ }\r
+\r
+ if(borderleft)\r
+ {\r
+ for(i=0;i<3;i++)\r
+ {\r
+ if(!isNaN(borderleft.substr(i,1)))\r
+ {\r
+ lensbleft = lensbleft + borderleft.substr(i,1)\r
+ }else\r
+ {\r
+ break;\r
+ }\r
+ }\r
+ }\r
+\r
+\r
+ lensbtop = (lensbtop.length > 0) ? eval(lensbtop) : 0;\r
+ lensbleft = (lensbleft.length > 0) ? eval(lensbleft) : 0;\r
+ }\r
+\r
+ //LARGEIMAGE\r
+ function Largeimage( url )\r
+ {\r
+ this.url = url;\r
+ this.node = new Image();\r
+\r
+ /*if(settings.preloadImages)\r
+ {\r
+ preload.push(new Image());\r
+ preload.slice(-1).src = url ;\r
+ }*/\r
+\r
+ this.loadimage = function()\r
+ {\r
+\r
+\r
+ if(!this.node)\r
+ this.node = new Image();\r
+\r
+ this.node.style.position = 'absolute';\r
+ this.node.style.display = 'none';\r
+ this.node.style.left = '-5000px';\r
+ this.node.style.top = '10px';\r
+ loader = new Loader();\r
+\r
+ if(settings.showPreload && !preloadshow)\r
+ {\r
+ loader.show();\r
+ preloadshow = true;\r
+ }\r
+\r
+ document.body.appendChild( this.node );\r
+ this.node.src = this.url; // fires off async\r
+ }\r
+\r
+ this.node.onload = function()\r
+ {\r
+ this.style.display = 'block';\r
+ var w = Math.round($(this).width());\r
+ var h = Math.round($(this).height());\r
+\r
+ this.style.display = 'none';\r
+\r
+ //setting scale\r
+ scale.x = (w / smallimagedata.w);\r
+ scale.y = (h / smallimagedata.h);\r
+\r
+\r
+\r
+\r
+\r
+ if($('div.preload').length > 0)\r
+ {\r
+ $('div.preload').remove();\r
+ }\r
+\r
+ largeimageloaded = true;\r
+\r
+ if(settings.zoomType != 'innerzoom' && running){\r
+ stage = new Stage();\r
+ stage.activate();\r
+ }\r
+\r
+ if(running)\r
+ {\r
+ //alert('in');\r
+ lens = new Lens();\r
+\r
+ lens.activate() ;\r
+\r
+ }\r
+ //la attivo\r
+\r
+ if($('div.preload').length > 0)\r
+ {\r
+ $('div.preload').remove();\r
+ }\r
+ }\r
+ return this;\r
+ }\r
+\r
+\r
+ Largeimage.prototype.setposition = function()\r
+ {\r
+ this.node.style.left = Math.ceil( - scale.x * parseInt(lens.getoffset().left) + bleft) + 'px';\r
+ this.node.style.top = Math.ceil( - scale.y * parseInt(lens.getoffset().top) +btop) + 'px';\r
+ };\r
+\r
+ //setto la posizione dell'immagine grande nel caso di innerzoom\r
+ Largeimage.prototype.setinner = function(e) {\r
+ this.node.style.left = Math.ceil( - scale.x * Math.abs(e.pageX - smallimagedata.pos.l)) + 'px';\r
+ this.node.style.top = Math.ceil( - scale.y * Math.abs(e.pageY - smallimagedata.pos.t)) + 'px';\r
+ $('div.jqZoomPup img',a).css({'position': 'absolute','top': this.node.style.top,'left': this.node.style.left });\r
+ };\r
+\r
+\r
+ Largeimage.prototype.setcenter = function() {\r
+ this.node.style.left = Math.ceil(- scale.x * Math.abs((smallimagedata.w)/2)) + 'px';\r
+ this.node.style.top = Math.ceil( - scale.y * Math.abs((smallimagedata.h)/2)) + 'px';\r
+\r
+\r
+ $('div.jqZoomPup img',a).css({'position': 'absolute','top': this.node.style.top,'left': this.node.style.left });\r
+ };\r
+\r
+\r
+ //STAGE\r
+ function Stage()\r
+ {\r
+\r
+ var leftpos = smallimagedata.pos.l;\r
+ var toppos = smallimagedata.pos.t;\r
+ //creating element and class\r
+ this.node = document.createElement("div");\r
+ $(this.node).addClass('jqZoomWindow');\r
+\r
+ $( this.node )\r
+ .css({\r
+ position: 'absolute',\r
+ width: Math.round(settings.zoomWidth) + 'px',\r
+ height: Math.round(settings.zoomHeight) + 'px',\r
+ display: 'none',\r
+ zIndex: 10000,\r
+ overflow: 'hidden'\r
+ });\r
+\r
+ //fa il positionamento\r
+ switch(settings.position)\r
+ {\r
+ case "right":\r
+\r
+ leftpos = (smallimagedata.pos.r + Math.abs(settings.xOffset) + settings.zoomWidth < screen.width)\r
+ ? (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset))\r
+ : (smallimagedata.pos.l - settings.zoomWidth - Math.abs(settings.xOffset));\r
+\r
+ topwindow = smallimagedata.pos.t + settings.yOffset + settings.zoomHeight;\r
+ toppos = (topwindow < screen.height && topwindow > 0)\r
+ ? smallimagedata.pos.t + settings.yOffset\r
+ : smallimagedata.pos.t;\r
+\r
+ break;\r
+ case "left":\r
+\r
+ leftpos = (smallimagedata.pos.l - Math.abs(settings.xOffset) - settings.zoomWidth > 0)\r
+ ? (smallimagedata.pos.l - Math.abs(settings.xOffset) - settings.zoomWidth)\r
+ : (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset));\r
+\r
+ topwindow = smallimagedata.pos.t + settings.yOffset + settings.zoomHeight;\r
+ toppos = (topwindow < screen.height && topwindow > 0)\r
+ ? smallimagedata.pos.t + settings.yOffset\r
+ : smallimagedata.pos.t;\r
+\r
+ break;\r
+ case "top":\r
+\r
+ toppos = (smallimagedata.pos.t - Math.abs(settings.yOffset) - settings.zoomHeight > 0)\r
+ ? (smallimagedata.pos.t - Math.abs(settings.yOffset) - settings.zoomHeight)\r
+ : (smallimagedata.pos.t + smallimagedata.h + Math.abs(settings.yOffset));\r
+\r
+\r
+ leftwindow = smallimagedata.pos.l + settings.xOffset + settings.zoomWidth;\r
+ leftpos = (leftwindow < screen.width && leftwindow > 0)\r
+ ? smallimagedata.pos.l + settings.xOffset\r
+ : smallimagedata.pos.l;\r
+\r
+ break;\r
+ case "bottom":\r
+\r
+\r
+ toppos = (smallimagedata.pos.b + Math.abs(settings.yOffset) + settings.zoomHeight < $('body').height())\r
+ ? (smallimagedata.pos.b + Math.abs(settings.yOffset))\r
+ : (smallimagedata.pos.t - settings.zoomHeight - Math.abs(settings.yOffset));\r
+\r
+\r
+ leftwindow = smallimagedata.pos.l + settings.xOffset + settings.zoomWidth;\r
+ leftpos = (leftwindow < screen.width && leftwindow > 0)\r
+ ? smallimagedata.pos.l + settings.xOffset\r
+ : smallimagedata.pos.l;\r
+\r
+ break;\r
+ default:\r
+\r
+ leftpos = (smallimagedata.pos.l + smallimagedata.w + settings.xOffset + settings.zoomWidth < screen.width)\r
+ ? (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset))\r
+ : (smallimagedata.pos.l - settings.zoomWidth - Math.abs(settings.xOffset));\r
+\r
+ toppos = (smallimagedata.pos.b + Math.abs(settings.yOffset) + settings.zoomHeight < screen.height)\r
+ ? (smallimagedata.pos.b + Math.abs(settings.yOffset))\r
+ : (smallimagedata.pos.t - settings.zoomHeight - Math.abs(settings.yOffset));\r
+\r
+ break;\r
+ }\r
+\r
+ this.node.style.left = leftpos + 'px';\r
+ this.node.style.top = toppos + 'px';\r
+ return this;\r
+ }\r
+\r
+\r
+ Stage.prototype.activate = function()\r
+ {\r
+\r
+ if ( !this.node.firstChild )\r
+ this.node.appendChild( largeimage.node );\r
+\r
+\r
+ if(settings.title)\r
+ {\r
+ ZoomTitleObj.loadtitle();\r
+ }\r
+\r
+\r
+\r
+ document.body.appendChild( this.node );\r
+\r
+\r
+ switch(settings.showEffect)\r
+ {\r
+ case 'show':\r
+ $(this.node).show();\r
+ break;\r
+ case 'fadein':\r
+ $(this.node).fadeIn(settings.fadeinSpeed);\r
+ break;\r
+ default:\r
+ $(this.node).show();\r
+ break;\r
+ }\r
+\r
+ $(this.node).show();\r
+\r
+ if ($.browser.msie && $.browser.version < 7) {\r
+ this.ieframe = $('<iframe class="zoom_ieframe" frameborder="0" src="#"></iframe>')\r
+ .css({ position: "absolute", left:this.node.style.left,top:this.node.style.top,zIndex: 99,width:settings.zoomWidth,height:settings.zoomHeight })\r
+ .insertBefore(this.node);\r
+ };\r
+\r
+\r
+ largeimage.node.style.display = 'block';\r
+ }\r
+\r
+ Stage.prototype.remove = function() {\r
+ switch(settings.hideEffect)\r
+ {\r
+ case 'hide':\r
+ $('.jqZoomWindow').remove();\r
+ break;\r
+ case 'fadeout':\r
+ $('.jqZoomWindow').fadeOut(settings.fadeoutSpeed);\r
+ break;\r
+ default:\r
+ $('.jqZoomWindow').remove();\r
+ break;\r
+ }\r
+ }\r
+\r
+ function zoomTitle()\r
+ {\r
+\r
+ this.node = jQuery('<div />')\r
+ .addClass('jqZoomTitle')\r
+ .html('' + ZoomTitle +'');\r
+\r
+ this.loadtitle = function()\r
+ {\r
+ if(settings.zoomType == 'innerzoom')\r
+ {\r
+ $(this.node)\r
+ .css({position: 'absolute',\r
+ top: smallimagedata.pos.b +3,\r
+ left: (smallimagedata.pos.l+1),\r
+ width:smallimagedata.w\r
+ })\r
+ .appendTo('body');\r
+ }else\r
+ {\r
+ $(this.node).appendTo(stage.node);\r
+ }\r
+ };\r
+ }\r
+\r
+ zoomTitle.prototype.remove = function() {\r
+ $('.jqZoomTitle').remove();\r
+ }\r
+\r
+\r
+ function Loader()\r
+ {\r
+\r
+ this.node = document.createElement("div");\r
+ $(this.node).addClass('preload');\r
+ $(this.node).html(settings.preloadText);//appendo il testo\r
+\r
+ $(this.node )\r
+ .appendTo("body")\r
+ .css('visibility','hidden');\r
+\r
+\r
+\r
+ this.show = function()\r
+ {\r
+ switch(settings.preloadPosition)\r
+ {\r
+ case 'center':\r
+ loadertop = smallimagedata.pos.t + (smallimagedata.h - $(this.node ).height())/2;\r
+ loaderleft = smallimagedata.pos.l + (smallimagedata.w - $(this.node ).width())/2;\r
+ break;\r
+ default:\r
+ var loaderoffset = this.getoffset();\r
+ loadertop = !isNaN(loaderoffset.top) ? smallimagedata.pos.t + loaderoffset.top : smallimagedata.pos.t + 0;\r
+ loaderleft = !isNaN(loaderoffset.left) ? smallimagedata.pos.l + loaderoffset.left : smallimagedata.pos.l + 0;\r
+ break;\r
+ }\r
+\r
+ //setting position\r
+ $(this.node).css({\r
+ top: loadertop ,\r
+ left: loaderleft ,\r
+ position: 'absolute',\r
+ visibility:'visible'\r
+ });\r
+ }\r
+ return this;\r
+ }\r
+\r
+ Loader.prototype.getoffset = function()\r
+ {\r
+ var o = null;\r
+ o = $('div.preload').offset();\r
+ return o;\r
+ }\r
+\r
+ });\r
+ }\r
+})(jQuery);\r
+\r
+ function trim(stringa)\r
+ {\r
+ while (stringa.substring(0,1) == ' '){\r
+ stringa = stringa.substring(1, stringa.length);\r
+ }\r
+ while (stringa.substring(stringa.length-1, stringa.length) == ' '){\r
+ stringa = stringa.substring(0,stringa.length-1);\r
+ }\r
+ return stringa;\r
+ }
\ No newline at end of file
--- /dev/null
+/*
+ * jQuery JavaScript Library v1.3.2
+ * http://jquery.com/
+ *
+ * Copyright (c) 2009 John Resig
+ * Dual licensed under the MIT and GPL licenses.
+ * http://docs.jquery.com/License
+ *
+ * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
+ * Revision: 6246
+ */
+(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
+/*
+ * Sizzle CSS Selector Engine - v0.9.3
+ * Copyright 2009, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
\ No newline at end of file
--- /dev/null
+(function(f){var b,c,j,m,l,i,g,e,h,a,k;b=document.namespaces;has_canvas=!!document.createElement("canvas").getContext;if(!(has_canvas||b)){f.fn.maphilight=function(){return this};return}if(has_canvas){g=function(p,o,n){if(o<=1){p.style.opacity=o;window.setTimeout(g,10,p,o+0.1,10)}};e=function(n){return Math.max(0,Math.min(parseInt(n,16),255))};h=function(n,o){return"rgba("+e(n.substr(0,2))+","+e(n.substr(2,2))+","+e(n.substr(4,2))+","+o+")"};c=function(n){var o=f('<canvas style="width:'+n.width+"px;height:"+n.height+'px;"></canvas>').get(0);o.getContext("2d").clearRect(0,0,o.width,o.height);return o};j=function(q,n,t,p,o){var s,r=q.getContext("2d");r.beginPath();if(n=="rect"){r.rect(t[0],t[1],t[2]-t[0],t[3]-t[1])}else{if(n=="poly"){r.moveTo(t[0],t[1]);for(s=2;s<t.length;s+=2){r.lineTo(t[s],t[s+1])}}else{if(n=="circ"){r.arc(t[0],t[1],t[2],0,Math.PI*2,false)}}}r.closePath();if(p.fill){r.fillStyle=h(p.fillColor,p.fillOpacity);r.fill()}if(p.stroke){r.strokeStyle=h(p.strokeColor,p.strokeOpacity);r.lineWidth=p.strokeWidth;r.stroke()}if(p.fade){g(q,0)}};m=function(n,o){n.getContext("2d").clearRect(0,0,n.width,n.height)}}else{c=function(n){return f('<var style="zoom:1;overflow:hidden;display:block;width:'+n.width+"px;height:"+n.height+'px;"></var>').get(0)};j=function(o,r,s,v,n){var t,u,p,q;t='<v:fill color="#'+v.fillColor+'" opacity="'+(v.fill?v.fillOpacity:0)+'" />';u=(v.stroke?'strokeweight="'+v.strokeWidth+'" stroked="t" strokecolor="#'+v.strokeColor+'"':'stroked="f"');p='<v:stroke opacity="'+v.strokeOpacity+'"/>';if(r=="rect"){q=f('<v:rect name="'+n+'" filled="t" '+u+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+s[0]+"px;top:"+s[1]+"px;width:"+(s[2]-s[0])+"px;height:"+(s[3]-s[1])+'px;"></v:rect>')}else{if(r=="poly"){q=f('<v:shape name="'+n+'" filled="t" '+u+' coordorigin="0,0" coordsize="'+o.width+","+o.height+'" path="m '+s[0]+","+s[1]+" l "+s.join(",")+' x e" style="zoom:1;margin:0;padding:0;display:block;position:absolute;top:0px;left:0px;width:'+o.width+"px;height:"+o.height+'px;"></v:shape>')}else{if(r=="circ"){q=f('<v:oval name="'+n+'" filled="t" '+u+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(s[0]-s[2])+"px;top:"+(s[1]-s[2])+"px;width:"+(s[2]*2)+"px;height:"+(s[2]*2)+'px;"></v:oval>')}}}q.get(0).innerHTML=t+p;f(o).append(q)};m=function(n){f(n).find("[name=highlighted]").remove()}}l=function(o){var n,p=o.getAttribute("coords").split(",");for(n=0;n<p.length;n++){p[n]=parseFloat(p[n])}return[o.getAttribute("shape").toLowerCase().substr(0,4),p]};k=function(p,o){var n=f(p);return f.extend({},o,f.metadata?n.metadata():false,n.data("maphilight"))};a=function(n){if(!n.complete){return false}if(typeof n.naturalWidth!="undefined"&&n.naturalWidth==0){return false}return true};i={position:"absolute",left:0,top:0,padding:0,border:0};var d=false;f.fn.maphilight=function(p){p=f.extend({},f.fn.maphilight.defaults,p);if(f.browser.msie&&!d){document.namespaces.add("v","urn:schemas-microsoft-com:vml");var o=document.createStyleSheet();var n=["shape","rect","oval","circ","fill","stroke","imagedata","group","textbox"];f.each(n,function(){o.addRule("v\\:"+this,"behavior: url(#default#VML); antialias:true")});d=true}return this.each(function(){var v,s,z,r,u,w,y,t,x;v=f(this);if(!a(this)){return window.setTimeout(function(){v.maphilight(p)},200)}z=f.extend({},p,f.metadata?v.metadata():false,v.data("maphilight"));x=v.get(0).getAttribute("usemap");r=f('map[name="'+x.substr(1)+'"]');if(!(v.is("img")&&x&&r.size()>0)){return}if(v.hasClass("maphilighted")){var q=v.parent();v.insertBefore(q);q.remove()}s=f("<div></div>").css({display:"block",background:"url("+this.src+")",position:"relative",padding:0,width:this.width,height:this.height});if(z.wrapClass){if(z.wrapClass===true){s.addClass(f(this).attr("class"))}else{s.addClass(z.wrapClass)}}v.before(s).css("opacity",0).css(i).remove();if(f.browser.msie){v.css("filter","Alpha(opacity=0)")}s.append(v);u=c(this);f(u).css(i);u.height=this.height;u.width=this.width;y=function(C){var A,B;B=k(this,z);if(!B.neverOn&&!B.alwaysOn){A=l(this);j(u,A[0],A[1],B,"highlighted");if(B.groupBy&&f(this).attr(B.groupBy)){var D=this;r.find("area["+B.groupBy+"="+f(this).attr(B.groupBy)+"]").each(function(){if(this!=D){var F=k(this,z);if(!F.neverOn&&!F.alwaysOn){var E=l(this);j(u,E[0],E[1],F,"highlighted")}}})}}};if(z.alwaysOn){f(r).find("area[coords]").each(y)}else{f(r).find("area[coords]").each(function(){var A,B;B=k(this,z);if(B.alwaysOn){if(!w){w=c(v.get());f(w).css(i);w.width=v.width();w.height=v.height();v.before(w)}A=l(this);if(f.browser.msie){j(u,A[0],A[1],B,"")}else{j(w,A[0],A[1],B,"")}}});f(r).find("area[coords]").mouseover(y).mouseout(function(A){m(u)})}v.before(u);v.addClass("maphilighted")})};f.fn.maphilight.defaults={fill:true,fillColor:"000000",fillOpacity:0.2,stroke:true,strokeColor:"ff0000",strokeOpacity:1,strokeWidth:1,fade:true,alwaysOn:false,neverOn:false,groupBy:false,wrapClass:true}})(jQuery);
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+\r
+$rotina = $input->get('action');\r
+\r
+switch($rotina) {\r
+ case 'insertComentario':\r
+ $load->config('classes/CasoEstudo.php');\r
+ $o_casoEstudo = new CasoEstudo();\r
+ $retorno = $o_casoEstudo->insertComentario();\r
+ switch($retorno){\r
+ case 0:\r
+ $input->setSession('msg','Erro ao inserir comentário. Tente novamente mais tarde.');\r
+ break;\r
+ case 1:\r
+ $input->setSession('msg','Comentário inserido com sucesso!');\r
+ break;\r
+ }\r
+ redir($_SERVER["HTTP_REFERER"]);\r
+ die;\r
+ break;\r
+ case 'inativeComentario':\r
+ $load->config('classes/CasoEstudo.php');\r
+ $o_casoEstudo = new CasoEstudo();\r
+ $retorno = $o_casoEstudo->inativeComentario($input->get('id'));\r
+ switch($retorno){\r
+ case 0:\r
+ $input->setSession('msg','Erro ao inativar comentário. Tente novamente mais tarde.');\r
+ break;\r
+ case 1:\r
+ $input->setSession('msg','Comentário inativado com sucesso!');\r
+ break;\r
+ }\r
+ redir($_SERVER["HTTP_REFERER"]);\r
+ die;\r
+ break;\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+$db->close();\r
+//google analytics\r
+if($input->session('session_msg') != ''){\r
+?>\r
+<script type="text/javascript">\r
+ alert("<?=$input->session('session_msg');?>");\r
+</script>\r
+<?\r
+ $input->unsetSession('session_msg');\r
+}\r
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+include("../../../_system/app.php");\r
+$load->config('classes/GrupoOrgao.php');\r
+$o_grupoOrgao = new GrupoOrgao();\r
+$rowsCamada = $o_grupoOrgao->findCamadas();\r
+?>\r
+<html xmlns="http://www.w3.org/1999/xhtml">\r
+ <head>\r
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />\r
+ </head>\r
+ <body oncontextmenu="return false;">\r
+ <table cellspacing="0" cellpadding="0" width="570" height="550">\r
+ <tr>\r
+ <td style="padding:15px 0px 15px 15px;">\r
+ <img src="../../img/pt/tit/topografia.jpg" alt="Topografia" title="Topografia" /><br /><br />\r
+ Selecione uma camada topográfica e clique sobre o corpo.\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding:0 15px;">\r
+ <? while(!$rowsCamada->EOF){\r
+ $rowsGrupoOrgao = $o_grupoOrgao->findGrupoByCamada($rowsCamada->fields('id'));\r
+ if(!$rowsGrupoOrgao->EOF){?>\r
+ <div style="width:100px; float:left;">\r
+ <input type="radio" value="<?=$rowsCamada->fields('id');?>" id="radio<?=$rowsCamada->fields('id');?>" name="grupoorgao" onchange="javascript: trocaCamada(this.value);" onclick="javascript: trocaCamada(this.value);" /> <label for="radio<?=$rowsCamada->fields('id');?>"><?=$rowsCamada->fields('nome');?></label>\r
+ </div>\r
+ <map name="GrupoOrgao<?=$rowsCamada->fields('id');?>" id="GrupoOrgao<?=$rowsCamada->fields('id');?>">\r
+ <? while(!$rowsGrupoOrgao->EOF){?>\r
+ <area href="javascript: selectBoneco(<?=$rowsGrupoOrgao->fields('id');?>,'<?=$rowsGrupoOrgao->fields('nome');?>','<?=$input->get('name');?>');" shape="rect" coords="<?=($rowsGrupoOrgao->fields('x1').','.$rowsGrupoOrgao->fields('y1').','.$rowsGrupoOrgao->fields('x2').','.$rowsGrupoOrgao->fields('y2'));?>" alt="<?=$rowsGrupoOrgao->fields('nome');?>" title="<?=$rowsGrupoOrgao->fields('nome');?>" />\r
+ <? $rowsGrupoOrgao->moveNext();\r
+ }?>\r
+ </map>\r
+ <? }\r
+ $rowsCamada->moveNext();\r
+ }?>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="padding:3px 15px;">\r
+ (<a id="hightlightall" style="font-size:10px;" href="javascript: void(0);">Mostrar Todos os pontos da camada selecionada</a>)\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td style="text-align:center;" align="center" id="td_img_boneco">\r
+ <img id="img_boneco" src="../../../upload/sis_boneco/boneco.gif" border="0" style="text-align:center;" />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </body>\r
+</html>
\ No newline at end of file
--- /dev/null
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\r
+<style type="text/css">\r
+@import "../../../_system/css/default.css";\r
+@import "../../inc/css/default.css";\r
+</style>\r
+\r
+<script src="../../inc/js/jquery.js" type="text/javascript"></script>\r
+<script src="../../inc/js/jquery.jqzoom.js" type="text/javascript"></script>\r
+<script src="../../inc/js/jquery.maphilight.js" type="text/javascript"></script>\r
+\r
+<script src="../../../_system/js/default.js" type="text/javascript"></script>\r
+<script src="../../../_system/js/swf.js" type="text/javascript"></script>\r
+<script src="../../../_system/js/form.js" type="text/javascript"></script>\r
+<script src="../../../_system/js/ajax.js" type="text/javascript"></script>\r
+<script src="../../../_system/js/popup.js" type="text/javascript"></script>\r
+<script src="../../inc/js/default.js" type="text/javascript"></script>\r
+\r
+<script type="text/javascript">\r
+var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");\r
+document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));\r
+</script>\r
+<script type="text/javascript">\r
+try {\r
+var pageTracker = _gat._getTracker("UA-15405975-1");\r
+pageTracker._trackPageview();\r
+} catch(err) {}</script>
\ No newline at end of file
--- /dev/null
+<?
+//seta lingua
+if ($input->get("language") != ""){
+ $input->setSession("session_language",$input->get("language"));
+} elseif ($input->session("session_language") == ""){
+ $input->setSession("session_language",1);
+}
+
+//carregar xml com conteúdo
+$load->system("library/XmlToArray.php");
+$conteudo_xml = $file->readFile("../../inc/language/".$cfg["language".$input->session("session_language")].".xml");
+$xml = new XmlToArray($conteudo_xml);
+$arr_content = $xml->createArray();
+?>
\ No newline at end of file
--- /dev/null
+<?\r
+//$totalPage = total de paginas\r
+//$actualPage = pagina atual\r
+if((isset($totalPage)) && (isset($actualPage))){//se pagina total e atual estão setadas...\r
+ if(!(isset($pageBaseLink))){\r
+ $pageBaseLink = "index.php?1=1";//base do link de paginação\r
+ }\r
+ if(!(isset($pageLinkName))){\r
+ $pageLinkName = "pagina";//nome da variavel de paginação\r
+ }\r
+ //listagem de X paginas\r
+ $pagelist = 15;\r
+ \r
+ $initialPage = 1;\r
+ $finalPage = $totalPage;\r
+ if($finalPage > $pagelist){\r
+ if($actualPage > ceil($pagelist/2)){\r
+ $initialPage = $actualPage-ceil($pagelist/2);\r
+ }\r
+ if($initialPage > $totalPage-$pagelist){\r
+ $initialPage = $totalPage-$pagelist;\r
+ }\r
+ if($finalPage > $initialPage+$pagelist){\r
+ $finalPage = $initialPage+$pagelist;\r
+ }\r
+ }\r
+ //põe pagina 1\r
+ if($initialPage > 1){?>\r
+ <a class="underlaine" href="<?=$pageBaseLink.'&'.$pageLinkName.'=1';?>"><?=substr('000001',-strlen($finalPage.''));?></a> ... \r
+<? }\r
+ //lista todas as paginas\r
+ for($x=$initialPage;$x<=$finalPage;$x++){\r
+ if($actualPage == $x){?>\r
+ <a class="underlaine" style="text-decoration:none;font-weight:bold;" href="<?=$pageBaseLink.'&'.$pageLinkName.'='.$x;?>"><?=substr('00000'.$x,-strlen($finalPage.''));?></a> \r
+ <? } else {?>\r
+ <a class="underlaine" href="<?=$pageBaseLink.'&'.$pageLinkName.'='.$x;?>"><?=substr('00000'.$x,-strlen($finalPage.''));?></a> \r
+ <? }\r
+ }\r
+ //põe pagina final\r
+ if($finalPage < $totalPage){?>\r
+ ... <a class="underlaine" href="<?=$pageBaseLink.'&'.$pageLinkName.'='.$totalPage;?>"><?=substr('00000'.$totalPage,-strlen($finalPage.''));?></a>\r
+<? }\r
+ \r
+}?>
\ No newline at end of file
--- /dev/null
+<?
+$cfg["database_connect"][0] = false;
+include("../../../_system/app.php");
+?>
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
+ </head>
+ <body oncontextmenu="return false;">
+ <div style="padding:15px;">
+ <table cellspacing="0" cellpadding="0" width="100%">
+ <tr>
+ <td>
+ <img src="../../img/pt/tit/atencao.gif" alt="Atenção" title="Atenção"/>
+ </td>
+ </tr>
+ <tr>
+ <td style="padding-top:15px; padding-bottom:15px;">
+ O conteúdo deste site é de cunho educacional, e mérito da Universidade Federal de Ciências da Saúde de Porto Alegre, por tanto, todo material aqui contido pertence à instituição.
+ <br /><br />
+ O Uso do material é liberado para fins educacionais, tendo em vista que a Universidade Federal de Ciências da Saúde de Porto Alegre (UFCSPA) deve ser sempre mensionada como fonte de informação.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a href="../../../_system/scripts/download.php?name=<?=$input->get('name');?>&file=<?=str_replace('IDIDID',$input->get('id',true),$input->get('path'));?>" alt="Iniciar o download" title="Iniciar o download"><img src="../../img/pt/bt/download.jpg" /></a>
+ </td>
+ </tr>
+ </table>
+ </div>
+ </body>
+</html>
\ No newline at end of file
--- /dev/null
+<?
+$cfg["database_connect"][0] = false;
+include("../../../_system/app.php");
+//include("../../inc/structure/posApp.php");
+
+if ($input->get("iframe") == "none") {
+ ?>
+ <html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
+ </head>
+ <body oncontextmenu="return false;">
+ <div style="cursor:move;">
+ <table cellpadding="0" cellspacing="0">
+ <tr>
+ <td>
+ <img id="img" style="top: 0px; left: 0px; position:relative;" src="<?=str_replace('IDIDID',$input->get('id',true),$input->get('path'));?>" class="dragme" />
+ </td>
+ </tr>
+ </table>
+ </div>
+ <script type="text/javascript">
+ var ie=document.all;
+ var nn6=document.getElementById&&!document.all;
+ var isdrag=false;
+ var x,y;
+ var dobj;
+ var _img_w, _img_h;
+ var _win_w = 500, _win_h = 400;
+
+ function movemouse(e) {
+ if (isdrag) {
+ var _x = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
+ var _y = nn6 ? ty + e.clientY - y : ty + event.clientY - y;
+
+ if (_x > 0) { _x = 0; }
+ if (_y > 0) { _y = 0; }
+
+ if (_x < -(_img_w - _win_w)) { _x = -(_img_w - _win_w); }
+ if (_y < -(_img_h - _win_h)) { _y = -(_img_h - _win_h); }
+
+ dobj.style.left = _x;
+ dobj.style.top = _y;
+
+ return false;
+ }
+ }
+
+ function selectmouse(e) {
+ var fobj = nn6 ? e.target : event.srcElement;
+ var topelement = nn6 ? "HTML" : "BODY";
+ while (fobj.tagName != topelement && fobj.className != "dragme") {
+ fobj = nn6 ? fobj.parentNode : fobj.parentElement;
+ }
+
+ if (fobj.className=="dragme") {
+ isdrag = true;
+ dobj = fobj;
+ tx = parseInt(dobj.style.left+0);
+ ty = parseInt(dobj.style.top+0);
+ x = nn6 ? e.clientX : event.clientX;
+ y = nn6 ? e.clientY : event.clientY;
+
+ _img_w = dobj.width;
+ _img_w++; _img_w--;
+
+ _img_h = dobj.height;
+ _img_h++; _img_h--;
+
+ document.onmousemove=movemouse;
+ return false;
+ }
+ }
+
+ document.onmousedown = selectmouse;
+ document.onmouseup = new Function("isdrag=false");
+ window.parent.document.onmouseup = function () { isdrag = false; };
+ </script>
+ </body>
+ </html>
+ <?
+} else {
+ ?>
+ <iframe style="width: 500px; height: 400px; " name="ifr" id="ifr" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="../../inc/structure/popup_zoom.php?path=<?=$input->get("path");?>&id=<?=$input->get("id");?>&iframe=none"></iframe>
+ <?
+}
+?>
\ No newline at end of file
--- /dev/null
+<?
+$cfg["database_connect"][0] = false;
+include("../../../_system/app.php");
+?>
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
+ </head>
+ <body oncontextmenu="return false;">
+ <a href="javascript: Popup_atual.close();" alt="Clique para fechar" title="Clique para fechar"><img id="img" style="top: 0px; left: 0px; position:relative;" src="<?=str_replace('IDIDID',$input->get('id',true),$input->get('path'));?>" /></a>
+ </body>
+</html>
\ No newline at end of file
--- /dev/null
+<?\r
+//include("../../inc/structure/language.php");\r
+$load->system('functions/swf.php');\r
+$load->config('classes/Helper.php');\r
+$o_helper = new Helper();\r
+$load->config('classes/Html.php');\r
+$o_html = new Html();\r
+global $o_helper;\r
+global $selected;\r
+?>
\ No newline at end of file
--- /dev/null
+<tr height="10">\r
+ <td>\r
+ \r
+ </td>\r
+</tr>\r
+<tr height="59">\r
+ <td style="background:url(../../img/common/bg/rodape.jpg) top left repeat-x;">\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td align="right" style="padding-top:20px;">\r
+ © Copyright <?=date('Y');?> - SIAP - Sistema de Imagens Anatomopatológicas\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+</tr>
\ No newline at end of file
--- /dev/null
+<tr height="150">\r
+ <td>\r
+ <table cellspacing="0" cellpadding="0" align="center" width="994">\r
+ <tr>\r
+ <td class="ufcspa">\r
+ <div onclick="javascript:url('http://www.ufcspa.edu.br/');"> </div>\r
+ </td>\r
+ <td width="1"><div class="lftsia"> </div></td>\r
+ <td class="cntsia">\r
+ <div onclick="javascript: window.location = '../home';"> </div>\r
+ </td>\r
+ <td width="1"><div class="rgtsia"> </div></td>\r
+ <td style="padding-top:35px;">\r
+ <table cellspacing="0" cellpadding="0" class="tblMenu">\r
+ <tr>\r
+ <?=$o_html->getMenu('diagnosticos','../diagnosticos');?>\r
+ <?=$o_html->getMenu('orgaos','../orgaos');?>\r
+ <?=$o_html->getMenu('necropsia','../necropsia');?>\r
+ <?=$o_html->getMenu('casosdeestudo','../casosdeestudo');?>\r
+ <?=$o_html->getMenu('imagens','../imagens');?>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ <tr>\r
+ <td colspan="100%" style="padding-top:10px;">\r
+ <table cellspacing="0" cellpadding="0" align="right" onclick="javascript: url('<?=$cfg['root']?>manager/routines/?menu=0-0');" style="cursor:pointer;">\r
+ <tr>\r
+ <td>\r
+ <img src="../../img/pt/tit/arearestrita.gif" <?=$o_html->alt('Área Restrita');?> />\r
+ </td>\r
+ <td>\r
+ <img src="../../img/pt/bt/acessar.jpg" <?=$o_html->alt('Acessar');?> />\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </td>\r
+</tr>\r
--- /dev/null
+<html>
+ <head>
+ <meta http-equiv="refresh" content="0;url=content/home/" />
+ </head>
+</html>
\ No newline at end of file
--- /dev/null
+<?
+require ("_system/app.php");
+require ("site/inc/structure/posApp.php");
+?>