/**
  * {@inheritDoc}
  */
 public function processGet($request)
 {
     $gvRedeem = $this->getFormData($request);
     $translator = $this->get('translator');
     //XXX: fix for gv_mail generated URLs
     if (Toolbox::isEmpty($gvRedeem->getCouponCode())) {
         if (null != ($gvNo = $request->getParameter('gv_no'))) {
             $gvRedeem->setCouponCode($gvNo);
         }
     }
     if (!Toolbox::isEmpty($gvRedeem->getCouponCode())) {
         $couponService = $this->container->get('couponService');
         // only try to redeem if code given - people might browse the page without code parameter...
         $coupon = $couponService->getCouponForCode($gvRedeem->getCouponCode(), $request->getSession()->getLanguageId());
         if (null != $coupon && Coupon::TYPPE_GV == $coupon->getType() && $couponService->isCouponRedeemable($coupon->getId())) {
             // all good, set amount
             $gvRedeem->setAmount($coupon->getAmount());
             $gvRedeem->setRedeemed(true);
             // TODO: remote address
             $couponService->redeemCoupon($coupon->getId(), $this->getUser()->getId());
         } else {
             // not redeemable
             $this->get('session.flash_bag')->error($translator->trans('The provided gift voucher code seems to be invalid!'));
         }
     }
     return $this->findView();
 }
 /**
  * Inject html.
  */
 public function onFinaliseContent($event)
 {
     $content = $event->getArgument('content');
     // id on main div
     if (false !== strpos($content, 'theme-switcher')) {
         // already done, do not change
         return;
     }
     $request = $event->getArgument('request');
     $themeService = $this->container->get('themeService');
     $settingsService = $this->container->get('settingsService');
     $defaultConfig = null;
     if (!$settingsService->exists('plugins.themeSwitcher.themes')) {
         // iterate over all themes and build default config
         $defaultConfig = '';
         foreach ($themeService->getAvailableThemes() as $theme) {
             if (!$theme->getConfig('zencart')) {
                 $defaultConfig .= $theme->getId() . ':' . $theme->getName() . ',';
             }
         }
     }
     $themes = explode(',', $settingsService->get('plugins.themeSwitcher.themes', $defaultConfig));
     // prepare theme details list
     $themeList = array();
     foreach ($themes as $themeConfig) {
         if (!Toolbox::isEmpty(trim($themeConfig))) {
             // themeId:name
             $details = explode(':', $themeConfig);
             if (2 > count($details)) {
                 // default
                 $details[1] = $details[0];
             }
             // create url
             $router = $this->container->get('router');
             $url = $router->generate($request->getRequestId());
             $hasParams = false !== strpos($url, '?');
             $url .= ($hasParams ? '&' : '?') . 'themeId=' . $details[0];
             $themeChain = $themeService->getThemeChain($request->getSession()->getLanguageId());
             $currentTheme = array_pop($themeChain);
             $active = $details[0] == $currentTheme->getId();
             $themeList[] = array('url' => $url, 'name' => $details[1], 'active' => $active);
         }
     }
     if (null != ($view = $event->getArgument('view')) && $view instanceof TemplateView) {
         $switcherMarkup = $view->render('StorefrontBundle::theme-switcher.html.php', array('themeList' => $themeList));
         if (!empty($switcherMarkup)) {
             $content = preg_replace('/(<body[^>]*>)/', '\\1' . $switcherMarkup, $content, 1);
             $event->setArgument('content', $content);
         }
     }
 }
 /**
  * {@inheritDoc}
  *
  * @todo allow cancel at any time
  */
 public function processGet($request)
 {
     $translator = $this->get('translator');
     if (!Toolbox::asBoolean($this->getPlugin()->get('customerCancel'))) {
         $this->get('session.flash_bag')->error($translator->trans('Insufficient permission'));
         return $this->findView();
     }
     $orderId = $request->query->getInt('orderId');
     $order = $this->container->get('orderService')->getOrderForId($orderId, $request->getSession()->getLanguageId());
     $account = $order->getAccount();
     // make sure this is an allowed order
     if ($order->getAccountId() != $order->getAccountId()) {
         $this->get('session.flash_bag')->error($translator->trans('Invalid order selected'));
         return $this->findView();
     }
     $plugin = $this->getPlugin();
     // check for number of scheduled orders
     $sql = "SELECT COUNT(orders_id) AS total FROM %table.orders%\n                WHERE subscription_order_id = :subscriptionOrderId";
     $results = \ZMRuntime::getDatabase()->querySingle($sql, array('subscriptionOrderId' => $orderId), 'orders', Connection::MODEL_RAW);
     if ($results['total'] < $plugin->get('minOrders')) {
         $message = $translator->trans('This subscription can only be canceled after a minimum of %count% orders', array('%count%' => $plugin->get('minOrders')));
         $this->get('session.flash_bag')->error($message);
         return $this->findView();
     }
     $cancelDeadline = $plugin->get('cancelDeadline');
     if (0 < $cancelDeadline) {
         // this will return only a result if subscription_next_order is more than $cancelDeadline days in the future
         $sql = "SELECT orders_id\n                    FROM %table.orders%\n                    WHERE orders_id = :orderId\n                      AND DATE_SUB(subscription_next_order, INTERVAL " . $cancelDeadline . " DAY) >= CURDATE()";
         $result = \ZMRuntime::getDatabase()->querySingle($sql, array('orderId' => $orderId), 'orders', Connection::MODEL_RAW);
         if (null == $result) {
             $message = $translator->trans("Can't cancel less than %count% days before next subscription", array('%count%' => $cancelDeadline));
             $this->get('session.flash_bag')->error($message);
             return $this->findView();
         }
     }
     $sql = "UPDATE %table.orders%\n                SET is_subscription_canceled = :subscriptionCanceled\n                WHERE orders_id = :orderId";
     \ZMRuntime::getDatabase()->updateObj($sql, array('orderId' => $orderId, 'subscriptionCanceled' => true), 'orders');
     $this->get('session.flash_bag')->success($translator->trans('Subscription canceled!'));
     $settingsService = $this->container->get('settingsService');
     $emailTemplate = $settingsService->get('plugins.subscriptions.email.templates.cancel', 'subscription_cancel');
     $this->sendCancelEmail($order, $emailTemplate, $account->getEmail());
     $adminEmail = $plugin->get('adminEmail');
     if (empty($adminEmail)) {
         $adminEmail = $settingsService->get('storeEmail');
     }
     if (!Toolbox::isEmpty($adminEmail)) {
         $this->sendCancelEmail($order, $cancelEmailTemplate, $adminEmail);
     }
     return $this->findView();
 }
 /**
  * {@inheritDoc}
  */
 public function processPost($request)
 {
     $orderId = $request->request->getInt('orderId');
     $cancel = $request->request->get('cancel');
     $hard = Toolbox::asBoolean($request->request->get('hard'), false);
     if (0 != $orderId && 'cancel' == $cancel) {
         $sql = "UPDATE %table.orders%\n                    SET is_subscription_canceled = :subscriptionCanceled, is_subscription = :subscription\n                    WHERE orders_id = :orderId";
         \ZMRuntime::getDatabase()->updateObj($sql, array('orderId' => $orderId, 'subscriptionCanceled' => true, 'subscription' => !$hard), 'orders');
         $this->get('session.flash_bag')->success($this->get('translator')->trans("Subscription canceled!"));
     }
     $order = $this->container->get('orderService')->getOrderForId($orderId, $request->getSession()->getLanguageId());
     $emailTemplate = $this->container->get('settingsService')->get('plugins.subscriptions.email.templates.cancel', 'subscription_cancel');
     $email = $order->getAccount()->getEmail();
     if (!Toolbox::isEmpty($email)) {
         $this->sendCancelEmail($order, $emailTemplate, $email);
     }
     return $this->findView('success');
 }
