/**
  * {@inheritDoc}
  */
 public function processPost($request)
 {
     $shoppingCart = $this->get('shoppingCart');
     $checkoutHelper = $shoppingCart->getCheckoutHelper();
     $settingsService = $this->container->get('settingsService');
     if (!$checkoutHelper->verifyHash($request)) {
         return $this->findView('check_cart');
     }
     if ('free_free' == $_SESSION['shipping']) {
         // <johnny> When does this actually happen?
         $this->get('logger')->warn('fixing free_free shipping method info');
         $translator = $this->get('translator');
         $_SESSION['shipping'] = array('title' => $translator->trans('Free Shipping'), 'cost' => 0, 'id' => 'free_free');
     }
     if (null !== ($viewId = $checkoutHelper->validateCheckout($request, false))) {
         return $this->findView($viewId);
     }
     if (null !== ($viewId = $checkoutHelper->validateAddresses($request, true))) {
         return $this->findView($viewId);
     }
     if (null != ($comments = $request->request->get('comments'))) {
         $shoppingCart->setComments($comments);
     }
     if ($settingsService->get('isConditionsMessage') && !Toolbox::asBoolean($request->request->get('conditions'))) {
         $this->get('session.flash_bag')->error($translator->trans('Please confirm the terms and conditions bound to this order by ticking the box below.'));
         return $this->findView();
     }
     if (null != ($paymentMethod = $request->request->get('payment'))) {
         $request->getSession()->set('payment', $paymentMethod);
     }
     return $this->processGet($request);
 }
    /**
     * Event callback to add required JS.
     */
    public function onFinaliseContent($event)
    {
        $request = $event->getArgument('request');
        if ('store_locator' == $request->getRequestId()) {
            $storeKey = $this->get('storeKey');
            $location = $this->get('location');
            $zoom = $this->get('zoom');
            $markerText = $this->get('marker_text');
            $controls = Toolbox::asBoolean($this->get('controls'));
            $script = '
<script type="text/javascript" src="http://www.google.com/jsapi?key=' . $storeKey . '"></script>
<script type="text/javascript">
  google.load("maps", "2.x");
  function load_locator_map()
  {
    var map = new GMap2(document.getElementById("locator_map"));
    ' . ($controls ? 'map.addControl(new GLargeMapControl());/*map.addControl(new GMapTypeControl());*/' : '') . '
    map.setCenter(new GLatLng(' . $location . '), ' . $zoom . ');
    var marker = new GMarker(map.getCenter());
    map.addOverlay(marker);
    ' . (!empty($markerText) ? 'marker.openInfoWindowHtml("' . $markerText . '")' : '') . '
  }
  google.setOnLoadCallback(load_locator_map);
</script>
';
            $content = $event->getArgument('content');
            $content = preg_replace('/<\\/body>/', $script . '</body>', $content, 1);
            $event->setArgument('content', $content);
        }
    }
