Пример #1
1
	protected function _validate($context)
	{
		$config = $this->_config;
		$row = $context->caller;

		if (is_uploaded_file($row->file) && $config->restrict && !in_array($row->extension, $config->ignored_extensions->toArray())) 
		{
			if ($row->isImage()) 
			{
				if (getimagesize($row->file) === false) {
					$context->setError(JText::_('WARNINVALIDIMG'));
					return false;
				}
			}
			else 
			{
				$mime = KFactory::get('com://admin/files.database.row.file')->setData(array('path' => $row->file))->mimetype;

				if ($config->check_mime && $mime) 
				{
					if (in_array($mime, $config->illegal_mimetypes->toArray()) || !in_array($mime, $config->allowed_mimetypes->toArray())) {
						$context->setError(JText::_('WARNINVALIDMIME'));
						return false;
					}
				}
				elseif (!$config->authorized) {
					$context->setError(JText::_('WARNNOTADMIN'));
					return false;
				}
			}
		}
	}
Пример #2
0
 public function postProcess()
 {
     if (Tools::isSubmit('submitAdd' . $this->table)) {
         if ($id = intval(Tools::getValue('id_attachment')) and $a = new Attachment($id)) {
             $_POST['file'] = $a->file;
             $_POST['mime'] = $a->mime;
         }
         if (!sizeof($this->_errors)) {
             if (isset($_FILES['file']) and is_uploaded_file($_FILES['file']['tmp_name'])) {
                 if ($_FILES['file']['size'] > $this->maxFileSize) {
                     $this->_errors[] = $this->l('File too large, maximum size allowed:') . ' ' . $this->maxFileSize / 1000 . ' ' . $this->l('kb');
                 } else {
                     $uploadDir = dirname(__FILE__) . '/../../download/';
                     do {
                         $uniqid = sha1(microtime());
                     } while (file_exists($uploadDir . $uniqid));
                     if (!copy($_FILES['file']['tmp_name'], $uploadDir . $uniqid)) {
                         $this->_errors[] = $this->l('File copy failed');
                     }
                     @unlink($_FILES['file']['tmp_name']);
                     $_POST['name_2'] .= '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
                     $_POST['file'] = $uniqid;
                     $_POST['mime'] = $_FILES['file']['type'];
                 }
             }
         }
         $this->validateRules();
     }
     return parent::postProcess();
 }
