 <?php

error_reporting(E_ALL ^ E_NOTICE);

if($_POST["doctype"]==1) define('UPLOAD_DIR', __DIR__ . DIRECTORY_SEPARATOR . 'uploads/documents' . DIRECTORY_SEPARATOR);
if($_POST["doctype"]==2) define('UPLOAD_DIR', __DIR__ . DIRECTORY_SEPARATOR . 'uploads/reports' . DIRECTORY_SEPARATOR);

processRequest();

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

    $action = $_GET['action'];
    $filelist="";
    switch($action) {
        
        case 'dump': { // dump request information
           
            print('<h4>Files Uploaded</h4>');
            
            include('../db_con.php'); 

            $result0 = mysqli_query($con,"SELECT v_uid FROM applicant_table WHERE app_id='".$_GET['appid']."'");
            $row0 = mysqli_fetch_array($result0);
            $uid=$row0["v_uid"];

            $fileNames = handleUploadedFiles($uid);

            if(is_array($fileNames) && count($fileNames) > 0) {

                foreach($fileNames as $index => $filename) {

                    $sql = "insert into ver_docu_table (vr_id, vrcreate_datetime, doc_name, file, doc_type, app_id) values ('', '$now', '$filename', '$filename', '$_POST[doctype]', '$_POST[appid]')";                              
                    $filelist=$filelist."#".$filename." ";
                    $result = mysqli_query($con,$sql);
                }
             
                    echo "<span style='color:green;'>All Files successfully uploaded</span> <button class='btn btn-primary btn-xs' onclick='reloadFunction()''>View files</button>";
                    
                    include 'methodlist.php';
                    session_start();

                    if($_POST["doctype"]==1) $doctype="Document";
                    if($_POST["doctype"]==2) $doctype="Report";

                    ver_update_history('<b>'.count($fileNames).' '.$doctype.' </b>('.$filelist.') have been uploaded by', $_GET["appid"], $con);
            //         if(strpos($filename, 'ERROR:') === 0) {
            //             print("<p>$filename</p>");
            //         } else {
            //             $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            //             $targetUrl = dirname(getCurrentPageURL()) . str_replace(DIRECTORY_SEPARATOR, "/", substr(UPLOAD_DIR, strlen(__DIR__))) . $filename;
            //             print('<a href="' . $targetUrl . '" target="_blank">');
            //             if (strpos($filename, 'ERROR:') !== 0 && in_array($extension, array('jpg', 'jpeg', 'gif', 'png'))) {
            //                 $imgAnchor = '<img src="' . $targetUrl . '" height="160">';
            //             } else if (strpos($filename, 'ERROR:') !== 0 && in_array($extension, array('tif', 'tiff'))) {
            //                 $imgAnchor = '<img src="' . dirname(getCurrentPageURL()) . '/icon-tif.png">';
            //             } else if (strpos($filename, 'ERROR:') !== 0 && $extension == 'pdf') {
            //                 $imgAnchor = '<img src="' . dirname(getCurrentPageURL()) . '/icon-pdf.png">';
            //             } else {
            //                 $imgAnchor = '<img src="' . dirname(getCurrentPageURL()) . '/icon-others.png">';
            //             }
            //             print($imgAnchor . '</a>');
            //         }
                // }
             }
          
           // var_dump($_FILES);
            
           // var_dump($_POST);
            
            // $sql = "insert into ver_docu_table (vr_id, vrcreate_datetime, doc_name, file, doc_type, app_id) values ('', '$now', '$filename', '$filename', '$_POST[doctype]', '$_POST[appid]')";                              
            //     $filelist=$filelist."#".$file." ";//var_dump($sql) or die();
            //                         //echo $sql;
            //     $result = mysqli_query($con,$sql);
                
            //    // if($i==$no_files-1){
            //         echo "<span style='color:green;'>All Files successfully uploaded</span> <button class='btn btn-primary btn-xs' onclick='reloadFunction()''>View files</button>";
                    
            //         include 'methodlist.php';
            //         session_start();

            //         if($_POST["doctype"]==1) $doctype="Document";
            //         if($_POST["doctype"]==2) $doctype="Report";

            //         ver_update_history('<b>'.$no_files.' '.$doctype.' </b>('.$filelist.') have been uploaded by', $_GET["appid"], $con);


             //   }
                   
         
        }
        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($uid) {
    $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($fileNames, doHandleUploadedFile($fileSpec['name'][$index], $fileSpec['type'][$index], $fileSpec['tmp_name'][$index], $fileSpec['error'][$index], $fileSpec['size'][$index], $uid));
                    }
                }
            } else {
                if($fileSpec['error'] == UPLOAD_ERR_OK) {
                    array_push($fileNames, doHandleUploadedFile($fileSpec['name'], $fileSpec['type'], $fileSpec['tmp_name'], $fileSpec['error'], $fileSpec['size'], $uid));
                }
            }
        }
    }

    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, $uid) {
    if($error != UPLOAD_ERR_OK) {
        return 'ERROR: upload error code: ' . $error . ' for file ' . $name;
    }

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

    if($extension == null || strlen($extension) == 0 ||  (strlen($extension) > 0 && (!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);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $uid."-".$parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

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

    $moved = move_uploaded_file($tmp_name, UPLOAD_DIR . $name);
    if($moved) {
        chmod(UPLOAD_DIR . $name, 0644);
    } 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 'image/jpeg': return "jpg";
        case 'image/pjpeg': return 'jpg';
        case 'image/png': return 'png';
        case 'image/gif': return 'gif';
        case 'image/tiff': return 'tif';
        case 'image/x-tiff': return 'tif';
        case 'application/pdf': return 'pdf';
        default: return '';
    }
}

?> 