Пример #3
0
 /**
  * {@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();
 }
 /**
  * {@inheritDoc}
  */
 public function processPost($request)
 {
     $globalProductSubscriber = Toolbox::asBoolean($request->request->get('product_global', false));
     $account = $this->getUser();
     $isGlobalUpdate = false;
     if ($globalProductSubscriber != $account->isGlobalProductSubscriber()) {
         $account->setGlobalProductSubscriber($globalProductSubscriber);
         $this->container->get('accountService')->setGlobalProductSubscriber($account->getId(), $globalProductSubscriber);
         $isGlobalUpdate = true;
     }
     $notifyType = $request->request->get('notify_type');
     $subscribedProducts = $request->request->get('notify', array());
     if (!$isGlobalUpdate && 'set' == $notifyType) {
         // if global update is on, products are not listed in the form,
         // therefore, they would all be removed if updated!
         $account = $this->container->get('accountService')->setSubscribedProductIds($account, $subscribedProducts);
     }
     $message = $this->get('translator')->trans('Your product subscriptions have been updated.');
     $this->get('session.flash_bag')->success($message);
     switch ($notifyType) {
         case 'add':
             $account = $this->container->get('accountService')->addSubscribedProductIds($account, $subscribedProducts);
             return new RedirectResponse($request->headers->get('referer'));
             break;
         case 'remove':
             $account = $this->container->get('accountService')->removeSubscribedProductIds($account, $subscribedProducts);
             return new RedirectResponse($request->headers->get('referer'));
             break;
     }
     return $this->findView('success', array('currentAccount' => $account));
 }
 /**
  * {@inheritDoc}
  */
 public function processPost($request)
 {
     $translator = $this->get('translator');
     $emailAddress = $request->request->get('email_address');
     $account = $this->container->get('accountService')->getAccountForEmailAddress($emailAddress);
     if (null === $account || Account::REGISTERED != $account->getType()) {
         $this->get('session.flash_bag')->error($translator->trans("Sorry, there is no account with the email address '%email%'.", array('%email%' => $emailAddress)));
         return $this->findView();
     }
     $encoder = $this->get('security.encoder_factory')->getEncoder($account);
     $minLength = $this->get('settingsService')->get('zenmagick.base.security.authentication.minPasswordLength', 8);
     $newPassword = Toolbox::random($minLength, Toolbox::RANDOM_MIXED);
     $newEncodedPassword = $encoder->encodePassword($newPassword);
     // update account password (encrypted)
     $this->container->get('accountService')->setAccountPassword($account->getId(), $newEncodedPassword);
     // send email (clear text)
     $settingsService = $this->container->get('settingsService');
     $message = $this->container->get('messageBuilder')->createMessage('password_forgotten', true, $request, array('password' => $newPassword));
     $message->setSubject($translator->trans('Forgotten Password - %store_name%', array('%store_name%' => $settingsService->get('storeName'))))->setTo($emailAddress, $account->getFullName())->setFrom($settingsService->get('storeEmail'));
     $this->container->get('mailer')->send($message);
     $this->container->get('event_dispatcher')->dispatch('password_changed', new GenericEvent($this, array('controller' => $this, 'account' => $account, 'clearPassword' => $newPassword)));
     // report success
     $this->get('session.flash_bag')->success($translator->trans('A new password has been sent to your email address.'));
     return $this->findView('success');
 }
Пример #6
0
 /**
  * Get/load the feed.
  *
  * @param string url The feed url.
  * @param string category An optional category; default is <code>null</code>.
  * @param int limit An optional item limit; default is 5; use 0 for all.
  * @return RssFedd A <code>RssFeed</code> instance.
  */
 public function getFeed($url, $category = null, $limit = 5)
 {
     $cacheKey = Toolbox::hash('feeds', $url, implode(':', $this->config));
     if (!$this->cache || false === ($rssParser = $this->cache->lookup($cacheKey))) {
         $rssParser = new RssParser($this->config);
         // todo: conditional GET
         $rssParser->parse(file_get_contents($url, $this->config['useIncludePath'], $this->getContext()));
     }
     $feed = new RssFeed();
     $feed->setChannel(new RssChannel($rssParser->getChannel()));
     $items = array();
     foreach ($rssParser->getItems() as $itemData) {
         $item = new RssItem($itemData);
         if (null == $category || in_array($category, $item->getCategories())) {
             $items[] = $item;
         }
         if (0 != $limit && $limit <= count($items)) {
             break;
         }
     }
     $feed->setItems(new \ArrayIterator($items));
     // cache if enabled
     if ($this->cache) {
         $this->cache->save($rssParser, $cacheKey);
     }
     return $feed;
 }
 /**
  * {@inheritDoc}
  */
 public function encodePassword($raw, $salt = null)
 {
     $password = '';
     for ($i = 0; $i < 10; $i++) {
         $password .= Toolbox::random(Toolbox::RANDOM_MIXED);
     }
     $salt = substr(md5($password), 0, 2);
     $password = md5($salt . $raw) . ':' . $salt;
     return $password;
 }
