src/PromemoriaBundle/Controller/ApiController.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\PromemoriaBundle\Controller;
  3. use Pimcore\Db;
  4. use Pimcore\File;
  5. use Pimcore\Tool;
  6. use Pimcore\Model\User;
  7. use Pimcore\Security\User\User as UserAdmin;
  8. use Pimcore\Model\Asset;
  9. use Pimcore\Tool\Session;
  10. use Pimcore\Event\AdminEvents;
  11. use Pimcore\Tool\Authentication;
  12. use Pimcore\Controller\FrontendController;
  13. use Pimcore\Bundle\AdminBundle\Controller\Admin;
  14. use Pimcore\Controller\Configuration\ResponseHeader;
  15. use Pimcore\Event\Admin\Login\LoginCredentialsEvent;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\HttpFoundation\JsonResponse;
  20. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  21. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  22. use Symfony\Component\HttpFoundation\StreamedResponse;
  23. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  24. use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface;
  25. class ApiController extends FrontendController
  26. {
  27.        /**
  28.      * @Route("/promemoria/api/login", methods={"POST"})
  29.      * @param Request $request
  30.      *
  31.      * @return JsonResponse
  32.      */
  33.     public function login(Request $request)
  34.     {
  35.         $response = new Response();
  36.         $response->setStatusCode(401);
  37.         $data json_decode($request->getContent());
  38.         if (!empty($data->username) &&  !empty($data->password)) {
  39.             $credentials = [
  40.                 'username' => $data->username,
  41.                 'password' => $data->password
  42.             ];
  43.             $event = new LoginCredentialsEvent($request$credentials);
  44.             try {
  45.                 $this->dispatcher->dispatch(AdminEvents::LOGIN_CREDENTIALS$event);
  46.             } catch (\Throwable $th) {
  47.             }
  48.             $pimcoreUser Authentication::authenticatePlaintext($data->username$data->password);
  49.             if ($pimcoreUser) {
  50.                 return Session::useSession(function (AttributeBagInterface $adminSession) use ($pimcoreUser) {
  51.                     $user = new UserAdmin($pimcoreUser);
  52.                     Session::regenerateId();
  53.                     $adminSession->set('user'$pimcoreUser);
  54.                     $adminSession->set('2fa_required'true);
  55.                     return $this->json(['ok' => true'user' => array(
  56.                         'id' => $pimcoreUser->getId(),
  57.                         'firstname' => $pimcoreUser->getFirstname(),
  58.                         'lastname' => $pimcoreUser->getLastname(),
  59.                         'email' => $pimcoreUser->getEmail(),
  60.                         'roles' => $user->getRoles()
  61.                     )]);
  62.                 });
  63.             }
  64.         }
  65.         return $response;
  66.     }
  67.     /**
  68.      * @Route("/promemoria/api/logout", methods={"POST", "GET"})
  69.      *
  70.      * @return JsonResponse
  71.      */
  72.     public function logout()
  73.     {
  74.         return $this->redirectToRoute('pimcore_admin_logout');
  75.     }
  76.     /**
  77.      * @Route("/promemoria/api/get-audio-thumbnail", methods={"GET"})
  78.      *
  79.      * @param Request $request
  80.      *
  81.      * @return BinaryFileResponse
  82.      */
  83.     public function getAudioThumbnail(Request $request)
  84.     {
  85.         $tmpfname tempnam("/tmp""audio.png");
  86.         file_put_contents($tmpfnamefile_get_contents("https://dummyimage.com/170x170/3e3e3e/ffffff.png&text=%20audio%20"));
  87.         $response = new BinaryFileResponse($tmpfname);
  88.         $this->addThumbnailCacheHeaders($response);
  89.         return $response;
  90.     }
  91.     /**
  92.      * @Route("/promemoria/api/get-image-thumbnail", methods={"GET"})
  93.      *
  94.      * @param Request $request
  95.      *
  96.      * @return BinaryFileResponse|StreamedResponse
  97.      */
  98.     public function getImageThumbnail(Request $request)
  99.     {
  100.         $id $request->get('id');
  101.         if(!$this->checkHash($id)){
  102.             $response = new Response();
  103.             $response->setStatusCode(401);
  104.             return $response;
  105.         }
  106.         $image Asset\Image::getById(intval($id));
  107.         $thumb $this->getThumb($image$request->get('version''thumbnail'));
  108.         return $this->responseThumbnail($thumb);
  109.     }
  110.     /**
  111.      * @Route("/promemoria/api/get-video-thumbnail", methods={"GET"})
  112.      *
  113.      * @param Request $request
  114.      *
  115.      * @return BinaryFileResponse|StreamedResponse
  116.      */
  117.     public function getVideoThumbnail(Request $request)
  118.     {
  119.         $id $request->get('id');
  120.         if(!$this->checkHash($id)){
  121.             $response = new Response();
  122.             $response->setStatusCode(401);
  123.             return $response;
  124.         }
  125.         $video Asset\Video::getById(intval($id));
  126.         $thumb $video->getImageThumbnail(Asset\Image\Thumbnail\Config::getPreviewConfig());
  127.         return $this->responseThumbnail($thumb);
  128.     }
  129.     /**
  130.      * @Route("/promemoria/api/get-document-thumbnail", methods={"GET"})
  131.      *
  132.      * @param Request $request
  133.      *
  134.      * @return BinaryFileResponse|StreamedResponse
  135.      */
  136.     public function getDocumentThumbnail(Request $request)
  137.     {
  138.         $id $request->get('id');
  139.         if(!$this->checkHash($id)){
  140.             $response = new Response();
  141.             $response->setStatusCode(401);
  142.             return $response;
  143.         }
  144.         $document Asset\Document::getById(intval($id));
  145.         $thumb = new Asset\Document\ImageThumbnail($documentAsset\Image\Thumbnail\Config::getPreviewConfig(), 1);
  146.         return $this->responseThumbnail($thumb);
  147.     }
  148.     /**
  149.      * @Route("/promemoria/api/get-video-preview", methods={"GET"})
  150.      *
  151.      * @param Request $request
  152.      *
  153.      * @return BinaryFileResponse
  154.      */
  155.     public function getVideoPreview(Request $request)
  156.     {
  157.         $response = new Response();
  158.         $response->setStatusCode(400);
  159.         $id $request->get('id');
  160.         if(!$this->checkHash($id)){
  161.             $response->setStatusCode(401);
  162.             return $response;
  163.         }
  164.         $asset Asset::getById(intval($id));
  165.         if(!empty($asset) && $asset->getType()=='video'){
  166.             $thumbnail $asset->getThumbnail(Asset\Video\Thumbnail\Config::getPreviewConfig(), ['mp4']);
  167.             $storagePath $asset->getRealPath() . '/' preg_replace('@^' preg_quote($asset->getPath(), '@') . '@'''urldecode($thumbnail['formats']['mp4']));
  168.             $storage \Pimcore\Tool\Storage::get('thumbnail');
  169.             if ($storage->fileExists($storagePath)) {
  170.                 $fs $storage->fileSize($storagePath);
  171.                 $stream $storage->readStream($storagePath);
  172.                 return new StreamedResponse(function () use ($stream) {
  173.                     fpassthru($stream);
  174.                 }, 200, [
  175.                     'Content-Type' => 'video/mp4',
  176.                     'Content-Length' => $fs,
  177.                     'Accept-Ranges' => 'bytes',
  178.                 ]);
  179.             } else {
  180.                 $response->setStatusCode(204);
  181.             }
  182.         }
  183.         return $response;
  184.     }
  185.     /**
  186.      * @param Response $response
  187.      */
  188.     protected function responseThumbnail($thumb)
  189.     {
  190.         $stream $thumb->getStream();
  191.         if ($stream) {
  192.             $response = new StreamedResponse(function () use ($stream) {
  193.                 fpassthru($stream);
  194.             }, 200, [
  195.                 'Content-Type' => 'image/' $thumb->getFileExtension(),
  196.             ]);
  197.         } else {
  198.             $pathparts pathinfo($thumb->getAsset()->getFilename());
  199.             $ext = isset($pathparts["extension"]) ? $pathparts["extension"] : 'image';
  200.             $tmpfname tempnam("/tmp""image.png");
  201.             file_put_contents($tmpfnamefile_get_contents("https://dummyimage.com/300x300/3e3e3e/ffffff.png&text=%20{$ext}%20"));
  202.             $response = new BinaryFileResponse($tmpfname);
  203.         }
  204.         $this->addThumbnailCacheHeaders($response);
  205.         return $response;
  206.     }
  207.     /**
  208.      * @Route("/promemoria/api/download-as-zip", methods={"GET"})
  209.      *
  210.      * @param Request $request
  211.      *
  212.      * @return BinaryFileResponse|BinaryFileResponse
  213.      */
  214.     public function downloadAsZip(Request $request)
  215.     {
  216.         $name $request->get('name''');
  217.         $version $request->get('version''original');
  218.         $watermarked $request->get('watermarked'0);
  219.         $selectedIds $request->get('selectedIds''');
  220.         $selectedIds explode(','$selectedIds);
  221.         if(count($selectedIds) === 1){
  222.             if(!$this->checkHash($selectedIds[0])){
  223.                 $response = new Response();
  224.                 $response->setStatusCode(401);
  225.                 return $response;
  226.             }
  227.             $a Asset::getById(intval($selectedIds[0]));
  228.             if($a instanceof Asset\Image){
  229.                 $a $this->getThumb($a$watermarked $version "no_watermark"$version === 'original');
  230.             }
  231.             if ($a instanceof Asset\Image\Thumbnail) {
  232.                 $dir_prefix '/var/www/html/public/var/tmp/thumbnails';
  233.                 $pathReference $a->getPathReference();
  234.                 $fileContent Tool\Storage::get('thumbnail')->read($pathReference['storagePath']);
  235.                 $path urldecode($a->getPath());
  236.             } else {
  237.                 $dir_prefix '/var/www/html/public/var/assets';
  238.                 $path $a->getRealFullPath();
  239.             }
  240.             $response = new BinaryFileResponse($dir_prefix $path);
  241.             //$response->headers->set('Content-Type', 'image/' . $image->getFileExtension());
  242.             $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENTbasename($path));
  243.             return $response;
  244.         }else{
  245.             $zipName = ($name ?: 'collection-' time()) . '.zip';
  246.             $zipFile tempnam("/tmp"$zipName);
  247.             $zip = new \ZipArchive();
  248.             $zipState $zip->open($zipFile\ZipArchive::CREATE);
  249.             if (count($selectedIds) > && $zipState === true) {
  250.                 $conditionFilters = [];
  251.                 $ids = [];
  252.                 foreach ($selectedIds as $id) {
  253.                     if(!$this->checkHash($id)){
  254.                         $response = new Response();
  255.                         $response->setStatusCode(401);
  256.                         return $response;
  257.                     }
  258.                     $ids[] = intval($id);
  259.                 }
  260.                 $conditionFilters[] = 'id IN (' implode(','$ids) . ')';
  261.                 $conditionFilters[] .= "type != 'folder'";
  262.                 $condition implode(' AND '$conditionFilters);
  263.                 $assetList = new Asset\Listing();
  264.                 $assetList->setCondition($condition);
  265.                 $assetList->setOrderKey('LENGTH(path) ASC, id ASC'false);
  266.                 $assetList->setOffset((int)$request->get('offset'));
  267.                 $assetList->setLimit((int)$request->get('limit'));
  268.                 foreach ($assetList->load() as $a) {
  269.                     if (!$a instanceof Asset\Folder) {
  270.                         if($a instanceof Asset\Image){
  271.                             $a $this->getThumb($a$watermarked $version "no_watermark"$version === 'original');
  272.                         }
  273.                         if ($a instanceof Asset\Image\Thumbnail) {
  274.                             $dir_prefix '/var/www/html/public/var/tmp/thumbnails';
  275.                             $pathReference $a->getPathReference();
  276.                             //serve per generare la thumb nel caso non esista
  277.                             $fileContent Tool\Storage::get('thumbnail')->read($pathReference['storagePath']);
  278.                             $path urldecode($a->getPath());
  279.                         } else {
  280.                             $dir_prefix '/var/www/html/public/var/assets';
  281.                             $path $a->getRealFullPath();
  282.                         }
  283.                         $zip->addFile($dir_prefix.$pathbasename($path));
  284.                     }
  285.                 }
  286.                 $zip->close();
  287.                 $response = new BinaryFileResponse($zipFile);
  288.                 $response->headers->set('Content-Type''application/zip');
  289.                 $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT$zipName);
  290.                 $response->deleteFileAfterSend(true);
  291.                 return $response;
  292.             }
  293.         }
  294.         return $this->json(['error' => true]);
  295.     }
  296.     /**
  297.      * @Route("/promemoria/api/getShortToken", methods={"GET"})
  298.      * @param Request $request
  299.      *
  300.      * @return JsonResponse
  301.      */
  302.     public function getShortToken(Request $request)
  303.     {
  304.         $response = new Response();
  305.         $response->setStatusCode(400);
  306.         $db \Pimcore\Db::get();
  307.         $jwtToken $request->get('jwtToken');
  308.         $this->clearExpiredShortUrls();
  309.         if (!empty($jwtToken)) {
  310.             $generatedToken substr(md5(uniqid(mt_rand(), true)), 08);
  311.             $db->insert('promemoria_shorturl', [
  312.                 'jwtToken' => $jwtToken,
  313.                 'shortToken' => $generatedToken
  314.             ]);
  315.             return $this->json(['shortToken' => $generatedToken]);
  316.         }
  317.         return $response;
  318.     }
  319.     /**
  320.      * @Route("/promemoria/api/getJwtToken", methods={"GET"})
  321.      * @param Request $request
  322.      *
  323.      * @return JsonResponse
  324.      */
  325.     public function getJwtToken(Request $request)
  326.     {
  327.         $response = new Response();
  328.         $response->setStatusCode(400);
  329.         $db \Pimcore\Db::get();
  330.         $shortToken $request->get('shortToken');
  331.         $this->clearExpiredShortUrls();
  332.         if (!empty($shortToken)) {
  333.             $res $db->fetchRow("SELECT jwtToken FROM promemoria_shorturl WHERE shortToken = " $db->quote($shortToken));
  334.             return $this->json(['jwtToken' => $res['jwtToken']]);
  335.         }
  336.         return $response;
  337.     }
  338.     /**
  339.      * @Route("/promemoria/api/changePassword", methods={"POST"})
  340.      * @param Request $request
  341.      *
  342.      * @return JsonResponse
  343.      */
  344.     public function changePassword(Request $request)
  345.     {
  346.         $response = new Response();
  347.         $response->setStatusCode(401);
  348.         $data json_decode($request->getContent());
  349.         $newPassword $data->password;
  350.         $pimcoreUser Authentication::authenticateSession();
  351.         if(empty($pimcoreUser)){
  352.             return $response;
  353.         }
  354.         if (!empty($pimcoreUser) && !empty($newPassword)) {
  355.             $pimcoreUser->setPassword(Authentication::getPasswordHash($pimcoreUser->getUsername(), $newPassword));
  356.             $pimcoreUser->save();
  357.             return $this->json(['message' => 'Password changed']);
  358.         }
  359.         return $response;
  360.     }
  361.     /**
  362.      * @Route("/promemoria/api/getUserList", methods={"POST"}))
  363.      * @param Request $request
  364.      *
  365.      * @return JsonResponse
  366.      */
  367.     public function getUserList(Request $request)
  368.     {
  369.         $pimcoreUser Authentication::authenticateSession();
  370.         if(empty($pimcoreUser)){
  371.             $response = new Response();
  372.             $response->setStatusCode(401);
  373.             return $response;
  374.         }
  375.         $db \Pimcore\Db::get();
  376.         $query = <<<QUERY
  377.         SELECT u.id as user_id, u.name as user_name, u.firstname as fname, u.lastname as lname, u.email, r.id as role_id, r.name as role
  378.         FROM users u
  379.         INNER JOIN users r ON u.type = 'user' and u.roles = r.id and u.roles != '' and u.active = 1
  380.         order by u.name asc
  381. QUERY;
  382.         return $this->json(['users' => $db->executeQuery($query)->fetchAll()]);
  383.     }
  384.     /**
  385.     * @Route("/promemoria/api/getRoleList", methods={"POST"}))
  386.     * @param Request $request
  387.     *
  388.     * @return JsonResponse
  389.     */
  390.     public function getRoleList(Request $request)
  391.     {
  392.         $pimcoreUser Authentication::authenticateSession();
  393.         if(empty($pimcoreUser)){
  394.             $response = new Response();
  395.             $response->setStatusCode(401);
  396.             return $response;
  397.         }
  398.         $db \Pimcore\Db::get();
  399.         $query = <<<QUERY
  400.         SELECT u.id as role_id, u.name as name
  401.         FROM users u
  402.         WHERE
  403.         u.type = 'role'
  404.         order by u.name asc
  405. QUERY;
  406.         return $this->json(['roles' => $db->executeQuery($query)->fetchAll()]);
  407.     }
  408.     /**
  409.      * @Route("/promemoria/api/upsertUser", methods={"POST"})
  410.      * @param Request $request
  411.      *
  412.      * @return JsonResponse
  413.      */
  414.     public function upsertUser(Request $request)
  415.     {
  416.         $pimcoreUser Authentication::authenticateSession();
  417.         if(empty($pimcoreUser)){
  418.             $response = new Response();
  419.             $response->setStatusCode(401);
  420.             return $response;
  421.         }
  422.         $userAdmin = new UserAdmin($pimcoreUser);
  423.         if(!in_array("ROLE_PIMCORE_ADMIN"$userAdmin->getRoles())
  424.             && !in_array("ROLE_MANAGER"$userAdmin->getRoles())){
  425.             $response = new Response();
  426.             $response->setStatusCode(401);
  427.             return $response;
  428.         }
  429.         $data json_decode($request->getContent());
  430.         $user = new User();
  431.         if(!empty($data->user_id)){
  432.             $user User::getById($data->user_id);
  433.         }
  434.         $user->setParentid(0);
  435.         $user->setUsername($data->user_name);
  436.         $user->setFirstname($data->fname);
  437.         $user->setLastname($data->lname);
  438.         $user->setEmail($data->email);
  439.         $user->setActive($data->active);
  440.         $user->setLanguage("it");
  441.         $user->setContentLanguages("it,en");
  442.         if(!empty($data->password)){
  443.             $user->setPassword(Authentication::getPasswordHash($data->user_name$data->password));
  444.         }
  445.         $user->setRoles($data->role_id);
  446.         $user->save();
  447.         return $this->json(['message' => 'User updated']);
  448.     }
  449.     /**
  450.      * @Route("/promemoria/api/deleteUser", methods={"POST"})
  451.      * @param Request $request
  452.      *
  453.      * @return JsonResponse
  454.      */
  455.     public function deleteUser(Request $request)
  456.     {
  457.         $pimcoreUser Authentication::authenticateSession();
  458.         if(empty($pimcoreUser)){
  459.             $response = new Response();
  460.             $response->setStatusCode(401);
  461.             return $response;
  462.         }
  463.         $data json_decode($request->getContent());
  464.         $user User::getById($data->user_id);
  465.         $userAdmin = new UserAdmin($user);
  466.         if(in_array("ROLE_PIMCORE_ADMIN"$userAdmin->getRoles())){
  467.             $response = new Response();
  468.             $response->setStatusCode(401);
  469.             return $response;
  470.         }
  471.         $user->delete();
  472.         return $this->json(['message' => 'User deleted']);
  473.     }
  474.     /**
  475.      * @Route("/promemoria/api/buca", methods={"POST"})
  476.      * @param Request $request
  477.      *
  478.      * @return JsonResponse
  479.      */
  480.     public function buca(Request $request)
  481.     {
  482.         $token $request->get("token");
  483.         $config \App\PromemoriaBundle\PromemoriaBundle::getConfig();
  484.         if(!empty($config["googleRecaptchaSecretKey"]) && !empty($token)){
  485.             $verifyResponse file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' $config["googleRecaptchaSecretKey"] . '&response=' $token);
  486.             $responseData json_decode($verifyResponse);
  487.             if (!$responseData->success || $responseData->score 0.5) {
  488.                 $response = new Response();
  489.                 $response->setStatusCode(401);
  490.                 return $response;
  491.             }
  492.             $email $request->get("email");
  493.             $pimcoreUsername = empty($email) ? "website" $email;
  494.             $pimcoreId 0;
  495.         }else{
  496.             $pimcoreUser Authentication::authenticateSession();
  497.             if(empty($pimcoreUser)){
  498.                 $email $request->get("email");
  499.                 if(empty($email)){
  500.                     $response = new Response();
  501.                     $response->setStatusCode(401);
  502.                     return $response;
  503.                 }else{
  504.                     $pimcoreUsername $email;
  505.                     $pimcoreId 0;
  506.                 }
  507.             }else{
  508.                 $pimcoreUsername $pimcoreUser->getUsername();
  509.                 $pimcoreId $pimcoreUser->getId();
  510.             }
  511.         }
  512.         // crezione folder utente se non esiste
  513.         $parentBuca "/Buca/";
  514.         $parentPath $parentBuca $pimcoreUsername;
  515.         $parentAsset \Pimcore\Model\Asset::getByPath($parentPath);
  516.         if(!$parentAsset){
  517.             $parent \Pimcore\Model\Asset::getByPath($parentBuca);
  518.             $parentAsset $this->createFolder($pimcoreUsername$parent->getId(), 'asset');
  519.         }
  520.         $parentObject \Pimcore\Model\DataObject::getByPath($parentPath);
  521.         if(!$parentObject){
  522.             $parent \Pimcore\Model\DataObject::getByPath($parentBuca);
  523.             $parentObject $this->createFolder($pimcoreUsername$parent->getId());
  524.         }
  525.         // creazione oggetto e media
  526.         $separatore "$";
  527.         $classe "\Pimcore\Model\DataObject\\" $request->get("class");
  528.         $fields json_decode($request->get("fields"), TRUE);
  529.         $obj = new $classe();
  530.         $obj->setParentId($parentObject->getId());
  531.         foreach ($fields as $key => $typeField) {
  532.             $fieldDefiniton $obj->getClass()->getFieldDefinition($key);
  533.             $type $fieldDefiniton $fieldDefiniton->getFieldtype() : "localizedfield";
  534.             $type strpos($key$separatore) !== FALSE "block" $type;
  535.             if(in_array($typeField,["file","image"])){
  536.                 $files $request->files->get($key);
  537.                 $metadati $request->get($key "Metadati");
  538.                 if(!empty($files)){
  539.                     $isMultiple is_array($files);
  540.                     $files $isMultiple $files : [$files];
  541.                     if(!empty($metadati)){
  542.                         $metadati $isMultiple $metadati : [$metadati];
  543.                     }
  544.                     $values = [];
  545.                     if($typeField === "image"){
  546.                         foreach ($files as $index => $file) {
  547.                             $advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
  548.                             $metadatis = !empty($metadati) && !empty($metadati[$index]) ? json_decode($metadati[$index], TRUE) : [];
  549.                             $advancedImage->setImage($this->createAsset($parentAsset$file"image"$metadatis));
  550.                             $values[] = $advancedImage;
  551.                         }
  552.                         $values = new \Pimcore\Model\DataObject\Data\ImageGallery($values);
  553.                     }else{
  554.                         foreach ($files as $index => $file) {
  555.                             $values[] = $this->createAsset($parentAsset$file);
  556.                         }
  557.                     }
  558.                     $obj->{"set" ucfirst($key)}($isMultiple $values $values[0]);
  559.                 }
  560.             }else {
  561.                 $val $request->get($key);
  562.                 if(!empty($val)){
  563.                     switch($typeField){
  564.                         case "link":
  565.                             $link = new \Pimcore\Model\DataObject\Data\Link();
  566.                             $link->setText("Link");
  567.                             $link->setPath($val);
  568.                             $val $link;
  569.                             break;
  570.                         case 'date':
  571.                             $val \Carbon\Carbon::createFromFormat('Y-m-d'$val);
  572.                             break;
  573.                     }
  574.                     switch($type){
  575.                         case "video":
  576.                             $video = new \Pimcore\Model\DataObject\Data\Video();
  577.                             $video->setType("youtube");
  578.                             $video->setData($val);
  579.                             $result preg_match("/(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&]+(?=\?)|(?<=v=)[^&]+|(?<=youtu.be\/)[^&]+/"$val$matches);
  580.                             if($result){
  581.                                 $video->setType("youtube");
  582.                                 $video->setData($matches[0]);
  583.                             }
  584.                             $result preg_match("/(?<=vimeo.com\/)[^&]+/"$val$matches);
  585.                             if($result){
  586.                                 $video->setType("vimeo");
  587.                                 $video->setData($matches[0]);
  588.                             }
  589.                             $obj->{"set" ucfirst($key)}($video);
  590.                             break;
  591.                         case "block":
  592.                             list ($keyContainer$keyMeta) = explode($separatore$key);
  593.                             $metadata = [];
  594.                             $metadata[$keyMeta] = new \Pimcore\Model\DataObject\Data\BlockElement($keyMeta$typeField$val);
  595.                             $obj->{"set" ucfirst($keyContainer)}([$metadata]);
  596.                             break;
  597.                         case "localizedfield":
  598.                             $obj->{"set" ucfirst($key)}($val'it');
  599.                             break;
  600.                         case "multiselect":
  601.                             $obj->{"set" ucfirst($key)}([$val]);
  602.                             break;
  603.                         default:
  604.                             $obj->{"set" ucfirst($key)}($val);
  605.                             break;
  606.                     }
  607.                     if($key === 'dcTitle'){
  608.                         $obj->setKey(\Pimcore\Model\Element\Service::getValidKey($val'object'));
  609.                     }
  610.                 }
  611.             }
  612.         }
  613.         $obj->setUserOwner($pimcoreId);
  614.         $obj->setUserModification($pimcoreId);
  615.         $obj->save();
  616.         $tags $request->get("tags");
  617.         if(!empty($tags)){
  618.             \Pimcore\Model\Element\Tag::setTagsForElement('object'$obj->getId(), array_map(function($id){
  619.                 return \Pimcore\Model\Element\Tag::getById($id);
  620.             }, $tags));
  621.         }
  622.         return $this->json(["status" =>  true ]);
  623.     }
  624.     /**
  625.      * @Route("/promemoria/api/bucaSelect", methods={"POST"})
  626.      * @param Request $request
  627.      *
  628.      * @return JsonResponse
  629.      */
  630.     public function bucaSelect(Request $request)
  631.     {
  632.         $pimcoreUser Authentication::authenticateSession();
  633.         if(empty($pimcoreUser)){
  634.             $response = new Response();
  635.             $response->setStatusCode(401);
  636.             return $response;
  637.         }
  638.         $data json_decode($request->getContent());
  639.         $classe "\Pimcore\Model\DataObject\\" $data->class;
  640.         $obj = new $classe();
  641.         $fieldDefiniton $obj->getClass()->getFieldDefinition($data->field);
  642.         return $this->json($fieldDefiniton->getOptions());
  643.     }
  644.      /**
  645.      * @Route("/promemoria/api/bucaTags", methods={"POST"})
  646.      * @param Request $request
  647.      *
  648.      * @return JsonResponse
  649.      */
  650.     public function bucaTags(Request $request)
  651.     {
  652.         $pimcoreUser Authentication::authenticateSession();
  653.         if(empty($pimcoreUser)){
  654.             $response = new Response();
  655.             $response->setStatusCode(401);
  656.             return $response;
  657.         }
  658.         $data json_decode($request->getContent());
  659.         $tagList = new \Pimcore\Model\Element\Tag\Listing();
  660.         $tagList->setCondition("parentId = ?"$data->parentId);
  661.         $tagList->setOrderKey("id");
  662.         $tags = [];
  663.         foreach ($tagList->load() as $tag) {
  664.             $tags[] = [
  665.                 "id" => $tag->getId(),
  666.                 "label" => $tag->getName()
  667.             ];
  668.         }
  669.         return $this->json($tags);
  670.     }
  671.     /**
  672.      * @Route("/promemoria/api/check-email", methods={"POST"}))
  673.      * @param Request $request
  674.      *
  675.      * @return JsonResponse
  676.      */
  677.     public function checkEmail(Request $request)
  678.     {
  679.         $response = new Response();
  680.         $response->setStatusCode(400);
  681.         $data json_decode($request->getContent());
  682.         if(empty($data->email)){
  683.             return $response;
  684.         }
  685.         $user false;
  686.         $entries = new \Pimcore\Model\User\Listing();
  687.         $entries->setLimit(1);
  688.         $entries->setCondition("email LIKE ?", [$data->email]);
  689.         foreach ($entries as $entry) {
  690.             $user $entry;
  691.             return $this->json([
  692.                 'status' => true
  693.             ]);
  694.         }
  695.         return $response;
  696.     }
  697.     /**
  698.      * @Route("/promemoria/api/change-reset-password", methods={"POST"}))
  699.      * @param Request $request
  700.      *
  701.      * @return JsonResponse
  702.      */
  703.     public function changeResetPassword(Request $request)
  704.     {
  705.         $response = new Response();
  706.         $response->setStatusCode(400);
  707.         $data json_decode($request->getContent());
  708.         if(empty($data->email) || empty($data->password)){
  709.             return $response;
  710.         }
  711.         $entries = new \Pimcore\Model\User\Listing();
  712.         $entries->setLimit(1);
  713.         $entries->setCondition("email LIKE ?", [$data->email]);
  714.         foreach ($entries as $entry) {
  715.             $user $entry;
  716.             $user->setPassword(Authentication::getPasswordHash($user->getUsername(), $data->password));
  717.             $user->save();
  718.             return $this->json([
  719.                 'status' => true
  720.             ]);
  721.         }
  722.         return $response;
  723.     }
  724.     /* PRIVATE */
  725.     private function clearExpiredShortUrls()
  726.     {
  727.         $db \Pimcore\Db::get();
  728.         $db->deleteWhere('promemoria_shorturl''insertDate < NOW() - INTERVAL 1 WEEK');
  729.     }
  730.     private function createFolder($name$parent$type 'object'){
  731.         $folder $type === 'object' ? new \Pimcore\Model\DataObject\Folder() : new \Pimcore\Model\Asset\Folder();
  732.         $folder->setParentId($parent);
  733.         $type === 'object'  $folder->setKey($name) : $folder->setFilename($name);
  734.         $folder->save();
  735.         return $folder;
  736.     }
  737.     private function createAsset($parentAsset$file$type=""$metadati = []){
  738.         $newAsset $type ? new \Pimcore\Model\Asset\Image() : new \Pimcore\Model\Asset();
  739.         $newAsset->setFilename($this->checkFileAndRename($parentAsset->getFullPath(), $file->getClientOriginalName()));
  740.         $newAsset->setData(file_get_contents($file->getPathname()));
  741.         $newAsset->setParent($parentAsset);
  742.         if(!empty($metadati)){
  743.             foreach ($metadati as $key => $value) {
  744.                 $newAsset->addMetadata($key"input"$value);
  745.             }
  746.         }
  747.         $newAsset->save();
  748.         return $newAsset;
  749.     }
  750.     private function checkFileAndRename($parentPath$filename){
  751.         $path_parts pathinfo($filename);
  752.         $i 1;
  753.         while(\Pimcore\Model\Asset::getByPath($parentPath "/" $filename)){
  754.             $filename $path_parts['filename'] . "_$i." $path_parts['extension'];
  755.             $i++;
  756.         }
  757.         return $filename;
  758.     }
  759.     private function getThumb($image$type$original=false){
  760.         $thumb $this->getThumbnail($image"watermarked_" $type);
  761.         if(!$thumb || empty($thumb->getConfig())) {
  762.             $thumb $this->getThumbnail($image$type);
  763.         }
  764.         if(!$thumb || empty($thumb->getConfig())){
  765.             if($original) return $image;
  766.             $thumb $this->getThumbnail($imageAsset\Image\Thumbnail\Config::getPreviewConfig());
  767.         }
  768.         return $thumb;
  769.     }
  770.     private function getThumbnail($image$type){
  771.         try{
  772.             return $image->getThumbnail($type);
  773.         }catch(\Exception $err){
  774.             return null;
  775.         }
  776.     }
  777.     private function addThumbnailCacheHeaders(Response $response)
  778.     {
  779.        $lifetime 300;
  780.         $date = new \DateTime('now');
  781.         $date->add(new \DateInterval('PT' $lifetime 'S'));
  782.         $response->setMaxAge($lifetime);
  783.         $response->setPublic();
  784.         $response->setExpires($date);
  785.         $response->headers->set('Access-Control-Allow-Origin''*');
  786.     }
  787.     private function checkHash($id){
  788.         list($id$hash) = explode("-"$id);
  789.         return $hash === substr(md5($id md5(getenv("dotenv_suffix"))), 08);
  790.     }
  791. }