<?php
include("conexion_ECS.php");

error_reporting(E_ALL E_NOTICE);

define('UPLOAD_DIR'__DIR__ DIRECTORY_SEPARATOR);

processRequest();

// Front controller
function processRequest() {
    if(isset(
$_GET['delay']) && is_numeric($_GET['delay'])) {
        
sleep($_GET['delay']);
    }

    
    
$action $_GET['action'];
    switch(
$action) {
        case 
'upload': { // handle file upload
            
header('Content-type: text/plain; charset=utf-8');

            
$fileNames handleUploadedFiles();

            if(
is_array($fileNames) && count($fileNames) > 0) {
                foreach(
$fileNames as $index => $filename) {
                    if(
$index 0) {
                        print(
'\n');
                    }
                    if(
strpos($filename'ERROR:') === 0) {
                        print(
$filename); // error mesg
                    
} else {
                        print(
dirname(getCurrentPageURL()) . str_replace(DIRECTORY_SEPARATOR"/"substr(UPLOAD_DIRstrlen(__DIR__))) . $filename);
                    }
                }
            } else {
                print(
'ERROR: La evidencia no se pudo subir..');
            }
            return; 
// without printing footer
        
}
        break;

        case 
'source': { // display source code of this file
            
show_source(__FILE__);
        }
        break;

        case 
'dump': { // dump request information
            
            

            
$fileNames handleUploadedFiles();

            if(
is_array($fileNames) && count($fileNames) > 0) {
                    
                foreach(
$fileNames as $index => $filename) {
                    if(
strpos($filename'ERROR:') === 0) {
                        print(
"<p>$filename</p>");
                    } else {
                        
$extension strtolower(pathinfo($filenamePATHINFO_EXTENSION));
                        
$targetUrl dirname(getCurrentPageURL()) . str_replace(DIRECTORY_SEPARATOR"/"substr(UPLOAD_DIRstrlen(__DIR__))) . $filename;
                        
                        print(
'<a href="' $targetUrl '" target="_blank">');
                        if (
strpos($filename'ERROR:') !== && in_array($extension, array('jpg''jpeg''gif''png'))) {
                            
$imgAnchor '<img src="' $targetUrl '" height="160">';
                        } else if (
strpos($filename'ERROR:') !== && in_array($extension, array('tif''tiff'))) {
                            
$imgAnchor '<img src="' dirname(getCurrentPageURL()) . '/icon-tif.png">';
                        } else if (
strpos($filename'ERROR:') !== && $extension == 'pdf') {
                            
$imgAnchor '<div align="center"><img src="' dirname(getCurrentPageURL()) . '/icon-pdf.png"></div>';
                        } else {
                            
$imgAnchor '<img src="' dirname(getCurrentPageURL()) . '/icon-others.png">';
                        }
                        print(
$imgAnchor '</a>');//imprime el icono

                        
                    
}
                }
            }

             
            
            
            
$imgArray = array(); // print POST values pointing to image URL
            
foreach($_POST as $paramKey => $paramValue) {
                if(
strlen($paramValue) < 6) {
                    continue;
                }
                if(
strtolower(substr(trim($paramValue), 04)) == 'http' && in_array(strtolower(pathinfo($paramValuePATHINFO_EXTENSION)), array('jpg''jpeg''gif''png''tif''tiff')) )  {
                    
array_push($imgArray$paramValue);
                }
            }

            if(
is_array($imgArray) && count($imgArray) > 0) {
                print(
'<br>');
                foreach(
$imgArray as $imgSrc) {
                    print(
'<a href="' $imgSrc '" target="_blank">');
                    print(
'<img src="' $imgSrc '" style="border: solid 1px #19f" hspace=8 vspace=8 height=160></a>');
                }
            }

           
        }
        break;


        default: {
            print(
'Use a &lt;form&gt; to post scanned images or <a href="' $_SERVER["PHP_SELF"] .
                
'?action=form">manually upload</a> to this URL | <a href="' $_SERVER["PHP_SELF"] . '?action=source">Show source code</a>');
        }
    } 
// end of switch

    
}

/**
 * @return an array of mixing simple names of the files uploaded into UPLOAD_DIR and error strings starting with 'ERROR: ' or empty array if there is no uploaded file.
 */