Пример #8
0
 /**
  * Create a new result list sorter.
  *
  * @param string id Optional sorter id.
  * @param string name Optional sorter name.
  * @param string sortId Optional sort id.
  */
 public function __construct($id = null, $name = '', $sortId = null)
 {
     parent::__construct();
     $this->id = $id;
     $this->sortId = $sortId;
     $this->descending = Toolbox::endsWith($this->sortId, '_d');
     if (Toolbox::endsWith($this->sortId, '_a') || $this->descending) {
         $this->sortId = substr($this->sortId, 0, strlen($this->sortId) - 2);
     }
 }
 /**
  * {@inheritDoc}
  */
 public function processGet($request)
 {
     //TODO: this should be POST!!
     $productGroupPricing = Beans::getBean('ZenMagick\\plugins\\productGroupPricing\\model\\ProductGroupPricing');
     if (Toolbox::asBoolean($request->getParameter('delete'))) {
         $productGroupPricing->populate($request);
         // delete
         $this->container->get('productGroupPricingService')->updateProductGroupPricing($productGroupPricing);
     }
     return $this->findView(null, array('productGroupPricing' => $productGroupPricing));
 }
 /**
  * {@inheritDoc}
  */
 public function processPost($request)
 {
     $newsletterSubscriber = Toolbox::asBoolean($request->request->get('newsletter_general', false));
     $account = $this->getUser();
     if ($newsletterSubscriber != $account->isNewsletterSubscriber()) {
         $account->setNewsletterSubscriber($newsletterSubscriber);
         $this->container->get('accountService')->updateAccount($account);
     }
     $this->get('session.flash_bag')->success($this->get('translator')->trans('Your newsletter subscription has been updated.'));
     return $this->findView('success', array('currentAccount' => $account));
 }
Пример #11
0
 /**
  * Run cron.
  *
  * <p>This method is used by all methods to execute cron jobs.</p>
  *
  * <p>All output is captured and logged.</p>
  */
 public function runCron()
 {
     ob_start();
     $cron = new CronJobs($this->getConfigPath('etc/crontab.txt'), $this->getConfigPath('etc/cronhistory.txt'));
     if ($cron->isTimeToRun()) {
         // update timestamp to stop other instances from running
         $cron->updateTimestamp();
         foreach ($cron->getJobs(false, Toolbox::asBoolean($this->get('missedRuns'))) as $job) {
             $cron->runJob($job);
         }
     }
     $this->container->get('logger')->debug('Cron: ' . ob_get_clean());
 }
Пример #12
0
 /**
  * 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();
 }
Пример #14
0
 /**
  * Event handler.
  */
 public function onFinaliseContent($event)
 {
     $request = $event->getArgument('request');
     $trackerCode = $this->getTrackerCodeGa($request);
     $checkoutCode = $this->getCheckoutCodeGa($request);
     $code = !empty($checkoutCode) ? $checkoutCode : $trackerCode;
     $code .= $this->getConversionCode($request);
     if (Toolbox::asBoolean($this->get('debug'))) {
         $code = str_replace('<script', '<!--script', $code);
         $code = str_replace('</script>', '/script-->', $code);
     }
     $content = $event->getArgument('content');
     $content = preg_replace('/<\\/body>/', $code . '</body>', $content, 1);
     $event->setArgument('content', $content);
 }
 /**
  * {@inheritDoc}
  */
 public function getViewData($request)
 {
     if (!Toolbox::asBoolean($request->getParameter('other', false))) {
         $sql = "SELECT count(ci.customers_info_source_id) AS count, s.sources_name AS name, s.sources_id as sourceId\n                    FROM %table.customers_info% ci LEFT JOIN %table.sources% s ON s.sources_id = ci.customers_info_source_id\n                    GROUP BY s.sources_id\n                    ORDER BY ci.customers_info_source_id DESC";
         $isOther = false;
     } else {
         $sql = "SELECT count(ci.customers_info_source_id) as count, so.sources_other_name as name\n                  FROM %table.customers_info% ci, %table.sources_other% so\n                  WHERE ci.customers_info_source_id = " . ID_SOURCE_OTHER . " AND so.customers_id = ci.customers_info_id\n                  GROUP BY so.sources_other_name\n                  ORDER BY so.sources_other_name DESC";
         $isOther = true;
     }
     $sourceStats = \ZMRuntime::getDatabase()->fetchAll($sql, array(), array('sources'), 'ZenMagick\\Base\\ZMObject');
     $resultSource = new ZMArrayResultSource('ZenMagick\\Base\\ZMObject', $sourceStats);
     $resultList = Beans::getBean('ZMResultList');
     $resultList->setResultSource($resultSource);
     $resultList->setPageNumber($request->query->get('page', 1));
     return array('resultList' => $resultList, 'isOther' => $isOther);
 }
