<?php
namespace App\Application\Internit\ContentBundle\Controller;
use App\Application\Internit\ContentBundle\Controller\FileUploader;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Application\Internit\RealEstateBundle\Entity\Realty;
use App\Application\Internit\RealEstateBundle\Entity\RealEstate;
use Sonata\AdminBundle\Controller\CRUDController;
use App\Application\Internit\RealEstateBundle\Entity\File;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Application\Internit\RealEstateBundle\Entity\Media;
class CRUD extends CRUDController
{
public $bundle = '';
protected $allActionRoles = array('ROLE_MASTER_ADMIN', 'ROLE_CONSTRUTORA', 'ROLE_IMOBILIARIA', 'ROLE_CORRETOR', 'ROLE_AGENCIA');
protected $adminActionRoles = array('ROLE_MASTER_ADMIN');
protected $createActionRoles = array('ROLE_MASTER_ADMIN');
protected $editActionRoles = array('ROLE_MASTER_ADMIN');
protected $deleteActionRoles = array('ROLE_MASTER_ADMIN');
protected $listActionRoles = array('ROLE_MASTER_ADMIN');
protected $showActionRoles = array('ROLE_MASTER_ADMIN');
public function validateAccess(){
}
public function getUrlMedia($media, $format)
{
$mimes = new \Mimey\MimeTypes;
return "thumb_".$media->getId()."_".$media->getContext()."_".$format.".".pathinfo($media->getProviderReference(), PATHINFO_EXTENSION);
}
public function deleteAction($id)
{
if(!$this->permissionByRole($this->deleteActionRoles, $this->getUser()))
return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");
$object = $this->admin->getObject($id);
//dump($object);
$this->admin->delete($object);
return $this->listAction();
}
public function createAction()
{
if(!$this->permissionByRole($this->createActionRoles, $this->getUser()))
return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");
//return parent::createAction();
$request = $this->getRequest();
// the key used to lookup the template
$templateKey = 'edit';
$this->admin->checkAccess('create');
$class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());
$newObject = $this->admin->getNewInstance();
$preResponse = $this->preCreate($request, $newObject);
if (null !== $preResponse) {
return $preResponse;
}
$this->admin->setSubject($newObject);
$form = $this->admin->getForm();
$form->setData($newObject);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$isFormValid = $form->isValid();
// persist if the form was valid and if in preview mode the preview was approved
if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
$this->persistImageApresentation($form);
$submittedObject = $form->getData();
$this->admin->setSubject($submittedObject);
$this->admin->checkAccess('create', $submittedObject);
try {
$newObject = $this->admin->create($submittedObject);
if ($this->isXmlHttpRequest()) {
return $this->renderJson([
'result' => 'ok',
'objectId' => $this->admin->getNormalizedIdentifier($newObject),
'objectName' => $this->escapeHtml($this->admin->toString($newObject)),
], 200, []);
}
$this->get('session')->getFlashBag()->set('flash_create_success', 'Mensagem enviada com sucesso');
// redirect to edit mode
return $this->redirectTo($newObject);
} catch (ModelManagerException $e) {
$this->handleModelManagerException($e);
$isFormValid = false;
}
}
// show an error message if the form failed validation
if (!$isFormValid) {
if (!$this->isXmlHttpRequest())
{
$errors = array();
foreach ($form->getErrors(true) as $error) {
$errors[] = $error->getMessage();
}
$this->get('session')->getFlashBag()->set('flash_create_error', implode('<br>', $errors));
}
} elseif ($this->isPreviewRequested()) {
// pick the preview template if the form was valid and preview was requested
$templateKey = 'preview';
$this->admin->getShow();
}
}
$formView = $form->createView();
return $this->renderWithExtraParams($this->base."create.html.twig", [
'form' => $formView
], null);
}
public function listAction($order = array('id' => 'DESC'))
{
if(!$this->permissionByRole($this->listActionRoles, $this->getUser()))
return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");
/*
if (!$this->get('security.authorization_checker')->isGranted('ROLE_IMOBILIARIA'))
{
$realEstates = $this->get('security.token_storage')->getToken()->getUser()->getRealEstates();
$arrayRealEstates = array();
foreach($realEstates as $r)
{
$arrayRealEstates[] = $r->getId();
}
//var_dump("im.id = ".implode(' or im.id = ', $arrayRealEstates));exit;
$where = "im.id = ".implode(' or im.id = ', $arrayRealEstates);
//ver todos os seus corretores
}*/
$where = array();
//var_dump($this->get('security.token_storage')->getToken()->getUser()->getRoles());
//Edit
/*if (in_array('ROLE_CORRETOR', $this->get('security.token_storage')->getToken()->getUser()->getRoles()))
$where = array('user'=>$this->get('security.token_storage')->getToken()->getUser()->getid());*/
$data = $this->getDoctrine()->getRepository($this->bundle)->findBy($where, $order);
return $this->renderWithExtraParams($this->base."list.html.twig", [
'action' => 'list',
'datas' => $data,
'order' => $order
], null);
}
public function showAction($id = null)
{
if(!$this->permissionByRole($this->showActionRoles, $this->getUser()))
return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");
$request = $this->getRequest();
$id = $request->get($this->admin->getIdParameter());
$data = $this->getDoctrine()->getRepository($this->bundle)->find($id);
$template = $this->base.'show.html.twig';
return $this->renderWithExtraParams($template, [
'action' => 'show',
'data' => $data
,
], null);
}
public function editAction($id = null)
{
if(!$this->permissionByRole($this->editActionRoles, $this->getUser()))
return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");
//var_dump($_REQUEST);exit;
// $realty = new Realty();
$request = $this->getRequest();
$templateKey = 'edit';
$id = $request->get($this->admin->getIdParameter());
$existingObject = $this->admin->getObject($id);
//var_dump($existingObject->getPlainPassword());exit;
if (!$existingObject) {
throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
}
$form = $this->admin->getForm();
//var_dump($form['rgDoc']); exit;
$form->setData($existingObject);
//var_dump($request);exit;
$form->handleRequest($request);
//var_dump($form->getData()->getPassword());exit;
//var_dump($form['realestates']);exit;
if ($form->isSubmitted()) {
$isFormValid = $form->isValid();
// persist if the form was valid and if in preview mode the preview was approved
//if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
//dump($form);
//exit;
//##########UPLOAD##########
if(isset($form['gallerysFiles']) || isset($form['files']) || isset($form['gallerys']) || isset($form['imageApresentation']))
{
if ($form['gallerysFiles'])
{
//$fileUploader = $this->get('admin.upload.file.service');
$type = 'application/pdf, text/plain';
$name = 'files';
$i = 0;
foreach($form['gallerysFiles'] as $bf)
{
$files = new ArrayCollection();
if($bf[$name])
{
$FILE = array();
foreach($bf[$name]->getData() as $fil)
{
$FILE['name'] = $fil->getClientOriginalName();
$FILE['type'] = $fil->getClientMimeType();
$FILE['tmp_name'] = $fil->getPathName();
$FILE['error'] = $fil->getError();
$FILE['size'] = $fil->getSize();
//dump($name."_".$i);exit;
$file = $this->multiupload($FILE, $name."_".$i, $type);
//$brochureFileName = $fileUploader->upload($fil, $this->upload_folder_file);
$med = new Media();
$med->setGalleryFile($bf->getData());
$med->setName($fil->getClientOriginalName());
$med->setDescription(null);
$med->setEnabled(1);
$med->setProviderName('sonata.media.provider.file');
$med->setProviderStatus(1);
$med->setProviderMetadata(["filename"=>$fil->getClientOriginalName()]);
$med->setWidth(300);
$med->setHeight(100);
$med->setLength(1544);
$med->setProviderReference($file[0]['name']);
$med->setContentType($fil->getClientMimeType());
$med->setContext('default');
$files[] = $med;
unset($FILE);
}
}
$bf->getData()->setMedias($files);
unset($files);
$i++;
}
}
if ($form['gallerys'])
{
//$fileUploader = $this->get('admin.upload.file.service');
$type = 'image/*';
$name = 'medias';
$i = 0;
foreach($form['gallerys'] as $bf)
{
$files = new ArrayCollection();
if($bf[$name])
{
$FILE = array();
foreach($bf[$name]->getData() as $fil)
{
$FILE['name'] = $fil->getClientOriginalName();
$FILE['type'] = $fil->getClientMimeType();
$FILE['tmp_name'] = $fil->getPathName();
$FILE['error'] = $fil->getError();
$FILE['size'] = $fil->getSize();
$media = $this->multiupload($FILE, $name."_".$i, $type);
//dump($media);exit;
//dump($_POST);exit;
//$brochureFileName = $fileUploader->upload($fil, $this->upload_folder_image);
//dump($brochureFileName);exit;
$med = new Media();
$med->setGallery($bf->getData());
$med->setName($fil->getClientOriginalName());
$med->setDescription(null);
$med->setEnabled(1);
$med->setProviderName('sonata.media.provider.image');
$med->setProviderStatus(1);
$med->setProviderMetadata(["filename"=>$fil->getClientOriginalName()]);
$med->setWidth(300);
$med->setHeight(100);
$med->setLength(1544);
$med->setProviderReference($media[0]['name']);
$med->setContentType($fil->getClientMimeType());
$med->setContext('default');
$files[] = $med;
unset($FILE);
}
}
$bf->getData()->setMedias($files);
unset($files);
$i++;
}
}
$this->persistImageApresentation($form);
//exit;
/*if ($form['gallerys'])
{
$fileUploader = $this->get('admin.upload.file.service');
var_dump($form['gallerys']->getData()->first());
foreach($form['gallerys'] as $bf)
{
$files = new ArrayCollection();
if($bf['medias'])
{
foreach($bf['medias']->getData() as $fil)
{
$brochureFileName = $fileUploader->upload($fil, $this->upload_folder_file);
$med = new Media();
$med->setName($fil->getClientOriginalName());
$med->setDescription(null);
$med->setEnabled(1);
$med->setProviderName('sonata.media.provider.image');
$med->setProviderStatus(1);
$med->setProviderMetadata(["filename"=>$fil->getClientOriginalName()]);
$med->setWidth(300);
$med->setHeight(100);
$med->setLength(1544);
$med->setProviderReference($brochureFileName);
$med->setContentType($fil->getClientMimeType());
$med->setContext('default');
$files[] = $med;
}
exit;
$bf->getData()->setMedias($files);
}
}
}*/
//exit;
}
//##########UPLOAD##########
$submittedObject = $form->getData();
$this->admin->setSubject($submittedObject);
//
//dump($submittedObject);exit;
try {
$existingObject = $this->admin->update($submittedObject);
//var_dump($existingObject->getPassword());exit;
$this->get('session')->getFlashBag()->set('flash_create_success', 'Mensagem enviada com sucesso');
// redirect to edit mode
return $this->redirectTo($existingObject);exit;
} catch (ModelManagerException $e) {
$this->handleModelManagerException($e);
$isFormValid = false;
} catch (LockException $e) {
$this->get('session')->getFlashBag()->set('flash_create_error', 'Mensagem enviada com sucesso');
}
//}
// show an error message if the form failed validation
if (!$isFormValid) {
if (!$this->isXmlHttpRequest()) {
$this->addFlash(
'sonata_flash_error',
$this->trans(
'flash_edit_error',
['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
'SonataAdminBundle'
)
);
}
} elseif ($this->isPreviewRequested()) {
// enable the preview template if the form was valid and preview was requested
$templateKey = 'preview';
$this->admin->getShow();
}
}
$formView = $form->createView();
return $this->renderWithExtraParams($this->base."edit.html.twig", [
'action' => 'edit',
'form' => $formView
], null);
}
public function persistImageApresentation($form, $type = 'image/*', $name = 'imageApresentation')
{
if (isset($form[$name]) && !empty($form[$name]))
{
//$fileUploader = $this->get('admin.upload.file.service');
$i = 0;
/*foreach($form['imageApresentation'] as $bf)
{ */
$bf = $form[$name];
$files = new ArrayCollection();
if(!empty($bf->getData()))
{
$FILE = array();
foreach($bf->getData() as $fil)
{
$FILE['name'] = $fil->getClientOriginalName();
$FILE['type'] = $fil->getClientMimeType();
$FILE['tmp_name'] = $fil->getPathName();
$FILE['error'] = $fil->getError();
$FILE['size'] = $fil->getSize();
$media = $this->multiupload($FILE, $name."_".$i, $type);
//dump($media);exit;
//dump($_POST);exit;
//$brochureFileName = $fileUploader->upload($fil, $this->upload_folder_image);
//dump($brochureFileName);exit;
$med = new Media();
$med->setImageApresentation($form->getData());
$med->setName($fil->getClientOriginalName());
$med->setDescription(null);
$med->setEnabled(1);
$med->setProviderName('sonata.media.provider.image');
$med->setProviderStatus(1);
$med->setProviderMetadata(["filename"=>$fil->getClientOriginalName()]);
$med->setWidth(300);
$med->setHeight(100);
$med->setLength(1544);
$med->setProviderReference($media[0]['name']);
$med->setContentType($fil->getClientMimeType());
$med->setContext('default');
$files[] = $med;
unset($FILE);
}
$form->getData()->setImageApresentations($files);
unset($files);
$i++;
}
//}
}
}
public function upload($brochureFile)
{
$originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
$brochureFile->move(
$this->getParameter('realty_directory'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
return $newFilename;
}
public function multiupload($FILE, $name, $type)
{
$n = explode('_',$name);
$folder = $n[0];
//dump($folder);exit;
// define uploads path
$uploadDir = 'upload/realty/'.$folder.'/';
$thumbsDir = $uploadDir . 'thumbs/';
//dump($name);
// initialize FileUploader
$FileUploader = new FileUploader($name, array(
'limit' => null,
'maxSize' => null,
'extensions' => [$type],
'uploadDir' => $uploadDir,
'title' => 'name',
'$_FILE' => $FILE,
'editor' => array(
'maxWidth' => 1280,
'maxHeight' => 720,
'crop' => false,
'quality' => 90
)
));
//dump($FileUploader);exit;
// unlink the files
// !important only for preloaded files
// you will need to give the array with appendend files in 'files' option of the FileUploader
foreach($FileUploader->getRemovedFiles('file') as $key=>$value) {
$file = $uploadDir . $value['name'];
$thumb = $thumbsDir . $value['name'];
if (is_file($file))
unlink($file);
if (is_file($thumb))
unlink($thumb);
}
// call to upload the files
$data = $FileUploader->upload();
// echo '<pre>';
// print_r($FileUploader);
// echo '</pre>';
// exit;
//dump($data);exit;
// if uploaded and success
if($data['isSuccess'] && count($data['files']) > 0) {
// get uploaded files
$uploadedFiles = $data['files'];
// create thumbnails
if (!is_dir($thumbsDir))
mkdir($thumbsDir);
foreach($uploadedFiles as $item) {
FileUploader::resize($filename = $item['file'], $width = 100, $height = 100, $destination = $thumbsDir . $item['name'], $crop = false, $quality = 100);
}
}
// if warnings
if($data['hasWarnings']) {
// get warnings
$warnings = $data['warnings'];
echo '<pre>';
print_r($warnings);
echo '</pre>';
exit;
}
// get the fileList
$fileList = $FileUploader->getFileList();
// // show
// echo '<pre>';
// print_r($fileList);
// echo '</pre>';
// exit;
return $fileList;
}
public function getRouterName(){
$router = $this->get("router");
$router = $router->match($this->getRequest()->getPathInfo());
return $router['_route'];
}
public function routesNeedPermission(){
return [
'admin_internit_realestate_realty_listMirror',
];
}
public function userPermissionByModule($user){
dump($user);
dump($this->getUserModulos($user));
/** Super Admiministrador ? */
if( $this->isMasterAdmin($user->getRoles()) )
return true;
/** Validação por Rota */
$validateByRoute = in_array( $this->getRouterName(), $this->routesNeedPermission() );
if( $validateByRoute && in_array( $this->getRouterName(), $this->getUserModulos($user) ) )
return true;
/** Validação por Pacote/Bundle */
if( $this->getUserModulos($user) && in_array($this->bundle, $this->getUserModulos($user)) )
return true;
return false;
}
public function getUserModulos($user){
switch ($user->getRoles()[0]) {
case 'ROLE_CONSTRUTORA':
return $user->getBuilder()->getModulos();
break;
case 'ROLE_IMOBILIARIA':
return $user->getRealEstates()[0]->getModulosImobiliaria();
break;
case 'ROLE_CORRETOR':
return $user->getRealEstates()[0]->getModulosCorretor();
break;
case 'ROLE_AGENCIA':
return $user->getAgency()->getModulos();
break;
}
return [];
}
public function permissionByRole(array $modulesName, $user)
{
if( $this->isMasterAdmin($user->getRoles()) )
return true;
if( !$this->userPermissionByModule($user) )
return false;
foreach ($modulesName as $module)
if( in_array($module, $user->getRoles()) )
//dump($user);
return true;
return false;
}
public function isMasterAdmin($userRoles){
$masterAdmin = [
"ROLE_SUPER_ADMIN",
"ROLE_CORRETOR",
"ROLE_IMOBILIARIA",
"ROLE_CONSTRUTORA",
"ROLE_AGENCIA",
"ROLE_USER"
];
$isMaster = 0;
foreach ($masterAdmin as $module)
if( in_array($module, $userRoles) )
$isMaster ++;
if($isMaster == 6)
return true;
return false;
}
}