Exemple #5
0
 /**
  * Get all (available) payment types.
  *
  * @param boolean all Optional flag to return all installed; default is <code>false</code> to return enabled only.
  * @return array List of <code>ZMPaymentType</code> instances.
  */
 public function getPaymentTypes($all = false)
 {
     if (null === $this->paymentTypes) {
         $zcPath = $this->container->getParameter('zencart.root_dir');
         $this->paymentTypes = array();
         if (defined('MODULE_PAYMENT_INSTALLED') && !Toolbox::isEmpty(MODULE_PAYMENT_INSTALLED)) {
             // get a list of modules and stuff
             $moduleInfos = array();
             foreach (explode(';', MODULE_PAYMENT_INSTALLED) as $filename) {
                 $path = $zcPath . '/includes/modules/payment/' . $filename;
                 if (file_exists($path)) {
                     $class = substr($filename, 0, strrpos($filename, '.'));
                     $moduleInfos[] = array('class' => $class, 'filename' => $filename, 'path' => $path);
                 }
             }
             foreach ($moduleInfos as $info) {
                 if (isset($GLOBALS[$info['class']])) {
                     $module = $GLOBALS[$info['class']];
                     if ($all || $module->enabled) {
                         $wrapper = Beans::getBean('ZenMagick\\ZenCartBundle\\Wrapper\\PaymentTypeWrapper');
                         $wrapper->setModule($module);
                         $this->paymentTypes[$module->code] = $wrapper;
                     }
                     continue;
                 }
                 $lang_file = $zcPath . '/includes/languages/' . $_SESSION['language'] . '/modules/payment/' . $info['filename'];
                 if (@file_exists($lang_file)) {
                     include_once $lang_file;
                 }
                 include_once $info['path'];
                 $module = new $info['class']();
                 $module->update_status();
                 if ($all || $module->enabled) {
                     $wrapper = Beans::getBean('ZenMagick\\ZenCartBundle\\Wrapper\\PaymentTypeWrapper');
                     $wrapper->setModule($module);
                     $this->paymentTypes[$module->code] = $wrapper;
                 }
             }
         }
     }
     return $this->paymentTypes;
 }
 /**
  * {@inheritDoc}
  */
 public function processGet($request)
 {
     $searchCriteria = $this->getFormData($request);
     // never search inactive products
     $searchCriteria->setSearchAll(false);
     if (!Toolbox::isEmpty($searchCriteria->getKeywords()) && 'search' == $request->attributes->get('_route')) {
         $resultList = Beans::getBean('ZMResultList');
         //TODO: filter??
         foreach (explode(',', $this->container->get('settingsService')->get('resultListProductSorter')) as $sorter) {
             $resultList->addSorter(Beans::getBean($sorter));
         }
         $resultSource = Beans::getBean('ZMSearchResultSource');
         $resultSource->setSearchCriteria($searchCriteria);
         $resultList->setResultSource($resultSource);
         $resultList->setPageNumber($request->query->getInt('page'));
         $args = array('request' => $request, 'searchCriteria' => $searchCriteria, 'resultList' => $resultList, 'autoSearch' => $this->isAutoSearch());
         $this->container->get('event_dispatcher')->dispatch('search', new GenericEvent($this, $args));
         return $this->findView('results', array('resultList' => $resultList));
     }
     return $this->findView();
 }
 /**
  * Returns <code>true</code> if this filter is currently active.
  *
  * @return boolean <code>true</code> if the filter is active, <code>false</code> if not.
  */
 public function isActive()
 {
     return !Toolbox::isEmpty($this->value);
 }