Пример #16
0
 /**
  * Populate all available fields from the given request.
  *
  * @param ZenMagick\Http\Request request The current request.
  */
 public function populate($request)
 {
     $this->id = $request->getParameter('groupPricingId', '0');
     $this->productId = $request->get('productId');
     $this->groupId = $request->getParameter('groupId', '0');
     $this->discount = $request->getParameter('discount', '0');
     $this->type = $request->getParameter('type', '%');
     $this->allowSaleSpecial = Toolbox::asBoolean($request->getParameter('allowSaleSpecial', false));
     $startDate = $request->getParameter('startDate');
     if (empty($startDate)) {
         // default to current date
         $startDate = new \DateTime();
     }
     $localeService = $this->container->get('localeService');
     $this->startDate = \DateTime::createFromFormat($localeService->getFormat('date', 'short'), $startDate);
     $this->endDate = \DateTime::createFromFormat($localeService->getFormat('date', 'short'), $request->getParameter('endDate'));
 }
 /**
  * {@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');
 }
Пример #18
0
 /**
  * Pull either a Gravatar URL or complete image tag for a specified email address.
  *
  * @param  string $email The email address
  * @param  string $s     Size in pixels, defaults to 80px [ 1 - 512 ]
  * @param  string $d     Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
  * @param  string $r     Maximum rating (inclusive) [ g | pg | r | x ]
  * @param  boole  $img   True to return a complete IMG tag False for just the URL
  * @param  array  $atts  Optional, additional key/value attributes to include in the IMG tag
  * @return String containing either just a URL or a complete image tag
  * @source http://gravatar.com/site/implement/images/php/
  */
 private function pullGravatar($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array())
 {
     $request = $this->container->get('request');
     $url = $request->isSecure() ? 'https://secure.gravatar.com/avatar/' : 'http://www.gravatar.com/avatar/';
     $url .= md5(strtolower(trim($email)));
     $url .= "?s={$s}&d={$d}&r={$r}";
     if (Toolbox::asBoolean($this->get('forceReload'))) {
         $url .= '&ts=' . time();
     }
     if ($img) {
         $url = '<img src="' . $url . '"';
         foreach ($atts as $key => $val) {
             $url .= ' ' . $key . '="' . $val . '"';
         }
         $url .= ' />';
     }
     return $url;
 }
Пример #19
0
 /**
  * {@inheritDoc}
  */
 public function processAction(Request $request)
 {
     $controllers = $this->getCatalogContentControllers($request);
     $controller = null;
     if (null == ($catalogRequestId = $request->query->get('catalogRequestId'))) {
         if (0 < count($controllers)) {
             $controller = $controllers[0];
             $catalogRequestId = $controller->getCatalogRequestId();
             $this->get('logger')->debug('defaulting to controller : ' . get_class($controller));
         }
     } else {
         // let's see if we have a controller for this...
         $definition = Toolbox::className($catalogRequestId . 'Controller');
         $controller = Beans::getBean($definition);
         $this->get('logger')->debug('delegating to controller : ' . get_class($controller));
     }
     // check authorization as we'll need the follow up redirect point to the catalog URL, not a tab url
     $authorized = $this->container->get('sacsManager')->authorize($request, $request->getRequestId(), $this->getUser(), false);
     if (null == $controller || !$authorized) {
         // no controller found
         return parent::processAction($request);
     }
     // fake requestId
     $requestId = $request->getRequestId();
     $request->setRequestId($catalogRequestId);
     // processAction
     $catalogViewContent = null;
     try {
         $catalogContentView = $controller->processAction($request);
         $catalogContentView->setLayout(null);
         $catalogViewContent = $catalogContentView->generate($request);
     } catch (Exception $e) {
         $catalogViewContent = null;
     }
     // restore for normal processing
     $request->setRequestId($requestId);
     // now do the normal thing
     $view = parent::processAction($request);
     // add catalog content view to be used in catalog view template
     $view->setVariable('catalogRequestId', $catalogRequestId);
     $view->setVariable('catalogViewContent', $catalogViewContent);
     $view->setVariable('controllers', $controllers);
     return $view;
 }
