protected function execute(InputInterface $input, OutputInterface $output)
 {
     // get all thumbnails
     $dir = Asset\Image\Thumbnail\Config::getWorkingDir();
     $thumbnails = array();
     $files = scandir($dir);
     foreach ($files as $file) {
         if (strpos($file, ".xml")) {
             $thumbnails[] = str_replace(".xml", "", $file);
         }
     }
     $allowedThumbs = array();
     if ($input->getOption("thumbnails")) {
         $allowedThumbs = explode(",", $input->getOption("thumbnails"));
     }
     // get only images
     $conditions = array("type = 'image'");
     if ($input->getOption("parent")) {
         $parent = Asset::getById($input->getOption("parent"));
         if ($parent instanceof Asset\Folder) {
             $conditions[] = "path LIKE '" . $parent->getFullPath() . "/%'";
         } else {
             $this->writeError($input->getOption("parent") . " is not a valid asset folder ID!");
             exit;
         }
     }
     $list = new Asset\Listing();
     $list->setCondition(implode(" AND ", $conditions));
     $total = $list->getTotalCount();
     $perLoop = 10;
     for ($i = 0; $i < ceil($total / $perLoop); $i++) {
         $list->setLimit($perLoop);
         $list->setOffset($i * $perLoop);
         $images = $list->load();
         foreach ($images as $image) {
             foreach ($thumbnails as $thumbnail) {
                 if (empty($allowedThumbs) && !$input->getOption("system") || in_array($thumbnail, $allowedThumbs)) {
                     if ($input->getOption("force")) {
                         $image->clearThumbnail($thumbnail);
                     }
                     $this->output->writeln("generating thumbnail for image: " . $image->getFullpath() . " | " . $image->getId() . " | Thumbnail: " . $thumbnail . " : " . formatBytes(memory_get_usage()));
                     $this->output->writeln("generated thumbnail: " . $image->getThumbnail($thumbnail));
                 }
             }
             if ($input->getOption("system")) {
                 $thumbnail = Asset\Image\Thumbnail\Config::getPreviewConfig();
                 if ($input->getOption("force")) {
                     $image->clearThumbnail($thumbnail->getName());
                 }
                 $this->output->writeln("generating thumbnail for image: " . $image->getFullpath() . " | " . $image->getId() . " | Thumbnail: System Preview (tree) : " . formatBytes(memory_get_usage()));
                 $this->output->writeln("generated thumbnail: " . $image->getThumbnail($thumbnail));
             }
         }
         \Pimcore::collectGarbage();
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // clear all data
     $db = \Pimcore\Db::get();
     $db->query("TRUNCATE `search_backend_data`;");
     $elementsPerLoop = 100;
     $types = ["asset", "document", "object"];
     foreach ($types as $type) {
         $listClassName = "\\Pimcore\\Model\\" . ucfirst($type) . "\\Listing";
         $list = new $listClassName();
         if (method_exists($list, "setUnpublished")) {
             $list->setUnpublished(true);
         }
         $elementsTotal = $list->getTotalCount();
         for ($i = 0; $i < ceil($elementsTotal / $elementsPerLoop); $i++) {
             $list->setLimit($elementsPerLoop);
             $list->setOffset($i * $elementsPerLoop);
             $this->output->writeln("Processing " . $type . ": " . ($list->getOffset() + $elementsPerLoop) . "/" . $elementsTotal);
             $elements = $list->load();
             foreach ($elements as $element) {
                 try {
                     $searchEntry = Search\Backend\Data::getForElement($element);
                     if ($searchEntry instanceof Search\Backend\Data and $searchEntry->getId() instanceof Search\Backend\Data\Id) {
                         $searchEntry->setDataFromElement($element);
                     } else {
                         $searchEntry = new Search\Backend\Data($element);
                     }
                     $searchEntry->save();
                 } catch (\Exception $e) {
                     Logger::err($e);
                 }
             }
             \Pimcore::collectGarbage();
         }
     }
     $db->query("OPTIMIZE TABLE search_backend_data;");
 }
$elementsPerLoop = 100;
$types = array("asset", "document", "object");
foreach ($types as $type) {
    $listClassName = "\\Pimcore\\Model\\" . ucfirst($type) . "\\Listing";
    $list = new $listClassName();
    if (method_exists($list, "setUnpublished")) {
        $list->setUnpublished(true);
    }
    $elementsTotal = $list->getTotalCount();
    for ($i = 0; $i < ceil($elementsTotal / $elementsPerLoop); $i++) {
        $list->setLimit($elementsPerLoop);
        $list->setOffset($i * $elementsPerLoop);
        echo "Processing " . $type . ": " . ($list->getOffset() + $elementsPerLoop) . "/" . $elementsTotal . "\n";
        $elements = $list->load();
        foreach ($elements as $element) {
            try {
                $searchEntry = Search\Backend\Data::getForElement($element);
                if ($searchEntry instanceof Search\Backend\Data and $searchEntry->getId() instanceof Search\Backend\Data_Id) {
                    $searchEntry->setDataFromElement($element);
                } else {
                    $searchEntry = new Search\Backend\Data($element);
                }
                $searchEntry->save();
            } catch (Exception $e) {
                \Logger::err($e);
            }
        }
        \Pimcore::collectGarbage();
    }
}
$db->query("OPTIMIZE TABLE search_backend_data;");
Beispiel #4
0
 /**
  *
  */
 public function maintenanceCleanUp()
 {
     $conf["document"] = Config::getSystemConfig()->documents->versions;
     $conf["asset"] = Config::getSystemConfig()->assets->versions;
     $conf["object"] = Config::getSystemConfig()->objects->versions;
     $elementTypes = array();
     foreach ($conf as $elementType => $tConf) {
         if (intval($tConf->days) > 0) {
             $versioningType = "days";
             $value = intval($tConf->days);
         } else {
             $versioningType = "steps";
             $value = intval($tConf->steps);
         }
         if ($versioningType) {
             $elementTypes[] = array("elementType" => $elementType, $versioningType => $value);
         }
     }
     $ignoredIds = array();
     while (true) {
         $versions = $this->getDao()->maintenanceGetOutdatedVersions($elementTypes, $ignoredIds);
         if (count($versions) == 0) {
             break;
         }
         $counter = 0;
         \Logger::debug("versions to check: " . count($versions));
         if (is_array($versions) && !empty($versions)) {
             $totalCount = count($versions);
             foreach ($versions as $index => $id) {
                 try {
                     $version = Version::getById($id);
                 } catch (\Exception $e) {
                     $ignoredIds[] = $id;
                     \Logger::debug("Version with " . $id . " not found\n");
                     continue;
                 }
                 $counter++;
                 // do not delete public versions
                 if ($version->getPublic()) {
                     $ignoredIds[] = $version->getId();
                     continue;
                 }
                 if ($version->getCtype() == "document") {
                     $element = Document::getById($version->getCid());
                 } elseif ($version->getCtype() == "asset") {
                     $element = Asset::getById($version->getCid());
                 } elseif ($version->getCtype() == "object") {
                     $element = Object::getById($version->getCid());
                 }
                 if ($element instanceof ElementInterface) {
                     \Logger::debug("currently checking Element-ID: " . $element->getId() . " Element-Type: " . Element\Service::getElementType($element) . " in cycle: " . $counter . "/" . $totalCount);
                     if ($element->getModificationDate() >= $version->getDate()) {
                         // delete version if it is outdated
                         \Logger::debug("delete version: " . $version->getId() . " because it is outdated");
                         $version->delete();
                     } else {
                         $ignoredIds[] = $version->getId();
                         \Logger::debug("do not delete version (" . $version->getId() . ") because version's date is newer than the actual modification date of the element. Element-ID: " . $element->getId() . " Element-Type: " . Element\Service::getElementType($element));
                     }
                 } else {
                     // delete version if the corresponding element doesn't exist anymore
                     \Logger::debug("delete version (" . $version->getId() . ") because the corresponding element doesn't exist anymore");
                     $version->delete();
                 }
                 // call the garbage collector if memory consumption is > 100MB
                 if (memory_get_usage() > 100000000) {
                     \Pimcore::collectGarbage();
                 }
             }
         }
     }
 }
 /**
  * @param $elementTypes
  * @return array
  */
 public function maintenanceGetOutdatedVersions($elementTypes, $ignoreIds = array())
 {
     $ignoreIdsList = implode(",", $ignoreIds);
     if (!$ignoreIdsList) {
         $ignoreIdsList = "0";
         // set a default to avoid SQL errors (there's no version with ID 0)
     }
     $versionIds = array();
     \Logger::debug("ignore ID's: " . $ignoreIdsList);
     if (!empty($elementTypes)) {
         $count = 0;
         $stop = false;
         foreach ($elementTypes as $elementType) {
             if ($elementType["days"] > 0) {
                 // by days
                 $deadline = time() - $elementType["days"] * 86400;
                 $tmpVersionIds = $this->db->fetchCol("SELECT id FROM versions as a WHERE (ctype = ? AND date < ?) AND NOT public AND id NOT IN (" . $ignoreIdsList . ")", array($elementType["elementType"], $deadline));
                 $versionIds = array_merge($versionIds, $tmpVersionIds);
             } else {
                 // by steps
                 $elementIds = $this->db->fetchCol("SELECT cid,count(*) as amount FROM versions WHERE ctype = ? AND NOT public AND id NOT IN (" . $ignoreIdsList . ") GROUP BY cid HAVING amount > ?", array($elementType["elementType"], $elementType["steps"]));
                 foreach ($elementIds as $elementId) {
                     $count++;
                     \Logger::info($elementId . "(object " . $count . ") Vcount " . count($versionIds));
                     $elementVersions = $this->db->fetchCol("SELECT id FROM versions WHERE cid = ? and ctype = ? ORDER BY date DESC LIMIT " . $elementType["steps"] . ",1000000", array($elementId, $elementType["elementType"]));
                     $versionIds = array_merge($versionIds, $elementVersions);
                     // call the garbage collector if memory consumption is > 100MB
                     if (memory_get_usage() > 100000000 && $count % 100 == 0) {
                         \Pimcore::collectGarbage();
                         sleep(1);
                         $versionIds = array_unique($versionIds);
                     }
                     if (count($versionIds) > 1000) {
                         $stop = true;
                         break;
                     }
                 }
                 $versionIds = array_unique($versionIds);
                 if ($stop) {
                     break;
                 }
             }
         }
     }
     \Logger::info("return " . count($versionIds) . " ids\n");
     return $versionIds;
 }
function waitTillFinished($videoId, $thumbnail)
{
    $finished = false;
    // initial delay
    $video = Asset::getById($videoId);
    $thumb = $video->getThumbnail($thumbnail);
    if ($thumb["status"] != "finished") {
        sleep(20);
    }
    while (!$finished) {
        \Pimcore::collectGarbage();
        $video = Asset::getById($videoId);
        $thumb = $video->getThumbnail($thumbnail);
        if ($thumb["status"] == "finished") {
            $finished = true;
            \Logger::debug("video [" . $video->getId() . "] FINISHED");
        } else {
            if ($thumb["status"] == "inprogress") {
                $progress = Asset\Video\Thumbnail\Processor::getProgress($thumb["processId"]);
                \Logger::debug("video [" . $video->getId() . "] in progress: " . number_format($progress, 0) . "%");
                sleep(5);
            } else {
                // error
                \Logger::debug("video [" . $video->getId() . "] has status: '" . $thumb["status"] . "' -> skipping");
                break;
            }
        }
    }
}
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $newsletter = Model\Tool\Newsletter\Config::getByName($input->getArgument("id"));
     if ($newsletter) {
         $pidFile = $newsletter->getPidFile();
         if (file_exists($pidFile)) {
             \Logger::alert("Cannot send newsletters because there's already one active sending process");
             exit;
         }
         $elementsPerLoop = 10;
         $objectList = "\\Pimcore\\Model\\Object\\" . ucfirst($newsletter->getClass()) . "\\Listing";
         $list = new $objectList();
         $conditions = array("(newsletterActive = 1 AND newsletterConfirmed = 1)");
         if ($newsletter->getObjectFilterSQL()) {
             $conditions[] = $newsletter->getObjectFilterSQL();
         }
         if ($newsletter->getPersonas()) {
             $class = Model\Object\ClassDefinition::getByName($newsletter->getClass());
             if ($class && $class->getFieldDefinition("persona")) {
                 $personas = array();
                 $p = explode(",", $newsletter->getPersonas());
                 if ($class->getFieldDefinition("persona") instanceof \Pimcore\Model\Object\ClassDefinition\Data\Persona) {
                     foreach ($p as $value) {
                         if (!empty($value)) {
                             $personas[] = $list->quote($value);
                         }
                     }
                     $conditions[] = "persona IN (" . implode(",", $personas) . ")";
                 } else {
                     if ($class->getFieldDefinition("persona") instanceof \Pimcore\Model\Object\ClassDefinition\Data\Personamultiselect) {
                         $personasCondition = array();
                         foreach ($p as $value) {
                             $personasCondition[] = "persona LIKE " . $list->quote("%," . $value . ",%");
                         }
                         $conditions[] = "(" . implode(" OR ", $personasCondition) . ")";
                     }
                 }
             }
         }
         $list->setCondition(implode(" AND ", $conditions));
         $list->setOrderKey("email");
         $list->setOrder("ASC");
         $elementsTotal = $list->getTotalCount();
         $count = 0;
         $pidContents = array("start" => time(), "lastUpdate" => time(), "newsletter" => $newsletter->getName(), "total" => $elementsTotal, "current" => $count);
         $this->writePid($pidFile, $pidContents);
         for ($i = 0; $i < ceil($elementsTotal / $elementsPerLoop); $i++) {
             $list->setLimit($elementsPerLoop);
             $list->setOffset($i * $elementsPerLoop);
             $objects = $list->load();
             foreach ($objects as $object) {
                 try {
                     $count++;
                     \Logger::info("Sending newsletter " . $count . " / " . $elementsTotal . " [" . $newsletter->getName() . "]");
                     \Pimcore\Tool\Newsletter::sendMail($newsletter, $object, null, $input->getArgument("hostUrl"));
                     $note = new Model\Element\Note();
                     $note->setElement($object);
                     $note->setDate(time());
                     $note->setType("newsletter");
                     $note->setTitle("sent newsletter: '" . $newsletter->getName() . "'");
                     $note->setUser(0);
                     $note->setData(array());
                     $note->save();
                     \Logger::info("Sent newsletter to: " . $this->obfuscateEmail($object->getEmail()) . " [" . $newsletter->getName() . "]");
                 } catch (\Exception $e) {
                     \Logger::err($e);
                 }
             }
             // check if pid exists
             if (!file_exists($pidFile)) {
                 \Logger::alert("Newsletter PID not found, cancel sending process");
                 exit;
             }
             // update pid
             $pidContents["lastUpdate"] = time();
             $pidContents["current"] = $count;
             $this->writePid($pidFile, $pidContents);
             \Pimcore::collectGarbage();
         }
         // remove pid
         @unlink($pidFile);
     } else {
         \Logger::emerg("Newsletter '" . $input->getArgument("id") . "' doesn't exist");
     }
 }
 public function sitemapAction()
 {
     set_time_limit(900);
     $this->view->initial = false;
     if ($this->getParam("doc")) {
         $doc = $this->getParam("doc");
     } else {
         $doc = $this->document->getProperty("mainNavStartNode");
         $this->view->initial = true;
     }
     Pimcore::collectGarbage();
     $this->view->doc = $doc;
 }
