Skip to content

Instantly share code, notes, and snippets.

@kolyadin
Created July 28, 2014 17:39
Show Gist options
  • Save kolyadin/3f178d2dda767f8c6aee to your computer and use it in GitHub Desktop.
Save kolyadin/3f178d2dda767f8c6aee to your computer and use it in GitHub Desktop.
<?php
namespace Sp\UploadBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class DefaultController extends Controller
{
/**
* @param $file
* @throws \Exception
*/
private function checkMimeType($file){
$mime = mime_content_type($file);
if (!in_array($mime,array('image/jpeg','image/gif','image/png','image/pjpeg'))){
throw new \Exception('unauthorized file mime type');
}
}
/**
* @Template()
*/
public function byTypeAndIdFormAction()
{
return array();
}
public function byTypeAndIdAction()
{
$us = null;
$req = $this->getRequest();
$res = new JsonResponse();
if (!$req->isMethod('post')) return $res->setData(array('error' => 'not a post'));
$id = intval($req->get('id'));
if ($id < 1) return $res->setData(array('error' => 'id has to be positive'));
$type = trim($req->get('type'));
if (!$type) return $res->setData(array('error' => 'type is empty'));
$origName = trim($req->get('qqfile'));
if (!$origName) $origName = 'image.jpg';
try {
$us = $this->get('upload');
} catch (\Exception $e) {
return $res->setData(array('error' => $e->getMessage()));
}
try {
$us->getPath($type, $id);
} catch (\Exception $e) {
return $res->setData(array('error' => 'there is no such object type'));
}
$core = date('YmdHis').'_'.$type.'_'.md5(rand(1, 9999).time());
$cleanup = array();
try {
$lock = 'lock_'.$core;
if (!$us->lockInTmp($lock)) throw new \Exception('tmp lock failed');
$cleanup[] = $us->getWebTmpDir().'/'.$lock;
$src = $us->getWebTmpDir().'/src_'.$core.'.'.strtolower(pathinfo($origName, PATHINFO_EXTENSION));
if (isset($_FILES['qqfile'])) {
@move_uploaded_file($_FILES['qqfile']['tmp_name'], $src);
} else {
$raw = @file_get_contents('php://input');
@file_put_contents($src, $raw, LOCK_EX);
}
$this->checkMimeType($src);
$cleanup[] = $src;
@chmod($src, 0777);
if (!@filesize($src)) throw new \Exception('tmp upload failed');
if (!@is_readable($src)) throw new \Exception('tmp upload is unreadable');
$uf = new UploadedFile($src, $origName);
$mimes = $us->getMimeTypes();
$mime = $uf->getMimeType();
// if (!isset($mimes[$mime])) throw new \Exception('unknown mime type');
// if ($mimes[$mime]['type'] != 'image') throw new \Exception('file is not an image');
$us->moveFromSrcByTypeAndId($src, $type, $id);
foreach ($cleanup as $cl) @unlink($cl);
return $res->setData(array('success' => true, 'urls' => $us->getUrl($type, $id)));
} catch (\Exception $e) {
foreach ($cleanup as $cl) @unlink($cl);
return $res->setData(array('error' => $e->getMessage()));
}
return $res->setData(array('success' => false));
}
/**
* @Template()
*/
public function byTypeToTmpFormAction()
{
return array();
}
public function byTypeToTmpAction()
{
$us = null;
$req = $this->getRequest();
$res = new Response();
if (!$req->isMethod('post')) {
$res->setContent(json_encode(array('error' => 'not a post')));
return $res;
}
$type = trim($req->get('type'));
if (!$type) {
$res->setContent(json_encode(array('error' => 'type is empty')));
return $res;
}
$origName = trim($req->get('qqfile'));
if (!$origName) $origName = 'image.jpg';
try {
$us = $this->get('upload');
} catch (\Exception $e) {
$res->setContent(json_encode(array('error' => $e->getMessage())));
return $res;
}
$paths = null;
try {
$paths = $us->getPath($type, 1, false, '', null, true);
if (!is_array($paths)) throw new \Exception('invalid type');
if (!count($paths)) throw new \Exception('empty type config');
} catch (\Exception $e) {
$res->setContent(json_encode(array('error' => 'there is no such object type')));
return $res;
}
$core = date('YmdHis').'_'.$type.'_'.md5(rand(1, 9999).time());
$cleanup = array();
$tmpUrls = array();
try {
$lock = 'lock_'.$core;
if (!$us->lockInTmp($lock)) throw new \Exception('tmp lock failed');
$cleanup[] = $us->getWebTmpDir().'/'.$lock;
$src = $us->getWebTmpDir().'/src_'.$core.'.'.strtolower(pathinfo($origName, PATHINFO_EXTENSION));
if (isset($_FILES['qqfile'])) {
@move_uploaded_file($_FILES['qqfile']['tmp_name'], $src);
} else {
$raw = @file_get_contents('php://input');
@file_put_contents($src, $raw, LOCK_EX);
}
$this->checkMimeType($src);
$cleanup[] = $src;
@chmod($src, 0777);
if (!@filesize($src)) throw new \Exception('tmp upload failed');
if (!@is_readable($src)) throw new \Exception('tmp upload is unreadable');
$uf = new UploadedFile($src, $origName);
$mimes = $us->getMimeTypes();
$mime = $uf->getMimeType();
// if (!isset($mimes[$mime])) throw new \Exception('unknown mime type');
// if ($mimes[$mime]['type'] != 'image') throw new \Exception('file is not an image');
$ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
foreach ($paths as $size => $path) {
$sizeName = 'img_'.$core.'_'.$size.'.'.strtolower(pathinfo($origName, PATHINFO_EXTENSION));
$paths[$size]['path'] = $us->getWebTmpDir().'/'.$sizeName;
$paths[$size]['url'] = $us->getWebTmpUrl().'/'.$sizeName;
}
foreach ($paths as $size => $path) {
$us->copy($src, $path['path']);
$cleanup[] = $path['path'];
$tmpUrls[$size] = $path['url'];
}
if (@$mimes[$mime]['type'] == 'image') {
foreach ($paths as $size => $path) {
if ($size === 'orig') continue;
if (@$path['cfg']['crop'] === true) {
$us->crop($path['path'], $path['path'], @$path['cfg']['width'], @$path['cfg']['height']);
} else {
$us->rezise($path['path'], $path['path'], @$path['cfg']['width'], @$path['cfg']['height']);
}
}
}
@unlink($src);
$res->setContent(json_encode(array(
'success' => true,
'token' => $core,
'urls' => $tmpUrls,
'ext' => $ext,
'title' => 'file'
)));
return $res;
} catch (\Exception $e) {
foreach ($cleanup as $cl) @unlink($cl);
$res->setContent(json_encode(array('error' => $e->getMessage())));
return $res;
}
$res->setContent(json_encode(array('success' => false)));
return $res;
}
public function oneToTmpAction()
{
$req = $this->getRequest();
$res = new JsonResponse();
if (!$req->isMethod('post')) return $res->setData(array('error' => 'not a post'));
$cleanup = null;
try {
$um = $this->get('upload');
$name = $um->generateTmpName();
$path = $um->getWebTmpDir().'/'.$name;
$raw = @file_get_contents('php://input');
@file_put_contents($path, $raw, LOCK_EX);
$cleanup = $path;
$this->checkMimeType($path);
@chmod($path, 0777);
if (!@is_readable($path)) throw new \Exception('Ошибка загрузки файла');
if (!@filesize($path)) throw new \Exception('Ошибка загрузки файла.');
$uf = new UploadedFile($path, $name);
$mimes = $um->getMimeTypes();
$mime = $uf->getMimeType();
if (!isset($mimes[$mime])) throw new \Exception('Неизвестный тип файла');
if ($mimes[$mime]['type'] != 'image') throw new \Exception('Файл не является картинкой');
return $res->setData(array('success' => true, 'name' => $name));
} catch (\Exception $e) {
if ($cleanup) @unlink($cleanup);
return $res->setData(array('error' => $e->getMessage()));
}
return $res->setData(array('success' => false));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment