/**
  * @noAuth
  * @url POST /?submissions
  * @url PUT /?submissions/$id
  */
 function insertSubmission($id = null, $data)
 {
     if ($data == null) {
         $data = $_POST;
     } else {
         $data = get_object_vars($data);
     }
     //var_dump($data);
     //check if file submitted
     $file = false;
     if (isset($_FILES['file']) && !empty($_FILES['file']['name']) && $_FILES['file']['size'] > 0) {
         $file = $_FILES['file'];
         $data['image_result'] = $file['name'];
     }
     //validate
     $validationRules = array();
     if (isset($data['text_question']) && !empty($data['text_question'])) {
         $validationRules['text_result'] = VALIDATE_RULE_NON_EMPTY_STRING | VALIDATE_RULE_REQUIRED;
     }
     if (isset($data['image_question']) && !empty($data['image_question'])) {
         $validationRules['image_result'] = VALIDATE_RULE_NON_EMPTY_STRING | VALIDATE_RULE_REQUIRED;
     }
     $validator = new Validator($data);
     $errors = $validator->validate($validationRules);
     if (!empty($errors)) {
         throw new RestException(400, implode(" ", $errors));
     }
     //add new entry
     if ($id == null) {
         //insert into database
         $db = new SubmissionDatabase();
         $db->insertSubmission($data);
         $id = $db->lastInsertRowid();
         //upload file
         if ($file) {
             $upload_dir = DIR_SUBMISSION_FILES . '/' . $id;
             try {
                 checkFileType($file['name'], array("jpg", "jpeg", "gif", "png"));
                 uploadFile($file['tmp_name'], $upload_dir, $file['name']);
             } catch (Exception $e) {
                 // delete entry if upload failed
                 $db->deleteSubmission($id);
                 throw new RestException(400, $e->getMessage());
             }
         }
         return $db->getSubmission($id);
         // modify entry
     } else {
         //insert Model and return it
         $db = new SubmissionDatabase();
         $db->insertSubmission($data);
         return $db->getSubmission($id);
     }
 }
 /**
  * @noAuth
  * @url POST /?documents
  * @url PUT /?documents/$id
  */
 function insertDocument($id = null)
 {
     //validate post data
     $validator = new Validator($_POST);
     $errors = $validator->validate(array('title' => VALIDATE_RULE_REQUIRED | VALIDATE_RULE_NON_EMPTY_STRING, 'author' => VALIDATE_RULE_REQUIRED | VALIDATE_RULE_NON_EMPTY_STRING, 'published' => VALIDATE_RULE_YEAR, 'keywords' => VALIDATE_RULE_REQUIRED, 'isbn' => VALIDATE_RULE_ISBN));
     if (!empty($errors)) {
         throw new RestException(400, implode(" ", $errors));
     }
     //change string cases
     $_POST['title'] = ucfirst($_POST['title']);
     $_POST['author'] = ucwords($_POST['author']);
     $_POST['keywords'] = strtolower($_POST['keywords']);
     // submit new entry and upload file
     if ($id == null) {
         if (!isset($_FILES['file']) || empty($_FILES['file']['name'])) {
             throw new RestException(400, 'No File submitted');
         }
         $file = $_FILES['file'];
         if ($file['size'] < 1 || $file['size'] > UPLOAD_FILE_MAX_SIZE) {
             throw new RestException(400, "File is too large, maximum file size is " . strval(UPLOAD_FILE_MAX_SIZE / 8 / 1024 / 1024) . " MB.");
         }
         // append filename to post data and insert in database
         $db = new DocumentsDatabase();
         $_POST['file'] = $file['name'];
         $db->insertDocument($_POST);
         //upload file
         $id = $db->lastInsertRowid();
         $upload_dir = DIR_RECORD_FILES . '/' . $id;
         try {
             checkFileType($file['name']);
             uploadFile($file['tmp_name'], $upload_dir, $file['name']);
         } catch (Exception $e) {
             // delete entry if upload failed
             $db->deleteDocument($id);
             throw new RestException(400, $e->getMessage());
         }
         return $db->getDocument($id);
         // modify entry
     } else {
         //insert Model and return it
         $db = new DocumentsDatabase();
         $db->insertDocument($_POST);
         return $db->getDocument($id);
     }
 }
Exemple #3
0
<?php