Beispiel #9
0
 /**
  * @param AbstractListing $list
  */
 protected static function loadToCache(AbstractListing $list)
 {
     $totalCount = $list->getTotalCount();
     $iterations = ceil($totalCount / self::getPerIteration());
     \Logger::info("New list of elements queued for storing into the cache with " . $iterations . " iterations and " . $totalCount . " total items");
     for ($i = 0; $i < $iterations; $i++) {
         \Logger::info("Starting iteration " . $i . " with offset: " . self::getPerIteration() * $i);
         $list->setLimit(self::getPerIteration());
         $list->setOffset(self::getPerIteration() * $i);
         $elements = $list->load();
         foreach ($elements as $element) {
             $cacheKey = Element\Service::getElementType($element) . "_" . $element->getId();
             Cache::storeToCache($element, $cacheKey, [], null, null, true);
         }
         \Pimcore::collectGarbage();
         sleep(self::getTimoutBetweenIteration());
     }
 }
Beispiel #10
0
 /**
  * Save document and all child documents
  *
  * @param     $document
  * @param int $collectGarbageAfterIteration
  * @param int $saved
  */
 public static function saveRecursive($document, $collectGarbageAfterIteration = 25, &$saved = 0)
 {
     if ($document instanceof Document) {
         $document->save();
         $saved++;
         if ($saved % $collectGarbageAfterIteration === 0) {
             \Pimcore::collectGarbage();
         }
     }
     foreach ($document->getChilds() as $child) {
         if (!$child->hasChilds()) {
             $child->save();
             $saved++;
             if ($saved % $collectGarbageAfterIteration === 0) {
                 \Pimcore::collectGarbage();
             }
         }
         if ($child->hasChilds()) {
             self::saveRecursive($child, $collectGarbageAfterIteration, $saved);
         }
     }
 }