Exemple #8
0
 /**
  * Checks if the order has a shipping address.
  *
  * @return boolean <code>true</code> if a shipping address exists, <code>false</code> if not.
  */
 public function hasShippingAddress()
 {
     $address = $this->getShippingAddress();
     return !(Toolbox::isEmpty($address->getLastName()) || Toolbox::isEmpty($address->getAddressLine1()));
 }
Exemple #9
0
 /**
  * Get all accounts.
  *
  * @param string type Optional type (<code>Account::REGISTERED<code>, <code>Account::GUEST<code>); default is <code>null</code> for all.
  * @param int limit Optional limit; default is <em>0</em> for all.
  * @return array A <st of code>ZenMagick\StoreBundle\Entity\Account</code> instances.
  */
 public function getAllAccounts($type = null, $limit = 0)
 {
     $sql = "SELECT c.*, ci.*\n                FROM %table.customers% c\n                  LEFT JOIN %table.customers_info% ci ON (c.customers_id = ci.customers_info_id)";
     if (Account::REGISTERED == $type) {
         $sql .= " WHERE NOT (customers_password = '')";
     } elseif (Account::GUEST == $type) {
         $sql .= " WHERE (customers_password = '')";
     }
     $sql .= " ORDER BY c.customers_id DESC";
     if (0 < $limit) {
         $sql .= " LIMIT " . $limit;
     }
     $accounts = array();
     foreach (\ZMRuntime::getDatabase()->fetchAll($sql, array(), array('customers', 'customers_info'), 'ZenMagick\\StoreBundle\\Entity\\Account') as $account) {
         if (Toolbox::isEmpty($account->getPassword())) {
             $account->setType(Account::GUEST);
         }
         $accounts[] = $account;
     }
     return $accounts;
 }
 /**
  * Get a list of shipping providers.
  *
  * @param boolean configured If <code>true</code>, return only configured provider; default is <code>true</code>.
  * @return array List of <code>ZMShippingProvider</code> instances.
  */
 public function getShippingProviders($configured = true)
 {
     if (isset($this->providers[$configured])) {
         return $this->providers[$configured];
     }
     $settingsService = $this->container->get('settingsService');
     $zcPath = $this->container->getParameter('zencart.root_dir');
     $this->providers[$configured] = array();
     $moduleInfos = array();
     if ($configured) {
         if (defined('MODULE_SHIPPING_INSTALLED') && !Toolbox::isEmpty(MODULE_SHIPPING_INSTALLED)) {
             $files = explode(';', MODULE_SHIPPING_INSTALLED);
             foreach ($files as $file) {
                 $clazz = substr($file, 0, strrpos($file, '.'));
                 $moduleInfos[$file] = array('class' => $clazz, 'file' => $file);
             }
         }
     } else {
         $module_directory = $zcPath . '/includes/modules/shipping/';
         if ($dir = @dir($module_directory)) {
             while ($file = $dir->read()) {
                 if (!is_dir($module_directory . $file) && substr($file, strrpos($file, '.')) == '.php') {
                     $clazz = substr($file, 0, strrpos($file, '.'));
                     $moduleInfos[$file] = array('class' => $clazz, 'file' => $file);
                 }
             }
             $dir->close();
         }
     }
     sort($moduleInfos);
     //TODO:(1): bad, bad hack to make admin's zen_get_shipping_enabled() work for pages other than admin/modules.php
     global $PHP_SELF;
     $phpSelf = $PHP_SELF;
     $PHP_SELF = 'modules.php';
     // TODO: create fake environment
     global $template, $shipping_weight;
     if (!isset($template)) {
         $template = new template_func();
     }
     $activeTheme = $this->container->get('themeService')->getActiveTheme();
     $defaultLanguage = $this->container->get('languageService')->getLanguageForId($settingsService->get('storeDefaultLanguageId'));
     foreach ($moduleInfos as $moduleInfo) {
         $lang_files = array($zcPath . '/includes/languages/' . $defaultLanguage->getDirectory() . '/modules/shipping/' . $activeTheme->getId() . '/' . $moduleInfo['file'], $zcPath . '/includes/languages/' . $defaultLanguage->getDirectory() . '/modules/shipping/' . $moduleInfo['file']);
         foreach ($lang_files as $lf) {
             if (@file_exists($lf)) {
                 include_once $lf;
                 break;
             }
         }
         include_once $zcPath . '/includes/modules/shipping/' . $moduleInfo['file'];
         if (class_exists($moduleInfo['class'])) {
             // create instance
             $module = new $moduleInfo['class']();
             // either all or enabled (installed+enabled as per config option) - (is this different from $module->enabled?)
             if (!$configured || 0 < $module->check() && $module->enabled) {
                 $wrapper = Beans::getBean('ZenMagick\\ZenCartBundle\\Wrapper\\ShippingProviderWrapper');
                 $wrapper->setModule($module);
                 $this->providers[$configured][] = $wrapper;
             }
         }
     }
     //TODO:(2): revert
     $PHP_SELF = $phpSelf;
     return $this->providers[$configured];
 }
