/** * Filter expired sessions * * @param int $sessionLifeTime * @return $this */ public function filterExpiredSessions($sessionLifeTime) { $connection = $this->getConnection(); $gmtTimestamp = $this->dateTime->gmtTimestamp(); $this->addFieldToFilter('updated_at', ['gt' => $connection->formatDate($gmtTimestamp - $sessionLifeTime)]); return $this; }
/** * Prepare online visitors for collection * * @param \Magento\Log\Model\Visitor\Online $object * @return $this * @throws \Exception */ public function prepare(\Magento\Log\Model\Visitor\Online $object) { if ($object->getUpdateFrequency() + $object->getPrepareAt() > time()) { return $this; } $readAdapter = $this->_getReadAdapter(); $writeAdapter = $this->_getWriteAdapter(); $writeAdapter->beginTransaction(); try { $writeAdapter->delete($this->getMainTable()); $visitors = array(); $lastUrls = array(); // retrieve online visitors general data $lastDate = $this->_date->gmtTimestamp() - $object->getOnlineInterval() * 60; $select = $readAdapter->select()->from($this->getTable('log_visitor'), array('visitor_id', 'first_visit_at', 'last_visit_at', 'last_url_id'))->where('last_visit_at >= ?', $readAdapter->formatDate($lastDate)); $query = $readAdapter->query($select); while ($row = $query->fetch()) { $visitors[$row['visitor_id']] = $row; $lastUrls[$row['last_url_id']] = $row['visitor_id']; $visitors[$row['visitor_id']]['visitor_type'] = \Magento\Customer\Model\Visitor::VISITOR_TYPE_VISITOR; $visitors[$row['visitor_id']]['customer_id'] = null; } if (!$visitors) { $this->commit(); return $this; } // retrieve visitor remote addr $select = $readAdapter->select()->from($this->getTable('log_visitor_info'), array('visitor_id', 'remote_addr'))->where('visitor_id IN(?)', array_keys($visitors)); $query = $readAdapter->query($select); while ($row = $query->fetch()) { $visitors[$row['visitor_id']]['remote_addr'] = $row['remote_addr']; } // retrieve visitor last URLs $select = $readAdapter->select()->from($this->getTable('log_url_info'), array('url_id', 'url'))->where('url_id IN(?)', array_keys($lastUrls)); $query = $readAdapter->query($select); while ($row = $query->fetch()) { $visitorId = $lastUrls[$row['url_id']]; $visitors[$visitorId]['last_url'] = $row['url']; } // retrieve customers $select = $readAdapter->select()->from($this->getTable('log_customer'), array('visitor_id', 'customer_id'))->where('visitor_id IN(?)', array_keys($visitors)); $query = $readAdapter->query($select); while ($row = $query->fetch()) { $visitors[$row['visitor_id']]['visitor_type'] = \Magento\Customer\Model\Visitor::VISITOR_TYPE_CUSTOMER; $visitors[$row['visitor_id']]['customer_id'] = $row['customer_id']; } foreach ($visitors as $visitorData) { unset($visitorData['last_url_id']); $writeAdapter->insertForce($this->getMainTable(), $visitorData); } $writeAdapter->commit(); } catch (\Exception $e) { $writeAdapter->rollBack(); throw $e; } $object->setPrepareAt(); return $this; }
/** * Delete old entries * * @param int $minutes * @return int */ public function deleteOldEntries($minutes) { if ($minutes > 0) { $connection = $this->getConnection(); return $connection->delete($this->getMainTable(), $connection->quoteInto('type = "' . \Magento\Integration\Model\Oauth\Token::TYPE_REQUEST . '" AND created_at <= ?', $this->_dateTime->formatDate($this->date->gmtTimestamp() - $minutes * 60))); } else { return 0; } }
/** * Init collection select * * @return $this */ protected function _initSelect() { parent::_initSelect(); $connection = $this->getConnection(); $lastDate = $this->date->gmtTimestamp() - $this->visitorModel->getOnlineInterval() * self::SECONDS_IN_MINUTE; $this->getSelect()->joinLeft(['customer' => $this->getTable('customer_entity')], 'customer.entity_id = main_table.customer_id', ['email', 'firstname', 'lastname'])->where('main_table.last_visit_at >= ?', $connection->formatDate($lastDate)); $expression = $connection->getCheckSql('main_table.customer_id IS NOT NULL AND main_table.customer_id != 0', $connection->quote(Visitor::VISITOR_TYPE_CUSTOMER), $connection->quote(Visitor::VISITOR_TYPE_VISITOR)); $this->getSelect()->columns(['visitor_type' => $expression]); return $this; }
public function testGmtTimestamp() { $time = time(); $this->localeDate->expects($this->at(0))->method('date')->with($time)->will($this->returnValue($this->date)); $this->localeDate->expects($this->at(1))->method('date')->with(strtotime("10 September 2000"))->will($this->returnValue($this->date)); $this->assertSame(1403857349, $this->dateTime->gmtTimestamp($time)); $this->assertSame(1403857349, $this->dateTime->gmtTimestamp("10 September 2000")); $this->assertSame(false, $this->dateTime->gmtTimestamp("la-la-la")); $this->assertSame(1404377188, $this->dateTime->gmtTimestamp()); }
/** * {@inheritdoc} */ public function check($securityEventType, $accountReference = null, $longIp = null) { $isEnabled = $this->securityConfig->getPasswordResetProtectionType() != ResetMethod::OPTION_NONE; $limitTimeBetweenRequests = $this->securityConfig->getMinTimeBetweenPasswordResetRequests(); if ($isEnabled && $limitTimeBetweenRequests) { if (null === $longIp) { $longIp = $this->remoteAddress->getRemoteAddress(); } $lastRecordCreationTimestamp = $this->loadLastRecordCreationTimestamp($securityEventType, $accountReference, $longIp); if ($lastRecordCreationTimestamp && $limitTimeBetweenRequests > $this->dateTime->gmtTimestamp() - $lastRecordCreationTimestamp) { throw new SecurityViolationException(__('Too many password reset requests. Please wait and try again or contact %1.', $this->securityConfig->getCustomerServiceEmail())); } } }
/** * Filter by lifetime * * @param int $lifetime * @return $this */ public function filterByLifetime($lifetime) { $connection = $this->getConnection(); $gmtTimestamp = $this->dateTime->gmtTimestamp(); $this->addFieldToFilter('created_at', ['gt' => $connection->formatDate($gmtTimestamp - $lifetime)]); return $this; }
/** * Returns today month * * @return string */ public function getTodayMonth() { if (!$this->today) { $this->today = $this->dateTime->gmtTimestamp(); } return date('m', $this->today); }
/** * Generate Coupons Pool * * @throws \Magento\Framework\Exception\LocalizedException * @return $this */ public function generatePool() { $this->generatedCount = 0; $size = $this->getQty(); $maxAttempts = $this->getMaxAttempts() ? $this->getMaxAttempts() : self::MAX_GENERATE_ATTEMPTS; $this->increaseLength(); /** @var $coupon \Magento\SalesRule\Model\Coupon */ $coupon = $this->couponFactory->create(); $nowTimestamp = $this->dateTime->formatDate($this->date->gmtTimestamp()); for ($i = 0; $i < $size; $i++) { $attempt = 0; do { if ($attempt >= $maxAttempts) { throw new \Magento\Framework\Exception\LocalizedException(__('We cannot create the requested Coupon Qty. Please check your settings and try again.')); } $code = $this->generateCode(); ++$attempt; } while ($this->getResource()->exists($code)); $expirationDate = $this->getToDate(); if ($expirationDate instanceof \DateTime) { $expirationDate = $expirationDate->format('Y-m-d H:i:s'); } $coupon->setId(null)->setRuleId($this->getRuleId())->setUsageLimit($this->getUsesPerCoupon())->setUsagePerCustomer($this->getUsesPerCustomer())->setExpirationDate($expirationDate)->setCreatedAt($nowTimestamp)->setType(\Magento\SalesRule\Helper\Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)->setCode($code)->save(); $this->generatedCount += 1; } return $this; }
/** * Clean visitor's outdated records * * @param \Magento\Customer\Model\Visitor $object * @return $this */ public function clean(\Magento\Customer\Model\Visitor $object) { $cleanTime = $object->getCleanTime(); $connection = $this->getConnection(); $timeLimit = $this->dateTime->formatDate($this->date->gmtTimestamp() - $cleanTime); while (true) { $select = $connection->select()->from(['visitor_table' => $this->getTable('customer_visitor')], ['visitor_id' => 'visitor_table.visitor_id'])->where('visitor_table.last_visit_at < ?', $timeLimit)->limit(100); $visitorIds = $connection->fetchCol($select); if (!$visitorIds) { break; } $condition = ['visitor_id IN (?)' => $visitorIds]; $connection->delete($this->getTable('customer_visitor'), $condition); } return $this; }
/** * @test */ public function testGmtTimestamp() { $timezone = $this->getMockBuilder('Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface')->getMock(); $timezone->expects($this->any())->method('date')->willReturn(new \DateTime('2015-04-02 21:03:00')); /** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone */ $dateTime = new DateTime($timezone); $this->assertEquals(gmdate('U', strtotime('2015-04-02 21:03:00')), $dateTime->gmtTimestamp('2015-04-02 21:03:00')); }
/** * Update CatalogRuleGroupWebsite data * * @return $this */ protected function updateCatalogRuleGroupWebsiteData() { $this->connection->delete($this->getTable('catalogrule_group_website'), []); $timestamp = $this->dateTime->gmtTimestamp(); $select = $this->connection->select()->distinct(true)->from($this->getTable('catalogrule_product'), $this->_catalogRuleGroupWebsiteColumnsList)->where("{$timestamp} >= from_time AND (({$timestamp} <= to_time AND to_time > 0) OR to_time = 0)"); $query = $select->insertFromSelect($this->getTable('catalogrule_group_website'), $this->_catalogRuleGroupWebsiteColumnsList); $this->connection->query($query); return $this; }
/** * @param Product|null $product * @throws \Exception * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function applyAllRules(Product $product = null) { $write = $this->getWriteAdapter(); $fromDate = mktime(0, 0, 0, date('m'), date('d') - 1); $toDate = mktime(0, 0, 0, date('m'), date('d') + 1); $productId = $product ? $product->getId() : null; /** * Update products rules prices per each website separately * because of max join limit in mysql */ foreach ($this->storeManager->getWebsites(false) as $website) { $productsStmt = $this->getRuleProductsStmt($website->getId(), $productId); $dayPrices = []; $stopFlags = []; $prevKey = null; while ($ruleData = $productsStmt->fetch()) { $ruleProductId = $ruleData['product_id']; $productKey = $ruleProductId . '_' . $ruleData['website_id'] . '_' . $ruleData['customer_group_id']; if ($prevKey && $prevKey != $productKey) { $stopFlags = []; if (count($dayPrices) > $this->batchCount) { $this->saveRuleProductPrices($dayPrices); $dayPrices = []; } } /** * Build prices for each day */ for ($time = $fromDate; $time <= $toDate; $time += self::SECONDS_IN_DAY) { if (($ruleData['from_time'] == 0 || $time >= $ruleData['from_time']) && ($ruleData['to_time'] == 0 || $time <= $ruleData['to_time'])) { $priceKey = $time . '_' . $productKey; if (isset($stopFlags[$priceKey])) { continue; } if (!isset($dayPrices[$priceKey])) { $dayPrices[$priceKey] = ['rule_date' => $time, 'website_id' => $ruleData['website_id'], 'customer_group_id' => $ruleData['customer_group_id'], 'product_id' => $ruleProductId, 'rule_price' => $this->calcRuleProductPrice($ruleData), 'latest_start_date' => $ruleData['from_time'], 'earliest_end_date' => $ruleData['to_time']]; } else { $dayPrices[$priceKey]['rule_price'] = $this->calcRuleProductPrice($ruleData, $dayPrices[$priceKey]); $dayPrices[$priceKey]['latest_start_date'] = max($dayPrices[$priceKey]['latest_start_date'], $ruleData['from_time']); $dayPrices[$priceKey]['earliest_end_date'] = min($dayPrices[$priceKey]['earliest_end_date'], $ruleData['to_time']); } if ($ruleData['action_stop']) { $stopFlags[$priceKey] = true; } } } $prevKey = $productKey; } $this->saveRuleProductPrices($dayPrices); } $write->delete($this->getTable('catalogrule_group_website'), []); $timestamp = $this->dateTime->gmtTimestamp(); $select = $write->select()->distinct(true)->from($this->getTable('catalogrule_product'), ['rule_id', 'customer_group_id', 'website_id'])->where("{$timestamp} >= from_time AND (({$timestamp} <= to_time AND to_time > 0) OR to_time = 0)"); $query = $select->insertFromSelect($this->getTable('catalogrule_group_website')); $write->query($query); return $this; }
/** * Check whether the session is expired * * @return bool */ public function isSessionExpired() { $lifetime = $this->securityConfig->getAdminSessionLifetime(); $currentTime = $this->dateTime->gmtTimestamp(); $lastUpdatedTime = $this->getUpdatedAt(); if (!is_numeric($lastUpdatedTime)) { $lastUpdatedTime = strtotime($lastUpdatedTime); } return $lastUpdatedTime <= $currentTime - $lifetime ? true : false; }
/** * Clean customer table * * @param int $time * @return $this * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _cleanCustomers($time) { $readAdapter = $this->_getReadAdapter(); $writeAdapter = $this->_getWriteAdapter(); $timeLimit = $this->dateTime->formatDate($this->_date->gmtTimestamp() - $time); // retrieve last active customer log id $lastLogId = $readAdapter->fetchOne($readAdapter->select()->from($this->getTable('log_customer'), 'log_id')->where('login_at < ?', $timeLimit)->order('log_id DESC')->limit(1)); if (!$lastLogId) { return $this; } // Order by desc log_id before grouping (within-group aggregates query pattern) $select = $readAdapter->select()->from(['log_customer_main' => $this->getTable('log_customer')], ['log_id'])->joinLeft(['log_customer' => $this->getTable('log_customer')], 'log_customer_main.customer_id = log_customer.customer_id ' . 'AND log_customer_main.log_id < log_customer.log_id', [])->where('log_customer.customer_id IS NULL')->where('log_customer_main.log_id < ?', $lastLogId + 1); $needLogIds = []; $query = $readAdapter->query($select); while ($row = $query->fetch()) { $needLogIds[$row['log_id']] = 1; } $customerLogId = 0; while (true) { $visitorIds = []; $select = $readAdapter->select()->from($this->getTable('log_customer'), ['log_id', 'visitor_id'])->where('log_id > ?', $customerLogId)->where('log_id < ?', $lastLogId + 1)->order('log_id')->limit(100); $query = $readAdapter->query($select); $count = 0; while ($row = $query->fetch()) { $count++; $customerLogId = $row['log_id']; if (!isset($needLogIds[$row['log_id']])) { $visitorIds[] = $row['visitor_id']; } } if (!$count) { break; } if ($visitorIds) { $condition = ['visitor_id IN (?)' => $visitorIds]; // remove visitors from log/quote $writeAdapter->delete($this->getTable('log_quote'), $condition); // remove visitors from log/url $writeAdapter->delete($this->getTable('log_url'), $condition); // remove visitors from log/visitor_info $writeAdapter->delete($this->getTable('log_visitor_info'), $condition); // remove visitors from log/visitor $writeAdapter->delete($this->getTable('log_visitor'), $condition); // remove customers from log/customer $writeAdapter->delete($this->getTable('log_customer'), $condition); } if ($customerLogId == $lastLogId) { break; } } return $this; }
/** * Save composer packages available for update to cache * * @param array $availableVersions * @return bool|string */ private function savePackagesForUpdateToCache($availableVersions) { $syncInfo = []; $syncInfo['lastSyncDate'] = $this->dateTime->gmtTimestamp(); $syncInfo['packages'] = $availableVersions; $data = json_encode($syncInfo, JSON_UNESCAPED_SLASHES); try { $this->directory->writeFile($this->pathToCacheFile, $data); } catch (\Magento\Framework\Exception\FileSystemException $e) { return false; } return $data; }
/** * Generate Coupons Pool * * @throws \Magento\Framework\Model\Exception * @return $this */ public function generatePool() { $this->_generatedCount = 0; $size = $this->getQty(); $maxProbability = $this->getMaxProbability() ? $this->getMaxProbability() : self::MAX_PROBABILITY_OF_GUESSING; $maxAttempts = $this->getMaxAttempts() ? $this->getMaxAttempts() : self::MAX_GENERATE_ATTEMPTS; /** @var $coupon \Magento\SalesRule\Model\Coupon */ $coupon = $this->_couponFactory->create(); $chars = count($this->_salesRuleCoupon->getCharset($this->getFormat())); $length = (int) $this->getLength(); $maxCodes = pow($chars, $length); $probability = $size / $maxCodes; //increase the length of Code if probability is low if ($probability > $maxProbability) { do { $length++; $maxCodes = pow($chars, $length); $probability = $size / $maxCodes; } while ($probability > $maxProbability); $this->setLength($length); } $now = $this->dateTime->formatDate($this->_date->gmtTimestamp()); for ($i = 0; $i < $size; $i++) { $attempt = 0; do { if ($attempt >= $maxAttempts) { throw new \Magento\Framework\Model\Exception(__('We cannot create the requested Coupon Qty. Please check your settings and try again.')); } $code = $this->generateCode(); $attempt++; } while ($this->getResource()->exists($code)); $expirationDate = $this->getToDate(); if ($expirationDate instanceof \Zend_Date) { $expirationDate = $expirationDate->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); } $coupon->setId(null)->setRuleId($this->getRuleId())->setUsageLimit($this->getUsesPerCoupon())->setUsagePerCustomer($this->getUsesPerCustomer())->setExpirationDate($expirationDate)->setCreatedAt($now)->setType(\Magento\SalesRule\Helper\Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)->setCode($code)->save(); $this->_generatedCount++; } return $this; }
/** * get flexslider html id. * * @return string */ public function getFlexsliderHtmlId() { return 'magestore-bannerslider-flex-slider-' . $this->getSlider()->getId() . $this->_stdlibDateTime->gmtTimestamp(); }
/** * @param AbstractModel $object * @return $this */ public function _beforeSave(AbstractModel $object) { $object->setUpdatedAt($this->dateTime->formatDate($this->_date->gmtTimestamp())); return $this; }
/** * Generate new login credentials * @param int $adminId * @return $this */ public function generate($adminId) { return $this->setData(['customer_id' => $this->getCustomerId(), 'admin_id' => $adminId, 'secret' => $this->_random->getRandomString(64), 'used' => 0, 'created_at' => $this->_dateTime->gmtTimestamp()])->save(); }
/** * {@inheritdoc} */ public function clearExpiredFailures() { $date = (new \DateTime())->setTimestamp($this->dateTime->gmtTimestamp()); $dateTime = $date->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); $this->getConnection()->delete($this->getMainTable(), ['lock_expires_at <= ?' => $dateTime]); }
/** * Clean expired Admin Sessions * * @return $this */ public function cleanExpiredSessions() { $this->createAdminSessionInfoCollection()->deleteSessionsOlderThen($this->dateTime->gmtTimestamp() - self::ADMIN_SESSION_LIFETIME); return $this; }
/** * Clean expired Admin Sessions * * @return $this */ public function cleanExpiredRecords() { $this->passwordResetRequestEventCollectionFactory->create()->deleteRecordsOlderThen($this->dateTime->gmtTimestamp() - self::SECURITY_CONTROL_RECORDS_LIFE_TIME); return $this; }
/** * Generate catalog price rules prices for specified date range * If from date is not defined - will be used previous day by UTC * If to date is not defined - will be used next day by UTC * * @param int|string|null $fromDate * @param int|string|null $toDate * @param int $productId * @return $this * @throws \Exception */ public function applyAllRulesForDateRange($fromDate = null, $toDate = null, $productId = null) { $write = $this->_getWriteAdapter(); $write->beginTransaction(); $this->_eventManager->dispatch('catalogrule_before_apply', array('resource' => $this)); $clearOldData = false; if ($fromDate === null) { $fromDate = mktime(0, 0, 0, date('m'), date('d') - 1); /** * If fromDate not specified we can delete all data oldest than 1 day * We have run it for clear table in case when cron was not installed * and old data exist in table */ $clearOldData = true; } if (is_string($fromDate)) { $fromDate = strtotime($fromDate); } if ($toDate === null) { $toDate = mktime(0, 0, 0, date('m'), date('d') + 1); } if (is_string($toDate)) { $toDate = strtotime($toDate); } $product = null; if ($productId instanceof Product) { $product = $productId; $productId = $productId->getId(); } $this->removeCatalogPricesForDateRange($fromDate, $toDate, $productId); if ($clearOldData) { $this->deleteOldData($fromDate, $productId); } $dayPrices = array(); try { /** * Update products rules prices per each website separately * because of max join limit in mysql */ foreach ($this->_storeManager->getWebsites(false) as $website) { $productsStmt = $this->_getRuleProductsStmt($fromDate, $toDate, $productId, $website->getId()); $dayPrices = array(); $stopFlags = array(); $prevKey = null; while ($ruleData = $productsStmt->fetch()) { $ruleProductId = $ruleData['product_id']; $productKey = $ruleProductId . '_' . $ruleData['website_id'] . '_' . $ruleData['customer_group_id']; if ($prevKey && $prevKey != $productKey) { $stopFlags = array(); } /** * Build prices for each day */ for ($time = $fromDate; $time <= $toDate; $time += self::SECONDS_IN_DAY) { if (($ruleData['from_time'] == 0 || $time >= $ruleData['from_time']) && ($ruleData['to_time'] == 0 || $time <= $ruleData['to_time'])) { $priceKey = $time . '_' . $productKey; if (isset($stopFlags[$priceKey])) { continue; } if (!isset($dayPrices[$priceKey])) { $dayPrices[$priceKey] = array('rule_date' => $time, 'website_id' => $ruleData['website_id'], 'customer_group_id' => $ruleData['customer_group_id'], 'product_id' => $ruleProductId, 'rule_price' => $this->_calcRuleProductPrice($ruleData), 'latest_start_date' => $ruleData['from_time'], 'earliest_end_date' => $ruleData['to_time']); } else { $dayPrices[$priceKey]['rule_price'] = $this->_calcRuleProductPrice($ruleData, $dayPrices[$priceKey]); $dayPrices[$priceKey]['latest_start_date'] = max($dayPrices[$priceKey]['latest_start_date'], $ruleData['from_time']); $dayPrices[$priceKey]['earliest_end_date'] = min($dayPrices[$priceKey]['earliest_end_date'], $ruleData['to_time']); } if ($ruleData['action_stop']) { $stopFlags[$priceKey] = true; } } } $prevKey = $productKey; if (count($dayPrices) > 1000) { $this->_saveRuleProductPrices($dayPrices); $dayPrices = array(); } } $this->_saveRuleProductPrices($dayPrices); } $this->_saveRuleProductPrices($dayPrices); $write->delete($this->getTable('catalogrule_group_website'), array()); $timestamp = $this->_coreDate->gmtTimestamp(); $select = $write->select()->distinct(true)->from($this->getTable('catalogrule_product'), array('rule_id', 'customer_group_id', 'website_id'))->where("{$timestamp} >= from_time AND (({$timestamp} <= to_time AND to_time > 0) OR to_time = 0)"); $query = $select->insertFromSelect($this->getTable('catalogrule_group_website')); $write->query($query); $write->commit(); } catch (\Exception $e) { $this->_logger->logException($e); $write->rollback(); throw $e; } $productCondition = $this->_conditionFactory->create()->setTable($this->getTable('catalogrule_affected_product'))->setPkFieldName('product_id'); $this->_eventManager->dispatch('catalogrule_after_apply', array('product' => $product, 'product_condition' => $productCondition)); $write->delete($this->getTable('catalogrule_affected_product')); return $this; }