Beispiel #11
0
 /**
  *
  */
 public function maintenanceCleanUp()
 {
     $conf["document"] = Pimcore_Config::getSystemConfig()->documents->versions;
     $conf["asset"] = Pimcore_Config::getSystemConfig()->assets->versions;
     $conf["object"] = Pimcore_Config::getSystemConfig()->objects->versions;
     $elementTypes = array();
     foreach ($conf as $elementType => $tConf) {
         if (intval($tConf->days) > 0) {
             $versioningType = "days";
             $value = intval($tConf->days);
         } else {
             $versioningType = "steps";
             $value = intval($tConf->steps);
         }
         if ($versioningType) {
             $elementTypes[] = array("elementType" => $elementType, $versioningType => $value);
         }
     }
     $versions = $this->getResource()->maintenanceGetOutdatedVersions($elementTypes);
     if (is_array($versions)) {
         foreach ($versions as $index => $id) {
             $version = Version::getById($id);
             if ($version->getCtype() == "document") {
                 $element = Document::getById($version->getCid());
             } else {
                 if ($version->getCtype() == "asset") {
                     $element = Asset::getById($version->getCid());
                 } else {
                     if ($version->getCtype() == "object") {
                         $element = Object_Abstract::getById($version->getCid());
                     }
                 }
             }
             if ($element instanceof Element_Interface) {
                 if ($element->getModificationDate() > $version->getDate()) {
                     // delete version if it is outdated
                     $version->delete();
                 }
             } else {
                 // delete version if the correspondening element doesn't exist anymore
                 $version->delete();
             }
             // call the garbage collector every 100 iterations, to avoid a out-of-memory
             if ($index % 100 == 0) {
                 Pimcore::collectGarbage();
             }
         }
     }
 }
