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
  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.         $zipName = ($name ?: 'collection-' time()) . '.zip';
  220.         $zipFile tempnam("/tmp"$zipName);
  221.         $zip = new \ZipArchive();
  222.         $zipState $zip->open($zipFile\ZipArchive::CREATE);
  223.         $selectedIds $request->get('selectedIds''');
  224.         if (strlen($selectedIds) > && $zipState === true) {
  225.             $conditionFilters = [];
  226.             $selectedIds explode(','$selectedIds);
  227.             $ids = [];
  228.             foreach ($selectedIds as $id) {
  229.                 if(!$this->checkHash($id)){
  230.                     $response = new Response();
  231.                     $response->setStatusCode(401);
  232.                     return $response;
  233.                 }
  234.                 $ids[] = intval($id);
  235.             }
  236.             $conditionFilters[] = 'id IN (' implode(','$ids) . ')';
  237.             $conditionFilters[] .= "type != 'folder'";
  238.             $condition implode(' AND '$conditionFilters);
  239.             $assetList = new Asset\Listing();
  240.             $assetList->setCondition($condition);
  241.             $assetList->setOrderKey('LENGTH(path) ASC, id ASC'false);
  242.             $assetList->setOffset((int)$request->get('offset'));
  243.             $assetList->setLimit((int)$request->get('limit'));
  244.             foreach ($assetList->load() as $a) {
  245.                 if (!$a instanceof Asset\Folder) {
  246.                     if($a instanceof Asset\Image){
  247.                         $a $this->getThumb($a$watermarked $version "no_watermark"$version === 'original');
  248.                     }
  249.                     if ($a instanceof Asset\Image\Thumbnail) {
  250.                         $dir_prefix '/var/www/html/public/var/tmp/thumbnails';
  251.                         $pathReference $a->getPathReference();
  252.                         //serve per generare la thumb nel caso non esista
  253.                         $fileContent Tool\Storage::get('thumbnail')->read($pathReference['storagePath']);
  254.                         $path urldecode($a->getPath());
  255.                     } else {
  256.                         $dir_prefix '/var/www/html/public/var/assets';
  257.                         $path $a->getRealFullPath();
  258.                     }
  259.                     $zip->addFile($dir_prefix.$pathbasename($path));
  260.                 }
  261.             }
  262.             $zip->close();
  263.             $response = new BinaryFileResponse($zipFile);
  264.             $response->headers->set('Content-Type''application/zip');
  265.             $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT$zipName);
  266.             $response->deleteFileAfterSend(true);
  267.             return $response;
  268.         }
  269.         return $this->json(['error' => true]);
  270.     }
  271.     /**
  272.      * @Route("/promemoria/api/getShortToken", methods={"GET"})
  273.      * @param Request $request
  274.      *
  275.      * @return JsonResponse
  276.      */
  277.     public function getShortToken(Request $request)
  278.     {
  279.         $response = new Response();
  280.         $response->setStatusCode(400);
  281.         $db \Pimcore\Db::get();
  282.         $jwtToken $request->get('jwtToken');
  283.         $this->clearExpiredShortUrls();
  284.         if (!empty($jwtToken)) {
  285.             $generatedToken substr(md5(uniqid(mt_rand(), true)), 08);
  286.             $db->insert('promemoria_shorturl', [
  287.                 'jwtToken' => $jwtToken,
  288.                 'shortToken' => $generatedToken
  289.             ]);
  290.             return $this->json(['shortToken' => $generatedToken]);
  291.         }
  292.         return $response;
  293.     }
  294.     /**
  295.      * @Route("/promemoria/api/getJwtToken", methods={"GET"})
  296.      * @param Request $request
  297.      *
  298.      * @return JsonResponse
  299.      */
  300.     public function getJwtToken(Request $request)
  301.     {
  302.         $response = new Response();
  303.         $response->setStatusCode(400);
  304.         $db \Pimcore\Db::get();
  305.         $shortToken $request->get('shortToken');
  306.         $this->clearExpiredShortUrls();
  307.         if (!empty($shortToken)) {
  308.             $res $db->fetchRow("SELECT jwtToken FROM promemoria_shorturl WHERE shortToken = " $db->quote($shortToken));
  309.             return $this->json(['jwtToken' => $res['jwtToken']]);
  310.         }
  311.         return $response;
  312.     }
  313.     /**
  314.      * @Route("/promemoria/api/changePassword", methods={"POST"})
  315.      * @param Request $request
  316.      *
  317.      * @return JsonResponse
  318.      */
  319.     public function changePassword(Request $request)
  320.     {
  321.         $response = new Response();
  322.         $response->setStatusCode(401);
  323.         $data json_decode($request->getContent());
  324.         $newPassword $data->password;
  325.         $pimcoreUser Authentication::authenticateSession();
  326.         if(empty($pimcoreUser)){
  327.             return $response;
  328.         }
  329.         if (!empty($pimcoreUser) && !empty($newPassword)) {
  330.             $pimcoreUser->setPassword(Authentication::getPasswordHash($pimcoreUser->getUsername(), $newPassword));
  331.             $pimcoreUser->save();
  332.             return $this->json(['message' => 'Password changed']);
  333.         }
  334.         return $response;
  335.     }
  336.     /**
  337.      * @Route("/promemoria/api/getUserList", methods={"POST"}))
  338.      * @param Request $request
  339.      *
  340.      * @return JsonResponse
  341.      */
  342.     public function getUserList(Request $request)
  343.     {
  344.         $pimcoreUser Authentication::authenticateSession();
  345.         if(empty($pimcoreUser)){
  346.             $response = new Response();
  347.             $response->setStatusCode(401);
  348.             return $response;
  349.         }
  350.         $db \Pimcore\Db::get();
  351.         $query = <<<QUERY
  352.         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
  353.         FROM users u
  354.         INNER JOIN users r ON u.type = 'user' and u.roles = r.id and u.roles != '' and u.active = 1
  355.         order by u.name asc
  356. QUERY;
  357.         return $this->json(['users' => $db->executeQuery($query)->fetchAll()]);
  358.     }
  359.     /**
  360.     * @Route("/promemoria/api/getRoleList", methods={"POST"}))
  361.     * @param Request $request
  362.     *
  363.     * @return JsonResponse
  364.     */
  365.     public function getRoleList(Request $request)
  366.     {
  367.         $pimcoreUser Authentication::authenticateSession();
  368.         if(empty($pimcoreUser)){
  369.             $response = new Response();
  370.             $response->setStatusCode(401);
  371.             return $response;
  372.         }
  373.         $db \Pimcore\Db::get();
  374.         $query = <<<QUERY
  375.         SELECT u.id as role_id, u.name as name
  376.         FROM users u
  377.         WHERE
  378.         u.type = 'role'
  379.         order by u.name asc
  380. QUERY;
  381.         return $this->json(['roles' => $db->executeQuery($query)->fetchAll()]);
  382.     }
  383.     /**
  384.      * @Route("/promemoria/api/upsertUser", methods={"POST"})
  385.      * @param Request $request
  386.      *
  387.      * @return JsonResponse
  388.      */
  389.     public function upsertUser(Request $request)
  390.     {
  391.         $pimcoreUser Authentication::authenticateSession();
  392.         if(empty($pimcoreUser)){
  393.             $response = new Response();
  394.             $response->setStatusCode(401);
  395.             return $response;
  396.         }
  397.         $userAdmin = new UserAdmin($pimcoreUser);
  398.         if(!in_array("ROLE_PIMCORE_ADMIN"$userAdmin->getRoles())
  399.             && !in_array("ROLE_MANAGER"$userAdmin->getRoles())){
  400.             $response = new Response();
  401.             $response->setStatusCode(401);
  402.             return $response;
  403.         }
  404.         $data json_decode($request->getContent());
  405.         $user = new User();
  406.         if(!empty($data->user_id)){
  407.             $user User::getById($data->user_id);
  408.         }
  409.         $user->setParentid(0);
  410.         $user->setUsername($data->user_name);
  411.         $user->setFirstname($data->fname);
  412.         $user->setLastname($data->lname);
  413.         $user->setEmail($data->email);
  414.         $user->setActive($data->active);
  415.         $user->setLanguage("it");
  416.         $user->setContentLanguages("it,en");
  417.         if(!empty($data->password)){
  418.             $user->setPassword(Authentication::getPasswordHash($data->user_name$data->password));
  419.         }
  420.         $user->setRoles($data->role_id);
  421.         $user->save();
  422.         return $this->json(['message' => 'User updated']);
  423.     }
  424.     /**
  425.      * @Route("/promemoria/api/deleteUser", methods={"POST"})
  426.      * @param Request $request
  427.      *
  428.      * @return JsonResponse
  429.      */
  430.     public function deleteUser(Request $request)
  431.     {
  432.         $pimcoreUser Authentication::authenticateSession();
  433.         if(empty($pimcoreUser)){
  434.             $response = new Response();
  435.             $response->setStatusCode(401);
  436.             return $response;
  437.         }
  438.         $data json_decode($request->getContent());
  439.         $user User::getById($data->user_id);
  440.         $userAdmin = new UserAdmin($user);
  441.         if(in_array("ROLE_PIMCORE_ADMIN"$userAdmin->getRoles())){
  442.             $response = new Response();
  443.             $response->setStatusCode(401);
  444.             return $response;
  445.         }
  446.         $user->delete();
  447.         return $this->json(['message' => 'User deleted']);
  448.     }
  449.     /**
  450.      * @Route("/promemoria/api/buca", methods={"POST"})
  451.      * @param Request $request
  452.      *
  453.      * @return JsonResponse
  454.      */
  455.     public function buca(Request $request)
  456.     {
  457.         $token $request->get("token");
  458.         $config \App\PromemoriaBundle\PromemoriaBundle::getConfig();
  459.         if(!empty($config["googleRecaptchaSecretKey"]) && !empty($token)){
  460.             $verifyResponse file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' $config["googleRecaptchaSecretKey"] . '&response=' $token);
  461.             $responseData json_decode($verifyResponse);
  462.             if (!$responseData->success || $responseData->score 0.5) {
  463.                 $response = new Response();
  464.                 $response->setStatusCode(401);
  465.                 return $response;
  466.             }
  467.             $email $request->get("email");
  468.             $pimcoreUsername = empty($email) ? "website" $email;
  469.             $pimcoreId 0;
  470.         }else{
  471.             $pimcoreUser Authentication::authenticateSession();
  472.             if(empty($pimcoreUser)){
  473.                 $email $request->get("email");
  474.                 if(empty($email)){
  475.                     $response = new Response();
  476.                     $response->setStatusCode(401);
  477.                     return $response;
  478.                 }else{
  479.                     $pimcoreUsername $email;
  480.                     $pimcoreId 0;
  481.                 }
  482.             }else{
  483.                 $pimcoreUsername $pimcoreUser->getUsername();
  484.                 $pimcoreId $pimcoreUser->getId();
  485.             }
  486.         }
  487.         // crezione folder utente se non esiste
  488.         $parentBuca "/Buca/";
  489.         $parentPath $parentBuca $pimcoreUsername;
  490.         $parentAsset \Pimcore\Model\Asset::getByPath($parentPath);
  491.         if(!$parentAsset){
  492.             $parent \Pimcore\Model\Asset::getByPath($parentBuca);
  493.             $parentAsset $this->createFolder($pimcoreUsername$parent->getId(), 'asset');
  494.         }
  495.         $parentObject \Pimcore\Model\DataObject::getByPath($parentPath);
  496.         if(!$parentObject){
  497.             $parent \Pimcore\Model\DataObject::getByPath($parentBuca);
  498.             $parentObject $this->createFolder($pimcoreUsername$parent->getId());
  499.         }
  500.         // creazione oggetto e media
  501.         $separatore "$";
  502.         $classe "\Pimcore\Model\DataObject\\" $request->get("class");
  503.         $fields json_decode($request->get("fields"), TRUE);
  504.         $obj = new $classe();
  505.         $obj->setParentId($parentObject->getId());
  506.         foreach ($fields as $key => $typeField) {
  507.             $fieldDefiniton $obj->getClass()->getFieldDefinition($key);
  508.             $type $fieldDefiniton $fieldDefiniton->getFieldtype() : "localizedfield";
  509.             $type strpos($key$separatore) !== FALSE "block" $type;
  510.             if(in_array($typeField,["file","image"])){
  511.                 $files $request->files->get($key);
  512.                 $metadati $request->get($key "Metadati");
  513.                 if(!empty($files)){
  514.                     $isMultiple is_array($files);
  515.                     $files $isMultiple $files : [$files];
  516.                     if(!empty($metadati)){
  517.                         $metadati $isMultiple $metadati : [$metadati];
  518.                     }
  519.                     $values = [];
  520.                     if($typeField === "image"){
  521.                         foreach ($files as $index => $file) {
  522.                             $advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
  523.                             $metadatis = !empty($metadati) && !empty($metadati[$index]) ? json_decode($metadati[$index], TRUE) : [];
  524.                             $advancedImage->setImage($this->createAsset($parentAsset$file"image"$metadatis));
  525.                             $values[] = $advancedImage;
  526.                         }
  527.                         $values = new \Pimcore\Model\DataObject\Data\ImageGallery($values);
  528.                     }else{
  529.                         foreach ($files as $index => $file) {
  530.                             $values[] = $this->createAsset($parentAsset$file);
  531.                         }
  532.                     }
  533.                     $obj->{"set" ucfirst($key)}($isMultiple $values $values[0]);
  534.                 }
  535.             }else {
  536.                 $val $request->get($key);
  537.                 if(!empty($val)){
  538.                     switch($typeField){
  539.                         case "link":
  540.                             $link = new \Pimcore\Model\DataObject\Data\Link();
  541.                             $link->setText("Link");
  542.                             $link->setPath($val);
  543.                             $val $link;
  544.                             break;
  545.                         case 'date':
  546.                             $val \Carbon\Carbon::createFromFormat('Y-m-d'$val);
  547.                             break;
  548.                     }
  549.                     switch($type){
  550.                         case "video":
  551.                             $video = new \Pimcore\Model\DataObject\Data\Video();
  552.                             $video->setType("youtube");
  553.                             $video->setData($val);
  554.                             $result preg_match("/(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&]+(?=\?)|(?<=v=)[^&]+|(?<=youtu.be\/)[^&]+/"$val$matches);
  555.                             if($result){
  556.                                 $video->setType("youtube");
  557.                                 $video->setData($matches[0]);
  558.                             }
  559.                             $result preg_match("/(?<=vimeo.com\/)[^&]+/"$val$matches);
  560.                             if($result){
  561.                                 $video->setType("vimeo");
  562.                                 $video->setData($matches[0]);
  563.                             }
  564.                             $obj->{"set" ucfirst($key)}($video);
  565.                             break;
  566.                         case "block":
  567.                             list ($keyContainer$keyMeta) = explode($separatore$key);
  568.                             $metadata = [];
  569.                             $metadata[$keyMeta] = new \Pimcore\Model\DataObject\Data\BlockElement($keyMeta$typeField$val);
  570.                             $obj->{"set" ucfirst($keyContainer)}([$metadata]);
  571.                             break;
  572.                         case "localizedfield":
  573.                             $obj->{"set" ucfirst($key)}($val'it');
  574.                             break;
  575.                         case "multiselect":
  576.                             $obj->{"set" ucfirst($key)}([$val]);
  577.                             break;
  578.                         default:
  579.                             $obj->{"set" ucfirst($key)}($val);
  580.                             break;
  581.                     }
  582.                     if($key === 'dcTitle'){
  583.                         $obj->setKey(\Pimcore\Model\Element\Service::getValidKey($val'object'));
  584.                     }
  585.                 }
  586.             }
  587.         }
  588.         $obj->setUserOwner($pimcoreId);
  589.         $obj->setUserModification($pimcoreId);
  590.         $obj->save();
  591.         $tags $request->get("tags");
  592.         if(!empty($tags)){
  593.             \Pimcore\Model\Element\Tag::setTagsForElement('object'$obj->getId(), array_map(function($id){
  594.                 return \Pimcore\Model\Element\Tag::getById($id);
  595.             }, $tags));
  596.         }
  597.         return $this->json(["status" =>  true ]);
  598.     }
  599.     /**
  600.      * @Route("/promemoria/api/bucaSelect", methods={"POST"})
  601.      * @param Request $request
  602.      *
  603.      * @return JsonResponse
  604.      */
  605.     public function bucaSelect(Request $request)
  606.     {
  607.         $pimcoreUser Authentication::authenticateSession();
  608.         if(empty($pimcoreUser)){
  609.             $response = new Response();
  610.             $response->setStatusCode(401);
  611.             return $response;
  612.         }
  613.         $data json_decode($request->getContent());
  614.         $classe "\Pimcore\Model\DataObject\\" $data->class;
  615.         $obj = new $classe();
  616.         $fieldDefiniton $obj->getClass()->getFieldDefinition($data->field);
  617.         return $this->json($fieldDefiniton->getOptions());
  618.     }
  619.      /**
  620.      * @Route("/promemoria/api/bucaTags", methods={"POST"})
  621.      * @param Request $request
  622.      *
  623.      * @return JsonResponse
  624.      */
  625.     public function bucaTags(Request $request)
  626.     {
  627.         $pimcoreUser Authentication::authenticateSession();
  628.         if(empty($pimcoreUser)){
  629.             $response = new Response();
  630.             $response->setStatusCode(401);
  631.             return $response;
  632.         }
  633.         $data json_decode($request->getContent());
  634.         $tagList = new \Pimcore\Model\Element\Tag\Listing();
  635.         $tagList->setCondition("parentId = ?"$data->parentId);
  636.         $tagList->setOrderKey("id");
  637.         $tags = [];
  638.         foreach ($tagList->load() as $tag) {
  639.             $tags[] = [
  640.                 "id" => $tag->getId(),
  641.                 "label" => $tag->getName()
  642.             ];
  643.         }
  644.         return $this->json($tags);
  645.     }
  646.     /**
  647.      * @Route("/promemoria/api/check-email", methods={"POST"}))
  648.      * @param Request $request
  649.      *
  650.      * @return JsonResponse
  651.      */
  652.     public function checkEmail(Request $request)
  653.     {
  654.         $response = new Response();
  655.         $response->setStatusCode(400);
  656.         $data json_decode($request->getContent());
  657.         if(empty($data->email)){
  658.             return $response;
  659.         }
  660.         $user false;
  661.         $entries = new \Pimcore\Model\User\Listing();
  662.         $entries->setLimit(1);
  663.         $entries->setCondition("email LIKE ?", [$data->email]);
  664.         foreach ($entries as $entry) {
  665.             $user $entry;
  666.             return $this->json([
  667.                 'status' => true
  668.             ]);
  669.         }
  670.         return $response;
  671.     }
  672.     /**
  673.      * @Route("/promemoria/api/change-reset-password", methods={"POST"}))
  674.      * @param Request $request
  675.      *
  676.      * @return JsonResponse
  677.      */
  678.     public function changeResetPassword(Request $request)
  679.     {
  680.         $response = new Response();
  681.         $response->setStatusCode(400);
  682.         $data json_decode($request->getContent());
  683.         if(empty($data->email) || empty($data->password)){
  684.             return $response;
  685.         }
  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.             $user->setPassword(Authentication::getPasswordHash($user->getUsername(), $data->password));
  692.             $user->save();
  693.             return $this->json([
  694.                 'status' => true
  695.             ]);
  696.         }
  697.         return $response;
  698.     }
  699.     /* PRIVATE */
  700.     private function clearExpiredShortUrls()
  701.     {
  702.         $db \Pimcore\Db::get();
  703.         $db->deleteWhere('promemoria_shorturl''insertDate < NOW() - INTERVAL 1 WEEK');
  704.     }
  705.     private function createFolder($name$parent$type 'object'){
  706.         $folder $type === 'object' ? new \Pimcore\Model\DataObject\Folder() : new \Pimcore\Model\Asset\Folder();
  707.         $folder->setParentId($parent);
  708.         $type === 'object'  $folder->setKey($name) : $folder->setFilename($name);
  709.         $folder->save();
  710.         return $folder;
  711.     }
  712.     private function createAsset($parentAsset$file$type=""$metadati = []){
  713.         $newAsset $type ? new \Pimcore\Model\Asset\Image() : new \Pimcore\Model\Asset();
  714.         $newAsset->setFilename($this->checkFileAndRename($parentAsset->getFullPath(), $file->getClientOriginalName()));
  715.         $newAsset->setData(file_get_contents($file->getPathname()));
  716.         $newAsset->setParent($parentAsset);
  717.         if(!empty($metadati)){
  718.             foreach ($metadati as $key => $value) {
  719.                 $newAsset->addMetadata($key"input"$value);
  720.             }
  721.         }
  722.         $newAsset->save();
  723.         return $newAsset;
  724.     }
  725.     private function checkFileAndRename($parentPath$filename){
  726.         $path_parts pathinfo($filename);
  727.         $i 1;
  728.         while(\Pimcore\Model\Asset::getByPath($parentPath "/" $filename)){
  729.             $filename $path_parts['filename'] . "_$i." $path_parts['extension'];
  730.             $i++;
  731.         }
  732.         return $filename;
  733.     }
  734.     private function getThumb($image$type$original=false){
  735.         $thumb $this->getThumbnail($image"watermarked_" $type);
  736.         if(!$thumb || empty($thumb->getConfig())) {
  737.             $thumb $this->getThumbnail($image$type);
  738.         }
  739.         if(!$thumb || empty($thumb->getConfig())){
  740.             if($original) return $image;
  741.             $thumb $this->getThumbnail($imageAsset\Image\Thumbnail\Config::getPreviewConfig());
  742.         }
  743.         return $thumb;
  744.     }
  745.     private function getThumbnail($image$type){
  746.         try{
  747.             return $image->getThumbnail($type);
  748.         }catch(\Exception $err){
  749.             return null;
  750.         }
  751.     }
  752.     private function addThumbnailCacheHeaders(Response $response)
  753.     {
  754.        $lifetime 300;
  755.         $date = new \DateTime('now');
  756.         $date->add(new \DateInterval('PT' $lifetime 'S'));
  757.         $response->setMaxAge($lifetime);
  758.         $response->setPublic();
  759.         $response->setExpires($date);
  760.         $response->headers->set('Access-Control-Allow-Origin''*');
  761.     }
  762.     private function checkHash($id){
  763.         list($id$hash) = explode("-"$id);
  764.         return $hash === substr(md5($id md5(getenv("dotenv_suffix"))), 08);
  765.     }
  766. }