Пример #20
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;
 }
 /**
  * Update plugin status.
  */
 public function setPluginStatus($rpcRequest)
 {
     $data = $rpcRequest->getData();
     $pluginId = $data->pluginId;
     $status = Toolbox::asBoolean($data->status);
     $rpcResponse = $rpcRequest->createResponse();
     $pluginService = $this->container->get('pluginService');
     $translator = $this->get('translator');
     if (null == ($plugin = $pluginService->getPluginForId($pluginId, true))) {
         $rpcResponse->setStatus(false);
         $rpcResponse->addMessage($translator->trans('Invalid plugin id'), 'error');
     } else {
         $configPrefix = PluginsController::prefix($plugin);
         $configService = $this->container->get('configService');
         $this->container->get('configService')->updateConfigValue($configPrefix . PluginOptionsLoader::KEY_ENABLED, $status);
         $rpcResponse->addMessage($translator->trans('Status updated'), 'success');
     }
     $this->container->get('pluginStatusMapBuilder')->getStatusMap(true);
     return $rpcResponse;
 }
Пример #22
0
 /**
  * {@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();
 }
 /**
  * Set page property.
  */
 public function setEZPageProperty($rpcRequest)
 {
     $data = $rpcRequest->getData();
     $pageId = $data->pageId;
     $languageId = $data->languageId;
     $property = $data->property;
     $value = $data->value;
     if (in_array($property, array('NewWin', 'SSL', 'header', 'sidebox', 'footer', 'toc'))) {
         $value = Toolbox::asBoolean($value);
     }
     $rpcResponse = $rpcRequest->createResponse();
     $ezPageService = $this->container->get('ezPageService');
     if (null != ($ezPage = $ezPageService->getPageForId($pageId, $languageId))) {
         Beans::setAll($ezPage, array($property => $value));
         $ezPageService->updatePage($ezPage);
         $rpcResponse->setStatus(true);
     } else {
         $rpcResponse->setStatus(false);
     }
     return $rpcResponse;
 }
 /**
  * {@inheritDoc}
  */
 public function processPost($request)
 {
     $email = $request->request->get('email');
     $adminUserService = $this->container->get('adminUserService');
     $user = $adminUserService->getUserForEmail($email);
     $translator = $this->get('translator');
     if (null === $user) {
         $message = $translator->trans("Sorry, there is no account with that email address '%s'.", array('%email%' => $email));
         $this->get('session.flash_bag')->error($message);
         return $this->findView();
     }
     $encoder = $this->get('security.encoder_factory')->getEncoder($user);
     $minLength = $this->get('settingsService')->get('zenmagick.base.security.authentication.minPasswordLength', 8);
     $newPassword = Toolbox::random($minLength, Toolbox::RANDOM_MIXED);
     $newEncrpytedPassword = $encoder->encodePassword($newPassword);
     $user->setPassword($newEncrpytedPassword);
     $adminUserService->updateUser($user);
     $message = $this->container->get('messageBuilder')->createMessage('reset_password', false, $request, array('newPassword' => $newPassword));
     $message->setSubject($translator->trans('New password request'))->setTo($email)->setFrom($this->container->get('settingsService')->get('storeEmail'));
     $this->container->get('mailer')->send($message);
     // report success
     $this->get('session.flash_bag')->success($translator->trans('A new password has been sent to your email address.'));
     return $this->findView('success');
 }
Пример #25
0
 /**
  * Get all ZM menu data.
  *
  * @todo refactor this back into a loader system
  */
 protected function getMenuData()
 {
     $settingsService = $this->container->get('settingsService');
     $menuFiles = $settingsService->get('apps.store.admin.menus');
     $menuData = array();
     // @todo support relative and absolute paths (and also placeholder paths)
     foreach ($menuFiles as $menuFile) {
         $menuData = Toolbox::arrayMergeRecursive($menuData, Yaml::parse($this->container->getParameter('zenmagick.root_dir') . '/' . $menuFile));
     }
     $contextConfigLoader = $this->container->get('contextConfigLoader');
     foreach ($contextConfigLoader->getMenus() as $pluginMenu) {
         $menuData = Toolbox::arrayMergeRecursive($menuData, $pluginMenu);
     }
     $configGroups = $this->container->get('configService')->getConfigGroups();
     foreach ($configGroups as $group) {
         if ($group->isVisible()) {
             $id = strtolower($group->getName());
             $id = str_replace(' ', '-', $id);
             $id = str_replace('/', '-', $id);
             $menuData['children']['configuration']['children']['configuration-legacy']['children'][$id] = array('label' => $group->getName(), 'route' => 'legacy_config', 'routeParameters' => array('groupId' => $group->getId()));
         }
     }
     return $menuData;
 }