Beispiel #12
0
 /**
  * Runs processUpdateIndexQueue for given tenants or for all tenants
  *
  * @param null $tenants
  * @param int $maxRounds - max rounds after process returns. null for infinite run until no work is left
  * @param string $loggername
  * @throws OnlineShop_Framework_Exception_InvalidConfigException
  */
 public static function processUpdateIndexQueue($tenants = null, $maxRounds = null, $loggername = "indexupdater")
 {
     if ($tenants == null) {
         $tenants = OnlineShop_Framework_Factory::getInstance()->getAllTenants();
     }
     if (!is_array($tenants)) {
         $tenants = array($tenants);
     }
     foreach ($tenants as $tenant) {
         self::log($loggername, "=========================");
         self::log($loggername, "Processing update index elements for tenant: " . $tenant);
         self::log($loggername, "=========================");
         $env = OnlineShop_Framework_Factory::getInstance()->getEnvironment();
         $env->setCurrentAssortmentTenant($tenant);
         $indexService = OnlineShop_Framework_Factory::getInstance()->getIndexService();
         $worker = $indexService->getCurrentTenantWorker();
         if ($worker instanceof OnlineShop_Framework_IndexService_Tenant_IBatchProcessingWorker) {
             $result = true;
             $round = 0;
             while ($result) {
                 $round++;
                 self::log($loggername, "Starting round: " . $round);
                 $result = $worker->processUpdateIndexQueue();
                 self::log($loggername, "processed update index elements: " . $result);
                 Pimcore::collectGarbage();
                 if ($maxRounds && $maxRounds == $round) {
                     self::log($loggername, "skipping process after {$round} rounds.");
                     return;
                 }
             }
         }
     }
 }
 protected function waitTillFinished($videoId, $thumbnail)
 {
     $finished = false;
     // initial delay
     $video = Asset::getById($videoId);
     $thumb = $video->getThumbnail($thumbnail);
     if ($thumb["status"] != "finished") {
         sleep(20);
     }
     while (!$finished) {
         \Pimcore::collectGarbage();
         $video = Asset::getById($videoId);
         $thumb = $video->getThumbnail($thumbnail);
         if ($thumb["status"] == "finished") {
             $finished = true;
             Logger::debug("video [" . $video->getId() . "] FINISHED");
         } elseif ($thumb["status"] == "inprogress") {
             Logger::debug("video [" . $video->getId() . "] in progress ...");
             sleep(5);
         } else {
             // error
             Logger::debug("video [" . $video->getId() . "] has status: '" . $thumb["status"] . "' -> skipping");
             break;
         }
     }
 }
 protected function doSendMailInSingleMode(Model\Document\Newsletter $document, AddressSourceAdapterInterface $addressAdapter, $sendingId)
 {
     $totalCount = $addressAdapter->getTotalRecordCount();
     //calculate page size based on total item count - with min page size 3 and max page size 10
     $fifth = $totalCount / 5;
     $limit = $fifth > 10 ? 10 : ($fifth < 3 ? 3 : intval($fifth));
     $offset = 0;
     $hasElements = true;
     while ($hasElements) {
         $tmpStore = Model\Tool\TmpStore::get($sendingId);
         $data = $tmpStore->getData();
         Logger::info("Sending newsletter " . $hasElements . " / " . $totalCount . " [" . $document->getId() . "]");
         $data['progress'] = round($offset / $totalCount * 100, 2);
         $tmpStore->setData($data);
         $tmpStore->update();
         $sendingParamContainers = $addressAdapter->getParamsForSingleSending($limit, $offset);
         foreach ($sendingParamContainers as $sendingParamContainer) {
             $mail = \Pimcore\Tool\Newsletter::prepareMail($document, $sendingParamContainer);
             \Pimcore\Tool\Newsletter::sendNewsletterDocumentBasedMail($mail, $sendingParamContainer);
             if (empty($tmpStore)) {
                 Logger::warn("Sending configuration for sending ID {$sendingId} was deleted. Cancelling sending process.");
                 exit;
             }
         }
         $offset += $limit;
         $hasElements = count($sendingParamContainers);
         \Pimcore::collectGarbage();
     }
 }