function upload_file()
{
    echo "hi";
    $FromUserId = $_POST['FromUserId'];
    //	$upload_dir = 'C:\Users\Kumi\Desktop\phpUpload';
    echo $FromUserId;
    echo "hello0";
    $upload_dir = '/afs/cad/u/h/h/hhm4/public_html/UPLOADS/';
    $upload_dir_db = 'C:\\\\Users\\\\Kumi\\\\Desktop\\\\phpUpload';
    echo "hello1";
    print_r($_FILES);
    if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
        echo "hello2";
        $dest = $_FILES['userfile']['name'];
        print_r($_FILES);
        echo $dest;
        echo $upload_dir / $dest;
        $dest_db = "\\\\" . $dest;
        $store_dir = $upload_dir_db . $dest_db;
        echo "{$store_dir}";
        $moveBool = false;
        $moveBool = move_uploaded_file($_FILES['userfile']['tmp_name'], "{$upload_dir}/{$dest}");
        if ($moveBool) {
            print_r('Success');
        }
    } else {
        echo "Possible file upload attack: ";
        echo "filename '" . $_FILES['userfile']['tmp_name'] . "'.";
        print_r($_FILES);
    }
}
Пример #4
0
function upload($filename)
{
    $log = '../log/error.log';
    // print_r($_FILES);
    // exit();
    echo '<br>FILE NAME ->' . $_FILES['type'] . "<br>";
    if (preg_match('/^image\\/p?jpeg$/i', $_FILES['upload']['type'])) {
        $ext = '.jpg';
    } else {
        if (preg_match('/^image\\/gif$/i', $_FILES['upload']['type'])) {
            $ext = '.gif';
        } else {
            if (preg_match('/^image\\/(x-)?png$/i', $_FILES['upload']['type'])) {
                $ext = '.png';
            } else {
                $ext = '.unknown';
            }
        }
    }
    $filename = '/img/' . time() . $filename . $_SERVER['REMOTE_ADDR'] . $ext;
    if (!is_uploaded_file($_FILES['upload']['tmp_name']) or !copy($_FILES['upload']['tmp_name'], $filename)) {
        $error = PHP_EOL . time() . "\t" . $_SERVER['REMOTE_ADDR'] . "-\tCould not save file as {$filename}!";
        file_put_contents($log, $error, FILE_APPEND);
    }
    return $filename;
}
Пример #5
0
 /**
  * Handles an uploaded file, stores it to the correct folder, adds an entry
  * to the database and returns a TBGFile object
  * 
  * @param string $thefile The request parameter the file was sent as
  * 
  * @return TBGFile The TBGFile object
  */
 public function handleUpload($key, $file_name = null, $file_dir = null)
 {
     $apc_exists = self::CanGetUploadStatus();
     if ($apc_exists && !array_key_exists($this->getParameter('APC_UPLOAD_PROGRESS'), $_SESSION['__upload_status'])) {
         $_SESSION['__upload_status'][$this->getParameter('APC_UPLOAD_PROGRESS')] = array('id' => $this->getParameter('APC_UPLOAD_PROGRESS'), 'finished' => false, 'percent' => 0, 'total' => 0, 'complete' => 0);
     }
     try {
         $thefile = $this->getUploadedFile($key);
         if ($thefile !== null) {
             if ($thefile['error'] == UPLOAD_ERR_OK) {
                 Logging::log('No upload errors');
                 if (is_uploaded_file($thefile['tmp_name'])) {
                     Logging::log('Uploaded file is uploaded');
                     $files_dir = $file_dir === null ? Caspar::getUploadPath() : $file_dir;
                     $new_filename = $file_name === null ? Caspar::getUser()->getID() . '_' . NOW . '_' . basename($thefile['name']) : $file_name;
                     Logging::log('Moving uploaded file to ' . $new_filename);
                     if (!move_uploaded_file($thefile['tmp_name'], $files_dir . $new_filename)) {
                         Logging::log('Moving uploaded file failed!');
                         throw new \Exception(Caspar::getI18n()->__('An error occured when saving the file'));
                     } else {
                         Logging::log('Upload complete and ok');
                         return true;
                     }
                 } else {
                     Logging::log('Uploaded file was not uploaded correctly');
                     throw new \Exception(Caspar::getI18n()->__('The file was not uploaded correctly'));
                 }
             } else {
                 Logging::log('Upload error: ' . $thefile['error']);
                 switch ($thefile['error']) {
                     case UPLOAD_ERR_INI_SIZE:
                     case UPLOAD_ERR_FORM_SIZE:
                         throw new \Exception(Caspar::getI18n()->__('You cannot upload files bigger than %max_size% MB', array('%max_size%' => Settings::getUploadsMaxSize())));
                         break;
                     case UPLOAD_ERR_PARTIAL:
                         throw new \Exception(Caspar::getI18n()->__('The upload was interrupted, please try again'));
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         throw new \Exception(Caspar::getI18n()->__('No file was uploaded'));
                         break;
                     default:
                         throw new \Exception(Caspar::getI18n()->__('An unhandled error occured') . ': ' . $thefile['error']);
                         break;
                 }
             }
             Logging::log('Uploaded file could not be uploaded');
             throw new \Exception(Caspar::getI18n()->__('The file could not be uploaded'));
         }
         Logging::log('Could not find uploaded file' . $key);
         throw new \Exception(Caspar::getI18n()->__('Could not find the uploaded file. Please make sure that it is not too big.'));
     } catch (Exception $e) {
         Logging::log('Upload exception: ' . $e->getMessage());
         if ($apc_exists) {
             $_SESSION['__upload_status'][$this->getParameter('APC_UPLOAD_PROGRESS')]['error'] = $e->getMessage();
             $_SESSION['__upload_status'][$this->getParameter('APC_UPLOAD_PROGRESS')]['finished'] = true;
             $_SESSION['__upload_status'][$this->getParameter('APC_UPLOAD_PROGRESS')]['percent'] = 100;
         }
         throw $e;
     }
 }
Пример #6
0
 /**
  * Return the (temporary) path to an uploaded file.
  * @param $fileName string the name of the file used in the POST form
  * @return string (boolean false if no such file)
  */
 function getUploadedFilePath($fileName)
 {
     if (isset($_FILES[$fileName]['tmp_name']) && is_uploaded_file($_FILES[$fileName]['tmp_name'])) {
         return $_FILES[$fileName]['tmp_name'];
     }
     return false;
 }
Пример #7
0
 public function send($data, $name, $local)
 {
     if (!empty($data)) {
         //echo 'component: <pre>'; print_r ($data); echo '</pre>';
         //echo '<br>'.count($data);
         //exit;
         /*if ( count( $data ) > $this->max_files ) {
         			throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
         		}*/
         $file = $data;
         //foreach ($data as $file) {
         //echo 'component file: <pre>'; print_r ($file); echo '</pre>';
         //echo '<br>'.count($data);
         //exit;
         $filename = $file['name'];
         $file_tmp_name = $file['tmp_name'];
         $dir = WWW_ROOT . 'uploads' . DS . $local;
         $allowed = array('png', 'jpg', 'jpeg', 'pdf', 'doc', 'docx', 'txt', 'css', 'html');
         if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
             throw new InternalErrorException("Error Processing Request.", 1);
         } elseif (is_uploaded_file($file_tmp_name)) {
             //move_uploaded_file($file_tmp_name, $dir.DS.Text::uuid().'-'.$filename);
             move_uploaded_file($file_tmp_name, $dir . DS . $name);
         }
         //}
         //exit;
     }
 }
