public function boot() { $em = $this->container->get("doctrine.orm.entity_manager"); try { Registry::getInstance("app"); } catch (InvalidArgumentException $e) { Registry::addLogger($this->container->get("logger"), "app"); } try { Type::addType("encryptedstring", "\\Keboola\\ProvisioningBundle\\Types\\EncryptedStringType"); Type::addType("enumservertype", "\\Keboola\\ProvisioningBundle\\Types\\EnumServerTypeType"); Type::addType("enumservermode", "\\Keboola\\ProvisioningBundle\\Types\\EnumServerModeType"); Type::addType("enumaccounttype", "\\Keboola\\ProvisioningBundle\\Types\\EnumAccountTypeType"); Type::addType("enumwrdbaccounttype", "\\Keboola\\ProvisioningBundle\\Types\\EnumWrdbAccountTypeType"); Type::addType("enumredshiftaccounttype", "\\Keboola\\ProvisioningBundle\\Types\\EnumRedshiftAccountTypeType"); Type::addType("enumsnowflakeaccounttype", "\\Keboola\\ProvisioningBundle\\Types\\EnumSnowflakeAccountTypeType"); Type::addType("enumsnowflakeaccountwithluckyguesstype", "\\Keboola\\ProvisioningBundle\\Types\\EnumSnowflakeAccountWithLuckyguessTypeType"); Type::addType("enumsnowflakeaccountwithluckyguessandwritertype", "\\Keboola\\ProvisioningBundle\\Types\\EnumSnowflakeAccountWithLuckyguessAndWriterTypeType"); Type::addType("enumredshiftworkspaceaccounttype", "\\Keboola\\ProvisioningBundle\\Types\\EnumRedshiftWorkspaceAccountTypeType"); Type::addType("enumdockeraccounttype", "\\Keboola\\ProvisioningBundle\\Types\\EnumDockerAccountTypeType"); Type::addType("enumredshiftworkspaceaccountwithluckyguestype", "\\Keboola\\ProvisioningBundle\\Types\\EnumRedshiftWorkspaceAccountWithLuckyguessTypeType"); Type::addType("enumredshiftworkspaceaccountwithluckyguessandwritertype", "\\Keboola\\ProvisioningBundle\\Types\\EnumRedshiftWorkspaceAccountWithLuckyguessAndWriterTypeType"); $encryptor = new AesEncryptor($this->container->getParameter("provisioning_api.key")); // 256 bit key EncryptedStringType::setEncryptor($encryptor); $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping("encryptedstring", "encryptedstring"); } catch (\Doctrine\DBAL\DBALException $e) { // For some reason this exception gets thrown during // the clearing of the cache. I didn't have time to // find out why :-) } }
public function __construct(Container $di, Wordpress $wp, Options $options, ProductServiceInterface $productService) { $this->wp = $wp; $this->options = $options; $types = $options->getEnabledProductTypes(); foreach ($types as $typeClass) { /** @var Types\Product\Type $type */ $type = $di->get($typeClass); if (!$type instanceof Types\Product\Type) { if (WP_DEBUG) { throw new Exception(sprintf(__('Invalid type definition! Offending class: "%s".', 'jigoshop'), $typeClass)); } Registry::getInstance(JIGOSHOP_LOGGER)->addWarning(sprintf('Invalid type definition! Offending class: "%s".', $typeClass)); continue; } $this->enabledTypes[$type->getId()] = $type; $productService->addType($type->getId(), $type->getClass()); $wp->addAction('jigoshop\\product\\type\\init', array($type, 'initialize'), 10, 2); } $wp->doAction('jigoshop\\product\\type\\init', $wp, $this->enabledTypes); // Enable comments for all orders, disable pings $wp->addFilter('wp_insert_post_data', function ($data) { if ($data['post_type'] == Product::NAME) { $data['comment_status'] = 'open'; $data['ping_status'] = 'closed'; } return $data; }); }
/** * {@inheritdoc} */ public function initialize(array $options) { if (!isset($options['logger'])) { throw new ArgumentNullException('logger'); } $this->logger = Registry::getInstance($options['logger']); }
public function setName($name) { if (WP_DEBUG) { throw new Exception(__('Guest customer cannot be updated!', 'jigoshop')); } Registry::getInstance(JIGOSHOP_LOGGER)->addDebug('Guest customer cannot be updated!'); }
/** * @param $level * @param $message * @param array $context */ public function log($level, $message, $context = array()) { try { Registry::getInstance("app")->log($level, $message, $context); } catch (InvalidArgumentException $e) { // Nothing } }
public function testLoad() { Logger::load($this->config); $logger = \Monolog\Registry::getInstance('MAIN'); $this->assertInstanceOf('\\Monolog\\Logger', $logger); $handler = $logger->popHandler(); $this->assertInstanceOf('\\Monolog\\Handler\\StreamHandler', $handler); }
/** * Returns method by its ID. * * @param $id string ID of method. * * @return Method Method found. * @throws Exception When no method is found for specified ID. */ public function get($id) { if (!isset($this->methods[$id])) { Registry::getInstance(JIGOSHOP_LOGGER)->addWarning(sprintf(__('Shipping method "%s" does not exists', 'jigoshop'), $id)); return new Dummy($id); } return $this->methods[$id]; }
/** * Zwraca zarejestrowany dziennik. * * @param string $name Nazwa wybranego dziennika * @return LoggerInterface Dziennik * @throws InvalidArgumentException func_num_args() == 0 * @throws InvalidArgumentException Dziennik nie zarejestrowany * @throws LogicException Niepoprawna nazwa dziennika */ public function getLogger($name) { if (func_num_args() == 0) { throw new InvalidArgumentException("No arguments"); } if (is_string($name) == false || $name == "") { throw new LogicException("Invalid or empty logger name"); } return MonologRegistry::getInstance($name); }
private function query($type, $fields, $where) { $fieldsClause = join(', ', $fields); $whereClause = $this->buildWhereClause($where); $query = "SELECT {$fieldsClause} FROM {$type} WHERE {$whereClause}"; \Monolog\Registry::getInstance('logger')->debug("Query: '{$query}'"); $response = $this->soapClient->query(['queryString' => $query]); \Monolog\Registry::getInstance('logger')->debug("Response: '" . json_encode($response->result->records) . "'"); return $response->result->records; }
/** * Get a Logger instance by name. Creates a new one if a Logger with the * provided name does not exist * * @param string $name Name of the requested Logger instance * * @return Logger Requested instance of Logger or new instance */ public static function getLogger($name) { if (Registry::hasLogger($name)) { return Registry::getInstance($name); } else { if (Registry::hasLogger('default')) { return Registry::getInstance('default'); } } return self::createLogger($name); }
/** * Adds new page to Jigoshop admin panel. * Available parents: * * jigoshop - main Jigoshop menu, * * products - Jigoshop products menu * * orders - Jigoshop orders menu * * @param $page PageInterface Page to add. * * @throws Exception When trying to add page not in Jigoshop menus. */ public function addPage(PageInterface $page) { $parent = $page->getParent(); if (!isset($this->pages[$parent])) { if (WP_DEBUG) { throw new Exception(sprintf('Trying to add page to invalid parent (%s). Available ones are: %s', $parent, join(', ', array_keys($this->pages)))); } Registry::getInstance(JIGOSHOP_LOGGER)->addDebug(sprintf('Trying to add page to invalid parent (%s).', $parent), array('parents' => $this->pages)); return; } $this->pages[$parent][] = $page; }
/** * {@inheritdoc} */ public function initialize(array $options) { if (!isset($options['logger'])) { throw new ArgumentNullException('logger'); } if (is_array($options['rules']) && !empty($options['rules'])) { $this->rules = $options['rules']; } if (is_callable($options['context'])) { $this->context = $options['context']; } $this->logger = Registry::getInstance($options['logger']); }
/** * Returns empty product of selected type. * * @param $type string Type name of product. * * @throws \Jigoshop\Exception When product type does not exists. * @return \Jigoshop\Entity\Product */ public function get($type) { if (!isset($this->types[$type])) { if (WP_DEBUG) { throw new Exception(sprintf('Product type "%s" does not exists.', $type)); } Registry::getInstance(JIGOSHOP_LOGGER)->addWarning(sprintf('Product type "%s" does not exists.', $type)); $type = Simple::TYPE; } $class = $this->types[$type]; /** @var \Jigoshop\Entity\Product $instance */ $instance = new $class(); if ($instance instanceof Purchasable) { /** @var \Jigoshop\Entity\Product\Purchasable $instance */ $instance->getStock()->setManage($this->options->get('products.manage_stock')); $instance->getStock()->setStatus($this->options->get('products.stock_status')); } $instance->setTaxable($this->options->get('tax.defaults.taxable')); $instance->setTaxClasses($this->options->get('tax.defaults.classes')); return $instance; }
/** * Loads proper template based on current page. * * @param $template string Template chain. * * @return string Template to load. */ public function process($template) { if (!Pages::isJigoshop()) { return $template; } if ($this->page === null) { if (WP_DEBUG) { throw new Exception('Page object should already be set for Jigoshop pages, but none found.'); } Registry::getInstance(JIGOSHOP_LOGGER)->addCritical('Page object should already be set for Jigoshop pages, but none found.'); return false; } $content = $this->page->render(); $template = $this->wp->getOption('template'); $theme = $this->wp->wpGetTheme(); if ($theme->get('Author') === 'WooThemes') { $template = 'woothemes'; } if (!file_exists(\JigoshopInit::getDir() . '/templates/layout/' . $template . '.php')) { $template = 'default'; } Render::output('layout/' . $template, array('content' => $content)); return false; }
/** * @param int $quantity New item quantity. * * @throws Exception When quantity is invalid. */ public function setQuantity($quantity) { if ($quantity < 0) { if (WP_DEBUG) { throw new Exception(__('Item quantity cannot be below 0', 'jigoshop')); } Registry::getInstance(JIGOSHOP_LOGGER)->addCritical('Item quantity cannot be below 0'); $quantity = 0; } $this->quantity = $quantity; }
<?php /* * This file is part of the Pathfinder package. * * (c) bitExpert AG * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare (strict_types=1); // include and configure Composer autoloader include __DIR__ . '/../vendor/autoload.php'; // configure the Simple Logging Facade for PSR-3 loggers with a Monolog backend \bitExpert\Slf4PsrLog\LoggerFactory::registerFactoryCallback(function ($channel) { if (!\Monolog\Registry::hasLogger($channel)) { \Monolog\Registry::addLogger(new \Monolog\Logger($channel)); } return \Monolog\Registry::getInstance($channel); });
/** * @param $message * @param array $data * @param int $duration * @param bool $error * @throws \Keboola\StorageApi\Exception * @throws \Zend_Log_Exception */ public function log($message, $data = array(), $duration = 0, $error = false) { $params = array_merge($data, array('row' => $this->currentConfigRowNumber)); $logger = Registry::getInstance("log"); if ($error) { $logger->error($message, $data); } else { $logger->info($message, $data); } $event = new \Keboola\StorageApi\Event(); $event->setComponent($this->componentName)->setConfigurationId($this->configurationId)->setRunId($this->runId)->setType($error ? 'error' : 'info')->setDuration($duration)->setMessage($message)->setParams($params); $this->storageApi->createEvent($event); }
/** * Selects which address is to be used as tax address. * * @param $address string Name of address to be used as tax address. */ public function selectTaxAddress($address) { if (!in_array($address, array('billing', 'shipping'))) { if (WP_DEBUG) { throw new Exception(sprintf(__('Unknown address type: "%s".', 'jigoshop'), $address)); } Registry::getInstance(JIGOSHOP_LOGGER)->addCritical(sprintf('Unknown address type: "%s".', $address)); return; } $this->taxAddress = $address; }
/** Add information to the log file */ function add_log($text, $function, $type = LOG_INFO, $projectid = 0, $buildid = 0, $resourcetype = 0, $resourceid = 0) { global $CDASH_LOG_FILE, $CDASH_LOG_FILE_MAXSIZE_MB, $CDASH_LOG_LEVEL, $CDASH_TESTING_MODE; $level = to_psr3_level($type); if (($buildid === 0 || is_null($buildid)) && isset($GLOBALS['PHP_ERROR_BUILD_ID'])) { $buildid = $GLOBALS['PHP_ERROR_BUILD_ID']; } $context = array('function' => $function); if ($projectid !== 0 && !is_null($projectid)) { $context['project_id'] = $projectid; } if ($buildid !== 0 && !is_null($buildid)) { $context['build_id'] = strval($buildid); } if ($resourcetype !== 0 && !is_null($resourcetype)) { $context['resource_type'] = $resourcetype; } if ($resourceid !== 0 && !is_null($resourceid)) { $context['resource_id'] = $resourceid; } $minLevel = to_psr3_level($CDASH_LOG_LEVEL); if (!is_null($CDASH_LOG_FILE)) { // If the size of the log file is bigger than 10 times the allocated memory // we rotate $logFileMaxSize = $CDASH_LOG_FILE_MAXSIZE_MB * 100000; if (file_exists($CDASH_LOG_FILE) && filesize($CDASH_LOG_FILE) > $logFileMaxSize) { $tempLogFile = $CDASH_LOG_FILE . '.tmp'; if (!file_exists($tempLogFile)) { rename($CDASH_LOG_FILE, $tempLogFile); // This should be quick so we can keep logging for ($i = 9; $i >= 0; $i--) { // If we do not have compression we just rename the files if (function_exists('gzwrite') === false) { $currentLogFile = $CDASH_LOG_FILE . '.' . $i; $j = $i + 1; $newLogFile = $CDASH_LOG_FILE . '.' . $j; if (file_exists($newLogFile)) { cdash_unlink($newLogFile); } if (file_exists($currentLogFile)) { rename($currentLogFile, $newLogFile); } } else { $currentLogFile = $CDASH_LOG_FILE . '.' . $i . '.gz'; $j = $i + 1; $newLogFile = $CDASH_LOG_FILE . '.' . $j . '.gz'; if (file_exists($newLogFile)) { cdash_unlink($newLogFile); } if (file_exists($currentLogFile)) { $gz = gzopen($newLogFile, 'wb'); $f = fopen($currentLogFile, 'rb'); while ($f && !feof($f)) { gzwrite($gz, fread($f, 8192)); } fclose($f); unset($f); gzclose($gz); unset($gz); } } } // Move the current backup if (function_exists('gzwrite') === false) { rename($tempLogFile, $CDASH_LOG_FILE . '.0'); } else { $gz = gzopen($CDASH_LOG_FILE . '.0.gz', 'wb'); $f = fopen($tempLogFile, 'rb'); while ($f && !feof($f)) { gzwrite($gz, fread($f, 8192)); } fclose($f); unset($f); gzclose($gz); unset($gz); cdash_unlink($tempLogFile); } } } $pid = getmypid(); if ($pid !== false) { $context['pid'] = getmypid(); } } if (Registry::hasLogger('cdash') === false) { if ($CDASH_LOG_FILE === false) { $handler = new SyslogHandler('cdash', LOG_USER, $minLevel); $handler->getFormatter()->ignoreEmptyContextAndExtra(); } else { if ($CDASH_TESTING_MODE) { $filePermission = 0666; } else { $filePermission = 0664; } $handler = new StreamHandler($CDASH_LOG_FILE, $minLevel, true, $filePermission); $handler->getFormatter()->allowInlineLineBreaks(); $handler->getFormatter()->ignoreEmptyContextAndExtra(); } $logger = new Logger('cdash'); $logger->pushHandler($handler); Registry::addLogger($logger); } else { $logger = Registry::getInstance('cdash'); } $logger->log($level, $text, $context); }
public function ajaxMigrationProducts() { try { // 1 - if first time ajax request if ($_POST['msgLog'] == 1) { Migration::saveLog(__('Migration products START.', 'jigoshop'), true); } $wpdb = $this->wp->getWPDB(); $productsIdsMigration = array(); if (($TMP_productsIdsMigration = $this->wp->getOption('jigoshop_products_migrate_id')) === false) { $query = $wpdb->prepare("\n\t\t\t\tSELECT ID FROM {$wpdb->posts}\n\t\t\t\t\tWHERE post_type IN (%s, %s) AND post_status <> %s", 'product', 'product_variation', 'auto-draft'); $products = $wpdb->get_results($query); $countMeta = count($products); for ($aa = 0; $aa < $countMeta; $aa++) { $productsIdsMigration[] = $products[$aa]->ID; } $productsIdsMigration = array_unique($productsIdsMigration); $this->wp->updateOption('jigoshop_products_migrate_id', serialize($productsIdsMigration)); $this->wp->updateOption('jigoshop_products_migrate_count', count($productsIdsMigration)); } else { $productsIdsMigration = unserialize($TMP_productsIdsMigration); } $countAll = $this->wp->getOption('jigoshop_products_migrate_count'); $singleProductId = array_shift($productsIdsMigration); $countRemain = count($productsIdsMigration); $query = $wpdb->prepare("\n\t\t\tSELECT DISTINCT p.ID, pm.* FROM {$wpdb->posts} p\n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID\n\t\t\t\tWHERE p.post_type IN (%s, %s) AND p.post_status <> %s AND p.ID = %d", 'product', 'product_variation', 'auto-draft', $singleProductId); $product = $wpdb->get_results($query); $ajax_response = array('success' => true, 'percent' => floor(($countAll - $countRemain) / $countAll * 100), 'processed' => $countAll - $countRemain, 'remain' => $countRemain, 'total' => $countAll); if ($singleProductId) { if ($this->migrate($product)) { $this->wp->updateOption('jigoshop_products_migrate_id', serialize($productsIdsMigration)); } else { $ajax_response['success'] = false; Migration::saveLog(__('Migration products end with error.', 'jigoshop')); } } elseif ($countRemain == 0) { $this->wp->updateOption('jigoshop_products_migrate_id', serialize($productsIdsMigration)); $this->wp->deleteOption('jigoshop_attributes_anti_duplicate'); Migration::saveLog(__('Migration products END.', 'jigoshop')); } echo json_encode($ajax_response); } catch (Exception $e) { if (WP_DEBUG) { \Monolog\Registry::getInstance(JIGOSHOP_LOGGER)->addDebug($e); } echo json_encode(array('success' => false)); Migration::saveLog(__('Migration products end with error: ', 'jigoshop') . $e); } exit; }
/** * Returns item of selected key. * * @param $key string Item key to fetch. * * @return Item Order item. * @throws Exception When item is not found. */ public function getItem($key) { if (!isset($this->items[$key])) { if (WP_DEBUG) { throw new Exception(sprintf(__('No item with ID %d in order %d', 'jigoshop'), $key, $this->id)); } Registry::getInstance(JIGOSHOP_LOGGER)->addWarning(sprintf('No item with ID %d in order %d', $key, $this->id)); return null; } return $this->items[$key]; }
private function _createPage($slug, $data) { $wpdb = $this->wp->getWPDB(); $slug = esc_sql(_x($slug, 'page_slug', 'jigoshop')); $page_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_status = 'publish' AND post_status <> 'trash' LIMIT 1", $slug)); if (!$page_id) { Registry::getInstance(JIGOSHOP_LOGGER)->addDebug(sprintf('Installing page "%s".', $slug)); $data['post_name'] = $slug; $page_id = $this->wp->wpInsertPost($data); } $this->options->setPageId($slug, $page_id); $this->options->update('advanced.pages.' . $slug, $page_id); }
/** * Finds items specified using WordPress query. * * @param $query \WP_Query WordPress query. * * @return array Collection of found items. */ public function findByQuery($query) { if (WP_DEBUG) { throw new Exception('Customer service do not support fetching by query - users are not stored like posts.'); } Registry::getInstance(JIGOSHOP_LOGGER)->addWarning('Invalid call to Jigoshop\\Service\\Customer::findByQuery() method.'); return null; }
public function ajaxMigrationOptions() { try { // 1 - if first time ajax request if ($_POST['msgLog'] == 1) { Migration::saveLog(__('Migration options START.', 'jigoshop'), true); } $countAll = 93; $countRemain = 93; if (($itemsFromBase = $this->wp->getOption('jigoshop_options_migrate_id')) !== false) { if ($itemsFromBase === '1') { $countRemain = 0; } } $ajax_response = array('success' => true, 'percent' => floor(($countAll - $countRemain) / $countAll * 100), 'processed' => $countAll - $countRemain, 'remain' => $countRemain, 'total' => $countAll); if ($countRemain > 0) { if ($this->migrate()) { $this->wp->updateOption('jigoshop_options_migrate_id', '1'); } else { $ajax_response['success'] = false; Migration::saveLog(__('Migration coupons end with error.', 'jigoshop')); } } elseif ($countRemain == 0) { Migration::saveLog(__('Migration coupons END.', 'jigoshop')); } echo json_encode($ajax_response); } catch (Exception $e) { if (WP_DEBUG) { \Monolog\Registry::getInstance(JIGOSHOP_LOGGER)->addDebug($e); } echo json_encode(array('success' => false)); Migration::saveLog(__('Migration options end with error: ', 'jigoshop') . $e); } exit; }
/** * Checks for a valid postcode for a country * * @param string $postcode postcode * @param string $country country * * @return boolean */ public static function isPostcode($postcode, $country) { if (strlen(trim(preg_replace('/[\\s\\-A-Za-z0-9]/', '', $postcode))) > 0) { return false; } $country = strtoupper(trim($country)); $postcode = strtoupper(trim($postcode)); // Assume that unknown countries has proper postcodes if (!isset(self::$postcodes[$country]) && $country !== 'GB') { return true; } Registry::getInstance(JIGOSHOP_LOGGER)->addDebug(sprintf('Validating postcode "%s" for country "%s"', $postcode, $country)); switch ($country) { case 'GB': return self::isGreatBritainPostcode($postcode); default: $regex = '/^' . self::$postcodes[$country] . '$/'; Registry::getInstance(JIGOSHOP_LOGGER)->addDebug(sprintf('Validation regex: %s', $regex)); $match = preg_match($regex, $postcode); if ($match !== 1) { return false; } } return true; }
/** * Get a Logger instance by name. Creates a new one if a Logger with the * provided name does not exist * * @param string $name Name of the requested Logger instance * * @return Logger Requested instance of Logger or new instance */ public static function getLogger($name) { return Registry::hasLogger($name) ? Registry::getInstance($name) : self::createLogger($name); }
/** * Outputs simple static (constant) field. * * Available parameters (with defaults): * * id (null) - HTML id for the tag * * name (null) - HTML name for the tag * * label (null) - label for the tag * * value (false) - HTML value of the tag * * placeholder ('') - placeholder of the tag * * classes (array()) - list of HTML classes for the tag * * description (false) - description of the tag * * tip (false) - tip for the tag * * hidden (false) - whether to hide element by default * * size (12) - default size of the element (Bootstrap column size 12) * * Field's name is required. * * @param $field array Field parameters. * * @throws \Jigoshop\Exception */ public static function constant($field) { $defaults = array('id' => null, 'name' => null, 'label' => null, 'value' => false, 'placeholder' => '', 'classes' => array(), 'description' => false, 'tip' => false, 'hidden' => false, 'size' => 11, 'startDate' => false, 'endDate' => false); $field = wp_parse_args($field, $defaults); if (empty($field['name'])) { if (WP_DEBUG) { throw new Exception(sprintf('Field "%s" must have a name!', serialize($field))); } Registry::getInstance(JIGOSHOP_LOGGER)->addCritical('Field must have a name!', array('field' => $field)); return; } if (empty($field['id'])) { $field['id'] = self::prepareIdFromName($field['name']); } Render::output(static::$constantTemplate, $field); }
/** * Check PayPal IPN validity */ private function isResponseValid() { $values = $this->wp->getHelpers()->stripSlashesDeep($_POST); $values['cmd'] = '_notify-validate'; // Send back post vars to PayPal $params = array('body' => $values, 'sslverify' => false, 'timeout' => 30, 'user-agent' => 'Jigoshop/' . Core::VERSION); // Get url if ($this->settings['test_mode']) { $url = self::TEST_URL; } else { $url = self::LIVE_URL; } // Post back to get a response $response = $this->wp->wpSafeRemotePost($url, $params); // check to see if the request was valid if (!$this->wp->isWpError($response) && $response['response']['code'] >= 200 && $response['response']['code'] < 300 && strcmp($response['body'], "VERIFIED") == 0) { return true; } Registry::getInstance(JIGOSHOP_LOGGER)->addWarning('Received invalid response from PayPal!', array('response' => $response)); return false; }
/** * @param float $price Price to tax. * @param array $taxClasses List of applied tax classes. * @param array $definitions List of tax definitions to use. * * @return array List of tax values per tax class. */ public function get($price, array $taxClasses, array $definitions) { $tax = array(); $cost = $price; $standard = array(); $compound = array(); foreach ($taxClasses as $class) { if (!isset($definitions[$class])) { Registry::getInstance(JIGOSHOP_LOGGER)->addInfo(sprintf('No tax class: %s', $class)); $tax[$class] = 0.0; continue; } $standard[$class] = $definitions[$class]; if (isset($definitions['__compound__' . $class])) { $compound[$class] = $definitions['__compound__' . $class]; } } foreach ($standard as $class => $definition) { // TODO: Support for prices included in tax $tax[$class] = $definition['rate'] * $cost / 100; } $cost += array_sum($tax); foreach ($compound as $class => $definition) { // TODO: Support for prices included in tax $tax['__compound__' . $class] += $definition['rate'] * $cost / 100; } return array_filter($tax); }
public function ajaxMigrationEmails() { try { // 1 - if first time ajax request if ($_POST['msgLog'] == 1) { Migration::saveLog(__('Migration emails START.', 'jigoshop'), true); } $wpdb = $this->wp->getWPDB(); $query = $wpdb->prepare("\n\t\t\t\tSELECT DISTINCT p.ID, pm.* FROM {$wpdb->posts} p\n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID\n\t\t\t\t\tWHERE p.post_type IN (%s) AND p.post_status <> %s", array('shop_email', 'auto-draft')); $emails = $wpdb->get_results($query); $joinEmails = array(); $emailsIdsMigration = array(); for ($aa = 0; $aa < count($emails); $aa++) { $joinEmails[$emails[$aa]->ID][$emails[$aa]->meta_id] = new \stdClass(); foreach ($emails[$aa] as $k => $v) { $joinEmails[$emails[$aa]->ID][$emails[$aa]->meta_id]->{$k} = $v; $emailsIdsMigration[] = $emails[$aa]->ID; } } $emailsIdsMigration = array_unique($emailsIdsMigration); $countAll = count($emailsIdsMigration); if (($TMP_emailsIdsMigration = $this->wp->getOption('jigoshop_emails_migrate_id')) !== false) { $emailsIdsMigration = unserialize($TMP_emailsIdsMigration); } $singleEmailsId = array_shift($emailsIdsMigration); $countRemain = count($emailsIdsMigration); sort($joinEmails[$singleEmailsId]); $ajax_response = array('success' => true, 'percent' => floor(($countAll - $countRemain) / $countAll * 100), 'processed' => $countAll - $countRemain, 'remain' => $countRemain, 'total' => $countAll); if ($singleEmailsId) { if ($this->migrate($joinEmails[$singleEmailsId])) { $this->wp->updateOption('jigoshop_emails_migrate_id', serialize($emailsIdsMigration)); } else { $ajax_response['success'] = false; Migration::saveLog(__('Migration emails end with error.', 'jigoshop')); } } elseif ($countRemain == 0) { $this->wp->updateOption('jigoshop_emails_migrate_id', serialize($emailsIdsMigration)); Migration::saveLog(__('Migration emails END.', 'jigoshop')); } echo json_encode($ajax_response); } catch (Exception $e) { if (WP_DEBUG) { \Monolog\Registry::getInstance(JIGOSHOP_LOGGER)->addDebug($e); } echo json_encode(array('success' => false)); Migration::saveLog(__('Migration emails end with error: ', 'jigoshop') . $e); } exit; }