From 696f20d5513abfba8551efaf172646edfc736be8 Mon Sep 17 00:00:00 2001 From: Michele Silva Date: Fri, 6 Jan 2012 16:20:03 -0200 Subject: [PATCH 1/1] Initial import. --- _config/classes/!Busca.php | 14 + _config/classes/Busca.php | 362 + _config/classes/CasoEstudo.php | 407 + _config/classes/Diagnostico.php | 402 + _config/classes/GrupoOrgao.php | 22 + _config/classes/Helper.php | 262 + _config/classes/Html.php | 148 + _config/classes/Imagem.php | 513 ++ _config/classes/Orgao.php | 395 + _config/classes/Palavra.php | 196 + _config/config.php | 42 + _config/exeptions/home.php | 3 + _config/exeptions/pages/loja_gerenciar_texto.php | 199 + _config/exeptions/routines/backup.php | 64 + _config/exeptions/routines/cropper.php | 59 + .../exeptions/routines/routines - C\363pia.php" | 118 + _config/exeptions/routines/routines.php | 42 + _config/exeptions/routines/routines_orgao.php | 49 + _config/exeptions/routines/routines_search.php | 132 + _config/exeptions/routines/search.php | 165 + _config/exeptions/routines/search_diagnostico.php | 122 + _config/exeptions/routines/search_imagem.php | 158 + .../exeptions/routines/search_imagem_saudavel.php | 158 + _config/exeptions/routines/search_orgao.php | 130 + _config/exeptions/routines/search_orgao2.php | 122 + _config/forms/FormAdminSessao.php | 20 + _config/forms/FormAdminUsuario.php | 59 + _config/forms/FormCasoEstudo.php | 241 + _config/forms/FormCid10.php | 19 + _config/forms/FormDiagnostico.php | 146 + _config/forms/FormEspecialidade.php | 49 + _config/forms/FormGrupoImagem.php | 67 + _config/forms/FormGrupoOrgao.php | 100 + _config/forms/FormGrupoOrgaoCamada.php | 39 + "_config/forms/FormImagem - C\363pia.php" | 450 ++ _config/forms/FormImagem.php | 220 + _config/forms/FormOrgao.php | 94 + _config/forms/FormPalavra.php | 19 + _config/forms/FormPalavraBusca.php | 19 + _config/forms/FormPatologia.php | 60 + _config/forms/FormProcedencia.php | 38 + _config/forms/FormSistema.php | 60 + _config/menu.php | 76 + _system/app.php | 109 + _system/core/DBTable.php | 190 + _system/core/Debug.php | 116 + _system/core/Error.php | 51 + _system/core/File.php | 135 + _system/core/Input.php | 209 + _system/core/Load.php | 84 + _system/core/Output.php | 16 + _system/core/System.php | 67 + _system/css/default.css | 45 + _system/drivers/Connection.php | 15 + _system/drivers/mysql/Connection.php | 60 + _system/drivers/mysql/Recordset.php | 134 + _system/drivers/mysql/Sql.php | 42 + _system/drivers/sqlserver/Connection.php | 60 + _system/drivers/sqlserver/Recordset.php | 127 + _system/drivers/sqlserver/Sql.php | 39 + _system/functions/date.php | 78 + _system/functions/debug.php | 7 + _system/functions/helper.php | 17 + _system/functions/swf.php | 65 + _system/functions/text.php | 139 + _system/functions/url.php | 38 + _system/js/!popup.js | 213 + _system/js/ajax.js | 233 + _system/js/default.js | 238 + _system/js/form.js | 639 ++ _system/js/popup.js | 298 + _system/js/swf.js | 122 + _system/js/tween.js | 376 + _system/library/Date.php | 11 + _system/library/Email.php | 362 + _system/library/Http.php | 177 + _system/library/Image.php | 300 + _system/library/Xml.php | 247 + _system/library/XmlToArray.php | 94 + _system/scripts/download.php | 19 + _system/scripts/image.php | 13 + index.html | 5 + manager/app.php | 13 + manager/core/Menu.php | 151 + manager/core/Profile.php | 139 + manager/core/form/Form.php | 441 ++ manager/core/form/fields/Field.php | 380 + manager/core/form/fields/FieldAtivo.php | 125 + manager/core/form/fields/FieldChar.php | 134 + manager/core/form/fields/FieldColorPicker.php | 61 + manager/core/form/fields/FieldDate.php | 286 + manager/core/form/fields/FieldForm.php | 245 + manager/core/form/fields/FieldHidden.php | 35 + manager/core/form/fields/FieldHtml.php | 64 + manager/core/form/fields/FieldHtmlEditor.php | 130 + manager/core/form/fields/FieldImageMultiUpload.php | 530 ++ manager/core/form/fields/FieldImageUpload.php | 446 ++ manager/core/form/fields/FieldItems.php | 187 + manager/core/form/fields/FieldItemsRel.php | 200 + manager/core/form/fields/FieldMultiItems.php | 180 + manager/core/form/fields/FieldMultiUpload.php | 455 ++ manager/core/form/fields/FieldNumber.php | 190 + manager/core/form/fields/FieldOrder.php | 151 + manager/core/form/fields/FieldPassword.php | 89 + manager/core/form/fields/FieldRelItems.php | 224 + manager/core/form/fields/FieldTree.php | 239 + manager/core/form/fields/FieldUpload.php | 406 + manager/core/form/fields/FieldUploadArquivo.php | 358 + manager/inc/calendario/calendario.css | 94 + manager/inc/calendario/calendario.js | 371 + manager/inc/colorpicker/colorpicker.css | 22 + manager/inc/colorpicker/colorpicker.js | 204 + manager/inc/colorpicker/index.html | 23 + manager/inc/cropper/1.2.1/cropper.css | 185 + manager/inc/cropper/1.2.1/cropper.js | 17 + manager/inc/default.css | 99 + manager/inc/htmleditor/htmleditor.css | 47 + manager/inc/htmleditor/htmleditor.js | 569 ++ manager/inc/htmleditor/routines.php | 97 + manager/inc/inc.menu.php | 10 + manager/inc/inc.restrict.php | 9 + manager/inc/prototype/1.6.1.0/prototype.js | 4874 ++++++++++++ manager/inc/relItems/FieldRelItems.js | 288 + manager/inc/routines.js | 458 ++ manager/inc/scriptaculous/1.8.2/builder.js | 136 + manager/inc/scriptaculous/1.8.2/controls.js | 965 +++ manager/inc/scriptaculous/1.8.2/dragdrop.js | 974 +++ manager/inc/scriptaculous/1.8.2/effects.js | 1123 +++ manager/inc/scriptaculous/1.8.2/scriptaculous.js | 68 + manager/inc/scriptaculous/1.8.2/slider.js | 275 + manager/inc/scriptaculous/1.8.2/sound.js | 59 + manager/inc/scriptaculous/1.8.2/unittest.js | 568 ++ manager/inc/tree/FieldTree.js | 179 + manager/index.html | 5 + manager/routines/form/form.php | 144 + manager/routines/form/list.php | 284 + manager/routines/form/routines.php | 166 + manager/routines/index.php | 133 + manager/routines/system/login.php | 251 + manager/routines/system/routines.php | 29 + manager/routines/zoom.php | 10 + nusoap/lib/class.nusoap_base.php | 996 +++ nusoap/lib/class.soap_fault.php | 90 + nusoap/lib/class.soap_parser.php | 643 ++ nusoap/lib/class.soap_server.php | 1127 +++ nusoap/lib/class.soap_transport_http.php | 1307 ++++ nusoap/lib/class.soap_val.php | 107 + nusoap/lib/class.soapclient.php | 991 +++ nusoap/lib/class.wsdl.php | 1938 +++++ nusoap/lib/class.wsdlcache.php | 209 + nusoap/lib/class.xmlschema.php | 973 +++ nusoap/lib/nusoap.php | 8148 ++++++++++++++++++++ nusoap/lib/nusoapmime.php | 501 ++ nusoap/samples/client1.php | 51 + nusoap/samples/client2.php | 57 + nusoap/samples/client3.php | 56 + nusoap/samples/getfile1client.php | 37 + nusoap/samples/getfile2client.php | 37 + nusoap/samples/index.html | 67 + nusoap/samples/mimeclient.php | 53 + nusoap/samples/sslclient.php | 37 + nusoap/samples/wsdlclient1.php | 47 + nusoap/samples/wsdlclient10.php | 44 + nusoap/samples/wsdlclient11.php | 50 + nusoap/samples/wsdlclient12.php | 225 + nusoap/samples/wsdlclient13.php | 99 + nusoap/samples/wsdlclient14.php | 83 + nusoap/samples/wsdlclient15.php | 60 + nusoap/samples/wsdlclient2.php | 58 + nusoap/samples/wsdlclient3.php | 56 + nusoap/samples/wsdlclient3b.php | 46 + nusoap/samples/wsdlclient3c.php | 46 + nusoap/samples/wsdlclient4.php | 176 + nusoap/samples/wsdlclient5.php | 69 + nusoap/samples/wsdlclient6.php | 66 + nusoap/samples/wsdlclient7.php | 51 + nusoap/samples/wsdlclient8.php | 74 + nusoap/samples/wsdlclient9.php | 63 + php_test/index.php | 3 + siacc_wsclient.php | 91 + siap_ws.php | 126 + siap_ws_utils.php | 114 + site/content/busca/index.php | 14 + site/content/casosdeestudo/index.php | 309 + site/content/casosdeestudo/view.php | 164 + site/content/diagnosticos/index.php | 296 + site/content/diagnosticos/view.php | 100 + site/content/home/index.php | 182 + site/content/home/index_colunas.php | 145 + site/content/imagens/index.php | 286 + site/content/imagens/view.php | 175 + site/content/index.html | 5 + site/content/necropsia/index.php | 292 + site/content/necropsia/view.php | 91 + site/content/orgaos/index.php | 283 + site/content/orgaos/view.php | 124 + site/inc/css/default.css | 205 + site/inc/css/jqzoom.css | 68 + site/inc/js/default.js | 158 + site/inc/js/jquery.jqzoom.js | 1124 +++ site/inc/js/jquery.js | 19 + site/inc/js/jquery.maphilight.js | 1 + site/inc/routines/routines.php | 38 + site/inc/structure/footer.php | 12 + site/inc/structure/grupoorgao.php | 50 + site/inc/structure/header.php | 26 + site/inc/structure/language.php | 14 + site/inc/structure/paginacao.php | 44 + site/inc/structure/popup_download.php | 32 + site/inc/structure/popup_zoom.php | 87 + site/inc/structure/popup_zoom1.php | 12 + site/inc/structure/posApp.php | 10 + site/inc/structure/rodape.php | 16 + site/inc/structure/topo.php | 41 + site/index.html | 5 + test.php | 4 + 216 files changed, 53349 insertions(+), 0 deletions(-) create mode 100644 _config/classes/!Busca.php create mode 100644 _config/classes/Busca.php create mode 100644 _config/classes/CasoEstudo.php create mode 100644 _config/classes/Diagnostico.php create mode 100644 _config/classes/GrupoOrgao.php create mode 100644 _config/classes/Helper.php create mode 100644 _config/classes/Html.php create mode 100644 _config/classes/Imagem.php create mode 100644 _config/classes/Orgao.php create mode 100644 _config/classes/Palavra.php create mode 100644 _config/config.php create mode 100644 _config/exeptions/home.php create mode 100644 _config/exeptions/pages/loja_gerenciar_texto.php create mode 100644 _config/exeptions/routines/backup.php create mode 100644 _config/exeptions/routines/cropper.php create mode 100644 "_config/exeptions/routines/routines - C\363pia.php" create mode 100644 _config/exeptions/routines/routines.php create mode 100644 _config/exeptions/routines/routines_orgao.php create mode 100644 _config/exeptions/routines/routines_search.php create mode 100644 _config/exeptions/routines/search.php create mode 100644 _config/exeptions/routines/search_diagnostico.php create mode 100644 _config/exeptions/routines/search_imagem.php create mode 100644 _config/exeptions/routines/search_imagem_saudavel.php create mode 100644 _config/exeptions/routines/search_orgao.php create mode 100644 _config/exeptions/routines/search_orgao2.php create mode 100644 _config/forms/FormAdminSessao.php create mode 100644 _config/forms/FormAdminUsuario.php create mode 100644 _config/forms/FormCasoEstudo.php create mode 100644 _config/forms/FormCid10.php create mode 100644 _config/forms/FormDiagnostico.php create mode 100644 _config/forms/FormEspecialidade.php create mode 100644 _config/forms/FormGrupoImagem.php create mode 100644 _config/forms/FormGrupoOrgao.php create mode 100644 _config/forms/FormGrupoOrgaoCamada.php create mode 100644 "_config/forms/FormImagem - C\363pia.php" create mode 100644 _config/forms/FormImagem.php create mode 100644 _config/forms/FormOrgao.php create mode 100644 _config/forms/FormPalavra.php create mode 100644 _config/forms/FormPalavraBusca.php create mode 100644 _config/forms/FormPatologia.php create mode 100644 _config/forms/FormProcedencia.php create mode 100644 _config/forms/FormSistema.php create mode 100644 _config/menu.php create mode 100644 _system/app.php create mode 100644 _system/core/DBTable.php create mode 100644 _system/core/Debug.php create mode 100644 _system/core/Error.php create mode 100644 _system/core/File.php create mode 100644 _system/core/Input.php create mode 100644 _system/core/Load.php create mode 100644 _system/core/Output.php create mode 100644 _system/core/System.php create mode 100644 _system/css/default.css create mode 100644 _system/drivers/Connection.php create mode 100644 _system/drivers/mysql/Connection.php create mode 100644 _system/drivers/mysql/Recordset.php create mode 100644 _system/drivers/mysql/Sql.php create mode 100644 _system/drivers/sqlserver/Connection.php create mode 100644 _system/drivers/sqlserver/Recordset.php create mode 100644 _system/drivers/sqlserver/Sql.php create mode 100644 _system/functions/date.php create mode 100644 _system/functions/debug.php create mode 100644 _system/functions/helper.php create mode 100644 _system/functions/swf.php create mode 100644 _system/functions/text.php create mode 100644 _system/functions/url.php create mode 100644 _system/js/!popup.js create mode 100644 _system/js/ajax.js create mode 100644 _system/js/default.js create mode 100644 _system/js/form.js create mode 100644 _system/js/popup.js create mode 100644 _system/js/swf.js create mode 100644 _system/js/tween.js create mode 100644 _system/library/Date.php create mode 100644 _system/library/Email.php create mode 100644 _system/library/Http.php create mode 100644 _system/library/Image.php create mode 100644 _system/library/Xml.php create mode 100644 _system/library/XmlToArray.php create mode 100644 _system/scripts/download.php create mode 100644 _system/scripts/image.php create mode 100644 index.html create mode 100644 manager/app.php create mode 100644 manager/core/Menu.php create mode 100644 manager/core/Profile.php create mode 100644 manager/core/form/Form.php create mode 100644 manager/core/form/fields/Field.php create mode 100644 manager/core/form/fields/FieldAtivo.php create mode 100644 manager/core/form/fields/FieldChar.php create mode 100644 manager/core/form/fields/FieldColorPicker.php create mode 100644 manager/core/form/fields/FieldDate.php create mode 100644 manager/core/form/fields/FieldForm.php create mode 100644 manager/core/form/fields/FieldHidden.php create mode 100644 manager/core/form/fields/FieldHtml.php create mode 100644 manager/core/form/fields/FieldHtmlEditor.php create mode 100644 manager/core/form/fields/FieldImageMultiUpload.php create mode 100644 manager/core/form/fields/FieldImageUpload.php create mode 100644 manager/core/form/fields/FieldItems.php create mode 100644 manager/core/form/fields/FieldItemsRel.php create mode 100644 manager/core/form/fields/FieldMultiItems.php create mode 100644 manager/core/form/fields/FieldMultiUpload.php create mode 100644 manager/core/form/fields/FieldNumber.php create mode 100644 manager/core/form/fields/FieldOrder.php create mode 100644 manager/core/form/fields/FieldPassword.php create mode 100644 manager/core/form/fields/FieldRelItems.php create mode 100644 manager/core/form/fields/FieldTree.php create mode 100644 manager/core/form/fields/FieldUpload.php create mode 100644 manager/core/form/fields/FieldUploadArquivo.php create mode 100644 manager/inc/calendario/calendario.css create mode 100644 manager/inc/calendario/calendario.js create mode 100644 manager/inc/colorpicker/colorpicker.css create mode 100644 manager/inc/colorpicker/colorpicker.js create mode 100644 manager/inc/colorpicker/index.html create mode 100644 manager/inc/cropper/1.2.1/cropper.css create mode 100644 manager/inc/cropper/1.2.1/cropper.js create mode 100644 manager/inc/default.css create mode 100644 manager/inc/htmleditor/htmleditor.css create mode 100644 manager/inc/htmleditor/htmleditor.js create mode 100644 manager/inc/htmleditor/routines.php create mode 100644 manager/inc/inc.menu.php create mode 100644 manager/inc/inc.restrict.php create mode 100644 manager/inc/prototype/1.6.1.0/prototype.js create mode 100644 manager/inc/relItems/FieldRelItems.js create mode 100644 manager/inc/routines.js create mode 100644 manager/inc/scriptaculous/1.8.2/builder.js create mode 100644 manager/inc/scriptaculous/1.8.2/controls.js create mode 100644 manager/inc/scriptaculous/1.8.2/dragdrop.js create mode 100644 manager/inc/scriptaculous/1.8.2/effects.js create mode 100644 manager/inc/scriptaculous/1.8.2/scriptaculous.js create mode 100644 manager/inc/scriptaculous/1.8.2/slider.js create mode 100644 manager/inc/scriptaculous/1.8.2/sound.js create mode 100644 manager/inc/scriptaculous/1.8.2/unittest.js create mode 100644 manager/inc/tree/FieldTree.js create mode 100644 manager/index.html create mode 100644 manager/routines/form/form.php create mode 100644 manager/routines/form/list.php create mode 100644 manager/routines/form/routines.php create mode 100644 manager/routines/index.php create mode 100644 manager/routines/system/login.php create mode 100644 manager/routines/system/routines.php create mode 100644 manager/routines/zoom.php create mode 100644 nusoap/lib/class.nusoap_base.php create mode 100644 nusoap/lib/class.soap_fault.php create mode 100644 nusoap/lib/class.soap_parser.php create mode 100644 nusoap/lib/class.soap_server.php create mode 100644 nusoap/lib/class.soap_transport_http.php create mode 100644 nusoap/lib/class.soap_val.php create mode 100644 nusoap/lib/class.soapclient.php create mode 100644 nusoap/lib/class.wsdl.php create mode 100644 nusoap/lib/class.wsdlcache.php create mode 100644 nusoap/lib/class.xmlschema.php create mode 100644 nusoap/lib/nusoap.php create mode 100644 nusoap/lib/nusoapmime.php create mode 100644 nusoap/samples/client1.php create mode 100644 nusoap/samples/client2.php create mode 100644 nusoap/samples/client3.php create mode 100644 nusoap/samples/getfile1client.php create mode 100644 nusoap/samples/getfile2client.php create mode 100644 nusoap/samples/index.html create mode 100644 nusoap/samples/mimeclient.php create mode 100644 nusoap/samples/sslclient.php create mode 100644 nusoap/samples/wsdlclient1.php create mode 100644 nusoap/samples/wsdlclient10.php create mode 100644 nusoap/samples/wsdlclient11.php create mode 100644 nusoap/samples/wsdlclient12.php create mode 100644 nusoap/samples/wsdlclient13.php create mode 100644 nusoap/samples/wsdlclient14.php create mode 100644 nusoap/samples/wsdlclient15.php create mode 100644 nusoap/samples/wsdlclient2.php create mode 100644 nusoap/samples/wsdlclient3.php create mode 100644 nusoap/samples/wsdlclient3b.php create mode 100644 nusoap/samples/wsdlclient3c.php create mode 100644 nusoap/samples/wsdlclient4.php create mode 100644 nusoap/samples/wsdlclient5.php create mode 100644 nusoap/samples/wsdlclient6.php create mode 100644 nusoap/samples/wsdlclient7.php create mode 100644 nusoap/samples/wsdlclient8.php create mode 100644 nusoap/samples/wsdlclient9.php create mode 100644 php_test/index.php create mode 100644 siacc_wsclient.php create mode 100644 siap_ws.php create mode 100644 siap_ws_utils.php create mode 100644 site/content/busca/index.php create mode 100644 site/content/casosdeestudo/index.php create mode 100644 site/content/casosdeestudo/view.php create mode 100644 site/content/diagnosticos/index.php create mode 100644 site/content/diagnosticos/view.php create mode 100644 site/content/home/index.php create mode 100644 site/content/home/index_colunas.php create mode 100644 site/content/imagens/index.php create mode 100644 site/content/imagens/view.php create mode 100644 site/content/index.html create mode 100644 site/content/necropsia/index.php create mode 100644 site/content/necropsia/view.php create mode 100644 site/content/orgaos/index.php create mode 100644 site/content/orgaos/view.php create mode 100644 site/inc/css/default.css create mode 100644 site/inc/css/jqzoom.css create mode 100644 site/inc/js/default.js create mode 100644 site/inc/js/jquery.jqzoom.js create mode 100644 site/inc/js/jquery.js create mode 100644 site/inc/js/jquery.maphilight.js create mode 100644 site/inc/routines/routines.php create mode 100644 site/inc/structure/footer.php create mode 100644 site/inc/structure/grupoorgao.php create mode 100644 site/inc/structure/header.php create mode 100644 site/inc/structure/language.php create mode 100644 site/inc/structure/paginacao.php create mode 100644 site/inc/structure/popup_download.php create mode 100644 site/inc/structure/popup_zoom.php create mode 100644 site/inc/structure/popup_zoom1.php create mode 100644 site/inc/structure/posApp.php create mode 100644 site/inc/structure/rodape.php create mode 100644 site/inc/structure/topo.php create mode 100644 site/index.html create mode 100644 test.php diff --git a/_config/classes/!Busca.php b/_config/classes/!Busca.php new file mode 100644 index 0000000..145a5bd --- /dev/null +++ b/_config/classes/!Busca.php @@ -0,0 +1,14 @@ +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'); + $this->arr_resultado = array('08','16'); + $this->arr_ordenar = array('Nome','Sistema','Patologia'); + } + + +} +?> \ No newline at end of file diff --git a/_config/classes/Busca.php b/_config/classes/Busca.php new file mode 100644 index 0000000..0595501 --- /dev/null +++ b/_config/classes/Busca.php @@ -0,0 +1,362 @@ +busca = $tmp_busca; + // $this->somaBusca($tmp_busca); + } + function findPalavraAproximada($palavra, $sql = ""){ + global $db; + global $load; + + $load->system("functions/text.php"); + + $min = 55; + $mid = 80; + + $arr_busca = explode(' ',$palavra); + $arr_palavras = array(); + if($sql == "") + $sql = "SELECT palavra FROM site_palavra WHERE status = 1"; + $rs = $db->execute($sql); + while(!$rs->EOF){ + $arr_now = explode(" ",$rs->fields("palavra")); + if(is_array($arr_now)) { + for($x=0,$total=sizeof($arr_now);$x<$total;$x++){ + $arr_palavras[] = formatNameFile($arr_now[$x]); + } + } else { + $arr_palavras[] = formatNameFile($arr_now); + } + $rs->moveNext(); + } + $arr_palavras = array_values(array_unique($arr_palavras)); + $arr = array(array()); + + $porcentagem = 0; + + // BUSCA TODA A PALAVRA + for($x=0,$total=sizeof($arr_palavras);$x<$total;$x++){ + similar_text($palavra,$arr_palavras[$x],$r); + if ($r > $min) { + if ($r >= $mid) { + if ($porcentagem < $mid) { + $arr[0] = array(); + } + } + + if ($porcentagem < $r) { + $porcentagem = $r; + $arr[0][] = $arr_palavras[$x]; + } + } + } + + if (sizeof($arr_busca) > 1) { + $indice = 1; + //echo sizeof($arr_busca); + for ($x=0,$total=sizeof($arr_busca);$x<=$total;$x++) { + $porcentagem = 0; + //echo $x." - ".$total."
"; + if(isset($arr_busca[$x])){ + if (strlen($arr_busca[$x]) > 2) { + for($z=0,$total=sizeof($arr_palavras);$z<$total;$z++){ + similar_text($arr_busca[$x],$arr_palavras[$z],$r); + if ($r > $min) { + if ($r >= $mid) { + if ($porcentagem < $mid) { + $arr[$indice] = array(); + } + } + + if ($porcentagem < $r) { + $porcentagem = $r; + $arr[$indice][] = $arr_palavras[$z]; + } + } + } + $indice++; + } + } + } + } + + return $arr; + } + function makeSql($arrPalavra,$baseSql,$arrWherePalavra,$fixedWhere = ""){ + //arrPalavra: + //Array com as palavras aproximadas. Lembrando, posição 0, array de palavras completas (frases, titulos), posição 1, todas as palavras 'quebradas'. + + //baseSql: + //Sql contendo todo o conteudo necessario para fazer a busca naquela tabela, no lugar da sentença WHERE, subtituir por #WHERE#, como no exemplo: + //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 + + //arrWherePalavra: + //array com as condições, sem o where, e substituindo a palavra de busca por #PALAVRA#, como no exemplo: + //p.descricao LIKE '%#PALAVRA#%' + + //$fixedWhere: + //condições fixas a serem concatenadas com a query, como no exemplo: + //status = 1 AND data = '2009-10-20' + //note que não existe operador em nenhum dos lados (AND, OR, ou qualquer outro) + + if (isset($arrPalavra[0])) { + if ($arrPalavra[0] != '') { + $where = " AND (1=2 "; + for($x=0,$total=sizeof($arrPalavra[0]);$x<$total;$x++) { + $where .= " OR ("; + for($w=0,$totalW=sizeof($arrWherePalavra);$w<$totalW;$w++){ + if($w == 0){ + $where .= " ".str_replace("#PALAVRA#",$arrPalavra[0][$x],$arrWherePalavra[$w])." "; + } else { + $where .= " OR ".str_replace("#PALAVRA#",$arrPalavra[0][$x],$arrWherePalavra[$w])." "; + } + } + $where .= " )"; + } + $where .= ") "; + } else { + $where = 'AND 1=2'; + } + } elseif(isset($arrPalavra[1])) { + $where = ''; + for($i=1,$total=sizeof($arrPalavra);$i<=$total;$i++) { + $where .= " AND ((1=2) "; + for($x=0,$total=sizeof($arrPalavra[$i]);$x<=$total;$x++) { + if ($arrPalavra[$i][$x] != '') { + $where .= " OR ("; + for($w=0,$totalW=sizeof($arrWherePalavra);$w<$totalW;$w++){ + if($w == 0){ + $where .= " ".str_replace("#PALAVRA#",$arrPalavra[$i][$x],$arrWherePalavra[$w])." "; + } else { + $where .= " OR ".str_replace("#PALAVRA#",$arrPalavra[$i][$x],$arrWherePalavra[$w])." "; + } + } + $where .= " )"; + } + } + } + $where .= ") "; + } + if($fixedWhere == ""){ + $fixedWhere = " 1 = 1 "; + } else { + $fixedWhere = " ".$fixedWhere." "; + } + $sql = str_replace("#WHERE#"," WHERE ".$fixedWhere.$where,$baseSql); + return $sql; + } + function findComplexAgenda($arrPalavra){ + global $db; + $fixedWhere = "a.status = 1"; + + $arrWhere = array(); + $arrWhere[] = "a.nome like '%#PALAVRA#%'"; + $arrWhere[] = "a.descricao like '%#PALAVRA#%'"; + $arrWhere[] = "a.ingresso like '%#PALAVRA#%'"; + $arrWhere[] = "e.nome like '%#PALAVRA#%'"; + $arrWhere[] = "c.nome like '%#PALAVRA#%'"; + $arrWhere[] = "e.site like '%#PALAVRA#%'"; + $arrWhere[] = "e.endereco like '%#PALAVRA#%'"; + $arrWhere[] = "e.numero like '%#PALAVRA#%'"; + $arrWhere[] = "e.bairro like '%#PALAVRA#%'"; + + $baseSql = "SELECT a.id, + CAST(a.data as DATE) as data, + if(strcmp(a.id_estabelecimento, 0), e.nome, a.outroestabelecimento) as nome, + a.nome as festa + FROM site_agenda a + LEFT OUTER JOIN site_estabelecimento e ON e.id = a.id_estabelecimento + LEFT OUTER JOIN global_estado es ON es.id = e.id_estado + LEFT OUTER JOIN global_cidade c ON c.id = e.id_cidade + LEFT OUTER JOIN site_agenda_genero ag ON ag.id_agenda = a.id + #WHERE# + GROUP BY a.id ORDER BY a.data ASC"; + + return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function findComplexRedacao($arrPalavra){ + global $db; + $fixedWhere = "status = 1"; + + $arrWhere = array(); + $arrWhere[] = "nome like '%#PALAVRA#%'"; + $arrWhere[] = "descricao like '%#PALAVRA#%'"; + $arrWhere[] = "titulo like '%#PALAVRA#%'"; + + $baseSql = "SELECT id,nome,titulo,descricao,data FROM site_redacao #WHERE# ORDER BY data DESC"; + + return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function findComplexFoto($arrPalavra){ + global $db; + $fixedWhere = "g.status = 1"; + + $arrWhere = array(); + $arrWhere[] = "e.nome like '%#PALAVRA#%'"; + $arrWhere[] = "f.nome like '%#PALAVRA#%'"; + $arrWhere[] = "g.outraagenda like '%#PALAVRA#%'"; + $arrWhere[] = "a.nome like '%#PALAVRA#%'"; + + $baseSql = "SELECT g.id,e.nome as estabelecimento,a.nome as festa,a.data as data, f.nome as fotografo + FROM site_galeria g LEFT OUTER JOIN site_estabelecimento e ON e.id = g.id_estabelecimento + LEFT OUTER JOIN site_agenda a ON a.id_estabelecimento = g.id_estabelecimento + LEFT OUTER JOIN site_fotografo f ON f.id = g.id_fotografo + #WHERE# + ORDER BY data DESC "; + + return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function findComplexArtista($arrPalavra){ + global $db; + $fixedWhere = "a.status = 1"; + + $arrWhere = array(); + $arrWhere[] = "a.nome like '%#PALAVRA#%'"; + $arrWhere[] = "g.nome like '%#PALAVRA#%'"; + $arrWhere[] = "a.nomeoutraagencia like '%#PALAVRA#%'"; + $arrWhere[] = "a.descricao like '%#PALAVRA#%'"; + $arrWhere[] = "age.nome like '%#PALAVRA#%'"; + + $baseSql = "SELECT DISTINCT(a.id),a.nome + FROM (site_artista a + LEFT OUTER JOIN site_cadastro_artista ca ON(a.id=ca.id_artista) + LEFT OUTER JOIN site_artista_genero ag ON(a.id=ag.id_artista) + LEFT OUTER JOIN site_genero g ON(g.id=ag.id_genero) + LEFT OUTER JOIN site_agencia age ON(age.id=a.id_agencia)) + #WHERE# + GROUP BY a.id "; + + return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function findComplexEstabelecimento($arrPalavra){ + global $db; + $fixedWhere = "e.status = 1"; + + $arrWhere = array(); + $arrWhere[] = "e.nome like '%#PALAVRA#%'"; + $arrWhere[] = "e.nomeabreviado like '%#PALAVRA#%'"; + $arrWhere[] = "e.endereco like '%#PALAVRA#%'"; + $arrWhere[] = "e.numero like '%#PALAVRA#%'"; + $arrWhere[] = "e.bairro like '%#PALAVRA#%'"; + $arrWhere[] = "e.descricao like '%#PALAVRA#%'"; + $arrWhere[] = "c.nome like '%#PALAVRA#%'"; + $arrWhere[] = "es.nome like '%#PALAVRA#%'"; + + $baseSql = "SELECT e.id,e.nome FROM (site_estabelecimento e + LEFT OUTER JOIN site_cadastro_estabelecimento ce ON(ce.id_estabelecimento=e.id) + LEFT OUTER JOIN global_cidade c ON(e.id_cidade=c.id) + LEFT OUTER JOIN global_estado es ON(c.id_estado=es.id)) + #WHERE# + GROUP BY e.id ORDER BY e.nome ASC"; + + return $db->execute($this->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function findSimpleAgenda($tmp_busca = ""){ + if($tmp_busca == ""){ + $tmp_busca = $this->busca; + } + + global $db; + + $sql = "SELECT a.id, + CAST(a.data as DATE) as data, + if(strcmp(a.id_estabelecimento, 0), e.nome, a.outroestabelecimento) as nome, + a.nome as festa + FROM site_agenda a + LEFT OUTER JOIN site_estabelecimento e ON e.id = a.id_estabelecimento + LEFT OUTER JOIN global_estado es ON es.id = e.id_estado + LEFT OUTER JOIN global_cidade c ON c.id = e.id_cidade + LEFT OUTER JOIN site_agenda_genero ag ON ag.id_agenda = a.id + WHERE a.status = 1 AND + (a.nome like '%".$tmp_busca."%' + OR a.descricao like '%".$tmp_busca."%' + OR a.ingresso like '%".$tmp_busca."%' + OR e.nome like '%".$tmp_busca."%' + OR c.nome like '%".$tmp_busca."%' + OR e.site like '%".$tmp_busca."%' + OR e.endereco like '%".$tmp_busca."%' + OR e.numero like '%".$tmp_busca."%' + OR e.bairro like '%".$tmp_busca."%') + GROUP BY a.id ORDER BY a.data ASC"; + return $db->execute($sql); + } + function findSimpleRedacao($tmp_busca = ""){ + if($tmp_busca == ""){ + $tmp_busca = $this->busca; + } + + global $db; + + $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"; + return $db->execute($sql); + } + function findSimpleFoto($tmp_busca = ""){ + if($tmp_busca == ""){ + $tmp_busca = $this->busca; + } + + global $db; + + $sql = "SELECT g.id,e.nome as estabelecimento,a.nome as festa,a.data as data, f.nome as fotografo + FROM site_galeria g LEFT OUTER JOIN site_estabelecimento e ON e.id = g.id_estabelecimento + LEFT OUTER JOIN site_agenda a ON a.id_estabelecimento = g.id_estabelecimento + LEFT OUTER JOIN site_fotografo f ON f.id = g.id_fotografo + WHERE g.status = 1 AND ( + e.nome like '%".$tmp_busca."%' + OR f.nome like '%".$tmp_busca."%' + OR g.outraagenda like '%".$tmp_busca."%' + OR a.nome like '%".$tmp_busca."%' + ) + ORDER BY data DESC "; + return $db->execute($sql); + } + function findSimpleArtista($tmp_busca = ""){ + if($tmp_busca == ""){ + $tmp_busca = $this->busca; + } + + global $db; + + $sql = "SELECT DISTINCT(a.id),a.nome + FROM (site_artista a + LEFT OUTER JOIN site_cadastro_artista ca ON(a.id=ca.id_artista) + LEFT OUTER JOIN site_artista_genero ag ON(a.id=ag.id_artista) + LEFT OUTER JOIN site_genero g ON(g.id=ag.id_genero) + LEFT OUTER JOIN site_agencia age ON(age.id=a.id_agencia)) + WHERE a.status=1 AND ( + a.nome like '%".$tmp_busca."%' + OR g.nome like '%".$tmp_busca."%' + OR a.nomeoutraagencia like '%".$tmp_busca."%' + OR a.descricao like '%".$tmp_busca."%' + OR age.nome like '%".$tmp_busca."%' + ) + GROUP BY a.id "; + return $db->execute($sql); + } + function findSimpleEstabelecimento($tmp_busca = ""){ + if($tmp_busca == ""){ + $tmp_busca = $this->busca; + } + + global $db; + + $sql = "SELECT e.id,e.nome FROM (site_estabelecimento e + LEFT OUTER JOIN site_cadastro_estabelecimento ce ON(ce.id_estabelecimento=e.id) + LEFT OUTER JOIN global_cidade c ON(e.id_cidade=c.id) + LEFT OUTER JOIN global_estado es ON(c.id_estado=es.id)) + WHERE e.status = 1 AND ( + e.nome like '%".$tmp_busca."%' + OR e.nomeabreviado like '%".$tmp_busca."%' + OR e.endereco like '%".$tmp_busca."%' + OR e.numero like '%".$tmp_busca."%' + OR e.bairro like '%".$tmp_busca."%' + OR e.descricao like '%".$tmp_busca."%' + OR c.nome like '%".$tmp_busca."%' + OR es.nome like '%".$tmp_busca."%' + ) GROUP BY e.id ORDER BY e.nome ASC"; + return $db->execute($sql); + } +} +?> \ No newline at end of file diff --git a/_config/classes/CasoEstudo.php b/_config/classes/CasoEstudo.php new file mode 100644 index 0000000..ddbe80d --- /dev/null +++ b/_config/classes/CasoEstudo.php @@ -0,0 +1,407 @@ +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'); + $this->arr_resultado = array('08','16','32'); + $this->arr_ordenar = array('Nome','Especialidade'); + $this->getFiltrosFromSession(); + } + function setAlfabetoCasoEstudo() { + global $input; + + if ($input->session('session_letras_casoestudo') != '') { + $this->arr_alfabeto_casoestudo = unserialize($input->session('session_letras_casoestudo')); + if($this->arr_alfabeto_casoestudo == ''){ + $this->arr_alfabeto_casoestudo = array(); + } + } else { + $rowsLetra = $this->findLetraCasoEstudo(); + $this->arr_alfabeto_casoestudo = array(); + while (!$rowsLetra->EOF) { + $this->arr_alfabeto_casoestudo[] = strtoupper($rowsLetra->fields('letra')); + $rowsLetra->moveNext(); + } + $input->setSession('session_letras_casoestudo',serialize($this->arr_alfabeto_casoestudo)); + } + } + function findLetraCasoEstudo() { + global $db; + + $sql = "SELECT DISTINCT(SUBSTRING(nome,1,1)) AS letra FROM sis_casoestudo WHERE visualizacao = 1 ORDER BY nome ASC"; + return $db->execute($sql); + } + function getFiltrosFromSession(){ + $this->setAlfabetoCasoEstudo(); + + global $input; + $this->filtro_palavra = $input->session('session_casoestudo_filtro_palavra'); + $this->filtro_procedencia = $input->session('session_casoestudo_filtro_procedencia'); + $this->filtro_sistema = $input->session('session_casoestudo_filtro_sistema'); + $this->filtro_patologia = $input->session('session_casoestudo_filtro_patologia'); + + $this->filtro_ordenar = $input->get('casoestudo_filtro_ordenar'); + if($this->filtro_ordenar == ''){ + $this->filtro_ordenar = $input->session('session_casoestudo_filtro_ordenar'); + if($this->filtro_ordenar == ''){ + $this->filtro_ordenar = $this->arr_ordenar[0]; + } + } else { + $input->setSession('session_casoestudo_filtro_ordenar',$this->filtro_ordenar); + } + + $this->filtro_resultado = $input->get('casoestudo_filtro_resultado'); + if($this->filtro_resultado == ''){ + $this->filtro_resultado = $input->session('session_casoestudo_filtro_resultado'); + if($this->filtro_resultado == ''){ + $this->filtro_resultado = $this->arr_resultado[0]; + } + } else { + $input->setSession('session_casoestudo_filtro_resultado',$this->filtro_resultado); + } + } + function getResultado($tmp_baseLink = ''){ + $html = '
Resultados por página:  '; + $total = sizeof($this->arr_resultado); + for($r=0;$r<$total;$r++){ + if($this->arr_resultado[$r] == $this->filtro_resultado){ + $html .= ''.$this->arr_resultado[$r].''; + } else { + $html .= ''.$this->arr_resultado[$r].''; + } + if(($r+1) < $total){ + $html .= '  '; + } + } + $html .= '
'; + return $html; + } + function getAlfabeto(){ + $html = ''; + $total = sizeof($this->arr_alfabeto); + for($a=0;$a<$total;$a++){ + if(in_array($this->arr_alfabeto[$a],$this->arr_alfabeto_casoestudo)){ + $html .= ''; + } else { + $html .= ''; + } + } + $html .= '
'.$this->arr_alfabeto[$a].''.$this->arr_alfabeto[$a].'
'; + return $html; + } + function getImgesRelacionadas($tmp_id,$tmp_limit = ''){ + global $db; + global $load; + global $input; + + $load->config('classes/Imagem.php'); + $o_imagem = new Imagem(); + + if($tmp_limit != ''){ + $tmp_limit = " LIMIT ".$tmp_limit; + } + + $sql = "SELECT cei.id_imagem,i.nome FROM sis_casoestudo_imagem cei INNER JOIN + sis_imagem i ON i.id = id_imagem WHERE i.visualizacao = 1 AND cei.id_casoestudo = ".$tmp_id." ".$tmp_limit; + $rowsImagem = $db->execute($sql); + if(!$rowsImagem->EOF){ + $html = ''; + while(!$rowsImagem->EOF){ + $src = $o_imagem->getImage($rowsImagem->fields('id_imagem'),'pp'); + if($src != ''){ + $html .= '
'.$rowsImagem->fields('nome').'
'; + } + $rowsImagem->moveNext(); + } + return $html; + } else { + if($tmp_limit == ''){ + return 'Nenhuma imagem relacionada.'; + } + return ''; + } + } + function getOrdenar($tmp_baseLink = ''){ + $html = '
Ordenar por:  '; + $total = sizeof($this->arr_ordenar); + for($x=0;$x<$total;$x++){ + if($this->arr_ordenar[$x] == $this->filtro_ordenar){ + $html .= ''.$this->arr_ordenar[$x].''; + } else { + $html .= ''.$this->arr_ordenar[$x].''; + } + if(($x+1) < $total){ + $html .= '  '; + } + } + $html .= '
'; + return $html; + } + function searchLetter($tmp_letra){ + global $db; + + $sql = "SELECT ce.id,ce.codigo, + ce.id_especialidade, + ce.id_usuario, + ce.nome, + SUBSTRING(ce.texto,1,250) as texto, + esp.nome as especialidade, + u.nome as professor + FROM sis_casoestudo ce + LEFT OUTER JOIN sis_especialidade esp ON ce.id_especialidade = esp.id + LEFT OUTER JOIN admin_usuario u ON ce.id_usuario = u.id + WHERE ce.visualizacao = 1 AND ce.nome like '".$tmp_letra."%' ".$this->getOrderBy(); + return $db->execute($sql); + } + function simpleSeach($tmp_palavraChave,$tmp_professor = '',$tmp_especialidade = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = '',$tmp_codigo = ''){ + global $db; + global $o_helper; + $o_helper->somaBusca($tmp_palavraChave); + + $andPalavraChave = ''; + if($tmp_palavraChave != ''){ + $andPalavraChave = " AND ( + ce.nome like '%".$tmp_palavraChave."%' OR + ce.texto like '%".$tmp_palavraChave."%' OR + ce.palavrachave like '%".$tmp_palavraChave."%' OR + i.nome like '%".$tmp_palavraChave."%' OR + d.nome like '%".$tmp_palavraChave."%' OR + o.nome like '%".$tmp_palavraChave."%' OR + pat.nome like '%".$tmp_palavraChave."%' OR + sis.nome like '%".$tmp_palavraChave."%' + ) "; + } + $andProfessor = ''; + if($tmp_professor != ''){ + $andProfessor = ' AND ce.id_usuario = '.$tmp_professor.' '; + } + $andEspecialidade = ''; + if($tmp_especialidade != ''){ + $andEspecialidade = ' AND ce.id_especialidade = '.$tmp_especialidade.' '; + } + $andSistema = ''; + if($tmp_sistema != ''){ + $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' '; + } + $andPatologia = ''; + if($tmp_patologia != ''){ + $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' '; + } + $andGrupoOrgao = ''; + if($tmp_grupoorgao != ''){ + $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' '; + } + $andCodigo = ''; + if($tmp_codigo != ''){ + $andCodigo = " AND ce.codigo LIKE '%".$tmp_codigo."%'"; + } + + $sql = "SELECT ce.id,ce.codigo, + ce.id_especialidade, + ce.id_usuario, + ce.nome, + SUBSTRING(ce.texto,1,250) as texto, + esp.nome as especialidade, + u.nome as professor + + FROM sis_casoestudo ce + LEFT OUTER JOIN sis_especialidade esp ON ce.id_especialidade = esp.id + LEFT OUTER JOIN admin_usuario u ON ce.id_usuario = u.id + + LEFT OUTER JOIN sis_casoestudo_imagem cei ON ce.id = cei.id_casoestudo + LEFT OUTER JOIN sis_imagem i ON cei.id_imagem = i.id + + LEFT OUTER JOIN sis_casoestudo_diagnostico ced ON ce.id = ced.id_casoestudo + LEFT OUTER JOIN sis_diagnostico d ON ced.id_diagnostico = d.id + + LEFT OUTER JOIN sis_casoestudo_orgao ceo ON ce.id = ceo.id_casoestudo + LEFT OUTER JOIN sis_orgao o ON ceo.id_orgao = o.id + LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao + + LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id + LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id + + WHERE ce.visualizacao = 1 ".$andPalavraChave.$andProfessor.$andEspecialidade.$andSistema.$andPatologia.$andGrupoOrgao.$andCodigo." GROUP BY ce.id ".$this->getOrderBy(); + return $db->execute($sql); + } + function complexSeach($arrPalavra,$tmp_professor = '',$tmp_especialidade = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = '',$tmp_codigo = ''){ + global $db; + global $o_helper; + + $andProfessor = ''; + if($tmp_professor != ''){ + $andProfessor = ' AND ce.id_usuario = '.$tmp_professor.' '; + } + $andEspecialidade = ''; + if($tmp_especialidade != ''){ + $andEspecialidade = ' AND ce.id_especialidade = '.$tmp_especialidade.' '; + } + $andSistema = ''; + if($tmp_sistema != ''){ + $andSistema = ' AND i.id_sistema = '.$tmp_sistema.' '; + } + $andPatologia = ''; + if($tmp_patologia != ''){ + $andPatologia = ' AND i.id_patologia = '.$tmp_patologia.' '; + } + $andGrupoOrgao = ''; + if($tmp_grupoorgao != ''){ + $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' '; + } + $andCodigo = ''; + if($tmp_codigo != ''){ + $andCodigo = " AND ce.codigo LIKE '%".$tmp_codigo."%'"; + } + + $fixedWhere = " ce.visualizacao = 1 ".$andProfessor.$andEspecialidade.$andSistema.$andPatologia.$andGrupoOrgao.$andCodigo; + + $arrWhere = array(); + $arrWhere[] = "ce.nome like '%#PALAVRA#%'"; + $arrWhere[] = "ce.texto like '%#PALAVRA#%'"; + $arrWhere[] = "ce.palavrachave like '%#PALAVRA#%'"; + $arrWhere[] = "i.nome like '%#PALAVRA#%'"; + $arrWhere[] = "d.nome like '%#PALAVRA#%'"; + $arrWhere[] = "o.nome like '%#PALAVRA#%'"; + $arrWhere[] = "pat.nome like '%#PALAVRA#%'"; + $arrWhere[] = "sis.nome like '%#PALAVRA#%'"; + + $baseSql = "SELECT ce.id,ce.codigo, + ce.id_especialidade, + ce.id_usuario, + ce.nome, + SUBSTRING(ce.texto,1,250) as texto, + esp.nome as especialidade, + u.nome as professor + + FROM sis_casoestudo ce + LEFT OUTER JOIN sis_especialidade esp ON ce.id_especialidade = esp.id + LEFT OUTER JOIN admin_usuario u ON ce.id_usuario = u.id + + LEFT OUTER JOIN sis_casoestudo_imagem cei ON ce.id = cei.id_casoestudo + LEFT OUTER JOIN sis_imagem i ON cei.id_imagem = i.id + + LEFT OUTER JOIN sis_casoestudo_diagnostico ced ON ce.id = ced.id_casoestudo + LEFT OUTER JOIN sis_diagnostico d ON ced.id_diagnostico = d.id + + LEFT OUTER JOIN sis_casoestudo_orgao ceo ON ce.id = ceo.id_casoestudo + LEFT OUTER JOIN sis_orgao o ON ceo.id_orgao = o.id + LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao + + LEFT OUTER JOIN sis_patologia pat ON i.id_patologia = pat.id + LEFT OUTER JOIN sis_sistema sis ON i.id_sistema = sis.id + #WHERE# + ".$this->getOrderBy(); + + return $db->execute($o_helper->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function getOrderBy(){ + switch($this->filtro_ordenar){ + case 'Nome': + return ' ORDER BY ce.nome ASC'; + break; + case 'Especialidade': + return ' ORDER BY especialidade ASC'; + break; + case 'Sistema': + return ' ORDER BY sistema ASC'; + break; + case 'Patologia': + return ' ORDER BY patologia ASC'; + break; + } + } + function findCasoEstudoById($tmp_id){ + global $db; + + $sql = "SELECT ce.id,ce.codigo, + ce.id_especialidade, + ce.id_usuario, + ce.nome, + ce.texto, + esp.nome as especialidade, + u.nome as professor + FROM sis_casoestudo ce + LEFT OUTER JOIN sis_especialidade esp ON ce.id_especialidade = esp.id + LEFT OUTER JOIN admin_usuario u ON ce.id_usuario = u.id + WHERE ce.visualizacao = 1 AND ce.id = ".$tmp_id." GROUP BY ce.id ".$this->getOrderBy(); + return $db->execute($sql); + } + function orgaosrelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsOrgao = $db->execute($sql); + + $obj = ''; + if(!$rowsOrgao->EOF){ + $obj .= 'Orgãos Relacionados:
'; + while(!$rowsOrgao->EOF){ + $obj .= ''.$rowsOrgao->fields('nome').'
'; + $rowsOrgao->moveNext(); + } + } + return $obj; + } + function diagnosticosrelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsDiagnostico = $db->execute($sql); + + $obj = ''; + if(!$rowsDiagnostico->EOF){ + while(!$rowsDiagnostico->EOF){ + $obj .= '
'.$rowsDiagnostico->fields('nome').'
'; + $rowsDiagnostico->moveNext(); + } + } else { + $obj = 'Nenhum diagnóstico relacionado.'; + } + return $obj; + } + function findComentariosByIdCasoEstudo($tmp_id){ + global $db; + + $sql = "SELECT id, id_casoestudo, nome, comentario FROM sis_casoestudo_comentario WHERE status = 1 AND id_casoestudo = ".$tmp_id." ORDER BY datacomentario DESC"; + return $db->execute($sql); + } + function insertComentario(){ + global $input; + global $db; + + $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)"; + $db->execute($sql); + if(mysql_insert_id() != 0){ + return 1; + } else { + return 0; + } + } + function inativeComentario($tmp_id){ + global $db; + + if($tmp_id != ''){ + $sql = "UPDATE sis_casoestudo_comentario SET status = 0 WHERE id = ".$tmp_id; + $db->execute($sql); + return 1; + } + return 0; + } +} +?> \ No newline at end of file diff --git a/_config/classes/Diagnostico.php b/_config/classes/Diagnostico.php new file mode 100644 index 0000000..850bfe3 --- /dev/null +++ b/_config/classes/Diagnostico.php @@ -0,0 +1,402 @@ +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'); + $this->arr_resultado = array('08','16','32'); + $this->arr_ordenar = array('Nome','Especialidade'); + $this->getFiltrosFromSession($tmp_patologia); + } + function setAlfabetoDiagnostico($tmp_patologia = '') { + global $input; + + $session = 'session_letras_diagnostico'; + if($tmp_patologia != ''){ + $session = 'session_letras_diagnostico_necropsia'; + } + + if ($input->session($session) != '') { + $this->arr_alfabeto_diagnostico = unserialize($input->session($session)); + if($this->arr_alfabeto_diagnostico == ''){ + $this->arr_alfabeto_diagnostico = array(); + } + } else { + $rowsLetra = $this->findLetraDiagnostico($tmp_patologia); + $this->arr_alfabeto_diagnostico = array(); + while (!$rowsLetra->EOF) { + $this->arr_alfabeto_diagnostico[] = strtoupper($rowsLetra->fields('letra')); + $rowsLetra->moveNext(); + } + $input->setSession($session,serialize($this->arr_alfabeto_diagnostico)); + } + } + function findLetraDiagnostico($tmp_patologia = '') { + global $db; + + $sql = "SELECT DISTINCT(SUBSTRING(nome,1,1)) AS letra FROM sis_diagnostico WHERE visualizacao = 1 ORDER BY nome ASC"; + if($tmp_patologia != ''){ + $sql = "SELECT DISTINCT(SUBSTRING(d.nome,1,1)) AS letra FROM sis_diagnostico d + INNER JOIN sis_diagnostico_imagem di ON d.id = di.id_diagnostico + INNER JOIN sis_imagem i ON di.id_imagem = i.id + WHERE d.visualizacao = 1 AND i.id_patologia = ".$tmp_patologia." + GROUP BY d.id + ORDER BY d.nome ASC"; + } + return $db->execute($sql); + } + function getFiltrosFromSession($tmp_patologia = ''){ + $this->setAlfabetoDiagnostico($tmp_patologia); + + global $input; + $this->filtro_palavra = $input->session('session_diagnostico_filtro_palavra'); + $this->filtro_procedencia = $input->session('session_diagnostico_filtro_procedencia'); + $this->filtro_sistema = $input->session('session_diagnostico_filtro_sistema'); + $this->filtro_patologia = $input->session('session_diagnostico_filtro_patologia'); + + $this->filtro_ordenar = $input->get('diagnostico_filtro_ordenar'); + if($this->filtro_ordenar == ''){ + $this->filtro_ordenar = $input->session('session_diagnostico_filtro_ordenar'); + if($this->filtro_ordenar == ''){ + $this->filtro_ordenar = $this->arr_ordenar[0]; + } + } else { + $input->setSession('session_diagnostico_filtro_ordenar',$this->filtro_ordenar); + } + + $this->filtro_resultado = $input->get('diagnostico_filtro_resultado'); + if($this->filtro_resultado == ''){ + $this->filtro_resultado = $input->session('session_diagnostico_filtro_resultado'); + if($this->filtro_resultado == ''){ + $this->filtro_resultado = $this->arr_resultado[0]; + } + } else { + $input->setSession('session_diagnostico_filtro_resultado',$this->filtro_resultado); + } + } + function getAlfabeto(){ + $html = ''; + $total = sizeof($this->arr_alfabeto); + for($a=0;$a<$total;$a++){ + if(in_array($this->arr_alfabeto[$a],$this->arr_alfabeto_diagnostico)){ + $html .= ''; + } else { + $html .= ''; + } + } + $html .= '
'.$this->arr_alfabeto[$a].''.$this->arr_alfabeto[$a].'
'; + return $html; + } + function getResultado($tmp_baseLink = ''){ + $html = '
Resultados por página:  '; + $total = sizeof($this->arr_resultado); + for($r=0;$r<$total;$r++){ + if($this->arr_resultado[$r] == $this->filtro_resultado){ + $html .= ''.$this->arr_resultado[$r].''; + } else { + $html .= ''.$this->arr_resultado[$r].''; + } + if(($r+1) < $total){ + $html .= '  '; + } + } + $html .= '
'; + return $html; + } + function getOrdenar($tmp_baseLink = ''){ + $html = '
Ordenar por:  '; + $total = sizeof($this->arr_ordenar); + for($x=0;$x<$total;$x++){ + if($this->arr_ordenar[$x] == $this->filtro_ordenar){ + $html .= ''.$this->arr_ordenar[$x].''; + } else { + $html .= ''.$this->arr_ordenar[$x].''; + } + if(($x+1) < $total){ + $html .= '  '; + } + } + $html .= '
'; + return $html; + } + function getImages($tmp_id){ + global $db; + + $sql = "SELECT id, nome FROM sis_imagem i + INNER JOIN sis_diagnostico_imagem di ON di.id_imagem = i.id + WHERE di.id_diagnostico = ".$tmp_id; + return $db->execute($sql); + } + function searchLetter($tmp_letra,$tmp_patologia = ''){ + global $db; + + $sql = "SELECT d.id, + d.id_especialidade, + d.nome, + d.cid10, + SUBSTRING(d.texto,0,250) as texto, + esp.nome as especialidade + + FROM sis_diagnostico d + LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id + WHERE d.visualizacao = 1 AND ( + d.nome like '".$tmp_letra."%') GROUP BY d.id ".$this->getOrderBy(); + if($tmp_patologia != ''){ + $sql = "SELECT d.id, + d.id_especialidade, + d.nome, + d.cid10, + SUBSTRING(d.texto,0,250) as texto, + esp.nome as especialidade + + FROM sis_diagnostico d + INNER JOIN sis_diagnostico_imagem di ON d.id = di.id_diagnostico + INNER JOIN sis_imagem i ON di.id_imagem = i.id + LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id + WHERE d.visualizacao = 1 AND i.id_patologia = ".$tmp_patologia." AND ( + d.nome like '".$tmp_letra."%') GROUP BY d.id ".$this->getOrderBy(); + } + return $db->execute($sql); + } + function simpleSeach($tmp_palavraChave,$tmp_especialidade = '',$tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = ''){ + global $db; + global $o_helper; + $o_helper->somaBusca($tmp_palavraChave); + + $andPalavraChave = ''; + if($tmp_palavraChave != ''){ + $andPalavraChave = " AND ( + d.nome like '%".$tmp_palavraChave."%' OR + d.texto like '%".$tmp_palavraChave."%' OR + d.palavrachave like '%".$tmp_palavraChave."%' OR + i.nome like '%".$tmp_palavraChave."%' OR + proc.nome like '%".$tmp_palavraChave."%' OR + pat.nome like '%".$tmp_palavraChave."%' OR + sis.nome like '%".$tmp_palavraChave."%' OR + c.nome like '%".$tmp_palavraChave."%' OR + c.palavrachave like '%".$tmp_palavraChave."%' + ) "; + } + $andEspecialidade = ''; + if($tmp_especialidade != ''){ + $andEspecialidade = ' AND d.id_especialidade = '.$tmp_especialidade.' '; + } + $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.' '; + } + $andGrupoOrgao = ''; + if($tmp_grupoorgao != ''){ + $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' '; + } + + $sql = "SELECT d.id, + d.id_especialidade, + d.nome, + d.cid10, + SUBSTRING(d.texto,1,250) as texto, + esp.nome as especialidade + + FROM sis_diagnostico d + LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id + + LEFT OUTER JOIN sis_diagnostico_imagem di ON d.id = di.id_diagnostico + LEFT OUTER JOIN sis_imagem i ON di.id_imagem = i.id + + 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_orgao do ON d.id = do.id_diagnostico + LEFT OUTER JOIN sis_orgao o ON do.id_orgao = o.id + LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao + + LEFT OUTER JOIN sis_casoestudo_diagnostico cd ON d.id = cd.id_diagnostico + LEFT OUTER JOIN sis_casoestudo c ON cd.id_casoestudo = c.id + WHERE d.visualizacao = 1 ".$andPalavraChave.$andEspecialidade.$andProcedencia.$andSistema.$andPatologia.$andGrupoOrgao." GROUP BY d.id ".$this->getOrderBy(); + return $db->execute($sql); + } + function complexSeach($arrPalavra,$tmp_especialidade = '',$tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = ''){ + global $db; + global $o_helper; + + $andEspecialidade = ''; + if($tmp_especialidade != ''){ + $andEspecialidade = ' AND d.id_especialidade = '.$tmp_especialidade.' '; + } + $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.' '; + } + $andGrupoOrgao = ''; + if($tmp_grupoorgao != ''){ + $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' '; + } + + $fixedWhere = " d.visualizacao = 1 ".$andEspecialidade.$andProcedencia.$andSistema.$andPatologia.$andGrupoOrgao; + + $arrWhere = array(); + $arrWhere[] = "d.nome like '%#PALAVRA#%'"; + $arrWhere[] = "d.texto like '%#PALAVRA#%'"; + $arrWhere[] = "d.palavrachave like '%#PALAVRA#%'"; + $arrWhere[] = "i.nome like '%#PALAVRA#%'"; + $arrWhere[] = "proc.nome like '%#PALAVRA#%'"; + $arrWhere[] = "pat.nome like '%#PALAVRA#%'"; + $arrWhere[] = "sis.nome like '%#PALAVRA#%'"; + $arrWhere[] = "c.nome like '%#PALAVRA#%'"; + $arrWhere[] = "c.palavrachave like '%#PALAVRA#%'"; + + $baseSql = "SELECT d.id, + d.id_especialidade, + d.nome, + d.cid10, + SUBSTRING(d.texto,1,250) as texto, + esp.nome as especialidade + + FROM sis_diagnostico d + LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id + + LEFT OUTER JOIN sis_diagnostico_imagem di ON d.id = di.id_diagnostico + LEFT OUTER JOIN sis_imagem i ON di.id_imagem = i.id + + 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_orgao do ON d.id = do.id_diagnostico + LEFT OUTER JOIN sis_orgao o ON do.id_orgao = o.id + LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao + + LEFT OUTER JOIN sis_casoestudo_diagnostico cd ON d.id = cd.id_diagnostico + LEFT OUTER JOIN sis_casoestudo c ON cd.id_casoestudo = c.id + #WHERE# + GROUP BY d.id + ".$this->getOrderBy(); + + return $db->execute($o_helper->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function getImgesRelacionadas($tmp_id,$tmp_limit = ''){ + global $db; + global $load; + global $input; + + $load->config('classes/Imagem.php'); + $o_imagem = new Imagem(); + + if($tmp_limit != ''){ + $tmp_limit = " LIMIT ".$tmp_limit; + } + + $sql = "SELECT di.id_imagem,i.nome FROM sis_diagnostico_imagem di INNER JOIN + sis_imagem i ON i.id = id_imagem WHERE i.visualizacao = 1 AND di.id_diagnostico = ".$tmp_id." ".$tmp_limit; + $rowsImagem = $db->execute($sql); + if(!$rowsImagem->EOF){ + $html = ''; + while(!$rowsImagem->EOF){ + $src = $o_imagem->getImage($rowsImagem->fields('id_imagem'),'pp'); + if($src != ''){ + $html .= '
'.$rowsImagem->fields('nome').'
'; + } + $rowsImagem->moveNext(); + } + return $html; + } else { + return ''; + } + } + function findDiagnoticoById($tmp_id){ + global $db; + + $sql = "SELECT d.id, + d.id_especialidade, + d.nome, + d.cid10, + d.texto, + esp.nome as especialidade + + FROM sis_diagnostico d + LEFT OUTER JOIN sis_especialidade esp ON d.id_especialidade = esp.id + WHERE d.visualizacao = 1 AND d.id = ".$tmp_id." GROUP BY d.id ".$this->getOrderBy(); + return $db->execute($sql); + } + function orgaosrelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsOrgao = $db->execute($sql); + + $obj = ''; + if(!$rowsOrgao->EOF){ + $obj .= 'Orgãos Relacionados:
'; + while(!$rowsOrgao->EOF){ + $obj .= ''.$rowsOrgao->fields('nome').'
'; + $rowsOrgao->moveNext(); + } + } + return $obj; + } + function casosdeestudorelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsDiagnostico = $db->execute($sql); + + $obj = ''; + if(!$rowsDiagnostico->EOF){ + while(!$rowsDiagnostico->EOF){ + $obj .= '
'.$rowsDiagnostico->fields('nome').'
'; + $rowsDiagnostico->moveNext(); + } + } else { + $obj = 'Nenhum caso de estudo relacionado.'; + } + return $obj; + } + function getOrderBy(){ + switch($this->filtro_ordenar){ + case 'Nome': + return ' ORDER BY d.nome ASC'; + break; + case 'Especialidade': + return ' ORDER BY especialidade ASC'; + break; + case 'Sistema': + return ' ORDER BY sistema ASC'; + break; + case 'Patologia': + return ' ORDER BY patologia ASC'; + break; + } + } +} +?> \ No newline at end of file diff --git a/_config/classes/GrupoOrgao.php b/_config/classes/GrupoOrgao.php new file mode 100644 index 0000000..602a206 --- /dev/null +++ b/_config/classes/GrupoOrgao.php @@ -0,0 +1,22 @@ +execute($sql); + } + function findGrupoByCamada($tmp_idCamada){ + global $db; + + $sql = "SELECT g.id,g.nome,g.x1,g.y1,g.x2,g.y2,(g.x1 * g.y1) as area FROM sis_grupoorgao g + WHERE id_camada = ".$tmp_idCamada." ORDER BY area"; + return $db->execute($sql); + } +} +?> \ No newline at end of file diff --git a/_config/classes/Helper.php b/_config/classes/Helper.php new file mode 100644 index 0000000..3b0d407 --- /dev/null +++ b/_config/classes/Helper.php @@ -0,0 +1,262 @@ +get('palavrachave') != '') + || ($input->get('grupoorgao') != '') + || ($input->get('procedencia') != '') + || ($input->get('sistema') != '') + || ($input->get('patologia') != '') + || ($input->get('especialidade') != '') + || ($input->get('professor') != '') + || ($input->get('boneco') != '') + || ($input->get('codigo') != '') + || (($input->get('letra') != '') && ($tmp_letra))){ + return true; + } else { + return false; + } + } + function findTopografiaById($tmp_id){ + if($tmp_id != ''){ + global $db; + + $sql = "SELECT id,nome FROM sis_grupoorgao WHERE id = ".$tmp_id." ORDER BY nome ASC LIMIT 1"; + $row = $db->execute($sql); + if($row->EOF){ + return ''; + } else { + return $row->fields('nome'); + } + } + } + function findEspecialidade($tmp_asArray = false){ + global $db; + + $sql = "SELECT id,nome FROM sis_especialidade ORDER BY nome ASC"; + if($tmp_asArray){ + return $this->rowsIdNomeToArray($db->execute($sql)); + } else { + return $db->execute($sql); + } + } + function findGrupoOrgao($tmp_asArray = false){ + global $db; + + $sql = "SELECT id,nome FROM sis_grupoorgao ORDER BY nome ASC"; + if($tmp_asArray){ + return $this->rowsIdNomeToArray($db->execute($sql)); + } else { + return $db->execute($sql); + } + } + function findProfesores($tmp_asArray = false){ + global $db; + + $sql = "SELECT u.id,u.nome FROM admin_usuario u + INNER JOIN sis_casoestudo ce ON ce.id_usuario = u.id + GROUP BY u.id ORDER BY u.nome ASC"; + if($tmp_asArray){ + return $this->rowsIdNomeToArray($db->execute($sql)); + } else { + return $db->execute($sql); + } + } + function findProcedencias($tmp_asArray = false){ + global $db; + + $sql = "SELECT id,nome FROM sis_procedencia ORDER BY nome ASC"; + if($tmp_asArray){ + return $this->rowsIdNomeToArray($db->execute($sql)); + } else { + return $db->execute($sql); + } + } + function findSistemas($tmp_asArray = false){ + global $db; + + $sql = "SELECT id,nome FROM sis_sistema ORDER BY nome ASC"; + if($tmp_asArray){ + return $this->rowsIdNomeToArray($db->execute($sql)); + } else { + return $db->execute($sql); + } + } + function findPatologias($tmp_asArray = false){ + global $db; + + $sql = "SELECT id,nome FROM sis_patologia ORDER BY nome ASC"; + if($tmp_asArray){ + return $this->rowsIdNomeToArray($db->execute($sql)); + } else { + return $db->execute($sql); + } + } + function rowsIdNomeToArray($tmp_rows){ + $arr = Array(); + + while(!$tmp_rows->EOF){ + $arr[$tmp_rows->fields("id")] = $tmp_rows->fields("nome"); + $tmp_rows->moveNext(); + } + return $arr; + } + function somaBusca($tmp_palavraChave){ + global $db; + + if($tmp_palavraChave != ''){ + $sql = "SELECT * FROM sis_palavrabusca WHERE palavra = '".$tmp_palavraChave."'"; + $rowPalavra = $db->execute($sql); + if($rowPalavra->EOF){ + $sql = "INSERT INTO sis_palavrabusca (palavra,quantidade) VALUES('".$tmp_palavraChave."',1)"; + $db->execute($sql); + } else { + $sql = "UPDATE sis_palavrabusca SET quantidade = quantidade+1 WHERE palavra ='".$tmp_palavraChave."'"; + $db->execute($sql); + } + } + } + function findPalavraAproximada($palavra, $sql = ""){ + global $db; + global $load; + + $load->system("functions/text.php"); + + $min = 55; + $mid = 80; + + $arr_busca = explode(' ',$palavra); + $arr_palavras = array(); + if($sql == "") + $sql = "SELECT palavra FROM sis_palavra WHERE status = 1"; + $rs = $db->execute($sql); + while(!$rs->EOF){ + $arr_now = explode(" ",$rs->fields("palavra")); + if(is_array($arr_now)) { + for($x=0,$total=sizeof($arr_now);$x<$total;$x++){ + $arr_palavras[] = formatNameFile($arr_now[$x]); + } + } else { + $arr_palavras[] = formatNameFile($arr_now); + } + $rs->moveNext(); + } + $arr_palavras = array_values(array_unique($arr_palavras)); + $arr = array(array()); + + $porcentagem = 0; + + // BUSCA TODA A PALAVRA + for($x=0,$total=sizeof($arr_palavras);$x<$total;$x++){ + similar_text($palavra,$arr_palavras[$x],$r); + if ($r > $min) { + if ($r >= $mid) { + if ($porcentagem < $mid) { + $arr[0] = array(); + } + } + + if ($porcentagem < $r) { + $porcentagem = $r; + $arr[0][] = $arr_palavras[$x]; + } + } + } + + if (sizeof($arr_busca) > 1) { + $indice = 1; + //echo sizeof($arr_busca); + for ($x=0,$total=sizeof($arr_busca);$x<=$total;$x++) { + $porcentagem = 0; + //echo $x." - ".$total."
"; + if(isset($arr_busca[$x])){ + if (strlen($arr_busca[$x]) > 2) { + for($z=0,$total=sizeof($arr_palavras);$z<$total;$z++){ + similar_text($arr_busca[$x],$arr_palavras[$z],$r); + if ($r > $min) { + if ($r >= $mid) { + if ($porcentagem < $mid) { + $arr[$indice] = array(); + } + } + + if ($porcentagem < $r) { + $porcentagem = $r; + $arr[$indice][] = $arr_palavras[$z]; + } + } + } + $indice++; + } + } + } + } + + return $arr; + } + function makeSql($arrPalavra,$baseSql,$arrWherePalavra,$fixedWhere = ""){ + //arrPalavra: + //Array com as palavras aproximadas. Lembrando, posição 0, array de palavras completas (frases, titulos), posição 1, todas as palavras 'quebradas'. + + //baseSql: + //Sql contendo todo o conteudo necessario para fazer a busca naquela tabela, no lugar da sentença WHERE, subtituir por #WHERE#, como no exemplo: + //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 + + //arrWherePalavra: + //array com as condições, sem o where, e substituindo a palavra de busca por #PALAVRA#, como no exemplo: + //p.descricao LIKE '%#PALAVRA#%' + + //$fixedWhere: + //condições fixas a serem concatenadas com a query, como no exemplo: + //status = 1 AND data = '2009-10-20' + //note que não existe operador em nenhum dos lados (AND, OR, ou qualquer outro) + + if (isset($arrPalavra[0])) { + if ($arrPalavra[0] != '') { + $where = " AND (1=2 "; + for($x=0,$total=sizeof($arrPalavra[0]);$x<$total;$x++) { + $where .= " OR ("; + for($w=0,$totalW=sizeof($arrWherePalavra);$w<$totalW;$w++){ + if($w == 0){ + $where .= " ".str_replace("#PALAVRA#",$arrPalavra[0][$x],$arrWherePalavra[$w])." "; + } else { + $where .= " OR ".str_replace("#PALAVRA#",$arrPalavra[0][$x],$arrWherePalavra[$w])." "; + } + } + $where .= " )"; + } + $where .= ") "; + } else { + $where = 'AND 1=2'; + } + } elseif(isset($arrPalavra[1])) { + $where = ''; + for($i=1,$total=sizeof($arrPalavra);$i<=$total;$i++) { + $where .= " AND ((1=2) "; + for($x=0,$total=sizeof($arrPalavra[$i]);$x<=$total;$x++) { + if ($arrPalavra[$i][$x] != '') { + $where .= " OR ("; + for($w=0,$totalW=sizeof($arrWherePalavra);$w<$totalW;$w++){ + if($w == 0){ + $where .= " ".str_replace("#PALAVRA#",$arrPalavra[$i][$x],$arrWherePalavra[$w])." "; + } else { + $where .= " OR ".str_replace("#PALAVRA#",$arrPalavra[$i][$x],$arrWherePalavra[$w])." "; + } + } + $where .= " )"; + } + } + } + $where .= ") "; + } + if($fixedWhere == ""){ + $fixedWhere = " 1 = 1 "; + } else { + $fixedWhere = " ".$fixedWhere." "; + } + $sql = str_replace("#WHERE#"," WHERE ".$fixedWhere.$where,$baseSql); + return $sql; + } +} +?> \ No newline at end of file diff --git a/_config/classes/Html.php b/_config/classes/Html.php new file mode 100644 index 0000000..c96a29c --- /dev/null +++ b/_config/classes/Html.php @@ -0,0 +1,148 @@ +'; + return $obj; + } + function getInput($label,$sufixo,$name,$extra = "",$testDV = true,$type = "text"){ + $obj = ''; + switch($type){ + case "text": + $func = ' onfocus="javascript: swapI(this,true);" onblur="javascript: swapI(this,false);" testDV="true" '; + $value = $label; + + if(!$testDV){ + $func = ''; + $value = ''; + } + + $obj = ''; + break; + case "password": + $id = $label.'_'.$sufixo; + $func = ' onfocus="javascript: swapP(document.getElementById(\'div'.$id.'\'),true);" onblur="javascript: swapP(this,false);" '; + + $obj = '
'.$label.'
'; + if(!$testDV){ + $func = ''; + $obj = ''; + } + $obj .= ''; + break; + case "textarea": + $id = $label.'_'.$sufixo; + $func = ' onfocus="javascript: swapI(this,true);" onblur="javascript: swapI(this,false);" testDV="true" '; + $value = $label; + + if(!$testDV){ + $func = ''; + $value = ''; + } + + $obj .= ''; + break; + } + return $obj; + } + function getSelect($arr,$label,$sufixo,$name,$extra = "",$secondItem = "------",$selected = ""){ + $obj = ''; + $total = sizeof($arr); + + if($total > 0){ + $obj = ''; + } + + return $obj; + } + function getSelectByRows($rows,$label,$sufixo,$name,$extra = "",$secondItem = "------",$selected = ""){ + $arr = Array(); + + while(!$rows->EOF){ + $arr[$rows->fields("id")] = $rows->fields("nome"); + $rows->moveNext(); + } + + return $this->getSelect($arr,$label,$sufixo,$name,$extra,$secondItem,$selected); + } + function getSelectByPagecount($pagecount,$label,$sufixo,$name,$extra = "",$zeroBased = true){ + $arr = array(); + for($x=1;$x<=$pagecount;$x++){ + if($zeroBased){ + $arr[] = $x; + } else { + $arr[$x] = $x; + } + } + + $obj = ''; + $total = sizeof($arr); + + if($total > 0){ + $obj = ''; + } + + return $obj; + } + function getTitle($arr_caminho = array()){ + global $cfg; + + if (sizeof($arr_caminho)>0) { + $titulo = ''; + + for($x=0,$total=sizeof($arr_caminho);$x<$total;$x++){ + $titulo .= $arr_caminho[$x][0] . ' - '; + } + $titulo .= 'FLY BY NIGHT'; + } else { + $titulo = $cfg["site_title"]; + } + + echo(''. $titulo .''); + } + function getBoneco($label,$sufixo,$name){ + $obj = ''; + + $obj = '
+ +
+
+
'; + + return $obj; + } +} +?> \ No newline at end of file diff --git a/_config/classes/Imagem.php b/_config/classes/Imagem.php new file mode 100644 index 0000000..ed616ba --- /dev/null +++ b/_config/classes/Imagem.php @@ -0,0 +1,513 @@ +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'); + $this->arr_resultado = array('08','16','32'); + $this->arr_ordenar = array('Nome','Sistema','Patologia'); + $this->getFiltrosFromSession(); + } + function setAlfabetoImagem() { + global $input; + + if ($input->session('session_letras_imagem') != '') { + $this->arr_alfabeto_imagem = unserialize($input->session('session_letras_imagem')); + } else { + $rowsLetra = $this->findLetraImagem(); + + while (!$rowsLetra->EOF) { + $this->arr_alfabeto_imagem[] = strtoupper($rowsLetra->fields('letra')); + $rowsLetra->moveNext(); + } + $input->setSession('session_letras_imagem',serialize($this->arr_alfabeto_imagem)); + } + } + function findLetraImagem() { + global $db; + + $sql = "SELECT DISTINCT(SUBSTRING(nome,1,1)) AS letra FROM sis_imagem WHERE visualizacao = 1 ORDER BY nome ASC"; + return $db->execute($sql); + } + function getFiltrosFromSession(){ + $this->setAlfabetoImagem(); + + global $input; + $this->filtro_palavra = $input->session('session_image_filtro_palavra'); + $this->filtro_procedencia = $input->session('session_image_filtro_procedencia'); + $this->filtro_sistema = $input->session('session_image_filtro_sistema'); + $this->filtro_patologia = $input->session('session_image_filtro_patologia'); + + $this->filtro_ordenar = $input->get('image_filtro_ordenar'); + if($this->filtro_ordenar == ''){ + $this->filtro_ordenar = $input->session('session_image_filtro_ordenar'); + if($this->filtro_ordenar == ''){ + $this->filtro_ordenar = $this->arr_ordenar[0]; + } + } else { + $input->setSession('session_image_filtro_ordenar',$this->filtro_ordenar); + } + + $this->filtro_resultado = $input->get('image_filtro_resultado'); + if($this->filtro_resultado == ''){ + $this->filtro_resultado = $input->session('session_image_filtro_resultado'); + if($this->filtro_resultado == ''){ + $this->filtro_resultado = $this->arr_resultado[0]; + } + } else { + $input->setSession('session_image_filtro_resultado',$this->filtro_resultado); + } + } + function getResultado($tmp_baseLink = ''){ + $html = '
Resultados por página:  '; + $total = sizeof($this->arr_resultado); + for($r=0;$r<$total;$r++){ + if($this->arr_resultado[$r] == $this->filtro_resultado){ + $html .= ''.$this->arr_resultado[$r].''; + } else { + $html .= ''.$this->arr_resultado[$r].''; + } + if(($r+1) < $total){ + $html .= '  '; + } + } + $html .= '
'; + return $html; + } + function getAlfabeto(){ + $html = ''; + $total = sizeof($this->arr_alfabeto); + for($a=0;$a<$total;$a++){ + if(in_array($this->arr_alfabeto[$a],$this->arr_alfabeto_imagem)){ + $html .= ''; + } else { + $html .= ''; + } + } + $html .= '
'.$this->arr_alfabeto[$a].''.$this->arr_alfabeto[$a].'
'; + return $html; + } + function getOrdenar($tmp_baseLink = ''){ + $html = '
Ordenar por:  '; + $total = sizeof($this->arr_ordenar); + for($x=0;$x<$total;$x++){ + if($this->arr_ordenar[$x] == $this->filtro_ordenar){ + $html .= ''.$this->arr_ordenar[$x].''; + } else { + $html .= ''.$this->arr_ordenar[$x].''; + } + if(($x+1) < $total){ + $html .= '  '; + } + } + $html .= '
'; + return $html; + } + function findLastImages(){ + global $db; + + $sql = "SELECT id,nome FROM sis_imagem WHERE visualizacao = 1 ORDER BY dataorigem DESC LIMIT 9"; + return $db->execute($sql); + } + function getImage($tmp_id,$tmp_thumb = 'p',$tmp_method = 2){//p,m,g + global $load; + $load->system('library/Image.php'); + + $src = ''; + $baseDot = '../../../'; + $baseSrc = 'upload/sis_imagem/'.$tmp_id.'.jpg'; + $baseThb = '_system/scripts/image.php'; + if(file_exists($baseDot.$baseSrc)){ + switch($tmp_thumb){ + case 'pp': + if($tmp_method == 2){ + $src = str_replace('sis_imagem','sis_imagem_pp',$baseDot.$baseSrc); + if(!file_exists($src)){ + $img = new Image($baseDot.$baseSrc); + $img->resize(55, 48, 2); + $img->save($src); + } + } else { + $src = $baseDot.$baseThb.'?w=55&h=48&resize='.$tmp_method.'&file='.$baseSrc; + } + break; + case 'p': + if($tmp_method == 2){ + $src = str_replace('sis_imagem','sis_imagem_p',$baseDot.$baseSrc); + if(!file_exists($src)){ + $img = new Image($baseDot.$baseSrc); + $img->resize(86, 74, 2); + $img->save($src); + } + } else { + $src = $baseDot.$baseThb.'?w=86&h=74&resize='.$tmp_method.'&file='.$baseSrc; + } + break; + case 'm': + if($tmp_method == 2){ + $src = str_replace('sis_imagem','sis_imagem_m',$baseDot.$baseSrc); + if(!file_exists($src)){ + $img = new Image($baseDot.$baseSrc); + $img->resize(241, 207, 2); + $img->save($src); + } + } else { + $src = $baseDot.$baseThb.'?w=241&h=207&resize='.$tmp_method.'&file='.$baseSrc; + } + break; + case 'g': + $src = $baseDot.$baseThb.'?w=86&h=74&resize='.$tmp_method.'&file='.$baseSrc; + break; + } + } + return $src; + } + function findImageById($tmp_id){ + global $db; + + if($tmp_id == ''){ + $tmp_id = 0; + } + $sql = "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, + i.id_grupoimagem, + i.carimbo + 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 + WHERE visualizacao = 1 AND i.id = ".$tmp_id; + return $db->execute($sql); + } + function dataorigem($tmp_dataorigem){ + $obj = ''; + if($tmp_dataorigem != ''){ + $arr = explode('-',$tmp_dataorigem); + $obj = 'Data da imagem: '.$arr[2].'.'.$arr[1].'.'.$arr[0].'
'; + } + return $obj; + } + function procedencia($tmp_procedencia){ + $obj = ''; + if($tmp_procedencia != ''){ + $obj = 'Procedência: '.$tmp_procedencia.'
'; + } + return $obj; + } + function getImgesRelacionadasByGrupo($tmp_idGrupo,$tmp_limit = ''){ + global $db; + global $load; + global $input; + + $load->config('classes/Imagem.php'); + $o_imagem = new Imagem(); + + if($tmp_limit != ''){ + $tmp_limit = " LIMIT ".$tmp_limit; + } + + $sql = "SELECT i.id,i.nome FROM sis_imagem i WHERE i.visualizacao = 1 AND i.id_grupoimagem = ".$tmp_idGrupo." ".$tmp_limit; + $rowsImagem = $db->execute($sql); + + if(!$rowsImagem->EOF){ + $html = ''; + while(!$rowsImagem->EOF){ + $src = $o_imagem->getImage($rowsImagem->fields('id'),'pp'); + if($src != ''){ + $html .= '
'.$rowsImagem->fields('nome').'
'; + } + $rowsImagem->moveNext(); + } + return $html; + } else { + return ''; + } + } + function orgaosrelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsOrgao = $db->execute($sql); + + $obj = ''; + if(!$rowsOrgao->EOF){ + $obj .= 'Orgãos Relacionados:
'; + while(!$rowsOrgao->EOF){ + $obj .= ''.$rowsOrgao->fields('nome').'
'; + $rowsOrgao->moveNext(); + } + } + return $obj; + } + function diagnosticosrelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsDiagnostico = $db->execute($sql); + + $obj = ''; + if(!$rowsDiagnostico->EOF){ + while(!$rowsDiagnostico->EOF){ + $obj .= '
'.$rowsDiagnostico->fields('nome').'
'; + $rowsDiagnostico->moveNext(); + } + } else { + $obj = 'Nenhum diagnóstico relacionado.'; + } + return $obj; + } + function casosdeestudorelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsCasoEstudo = $db->execute($sql); + + $obj = ''; + if(!$rowsCasoEstudo->EOF){ + while(!$rowsCasoEstudo->EOF){ + $obj .= '
'.$rowsCasoEstudo->fields('nome').'
'; + $rowsCasoEstudo->moveNext(); + } + } else { + $obj = 'Nenhum caso de estudo relacionado.'; + } + return $obj; + } + function searchLetter($tmp_letra){ + global $db; + + $sql = "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 + WHERE i.visualizacao = 1 AND i.saudavel = 0 AND i.nome like '".$tmp_letra."%' ".$this->getOrderBy(); + return $db->execute($sql); + } + function simpleSeach($tmp_palavraChave,$tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = ''){ + global $db; + global $o_helper; + $o_helper->somaBusca($tmp_palavraChave); + + $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.' '; + } + $andGrupoOrgao = ''; + if($tmp_grupoorgao != ''){ + $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' '; + } + + $sql = "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.$andGrupoOrgao." GROUP BY i.id ".$this->getOrderBy(); + return $db->execute($sql); + } + function complexSeach($arrPalavra,$tmp_procedencia = '',$tmp_sistema = '',$tmp_patologia = '',$tmp_grupoorgao = ''){ + global $db; + global $o_helper; + + $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.' '; + } + $andGrupoOrgao = ''; + if($tmp_grupoorgao != ''){ + $andGrupoOrgao = ' AND og.id_grupoorgao = '.$tmp_grupoorgao.' '; + } + + $fixedWhere = " i.visualizacao = 1 AND i.saudavel = 0 ".$andProcedencia.$andSistema.$andPatologia.$andGrupoOrgao; + + $arrWhere = array(); + $arrWhere[] = "i.nome like '%#PALAVRA#%'"; + $arrWhere[] = "i.texto like '%#PALAVRA#%'"; + $arrWhere[] = "proc.nome like '%#PALAVRA#%'"; + $arrWhere[] = "pat.nome like '%#PALAVRA#%'"; + $arrWhere[] = "sis.nome like '%#PALAVRA#%'"; + $arrWhere[] = "d.nome like '%#PALAVRA#%'"; + $arrWhere[] = "d.palavrachave like '%#PALAVRA#%'"; + $arrWhere[] = "o.nome like '%#PALAVRA#%'"; + $arrWhere[] = "o.palavrachave like '%#PALAVRA#%'"; + $arrWhere[] = "c.nome like '%#PALAVRA#%'"; + $arrWhere[] = "c.palavrachave like '%#PALAVRA#%'"; + + $baseSql = "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# + GROUP BY i.id ".$this->getOrderBy(); + + return $db->execute($o_helper->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function getOrderBy(){ + switch($this->filtro_ordenar){ + case 'Nome': + return ' ORDER BY i.nome ASC'; + break; + case 'Sistema': + return ' ORDER BY sistema ASC'; + break; + case 'Patologia': + return ' ORDER BY patologia ASC'; + break; + } + } + function verifyWaterMark($tmp_id,$tmp_carimbo,$tmp_overwrite = false){ + if($tmp_carimbo != 4){ + global $load; + global $input; + + $baseBack = '../../../'; + $basePath = 'upload/sis_imagem/'.$tmp_id.'.jpg'; + $baseNewPath = str_replace('sis_imagem','sis_imagem_wm',$basePath); + $wm_Path = '_config/img/logo.png'; + + $padding = 15; + $wm_width = 85;//largura da imagem de marca d'agua + $wm_height = 82;//altura da imagem de marca d'agua + + if((file_exists($baseBack.$basePath)) && (($tmp_overwrite) || (!file_exists($baseBack.$baseNewPath)))){ + $load->system('library/Image.php'); + $img = new Image($baseBack.$basePath); + + //calcula posição inicial da marca d'agua conforme a escolha do usuario + $tmp_x = 0; + $tmp_y = 0; + switch($tmp_carimbo){ + case 0://Esquerdo superior + $tmp_x = $padding; + $tmp_y = $padding; + break; + case 1://Direito superior + $tmp_x = $img->width - $wm_width - $padding; + $tmp_y = $padding; + break; + case 2://Esquerdo inferior + $tmp_x = $padding; + $tmp_y = $img->height - $wm_height - $padding; + break; + case 3://Direito inferior + $tmp_x = $img->width - $wm_width - $padding; + $tmp_y = $img->height - $wm_height - $padding; + break; + } + + $img->waterMark($baseBack.$wm_Path,$tmp_x,$tmp_y,$baseBack.$baseNewPath); + } + } + } + function saudavel($tmp_saudavel){ + if($tmp_saudavel == '1'){ + return '(saudável)'; + } + } +} +?> \ No newline at end of file diff --git a/_config/classes/Orgao.php b/_config/classes/Orgao.php new file mode 100644 index 0000000..36fffc8 --- /dev/null +++ b/_config/classes/Orgao.php @@ -0,0 +1,395 @@ +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'); + $this->arr_resultado = array('08','16','32'); + $this->arr_ordenar = array('Nome'); + $this->getFiltrosFromSession(); + } + function setAlfabetoOrgao() { + global $input; + + if ($input->session('session_letras_orgao') != '') { + $this->arr_alfabeto_orgao = unserialize($input->session('session_letras_orgao')); + } else { + $rowsLetra = $this->findLetraOrgao(); + + while (!$rowsLetra->EOF) { + $this->arr_alfabeto_orgao[] = strtoupper($rowsLetra->fields('letra')); + $rowsLetra->moveNext(); + } + $input->setSession('session_letras_orgao',serialize($this->arr_alfabeto_orgao)); + } + } + function findLetraorgao() { + global $db; + + $sql = "SELECT DISTINCT(SUBSTRING(nome,1,1)) AS letra FROM sis_orgao ORDER BY nome ASC"; + return $db->execute($sql); + } + function getFiltrosFromSession(){ + $this->setAlfabetoOrgao(); + + global $input; + $this->filtro_palavra = $input->session('session_orgao_filtro_palavra'); + $this->filtro_procedencia = $input->session('session_orgao_filtro_procedencia'); + $this->filtro_sistema = $input->session('session_orgao_filtro_sistema'); + $this->filtro_patologia = $input->session('session_orgao_filtro_patologia'); + + $this->filtro_ordenar = $input->get('orgao_filtro_ordenar'); + if($this->filtro_ordenar == ''){ + $this->filtro_ordenar = $input->session('session_orgao_filtro_ordenar'); + if($this->filtro_ordenar == ''){ + $this->filtro_ordenar = $this->arr_ordenar[0]; + } + } else { + $input->setSession('session_orgao_filtro_ordenar',$this->filtro_ordenar); + } + + $this->filtro_resultado = $input->get('orgao_filtro_resultado'); + if($this->filtro_resultado == ''){ + $this->filtro_resultado = $input->session('session_orgao_filtro_resultado'); + if($this->filtro_resultado == ''){ + $this->filtro_resultado = $this->arr_resultado[0]; + } + } else { + $input->setSession('session_orgao_filtro_resultado',$this->filtro_resultado); + } + } + function getResultado($tmp_baseLink = ''){ + $html = '
Resultados por página:  '; + $total = sizeof($this->arr_resultado); + for($r=0;$r<$total;$r++){ + if($this->arr_resultado[$r] == $this->filtro_resultado){ + $html .= ''.$this->arr_resultado[$r].''; + } else { + $html .= ''.$this->arr_resultado[$r].''; + } + if(($r+1) < $total){ + $html .= '  '; + } + } + $html .= '
'; + return $html; + } + function getAlfabeto(){ + $html = ''; + $total = sizeof($this->arr_alfabeto); + for($a=0;$a<$total;$a++){ + if(in_array($this->arr_alfabeto[$a],$this->arr_alfabeto_orgao)){ + $html .= ''; + } else { + $html .= ''; + } + } + $html .= '
'.$this->arr_alfabeto[$a].''.$this->arr_alfabeto[$a].'
'; + return $html; + } + function getOrdenar($tmp_baseLink = ''){ + $html = '
Ordenar por:  '; + $total = sizeof($this->arr_ordenar); + for($x=0;$x<$total;$x++){ + if($this->arr_ordenar[$x] == $this->filtro_ordenar){ + $html .= ''.$this->arr_ordenar[$x].''; + } else { + $html .= ''.$this->arr_ordenar[$x].''; + } + if(($x+1) < $total){ + $html .= '  '; + } + } + $html .= '
'; + return $html; + } + function getImage($tmp_id,$tmp_thumb = 'p',$tmp_method = 2){//p,m,g + $src = ''; + $baseDot = '../../../'; + $baseSrc = 'upload/sis_orgao/'.$tmp_id.'.jpg'; + $baseThb = '_system/scripts/image.php'; + if(file_exists($baseDot.$baseSrc)){ + switch($tmp_thumb){ + case 'pp': + $src = $baseDot.$baseThb.'?w=55&h=48&resize='.$tmp_method.'&file='.$baseSrc; + break; + case 'p': + $src = $baseDot.$baseThb.'?w=86&h=74&resize='.$tmp_method.'&file='.$baseSrc; + break; + case 'm': + $src = $baseDot.$baseThb.'?w=241&h=207&resize='.$tmp_method.'&file='.$baseSrc; + break; + case 'g': + $src = $baseDot.$baseThb.'?w=86&h=74&resize='.$tmp_method.'&file='.$baseSrc; + break; + } + } + return $src; + } + function searchLetter($tmp_letra){ + global $db; + + $sql = "SELECT o.id, + o.nome + FROM sis_orgao o + WHERE o.nome like '".$tmp_letra."%' ".$this->getOrderBy(); + return $db->execute($sql); + } + function findAll(){ + global $db; + + $sql = "SELECT o.id, + o.nome + FROM sis_orgao o "; + return $db->execute($sql); + } + function simpleSeach($tmp_palavraChave,$tmp_grupoorgao = '',$tmp_sistema = ''){ + global $db; + global $o_helper; + $o_helper->somaBusca($tmp_palavraChave); + + $andPalavraChave = ''; + if($tmp_palavraChave != ''){ + $andPalavraChave = " AND ( + o.nome like '%".$tmp_palavraChave."%' OR + o.palavrachave like '%".$tmp_palavraChave."%' OR + + g.nome like '%".$tmp_palavraChave."%' OR + s.nome like '%".$tmp_palavraChave."%' OR + i.nome like '%".$tmp_palavraChave."%' OR + i.texto like '%".$tmp_palavraChave."%' OR + d.nome like '%".$tmp_palavraChave."%' OR + d.texto like '%".$tmp_palavraChave."%' OR + d.palavrachave like '%".$tmp_palavraChave."%' OR + ce.nome like '%".$tmp_palavraChave."%' OR + ce.texto like '%".$tmp_palavraChave."%' OR + ce.palavrachave like '%".$tmp_palavraChave."%' + ) "; + } + $andGrupoOrgao = ''; + if($tmp_grupoorgao != ''){ + $andGrupoOrgao = ' AND g.id = '.$tmp_grupoorgao.' '; + } + $andSistema = ''; + if($tmp_sistema != ''){ + $andSistema = ' AND s.id = '.$tmp_sistema.' '; + } + + $sql = "SELECT o.id, + o.nome + FROM sis_orgao o + LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao + LEFT OUTER JOIN sis_grupoorgao g ON og.id_grupoorgao = g.id + + LEFT OUTER JOIN sis_orgao_sistema os ON o.id = os.id_orgao + LEFT OUTER JOIN sis_sistema s ON os.id_sistema = s.id + + LEFT OUTER JOIN sis_imagem_orgao io ON o.id = io.id_orgao + LEFT OUTER JOIN sis_imagem i ON io.id_imagem = i.id + + LEFT OUTER JOIN sis_diagnostico_orgao do ON o.id = do.id_orgao + LEFT OUTER JOIN sis_diagnostico d ON do.id_diagnostico = d.id + + LEFT OUTER JOIN sis_casoestudo_orgao ceo ON o.id = ceo.id_orgao + LEFT OUTER JOIN sis_casoestudo ce ON ceo.id_casoestudo = ce.id + + WHERE 1 = 1 ".$andPalavraChave.$andGrupoOrgao.$andSistema." GROUP BY o.id ".$this->getOrderBy(); + return $db->execute($sql); + } + function complexSeach($arrPalavra,$tmp_grupoorgao = '',$tmp_sistema = ''){ + global $db; + global $o_helper; + + $andGrupoOrgao = ''; + if($tmp_grupoorgao != ''){ + $andGrupoOrgao = ' AND g.id = '.$tmp_grupoorgao.' '; + } + $andSistema = ''; + if($tmp_sistema != ''){ + $andSistema = ' AND s.id = '.$tmp_sistema.' '; + } + + $fixedWhere = " 1 = 1 ".$andGrupoOrgao.$andSistema; + + $arrWhere = array(); + $arrWhere[] = "o.nome like '%#PALAVRA#%'"; + $arrWhere[] = "o.palavrachave like '%#PALAVRA#%'"; + $arrWhere[] = "g.nome like '%#PALAVRA#%'"; + $arrWhere[] = "s.nome like '%#PALAVRA#%'"; + $arrWhere[] = "i.nome like '%#PALAVRA#%'"; + $arrWhere[] = "i.texto like '%#PALAVRA#%'"; + $arrWhere[] = "d.nome like '%#PALAVRA#%'"; + $arrWhere[] = "d.texto like '%#PALAVRA#%'"; + $arrWhere[] = "d.palavrachave like '%#PALAVRA#%'"; + $arrWhere[] = "ce.nome like '%#PALAVRA#%'"; + $arrWhere[] = "ce.texto like '%#PALAVRA#%'"; + $arrWhere[] = "ce.palavrachave like '%#PALAVRA#%'"; + + $baseSql = "SELECT o.id, + o.nome + FROM sis_orgao o + LEFT OUTER JOIN sis_orgao_grupoorgao og ON o.id = og.id_orgao + LEFT OUTER JOIN sis_grupoorgao g ON og.id_grupoorgao = g.id + + LEFT OUTER JOIN sis_orgao_sistema os ON o.id = os.id_orgao + LEFT OUTER JOIN sis_sistema s ON os.id_sistema = s.id + + LEFT OUTER JOIN sis_imagem_orgao io ON o.id = io.id_orgao + LEFT OUTER JOIN sis_imagem i ON io.id_imagem = i.id + + LEFT OUTER JOIN sis_diagnostico_orgao do ON o.id = do.id_orgao + LEFT OUTER JOIN sis_diagnostico d ON do.id_diagnostico = d.id + + LEFT OUTER JOIN sis_casoestudo_orgao ceo ON o.id = ceo.id_orgao + LEFT OUTER JOIN sis_casoestudo ce ON ceo.id_casoestudo = ce.id + #WHERE# + GROUP BY o.id ".$this->getOrderBy(); + + return $db->execute($o_helper->makeSql($arrPalavra,$baseSql,$arrWhere,$fixedWhere)); + } + function sistemasrelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsSistema = $db->execute($sql); + + $obj = ''; + if(!$rowsSistema->EOF){ + while(!$rowsSistema->EOF){ + $obj .= ''.$rowsSistema->fields('nome').''; + $rowsSistema->moveNext(); + if(!$rowsSistema->EOF){ + $obj .= ', '; + } + } + if($obj != ''){ + $obj = 'Sistemas
'.$obj; + } + } else { + $obj = 'Nenhum sistema relacionado.'; + } + return $obj; + } + function grupodeorgaorelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsGrupoOrgao = $db->execute($sql); + + $obj = ''; + if(!$rowsGrupoOrgao->EOF){ + while(!$rowsGrupoOrgao->EOF){ + $obj .= ''.$rowsGrupoOrgao->fields('nome').''; + $rowsGrupoOrgao->moveNext(); + if(!$rowsGrupoOrgao->EOF){ + $obj .= ', '; + } + } + if($obj != ''){ + $obj = 'Topografia
'.$obj; + } + } else { + $obj = 'Nenhum grupo de órgão relacionado.'; + } + return $obj; + } + function getImgesRelacionadas($tmp_id,$tmp_limit = ''){ + global $db; + global $load; + global $input; + + $load->config('classes/Imagem.php'); + $o_imagem = new Imagem(); + + if($tmp_limit != ''){ + $tmp_limit = " LIMIT ".$tmp_limit; + } + + $sql = "SELECT io.id_imagem,i.nome FROM sis_imagem_orgao io INNER JOIN + sis_imagem i ON i.id = id_imagem WHERE i.visualizacao = 1 AND io.id_orgao = ".$tmp_id." ".$tmp_limit; + $rowsImagem = $db->execute($sql); + if(!$rowsImagem->EOF){ + $html = ''; + while(!$rowsImagem->EOF){ + $src = $o_imagem->getImage($rowsImagem->fields('id_imagem'),'pp'); + if($src != ''){ + $html .= '
'.$rowsImagem->fields('nome').'
'; + } + $rowsImagem->moveNext(); + } + return $html; + } else { + return ''; + } + } + function diagnosticosrelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsDiagnostico = $db->execute($sql); + + $obj = ''; + if(!$rowsDiagnostico->EOF){ + while(!$rowsDiagnostico->EOF){ + $obj .= '
'.$rowsDiagnostico->fields('nome').'
'; + $rowsDiagnostico->moveNext(); + } + } else { + $obj = 'Nenhum diagnóstico relacionado.'; + } + return $obj; + } + function casosdeestudorelacionados($tmp_id){ + global $db; + global $input; + + $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"; + $rowsCasoEstudo = $db->execute($sql); + + $obj = ''; + if(!$rowsCasoEstudo->EOF){ + while(!$rowsCasoEstudo->EOF){ + $obj .= '
'.$rowsCasoEstudo->fields('nome').'
'; + $rowsCasoEstudo->moveNext(); + } + } else { + $obj = 'Nenhum caso de estudo relacionado.'; + } + return $obj; + } + function findOrgaoById($tmp_id){ + global $db; + + $sql = "SELECT id,nome,texto,pagina,palavrachave FROM sis_orgao WHERE id = ".$tmp_id; + return $db->execute($sql); + } + function getOrderBy(){ + switch($this->filtro_ordenar){ + case 'Nome': + return ' ORDER BY o.nome ASC'; + break; + case 'Sistema': + return ' ORDER BY sistema ASC'; + break; + case 'Patologia': + return ' ORDER BY patologia ASC'; + break; + } + } +} +?> \ No newline at end of file diff --git a/_config/classes/Palavra.php b/_config/classes/Palavra.php new file mode 100644 index 0000000..e38aa33 --- /dev/null +++ b/_config/classes/Palavra.php @@ -0,0 +1,196 @@ +tabela = $tmp_tabela; + } + + function retornaInexistentes($todas){ + $palavra = array(); + if(is_array($todas)) + $palavra = array_unique($todas); + + global $db; + $arr_existentes = array(); + + if(is_array($todas)) + $sql = "SELECT palavra FROM ".$this->tabela." WHERE palavra COLLATE latin1_bin in ('".implode("','", $palavra)."')"; + else + $sql = "SELECT palavra FROM ".$this->tabela." WHERE palavra COLLATE latin1_bin = '".$todas."'"; + + $rs = $db->execute($sql); + while(!$rs->EOF) { + $arr_existentes[] = $rs->fields("palavra"); + $rs->moveNext(); + } + + $arr_retorno = array(); + + if(is_array($todas)){ + for($z=0;$z -1))&&($palavra[$z] != '')){ + array_push($arr_retorno,$palavra[$z]); + } + } + } + }else{ + if((!(array_search($todas,$arr_existentes) > -1))&&($todas != '')){ + array_push($arr_retorno,$todas); + } + } + + return $arr_retorno; + } + + //private + function existePalavra($palavra) { + global $db; + $arr_existentes = array(); + + if(is_array($palavra)) + $sql = "SELECT distinct palavra FROM ".$this->tabela." WHERE palavra in ('".implode("','", $palavra)."')"; + else + $sql = "SELECT distinct palavra FROM ".$this->tabela." WHERE palavra = '".$palavra."'"; + $rs = $db->execute($sql); + + while(!$rs->EOF) { + $arr_existentes[] = $rs->fields("palavra"); + $rs->moveNext(); + } + + return $arr_existentes; + } + + //busca por um array de palavras no banco e retorna as que existem + //private + function existePalavras($arr_palavras) { + global $db; + + $sql = "SELECT distinct palavra FROM ".$this->tabela." WHERE palavra in ('".implode("','", $arr_palavras)."')"; + $rs = $db->execute($sql); + + while(!$rs->EOF) { + $arr_existentes[] = $rs->fields("palavra"); + $rs->moveNext(); + } + + return $arr_existentes; + } + + //private + function salvaPalavras($palavras) { + global $db; + if(is_array($palavras)) { + if((sizeof($palavras) > 0)&&($palavras[0] != '')) { + $sql = "INSERT INTO ".$this->tabela." (palavra) VALUES('".implode("'),('",$palavras)."')"; + $rs = $db->execute($sql); + } + }else{ + if($palavras != ''){ + $sql = "INSERT INTO ".$this->tabela." (palavra) VALUES('".$palavras."')"; + $rs = $db->execute($sql); + } + } + } + + function retiraPontos($string, $troca = " "){ + $string = strtolower($string); + $string = strip_tags($string); + $string = str_replace(",",$troca,$string); + $string = str_replace(".",$troca,$string); + $string = str_replace(":",$troca,$string); + $string = str_replace("?",$troca,$string); + $string = str_replace("!",$troca,$string); + $string = str_replace(";",$troca,$string); + $string = str_replace("
",$troca,$string); + $string = str_replace("<",$troca,$string); + $string = str_replace(">",$troca,$string); + $string = str_replace("[",$troca,$string); + $string = str_replace("]",$troca,$string); + $string = str_replace("{",$troca,$string); + $string = str_replace("}",$troca,$string); + $string = str_replace("(",$troca,$string); + $string = str_replace(")",$troca,$string); + $string = str_replace("/",$troca,$string); + $string = str_replace("|",$troca,$string); + $string = str_replace("\\",$troca,$string); + $string = str_replace("-",$troca,$string); + $string = str_replace("@",$troca,$string); + $string = str_replace("#",$troca,$string); + $string = str_replace("$",$troca,$string); + $string = str_replace("%",$troca,$string); + $string = str_replace("*",$troca,$string); + $string = str_replace("\"",$troca,$string); + $string = str_replace("'",$troca,$string); + $string = str_replace(" ",$troca,$string); + $string = str_replace(chr(13),$troca,$string); + $string = str_replace(chr(10),$troca,$string); + + return $string; + } + + function filtraParaCadastro($arr_palavras) { + if(is_array($arr_palavras)){ + $stringReplaced = array(); + + //retira pontos espaços etc + $i=0; + while($iretiraPontos(strtolower(strip_tags($arr_palavras[$i]))); + $i++; + } + unset($arr_palavras); + $arr_palavras = array(); + //retirados os pontos, explode em um array maior com as novas palavras formadas truncadas por espaço + $i=0; + while($ifiltraParaCadastro($string); + } + else { + $arr_palavras = explode($string_de_quebra,$this->retiraPontos($string)); + } + + $this->salvaPalavras($this->retornaInexistentes($arr_palavras)); + } + else { + if(is_array($string)){ + $palavras = array(); + //retira as tags de cada uma das entradas e adiciona num novo array. + $i=0; + while($isalvaPalavras($this->retornaInexistentes($palavras)); + }else{ + $string = strtolower(strip_tags($string)); + $this->salvaPalavras($this->retornaInexistentes($string)); + } + } + } +} +?> \ No newline at end of file diff --git a/_config/config.php b/_config/config.php new file mode 100644 index 0000000..3587f6d --- /dev/null +++ b/_config/config.php @@ -0,0 +1,42 @@ + diff --git a/_config/exeptions/home.php b/_config/exeptions/home.php new file mode 100644 index 0000000..afc12d2 --- /dev/null +++ b/_config/exeptions/home.php @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/_config/exeptions/pages/loja_gerenciar_texto.php b/_config/exeptions/pages/loja_gerenciar_texto.php new file mode 100644 index 0000000..e2d0241 --- /dev/null +++ b/_config/exeptions/pages/loja_gerenciar_texto.php @@ -0,0 +1,199 @@ +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 +} + +?> +
+ +
+

INSERIR TEXTO

+
+ + + + + + + + + + + + + + + + + + +
LABEL
+
+ +

ALTERAR TEXTO

+
+ + + + + + + + $value) { + ?> + > + + + + + + + + + + +
LABEL
+ + +
+ + +
+ +
\ No newline at end of file diff --git a/_config/exeptions/routines/backup.php b/_config/exeptions/routines/backup.php new file mode 100644 index 0000000..f613c43 --- /dev/null +++ b/_config/exeptions/routines/backup.php @@ -0,0 +1,64 @@ +ajaxHeader(); +$routine = $input->get("routine"); + +switch($routine){ + case 'imgBku'://faz backup da imagem atual (limite de três backups por imagem) + $id = $input->get("id",true); + $path = '../../../upload/sis_imagem/'.$id.'.jpg'; + if(file_exists($path)){ + $size = filesize($path); + $image = addslashes(fread(fopen($path, "r"), $size)); + + $sql = "DELETE FROM bku_imagem WHERE id_imagem = ".$id; + $db->execute($sql); + + $sql = "INSERT INTO bku_imagem (id_imagem,imagem,tamanho,extensao,datahora) VALUES (".$id.",'".$image."','".$size."','jpg','".date('Y-m-d H:i:s')."')"; + $db->execute($sql); + $bku_id = mysql_insert_id(); + echo 'Backup efetuado com sucesso!'; + } else { + echo 'Erro, imagem inexistente.'; + } + break; + case 'imgDBku'://faz download do backup da imagem + $id = $input->get("id",true); + $load->system('library/Image.php'); + + $sql = 'SELECT id FROM bku_imagem WHERE id_imagem = '.$id; + $rows = $db->execute($sql); + //print_r2($rows); + + if($rows->EOF){ + die('Erro, backup não existe.'); + } else { + global $input; + die('../../_config/exeptions/routines/backup.php?routine=downloadImage&id='.$input->get('id')); + // $tmp_path = 'upload/tmp/'.time().'-'.md5($id).'.jpg'; + // $img = new Image(); + // $img->p = $rows->fields('imagem'); + // $img->save('../../../'.$tmp_path); + // if(file_exists('../../../'.$tmp_path)){ + // die('../../../_system/scripts/download.php?file='.$tmp_path.'&name=Backup_image_'.$id); + // } + } + die('Erro.'); + break; + case 'downloadImage': + $id = $input->get("id",true); + $sql = 'SELECT id,imagem,tamanho,extensao FROM bku_imagem WHERE id_imagem = '.$id; + $rows = $db->execute($sql); + if($rows->EOF){ + die('Erro, backup não existe.'); + } else { + header("Content-length: " . $rows->fields('tamanho')); + header("Content-type: " . $rows->fields('extensao')); + header("Content-Disposition: attachment; filename=" . 'backup_'.$rows->fields('id').'.'.$rows->fields('extensao')); + echo $rows->fields('imagem'); + } + break; +} +?> \ No newline at end of file diff --git a/_config/exeptions/routines/cropper.php b/_config/exeptions/routines/cropper.php new file mode 100644 index 0000000..b6b37c1 --- /dev/null +++ b/_config/exeptions/routines/cropper.php @@ -0,0 +1,59 @@ +ajaxHeader(); + +$tmp_img = $input->get('file');//caminho da imagem a selecionar +$tmp_endCrop = $input->get('endCrop');//função a chamar após o crop +$x1 = $input->get('x1'); +$y1 = $input->get('y1'); +$x2 = $input->get('x2'); +$y2 = $input->get('y2'); +?> + + + + + + + + + +
+ + + + +
+ +
+
\ No newline at end of file diff --git "a/_config/exeptions/routines/routines - C\363pia.php" "b/_config/exeptions/routines/routines - C\363pia.php" new file mode 100644 index 0000000..8313217 --- /dev/null +++ "b/_config/exeptions/routines/routines - C\363pia.php" @@ -0,0 +1,118 @@ +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. + + + + + + + + + EOF){ + if($bg == "#FFFFFF") + $bg = "#EEEEEE"; + else if($bg == "#EEEEEE") + $bg = "#DDDDDD"; + else if($bg == "#DDDDDD") + $bg = "#FFFFFF"; + + if($x>0){ + echo(""); + } + ?> + + + + moveNext(); + $x++; + } + ?> + +
+ Nome + + Código + + Sistema +
+ )" alt="Clique para relacionar" title="Clique para relacionar">fields("nome");?> + + fields("cid10");?> + + fields("sistema");?> +
+ 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){ + ?> + + EOF){ + ?> + + + + + + moveNext(); + } + ?> +
+ fields("nome");?> + + fields("cid10");?> + + fields("sistema");?> +
+ \ No newline at end of file diff --git a/_config/exeptions/routines/routines.php b/_config/exeptions/routines/routines.php new file mode 100644 index 0000000..eee5e9d --- /dev/null +++ b/_config/exeptions/routines/routines.php @@ -0,0 +1,42 @@ +ajaxHeader(); +$routine = $input->get("routine"); + +switch($routine){ + case "check": + $sql = "SELECT 1 FROM ".$input->get('table',true)." WHERE ".$input->get('field',true)." = '".$input->get('search')."' ".$input->get('u',true); + $rows = $db->execute($sql); + if($rows->EOF){ + echo('1'); + } else { + echo('0'); + } + break; + case "sugestion": + $sql = "SELECT codigo,descricao FROM global_cid10 WHERE status = 1 AND codigo LIKE '".$input->get('codigo')."%' LIMIT 10"; + $rows = $db->execute($sql); + + $html = ''; + if(!$rows->EOF){ + if($rows->recordcount > 1){ + $html .= '
'; + $html .= '
'; + while(!$rows->EOF){ + $html .= ''.$rows->fields('codigo').' - '.$rows->fields('descricao').''; + $rows->moveNext(); + if(!$rows->EOF){ + $html .= '
'; + } + } + $html .= '
'; + } else { + $html .= $rows->fields('codigo').' - '.$rows->fields('descricao'); + } + } + echo $html; + break; +} +?> \ No newline at end of file diff --git a/_config/exeptions/routines/routines_orgao.php b/_config/exeptions/routines/routines_orgao.php new file mode 100644 index 0000000..3732eb5 --- /dev/null +++ b/_config/exeptions/routines/routines_orgao.php @@ -0,0 +1,49 @@ +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 diff --git a/_config/exeptions/routines/routines_search.php b/_config/exeptions/routines/routines_search.php new file mode 100644 index 0000000..a2e1631 --- /dev/null +++ b/_config/exeptions/routines/routines_search.php @@ -0,0 +1,132 @@ +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($sistema != "") + $sistema = " AND os.id_sistema = ".$sistema; + + $where = ""; + if(($nome != "") || ($codigo != "") || ($sistema != "")) + $where = " WHERE 1 = 1 ".$nome.$codigo.$sistema; + + $sql = "SELECT o.id, o.nome FROM sis_orgao o + LEFT OUTER JOIN sis_orgao_sistema os ON os.id_orgao = o.id + LEFT OUTER JOIN sis_sistema s ON s.id = os.id_sistema ".$where." GROUP BY o.id 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; + case "busca_imagem": + $nome = $input->get("nome"); + $procedencia = $input->get("procedencia"); + $patologia = $input->get("patologia"); + $sistema = $input->get("sistema"); + $saudaveis = $input->get("saudaveis"); + + if($nome != "") + $nome = " AND o.nome like '%".$nome."%'"; + if($procedencia != "") + $procedencia = " AND o.id_procedencia = ".$procedencia; + if($patologia != "") + $patologia = " AND o.id_patologia = ".$patologia; + if($sistema != "") + $sistema = " AND o.id_sistema = ".$sistema; + + $where = " saudavel = 0 ";//todos buscam somente imagens não saudaveis + if($saudaveis != ''){ + $where = " 1 = 1 "; + } + if(($nome != "") || ($procedencia != "") || ($patologia != "") || ($sistema != "")) + $where = " WHERE ".$where." ".$nome.$procedencia.$patologia.$sistema; + + $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"; + $rowsImagem = $db->execute($sql); + + //entre registros + $entreReg = "###"; + //entre valores + $entreVal = "$$$"; + if(!$rowsImagem->EOF){ + while(!$rowsImagem->EOF){ + echo $rowsImagem->fields("id"); + echo $entreVal; + echo $rowsImagem->fields("nome"); + + $src = "../../_system/scripts/image.php?file=upload/sis_imagem/".$rowsImagem->fields("id").".jpg&w=60&h=60"; + $img = ''; + echo $entreVal; + echo $img; + + $rowsImagem->moveNext(); + if(!$rowsImagem->EOF) + echo $entreReg; + } + } + break; + case "busca_diagnostico": + $nome = $input->get("nome"); + $especialidade = $input->get("especialidade"); + + if($nome != "") + $nome = " AND d.nome like '%".$nome."%'"; + if($especialidade != "") + $especialidade = " AND d.id_especialidade = ".$especialidade; + + $where = ""; + if(($nome != "") || ($especialidade != "")) + $where = " WHERE 1 = 1 ".$nome.$especialidade; + + $sql = "SELECT d.id, d.nome FROM sis_diagnostico d ".$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 diff --git a/_config/exeptions/routines/search.php b/_config/exeptions/routines/search.php new file mode 100644 index 0000000..4e84585 --- /dev/null +++ b/_config/exeptions/routines/search.php @@ -0,0 +1,165 @@ +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); +?> + + + + + + + + + +
+ + + + + + + + + + +
+ Buscas de órgão +
+
+ + + + + + + + + + + + + + + + + +
+ Nome: + + +
+ Código: + + +
+ Sistema: + + +
+ + Buscar +
+
+
+ resultados +
+
+ + + + + + + +
+ Órgãos já relacionados +
+ +
+
+ \ No newline at end of file diff --git a/_config/exeptions/routines/search_diagnostico.php b/_config/exeptions/routines/search_diagnostico.php new file mode 100644 index 0000000..ce71d0a --- /dev/null +++ b/_config/exeptions/routines/search_diagnostico.php @@ -0,0 +1,122 @@ +ajaxHeader(); + +$id_js = $input->get("_id_js"); +$sis_table = "sis_orgao"; +$sis_table_rel = "sis_imagem_orgao"; + +$sql = "SELECT id, nome FROM sis_especialidade ORDER BY nome ASC"; +$rowsEspecialidade = $db->execute($sql); +?> + + + + + + + + +
+ + + + + +
+
+ + + + + + + + + + + + + +
+ Nome: + + +
+ Especialidade: + + +
+ +
+
+ +
+
+ +
+
+
+
+
+
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas. +
+
+
\ No newline at end of file diff --git a/_config/exeptions/routines/search_imagem.php b/_config/exeptions/routines/search_imagem.php new file mode 100644 index 0000000..8cd6542 --- /dev/null +++ b/_config/exeptions/routines/search_imagem.php @@ -0,0 +1,158 @@ +ajaxHeader(); + +$id_js = $input->get("_id_js"); + +$sql = "SELECT id, nome FROM sis_procedencia ORDER BY nome ASC"; +$rowsProcedencia = $db->execute($sql); + +$sql = "SELECT id, nome FROM sis_patologia ORDER BY nome ASC"; +$rowsPatologia = $db->execute($sql); + +$sql = "SELECT id, nome FROM sis_sistema ORDER BY nome ASC"; +$rowsSistema = $db->execute($sql); +?> + + + + + + + + +
+ + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + +
+ Nome: + + +
+ Procedência: + + +
+ Patologia: + + +
+ Sistema: + + +
+ +
+
+ +
+
+ +
+
+
+
+
+
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas. +
+
+
\ No newline at end of file diff --git a/_config/exeptions/routines/search_imagem_saudavel.php b/_config/exeptions/routines/search_imagem_saudavel.php new file mode 100644 index 0000000..20bf621 --- /dev/null +++ b/_config/exeptions/routines/search_imagem_saudavel.php @@ -0,0 +1,158 @@ +ajaxHeader(); + +$id_js = $input->get("_id_js"); + +$sql = "SELECT id, nome FROM sis_procedencia ORDER BY nome ASC"; +$rowsProcedencia = $db->execute($sql); + +$sql = "SELECT id, nome FROM sis_patologia ORDER BY nome ASC"; +$rowsPatologia = $db->execute($sql); + +$sql = "SELECT id, nome FROM sis_sistema ORDER BY nome ASC"; +$rowsSistema = $db->execute($sql); +?> + + + + + + + + +
+ + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + +
+ Nome: + + +
+ Procedência: + + +
+ Patologia: + + +
+ Sistema: + + +
+ +
+
+ +
+
+ +
+
+
+
+
+
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas. +
+
+
\ No newline at end of file diff --git a/_config/exeptions/routines/search_orgao.php b/_config/exeptions/routines/search_orgao.php new file mode 100644 index 0000000..3b34d14 --- /dev/null +++ b/_config/exeptions/routines/search_orgao.php @@ -0,0 +1,130 @@ +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); +?> + + + + + + + + +
+ + + + + +
+
+ + + + + + + + + + + + + + + + + +
+ Nome: + + +
+ Código: + + +
+ Sistema: + + +
+ +
+
+ Buscar +
+
+ Limpar +
+
+
+
+
+
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas. +
+
+
\ No newline at end of file diff --git a/_config/exeptions/routines/search_orgao2.php b/_config/exeptions/routines/search_orgao2.php new file mode 100644 index 0000000..5f2ff43 --- /dev/null +++ b/_config/exeptions/routines/search_orgao2.php @@ -0,0 +1,122 @@ +ajaxHeader(); + +$id_js = $input->get("_id_js"); +$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); +?> + + + + + + + + +
+ + + + + +
+
+ + + + + + + + + + + + + +
+ Nome: + + +
+ Sistema: + + +
+ +
+
+ +
+
+ +
+
+
+
+
+
+ Atenção, a busca é automaticamente limitada em apenas 50 resultados, por favor, para um melhor resultado, seja específico em suas buscas. +
+
+
\ No newline at end of file diff --git a/_config/forms/FormAdminSessao.php b/_config/forms/FormAdminSessao.php new file mode 100644 index 0000000..15497fa --- /dev/null +++ b/_config/forms/FormAdminSessao.php @@ -0,0 +1,20 @@ +flags = "UI"; + } + + function configFields() { + + $f = $this->newField("char", array("id", "ID")); + $f->is_static = true; + $this->addField($f, "LOFU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = "100"; + $this->addField($f, "LOFIU"); + } + +} +?> \ No newline at end of file diff --git a/_config/forms/FormAdminUsuario.php b/_config/forms/FormAdminUsuario.php new file mode 100644 index 0000000..a341759 --- /dev/null +++ b/_config/forms/FormAdminUsuario.php @@ -0,0 +1,59 @@ +newField("char", array("nome", "Nome")); + $f->maxlength = "100"; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("email", "E-mail")); + $f->loadConfig("email"); + $f->maxlength = "150"; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("nivel", "Nível de Usuário")); + $f->setInputType('radio'); + $f->addElementsByArray(array('1' => 'Administrador','2' => 'Professor')); + $this->addField($f, "LOFIU"); + + $f = $this->newField("ativo"); + $f->value_initial = 1; + $this->addField($f, "LOFIU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f); + + $f = $this->newField("char", array("usuario", "Usuário")); + $f->maxlength = "60"; + $this->addField($f, "IU"); + + $f = $this->newField("password", array("senha")); + $f->maxlength = "15"; + $this->addField($f, "UI"); + + $f = $this->newField('html',array('box')); + $this->addField($f); + + $f = $this->newField('html',array('label', 'Sessões')); + $this->addField($f); + + $f = $this->newField('multiItems', array('sessao','','admin_usuario_sessao','id_usuario','id_sessao')); + $f->addElementsByTable('admin_sessao'); + $this->addField($f,'IU'); + + } + + function getListSql($tmp_sql_filter, $tmp_sql_order) { + global $profile; + if ($profile->fields("id") != 1) { + return "select * from ".$this->table." where id <> 1 ".$tmp_sql_filter." ".$tmp_sql_order; + } else { + return "select * from ".$this->table." where 1 = 1 ".$tmp_sql_filter." ".$tmp_sql_order; + } + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormCasoEstudo.php b/_config/forms/FormCasoEstudo.php new file mode 100644 index 0000000..74a01f5 --- /dev/null +++ b/_config/forms/FormCasoEstudo.php @@ -0,0 +1,241 @@ +flags = $profile->getFlags(); + $this->table_rel = 'sis_casoestudo_comentario'; + $this->id_rel = 'id_casoestudo'; + } + + function configFields() { + global $routine; + global $db; + global $profile; + global $load; + $load->system('functions/date.php'); + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados do Caso de Estudo")); + $this->addField($f); + + $f = $this->newField("char", array("nome", "Nome")); + $f->setInputType('textarea'); + $f->size_cols = 55; + $f->size_rows = 2; + $f->maxlength = 200; + $f->input_extra = " onblur='javascript: checkMe(this.value);' "; + $f->field_extra = "
"; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("codigo", "Código")); + $f->maxlength = 100; + $f->comment = 'Número do caso Ex: A-13069.'; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_especialidade", "Especialidade")); + $f->addElementsByTable("sis_especialidade"); + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("referencia", "Referências")); + $f->setInputType("textarea"); + $f->maxlength = 10000; + $f->is_required = false; + $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."; + $this->addField($f, "IU"); + + $f = $this->newField("char", array("palavrachave", "Palavras-chave")); + $f->maxlength = 250; + $f->is_required = false; + $f->comment = "Palavras relacionadas ao diagnóstico, que eventualmente podem facilitar a pesquisa."; + $this->addField($f, "LOFIU"); + + $f = $this->newField("ativo",array("visualizacao","Visualização")); + $f->value_initial = 1; + $f->comment = "Este campo determina se a imagem será visualizada no site."; + $this->addField($f, "LOFIU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f); + + $f = $this->newField("html", array("label","O Caso de Estudo")); + $this->addField($f); + + $f = $this->newField("char", array("texto", "Texto")); + $f->setInputType("textarea"); + $f->maxlength = 20000; + $f->is_required = false; + $f->size_rows = 13; + $f->comment = "O Caso de Estudo em sí, todo o desenvolvimento da idéia do mesmo."; + $this->addField($f, "IU"); + + $f = $this->newField("char", array("texto_professor", "Texto/Anotações do professor")); + $f->setInputType("textarea"); + $f->maxlength = 20000; + $f->is_required = false; + $f->size_rows = 7; + $f->comment = "Este campo não será visualizado no site, são apenas anotações para uso do professor."; + $this->addField($f, "IU"); + + $f = $this->newField("relItems", array("orgaos","Órgãos","sis_casoestudo_orgao","id_casoestudo","id_orgao","sis_orgao","_config/exeptions/routines/search_orgao2.php")); + $this->addField($f, "IU"); + + $f = $this->newField("relItems", array("imagens","Imagens","sis_casoestudo_imagem","id_casoestudo","id_imagem","sis_imagem","_config/exeptions/routines/search_imagem_saudavel.php")); + $f->search_page_height = 160; + $this->addField($f, "IU"); + + $f = $this->newField("relItems", array("diagnosticos","Diagnósticos","sis_casoestudo_diagnostico","id_casoestudo","id_diagnostico","sis_diagnostico","_config/exeptions/routines/search_diagnostico.php")); + //$f->search_page_height = 160; + $this->addField($f, "IU"); + + /******************** COMENTARIOS ************************/ + + $f = $this->newField("html",array('box','div_botao_mais_arquivo')); + $this->addField($f); + + $html = " + + + + + "; + $f = $this->newField("html", array("html")); + $f->html = $html; + $this->addField($f); + + $f = $this->newField("html",array('box')); + $this->addField($f); + + $f = $this->newField("html",array('label','Comentários')); + $this->addField($f); + + $f = $this->newField("html",array('box')); + $this->addField($f); + + $total_arquivos = 20; + $arquivo_atual = 1; + + if ($routine == 'update') { + $sql = "SELECT * FROM ".$this->table_rel." WHERE ".$this->id_rel." = ".$this->fields('id')." "; + $rs = $db->execute($sql); + + if (!$rs->EOF) { + while(!$rs->EOF) { + $f = $this->newField("char", array("nome_id_".$rs->fields('id'), "Nome")); + $f->value_static = $rs->fields("nome"); + $f->is_static = true; + $f->is_required = false; + $this->addField($f, "IU"); + + $f = $this->newField("char", array("email_id_".$rs->fields('id'), "E-mail")); + $f->value_static = $rs->fields("email"); + $f->is_static = true; + $f->is_required = false; + $this->addField($f, "IU"); + + $f = $this->newField("char", array("comentario_id_".$rs->fields('id'), "Comentário")); + $f->value_static = $rs->fields("comentario"); + $f->is_static = true; + $f->is_required = false; + $this->addField($f, "IU"); + + $f = $this->newField("char", array("datacomentario_id_".$rs->fields('id'), "Data")); + $f->value_static = datetimeFromMysql($rs->fields("datacomentario")); + $f->is_static = true; + //$f->is_required = false; + $this->addField($f, "IU"); + + $f = $this->newField("ativo", array("status_id_".$rs->fields('id'), "Status")); + $f->value = $rs->fields("status"); + $f->is_required = false; + $this->addField($f, "IU"); + + if (($arquivo_atual % 2 == 1) && ($arquivo_atual < $total_arquivos)) { + $f = $this->newField("html",array("separador")); + $this->addField($f); + } elseif ($arquivo_atual < $total_arquivos) { + $f = $this->newField("html",array("box")); + $this->addField($f); + } + + $arquivo_atual++; + $rs->moveNext(); + } + } + } + + $f = $this->newField("hidden", array("arquivo_atual", "arquivoAtual")); + $f->value = $arquivo_atual; + $f->is_required = false; + $this->addField($f, "IU"); + + /******************** / COMENTARIOS ************************/ + } + function loadInit($rotina) { + global $input; + $u = ''; + if ($rotina == 'U') { + $u = $input->encode(' AND id != '.$this->fields('id')); + } + ?> + + system('functions/text.php'); + + $total_arquivos = $input->post('arquivo_atual'); + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + $cadastra->cadastraPalavras($this->fields("palavrachave"),true,';'); + + if ($routine == 'U') {//atualiza estoque + $sql = "SELECT * FROM ".$this->table_rel." WHERE ".$this->id_rel."=".$this->fields('id')." "; + $rs = $db->execute($sql); + + if (!$rs->EOF) { + while(!$rs->EOF){ + $sql = "UPDATE ".$this->table_rel." SET + status='".$input->post('status_id_'.$rs->fields('id'))."' + WHERE id=".$rs->fields('id'); + $db->execute($sql); + $rs->moveNext(); + } + } + } + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormCid10.php b/_config/forms/FormCid10.php new file mode 100644 index 0000000..1b20f37 --- /dev/null +++ b/_config/forms/FormCid10.php @@ -0,0 +1,19 @@ +newField("char", array("codigo", "Código")); + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("descricao", "Descrição")); + $this->addField($f, "LOFIU"); + + $f = $this->newField("ativo"); + $f->value_initial = 1; + $this->addField($f, "LOFIU"); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormDiagnostico.php b/_config/forms/FormDiagnostico.php new file mode 100644 index 0000000..5cc507d --- /dev/null +++ b/_config/forms/FormDiagnostico.php @@ -0,0 +1,146 @@ +flags = $profile->getFlags(); + } + + function configFields() { + global $profile; + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados do Diagnóstico")); + $this->addField($f); + + $f = $this->newField("char", array("nome", "Nome")); + $f->setInputType('textarea'); + $f->size_cols = 55; + $f->size_rows = 2; + $f->maxlength = 200; + $f->input_extra = " onblur='javascript: checkMe(this.value);' "; + $f->field_extra = "
"; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("cid10", "Código CID10")); + $f->maxlength = 10; + $f->size_cols = 10; + $f->is_required = false; + $f->field_extra = "
 
"; + $f->input_extra = " onkeyup='javascript: initSugestion();' "; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_especialidade", "Especialidade")); + $f->addElementsByTable("sis_especialidade"); + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("referencia", "Referências")); + $f->setInputType("textarea"); + $f->maxlength = 10000; + $f->is_required = false; + $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."; + $this->addField($f, "IU"); + + $f = $this->newField("char", array("palavrachave", "Palavras-chave")); + $f->maxlength = 250; + $f->is_required = false; + $f->comment = "Palavras relacionadas ao diagnóstico, que eventualmente podem facilitar a pesquisa. Separar palavras com ponto e vírgula."; + $this->addField($f, "LOFIU"); + + $f = $this->newField("ativo",array("visualizacao","Visualização")); + $f->value_initial = 1; + $f->comment = "Este campo determina se a imagem será visualizada no site."; + $this->addField($f, "LOFIU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f); + + $f = $this->newField("html", array("label","O Diagnóstico")); + $this->addField($f); + + $f = $this->newField("char", array("texto", "Texto")); + $f->setInputType("textarea"); + $f->maxlength = 25000; + $f->is_required = false; + $f->size_rows = 26; + $f->comment = "O diagnóstico em sí, todo o desenvolvimento da idéia do mesmo."; + $this->addField($f, "IU"); + + $f = $this->newField("relItems", array("orgaos","Órgãos","sis_diagnostico_orgao","id_diagnostico","id_orgao","sis_orgao","_config/exeptions/routines/search_orgao2.php")); + $this->addField($f, "IU"); + + $f = $this->newField("relItems", array("imagens","Imagens","sis_diagnostico_imagem","id_diagnostico","id_imagem","sis_imagem","_config/exeptions/routines/search_imagem.php")); + $f->search_page_height = 160; + $this->addField($f, "IU"); + } + function loadInit($rotina) { + global $input; + $u = ''; + if ($rotina == 'U') { + $u = $input->encode(' AND id != '.$this->fields('id')); + } + ?> + + config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + $cadastra->cadastraPalavras($this->fields("palavrachave"),true,';'); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormEspecialidade.php b/_config/forms/FormEspecialidade.php new file mode 100644 index 0000000..0b76eab --- /dev/null +++ b/_config/forms/FormEspecialidade.php @@ -0,0 +1,49 @@ +flags = $profile->getFlags(); + } + + function configFields() { + global $profile; + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados da Especialidade (área médica)")); + $this->addField($f); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 50; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("texto", "Texto")); + $f->setInputType("textarea"); + $f->maxlength = 10000; + $f->is_required = false; + $f->comment = "Uma breve descrição da especialidade, como se define, quais os focus de estudo, exemplos, etc."; + $this->addField($f, "IU"); + + $f = $this->newField("char", array("pagina", "URL com http://")); + $f->maxlength = 250; + $f->is_required = false; + $this->addField($f, "LOFIU"); + } + + function onPosPost($routine){ + global $load; + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormGrupoImagem.php b/_config/forms/FormGrupoImagem.php new file mode 100644 index 0000000..3ef0aff --- /dev/null +++ b/_config/forms/FormGrupoImagem.php @@ -0,0 +1,67 @@ +flags = $profile->getFlags(); + } + + function configFields() { + global $routine; + global $profile; + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 250; + $this->addField($f, "LOFIU"); + //if(($routine == 'U') || ($routine == 'L')){ + if(($routine == 'update')){ + global $db; + $row = $db->execute('SELECT COUNT(ID) as conta FROM sis_imagem where id_grupoimagem = '.$this->fields('id')); + $quantidade = 0; + if(!$row->EOF){ + $quantidade = $row->fields('conta'); + if($quantidade == ''){ + $quantidade = 0; + } + } + + $f = $this->newField("char", array("quantidade", "Quantidade")); + $f->value = $quantidade; + $f->is_sql_affect = false; + $f->is_required = false; + $f->input_extra = ' disabled="disabled" '; + $this->addField($f, "IU"); + } + + $f = $this->newField("char", array("quantidade", "Quantidade")); + $f->is_required = false; + $this->addField($f, "LO"); + + $f = $this->newField("ativo", array("status", "Status")); + $f->value_initial = 1; + $this->addField($f, "LOFIU"); + } + + function getListSql($tmp_sql_filter, $tmp_sql_order) { + $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; + return $sql; + } + + function onPosPost($routine){ + global $load; + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormGrupoOrgao.php b/_config/forms/FormGrupoOrgao.php new file mode 100644 index 0000000..fe43b3d --- /dev/null +++ b/_config/forms/FormGrupoOrgao.php @@ -0,0 +1,100 @@ +flags = $profile->getFlags(); + } + + function configFields() { + global $profile; + global $routine; + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados do grupo")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 50; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_camada", "Camada")); + $f->addElementsByTable('sis_grupoorgao_camada'); + $f->comment = 'A Camada de Topografia é utilizado para especificar níveis (camadas) de topografia, afim de evitar a sobreposição de itens.'; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("x1", "X1")); + $f->maxlength = 10; + $f->is_required = false; + $f->size_cols = 10; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("y1", "Y1")); + $f->maxlength = 10; + $f->is_required = false; + $f->size_cols = 10; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("x2", "X2")); + $f->maxlength = 10; + $f->is_required = false; + $f->size_cols = 10; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("y2", "Y2")); + $f->maxlength = 10; + $f->is_required = false; + $f->size_cols = 10; + $this->addField($f, "LOFIU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f); + + $src = '../../_config/exeptions/routines/cropper.php?file=../../../upload/sis_boneco/boneco.gif&endCrop=htmlEditor5'; + if($routine == 'update'){ + if($this->fields('x1') && $this->fields('x2') && $this->fields('y1') && $this->fields('y2')){ + $src .= '&x1='.$this->fields('x1'); + $src .= '&y1='.$this->fields('y1'); + $src .= '&x2='.$this->fields('x2'); + $src .= '&y2='.$this->fields('y2'); + } + } + + $f = $this->newField("html", array("html")); + $html = ''; + $f->html = $html; + $this->addField($f); + } + + function onPosPost($routine){ + global $load; + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + } + + function loadInit($rotina) { + if (($rotina == 'U') || ($rotina == 'I')) { + ?> + + \ No newline at end of file diff --git a/_config/forms/FormGrupoOrgaoCamada.php b/_config/forms/FormGrupoOrgaoCamada.php new file mode 100644 index 0000000..b56fb56 --- /dev/null +++ b/_config/forms/FormGrupoOrgaoCamada.php @@ -0,0 +1,39 @@ +newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Camada Topográfica")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 150; + $this->addField($f, "LOFIU"); + + $f = $this->newField("ativo"); + $f->value_initial = 1; + $this->addField($f, "LOFIU"); + } + + function onPosPost($routine){ + global $load; + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + } +} +?> \ No newline at end of file diff --git "a/_config/forms/FormImagem - C\363pia.php" "b/_config/forms/FormImagem - C\363pia.php" new file mode 100644 index 0000000..631e774 --- /dev/null +++ "b/_config/forms/FormImagem - C\363pia.php" @@ -0,0 +1,450 @@ +table_rel_orgao = "sis_imagem_orgao"; + } + + function configFields() { + global $profile; + global $routine; + + $valor = ""; + if($routine == "update"){ + global $db; + global $load; + $load->system("functions/text.php"); + + $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"; + $rows = $db->execute($sql); + $arr = array(); + while(!$rows->EOF){ + $arr[] = array($rows->fields("id"),$rows->fields("nome")); + $rows->moveNext(); + } + $valor = se($arr); + } + //carregar com relacionados ao fazer update - alteração + $f = $this->newField("hidden", array("relacionados","Relacionados")); + $f->is_sql_affect = false; + $f->is_required = false; + $f->value = $valor; + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados da Imagem")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 50; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_procedencia", "Procedencia")); + $f->addElementsByTable("sis_procedencia"); + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_patologia", "Patologia")); + $f->addElementsByTable("sis_patologia"); + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_sistema", "Sistema")); + $f->addElementsByTable("sis_sistema"); + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("imageUpload", array("imagem", "Imagem (tamanho máximo: 1500x1500) ", "upload/sis_imagem/")); + $f->addThumb("#ID#", 1500, 1500, 4); + $f->is_required = false; + $this->addField($f, "IU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados da Imagem")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("texto", "Texto")); + $f->setInputType("textarea"); + $f->maxlength = 10000; + $f->is_required = false; + $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."; + $this->addField($f, "IU"); + + $f = $this->newField("date", array("dataorigem", "Data de origem")); + $f->is_required = false; + $f->comment = "Data de origem significa a data em que a foto foi tirada, ou obtida."; + $this->addField($f, "IU"); + + $f = $this->newField("html", array("box")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Pesquise Órgãos para relacionar")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("html")); + $f->html = ' + + + + + + +
+ +
+ + + + + Resultados da pesquisa + + + + + Nenhum item encontrado + + + '; + $this->addField($f, "IU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Órgãos já relacionados")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("html")); + $f->html = ' + + + Nenhum item relacionado. + + + '; + $this->addField($f, "IU"); + } + + function loadInit($rotina) { + if (($rotina == 'U') || ($rotina == 'I')) { + ?> + + + system('functions/text.php'); + + $arrRel = unse($input->post('relacionados')); + + if ($routine == 'U') { + $sql = "DELETE FROM ".$this->table_rel_orgao." WHERE id_imagem = ".$this->fields('id'); + $db->execute($sql); + + for($x=0;$xtable_rel_orgao." (id_imagem,id_orgao) VALUES (".$this->fields('id').",".$id.")"; + $db->execute($sql); + } + } else if ($routine == "I"){ + for($x=0;$xtable_rel_orgao." (id_imagem,id_orgao) VALUES (".$this->fields('id').",".$id.")"; + $db->execute($sql); + } + } + } + + function postDelete() { + global $db; + + $sql = "DELETE FROM ".$this->table_rel_orgao." WHERE id_imagem = ".$this->fields('id'); + $db->execute($sql); + + $this->onDelete(); + $this->_onDeleteFields(); + $this->delete(); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormImagem.php b/_config/forms/FormImagem.php new file mode 100644 index 0000000..660df4f --- /dev/null +++ b/_config/forms/FormImagem.php @@ -0,0 +1,220 @@ +table_rel_orgao = "sis_imagem_orgao"; + // global $profile; + // $this->flags = $profile->getFlags(); + } + + function configFields() { + global $profile; + global $routine; + global $input; + global $db; + + //$f = $this->newField("char", array("id", "ID")); + //$this->addField($f, "LOF"); + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + if($routine == 'update'){ + $sql = 'SELECT id FROM bku_imagem WHERE id_imagem = '.$this->fields('id').' ORDER BY datahora DESC'; + $rows = $db->execute($sql); + + $downloadBackup = ''; + if(!$rows->EOF){ + $downloadBackup = '
+ +
'; + } + + $f = $this->newField("html", array("label","Restauração")); + $this->addField($f, "U"); + + $f = $this->newField("html", array("html")); + $html = ' + +
+ + + +
+ '.$downloadBackup.' + + '; + $f->html = $html; + $this->addField($f, "U"); + } + + $f = $this->newField("html", array("label","Dados da Imagem")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->setInputType('textarea'); + $f->size_cols = 55; + $f->size_rows = 2; + $f->maxlength = 200; + $f->input_extra = " onblur='javascript: checkMe(this.value);' "; + $f->field_extra = "
"; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_grupoimagem", "Grupo")); + $f->addElementsByTable("sis_grupoimagem"); + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_procedencia", "Procedencia")); + $f->addElementsByTable("sis_procedencia"); + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_patologia", "Patologia")); + $f->addElementsByTable("sis_patologia"); + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("items", array("id_sistema", "Sistema")); + $f->addElementsByTable("sis_sistema"); + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("imageUpload", array("imagem", "Imagem (tamanho máximo: 1500x1500) ", "upload/sis_imagem/")); + $f->addThumb("#ID#", 1500, 1500, 4); + $f->is_required = false; + $f->extensions_accept = array("jpg"); + $f->hint = 'Somente imagens em jpg

Imagem para visualização no site.'; + $this->addField($f, "IU"); + + $f = $this->newField("items",array("carimbo","Carimbo")); + $f->setInputType('radio'); + $f->addElementsByArray(array('Esquerdo superior','Direito superior','Esquerdo inferior','Direito inferior','Sem carimbo')); + $f->comment = "Este campo determina aonde será localizado o carimbo da UFCSPA."; + $f->is_required = false; + $f->value_initial = 4; + $this->addField($f, "IU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados da Imagem")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("texto", "Texto")); + $f->setInputType("textarea"); + $f->maxlength = 19000; + $f->is_required = false; + $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."; + $this->addField($f, "IU"); + + $f = $this->newField("date", array("dataorigem", "Data de origem")); + $f->is_required = false; + $f->comment = "Data de origem significa a data em que a foto foi tirada, ou obtida."; + $this->addField($f, "IU"); + + $f = $this->newField("ativo",array("visualizacao","Visualização")); + $f->value_initial = 1; + $f->comment = "Este campo determina se a imagem será visualizada no site."; + $this->addField($f, "LOFIU"); + + $f = $this->newField("ativo",array("saudavel","Saudável?")); + $this->addField($f, "L"); + + $f = $this->newField("items",array("saudavel","É Saudável?")); + $f->value_initial = 1; + $f->loadConfig('simnao'); + $f->comment = "Imagens marcadas como saudáveis só podem ser relacionadas a casos de estudo."; + $this->addField($f, "OFIU"); + + // $f = $this->newField("upload", array("imagemoriginal", "Imagem Original ", "upload/sis_imagem_original/")); + // $f->setFileName("#ID#"); + // $f->is_required = false; + // $f->extensions_accept = array('tif','bmp','jpg','gif','png'); + // $f->hint = 'Somente a original (tif,bmp,jpg,gif,png)

Imagem para download no site. Limite de 1MB.'; + // $this->addField($f, "IU"); + + $f = $this->newField("relItems", array("orgaos","Órgãos","sis_imagem_orgao","id_imagem","id_orgao","sis_orgao","_config/exeptions/routines/search_orgao2.php")); + $this->addField($f, "IU"); + } + function loadInit($rotina) { + global $input; + $u = ''; + if ($rotina == 'U') { + $u = $input->encode(' AND id != '.$this->fields('id')); + ?> + + + + config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + //$cadastra->cadastraPalavras($this->fields("palavrachave"),true,';'); + + $load->config('classes/Imagem.php'); + $img = new Imagem(); + $img->verifyWaterMark($this->fields('id'),$this->fields('carimbo'),true); + + if($routine == 'U'){ + $arr_folders = array('sis_imagem_p','sis_imagem_pp','sis_imagem_m'); + $totalFolder = count($arr_folders); + for($x=0;$x<$totalFolder;$x++){ + $temp_src = '../../../upload/'.$arr_folders[$x].'/'.$this->fields('id').'.jpg'; + @unlink($temp_src); + } + } + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormOrgao.php b/_config/forms/FormOrgao.php new file mode 100644 index 0000000..f03b73a --- /dev/null +++ b/_config/forms/FormOrgao.php @@ -0,0 +1,94 @@ +page_size = 50; + // global $profile; + // $this->flags = $profile->getFlags(); + } + + function configFields() { + global $profile; + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados do órgão")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 50; + $this->addField($f, "LOFIU"); + + // $f = $this->newField("char", array("cid10", "Código CID10")); + // $f->maxlength = 10; + // $f->size_cols = 10; + // $f->is_required = false; + // $this->addField($f, "LOFIU"); + + $f = $this->newField("imageUpload", array("imagem", "Ícone ilustrutivo (50x50 px)", "upload/sis_orgao/")); + $f->addThumb("#ID#", 1000, 1000, 4); + $f->addThumb("#ID#_p", 50, 50, 4); + $f->is_required = false; + $this->addField($f, "IU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados extras")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("pagina", "URL com http://")); + $f->maxlength = 250; + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("char", array("palavrachave", "Palavras-chave")); + $f->maxlength = 250; + $f->is_required = false; + $f->comment = "Palavras relacionadas ao órgão, que eventualmente podem facilitar a pesquisa. Separar palavras com ponto e vírgula."; + $this->addField($f, "LOFIU"); + + $f = $this->newField("imageUpload", array("imagem", "Ícone", "upload/sis_orgao/")); + $f->addThumb("#ID#", 1000, 1000, 4); + $f->addThumb("#ID#_p", 50, 50, 4); + $f->is_required = false; + $this->addField($f, "L"); + + $f = $this->newField('html',array('box')); + $this->addField($f); + + $f = $this->newField('html',array('label', 'Sistemas relacionados')); + $this->addField($f); + + $f = $this->newField('multiItems', array('orgaosistema','','sis_orgao_sistema','id_orgao','id_sistema')); + $f->addElementsByTable('sis_sistema'); + $this->addField($f,'IU'); + + $f = $this->newField('html',array('box')); + $this->addField($f); + + $f = $this->newField('html',array('label', 'Topografia')); + $this->addField($f); + + $f = $this->newField('multiItems', array('orgaogrupoorgao','','sis_orgao_grupoorgao','id_orgao','id_grupoorgao')); + $f->addElementsByTable('sis_grupoorgao'); + $this->addField($f,'IU'); + } + + function onPosPost($routine){ + global $load; + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + $cadastra->cadastraPalavras($this->fields("palavrachave"),true,';'); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormPalavra.php b/_config/forms/FormPalavra.php new file mode 100644 index 0000000..4b292ec --- /dev/null +++ b/_config/forms/FormPalavra.php @@ -0,0 +1,19 @@ +flags = "LU"; + } + + function configFields() { + $f = $this->newField("char", array("palavra", "Palavra")); + $f->is_static = true; + $this->addField($f, "LOFU"); + + $f = $this->newField("ativo"); + $f->value_initial = 1; + $this->addField($f, "LOFU"); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormPalavraBusca.php b/_config/forms/FormPalavraBusca.php new file mode 100644 index 0000000..bd160c1 --- /dev/null +++ b/_config/forms/FormPalavraBusca.php @@ -0,0 +1,19 @@ +flags = "L"; + } + + function configFields() { + $f = $this->newField("char", array("palavra", "Palavra")); + $f->is_static = true; + $this->addField($f, "LOF"); + + $f = $this->newField("number", array("quantidade", "Quantidade")); + $f->is_static = true; + $this->addField($f, "LOF"); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormPatologia.php b/_config/forms/FormPatologia.php new file mode 100644 index 0000000..40f3324 --- /dev/null +++ b/_config/forms/FormPatologia.php @@ -0,0 +1,60 @@ +flags = $profile->getFlags(); + } + + function configFields() { + global $profile; + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados do patologia")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 50; + $this->addField($f, "LOFIU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados extra")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("pagina", "URL com http://")); + $f->maxlength = 250; + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("imageUpload", array("imagem", "Ícone ilustrutivo (50x50 px)", "upload/sis_patologia/")); + $f->addThumb("#ID#", 1000, 1000, 4); + $f->addThumb("#ID#_p", 50, 50, 4); + $f->is_required = false; + $this->addField($f, "IU"); + + $f = $this->newField("imageUpload", array("imagem", "Ícone", "upload/sis_patologia/")); + $f->addThumb("#ID#", 1000, 1000, 4); + $f->addThumb("#ID#_p", 50, 50, 4); + $f->is_required = false; + $this->addField($f, "L"); + } + + function onPosPost($routine){ + global $load; + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormProcedencia.php b/_config/forms/FormProcedencia.php new file mode 100644 index 0000000..7b7b517 --- /dev/null +++ b/_config/forms/FormProcedencia.php @@ -0,0 +1,38 @@ +flags = $profile->getFlags(); + } + + function configFields() { + global $profile; + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados da procedência")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 50; + $f->comment = "A procedência identifica o tipo da imagem, como por exemplo: Imagem de Raio X, Ultrasom, foto simples, ressonância, etc."; + $this->addField($f, "LOFIU"); + } + + function onPosPost($routine){ + global $load; + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + } +} +?> \ No newline at end of file diff --git a/_config/forms/FormSistema.php b/_config/forms/FormSistema.php new file mode 100644 index 0000000..7b1d65c --- /dev/null +++ b/_config/forms/FormSistema.php @@ -0,0 +1,60 @@ +flags = $profile->getFlags(); + } + + function configFields() { + global $profile; + + $f = $this->newField("hidden", array("id_usuario", "Responsável")); + $f->value = $profile->fields('id'); + $this->addField($f, "IU"); + + $f = $this->newField("hidden", array("dataalteracao", "Data Alteração")); + $f->value = date("Y-m-d H:i:s"); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados do sistema")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("nome", "Nome")); + $f->maxlength = 50; + $this->addField($f, "LOFIU"); + + $f = $this->newField("html", array("separador")); + $this->addField($f, "IU"); + + $f = $this->newField("html", array("label","Dados extra")); + $this->addField($f, "IU"); + + $f = $this->newField("char", array("pagina", "URL com http://")); + $f->maxlength = 250; + $f->is_required = false; + $this->addField($f, "LOFIU"); + + $f = $this->newField("imageUpload", array("imagem", "Ícone ilustrutivo (50x50 px)", "upload/sis_sistema/")); + $f->addThumb("#ID#", 1000, 1000, 4); + $f->addThumb("#ID#_p", 50, 50, 4); + $f->is_required = false; + $this->addField($f, "IU"); + + $f = $this->newField("imageUpload", array("imagem", "Ícone", "upload/sis_sistema/")); + $f->addThumb("#ID#", 1000, 1000, 4); + $f->addThumb("#ID#_p", 50, 50, 4); + $f->is_required = false; + $this->addField($f, "L"); + } + + function onPosPost($routine){ + global $load; + + $load->config('classes/Palavra.php'); + $cadastra = new Palavra(); + $cadastra->cadastraPalavras($this->fields("nome")); + $cadastra->cadastraPalavras($this->fields("nome"), false); + } +} +?> \ No newline at end of file diff --git a/_config/menu.php b/_config/menu.php new file mode 100644 index 0000000..e16016b --- /dev/null +++ b/_config/menu.php @@ -0,0 +1,76 @@ +checkMenu(1)) { + $subs[] = new Menu_sub("Patologia", "Patologias"); +} +if ($profile->checkMenu(3)) { + $subs[] = new Menu_sub("Sistema", "Sistemas"); +} +if ($profile->checkMenu(16)) { + $subs[] = new Menu_sub("GrupoOrgaoCamada", "Camada Topográfica"); +} +if ($profile->checkMenu(4)) { + $subs[] = new Menu_sub("GrupoOrgao", "Topografia"); +} +if ($profile->checkMenu(2)) { + $subs[] = new Menu_sub("Orgao", "Órgãos"); +} +if ($profile->checkMenu(5)) { + $subs[] = new Menu_sub("Procedencia", "Procedência/Tipo"); +} +if ($profile->checkMenu(6)) { + $subs[] = new Menu_sub("Especialidade", "Especialidade"); +} +if ($profile->checkMenu(15)) { + $subs[] = new Menu_sub("Cid10", "CID 10"); +} +if (count($subs) > 0) { + $menu->add("Informações Gerais", $subs); +} + +$subs = array(); +if ($profile->checkMenu(7)) { + $subs[] = new Menu_sub("Imagem", "Imagens"); +} +if ($profile->checkMenu(8)) { + $subs[] = new Menu_sub("Diagnostico", "Diagnósticos"); +} +if ($profile->checkMenu(13)) { + $subs[] = new Menu_sub("GrupoImagem", "Grupos de imagem"); +} +if ($profile->checkMenu(9)) { + $subs[] = new Menu_sub("CasoEstudo", "Casos de Estudo"); +} +if (count($subs) > 0) { + $menu->add("Informações de Material", $subs); +} + +$subs = array(); +if ($profile->checkMenu(11)) { + $subs[] = new Menu_sub("Palavra", "Palavras"); +} +if ($profile->checkMenu(12)) { + $subs[] = new Menu_sub("PalavraBusca", "Palavras Buscadas"); +} +if (count($subs) > 0) { + $menu->add("Banco de Palavras", $subs); +} + +$subs = array(); +if ($profile->checkMenu(10)) { + $subs[] = new Menu_sub("adminUsuario", "Usuários"); +} +if ($profile->fields('id') == 1) { + $subs[] = new Menu_sub("adminSessao", "Sessões Manager"); + //$subs[] = new Menu_sub("lojaTexto", "Textos Loja","loja_gerenciar_texto.php"); +} + +if (count($subs) > 0) { + $menu->add("Usuários", $subs); +} + +?> \ No newline at end of file diff --git a/_system/app.php b/_system/app.php new file mode 100644 index 0000000..06ac369 --- /dev/null +++ b/_system/app.php @@ -0,0 +1,109 @@ +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"); +?> diff --git a/_system/core/DBTable.php b/_system/core/DBTable.php new file mode 100644 index 0000000..f267df5 --- /dev/null +++ b/_system/core/DBTable.php @@ -0,0 +1,190 @@ +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 diff --git a/_system/core/Debug.php b/_system/core/Debug.php new file mode 100644 index 0000000..20913e4 --- /dev/null +++ b/_system/core/Debug.php @@ -0,0 +1,116 @@ +_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("$" . "debug->loadList();"); + + echo "
" . LF; + + //Events + echo "

Eventos

" . LF; + + foreach ($this->_messages as $k => $v) { + $message = str_replace("[", "$", $v[1]); + $message = str_replace("]", "", $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 . "
" . LF; + } else { + //instant time + echo number_format(($v[0] - $this->_time_ini) * 1000, 2, ",", ".") . "ms - " . $message . "
" . LF; + } + } + + echo "

"; + + //Sqls + echo "

Sqls

" . LF; + + foreach ($this->_sqls as $k => $v) { + $sql = str_replace("[", "$", $v[1]); + $sql = str_replace("]", "", $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 . "
" . LF; + } else { + //instant time + echo number_format(($v[0] - $this->_time_ini) * 1000, 2, ",", ".") . "ms - " . $sql . "
" . LF; + } + } + + echo "
"; + } + } + + //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 diff --git a/_system/core/Error.php b/_system/core/Error.php new file mode 100644 index 0000000..58b2597 --- /dev/null +++ b/_system/core/Error.php @@ -0,0 +1,51 @@ +_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 "
" . LF; + + echo "

" . $this->_levels[$tmp_level] . "

" . LF; + + echo "MESSAGE: " . str_replace(DIR_ROOT, "/", $tmp_message) . "" . LF; + + if ($tmp_line > 0) { + echo "
LINE: " . $tmp_line . LF; + } + + if ($tmp_file != "") { + echo "
FILE: " . str_replace(DIR_ROOT, "/", $tmp_file) . LF; + } + + if ($tmp_class != "") { + echo "
FUNCTION: " . $tmp_class . "::" . $tmp_function . "()" . LF; + } else if ($tmp_function != "") { + echo "
FUNCTION: " . $tmp_function . LF; + } + + echo "
" . 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 diff --git a/_system/core/File.php b/_system/core/File.php new file mode 100644 index 0000000..61b3994 --- /dev/null +++ b/_system/core/File.php @@ -0,0 +1,135 @@ +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 . "/
"; + $this->deleteFolder($tmp_folder . $v . "/"); + } else { + echo "delete file: " . $tmp_folder . $v . "
"; + $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 diff --git a/_system/core/Input.php b/_system/core/Input.php new file mode 100644 index 0000000..487ff34 --- /dev/null +++ b/_system/core/Input.php @@ -0,0 +1,209 @@ +_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[' + ); + + 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 diff --git a/_system/core/Load.php b/_system/core/Load.php new file mode 100644 index 0000000..629594d --- /dev/null +++ b/_system/core/Load.php @@ -0,0 +1,84 @@ +_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 "
" . LF; + + echo "

Includes

" . LF; + + foreach ($this->_includes as $v) { + echo $v . "
" . LF; + } + + echo "
"; + } + + //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 diff --git a/_system/core/Output.php b/_system/core/Output.php new file mode 100644 index 0000000..bd84be5 --- /dev/null +++ b/_system/core/Output.php @@ -0,0 +1,16 @@ +is_ajax = false; + } + + function ajaxHeader() { + header("Content-Type: text/html; charset=iso-8859-1"); + $this->is_ajax = true; + } +} +?> \ No newline at end of file diff --git a/_system/core/System.php b/_system/core/System.php new file mode 100644 index 0000000..992299f --- /dev/null +++ b/_system/core/System.php @@ -0,0 +1,67 @@ +"; + } + } +} +?> \ No newline at end of file diff --git a/_system/css/default.css b/_system/css/default.css new file mode 100644 index 0000000..868d274 --- /dev/null +++ b/_system/css/default.css @@ -0,0 +1,45 @@ +/* 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 */ diff --git a/_system/drivers/Connection.php b/_system/drivers/Connection.php new file mode 100644 index 0000000..733e6b1 --- /dev/null +++ b/_system/drivers/Connection.php @@ -0,0 +1,15 @@ +" . $tmp_cfg["database_server"][$position] . "(" . $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 diff --git a/_system/drivers/mysql/Connection.php b/_system/drivers/mysql/Connection.php new file mode 100644 index 0000000..6d04a37 --- /dev/null +++ b/_system/drivers/mysql/Connection.php @@ -0,0 +1,60 @@ +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. (" . mysql_error() . ")", "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 . " (" . $r->error . ").", "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 diff --git a/_system/drivers/mysql/Recordset.php b/_system/drivers/mysql/Recordset.php new file mode 100644 index 0000000..5d6fa5d --- /dev/null +++ b/_system/drivers/mysql/Recordset.php @@ -0,0 +1,134 @@ +_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 diff --git a/_system/drivers/mysql/Sql.php b/_system/drivers/mysql/Sql.php new file mode 100644 index 0000000..b4d7772 --- /dev/null +++ b/_system/drivers/mysql/Sql.php @@ -0,0 +1,42 @@ +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 diff --git a/_system/drivers/sqlserver/Connection.php b/_system/drivers/sqlserver/Connection.php new file mode 100644 index 0000000..af91b4b --- /dev/null +++ b/_system/drivers/sqlserver/Connection.php @@ -0,0 +1,60 @@ +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. (" . mssql_error() . ")", "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 . " (" . $r->error . ").", "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 diff --git a/_system/drivers/sqlserver/Recordset.php b/_system/drivers/sqlserver/Recordset.php new file mode 100644 index 0000000..6bbf06d --- /dev/null +++ b/_system/drivers/sqlserver/Recordset.php @@ -0,0 +1,127 @@ +_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 diff --git a/_system/drivers/sqlserver/Sql.php b/_system/drivers/sqlserver/Sql.php new file mode 100644 index 0000000..40f12d8 --- /dev/null +++ b/_system/drivers/sqlserver/Sql.php @@ -0,0 +1,39 @@ +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 diff --git a/_system/functions/date.php b/_system/functions/date.php new file mode 100644 index 0000000..c92c11f --- /dev/null +++ b/_system/functions/date.php @@ -0,0 +1,78 @@ + 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 diff --git a/_system/functions/debug.php b/_system/functions/debug.php new file mode 100644 index 0000000..eead061 --- /dev/null +++ b/_system/functions/debug.php @@ -0,0 +1,7 @@ +"; + print_r($tmp_var); + echo ""; +} +?> \ No newline at end of file diff --git a/_system/functions/helper.php b/_system/functions/helper.php new file mode 100644 index 0000000..aca8568 --- /dev/null +++ b/_system/functions/helper.php @@ -0,0 +1,17 @@ +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 diff --git a/_system/functions/swf.php b/_system/functions/swf.php new file mode 100644 index 0000000..eea3d8e --- /dev/null +++ b/_system/functions/swf.php @@ -0,0 +1,65 @@ + 0) { + $arr = explode("?",$src); + + $src = $arr[0]; + $vars = $arr[1]; + } + + $id = " " . $id; + $id = str_replace(" ", "",$id); + + if ($not_ffv) { + $vars = formatFlashVars($vars); + } + + $html = ''; + $html .= ' '; + $html .= ' '; + $html .= ' '; + + $html .= ' '; + $html .= ' '; + + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + $html .= ' '; + + $html .= ' '; + $html .= ' '; + + echo($html); +} + + +function formatFlashVars($tmp_string) { + $words = array(); + $i = 0; + $control_string = ""; + + $words[0] = array("!","\"","#","$","'","\(","\)","\*","\+",",","\"",":",";","<",">","\?","@","\[","\]","\^","\`","\{","|","\}","~","","€","‚","ƒ","„","…","†","‡","ˆ","‰","Š","‹", "Œ","Ž","‘","’","“","”","•","–", "—","˜","™","š","›","œ","ž","Ÿ","¡","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","­","®", "¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ý","þ","ÿ"); + $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 diff --git a/_system/functions/text.php b/_system/functions/text.php new file mode 100644 index 0000000..f13a68c --- /dev/null +++ b/_system/functions/text.php @@ -0,0 +1,139 @@ + $tmp_limit) { + $tmp_text = substr($tmp_text, 0, ($tmp_limit - 3)) . "..."; + } + + return $tmp_text; +} + +function formatHtmlField($tmp_html, $tmp_root = "") { + global $cfg; + + if ($tmp_root != "") { + $bkp = $cfg["root"]; + $cfg["root"] = $tmp_root; + } + + $r = str_replace("#ROOT#", $cfg["root"], $tmp_html); + + if ($tmp_root != "") { + $cfg["root"] = $bkp; + } + + $r = formatSpecialCaracter($r,true); + + echo $r; +} + +function formatFloat($tmp_value) { + return str_replace(".",",",((float)($tmp_value))); +} + +function formatMoney($tmp_value) { + return number_format($tmp_value, 2, ",", "."); +} + +function formatUrlComplete($url) { + if ((strpos($url,'http://') === false) && (strpos($url,'https://') === false) && (strpos($url,'ftp://') === false)) { + return 'http://' . $url; + } else { + return $url; + } + +} + +function formatNameFile($name, $lower = true) { + $name = clearAcents($name,$lower); + + $name = str_replace(' ','_',$name); + + return $name; +} + +function clearAcents($tmp_string, $lower = true) { + if ($lower) { + $tmp_string = strtolower($tmp_string); + } else { + $acents = "ÂÀÁÄÃÊÈÉËÎÍÌÏÔÕÒÓÖÛÙÚÜÇ"; + $normal = "AAAAAEEEEIIIIOOOOOUUUUC"; + + $tmp_string = strtr($tmp_string,$acents,$normal); + } + + $acents = "áàâãäªéèêëîíìïóòôõºúùûüç"; + $normal = "aaaaaaeeeeiiiiooooouuuuc"; + + $tmp_string = strtr($tmp_string,$acents,$normal); + + return $tmp_string; +} + +function formatSpecialCaracter($string, $encode = true) { + $arr_caracter = array( + chr(145),chr(150),chr(148),chr(147),'×','÷','“','”','Œ','‡','¢',chr(128),'™','‰','ƒ','†','¼','½','¾','©','®','ª','²','³','¹','¯','°','¡','£','º' + ); + + $arr_code = array( + chr(96),chr(45),chr(34),chr(34),'×','÷','“','”','Œ','‡','¢','€','™','‰','ƒ','†','¼','½','¾','©','®','ª','²','³','¹','¯','°','¡','£','º' + ); + + if ($encode) { + return str_replace($arr_caracter,$arr_code,$string); + } else { + return str_replace($arr_code,$arr_caracter,$string); + } +} +function scapeAp($tmp_string){ + return str_replace("'", "`", $tmp_string); +} +function getNameFile($name){ + $arr_aux = explode(".",$name); + + if (sizeof($arr_aux) > 1){ + $extensao = $arr_aux[sizeof($arr_aux)-1]; + } else { + $extensao = ""; + } + + if (strlen($extensao) > 0){ + $arquivo = substr($name,0, strlen($name)-(1+strlen($extensao))); + $arr_aux = array($arquivo,$extensao); + } else { + $arr_aux = array($name); + } + + return $arr_aux; +} +function se($arr){ + if(sizeof($arr) > 0){ + $str = ""; + for($x=0;$x \ No newline at end of file diff --git a/_system/functions/url.php b/_system/functions/url.php new file mode 100644 index 0000000..7004dde --- /dev/null +++ b/_system/functions/url.php @@ -0,0 +1,38 @@ +window.open('" . $tmp_url . "', '" . $tmp_frame . "', '');"; + 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 ""; + } else { + if (!(@header("location: " . $tmp_url))) { + if ($tmp_execute_js) { + echo ""; + } + } + } +} +?> \ No newline at end of file diff --git a/_system/js/!popup.js b/_system/js/!popup.js new file mode 100644 index 0000000..41f9fc7 --- /dev/null +++ b/_system/js/!popup.js @@ -0,0 +1,213 @@ +//Requires include default.js +try { var _test_popup = __include_default; } +catch(e) { alert("popup.js : Include '_system/js/default.js' é obrigatório"); } + +//Requires include ajax.js +try { var _test_popup2 = __include_ajax; } +catch(e) { alert("popup.js : Include '_system/js/ajax.js' é obrigatório"); } + +var __include_popup = true; + +var Popup_atual = false; + +function Popup(tmp_w, tmp_h) { + this.title = ""; + this.bg_alpha = 60; + + this.width = tmp_w; + this.height = tmp_h; + + this.overflow = 'auto'; + this.template = 1; + + this.onLoad = new Function(); + + this._id_bg = ""; + this._id_box = ""; + + this.open = function (tmp_url) { + var b = document.getElementsByTagName('body')[0]; + var self = this; + + //Create ids + this._id_bg = this._genId(); + this._id_box = this._genId(); + + //Create bg + var bg = document.createElement('div'); + bg.setAttribute('id', this._id_bg); + 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 + ');'); + bg.style.position = 'absolute'; + bg.style.left = "0px"; + bg.style.top = "0px"; + bg.style.width = this.setWidthBox(); + bg.style.height = this.setHeightBox(); + bg.style.background = '#000'; + bg.style.filter = 'alpha(opacity=' + this.bg_alpha + ')'; + bg.innerHTML = ' '; + b.appendChild(bg); + + //Adjust positions + this.Popup_f = function (e, n) { + var pos = new WindowPosition(); + var div = $$(self._id_bg); + var box = $$(self._id_box); + var box2 = $$(self._id_box + "_ext"); + + if (div) { + var x = pos.x + (pos.w / 2) - ((self.width) / 2); + var y = pos.y + (pos.h / 2) - ((self.height) / 2); + + box.style.left = x + "px"; + box.style.top = y + "px"; + + if ((self.template == 1) || (self.template == 3)) { + box2.style.left = (x - 5) + "px"; + box2.style.top = (y - 20) + "px"; + } + + div.style.display = ''; + box.style.display = ''; + div.style.zIndex = 999; + + if ((n == undefined) && (window.Popup_f)) { + window.Popup_f(e, 1); + } + } + } + addEvent(window, "scroll resize", this.Popup_f); + window.Popup_f = this.Popup_f; + + //Create html + switch (this.template) { + default: + case 1: + var html = '
'; + html += '
'; + html += '
'; + html += '
Carregando janela
'; + html += '
'; + + tn = document.createElement('div'); + tn.innerHTML = html; + b.appendChild(tn); + + var box = $$(this._id_box); + box.style.width = this.width + 'px'; + box.style.height = this.height + 'px'; + box.style.overflow = this.overflow; + + var box2 = $$(this._id_box + "_ext"); + box2.style.filter = 'alpha(opacity=' + this.bg_alpha + ')'; + box2.style.width = (this.width + 10) + 'px'; + box2.style.height = (this.height + 25) + 'px'; + + break; + case 2: + var html = '
'; + html += '
Carregando janela
'; + html += '
'; + + tn = document.createElement('div'); + tn.innerHTML = html; + b.appendChild(tn); + + var box = $$(this._id_box); + box.style.width = this.width + 'px'; + box.style.height = this.height + 'px'; + box.style.overflow = this.overflow; + + break; + case 3: + var html = '
'; + html += '
'; + html += '
'; + html += '
Carregando janela
'; + html += '
'; + + tn = document.createElement('div'); + tn.innerHTML = html; + b.appendChild(tn); + + var box = $$(this._id_box); + box.style.width = this.width + 'px'; + box.style.height = this.height + 'px'; + box.style.overflow = this.overflow; + + var box2 = $$(this._id_box + "_ext"); + box2.style.filter = 'alpha(opacity=' + this.bg_alpha + ')'; + box2.style.width = (this.width + 10) + 'px'; + box2.style.height = (this.height + 25) + 'px'; + + break; + } + + this.Popup_f(); + setTimeout(Popup_f, 50); + setTimeout(Popup_f, 100); + setTimeout(Popup_f, 150); + setTimeout(Popup_f, 300); + setTimeout(Popup_f, 500); + + var a = new Ajax(); + a.onLoad = function () { + $$(self._id_box).innerHTML = this.html; + + this.runJS(this.html); + + if (self.onLoad) { + self.onLoad(); + } + } + a.get(tmp_url); + + Popup_atual = this; + } + + this.close = function () { + var box = $$(this._id_bg); + var div = $$(this._id_box); + var div2 = $$(this._id_box + "_ext"); + var b = document.getElementsByTagName('body')[0]; + + if (div) { removeElement(div); } + if (div2) { removeElement(div2); } + if (box) { removeElement(box); } + + removeEvent(window, "scroll", this.Popup_f); + removeEvent(window, "resize", this.Popup_f); + window.Popup_f = undefined; + } + + this._genId = function () { + var id = "popup" + new String(Math.round(Math.random() * 1000)); + + if ($$(id)) { + id = this._genId(); + } + + return id; + } + + this.setHeightBox = function() { + var heightBody = document.body.clientHeight; + var heightScroll = document.body.scrollHeight; + + if (heightBody > heightScroll) { + return "100%"; + } else { + return heightScroll+'px'; + } + } + + this.setWidthBox = function() { + var widthBody = document.body.clientWidth; + var widthScroll = document.body.scrollWidth; + + if (widthBody > widthScroll) { + return "100%"; + } else { + return widthScroll+'px'; + } + } +} \ No newline at end of file diff --git a/_system/js/ajax.js b/_system/js/ajax.js new file mode 100644 index 0000000..85c22f2 --- /dev/null +++ b/_system/js/ajax.js @@ -0,0 +1,233 @@ +/* +Ajax handler +by Ramon Fritsch (www.ramonfritsch.com) + +Ex.: +var a = new Ajax(); +a.onLoad = function () { + alert(this.html); +} +a.get("url.php"); +*/ + + +//Requires include default.js +try { var _test_ajax = __include_default; } +catch(e) { alert("ajax.js : Include '_system/js/default.js' é obrigatório"); } + +var __include_ajax = true; + +//class Ajax +function Ajax() { + var obj; + + var unique = true; + + var html; + var xml; + + var response_type = "html"; + + var onLoad = new Function(); + var onPreLoad = new Function(); + + this.createObject = function () { + var parent = this; + + obj = this.getAjaxObj(); + obj.onreadystatechange = function() { + if(obj.readyState == 4) { + var arr; + + //xml + if (response_type == "xml") { + //need test + if (obj.responseXml != undefined) { + try { + parent.xml = obj.responseXml; + } catch (e) { } + } else { + try { + parent.xml = parent.parseXML(obj.responseText); + } catch (e) { } + } + } else { + //html + parent.html = obj.responseText; + } + + obj = null; + + parent.onLoad(); + + Ajax_unique = false; + } + } + } + + this.get = function (tmp_url) { + if (tmp_url == '') { + alert("Ajax.get() : Url vazia"); + + return; + } + + if (this.isFree()) { + this.createObject(); + + if (typeof(this.onPreLoad) == "function") { + this.onPreLoad(); + } + + obj.open('GET', tmp_url); + obj.setRequestHeader("Content-type", "text/html;charset=iso-8859-1"); + obj.setRequestHeader("Connection", "close"); + obj.send(null); + } + } + + this.post = function (tmp_url, tmp_parameters, tmp_content_type) { + if (tmp_url == '') { + alert("Erro - Ajax.post() : Url vazia"); + + return; + } + + if (tmp_content_type == undefined) { + tmp_content_type = "application/x-www-form-urlencoded"; + } + + if (this.isFree()) { + this.createObject(); + + if (typeof(this.onPreLoad) == "function") { + this.onPreLoad(); + } + + obj.open('POST', tmp_url); + obj.setRequestHeader("Content-type", tmp_content_type); + obj.setRequestHeader("Content-length", tmp_parameters.length); + obj.setRequestHeader("Connection", "close"); + obj.send(tmp_parameters); + } + } + + this.sendForm = function(tmp_id) { + var p = ""; + var field; + var form = $$(tmp_id); + + for (i = 0; i < form.length; i++) { + field = form.elements[i]; + + if (field.type == 'checkbox' || field.type == 'radio') { + if (field.checked) { + p += '&' + field.name + '=' + this.formatString(field.value); + } + } else { + p += '&' + field.name + '=' + this.formatString(field.value); + } + } + + this.post(form.action, p); + } + + //Unique + this.isFree = function () { + var r = (!(this.unique && Ajax_unique)) || !this.unique; + + if (r) { + Ajax_unique = true; + } + + return r; + } + + this.setUnique = function (tmp_valor) { + this.unique = tmp_valor; + } + + //Funções auxiliares + this.getAjaxObj = function () { + var xmlhttp; + try { + xmlhttp = new XMLHttpRequest(); + } catch (e) { + try { + xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); + } catch (ex) { + try { + xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); + } catch(exc) { + alert("Erro - Ajax.getAjaxObj() : " + exc.error); + } + } + } + return xmlhttp?xmlhttp:false; + } + + this.parseXML = function (tmp_string) { + var xml; + + try { + xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async="false"; + xml.loadXML(tmp_string); + } catch(e) { + try { + Parser = new DOMParser(); + xml = Parser.parseFromString(tmp_string,"text/xml"); + } catch(ex) { + alert("Erro - Ajax.parseXML('" + tmp_string.substr(0, 16) + "...') : " + ex.message); + } + } + + return xml; + } + + this.runJS = function (tmp_html) { + var el = document.createElement('div'); + el.innerHTML = '
content
' + tmp_html; //Ie sucx! + + var scripts = el.getElementsByTagName('script'); + var js_exec = ""; + var total_eval = scripts.length; + var i_eval = 0; + + for (; i_eval < total_eval; i_eval++) { + if (isIE) { + js_exec = scripts[i_eval].text; + } else if (isMoz) { + js_exec = scripts[i_eval].textContent; + } else { + js_exec = scripts[i_eval].innerHTML; + } + + try { + eval(js_exec); + } catch(e) { + alert("Erro - Ajax.runJS('" + tmp_html.substr(0, 16) + "...') : " + e.message); + } + } + } + + this.formatString = function (tmp_string) { + var words = new Array(); + var i = 0; + var new_string = ""; + var control_string = ""; + + words[0] = new Array("!","\"","#","$","&","'","\(","\)","\*","\+",",","\"",":",";","<","=",">","\?","@","\[","\]","\^","\`","\{","|","\}","~","","€","‚","ƒ","„","…","†","‡","ˆ","‰","Š","‹", "Œ","Ž","‘","’","“","”","•","–", "—","˜","™","š","›","œ","ž","Ÿ","¡","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","­","®", "¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ý","þ","ÿ"); + 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"); + + 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; + } +} +var Ajax_unique = false; \ No newline at end of file diff --git a/_system/js/default.js b/_system/js/default.js new file mode 100644 index 0000000..698eff1 --- /dev/null +++ b/_system/js/default.js @@ -0,0 +1,238 @@ +var __include_default = true; + +//Browser detector +var isIE = false, isMoz = false, isSaf = false; +(function () { + if ((navigator.userAgent.indexOf('Safari') != -1)) { isSaf = true; } + else if ((navigator.appName == 'Netscape')) { isMoz = true; } + else { isIE = true; } +}()); + +//Get element(s) by id, #id or .classname +function $$(tmp_query, tmp_root) { + if (tmp_query.indexOf('.') > -1) { + var r = [], elms, i = 0, i2 = 0, r2; + + tmp_query = tmp_query.substr(1, tmp_query.length - 1); + + tmp_root = (tmp_root != null) ? tmp_root : document; + elms = (tmp_root.all) ? tmp_root.all : tmp_root.getElementsByTagName('*'); + + for (; i < elms.length; i++) { + if (tmp_query == elms[i].className) { + r.push(elms[i]); + } + } + + return r; + } else if (tmp_query.indexOf('#') > -1) { + var r = [], elms, i = 0, i2 = 0, r2; + + tmp_query = tmp_query.substr(1, tmp_query.length - 1); + + tmp_root = (tmp_root != null) ? tmp_root : document; + elms = (tmp_root.all) ? tmp_root.all : tmp_root.getElementsByTagName('*'); + + for (; i < elms.length; i++) { + if (tmp_query == elms[i].id) { + r.push(elms[i]); + } + } + + return r; + } else { + if (document.getElementById(tmp_query)) { + return document.getElementById(tmp_query); + } else { + return null; + } + } +} + +//Nothing function for href property of tag +function nothing_func() { } + +//Alert describe object +function alert_r(tmp_obj, tmp_alert) { + var msg = ''; + + for (var v in tmp_obj) { + msg += ' ' + v + ' = \'' + (new String(tmp_obj[v])) + '\'\n'; + } + + if (tmp_alert == true) { + alert('Object (' + tmp_obj + '):\n' + msg); + } else { + var div = document.createElement('div'); + div.id = 'alert_r_' + Math.round(Math.random() * 99999); + div.style.position = 'absolute'; + div.style.top = '0px'; + div.style.left = '0px'; + div.style.background = '#EEEEEE'; + div.innerHTML = '
' + msg + '
'; + + document.getElementsByTagName('body')[0].appendChild(div); + + addEvent(div, 'click', function () { removeElement(this); }); + } +} + +//Add tmp_function event for tmp_object +function addEvent(tmp_obj, tmp_event, tmp_function) { + var f = function (e) { + tmp_function.apply(tmp_obj, [e || event]); + }; + + if (typeof tmp_event == "string") { + if (tmp_event.indexOf(" ") > -1) { + var arr = tmp_event.split(" "); + for (var i = 0; i < arr.length; i++) { + addEvent(tmp_obj, arr[i], tmp_function); + } + + return true; + } + } else if (typeof tmp_event == "object") { + for (var i = 0; i < tmp_event.length; i++) { + addEvent(tmp_obj, tmp_event[i], tmp_function); + } + + return true; + } + + if (tmp_obj) { + try { + tmp_obj.addEventListener(tmp_event, f, false); + } catch (e) { + try { + tmp_obj.attachEvent("on" + tmp_event, f); + } catch (e2) { + return false; + } + } + + return true; + } else { + return false; + } +} + +function removeEvent(tmp_obj, tmp_type, tmp_function) { + if (isIE) { + tmp_obj.detachEvent("on" + tmp_type, tmp_function); + } else { + tmp_obj.removeEventListener(tmp_type, tmp_function, false); + } +} + +function removeElement(tmp_obj) { + tmp_obj.parentNode.removeChild(tmp_obj); +} + +function redir(tmp_pagina) { + document.location = tmp_pagina; +} + +function openPopup(tmp_url, tmp_w, tmp_h, tmp_name) { + var x = (screen.width - tmp_w) / 2; + var y = (screen.height - tmp_h) / 2; + + if (!tmp_name) { + var rnd = Math.round(Math.random() * 99999); + tmp_name = "nova_janela" + rnd; + } + + var v = window.open(tmp_url, tmp_name,'height=' + tmp_h + ', width=' + tmp_w + ', left=' + x + ', top=' + y); +} + +//Prototypes +String.prototype.trim = function () { + var r = /\s*((\S+\s*)*)/g; + var r2 = /((\s*\S+)*)\s*/g; + + return this.replace(r, "$1").replace(r2, "$1"); +} + +Function.prototype.bind = function(tmp_object) { + var tmp_method = this; + + return function() { return tmp_method.apply(tmp_object, arguments); } +} + +Array.prototype.each = function (tmp_func) { + var i = 0; + var length = this.length; + + var ev = "tmp_func(i, this[i])"; + + for (; i < length; i++) { + eval(ev); + } +} + +if (!Array.prototype.indexOf) Array.prototype.indexOf = function(tmp_item, tmp_i) { + var length = this.length; + + tmp_i || (tmp_i = 0); + if (tmp_i < 0) tmp_i = length + tmp_i; + + for (; tmp_i < length; tmp_i++) { if (this[tmp_i] === tmp_item) return tmp_i; } + + return -1; +} + +Array.prototype.remove = function (tmp_itens) { + if (typeof(tmp_itens) != "object") { + tmp_itens = [tmp_itens]; + } + + var i = 0; i2 = 0; + var new_array = []; + + for (; i < this.length; i++) { + if (tmp_itens.indexOf(this[i]) == -1) { + new_array[i2] = this[i]; + i2++; + } + } + + return new_array; +} + + +//Window Position class +function WindowPosition() { + this.x = 0; + this.y = 0; + this.w = 0; + this.h = 0; + + if (typeof(window.pageYOffset) == 'number') { + this.x = window.pageXOffset; + this.y = window.pageYOffset; + } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) { + this.x = document.body.scrollLeft; + this.y = document.body.scrollTop; + } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { + this.x = document.documentElement.scrollLeft; + this.y = document.documentElement.scrollTop; + } + + if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { + // Se o DOCTYPE foi retirado da pagina, as 2 linhas de cima devem ser comentadas e deixar as duas abaixa descomentada + // Caso contrario, descomentar as 2 de cima e comentar as 2 linhas de baixo + +// this.w = document.documentElement.clientWidth; +// this.h = document.documentElement.clientHeight; + this.w = document.body.clientWidth; + this.h = document.body.clientHeight; + } else if (typeof(window.innerWidth) == 'number') { + this.w = window.innerWidth; + this.h = window.innerHeight; + } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) { + this.w = document.body.clientWidth; + this.h = document.body.clientHeight; + } +} + + diff --git a/_system/js/form.js b/_system/js/form.js new file mode 100644 index 0000000..21bbb8e --- /dev/null +++ b/_system/js/form.js @@ -0,0 +1,639 @@ +/* +Form validation +by Ramon Fritsch (www.ramonfritsch.com) + +Types: TXT, NUM, CEP, TEL, PW1, PW2, DAT, HOR, EML, CPF, CMB, RDO, CNP, DIN, FLO, INT +Required: 1 = true, 0 = false + +Sintax: (Label)[#Index]_(Type)(Required)[_(Minchars)] + +Ex.: +id="CPF_CPF1" //Simple +id="Nome#2_TXT1_255" //Complex +*/ + + +//Requires include default.js +try { var _test_form = __include_default; } +catch(e) { alert("form.js : Include '_system/js/default.js' é obrigatório"); } + +var __include_form = true; + +//class Form +function Form() { + this.linguage = 1; //1 => port + + this.send = function (tmp_id, tmp_return) { + if (tmp_return == undefined) { + tmp_return = false; + } + + var i = 0; + var error = false; + var form = $$(tmp_id); + var valid_numbers = '0123456789,.'; + var valid_telphone = '0123456789. ()'; + var valid_cep = '0123456789-'; + var tmp_pass = ''; + var param_id; + var param_type; + var param_name; + var param_value; + var obj; + var r_parse; + + var label; + var type; + var required; + var minchars; + + + form.onsubmit = function () { return false; } + + + //elements loop + while (form.elements[i]) { + obj = form.elements[i]; + + param_id = obj.id; + param_type = obj.type; + param_name = obj.name; + param_value = obj.value; + param_testDV = false; + + if(obj.attributes["testDV"]){ + if(obj.attributes["testDV"].value != "") + param_testDV = true; + } + + r_parse = this._parseId(param_id); + + label = r_parse[0]; + type = r_parse[1]; + required = r_parse[2]; + minchars = r_parse[3]; + + switch (type) { + case "FIL": + if ((required) && (!param_value)) { + this._showMessage(0, label); + obj.focus(); + return false; + } else if((required) || (param_value)) { + arr_types = Array(); + if (obj.accept != ""){ + arr_types = obj.accept.split(","); + arr_file = param_value.split("."); + valid = false; + if (arr_file.length > 1){ + for (cont = 0; cont 0) && (month <= 12) && (month > 0) && (year >= 1800)) { + //Valid Date + } else { + this._showMessage(4, label); + obj.focus(); + return false; + } + } else if (required) { + this._showMessage(0, label); + obj.focus(); + return false; + } + + break; + case "HOR": + if (param_value) { + if ((param_value.length == 5) && (param_value.charAt(2) == ':') && (param_value.split(':')[0]*1 <= 24) && (param_value.split(':')[1]*1 <= 59)) { + //Valid Hour + } else { + this._showMessage(8, label); + obj.focus(); + return false; + } + } else if (required) { + this._showMessage(0, label); + obj.focus(); + return false; + } + + break; + case "HO2": + if (param_value) { + 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)) { + //Valid Hour + } else { + this._showMessage(10, label); + obj.focus(); + return false; + } + } else if (required) { + this._showMessage(0, label); + obj.focus(); + return false; + } + + break; + case "EML": + if (param_value) { + if ((param_value.indexOf(".") > 0) && (param_value.indexOf("@") > 0) && (param_value.length > 3) && (param_value != "@.")) { + //Valid e-mail + } else { + this._showMessage(5, label); + obj.focus(); + return false; + } + } else if (required) { + this._showMessage(0, label); + obj.focus(); + return false; + } + + break; + case "CPF": + if (param_value) { + var p1 = param_value.substring(0,3); + var p2 = param_value.substring(4,7); + var p3 = param_value.substring(8,11); + var p4 = param_value.substring(12,14); + var cpf = p1 + p2 + p3 + p4; + var cpf_verif = cpf.substring(9,11); + var c = 0; + var position=1; + + for (cont=0;cont<9;cont++) { + c+=cpf.substring(cont,position)*(10-cont); + position++; + } + + c = (11-(c % 11)); + if (c > 9) { c=0; } + if (cpf_verif.substring(0,1) != c) { + this._showMessage(6); + obj.focus(); + return false; + } + + c *= 2; + position = 1; + for (cont=0; cont<9; cont++) { + c+=cpf.substring(cont,position)*(11-cont); + position++; + } + + c = (11-(c % 11)); + if (c > 9) { c = 0; } + + if (cpf_verif.substring(1,2) != c) { + this._showMessage(6); + obj.focus(); + return false; + } + + if ((cpf == '99999999999') || (cpf == '88888888888') || (cpf == '77777777777') || (cpf == '66666666666') || (cpf == '55555555555') || (cpf == '44444444444') || (cpf == '33333333333') || (cpf == '22222222222') || (cpf == '11111111111')) { + this._showMessage(6); + obj.focus(); + return false; + } + } else if (required) { + this._showMessage(0, label); + obj.focus(); + return false; + } + + break; + + case "CNP": + if (param_value) { + var p1 = param_value.substring(0,2); + var p2 = param_value.substring(3,6); + var p3 = param_value.substring(7,10); + var p4 = param_value.substring(11,15); + var digitoverificador = param_value.substring(16,18); + var cnpj = p1 + p2 + p3 + p4; + var position=1; + var arr_multiplicadores1 = new Array(5,4,3,2,9,8,7,6,5,4,3,2); + var arr_multiplicadores2 = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2); + var soma = 0; + var divisao = 0; + var resto = 0; + var verificador1; + var verificador2; + + //---------- PRIMEIRO DIGITO ----------------- + for (cont=0;cont<12;cont++) { + soma += (cnpj.substring(cont,position)*(arr_multiplicadores1[cont])); + position++; + } + + divisao = parseInt(soma / 11); + resto = soma % 11; + + if (resto > 1) { + verificador1 = 11 - resto + } else { + verificador1 = 0; + } + //---------- / PRIMEIRO DIGITO ----------------- + + //---------- SEGUNDO DIGITO ----------------- + soma = 0; + position = 1; + for (cont=0;cont<12;cont++) { + soma += (cnpj.substring(cont,position)*(arr_multiplicadores2[cont])); + position++; + } + + soma += verificador1 * arr_multiplicadores2[12]; + + divisao = parseInt(soma / 11); + resto = soma % 11; + + if (resto > 1) { + verificador2 = 11 - resto + } else { + verificador2 = 0; + } + //---------- SEGUNDO DIGITO ----------------- + + if (digitoverificador != (verificador1+''+verificador2)) { + this._showMessage(11); + obj.focus(); + return false; + } + } else if (required) { + this._showMessage(0, label); + obj.focus(); + return false; + } + break; + case "CMB": + if (((obj.selectedIndex == 0) || (obj.selectedIndex == 1)) && (required)) { + this._showMessage(7, label); + obj.focus(); + return false; + } + + break; + case "RDO": + var ok = 0; + var el = document.getElementsByName(param_name); + + for (i_el=0; i_el < el.length; i_el++) { + var tmp = el[i_el].checked; + if (tmp) { ok = 1; } + } + + if ((required) && (ok == 0)) { + this._showMessage(7, label); + obj.focus(); + return false; + } + + break; + } + + //filter min chars + if ((minchars > 0) && (param_value.length < minchars) && (required)) { + this._showMessage(9, label, minchars); + obj.focus(); + return false; + } + + i++; + } + + if (tmp_return) { + return true; + } else { + form.submit(); + } + } + + this.maskFields = function () { + var inputs = document.getElementsByTagName('input'); + var length = inputs.length; + var el; + var type; + var id; + var r_parse; + + for (i = 0; i < length; i++) { + el = inputs[i]; + id = el.id; + + r_parse = f._parseId(id); + + type = r_parse[1]; + switch (type) { + case "CPF": + addEvent(el, 'keyup keypress keydown', function() { f._mask('CPF', this.id); }); + el.maxLength = 14; + + break; + case "DAT": + addEvent(el, 'keyup keypress keydown', function() { f._mask('DAT', this.id); }); + el.maxLength = 10; + + break; + case "HOR": + addEvent(el, 'keyup keypress keydown', function() { f._mask('HOR', this.id); }); + el.maxLength = 5; + + break; + + case "HO2": + addEvent(el, 'keyup keypress keydown', function() { f._mask('HO2', this.id); }); + el.maxLength = 8; + + break; + + case "TEL": + addEvent(el, 'keyup keypress keydown', function() { f._mask('TEL', this.id); }); + el.maxLength = 14; + + break; + case "CNP": + addEvent(el, 'keyup keypress keydown', function() { f._mask('CNP', this.id); }); + el.maxLength = 18; + + break; + case "CEP": + addEvent(el, "keyup keypress keydown", function() { f._mask('CEP', this.id); }); + el.maxLength = 9; + + break; + case "NUM": + addEvent(el, 'keyup', function() { f._mask('NUM', this.id); }); + + break; + case "FLO": + addEvent(el, 'keyup', function() { f._mask('FLO', this.id); }); + + break; + case "DIN": + addEvent(el, 'keyup', function() { f._mask('DIN', this.id); }); + el.maxLength = 15; + + break; + } + } + } + + this._showMessage = function (tmp_index) { + msgs = Array(); + + if (this.linguage == 1) { + msgs[0] = 'Por favor complete o campo "%1"'; + msgs[1] = 'Caracter inválido colocado no campo %1'; + msgs[2] = 'Você precisa digitar uma senha.'; + msgs[3] = 'A confirmação da senha não é válida.'; + msgs[4] = 'Por favor complete o campo "%1" com formato dd/mm/aaaa'; + msgs[5] = 'Dados inválidos colocados no campo %1'; + msgs[6] = 'CPF Inválido!'; + msgs[7] = 'Por favor selecione uma opção para o campo "%1"'; + msgs[8] = 'Por favor complete o campo "%1" com formato hh:mm'; + msgs[9] = 'O campo "%1" deve conter pelo menos %2 caracteres.' ; + msgs[10] = 'Por favor complete o campo "%1" com formato hh:mm:ss'; + msgs[11] = 'CNPJ Inválido!'; + msgs[12] = 'Tipo de arquivo inválido. \nO campo "%1" aceita somente arquivos com as extensões "%2".'; + } + //TODO: Make strings of different languages. (English, Spanish...) + + var r = String(msgs[tmp_index]); + for (i = 1; i <= 5; i++) { + r = r.replace("%" + i, arguments[i]); + } + + alert(r); + } + + this._parseId = function (tmp_id) { + var i = 0; + var underscore = 0; + var qnt = 0; + var type = ''; + var required; + var label = ''; + var minchars = ''; + + while (i < tmp_id.length) { + if ((tmp_id.charAt(i) != '_') && (!underscore)) { + label = label + tmp_id.charAt(i); + } else if (tmp_id.charAt(i) == '_') { + underscore++; + } else if (underscore == 1) { + if (type.length < 3) { + type = type + tmp_id.charAt(i); + } else { + if (tmp_id.charAt(i) == '0') { + required = false; + } else { + required = true; + } + } + } else if (underscore == 2) { + minchars = minchars + '' + tmp_id.charAt(i); + } + i++; + } + + //format minchars + if (minchars == '') { + minchars = 0; + } + minchars = parseInt(minchars); + + //parse name + var arr = label.split("**"); + label = arr[0].trim(); + + return Array(label, type, required, minchars); + } + + + this._mask = function (tmp_type, tmp_id) { + var obj = $$(tmp_id); + + switch (tmp_type) { + case "CPF": + var value = f._filterChars(obj.value, "0123456789"); + value = f._filterMask(value, "XXX.XXX.XXX-XX"); + obj.value = value; + + break; + case "DAT": + var value = f._filterChars(obj.value, "0123456789"); + value = f._filterMask(value, "XX/XX/XXXX"); + obj.value = value; + + break; + case "HOR": + var value = f._filterChars(obj.value, "0123456789"); + value = f._filterMask(value, "XX:XX"); + obj.value = value; + + break; + case "HO2": + var value = f._filterChars(obj.value, "0123456789"); + value = f._filterMask(value, "XX:XX:XX"); + obj.value = value; + + break; + case "TEL": + var value = f._filterChars(obj.value, "0123456789"); + value = f._filterMask(value, "(XX) XXXX-XXXX"); + + obj.value = value; + + break; + case "CNP": + var value = f._filterChars(obj.value, "0123456789"); + value = f._filterMask(value, "XX-XXX-XXX/XXXX-XX"); + obj.value = value; + + break; + case "CEP": + var value = f._filterChars(obj.value, "0123456789"); + value = f._filterMask(value, "XXXXX-XXX"); + obj.value = value; + + break; + case "NUM": + var value = f._filterChars(obj.value, "0123456789"); + obj.value = value; + + break; + + case "FLO": + var value = f._filterChars(obj.value, "0123456789,"); + obj.value = value; + + break; + case "DIN": + var possui_menos = false; var n = '__0123456789-'; var d = obj.value; var l = d.length; var r = ''; var len = 15; + var wa, wb, w, verificador, z, c, n, a; + if (l > 0) { z = d.substr(0,l-1); s = ''; a = 2; + 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); }; + 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; }; }; }; + 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; }; }; + }; + if (r.length <= len) { obj.value=r; } else { obj.value=z; }; + + break; + + } + } + + //Mask functions + this._filterChars = function (tmp_valor, tmp_mask) { + var txt = ""; + var i = 0; + var c; + + while (i < tmp_valor.length) { + c = tmp_valor.charAt(i); + + if (tmp_mask.indexOf(c) != -1) { + txt += c; + } + + i++; + } + + return txt; + } + + this._filterMask = function (tmp_valor, tmp_mask) { + var txt = ""; + var txt2 = ""; + var i = 0; + var c; + var i2 = 0; + var i_ultimo; + var i_ultimo2 = 0; + var i_ultimo_fake = true; + + while (i < tmp_mask.length) { + c = tmp_mask.charAt(i); + + if (c == 'X') { + if (tmp_valor.charAt(i2) != '') { + txt += tmp_valor.charAt(i2); + txt2 += tmp_valor.charAt(i2); + i2++; + i_ultimo = i; + i_ultimo2 = i2; + } else { + i_ultimo_fake = false; + } + } else { + if (i_ultimo2 < tmp_valor.length) { + txt2 += c; + } + txt += c; + } + + i++; + } + + if (i_ultimo_fake) { + txt2 = txt; + } + + return txt2; + } +} +var f = new Form(); +addEvent(window, 'load', f.maskFields); \ No newline at end of file diff --git a/_system/js/popup.js b/_system/js/popup.js new file mode 100644 index 0000000..8e1c738 --- /dev/null +++ b/_system/js/popup.js @@ -0,0 +1,298 @@ +//Requires include default.js +try { var _test_popup = __include_default; } +catch(e) { alert("popup.js : Include '_system/js/default.js' é obrigatório"); } + +//Requires include ajax.js +try { var _test_popup2 = __include_ajax; } +catch(e) { alert("popup.js : Include '_system/js/ajax.js' é obrigatório"); } + +var __include_popup = true; + +var Popup_atual = false; + +function Popup(tmp_w, tmp_h) { + this.title = ""; + this.bg_alpha = 60; + + this.width = tmp_w; + this.height = tmp_h; + + this.overflow = 'auto'; + this.template = 1; + + this.valign = "middle"; + this.align = "center"; + + this.fixPosition = true; + + this.ownTop = 0; + this.ownLeft = 0; + + this.position = "relative"; + + this.onLoad = new Function(); + + this._id_bg = ""; + this._id_box = ""; + + this.open = function (tmp_url) { + var b = document.getElementsByTagName('body')[0]; + var self = this; + + //Create ids + this._id_bg = this._genId(); + this._id_box = this._genId(); + + //Create bg + var bg = document.createElement('div'); + bg.setAttribute('id', this._id_bg); + 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 + ');'); + bg.style.position = 'absolute'; + bg.style.left = "0px"; + bg.style.top = "0px"; + bg.style.width = this.setWidthBox(); + bg.style.height = this.setHeightBox(); + bg.style.background = '#000'; + bg.style.filter = 'alpha(opacity=' + this.bg_alpha + ')'; + bg.innerHTML = ' '; + b.appendChild(bg); + + //Adjust positions + this.Popup_bg = function (e, n){ + var div = $$(self._id_bg); + if(div){ + div.style.width = self.setWidthBox(); + div.style.height = self.setHeightBox(); + } + } + this.Popup_f = function (e, n) { + var pos = new WindowPosition(); + var div = $$(self._id_bg); + var box = $$(self._id_box); + var box2 = $$(self._id_box + "_ext"); + + if (div) { + var x; + var y; + + switch(self.valign){ + case "top": + y = pos.y + self.ownTop; + break; + case "middle": + y = pos.y + (pos.h / 2) - ((self.height) / 2) + self.ownTop; + break; + case "bottom": + y = pos.y + pos.h - self.height + self.ownTop; + break; + } + + switch(self.align){ + case "left": + x = pos.x + self.ownLeft; + break; + case "center": + x = pos.x + (pos.w / 2) - ((self.width) / 2) + self.ownLeft; + break; + case "right": + x = pos.x + (pos.w / 2) - ((self.width) / 2) + self.ownLeft; + break; + } + + box.style.left = x + "px"; + box.style.top = y + "px"; + + if ((self.template == 1) || (self.template == 3)) { + box2.style.left = (x - 5) + "px"; + box2.style.top = (y - 20) + "px"; + } + + if(self.fixPosition){ + var boxTop = box.style.top.replace('px',''); + var boxLeft = box.style.left.replace('px',''); + + var boxTop2 = boxTop-20; + var boxLeft2 = boxLeft-5; + + if(boxTop2 < 0){ + box2.style.top = '0px'; + box.style.top = '20px'; + } + //alert('box.style.left = '+boxLeft+'\nbox.style.top = '+boxTop); + //alert('box2.style.left = '+boxLeft2+'\nbox2.style.top = '+boxTop2); + } + + div.style.display = ''; + box.style.display = ''; + div.style.zIndex = 999; + + if ((n == undefined) && (window.Popup_f)) { + window.Popup_f(e, 1); + } + } + } + if(self.position != "fixed") + addEvent(window, "scroll resize", this.Popup_f); + addEvent(window, "scroll resize", this.Popup_bg); + window.Popup_f = this.Popup_f; + + //Create html + switch (this.template) { + default: + case 1: + var html = '
'; + html += ''; + + tn = document.createElement('div'); + tn.innerHTML = html; + b.appendChild(tn); + + var box = $$(this._id_box); + box.style.width = this.width + 'px'; + box.style.height = this.height + 'px'; + box.style.overflow = this.overflow; + + var box2 = $$(this._id_box + "_ext"); + box2.style.filter = 'alpha(opacity=' + this.bg_alpha + ')'; + box2.style.width = (this.width + 10) + 'px'; + box2.style.height = (this.height + 25) + 'px'; + + break; + case 2: + var html = ''; + + tn = document.createElement('div'); + tn.innerHTML = html; + b.appendChild(tn); + + var box = $$(this._id_box); + box.style.width = this.width + 'px'; + box.style.height = this.height + 'px'; + box.style.overflow = this.overflow; + + break; + case 3: + var html = '
'; + html += '
'; + html += ''; + + tn = document.createElement('div'); + tn.innerHTML = html; + b.appendChild(tn); + + var box = $$(this._id_box); + box.style.width = this.width + 'px'; + box.style.height = this.height + 'px'; + box.style.overflow = this.overflow; + + var box2 = $$(this._id_box + "_ext"); + box2.style.filter = 'alpha(opacity=' + this.bg_alpha + ')'; + box2.style.width = (this.width + 10) + 'px'; + box2.style.height = (this.height + 25) + 'px'; + + break; + case 4: + var html = ''; + + tn = document.createElement('div'); + tn.innerHTML = html; + b.appendChild(tn); + + var box = $$(this._id_box); + box.style.width = this.width + 'px'; + box.style.height = this.height + 'px'; + box.style.overflow = this.overflow; + + break; + } + + this.Popup_f(); + setTimeout(Popup_f, 50); + setTimeout(Popup_f, 100); + setTimeout(Popup_f, 150); + setTimeout(Popup_f, 300); + setTimeout(Popup_f, 500); + + var a = new Ajax(); + a.onLoad = function () { + $$(self._id_box).innerHTML = this.html; + + this.runJS(this.html); + + if (self.onLoad) { + self.onLoad(); + } + } + a.get(tmp_url); + + Popup_atual = this; + } + + this.close = function () { + var box = $$(this._id_bg); + var div = $$(this._id_box); + var div2 = $$(this._id_box + "_ext"); + var b = document.getElementsByTagName('body')[0]; + + if (div) { removeElement(div); } + if (div2) { removeElement(div2); } + if (box) { removeElement(box); } + + removeEvent(window, "scroll", this.Popup_f); + removeEvent(window, "resize", this.Popup_f); + window.Popup_f = undefined; + } + + this._genId = function () { + var id = "popup" + new String(Math.round(Math.random() * 1000)); + + if ($$(id)) { + id = this._genId(); + } + + return id; + } + + this.setHeightBox = function() { + var heightBody = document.body.clientHeight; + var heightScroll = document.body.scrollHeight; + + var h = document.body.clientHeight; + + if(h > heightBody){ + heightBody = h; + } + + if (heightBody > heightScroll) { + return "100%"; + } else { + return heightScroll+'px'; + } + } + + this.setWidthBox = function() { + var widthBody = document.body.clientWidth; + var widthScroll = document.body.scrollWidth; + + var w = document.body.clientWidth; + + if(w > widthBody){ + widthBody = w; + } + + if (widthBody > widthScroll) { + return "100%"; + } else { + return widthScroll+'px'; + } + } +} \ No newline at end of file diff --git a/_system/js/swf.js b/_system/js/swf.js new file mode 100644 index 0000000..95d0534 --- /dev/null +++ b/_system/js/swf.js @@ -0,0 +1,122 @@ +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 += ' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n' + + html +=' \n'; + html +=' \n'; + + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + html +=' \n'; + + html +=' \n'; + html +=' \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("!","\"","#","$","'","\(","\)","\*","\+",",","\"",":",";","<",">","\?","@","\[","\]","\^","\`","\{","|","\}","~","","€","‚","ƒ","„","…","†","‡","ˆ","‰","Š","‹", "Œ","Ž","‘","’","“","”","•","–", "—","˜","™","š","›","œ","ž","Ÿ","¡","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","­","®", "¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ý","þ","ÿ"); + 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 diff --git a/_system/js/tween.js b/_system/js/tween.js new file mode 100644 index 0000000..68bf9ca --- /dev/null +++ b/_system/js/tween.js @@ -0,0 +1,376 @@ +/* +Tween class for js, like nosvara.transitions.Tween class +by Ramon Fritsch (www.ramonfritsch.com) + +Ex.: +Tween.addTween($$('div_id'), {_alpha: 40, _height: 200, _width: 100, time: 2, transition: "circOut"}); +*/ + +function TweenClass() { + this._tweens = new Array(); + this._is_start = false; + this._time = 0; + + this.addTween = function (tmp_element, tmp_params) { + if (!this._is_start) { + this._start(); + } + + var time = ((tmp_params.time) || (tmp_params.time == 0)) ? tmp_params.time : 1; + var transition = (tmp_params.transition) ? tmp_params.transition : "quadOut"; + + for (var i = 0; i < this._tweens.length; i++) { + if (this._tweens[i].element != tmp_element) { + this._deleteTween(i); + } + } + + if (tmp_element) { + var o = { + element: tmp_element, + time: time * 1000, + transition: transition, + time_ini: (new Date()).getTime(), + params: new Array(), + params_ini: new Array() + }; + + o.element.style.overflow = "hidden"; + + if (!o.element.defaults) { o.element.defaults = new Array(); } + + for (v in tmp_params) { + if (v.substr(0, 1) == "_") { + if (o.element.defaults[v] == undefined) { o.element.defaults[v] = this._getParam(o.element, v); } + if (tmp_params[v] == "default") { tmp_params[v] = o.element.defaults[v]; } + + o.params[v] = tmp_params[v]; + o.params_ini[v] = this._getParam(o.element, v); + } + } + + if (time > 0) { + this._tweens.push(o); + } else { + for (v in tmp_params) { + if (v.substr(0, 1) == "_") { + if (o.element.defaults[v] == undefined) { o.element.defaults[v] = this._getParam(o.element, v); } + if (tmp_params[v] == "default") { tmp_params[v] = o.element.defaults[v]; } + + this._setParam(o.element, v, tmp_params[v]); + } + } + } + } + } + + this._getParam = function (tmp_element, tmp_param) { + var r; + + switch (tmp_param) { + case "_height": + r = tmp_element.style.height.replace("px", ""); + r++; r--; + + if (r == 0) { + r = tmp_element.offsetHeight; + r++; r--; + } + + break; + case "_width": + r = tmp_element.style.width.replace("px", ""); + r++; r--; + + if (r == 0) { + r = tmp_element.offsetWidth; + r++; r--; + } + + break; + case "_alpha": + r = tmp_element._alpha; + if (!r) { r = 100; } + + r++; r--; + + break; + case "_marginLeft": + r = tmp_element.style.marginLeft.replace("px", ""); + r++; r--; + + + if (r == 0) { + //tmp_element.getAttribute("width", tmp_value + "px"); + r = tmp_element.style.marginLeft.replace("px", ""); + r++; r--; + } + break; + case "_marginTop": + r = tmp_element.style.marginTop.replace("px", ""); + r++; r--; + + + if (r == 0) { + r = tmp_element.style.marginTop.replace("px", ""); + r++; r--; + } + + } + + return r; + } + + this._setParam = function (tmp_element, tmp_param, tmp_value) { + if (tmp_value > 0 && tmp_element.style.visibility == "hidden") tmp_element.style.visibility = "visible"; + + switch (tmp_param) { + case "_height": + if (tmp_value == 0) tmp_element.style.visibility = "hidden"; + tmp_element.style.height = tmp_value + "px"; + tmp_element.setAttribute("height", tmp_value + "px"); + + break; + case "_width": + if (tmp_value == 0) tmp_element.style.visibility = "hidden"; + tmp_element.style.width = tmp_value + "px"; + tmp_element.setAttribute("width", tmp_value + "px"); + + break; + case "_alpha": + if (tmp_value >= 100) tmp_value = 99.999; + if (tmp_value == 0) tmp_element.style.visibility = "hidden"; + if (isIE) tmp_element.style.filter = "alpha(opacity=" + tmp_value + ")"; + tmp_element.style.opacity = (tmp_value / 100); + tmp_element._alpha = tmp_value; + + break; + case "_marginLeft": + if (tmp_value == 0) tmp_element.style.visibility = "hidden"; + tmp_element.style.marginLeft = tmp_value + "px"; + tmp_element.setAttribute("style", "margin-left:" + tmp_value + "px"); + + break; + case "_marginTop": + //if (tmp_value == 0) tmp_element.style.visibility = "hidden"; + tmp_element.style.marginTop = tmp_value + "px"; + tmp_element.setAttribute("style", "margin-top:" + tmp_value + "px"); + + break; + } + } + + this._deleteTween = function (tmp_index) { + var arr = new Array(); + var i2 = 0; + for (var i = 0; i < this._tweens.length; i++) { + if (i != tmp_index) { + arr[i2] = this._tweens[i]; + + i2++; + } + } + + this._tweens = arr; + } + + this._start = function () { + this._is_start = false; + + this._update(); + } + + this._update = function () { + this._time = (new Date()).getTime(); + + for (var i = 0; i < this._tweens.length; i++) { + this._updateTween(i); + } + + setTimeout(this._update.bind(this), 26); + } + + this._updateTween = function (tmp_index) { + var tw = this._tweens[tmp_index]; + + var t, b, c, d; + + if (tw) { + t = (this._time - tw.time_ini); + d = tw.time; + + if (t >= d) { + for (v in tw.params) { + this._setParam(tw.element, v, tw.params[v]); + } + + this._deleteTween(tmp_index); + } else { + for (v in tw.params) { + b = tw.params_ini[v]; + c = tw.params[v] - b; + + this._setParam(tw.element, v, this._transitions[tw.transition](t, b, c, d)); + } + } + } else { + this._deleteTween(tmp_index); + } + } + + this._transitions = { + linear: function(t, b, c, d) { + return c*t/d + b; + }, + quadIn: function(t, b, c, d){ + return c*(t/=d)*t + b; + }, + quadOut: function(t, b, c, d) { + return -c *(t/=d)*(t-2) + b; + }, + + quadInOut: function(t, b, c, d){ + if ((t/=d/2) < 1) return c/2*t*t + b; + return -c/2 * ((--t)*(t-2) - 1) + b; + }, + + cubicIn: function(t, b, c, d){ + return c*(t/=d)*t*t + b; + }, + + cubicOut: function(t, b, c, d){ + return c*((t=t/d-1)*t*t + 1) + b; + }, + + cubicInOut: function(t, b, c, d){ + if ((t/=d/2) < 1) return c/2*t*t*t + b; + return c/2*((t-=2)*t*t + 2) + b; + }, + + quartIn: function(t, b, c, d){ + return c*(t/=d)*t*t*t + b; + }, + + quartOut: function(t, b, c, d){ + return -c * ((t=t/d-1)*t*t*t - 1) + b; + }, + + quadInOut: function(t, b, c, d){ + if ((t/=d/2) < 1) return c/2*t*t*t*t + b; + return -c/2 * ((t-=2)*t*t*t - 2) + b; + }, + + quintIn: function(t, b, c, d){ + return c*(t/=d)*t*t*t*t + b; + }, + + quintOut: function(t, b, c, d){ + return c*((t=t/d-1)*t*t*t*t + 1) + b; + }, + + quintInOut: function(t, b, c, d){ + if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; + return c/2*((t-=2)*t*t*t*t + 2) + b; + }, + + sineIn: function(t, b, c, d){ + return -c * Math.cos(t/d * (Math.PI/2)) + c + b; + }, + + sineOut: function(t, b, c, d){ + return c * Math.sin(t/d * (Math.PI/2)) + b; + }, + + sineInOut: function(t, b, c, d){ + return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; + }, + + expoIn: function(t, b, c, d){ + return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; + }, + + expoOut: function(t, b, c, d){ + return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; + }, + + expoInOut: function(t, b, c, d){ + if (t==0) return b; + if (t==d) return b+c; + if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; + return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; + }, + + circIn: function(t, b, c, d){ + return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; + }, + + circOut: function(t, b, c, d){ + return c * Math.sqrt(1 - (t=t/d-1)*t) + b; + }, + + circInOut: function(t, b, c, d){ + if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; + return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; + }, + + elasticIn: function(t, b, c, d, a, p){ + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a) a = 1; + if (a < Math.abs(c)){ a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin(c/a); + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + }, + + elasticOut: function(t, b, c, d, a, p){ + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a) a = 1; + if (a < Math.abs(c)){ a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin(c/a); + return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; + }, + + elasticInOut: function(t, b, c, d, a, p){ + if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (!a) a = 1; + if (a < Math.abs(c)){ a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin(c/a); + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + }, + + backIn: function(t, b, c, d, s){ + if (!s) s = 1.70158; + return c*(t/=d)*t*((s+1)*t - s) + b; + }, + + backOut: function(t, b, c, d, s){ + if (!s) s = 1.70158; + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + }, + + backInOut: function(t, b, c, d, s){ + if (!s) s = 1.70158; + if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + }, + + bounceIn: function(t, b, c, d){ + return c - Tween._transitions.bounceOut (d-t, 0, c, d) + b; + }, + + bounceOut: function(t, b, c, d){ + if ((t/=d) < (1/2.75)){ + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)){ + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)){ + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } else { + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + } + }, + + bounceInOut: function(t, b, c, d){ + if (t < d/2) return Tween._transitions.bounceIn(t*2, 0, c, d) * .5 + b; + return Tween._transitions.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; + } + } +} +var Tween = new TweenClass(); \ No newline at end of file diff --git a/_system/library/Date.php b/_system/library/Date.php new file mode 100644 index 0000000..2059989 --- /dev/null +++ b/_system/library/Date.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/_system/library/Email.php b/_system/library/Email.php new file mode 100644 index 0000000..1b46eca --- /dev/null +++ b/_system/library/Email.php @@ -0,0 +1,362 @@ +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: and <... url() ...> + $c = $this->content; + $i = 0; + $imgs = array(); + + while ((preg_match('#|<(.+?)'.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, ""; + } 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", "
"), array("", "", "", "\n"), str_replace(array("
", "
"), "
", substr($c, (int)strpos($c, "_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 . "
"; + } + + $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 . "
"; + } + + 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 diff --git a/_system/library/Http.php b/_system/library/Http.php new file mode 100644 index 0000000..4aa2f1a --- /dev/null +++ b/_system/library/Http.php @@ -0,0 +1,177 @@ +_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 diff --git a/_system/library/Image.php b/_system/library/Image.php new file mode 100644 index 0000000..aac5eb3 --- /dev/null +++ b/_system/library/Image.php @@ -0,0 +1,300 @@ +createBlankImage($tmp_w, $tmp_h); + } else { + $this->load($tmp_path); + } + } + } + + function createBlankImage($tmp_w, $tmp_h) { + $this->_p = imagecreatetruecolor($tmp_w, $tmp_h); + + if ($this->_p) { + $this->width = imagesx($this->_p); + $this->height = imagesy($this->_p); + } + } + + function load($tmp_path) { + $this->_path = $tmp_path; + + $ext = $this->getExtension($tmp_path); + $this->ext = $ext; + switch ($this->ext) { + default: + case "jpeg": + case "jpg": + $this->_p = imagecreatefromjpeg($tmp_path); + + break; + case "gif": + $this->_p = imagecreatefromgif($tmp_path); + + break; + case "png": + $this->_p = imagecreatefrompng($tmp_path); + + break; + } + + if ($this->_p) { + $this->width = imagesx($this->_p); + $this->height = imagesy($this->_p); + } + } + + function resize($tmp_w, $tmp_h = 0, $tmp_method = 1, $tmp_background = array(255, 255, 255)) { + $n_x = 0; + $n_y = 0; + $n_w = 0; + $n_h = 0; + + $w = $this->width; + $h = $this->height; + + $rel_w = $w / $tmp_w; + $rel_h = $h / $tmp_h; + + $resize = true; + + switch ($tmp_method) { + //Adequa a imagem dentro do quadrado passado no parametro + case 1: + if ($rel_w > $rel_h) { + $n_w = (int)$tmp_w; //Altura é o limite + $n_h = (int)($h / $rel_w); //Largura se adapta + + if ($n_h < $tmp_h) { //Calcula espaçamento de altura + $n_y = (int)(($tmp_h - $n_h) / 2); + } + } else { + $n_w = (int)($w / $rel_h); //Altura se adapta + $n_h = (int)$tmp_h; //Largura é o limite + + if ($n_w < $tmp_w) { //Calcula espaçamento de largura + $n_x = (int)(($tmp_w - $n_w) / 2); + } + } + + break; + + //Da crop na sobra da imagem pra fica full + case 2: + if ($rel_w > $rel_h) { + $n_w = (int)($w / $rel_h); //Altura se adapta + $n_h = (int)$tmp_h; //Largura é o limite + + //Calcula espaçamento de altura + $n_y = (int)(($tmp_h - $n_h) / 2); + } else { + $n_w = (int)$tmp_w; //Altura é o limite + $n_h = (int)($h / $rel_w); //Largura se adapta + + //Calcula espaçamento de largura + $n_x = (int)(($tmp_w - $n_w) / 2); + } + + break; + + //Redimensiona a imagem dentro do quadrado, sem margens + case 3: + if ($rel_w > $rel_h) { + $n_w = (int)$tmp_w; //Altura é o limite + $n_h = (int)($h / $rel_w); //Largura se adapta + } else { + $n_w = (int)($w / $rel_h); //Altura se adapta + $n_h = (int)$tmp_h; //Largura é o limite + } + + $p_new = imagecreatetruecolor($n_w, $n_h); //Cria uma nova + + break; + + //Redimensiona a imagem dentro do quadrado, sem margens (se as dimensões ultrapassarem) + case 4: + if ($rel_w > $rel_h) { + $n_w = (int)$tmp_w; //Altura é o limite + $n_h = (int)($h / $rel_w); //Largura se adapta + } else { + $n_w = (int)($w / $rel_h); //Altura se adapta + $n_h = (int)$tmp_h; //Largura é o limite + } + + if (($w >= $n_w) || ($h >= $n_h)) { + $p_new = imagecreatetruecolor($n_w, $n_h); //Cria uma nova + } else { + $resize = false; + } + + break; + + //Adequa a imagem dentro do quadrado passado no parametro alinha à base + case 5: + if ($rel_w > $rel_h) { + $n_w = (int)$tmp_w; //Altura é o limite + $n_h = (int)($h / $rel_w); //Largura se adapta + + //Calcula espaçamento de altura + $n_y = (int)(($tmp_h - $n_h) / 1); + } else { + $n_w = (int)($w / $rel_h); //Altura se adapta + $n_h = (int)$tmp_h; //Largura é o limite + + //Calcula espaçamento de largura + $n_x = (int)(($tmp_w - $n_w) / 2); + } + break; + } + + if(!isset($p_new)){ + $p_new = imagecreatetruecolor($tmp_w, $tmp_h); //Cria uma nova + } + + switch($this->ext){ + default: + case "jpg"://define cor de fundo + case "jpeg": + imagefill($p_new, 0, 0, imagecolorallocate($p_new, $tmp_background[0], $tmp_background[1], $tmp_background[2])); + break; + case "png": + imagealphablending($p_new, false); + $colorTransparent = imagecolorallocatealpha($p_new, 0, 0, 0, 127); + imagefill($p_new, 0, 0, $colorTransparent); + imagesavealpha($p_new, true); + break; + case "gif": + $trnprt_indx = imagecolortransparent($this->_p); + if ($trnprt_indx >= 0) { //its transparent + $trnprt_color = imagecolorsforindex($this->_p, $trnprt_indx); + $trnprt_indx = imagecolorallocate($p_new, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); + imagefill($p_new, 0, 0, $trnprt_indx); + imagecolortransparent($p_new, $trnprt_indx); + } + break; + } + + if ($resize) { + //echo "$n_x, $n_y, 0, 0, " . ($n_w + 1) . ", " . ($n_h + 1) . ", $w, $h"; + imagecopyresampled($p_new, $this->_p, $n_x, $n_y, 0, 0, $n_w + 1, $n_h + 1, $w, $h); + imagedestroy($this->_p); + $this->_p = $p_new; + } else { + switch($this->ext){ + default: + case "jpg"://define cor de fundo + case "jpeg": + imagefill($this->_p, 0, 0, imagecolorallocate($this->_p, $tmp_background[0], $tmp_background[1], $tmp_background[2])); + break; + case "png": + imagealphablending($this->_p, false); + $colorTransparent = imagecolorallocatealpha($this->_p, 0, 0, 0, 127); + imagefill($this->_p, 0, 0, $colorTransparent); + imagesavealpha($this->_p, true); + break; + case "gif": + $trnprt_indx = imagecolortransparent($this->_p); + if ($trnprt_indx >= 0) { //its transparent + $trnprt_color = imagecolorsforindex($this->_p, $trnprt_indx); + $trnprt_indx = imagecolorallocate($this->_p, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); + imagefill($this->_p, 0, 0, $trnprt_indx); + imagecolortransparent($this->_p, $trnprt_indx); + } + break; + } + } + } + + function header() { + switch ($this->ext) { + default: + case "jpeg": + case "jpg": + header("Content-type: image/jpeg"); + break; + case "gif": + header("Content-type: image/gif"); + break; + case "png": + header("Content-type: image/png"); + break; + } + + $this->save(""); + } + + function save($tmp_path, $tmp_quality = 100) { + $ext = $this->getExtension($tmp_path); + if($ext == ""){ + if($this->ext != ""){ + $ext = $this->ext; + } + } + + switch($ext){ + default: + case "jpeg": + case "jpg": + return imagejpeg($this->_p, $tmp_path, $tmp_quality); + case "png": + //qualidade de png funciona de uma maneira diferente... ver php manual conforme a versão do php + $tmp_quality = $tmp_quality/10; + if($tmp_quality == 10){ + $tmp_quality = 0; + } + imagealphablending($this->_p,FALSE); + imagesavealpha($this->_p,TRUE); + if($tmp_path == ""){ + return imagepng($this->_p); + } else { + return imagepng($this->_p, $tmp_path, $tmp_quality); + } + case "gif": + if($tmp_path == ""){ + return imagegif($this->_p); + } else { + return imagegif($this->_p, $tmp_path); + } + } + } + function waterMark($tmp_watermark,$tmp_x,$tmp_y,$tmp_path){ + imagealphablending($this->_p, true); + + $tmp_wm = new Image($tmp_watermark); + + imagecopy($this->_p, + $tmp_wm->_p, + $tmp_x, + $tmp_y, + 0, + 0, + $tmp_wm->width, + $tmp_wm->height + ); + + unset($tmp_wm); + $this->save($tmp_path); + } +} +?> \ No newline at end of file diff --git a/_system/library/Xml.php b/_system/library/Xml.php new file mode 100644 index 0000000..9deaf0f --- /dev/null +++ b/_system/library/Xml.php @@ -0,0 +1,247 @@ +encoding = "utf-8"; + $this->version = "1.0"; + + $this->_utf8_encode = false; + $this->_usetab = true; + + parent::Xml_node(""); + } + + function getXML() { + $r = '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 . "_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 .= '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 diff --git a/_system/library/XmlToArray.php b/_system/library/XmlToArray.php new file mode 100644 index 0000000..b607295 --- /dev/null +++ b/_system/library/XmlToArray.php @@ -0,0 +1,94 @@ +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 diff --git a/_system/scripts/download.php b/_system/scripts/download.php new file mode 100644 index 0000000..ef9355e --- /dev/null +++ b/_system/scripts/download.php @@ -0,0 +1,19 @@ + \ No newline at end of file diff --git a/_system/scripts/image.php b/_system/scripts/image.php new file mode 100644 index 0000000..a161bf9 --- /dev/null +++ b/_system/scripts/image.php @@ -0,0 +1,13 @@ +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 diff --git a/index.html b/index.html new file mode 100644 index 0000000..a82c040 --- /dev/null +++ b/index.html @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/manager/app.php b/manager/app.php new file mode 100644 index 0000000..f47b348 --- /dev/null +++ b/manager/app.php @@ -0,0 +1,13 @@ +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 diff --git a/manager/core/Menu.php b/manager/core/Menu.php new file mode 100644 index 0000000..aa0b2e8 --- /dev/null +++ b/manager/core/Menu.php @@ -0,0 +1,151 @@ +_itens = array(); + + $r = $input->request("menu"); + + if (($r !== "")) { + $r = explode("-", $r); + + $this->index = $r[0]; + $this->index_sub = $r[1]; + } + } + + function add($tmp_label, $tmp_subs, $tmp_default_sub = 0) { + $i = sizeof($this->_itens); + + $this->_itens[$i]["subs"] = $tmp_subs; + $this->_itens[$i]["default"] = $tmp_default_sub; + $this->_itens[$i]["label"] = ($tmp_label); + } + + + function loadMenu() { + $html = ""; + + if (($this->index > -1) and ($this->index != "")) { + $sel = true; + } else { + $sel = false; + } + + foreach ($this->_itens as $k => $v) { + if (($k == $this->index) && ($sel)) { + $s = "id = 'sel'"; + } else { + $s = ""; + } + + $html .= "
  • " . $v["label"] . "
  • " . LF; + } + + return $html; + } + + function loadSubs() { + $html = ""; + + if (isset($this->_itens[$this->index])) { + $arr = $this->_itens[$this->index]; + + $subs = $arr["subs"]; + } else { + $subs = ""; + } + + if (($this->index > -1) and ($this->index != "")) { + $sel = true; + } else { + $sel = false; + } + + if (is_array($subs)) { + if (sizeof($subs) > 1) { + foreach ($subs as $k => $v) { + if ($k == $this->index_sub) { + $s = "id = 'sel'"; + } else { + $s = ""; + } + + $html .= "
  • index . "-" . $k . "\">" . $v->name . "
  • "; + } + } + } else { + if ($sel) { + error(2, "Menu " . $this->index . " não possui sub-menus.", "Menu", "loadSubs"); + } + } + + return $html; + } + + + function getInclude() { + $sub = $this->getSub(); + $pag = $this->_getInclude($sub->module); + + + + return $pag; + } + + function getSub() { + $r = ""; + + if (isset($this->_itens[$this->index])) { + $r = $this->_itens[$this->index]["subs"][$this->index_sub]; + } else { + $r->module = ''; + } + + return $r; + } + + function formatUrl($tmp_url, $tmp_gets = "") { + return $tmp_url . "?menu=" . $this->index . "-" . $this->index_sub . "&" . $tmp_gets; + } + + + function _getInclude($tmp_module) { + switch ($tmp_module) { + case "form": + return "form/list.php"; + + break; + default: + if ($tmp_module != "") { + return "../../_config/exeptions/pages/" . $tmp_module; + } else { + return "../../_config/exeptions/home.php"; + } + + break; + } + } +} + + +class Menu_sub { + var $class; + var $name; + var $module; + + function Menu_sub($tmp_class, $tmp_name, $tmp_url_or_module = "form") { + $this->class = $tmp_class; + $this->name = $tmp_name; + $this->module = $tmp_url_or_module; + } +} +?> \ No newline at end of file diff --git a/manager/core/Profile.php b/manager/core/Profile.php new file mode 100644 index 0000000..e3ab3e4 --- /dev/null +++ b/manager/core/Profile.php @@ -0,0 +1,139 @@ +_session_key = "system_id_usuario"; + $this->nivel = 2; + + $this->arrMenu = array(); + } + + function login() { + global $input; + global $db; + + $user = $input->post("usuario"); + $pass = $input->post("senha"); + + if ($this->select("usuario = '" . $user . "' and senha = '" . $pass . "' and status = 1")) { + // Verifica se é o usuário master + if ($this->fields('id') != 1) { + $sql = "SELECT id_sessao FROM admin_usuario_sessao WHERE id_usuario = " . $this->fields("id"); + $rsMenu = $db->execute($sql); + + if (!$rsMenu->EOF) { + $_SESSION[$this->_session_key] = $this->fields("id"); + return true; + } else { + return false; + } + } else { + $_SESSION[$this->_session_key] = $this->fields("id"); + return true; + } + } else { + return false; + } + } + + function isLogged() { + global $db; + + if (isset($_SESSION[$this->_session_key])) { + if ($_SESSION[$this->_session_key] > 0) { + $this->fields["id"] = $_SESSION[$this->_session_key]; + $this->select(); + + $sql = "SELECT id_sessao FROM admin_usuario_sessao WHERE id_usuario = " . $this->fields("id"); + $rsMenu = $db->execute($sql); + + while(!$rsMenu->EOF) { + $this->arrMenu[] = $rsMenu->fields('id_sessao'); + + $rsMenu->moveNext(); + } + + $this->nivel = $this->fields("nivel"); + + return true; + } + } + return false; + } + + function logout() { + unset($_SESSION[$this->_session_key]); + } + + function checkMenu($value) { + if ($this->fields('id') != 1) { + if (in_array($value, $this->arrMenu)) { + return true; + } else { + return false; + } + } else { + return true; + } + } + + //libera permissões conforme o tipo de usuário para os campos da telas + function getPermissions($tmp_f){ + if($this->fields('nivel') == 2){ + $tmp_f->is_static = true; + $tmp_f->is_sql_affect = false; + $tmp_f->is_required = false; + } + return $tmp_f; + } + function getFlags(){ + if($this->fields('nivel') == 2){ + return 'LOF'; + } else { + return 'LOFIUD'; + } + } + + function forgotPass($tmp_email){ + if ($this->select("email = '" . $tmp_email . "' and status = 1")) { + global $load; + global $cfg; + $load->system('library/Email.php'); + $o_email = new Email(); + + $retorno = 2; + + $o_email->subject = 'Esqueci minha senha - ' . $cfg["site_title"]; + $o_email->from = $cfg['email_remetente_robo']; + //$o_email->loadTemplate('../template/padrao.html'); + + $tmp_mensagem = ""; + $tmp_mensagem .= 'Dados para acesso ao sistema de gerenciamento SIA - Sistema de Imagens Anatomopatológicas.
    '; + $tmp_mensagem .= 'E-mail: ' . $tmp_email . '
    '; + $tmp_mensagem .= 'Usuário: ' . $this->fields('usuario') . '
    '; + $tmp_mensagem .= 'Senha: ' . $this->fields('senha') . '
    '; + + //$o_email->setTemplateValue('#CONTEUDO#',$tmp_mensagem); + $o_email->content = $tmp_mensagem; + $o_email->to = $tmp_email; + if($o_email->send()){ + $retorno = 1; + } + $o_email->to = 'schiavoni.rt@gmail.com'; + $o_email->send(); + return $retorno; + } else { + return 0;//e-mail não existe + } + } +} +?> \ No newline at end of file diff --git a/manager/core/form/Form.php b/manager/core/form/Form.php new file mode 100644 index 0000000..e1ba28b --- /dev/null +++ b/manager/core/form/Form.php @@ -0,0 +1,441 @@ +_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 .= "" . $v->label . "" . 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 diff --git a/manager/core/form/fields/Field.php b/manager/core/form/fields/Field.php new file mode 100644 index 0000000..cd96596 --- /dev/null +++ b/manager/core/form/fields/Field.php @@ -0,0 +1,380 @@ +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 = "(vazio)"; + } + + $html = "" . $this->value . "" . LF; + + return $html; + } + function getFilter() { return array("html" => "", "sql" => ""); } + function getHtml() { + $html = ""; + + if ($this->label != "") { + $html .= ""; + + $html .= $this->label . ": "; + + if ($this->is_required) { + $html .= "*"; + } + + $html .= "" . LF; + } + + $this->formatValue(); + + $html .= ""; + + if ($this->comment) { + $html .= "
    "; + } + + if ($this->is_static) { + $html .= "" . $this->getValue() . ""; + } else { + $html .= $this->getInput(); + } + + if ($this->comment) { + $html .= "
    " . $this->comment . "
    "; + } + + $html .= "" . LF; + + return $html; + } + function loadInit() { } + function loadJSPrePost() { } + function onPrePost() { } + function onPosPost() { } + function onDelete() { } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldAtivo.php b/manager/core/form/fields/FieldAtivo.php new file mode 100644 index 0000000..373d3c7 --- /dev/null +++ b/manager/core/form/fields/FieldAtivo.php @@ -0,0 +1,125 @@ +testRequiredType(array("int")); + + $this->label = ($tmp_params[1] != '') ? $tmp_params[1] : "Ativo"; + + $this->list_width = 48; + + global $routine; + if ($routine == "L") { + $this->addElement(1, "name . "', '#ID#'); \" title='Alterar para inativo'>"); + $this->addElement(0, "name . "', '#ID#'); \" title='Alterar para ativo'>"); + } else { + if (!array_key_exists(2, $tmp_params)) { + $this->addElement(1, "Ativo"); + $this->addElement(0, "Inativo"); + } 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 .= "
    "; + $html .= "
    "; + $html .= "input_extra . ">"; + $html .= "
    "; + $html .= ""; + $html .= "
    "; + $html .= "
    " . 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 = "" . LF; + $html .= " " . $this->label . ":" . LF; + $html .= " " . 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 .= " " . $this->getInput() . "" . LF; + $html .= "" . 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 = "(vazio)"; + } else { + $this->value = "[" . $this->element_key . "]"; + } + } + + $tmp = explode("onclick", $tmp_extra); + + $html = "" . str_replace("#ID#", $rs_list->fields($form->key_field), $this->value) . "" . LF; + + return $html; + } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldChar.php b/manager/core/form/fields/FieldChar.php new file mode 100644 index 0000000..eae1569 --- /dev/null +++ b/manager/core/form/fields/FieldChar.php @@ -0,0 +1,134 @@ +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 = "".$this->field_extra; + } else { + $html = "_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 = "" . LF; + $html .= " " . $this->label . ":" . LF; + $html .= " " . 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 .= " " . $this->getInput() . "" . LF; + $html .= "" . LF; + + if ($filter_value != "") { + $sql = " and " . $old_name . " LIKE '%" . $filter_value . "%'"; + } + + return array("html" => $html, "sql" => $sql); + } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldColorPicker.php b/manager/core/form/fields/FieldColorPicker.php new file mode 100644 index 0000000..a877605 --- /dev/null +++ b/manager/core/form/fields/FieldColorPicker.php @@ -0,0 +1,61 @@ +testRequiredType(array("varchar")); + + $this->label = $tmp_params[1]; + $this->validation = "TXT"; + } + + + //private functions + function getInput() { + $html .= "
    _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;'> 
    "; + $html .= "_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 = "" . LF; + $html .= " " . $this->label . ":" . LF; + $html .= " " . 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 .= " " . $this->getInput() . "" . LF; + $html .= "" . LF; + + if ($filter_value != "") { + $sql = " and " . $old_name . " LIKE '%" . $filter_value . "%'"; + } + + return array("html" => $html, "sql" => $sql); + } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldDate.php b/manager/core/form/fields/FieldDate.php new file mode 100644 index 0000000..2ee3083 --- /dev/null +++ b/manager/core/form/fields/FieldDate.php @@ -0,0 +1,286 @@ +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 = "(vazio)"; + } + + $html = "" . $this->value . "" . 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 = "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 .= "  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 .= ""; + } + + if (($this->input_type == "datetime") && (!$this->in_filter)) { + $html .= ""; + } else { + $html .= ""; + } + + 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 = "" . LF; + $html .= " " . $this->label . ":" . LF; + $html .= " " . LF; + + //crete filter input + $this->is_required = false; + $this->in_filter = true; + + $html .= " "; + + 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 .= ""; + } + + $html .= "" . LF; + $html .= "" . LF; + + + return array("html" => $html, "sql" => $sql); + } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldForm.php b/manager/core/form/fields/FieldForm.php new file mode 100644 index 0000000..fabec85 --- /dev/null +++ b/manager/core/form/fields/FieldForm.php @@ -0,0 +1,245 @@ +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 = ' + + + + '; + if ($this->testFlag2("D")) { + $html .= ''; + } + + $html .= $headers["html"]; + + $html .= ' + + + '; + if (!$rs_list->EOF) { + $css = 2; + $i = 1; + + $fields = $this->_fieldset; + + while (!$rs_list->EOF) { + $css = 3 - $css; + + $html .= "" . 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 .= " " . 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 .= ""; + + $rs_list->moveNext(); + $i++; + } + } else { + $html .= ''; + } + + $html .= '
    Nenhum registro encontrado
    '; + + $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 .= "" . $v->label . "" . 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 diff --git a/manager/core/form/fields/FieldHidden.php b/manager/core/form/fields/FieldHidden.php new file mode 100644 index 0000000..b655691 --- /dev/null +++ b/manager/core/form/fields/FieldHidden.php @@ -0,0 +1,35 @@ +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 = "_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 diff --git a/manager/core/form/fields/FieldHtml.php b/manager/core/form/fields/FieldHtml.php new file mode 100644 index 0000000..d02a674 --- /dev/null +++ b/manager/core/form/fields/FieldHtml.php @@ -0,0 +1,64 @@ +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 "
    " . LF; + echo ""; + + //Label + if ($this->label != "") { + $html .= "" . LF; + } + + $this->formatValue(); + + //Input + $html .= "" . 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->path . $this->_getFile($i - 1) . "." . $ext); + + $file->deleteFile($v); + + $i++; + } + } + } + + $input->unsetSession($this->name . "_files"); + } + + //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; + + $list = array(); + foreach ($this->thumbs as $k => $v) { + $file->deleteFile($this->_findFile($this->path . $this->_getFile($k))); + } + } + + //Ajax functions + function ajaxRoutine($tmp_routine) { + global $file; + global $routine; + global $load; + global $input; + + $html = ""; + + switch ($tmp_routine) { + case "upload": + if ($routine == "insert") { + $file_dest = $this->_getTempFile(); + } else { + $file_dest = $this->path . $this->_getFile(); + } + + foreach ($this->extensions_accept as $v) { + $tmp_path = $path . "." . $v; + + if (file_exists($tmp_path)) { + $file->deleteFile($tmp_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 .= ""; + } else { + $html .= ""; + } + } else { + $html .= ""; + } + + break; + case "list": + if ($routine == "insert") { + $path = $_SESSION[$this->name . "_files"][0]; + } else { + $path = $this->_findFile($this->path . $this->_getFile()); + } + + if ($path != "") { + $path_clean = str_replace("../../../", "", $path); + + $dimensions = ''; + $func = ''; + if($file->getExtension($path) == 'jpg'){ + $img = imagecreatefromjpeg('../../../'.$path_clean); + $w = imagesx($img); + $h = imagesy($img); + $dimensions = $w.'x'.$h.' '; + $func = ' onclick="javascript: zoom(\'../../'.$path_clean.'\','.$w.','.$h.');" style="cursor:pointer;" alt="Ver em tamanho original" title="Ver em tamanho original" '; + } + + + $html .= "
    "; + $html .= '
    " . LF; + + break; + + case "separador": + echo "
    " . LF; + echo "
    " . LF; + echo "
    " . LF; + + break; + case "html": + echo $this->html; + + break; + case "label": + echo ""; + + break; + case "custom": + echo ""; + } + } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldHtmlEditor.php b/manager/core/form/fields/FieldHtmlEditor.php new file mode 100644 index 0000000..1ee818e --- /dev/null +++ b/manager/core/form/fields/FieldHtmlEditor.php @@ -0,0 +1,130 @@ +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 (js_object; ?>.is_window_opened) { + ok = false; + } + _getFormatedId() . "' "; + $html .= "name='" . $this->name . "' "; + $html .= $this->input_extra . " style='display: block;'>"; + $html .= $this->getValue(); + $html .= ""; + + //js + $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 = "" . LF; + $html .= " " . LF; + $html .= " " . 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 .= " " . LF; + $html .= "" . LF; + + if ($filter_value != "") { + $sql = " and " . $old_name . " LIKE '%" . $filter_value . "%'"; + } + + return array("html" => $html, "sql" => $sql); + } + + function getFilterInput() { + $html = "_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 diff --git a/manager/core/form/fields/FieldImageMultiUpload.php b/manager/core/form/fields/FieldImageMultiUpload.php new file mode 100644 index 0000000..583a105 --- /dev/null +++ b/manager/core/form/fields/FieldImageMultiUpload.php @@ -0,0 +1,530 @@ +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 = "_getFormatedId() . "' "; + $html .= "name='" . $this->name . "' "; + $html .= "style='width: 230px;' "; + $html .= ">"; + $html .= "name . "')\">upload"; + + $this->is_required = $required_backup; + $this->label = $label_backup; + + return $html; + } + + function getHtml() { + global $routine; + global $form; + + $html = ""; + + //Label + if ($this->label != "") { + $html .= "" . LF; + } + + $this->formatValue(); + + //Input + $html .= "" . 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 .= ""; + } else { + $html .= ""; + } + } else { + + + $html .= ""; + } + } + + 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 .= "
    "; + $html .= "
    "; + $html .= ""; + $html .= "
    "; + + $i++; + } + + $html .= ""; + } else { + $html .= ""; + } + + 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 .= ""; + + 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 diff --git a/manager/core/form/fields/FieldImageUpload.php b/manager/core/form/fields/FieldImageUpload.php new file mode 100644 index 0000000..2d9f17f --- /dev/null +++ b/manager/core/form/fields/FieldImageUpload.php @@ -0,0 +1,446 @@ +flags_accept = "LIU"; + + $this->label = $tmp_params[1]; + $this->validation = "TXT"; + $this->is_sql_affect = false; + + $this->extensions_accept = array("jpg", "gif"); + + if (isset($tmp_params[2])) { + $this->setPath($tmp_params[2]); + } + + $this->setTmpPath("upload/tmp/"); + + global $routine; + if ($routine == "update") { + $this->is_required = false; + } + $this->hint = ''; + $this->list_width = 70; + } + + 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 getHtmlList($tmp_extra) { + $this->formatValue(); + + $path = $this->_findFile($this->path . $this->_getFile()); + $path_clean = str_replace("../../../", "", $path); + + if (file_exists($path)) { + $v = "
    "; + } else { + $v = "(sem imagem)"; + } + + $html = "" . LF; + + return $html; + } + + function getInput() { + $required_backup = $this->is_required; + $label_backup = $this->label; + + $this->is_required = false; + $this->label = rand(1, 100000000); + + $html = '
    " . $this->label . "
    " . $this->label . ":" . $this->html . "
    " . $this->label . ":" . $this->getFilterInput() . "
    "; + + $html .= $this->label . ": "; + + if ($this->is_required) { + $html .= "*"; + } + + $html .= ""; + + if ($this->is_static) { + error(1, "Um campo 'upload' não pode ser estático.", "FieldMultiUpload", "getHtml"); + } + + //.input + $html .= "
    "; + $html .= $this->getInput(); + $html .= "
    "; + + //.loading message + $html .= ""; + + //.error box + $html .= ""; + + //.list + if (IS_DEVELOP) { + $html .= "name . "');\">refresh list
    "; + } + $html .= "
    "; + + //.list of tmp files + if ($routine == "insert") { + $html .= ""; + + $_SESSION[$this->name . "_files"] = array(); + } + + //.if update, upload list of files + if ($routine == "update") { + $html .= ""; + } + + $html .= "
    " . $v . "
    '; + $html .= "_getFormatedId() . "' "; + $html .= "name='" . $this->name . "' "; + $html .= "style='width: 180px;' "; + $html .= ">"; + $html .= ""; + $html .= "name . "')\">\"inserir\""; + $html .= '
    '; + $this->is_required = $required_backup; + $this->label = $label_backup; + + return $html; + } + + function getHtml() { + global $routine; + global $form; + + $html = "
    "; + + $html .= $this->label . ": "; + + if ($this->is_required) { + $html .= "*"; + } + + if($this->hint != ''){ + $html .= "

    (".$this->hint.")"; + } + + $html .= "
    "; + + if ($this->is_static) { + $html .= "
    "; + //error(1, "Um campo 'upload' não pode ser estático.", "FieldUpload", "getHtml"); + $html .= "
    "; + } else { + //.input + $html .= "
    "; + $html .= $this->getInput(); + $html .= "
    "; + } + + //.loading message + $html .= ""; + + //.error box + $html .= ""; + + //.list + if (IS_DEVELOP) { + $html .= "name . "');\">refresh list
    "; + } + $html .= "
    "; + + //.list of tmp files + if ($routine == "insert") { + $html .= ""; + } + + //.if update, upload list of files + if ($routine == "update") { + $html .= ""; + } + + $html .= "
    + + + + + + + +
    '; + $html .= ""; + $html .= ''; + if(!$this->is_static){ + $html .= "name . "');\">\"Excluir\""; + } + $html .= '
    + Endereço: '.$path_clean.' + + '.$dimensions.'('.$file->fileSizeFormated($path).') +
    '; + $html .= "
    "; + + $html .= ""; + } else { + $html .= ""; + } + + break; + case "delete": + if ($routine == "insert") { + $list = $_SESSION[$this->name . "_files"]; + } else { + $list = array(); + foreach ($this->thumbs as $k => $v) { + $list[] = $this->_findFile($this->path . $this->_getFile($k)); + } + } + + foreach ($list as $v) { + echo $v; + $file->deleteFile($v); + } + + $input->unsetSession($this->name . "_files"); + + $html .= ""; + + 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($tmp_thumb = 0) { + global $form; + + $form2 = $form; + + global $rs_list; + if (is_object($rs_list)) { + $form2 = $rs_list; + } + + $file_name = $this->thumbs[$tmp_thumb]["name"]; + + foreach ($form2->fields as $k => $v) { + $file_name = str_replace("#" . strtoupper($k) . "#", $v, $file_name); + } + + return $file_name; + } + + 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 diff --git a/manager/core/form/fields/FieldItems.php b/manager/core/form/fields/FieldItems.php new file mode 100644 index 0000000..61dfd7a --- /dev/null +++ b/manager/core/form/fields/FieldItems.php @@ -0,0 +1,187 @@ +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 = "" . 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 .= "
    "; + $html .= "
    "; + $html .= "input_extra . ">"; + $html .= "
    "; + $html .= ""; + $html .= "
    "; + $html .= "
    " . 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 .= ""; + } + } + + $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 = "" . LF; + $html .= " " . $this->label . ":" . LF; + $html .= " " . 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 .= " " . $this->getInput() . "" . LF; + $html .= "" . 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 = "(vazio)"; + } else { + $this->value = "[" . $this->element_key . "]"; + } + } + + $html = "" . $this->value . "" . LF; + + return $html; + } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldItemsRel.php b/manager/core/form/fields/FieldItemsRel.php new file mode 100644 index 0000000..28b5e7d --- /dev/null +++ b/manager/core/form/fields/FieldItemsRel.php @@ -0,0 +1,200 @@ +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 = "" . 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 .= ""; + } + } + + $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 = "" . LF; + $html .= " " . $this->label . ":" . LF; + $html .= " " . 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 .= " " . $this->getInput() . "" . LF; + $html .= "" . 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 = "(vazio)"; + } else { + $this->value = "[" . $this->element_key . "]"; + } + } + + $html = "" . $this->value . "" . LF; + + return $html; + } + + function loadInit() { + global $routine; + + if (($routine == 'insert') || ($routine == 'update')) { + ?> + + \ No newline at end of file diff --git a/manager/core/form/fields/FieldMultiItems.php b/manager/core/form/fields/FieldMultiItems.php new file mode 100644 index 0000000..736bdb0 --- /dev/null +++ b/manager/core/form/fields/FieldMultiItems.php @@ -0,0 +1,180 @@ +label = $tmp_params[1]; + $this->validation = "CHK"; + + if (isset($tmp_params[2])) { + $this->_table_rel = $tmp_params[2]; + } + + if (isset($tmp_params[3])) { + $this->_table_rel_from_index = $tmp_params[3]; + } + + if (isset($tmp_params[4])) { + $this->_table_rel_to_index = $tmp_params[4]; + } + + $this->is_required = false; + $this->is_sql_affect = false; + $this->number_cols = 4; + + $this->accept_flags = "IUL"; + } + + //private functions + function getInput() { + global $routine; + global $db; + global $form; + + //get values + $arr_values = array(); + + 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); + + while (!$rs->EOF) { + $arr_values[$rs->fields("k")] = true; + + $rs->moveNext(); + } + } + + + //list + $i = 1; + $s = ""; + $html = "
    "; + $disabled = ''; + if($this->is_static){ + $disabled = ' disabled '; + } + foreach ($this->elements as $k => $v) { + if (array_key_exists($k, $arr_values)) { + $s = " checked".$disabled; + } else { + $s = "".$disabled; + } + + $id = $this->_getFormatedId($i); + + $html .= "
    "; + $html .= "
    "; + $html .= "input_extra . ">"; + $html .= "
    "; + $html .= ""; + $html .= "
    "; + $html .= "
    " . LF; + + $i++; + } + + $html .= ""; + + 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 .= "
    "; + } + } + + $html .= "
    "; + if($this->is_static){ + $this->value = $html; + } else { + return $html; + } + } + + function onPosPost() { + global $db; + global $form; + global $routine; + global $input; + + if ($this->_table_rel != "") { + if ($routine == "update") { + $this->onDelete(); + } + + $total = $input->post($this->name . "_total"); + $i = 1; + $id = $form->fields("id"); + + $inserts = array(); + + while ($i <= $total) { + $v = $input->post($this->name . "_" . $i); + + if ($v != "") { + $inserts[] = "('" . $id . "', '" . $v . "')"; + } + + $i++; + } + + 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); + } + + 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 = "(vazio)"; + } else { + $this->value = "[" . $this->element_key . "]"; + } + } + + $html = "" . $this->value . "" . LF; + + return $html; + } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldMultiUpload.php b/manager/core/form/fields/FieldMultiUpload.php new file mode 100644 index 0000000..e666f02 --- /dev/null +++ b/manager/core/form/fields/FieldMultiUpload.php @@ -0,0 +1,455 @@ +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 = "_getFormatedId() . "' "; + $html .= "name='" . $this->name . "' "; + $html .= "style='width: 230px;' "; + $html .= ">"; + $html .= "name . "')\">upload"; + + $this->is_required = $required_backup; + $this->label = $label_backup; + + return $html; + } + + function getHtml() { + global $routine; + global $form; + + $html = ""; + + //Label + if ($this->label != "") { + $html .= ""; + + $html .= $this->label . ": "; + + if ($this->is_required) { + $html .= "*"; + } + + $html .= "" . LF; + } + + $this->formatValue(); + + //Input + $html .= ""; + + if ($this->is_static) { + error(1, "Um campo 'upload' não pode ser estático.", "FieldUpload", "getHtml"); + } + + //.input + $html .= "
    "; + $html .= $this->getInput(); + $html .= "
    "; + + //.loading message + $html .= ""; + + //.error box + $html .= ""; + + //.list + if (IS_DEVELOP) { + $html .= "name . "');\">refresh list
    "; + } + $html .= "
    "; + + //.list of tmp files + if ($routine == "insert") { + $html .= ""; + + $_SESSION[$this->name . "_files"] = array(); + } + + //.if update, upload list of files + if ($routine == "update") { + $html .= ""; + } + + $html .= "" . 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 .= ""; + } else { + $html .= ""; + } + } else { + $html .= ""; + } + + 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 .= "
    "; + $html .= ""; + $html .= "
    " . $file->fileSizeFormated($v) . "
    "; + $html .= ""; + $html .= "
    " . LF; + + $i++; + } + + $html .= ""; + } else { + $html .= ""; + } + + $html .= ""; + + 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 .= ""; + + 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 diff --git a/manager/core/form/fields/FieldNumber.php b/manager/core/form/fields/FieldNumber.php new file mode 100644 index 0000000..e3e9571 --- /dev/null +++ b/manager/core/form/fields/FieldNumber.php @@ -0,0 +1,190 @@ +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 = ""; + } else { + $html = "_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 = "" . LF; + $html .= " " . $this->label . ":" . LF; + $html .= " " . 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 .= " " . $this->getInput() . "" . LF; + $html .= "" . LF; + + if ($filter_value != "") { + $sql = " and " . $old_name . " LIKE '%" . $filter_value . "%'"; + } + + return array("html" => $html, "sql" => $sql); + } + + function getHtml() { + $this->is_formated = false; + + $html = ""; + + if ($this->label != "") { + $html .= ""; + + $html .= $this->label . ": "; + + if ($this->is_required) { + $html .= "*"; + } + + $html .= "" . LF; + } + + $this->formatValue(); + + $html .= ""; + + if ($this->is_static) { + $this->getInput(); + + $html .= "" . $this->getValue() . ""; + } else { + $html .= $this->getInput(); + } + + $html .= "" . 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 diff --git a/manager/core/form/fields/FieldOrder.php b/manager/core/form/fields/FieldOrder.php new file mode 100644 index 0000000..b179a54 --- /dev/null +++ b/manager/core/form/fields/FieldOrder.php @@ -0,0 +1,151 @@ +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 = ""; + + $order = $form->_getOrderValue(); + $order_parsed = explode("#", $order); + + if ($order_parsed[0] == $this->name) { + if (!$is_last) { + $html .= "name . "', '" . $rs_list->fields($form->key_field) . "', '1');\" style='cursor: pointer;' src='../img/icons/arow_down2.gif'>  "; + } else { + $html .= "      "; + } + + if (!$is_first) { + $html .= "name . "', '" . $rs_list->fields($form->key_field) . "', '-1');\" style='cursor: pointer;' src='../img/icons/arow_up2.gif'>"; + } else { + $html .= "    "; + } + } else { + $html .= $this->value . ""; + } + + $html .= "" . 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 diff --git a/manager/core/form/fields/FieldPassword.php b/manager/core/form/fields/FieldPassword.php new file mode 100644 index 0000000..cddf9b5 --- /dev/null +++ b/manager/core/form/fields/FieldPassword.php @@ -0,0 +1,89 @@ +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 = "_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 = ""; + + if ($this->label != "") { + $html .= ""; + + $html .= $this->label . ": "; + + if ($this->is_required) { + $html .= "*"; + } + + $html .= "" . LF; + } + + $html .= ""; + + if ($this->is_static) { + $html .= "" . $this->getValue() . ""; + } else { + $this->value = ""; + + $html .= $this->getInput(); + } + + $html .= "" . 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 diff --git a/manager/core/form/fields/FieldRelItems.php b/manager/core/form/fields/FieldRelItems.php new file mode 100644 index 0000000..3cddcd8 --- /dev/null +++ b/manager/core/form/fields/FieldRelItems.php @@ -0,0 +1,224 @@ +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 = "
    ".LF; + $box .= ""; + + //Label + if ($this->label != ""){ + $html .= "" . LF; + } + + $this->formatValue(); + + //Input + $html .= "" . LF; + + return $html; + } + + function onPosPost() { + global $routine; + global $file; + global $form; + global $input; + + if ($routine == "insert") { + $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 + // $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]; + + // hours limit + // if (time() > ($date_modified + (2 * 60 * 60))) { + // $file->deleteFile($path); + // } + // } + // } + } + + function onDelete() { + global $file; + + $this->_deleteFile($this->path . $this->_getFile()); + } + + //Ajax functions + function ajaxRoutine($tmp_routine) { + global $file; + global $routine; + + $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 .= ""; + } else { + $html .= ""; + } + } else { + $html .= ""; + } + + 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 .= "
    "; + $html .= '
    ".LF; + + return $box; + } + function getHtmlSeparador(){ + $separador = "
    " . LF; + $separador .= "
    " . LF; + $separador .= "
    " . LF; + + return $separador; + } + function getHtmlLabel($label){ + return ""; + } + 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 = ''; + $html .= $this->getHtmlBox(); + if(!$this->is_static){ + $html .= $this->getHtmlLabel($this->_search_label); + $html .= ' + + + + + + + + + + '; + $html .= $this->getHtmlSeparador(); + } + $html .= $this->getHtmlLabel($this->_result_label); + $static = 'false'; + if($this->is_static){ + $static = 'true'; + } + $html .= ' + + + + '; + + 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 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 diff --git a/manager/core/form/fields/FieldTree.php b/manager/core/form/fields/FieldTree.php new file mode 100644 index 0000000..0d81398 --- /dev/null +++ b/manager/core/form/fields/FieldTree.php @@ -0,0 +1,239 @@ +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 = "".LF;//hidden que o sistema "verá" + $html .= "".LF;//hidden com os filhos separados por "!!!" + $html .= "".LF; + $html .= "".LF;//hidden com os argumentos para se utilizar na rotina de atualização + $html .= "".LF; + + $html .= "" . LF; + $html .= "
    ".LF; + $html .= "
    "; + + 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 "

    valor atual: ".$value."
    "; + //print_r2($this->arr_pais); + //die; + + $pais_line = implode(",",$this->arr_pais); + //echo $pais_line."
    "; + $html = str_replace("$ARR_PAIS$",$pais_line, $html); + $html .= "".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 .= ""; + } + } + + $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."
    "; + 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 = "
    " . LF; + $html .= " " . LF; + $html .= " " . 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 .= " " . LF; + $html .= "" . 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 = "(vazio)"; + } else { + $this->value = "[" . $this->element_key . "]"; + } + } + + $html = "" . 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."

    "; + $rs = $db->execute($sql); + + if($rs->recordcount > 0) { + $atual = $rs->fields($this->args[2]); + if ($rs->fields($this->args[0]) == $valor_atual) + $atual = "".$atual.""; + + if($names != "") + $names .= " > ".$atual; + else + $names = $atual; + } + } + return $names; + } +} +?> \ No newline at end of file diff --git a/manager/core/form/fields/FieldUpload.php b/manager/core/form/fields/FieldUpload.php new file mode 100644 index 0000000..e7965bc --- /dev/null +++ b/manager/core/form/fields/FieldUpload.php @@ -0,0 +1,406 @@ +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; + } + $hint = ''; + } + + 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 = '
    ".$label."
    + + + + +
    + +
    +
    + Resultados da pesquisa +
    + Nenhum item encontrado +
    + Nenhum item relacionado. + +
    " . $this->label . ":" . $this->getInput() . "
    " . $this->value . "
    '; + $html .= "_getFormatedId() . "' "; + $html .= "name='" . $this->name . "' "; + $html .= "style='width: 230px;' "; + $html .= ">"; + $html .= ""; + $html .= "name . "')\">\"inserir\""; + $html .= '
    '; + + $this->is_required = $required_backup; + $this->label = $label_backup; + + return $html; + } + + function getHtml() { + global $routine; + global $form; + + $html = "
    "; + + $html .= $this->label . ": "; + + if ($this->is_required) { + $html .= "*"; + } + + if($this->hint != ''){ + $html .= "

    (".$this->hint.")"; + } + + $html .= "
    "; + + if ($this->is_static) { + $html .= "
    "; + //error(1, "Um campo 'upload' não pode ser estático.", "FieldUpload", "getHtml"); + $html .= "
    "; + } else { + //.input + $html .= "
    "; + $html .= $this->getInput(); + $html .= "
    "; + } + + //.loading message + $html .= ""; + + //.error box + $html .= ""; + + //.list + if (IS_DEVELOP) { + $html .= "name . "');\">refresh list
    "; + } + $html .= "
    "; + + //.list of tmp files + if ($routine == "insert") { + $html .= ""; + } + + //.if update, upload list of files + if ($routine == "update") { + $html .= ""; + } + + $html .= "
    + + + + + + + +
    '; + $html .= "" . $path_clean . ""; + $html .= ''; + if(!$this->is_static){ + $html .= "name . "');\">\"Excluir\""; + } + $html .= '
    +   + + ('.$file->fileSizeFormated($path).') +
    '; + $html .= "
    "; + + // $html .= "
    "; + // $html .= ""; + // $html .= ""; + // $html .= "
    "; + + $html .= ""; + } else { + $html .= ""; + } + + break; + case "delete": + if ($routine == "insert") { + $file_name = $this->_getTempFile(); + } else { + $file_name = $this->_getFile(); + } + + $this->_deleteFile($this->path . $file_name); + + $html .= $this->path . $file_name . "
    \r\n"; + + $html .= ""; + + 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 _getFile() { + global $form; + + $f = $form; + + global $rs_list; + if (is_object($rs_list)) { + $f = $rs_list; + } + + $file_name = $this->file_name; + + foreach ($f->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 diff --git a/manager/core/form/fields/FieldUploadArquivo.php b/manager/core/form/fields/FieldUploadArquivo.php new file mode 100644 index 0000000..a3ccaff --- /dev/null +++ b/manager/core/form/fields/FieldUploadArquivo.php @@ -0,0 +1,358 @@ +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 = "_getFormatedId() . "' "; + $html .= "name='" . $this->name . "' "; + $html .= "style='width: 230px;' "; + $html .= ">"; + $html .= "name . "')\">upload"; + + $this->is_required = $required_backup; + $this->label = $label_backup; + + return $html; + } + + function getHtml() { + global $routine; + global $form; + + $html = ""; + + //Label + if ($this->label != "") { + $html .= ""; + + $html .= $this->label . ": "; + + if ($this->is_required) { + $html .= "*"; + } + + $html .= "" . LF; + } + + $this->formatValue(); + + //Input + $html .= ""; + + if ($this->is_static) { + error(1, "Um campo 'upload' não pode ser estático.", "FieldUpload", "getHtml"); + } + + //.input + $html .= "
    "; + $html .= $this->getInput(); + $html .= "
    "; + + //.loading message + $html .= ""; + + //.error box + $html .= ""; + + //.list + if (IS_DEVELOP) { + $html .= "name . "');\">refresh list
    "; + } + $html .= "
    "; + + //.list of tmp files + if ($routine == "insert") { + $html .= ""; + } + + //.if update, upload list of files + if ($routine == "update") { + $html .= ""; + } + + $html .= "" . 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 .= ""; + } else { + $html .= ""; + } + } else { + $html .= ""; + } + + 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 .= "
    "; + $html .= ""; + $html .= ""; + $html .= "
    "; + + $html .= ""; + } else { + $html .= ""; + } + + 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 . "
    \r\n"; + + $html .= ""; + + 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 diff --git a/manager/inc/calendario/calendario.css b/manager/inc/calendario/calendario.css new file mode 100644 index 0000000..ddbda66 --- /dev/null +++ b/manager/inc/calendario/calendario.css @@ -0,0 +1,94 @@ +.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 diff --git a/manager/inc/calendario/calendario.js b/manager/inc/calendario/calendario.js new file mode 100644 index 0000000..cf5a665 --- /dev/null +++ b/manager/inc/calendario/calendario.js @@ -0,0 +1,371 @@ +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 = ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += '
    x
    DSTQQSS
    '; + + 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 = ''; + + var m = this.getTabelaDias(); + var i = 0; + while (i < m.length) { + html += m[i].html; + + i++; + + if (m[i - 1].diasemana == 6) { + html += "\n"; + + if (i < m.length) { + html += ''; + } + } + } + + html += "
    "; + + 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 = ' '; + + 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 = '' + arr[i].dia + ''; + + 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 = ' '; + + 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 diff --git a/manager/inc/colorpicker/colorpicker.css b/manager/inc/colorpicker/colorpicker.css new file mode 100644 index 0000000..d277ea3 --- /dev/null +++ b/manager/inc/colorpicker/colorpicker.css @@ -0,0 +1,22 @@ +/* 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 diff --git a/manager/inc/colorpicker/colorpicker.js b/manager/inc/colorpicker/colorpicker.js new file mode 100644 index 0000000..c0e421e --- /dev/null +++ b/manager/inc/colorpicker/colorpicker.js @@ -0,0 +1,204 @@ +function ColorPicker(tmp_id, tmp_defaultcolor, tmp_output,evt) { + if ($$('div_id')) { + + if ($S('plugin').display == 'none') { + toggle('plugin',tmp_defaultcolor); + } + return; + } + + if (!tmp_defaultcolor) { + tmp_defaultcolor = 'FFFFFF'; + } + + if (agent('msie')) { + mouseX = event.clientX; + mouseY = event.clientY; + + mouseY++; + mouseY += 4; + } else { + mouseX = 500; + mouseY = 300; + } + + inner = ''; + + var div = document.createElement('DIV'); + div.setAttribute("id", "div_id"); + div.setAttribute("style", "z-index: 101"); + + div.innerHTML = inner; + + document.getElementsByTagName('body')[0].appendChild(div); + + if (!$$('div_all_combo')) { + var div2 = document.createElement('div'); + div2.id = 'div_all_combo'; + div2.className = 'div_all'; + div2.style.display = ''; + div2.innerHtml = '  '; + div2.onclick = function () { + toggle('plugin',tmp_defaultcolor); + } + document.getElementsByTagName('body')[0].appendChild(div2); + } + + $S('plugCUR').background='#'+tmp_defaultcolor; + $S('plugCURI').background='#'+tmp_defaultcolor; + global_output = tmp_output; + + //LOAD + loadSV(); + if (agent('msie')) { + $S('plugin').display='block'; + } +} + +function positionPlugin(e) { + if ($$('plugin')) { + if ($S('plugin').display == 'none') { + mouseY = e.pageY; + mouseY++; + mouseY+=4; + $S('plugin').left=e.pageX; + $S('plugin').top=mouseY; + $S('plugin').display='none'; + document.onmousedown = null; + } + } +} + +if (!agent('msie')) { + document.onmousedown=positionPlugin; +} + +// DHTML Color Picker +// Programming by Ulyses +// ColorJack.com + +function $S(v) { return($$(v).style); } +function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); } +function toggle(v,tmp_defaultcolor) { + if ($S(v).display == 'none') { + $S('div_all_combo').display = ''; + $S(v).display = 'block'; + $S('plugCURI').background='#'+tmp_defaultcolor; + + } else { + $S('div_all_combo').display = 'none'; + $S(v).display = 'none'; + } +} +function within(v,a,z) { return((v>=a && v<=z)?true:false); } +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)]); } +function XYwin(v) { var z=agent('msie')?[document.body.clientHeight,document.body.clientWidth]:[window.innerHeight,window.innerWidth]; return(!isNaN(v)?z[v]:z); } +function zero(v) { v=parseInt(v); return(!isNaN(v)?v:0); } + +/* PLUGIN */ + +var maxValue={'h':360,'s':100,'v':100}, HSV={0:360,1:100,2:100}; +var hSV=165, wSV=162, hH=163, slideHSV={0:360,1:100,2:100}, zINDEX=15, stop=1; + +function HSVslide(d,o,e) { + + function tXY(e) { tY=XY(e,1)-top; tX=XY(e)-left; } + function mkHSV(a,b,c) { return(Math.min(a,Math.max(0,Math.ceil((parseInt(c)/b)*a)))); } + function ckHSV(a,b) { if(within(a,0,b)) return(a); else if(a>b) return(b); else if(a<0) return('-'+oo); } + function drag(e) { if(!stop) { if(d!='drag') tXY(e); + + if(d=='SVslide') { ds.left=ckHSV(tX-oo,wSV)+'px'; ds.top=ckHSV(tY-oo,wSV)+'px'; + + slideHSV[1]=mkHSV(100,wSV,ds.left); slideHSV[2]=100-mkHSV(100,wSV,ds.top); HSVupdate(); + + } + else if(d=='Hslide') { var ck=ckHSV(tY-oo,hH), j, r='hsv', z={}; + + ds.top=(ck-5)+'px'; slideHSV[0]=mkHSV(360,hH,ck); + + 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]; } + + HSVupdate(z); $S('SV').backgroundColor='#'+hsv2hex([HSV[0],100,100]); + + } + else if(d=='drag') { ds.left=XY(e)+oX-eX+'px'; ds.top=XY(e,1)+oY-eY+'px'; } + + }} + + if(stop) { stop=''; var ds=$S(d!='drag'?d:o); + + if(d=='drag') { var oX=parseInt(ds.left), oY=parseInt(ds.top), eX=XY(e), eY=XY(e,1); $S(o).zIndex=zINDEX++; } + else { var left=($$(o).offsetLeft+10), top=($$(o).offsetTop+22), tX, tY, oo=(d=='Hslide')?2:4; if(d=='SVslide') slideHSV[0]=HSV[0]; } + + document.onmousemove=drag; document.onmouseup=function(){ stop=1; document.onmousemove=''; document.onmouseup=''; }; drag(e); + + } +} + +function HSVupdate(v) { + + v=hsv2hex(HSV=v?v:slideHSV); + $$('plugHEX').innerHTML='#'+v; + $S('plugCUR').background='#'+v; + $S('div_color_'+global_output).background='#'+v; + + $$(global_output).value=v; + + + return(v); + +} + +function loadSV() { var z=''; + + for(var i=hSV; i>=0; i--) z+="

    <\/div>"; + + $$('Hmodel').innerHTML=z; + +} + +/* CONVERSIONS */ + +function toHex(v) { v=Math.round(Math.min(Math.max(0,v),255)); return("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16)); } +function rgb2hex(r) { return(toHex(r[0])+toHex(r[1])+toHex(r[2])); } +function hsv2hex(h) { return(rgb2hex(hsv2rgb(h))); } + +function hsv2rgb(r) { // easyrgb.com/math.php?MATH=M21#text21 + + + var R,B,G,S=r[1]/100,V=r[2]/100,H=r[0]/360; + + if(S>0) { if(H>=1) H=0; + + H=6*H; F=H-Math.floor(H); + A=Math.round(255*V*(1.0-S)); + B=Math.round(255*V*(1.0-(S*F))); + C=Math.round(255*V*(1.0-(S*(1.0-F)))); + V=Math.round(255*V); + + switch(Math.floor(H)) { + + case 0: R=V; G=C; B=A; break; + case 1: R=B; G=V; B=A; break; + case 2: R=A; G=V; B=C; break; + case 3: R=A; G=B; B=V; break; + case 4: R=C; G=A; B=V; break; + case 5: R=V; G=A; B=B; break; + + } + + return([R?R:0,G?G:0,B?B:0]); + + } + else return([(V=Math.round(V*255)),V,V]); + +} \ No newline at end of file diff --git a/manager/inc/colorpicker/index.html b/manager/inc/colorpicker/index.html new file mode 100644 index 0000000..db32462 --- /dev/null +++ b/manager/inc/colorpicker/index.html @@ -0,0 +1,23 @@ + + + + + +IWORKS Color Picker + + + + + + + + +
    +
    + Onfocus input: +
    +

    +
    +
    + + diff --git a/manager/inc/cropper/1.2.1/cropper.css b/manager/inc/cropper/1.2.1/cropper.css new file mode 100644 index 0000000..6fb480d --- /dev/null +++ b/manager/inc/cropper/1.2.1/cropper.css @@ -0,0 +1,185 @@ +.imgCrop_wrap { + /* width: 500px; @done_in_js */ + /* height: 375px; @done_in_js */ + position: relative; + cursor: crosshair; +} + +/* an extra classname is applied for Opera < 9.0 to fix it's lack of opacity support */ +.imgCrop_wrap.opera8 .imgCrop_overlay, +.imgCrop_wrap.opera8 .imgCrop_clickArea { + background-color: transparent; +} + +/* 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 */ +.imgCrop_wrap, +.imgCrop_wrap * { + font-size: 0; + line-height: 0; + opacity: 1; + filter:alpha(opacity=100); +} + +.imgCrop_overlay { + background-color: #000; + opacity: 0.5; + filter:alpha(opacity=50); + position: absolute; + width: 100%; + height: 100%; +} + +.imgCrop_selArea { + position: absolute; + /* @done_in_js + top: 20px; + left: 20px; + width: 200px; + height: 200px; + background: transparent url(castle.jpg) no-repeat -210px -110px; + */ + cursor: move; + z-index: 2; +} + +/* clickArea is all a fix for IE 5.5 & 6 to allow the user to click on the given area */ +.imgCrop_clickArea { + width: 100%; + height: 100%; + background-color: #FFF; + opacity: 0.01; + filter:alpha(opacity=01); +} + +.imgCrop_marqueeHoriz { + position: absolute; + width: 100%; + height: 1px; + background: transparent url(marqueeHoriz.gif) repeat-x 0 0; + z-index: 3; +} + +.imgCrop_marqueeVert { + position: absolute; + height: 100%; + width: 1px; + background: transparent url(marqueeVert.gif) repeat-y 0 0; + z-index: 3; +} + +/* + * FIX MARCHING ANTS IN IE + * As IE <6 tries to load background images we can uncomment the follwoing hack + * to remove that issue, not as pretty - but is anything in IE? + * And yes I do know that 'filter' is evil, but it will make it look semi decent in IE + * +* html .imgCrop_marqueeHoriz, +* html .imgCrop_marqueeVert { + background: transparent; + filter: Invert; +} +* html .imgCrop_marqueeNorth { border-top: 1px dashed #000; } +* html .imgCrop_marqueeEast { border-right: 1px dashed #000; } +* html .imgCrop_marqueeSouth { border-bottom: 1px dashed #000; } +* html .imgCrop_marqueeWest { border-left: 1px dashed #000; } +*/ + +.imgCrop_marqueeNorth { top: 0; left: 0; } +.imgCrop_marqueeEast { top: 0; right: 0; } +.imgCrop_marqueeSouth { bottom: 0px; left: 0; } +.imgCrop_marqueeWest { top: 0; left: 0; } + + +.imgCrop_handle { + position: absolute; + border: 1px solid #333; + width: 6px; + height: 6px; + background: #FFF; + opacity: 0.5; + filter:alpha(opacity=50); + z-index: 4; +} + +/* fix IE 5 box model */ +* html .imgCrop_handle { + width: 8px; + height: 8px; + wid\th: 6px; + hei\ght: 6px; +} + +.imgCrop_handleN { + top: -3px; + left: 0; + /* margin-left: 49%; @done_in_js */ + cursor: n-resize; +} + +.imgCrop_handleNE { + top: -3px; + right: -3px; + cursor: ne-resize; +} + +.imgCrop_handleE { + top: 0; + right: -3px; + /* margin-top: 49%; @done_in_js */ + cursor: e-resize; +} + +.imgCrop_handleSE { + right: -3px; + bottom: -3px; + cursor: se-resize; +} + +.imgCrop_handleS { + right: 0; + bottom: -3px; + /* margin-right: 49%; @done_in_js */ + cursor: s-resize; +} + +.imgCrop_handleSW { + left: -3px; + bottom: -3px; + cursor: sw-resize; +} + +.imgCrop_handleW { + top: 0; + left: -3px; + /* margin-top: 49%; @done_in_js */ + cursor: w-resize; +} + +.imgCrop_handleNW { + top: -3px; + left: -3px; + cursor: nw-resize; +} + +/** + * Create an area to click & drag around on as the default browser behaviour is to let you drag the image + */ +.imgCrop_dragArea { + width: 100%; + height: 100%; + z-index: 200; + position: absolute; + top: 0; + left: 0; +} + +.imgCrop_previewWrap { + /* width: 200px; @done_in_js */ + /* height: 200px; @done_in_js */ + overflow: hidden; + position: relative; +} + +.imgCrop_previewWrap img { + position: absolute; +} \ No newline at end of file diff --git a/manager/inc/cropper/1.2.1/cropper.js b/manager/inc/cropper/1.2.1/cropper.js new file mode 100644 index 0000000..038d850 --- /dev/null +++ b/manager/inc/cropper/1.2.1/cropper.js @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2006-2009, David Spurr (http://www.defusion.org.uk/) + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * * 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. + * * 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. + * + * 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. + * + * http://www.opensource.org/licenses/bsd-license.php + * + * See scriptaculous.js for full scriptaculous licence + */ + +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;d0&&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);}if(a){if(e==1){d.a2=d.a1+f;}else{d.a1=d.a2-f;}if(d.a1c.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(ga){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;}}}); diff --git a/manager/inc/default.css b/manager/inc/default.css new file mode 100644 index 0000000..b3db3c7 --- /dev/null +++ b/manager/inc/default.css @@ -0,0 +1,99 @@ +@import "../../_system/css/default.css"; + +.trRo { + height:56px; + background:url(../img/bg-rodape.gif) top left repeat-x; +} +.trRo td{ + text-align:center; +} +.trRo div.divRo{ + text-align:right; + padding-right:30px; + font-size:11px; + width:964px; + margin:auto; + color:#000000; +} + +body.bg { background: url(../img/bginn.jpg) top left repeat-x #FFFFFF; } + +/* Top */ +table.boxTopo { + padding:0px; + width: 980px; + height:111px; + border: 0px solid #CCCCCC; + margin: auto; + color: #EEEEEE; + font-size: 10px; + font-family: Tahoma; + margin-bottom: 10px; +} +table.box { width: 980px; border: 0px solid #CCCCCC; margin: auto; background: #FFFFFF; color: #777777; font-size: 10px; font-family: Tahoma; margin-bottom: 10px; } + +/* Top : menu */ +ul.menu { display: inline; width: 100%; } +ul.menu li { display: inline; padding:0px; margin:0px; float: left; vertical-align:middle; } +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; } +ul.menu li a:hover { font-weight: bold; text-decoration: none; color: #D7A964; } +ul.menu li a#sel { font-weight: bold; color: #D7A964 } + +/* Top : subs */ +ul.menu_abas { padding:0px; margin:0px; float: left; list-style: none; } +ul.menu_abas li { display: inline; } +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; } +ul.menu_abas li a:hover { background: #DADCDC; } +ul.menu_abas li a#sel { font-weight: bold; background: #DADCDC; color: #194D7F; } + +/* Titles */ +h1 { font-family: Arial; font-size: 25px; color: #0F3357; font-weight: bold; text-align: center; line-height: 0px; margin-top: 10px; } + +/* List */ +table { font-size: 10px; font-family: Tahoma; color: #999999; } +table.box tr td div.sep, div.form { border-top: 1px solid #CCCCCC; margin-top: 5px; padding-top: 5px; text-align: center; } +.listagem tr td { height: 20px; padding: 0 5 0 5px; } +.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; } +.listagem tr td.header_up { background: #C1CCD2 url(../img/icons/arow_up.gif) right top no-repeat; } +.listagem tr td.header_down { background: #C1CCD2 url(../img/icons/arow_down.gif) right top no-repeat; } +.listagem tr td.header_cinza { background: #D8D8D8; } +.listagem tr td.td1 { background: #F7F7F7; cursor: pointer; color: #777777; } +.listagem tr td.td2 { background: #EEEEEE; cursor: pointer; color: #666666; } +.listagem tr td.td1-over { background: #E5E5E5; cursor: pointer; } +.listagem tr td.td2-over { background: #E5E5E5; cursor: pointer; } +.listagem tr td.td3 { background: #F2F1C8; cursor: pointer; color: #777777; } +.listagem tr td.td3-over { background: #E6E5A1; cursor: pointer; } + +/* Form / Filters */ +tr.fieldset td.label { padding: 5px; width: 130px; text-align: right; background: #F9F9F9; vertical-align: top; } +tr.fieldset td.input { padding: 5px; text-align: left; background: #FAFAFA; } +div.form { text-align: left; margin: 0px; } +div.form table tr td.label { text-align: right; width: 140px; height: 30px; padding: 13 10 10 10px; background: #F9F9F9; vertical-align: top; } +div.form table tr td.input { vertical-align: top; text-align: left; background: #FAFAFA; padding: 10px; } +div.form table tr td.custom { text-align: left; height: 20px; padding: 5px; background: #F5F5F5; vertical-align: top; color: #003366; } +div.form td.comment { vertical-align: top; text-align: left; color: #AAAAAA; font-size: 9px; padding-top: 4px; } +.item { float: left; width: 139px; height: 18px; } +.item #input { float: left; width: 20px; } +.item #label { float: left; width: 100px; padding: 2px; } + +/* Fieldset */ +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; } + +/* Text */ +font.red { color: #990000; font-weight: bold; } + +/* Boxes */ +.box_green { padding: 10px; border: 1px solid #58D73D; background: #D0F1C9; } +.box_yellow { padding: 10px; border: 1px solid #DAD73D; background: #F2F1C9; } +.box_red { padding: 10px; border: 1px solid #DA553D; background: #F2CFC9; } +.box_silver { padding: 10px; border: 1px solid #54628B; background: #CCD1E0; } + +/* Upload */ +div.upload_item { height: 15px; } +div.upload_item div.label { width: 192px; float: left; } +div.upload_item div.size { width: 40px; float: left; text-align: right; } +div.upload_item div.buttons { width: 20px; float: left; text-align: right; } + +/* Links */ +a { color: #003366; text-decoration: none; } +a:hover { text-decoration: underline; } \ No newline at end of file diff --git a/manager/inc/htmleditor/htmleditor.css b/manager/inc/htmleditor/htmleditor.css new file mode 100644 index 0000000..e3b116f --- /dev/null +++ b/manager/inc/htmleditor/htmleditor.css @@ -0,0 +1,47 @@ +.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 diff --git a/manager/inc/htmleditor/htmleditor.js b/manager/inc/htmleditor/htmleditor.js new file mode 100644 index 0000000..d8042e2 --- /dev/null +++ b/manager/inc/htmleditor/htmleditor.js @@ -0,0 +1,569 @@ +/* +TODO: + - Tag do youtube + - Ver botão de excluir elemento quando selecionado (img, retirar link...)(estudar isso) + - Ver editar url(estudar isso) + - Ver se tem como dar resize por php nas imagems + +Lembrar: + - Na hora de gravar no banco, dar resize no php nas imagems + - Limpar o html +*/ + +//Requires include default.js +try { var _test_htmleditor = __include_default; } +catch(e) { + alert("htmleditor.js : Include '_system/js/default.js' é obrigatório"); +} + +var __include_htmleditor = true; + +var HtmlEditor_ROOT = "../inc/htmleditor/"; + +function HtmlEditor() { + this.class_name = ""; //Name of instancied js var + this.field_id = ""; //Textarea hidden id + this.buttons = []; //array of removed buttons + this.width = '100%'; + this.height = '300'; + this.images_path = ""; + this.root_path = ""; + this.is_window_opened = false; + + this.onLoad = new Function(); + + this._toolbar = ["viewhtml", "|", "removeformat", "|", "bold", "italic", "underline", "|", "justifyleft", "justifycenter", "justifyright", "justifyfull", "|", "insertorderedlist", "insertunorderedlist", "|", "createlink", "unlink", "|", "image"]; + this._content = ''; + this._image_aba = 0; + this._list_refresh = false; + this._key_status = []; //Remember keys status + this._is_view_html = false; + this._last_range = null; + + this.make = function () { + var html = ''; + + html += ''; + html += ''; + + html += ''; + + html += ''; + + html += ''; + + var d = document.createElement('div'); + d.setAttribute('id', this.class_name + '_div'); + d.setAttribute('className', 'html_editor'); + d.setAttribute('class', 'html_editor'); + d.innerHTML = html; + $$(this.field_id).parentNode.appendChild(d); + + //get content from textarea element + this._content = $$(this.field_id).value; + + //enable design mode to iframe + setTimeout(this._enableIframe.bind(this), 50); + + //hidden textarea element + $$(this.field_id).style.display = 'none'; + } + + this.loadFile = function (tmp_path) { + var a = new Ajax(); + var self = this; + + a.onLoad = function () { + this.html = this.html.replace(new RegExp('#ROOT#', 'g'), self.root_path); + + self._getIframeDocument().body.innerHTML = this.html; + self._insertHTML(''); + } + a.get(tmp_path); + } + + this.getContent = function () { + return $$(this.field_id).value; + } + + this._enableIframe = function () { + this._getIframeDocument().designMode = 'on'; + + if (this._getIframeDocument().body) { + this._getIframeDocument().body.innerHTML = ''; + } + + //set content to iframe + setTimeout(this._initContent.bind(this), 300); + + //enable timer for copy text from iframe to textarea + setTimeout(this._updateField.bind(this), 350); + + //set ok events for boxes + var self = this; + addEvent($$(this.class_name + '_link_box_url'), "keydown", function (e) { self._okEvent(e, self.class_name + '._linkOK()'); }); + addEvent($$(this.class_name + '_image_box_url'), "keydown", function (e) { self._okEvent(e, self.class_name + '._imageOK()'); }); + } + + this._initContent = function () { + var self = this; + + this._getIframeDocument().body.innerHTML = this._content; + this._insertHTML(''); + + addEvent(this._getIframeDocument(), "keydown", function (e) { self._fireEvent('keydown', e); }); + addEvent(this._getIframeDocument(), "keyup", function (e) { self._fireEvent('keyup', e); }); + + if (document.all) { + addEvent(this._getIframeDocument(), "selectionchange", function (e) { self._fireEvent('selectionchange', e || event); }); + } else { + addEvent(this._getIframeDocument(), "mouseup", function (e) { self._fireEvent('selectionchange', e || event); }); + } + + this.onLoad(); + } + + this._fireEvent = function (tmp_type, tmp_e) { + var k = tmp_e.keyCode; + + switch (tmp_type) { + case "keydown": + this._key_status[k] = true; + + if (this._key_status[17] && (k == 13)) { + //this._insertHTML('

    teste!

    '); + } + + break; + + case "keyup": + this._key_status[k] = false; + + break; + + case "selectionchange": + + break; + } + } + + this._okEvent = function (tmp_e, tmp_func) { + var k = tmp_e.keyCode; + + if (k == 13) { + eval(tmp_func); + } + } + + this._getIframeDocument = function () { + if ($$(this.class_name + '_iframe').contentDocument) { + return $$(this.class_name + '_iframe').contentDocument; + } else { + return document.frames[this.class_name + '_iframe'].document; + } + } + + this._updateField = function () { + if ($$(this.class_name + '_iframe') && (!this._is_view_html)) { + var content = this._getIframeDocument().body.innerHTML; + + //clean content + if (content.substr(-4) == '
    ') { + content = content.substr(0, content.length - 4); + } + + content = content.replace('

    ', '

    '); + content = content.replace('', ''); + + if (content == '

     

    ') { + content = ''; + } + + $$(this.field_id).value = content.trim(); + } + + setTimeout(this._updateField.bind(this), 500); + } + + this._insertHTML = function (tmp_html) { + if (document.all) { + this._getIframeDocument().body.setActive(); + } + + if (document.all) { + var r = this._last_range; + + if (r == null) { + r = this._getIframeDocument().selection.createRange() + } + + r.select(); + r.collapse(false); + r.pasteHTML(tmp_html); + } else { + var rnd_str = "insert_html_" + Math.round(Math.random()*100000000); + this._getIframeDocument().execCommand('insertimage', false, rnd_str); + this._getIframeDocument().body.innerHTML = this._getIframeDocument().body.innerHTML.replace(new RegExp('<[^<]*' + rnd_str + '[^>]*>'), tmp_html); + } + } + + this._command = function (tmp_command) { + switch (tmp_command) { + case 'image': + if ($$(this.class_name + '_image_box').style.display == 'none') { + if (document.all) { + this._last_range = this._getIframeDocument().selection.createRange(); + } + + $$(this.class_name + '_image_box').style.display = ''; + screenLock(true); + + this.is_window_opened = true; + } else { + $$(this.class_name + '_image_box').style.display = 'none'; + screenLock(false); + + this.is_window_opened = false; + } + + break; + case 'createlink': + if ($$(this.class_name + '_link_box').style.display == 'none') { + if (document.all) { + this._last_range = this._getIframeDocument().selection.createRange(); + } + + $$(this.class_name + '_link_box').style.display = ''; + screenLock(true); + + this.is_window_opened = true; + } else { + $$(this.class_name + '_link_box').style.display = 'none'; + screenLock(false); + + this.is_window_opened = false; + } + + break; + case 'viewhtml': + if (!this._is_view_html) { + $$(this.class_name + '_td_iframe').style.display = 'none'; + $$(this.class_name + '_td_bar').style.display = 'none'; + + $$(this.class_name + '_td_codehtml').style.display = ''; + + $$(this.class_name + '_codehtml').value = this._getIframeDocument().body.innerHTML.replace(new RegExp("
    ", "gi"), "
    \n").replace(new RegExp("<\p>", "gi"), "<\p>\n"); + + $$(this.class_name + '_codehtml').focus(); + + this._is_view_html = true; + } else { + this._is_view_html = false; + + $$(this.class_name + '_td_iframe').style.display = ''; + $$(this.class_name + '_td_bar').style.display = ''; + + $$(this.class_name + '_td_codehtml').style.display = 'none'; + + this._getIframeDocument().body.innerHTML = $$(this.class_name + '_codehtml').value; + this._insertHTML(''); + } + + break; + default: + $$(this.class_name + '_iframe').focus(); + this._getIframeDocument().execCommand(tmp_command, false, ''); + + break; + } + + try { + $$(this.class_name + '_iframe').contentWindow.focus(); + } catch (e) { } + } + + this._getDescription = function (tmp_button) { + switch (tmp_button) { + case "removeformat": return "Remover formatação"; break; + case "bold": return "Aplicar/Retirar negrito"; break; + case "italic": return "Aplicar/Retirar itálico"; break; + case "underline": return "Aplicar/Retirar underline"; break; + case "justifyleft": return "Alinhar à esquerda"; break; + case "justifylright": return "Alinhar ao centro"; break; + case "justifylright": return "Alinhar à direita"; break; + case "justifyfull": return "Justificar"; break; + case "insertorderedlist": return "Inserir/Remover lista ordenada"; break; + case "insertunorderedlist": return "Inserir/Remover lista não ordenada"; break; + case "createlink": return "Inserir link"; break; + case "unlink": return "Remover link"; break; + case "image": return "Inserir imagem"; break; + case "viewhtml": return "Editar html"; break; + default: return ""; break; + } + } + + //Image + this._imageAbaEvent = function (tmp_event, tmp_index) { + this._image_aba++; this._image_aba--; + tmp_index++; tmp_index--; + + switch (tmp_event) { + case 'over': + if (tmp_index != this._image_aba) { + $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('className', 'aba_over'); + $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('class', 'aba_over'); + } + + break; + case 'out': + if (tmp_index != this._image_aba) { + $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('className', 'aba'); + $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('class', 'aba'); + } + + break; + case 'click': + if (tmp_index != this._image_aba) { + $$(this.class_name + '_image_box_aba' + this._image_aba).setAttribute('className', 'aba'); + $$(this.class_name + '_image_box_aba' + this._image_aba).setAttribute('class', 'aba'); + $$(this.class_name + '_image_box_content' + this._image_aba).style.display = 'none'; + + this._image_aba = tmp_index; + + $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('className', 'aba_sel'); + $$(this.class_name + '_image_box_aba' + tmp_index).setAttribute('class', 'aba_sel'); + $$(this.class_name + '_image_box_content' + tmp_index).style.display = ''; + + if ((this._image_aba == 1) && (!this._list_refresh)) { + this._list_refresh = true; + + this._imageListRefresh(); + } + } + + break; + } + } + + this._imageThumb = function () { + var url = $$(this.class_name + '_image_box_url').value; + var ext = url.substr(url.length - 3, 3).toLowerCase(); + var html = '



    sem imagem'; + + url = url.replace(this.root_path, ''); + + if ((ext == 'jpg') || (ext == 'gif')) { + html = ''; + } + + $$(this.class_name + '_image_thumb').innerHTML = html; + } + + this._imageListRefresh = function () { + var a = new Ajax(); + var self = this; + + a.onLoad = function () { + var ext, html = ''; + var arr = this.html.split('##'); + + arr.each(function (k, v) { + if (v != '') { + ext = v.substr(v.length - 3, 3).toLowerCase(); + + if ((ext == 'jpg') || (ext == 'gif')) { + html += '
    '; + } + } + }, this); + + $$(self.class_name + '_image_box_content1').innerHTML = html; + } + a.get(HtmlEditor_ROOT + "routines.php?routine=list&path=" + this.images_path); + } + + this._imageSelect = function (tmp_path) { + $$(this.class_name + '_image_box_url').value = tmp_path; + + this._imageAbaEvent('click', 0); + this._imageThumb(); + } + + this._imageUpload = function () { + var onload, input, form, iframe, self, ext; + + self = this; + + iframe = document.createElement("iframe"); + iframe.setAttribute("id","ifr_tmp"); + iframe.setAttribute("name","ifr_tmp"); + iframe.setAttribute("width","0"); + iframe.setAttribute("height","0"); + iframe.setAttribute("border","0"); + iframe.setAttribute("style","width: 0; height: 0; border: none;"); + $$(this.field_id).parentNode.appendChild(iframe); + window.frames["ifr_tmp"].name = "ifr_tmp"; //Ie sux + + //Verify if input file is not empty + input = $$(this.class_name + '_image_box_file'); + + if (input.value != '') { + //Verify extension + ext = input.value.substr(input.value.length - 3, 3).toLowerCase(); + + if ((ext == 'jpg') || (ext == 'gif') || (ext == 'png')) { + onload = function () { + self._imageAbaEvent('click', 1); + + //Removes iframe element + setTimeout(function () { removeElement($$('ifr_tmp')); }, 250); + + $$(self.class_name + '_image_box_upload').style.display = ''; + removeElement($$(self.class_name + '_image_box_carregando')); + + self._imageListRefresh(); + } + addEvent($$('ifr_tmp'), "load", onload); + + //Config form element + form = $$(this.class_name + '_image_box_form'); + form.setAttribute("target", "ifr_tmp"); + form.setAttribute("action", HtmlEditor_ROOT + "routines.php?routine=upload&path=" + this.images_path); + form.setAttribute("method", "post"); + form.setAttribute("enctype", "multipart/form-data"); + form.setAttribute("encoding", "multipart/form-data"); + + form.submit(); + + var d = document.createElement("div"); + d.id = this.class_name + "_image_box_carregando"; + d.innerHTML = "Carregando..."; + $$(this.class_name + '_image_box_upload').parentNode.appendChild(d); + + $$(this.class_name + '_image_box_upload').style.display = 'none'; + } else { + alert("Arquivo inválido.\nSão permitidos apenas arquivos .jpg, .gif e .png"); + } + } else { + alert("O campo 'Arquivo' está vazio"); + + input.focus(); + } + } + + this._imageOK = function () { + var url = $$(this.class_name + '_image_box_url').value; + var ext = url.substr(url.length - 3, 3).toLowerCase(); + + if ((ext == 'jpg') || (ext == 'gif')) { + if (url.indexOf('http://') == -1) { + url = this.root_path + url; + } + + this._insertHTML(''); + + this._command('image'); + + this._imageThumb(); + } else { + alert('Imagem inválida, verifique a url informada.'); + } + } + + //Link + this._linkOK = function () { + var url = $$(this.class_name + '_link_box_url').value; + var http = url.substr(0, 4); + + if (http == 'http') { + if (document.all) { + this._getIframeDocument().body.setActive(); + + var r = this._last_range; + + if (r == null) { + r = this._getIframeDocument().selection.createRange() + } + + r.select(); + + r.collapse(false); + } + + this._getIframeDocument().execCommand('createlink', false, url); + + this._command('createlink'); + + $$(this.class_name + '_link_box_url').value = 'http://'; + } else { + alert('Link inválido, verifique a url informada.'); + } + } +} \ No newline at end of file diff --git a/manager/inc/htmleditor/routines.php b/manager/inc/htmleditor/routines.php new file mode 100644 index 0000000..308480b --- /dev/null +++ b/manager/inc/htmleditor/routines.php @@ -0,0 +1,97 @@ +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 diff --git a/manager/inc/inc.menu.php b/manager/inc/inc.menu.php new file mode 100644 index 0000000..aae4308 --- /dev/null +++ b/manager/inc/inc.menu.php @@ -0,0 +1,10 @@ +manager("core/Menu.php"); +$menu = new Menu(); + +$load->config("menu.php"); +?> \ No newline at end of file diff --git a/manager/inc/inc.restrict.php b/manager/inc/inc.restrict.php new file mode 100644 index 0000000..f6289de --- /dev/null +++ b/manager/inc/inc.restrict.php @@ -0,0 +1,9 @@ +isLogged()) { + redir("../", true); +} +?> \ No newline at end of file diff --git a/manager/inc/prototype/1.6.1.0/prototype.js b/manager/inc/prototype/1.6.1.0/prototype.js new file mode 100644 index 0000000..8bd02fd --- /dev/null +++ b/manager/inc/prototype/1.6.1.0/prototype.js @@ -0,0 +1,4874 @@ +/* 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: ']*>([\\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,'>'); + } + + 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 '#'; + } + + + + + + + + + + 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 '#'; + } + + 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 = ""; + 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 = ""; + 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: ['
    '; + + var toolbar_ = this._toolbar.remove(this.buttons); //Remove buttons + var self = this; + var tab_order_ = 200; + toolbar_.each(function (k, v) { + if (v == '|') { + html += ''; + } else { + html += ''; + + tab_order_++; + } + }, this); + + this._toolbar = toolbar_; + + html += '
      '; + + if (v == 'image') { + html += ''; + } else if (v == 'createlink') { + html += ''; + } + + html += '
    '; + html += ' '; + html += '
    test
    ', '
    ', 1], + TBODY: ['', '
    ', 2], + TR: ['', '
    ', 3], + TD: ['
    ', '
    ', 4], + 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 = '
    '; + + 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"; + } +}); + +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= 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); + +/*--------------------------------------------------------------------------*/ diff --git a/manager/inc/relItems/FieldRelItems.js b/manager/inc/relItems/FieldRelItems.js new file mode 100644 index 0000000..71959b1 --- /dev/null +++ b/manager/inc/relItems/FieldRelItems.js @@ -0,0 +1,288 @@ +//Requires include default.js +try { var _test_relItems = __include_default; } +catch(e) { + alert("relItems.js : Include '_system/js/default.js' é obrigatório"); +} + +var __include_relItems = true; + +var HtmlEditor_ROOT = "../inc/htmleditor/"; + +unse = function (str) { + if(str != ""){ + var arrAux = str.split("###"); + var arrAux2 = new Array(); + + for(var x=0;x 0){ + var str = ""; + + for(var x=0;x 0){ + this.feedResult(); + } else { + this.clearSearch(); + } + } + this.getDoRelationButton = function (tag_name) { + var divButton = document.createElement("div"); + var html = '
    '; + html += ''; + html += '
    '; + divButton.innerHTML = html; + return divButton; + } + this.getUndoRelationButton = function (tag_name) { + var divButton = document.createElement("div"); + var html = '
    '; + html += ''; + html += '
    '; + divButton.innerHTML = html; + return divButton; + } + this.clearSearch = function () { + this.arrSearch = new Array(); + this.td_result.innerHTML = "Nenhum item encontrado."; + } + this.feedResult = function () { + var tag_name = this.td_result.id+"_result";//da nome aos check box para relacionamento + this.td_result.innerHTML = ""; + + this.td_result.appendChild(this.getDoRelationButton(tag_name)); + + var divParent = document.createElement("div"); + divParent.style.background = "#FFFFFF"; + divParent.style.width = "100%"; + //divParent.style.height = "150px"; + divParent.innerHTML = " "; + + var bg = "#FFFFFF"; + for(var x=0;x'; + tableItem += ''; + tableItem += ''; + tableItem += ''; + //tableItem += ''+this.arrSearch[x][1]+''; + tableItem += this.arrSearch[x][1]; + tableItem += ''; + + for(var y=2;y 0){ + this.td_rel.innerHTML = ""; + if(!this.is_static){ + this.td_rel.appendChild(this.getUndoRelationButton(tag_name)); + } + var divParent = document.createElement("div"); + divParent.style.background = "#FFFFFF"; + divParent.style.width = "100%"; + //divParent.style.height = "150px"; + divParent.innerHTML = " "; + + var bg = "#FFFFFF"; + var extra = ' style="cursor:pointer;" onclick="javascript: document.getElementById(\''+tag_name+x+'\').checked = !(document.getElementById(\''+tag_name+x+'\').checked);" '; + var disabled = ''; + if(this.is_static){ + disabled = ' checked disabled '; + extra = ''; + } + for(var x=0;x'; + tableItem += ''; + tableItem += ''; + tableItem += ''; + //tableItem += ''+this.arrRel[x][1]+''; + tableItem += this.arrRel[x][1]; + tableItem += ''; + + // for(var y=2;y'; + // tableItem += this.arrRel[x][y]; + // tableItem += ''; + // } + tableItem += ''; + divItem.innerHTML = tableItem; + divParent.appendChild(divItem); + } + + this.td_rel.appendChild(divParent); + if(!this.is_static){ + this.td_rel.appendChild(this.getUndoRelationButton(tag_name)); + } + } else { + this.td_rel.innerHTML = "Nenhum item relacionado."; + } + } + this.doRelationWithResult = function (tag_name) { + var elements = document.getElementsByName(tag_name); + var arrChecked = new Array(); + for(var x=0;x 0){ + this.addIds(arrChecked); + this.feedRel(); + } else { + alert("Selecione ao menus um item para relacionar."); + } + } + this.undoRelationWithResult = function (tag_name) { + var elements = document.getElementsByName(tag_name); + var arrChecked = new Array(); + for(var x=0;x 0){ + this.removeIds(arrChecked); + this.feedRel(); + } else { + alert("Selecione ao menus um item para relacionar."); + } + } + this.fromRelHidden = function () { + this.arrRel = unse(this.hidden.value); + } + this.toRelHidden = function(){ + this.hidden.value = se(this.arrRel); + } + this.addIds = function (arr){ + this.fromRelHidden(); + + for(var x=0;x/g, ">") + "\n" + (new String(Math.round((tmp_html.length / 1024) * 100) / 100)).replace(".", ",") + " Kb"; + } +} + +function listOrder(tmp_order) { + $$('input_order').value = tmp_order; + + listSubmitFilters(); +} + +function listPage(tmp_page) { + $$('input_page').value = tmp_page; + + listSubmitFilters(); +} + + +function listInsert() { + ajaxGet('form/form.php?routine=insert'); +} + +function listUpdate(tmp_id) { + ajaxGet('form/form.php?routine=update&id=' + tmp_id); +} + +//filters +function showHideFilters() { + if ($$('div_filtros').style.display == '') { + $$('img_filter').src = '../img/buttons/filter.jpg'; + $$('div_filtros').style.display = 'none'; + } else { + $$('img_filter').src = '../img/buttons/filter_disabled.jpg'; + $$('div_filtros').style.display = ''; + } +} + +function preListSubmitFilters() { + $$('input_page').value = ""; + + listSubmitFilters(); +} + +function listSubmitFilters() { + if (f.send('frm_filters', true)) { + var a = new Ajax(); + a.onLoad = function () { + $$('conteudo').innerHTML = this.html; + + debugHtml(this.html); + + this.runJS(this.html); + } + a.sendForm('frm_filters'); + + showLoading(); + } +} + + +//over list +function listOverOut(tmp_acao, tmp_i) { + var tds = $$('tr_' + tmp_i).getElementsByTagName('td'); + var obj; + var css = ''; + var i; + var class_name = 'td' + (2 - (tmp_i % 2)); + + if (delete_enabled) { + i = 1; + if ($$('chk_' + tmp_i).checked) { + class_name = 'td3'; + } + } else { + i = 0; + } + + tds[i].className = class_name; + + for (; i < (tds.length); i++) { + obj = tds[i]; + + if (css == '') { + switch (tmp_acao) { + case "over": + css = obj.className.replace("-over", "") + '-over'; + break; + case "out": + css = obj.className.replace("-over", ""); + break; + } + } + + obj.className = css; + } +} + +//checks +function check(tmp_obj) { + var i = 1; + var r; + + if (tmp_obj.checked) { + r = true; + } else { + r = false; + } + + while ($$('chk_' + i)) { + $$('chk_' + i).checked = r; + + i++; + } + + checkMostrar(); +} + +function checkMostrar() { + var i = 1; + var ok = false; + + while ($$('chk_' + i)) { + if ($$('chk_' + i).checked) { + ok = true; + } + + listOverOut('out', i); + + i++; + } + + if (ok) { + $$('div_botao_excluir').style.display = ''; + } else { + $$('div_botao_excluir').style.display = 'none'; + } +} + +function checkExcluir() { + if (confirm("Deseja realmente excluir este(s) item(ns)?")) { + if (f.send('frm_list', true)) { + var a = new Ajax(); + a.onLoad = function () { + $$('conteudo').innerHTML = this.html; + + debugHtml(this.html); + + this.runJS(this.html); + } + a.sendForm('frm_list'); + } + } +} + +//buttons +function listButton(tmp_name) { + var ifr = createHiddenIframe('ifr_button_' + tmp_name, 'button_bar'); + var cfg = new Array(); + + var onload = function () { + //Removes iframe element + //setTimeout(function () { removeElement('ifr_button_' + tmp_name); alert("remove: " + 'ifr_button_' + tmp_name); }, 250); + } + addEvent(ifr, "load", onload); + + cfg["target"] = $$('frm_filters').target; + cfg["action"] = $$('frm_filters').action; + + $$('frm_filters').target = "ifr_button_" + tmp_name; + $$('frm_filters').action = "form/list.php?routine=list_button&name=" + tmp_name; + + if (f.send('frm_filters', true)) { + $$('frm_filters').submit(); + } else { + //setTimeout(function () { removeElement('ifr_button_' + tmp_name); alert("remove: " + 'ifr_button_' + tmp_name); }, 250); + } + + $$('frm_filters').setAttribute('target', cfg["target"]); + $$('frm_filters').setAttribute('action', cfg["action"]); +} + +//Form +var customPrePost; +function prePost() { + try { + customPrePost(); + } catch(e) { alert("Erro - prePost() : " + e); } +} + +function formSubmit() { + if (f.send('frm_form', true)) { + var a = new Ajax(); + a.onLoad = function () { + $$('conteudo').innerHTML = this.html; + + debugHtml(this.html); + + this.runJS(this.html); + } + a.sendForm('frm_form'); + + showLoading(); + } +} + +//Aux functions +function createHiddenIframe(tmp_id, tmp_id_parent) { + var iframe = document.createElement("iframe"); + iframe.setAttribute("id",tmp_id); + iframe.setAttribute("name",tmp_id); + if (!$$('box_html')) { + iframe.setAttribute("width","0"); + iframe.setAttribute("height","0"); + iframe.setAttribute("border","0"); + iframe.setAttribute("style","width: 0; height: 0; border: none; visibility: hidden; display: none;"); + } + $$(tmp_id_parent).parentNode.appendChild(iframe); + window.frames[tmp_id].name = tmp_id; //Ie sux + + return iframe; +} + +function screenLock(tmp_lock) { + if (tmp_lock == null) { tmp_lock = false; } + + if (!$$('div_lock')) { + var div = document.createElement('div'); + div.setAttribute('id', 'div_lock'); + 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);'); + div.style.position = 'absolute'; + div.style.background = '#000'; + div.style.filter = 'alpha(opacity=60)'; + div.innerHTML = ' '; + document.getElementsByTagName('body')[0].appendChild(div); + } + + if (tmp_lock) { + $$('div_lock').style.display = ''; + + addEvent(window, 'scroll', screenLock_scroll); + screenLock_scroll(); + } else { + $$('div_lock').style.display = 'none'; + + removeEvent(window, 'scroll', screenLock_scroll); + } +} + +function screenLock_scroll(e) { + var obj = $$('div_lock'); + + if (obj) { + var pos = new WindowPosition(); + + obj.style.left = pos.x + "px"; + obj.style.top = pos.y + "px"; + obj.style.width = pos.w + "px"; + obj.style.height = pos.h + "px"; + } +} + +function setCSS(tmp_css, tmp_id) { + var s; + + if (!tmp_id) { + tmp_id = "css_" + Math.round(Math.random() * 10000); + } + + if (document.all) { + if ($$(tmp_id)) { + s = $$(tmp_id); + } else { + s = document.createStyleSheet(); + } + s.cssText = tmp_css; + } else { + if ($$(tmp_id)) { + s = $$(tmp_id); + } else { + s = document.createElement('style'); + s.type = 'text/css'; + } + s.innerHTML = tmp_css; + } + + if (!$$(tmp_id)) { + try { + document.getElementsByTagName('head')[0].appendChild(s); + } catch (e) { } + } +} + +//Upload +function uploadSubmit(tmp_name) { + var iframe + var onload; + var configs = new Array(); + var div; + var input; + + //Verify if input file is not empty + div = $$(tmp_name + '_div_input'); + input = div.getElementsByTagName("input")[0]; + + if (input.value != '') { + //Create iframe element + iframe = createHiddenIframe('ifr_tmp', 'frm_form'); + onload = function () { + uploadList(tmp_name); + + $$(tmp_name + '_div_loading').style.display = 'none'; + + //Removes iframe element + if (!$$('box_html')) { + setTimeout(function () { removeElement($$('ifr_tmp')); }, 250); + } + } + addEvent($$('ifr_tmp'), "load", onload); + + $$(tmp_name + '_div_input').style.display = 'none'; + $$(tmp_name + '_div_loading').style.display = ''; + + //Save configuration + configs["target"] = $$('frm_form').target; + configs["action"] = $$('frm_form').action; + configs["method"] = $$('frm_form').method; + configs["enctype"] = $$('frm_form').enctype; + configs["encoding"] = $$('frm_form').encoding; + + //Config form element + $$('frm_form').setAttribute("target", "ifr_tmp"); + $$('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)); + $$('frm_form').setAttribute("method", "post"); + $$('frm_form').setAttribute("enctype", "multipart/form-data"); + $$('frm_form').setAttribute("encoding", "multipart/form-data"); + + $$('frm_form').submit(); + + //Remember old configuration + $$('frm_form').setAttribute("target", configs["target"]); + $$('frm_form').setAttribute("action", configs["action"]); + $$('frm_form').setAttribute("method", configs["method"]); + $$('frm_form').setAttribute("enctype", configs["enctype"]); + $$('frm_form').setAttribute("encoding", configs["encoding"]); + } +} + +function uploadList(tmp_name) { + $$(tmp_name + '_div_loading').style.display = ''; + + var a = new Ajax(); + a.onLoad = function () { + $$(tmp_name + '_div_list').innerHTML = this.html; + + debugHtml(this.html); + + this.runJS(this.html); + + $$(tmp_name + '_div_loading').style.display = 'none'; + } + a.get('form/routines.php?menu=' + menu + '&routine=' + routine + '&routine_field=list&name=' + tmp_name + "&tmp_id=" + tmp_id + "&id=" + id); +} + +function uploadDelete(tmp_name, tmp_n) { + $$(tmp_name + '_div_loading').style.display = ''; + + var a = new Ajax(); + a.onLoad = function () { + debugHtml(this.html); + + this.runJS(this.html); + + $$(tmp_name + '_div_loading').style.display = 'none'; + } + a.get('form/routines.php?menu=' + menu + '&routine=' + routine + '&routine_field=delete&name=' + tmp_name + "&tmp_id=" + tmp_id + "&id=" + id + "&n=" + tmp_n); +} + +//Ativo +function ativoSwap(tmp_obj, tmp_field_name, tmp_id) { + var container = tmp_obj.parentNode; + var a = new Ajax(); + + container.innerHTML = ''; + + a.onLoad = function () { + container.innerHTML = this.html; + } + a.get('form/routines.php?menu=' + menu + '&routine=ativo&name=' + tmp_field_name + "&id=" + tmp_id + "&rnd=" + rnd); +} + +//Ordem +function orderSwap(tmp_name, tmp_id, tmp_direction) { + var cfg = Array(); + var a = new Ajax(); + + if (f.send('frm_filters', true)) { + cfg["action"] = $$('frm_filters').action; + + $$('input_extra').value = tmp_id + "#" + tmp_direction; + + $$('frm_filters').action = 'form/routines.php?menu=' + menu + '&routine_field=order&name=' + tmp_name + "&tmp_id=" + tmp_id + "&direction=" + tmp_direction; + + a.onLoad = function () { + listSubmitFilters(); + } + a.sendForm('frm_filters'); + + $$('input_extra').value = ''; + + $$('frm_filters').setAttribute('action', cfg["action"]); + } +} + +function statusSwap(tmp_obj, tmp_field_name, tmp_id) { + var container = tmp_obj.parentNode; + var a = new Ajax(); + + container.innerHTML = ''; + + a.onLoad = function () { + container.innerHTML = this.html; + } + a.get('../../_config/exeptions/routines/routines.php?menu=' + menu + '&routine=status&name=' + tmp_field_name + "&id=" + tmp_id + "&rnd=" + rnd); +} +function zoom(tmp_path,tmp_width,tmp_height){ + var p = new Popup(tmp_width,tmp_height); + p.position = "fixed"; + p.overflow = "hidden"; + p.open("zoom.php?path="+tmp_path); +} \ No newline at end of file diff --git a/manager/inc/scriptaculous/1.8.2/builder.js b/manager/inc/scriptaculous/1.8.2/builder.js new file mode 100644 index 0000000..18a0511 --- /dev/null +++ b/manager/inc/scriptaculous/1.8.2/builder.js @@ -0,0 +1,136 @@ +// 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 + ">"; + } 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 + ">"; + } 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 diff --git a/manager/inc/scriptaculous/1.8.2/controls.js b/manager/inc/scriptaculous/1.8.2/controls.js new file mode 100644 index 0000000..3c2287f --- /dev/null +++ b/manager/inc/scriptaculous/1.8.2/controls.js @@ -0,0 +1,965 @@ +// 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, + ''); + 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("
  • " + elem.substr(0, entry.length) + "" + + elem.substr(entry.length) + "
  • "); + 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("
  • " + elem.substr(0, foundPos) + "" + + elem.substr(foundPos, entry.length) + "" + elem.substr( + foundPos + entry.length) + "
  • "); + 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 "
      " + ret.join('') + "
    "; + } + }, options || { }); + } +}); + +// AJAX in-place editor and collection editor +// Full rewrite by Christophe Porteneuve (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 diff --git a/manager/inc/scriptaculous/1.8.2/dragdrop.js b/manager/inc/scriptaculous/1.8.2/dragdrop.js new file mode 100644 index 0000000..122de98 --- /dev/null +++ b/manager/inc/scriptaculous/1.8.2/dragdrop.js @@ -0,0 +1,974 @@ +// 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 diff --git a/manager/inc/scriptaculous/1.8.2/effects.js b/manager/inc/scriptaculous/1.8.2/effects.js new file mode 100644 index 0000000..acec96d --- /dev/null +++ b/manager/inc/scriptaculous/1.8.2/effects.js @@ -0,0 +1,1123 @@ +// 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= 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.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 = '
    '; + 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 diff --git a/manager/inc/scriptaculous/1.8.2/scriptaculous.js b/manager/inc/scriptaculous/1.8.2/scriptaculous.js new file mode 100644 index 0000000..fc5c2a9 --- /dev/null +++ b/manager/inc/scriptaculous/1.8.2/scriptaculous.js @@ -0,0 +1,68 @@ +// 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(' +
    + + + + + +
    + Campos marcados com * são obrigatórios. + + testFlag("D")) && ($show)) { ?> + &routine=delete&id=fields[$form->key_field]; ?>'); } }" title="Excluir registro">Excluir + +
    +
    +
    &routine=&id=fields["id"]; ?>" method="post" onsubmit="return false;"> + +
    + + + + +
    + + getFieldSet(); + + foreach ($fields as $k => $v) { + if ($v->testFlag($flag)) { + echo $v->getHtml() . CRLF; + } + } + ?> +
    +
    +
    +
    +
    + enable_update)) { + $show = false; + } + + if ($show) { + ?> + + ');" /> + + ');" /> + +
    +
    + +
    +loadList(); +?> \ No newline at end of file diff --git a/manager/routines/form/list.php b/manager/routines/form/list.php new file mode 100644 index 0000000..bb987e4 --- /dev/null +++ b/manager/routines/form/list.php @@ -0,0 +1,284 @@ +ajaxHeader(); + +$sub = $menu->getSub(); +$load->config("forms/Form" . ucfirst($sub->class) . ".php"); +$class = "Form" . $sub->class; +$form = new $class(); + +//if is a form only +if ($form->is_unique) { + redir("form.php?menu=" . $input->request("menu") . "&routine=insert"); + die(); +} + +//headers +$routine = "O"; +$headers = $form->getHeaders(); + +//filters +$routine = "F"; +$filters = $form->getFilters(); + + +//Reset fieldset for list +$routine = "L"; +$form->resetFieldSet(); + + +//procces query/page +$records_total = 0; +if (($filters["sql"] != "") || ($form->show_list_init)) { + //.query + $sql = $form->getListSql($filters["sql"], $headers["sql"]); + + $rs_list = $db->execute($sql); + + //.page + $page = $form->getListPage(); + $rs_list->pagesize = $form->page_size; + $records_total = $rs_list->recordCount(); + + if ($records_total > $form->page_size) { + $rs_list->page($page); + } +} + +//execute routine of button(if request) +$old_routine = $routine; +$routine = $input->get("routine"); +if ($routine == "list_button") { + $form->execButton($input->get("name")); + + die(); +} +$routine = $old_routine; + +//load init of form and fields +$form->loadInitAll("L"); + +//display filters +if (($filters["sql"] == "") && (!$form->show_filters_init)) { + $filters_display = "none"; + $filters_img = ""; +} else { + $filters_display = ""; + $filters_img = "_disabled"; +} + +if ((IS_LOCAL) && (IS_DEVELOP)) { + ?>
    + +
    + + + + + + + +
    + + + + + Listando registro 1) { + ?>s + show_list_init)) && ($rs_list->recordCount() > 0) && ($rs_list->pagecount > 1)) { + ?> + + + + + + +
    + absolutepage > 1) { ?> + Anterior + + + pagecount > 10){ + if ($rs_list->absolutepage + 5 <= $rs_list->pagecount) { + $i = $rs_list->absolutepage - 5; + } else { + $i = $rs_list->pagecount - 9; + } + if($i <= 0){ + $i = 1; + } + } + $counter = 0; + while (($i <= $rs_list->pagecount) && ($counter < 10)) { + if ($rs_list->absolutepage <> $i) { + ?>pagecount) { + ?> | + + absolutepage < $rs_list->pagecount) { ?> + Próximo + +
    + +
    + _buttons as $v) { + $title = ""; + if ($v["label"] != "") { + $title = "title=\"" . $v["label"] . "\""; + } + + + ?> href="javascript: nothing_func();" onclick="javascript: listButton(''); ">.gif" style="margin-bottom: 2px; margin-right: 5px;" /> + testFlag("I")) { ?> + Inserir + +
    +
    +
    +
    " method="post"> + + + + + " /> + + " /> + + + + +
    + Filtros + + + +
    + +
    + + ?> + + +

    +
    +
    +
    +
    +
    &routine=delete_checks" method="post"> + + show_list_init)) { ?> + + + testFlag("D")) { + //condição conforme perfil adicionada + if (($form->testFlag("D")) && ($profile->fields('nivel') == 1)) { ?> + + + + + + + EOF) { + $css = 2; + $i = 1; + + $fields = $form->getFieldSet(); + + while (!$rs_list->EOF) { + $css = 3 - $css; + + echo "" . CRLF; + + $extra = "class='td" . $css . "' "; + // $canChange = true; + // if($rs_list->fields('id_usuario') != ''){ + // global $profile; + // if($profile->fields('id') != 1){ + // if($profile->fields('id') != $rs_list->fields('id_usuario')){ + // $canChange = false; + // } + // } + // } + + //if (($form->testFlag("U")) && ($canChange)) { + if ($form->testFlag("U")) { + $extra .= "onclick=\"javascript: listUpdate('" . $rs_list->fields($form->key_field) . "');\""; + } else { + $extra .= "style=\"cursor: default;\""; + } + + if (($form->testFlag("D")) && ($profile->fields('nivel') == 1)) { + echo " " . CRLF; + } + + $form->setValuesFromRs($rs_list); + + foreach ($fields as $k => $v) { + if ($v->testFlag("L")) { + $v->value = $rs_list->fields($v->name); + $v->is_formated = false; + + echo " " . trim($v->getHtmlList($extra)) . LF; + } + } + + echo ""; + + $rs_list->moveNext(); + $i++; + } + } else { + ?> + + +
    Nenhum registro encontrado
    +
    +
    + +loadList(); +?> \ No newline at end of file diff --git a/manager/routines/form/routines.php b/manager/routines/form/routines.php new file mode 100644 index 0000000..ccbf8c7 --- /dev/null +++ b/manager/routines/form/routines.php @@ -0,0 +1,166 @@ +ajaxHeader(); + +global $routine; + +$routine = $input->get("routine"); +$routine_field = $input->get("routine_field"); + +//form class +$sub = $menu->getSub(); +if (isset($sub)) { + if($sub->module != ""){ + $load->config("forms/Form" . ucfirst($sub->class) . ".php"); + $class = "Form" . $sub->class; + $form = new $class(); + } +} + +//insert / update / delete +if ($routine_field == "") { + switch($routine) { + case 'insert': + $form->postInsert(); + + redir("list.php?menu=" . $input->request("menu"), false, "", false); + + break; + + case 'update': + $form->fields[$form->key_field] = $input->get("id"); + $form->select(); + + $form->postUpdate(); + + redir("list.php?menu=" . $input->request("menu"), false, "", false); + + break; + + case 'delete': + $form->fields[$form->key_field] = $input->get("id"); + $form->select(); + + $form->postDelete(); + + redir("list.php?menu=" . $input->request("menu"), false, "", false); + + break; + + case 'delete_checks': + foreach ($_POST as $k => $v) { + $form->fields[$form->key_field] = $v; + $form->select(); + + $form->postDelete(); + } + + redir("list.php?menu=" . $input->request("menu")); + + break; + + case 'ativo': + $id = $input->get("id"); + + $form->fields[$form->key_field] = $id; + $form->select(); + + $name = $input->get("name"); + + if($form->fields[$name] == 1){ + $form->fields[$name] = '0'; + } else { + $form->fields[$name] = '1'; + } + + $form->update(); + + if ($form->fields[$name] == 1) { + echo ""; + } else { + echo ""; + } + + break; + + case 'refresh_combo': + $value = $input->get('value'); + $name_fields = $input->get('name_fields'); + $table_rel = $input->get('table_rel'); + $value_field_rel = $input->get('value_field_rel'); + $name_field_rel = $input->get('name_field_rel'); + $value_select = $input->get('value_select'); + + $sql = "SELECT DISTINCT(" . $value_field_rel . "), " . $name_field_rel . " FROM " . $table_rel . " WHERE " . $name_fields . " LIKE '". $value."' ORDER BY ". $name_field_rel . " ASC"; + $rs = $db->execute($sql); + + if (!$rs->EOF) { + echo("+ Selecione #+-------------"); + while(!$rs->EOF) { + echo("#".$rs->fields($value_field_rel)."+".$rs->fields($name_field_rel)); + $rs->moveNext(); + } + } else { + echo("+Nenhum elemento relacionado"); + } + break; + + case 'refresh_tree': + /* + * 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) + */ + $args = array(); + $args[] = $input->get('arg0'); + $args[] = $input->get('arg1'); + $args[] = $input->get('arg2'); + $args[] = $input->get('arg3'); + $id = $input->get('id'); + + $sql = "SELECT DISTINCT ".$args[0].",".$args[2]." FROM ".$args[3]." WHERE ".$args[1]." = ".$id." ORDER BY ". $args[2] . " ASC"; + //echo $sql; + $rs = ""; + if ($id != "") { + $rs = $db->execute($sql); + }else{ + break; + } + + if ((!$rs->EOF)&&($rs->recordcount > 0)){ + echo("+ Selecione #+-------------"); + //print_r2($rs); + while(!$rs->EOF) { + echo("#".$rs->fields($args[0])."+".$rs->fields($args[2])); + $rs->moveNext(); + } + }/* else { + echo(""); + }*/ + break; + } +} + +//fields routines +if ($routine_field != "") { + $output->ajaxHeader(); + + if ($routine == "update") { + $id = $input->get("id"); + if ($id != "") { + $form->fields[$form->key_field] = $id; + $form->select(); + } + } + + $f =& $form->getFieldByName($input->request("name")); + + echo $f->ajaxRoutine($routine_field); +} +?> \ No newline at end of file diff --git a/manager/routines/index.php b/manager/routines/index.php new file mode 100644 index 0000000..b68a587 --- /dev/null +++ b/manager/routines/index.php @@ -0,0 +1,133 @@ + + + + getFaviconHeader(); ?> + + <?= strip_tags($cfg["system_title"]); ?> + + + + + + + + + + + + + + + + + + + + + + loadSubs(); + + if ($subs != "") { + ?> + + + + + + + + + + +
    + + + + + + +
    + + + + + +
    + + + 100) {?> 100) {?> +
    +
    + + +
    + fields("usuario"); ?> - - +
    +


    +
    + Sair

    +
    +
    +
    + + + + +
    + +
    +
    + + + + +
    +
    Carregando...
    +
    +
    +
    © Copyright - SIAP - Sistema de Imagens Anatomopatológicas
    +
    + +
    + +
    + + getInclude(); + + if (file_exists($page)) { + ?> + + \ No newline at end of file diff --git a/manager/routines/system/login.php b/manager/routines/system/login.php new file mode 100644 index 0000000..7d2e96f --- /dev/null +++ b/manager/routines/system/login.php @@ -0,0 +1,251 @@ + + + + getFaviconHeader("login"); ?> + + + + <?= strip_tags($cfg["system_title"]); ?> + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
     
     
     
      
    +
    +
    + + + + + + + + + + + + +
    Área Restrita
    +
    +
    Usuário
    + +
    +
    +
    +
    Senha
    + +
    +
    + get("r") == 1) { + $msg = 'Usuário ou senha inválido.
    '; + } else { + switch($input->get("f")){ + case '': + break; + case 0: + $msg = 'E-mail inválido.
    '; + break; + case 1: + $msg = 'Seus dados de acesso foram enviado com sucesso ao e-mail enformado.
    '; + break; + case 2: + $msg = 'Erro ao enviar e-mail, tente novamente mais tarde.
    '; + break; + } + } echo $msg;?> + Esqueci minha senha +
    + +
    +
    +
    +
    © Copyright - SIAP - Sistema de Imagens Anatomopatológicas
    +
    + + \ No newline at end of file diff --git a/manager/routines/system/routines.php b/manager/routines/system/routines.php new file mode 100644 index 0000000..77a02f7 --- /dev/null +++ b/manager/routines/system/routines.php @@ -0,0 +1,29 @@ +get("routine"); + +switch($routine){ + case "login": + $profile = new Profile(); + + if ($profile->login()) { + redir("../"); + } else { + redir("login.php?r=1"); + } + break; + case "logout": + $profile = new Profile(); + + $profile->logout(); + + redir("login.php"); + break; + case "forget": + $profile = new Profile(); + $retorno = $profile->forgotPass($input->post('email')); + redir("login.php?f=".$retorno); + break; +} +?> \ No newline at end of file diff --git a/manager/routines/zoom.php b/manager/routines/zoom.php new file mode 100644 index 0000000..498cee5 --- /dev/null +++ b/manager/routines/zoom.php @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/nusoap/lib/class.nusoap_base.php b/nusoap/lib/class.nusoap_base.php new file mode 100644 index 0000000..4ed92a7 --- /dev/null +++ b/nusoap/lib/class.nusoap_base.php @@ -0,0 +1,996 @@ + +* @author Scott Nichol +* @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 = ""; + 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"; + $this->debug("serialize_val returning $xml"); + return $xml; + } else { + $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val"; + $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"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; + } + break; + case (is_int($val) || is_long($val) || $type == 'int'): + $this->debug("serialize_val: serialize int"); + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$val"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val"; + } + break; + case (is_float($val)|| is_double($val) || $type == 'float'): + $this->debug("serialize_val: serialize float"); + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$val"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; + } + 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"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; + } + 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"; + } else { + $xml .= "<$name$xmlns$type_str$atts>$pXml"; + } + 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.""; + } 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 .= ''; + $xml .= $this->serialize_val($k,'key',false,false,false,false,$use); + $xml .= $this->serialize_val($v,'value',false,false,false,false,$use); + $xml .= ''; + } else { + $xml .= $this->serialize_val($v,$k,false,false,false,false,$use); + } + } + $xml .= ""; + } + 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 = "".$headers.""; + } + // serialize envelope + return + 'soap_defencoding .'"?'.">". + '". + $headers. + "". + $body. + "". + ""; + } + + /** + * 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 diff --git a/nusoap/lib/class.soap_fault.php b/nusoap/lib/class.soap_fault.php new file mode 100644 index 0000000..1515b50 --- /dev/null +++ b/nusoap/lib/class.soap_fault.php @@ -0,0 +1,90 @@ + +* @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 = + 'soap_defencoding.'"?>'. + '\n". + ''. + ''. + $this->serialize_val($this->faultcode, 'faultcode'). + $this->serialize_val($this->faultactor, 'faultactor'). + $this->serialize_val($this->faultstring, 'faultstring'). + $this->serialize_val($this->faultdetail, 'detail'). + ''. + ''. + ''; + return $return_msg; + } +} + +/** + * Backward compatibility + */ +class soap_fault extends nusoap_fault { +} + + +?> \ No newline at end of file diff --git a/nusoap/lib/class.soap_parser.php b/nusoap/lib/class.soap_parser.php new file mode 100644 index 0000000..f6932aa --- /dev/null +++ b/nusoap/lib/class.soap_parser.php @@ -0,0 +1,643 @@ + +* @author Scott Nichol +* @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, '', $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 .= ""; + } + } elseif($pos >= $this->root_struct){ + $this->document .= ""; + } + // 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 diff --git a/nusoap/lib/class.soap_server.php b/nusoap/lib/class.soap_server.php new file mode 100644 index 0000000..4f1321d --- /dev/null +++ b/nusoap/lib/class.soap_server.php @@ -0,0 +1,1127 @@ + +* @author Scott Nichol +* @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 = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; + } else { + $payload = '<'.$this->methodname.'Response>'.$return_val.'methodname.'Response>'; + } + } else { + if ($this->methodURI) { + $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; + } else { + $payload = '<'.$this->methodname.'Response>'.$return_val.'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 = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'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 .= ""; + } + $this->outgoing_headers[] = "Content-Encoding: gzip"; + $payload = gzencode($payload); + } else { + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= ""; + } + } + } 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 .= ""; + } + $this->outgoing_headers[] = "Content-Encoding: deflate"; + $payload = gzdeflate($payload); + } else { + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= ""; + } + } + } + } + //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 diff --git a/nusoap/lib/class.soap_transport_http.php b/nusoap/lib/class.soap_transport_http.php new file mode 100644 index 0000000..4698209 --- /dev/null +++ b/nusoap/lib/class.soap_transport_http.php @@ -0,0 +1,1307 @@ + +* @author Scott Nichol +* @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 "
    \nde-chunked:\n---------------\n$data\n\n---------------\n
    "; + // 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.'
    '; + // 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
    "; + } + $this->debug($err); + $this->setError($err); + curl_close($this->ch); + return false; + } else { + //echo '
    ';
    +			//var_dump(curl_getinfo($this->ch));
    +			//echo '
    '; + } + // 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 "\nde-inflated:\n---------------\n$data\n-------------\n"; + // 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 diff --git a/nusoap/lib/class.soap_val.php b/nusoap/lib/class.soap_val.php new file mode 100644 index 0000000..4438f5c --- /dev/null +++ b/nusoap/lib/class.soap_val.php @@ -0,0 +1,107 @@ + +* @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 diff --git a/nusoap/lib/class.soapclient.php b/nusoap/lib/class.soapclient.php new file mode 100644 index 0000000..6944c2a --- /dev/null +++ b/nusoap/lib/class.soapclient.php @@ -0,0 +1,991 @@ +call( string methodname [ ,array parameters] ); +* +* // bye bye client +* unset($soapclient); +* +* @author Dietrich Ayala +* @author Scott Nichol +* @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 . + ""; + } else { + $payload = "<$operation>" . $payload . ""; + } + } else { + $this->debug("wrapping RPC request with encoded method element"); + if ($namespace) { + $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" . + $payload . + ""; + } else { + $payload = "<$operation>" . + $payload . + ""; + } + } + } + // 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
    "); + } + 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 { + } +} +?> diff --git a/nusoap/lib/class.wsdl.php b/nusoap/lib/class.wsdl.php new file mode 100644 index 0000000..6d2a693 --- /dev/null +++ b/nusoap/lib/class.wsdl.php @@ -0,0 +1,1938 @@ + +* @author Scott Nichol +* @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 = ' + NuSOAP: '.$this->serviceName.' + + + + +
    +

    +
    '.$this->serviceName.'
    + +
    '; + 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 .= "\nnamespaces 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 .= ''; + } else { + $xml .= ''; + } + } + } + } + // types + if (count($this->schemas)>=1) { + $xml .= "\n\n"; + foreach ($this->schemas as $ns => $list) { + foreach ($list as $xs) { + $xml .= $xs->serializeSchema(); + } + } + $xml .= ''; + } + // messages + if (count($this->messages) >= 1) { + foreach($this->messages as $msgName => $msgParts) { + $xml .= "\n'; + if(is_array($msgParts)){ + foreach($msgParts as $partName => $partType) { + // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'
    '; + if (strpos($partType, ':')) { + $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType)); + } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) { + // print 'checking typemap: '.$this->XMLSchemaVersion.'
    '; + $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" . ' '; + } + } + $xml .= '
    '; + } + } + // bindings & porttypes + if (count($this->bindings) >= 1) { + $binding_xml = ''; + $portType_xml = ''; + foreach($this->bindings as $bindingName => $attrs) { + $binding_xml .= "\n'; + $binding_xml .= "\n" . ' '; + $portType_xml .= "\n'; + foreach($attrs['operations'] as $opName => $opParts) { + $binding_xml .= "\n" . ' '; + $binding_xml .= "\n" . ' '; + if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') { + $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"'; + } else { + $enc_style = ''; + } + $binding_xml .= "\n" . ' '; + if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') { + $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"'; + } else { + $enc_style = ''; + } + $binding_xml .= "\n" . ' '; + $binding_xml .= "\n" . ' '; + $portType_xml .= "\n" . ' ' . htmlspecialchars($opParts['documentation']) . ''; + } + $portType_xml .= "\n" . ' '; + $portType_xml .= "\n" . ' '; + $portType_xml .= "\n" . ' '; + } + $portType_xml .= "\n" . ''; + $binding_xml .= "\n" . ''; + } + $xml .= $portType_xml . $binding_xml; + } + // services + $xml .= "\nserviceName . '">'; + if (count($this->ports) >= 1) { + foreach($this->ports as $pName => $attrs) { + $xml .= "\n" . ' '; + $xml .= "\n" . ' '; + $xml .= "\n" . ' '; + } + } + $xml .= "\n" . ''; + return $xml . "\n"; + } + + /** + * 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"; + } else { + $xml = "<$name$elementNS>$value"; + } + } else { + $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; + } + $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 .= ''; + $contents .= $this->serialize_val($k,'key',false,false,false,false,$use); + $contents .= $this->serialize_val($v,'value',false,false,false,false,$use); + $contents .= ''; + } + if ($use == 'literal') { + if ($forceType) { + $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents"; + } else { + $xml = "<$name>$contents"; + } + } else { + $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents"; + } + $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 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 .= ""; + } 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 + .""; + } 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 + .""; + } + } 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"; + } else { + $xml = "<$name$elementNS>$value"; + } + } else { + $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; + } + } + $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 diff --git a/nusoap/lib/class.wsdlcache.php b/nusoap/lib/class.wsdlcache.php new file mode 100644 index 0000000..9824bb3 --- /dev/null +++ b/nusoap/lib/class.wsdlcache.php @@ -0,0 +1,209 @@ + +* @author Ingo Fischer +* @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 { +} +?> diff --git a/nusoap/lib/class.xmlschema.php b/nusoap/lib/class.xmlschema.php new file mode 100644 index 0000000..02866bf --- /dev/null +++ b/nusoap/lib/class.xmlschema.php @@ -0,0 +1,973 @@ + +* @author Scott Nichol +* @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 + // + // + // + // + // + 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 + // + // + // + // + // + 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 + // + // + // + // + // + 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." \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." \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." \n"; + } + } + // finalize complex type + if($contentStr != ''){ + $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." \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 .= " \n "; + } + } + // 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."\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
    "; + return $this->typemap[$ns][$type]; + } elseif(isset($this->complexTypes[$type])){ + //print "getting type '$type' and ns $ns from complexTypes array
    "; + 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
    "; + 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 .= ""; + } elseif($typeDef['typeClass'] == 'element') { + $str .= ">"; + } 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 .= ''; + foreach($typeDef['elements'] as $child => $childDef){ + $buffer .= " + + "; + } + $buffer .= '
    $childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):
    '; + // if array + } elseif($typeDef['phpType'] == 'array'){ + $buffer .= ''; + for($i=0;$i < 3; $i++){ + $buffer .= " + + "; + } + $buffer .= '
    array item (type: $typeDef[arrayType]):
    '; + // if scalar + } else { + $buffer .= ""; + } + } else { + $buffer .= ""; + } + 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 diff --git a/nusoap/lib/nusoap.php b/nusoap/lib/nusoap.php new file mode 100644 index 0000000..4973532 --- /dev/null +++ b/nusoap/lib/nusoap.php @@ -0,0 +1,8148 @@ + +* @author Scott Nichol +* @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 = ""; + 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"; + $this->debug("serialize_val returning $xml"); + return $xml; + } else { + $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val"; + $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"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; + } + break; + case (is_int($val) || is_long($val) || $type == 'int'): + $this->debug("serialize_val: serialize int"); + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$val"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val"; + } + break; + case (is_float($val)|| is_double($val) || $type == 'float'): + $this->debug("serialize_val: serialize float"); + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$val"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; + } + 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"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; + } + 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"; + } else { + $xml .= "<$name$xmlns$type_str$atts>$pXml"; + } + 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.""; + } 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 .= ''; + $xml .= $this->serialize_val($k,'key',false,false,false,false,$use); + $xml .= $this->serialize_val($v,'value',false,false,false,false,$use); + $xml .= ''; + } else { + $xml .= $this->serialize_val($v,$k,false,false,false,false,$use); + } + } + $xml .= ""; + } + 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 = "".$headers.""; + } + // serialize envelope + return + 'soap_defencoding .'"?'.">". + '". + $headers. + "". + $body. + "". + ""; + } + + /** + * 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); +} + +?> +* @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 = + 'soap_defencoding.'"?>'. + '\n". + ''. + ''. + $this->serialize_val($this->faultcode, 'faultcode'). + $this->serialize_val($this->faultactor, 'faultactor'). + $this->serialize_val($this->faultstring, 'faultstring'). + $this->serialize_val($this->faultdetail, 'detail'). + ''. + ''. + ''; + return $return_msg; + } +} + +/** + * Backward compatibility + */ +class soap_fault extends nusoap_fault { +} + +?> +* @author Scott Nichol +* @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 + // + // + // + // + // + 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 + // + // + // + // + // + 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 + // + // + // + // + // + 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." \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." \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." \n"; + } + } + // finalize complex type + if($contentStr != ''){ + $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." \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 .= " \n "; + } + } + // 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."\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
    "; + return $this->typemap[$ns][$type]; + } elseif(isset($this->complexTypes[$type])){ + //print "getting type '$type' and ns $ns from complexTypes array
    "; + 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
    "; + 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 .= ""; + } elseif($typeDef['typeClass'] == 'element') { + $str .= ">"; + } 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 .= ''; + foreach($typeDef['elements'] as $child => $childDef){ + $buffer .= " + + "; + } + $buffer .= '
    $childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):
    '; + // if array + } elseif($typeDef['phpType'] == 'array'){ + $buffer .= ''; + for($i=0;$i < 3; $i++){ + $buffer .= " + + "; + } + $buffer .= '
    array item (type: $typeDef[arrayType]):
    '; + // if scalar + } else { + $buffer .= ""; + } + } else { + $buffer .= ""; + } + 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 { +} + +?> +* @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; + } +} + + + +?> +* @author Scott Nichol +* @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 "
    \nde-chunked:\n---------------\n$data\n\n---------------\n
    "; + // 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.'
    '; + // 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
    "; + } + $this->debug($err); + $this->setError($err); + curl_close($this->ch); + return false; + } else { + //echo '
    ';
    +			//var_dump(curl_getinfo($this->ch));
    +			//echo '
    '; + } + // 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 "\nde-inflated:\n---------------\n$data\n-------------\n"; + // 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; + } +} + +?> +* @author Scott Nichol +* @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 = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; + } else { + $payload = '<'.$this->methodname.'Response>'.$return_val.'methodname.'Response>'; + } + } else { + if ($this->methodURI) { + $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; + } else { + $payload = '<'.$this->methodname.'Response>'.$return_val.'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 = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'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 .= ""; + } + $this->outgoing_headers[] = "Content-Encoding: gzip"; + $payload = gzencode($payload); + } else { + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= ""; + } + } + } 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 .= ""; + } + $this->outgoing_headers[] = "Content-Encoding: deflate"; + $payload = gzdeflate($payload); + } else { + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= ""; + } + } + } + } + //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 { +} + +?> +* @author Scott Nichol +* @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 = ' + NuSOAP: '.$this->serviceName.' + + + + +
    +

    +
    '.$this->serviceName.'
    + +
    '; + 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 .= "\nnamespaces 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 .= ''; + } else { + $xml .= ''; + } + } + } + } + // types + if (count($this->schemas)>=1) { + $xml .= "\n\n"; + foreach ($this->schemas as $ns => $list) { + foreach ($list as $xs) { + $xml .= $xs->serializeSchema(); + } + } + $xml .= ''; + } + // messages + if (count($this->messages) >= 1) { + foreach($this->messages as $msgName => $msgParts) { + $xml .= "\n'; + if(is_array($msgParts)){ + foreach($msgParts as $partName => $partType) { + // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'
    '; + if (strpos($partType, ':')) { + $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType)); + } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) { + // print 'checking typemap: '.$this->XMLSchemaVersion.'
    '; + $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" . ' '; + } + } + $xml .= '
    '; + } + } + // bindings & porttypes + if (count($this->bindings) >= 1) { + $binding_xml = ''; + $portType_xml = ''; + foreach($this->bindings as $bindingName => $attrs) { + $binding_xml .= "\n'; + $binding_xml .= "\n" . ' '; + $portType_xml .= "\n'; + foreach($attrs['operations'] as $opName => $opParts) { + $binding_xml .= "\n" . ' '; + $binding_xml .= "\n" . ' '; + if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') { + $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"'; + } else { + $enc_style = ''; + } + $binding_xml .= "\n" . ' '; + if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') { + $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"'; + } else { + $enc_style = ''; + } + $binding_xml .= "\n" . ' '; + $binding_xml .= "\n" . ' '; + $portType_xml .= "\n" . ' ' . htmlspecialchars($opParts['documentation']) . ''; + } + $portType_xml .= "\n" . ' '; + $portType_xml .= "\n" . ' '; + $portType_xml .= "\n" . ' '; + } + $portType_xml .= "\n" . ''; + $binding_xml .= "\n" . ''; + } + $xml .= $portType_xml . $binding_xml; + } + // services + $xml .= "\nserviceName . '">'; + if (count($this->ports) >= 1) { + foreach($this->ports as $pName => $attrs) { + $xml .= "\n" . ' '; + $xml .= "\n" . ' '; + $xml .= "\n" . ' '; + } + } + $xml .= "\n" . ''; + return $xml . "\n"; + } + + /** + * 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"; + } else { + $xml = "<$name$elementNS>$value"; + } + } else { + $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; + } + $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 .= ''; + $contents .= $this->serialize_val($k,'key',false,false,false,false,$use); + $contents .= $this->serialize_val($v,'value',false,false,false,false,$use); + $contents .= ''; + } + if ($use == 'literal') { + if ($forceType) { + $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents"; + } else { + $xml = "<$name>$contents"; + } + } else { + $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents"; + } + $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 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 .= ""; + } 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 + .""; + } 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 + .""; + } + } 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"; + } else { + $xml = "<$name$elementNS>$value"; + } + } else { + $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; + } + } + $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; + } +} +?> +* @author Scott Nichol +* @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, '', $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 .= ""; + } + } elseif($pos >= $this->root_struct){ + $this->document .= ""; + } + // 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 { +} + +?>call( string methodname [ ,array parameters] ); +* +* // bye bye client +* unset($soapclient); +* +* @author Dietrich Ayala +* @author Scott Nichol +* @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 . + ""; + } else { + $payload = "<$operation>" . $payload . ""; + } + } else { + $this->debug("wrapping RPC request with encoded method element"); + if ($namespace) { + $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" . + $payload . + ""; + } else { + $payload = "<$operation>" . + $payload . + ""; + } + } + } + // 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
    "); + } + 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 { + } +} +?> diff --git a/nusoap/lib/nusoapmime.php b/nusoap/lib/nusoapmime.php new file mode 100644 index 0000000..6493863 --- /dev/null +++ b/nusoap/lib/nusoapmime.php @@ -0,0 +1,501 @@ + +* @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 +* @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 { +} + +?> diff --git a/nusoap/samples/client1.php b/nusoap/samples/client1.php new file mode 100644 index 0000000..ffc6362 --- /dev/null +++ b/nusoap/samples/client1.php @@ -0,0 +1,51 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; + echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; + 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 '

    Fault (Expect - The request contains an invalid SOAP body)

    '; print_r($result); echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    '; print_r($result); echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/client2.php b/nusoap/samples/client2.php new file mode 100644 index 0000000..599a8cc --- /dev/null +++ b/nusoap/samples/client2.php @@ -0,0 +1,57 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; + echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; + 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 '

    Fault

    '; print_r($result); echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    '; print_r($result); echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/client3.php b/nusoap/samples/client3.php new file mode 100644 index 0000000..83f22cd --- /dev/null +++ b/nusoap/samples/client3.php @@ -0,0 +1,56 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; + echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; + 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 '

    Fault

    '; print_r($result); echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    '; print_r($result); echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/getfile1client.php b/nusoap/samples/getfile1client.php new file mode 100644 index 0000000..45e024d --- /dev/null +++ b/nusoap/samples/getfile1client.php @@ -0,0 +1,37 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$result = $client->call('getFile', array('filename' => 'getfile1.php')); +if ($client->fault) { + echo '

    Fault

    '; print_r($result); echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    ' . htmlspecialchars($result, ENT_QUOTES) . '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/getfile2client.php b/nusoap/samples/getfile2client.php new file mode 100644 index 0000000..c5f7c0b --- /dev/null +++ b/nusoap/samples/getfile2client.php @@ -0,0 +1,37 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$result = $client->call('getFile', array('filename' => 'getfile2.php')); +if ($client->fault) { + echo '

    Fault

    '; print_r($result); echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    ' . htmlspecialchars($result, ENT_QUOTES) . '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/index.html b/nusoap/samples/index.html new file mode 100644 index 0000000..f657bf3 --- /dev/null +++ b/nusoap/samples/index.html @@ -0,0 +1,67 @@ + + + +NuSOAP Samples + + + +

    NuSOAP Samples

    +

    +These links allow you to launch sample clients. As of 26 April 2010, most of the links to commercial services no longer work. +

    +
    +Amazon endpoint (Fault expected)
    +Amazon endpoint
    +Google endpoint (you must have a key)
    +MIME Attachment
    +SSL endpoint
    +Stock quote WSDL
    +Amazon WSDL
    +Hello WSDL (PHP function)
    +Hello WSDL (PHP instance method)
    +Hello WSDL (PHP class method)
    +Hello WSDL with pre-formed parameter XML
    +Hello WSDL (rpc/literal version)
    +Interop WSDL
    +Price quote WSDL (uses wsdlcache)
    +Google WSDL (you must have WSDL file local)
    +MapPoint WSDL #1 (you must have a username/password)
    +MapPoint WSDL #2 (you must have a username/password)
    +MapPoint WSDL #3 (you must have a username/password)
    +Country list WSDL
    +Hello WSDL (document/literal version)
    +Amazon E-Commerce Service (ItemLookup by node)
    +Amazon E-Commerce Service (ItemSearch by node)
    +Amazon E-Commerce Service (ItemSearch by keyword)
    +Amazon E-Commerce Service (ListLookup)
    +Amazon E-Commerce Service (ListSearch)
    +Amazon E-Commerce Service (CartCreate)
    +Maintain a Session
    +Via Michelin
    +UTF-8 Character Encoding
    +Get a file #1 (uses base64Binary)
    +Get a file #2 (uses base64Binary; service uses external WSDL file)
    +
    + + +
    Use cURL?
    +

    +If you access the Internet through a proxy, provide the proxy +information below. +

    + + + + + +
    Proxy Host:
    Proxy Port:
    Proxy Username:
    Proxy Password:
    +
    + + diff --git a/nusoap/samples/mimeclient.php b/nusoap/samples/mimeclient.php new file mode 100644 index 0000000..6cb1d96 --- /dev/null +++ b/nusoap/samples/mimeclient.php @@ -0,0 +1,53 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$client->setUseCurl($useCURL); +$client->setHTTPEncoding('deflate, gzip'); +$cid = $client->addAttachment('', 'mimeclient.php'); +$result = $client->call('hello', array('name' => 'Scott')); +if ($client->fault) { + echo '

    Fault

    '; print_r($result); echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    '; print_r($result); echo '
    '; + echo '

    Attachments

    ';
    +		$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 '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    ResponseData

    ' . htmlspecialchars($client->responseData, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/sslclient.php b/nusoap/samples/sslclient.php new file mode 100644 index 0000000..8f6cab2 --- /dev/null +++ b/nusoap/samples/sslclient.php @@ -0,0 +1,37 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$result = $client->call('getVersion', array(), 'http://arcweb.esri.com/v2', 'getVersion'); +if ($client->fault) { + echo '

    Fault

    '; print_r($result); echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    '; print_r($result); echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient1.php b/nusoap/samples/wsdlclient1.php new file mode 100644 index 0000000..60f3c4e --- /dev/null +++ b/nusoap/samples/wsdlclient1.php @@ -0,0 +1,47 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +// 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 '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient10.php b/nusoap/samples/wsdlclient10.php new file mode 100644 index 0000000..dfd14b7 --- /dev/null +++ b/nusoap/samples/wsdlclient10.php @@ -0,0 +1,44 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$client->setUseCurl($useCURL); +$result = $client->call('getCountries', array(), '', '', false, true); +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient11.php b/nusoap/samples/wsdlclient11.php new file mode 100644 index 0000000..44561f5 --- /dev/null +++ b/nusoap/samples/wsdlclient11.php @@ -0,0 +1,50 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$client->setUseCurl($useCURL); +$person = array('firstname' => 'Willi', 'age' => 22, 'gender' => 'male'); +$name = array('name' => $person); +$result = $client->call('hello', $name); +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    ';
    +		print_r($result);
    +	echo '
    '; + } +} +echo '

    Request

    '; +echo '
    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    '; +echo '
    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    '; +echo '
    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient12.php b/nusoap/samples/wsdlclient12.php new file mode 100644 index 0000000..7947328 --- /dev/null +++ b/nusoap/samples/wsdlclient12.php @@ -0,0 +1,225 @@ +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 '

    Constructor error

    ' . $err . '
    '; +} + +$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 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 '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient13.php b/nusoap/samples/wsdlclient13.php new file mode 100644 index 0000000..3bd086e --- /dev/null +++ b/nusoap/samples/wsdlclient13.php @@ -0,0 +1,99 @@ +Constructor'; +$client = new nusoap_client('http://www.scottnichol.com/samples/session.php?wsdl', true, + $proxyhost, $proxyport, $proxyusername, $proxypassword); +$err = $client->getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +$client->clearDebug(); +// A persistent connection is *optional*, *not* necessary +$client->useHTTPPersistentConnection(); +echo '

    GetSessionID

    '; +$result = $client->call('GetSessionID', array()); +// Check for a fault +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +$client->clearDebug(); +echo '

    SetSession

    '; +$result = $client->call('SetSession', array('name' => 'testvalue', 'value' => 'it works')); +// Check for a fault +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +$client->clearDebug(); +echo '

    GetSession

    '; +$result = $client->call('GetSession', array('name' => 'testvalue')); +// Check for a fault +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient14.php b/nusoap/samples/wsdlclient14.php new file mode 100644 index 0000000..06469fe --- /dev/null +++ b/nusoap/samples/wsdlclient14.php @@ -0,0 +1,83 @@ +get($wsdlurl); +if (is_null($wsdl)) { + $wsdl = new wsdl($wsdlurl, + $proxyhost, $proxyport, $proxyusername, $proxypassword, + 0, 30, null, $useCURL); + $err = $wsdl->getError(); + if ($err) { + echo '

    WSDL Constructor error

    ' . $err . '
    '; + echo '

    Debug

    ' . htmlspecialchars($wsdl->getDebug(), ENT_QUOTES) . '
    '; + 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 '

    Constructor error

    ' . $err . '
    '; + echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; + 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 '

    Fault (Expect - AUTHENTIFICATION)

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient15.php b/nusoap/samples/wsdlclient15.php new file mode 100644 index 0000000..d4051f4 --- /dev/null +++ b/nusoap/samples/wsdlclient15.php @@ -0,0 +1,60 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; + echo '

    Debug

    '; + echo '
    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; + 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 '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + $err = $client->getError(); + if ($err) { + echo '

    Error

    ' . $err . '
    '; + } else { + echo '

    Result

    ';
    +		// 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 '
    '; + } +} +echo '

    Request

    '; +echo '
    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    '; +echo '
    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    '; +echo '
    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient2.php b/nusoap/samples/wsdlclient2.php new file mode 100644 index 0000000..119dd67 --- /dev/null +++ b/nusoap/samples/wsdlclient2.php @@ -0,0 +1,58 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; + 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 '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $proxy->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($proxy->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($proxy->response, ENT_QUOTES) . '
    '; +echo '

    Client Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +echo '

    Proxy Debug

    ' . htmlspecialchars($proxy->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient3.php b/nusoap/samples/wsdlclient3.php new file mode 100644 index 0000000..9104de6 --- /dev/null +++ b/nusoap/samples/wsdlclient3.php @@ -0,0 +1,56 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$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 '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient3b.php b/nusoap/samples/wsdlclient3b.php new file mode 100644 index 0000000..dc289a0 --- /dev/null +++ b/nusoap/samples/wsdlclient3b.php @@ -0,0 +1,46 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$params = 'Willi22male'; +$result = $client->call('hello', $params); +// Check for a fault +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient3c.php b/nusoap/samples/wsdlclient3c.php new file mode 100644 index 0000000..ad7144d --- /dev/null +++ b/nusoap/samples/wsdlclient3c.php @@ -0,0 +1,46 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$person = array('firstname' => 'Willi', 'age' => 22, 'gender' => 'male'); +$result = $client->call('hello', array('person' => $person)); +// Check for a fault +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient4.php b/nusoap/samples/wsdlclient4.php new file mode 100644 index 0000000..bc8457d --- /dev/null +++ b/nusoap/samples/wsdlclient4.php @@ -0,0 +1,176 @@ +'; + echo ''; + echo ''; + echo ''; + echo ''; + echo 'Method:

    '; + echo 'Null parameter?
    '; + echo 'Empty array?

    '; + echo ''; + echo ''; + 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 '

    Constructor error

    ' . $err . '
    '; +} +$client->useHTTPPersistentConnection(); +echo '

    Execute ' . $method . '

    '; +$result = $client->call($method, $params); +// Check for a fault +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r((!is_bool($result)) ? $result : ($result ? 'true' : 'false'));
    +		echo '
    '; + // And execute again to test persistent connection + echo '

    Execute ' . $method . ' again to test persistent connection (see debug)

    '; + $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 '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient5.php b/nusoap/samples/wsdlclient5.php new file mode 100644 index 0000000..0691255 --- /dev/null +++ b/nusoap/samples/wsdlclient5.php @@ -0,0 +1,69 @@ +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 '

    WSDL Constructor error (Expect - 404 Not Found)

    ' . $err . '
    '; + echo '

    Debug

    ' . htmlspecialchars($wsdl->getDebug(), ENT_QUOTES) . '
    '; + 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 '

    Constructor error

    ' . $err . '
    '; + exit(); +} +$client->setUseCurl($useCURL); +$params = array('isbn' => '0060188782'); +$result = $client->call('getPrice', $params); +// Check for a fault +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Cache Debug

    ' . htmlspecialchars($cache->getDebug(), ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient6.php b/nusoap/samples/wsdlclient6.php new file mode 100644 index 0000000..002b9c7 --- /dev/null +++ b/nusoap/samples/wsdlclient6.php @@ -0,0 +1,66 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$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 '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient7.php b/nusoap/samples/wsdlclient7.php new file mode 100644 index 0000000..48be135 --- /dev/null +++ b/nusoap/samples/wsdlclient7.php @@ -0,0 +1,51 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$client->setUseCurl($useCURL); +$client->loadWSDL(); +$client->setCredentials($username, $password, 'digest'); +$result = $client->call('GetVersionInfo', array()); +// Check for a fault +if ($client->fault) { + echo '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient8.php b/nusoap/samples/wsdlclient8.php new file mode 100644 index 0000000..e4e4905 --- /dev/null +++ b/nusoap/samples/wsdlclient8.php @@ -0,0 +1,74 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$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 '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/nusoap/samples/wsdlclient9.php b/nusoap/samples/wsdlclient9.php new file mode 100644 index 0000000..8b2a695 --- /dev/null +++ b/nusoap/samples/wsdlclient9.php @@ -0,0 +1,63 @@ +getError(); +if ($err) { + echo '

    Constructor error

    ' . $err . '
    '; +} +$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 '

    Fault

    ';
    +	print_r($result);
    +	echo '
    '; +} else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + } else { + // Display the result + echo '

    Result

    ';
    +		print_r($result);
    +		echo '
    '; + } +} +echo '

    Request

    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; +echo '

    Debug

    ' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '
    '; +?> diff --git a/php_test/index.php b/php_test/index.php new file mode 100644 index 0000000..cd0ccfd --- /dev/null +++ b/php_test/index.php @@ -0,0 +1,3 @@ + diff --git a/siacc_wsclient.php b/siacc_wsclient.php new file mode 100644 index 0000000..8e5620f --- /dev/null +++ b/siacc_wsclient.php @@ -0,0 +1,91 @@ +getError(); + if ($err) { + // Display the error + echo '

    Constructor error

    ' . $err . '
    '; + // 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 '

    Fault

    ';
    +        print_r($result);
    +        echo '
    '; + $result = NULL; + } else { + // Check for errors + $err = $client->getError(); + if ($err) { + // Display the error + echo '

    Error

    ' . $err . '
    '; + $result = NULL; + } + } + return $result; +} + +function print_wordlist($wordlist){ + foreach($wordlist as $word){ + echo '

    '.$word['id'].' => '.$word['nome'].'

    '; + } +} + + +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 '

    Tipos de busca para Imagem

    ';
    +    print_wordlist($search_types);
    +    echo '
    '; +} + +foreach ($search_types as &$search_type) { + $result = call_soap_method($client, 'get_search_type_keywords', array('search_type' => $search_type['id'])); + if ($result) { + echo '

    Palavras-chave para '.$search_type['nome'].':

    ';
    +        print_wordlist($result);
    +        echo '
    '; + } +} + + +$search_results = call_soap_method($client, 'search', array('search_request' => array( + 'palavra'=>'abscesso', 'sistema'=>8, 'procedencia'=>15, 'patologia'=>''))); + +if ($search_results) { + echo '

    Resultados da busca para "abscesso" no sistema nervoso:

    ';
    +    echo 'Mostrando ' .sizeof($search_results).' resultados. 

    '; + foreach($search_results as &$result){ + echo 'Nome: '.$result['nome'].'
    '; + echo 'Sistema: '.$result['sistema'].'
    '; + echo 'Procedencia: '.$result['procedencia'].'
    '; + echo 'Patologia: '.$result['patologia'].'
    '; + echo 'URL: '.$result['url'].'
    '; + echo '
    '; + + } + echo '
    '; +} + + +// Display the request and response +echo '

    Request

    '; +echo '
    ' . htmlspecialchars($client->request, ENT_QUOTES) . '
    '; +echo '

    Response

    '; +echo '
    ' . htmlspecialchars($client->response, ENT_QUOTES) . '
    '; + +?> diff --git a/siap_ws.php b/siap_ws.php new file mode 100644 index 0000000..12a0320 --- /dev/null +++ b/siap_ws.php @@ -0,0 +1,126 @@ +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); +?> diff --git a/siap_ws_utils.php b/siap_ws_utils.php new file mode 100644 index 0000000..cdb3a3c --- /dev/null +++ b/siap_ws_utils.php @@ -0,0 +1,114 @@ + $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; +} +?> diff --git a/site/content/busca/index.php b/site/content/busca/index.php new file mode 100644 index 0000000..697f503 --- /dev/null +++ b/site/content/busca/index.php @@ -0,0 +1,14 @@ + + + + + + + <?= $cfg["site_title"]; ?> + + + [Conteúdo] + + diff --git a/site/content/casosdeestudo/index.php b/site/content/casosdeestudo/index.php new file mode 100644 index 0000000..68d830b --- /dev/null +++ b/site/content/casosdeestudo/index.php @@ -0,0 +1,309 @@ +config('classes/CasoEstudo.php'); +$o_casoEstudo = new CasoEstudo(); + +$arrProfessor = $o_helper->findProfesores(true); +$arrProcedencia = $o_helper->findProcedencias(true); +$arrSistema = $o_helper->findSistemas(true); +$arrPatologia = $o_helper->findPatologias(true); +$arrEspecialidade = $o_helper->findEspecialidade(true); + +$letra = $input->get('letra'); +$palavraChave = $input->get('palavrachave'); +$professor = $input->get('professor'); +$especialidade = $input->get('especialidade'); +$sistema = $input->get('sistema'); +$patologia = $input->get('patologia'); +$boneco = $input->get("boneco"); +$codigo = $input->get("codigo"); +if($codigo == 'Código'){ + $codigo = ''; +} +$pagina = $input->get("pagina"); +if($pagina == ""){ + $pagina = 1; +} + +$total = 0; +if($o_helper->hasFilter()){ + if($o_helper->hasFilter(false)){ + $base = '?palavrachave='.$palavraChave.'&professor='.$professor.'&especialidade='.$especialidade.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco.'&codigo='.$codigo; + $rowsCasoEstudo = $o_casoEstudo->simpleSeach($palavraChave,$professor,$especialidade,$sistema,$patologia,$boneco,$codigo); + if(($rowsCasoEstudo->EOF) && ($palavraChave != '')){ + $arr_palavras = $o_helper->findPalavraAproximada($palavraChave); + //print_r2($arr_palavras); + $segestoes = ''; + if(sizeof($arr_palavras[0]) > 0){ + for($x=0;$x".$arr_palavras[0][$x].", "; + } + } + if($segestoes != ""){ + $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2); + } + } + $rowsCasoEstudo = $o_casoEstudo->complexSeach($arr_palavras,$professor,$especialidade,$sistema,$patologia,$boneco,$codigo); + } + } else { + $base = '?letra='.$letra; + $rowsCasoEstudo = $o_casoEstudo->searchLetter($letra); + } + $total = $rowsCasoEstudo->recordCount(); + $rowsCasoEstudo->pagesize = $o_casoEstudo->filtro_resultado; + $rowsCasoEstudo->page($pagina); +} + +$selected = 'casosdeestudo'; +?> + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + +
    + + + + + +
    +
    + +
    +

    + +
    + + + + +
    + Listando: resultado 1)?'s':'');?>.
    + hasFilter(false)){?> + +
    Palavra-chave: + + +
    Professor: + + +
    Especialidade: + + +
    Sistema: + + +
    Patologia: + + +
    Topografia: findTopografiaById($boneco);?> + + +
    Código: + + +
    + + + Índice: + +
    +
    + +
    +
    + + + + + + + + + + + + + + + + +
    + getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?> +
    + +
    + +
    +
    + getSelect($arrProfessor,'Professor','CMB0','professor',' style="width:360px;" ');?> +
    + Busca Avançada +
    + + + + + +
    + getBoneco('Boneco','TXT0','boneco');?> + +
    + getInput('Código','TXT0','codigo',' style="width:200px;" ');?> +
    +
    + getSelect($arrEspecialidade,'Especialidade','CMB0','especialidade',' style="width:210px;" ');?> +
    +
    + getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?> +
    +
    + getSelect($arrPatologia,'Patologia','CMB0','patologia',' style="width:210px;" ');?> +
    +
    + +
    +
    +
    +
    +
    +
    + + + + + + + + + EOF){?> + + + + + + + + + + + + + + + + + pagecount > 1){?> + + + + +
    + +
     
    +
    + getAlfabeto();;?> +
    + Nenhum registro encontrado. +
    +
     
    +
    + getResultado($base);?> + getOrdenar($base);?> +
    + + EOF){ + $url = ' onclick="javascript:url(\'view.php?id='.$input->encode($rowsCasoEstudo->fields('id')).'\');" ';?> + + + + moveNext(); + }?> +
    + + + + + + + + + + + + + + + + +
    + fields('nome');?> fields('codigo') == '')?'':('('.($rowsCasoEstudo->fields('codigo')).')'));?> +
    + fields('especialidade');?> | fields('professor');?> +
    + fields('texto');?> +
    + getImgesRelacionadas($rowsCasoEstudo->fields('id'),8);?> +
    + /> +
    +
    +
    +
     
    +
    + Páginas: pagecount; + //pagina atual + $actualPage = $pagina; + //baseLink + $pageBaseLink = $base; + //nome do link da pagina (pagina=1) + $pageLinkName = 'pagina'; + include('../../inc/structure/paginacao.php'); + ?> +
    + + + + + + + + +
    + +
     
    +
    + getAlfabeto();;?> +
    + +
    +
    + + + \ No newline at end of file diff --git a/site/content/casosdeestudo/view.php b/site/content/casosdeestudo/view.php new file mode 100644 index 0000000..449a97a --- /dev/null +++ b/site/content/casosdeestudo/view.php @@ -0,0 +1,164 @@ +config('classes/CasoEstudo.php'); +$o_casoEstudo = new CasoEstudo(); +$rowCasoEstudo = $o_casoEstudo->findCasoEstudoById($input->get('id',true)); +if($rowCasoEstudo->EOF){ + redir('index.php'); + die; +} + +$load->manager('core/Profile.php'); +$o_profile = new Profile(); + +$rowsComentario = $o_casoEstudo->findComentariosByIdCasoEstudo($input->get('id',true)); +?> + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + +
    + + + + + EOF){?> + + + + + + + + + + + + +
    +
    + +
    +

    + + + + + + + + + +
    +
    + fields('nome');?> +
    +
    + fields('especialidade');?> +
    +
    + + + + + + + +
    + fields('texto'));?> +
    + orgaosrelacionados($rowCasoEstudo->fields('id'));?> +
    +
    +
    + alt('Imagens Relacionadas');?> /> +
    + getImgesRelacionadas($rowCasoEstudo->fields('id'));?> +
    +
    + alt('Casos de Estudo Relacionados');?> /> +
    + diagnosticosrelacionados($rowCasoEstudo->fields('id'));?> +
    +
    + + + + + EOF){ + if($bg == 'F2F2F2'){ + $bg = 'FFFFFF'; + } else { + $bg = 'F2F2F2'; + }?> + + + + moveNext(); + }?> +
    + +
    +
    + fields('nome');?> +
    + isLogged()){ + if(($o_profile->fields['id'] == 1) || ($o_profile->fields['id'] == $rowCasoEstudo->fields('id_usuario'))){?> + + +
    + fields('comentario'));?> +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    + Comente sobre este caso +
    + getInput('Nome','TXT1','nome',' style="width:270px;" ');?> + + getInput('Comentário','TXT1','comentario',' style="width:620px; height: 51px;" ',true,'textarea');?> +
    + getInput('E-mail','EML1','email',' style="width:270px;" ');?> +
    + +
    +
    +
    + alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" /> +
    +
    + + + \ No newline at end of file diff --git a/site/content/diagnosticos/index.php b/site/content/diagnosticos/index.php new file mode 100644 index 0000000..2c9cf49 --- /dev/null +++ b/site/content/diagnosticos/index.php @@ -0,0 +1,296 @@ +config('classes/Diagnostico.php'); +$o_diagnostico = new Diagnostico(); + +$arrProcedencia = $o_helper->findProcedencias(true); +$arrSistema = $o_helper->findSistemas(true); +$arrPatologia = $o_helper->findPatologias(true); +$arrEspecialidade = $o_helper->findEspecialidade(true); + +$letra = $input->get('letra'); +$palavraChave = $input->get('palavrachave'); +$especialidade = $input->get('especialidade'); +$procedencia = $input->get('procedencia'); +$sistema = $input->get('sistema'); +$patologia = $input->get('patologia'); +$like = $input->get('pp');//0 - qualquer palavra (quebrar em array por espaços) / 1 - todas, não quebra nada +$boneco = $input->get("boneco"); +$pagina = $input->get("pagina"); +if($pagina == ""){ + $pagina = 1; +} + +$total = 0; +if($o_helper->hasFilter()){ + if($o_helper->hasFilter(false)){ + $base = '?palavrachave='.$palavraChave.'&especialidade='.$especialidade.'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco; + $rowsDiagnostico = $o_diagnostico->simpleSeach($palavraChave,$especialidade,$procedencia,$sistema,$patologia,$boneco); + if(($rowsDiagnostico->EOF) && ($palavraChave != '')){ + $arr_palavras = $o_helper->findPalavraAproximada($palavraChave); + //print_r2($arr_palavras); + $segestoes = ''; + if(sizeof($arr_palavras[0]) > 0){ + for($x=0;$x".$arr_palavras[0][$x].", "; + } + } + if($segestoes != ""){ + $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2); + } + } + $rowsDiagnostico = $o_diagnostico->complexSeach($arr_palavras,$procedencia,$sistema,$patologia,$boneco); + } + } else { + $base = '?letra='.$letra; + $rowsDiagnostico = $o_diagnostico->searchLetter($letra); + } + $total = $rowsDiagnostico->recordCount(); + $rowsDiagnostico->pagesize = $o_diagnostico->filtro_resultado; + $rowsDiagnostico->page($pagina); +} +$selected = 'diagnosticos'; +?> + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + +
    + + + + + +
    +
    + +
    +

    + +
    + + + + +
    + Listando: resultado 1)?'s':'');?>.
    + hasFilter(false)){?> + +
    Palavra-chave: + + +
    Especialidade: + + +
    Procedência: + + +
    Sistema: + + +
    Patologia: + + +
    Topografia: findTopografiaById($boneco);?> + + +
    + + + Índice: + +
    +
    + +
    +
    + + + + + + + + + + + + + +
    + getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?> +
    + +
    + +
    +
    + Busca Avançada +
    + + + + + +
    + getBoneco('Boneco','TXT0','boneco');?> + +
    + getSelect($arrEspecialidade,'Especialidade','CMB0','especialidade',' style="width:210px;" ');?> +
    +
    + getSelect($arrProcedencia,'Procedência','CMB0','procedencia',' style="width:210px;" ');?> +
    +
    + getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?> +
    +
    + getSelect($arrPatologia,'Patologia','CMB0','patologia',' style="width:210px;" ');?> +
    +
    + +
    +
    +
    +
    +
    +
    + + +
     
    + + + + + + EOF){?> + + + + + + + + + + + + + + + + + pagecount > 1){?> + + + + +
    + getAlfabeto();;?> +
    + Nenhum registro encontrado. +
    +
     
    +
    + getResultado($base);?> + getOrdenar($base);?> +
    + EOF){ + $url = ' onclick="javascript:url(\'view.php?id='.$input->encode($rowsDiagnostico->fields('id')).'\');" ';?> + + + + +
    + + + + + + + + + + + + + + + + +
    > + fields('nome');?> +
    + fields('especialidade');?>fields('cid10') == '')?'':' | '.$rowsDiagnostico->fields('cid10'));?> +
    > + fields('texto');?> +
    + getImgesRelacionadas($rowsDiagnostico->fields('id'),8);?> +
    + /> +
    +
    + moveNext(); + }?> +
    +
     
    +
    + Páginas: pagecount; + //pagina atual + $actualPage = $pagina; + //baseLink + $pageBaseLink = $base; + //nome do link da pagina (pagina=1) + $pageLinkName = 'pagina'; + include('../../inc/structure/paginacao.php'); + ?> +
    + + + + + + + + +
    + +
     
    +
    + getAlfabeto();;?> +
    + +
    +
    + + + \ No newline at end of file diff --git a/site/content/diagnosticos/view.php b/site/content/diagnosticos/view.php new file mode 100644 index 0000000..eee525b --- /dev/null +++ b/site/content/diagnosticos/view.php @@ -0,0 +1,100 @@ +config('classes/Diagnostico.php'); +$o_diagnostico = new Diagnostico(); +$rowDiagnostico = $o_diagnostico->findDiagnoticoById($input->get('id',true)); +if($rowDiagnostico->EOF){ + redir('index.php'); + die; +} +?> + + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + + +
    + + + + +
    +
    + +
    +

    + + + + + + + + + +
    +
    + fields('nome');?> +
    +
    + fields('especialidade');?> +
    + fields('cid10') != ''){?> +
    + fields('cid10');?> +
    + +
    + + + + + + + + + + +
    + fields('texto'));?> +
    + orgaosrelacionados($rowDiagnostico->fields('id'));?> +
    + alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" /> +
    +
    +
    + alt('Imagens Relacionadas');?> /> +
    + getImgesRelacionadas($rowDiagnostico->fields('id'));?> +
    +
    + alt('Casos de Estudo Relacionados');?> /> +
    + casosdeestudorelacionados($rowDiagnostico->fields('id'));?> +
    +
    +
    + + + \ No newline at end of file diff --git a/site/content/home/index.php b/site/content/home/index.php new file mode 100644 index 0000000..393dd5b --- /dev/null +++ b/site/content/home/index.php @@ -0,0 +1,182 @@ +get('tipobusca') != ''){ + $url = ''; + switch($input->get('tipobusca')){ + case 1: + $url = '../diagnosticos/?palavrachave='.$input->get('palavrachave'); + break; + case 2: + $url = '../orgaos/?palavrachave='.$input->get('palavrachave'); + break; + case 3: + $url = '../necropsias/?palavrachave='.$input->get('palavrachave'); + break; + case 4: + $url = '../casosdeestudo/?palavrachave='.$input->get('palavrachave'); + break; + case 5: + $url = '../imagens/?palavrachave='.$input->get('palavrachave'); + break; + } + $url .= '&grupoorgao='.$input->get('grupoorgao'); + $url .= '&procedencia='.$input->get('procedencia'); + $url .= '&sistema='.$input->get('sistema'); + $url .= '&patologia='.$input->get('patologia'); + $url .= '&boneco='.$input->get('boneco'); + $url .= '&especialidade='.$input->get('especialidade'); + redir($url); + die; +} + +$arrGrupoOrgao = $o_helper->findGrupoOrgao(true); +$arrProcedencia = $o_helper->findProcedencias(true); +$arrSistema = $o_helper->findSistemas(true); +$arrPatologia = $o_helper->findPatologias(true); +$arrEspecialidade = $o_helper->findEspecialidade(true); +?> + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + + +
    + + + + + +
    +   + +
    + + + + + + + + + + + + + +
    + +
    + getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?> +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + + + + + +
    + getBoneco('Boneco','TXT0','boneco');?> + +
    + getSelect($arrGrupoOrgao,'Topografia','CMB0','grupoorgao',' style="width:210px;" ');?> +
    +
    + getSelect($arrProcedencia,'Procedência','CMB0','procedencia',' style="width:210px;" ');?> +
    +
    + getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?> +
    +
    + getSelect($arrPatologia,'Patologia','CMB0','patologia',' style="width:210px;" ');?> +
    +
    + getSelect($arrEspecialidade,'Especialidade','CMB0','especialidade',' style="width:210px;" ');?> +
    +
    + +
    +
    +
    +
    +
    +
    + + + \ No newline at end of file diff --git a/site/content/home/index_colunas.php b/site/content/home/index_colunas.php new file mode 100644 index 0000000..17dfa64 --- /dev/null +++ b/site/content/home/index_colunas.php @@ -0,0 +1,145 @@ +config('classes/Image.php'); +$o_image = new Image(); +$rowsImage = $o_image->findLastImages(); +//print_r2($rowsImage); +?> + + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + +
    + + + + + + + + + +
    + +
    +
    + +
    +
     
    +
    + Rinite +
    +
    + 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 +
    +
    + alt('ver');?> /> +
    +
     
    +
    + Rinite +
    +
    + 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 +
    +
    + alt('ver');?> /> +
    +
     
    +
    + Rinite +
    +
    + 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 +
    +
    + alt('ver');?> /> +
    +
    +
    + +
    +
     
    +
    + EOF){?> + Nenhuma imagem cadastrada. + EOF){ + if($x == 1){ + $style = 'padding-left:20px;padding-right:20px;'; + } else { + $style = ''; + }?> +
    +
    + getImage($rowsImage->fields('id')); + if($src == ''){ + $src = '../../img/olho.jpg'; + }?> + alt($rowsImage->fields('nome'));?> /> +
    +
    + fields('nome');?> +
    +
    + moveNext(); + $x++; + if($x == 3){ + $x = 0; + } + } + }?> +
    +
    +
    + +
    +
     
    +
    + Rinite +
    +
    + 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 +
    +
    + alt('ver');?> /> +
    +
     
    +
    + Rinite +
    +
    + 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 +
    +
    + alt('ver');?> /> +
    +
     
    +
    + Rinite +
    +
    + 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 +
    +
    + alt('ver');?> /> +
    +
    +
    + + + \ No newline at end of file diff --git a/site/content/imagens/index.php b/site/content/imagens/index.php new file mode 100644 index 0000000..a187c73 --- /dev/null +++ b/site/content/imagens/index.php @@ -0,0 +1,286 @@ +config('classes/Imagem.php'); +$o_imagem = new Imagem(); + +$arrProcedencia = $o_helper->findProcedencias(true); +$arrSistema = $o_helper->findSistemas(true); +$arrPatologia = $o_helper->findPatologias(true); + +$letra = $input->get('letra'); +$palavraChave = $input->get('palavrachave'); +$procedencia = $input->get('procedencia'); +$sistema = $input->get('sistema'); +$patologia = $input->get('patologia'); +$like = $input->get('pp');//0 - qualquer palavra (quebrar em array por espaços) / 1 - todas, não quebra nada +$boneco = $input->get("boneco"); +$pagina = $input->get("pagina"); +if($pagina == ""){ + $pagina = 1; +} + +$total = 0; +if($o_helper->hasFilter()){ + if($o_helper->hasFilter(false)){ + $base = '?palavrachave='.$palavraChave.'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco; + $rowsImage = $o_imagem->simpleSeach($palavraChave,$procedencia,$sistema,$patologia,$boneco); + if(($rowsImage->EOF) && ($palavraChave != '')){ + $arr_palavras = $o_helper->findPalavraAproximada($palavraChave); + //print_r2($arr_palavras); + $segestoes = ''; + if(sizeof($arr_palavras[0]) > 0){ + for($x=0;$x".$arr_palavras[0][$x].", "; + } + } + if($segestoes != ""){ + $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2); + } + } + $rowsImage = $o_imagem->complexSeach($arr_palavras,$procedencia,$sistema,$patologia,$boneco); + } + } else { + $base = '?letra='.$letra; + $rowsImage = $o_imagem->searchLetter($letra); + } + $total = $rowsImage->recordCount(); + $rowsImage->pagesize = $o_imagem->filtro_resultado; + $rowsImage->page($pagina); +} +//print_r2($rowsImage); +$selected = 'imagens'; +?> + + + + +<?= $cfg["site_title"]; ?> + + + + + + + + +
    + + + + + +
    +
    + +
    +

    + +
    + + + + +
    + Listando: resultado 1)?'s':'');?>.
    + hasFilter(false)){?> + +
    Palavra-chave: + + +
    Procedência: + + +
    Sistema: + + +
    Patologia: + + +
    Topografia: findTopografiaById($boneco);?> + + +
    + + + Índice: + +
    +
    + +
    +
    + + + + + + + + + + + + + +
    + getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?> +
    + +
    + +
    +
    + Busca Avançada +
    + + + + + +
    + getBoneco('Boneco','TXT0','boneco');?> + +
    + getSelect($arrProcedencia,'Procedência','CMB0','procedencia',' style="width:210px;" ');?> +
    +
    + getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?> +
    +
    + getSelect($arrPatologia,'Patologia','CMB0','patologia',' style="width:210px;" ');?> +
    +
    + +
    +
    +
    +
    +
    +
    + + + + + + + + + EOF){?> + + + + + + + + + + + + + + + + + pagecount > 1){?> + + + + +
    + +
     
    +
    + getAlfabeto();;?> +
    + Nenhum registro encontrado. +
    +
     
    +
    + getResultado($base);?> + getOrdenar($base);?> +
    + + + EOF){ + if(($x != 0) && (($x%2) == 0)){ + echo ''; + }?> + + moveNext(); + $x++; + }?> + +
    +
    + + + + + +
    getImage($rowsImage->fields('id')); + if($src == ''){ + $src = '../../img/olho.jpg'; + } + ?>
    + +
    +
    +
    fields('nome');?> saudavel($rowsImage->fields('saudavel'));?>
    +
    fields('sistema');?>
    +
    fields('patologia');?>
    +
    +
    +
    +
    +
     
    +
    + Páginas: pagecount; + //pagina atual + $actualPage = $pagina; + //baseLink + $pageBaseLink = $base; + //nome do link da pagina (pagina=1) + $pageLinkName = 'pagina'; + include('../../inc/structure/paginacao.php'); + ?> +
    + + + + + + + + +
    + +
     
    +
    + getAlfabeto();;?> +
    + +
    +
    + + + diff --git a/site/content/imagens/view.php b/site/content/imagens/view.php new file mode 100644 index 0000000..0a28ac5 --- /dev/null +++ b/site/content/imagens/view.php @@ -0,0 +1,175 @@ +system('functions/text.php'); + +$selected = 'imagens'; + +$load->config('classes/Imagem.php'); +$o_imagem = new Imagem(); +$rowImage = $o_imagem->findImageById($input->get('id',true)); +if($rowImage->EOF){ + redir('index.php'); + die; +} +$o_imagem->verifyWaterMark($rowImage->fields('id'),$rowImage->fields('carimbo')); +$folder = 'sis_imagem_wm'; +if($rowImage->fields('carimbo') == 4){ + $folder = 'sis_imagem'; +} +?> + + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + + +
    + + + + +
    +
    + +
    +

    + + + + + + + + + +
    +
    + fields('nome');?> saudavel($rowImage->fields('saudavel'));?> +
    +
    + fields('sistema');?> +
    +
    + fields('patologia');?> +
    +
    + + + + + + + + + fields('id_grupoimagem') != ''){?> + + + + + + + +
    + fields('texto'));?> +
    + getImage($rowImage->fields('id'),'m',4); + $srcG = '../../../upload/'.$folder.'/'.$rowImage->fields('id').'.jpg'; + $funcSimples = ''; + $funcDetalhe = ''; + if($src == ''){ + $src = '../../img/olho_g.jpg'; + } else { + $img = imagecreatefromjpeg($srcG); + $w = imagesx($img); + $h = imagesy($img); + $funcSimples = ' onclick="javascript: zoom1('.$w.','.$h.');" style="cursor:pointer;" '; + $funcDetalhe = ' onclick="javascript: zoom();" style="cursor:pointer;" '; + } + + ?> + + +
    + /> +
    +
    + /> +
    +
    + +
    + +
    + dataorigem($rowImage->fields('dataorigem'));?> + procedencia($rowImage->fields('procedencia'));?> + orgaosrelacionados($rowImage->fields('id'));?> +
    +
    + alt('Imagens Relacionadas');?> /> +
    +
    + getImgesRelacionadasByGrupo($rowImage->fields('id_grupoimagem'));?> +
    +
    + alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" /> +
    +
    +
    + alt('Diagnósticos Relacionados');?> /> +
    + diagnosticosrelacionados($rowImage->fields('id'));?> +
    +
    + alt('Casos de Estudo Relacionados');?> /> +
    + casosdeestudorelacionados($rowImage->fields('id'));?> +
    +
    +
    + + + \ No newline at end of file diff --git a/site/content/index.html b/site/content/index.html new file mode 100644 index 0000000..0ba0ba1 --- /dev/null +++ b/site/content/index.html @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/site/content/necropsia/index.php b/site/content/necropsia/index.php new file mode 100644 index 0000000..9600f56 --- /dev/null +++ b/site/content/necropsia/index.php @@ -0,0 +1,292 @@ +config('classes/Diagnostico.php'); +$o_diagnostico = new Diagnostico($patologia); + +$arrProcedencia = $o_helper->findProcedencias(true); +$arrSistema = $o_helper->findSistemas(true); +$arrEspecialidade = $o_helper->findEspecialidade(true); + +$letra = $input->get('letra'); +$palavraChave = $input->get('palavrachave'); +$especialidade = $input->get('especialidade'); +$procedencia = $input->get('procedencia'); +$sistema = $input->get('sistema'); +//$patologia = $input->get('patologia'); +$like = $input->get('pp');//0 - qualquer palavra (quebrar em array por espaços) / 1 - todas, não quebra nada +$boneco = $input->get("boneco"); +$pagina = $input->get("pagina"); +if($pagina == ""){ + $pagina = 1; +} + +$total = 0; +if($o_helper->hasFilter()){ + if($o_helper->hasFilter(false)){ + $base = '?palavrachave='.$palavraChave.'&especialidade='.$especialidade.'&procedencia='.$procedencia.'&sistema='.$sistema.'&patologia='.$patologia.'&boneco='.$boneco; + $rowsDiagnostico = $o_diagnostico->simpleSeach($palavraChave,$especialidade,$procedencia,$sistema,$patologia,$boneco); + if(($rowsDiagnostico->EOF) && ($palavraChave != '')){ + $arr_palavras = $o_helper->findPalavraAproximada($palavraChave); + //print_r2($arr_palavras); + $segestoes = ''; + if(sizeof($arr_palavras[0]) > 0){ + for($x=0;$x".$arr_palavras[0][$x].", "; + } + } + if($segestoes != ""){ + $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2); + } + } + $rowsDiagnostico = $o_diagnostico->complexSeach($arr_palavras,$procedencia,$sistema,$patologia,$boneco); + } + } else { + $base = '?letra='.$letra; + $rowsDiagnostico = $o_diagnostico->searchLetter($letra,$patologia); + } + $total = $rowsDiagnostico->recordCount(); + $rowsDiagnostico->pagesize = $o_diagnostico->filtro_resultado; + $rowsDiagnostico->page($pagina); +} + +$selected = 'necropsia'; +?> + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + +
    + + + + + +
    +
    + +
    +

    + +
    + + + + +
    + Listando: resultado 1)?'s':'');?>.
    + hasFilter(false)){?> + +
    Palavra-chave: + + +
    Especialidade: + + +
    Procedência: + + +
    Sistema: + + +
    Topografia: findTopografiaById($boneco);?> + + +
    + + + Índice: + +
    +
    + +
    +
    + + + + + + + + + + + + + +
    + getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?> +
    + +
    + +
    +
    + Busca Avançada +
    + + + + + +
    + getBoneco('Boneco','TXT0','boneco');?> + +
    + getSelect($arrEspecialidade,'Especialidade','CMB0','especialidade',' style="width:210px;" ');?> +
    +
    + getSelect($arrProcedencia,'Procedência','CMB0','procedencia',' style="width:210px;" ');?> +
    +
    + getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?> +
    +
    + +
    +
    +
    +
    +
    +
    + + +
     
    + + + + + + EOF){?> + + + + + + + + + + + + + + + + + pagecount > 1){?> + + + + +
    + getAlfabeto();;?> +
    + Nenhum registro encontrado. +
    +
     
    +
    + getResultado($base);?> + getOrdenar($base);?> +
    + EOF){ + $url = ' onclick="javascript:url(\'view.php?id='.$input->encode($rowsDiagnostico->fields('id')).'\');" ';?> + + + + +
    + + + + + + + + + + + + + + + + +
    > + fields('nome');?> +
    + fields('especialidade');?>fields('cid10') == '')?'':' | '.$rowsDiagnostico->fields('cid10'));?> +
    > + fields('texto');?> +
    + getImgesRelacionadas($rowsDiagnostico->fields('id'),8);?> +
    + /> +
    +
    + moveNext(); + }?> +
    +
     
    +
    + Páginas: pagecount; + //pagina atual + $actualPage = $pagina; + //baseLink + $pageBaseLink = $base; + //nome do link da pagina (pagina=1) + $pageLinkName = 'pagina'; + include('../../inc/structure/paginacao.php'); + ?> +
    + + + + + + + + +
    + +
     
    +
    + getAlfabeto();;?> +
    + +
    +
    + + + \ No newline at end of file diff --git a/site/content/necropsia/view.php b/site/content/necropsia/view.php new file mode 100644 index 0000000..f9cfb83 --- /dev/null +++ b/site/content/necropsia/view.php @@ -0,0 +1,91 @@ +config('classes/Diagnostico.php'); +$o_diagnostico = new Diagnostico(); +$rowDiagnostico = $o_diagnostico->findDiagnoticoById($input->get('id',true)); +if($rowDiagnostico->EOF){ + redir('index.php'); + die; +} +?> + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + +
    + + + + +
    +
    + +
    +

    + + + + + + + + + +
    +
    + fields('nome');?> +
    +
    + fields('especialidade');?> +
    + fields('cid10') != ''){?> +
    + fields('cid10');?> +
    + +
    + + + + + + + + + + +
    + fields('texto');?> +
    + orgaosrelacionados($rowDiagnostico->fields('id'));?> +
    + alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" /> +
    +
    +
    + alt('Imagens Relacionadas');?> /> +
    + getImgesRelacionadas($rowDiagnostico->fields('id'));?> +
    +
    + alt('Casos de Estudo Relacionados');?> /> +
    + casosdeestudorelacionados($rowDiagnostico->fields('id'));?> +
    +
    +
    + + + \ No newline at end of file diff --git a/site/content/orgaos/index.php b/site/content/orgaos/index.php new file mode 100644 index 0000000..21ceb80 --- /dev/null +++ b/site/content/orgaos/index.php @@ -0,0 +1,283 @@ +config('classes/Orgao.php'); +$o_orgao = new Orgao(); + +$arrGrupoOrgao = $o_helper->findGrupoOrgao(true); +$arrSistema = $o_helper->findSistemas(true); + +$letra = $input->get('letra'); +$palavraChave = $input->get('palavrachave'); +$grupoorgao = $input->get('grupoorgao'); +$sistema = $input->get('sistema'); +$boneco = $input->get("boneco"); +$pagina = $input->get("pagina"); +if($pagina == ""){ + $pagina = 1; +} + +$total = 0; +if($o_helper->hasFilter()){ + if($o_helper->hasFilter(false)){ + $base = '?palavrachave='.$palavraChave.'&grupoorgao='.$grupoorgao.'&sistema='.$sistema.'&boneco='.$boneco; + $rowsOrgao = $o_orgao->simpleSeach($palavraChave,$grupoorgao,$sistema,$boneco); + if(($rowsOrgao->EOF) && ($palavraChave != '')){ + $arr_palavras = $o_helper->findPalavraAproximada($palavraChave); + + $segestoes = ''; + if(sizeof($arr_palavras[0]) > 0){ + for($x=0;$x".$arr_palavras[0][$x].", "; + } + } + if($segestoes != ""){ + $segestoes = "Sugestões de pesquisa: ".substr($segestoes,0,strlen($segestoes)-2); + } + } + $rowsOrgao = $o_orgao->complexSeach($arr_palavras,$grupoorgao,$sistema,$boneco); + } + } else { + $base = '?letra='.$letra; + $rowsOrgao = $o_orgao->searchLetter($letra); + } + $total = $rowsOrgao->recordCount(); + $rowsOrgao->pagesize = $o_orgao->filtro_resultado; + $rowsOrgao->page($pagina); +} else { + $rowsOrgao = $o_orgao->findAll(); + $total = $rowsOrgao->recordCount(); + $rowsOrgao->pagesize = $o_orgao->filtro_resultado; + $rowsOrgao->page($pagina); + $base = '?1=1'; +} + +$selected = 'orgaos'; +?> + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + +
    + + + + + +
    +
    + +
    +

    + +
    + + + + +
    + Listando: resultado 1)?'s':'');?>.
    + hasFilter(false)){?> + +
    Palavra-chave: + + +
    Topografia: + + +
    Sistema: + + +
    Topografia: findTopografiaById($boneco);?> + + +
    + + + Índice: + +
    +
    + +
    +
    + + + + + + + + + + + + + +
    + getInput('Palavra-chave','TXT0','palavrachave',' style="width:350px;" ');?> +
    + +
    + +
    +
    + Busca Avançada +
    + + + + + +
    + getBoneco('Boneco','TXT0','boneco');?> + +
    + getSelect($arrGrupoOrgao,'Topografia','CMB0','grupoorgao',' style="width:210px;" ');?> +
    +
    + getSelect($arrSistema,'Sistema','CMB0','sistema',' style="width:210px;" ');?> +
    +
    + +
    +
    +
    +
    +
    +
    + + + + + + + + + EOF){?> + + + + + + + + + + + + + + + + + pagecount > 1){?> + + + + +
    + +
     
    +
    + getAlfabeto();;?> +
    + Nenhum registro encontrado. +
    +
     
    +
    + getResultado($base);?> + getOrdenar($base);?> +
    + + + EOF){ + if(($x != 0) && (($x%2) == 0)){ + echo ''; + }?> + + moveNext(); + $x++; + }?> + +
    +
    + + + + + +
    getImage($rowsOrgao->fields('id')); + if($src == ''){ + $src = '../../img/olho.jpg'; + } + ?>
    + +
    +
    +
    fields('nome');?>
    +
    sistemasrelacionados($rowsOrgao->fields('id'));?>
    +
    grupodeorgaorelacionados($rowsOrgao->fields('id'));?>
    +
    +
    +
    +
    +
     
    +
    + Páginas: pagecount; + //pagina atual + $actualPage = $pagina; + //baseLink + $pageBaseLink = $base; + //nome do link da pagina (pagina=1) + $pageLinkName = 'pagina'; + include('../../inc/structure/paginacao.php'); + ?> +
    + + + + + + + + +
    + +
     
    +
    + getAlfabeto();;?> +
    + +
    +
    + + + \ No newline at end of file diff --git a/site/content/orgaos/view.php b/site/content/orgaos/view.php new file mode 100644 index 0000000..0e36eac --- /dev/null +++ b/site/content/orgaos/view.php @@ -0,0 +1,124 @@ +system('functions/text.php'); + +$load->config('classes/Orgao.php'); +$o_orgao = new Orgao(); +$rowOrgao = $o_orgao->findOrgaoById($input->get('id',true)); +if($rowOrgao->EOF){ + redir('index.php'); + die; +} +?> + + + + + + <?= $cfg["site_title"]; ?> + + + + + + + + + +
    + + + + +
    +
    + +
    +

    + + + + + + + + + +
    +
    + fields('nome');?> +
    + fields('pagina') != ''){?> +
    + Mais informações:  fields('pagina');?> +
    + +
    + + + + + + + + + + + + + + +
    + fields('texto'));?> +
    + getImage($rowOrgao->fields('id'),'m'); + $func = ''; + if($src == ''){ + $src = '../../img/olho_g.jpg'; + } else { + $img = imagecreatefromjpeg('../../../upload/sis_orgao/'.$rowOrgao->fields('id').'.jpg'); + $w = imagesx($img); + $h = imagesy($img); + $func = ' onclick="javascript: zoom('.$w.','.$h.');" style="cursor:pointer;" '; + } + + ?> + /> + + sistemasrelacionados($rowOrgao->fields('id'));?>

    + grupodeorgaorelacionados($rowOrgao->fields('id'));?> +
    +
    + alt('Imagens Relacionadas');?> /> +
    +
    + getImgesRelacionadas($rowOrgao->fields('id'));?> +
    +
    + alt('Voltar');?> style="cursor:pointer;" onclick="javascript: window.history.back();" /> +
    +
    +
    + alt('Diagnósticos Relacionados');?> /> +
    + diagnosticosrelacionados($rowOrgao->fields('id'));?> +
    +
    + alt('Casos de Estudo Relacionados');?> /> +
    + casosdeestudorelacionados($rowOrgao->fields('id'));?> +
    +
    +
    + + + \ No newline at end of file diff --git a/site/inc/css/default.css b/site/inc/css/default.css new file mode 100644 index 0000000..2410c1d --- /dev/null +++ b/site/inc/css/default.css @@ -0,0 +1,205 @@ +html,body { + width:100%; + height:100%; + margin:0px; + padding:0px; + background:url(../../img/common/bg/default.jpg) top left repeat-x #FFFFFF; +} +div{ + margin:auto; +} +table { + font-family:Tahoma, Geneva, sans-serif; + font-size:11px; + color:#353535; +} +td { + vertical-align:top; + font-size:11px; +} +img { + border:0px; +} + +p { + margin:4px; +} + +a { + color:#4E4E4E; + text-decoration:none; +} + +a:hover { + color:#8D8D8D; + text-decoration:none; +} +td.ufcspa { + padding-right:24px; padding-top:15px; +} +td.ufcspa div{ + width:86px; height:84px; background:url(../../img/pt/ufcspa.jpg) center center no-repeat; cursor:pointer; +} +div.lftsia { + width:6px; height:112px; background:url(../../img/common/bg/topleft.gif) top left no-repeat; +} +div.rgtsia { + width:6px; height:112px; background:url(../../img/common/bg/topright.gif) top left no-repeat; +} +td.cntsia { + background:url(../../img/common/bg/topcenter.gif) top left repeat-x; padding-top:45px; padding-left:25px; padding-right:25px; +} +td.cntsia div{ + width:242px; height:40px; background:url(../../img/pt/tit/siap.png) center center no-repeat #22588C; cursor:pointer; +} +td.topsep { + padding-left:10px; padding-right:10px; padding-top:25px; +} +td.topsep div{ + width:1px; height:69px; background-color:#22588C; font-size:1px +} +.tblMenu td{ + padding-left:10px; + padding-right:10px; + cursor:pointer; + height:50px; +} +.rdoPal { + float:left; + vertical-align:middle; + color:#FFFFFF; + font-family:Tahoma; +} +.divlncn{ + height:20px;font-size:1px;border-bottom:1px solid #b1b1b1;margin-bottom:20px; +} +.divLnAm { + height:8px;font-size:1px;border-bottom:1px solid #cca365;margin-bottom:20px; +} +.subaztit{ + font-size:11px;font-weight:bold;color:#194c7f; +} +.txtdivin { + margin-top:11px;margin-bottom:11px; +} +input.input { + vertical-align:top; + padding:4px; + color:#353535; + font-size:11px; + font-family:Tahoma; +} +textarea.input { + vertical-align:top; + padding:4px; + color:#353535; + font-size:11px; + font-family:Tahoma; + overflow:auto; +} +a.underlaine{ + font-family:Tahoma; + color:#194c7f; + font-size:11px; + text-decoration:underline; +} +a:hover.underlaine{ + text-decoration:none; +} +a.underlaine2{ + font-family:Tahoma; + color:#444444; + font-size:11px; + font-weight:bold; + text-decoration:underline; +} +a:hover.underlaine2{ + text-decoration:none; +} +.nletra{ + font-family:Tahoma; + color:#666666; + font-weight:bold; + font-size:11px; + text-decoration:underline; +} +a.ltra{ + font-family:Tahoma; + color:#CCA365; + font-weight:bold; + font-size:11px; + text-decoration:underline; + padding-left:3px; + padding-right:3px; +} +a:hover.ltra{ + padding-left:3px; + padding-right:3px; + background:#FFFFFF; + text-decoration:none; +} +div.tosear { + width:100%; + margin-top:10px; + text-align:right; +} +div.resultados { + float:left; + padding-top:10px; +} +div.ordenar { + float:right; + margin-top:10px; +} +td.tddados { + vertical-align:middle; + padding-left:10px; +} +td.tddados div{ + margin-bottom:10px; +} +.bold_444 { + color:#444444; + font-weight:bold; +} +.italic_444 { + color:#444444; + font-style:italic; +} +.blue_normal { + color:#194C7F; + font-style:normal; +} +.divlist { + background:url(../../img/common/bg/dot.gif) center left no-repeat; padding-left:15px; +} +div.nomeComentario { + font-size:11px; + font-family:Tahoma; + color:#194c7f; + font-style:italic; + padding-top:10px; + float:left; +} +div.excluirComentario { + font-size:11px; + font-family:Tahoma; + color:#194c7f; + font-style:italic; + padding-top:10px; + float:right; +} +div.textoComentario { + width:100%; + font-size:11px; + font-family:Tahoma; + color:#353535; + font-style:none; + padding-top:10px; + padding-bottom:10px; + float:left; +} +span.saudavel { + font-size:9px; + color:ForestGreen; +} \ No newline at end of file diff --git a/site/inc/css/jqzoom.css b/site/inc/css/jqzoom.css new file mode 100644 index 0000000..1f37a13 --- /dev/null +++ b/site/inc/css/jqzoom.css @@ -0,0 +1,68 @@ +div.jqZoomTitle +{ + z-index:5000; + text-align:center; + font-size:11px; + font-family:Tahoma; + height:16px; + padding-top:2px; + position:absolute; + top: 0px; + left: 0px; + width: 100%; + color: #FFF; + background: #999; + +} + +.jqZoomPup +{ + overflow:hidden; + background-color: #FFF; + -moz-opacity:0.6; + opacity: 0.6; + filter: alpha(opacity = 60); + z-index:10; + border-color:#c4c4c4; + border-style: solid; + cursor:crosshair; +} + +.jqZoomPup img +{ + border: 0px; +} + +.preload{ + -moz-opacity:0.8; + opacity: 0.8; + filter: alpha(opacity = 80); + color: #333; + font-size: 12px; + font-family: Tahoma; + text-decoration: none; + border: 1px solid #CCC; + background-color: white; + padding: 8px; + text-align:center; + background-image: url(../images/zoomloader.gif); + background-repeat: no-repeat; + background-position: 43px 30px; + width:90px; + * width:100px; + height:43px; + *height:55px; + z-index:10; + position:absolute; + top:3px; + left:3px; + +} + +.jqZoomWindow +{ + border: 1px solid #999; + background-color: #FFF; +} + + diff --git a/site/inc/js/default.js b/site/inc/js/default.js new file mode 100644 index 0000000..2a7ad9e --- /dev/null +++ b/site/inc/js/default.js @@ -0,0 +1,158 @@ +var baseSrc = "../../img/pt/menu/"; +function swapM(menu,focus){ + var img = document.getElementById("img_"+menu); + if(img){ + if(focus){ + img.src = baseSrc+menu+"_over.jpg"; + } else { + img.src = baseSrc+menu+".jpg"; + } + } +} +function swapI(obj,focus){ + if(focus){ + if(obj.value == obj.attributes["label"].value){ + obj.value = ""; + } + } else { + if(obj.value.trim() == ""){ + obj.value = obj.attributes["label"].value; + } + } +} +function swapP(obj,focus){ + if(focus){ + var pass = document.getElementById(obj.attributes["parent"].value); + if(pass){ + obj.innerHTML = ""; + pass.focus(); + } + } else { + if(obj.value == ""){ + var div = document.getElementById("div"+obj.id); + if(div){ + div.innerHTML = obj.attributes["label"].value; + } + } + } +} +function swapElement(tmp_id){ + var obj = document.getElementById(tmp_id); + if(obj){ + if(obj.style.display == ''){ + obj.style.display = 'none'; + } else { + obj.style.display = ''; + } + } +} +function url(url){ + window.location = url; +} +function sendFilter(tmp_form){ + var ok = false; + + var palavrachave = document.getElementById('Palavra-chave_TXT0'); + var codigo = document.getElementById('Código_TXT0'); + var topografia = document.getElementById('Topografia_CMB0'); + var procedencia = document.getElementById('Procedência_CMB0'); + var sistema = document.getElementById('Sistema_CMB0'); + var patologia = document.getElementById('Patologia_CMB0'); + var especialidade = document.getElementById('Especialidade_CMB0'); + var professor = document.getElementById('Professor_CMB0'); + var boneco = document.getElementById('Boneco_TXT0'); + + if(palavrachave){ + if((palavrachave.value.trim() != '') && (palavrachave.value.trim() != palavrachave.defaultValue)){ + ok = true; + } + } + + if(topografia){ + if(topografia.value != ''){ + ok = true; + } + } + + if(codigo){ + if((codigo.value.trim() != '') && (codigo.value.trim() != codigo.defaultValue)){ + ok = true; + } + } + + if(procedencia){ + if(procedencia.value != ''){ + ok = true; + } + } + + if(sistema){ + if(sistema.value != ''){ + ok = true; + } + } + + if(patologia){ + if(patologia.value != ''){ + ok = true; + } + } + + if(especialidade){ + if(especialidade.value != ''){ + ok = true; + } + } + + if(professor){ + if(professor.value != ''){ + ok = true; + } + } + + if(boneco){ + if(boneco.value != ''){ + ok = true; + } + } + + + if(ok){ + if(palavrachave.value == palavrachave.defaultValue){ + palavrachave.value = ''; + } + return f.send(tmp_form); + } else { + alert('Selecione ao menos um filtro para fazer sua pesquisa.'); + return; + } +} +function openBoneco(name){ + var p = new Popup(570,580); + p.overflow = 'hidden'; + p.position = 'fixed'; + p.onLoad = function (){ + $(function() { + $('#hightlightall').mouseover(function(e) { + $($$('img_boneco').useMap+' area').mouseover(); + }).mouseout(function(e) { + $($$('img_boneco').useMap+' area').mouseout(); + }).click(function(e) { e.preventDefault(); }); + }); + } + p.open('../../inc/structure/grupoorgao.php?name='+name); +} +function trocaCamada(id_camada){ + $$('img_boneco').useMap = '#GrupoOrgao'+id_camada; + $(function() { + $('#img_boneco').maphilight({strokeColor: '22588c'}); + }); +} +function selectBoneco(id,nome,sufix){ + var elms = document.getElementsByName(sufix); + if(elms.length == 1){ + elms[0].value = id; + } + $$('results_'+sufix).innerHTML = 'Selecionado: '+nome; + Popup_atual.close(); +} \ No newline at end of file diff --git a/site/inc/js/jquery.jqzoom.js b/site/inc/js/jquery.jqzoom.js new file mode 100644 index 0000000..c40a295 --- /dev/null +++ b/site/inc/js/jquery.jqzoom.js @@ -0,0 +1,1124 @@ +/* + * JQZoom Evolution 1.0.1 - Javascript Image magnifier + * + * Copyright (c) Engineer Renzi Marco(www.mind-projects.it) + * + * $Date: 12-12-2008 + * + * ChangeLog: + * + * $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). + */ +(function($) +{ + $.fn.jqzoom = function(options) + { + var settings = { + zoomType: 'standard', //standard/reverse/innerzoom + zoomWidth: 200, //zoomed width default width + zoomHeight: 200, //zoomed div default width + xOffset: 10, //zoomed div default offset + yOffset: 0, + position: "right" ,//zoomed div default position,offset position is to the right of the image + lens:true, //zooming lens over the image,by default is 1; + lensReset : false, + imageOpacity: 0.2, + title : true, + alwaysOn: false, + showEffect: 'show', + hideEffect: 'hide', + fadeinSpeed: 'fast', + fadeoutSpeed: 'slow', + preloadImages :true, + showPreload: true, + preloadText : 'Loading zoom', + preloadPosition : 'center' //bycss + }; + + //extending options + options = options || {}; + $.extend(settings, options); + + + return this.each(function() + { + var a = $(this); + var aTitle = a.attr('title'); //variabile per memorizzare il titolo href + $(a).removeAttr('title'); + $(a).css('outline-style','none'); + + + var img = $("img", this); + var imageTitle = img.attr('title'); + img.removeAttr('title'); //variabile per memorizzare il titolo immagine + + + var smallimage = new Smallimage( img ); + var smallimagedata = {}; + //imageborder + var btop = 0; + var bleft = 0; + + var loader = null; //variabile per memorizzare oggetto loader + loader = new Loader(); + + var ZoomTitle = (trim(aTitle).length > 0) ? aTitle : + (trim(imageTitle).length > 0) ? imageTitle : null; //setting zoomtitle + var ZoomTitleObj = new zoomTitle(); + + var largeimage = new Largeimage( a[0].href ); + + var lens = new Lens(); + var lensdata = {}; + //lensborder + + + + var largeimageloaded = false; + var scale = {}; //rapporto tra immagine grande e piccola scale.x/scale.y + var stage = null; // quadrato che mostra l'immagine ingrandita + var running = false; // running = true quando si verifica l'evento che mostra lo zoom(adesso mouseover). + var mousepos = {}; + var firstime = 0; + var preloadshow = false; + var isMouseDown = false; + var dragstatus = false + //loading smallimagedata + smallimage.loadimage(); + + //ritorna false al click dell href + $(this).click(function(){return false;}); + + //se settato alwaysOn attivo lo Zoom e lo mostro. + + //attivo al mouseover + $(this).hover(function(e) + { + mousepos.x = e.pageX; + mousepos.y = e.pageY; + activate(); + },function() + { + deactivate(); + }); + + + //ALWAYS ON + if(settings.alwaysOn) + { + setTimeout(function(){activate();},150); + } + + + function activate() + { + + if ( !running ) { + + //finding border + smallimage.findborder(); + + running = true; + + //rimuovo il titolo al mouseover + imageTitle = img.attr('title'); + img.removeAttr('title'); + aTitle = a.attr('title'); + $(a).removeAttr('title'); + + //se non cè creo l'oggetto largeimage + if (!largeimage || $.browser.safari) { + largeimage = new Largeimage( a[0].href ); + } + + //se l'immagine grande non è stata caricata la carico + if(!largeimageloaded || $.browser.safari) + { + largeimage.loadimage(); + }else + { + //after preload + if(settings.zoomType != 'innerzoom') + { + stage = new Stage(); + stage.activate(); + } + lens = new Lens; + lens.activate(); + } + + //hack per MAC + /* if($.browser.safari) + { + if(settings.zoomType != 'innerzoom') //se innerzoom non mostro la finestra dello zoom + { + stage = new Stage(); + stage.activate(); + } + if($('div.jqZoomPup').length <= 0) + { + lens = new Lens(); + } + //if(settings.zoomType == 'innerzoom'){lens = new Lens()}; + lens.activate(); + (settings.alwaysOn) ? lens.center() : lens.setposition(null); + } + */ + a[0].blur(); + //alert($('div.jqZoomPup').length); + return false; + } + + + + + } + + function deactivate() + { + if(settings.zoomType == 'reverse' && !settings.alwaysOn) + { + img.css({'opacity' : 1}); + } + + if(!settings.alwaysOn) + { + //resetting parameters + running = false; + largeimageloaded = false; + $(lens.node).unbind('mousemove'); + lens.remove(); + if($('div.jqZoomWindow').length >0) + { + stage.remove(); + } + if($('div.jqZoomTitle').length > 0) + { + ZoomTitleObj.remove(); + } + //resetting title + img.attr('title',imageTitle); + a.attr('title',aTitle); + $().unbind(); + + a.unbind('mousemove'); + //resetto il parametro che mi dice che è la prima volta che mostor lo zoom + firstime = 0; + //remove ieiframe + if(jQuery('.zoom_ieframe').length > 0) + { + jQuery('.zoom_ieframe').remove(); + } + }else + { + if(settings.lensReset) + { + switch(settings.zoomType) + { + case 'innerzoom': + largeimage.setcenter(); + break; + default: + lens.center(); + break; + } + } + } + + //non so se serve da provare + if(settings.alwaysOn) + { + activate(); + } + }; + + + + + + //smallimage + function Smallimage( image ) + { + this.node = image[0]; + + this.loadimage = function() { + this.node.src = image[0].src; + }; + this.findborder = function() + { + var bordertop = ''; + bordertop = $(img).css('border-top-width'); + btop = ''; + var borderleft = ''; + borderleft = $(img).css('border-left-width'); + bleft = ''; + /*if($.browser.msie) + { + var temp = bordertop.split(' '); + + bordertop = temp[1]; + var temp = borderleft.split(' '); + borderleft = temp[1]; + }*/ + + if(bordertop) + { + for(i=0;i<3;i++) + { + var x = []; + x = bordertop.substr(i,1); + + if(isNaN(x) == false) + { + btop = btop +''+ bordertop.substr(i,1); + }else + { + break; + } + } + } + + if(borderleft) + { + for(i=0;i<3;i++) + { + if(!isNaN(borderleft.substr(i,1))) + { + bleft = bleft + borderleft.substr(i,1) + }else + { + break; + } + } + } + btop = (btop.length > 0) ? eval(btop) : 0; + bleft = (bleft.length > 0) ? eval(bleft) : 0; + + + } + this.node.onload = function() + { + //setto il cursor e la posizione dell'href + + + a.css({'cursor':'crosshair','display':'block'}); + + if(a.css('position')!= 'absolute' && a.parent().css('position')) + { + a.css({'cursor':'crosshair','position':'relative','display':'block'}); + } + if(a.parent().css('position') != 'absolute') + { + a.parent().css('position','relative'); + //a.css('position','relative'); + } + else{ + //a.css('position','relative'); + } + if($.browser.safari || $.browser.opera) + { + $(img).css({position:'absolute',top:'0px',left:'0px'}); + } + /*if(a.css('position')!= 'absolute' && a.parent().css('position')) + { + a.css({'cursor':'crosshair','position':'relative','display':'block'}); + } + if(a.parent().css('position') != 'absolute') + { + alert('in'); + a.parent().css('position','relative'); + //a.css('position','relative'); + } + else{ + //a.css('position','relative'); + }*/ + + + + /* + if(a.parent().css('position') != 'relative' && a.css('position') != 'absolute') + { + a.css({'cursor':'crosshair','position':'relative','display':'block'}); + }*/ + + //al docuemnt ready viene caricato l'src quindi viene azionato l'onload e carico tutti i dati + smallimagedata.w = $( this ).width(); + smallimagedata.h = $( this ).height(); + + + //non viene fatta assegnazione alla variabile globale + smallimagedata.h = $( this ).height(); + smallimagedata.pos = $( this ).offset(); + smallimagedata.pos.l = $( this ).offset().left; + smallimagedata.pos.t = $( this ).offset().top; + smallimagedata.pos.r = smallimagedata.w + smallimagedata.pos.l; + smallimagedata.pos.b = smallimagedata.h + smallimagedata.pos.t; + + //per sicurezza setto l'altezza e la width dell'href + a.height(smallimagedata.h); + a.width(smallimagedata.w); + + + //PRELOAD IMAGES + if(settings.preloadImages) + { + largeimage.loadimage(); + } + + + + }; + + + + return this; + }; + + + + //Lens + function Lens() + { + + + //creating element and adding class + this.node = document.createElement("div"); + $(this.node).addClass('jqZoomPup'); + + this.node.onerror = function() { + $( lens.node ).remove(); + lens = new Lens(); + lens.activate() ; + }; + + + + + //funzione privata per il caricamento dello zoom + this.loadlens = function() + { + + + switch(settings.zoomType) + { + case 'reverse': + this.image = new Image(); + this.image.src = smallimage.node.src; // fires off async + this.node.appendChild( this.image ); + $( this.node ).css({'opacity' : 1}); + break; + case 'innerzoom': + + this.image = new Image(); + this.image.src = largeimage.node.src; // fires off async + this.node.appendChild( this.image ); + $( this.node ).css({'opacity' : 1}); + break + default: + break; + } + + + + switch(settings.zoomType) + { + case 'innerzoom': + lensdata.w = smallimagedata.w; + lensdata.h = smallimagedata.h; + break; + default: + lensdata.w = (settings.zoomWidth)/scale.x; + lensdata.h = (settings.zoomHeight)/scale.y; + break; + } + + $( this.node ).css({ + width: lensdata.w + 'px', + height: lensdata.h + 'px', + position: 'absolute', + /*cursor: 'crosshair',*/ + display: 'none', + //border: '1px solid blue' + borderWidth: 1+'px' + }); + a.append(this.node); + } + return this; + }; + + Lens.prototype.activate = function() + { + //carico la lente + this.loadlens(); + + switch(settings.zoomType) + { + case 'reverse': + img.css({'opacity' : settings.imageOpacity}); + + (settings.alwaysOn) ? lens.center() : lens.setposition(null); + //lens.center(); + //bindo ad a il mousemove della lente + a.bind( 'mousemove', function(e) + { + mousepos.x = e.pageX; + mousepos.y = e.pageY; + lens.setposition( e ); + }); + break; + case 'innerzoom': + + // lens = new Lens(); + // lens.activate(); + + $( this.node ).css({top : 0 ,left: 0}); + if(settings.title) + { + ZoomTitleObj.loadtitle(); + } + + largeimage.setcenter(); + + a.bind( 'mousemove', function(e) + { + mousepos.x = e.pageX; + mousepos.y = e.pageY; + largeimage.setinner( e ); + + /*if(settings.zoomType == 'innerzoom' && running) + { + $(a).mousemove(function(){ + if($('div.jqZoomPup').length <= 0) + { + lens = new Lens(); + lens.activate(); + } + }); + }*/ + + /*if($('div.jqZoomPup').length <= 0) + { + lens = new Lens(); + lens.activate(); + }*/ + + }); + break; + default: + /*$(document).mousemove(function(e){ + if(isMouseDown && dragstatus != false){ + lens.setposition( e ); + } + }); + lens.center() + + + dragstatus = 'on' + $(document).mouseup(function(e){ + if(isMouseDown && dragstatus != false){ + isMouseDown = false; + dragstatus = false; + + } + }); + + $(this.node).mousedown(function(e){ + $('div.jqZoomPup').css("cursor", "move"); + $(this.node).css("position", "absolute"); + + // set z-index + $(this.node).css("z-index", parseInt( new Date().getTime()/1000 )); + if($.browser.safari) + { + $(a).css("cursor", "move"); + } + isMouseDown = true; + dragstatus = 'on'; + lens.setposition( e ); + }); + */ + + + (settings.alwaysOn) ? lens.center() : lens.setposition(null); + + //bindo ad a il mousemove della lente + $(a).bind( 'mousemove', function(e) + { + + mousepos.x = e.pageX; + mousepos.y = e.pageY; + lens.setposition( e ); + }); + + break; + } + + + return this; + }; + + Lens.prototype.setposition = function( e) + { + + + if(e) + { + mousepos.x = e.pageX; + mousepos.y = e.pageY; + } + + if(firstime == 0) + { + var lensleft = (smallimagedata.w)/2 - (lensdata.w)/2 ; + var lenstop = (smallimagedata.h)/2 - (lensdata.h)/2 ; + //ADDED + + $('div.jqZoomPup').show() + if(settings.lens) + { + this.node.style.visibility = 'visible'; + } + else + { + this.node.style.visibility = 'hidden'; + $('div.jqZoomPup').hide(); + } + //ADDED + firstime = 1; + + }else + { + var lensleft = mousepos.x - smallimagedata.pos.l - (lensdata.w)/2 ; + var lenstop = mousepos.y - smallimagedata.pos.t -(lensdata.h)/2 ; + } + + + //a sinistra + if(overleft()) + { + lensleft = 0 + bleft; + }else + //a destra + if(overright()) + { + if($.browser.msie) + { + lensleft = smallimagedata.w - lensdata.w + bleft + 1 ; + }else + { + lensleft = smallimagedata.w - lensdata.w + bleft - 1 ; + } + + + } + + //in alto + if(overtop()) + { + lenstop = 0 + btop ; + }else + //sotto + if(overbottom()) + { + + if($.browser.msie) + { + lenstop = smallimagedata.h - lensdata.h + btop + 1 ; + }else + { + lenstop = smallimagedata.h - lensdata.h - 1 + btop ; + } + + } + lensleft = parseInt(lensleft); + lenstop = parseInt(lenstop); + + //setto lo zoom ed un eventuale immagine al centro + $('div.jqZoomPup',a).css({top: lenstop,left: lensleft }); + + if(settings.zoomType == 'reverse') + { + $('div.jqZoomPup img',a).css({'position': 'absolute','top': -( lenstop - btop +1) ,'left': -(lensleft - bleft +1) }); + } + + this.node.style.left = lensleft + 'px'; + this.node.style.top = lenstop + 'px'; + + //setto l'immagine grande + largeimage.setposition(); + + function overleft() { + return mousepos.x - (lensdata.w +2*1)/2 - bleft < smallimagedata.pos.l; + } + + function overright() { + + return mousepos.x + (lensdata.w + 2* 1)/2 > smallimagedata.pos.r + bleft ; + } + + function overtop() { + return mousepos.y - (lensdata.h + 2* 1)/2 - btop < smallimagedata.pos.t; + } + + function overbottom() { + return mousepos.y + (lensdata.h + 2* 1)/2 > smallimagedata.pos.b + btop; + } + + return this; + }; + + + //mostra la lente al centro dell'immagine + Lens.prototype.center = function() + { + $('div.jqZoomPup',a).css('display','none'); + var lensleft = (smallimagedata.w)/2 - (lensdata.w)/2 ; + var lenstop = (smallimagedata.h)/2 - (lensdata.h)/2; + this.node.style.left = lensleft + 'px'; + this.node.style.top = lenstop + 'px'; + $('div.jqZoomPup',a).css({top: lenstop,left: lensleft }); + + if(settings.zoomType == 'reverse') + { + /*if($.browser.safari){ + alert('safari'); + alert(2*bleft); + $('div.jqZoomPup img',a).css({'position': 'absolute','top': -( lenstop - btop +1) ,'left': -(lensleft - 2*bleft) }); + }else + {*/ + $('div.jqZoomPup img',a).css({'position': 'absolute','top': -(lenstop - btop + 1) ,'left': -( lensleft - bleft +1) }); + //} + } + + largeimage.setposition(); + if($.browser.msie) + { + $('div.jqZoomPup',a).show(); + }else + { + setTimeout(function(){$('div.jqZoomPup').fadeIn('fast');},10); + } + }; + + + //ritorna l'offset + Lens.prototype.getoffset = function() { + var o = {}; + o.left = parseInt(this.node.style.left) ; + o.top = parseInt(this.node.style.top) ; + return o; + }; + + //rimuove la lente + Lens.prototype.remove = function() + { + + if(settings.zoomType == 'innerzoom') + { + $('div.jqZoomPup',a).fadeOut('fast',function(){/*$('div.jqZoomPup img').remove();*/$(this).remove();}); + }else + { + //$('div.jqZoomPup img').remove(); + $('div.jqZoomPup',a).remove(); + } + }; + + Lens.prototype.findborder = function() + { + var bordertop = ''; + bordertop = $('div.jqZoomPup').css('borderTop'); + //alert(bordertop); + lensbtop = ''; + var borderleft = ''; + borderleft = $('div.jqZoomPup').css('borderLeft'); + lensbleft = ''; + if($.browser.msie) + { + var temp = bordertop.split(' '); + + bordertop = temp[1]; + var temp = borderleft.split(' '); + borderleft = temp[1]; + } + + if(bordertop) + { + for(i=0;i<3;i++) + { + var x = []; + x = bordertop.substr(i,1); + + if(isNaN(x) == false) + { + lensbtop = lensbtop +''+ bordertop.substr(i,1); + }else + { + break; + } + } + } + + if(borderleft) + { + for(i=0;i<3;i++) + { + if(!isNaN(borderleft.substr(i,1))) + { + lensbleft = lensbleft + borderleft.substr(i,1) + }else + { + break; + } + } + } + + + lensbtop = (lensbtop.length > 0) ? eval(lensbtop) : 0; + lensbleft = (lensbleft.length > 0) ? eval(lensbleft) : 0; + } + + //LARGEIMAGE + function Largeimage( url ) + { + this.url = url; + this.node = new Image(); + + /*if(settings.preloadImages) + { + preload.push(new Image()); + preload.slice(-1).src = url ; + }*/ + + this.loadimage = function() + { + + + if(!this.node) + this.node = new Image(); + + this.node.style.position = 'absolute'; + this.node.style.display = 'none'; + this.node.style.left = '-5000px'; + this.node.style.top = '10px'; + loader = new Loader(); + + if(settings.showPreload && !preloadshow) + { + loader.show(); + preloadshow = true; + } + + document.body.appendChild( this.node ); + this.node.src = this.url; // fires off async + } + + this.node.onload = function() + { + this.style.display = 'block'; + var w = Math.round($(this).width()); + var h = Math.round($(this).height()); + + this.style.display = 'none'; + + //setting scale + scale.x = (w / smallimagedata.w); + scale.y = (h / smallimagedata.h); + + + + + + if($('div.preload').length > 0) + { + $('div.preload').remove(); + } + + largeimageloaded = true; + + if(settings.zoomType != 'innerzoom' && running){ + stage = new Stage(); + stage.activate(); + } + + if(running) + { + //alert('in'); + lens = new Lens(); + + lens.activate() ; + + } + //la attivo + + if($('div.preload').length > 0) + { + $('div.preload').remove(); + } + } + return this; + } + + + Largeimage.prototype.setposition = function() + { + this.node.style.left = Math.ceil( - scale.x * parseInt(lens.getoffset().left) + bleft) + 'px'; + this.node.style.top = Math.ceil( - scale.y * parseInt(lens.getoffset().top) +btop) + 'px'; + }; + + //setto la posizione dell'immagine grande nel caso di innerzoom + Largeimage.prototype.setinner = function(e) { + this.node.style.left = Math.ceil( - scale.x * Math.abs(e.pageX - smallimagedata.pos.l)) + 'px'; + this.node.style.top = Math.ceil( - scale.y * Math.abs(e.pageY - smallimagedata.pos.t)) + 'px'; + $('div.jqZoomPup img',a).css({'position': 'absolute','top': this.node.style.top,'left': this.node.style.left }); + }; + + + Largeimage.prototype.setcenter = function() { + this.node.style.left = Math.ceil(- scale.x * Math.abs((smallimagedata.w)/2)) + 'px'; + this.node.style.top = Math.ceil( - scale.y * Math.abs((smallimagedata.h)/2)) + 'px'; + + + $('div.jqZoomPup img',a).css({'position': 'absolute','top': this.node.style.top,'left': this.node.style.left }); + }; + + + //STAGE + function Stage() + { + + var leftpos = smallimagedata.pos.l; + var toppos = smallimagedata.pos.t; + //creating element and class + this.node = document.createElement("div"); + $(this.node).addClass('jqZoomWindow'); + + $( this.node ) + .css({ + position: 'absolute', + width: Math.round(settings.zoomWidth) + 'px', + height: Math.round(settings.zoomHeight) + 'px', + display: 'none', + zIndex: 10000, + overflow: 'hidden' + }); + + //fa il positionamento + switch(settings.position) + { + case "right": + + leftpos = (smallimagedata.pos.r + Math.abs(settings.xOffset) + settings.zoomWidth < screen.width) + ? (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset)) + : (smallimagedata.pos.l - settings.zoomWidth - Math.abs(settings.xOffset)); + + topwindow = smallimagedata.pos.t + settings.yOffset + settings.zoomHeight; + toppos = (topwindow < screen.height && topwindow > 0) + ? smallimagedata.pos.t + settings.yOffset + : smallimagedata.pos.t; + + break; + case "left": + + leftpos = (smallimagedata.pos.l - Math.abs(settings.xOffset) - settings.zoomWidth > 0) + ? (smallimagedata.pos.l - Math.abs(settings.xOffset) - settings.zoomWidth) + : (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset)); + + topwindow = smallimagedata.pos.t + settings.yOffset + settings.zoomHeight; + toppos = (topwindow < screen.height && topwindow > 0) + ? smallimagedata.pos.t + settings.yOffset + : smallimagedata.pos.t; + + break; + case "top": + + toppos = (smallimagedata.pos.t - Math.abs(settings.yOffset) - settings.zoomHeight > 0) + ? (smallimagedata.pos.t - Math.abs(settings.yOffset) - settings.zoomHeight) + : (smallimagedata.pos.t + smallimagedata.h + Math.abs(settings.yOffset)); + + + leftwindow = smallimagedata.pos.l + settings.xOffset + settings.zoomWidth; + leftpos = (leftwindow < screen.width && leftwindow > 0) + ? smallimagedata.pos.l + settings.xOffset + : smallimagedata.pos.l; + + break; + case "bottom": + + + toppos = (smallimagedata.pos.b + Math.abs(settings.yOffset) + settings.zoomHeight < $('body').height()) + ? (smallimagedata.pos.b + Math.abs(settings.yOffset)) + : (smallimagedata.pos.t - settings.zoomHeight - Math.abs(settings.yOffset)); + + + leftwindow = smallimagedata.pos.l + settings.xOffset + settings.zoomWidth; + leftpos = (leftwindow < screen.width && leftwindow > 0) + ? smallimagedata.pos.l + settings.xOffset + : smallimagedata.pos.l; + + break; + default: + + leftpos = (smallimagedata.pos.l + smallimagedata.w + settings.xOffset + settings.zoomWidth < screen.width) + ? (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset)) + : (smallimagedata.pos.l - settings.zoomWidth - Math.abs(settings.xOffset)); + + toppos = (smallimagedata.pos.b + Math.abs(settings.yOffset) + settings.zoomHeight < screen.height) + ? (smallimagedata.pos.b + Math.abs(settings.yOffset)) + : (smallimagedata.pos.t - settings.zoomHeight - Math.abs(settings.yOffset)); + + break; + } + + this.node.style.left = leftpos + 'px'; + this.node.style.top = toppos + 'px'; + return this; + } + + + Stage.prototype.activate = function() + { + + if ( !this.node.firstChild ) + this.node.appendChild( largeimage.node ); + + + if(settings.title) + { + ZoomTitleObj.loadtitle(); + } + + + + document.body.appendChild( this.node ); + + + switch(settings.showEffect) + { + case 'show': + $(this.node).show(); + break; + case 'fadein': + $(this.node).fadeIn(settings.fadeinSpeed); + break; + default: + $(this.node).show(); + break; + } + + $(this.node).show(); + + if ($.browser.msie && $.browser.version < 7) { + this.ieframe = $('') + .css({ position: "absolute", left:this.node.style.left,top:this.node.style.top,zIndex: 99,width:settings.zoomWidth,height:settings.zoomHeight }) + .insertBefore(this.node); + }; + + + largeimage.node.style.display = 'block'; + } + + Stage.prototype.remove = function() { + switch(settings.hideEffect) + { + case 'hide': + $('.jqZoomWindow').remove(); + break; + case 'fadeout': + $('.jqZoomWindow').fadeOut(settings.fadeoutSpeed); + break; + default: + $('.jqZoomWindow').remove(); + break; + } + } + + function zoomTitle() + { + + this.node = jQuery('
    ') + .addClass('jqZoomTitle') + .html('' + ZoomTitle +''); + + this.loadtitle = function() + { + if(settings.zoomType == 'innerzoom') + { + $(this.node) + .css({position: 'absolute', + top: smallimagedata.pos.b +3, + left: (smallimagedata.pos.l+1), + width:smallimagedata.w + }) + .appendTo('body'); + }else + { + $(this.node).appendTo(stage.node); + } + }; + } + + zoomTitle.prototype.remove = function() { + $('.jqZoomTitle').remove(); + } + + + function Loader() + { + + this.node = document.createElement("div"); + $(this.node).addClass('preload'); + $(this.node).html(settings.preloadText);//appendo il testo + + $(this.node ) + .appendTo("body") + .css('visibility','hidden'); + + + + this.show = function() + { + switch(settings.preloadPosition) + { + case 'center': + loadertop = smallimagedata.pos.t + (smallimagedata.h - $(this.node ).height())/2; + loaderleft = smallimagedata.pos.l + (smallimagedata.w - $(this.node ).width())/2; + break; + default: + var loaderoffset = this.getoffset(); + loadertop = !isNaN(loaderoffset.top) ? smallimagedata.pos.t + loaderoffset.top : smallimagedata.pos.t + 0; + loaderleft = !isNaN(loaderoffset.left) ? smallimagedata.pos.l + loaderoffset.left : smallimagedata.pos.l + 0; + break; + } + + //setting position + $(this.node).css({ + top: loadertop , + left: loaderleft , + position: 'absolute', + visibility:'visible' + }); + } + return this; + } + + Loader.prototype.getoffset = function() + { + var o = null; + o = $('div.preload').offset(); + return o; + } + + }); + } +})(jQuery); + + function trim(stringa) + { + while (stringa.substring(0,1) == ' '){ + stringa = stringa.substring(1, stringa.length); + } + while (stringa.substring(stringa.length-1, stringa.length) == ' '){ + stringa = stringa.substring(0,stringa.length-1); + } + return stringa; + } \ No newline at end of file diff --git a/site/inc/js/jquery.js b/site/inc/js/jquery.js new file mode 100644 index 0000000..b1ae21d --- /dev/null +++ b/site/inc/js/jquery.js @@ -0,0 +1,19 @@ +/* + * 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=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;G1||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-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+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("",""]||!O.indexOf("",""]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
    "]||!O.indexOf("",""]||(!O.indexOf("",""]||!O.indexOf("",""]||!o.support.htmlSerialize&&[1,"div
    ","
    "]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/"&&!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;E0?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":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=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 UT[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=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";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="";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="

    ";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="
    ";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;W0){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;Z0||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=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("
    ").append(M.responseText.replace(//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").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=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=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='
    ';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 diff --git a/site/inc/js/jquery.maphilight.js b/site/inc/js/jquery.maphilight.js new file mode 100644 index 0000000..d011413 --- /dev/null +++ b/site/inc/js/jquery.maphilight.js @@ -0,0 +1 @@ +(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('').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').get(0)};j=function(o,r,s,v,n){var t,u,p,q;t='';u=(v.stroke?'strokeweight="'+v.strokeWidth+'" stroked="t" strokecolor="#'+v.strokeColor+'"':'stroked="f"');p='';if(r=="rect"){q=f('')}else{if(r=="poly"){q=f('')}else{if(r=="circ"){q=f('')}}}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;n0)){return}if(v.hasClass("maphilighted")){var q=v.parent();v.insertBefore(q);q.remove()}s=f("
    ").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 diff --git a/site/inc/routines/routines.php b/site/inc/routines/routines.php new file mode 100644 index 0000000..f906ef3 --- /dev/null +++ b/site/inc/routines/routines.php @@ -0,0 +1,38 @@ +get('action'); + +switch($rotina) { + case 'insertComentario': + $load->config('classes/CasoEstudo.php'); + $o_casoEstudo = new CasoEstudo(); + $retorno = $o_casoEstudo->insertComentario(); + switch($retorno){ + case 0: + $input->setSession('msg','Erro ao inserir comentário. Tente novamente mais tarde.'); + break; + case 1: + $input->setSession('msg','Comentário inserido com sucesso!'); + break; + } + redir($_SERVER["HTTP_REFERER"]); + die; + break; + case 'inativeComentario': + $load->config('classes/CasoEstudo.php'); + $o_casoEstudo = new CasoEstudo(); + $retorno = $o_casoEstudo->inativeComentario($input->get('id')); + switch($retorno){ + case 0: + $input->setSession('msg','Erro ao inativar comentário. Tente novamente mais tarde.'); + break; + case 1: + $input->setSession('msg','Comentário inativado com sucesso!'); + break; + } + redir($_SERVER["HTTP_REFERER"]); + die; + break; +} +?> \ No newline at end of file diff --git a/site/inc/structure/footer.php b/site/inc/structure/footer.php new file mode 100644 index 0000000..1114c4b --- /dev/null +++ b/site/inc/structure/footer.php @@ -0,0 +1,12 @@ +close(); +//google analytics +if($input->session('session_msg') != ''){ +?> + +unsetSession('session_msg'); +} +?> \ No newline at end of file diff --git a/site/inc/structure/grupoorgao.php b/site/inc/structure/grupoorgao.php new file mode 100644 index 0000000..521faaa --- /dev/null +++ b/site/inc/structure/grupoorgao.php @@ -0,0 +1,50 @@ +config('classes/GrupoOrgao.php'); +$o_grupoOrgao = new GrupoOrgao(); +$rowsCamada = $o_grupoOrgao->findCamadas(); +?> + + + + + + + + + + + + + + + + + + +
    + Topografia

    + Selecione uma camada topográfica e clique sobre o corpo. +
    + EOF){ + $rowsGrupoOrgao = $o_grupoOrgao->findGrupoByCamada($rowsCamada->fields('id')); + if(!$rowsGrupoOrgao->EOF){?> +
    + +
    + + EOF){?> + <?=$rowsGrupoOrgao->fields('nome');?> + moveNext(); + }?> + + moveNext(); + }?> +
    + (Mostrar Todos os pontos da camada selecionada) +
    + +
    + + \ No newline at end of file diff --git a/site/inc/structure/header.php b/site/inc/structure/header.php new file mode 100644 index 0000000..6efece1 --- /dev/null +++ b/site/inc/structure/header.php @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/site/inc/structure/language.php b/site/inc/structure/language.php new file mode 100644 index 0000000..84e1fd6 --- /dev/null +++ b/site/inc/structure/language.php @@ -0,0 +1,14 @@ +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 diff --git a/site/inc/structure/paginacao.php b/site/inc/structure/paginacao.php new file mode 100644 index 0000000..bfec9e7 --- /dev/null +++ b/site/inc/structure/paginacao.php @@ -0,0 +1,44 @@ + $pagelist){ + if($actualPage > ceil($pagelist/2)){ + $initialPage = $actualPage-ceil($pagelist/2); + } + if($initialPage > $totalPage-$pagelist){ + $initialPage = $totalPage-$pagelist; + } + if($finalPage > $initialPage+$pagelist){ + $finalPage = $initialPage+$pagelist; + } + } + //põe pagina 1 + if($initialPage > 1){?> +  ...    + +     + +     + + ...  + \ No newline at end of file diff --git a/site/inc/structure/popup_download.php b/site/inc/structure/popup_download.php new file mode 100644 index 0000000..89269c3 --- /dev/null +++ b/site/inc/structure/popup_download.php @@ -0,0 +1,32 @@ + + + + + + +
    + + + + + + + + + + +
    + Atenção +
    + 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. +

    + 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. +
    + +
    +
    + + \ No newline at end of file diff --git a/site/inc/structure/popup_zoom.php b/site/inc/structure/popup_zoom.php new file mode 100644 index 0000000..dd9fbed --- /dev/null +++ b/site/inc/structure/popup_zoom.php @@ -0,0 +1,87 @@ +get("iframe") == "none") { + ?> + + + + + +
    + + + + +
    + +
    +
    + + + + + + \ No newline at end of file diff --git a/site/inc/structure/popup_zoom1.php b/site/inc/structure/popup_zoom1.php new file mode 100644 index 0000000..d5d69f5 --- /dev/null +++ b/site/inc/structure/popup_zoom1.php @@ -0,0 +1,12 @@ + + + + + + + + + \ No newline at end of file diff --git a/site/inc/structure/posApp.php b/site/inc/structure/posApp.php new file mode 100644 index 0000000..96ded23 --- /dev/null +++ b/site/inc/structure/posApp.php @@ -0,0 +1,10 @@ +system('functions/swf.php'); +$load->config('classes/Helper.php'); +$o_helper = new Helper(); +$load->config('classes/Html.php'); +$o_html = new Html(); +global $o_helper; +global $selected; +?> \ No newline at end of file diff --git a/site/inc/structure/rodape.php b/site/inc/structure/rodape.php new file mode 100644 index 0000000..41bf4c3 --- /dev/null +++ b/site/inc/structure/rodape.php @@ -0,0 +1,16 @@ + + +   + + + + + + + + +
    + © Copyright - SIAP - Sistema de Imagens Anatomopatológicas +
    + + \ No newline at end of file diff --git a/site/inc/structure/topo.php b/site/inc/structure/topo.php new file mode 100644 index 0000000..98d1b09 --- /dev/null +++ b/site/inc/structure/topo.php @@ -0,0 +1,41 @@ + + + + + + + + + + + + + +
    +
     
    +
     
    +
     
    +
     
    + + + getMenu('diagnosticos','../diagnosticos');?> + getMenu('orgaos','../orgaos');?> + getMenu('necropsia','../necropsia');?> + getMenu('casosdeestudo','../casosdeestudo');?> + getMenu('imagens','../imagens');?> + +
    +
    + + + + + +
    + alt('Área Restrita');?> /> + + alt('Acessar');?> /> +
    +
    + + diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..b8dab5a --- /dev/null +++ b/site/index.html @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/test.php b/test.php new file mode 100644 index 0000000..317a4de --- /dev/null +++ b/test.php @@ -0,0 +1,4 @@ + -- 1.7.6.4