src/EventListener/MembersListener.php line 219

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Message\ManualRegistrationMessage;
  4. use App\Services\Functions;
  5. use App\Services\PromoGetter;
  6. use App\StripeManager\CreateCustomer;
  7. use Pimcore\Event\Model\ElementEventInterface;
  8. use Pimcore\Event\Model\DataObjectEvent;
  9. use Pimcore\Log\ApplicationLogger;
  10. use Pimcore\Model\Asset;
  11. use Pimcore\Model\DataObject\MembersUser;
  12. use Symfony\Component\Messenger\MessageBusInterface;
  13. use Carbon\Carbon;
  14. use Exception;
  15. use Pimcore\Log\Simple;
  16. use Pimcore\Model\DataObject\Service;
  17. use Pimcore\Model\DataObject\Folder;
  18. use Pimcore\Model\DataObject\MemberStripeAccount;
  19. use Pimcore\Model\DataObject\PromoRules;
  20. class MembersListener
  21. {
  22.     private $bus;
  23.     private $logger;
  24.     public function __construct(MessageBusInterface $busApplicationLogger $logger)
  25.     {
  26.         $this->bus $bus;
  27.         $this->logger $logger;
  28.     }
  29.     public function onPreAdd(ElementEventInterface $e)
  30.     {
  31.         if ($e instanceof DataObjectEvent) {
  32.             $object $e->getObject();
  33.             if ($object instanceof MembersUser) {
  34.                 $bytes openssl_random_pseudo_bytes(4);
  35.                 $pwd bin2hex($bytes);
  36.                 // $group = \Pimcore\Model\DataObject\MembersGroup::getByName('Subscriber',1);
  37.                 if (empty($object->getPassword())) {
  38.                     $object->setPassword($pwd);
  39.                     $object->setTempPlainPwd($pwd);
  40.                 } else {
  41.                     $object->setTempPlainPwd($object->getPassword());
  42.                 }
  43.                 $object->setActive(false);
  44.                 $object->setCreatedDate(Carbon::now());
  45.                 $object->setLastUpdateDate(Carbon::now());
  46.                 //                $object->setGroups([$group]);
  47.             }
  48.         }
  49.     }
  50.     public function onPreUpdate(ElementEventInterface $e)
  51.     {
  52.         if ($e instanceof DataObjectEvent) {
  53.             $object $e->getObject();
  54.             if ($object instanceof \Pimcore\Model\DataObject\MembersUser) {
  55.                 try {
  56.                     if (!empty($object->getSource()) && $object->getActive()) {
  57.                         // $object->setStripeCustomerId($customerStripeId);
  58.                         $source $object->getSource();
  59.                         if ($source !== null) {
  60.                             $MemberStripeAccount = new MemberStripeAccount\Listing();
  61.                             $MemberStripeAccount->setUnpublished(true);
  62.                             $MemberStripeAccount->setCondition('customerId = ? AND source__id = ?', [
  63.                                 $object->getId(),
  64.                                 $object->getSource()->getId()
  65.                             ]);
  66.                             $MemberStripeAccount->setLimit(1);
  67.                             $stripeDataObj $MemberStripeAccount->current();
  68.                             if ($stripeDataObj == null || null == ($customerStripeId $stripeDataObj->getStripeCustomerId())) {
  69.                                 $customerStripeId CreateCustomer::add($object);
  70.                             }
  71.                             if (!empty($customerStripeId)) {
  72.                                 $folder Folder::getByPath(PIMCORE_MEMBER_STRIPE_ACCOUNT_FOLDER);
  73.                                 if (!($folder instanceof Folder))
  74.                                     $folder Service::createFolderByPath(PIMCORE_MEMBER_STRIPE_ACCOUNT_FOLDER);
  75.                                 if ($stripeDataObj == null) {
  76.                                     $stripeDataObj = new MemberStripeAccount();
  77.                                     $stripeDataObj->setKey($object->getId() . '_' $customerStripeId);
  78.                                     $stripeDataObj->setParent($folder);
  79.                                 }
  80.                                 $stripeDataObj->setCustomerId($object->getId());
  81.                                 $stripeDataObj->setSource($source);
  82.                                 $stripeDataObj->setStripeCustomerId($customerStripeId);
  83.                                 $stripeDataObj->setPublished(true);
  84.                                 $stripeDataObj->save();
  85.                                 $object->setSource(null);
  86.                                 $object->setStripeCustomerId(null);
  87.                                 $object->setStripeData($this->getUserSourceList($object));
  88.                             }
  89.                         }
  90.                     }
  91.                     /**  $pathConvention could be "/restricted-assets/{MembersKey}-{MembersUsername}" */
  92.                     $pathConvention Functions::getPathConvention([$object->getKey(), $object->getUserName()]);
  93.                     // Check Asset folder
  94.                     $storeAssetsFolder Asset\Folder::getByPath($pathConvention);
  95.                     if (!($storeAssetsFolder instanceof Asset\Folder))
  96.                         $storeAssetsFolder Asset\Service::createFolderByPath($pathConvention);
  97.                     // Check and move Gallery Images
  98.                     foreach ($object->getDocuments() as $document) {
  99.                         if ($document instanceof Asset) {
  100.                             $document Functions::moveAssetToFolder($document$storeAssetsFolder);
  101.                         }
  102.                     }
  103.                     $promos PromoRules::getById($object->getRules());
  104.                     if (!empty($promos)) {
  105.                         $promoTable = [];
  106.                         foreach ($promos->getPromo() as $i => $promo) {
  107.                             $priceObj $promo['price']->getData();
  108.                             $price $priceObj->getPriceId();
  109.                             $promotionObj $promo['promo']->getData();
  110.                             $promotion $promotionObj->getPromoId();
  111.                             $promoTable[$i][] = $price;
  112.                             $promoTable[$i][] = $promotion;
  113.                         }
  114.                         $msa = new MemberStripeAccount\Listing();
  115.                         $msa->setCondition('customerId = ? AND source__id = ?', [
  116.                             $object->getId(),
  117.                             $promos->getAccount()
  118.                         ]);
  119.                         $msa $msa->current();
  120.                         try {
  121.                             if ($promoTable && $msa !== false) {
  122.                                 $msa->setPromoCode($promoTable);
  123.                                 $msa->save();
  124.                                 $object->setRules(null);
  125.                             }
  126.                         } catch (Exception $e) {
  127.                             $this->logger->error($e->getMessage());
  128.                         }
  129.                         // $object->setRules(null);
  130.                     }
  131.                 } catch (\Exception $e) {
  132.                     $this->logger->error($e->getMessage());
  133.                 }
  134.             }
  135.         }
  136.     }
  137.     private function getUserSourceList($object)
  138.     {
  139.         return MemberStripeAccount::getByCustomerId($object->getId())->getData();
  140.     }
  141.     public function onPostUpdate(ElementEventInterface $e)
  142.     {
  143.         try {
  144.             if ($e instanceof DataObjectEvent) {
  145.                 $object $e->getObject();
  146.                 if ($object instanceof MembersUser) {
  147.                     if ($object->getStripeData()) {
  148.                         foreach ($object->getStripeData() as $stripeAccount) {
  149.                             if ($stripeAccount->getSource()->getServiceEndpoint()?->getHref()) {
  150.                                 $promoCodes PromoGetter::getUserPromoCodes($stripeAccount->getSource()->getObjectKey(), $object);
  151.                                 if (isset($object->getGroups()[0])) {
  152.                                     $this->updateUser($object->getEmail(), $object->getPassword(), $object->getGroups()[0]->getName(), $object->getActive(), $stripeAccount->getSource()->getServiceEndpoint()->getHref(), $promoCodes);
  153.                                 } else {
  154.                                     $this->logger->warning("Missing group " $object->getId());
  155.                                 }
  156.                             }
  157.                         }
  158.                     } elseif ($object->getSource()) {
  159.                         $promoCodes PromoGetter::getUserPromoCodes($object->getSource()->getObjectKey(), $object);
  160.                         if (isset($object->getGroups()[0])) {
  161.                             $this->updateUser($object->getEmail(), $object->getPassword(), $object->getGroups()[0]->getName(), $object->getActive(), $object->getSource()->getServiceEndpoint()->getHref(), $promoCodes);
  162.                         } else {
  163.                             $this->logger->warning("Missing group " $object->getId());
  164.                         }
  165.                     }
  166.                     if (empty($object->getMailSent()) && empty($object->getLastLogin()) && $object->getActive()) {
  167.                         $this->logger->info('Invio mail registrazione');
  168.                         $this->bus->dispatch(new ManualRegistrationMessage($object));
  169.                     }
  170.                     if ($object->getActive() && $object->getSource()) {
  171.                         $promoCodes PromoGetter::getUserPromoCodes($object->getSource()->getObjectKey(), $object);
  172.                         if (isset($object->getGroups()[0])) {
  173.                             $this->registrationToServicePortal($object->getUserName(), $object->getTempPlainPwd(), $object->getGroups()[0]->getName(), $object->getSource()->getServiceEndpoint()->getHref(), $promoCodes);
  174.                         } else {
  175.                             $this->logger->warning("Missing group " $object->getId());
  176.                         }
  177.                         // $object->setSource(null);
  178.                         // $object->save();
  179.                     }
  180.                 }
  181.             }
  182.         } catch (\Exception $e) {
  183.             $this->logger->error($e);
  184.         }
  185.     }
  186.     public function onPostAdd(ElementEventInterface $e)
  187.     {
  188.         //        if ($e instanceof DataObjectEvent) {
  189.         //            $object = $e->getObject();
  190.         //
  191.         //            if($object instanceof MembersUser){
  192.         //                if (empty($object->getMailSent())) {
  193.         //                    if ($object->getActive() && !empty($object->getTempPlainPwd())){
  194.         //                        $this->bus->dispatch(new ManualRegistrationMessage($object));
  195.         //                    }
  196.         //                }
  197.         //            }
  198.         //        }
  199.     }
  200.     public function onPostDelete(ElementEventInterface $e)
  201.     {
  202.         if ($e instanceof DataObjectEvent) {
  203.             $object $e->getObject();
  204.             if ($object instanceof MembersUser) {
  205.                 $userStripeAccounts MemberStripeAccount::getByCustomerId($object->getId());
  206.                 foreach ($userStripeAccounts as $userStripeAccount) {
  207.                     $userStripeAccount->delete();
  208.                 }
  209.             }
  210.         }
  211.     }
  212.     public function onRegistrationConfirm(\MembersBundle\Event\GetResponseUserEvent $e)
  213.     {
  214.         try {
  215.             $object $e->getUser();
  216.             if ($object instanceof MembersUser) {
  217.                 $object->setActive(true);
  218.                 $promoCodes PromoGetter::getUserPromoCodes($object->getSource()->getObjectKey(), $object);
  219.                 $this->registrationToServicePortal($object->getUserName(), $object->getTempPlainPwd(), $object->getGroups()[0]->getName(), $object->getSource()->getServiceEndpoint()->getHref(), $promoCodes);
  220.                 // $object->setSource(null);
  221.                 // $object->save();
  222.             }
  223.         } catch (\Exception $e) {
  224.             $this->logger->error($e);
  225.         }
  226.     }
  227.     private function updateUser($user$password$type$active$endpoint$promo)
  228.     {
  229.         try {
  230.             $data = array(
  231.                 'email' => $user,
  232.                 'pwd' => $password,
  233.                 'type' => $type,
  234.                 'active' => $active 0,
  235.                 'authorizationKey' => '9825ec00fe638ad48591b0016c1916f4484aa3683168c8dcb97174bb86894d55',
  236.                 'promo' => serialize($promo)
  237.             );
  238.             $agent 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)';
  239.             $json json_encode($data);
  240.             $curl curl_init();
  241.             curl_setopt_array($curl, array(
  242.                 CURLOPT_URL => $endpoint '/api/updateUser',
  243.                 CURLOPT_RETURNTRANSFER => true,
  244.                 CURLOPT_ENCODING => '',
  245.                 CURLOPT_USERAGENT => $agent,
  246.                 CURLOPT_MAXREDIRS => 10,
  247.                 CURLOPT_TIMEOUT => 0,
  248.                 CURLOPT_FOLLOWLOCATION => true,
  249.                 CURLOPT_VERBOSE => false,
  250.                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  251.                 CURLOPT_CUSTOMREQUEST => 'POST',
  252.                 CURLOPT_POSTFIELDS => $json,
  253.                 CURLOPT_HTTPHEADER => array(
  254.                     'Content-Type: application/json',
  255.                     'Content-Length: ' strlen($json)
  256.                 ),
  257.             ));
  258.             $response curl_exec($curl);
  259.             $result json_decode($responsetrue);
  260.             if ($result === false || empty($result)) {
  261.                 $this->logger->error(curl_error($curl));
  262.                 return false;
  263.             }
  264.             if ($result['error']) {
  265.                 $this->logger->error($result);
  266.             }
  267.             curl_close($curl);
  268.             $this->logger->info($response);
  269.             // return $response && $response['success'] == false ? false : true;
  270.         } catch (\Exception $e) {
  271.             $this->logger->error($e);
  272.             return false;
  273.         }
  274.     }
  275.     private function registrationToServicePortal($user$password$type$endpoint$promo)
  276.     {
  277.         try {
  278.             $data = array(
  279.                 'email' => $user,
  280.                 'pwd' => $password,
  281.                 'type' => $type,
  282.                 'authorizationKey' => '9825ec00fe638ad48591b0016c1916f4484aa3683168c8dcb97174bb86894d55',
  283.                 'promo' => serialize($promo)
  284.             );
  285.             $agent 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)';
  286.             $json json_encode($data);
  287.             $curl curl_init();
  288.             Simple::log('member'$endpoint '/api/userRegistration');
  289.             curl_setopt_array($curl, array(
  290.                 CURLOPT_URL => $endpoint '/api/userRegistration',
  291.                 CURLOPT_RETURNTRANSFER => true,
  292.                 CURLOPT_ENCODING => '',
  293.                 CURLOPT_USERAGENT => $agent,
  294.                 CURLOPT_MAXREDIRS => 10,
  295.                 CURLOPT_TIMEOUT => 0,
  296.                 CURLOPT_FOLLOWLOCATION => true,
  297.                 CURLOPT_VERBOSE => false,
  298.                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  299.                 CURLOPT_CUSTOMREQUEST => 'POST',
  300.                 CURLOPT_POSTFIELDS => $json,
  301.                 CURLOPT_HTTPHEADER => array(
  302.                     'Content-Type: application/json',
  303.                     'Content-Length: ' strlen($json)
  304.                 ),
  305.             ));
  306.             $response curl_exec($curl);
  307.             $result json_decode($responsetrue);
  308.             if ($result === false || empty($result)) {
  309.                 throw new Exception(curl_error($curl), curl_errno($curl));
  310.             }
  311.             if ($result['error']) {
  312.                 $this->logger->error($result);
  313.             }
  314.             curl_close($curl);
  315.             // return $response && $response['success'] == false ? false : true;
  316.         } catch (\Exception $e) {
  317.             $this->logger->error($e->getMessage());
  318.             return false;
  319.         }
  320.     }
  321. }