function handleUploadedFiles() {
    
$fileNames = array();
    if(
is_array($_FILES)) {
        foreach(
$_FILES as $name => $fileSpec) {
            if(! 
is_array($fileSpec)) {
                continue;
            }

            if(
is_array($fileSpec['tmp_name'])) { // multiple files with same name
                
foreach($fileSpec['tmp_name'] as $index => $value) {
                    if(
$fileSpec['error'][$index] == UPLOAD_ERR_OK) {
                        
array_push($fileNamesdoHandleUploadedFile($fileSpec['name'][$index], $fileSpec['type'][$index], $fileSpec['tmp_name'][$index], $fileSpec['error'][$index], $fileSpec['size'][$index]));
                    }
                }
            } else {
                if(
$fileSpec['error'] == UPLOAD_ERR_OK) {
                    
array_push($fileNamesdoHandleUploadedFile($fileSpec['name'], $fileSpec['type'], $fileSpec['tmp_name'], $fileSpec['error'], $fileSpec['size']));
                }
            }
        }
    }

    return 
$fileNames;

}


/**
 * @return simple name of the file in the UPLOAD_DIR or an error string starting with 'ERROR: '.
 */
function doHandleUploadedFile($name$type$tmp_name$error$size) {
    
    
$cliente $_GET['cliente'];
    
$guia $_GET['guia'];
    
$hoy date("Y-m-d");     


    
    
$name$cliente."-".$guia.".pdf";
    if(
$error != UPLOAD_ERR_OK) {
        return 
'ERROR: upload error code: ' $error ' for file ' $name;
    }

    
$extension pathinfo($namePATHINFO_EXTENSION);
  
    if(
$extension == null || strlen($extension) == 0) {
        
$extension getImageExtensionByMimeType($type);
        if(
$extension != null) {
            
$name .= '.' $extension;
        }
    }

    if(
$extension == null || strlen($extension) == ||  (strlen($extension) > && (!in_array(strtolower($extension), array('jpg''jpeg''gif''png''tif''tiff''pdf'))))) {
        return 
'ERROR: extension not allowed: ' $extension ' for file ' $name;
    }

    
$name preg_replace("/[^A-Z0-9._-]/i""_"$name);
    
// don't overwrite an existing file
    
$i 0;
    
    
$parts pathinfo($name);
   
    if (
file_exists(UPLOAD_DIR $name)) {

                 echo 
'<br><p class="alert alert-danger" role="alert">La Evidencia ya Existe!</p><br>';
        } else {
                  
                
$no='http://130.211.172.60/ECS/'.$name;

                
$conexion_sepvalora pg_connect("host=104.154.100.195 dbname=ECS user=k1vvln9j password=Es7S4fntLbBQIVuDuU2o"
                or die(
'No pudo conectarse a ECS: ' pg_last_error());

                
$sqlinsert "INSERT INTO biblioteca (id_cliente, fecha_evidencia, link, id_guia, 
                estatus_aprobacion)
                VALUES ('
$cliente','$hoy','$no','$guia','Sin Aprobar')";
                
$resultsqlinsert pg_query($sqlinsert)or die('Insert evidenica falló ' pg_last_error());
                

                echo 
'<p class="alert alert-primary" role="alert">La Evidencia '.$sqlinsert.'se cargo con exito!</p><br>';

        }

    if(! 
file_exists(UPLOAD_DIR)) {
        
mkdir(UPLOAD_DIR); // try to mkedir
    
}

    
$moved move_uploaded_file($tmp_nameUPLOAD_DIR $name);
    if(
$moved) {
        
chmod(UPLOAD_DIR $name0644);
    } else {
        return 
'ERROR: moving uploaded file failed' ' for file ' $name;
    }

    return 
$name;
}

function 
getCurrentPageURL() {
    
$defaultPort "80";
    
$pageURL 'http';
    if (
$_SERVER["HTTPS"] == "on") {
        
$pageURL .= "s";
        
$defaultPort "443";
    }
    
$pageURL .= "://";
    if (
$_SERVER["SERVER_PORT"] != $defaultPort) {
        
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return 
$pageURL;
}

function 
getImageExtensionByMimeType($mimeType) {
    
$mimeType strtolower($mimeType);
    switch(
$mimeType) {
        case 
'application/pdf': return 'pdf';
        default: return 
'';
    }
}

?>