Пример #26
0
 /**
  * Merge in a map of settings.
  *
  * @param mixed settings Either a map of settings or another <code>Settings</code> instance.
  */
 public function setAll($settings)
 {
     if ($settings instanceof Settings) {
         $settings = $settings->getAll();
     }
     if (is_array($settings)) {
         $this->settings = Toolbox::arrayMergeRecursive($this->settings, $settings);
     }
 }
Пример #27
0
 /**
  * Check if guest checkout should be handled as well.
  *
  * @return boolean <code>true</code> if enabled.
  */
 public function isEnableOnGuestCheckout()
 {
     return Toolbox::asBoolean($this->get('enableOnGuestCheckout'));
 }
Пример #28
0
 /**
  * Build status map.
  *
  * @return array Plugin status map.
  */
 protected function buildStatusMap()
 {
     // this could be merged, but it seems simpler to avoid more nesting...
     $pathIdMap = array();
     foreach ($this->pluginDirs as $basePath) {
         if (file_exists($basePath) && is_dir($basePath)) {
             $pathIdMap[$basePath] = array();
             foreach (new \DirectoryIterator($basePath) as $filename => $fileInfo) {
                 if ($fileInfo->isDir() && !$fileInfo->isDot() && file_exists($fileInfo->getPathname() . '/plugin.yaml')) {
                     $id = $fileInfo->getFilename();
                     $pathIdMap[$basePath][] = array('id' => $fileInfo->getFilename(), 'pluginDir' => $fileInfo->getPathname());
                 }
             }
         }
     }
     $statusMap = array();
     foreach ($pathIdMap as $basePath => $pathInfo) {
         foreach ($pathInfo as $info) {
             $id = $info['id'];
             $pluginDir = $info['pluginDir'];
             $pluginClass = Toolbox::className($id);
             $pluginClasses = array();
             $pluginClasses[] = sprintf(Plugins::PLUGIN_BASE_NAMESPACE . '\\%s\\%sPlugin', $id, $pluginClass);
             $pluginClasses[] = $this->defaultPluginClass;
             foreach ($pluginClasses as $pluginClass) {
                 if (class_exists($pluginClass)) {
                     break;
                 }
                 $pluginClass = null;
             }
             if ($pluginClass && class_exists($pluginClass)) {
                 $config = array();
                 $pluginConfig = $pluginDir . '/plugin.yaml';
                 $config = Yaml::parse($pluginConfig);
                 // add some stuff
                 $config['meta']['id'] = $id;
                 $config['meta']['pluginDir'] = $pluginDir;
                 $config['meta']['class'] = $pluginClass;
                 // final adjustments
                 $statusMap[$id] = $this->pluginOptionsLoader->load($id, $config);
             }
         }
     }
     return $statusMap;
 }
Пример #29
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
 }
Пример #30
0
 /**
  * Load rules
  *
  * @param mixed resource yaml data or filename
  * @param boolean override Optional flag to control whether to override existing mappings or to merge;
  *  default is <code>true</code> to override.
  *
  * @todo use a real loader
  */
 public function load($resource, $override = true)
 {
     if (Toolbox::endsWith($resource, '.php') && file_exists($resource)) {
         include $resource;
         return;
     }
     if (null != ($rules = Yaml::parse($resource)) && is_array($rules)) {
         foreach ($rules as $id => $fieldRules) {
             foreach ($fieldRules as $field => $rules) {
                 foreach ($rules as $rule => $params) {
                     $this->addRule($id, array_merge(array($rule, $field), $params));
                 }
             }
         }
     }
 }