Beispiel #15
0
 /**
  * @param $shopConfigurations Object\OnlineShopConfiguration
  */
 public function import($shopConfigurations)
 {
     if ($shopConfigurations && !is_array($shopConfigurations)) {
         $shopConfigurations = array($shopConfigurations);
     }
     $pageSize = 20;
     $page = 0;
     /** @var  $shopConfiguration Object\OnlineShopConfiguration */
     foreach ($shopConfigurations as $shopConfiguration) {
         $importDirectory = $shopConfiguration->getTrustedShopReviewsimportDirectory();
         $startTime = time();
         if ($this->logToConsole) {
             echo "Importing reviews for " . $shopConfiguration->getFullPath() . " ...\n";
         }
         /** @var  $startDate Pimcore\Date */
         $startDate = $shopConfiguration->getLastSync();
         while (true) {
             if ($this->logToConsole) {
                 echo "Page=" . $page . "\n";
             }
             $uri = "https://%s:%s@api.trustedshops.com/rest/restricted/v2/shops/%s/reviews.json?page=" . $page . "&size=" . $pageSize;
             if ($startDate) {
                 $uri .= "&startDate=" . date('Y-m-d', $startDate->getTimestamp() - 3600 * 24 * 30);
                 //get ratins from last 30 days - for some reasons trusted shop sometimes dont show all ratings imediately
             }
             $uri = sprintf($uri, $shopConfiguration->getTrustedShopUser(), $shopConfiguration->getTrustedShopPassword(), $shopConfiguration->getTrustedShopKey());
             if ($this->logToConsole) {
                 echo $uri . "\n";
             }
             $this->client->setUri($uri);
             $result = $this->client->request();
             if ($result->getStatus() != 200) {
                 $this->logger->error("Status code " . $result->getStatus(), null, null, self::COMPONENT);
                 throw new \Exception("Status Code: " . $result->getStatus());
             }
             $body = $result->getBody();
             $data = json_decode($body);
             if (!$data) {
                 $this->logger->error("Could not decode data " . $body, null, null, self::COMPONENT);
                 throw new \Exception("Could not decode data");
             }
             $response = $data->response;
             $data = $response->data;
             $shop = $data->shop;
             if ($shop->tsId != $shopConfiguration->getTrustedShopKey()) {
                 $this->logger->error("Tsid mismatch", null, null, self::COMPONENT);
                 throw new \Exception("Tsid mismatch");
             }
             $reviews = $shop->reviews;
             foreach ((array) $reviews as $review) {
                 $uid = $review->UID;
                 $comment = $review->comment;
                 $criterias = $review->criteria;
                 $consumerEmail = $review->consumerEmail;
                 $mark = $review->mark;
                 $markDescription = $review->markDescription;
                 $orderReference = $review->orderReference;
                 $changeDate = $review->changeDate;
                 $creationDate = $review->creationDate;
                 $confirmationDate = $review->confirmationDate;
                 $changeDate = $changeDate ? strtotime($changeDate) : 0;
                 $creationDate = $creationDate ? strtotime($creationDate) : 0;
                 $confirmationDate = $confirmationDate ? strtotime($confirmationDate) : 0;
                 $fc = new Object\Fieldcollection();
                 foreach ($criterias as $criteria) {
                     $mark = $criteria->mark;
                     $criteriaMarkDescription = $criteria->markDescription;
                     $type = $criteria->type;
                     $item = new Object\Fieldcollection\Data\TrustedShopCriteria();
                     $item->setMark($mark);
                     $item->setMarkDescription($criteriaMarkDescription);
                     $item->setCriteriaType($type);
                     $fc->add($item);
                 }
                 $reviewObject = $this->getReview($shopConfiguration, $uid, $consumerEmail, $creationDate);
                 $reviewObject->setShopConfig($shopConfiguration);
                 $reviewObject->setUid($uid);
                 $reviewObject->setComment($comment);
                 $reviewObject->setConsumerEmail($consumerEmail);
                 $reviewObject->setReviewConfirmationDate(new Pimcore\Date($confirmationDate));
                 $reviewObject->setReviewCreationDate(new Pimcore\Date($creationDate));
                 $reviewObject->setReviewChangeDate(new Pimcore\Date($changeDate));
                 $reviewObject->setMark($mark);
                 $reviewObject->setMarkDescription($markDescription);
                 $reviewObject->setCritera($fc);
                 $reviewObject->setOrderReference($orderReference);
                 if (!$creationDate) {
                     $path = '/unknown';
                 } else {
                     $path = '/' . date('Y/m/d', $creationDate);
                 }
                 $path = $importDirectory . $path;
                 $reviewObject->setParent(Object\Service::createFolderByPath($path));
                 $reviewObject->save();
                 if ($this->logToConsole) {
                     echo "Saved review " . $reviewObject->getId() . " " . $reviewObject->getFullPath() . "\n";
                 }
                 $this->logger->info("Updated review " . $reviewObject->getId(), $reviewObject, null, self::COMPONENT);
                 if ($page % 5 == 0) {
                     \Pimcore::collectGarbage();
                 }
             }
             if (count($reviews) < $pageSize) {
                 break;
             }
             $page++;
         }
         $shopConfiguration->setLastSync(new Pimcore\Date($startTime));
         $shopConfiguration->save();
     }
 }
Beispiel #16
0
 /**
  *
  */
 public static function runSanityCheck()
 {
     $sanityCheck = Sanitycheck::getNext();
     $count = 0;
     while ($sanityCheck) {
         $count++;
         if ($count % 10 == 0) {
             \Pimcore::collectGarbage();
         }
         $element = self::getElementById($sanityCheck->getType(), $sanityCheck->getId());
         if ($element) {
             try {
                 self::performSanityCheck($element);
             } catch (\Exception $e) {
                 Logger::error("Element\\Service: sanity check for element with id [ " . $element->getId() . " ] and type [ " . self::getType($element) . " ] failed");
             }
             $sanityCheck->delete();
         } else {
             $sanityCheck->delete();
         }
         $sanityCheck = Sanitycheck::getNext();
         // reduce load on server
         Logger::debug("Now timeout for 3 seconds");
         sleep(3);
     }
 }