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