Пример #8
0
 function check()
 {
     if (isset($_FILES[$this->ref])) {
         $this->fileInfo = $_FILES[$this->ref];
     } else {
         $this->fileInfo = array('name' => '', 'type' => '', 'size' => 0, 'tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE);
     }
     if ($this->fileInfo['error'] == UPLOAD_ERR_NO_FILE) {
         if ($this->required) {
             return $this->container->errors[$this->ref] = jForms::ERRDATA_REQUIRED;
         }
     } else {
         if ($this->fileInfo['error'] == UPLOAD_ERR_NO_TMP_DIR || $this->fileInfo['error'] == UPLOAD_ERR_CANT_WRITE) {
             return $this->container->errors[$this->ref] = jForms::ERRDATA_FILE_UPLOAD_ERROR;
         }
         if ($this->fileInfo['error'] == UPLOAD_ERR_INI_SIZE || $this->fileInfo['error'] == UPLOAD_ERR_FORM_SIZE || $this->maxsize && $this->fileInfo['size'] > $this->maxsize) {
             return $this->container->errors[$this->ref] = jForms::ERRDATA_INVALID_FILE_SIZE;
         }
         if ($this->fileInfo['error'] == UPLOAD_ERR_PARTIAL || !is_uploaded_file($this->fileInfo['tmp_name'])) {
             return $this->container->errors[$this->ref] = jForms::ERRDATA_INVALID;
         }
         if (count($this->mimetype)) {
             $this->fileInfo['type'] = \Jelix\FileUtilities\File::getMimeType($this->fileInfo['tmp_name']);
             if ($this->fileInfo['type'] == 'application/octet-stream') {
                 // let's try with the name
                 $this->fileInfo['type'] = \Jelix\FileUtilities\File::getMimeTypeFromFilename($this->fileInfo['name']);
             }
             if (!in_array($this->fileInfo['type'], $this->mimetype)) {
                 return $this->container->errors[$this->ref] = jForms::ERRDATA_INVALID_FILE_TYPE;
             }
         }
     }
     return null;
 }
Пример #9
0
function downloadCsv()
{
    /*Validating photo - checking if downloaded, size, type*/
    if (isset($_FILES['csv_file'])) {
        /*checking photo size*/
        if ($_FILES["csv_file"]["size"] > 1024 * 1024) {
            echo "<p>Слишком большой файл.</p>";
            exit;
        } elseif (validateFileType($_FILES["csv_file"]["type"]) == false) {
            echo "Файл должен быть в формате CSV";
            exit;
        }
        /*Checking/creating image folder*/
        $dir = "download_to";
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        /*checking if photo downloaded correctly*/
        if (is_uploaded_file($_FILES["csv_file"]["tmp_name"])) {
            if ($_FILES['csv_file']['error'] == 0) {
                // Если файл загружен успешно, перемещаем его из временной директории в конечную
                move_uploaded_file($_FILES["csv_file"]["tmp_name"], "download_to/" . $_FILES["csv_file"]["name"]);
                $_FILES["csv_file"]["tmp_name"] = "/import-of-products/download_to/";
            }
        }
        echo "CSV file downloaded successfully!<br>";
        //var_dump($_FILES['csv_file']);
    } else {
        echo "Вы не выбрали файл.";
    }
}
Пример #10
0
 function upload($to_name = "")
 {
     $new_name = $this->set_file_name($to_name);
     if ($this->check_file_name($new_name)) {
         if ($this->validateExtension()) {
             if (is_uploaded_file($this->the_temp_file)) {
                 $this->file_copy = $new_name;
                 if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
                     $this->message[] = $this->error_text($this->http_error);
                     if ($this->rename_file) {
                         $this->message[] = $this->error_text(16);
                     }
                     return true;
                 }
             } else {
                 $this->message[] = $this->error_text($this->http_error);
                 return false;
             }
         } else {
             $this->show_extensions();
             $this->message[] = $this->error_text(11);
             return false;
         }
     } else {
         return false;
     }
 }
Пример #11
0
function subirArchivo($arch, $folder, $filename, $extensionesPermitidas, $maxFileSize, &$error, &$finalFilename) {
	$tmpfile = $arch["tmp_name"];
	$partes_ruta = pathinfo(strtolower($arch["name"]));

	if (!in_array($partes_ruta["extension"], $extensionesPermitidas)) {
		$error = "El archivo debe tener alguna de las siguientes extensiones: ".implode(" o ", $extensionesPermitidas).".";
		return false;
	}

	$filename = stringToLower($filename.".".$partes_ruta["extension"]);
	$finalFilename = $folder.$filename;

	if (!is_uploaded_file($tmpfile)) {
		$error = "El archivo no subió correctamente.";
		return false;
	}

	if (filesize($tmpfile) > $maxFileSize) {
		$error = "El archivo no puede ser mayor a ".tamanoArchivo($maxFileSize).".";
		return false;
	}

	if (!move_uploaded_file($tmpfile, $folder.$filename)) {
		$error = "El archivo no pudo ser guardado.";
		return false;
	}

	return true;
}
Пример #12
0
 /**
  * 上传图片
  */
 protected function Uploadpic($picdir = "")
 {
     $res['error'] = "";
     if (is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
         $info = explode('.', strrev($_FILES['fileToUpload']['name']));
         //配置要上传目录地址
         $datadir = date("Y-m-d");
         $picdir = $picdir . "/" . $datadir;
         $picname = "user_" . intval($_REQUEST['project_id']) . "_" . time() . "." . strrev($info[0]);
         $fullname = $picdir . "/" . $picname;
         if (BaseTool::createABFolder($picdir)) {
             if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $fullname)) {
                 $res["msg"] = "success";
                 $res["dir"] = $datadir . "/" . $picname;
             } else {
                 $res["error"] = "上传失败";
             }
         } else {
             $res['error'] = "上传失败";
         }
     } else {
         $res['error'] = '上传的文件不存在';
     }
     return $res;
 }