Exemple #11
0
 public static function check_alter_command($param)
 {
     $db = self::get_db();
     if (Toolbox::isEmpty($param)) {
         return "Empty SQL Statement";
     }
     switch (strtoupper($param[3])) {
         case "ADD":
             if (strtoupper($param[4]) == 'INDEX') {
                 // check that the index to be added doesn't already exist
                 $index = $param[5];
                 $sql = "show index from " . self::$prefix . $param[2];
                 $rows = $db->fetchAll($sql);
                 foreach ($rows as $fields) {
                     if (ZC_UPG_DEBUG3 == true) {
                         echo 'KEY: ' . $fields['Key_name'] . '<br />';
                     }
                     if ($fields['Key_name'] == $index) {
                         return sprintf(REASON_INDEX_ALREADY_EXISTS, $index, $param[2]);
                     }
                 }
             } elseif (strtoupper($param[4]) == 'PRIMARY') {
                 // check that the primary key to be added doesn't exist
                 if ($param[5] != 'KEY') {
                     return;
                 }
                 $sql = "show index from " . self::$prefix . $param[2];
                 $rows = $db->fetchAll($sql);
                 foreach ($rows as $fields) {
                     if (ZC_UPG_DEBUG3 == true) {
                         echo $fields['Key_name'] . '<br />';
                     }
                     if ($fields['Key_name'] == 'PRIMARY') {
                         return sprintf(REASON_PRIMARY_KEY_ALREADY_EXISTS, $param[2]);
                     }
                 }
             } elseif (!in_array(strtoupper($param[4]), array('CONSTRAINT', 'UNIQUE', 'PRIMARY', 'FULLTEXT', 'FOREIGN', 'SPATIAL'))) {
                 // check that the column to be added does not exist
                 $colname = $param[4] == 'COLUMN' ? $param[5] : $param[4];
                 $sql = "show fields from " . self::$prefix . $param[2];
                 $rows = $db->fetchAll($sql);
                 foreach ($rows as $fields) {
                     if (ZC_UPG_DEBUG3 == true) {
                         echo $fields['Field'] . '<br />';
                     }
                     if ($fields['Field'] == $colname) {
                         return sprintf(REASON_COLUMN_ALREADY_EXISTS, $colname);
                     }
                 }
             } elseif (strtoupper($param[5]) == 'AFTER') {
                 // check that the requested "after" field actually exists
                 $colname = $param[6] == 'COLUMN' ? $param[7] : $param[6];
                 $sql = "show fields from " . self::$prefix . $param[2];
                 $rows = $db->fetchAll($sql);
                 foreach ($rows as $fields) {
                     if (ZC_UPG_DEBUG3 == true) {
                         echo $fields['Field'] . '<br />';
                     }
                     if ($fields['Field'] == $colname) {
                         return;
                         // exists, so return with no error
                     }
                 }
             } elseif (strtoupper($param[6]) == 'AFTER') {
                 // check that the requested "after" field actually exists
                 $colname = $param[7] == 'COLUMN' ? $param[8] : $param[7];
                 $sql = "show fields from " . self::$prefix . $param[2];
                 $rows = $db->fetchAll($sql);
                 foreach ($rows as $fields) {
                     if (ZC_UPG_DEBUG3 == true) {
                         echo $fields['Field'] . '<br />';
                     }
                     if ($fields['Field'] == $colname) {
                         return;
                         // exists, so return with no error
                     }
                 }
                 /*
                  * @TODO -- add check for FIRST parameter, to check that the FIRST colname specified actually exists
                  */
             }
             break;
         case "DROP":
             if (strtoupper($param[4]) == 'INDEX') {
                 // check that the index to be dropped exists
                 $index = $param[5];
                 $sql = "show index from " . self::$prefix . $param[2];
                 $rows = $db->fetchAll($sql);
                 foreach ($rows as $fields) {
                     if (ZC_UPG_DEBUG3 == true) {
                         echo $fields['Key_name'] . '<br />';
                     }
                     if ($fields['Key_name'] == $index) {
                         return;
                         // exists, so return with no error
                     }
                 }
                 // if we get here, then the index didn't exist
                 return sprintf(REASON_INDEX_DOESNT_EXIST_TO_DROP, $index, $param[2]);
             } elseif (strtoupper($param[4]) == 'PRIMARY') {
                 // check that the primary key to be dropped exists
                 if ($param[5] != 'KEY') {
                     return;
                 }
                 $sql = "show index from " . self::$prefix . $param[2];
                 $rows = $db->fetchAll($sql);
                 foreach ($rows as $fields) {
                     if (ZC_UPG_DEBUG3 == true) {
                         echo $fields['Key_name'] . '<br />';
                     }
                     if ($fields['Key_name'] == 'PRIMARY') {
                         return;
                         // exists, so return with no error
                     }
                 }
                 // if we get here, then the primary key didn't exist
                 return sprintf(REASON_PRIMARY_KEY_DOESNT_EXIST_TO_DROP, $param[2]);
             } elseif (!in_array(strtoupper($param[4]), array('CONSTRAINT', 'UNIQUE', 'PRIMARY', 'FULLTEXT', 'FOREIGN', 'SPATIAL'))) {
                 // check that the column to be dropped exists
                 $colname = $param[4] == 'COLUMN' ? $param[5] : $param[4];
                 $sql = "show fields from " . self::$prefix . $param[2];
                 $rows = $db->fetchAll($sql);
                 foreach ($rows as $fields) {
                     if (ZC_UPG_DEBUG3 == true) {
                         echo $fields['Field'] . '<br />';
                     }
                     if ($fields['Field'] == $colname) {
                         return;
                         // exists, so return with no error
                     }
                 }
                 // if we get here, then the column didn't exist
                 return sprintf(REASON_COLUMN_DOESNT_EXIST_TO_DROP, $colname);
             }
             //endif 'DROP'
             break;
         case "ALTER":
         case "MODIFY":
         case "CHANGE":
             // just check that the column to be changed 'exists'
             $colname = $param[4] == 'COLUMN' ? $param[5] : $param[4];
             $sql = "show fields from " . self::$prefix . $param[2];
             $rows = $db->fetchAll($sql);
             foreach ($rows as $fields) {
                 if (ZC_UPG_DEBUG3 == true) {
                     echo $fields['Field'] . '<br />';
                 }
                 if ($fields['Field'] == $colname) {
                     return;
                     // exists, so return with no error
                 }
             }
             // if we get here, then the column didn't exist
             return sprintf(REASON_COLUMN_DOESNT_EXIST_TO_CHANGE, $colname);
             break;
         default:
             // if we get here, then we're processing an ALTER command other than what we're checking for, so let it be processed.
             return;
             break;
     }
     //end switch
 }
 /**
  * {@inheritDoc}
  */
 public function execute()
 {
     if (!$plugin || !$plugin->isEnabled()) {
         return true;
     }
     $plugin = $this->getPlugin();
     $scheduledOrders = self::findScheduledOrders();
     $scheduleEmailTemplate = Runtime::getSettings()->get('plugins.subscriptions.email.templates.schedule', 'checkout');
     $orderService = $this->container->get('orderService');
     $translator = $this->container->get('translator');
     foreach ($scheduledOrders as $scheduledOrderId) {
         // 1) copy
         $newOrder = self::copyOrder($scheduledOrderId);
         // load the new order as proper ZenMagick\StoreBundle\Entity\Order\Order instance for further use
         $order = $orderService->getOrderForId($newOrder->getOrderId(), $this->container->get('session')->getLanguageId());
         if (null === $order) {
             $this->container->get('logger')->err('copy order failed for scheduled order: ' . $scheduledOrderId);
             continue;
         }
         // 2) update shipping/billing from account to avoid stale addresses
         if ('account' == $plugin->get('addressPolicy')) {
             $account = $this->container->get('accountService')->getAccountForId($order->getAccountId());
             if (null === $account) {
                 $this->container->get('logger')->warn('invalid accountId on order: ' . $order->getId());
                 continue;
             }
             $defaultAddressId = $account->getDefaultAddressId();
             $defaultAddress = $this->container->get('addressService')->getAddressForId($defaultAddressId);
             $order->setShippingAddress($defaultAddress);
             $orderService->updateOrder($order);
         }
         // 3) update subscription specific data
         $order->set('subscriptionOrderId', $scheduledOrderId);
         $order->set('subscription', false);
         $order->setStatus($plugin->get('orderStatus'));
         $orderService->updateOrder($order);
         // 4) Create history entry if enabled
         if (Toolbox::asBoolean($plugin->get('orderHistory'))) {
             $status = Beans::getBean('ZenMagick\\StoreBundle\\Entity\\Order\\OrderStatusHistory');
             $status->setId($plugin->get('orderStatus'));
             $status->setOrderId($order->getId());
             $status->setOrderStatusId($order->getOrderStatusId());
             $status->setCustomerNotified(!Toolbox::isEmpty($scheduleEmailTemplate));
             $comment = $translator->trans('Scheduled order for subscription #%s', array('%id%' => $scheduledOrderId));
             $status->setComment($comment);
             $orderService->createOrderStatusHistory($status);
         }
         // 5) Update subscription order with next schedule date
         // calculate new subscription_next_order based on current subscription_next_order, as we might not run on the same day
         $sql = "UPDATE %table.orders%\n                    SET subscription_next_order = DATE_ADD(subscription_next_order, INTERVAL " . zm_subscriptions::schedule2SQL($order->get('schedule')) . ")\n                    WHERE orders_id = :orderId";
         $args = array('orderId' => $scheduledOrderId);
         ZMRuntime::getDatabase()->updateObj($sql, $args, 'orders');
         if (!Toolbox::isEmpty($scheduleEmailTemplate)) {
             $this->sendOrderEmail($order, $scheduleEmailTemplate);
         }
         // event
         $this->container->get('event_dispatcher')->dispatch('create_order', new GenericEvent($this, array('orderId' => $order->getId())));
     }
     return true;
 }
 /**
  * Build the search SQL.
  *
  * @param ZMSearchCriteria criteria Search criteria.
  * @return ZenMagick\Base\Database\QueryDetails The search SQL.
  */
 protected function buildQuery($criteria)
 {
     $args = array();
     $useFulltext = $this->container->get('settingsService')->get('apps.store.search.fulltext', false);
     $select = "SELECT DISTINCT p.products_id";
     if ($criteria->isIncludeTax() && (!Toolbox::isEmpty($criteria->getPriceFrom()) || !Toolbox::isEmpty($criteria->getPriceTo()))) {
         $select .= ", SUM(tr.tax_rate) AS tax_rate";
     }
     $needsP2c = 0 != $criteria->getCategoryId();
     $from = " FROM (%table.products% p\n                 LEFT JOIN %table.manufacturers% m USING(manufacturers_id),\n                 %table.products_description% pd " . ($needsP2c ? ',
                 %table.categories% c,
                 %table.products_to_categories% p2c' : '') . ") LEFT JOIN %table.meta_tags_products_description% mtpd ON mtpd.products_id= p.products_id AND mtpd.language_id = :languageId";
     $args['languageId'] = $criteria->getLanguageId();
     if ($criteria->isIncludeTax() && (!Toolbox::isEmpty($criteria->getPriceFrom()) || !Toolbox::isEmpty($criteria->getPriceTo()))) {
         $from .= " LEFT JOIN %table.tax_rates% tr ON p.products_tax_class_id = tr.tax_class_id\n                       LEFT JOIN %table.zones_to_geo_zones% gz ON tr.tax_zone_id = gz.geo_zone_id\n                         AND (gz.zone_country_id IS null OR gz.zone_country_id = 0 OR gz.zone_country_id = :zoneId)\n                         AND (gz.zone_id IS null OR gz.zone_id = 0 OR gz.zone_id = :zoneId)";
         $args['countryId'] = $criteria->getCountryId();
         $args['zoneId'] = $criteria->getZoneId();
     }
     $where = " WHERE (";
     if (!$criteria->isSearchAll()) {
         $where .= "p.products_status = 1 AND ";
     }
     $where .= "p.products_id = pd.products_id AND pd.language_id = :languageId";
     if ($needsP2c) {
         $where .= " AND p.products_id = p2c.products_id AND p2c.categories_id = c.categories_id";
         if ($criteria->isIncludeSubcategories()) {
             $where .= " AND p2c.products_id = p.products_id\n                            AND p2c.products_id = pd.products_id\n                            AND p2c.categories_id in (:categoryId)";
             $category = $this->container->get('categoryService')->getCategoryForId($criteria->getCategoryId(), $this->container->get('session')->getLanguageId());
             $args['categoryId'] = $category->getDecendantIds();
         } else {
             $where .= " AND p2c.products_id = p.products_id\n                            AND p2c.products_id = pd.products_id\n                            AND pd.language_id = :languageId\n                            AND p2c.categories_id = :categoryId";
             $args['categoryId'] = $criteria->getCategoryId();
         }
     }
     if (0 != $criteria->getManufacturerId()) {
         $where .= " AND m.manufacturers_id = :manufacturerId";
         $args['manufacturerId'] = $criteria->getManufacturerId();
     }
     $fulltext_match_order = array();
     if (!Toolbox::isEmpty($criteria->getKeywords())) {
         if ($this->parseSearchString(stripslashes($criteria->getKeywords()), $tokens)) {
             $index = 0;
             $where .= " AND (";
             foreach ($tokens as $token) {
                 switch ($token) {
                     case '(':
                     case ')':
                     case 'and':
                     case 'or':
                         $where .= " " . $token . " ";
                         break;
                     default:
                         // use name for all string operations
                         $name = ++$index . '#name';
                         $args[$name] = '%' . $token . '%';
                         if ($useFulltext) {
                             $where .= "(match(pd.products_name) against (:" . $name . ")\n                                OR match(p.products_model) against (:" . $name . ")\n                                OR m.manufacturers_name LIKE :" . $name . "";
                             $fulltext_match_order[] = "match(pd.products_name) against (:" . $name . ")+1";
                             $fulltext_match_order[] = "match(p.products_model) against (:" . $name . ")+1";
                         } else {
                             $where .= "(pd.products_name LIKE :" . $name . "\n                                OR p.products_model LIKE :" . $name . "\n                                OR m.manufacturers_name LIKE :" . $name . "";
                         }
                         // search meta tags
                         $where .= " OR (mtpd.metatags_keywords LIKE :" . $name . "\n                                    AND mtpd.metatags_keywords !='')";
                         $where .= " OR (mtpd.metatags_description LIKE :" . $name . "\n                                    AND mtpd.metatags_description !='')";
                         if ($criteria->isIncludeDescription()) {
                             if ($useFulltext) {
                                 $where .= " OR match(pd.products_description) against (:" . $name . ")";
                             } else {
                                 $where .= " OR pd.products_description LIKE :" . $name . "";
                             }
                         }
                         $where .= ')';
                         break;
                 }
             }
             $where .= ")";
         }
     }
     $where .= ')';
     $dateFormat = $this->container->get('localeService')->getFormat('date', 'short');
     if (!Toolbox::isEmpty($criteria->getDateFrom())) {
         $where .= " AND p.products_date_added >= :1#dateAdded";
         $args['1#dateAdded'] = \DateTime::createFromFormat($dateFormat, $criteria->getDateFrom());
     }
     if (!Toolbox::isEmpty($criteria->getDateTo())) {
         $where .= " AND p.products_date_added <= :2#dateAdded";
         $args['2#dateAdded'] = \DateTime::createFromFormat($dateFormat, $criteria->getDateTo());
     }
     if ($criteria->isIncludeTax()) {
         if (!Toolbox::isEmpty($criteria->getPriceFrom())) {
             $where .= " AND (p.products_price_sorter * IF(gz.geo_zone_id IS null, 1, 1 + (tr.tax_rate / 100)) >= :1#productPrice)";
             $args['1#productPrice'] = $criteria->getPriceFrom();
         }
         if (!Toolbox::isEmpty($criteria->getPriceTo())) {
             $where .= " AND (p.products_price_sorter * IF(gz.geo_zone_id IS null, 1, 1 + (tr.tax_rate / 100)) <= :2#productPrice)";
             $args['2#productPrice'] = $criteria->getPriceTo();
         }
     } else {
         if (!Toolbox::isEmpty($criteria->getPriceFrom())) {
             $where .= " AND (p.products_price_sorter >= :1#productPrice)";
             $args['1#productPrice'] = $criteria->getPriceFrom();
         }
         if (!Toolbox::isEmpty($criteria->getPriceTo())) {
             $where .= " AND (p.products_price_sorter <= :2#productPrice)";
             $args['2#productPrice'] = $criteria->getPriceTo();
         }
     }
     if ($criteria->isIncludeTax() && (!Toolbox::isEmpty($criteria->getPriceFrom()) || !Toolbox::isEmpty($criteria->getPriceTo()))) {
         $where .= " GROUP BY p.products_id, tr.tax_priority";
     }
     $sort = " ORDER BY\n";
     if (null !== $this->sortId) {
         switch ($this->sortId) {
             case 'model':
                 $sort .= " p.products_model " . ($this->descending ? "DESC" : "") . ", pd.products_name";
                 break;
             case 'name':
                 $sort .= " pd.products_name " . ($this->descending ? "DESC" : "");
                 break;
             case 'manufacturer':
                 $sort .= " m.manufacturers_name " . ($this->descending ? "DESC" : "") . ", pd.products_name";
                 break;
             case 'price':
                 $sort .= " p.products_price_sorter " . ($this->descending ? "DESC" : "") . ", pd.products_name";
                 break;
             case 'weight':
                 $sort .= " p.products_weight " . ($this->descending ? "DESC" : "") . ", pd.products_name";
                 break;
             default:
                 $this->container->get('logger')->warn('invalid sort id: ' . $this->sortId);
                 $sort .= " p.products_sort_order,  pd.products_name";
                 break;
         }
     } else {
         if ($useFulltext) {
             $sort .= join('*', $fulltext_match_order) . ' DESC, ';
         }
         $sort .= " p.products_sort_order,  pd.products_name";
     }
     $sql = $select . $from . $where . $sort;
     $tables = array('products', 'products_description', 'manufacturers', 'categories', 'tax_rates', 'zones_to_geo_zones');
     return new QueryDetails(\ZMRuntime::getDatabase(), $sql, $args, $tables, null, 'p.products_id');
 }
 /**
  * {@inheritDoc}
  */
 public function getInfo()
 {
     if (isset($this->module->email_footer) && !Toolbox::isEmpty($this->module->email_footer)) {
         return $this->module->email_footer;
     }
     return null;
 }
 /**
  * Load product info.
  */
 protected function loadProduct()
 {
     if (null == $this->getRequest()->query->get('productId') || null != $this->productName) {
         return;
     }
     if (null != ($this->product = $this->container->get('productService')->getProductForId($this->getRequest()->query->get('productId'), $this->getRequest()->getSession()->getLanguageId()))) {
         $this->productName = $this->product->getName();
         if (!Toolbox::isEmpty($this->product->getModel())) {
             $this->productName .= ' [' . $this->product->getModel() . ']';
         }
     }
 }
 /**
  * {@inheritDoc}
  */
 public function hasIcon()
 {
     return !Toolbox::isEmpty($this->zenModule->icon);
 }
Exemple #17
0
 /**
  * Format an address according to the countries address format.
  *
  * <p>The following values are available for display:</p>
  *
  * <ul>
  *  <li><code>$firstname</code> - The first name</li>
  *  <li><code>$lastname</code> - The last name</li>
  *  <li><code>$company</code> - The company name</li>
  *  <li><code>$street</code> - The street address</li>
  *  <li><code>$streets</code> - Depending on availablility either <code>$street</code> or <code>$street$cr$suburb</code></li>
  *  <li><code>$suburb</code> - The subrub</li>
  *  <li><code>$city</code> - The city</li>
  *  <li><code>$state</code> - The state (either from the list of states or manually entered)</li>
  *  <li><code>$country</code> - The country name</li>
  *  <li><code>$postcode</code>/<code>$zip</code> - The post/zip code</li>
  *  <li><code>$hr</code> - A horizontal line</li>
  *  <li><code>$cr</code> - New line character</li>
  *  <li><code>$statecomma</code> - The sequence <code>$state, </code> (note the trailing space)</li>
  * </ul>
  *
  * <p>If address is <code>null</code>, the localized version of <em>N/A</em> will be returned.</p>
  *
  * @param ZenMagick\StoreBundle\Entity\Address address The address to format.
  * @param boolean html If <code>true</code>, format as HTML, otherwise plain text.
  * @return string A fully formatted address that, depending on the <em>html</code> flag, is either HTML or ASCII formatted.
  */
 public function formatAddress($address, $html = true)
 {
     if (null == $address) {
         $out = $this->container->get('translator')->trans('N/A');
     } else {
         if (!Toolbox::isEmpty($address->getLastName())) {
             $firstname = $address->getFirstName();
             $lastname = $address->getLastName();
         } else {
             $firstname = '';
             $lastname = '';
         }
         $company = $address->getCompanyName();
         $street = $address->getAddressLine1();
         $suburb = $address->getSuburb();
         $city = $address->getCity();
         $state = $address->getState();
         $countryService = $this->container->get('countryService');
         if (0 != $address->getCountryId()) {
             $zmcountry = $address->getCountry();
             $country = $zmcountry->getName();
             if (0 != $address->getZoneId()) {
                 $state = $countryService->getZoneCode($zmcountry->getId(), $address->getZoneId(), $state);
             }
         } else {
             $zmcountry = $countryService->getCountryForId($this->container->get('settingsService')->get('storeCountry'));
             $country = '';
             $state = '';
         }
         $postcode = $address->getPostcode();
         $boln = '';
         if ($html) {
             $hr = '<hr>';
             $cr = '<br />';
         } else {
             $hr = '----------------------------------------';
             $cr = "\n";
         }
         // encode
         $vars = array('firstname', 'lastname', 'company', 'street', 'suburb', 'city', 'state', 'country', 'postcode');
         foreach ($vars as $var) {
             ${$var} = $this->getToolbox()->html->encode(${$var});
         }
         // alias or derived
         $zip = $postcode;
         $statecomma = '';
         $streets = $street;
         if ($suburb != '') {
             $streets = $street . $cr . $suburb;
         }
         if ($state != '') {
             $statecomma = $state . ', ';
         }
         $format = $this->container->get('addressService')->getAddressFormatForId($zmcountry->getAddressFormatId());
         // $format is using all the local variables...
         eval("\$out = \"{$format}\";");
         $company = $address->getCompanyName();
         if ($this->container->get('settingsService')->get('isAccountCompany') && !empty($company)) {
             $out = $company . $cr . $out;
         }
     }
     return $out;
 }
 /**
  * {@inheritDoc}
  */
 public function render($request, TemplateView $templateView)
 {
     if (!$this->container->get('settingsService')->get('apps.store.banners.enabled', true)) {
         return '';
     }
     $bannerService = $this->container->get('bannerService');
     // try to load banners for the given group
     if (empty($this->group) || null == ($banners = $bannerService->getBannersForGroupName($this->group, $request->isSecure()))) {
         return '';
     }
     // make random
     shuffle($banners);
     // first or all
     if (!$this->showAll) {
         $banners = array(array_pop($banners));
     }
     // render banner(s)
     $bannerContentList = array();
     foreach ($banners as $banner) {
         $content = '';
         if (!Toolbox::isEmpty($banner->getText())) {
             // use text if not empty
             $content .= $banner->getText();
         } else {
             $toolbox = Runtime::getContainer()->get('toolbox');
             $html = $toolbox->html;
             $net = $toolbox->net;
             $img = '<img src="' . $net->image($banner->getImage()) . '" alt="' . $html->encode($banner->getTitle()) . '" />';
             if (Toolbox::isEmpty($banner->getUrl())) {
                 // if we do not have a url try our luck with the image...
                 $content .= $img;
             } else {
                 $class = '';
                 if ($banner->isNewWin()) {
                     $class = ' class="new-win" ';
                 }
                 $content .= '<a href="' . $net->trackLink('banner', $banner->getId()) . '"' . $class . '>' . $img . '</a>';
             }
         }
         if ($this->isTrackDisplay()) {
             $bannerService->updateBannerDisplayCount($banner->getId());
         }
         if (!Toolbox::isEmpty($this->getFormat()) && !empty($content)) {
             $content = sprintf($this->getFormat(), $content);
         }
         $bannerContentList[] = $content;
     }
     // always set
     $this->set('bannerContentList', $bannerContentList);
     if (!Toolbox::isEmpty($this->getTemplate())) {
         // leave formatting to template rather than just concatenating
         return parent::render($request, $engine);
     }
     return implode('', $bannerContentList);
 }
Exemple #19
0
 /**
  * Build an ez-page URL.
  *
  * @param ZenMagick\StoreBundle\Entity\EZPage an EZPage instance
  * @param bool absolute generate absolute url
  * @return string A complete URL for the given ez-page.
  * @todo create ezpage router loader for SSL links.
  * @todo remove absolute param
  */
 public function ezPage($page, $absolute = false)
 {
     if (null === $page) {
         $translator = $this->container->get('translator');
         $href = $translator->trans('ezpage not found');
         return $href;
     }
     $params = array('id' => $page->getId());
     if (0 != $page->getTocChapter()) {
         $params['chapter'] = $page->getTocChapter();
     }
     // We are abusing the 3rd generate param to hack up SSL links
     $absolute = $absolute || $page->isSsl();
     $router = $this->container->get('router');
     $href = $router->generate('page', $params, $absolute);
     if (!Toolbox::isEmpty($page->getAltUrl())) {
         $url = parse_url($page->getAltUrl());
         parse_str($url['query'], $query);
         $view = $query['main_page'];
         unset($query['main_page']);
         $href = $router->generate($view, $query, $absolute);
     } elseif (!Toolbox::isEmpty($page->getAltUrlExternal())) {
         $href = $page->getAltUrlExternal();
     }
     if ($page->isSsl()) {
         $href = str_replace('http:', 'https:', $href);
     }
     return $href;
 }
 /**
  * Validate the captcha value.
  *
  * @param ZenMagick\Http\Request request The current request.
  * @param array data The data.
  * @return boolean <code>true</code> if the captcha is valid, <code>false</code> if not.
  */
 public function vRecaptcha($request, $data)
 {
     if (Toolbox::isEmpty($request->getParameter(RECAPTCHA_FIELD))) {
         // we have a required rule, so no need for additional checks
         return true;
     }
     $resp = recaptcha_check_answer($this->get('privateKey'), $request->getClientIp(), $request->request->get('recaptcha_challenge_field'), $request->request->get('recaptcha_response_field'));
     if ($resp->is_valid) {
         return true;
     } else {
         $this->setError($resp->error);
         return false;
     }
 }