Ir para conteúdo
Fórum CódigoFonte.net

igorfds

Membros
  • Total de itens

    8
  • Registro em

  • Última visita

  1. Fiz em PHP mesmo! if (substr($dataini,4,2)==substr($datafim,4,2) && substr($dataini,7,4)==substr($datafim,7,4)){ $configurar= new configurar(); $configurar->setConfiguracao($cnpj,$dataini,$datafim); }else{ echo "<script type='text/javascript'> alert('O intervalo de datas n&atilde;o pode ser maior que 31 dias!'); </script>";
  2. Até Peguei uma if var dtFrom=$("#dateFrom").val().split("/"); var dtTo=$("#dateTo").val().split("/"); var dtF=new Date(dtFrom[2],dtFrom[1]-1,dtFrom[0]); var dtT=new Date(dtTo[2],dtTo[1]-1,dtTo[0]); if(!(dtT.getTime()-dtF.getTime()<4*31*86400000)&&(dtT.getTime()-dtF.getTime()>0)){exibeErro("O intervalo de tempo máximo deve ser 4 meses."); Mais não sei com inserir na validação que fiz ! <script> function valida(){ var campo = document.getElementById("dataini"); if(campo.value == ""){ alert("Insira uma data valida!"); return false; } var campo = document.getElementById("datafim"); if(campo.value == ""){ alert("Insira uma data valida!"); return false; } var campo = document.getElementById("cnpj"); if(campo.value == ""){ alert("Insira um CNPJ cadastrado!"); return false; } } </script> Ninguem consegue me ajudar PELO AMOR.... rsrs
  3. Olá.. Tenho um sistema simples de consulta e precisaria somente colocar uma validação que limitasse um período máximo de 3 meses para a consulta! Tenho um script de validação, mais não estou sabendo criar um if para limitar isso! <script> function valida(){ var campo = document.getElementById("dataini"); if(campo.value == ""){ alert("Insira uma data valida!"); return false; } var campo = document.getElementById("datafim"); if(campo.value == ""){ alert("Insira uma data valida!"); return false; } var campo = document.getElementById("cnpj"); if(campo.value == ""){ alert("Insira um CNPJ cadastrado!"); return false; } } </script>
  4. Precisava de uma ajudinha acho que rápida! Tenho um sistema de consulta que está abrindo em um modal... mais como tenho permissões de usuários, preciso passar um parâmetro pra essa busca... Não Tenho nem idéia de como fazer! var dialog = document.getElementById ('dialog'); $(dialog).load('/sistema/class/menu_config_consult.php'); <!--LINK DE BUSCA E EDIÇÃO --> Codigo inteiro do modal! <script type="text/javascript"> $(document).ready(function() { $('a[name=modal]').click(function(e) { e.preventDefault(); var id = $(this).attr('href'); var maskHeight = $(document).height(); var maskWidth = $(window).width(); $('#mask').css({'width':maskWidth,'height':maskHeight}); $('#mask').fadeIn(1000); $('#mask').fadeTo("slow",0.8); //Get the window height and width var winH = $(window).height(); var winW = $(window).width(); $(id).css('top', winH/2-$(id).height()/2); $(id).css('left', winW/2-$(id).width()/2); $(id).fadeIn(2000); }); $('.window .close').click(function (e) { e.preventDefault(); $('#mask').hide(); $('.window').hide(); }); $('#mask').click(function () { $(this).hide(); $('.window').hide(); }); var dialog = document.getElementById ('dialog'); $(dialog).load('/sistema/class/menu_config_consult.php'); <!--LINK DE BUSCA E EDIÇÃO --> }); </script> Se alguem puder ajudar agradeço!
  5. igorfds

    Ajustar Drop Area a Download

    Possuo um sistema de upload "fancyupload" e paralelamente gostaria de add uma DropArea que já tenho pronta tb... O problema é que não estou conseguindo ajustar para que ao arrastar os arquivos entre na área do fancy! Segue js.... primeiro o do fancyupload, depois da drop! <script type="text/javascript" > window.addEvent('load', function() { var swiffy = new FancyUpload2($('status'), $('images-list'), { url: $('form_imagens').action, fieldName: 'photoupload', path: 'Swiff.Uploader.swf', onLoad: function() { $('loading').destroy(); $('status').removeClass('hide'); this.options.typeFilter = {'Arquivos (*.xml, *.zip, *.XML, *.ZIP )': '*.xml; *.zip; *.XML; *.ZIP'}; }, limitFiles: 300, debug: true, target: 'add-image' }); $('add-image').addEvent('click', function() { swiffy.browse(); return false; }); $('clear-list').addEvent('click', function() { swiffy.removeFile(); return false; }); $('upload-images').addEvent('click', function() { swiffy.upload(); return false; }); }); </script> <script type="text/javascript" > function uploader(place, status, targetPHP, show) { // Upload image files upload = function(file) { // Firefox 3.6, Chrome 6, WebKit if(window.FileReader) { // Once the process of reading file this.loadEnd = function() { bin = reader.result; xhr = new XMLHttpRequest(); xhr.open('POST', targetPHP+'?up=true', true); var boundary = 'xxxxxxxxx'; var body = '--' + boundary + "\r\n"; body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n"; body += "Content-Type: application/octet-stream\r\n\r\n"; body += bin + "\r\n"; body += '--' + boundary + '--'; xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary); // Firefox 3.6 provides a feature sendAsBinary () if(xhr.sendAsBinary != null) { xhr.sendAsBinary(body); // Chrome 7 sends data but you must use the base64_decode on the PHP side } else { xhr.open('POST', targetPHP+'?up=true&base64=true', true); xhr.setRequestHeader('UP-FILENAME', file.name); xhr.setRequestHeader('UP-SIZE', file.size); xhr.setRequestHeader('UP-TYPE', file.type); xhr.send(window.btoa(bin)); } if (show) { var newFile = document.createElement('div'); newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B'; document.getElementById(show).appendChild(newFile); } if (status) { document.getElementById(status).innerHTML = 'Loaded : 100%<br/>Next file ...'; } } // Loading errors this.loadError = function(event) { switch(event.target.error.code) { case event.target.error.NOT_FOUND_ERR: document.getElementById(status).innerHTML = 'File not found!'; break; case event.target.error.NOT_READABLE_ERR: document.getElementById(status).innerHTML = 'File not readable!'; break; case event.target.error.ABORT_ERR: break; default: document.getElementById(status).innerHTML = 'Read error.'; } } // Reading Progress this.loadProgress = function(event) { if (event.lengthComputable) { var percentage = Math.round((event.loaded * 100) / event.total); document.getElementById(status).innerHTML = 'Loaded : '+percentage+'%'; } } // Preview images this.previewNow = function(event) { bin = preview.result; var img = document.createElement("img"); img.className = 'addedIMG'; img.file = file; img.src = bin; document.getElementById(show).appendChild(img); } reader = new FileReader(); // Firefox 3.6, WebKit if(reader.addEventListener) { reader.addEventListener('loadend', this.loadEnd, false); if (status != null) { reader.addEventListener('error', this.loadError, false); reader.addEventListener('progress', this.loadProgress, false); } // Chrome 7 } else { reader.onloadend = this.loadEnd; if (status != null) { reader.onerror = this.loadError; reader.onprogress = this.loadProgress; } } var preview = new FileReader(); // Firefox 3.6, WebKit if(preview.addEventListener) { preview.addEventListener('loadend', this.previewNow, false); // Chrome 7 } else { preview.onloadend = this.previewNow; } // The function that starts reading the file as a binary string reader.readAsBinaryString(file); // Preview uploaded files if (show) { preview.readAsDataURL(file); } // Safari 5 does not support FileReader } else { xhr = new XMLHttpRequest(); xhr.open('POST', targetPHP+'?up=true', true); xhr.setRequestHeader('UP-FILENAME', file.name); xhr.setRequestHeader('UP-SIZE', file.size); xhr.setRequestHeader('UP-TYPE', file.type); xhr.send(file); if (status) { document.getElementById(status).innerHTML = 'Loaded : 100%'; } if (show) { var newFile = document.createElement('div'); newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B'; document.getElementById(show).appendChild(newFile); } } } // Function drop file this.drop = function(event) { event.preventDefault(); var dt = event.dataTransfer; var files = dt.files; for (var i = 0; i<files.length; i++) { var file = files[i]; upload(file); } } // The inclusion of the event listeners (DragOver and drop) this.uploadPlace = document.getElementById(place); this.uploadPlace.addEventListener("dragover", function(event) { event.stopPropagation(); event.preventDefault(); }, true); this.uploadPlace.addEventListener("drop", this.drop, false); } </script> Obrigadoo!
  6. igorfds

    Inserir Validação Java em html5

    Olá Bom Dia! Peguei um script pronto http://www.ohmsapoio.com.br/sistema_testes/upload/upload/examples/jquery/events.html de upload de arquivos... o problema agora é que tenho um sistema de validação em meu BD que preciso inserir neste script! e como não conheço nada de JS fica difícil! Segue js que veio e o js que preciso inserir! Script de envio do index: <script type="text/javascript"> $(function() { function log() { var str = ""; plupload.each(arguments, function(arg) { var row = ""; if (typeof(arg) != "string") { plupload.each(arg, function(value, key) { // Convert items in File objects to human readable form if (arg instanceof plupload.File) { // Convert status to human readable switch (value) { case plupload.QUEUED: value = 'QUEUED'; break; case plupload.UPLOADING: value = 'UPLOADING'; break; case plupload.FAILED: value = 'FAILED'; break; case plupload.DONE: value = 'DONE'; break; } } if (typeof(value) != "function") { row += (row ? ', ': '') + key + '=' + value; } }); str += row + " "; } else { str += arg + " "; } }); $('#log').val($('#log').val() + str + "\r\n"); } $("#uploader").pluploadQueue({ // General settings runtimes: 'html5,gears,browserplus,silverlight,flash,html4', url: 'upload/examples/upload.php', max_file_size: '100mb', chunk_size: '100mb', unique_names: false, // Resize images on clientside if we can resize: {width: 320, height: 240, quality: 90}, // Specify what files to browse for filters: [ {title: "Image files", extensions: "zip,ZIP,xml,XML"}, ], // Flash/Silverlight paths flash_swf_url: 'upload/plupload.flash.swf', silverlight_xap_url: 'upload/js/plupload.silverlight.xap', // PreInit events, bound before any internal events preinit: { Init: function(up, info) { log('[Init]', 'Info:', info, 'Features:', up.features); }, UploadFile: function(up, file) { log('[UploadFile]', file); // You can override settings before the file is uploaded // up.settings.url = 'upload.php?id=' + file.id; // up.settings.multipart_params = {param1: 'value1', param2: 'value2'}; } }, // Post init events, bound after the internal events init: { Refresh: function(up) { // Called when upload shim is moved log('[Refresh]'); }, StateChanged: function(up) { // Called when the state of the queue is changed log('[StateChanged]', up.state == plupload.STARTED ? "STARTED": "STOPPED"); }, QueueChanged: function(up) { // Called when the files in queue are changed by adding/removing files log('[QueueChanged]'); }, UploadProgress: function(up, file) { // Called while a file is being uploaded log('[UploadProgress]', 'File:', file, "Total:", up.total); }, FilesAdded: function(up, files) { // Callced when files are added to queue log('[FilesAdded]'); plupload.each(files, function(file) { log(' File:', file); }); }, FilesRemoved: function(up, files) { // Called when files where removed from queue log('[FilesRemoved]'); plupload.each(files, function(file) { log(' File:', file); }); }, FileUploaded: function(up, file, info) { // Called when a file has finished uploading log('[FileUploaded] File:', file, "Info:", info); }, ChunkUploaded: function(up, file, info) { // Called when a file chunk has finished uploading log('[ChunkUploaded] File:', file, "Info:", info); }, Error: function(up, args) { // Called when a error has occured // Handle file specific error and general error if (args.file) { log('[error]', args, "File:", args.file); } else { log('[error]', args); } } } }); $('#log').val(''); $('#clear').click(function(e) { e.preventDefault(); $("#uploader").pluploadQueue().splice(); }); }); </script> Destino Upload.php <?php /** * upload.php * * Copyright 2009, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ // HTTP headers for no cache etc header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // Settings //$targetDir = ''; $targetDir = '../../../nfe'; //$targetDir = '../../../nfe12'; $cleanupTargetDir = true; // Remove old files $maxFileAge = 5 * 3600; // Temp file age in seconds // 5 minutes execution time @set_time_limit(5 * 60); // Uncomment this one to fake upload time // usleep(5000); // Get parameters $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0; $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; // Clean the fileName for security reasons $fileName = preg_replace('/[^\w\._]+/', '_', $fileName); // Make sure the fileName is unique but only if chunking is disabled if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) { $ext = strrpos($fileName, '.'); $fileName_a = substr($fileName, 0, $ext); $fileName_b = substr($fileName, $ext); $count = 1; while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) $count++; $fileName = $fileName_a . '_' . $count . $fileName_b; } $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; // Create target dir if (!file_exists($targetDir)) @mkdir($targetDir); // Remove old temp files if ($cleanupTargetDir) { if (is_dir($targetDir) && ($dir = opendir($targetDir))) { while (($file = readdir($dir)) !== false) { $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; // Remove temp file if it is older than the max age and is not the current file if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) { @unlink($tmpfilePath); } } closedir($dir); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); } } // Look for the content type header if (isset($_SERVER["HTTP_CONTENT_TYPE"])) $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; if (isset($_SERVER["CONTENT_TYPE"])) $contentType = $_SERVER["CONTENT_TYPE"]; // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5 if (strpos($contentType, "multipart") !== false) { if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { // Open temp file $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = @fopen($_FILES['file']['tmp_name'], "rb"); if ($in) { while ($buff = fread($in, 4096)) fwrite($out, $buff); } else die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); @fclose($in); @fclose($out); @unlink($_FILES['file']['tmp_name']); } else die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } else die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } else { // Open temp file $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = @fopen("php://input", "rb"); if ($in) { while ($buff = fread($in, 4096)) fwrite($out, $buff); } else die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); @fclose($in); @fclose($out); } else die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } // Check if file has been uploaded if (!$chunks || $chunk == $chunks - 1) { // Strip the temp .part suffix off rename("{$filePath}.part", $filePath); } die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); js (function(c){var d={};function a(e){return plupload.translate(e)||e}function b(f,e){e.contents().each(function(g,h){h=c(h);if(!h.is(".plupload")){h.remove()}});e.prepend('<div class="plupload_wrapper plupload_scroll"><div id="'+f+'_container" class="plupload_container"><div class="plupload"><div class="plupload_header"><div class="plupload_header_content"><div class="plupload_header_title">'+a("")+'</div><div class="plupload_header_text">'+a("")+'</div></div></div><div class="plupload_content"><div class="plupload_filelist_header"><div class="plupload_file_name">'+a("Nome do Arquivo")+'</div><div class="plupload_file_action">&nbsp;</div><div class="plupload_file_status"><span>'+a("Status")+'</span></div><div class="plupload_file_size">'+a("Tamanho")+'</div><div class="plupload_clearer">&nbsp;</div></div><ul id="'+f+'_filelist" class="plupload_filelist"></ul><div class="plupload_filelist_footer"><div class="plupload_file_name"><div class="plupload_buttons"><a href="#" class="plupload_button plupload_add">'+a("Buscar Arquivos")+'</a><a href="#" class="plupload_button plupload_start">'+a("Iniciar Upload")+'</a></div><span class="plupload_upload_status"></span></div><div class="plupload_file_action"></div><div class="plupload_file_status"><span class="plupload_total_status">0%</span></div><div class="plupload_file_size"><span class="plupload_total_file_size">0 b</span></div><div class="plupload_progress"><div class="plupload_progress_container"><div class="plupload_progress_bar"></div></div></div><div class="plupload_clearer">&nbsp;</div></div></div></div></div><input type="hidden" id="'+f+'_count" name="'+f+'_count" value="0" /></div>')}c.fn.pluploadQueue=function(e){if(e){this.each(function(){var j,i,k;i=c(this);k=i.attr("id");if(!k){k=plupload.guid();i.attr("id",k)}j=new plupload.Uploader(c.extend({dragdrop:true,container:k},e));d[k]=j;function h(l){var n;if(l.status==plupload.DONE){n="plupload_done"}if(l.status==plupload.FAILED){n="plupload_failed"}if(l.status==plupload.QUEUED){n="plupload_delete"}if(l.status==plupload.UPLOADING){n="plupload_uploading"}var m=c("#"+l.id).attr("class",n).find("a").css("display","block");if(l.hint){m.attr("title",l.hint)}}function f(){c("span.plupload_total_status",i).html(j.total.percent+"%");c("div.plupload_progress_bar",i).css("width",j.total.percent+"%");c("span.plupload_upload_status",i).html(a("Baixando %d/%d arquivos").replace(/%d\/%d/,j.total.uploaded+"/"+j.files.length))}function g(){var m=c("ul.plupload_filelist",i).html(""),n=0,l;c.each(j.files,function(p,o){l="";if(o.status==plupload.DONE){if(o.target_name){l+='<input type="hidden" name="'+k+"_"+n+'_tmpname" value="'+plupload.xmlEncode(o.target_name)+'" />'}l+='<input type="hidden" name="'+k+"_"+n+'_name" value="'+plupload.xmlEncode(o.name)+'" />';l+='<input type="hidden" name="'+k+"_"+n+'_status" value="'+(o.status==plupload.DONE?"done":"failed")+'" />';n++;c("#"+k+"_count").val(n)}m.append('<li id="'+o.id+'"><div class="plupload_file_name"><span>'+o.name+'</span></div><div class="plupload_file_action"><a href="#"></a></div><div class="plupload_file_status">'+o.percent+'%</div><div class="plupload_file_size">'+plupload.formatSize(o.size)+'</div><div class="plupload_clearer">&nbsp;</div>'+l+"</li>");h(o);c("#"+o.id+".plupload_delete a").click(function(q){c("#"+o.id).remove();j.removeFile(o);q.preventDefault()})});c("span.plupload_total_file_size",i).html(plupload.formatSize(j.total.size));if(j.total.queued===0){c("span.plupload_add_text",i).html(a("Add files."))}else{c("span.plupload_add_text",i).html(j.total.queued+" files queued.")}c("a.plupload_start",i).toggleClass("plupload_disabled",j.files.length==(j.total.uploaded+j.total.failed));m[0].scrollTop=m[0].scrollHeight;f();if(!j.files.length&&j.features.dragdrop&&j.settings.dragdrop){c("#"+k+"_filelist").append('<li class="plupload_droptext">'+a("")+"</li>")}}j.bind("UploadFile",function(l,m){c("#"+m.id).addClass("plupload_current_file")});j.bind("Init",function(l,m){b(k,i);if(!e.unique_names&&e.rename){i.on("click","#"+k+"_filelist div.plupload_file_name span",function(s){var q=c(s.target),o,r,n,p="";o=l.getFile(q.parents("li")[0].id);n=o.name;r=/^(.+)(\.[^.]+)$/.exec(n);if(r){n=r[1];p=r[2]}q.hide().after('<input type="text" />');q.next().val(n).focus().blur(function(){q.show().next().remove()}).keydown(function(u){var t=c(this);if(c.inArray(u.keyCode,[13,27])!==-1){u.preventDefault();if(u.keyCode===13){o.name=t.val()+p;q.html(o.name)}t.blur()}})})}c("a.plupload_add",i).attr("id",k+"_browse");l.settings.browse_button=k+"_browse";if(l.features.dragdrop&&l.settings.dragdrop){l.settings.drop_element=k+"_filelist";c("#"+k+"_filelist").append('<li class="plupload_droptext">'+a("")+"</li>")}c("#"+k+"_container").attr("title","Utilizando: "+m.runtime);c("a.plupload_start",i).click(function(n){if(!c(this).hasClass("plupload_disabled")){j.start()}n.preventDefault()});c("a.plupload_stop",i).click(function(n){n.preventDefault();j.stop()});c("a.plupload_start",i).addClass("plupload_disabled")});j.init();j.bind("Error",function(l,o){var m=o.file,n;if(m){n=o.message;if(o.details){n+=" ("+o.details+")"}if(o.code==plupload.FILE_SIZE_ERROR){alert(a("Erro: Arquivo muito grande, Máx. permitido 90MB!: ")+m.name)}if(o.code==plupload.FILE_EXTENSION_ERROR){alert(a("Erro: Extensao de arquivo invalida! Permitido somente arquivos xml e zip: ")+m.name)}m.hint=n;c("#"+m.id).attr("class","plupload_failed").find("a").css("display","block").attr("title",n)}});j.bind("StateChanged",function(){if(j.state===plupload.STARTED){c("li.plupload_delete a,div.plupload_buttons",i).hide();c("span.plupload_upload_status,div.plupload_progress,a.plupload_stop",i).css("display","block");c("span.plupload_upload_status",i).html("Baixando "+j.total.uploaded+"/"+j.files.length+" files");if(e.multiple_queues){c("span.plupload_total_status,span.plupload_total_file_size",i).show()}}else{g();c("a.plupload_stop,div.plupload_progress",i).hide();c("a.plupload_delete",i).css("display","block")}});j.bind("QueueChanged",g);j.bind("FileUploaded",function(l,m){h(m)});j.bind("UploadProgress",function(l,m){c("#"+m.id+" div.plupload_file_status",i).html(m.percent+"%");h(m);f();if(e.multiple_queues&&j.total.uploaded+j.total.failed==j.files.length){c(".plupload_buttons,.plupload_upload_status",i).css("display","inline");c(".plupload_start",i).addClass("plupload_disabled");c("span.plupload_total_status,span.plupload_total_file_size",i).hide()}});if(e.setup){e.setup(j)}});return this}else{return d[c(this[0]).attr("id")]}}})(jQuery); SCRIPT DO MEU BD QUE PRECISO INSERIR <?php session_start(); require_once('../../BD/conexao2.php'); $xml = new XMLReader (); $n_infNFe = 0; $n_infCanc = 'NULL'; $n_nItem = 0; $a_colunas = array(array()); $d_dEmi = date("YYYY-mm-dd"); $s_Id = ''; $sql_insert = array(); $n_insert = 0; $result = array(); #Contar Importações $n_NF = 0; $n_CANC = 0; $n_INUT = 0; $n_EXIS = 0; $n_REJE = 0; $n_ERRO = 0; $n_arqComp =0; /** * Esta função descompacta arquivos * de um zip * @param String $path: Local do arquivo .zip * @param String $pathunzip: Pasta onde os arquivos devem ser descompactados */ function unZip($path,$caminho){ criar_pasta('compac'); # ===— Instancia a classe do Zip $zip = new ZipArchive; # ===— Tenta abrir o zip if($zip->open($path)){ $return = $zip->extractTo($caminho.'/compac'); // executa o unzip } else { // echo 'O arquivo não pode ser aberto.'; } $zip->close(); // fecha a coneção com o .zip } function GravaLog($usuario, $tela, $acao) { extract($_GET); $horario = date(" Y-m-d H:i:s"); $ips=getIp(); $inseri=mssql_query("INSERT INTO TBL_LOG (COD_USUARIO , TELA, ACAO, DATA_INC,IP) VALUES ("."'".$usuarios."'".","."'".$tela."'".","."'".$acao."'".","."'".$horario."'".","."'".$ips."'".")"); } function getIp() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else{ $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } function LerArquivosCompactados(){ $pasta = "../nfe/compac"; $listar = new RecursiveDirectoryIterator($pasta); $recursivo = new RecursiveIteratorIterator($listar); foreach($recursivo as $obj){ //echo $obj->getFilename().'<br />'; //echo $obj->getPathname().'<br />'; // $caminho = str_replace("\\","/",$obj->getPath()); $nome = $obj->getBasename(); //echo $caminho.'<br>'; //echo $nome.'<br><br>'; if (strtoupper(substr($nome,-4)) == ".XML"){ //echo 'arquivo xml'; $de = $caminho.'/'.$nome; rename($de, '../nfe/'.$nome); // echo "Arquivo renomeado com sucesso.<br>"; // else // echo "Não foi possível renomear o arquivo.<br>"; } } } function unRar($filename,$filepath){ $rar_file = rar_open('02.rar') or die("Can't open Rar archive"); $entries = rar_list($rar_file); foreach ($entries as $entry) { // echo 'Filename: ' . $entry->getName() . "\n"; // echo 'Packed size: ' . $entry->getPackedSize() . "\n"; // echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n"; $entry->extract('/dir/extract/to/'); } rar_close($rar_file); } # Validar XML --------------------------------------------------------------------- function libxml_display_errors() { $errors = libxml_get_errors(); foreach ($errors as $error) { $return = "<br/>\n"; switch ($error->level) { case LIBXML_ERR_WARNING: $return .= "<b>Warning $error->code</b>: "; break; case LIBXML_ERR_ERROR: $return .= "<b>Error $error->code</b>: "; break; case LIBXML_ERR_FATAL: $return .= "<b>Fatal Error $error->code</b>: "; break; } $return .= trim($error->message); if ($error->file) { $return .= " in <b>$error->file</b>"; } $return .= " on line <b>$error->line</b>\n"; //print($return); } libxml_clear_errors(); } function Valida_XML($arq_xml){ global $d_dEmi; $xml = new DOMDocument(); $xml->load($arq_xml); if (($xml->schemaValidate('xsd/procNFe_v2.00.xsd')) || ($xml->schemaValidate('xsd/nfe_v2.00.xsd'))){ $v_retorno = 'NF'; $datas = $xml->getElementsByTagName( "dEmi" ); $d_dEmi = $datas->item(0)->nodeValue; }elseif (($xml->schemaValidate('xsd/procCancNFe_v2.00.xsd')) || ($xml->schemaValidate('xsd/cancNFe_v2.00.xsd'))){ $v_retorno = 'CANC'; }elseif (($xml->schemaValidate('xsd/procInutNFe_v2.00.xsd')) || ($xml->schemaValidate('xsd/inutNFe_v2.00.xsd'))) { $v_retorno = 'INUT'; }else{ $v_retorno = 'REJEITADO'; libxml_display_errors(); } return $v_retorno; } # Fim Validar XML --------------------------------------------------------------------- function remove_aspas($texto){ $texto = $palavra = str_replace('\/', '|',$texto); $texto = $palavra = str_replace('\\', '|',$texto); $texto = $palavra = str_replace('\'', '|',$texto); return $palavra = str_replace("\"", "|",$texto); } //Busca Sequencia de Inserções function prox_seq($tabela){ $sql = mssql_query("EXEC FCT_NFE_SEQ_PROX '".$tabela."'"); $linha = mssql_fetch_assoc($sql); return $linha['SEQ']; } //Identificação do Tipo do Campo function carrega_tipo_campo (){ global $a_colunas; $sql = mssql_query("SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM tbl_nfe_layout"); while ($linha = mssql_fetch_array($sql)){ $a_colunas[strtoupper($linha['TABLE_NAME'])][strtoupper($linha['COLUMN_NAME'])] = strtoupper($linha['DATA_TYPE']); } } function tipo_campo ($tabela,$coluna){ global $a_colunas; return $a_colunas[strtoupper("tbl_nfe_".$tabela)][strtoupper($coluna)]; } function grava_insert($sql){ global $sql_insert, $n_insert; $n_insert += 1; $sql_insert[$n_insert] = $sql; } function executa_insert () { global $sql_insert, $n_insert; $null = mssql_query("BEGIN TRANSACTION"); for($i=1;$i<=$n_insert;$i++){ #print($sql_insert[$i].';<br>'); $exec = mssql_query($sql_insert[$i]); if (! $exec){ $n_insert = -1; } } if ($n_insert == -1){ $v_return = "Erro"; #print('ROLLBACK<br>'); $null = mssql_query("ROLLBACK"); } else { $v_return = "OK"; #print('COMMIT<br>'); $null = mssql_query("COMMIT"); } $n_insert = 0; return $v_return; } function exec_sql($sql){ $exec = mssql_query($sql); if (! $exec) { print($sql."<br>"); $null = mssql_query("INSERT INTO TBL_NFE_SQL_ERRO (DATA, COMANDO) VALUES (GETDATE(), '".$sql."')"); } return $exec; } function exec_insert_xml ($n_infNFe, $s_Id, $s_pasta, $s_arquivo, $s_status){ global $n_infCanc; if ($n_infCanc <> 'null') { $s_status = 'NF_CANC'; } $exec = exec_sql("INSERT INTO TBL_NFE_XML (infNFE,Id,PASTA_ARQUIVO,NOME_ARQUIVO,STATUS, infCanc) VALUES (".$n_infNFe.",'".$s_Id."','".$s_pasta."','".$s_arquivo."','".$s_status."',".$n_infCanc.")"); } //Gravar infNFe function grava_infNFe (){ global $xml, $n_infNFe, $s_Id; $n_infNFe = 0; if( $xml -> hasAttributes ) { $campos = ''; $valores = ''; while( $xml -> moveToNextAttribute ()) { $tipo_campo = tipo_campo('infNFe',$xml->name); if ($tipo_campo <> ''){ if ($xml->name == 'Id'){ $sql_id = mssql_query("SELECT COUNT(1) AS EXISTE FROM TBL_NFE_infNFe where Id = '".$xml->value."'"); $linha_id = mssql_fetch_assoc($sql_id); $s_Id = $xml->value; if ($linha_id['EXISTE'] > 0){ $n_infNFe = -1; } } if ($campos <> '') { $campos = $campos.","; } $campos = $campos.$xml->name; if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } } } if ($n_infNFe == 0){ $n_infNFe = prox_seq('infNFe'); grava_insert("INSERT INTO TBL_NFE_infNFe (infNFe,".$campos.") VALUES (".$n_infNFe.",".$valores.")"); } } } //gravar os filhos da infNFe function grava_infNFe_pai ($tag){ global $xml, $n_infNFe; $no = $xml->depth; $xml->read(); $campos = ''; $valores = ''; while ($no < $xml->depth) { if ($xml->name == 'NFref'){ grava_infNFe_pai('NFref'); } if( $xml -> nodeType == XMLReader :: ELEMENT ){ if ($xml->name == 'mod') { $tipo_campo = 'VARCHAR'; }else{ $tipo_campo = tipo_campo($tag,$xml->name); } if ($tipo_campo <> ''){ $campo = ''; if ($campos <> '') { $campo = ","; } } if ($xml->name == 'mod') { $campo = $campo.'modelo'; }else{ $campo = $campo.$xml->name; } } if( $xml -> nodeType == XMLReader :: TEXT ){ if ($tipo_campo <> ''){ if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."CONVERT(DATETIME,'"; } if ($campo == ',dSaiEnt'){ $v_dSaiEnt = $xml->value; } if ($campo == ',hSaiEnt'){ $valores = $valores.$v_dSaiEnt." "; } $campos = $campos.$campo; $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."',101)"; } } } $xml->read(); } if ($campos != ''){ $campos = ','.$campos; $valores = ','.$valores; } grava_insert("INSERT INTO TBL_NFE_".$tag." (infNFe".$campos.") VALUES (".$n_infNFe.$valores.")"); } //gravar det function grava_det (){ global $xml, $n_infNFe, $n_nItem; $no = $xml->depth; while( $xml -> moveToNextAttribute ()) { if ($xml->name == 'nItem'){ $n_nItem = $xml->value; } } $xml->read(); while ($no < $xml->depth){ if( $xml -> nodeType == XMLReader :: ELEMENT ) { if ($xml->name == 'prod'){ grava_det_nItem('prod'); } if (($xml->name == 'ICMS00') or ($xml->name == 'ICMS10') or ($xml->name == 'ICMS20') or ($xml->name == 'ICMS30') or ($xml->name == 'ICMS40') or ($xml->name == 'ICMS51') or ($xml->name == 'ICMS60') or ($xml->name == 'ICMS70') or ($xml->name == 'ICMS90') ){ grava_det_nItem('ICMS'); } if ($xml->name == 'ICMSPart'){ grava_det_nItem('ICMSPart'); } if ($xml->name == 'ICMSST'){ grava_det_nItem('ICMSST'); } if (($xml->name == 'ICMSSN101') or ($xml->name == 'ICMSSN102') or ($xml->name == 'ICMSSN201') or ($xml->name == 'ICMSSN202') or ($xml->name == 'ICMSSN500') or ($xml->name == 'ICMSSN900') ){ grava_det_nItem('ICMSSN'); } if ($xml->name == 'IPI'){ grava_det_nItem('IPI'); } if ($xml->name == 'II'){ grava_det_nItem('II'); } if ($xml->name == 'PIS'){ grava_det_nItem('PIS'); } if ($xml->name == 'PISST'){ grava_det_nItem('PISST'); } if ($xml->name == 'COFINS'){ grava_det_nItem('COFINS'); } if ($xml->name == 'COFINSST'){ grava_det_nItem('COFINSST'); } if ($xml->name == 'ISSQN'){ grava_det_nItem('ISSQN'); } } $xml->read(); } } //gravar os filhos da det function grava_det_nItem ($tag){ global $xml, $n_infNFe, $n_nItem; $no = $xml->depth; $xml->read(); $campos = ''; $valores = ''; while ($no < $xml->depth) { if ($xml->name == 'DI'){ #grava_DI(); } if ($xml->name == 'veicProd'){ grava_det_nItem('veicProd'); } if ($xml->name == 'med'){ grava_det_nItem('med'); } if ($xml->name == 'arma'){ grava_det_nItem('arma'); } if ($xml->name == 'comb'){ grava_det_nItem('comb'); } if( $xml -> nodeType == XMLReader :: ELEMENT ){ if ($xml->name == 'mod') { $tipo_campo = 'VARCHAR'; }else{ $tipo_campo = tipo_campo($tag,$xml->name); } if ($tipo_campo <> ''){ $campo = ''; if ($campos <> '') { $campo = ","; } } if ($xml->name == 'mod') { $campo = $campo.'modelo'; }else{ $campo = $campo.$xml->name; } } if( $xml -> nodeType == XMLReader :: TEXT ){ if ($tipo_campo <> ''){ if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."CONVERT(DATETIME,'"; } $campos = $campos.$campo; $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."',101)"; } } } $xml->read(); } if ($campos != ''){ $campos = ','.$campos; $valores = ','.$valores; } grava_insert("INSERT INTO TBL_NFE_".$tag." (infNFe,nItem".$campos.") VALUES (".$n_infNFe.",".$n_nItem.$valores.")"); } #gravar infNFE e ID function grava_infNFe_id ($tag){ global $xml, $n_infNFe; $n_id = prox_seq($tag); $no = $xml->depth; $xml->read(); while ($no < $xml->depth){ if ($xml->name == 'ICMSTot'){ grava_com_id('ICMSTot',$tag,$n_id); } if ($xml->name == 'ISSQNtot'){ grava_com_id('ISSQNtot',$tag,$n_id); } if ($xml->name == 'retTrib'){ grava_com_id('retTrib',$tag,$n_id); } if ($xml->name == 'transporta'){ grava_com_id('transporta',$tag,$n_id); } if ($xml->name == 'retTransp'){ grava_com_id('retTransp',$tag,$n_id); } if ($xml->name == 'veicTransp'){ grava_com_id('veicTransp',$tag,$n_id); } if ($xml->name == 'reboque'){ grava_com_id('reboque',$tag,$n_id); } if ($xml->name == 'vol'){ grava_com_ids('vol',$tag,$n_id); } if ($xml->name == 'dup'){ grava_com_id('dup',$tag,$n_id); } if ($xml->name == 'obsCont'){ grava_com_id('obsCont',$tag,$n_id); } if ($xml->name == 'obsFisco'){ grava_com_id('obsFisco',$tag,$n_id); } if ($xml->name == 'procRef'){ grava_com_id('procRef',$tag,$n_id); } if ($xml->name == 'forDia'){ grava_com_id('forDia',$tag,$n_id); } if ($xml->name == 'deduc'){ grava_com_id('deduc',$tag,$n_id); } if( $xml -> nodeType == XMLReader :: ELEMENT ){ if ($xml->name == 'mod') { $tipo_campo = 'VARCHAR'; }else{ $tipo_campo = tipo_campo($tag,$xml->name); } if ($tipo_campo <> ''){ $campo = ''; if ($campos <> '') { $campo = ","; } } if ($xml->name == 'mod') { $campo = $campo.'modelo'; }else{ $campo = $campo.$xml->name; } } if( $xml -> nodeType == XMLReader :: TEXT ){ if ($tipo_campo <> ''){ if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."CONVERT(DATETIME,'"; } $campos = $campos.$campo; $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."',101)"; } } } $xml->read(); } if ($valores != '') { $valores = ",".$valores; $campos = ",".$campos; } grava_insert("INSERT INTO TBL_NFE_".$tag." (infNFe,".$tag.$campos.") VALUES (".$n_infNFe.",".$n_id.$valores.")"); } #gravar com ID function grava_com_id ($tabela,$tag,$n_id){ global $xml, $n_infNFe; $no = $xml->depth; $xml->read(); while ($no < $xml->depth){ if( $xml -> nodeType == XMLReader :: ELEMENT ){ if ($xml->name == 'mod') { $tipo_campo = 'VARCHAR'; }else{ $tipo_campo = tipo_campo($tabela,$xml->name); } if ($tipo_campo <> ''){ $campo = ''; if ($campos <> '') { $campo = ","; } } if ($xml->name == 'mod') { $campo = $campo.'modelo'; }else{ $campo = $campo.$xml->name; } } if( $xml -> nodeType == XMLReader :: TEXT ){ if ($tipo_campo <> ''){ if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."CONVERT(DATETIME,'"; } $campos = $campos.$campo; $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."',101)"; } } } $xml->read(); } if ($campos != ''){ $campos = ','.$campos; $valores = ','.$valores; } grava_insert("INSERT INTO TBL_NFE_".$tabela." (".$tag.$campos.") VALUES (".$n_id.$valores.")"); } #gravar com IDs function grava_com_ids ($tabela,$tag,$n_id){ global $xml, $n_infNFe; $n_id2 = prox_seq($tabela); $no = $xml->depth; $xml->read(); while ($no < $xml->depth){ if ($xml->name == 'lacres'){ grava_com_id('lacres',$tabela,$n_id2); } if( $xml -> nodeType == XMLReader :: ELEMENT ){ if ($xml->name == 'mod') { $tipo_campo = 'VARCHAR'; }else{ $tipo_campo = tipo_campo($tabela,$xml->name); } if ($tipo_campo <> ''){ $campo = ''; if ($campos <> '') { $campo = ","; } } if ($xml->name == 'mod') { $campo = $campo.'modelo'; }else{ $campo = $campo.$xml->name; } } if( $xml -> nodeType == XMLReader :: TEXT ){ if ($tipo_campo <> ''){ if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."CONVERT(DATETIME,'"; } $campos = $campos.$campo; $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } if ($tipo_campo == 'DATETIME'){ $valores = $valores."',101)"; } } } $xml->read(); } if ($campos != ''){ $campos = ','.$campos; $valores = ','.$valores; } grava_insert("INSERT INTO TBL_NFE_".$tabela." (".$tag.",".$tabela.$campos.") VALUES (".$n_id.",".$n_id2.$valores.")"); } #Ler cancNFe function grava_cancNFe() { global $xml; $no = $xml->depth; $xml->read(); while ($no < $xml->depth) { if ($xml->name == 'infCanc'){ grava_infCanc(); } $xml->read(); } } #Gravar infCanc function grava_infCanc (){ global $xml, $n_infNFe, $s_Id; $n_infNFe = 0; $no = $xml->depth; $campos = ''; $valores = ''; #Ler atributos if( $xml -> hasAttributes ) { while( $xml -> moveToNextAttribute ()) { $tipo_campo = tipo_campo('infCanc',$xml->name); if ($tipo_campo <> ''){ if ($xml->name == 'Id'){ $sql_id = mssql_query("SELECT COUNT(1) AS EXISTE FROM TBL_NFE_infCanc where Id = '".$xml->value."'"); $linha_id = mssql_fetch_assoc($sql_id); $s_Id = $xml->value; if ($linha_id['EXISTE'] > 0){ $n_infNFe = -1; } } if ($campos <> '') { $campos = $campos.","; } $campos = $campos.$xml->name; if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } } } } # Ler Elementos $xml->read(); while ($no < $xml->depth) { if( $xml -> nodeType == XMLReader :: ELEMENT ){ if ($xml->name == 'mod') { $tipo_campo = 'VARCHAR'; }else{ $tipo_campo = tipo_campo('infCanc',$xml->name); } if ($tipo_campo <> ''){ $campo = ''; if ($campos <> '') { $campo = ","; } } if ($xml->name == 'mod') { $campo = $campo.'modelo'; }else{ $campo = $campo.$xml->name; } } if( $xml -> nodeType == XMLReader :: TEXT ){ if ($tipo_campo <> ''){ if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } $campos = $campos.$campo; $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } } } $xml->read(); } #Inserir na tabela if ($n_infNFe == 0){ $n_infNFe = prox_seq('infCanc'); grava_insert("INSERT INTO TBL_NFE_infCanc (infCanc,".$campos.") VALUES (".$n_infNFe.",".$valores.")"); } } #Ler inutNfe function grava_inutNfe() { global $xml; $no = $xml->depth; $xml->read(); while ($no < $xml->depth) { if ($xml->name == 'infInut'){ grava_infInut(); } $xml->read(); } } #Gravar infInut function grava_infInut (){ global $xml, $n_infNFe, $s_Id; $n_infNFe = 0; $no = $xml->depth; $campos = ''; $valores = ''; #Ler atributos if( $xml -> hasAttributes ) { while( $xml -> moveToNextAttribute ()) { $tipo_campo = tipo_campo('infInut',$xml->name); if ($tipo_campo <> ''){ if ($xml->name == 'Id'){ $sql_id = mssql_query("SELECT COUNT(1) AS EXISTE FROM TBL_NFE_infInut where Id = '".$xml->value."'"); $linha_id = mssql_fetch_assoc($sql_id); $s_Id = $xml->value; if ($linha_id['EXISTE'] > 0){ $n_infNFe = -1; } } if ($campos <> '') { $campos = $campos.","; } $campos = $campos.$xml->name; if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } } } } # Ler Elementos $xml->read(); while ($no < $xml->depth) { if( $xml -> nodeType == XMLReader :: ELEMENT ){ if ($xml->name == 'mod') { $tipo_campo = 'VARCHAR'; }else{ $tipo_campo = tipo_campo('infInut',$xml->name); } if ($tipo_campo <> ''){ $campo = ''; if ($campos <> '') { $campo = ","; } } if ($xml->name == 'mod') { $campo = $campo.'modelo'; }else{ $campo = $campo.$xml->name; } } if( $xml -> nodeType == XMLReader :: TEXT ){ if ($tipo_campo <> ''){ if ($valores <> '') { $valores = $valores.","; } if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } $campos = $campos.$campo; $valores = $valores.remove_aspas($xml->value); if ($tipo_campo == 'VARCHAR'){ $valores = $valores."'"; } } } $xml->read(); } #Inserir na tabela if ($n_infNFe == 0){ $n_infNFe = prox_seq('infInut'); grava_insert("INSERT INTO TBL_NFE_infInut (infInut,".$campos.") VALUES (".$n_infNFe.",".$valores.")"); } } function busca_se_cancelada ($sTipoNota){ global $s_Id, $n_infNFe, $n_infCanc; if ($sTipoNota == 'NF'){ $sql_id = mssql_query("SELECT infCanc FROM TBL_NFE_infCanc WHERE SUBSTRING(Id,0,3) = SUBSTRING('".$s_Id."',0,4)"); $linha_id = mssql_fetch_assoc($sql_id); if ($linha_id['infCanc'] > 0){ $n_infCanc = $linha_id['infCanc']; } } elseif ($sTipoNota == 'CANC'){ $sql_id = exec_sql("UPDATE TBL_NFE_XML SET infCanc = ".$n_infNFe.", STATUS = 'NF_CANC' WHERE SUBSTRING(Id,0,4) = SUBSTRING('".$s_Id."',0, 3) AND STATUS = 'NF'"); } } function ler_xml () { global $xml, $n_infNFe; while( $xml -> read ()) { if( $xml -> nodeType == XMLReader :: END_ELEMENT ) { }else if( $xml -> nodeType == XMLReader :: ELEMENT ) { if ($xml->name == 'infNFe'){ grava_infNFe(); busca_se_cancelada('NF'); }elseif ($xml->name == 'cancNFe'){ grava_cancNFe(); busca_se_cancelada('CANC'); }elseif ($xml->name == 'inutNFe'){ grava_inutNFe(); } if ($n_infNFe == -1){ break; } if ($xml->name == 'ide'){ grava_infNFe_pai('ide'); } if ($xml->name == 'emit'){ grava_infNFe_pai('emit'); } if ($xml->name == 'avulsa'){ grava_infNFe_pai('avulsa'); } if ($xml->name == 'dest'){ grava_infNFe_pai('dest'); } if ($xml->name == 'retirada'){ grava_infNFe_pai('retirada'); } if ($xml->name == 'entrega'){ grava_infNFe_pai('entrega'); } if ($xml->name == 'det'){ grava_det(); } if ($xml->name == 'total'){ grava_infNFe_id('total'); } if ($xml->name == 'transp'){ grava_infNFe_id('transp'); } if ($xml->name == 'cobr'){ grava_infNFe_id('cobr'); } if ($xml->name == 'infAdic'){ grava_infNFe_id('infAdic'); } if ($xml->name == 'exporta'){ grava_infNFe_pai('exporta'); } if ($xml->name == 'compra'){ grava_infNFe_pai('compra'); } if ($xml->name == 'cana'){ grava_infNFe_id('cana'); } } else if( $xml -> nodeType == XMLReader :: TEXT ) { } } } # Manutenção dos arquivos XML function criar_pasta ($nome_pasta){ //// Definicao de Diretorios / $diretorio = "../nfe/".$nome_pasta; ///// certifique que seu diretório tenha permissao para escrita (chmod 0777) if(!file_exists($diretorio)) { mkdir($diretorio); } } function criar_pastas_data(){ global $d_dEmi; $ano = substr($d_dEmi,0,4); $mes = substr($d_dEmi,5,2); $dia = substr($d_dEmi,8,2); criar_pasta($ano); criar_pasta($ano."/".$mes); criar_pasta($ano."/".$mes."/".$dia); return $ano."/".$mes."/".$dia; } function copia_arquivo ($nome_arquivo, $pasta_origem, $pasta_destino, $nome_arquivo_novo){ $n = 1; if (file_exists($pasta_destino.$nome_arquivo_novo.'.xml')) { while (file_exists($pasta_destino.$nome_arquivo_novo."_".$n.".xml")) { $n += 1; } $nome_arquivo_novo = $nome_arquivo_novo."_".$n; } #print("<br><br> Copiar Arquivo: ".$nome_arquivo_novo.". Da pasta: ".$pasta_origem.". Para pasta: ".$pasta_destino."<br>"); rename($pasta_origem.$nome_arquivo, $pasta_destino.$nome_arquivo_novo.".xml"); return $nome_arquivo_novo; } function gravar_xml ($pasta, $nome_xml){ global $xml, $n_infNFe, $n_infCanc, $s_Id, $n_NF, $n_CANC, $n_INUT, $n_EXIS, $n_REJE, $n_ERRO, $result; $n_infCanc = 'null'; if (strtoupper(substr($nome_xml,-4)) == ".XML"){ $v_valida_xml = Valida_XML($pasta.'/'.$nome_xml); if (($v_valida_xml == 'NF') or ($v_valida_xml == 'CANC') or ($v_valida_xml == 'INUT')){ $xml->open($pasta.'/'.$nome_xml); ler_xml(); $res_exec = executa_insert(); $xml->close(); if ($res_exec == 'OK'){ if ($n_infNFe != -1) { if ($v_valida_xml == 'NF') { $pasta_copiar = criar_pastas_data(); $pasta_copiar = $pasta.'/'.$pasta_copiar.'/'; $n_NF += 1; } elseif ($v_valida_xml == 'CANC') { criar_pasta('canc'); $pasta_copiar = $pasta.'/canc/'; $n_CANC += 1; } elseif ($v_valida_xml == 'INUT') { criar_pasta('inut'); $pasta_copiar = $pasta.'/inut/'; $n_INUT += 1; } // $result['result'] = 'success'; // $result['size'] = "Upload Com Sucesso !"; GravaLog('0','Upload','Arquivo: '.$s_Id.'. '.$v_valida_xml.'. Antigo: '.$nome_xml); $nome_xml = copia_arquivo($nome_xml,$pasta.'/',$pasta_copiar,$s_Id); exec_insert_xml($n_infNFe,$s_Id,$pasta_copiar,$s_Id.'.xml',$v_valida_xml); }else{ #unlink($dir.'/'.$filename); criar_pasta('existentes'); GravaLog('0','Upload','Arquivo: '.$nome_xml.'. EXISTENTE.'); $nome_xml = copia_arquivo($nome_xml,$pasta.'/',$pasta.'/existentes/',substr($nome_xml,0,-4)); exec_insert_xml($n_infNFe,$s_Id,'',$nome_xml,'EXISTENTE'); #print("<br><br> # Arquivo já existente: ".$filename." <br>"); $n_EXIS += 1; } } else { $result['result'] = 'failed'; $result['error'] = "Foi encontrado incompatibilidade no arquivo! "; criar_pasta('erros'); GravaLog('0','Upload','Arquivo: '.$nome_xml.'. ERRO'); $nome_xml = copia_arquivo($nome_xml,$pasta.'/',$pasta.'/erros/',substr($nome_xml,0,-4)); exec_insert_xml(-3,'','',$nome_xml,'ERRO'); $n_ERRO += 1; } $n_infNFe = 0; } else{ #Copiar para pasta de arquivos com erros $result['result'] = 'failed'; $result['error'] = "Foi encontrado incompatibilidade no arquivo! "; criar_pasta('rejeitados'); GravaLog('0','Upload','Arquivo: '.$nome_xml.'. REJEITADO'); $nome_xml = copia_arquivo($nome_xml,$pasta.'/',$pasta.'/rejeitados/',substr($nome_xml,0,-4)); exec_insert_xml(-2,'',$pasta.'/rejeitados/',$nome_xml,'REJEITADO'); $n_REJE += 1; } } } # ============================================================= libxml_use_internal_errors(true); # Inicio do processo de Importação do XML //Abre Pasta "xml'/ $dir = "../nfe"; $dh = opendir($dir); //Loop para os arquivos na pasta if (false !== ($filename = readdir($dh))) { carrega_tipo_campo(); } #exec_sql("UPDATE TBL_NFE_XML A, TBL_NFE_infCanc B SET A.infCanc = B.infCanc, A.STATUS = 'NF_CANC' WHERE SUBSTR(A.Id,4) = SUBSTR(B.Id, 3) AND A.STATUS = 'NF'"); function chave($arquivo){ $xml = simplexml_load_file('../nfe/'.$arquivo); $canc = $xml->cancNFe->infCanc->xServ; $inut = $xml->infInut->xServ; if (!empty($canc)=='CANCELAR'){ $chave = $xml->cancNFe->infCanc['Id']; $comp='_1_CAN_'; } else if(!empty($inut)=='INUTILIZAR'){ $chave = $xml->infInut['Id']; $comp='_1_INU_'; }else{ $chave = $xml->NFe->infNFe['Id']; $comp='_1'; } $rename = '../nfe'.'/'.$chave.$comp.".xml"; $de = '../nfe/'.$arquivo; $para = $rename; if (rename($de, $para)){} } function diretorio(){ $dir = "../nfe"; $dh = opendir($dir); while (false !== ($filename = readdir($dh))) { if (substr($filename,-4) == ".xml") { chave($filename); } } } ?> <?php /*--------------------------- UPLOAD DE ARQUIVOS ---------------------------------*/ function upload(){ global $result; if (isset($_FILES['photoupload']) ){ $arquivo = '../nfe/'.$_FILES['photoupload']['name']; $file = $_FILES['photoupload']['tmp_name']; $error = false; #$size = false; //move_uploaded_file($file, '../nfe/'.$arquivo); #chmod('../nfe/'.$_FILES['photoupload']['name'], 0777); #$tmp_name = $_FILES['photoupload']['tmp_name']; #$aux_tipo_imagem = $size['mime']; #$diretorio = "xml/"; //// certifique que seu diretório tenha permissao para escrita (chmod 0777) #if(!file_exists($diretorio)) { # mkdir($diretorio); #} #$addr = gethostbyaddr($_SERVER['REMOTE_ADDR']); gravar_xml("../nfe",$_FILES['photoupload']['name']); if (substr($arquivo,-4) == ".zip") { GravaLog(0,'TesteGustavo','Arquivo ZIP'); $result['result'] = 'success'; $result['size'] = "Upload Com Sucesso !"; GravaLog('0','Upload','Arquivo compactado'.$arquivo); } } if (!headers_sent() ){ header('Content-type: application/json'); } echo json_encode($result); } ?> Obrigado!
  7. Olá Boa Tarde! baixei um script para fazer download : http://ohmsapoio.com...pload/index.php o que acontece é que na hora de baixar ele cria um nome codificado! Segue Js... (function(c){var d={};function a(e){return plupload.translate(e)||e}function b(f,e){e.contents().each(function(g,h){h=c(h);if(!h.is(".plupload")){h.remove()}});e.prepend('<div class="plupload_wrapper plupload_scroll"><div id="'+f+'_container" class="plupload_container"><div class="plupload"><div class="plupload_header"><div class="plupload_header_content"><div class="plupload_header_title">'+a("Select files")+'</div><div class="plupload_header_text">'+a("Add files to the upload queue and click the start button.")+'</div></div></div><div class="plupload_content"><div class="plupload_filelist_header"><div class="plupload_file_name">'+a("Filename")+'</div><div class="plupload_file_action">&nbsp;</div><div class="plupload_file_status"><span>'+a("Status")+'</span></div><div class="plupload_file_size">'+a("Size")+'</div><div class="plupload_clearer">&nbsp;</div></div><ul id="'+f+'_filelist" class="plupload_filelist"></ul><div class="plupload_filelist_footer"><div class="plupload_file_name"><div class="plupload_buttons"><a href="#" class="plupload_button plupload_add">'+a("Add files")+'</a><a href="#" class="plupload_button plupload_start">'+a("Start upload")+'</a></div><span class="plupload_upload_status"></span></div><div class="plupload_file_action"></div><div class="plupload_file_status"><span class="plupload_total_status">0%</span></div><div class="plupload_file_size"><span class="plupload_total_file_size">0 b</span></div><div class="plupload_progress"><div class="plupload_progress_container"><div class="plupload_progress_bar"></div></div></div><div class="plupload_clearer">&nbsp;</div></div></div></div></div><input type="hidden" id="'+f+'_count" name="'+f+'_count" value="0" /></div>')}c.fn.pluploadQueue=function(e){if(e){this.each(function(){var j,i,k;i=c(this);k=i.attr("id");if(!k){k=plupload.guid();i.attr("id",k)}j=new plupload.Uploader(c.extend({dragdrop:true,container:k},e));d[k]=j;function h(l){var n;if(l.status==plupload.DONE){n="plupload_done"}if(l.status==plupload.FAILED){n="plupload_failed"}if(l.status==plupload.QUEUED){n="plupload_delete"}if(l.status==plupload.UPLOADING){n="plupload_uploading"}var m=c("#"+l.id).attr("class",n).find("a").css("display","block");if(l.hint){m.attr("title",l.hint)}}function f(){c("span.plupload_total_status",i).html(j.total.percent+"%");c("div.plupload_progress_bar",i).css("width",j.total.percent+"%");c("span.plupload_upload_status",i).text(a("Uploaded %d/%d files").replace(/%d\/%d/,j.total.uploaded+"/"+j.files.length))}function g(){var m=c("ul.plupload_filelist",i).html(""),n=0,l;c.each(j.files,function(p,o){l="";if(o.status==plupload.DONE){if(o.target_name){l+='<input type="hidden" name="'+k+"_"+n+'_tmpname" value="'+o.target_name+'" />'}l+='<input type="hidden" name="'+k+"_"+n+'_name" value="'+plupload.xmlEncode(o.name)+'" />';l+='<input type="hidden" name="'+k+"_"+n+'_status" value="'+(o.status==plupload.DONE?"done":"failed")+'" />';n++;c("#"+k+"_count").val(n)}m.append('<li id="'+o.id+'"><div class="plupload_file_name"><span>'+o.name+'</span></div><div class="plupload_file_action"><a href="#"></a></div><div class="plupload_file_status">'+o.percent+'%</div><div class="plupload_file_size">'+plupload.formatSize(o.size)+'</div><div class="plupload_clearer">&nbsp;</div>'+l+"</li>");h(o);c("#"+o.id+".plupload_delete a").click(function(q){c("#"+o.id).remove();j.removeFile(o);q.preventDefault()})});c("span.plupload_total_file_size",i).html(plupload.formatSize(j.total.size));if(j.total.queued===0){c("span.plupload_add_text",i).text(a("Add files."))}else{c("span.plupload_add_text",i).text(j.total.queued+" files queued.")}c("a.plupload_start",i).toggleClass("plupload_disabled",j.files.length==(j.total.uploaded+j.total.failed));m[0].scrollTop=m[0].scrollHeight;f();if(!j.files.length&&j.features.dragdrop&&j.settings.dragdrop){c("#"+k+"_filelist").append('<li class="plupload_droptext">'+a("Drag files here.")+"</li>")}}j.bind("UploadFile",function(l,m){c("#"+m.id).addClass("plupload_current_file")});j.bind("Init",function(l,m){b(k,i);if(!e.unique_names&&e.rename){c("#"+k+"_filelist div.plupload_file_name span",i).live("click",function(s){var q=c(s.target),o,r,n,p="";o=l.getFile(q.parents("li")[0].id);n=o.name;r=/^(.+)(\.[^.]+)$/.exec(n);if(r){n=r[1];p=r[2]}q.hide().after('<input type="text" />');q.next().val(n).focus().blur(function(){q.show().next().remove()}).keydown(function(u){var t=c(this);if(u.keyCode==13){u.preventDefault();o.name=t.val()+p;q.text(o.name);t.blur()}})})}c("a.plupload_add",i).attr("id",k+"_browse");l.settings.browse_button=k+"_browse";if(l.features.dragdrop&&l.settings.dragdrop){l.settings.drop_element=k+"_filelist";c("#"+k+"_filelist").append('<li class="plupload_droptext">'+a("Drag files here.")+"</li>")}c("#"+k+"_container").attr("title","Using runtime: "+m.runtime);c("a.plupload_start",i).click(function(n){if(!c(this).hasClass("plupload_disabled")){j.start()}n.preventDefault()});c("a.plupload_stop",i).click(function(n){n.preventDefault();j.stop()});c("a.plupload_start",i).addClass("plupload_disabled")});j.init();j.bind("Error",function(l,o){var m=o.file,n;if(m){n=o.message;if(o.details){n+=" ("+o.details+")"}if(o.code==plupload.FILE_SIZE_ERROR){alert(a("Error: File too large: ")+m.name)}if(o.code==plupload.FILE_EXTENSION_ERROR){alert(a("Error: Invalid file extension: ")+m.name)}m.hint=n;c("#"+m.id).attr("class","plupload_failed").find("a").css("display","block").attr("title",n)}});j.bind("StateChanged",function(){if(j.state===plupload.STARTED){c("li.plupload_delete a,div.plupload_buttons",i).hide();c("span.plupload_upload_status,div.plupload_progress,a.plupload_stop",i).css("display","block");c("span.plupload_upload_status",i).text("Uploaded "+j.total.uploaded+"/"+j.files.length+" files");if(e.multiple_queues){c("span.plupload_total_status,span.plupload_total_file_size",i).show()}}else{g();c("a.plupload_stop,div.plupload_progress",i).hide();c("a.plupload_delete",i).css("display","block")}});j.bind("QueueChanged",g);j.bind("FileUploaded",function(l,m){h(m)});j.bind("UploadProgress",function(l,m){c("#"+m.id+" div.plupload_file_status",i).html(m.percent+"%");h(m);f();if(e.multiple_queues&&j.total.uploaded+j.total.failed==j.files.length){c(".plupload_buttons,.plupload_upload_status",i).css("display","inline");c(".plupload_start",i).addClass("plupload_disabled");c("span.plupload_total_status,span.plupload_total_file_size",i).hide()}});if(e.setup){e.setup(j)}});return this}else{return d[c(this[0]).attr("id")]}}})(jQuery); e o script de download... <?php // HTTP headers for no cache etc header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // Settings $targetDir = "uploads" //ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload"; //$targetDir = 'uploads'; $cleanupTargetDir = true; // Remove old files $maxFileAge = 5 * 3600; // Temp file age in seconds // 5 minutes execution time @set_time_limit(5 * 60); // Uncomment this one to fake upload time // usleep(5000); // Get parameters $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0; $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; // Clean the fileName for security reasons $fileName = preg_replace('/[^\w\._]+/', '_', $fileName); // Make sure the fileName is unique but only if chunking is disabled if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) { $ext = strrpos($fileName, '.'); $fileName_a = substr($fileName, 0, $ext); $fileName_b = substr($fileName, $ext); $count = 1; while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) $count++; $fileName = $fileName_a . '_' . $count . $fileName_b; } $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; // Create target dir if (!file_exists($targetDir)) @mkdir($targetDir); // Remove old temp files if ($cleanupTargetDir) { if (is_dir($targetDir) && ($dir = opendir($targetDir))) { while (($file = readdir($dir)) !== false) { $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; // Remove temp file if it is older than the max age and is not the current file if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) { @unlink($tmpfilePath); } } closedir($dir); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); } } // Look for the content type header if (isset($_SERVER["HTTP_CONTENT_TYPE"])) $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; if (isset($_SERVER["CONTENT_TYPE"])) $contentType = $_SERVER["CONTENT_TYPE"]; // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5 if (strpos($contentType, "multipart") !== false) { if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { // Open temp file $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = @fopen($_FILES['file']['tmp_name'], "rb"); if ($in) { while ($buff = fread($in, 4096)) fwrite($out, $buff); } else die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); @fclose($in); @fclose($out); @unlink($_FILES['file']['tmp_name']); } else die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } else die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } else { // Open temp file $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = @fopen("php://input", "rb"); if ($in) { while ($buff = fread($in, 4096)) fwrite($out, $buff); } else die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); @fclose($in); @fclose($out); } else die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } // Check if file has been uploaded if (!$chunks || $chunk == $chunks - 1) { // Strip the temp .part suffix off rename("{$filePath}.part", $filePath); } die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); Será que alguem consegue me ajudar... quebrei a cabeça e nada!
×
×
  • Criar Novo...