Пример #13
0
 function import_translations_post($project_path, $locale_slug, $translation_set_slug)
 {
     $project = GP::$project->by_path($project_path);
     $locale = GP_Locales::by_slug($locale_slug);
     if (!$project || !$locale) {
         return $this->die_with_404();
     }
     $translation_set = GP::$translation_set->by_project_id_slug_and_locale($project->id, $translation_set_slug, $locale_slug);
     if (!$translation_set) {
         return $this->die_with_404();
     }
     if ($this->cannot_and_redirect('approve', 'translation-set', $translation_set->id)) {
         return;
     }
     $format = gp_array_get(GP::$formats, gp_post('format', 'po'), null);
     if (!$format) {
         $this->redirect_with_error(__('No such format.', 'glotpress'));
         return;
     }
     if (!is_uploaded_file($_FILES['import-file']['tmp_name'])) {
         $this->redirect_with_error(__('Error uploading the file.', 'glotpress'));
         return;
     }
     $translations = $format->read_translations_from_file($_FILES['import-file']['tmp_name'], $project);
     if (!$translations) {
         $this->redirect_with_error(__('Couldn&#8217;t load translations from file!', 'glotpress'));
         return;
     }
     $translations_added = $translation_set->import($translations);
     $this->notices[] = sprintf(__('%s translations were added', 'glotpress'), $translations_added);
     $this->redirect(gp_url_project($project, gp_url_join($locale->slug, $translation_set->slug)));
 }
Пример #14
0
 public static function saveFile($file, $form)
 {
     if (!is_uploaded_file($file['tmp_name'])) {
         return $form;
     }
     $fileName = mediaUtils::fixFileName($file['name']);
     $fileDir = dir::media($fileName);
     $extension = substr(strrchr($fileName, '.'), 1);
     // z.B. jpg
     $badExtensions = dyn::get('addons')['badExtensions'];
     // Wenn die Datei eine "verbotene" Datei ist
     if (in_array($extension, $badExtensions)) {
         $form->setSave(false);
         $form->setErrorMessage(sprintf(lang::get('media_error_bad_extension'), $file['name']));
         return $form;
     }
     if ($form->isEditMode()) {
         $media = new media(type::super('id', 'int', 0));
     }
     // Wenn Datei nicht Existiert
     // Oder man möchte sie überspeichern
     if ($form->isEditMode() && $media->get('filename') != $fileName || !$form->isEditMode() && file_exists($fileDir)) {
         $form->setSave(false);
         $form->setErrorMessage(sprintf(lang::get('media_error_already_exist'), $file['name']));
         return $form;
     }
     if (!move_uploaded_file($file['tmp_name'], $fileDir)) {
         $form->setSave(false);
         $form->setErrorMessage(sprintf(lang::get('media_error_move'), $file['name']));
         return $form;
     }
     $form->addPost('filename', $fileName);
     $form->addPost('size', filesize($fileDir));
     return $form;
 }
Пример #15
0
 private function initialize($file, $path = NULL)
 {
     if (is_array($file)) {
         // uploaded file
         // check if file is realy uploaded
         if (!array_key_exists('tmp_name', $file) || !is_uploaded_file($file['tmp_name'])) {
             throw new Exception('wrong file.');
         }
         // first move uploaded file to safe (read safemode) location
         $this->file = basename($file['tmp_name']);
         /*
         $director = Director::getInstance();
         $tmpPath = $director->getTempPath();
         move_uploaded_file($file['tmp_name'], $tmpPath."/".$this->file);
         */
         $this->setPath(dirname($file['tmp_name']));
         $this->filename = $file['name'];
         $this->uploaded = true;
     } else {
         // file from database or whatever
         $this->setPath(isset($path) ? realpath($path) : realpath(dirname($file)));
         $this->file = basename($file);
         $this->filename = $this->file;
         $this->uploaded = false;
         // check if file exists
         if (!is_file($this->getFileName())) {
             $this->file = '';
         }
     }
     // check if file is image
     //if(!$this->isImage($this->filename)) throw new Exception("file type not supported: {$this->filename}");
     if (!$this->isImage($this->filename)) {
         $this->file = '';
     }
 }