require_once 'config.php';
require_once 'gini.php';
$path = '/rechnung/';
$allowedFileTypes = array('pdf', 'png', 'jpg', 'gif', 'jpeg');
if (!empty($_FILES)) {
    $tempFile = $_FILES['file']['tmp_name'];
    if (!checkFileType(basename($_FILES['file']['name']), $allowedFileTypes)) {
        $A['status'] = 0;
        $A['answer'] = 'file extension not supported';
        header('Content-type: application/json');
        echo json_encode($A);
        die;
    }
    $gini = new gini();
    $status = $gini->upload($tempFile);
    header('Content-type: application/json');
    echo json_encode(array('url' => $path . $status['document_id']));
    die;
}
// does uploaded file has allowed extension?
function checkFileType($filename, $allowedFileTypes)
{
    $ext = getExtension($filename);
    return in_array($ext, $allowedFileTypes);
}
// get the file extension
function getExtension($filename)
{
    $extension = substr($filename, strrpos($filename, '.') + 1);
$basedir = isset($_GET['basedir']) ? $_GET['basedir'] : "../attachments/";
if (strrpos($basedir, "/") != strlen($basedir) - 1) {
    $basedir .= "/";
}
//echo $basedir;
//保存数据
if ($action == "save") {
    $check_info = 1;
    //检测输入内容
    if ($_FILES['myfile'] == "") {
        $ActionMessage = $strErrNull;
        $check_info = 0;
        $action = "add";
    }
    //检测允许上传类型
    if ($check_info == 1 && !checkFileType($_FILES["myfile"]["name"])) {
        $ActionMessage = $strAttachmentsError;
        $check_info = 0;
        $action = "add";
    }
    if ($check_info == 1 && $_FILES["myfile"]["name"] != "") {
        //上传
        $attachment = upload_file($_FILES["myfile"]["tmp_name"], $_FILES["myfile"]["name"], $basedir);
        do_filter("f2_attach", $basedir . "/" . $attachment);
    }
}
//保存修改文件名
if ($action == "savefile") {
    $attach_id = $_POST['attach_id'];
    $new_file = $_POST['attach_name'] . substr($attach_id, strrpos($attach_id, "."));
    $sql = "update " . $DBPrefix . "attachments set attTitle='" . $new_file . "' where name like '%" . $attach_id . "'";
function validateSingleEpisode($episodeFile)
{
    //include functions and variables in config.php
    include "core/includes.php";
    $episodeFile_parts = divideFilenameFromExtension($episodeFile);
    // PHP >= 5.2.0 needed
    $episodeFilenameWithoutExtension = $episodeFile_parts[0];
    $EpisodeFileExtension = strtolower($episodeFile_parts[1]);
    //lowercase extension
    $checkEpisodeFileFormat = checkFileType($EpisodeFileExtension, $absoluteurl);
    $episodeFileType = $checkEpisodeFileFormat[0];
    $episodeFileMimeType = $checkEpisodeFileFormat[1];
    $episodeFileFullPath = $absoluteurl . $upload_dir . $episodeFile;
    $episodeFileXMLDB = $absoluteurl . $upload_dir . $episodeFilenameWithoutExtension . '.xml';
    //database file
    //If media file is ok and XML file is associated to it
    if (isset($episodeFileType) and $EpisodeFileExtension == $episodeFileType and file_exists($episodeFileXMLDB)) {
        //NB. $GoForIt = TRUE means that the episode file format is supported, it has a corresponding XML data file
        $GoForIt = TRUE;
        $OkButNoXMLDBpresent = FALSE;
    } else {
        if (isset($episodeFileType) and $EpisodeFileExtension == $episodeFileType and !file_exists($episodeFileXMLDB)) {
            $GoForIt = FALSE;
            $OkButNoXMLDBpresent = TRUE;
        } else {
            $GoForIt = FALSE;
            $OkButNoXMLDBpresent = FALSE;
        }
    }
    return array($GoForIt, $episodeFileFullPath, $episodeFileXMLDB, $episodeFileType, $episodeFileMimeType, $episodeFilenameWithoutExtension, $OkButNoXMLDBpresent);
}
         }
     } else {
         if (!@unlink($file)) {
             echo "<p class=\"error\">" . printMsg("err") . printMsg("errFileNotDel", $file) . "</p>";
         } else {
             echo "<p class=\"okay\">" . printMsg("textFileDel", $file) . "</p>";
         }
     }
 } elseif ($action == "upload") {
     // If we are to upload a file we will do so.
     $tmp_name = $_FILES['localfile']['tmp_name'];
     $name = stripslashes("{$dir}/{$_FILES['localfile']['name']}");
     $ext = getExt($name);
     $type = $_FILES["localfile"]["type"];
     if ($_FILES["localfile"]["error"] == 0) {
         if (checkFileType($type, getExt($name)) == TRUE) {
             if (@move_uploaded_file($tmp_name, $name)) {
                 @chmod($name, 0777);
                 echo "<p class=\"okay\">" . printMsg("textUp", $name) . "</p>";
             }
         } else {
             echo "<p class=\"error\">" . printMsg("err") . printMsg("errUp0", $_FILES["localfile"]["type"], getExt($name)) . "</p>";
         }
     } else {
         switch ($_FILES["localfile"]["error"]) {
             case 1:
                 $currenterror = printMsg("errUp1");
                 break;
             case 2:
                 $currenterror = printMsg("errUp1");
                 break;
            $ActionMessage = $Error_Message . $OK_Message;
        }
    }
}
//保存修改文件名
if ($action == "savefile" && !empty($_POST['file_id'])) {
    $file_id = intval($_POST['file_id']);
    //更新附件
    if (!empty($_FILES['myfile'])) {
        $check_info = 1;
        $arrFileName = $_FILES['myfile']["name"];
        $arrFileSize = $_FILES['myfile']["size"];
        $arrTempName = $_FILES['myfile']["tmp_name"];
        $arrFileType = $_FILES['myfile']["type"];
        $fileTitle = encode($_POST['fileTitle']);
        if (!checkFileType($arrFileName)) {
            $ActionMessage = $strAttachmentsError;
            $check_info = 0;
            $action = "edit";
        }
        if ($check_info == 1 && $arrFileName != "") {
            //上传
            $attachment = upload_file($arrTempName, $arrFileName, $basedir);
            if ($attachment == "") {
                $ActionMessage = $strAttachmentsError;
                $action = "edit";
            } else {
                do_filter("f2_attach", $basedir . "/" . $attachment);
                $filename = str_replace("../attachments/", "", $basedir . $attachment);
                if ($imageAtt = getimagesize("../attachments/{$filename}")) {
                    $fileWidth = $imageAtt[0];
function upload_file($temp_file, $file_name, $dir, $tmp_name = "")
{
    if (empty($tmp_name)) {
        $tmp_name = validCode(10);
    }
    $return = "";
    if ($temp_file != "") {
        if (check_dir($dir)) {
            $type = getFileType($file_name);
            if (checkFileType($file_name)) {
                $file_path = "{$dir}/{$tmp_name}.{$type}";
                //$copy_result=copy($temp_file,"$file_path");
                if (@copy($temp_file, $file_path) || function_exists('move_uploaded_file') && @move_uploaded_file($temp_file, $file_path)) {
                    @unlink($temp_file);
                    $check_info = true;
                }
                if (!$check_info && is_readable($temp_file)) {
                    $attachedfile = readfromfile($temp_file);
                    $fp = @fopen($file_path, 'wb');
                    @flock($fp, 2);
                    if (@fwrite($fp, $attachedfile)) {
                        @unlink($temp_file);
                        $check_info = true;
                    }
                    @fclose($fp);
                }
                $return = $check_info ? $tmp_name . "." . $type : "";
            }
        }
    }
    return $return;
}
function upload_file($temp_file, $file_name, $dir)
{
    global $cfg_upload_file;
    $tmp_name = time();
    $return = "";
    if ($temp_file != "") {
        if (check_dir($dir)) {
            $type = getFileType($file_name);
            if (checkFileType($file_name)) {
                $file_path = "{$dir}/{$tmp_name}.{$type}";
                $copy_result = @copy($temp_file, "{$file_path}");
                $return = $tmp_name . "." . $type;
            }
        }
    }
    return $return;
}
Exemple #10
0
<?php

namespace Home\Service\FileAppService;

$file = $_FILES["picture"];
$allowFileType = array('jpeg', 'doc', 'docx', 'gif', 'bmp', 'png', 'rar', 'txt', 'pdf', 'zip', 'xlsx', 'xls');
$fileInfo = explode('.', $_POST['fileURL']);
// 	$handle=fopen('/home/testFile','w+');
// 	foreach($_POST as $key=>$value){
// 		$string="$key=>$value;";
// 		fwrite($handle, $string);
// 	}
// 	fclose($handle);
$fileType = checkFileType($file["tmp_name"]);
if (in_array($fileType, $allowFileType) || $fileInfo[count($fileInfo) - 1] == 'txt') {
    if ($file["error"] > 0) {
        // 		记录日志
        Logger::log("Upload failed. Field \$file['error'] is true.");
    } else {
        if (file_exists("upload/" . $file["name"])) {
            echo $file["name"] . " already exists. ";
        } else {
            $targetURL = $_POST["fileURL"];
            if (!file_exists(dirname($targetURL))) {
                mkdir(dirname($targetURL), 0777, true);
            }
            if (file_exists(dirname($targetURL))) {
                if (!file_exists($file["tmp_name"])) {
                    // 					记录日志
                    Logger::log("Upload failed. File " . $file["tmp_name"] . " dosen't exist.");
                    return;
########### End
//// FORCE DOWNLOAD OF SUPPORTED FILES (e.g. files don't play in the browser, even when a plugin is installed)
//NB. does not work with some mobile browsers
include "config.php";
include $absoluteurl . "core/functions.php";
$filename = $_GET['filename'];
//Clean variable, avoid downloading of file outside podcast generator root directory.
$filename = str_replace("/", "", $filename);
// Replace / in the filename
$filename = str_replace("\\", "", $filename);
// Replace \ in the filename
$filename_path = $absoluteurl . $upload_dir . $filename;
// absolute path of the filename to download
if (file_exists($filename_path)) {
    $file_media = divideFilenameFromExtension($filename);
    $fileData = checkFileType($file_media[1], $absoluteurl);
    $podcast_filetype = $fileData[0];
    $filemimetype = $fileData[1];
    $isFileSupported = $fileData[2];
    // SECURITY OPTION: if extension is supported (file to download must have a known episode extension)
    if ($isFileSupported == TRUE and $file_media[1] == $podcast_filetype and !publishInFuture($filename_path)) {
        //// Headers
        ### required by internet explorer
        if (ini_get('zlib.output_compression')) {
            ini_set('zlib.output_compression', 'Off');
        }
        ###
        header("Pragma: public");
        // required
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
if (!is_dir("{$uploadFolder}")) {
    $aErrors[] = "The directory <b>" . $uploadFolder . "</b> doesn't exist.";
}
//check if the directory is writable.
if (count($aErrors) == 0 && !is_writeable("{$uploadFolder}")) {
    $aErrors[] = "Unable to write to directory: <b>" . $uploadFolder . "</b>. Change directory permissions: First try 0755, and if that fails 0777";
}
//not determining correctly if writeable or not.  Might be checking for writeable via PHP, not public
//Check first if a file has been sent via HTTP POST. Returns false otherwise.
if (count($aErrors) == 0 && is_uploaded_file($_FILES['FileToUpload']['tmp_name'])) {
    $size = $_FILES['FileToUpload']['size'];
    //Get the Size of the File
    if (count($aErrors) == 0 && $size > $sizeBytes) {
        $aErrors[] = "The File you tried to upload is <b>" . $size . "</b>K. Maximum file size: <b>" . $sizeBytes . "</b>K. Please upload a smaller file.";
    }
    if (count($aErrors) == 0 && !checkFileType($file_types, $_FILES['FileToUpload']['type'])) {
        //Make sure file is of allowable file types
        $aErrors[] = "File you tried to upload is <b>" . $_FILES['FileToUpload']['type'] . "</b>. This file type is not currently allowed.";
    }
    //move_filetoupload_file('filename','destination') Moves file to directory
    if (count($aErrors) == 0 && move_uploaded_file($_FILES['FileToUpload']['tmp_name'], $uploadFolder . $FileName)) {
        if ($createThumb == "TRUE") {
            //create thumbnail in same folder, add thumbSuffix
            $tempImage = ImageCreateFromJPEG($uploadFolder . $FileName);
            //copy to temporary image
            $width = ImageSx($tempImage);
            // Original picture width
            $height = ImageSy($tempImage);
            // Original picture height
            $thumbHeight = floor($height * ($thumbWidth / $width));
            // calculate proper thumbnail height
     $auth_email = NULL;
     //ignore email
 }
 #show submitted data (debug purposes)
 //$PG_mainbody .= "Dati inseriti:</b><br><br>Titolo: <i>$title</i> <br>Descrizione breve: <i>$description</i> <br>Descrizione lunga: <i>$long_description</i>";
 ###
 ## start processing podcast
 $PG_mainbody .= "<p><b>" . _("Processing episode...") . "</b></p>";
 $PG_mainbody .= "<p>" . _("Original filename:") . " <i>{$file}</i></p>";
 $file_parts = divideFilenameFromExtension($file);
 $filenameWithoutExtension = $file_parts[0];
 $fileExtension = $file_parts[1];
 // $PG_mainbody .= "<p>"._("File")."_ext <i>$fileExtension</i></p>"; //display file extension
 ##############
 ### processing file extension
 $fileData = checkFileType(strtolower($fileExtension), $absoluteurl);
 //lowercase extension to compare with the accepted extensions array
 if (isset($fileData[0])) {
     //avoids php notice if array [0] doesn't exist
     $podcast_filetype = $fileData[0];
 } else {
     $podcast_filetype = NULL;
 }
 if ($fileExtension == strtoupper($podcast_filetype)) {
     $podcast_filetype = strtoupper($podcast_filetype);
 }
 //accept also uppercase extension
 if ($fileExtension == $podcast_filetype) {
     //003 (if file extension is accepted, go on....
     ##############
     ##############