<?php
namespace com\whitemagicsoftware;
require "constants.php";
class SecureImageUpload extends Obj {
private $extensions = array(
"image/bmp" => "bmp",
"image/gif" => "gif",
"image/jpeg" => "jpg",
"image/png" => "png",
"image/tif" => "tif",
"image/svg+xml" => "svg",
"application/pdf" => "pdf",
"applciation/postscript" => "eps",
"image/eps" => "eps"
);
private $url = "";
private $filename = "";
public function handle( $formElement, $id, $appId = "" ) {
global $FILE_MAX_UPLOAD_TIME;
$result = false;
set_time_limit( $FILE_MAX_UPLOAD_TIME );
$file = $_FILES[ $formElement ];
if( !empty( $file ) ) {
$error = $file[ "error" ];
if( $error === UPLOAD_ERR_OK ) {
$result = $this->relocate( $file, $id, $appId );
}
else if( $error === UPLOAD_ERR_INI_SIZE ) {
$this->log( "Upload exceeds maximum: $id/$appId" );
}
}
return $result;
}
private function relocate( $file, $id, $appId ) {
global $IMAGE_DIRECTORY_ROOT;
global $SERVICE_IMAGE;
$result = false;
$directory = "$id/$appId/";
$localPath = "$IMAGE_DIRECTORY_ROOT$directory";
$this->createDirectory( "$localPath" );
$tempFilename = $file[ "tmp_name" ];
$ext = $this->getExtension( $tempFilename );
$hashFilename = md5( uniqid( $file[ "name" ] ) ) . ".$ext";
$localFilename = "$localPath$hashFilename";
if( move_uploaded_file( $tempFilename, $localFilename ) ) {
if( ($result = chmod( $localFilename, 0644 )) === true ) {
$this->setFilename( $localFilename );
$this->setURL( "$SERVICE_IMAGE$directory$hashFilename" );
}
}
else {
$this->log( "Create failed: $localFilename" );
}
return $result;
}
private function getExtension( $filename ) {
$mimeType = $this->getMimeType( $filename );
return empty( $this->extensions[ $mimeType ] ) ?
"" : $this->extensions[ $mimeType ];
}
private function getMimeType( $filename ) {
$path = realpath( $filename );
return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $path );
}
private function setURL( $u ) {
if( !empty( $u ) ) {
$this->url = $u;
}
}
private function setFilename( $f ) {
if( !empty( $f ) ) {
$this->filename = $f;
}
}
public function getURL() {
return $this->url;
}
public function getFilename() {
return $this->filename;
}
}