Пример #16
0
 function parse()
 {
     global $messageStack;
     if (isset($_FILES[$this->file])) {
         $file = array('name' => $_FILES[$this->file]['name'], 'type' => $_FILES[$this->file]['type'], 'size' => $_FILES[$this->file]['size'], 'tmp_name' => $_FILES[$this->file]['tmp_name']);
     } elseif (isset($GLOBALS['_FILES'][$this->file])) {
         $file = array('name' => $_FILES[$this->file]['name'], 'type' => $_FILES[$this->file]['type'], 'size' => $_FILES[$this->file]['size'], 'tmp_name' => $_FILES[$this->file]['tmp_name']);
     } else {
         $file = array('name' => isset($GLOBALS[$this->file . '_name']) ? $GLOBALS[$this->file . '_name'] : '', 'type' => isset($GLOBALS[$this->file . '_type']) ? $GLOBALS[$this->file . '_type'] : '', 'size' => isset($GLOBALS[$this->file . '_size']) ? $GLOBALS[$this->file . '_size'] : '', 'tmp_name' => isset($GLOBALS[$this->file]) ? $GLOBALS[$this->file] : '');
     }
     if (tep_not_null($file['tmp_name']) && $file['tmp_name'] != 'none' && is_uploaded_file($file['tmp_name'])) {
         if (sizeof($this->extensions) > 0) {
             if (!in_array(strtolower(substr($file['name'], strrpos($file['name'], '.') + 1)), $this->extensions)) {
                 if ($this->message_location == 'direct') {
                     $messageStack->add(ERROR_FILETYPE_NOT_ALLOWED, 'error');
                 } else {
                     $messageStack->add_session(ERROR_FILETYPE_NOT_ALLOWED, 'error');
                 }
                 return false;
             }
         }
         $this->set_file($file);
         $this->set_filename($file['name']);
         $this->set_tmp_filename($file['tmp_name']);
         return $this->check_destination();
     } else {
         if ($this->message_location == 'direct') {
             $messageStack->add(WARNING_NO_FILE_UPLOADED, 'warning');
         } else {
             $messageStack->add_session(WARNING_NO_FILE_UPLOADED, 'warning');
         }
         return false;
     }
 }
Пример #17
0
 public function onSubmit(array $data, \HTMLForm $form = null)
 {
     // Get uploaded file
     $upload =& $_FILES['wpjsonimport'];
     // Check to make sure there is a file uploaded
     if ($upload === null || !$upload['name']) {
         return \Status::newFatal('importnofile');
     }
     // Messages borrowed from Special:Import
     if (!empty($upload['error'])) {
         switch ($upload['error']) {
             case 1:
             case 2:
                 return \Status::newFatal('importuploaderrorsize');
             case 3:
                 return \Status::newFatal('importuploaderrorpartial');
             case 4:
                 return \Status::newFatal('importuploaderrortemp');
             default:
                 return \Status::newFatal('importnofile');
         }
     }
     // Read file
     $fname = $upload['tmp_name'];
     if (!is_uploaded_file($fname)) {
         return \Status::newFatal('importnofile');
     }
     $data = \FormatJSON::parse(file_get_contents($fname));
     // If there is an error during JSON parsing, abort
     if (!$data->isOK()) {
         return $data;
     }
     $this->doImport($data->getValue());
 }
