src/Application/Internit/ContentBundle/Controller/CRUD.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\Application\Internit\ContentBundle\Controller;
  3. use App\Application\Internit\ContentBundle\Controller\FileUploader;
  4. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  5. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  9. use App\Application\Internit\RealEstateBundle\Entity\Realty;
  10. use App\Application\Internit\RealEstateBundle\Entity\RealEstate;
  11. use Sonata\AdminBundle\Controller\CRUDController;
  12. use App\Application\Internit\RealEstateBundle\Entity\File;
  13. use Doctrine\Common\Collections\ArrayCollection;
  14. use Symfony\Component\HttpFoundation\File\UploadedFile;
  15. use App\Application\Internit\RealEstateBundle\Entity\Media;
  16. class CRUD extends CRUDController
  17. {
  18.     public $bundle '';
  19.     private $allActionRoles    = array('ROLE_SUPER_ADMIN''ROLE_CONSTRUTORA''ROLE_IMOBILIARIA''ROLE_CORRETOR''ROLE_DIRETORIA''ROLE_CENTRAL_VENDAS');
  20.     private $adminActionRoles  = array('ROLE_SUPER_ADMIN');
  21.     private $createActionRoles = array('ROLE_SUPER_ADMIN');
  22.     private $editActionRoles   = array('ROLE_SUPER_ADMIN');
  23.     private $deleteActionRoles = array('ROLE_SUPER_ADMIN');
  24.     private $listActionRoles   = array('ROLE_SUPER_ADMIN');
  25.     private $showActionRoles   = array('ROLE_SUPER_ADMIN');
  26.     public function permissionByRole(array $rolesPermission$user)
  27.     {
  28.         /** Caso seja Super Administrador */
  29.         if( in_array('ROLE_SUPER_ADMIN'$user->getRoles()) )
  30.             return true;
  31.         foreach ($rolesPermission as $role)
  32.             if( in_array($role$user->getRoles()) )
  33.                 //dump($user);
  34.                 return true;
  35.         return false;
  36.     }
  37.     public function getUrlMedia($media$format)
  38.     {        
  39.         $mimes = new \Mimey\MimeTypes;
  40.         return "thumb_".$media->getId()."_".$media->getContext()."_".$format.".".pathinfo($media->getProviderReference(), PATHINFO_EXTENSION);
  41.     }
  42.     public function deleteAction($id)
  43.     {
  44. //        if(!$this->permissionByRole($this->deleteActionRoles, $this->getUser()))
  45. //            return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");
  46.         if (!$this->get('security.authorization_checker')->isGranted('ROLE_IMOBILIARIA')) 
  47.         {
  48.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  49.         }
  50.         $object $this->admin->getObject($id);
  51.         $this->admin->delete($object);
  52.         return $this->listAction();
  53.     }
  54.     public function createAction()
  55.     {
  56.         //return parent::createAction();             
  57.         $request $this->getRequest();
  58.         // the key used to lookup the template
  59.         $templateKey 'edit';
  60.         $this->admin->checkAccess('create');
  61.         
  62.         $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());
  63.         
  64.         $newObject $this->admin->getNewInstance();
  65.         $preResponse $this->preCreate($request$newObject);
  66.         if (null !== $preResponse) {
  67.             return $preResponse;
  68.         }
  69.         $this->admin->setSubject($newObject);
  70.         $form $this->admin->getForm();
  71.        
  72.         $form->setData($newObject);
  73.         $form->handleRequest($request);
  74.         
  75.         if ($form->isSubmitted()) {
  76.             
  77.             $isFormValid $form->isValid();            
  78.             
  79.             // persist if the form was valid and if in preview mode the preview was approved
  80.             if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  81.                 $this->persistImageApresentation($form);
  82.                 $submittedObject $form->getData();
  83.                 $this->admin->setSubject($submittedObject);
  84.                 $this->admin->checkAccess('create'$submittedObject);                
  85.                 try {
  86.                     
  87.                     $newObject $this->admin->create($submittedObject);
  88.                     if ($this->isXmlHttpRequest()) {
  89.                         return $this->renderJson([
  90.                             'result' => 'ok',
  91.                             'objectId' => $this->admin->getNormalizedIdentifier($newObject),
  92.                             'objectName' => $this->escapeHtml($this->admin->toString($newObject)),
  93.                         ], 200, []);
  94.                     }
  95.                     $this->get('session')->getFlashBag()->set('flash_create_success''Mensagem enviada com sucesso');
  96.                                         
  97.                     // redirect to edit mode
  98.                     return $this->redirectTo($newObject);
  99.                 } catch (ModelManagerException $e) {
  100.                     $this->handleModelManagerException($e);
  101.                     $isFormValid false;
  102.                 }
  103.             }
  104.             
  105.             // show an error message if the form failed validation
  106.             if (!$isFormValid) {
  107.                 if (!$this->isXmlHttpRequest()) 
  108.                 {        
  109.                     $errors = array();
  110.                     foreach ($form->getErrors(true) as $error) {
  111.                         $errors[] = $error->getMessage();
  112.                     } 
  113.                       
  114.                     $this->get('session')->getFlashBag()->set('flash_create_error'implode('<br>'$errors));
  115.                 }
  116.             } elseif ($this->isPreviewRequested()) {
  117.                 // pick the preview template if the form was valid and preview was requested
  118.                 $templateKey 'preview';
  119.                 $this->admin->getShow();
  120.             }
  121.         }
  122.         $formView $form->createView();
  123.     
  124.         return $this->renderWithExtraParams($this->base."create.html.twig", [
  125.             'form' => $formView
  126.         ], null);   
  127.     }
  128.     public function listAction($order = array('id' => 'DESC'))
  129.     {   
  130.         /*
  131.         if (!$this->get('security.authorization_checker')->isGranted('ROLE_IMOBILIARIA')) 
  132.         {
  133.             $realEstates = $this->get('security.token_storage')->getToken()->getUser()->getRealEstates();
  134.             $arrayRealEstates = array();
  135.             foreach($realEstates as $r)
  136.             {
  137.                 $arrayRealEstates[] = $r->getId();
  138.             }
  139.             
  140.             //var_dump("im.id = ".implode(' or im.id = ', $arrayRealEstates));exit;
  141.             $where = "im.id = ".implode(' or im.id = ', $arrayRealEstates); 
  142.             //ver todos os seus corretores
  143.         }*/
  144.         $where = array();
  145.         //var_dump($this->get('security.token_storage')->getToken()->getUser()->getRoles());
  146.         if (in_array('ROLE_CORRETOR'$this->get('security.token_storage')->getToken()->getUser()->getRoles()))
  147.             $where = array('user'=>$this->get('security.token_storage')->getToken()->getUser()->getid());
  148.       
  149.         $data $this->getDoctrine()->getRepository($this->bundle)->findBy($where$order); 
  150.         
  151.         return $this->renderWithExtraParams($this->base."list.html.twig", [
  152.             'action' => 'list',
  153.             'datas' => $data,
  154.             'order' => $order
  155.         ], null);       
  156.     }
  157.     public function showAction($id null)
  158.     {  
  159.         $request $this->getRequest();
  160.         $id $request->get($this->admin->getIdParameter());        
  161.         $data $this->getDoctrine()->getRepository($this->bundle)->find($id);
  162.         $template $this->base.'show.html.twig';
  163.         return $this->renderWithExtraParams($template, [
  164.             'action' => 'show',
  165.             'data' => $data
  166.             ,
  167.         ], null);
  168.     }
  169.     public function editAction($id null)
  170.     {
  171.         
  172.        //var_dump($_REQUEST);exit;
  173.        // $realty = new Realty();
  174.         $request $this->getRequest();        
  175.         $templateKey 'edit';
  176.         $id $request->get($this->admin->getIdParameter());       
  177.         $existingObject $this->admin->getObject($id);
  178.         
  179.         //var_dump($existingObject->getPlainPassword());exit;
  180.         
  181.         if (!$existingObject) {
  182.             throw $this->createNotFoundException(sprintf('unable to find the object with id: %s'$id));
  183.         }
  184.         
  185.         $form $this->admin->getForm();
  186.         //var_dump($form['rgDoc']); exit;
  187.         
  188.         $form->setData($existingObject);
  189.         //var_dump($request);exit;
  190.         $form->handleRequest($request);
  191.         //var_dump($form->getData()->getPassword());exit;
  192.         //var_dump($form['realestates']);exit;
  193.        
  194.         if ($form->isSubmitted()) {
  195.             
  196.             $isFormValid $form->isValid();
  197.             
  198.            
  199.             // persist if the form was valid and if in preview mode the preview was approved
  200.             //if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {                
  201.                 
  202.                 //dump($form);
  203.                 //exit;
  204.                 //##########UPLOAD##########   
  205.                
  206.                 if(isset($form['gallerysFiles']) || isset($form['files']) || isset($form['gallerys']) || isset($form['imageApresentation']))
  207.                 {     
  208.                     if ($form['gallerysFiles']) 
  209.                     {                        
  210.                         //$fileUploader = $this->get('admin.upload.file.service');   
  211.                         $type 'application/pdf, text/plain';
  212.                         $name 'files';                     
  213.                         $i 0;                    
  214.                         
  215.                         foreach($form['gallerysFiles'] as $bf)
  216.                         {  
  217.                             $files = new ArrayCollection();
  218.                             if($bf[$name])
  219.                             {      
  220.                                 $FILE = array();           
  221.                                 foreach($bf[$name]->getData() as $fil)
  222.                                 {      
  223.                                     
  224.                                     $FILE['name'] = $fil->getClientOriginalName();
  225.                                     $FILE['type'] = $fil->getClientMimeType();
  226.                                     $FILE['tmp_name'] = $fil->getPathName();
  227.                                     $FILE['error'] = $fil->getError();
  228.                                     $FILE['size'] = $fil->getSize();
  229.                                    //dump($name."_".$i);exit;
  230.                                     $file $this->multiupload($FILE$name."_".$i$type);
  231.                                     //$brochureFileName = $fileUploader->upload($fil, $this->upload_folder_file);                                                                                                       
  232.                                                                        
  233.                                     $med = new Media();
  234.                                     $med->setGalleryFile($bf->getData());
  235.                                     $med->setName($fil->getClientOriginalName());
  236.                                     $med->setDescription(null);
  237.                                     $med->setEnabled(1);
  238.                                     $med->setProviderName('sonata.media.provider.file');
  239.                                     $med->setProviderStatus(1);
  240.                                     $med->setProviderMetadata(["filename"=>$fil->getClientOriginalName()]);
  241.                                     $med->setWidth(300);
  242.                                     $med->setHeight(100);
  243.                                     $med->setLength(1544);
  244.                                     $med->setProviderReference($file[0]['name']);      
  245.                                     $med->setContentType($fil->getClientMimeType());      
  246.                                     $med->setContext('default'); 
  247.                                     $files[] = $med;      
  248.                                     unset($FILE);
  249.                                     
  250.                                 }                                                              
  251.                             }
  252.                             
  253.                             $bf->getData()->setMedias($files); 
  254.                             unset($files);
  255.                             $i++;
  256.                         }
  257.                                                 
  258.                     }
  259.                     if ($form['gallerys']) 
  260.                     {                        
  261.                         //$fileUploader = $this->get('admin.upload.file.service');  
  262.                         $type 'image/*';
  263.                         $name 'medias';                     
  264.                         $i 0;
  265.                         foreach($form['gallerys'] as $bf)
  266.                         {  
  267.                             $files = new ArrayCollection();
  268.                             if($bf[$name])
  269.                             {          
  270.                                 $FILE = array();    
  271.                                                      
  272.                                 foreach($bf[$name]->getData() as $fil)
  273.                                 {     
  274.                                     $FILE['name'] = $fil->getClientOriginalName();
  275.                                     $FILE['type'] = $fil->getClientMimeType();
  276.                                     $FILE['tmp_name'] = $fil->getPathName();
  277.                                     $FILE['error'] = $fil->getError();
  278.                                     $FILE['size'] = $fil->getSize();
  279.                                    
  280.                                    
  281.                                     $media $this->multiupload($FILE$name."_".$i$type);
  282.                                     
  283.                                     //dump($media);exit;
  284.                                     //dump($_POST);exit;
  285.                                     //$brochureFileName = $fileUploader->upload($fil, $this->upload_folder_image);                                                                                                       
  286.                                     //dump($brochureFileName);exit;
  287.                                     
  288.                                     $med = new Media();
  289.                                     $med->setGallery($bf->getData());
  290.                                     $med->setName($fil->getClientOriginalName());
  291.                                     $med->setDescription(null);
  292.                                     $med->setEnabled(1);
  293.                                     $med->setProviderName('sonata.media.provider.image');
  294.                                     $med->setProviderStatus(1);
  295.                                     $med->setProviderMetadata(["filename"=>$fil->getClientOriginalName()]);
  296.                                     $med->setWidth(300);
  297.                                     $med->setHeight(100);
  298.                                     $med->setLength(1544);
  299.                                     $med->setProviderReference($media[0]['name']);      
  300.                                     $med->setContentType($fil->getClientMimeType());      
  301.                                     $med->setContext('default'); 
  302.                                     $files[] = $med
  303.                                     unset($FILE);  
  304.                                     
  305.                                 }                                             
  306.                             }
  307.                             
  308.                             $bf->getData()->setMedias($files); 
  309.                             unset($files);
  310.                             $i++;
  311.                         }
  312.                                                 
  313.                     }
  314.                     $this->persistImageApresentation($form);
  315.                     //exit;
  316.                     /*if ($form['gallerys']) 
  317.                     {                        
  318.                         $fileUploader = $this->get('admin.upload.file.service');                       
  319.                         var_dump($form['gallerys']->getData()->first());
  320.                         foreach($form['gallerys'] as $bf)
  321.                         {  
  322.                             $files = new ArrayCollection();
  323.                             if($bf['medias'])
  324.                             {          
  325.                                                                    
  326.                                 foreach($bf['medias']->getData() as $fil)
  327.                                 {                                                                       
  328.                                     $brochureFileName = $fileUploader->upload($fil, $this->upload_folder_file);                                                                                                        
  329.                                                                         
  330.                                     $med = new Media();
  331.                                     $med->setName($fil->getClientOriginalName());
  332.                                     $med->setDescription(null);
  333.                                     $med->setEnabled(1);
  334.                                     $med->setProviderName('sonata.media.provider.image');
  335.                                     $med->setProviderStatus(1);
  336.                                     $med->setProviderMetadata(["filename"=>$fil->getClientOriginalName()]);
  337.                                     $med->setWidth(300);
  338.                                     $med->setHeight(100);
  339.                                     $med->setLength(1544);
  340.                                     $med->setProviderReference($brochureFileName);      
  341.                                     $med->setContentType($fil->getClientMimeType());      
  342.                                     $med->setContext('default'); 
  343.                                     $files[] = $med;  
  344.                                                                      
  345.                                     
  346.                                 }
  347.                                 
  348.                                 exit;
  349.                                $bf->getData()->setMedias($files);                                 
  350.                             }
  351.                         }
  352.                                                 
  353.                     }*/
  354.                     
  355.                     
  356.                     //exit; 
  357.                 }
  358.                
  359.                 //##########UPLOAD##########       
  360.                          
  361.                 $submittedObject $form->getData();
  362.                 
  363.                 $this->admin->setSubject($submittedObject);
  364.                 //
  365.                 //dump($submittedObject);exit;
  366.                 try {
  367.                     $existingObject $this->admin->update($submittedObject);
  368.                     //var_dump($existingObject->getPassword());exit;
  369.                    
  370.                     $this->get('session')->getFlashBag()->set('flash_create_success''Mensagem enviada com sucesso');
  371.                     // redirect to edit mode
  372.                     return $this->redirectTo($existingObject);exit;
  373.                 } catch (ModelManagerException $e) {
  374.                     $this->handleModelManagerException($e);
  375.                     $isFormValid false;
  376.                 } catch (LockException $e) {
  377.                     $this->get('session')->getFlashBag()->set('flash_create_error''Mensagem enviada com sucesso');
  378.                 }
  379.             //}
  380.             // show an error message if the form failed validation
  381.             if (!$isFormValid) {
  382.                 if (!$this->isXmlHttpRequest()) {
  383.                     $this->addFlash(
  384.                         'sonata_flash_error',
  385.                         $this->trans(
  386.                             'flash_edit_error',
  387.                             ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
  388.                             'SonataAdminBundle'
  389.                         )
  390.                     );
  391.                 }
  392.             } elseif ($this->isPreviewRequested()) {
  393.                 // enable the preview template if the form was valid and preview was requested
  394.                 $templateKey 'preview';
  395.                 $this->admin->getShow();
  396.             }
  397.         }
  398.         $formView $form->createView();
  399.         return $this->renderWithExtraParams($this->base."edit.html.twig", [
  400.             'action' => 'edit',
  401.             'form' => $formView
  402.         ], null);
  403.     }
  404.     public function persistImageApresentation($form$type 'image/*'$name 'imageApresentation')
  405.     {
  406.         if (isset($form[$name]) && !empty($form[$name])) 
  407.         {                                                
  408.             //$fileUploader = $this->get('admin.upload.file.service');  
  409.                   
  410.             $i 0;
  411.             /*foreach($form['imageApresentation'] as $bf)
  412.             { */ 
  413.                
  414.                 $bf $form[$name];
  415.                 $files = new ArrayCollection();
  416.                 if(!empty($bf->getData()))
  417.                 {
  418.                               
  419.                     $FILE = array();    
  420.                                          
  421.                     foreach($bf->getData() as $fil)
  422.                     {     
  423.                         $FILE['name'] = $fil->getClientOriginalName();
  424.                         $FILE['type'] = $fil->getClientMimeType();
  425.                         $FILE['tmp_name'] = $fil->getPathName();
  426.                         $FILE['error'] = $fil->getError();
  427.                         $FILE['size'] = $fil->getSize();
  428.                        
  429.                         $media $this->multiupload($FILE$name."_".$i$type);
  430.                         //dump($media);exit;
  431.                         //dump($_POST);exit;
  432.                         //$brochureFileName = $fileUploader->upload($fil, $this->upload_folder_image);                                                                                                       
  433.                         //dump($brochureFileName);exit;
  434.                         
  435.                         $med = new Media();
  436.                         $med->setImageApresentation($form->getData());
  437.                         $med->setName($fil->getClientOriginalName());
  438.                         $med->setDescription(null);
  439.                         $med->setEnabled(1);
  440.                         $med->setProviderName('sonata.media.provider.image');
  441.                         $med->setProviderStatus(1);
  442.                         $med->setProviderMetadata(["filename"=>$fil->getClientOriginalName()]);
  443.                         $med->setWidth(300);
  444.                         $med->setHeight(100);
  445.                         $med->setLength(1544);
  446.                         $med->setProviderReference($media[0]['name']);      
  447.                         $med->setContentType($fil->getClientMimeType());      
  448.                         $med->setContext('default'); 
  449.                         $files[] = $med
  450.                         unset($FILE);  
  451.                         
  452.                     }    
  453.                     $form->getData()->setImageApresentations($files); 
  454.                     unset($files);
  455.                     $i++;                                                          
  456.                 }
  457.             //}
  458.                                     
  459.         }
  460.     }
  461.     public function upload($brochureFile)
  462.     {
  463.         $originalFilename pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
  464.         // this is needed to safely include the file name as part of the URL
  465.         $safeFilename transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalFilename);
  466.         $newFilename $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
  467.         
  468.         // Move the file to the directory where brochures are stored
  469.         try {            
  470.             $brochureFile->move(
  471.                 $this->getParameter('realty_directory'),
  472.                 $newFilename
  473.             );
  474.         } catch (FileException $e) {
  475.             // ... handle exception if something happens during file upload
  476.         }        
  477.         return $newFilename;
  478.     }
  479.     public function multiupload($FILE$name$type)
  480.     {
  481.     
  482.         $n explode('_',$name);
  483.        
  484.         $folder $n[0];
  485.         //dump($folder);exit;
  486.         // define uploads path
  487.         $uploadDir 'upload/realty/'.$folder.'/';
  488.         $thumbsDir $uploadDir 'thumbs/';
  489.        
  490.         //dump($name);
  491.         
  492.         // initialize FileUploader
  493.         $FileUploader = new FileUploader($name, array(
  494.             'limit' => null,
  495.             'maxSize' => null,
  496.             'extensions' => [$type],
  497.             'uploadDir' => $uploadDir,
  498.             'title' => 'name',
  499.             '$_FILE' => $FILE,
  500.             'editor' => array(
  501.                 'maxWidth' => 1280,
  502.                 'maxHeight' => 720,
  503.                 'crop' => false,
  504.                 'quality' => 90
  505.             )
  506.         ));
  507.         //dump($FileUploader);exit;
  508.         
  509.        
  510.         // unlink the files
  511.         // !important only for preloaded files
  512.         // you will need to give the array with appendend files in 'files' option of the FileUploader
  513.         foreach($FileUploader->getRemovedFiles('file') as $key=>$value) {
  514.             
  515.             $file $uploadDir $value['name']; 
  516.             $thumb $thumbsDir $value['name'];
  517.             
  518.             if (is_file($file))
  519.                 unlink($file);
  520.             if (is_file($thumb))
  521.                 unlink($thumb);
  522.         }
  523.         
  524.         // call to upload the files
  525.         $data $FileUploader->upload();
  526.         
  527.         
  528.         
  529.         
  530.         // echo '<pre>';
  531.         // print_r($FileUploader);
  532.         // echo '</pre>';
  533.         // exit;
  534.         //dump($data);exit;
  535.         
  536.         
  537.         // if uploaded and success
  538.         if($data['isSuccess'] && count($data['files']) > 0) {
  539.             // get uploaded files
  540.             $uploadedFiles $data['files'];
  541.             
  542.             // create thumbnails
  543.             if (!is_dir($thumbsDir))
  544.                 mkdir($thumbsDir);
  545.             foreach($uploadedFiles as $item) {
  546.                 FileUploader::resize($filename $item['file'], $width 100$height 100$destination $thumbsDir $item['name'], $crop false$quality 100);
  547.             }
  548.         }
  549.         
  550.         // if warnings
  551.         if($data['hasWarnings']) {
  552.             // get warnings
  553.             $warnings $data['warnings'];
  554.             
  555.             echo '<pre>';
  556.             print_r($warnings);
  557.             echo '</pre>';
  558.             exit;
  559.         }
  560.         
  561.         
  562.         // get the fileList
  563.         $fileList $FileUploader->getFileList();
  564.         
  565.         // // show
  566.         // echo '<pre>';
  567.         // print_r($fileList);
  568.         // echo '</pre>';
  569.         // exit;
  570.         return $fileList;
  571.     }
  572. }