function cpm_action_multiple_upload_file()
{
    global $comicpress_manager, $comicpress_manager_admin;
    if (strtotime($_POST['time']) === false) {
        $comicpress_manager->warnings[] = sprintf(__('<strong>There was an error in the post time (%1$s)</strong>.  The time is not parseable by strtotime().', 'comicpress-manager'), $_POST['time']);
    } else {
        $files_to_handle = array();
        foreach ($_FILES as $name => $info) {
            if (strpos($name, "upload-") !== false) {
                if (is_uploaded_file($_FILES[$name]['tmp_name'])) {
                    $files_to_handle[] = $name;
                } else {
                    switch ($_FILES[$name]['error']) {
                        case UPLOAD_ERR_INI_SIZE:
                        case UPLOAD_ERR_FORM_SIZE:
                            $comicpress_manager->warnings[] = sprintf(__("<strong>The file %s was too large.</strong>  The max allowed filesize for uploads to your server is %s.", 'comicpress-manager'), $_FILES[$name]['name'], ini_get('upload_max_filesize'));
                            break;
                        case UPLOAD_ERR_NO_FILE:
                            break;
                        default:
                            $comicpress_manager->warnings[] = sprintf(__("<strong>There was an error in uploading %s.</strong>  The <a href='http://php.net/manual/en/features.file-upload.errors.php'>PHP upload error code</a> was %s.", 'comicpress-manager'), $_FILES[$name]['name'], $_FILES[$name]['error']);
                            break;
                    }
                }
            }
        }
        if (count($files_to_handle) > 0) {
            $comicpress_manager_admin->handle_file_uploads($files_to_handle);
            $comicpress_manager->comic_files = $comicpress_manager->read_comics_folder();
        } else {
            $comicpress_manager->warnings[] = __("<strong>You didn't upload any files!</strong>", 'comicpress-manager');
        }
    }
}
Пример #19
0
function subirImagen($file)
{
    $path = "../../imagenes/";
    $extension = "";
    $newName = "";
    $fullPath = "";
    $query = "";
    if ($file['error'] == 0) {
        if (is_uploaded_file($file['tmp_name'])) {
            $imagteType = exif_imagetype($file['tmp_name']);
            if ($imagteType == IMAGETYPE_JPEG) {
                $extension = ".jpeg";
                $newName = md5($file['name'] . date('d-m-Y H:i:s')) . $extension;
            } elseif ($imagteType == IMAGETYPE_PNG) {
                $extension = ".png";
                $newName = md5($file['name'] . date('d-m-Y H:i:s')) . $extension;
            }
            //Moviendo la imagen al directorio permanente
            if ($newName != "") {
                if (move_uploaded_file($file['tmp_name'], $path . $newName)) {
                    $fullPath = $path . $newName;
                }
            }
        }
    }
    return $fullPath;
}
function PhotoUploaded()
{
    $tmp_file = $_FILES['photo']['tmp_name'];
    $content_dir = dirname(__FILE__) . "/ressources/conf/upload";
    if (!is_dir($content_dir)) {
        @mkdir($content_dir);
    }
    if (!@is_uploaded_file($tmp_file)) {
        writelogs("PHOTO: error_unable_to_upload_file", __FUNCTION__, __FILE__, __LINE__);
        $GLOBALS["Photo_error"] = '{error_unable_to_upload_file} ' . $tmp_file;
        return;
    }
    $name_file = $_FILES['photo']['name'];
    if (file_exists($content_dir . "/" . $name_file)) {
        @unlink($content_dir . "/" . $name_file);
    }
    if (!move_uploaded_file($tmp_file, $content_dir . "/" . $name_file)) {
        $GLOBALS["Photo_error"] = "{error_unable_to_move_file} : " . $content_dir . "/" . $name_file;
        writelogs("PHOTO: {error_unable_to_move_file} : " . $content_dir . "/" . $name_file, __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    $file = $content_dir . "/" . $name_file;
    writelogs("PHOTO: {$file}", __FUNCTION__, __FILE__, __LINE__);
    $jpegPhoto_datas = file_get_contents($file);
    $ad = new external_ad_search();
    if (!$ad->SaveUserPhoto($jpegPhoto_datas, $_POST["DN"])) {
        $GLOBALS["Photo_error"] = $ad->ldap_error;
        return;
    }
}
Пример #21
0
 /**
  * Function to get data from imported XML file
  *
  * @return file xml
  * @added 2.2
  */
 static function getData($file)
 {
     if (!is_admin()) {
         exit;
     }
     if (!$file['tmp_name']) {
         return RM_Status::set('error', __('No Import File Attached', 'responsive-menu'));
     }
     if ($file['type'] != 'text/xml') {
         return RM_Status::set('error', __('Incorrect Import File Format', 'responsive-menu'));
     }
     if ($file['size'] > 500000) {
         return RM_Status::set('error', __('Import File Too Large', 'responsive-menu'));
     }
     if (!is_uploaded_file($file['tmp_name'])) {
         return RM_Status::set('error', __('Import File Not Valid', 'responsive-menu'));
     }
     $data = file_get_contents($file['tmp_name']);
     $xml = simplexml_load_string($data);
     $json = json_encode($xml);
     $array = json_decode($json, TRUE);
     $decoded = array();
     foreach ($array as $key => $val) {
         /* Need to JSON Decode HTML Shapes */
         if ($key == 'RMArShpA' || $key == 'RMArShpI') {
             $decoded[$key] = is_array($val) ? null : json_decode(base64_decode($val));
         } else {
             $decoded[$key] = is_array($val) ? null : base64_decode($val);
         }
     }
     return $decoded;
 }
Пример #22
0
 /**
  * 接受上传文件,成功返回文件保存路径,失败返回上传的错误代码,假如不是上传文件则返回false
  * 使用文件上传注意要设置php.ini中的几个配置
  * upload_max_filesize
  * max_input_time
  * post_max_size
  * 在iis上
  * <configuration>
  * </system.webServer>
  * <security>
  * <requestFiltering>
  * <requestLimits maxAllowedContentLength="314572800"/>
  * </requestFiltering>
  * </security>
  * </system.webServer>
  * </configuration>
  *
  * @param $_FILES['file'] $file        	
  * @param $config config('file');        	
  * @return unknown|string|number|bool
  */
 function receive($file, $config)
 {
     set_time_limit(0);
     //ini_set('memory_limit', $config->size);
     if (is_uploaded_file($file['tmp_name'])) {
         if ($file['error'] != UPLOAD_ERR_OK) {
             return $file['error'];
         }
         if (isset($config['size']) && $file['size'] > $config['size']) {
             return UPLOAD_ERR_INI_SIZE;
         }
         $mimetype = filesystem::mimetype($file['tmp_name']);
         if (isset($config['type']) && !in_array($mimetype, $config['type'])) {
             return 8;
         }
         if (!is_writable(filesystem::path($config['path'])) || !is_dir(filesystem::path($config['path']))) {
             return UPLOAD_ERR_CANT_WRITE;
         }
         $type = empty(filesystem::type($file['name'])) ? 'tmpuploadfile' : filesystem::type($file['name']);
         $filename = rtrim($config['path'], '/') . '/' . md5_file($file['tmp_name']) . sha1_file($file['tmp_name']) . '.' . $type;
         if (move_uploaded_file($file['tmp_name'], $filename)) {
             return $filename;
         }
     }
     return false;
 }
 /**
  * Prepara uma imagem para upload. Aceita apenas JPG, PNG ou GIF
  * 
  * @param array $imagem $_POST  da imagem enviada
  * @param type $maxwidth largura máxima em pixels
  * @throws Exception
  */
 public function __construct($imagem, $maxwidth)
 {
     if (is_uploaded_file($imagem['tmp_name'])) {
         $mime = $imagem['type'];
         if ($mime == "image/jpeg" || $mime == "image/pjpeg" || $mime == "image/png" || $mime == "image/gif") {
             $this->image = $imagem;
             list($larg_orig, $alt_orig) = @getimagesize($this->image['tmp_name']);
             $this->y = $alt_orig;
             $this->x = $larg_orig;
         } else {
             throw new Exception(__('Formato de imagem não suportado'));
             return;
         }
     }
     if (empty($this->image)) {
         throw new Exception(__('Imagem não enviada'));
         return;
     }
     list($larg_orig, $alt_orig) = @getimagesize($this->image['tmp_name']);
     $razao_orig = $larg_orig / $alt_orig;
     $this->y = $maxwidth / $razao_orig;
     $this->x = $maxwidth;
     if ($this->y > 1000) {
         $this->y = 1000;
     }
 }
Пример #24
0
 public function validate($input)
 {
     if ($input instanceof \SplFileInfo) {
         $input = $input->getPathname();
     }
     return is_string($input) && is_uploaded_file($input);
 }
 /**
  *	This function will tell if the file was actually uploaded or not.
  *
  *	@returns	Boolean indicating if the file was uploaded or not.
  */
 function isUploaded()
 {
     if (!isset($_FILES[$this->_form . '_' . $this->_name]['tmp_name'])) {
         return false;
     }
     return is_uploaded_file($_FILES[$this->_form . '_' . $this->_name]['tmp_name']) && filesize($_FILES[$this->_form . '_' . $this->_name]['tmp_name']) > 0;
 }
Пример #26
0
 public function update_avatar($uID = false)
 {
     $this->setupUser($uID);
     if (!Loader::helper('validation/token')->validate()) {
         throw new Exception(Loader::helper('validation/token')->getErrorMessage());
     }
     if ($this->canEditAvatar) {
         $av = Loader::helper('concrete/avatar');
         if (is_uploaded_file($_FILES['avatar']['tmp_name'])) {
             $image = \Image::open($_FILES['avatar']['tmp_name']);
             $image = $image->thumbnail(new Box(Config::get('concrete.icons.user_avatar.width'), Config::get('concrete.icons.user_avatar.height')));
             $this->user->updateUserAvatar($image);
         } else {
             if ($_POST['task'] == 'clear') {
                 $this->user->update(array('uHasAvatar' => 0));
             }
         }
     } else {
         throw new Exception(t('Access Denied.'));
     }
     $ui = UserInfo::getByID($uID);
     // avatar doesn't reload automatically
     $sr = new UserEditResponse();
     $sr->setUser($this->user);
     $sr->setMessage(t('Avatar saved successfully.'));
     $html = $av->outputUserAvatar($ui);
     $sr->setAdditionalDataAttribute('imageHTML', $html);
     $sr->outputJSON();
 }
 /**
  * collect all fileinformations of given file and
  * save them to the global fileinformation array
  *
  * @param string $file
  * @return boolean is valid file?
  */
 protected function setFileInformations($file)
 {
     $this->fileInfo = array();
     // reset previously information to have a cleaned object
     $this->file = $file instanceof \TYPO3\CMS\Core\Resource\File ? $file : NULL;
     if (is_string($file) && !empty($file)) {
         $this->fileInfo = TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($file);
         $this->fileInfo['mtime'] = filemtime($file);
         $this->fileInfo['atime'] = fileatime($file);
         $this->fileInfo['owner'] = fileowner($file);
         $this->fileInfo['group'] = filegroup($file);
         $this->fileInfo['size'] = filesize($file);
         $this->fileInfo['type'] = filetype($file);
         $this->fileInfo['perms'] = fileperms($file);
         $this->fileInfo['is_dir'] = is_dir($file);
         $this->fileInfo['is_file'] = is_file($file);
         $this->fileInfo['is_link'] = is_link($file);
         $this->fileInfo['is_readable'] = is_readable($file);
         $this->fileInfo['is_uploaded'] = is_uploaded_file($file);
         $this->fileInfo['is_writeable'] = is_writeable($file);
     }
     if ($file instanceof \TYPO3\CMS\Core\Resource\File) {
         $pathInfo = \TYPO3\CMS\Core\Utility\PathUtility::pathinfo($file->getName());
         $this->fileInfo = array('file' => $file->getName(), 'filebody' => $file->getNameWithoutExtension(), 'fileext' => $file->getExtension(), 'realFileext' => $pathInfo['extension'], 'atime' => $file->getCreationTime(), 'mtime' => $file->getModificationTime(), 'owner' => '', 'group' => '', 'size' => $file->getSize(), 'type' => 'file', 'perms' => '', 'is_dir' => FALSE, 'is_file' => $file->getStorage()->getDriverType() === 'Local' ? is_file($file->getForLocalProcessing(FALSE)) : TRUE, 'is_link' => $file->getStorage()->getDriverType() === 'Local' ? is_link($file->getForLocalProcessing(FALSE)) : FALSE, 'is_readable' => TRUE, 'is_uploaded' => FALSE, 'is_writeable' => FALSE);
     }
     return $this->fileInfo !== array();
 }
Пример #28
0
 function index()
 {
     if ($this->input->post('PHPSESSID')) {
         session_id($this->input->post('PHPSESSID'));
     } else {
         return FALSE;
     }
     if (is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
         $config['allowed_types'] = $this->input->post('upload_ext');
         $config['upload_path'] = DATA_PATH . '/temp';
         $config['max_size'] = $this->input->post('upload_size');
         $config['encrypt_name'] = TRUE;
         $this->load->library('upload', $config);
         if ($this->upload->do_upload('Filedata')) {
             $data = $this->upload->data();
             $file = '/temp/' . $data['file_name'];
             $filedir = $this->config->item('base_url') . DATA_DIR . $file;
             $filepath = DATA_PATH . $file;
             if (strpos('.jpg.gif.png', strtolower($data['file_ext'])) !== FALSE) {
                 $info = array('imageurl' => $filedir, 'filename' => $data['orig_name'], 'filesize' => filesize($filepath), 'imagealign' => 'L', 'thumburl' => $filedir);
             } else {
                 $info = array('attachurl' => $filedir, 'filemime' => $data['file_type'], 'filename' => $data['orig_name'], 'filesize' => filesize($filepath));
             }
             echo json_encode($info);
         } else {
             echo $this->upload->display_errors('', '');
         }
     } else {
         return FALSE;
     }
 }
Пример #29
0
 public static function dumpApiRequest($host, $onlyIfAvailable = false)
 {
     if ($onlyIfAvailable) {
         //validate that the other DC is available before dumping the request
         if (kConf::hasParam('disable_dump_api_request') && kConf::get('disable_dump_api_request')) {
             KalturaLog::debug('dumpApiRequest is disabled');
             return;
         }
     }
     if (kCurrentContext::$multiRequest_index > 1) {
         KExternalErrors::dieError(KExternalErrors::MULTIREQUEST_PROXY_FAILED);
     }
     self::closeDbConnections();
     // prevent loop back of the proxied request by detecting the "X-Kaltura-Proxy header
     if (isset($_SERVER["HTTP_X_KALTURA_PROXY"])) {
         KExternalErrors::dieError(KExternalErrors::PROXY_LOOPBACK);
     }
     $get_params = $post_params = array();
     // pass uploaded files by adding them as post data with curl @ prefix
     // signifying a file. the $_FILES[xxx][tmp_name] points to the location
     // of the uploaded file.
     // we preserve the original file name by passing the extra ;filename=$_FILES[xxx][name]
     foreach ($_FILES as $key => $value) {
         $post_params[$key] = "@" . $value['tmp_name'] . ";filename=" . $value['name'];
         if (!is_uploaded_file($value['tmp_name'])) {
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
     }
     foreach ($_POST as $key => $value) {
         $post_params[$key] = $value;
     }
     $url = $_SERVER['REQUEST_URI'];
     if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' && kConf::hasParam('https_param_salt')) {
         $post_params['apiProtocol'] = 'https_' . kConf::get('https_param_salt');
     }
     $httpHeader = array("X-Kaltura-Proxy: dumpApiRequest");
     $ipHeader = infraRequestUtils::getSignedIpAddressHeader();
     if ($ipHeader) {
         list($headerName, $headerValue) = $ipHeader;
         $httpHeader[] = $headerName . ": " . $headerValue;
     }
     $ch = curl_init();
     // set URL and other appropriate options
     curl_setopt($ch, CURLOPT_URL, $host . $url);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
     curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.11.1");
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_POST, TRUE);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
     // Set callback function for body
     curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'kFileUtils::read_body');
     // Set callback function for headers
     curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'kFileUtils::read_header');
     header("X-Kaltura:dumpApiRequest " . kDataCenterMgr::getCurrentDcId());
     // grab URL and pass it to the browser
     $content = curl_exec($ch);
     // close curl resource, and free up system resources
     curl_close($ch);
     KExternalErrors::dieGracefully();
 }
Пример #30
-2
 public function saveFile($data)
 {
     $post = (object) $data;
     self::setMapping();
     // recupera variáveis
     $fileData = $_FILES["filedata"];
     $fileName = $fileData["name"];
     $fileType = $fileData["type"];
     $tempName = $fileData["tmp_name"];
     $dataType = self::$mapping[$fileType];
     if (!is_uploaded_file($tempName)) {
         self::$response->success = false;
         self::$response->text = "O arquivo não foi enviado com sucesso. Erro de sistema: {$fileData['error']}.";
         return json_encode(self::$response);
     }
     if (!array_key_exists($fileType, self::$mapping)) {
         return '{"success":false,"records":0,"error":2,"root":[],"text":"Tipo de arquivo não mapeado para esta operação!"}';
     }
     // comprime arquivo temporário
     if ($dataType === true) {
         self::sizeFile();
         self::workSize($tempName);
     }
     $tempData = base64_encode(file_get_contents($tempName));
     // recupera extensão do arquivo
     $fileExtension = strtoupper(strrchr($fileName, "."));
     $fileExtension = str_replace(".", "", $fileExtension);
     $fileInfo = array("fileType" => $fileType, "fileExtension" => $fileExtension, "dataType" => $dataType, "fileName" => $fileName);
     $fileInfo = stripslashes(json_encode($fileInfo));
     $affectedRows = $this->exec("update {$post->tableName} set filedata = '{$tempData}', fileinfo = '{$fileInfo}' where id = {$post->id}");
     unlink($tempName);
     return $affectedRows;
 }