public function handle() { require_once PATH_CORE . DS . 'components' . DS . 'com_storefront' . DS . 'models' . DS . 'Memberships.php'; $ms = new \Components\Storefront\Models\Memberships(); /* NEW $subscription = StorefrontModelMemberships::getSubscriptionObject($this->type, $this->pId, $this->uId); // Get the expiration for the current subscription (if any) $currentExpiration = $subscription->getExpiration(); */ // Get current registration $membership = $ms->getMembershipInfo($this->crtId, $this->item['info']->pId); $expiration = $membership['crtmExpires']; /* Add the user to the corresponding user access group (pull access group ID from the meta) */ try { // Get user ID for the cart require_once dirname(dirname(dirname(__DIR__))) . DS . 'models' . DS . 'Cart.php'; $userId = \Components\Cart\Models\Cart::getCartUser($this->crtId); // Get the user group ID to set the user to (from meta) require_once PATH_CORE . DS . 'components' . DS . 'com_storefront' . DS . 'models' . DS . 'Product.php'; $userGId = \Components\Storefront\Models\Product::getMeta($this->item['info']->pId, 'userGroupId'); $add = \JUserHelper::addUserToGroup($userId, $userGId); if ($add instanceof \Exception) { mail(Config::get('mailfrom'), 'Error adding to the group', $add->getMessage() . ' Cart #' . $this->crtId); } $table = \JTable::getInstance('User', 'JTable', array()); $table->load($userId); // Trigger the onAftereStoreUser event Event::trigger('onUserAfterSave', array($table->getProperties(), false, true, null)); } catch (Exception $e) { // Error return false; } }
/** * Main handler. Does all the checks * * @param void * @return void */ public function audit() { /* Membership may have a limit on when it can be extended */ /* If no user, some checks may be skipped... */ // Get user $jUser = User::getRoot(); if (!$jUser->get('guest')) { // Check if there is a limitation on when the subscription can be extended $subscriptionMaxLen = Product::getMeta($this->pId, 'subscriptionMaxLen'); if ($subscriptionMaxLen) { /* Check if the current user has the existing subscription and how much is left on it i.e. figure out if he may extend his current subscription */ /* * This is not working very well for multiple SKUs with multiple subscriptionMaxLen's * at this point code doesn't know what SKU will be added, * so for one SKU subscriptionMaxLen should * be set to time less than actual membership length, ie if membership is sold for 1 year and * cannot be renewed more than 6 month before it expires the subscriptionMaxLen must be set to 6 MONTH * if it cannot be renewed more than 3 month before it expires the subscriptionMaxLen must be set to 3 MONTH * * so subscriptionMaxLen = XX is actually "let renew XX time before expiration" */ // Get the proper product type subscription object reference $subscription = Memberships::getSubscriptionObject($this->type, $this->pId, $this->uId); // Get the expiration for the current subscription (if any) $currentExpiration = $subscription->getExpiration(); if ($currentExpiration && $currentExpiration['crtmActive']) { // Do the check $currentExpirationTime = $currentExpiration['crtmExpires']; // See if current expiration is later than max allowed time from now (max allowed time + now) if (strtotime('+' . $subscriptionMaxLen) < strtotime($currentExpirationTime)) { // Expiration is not allowed -- the current expiration is too far in the future $this->setResponseStatus('error'); $this->setResponseNotice('You already have an active subscription to this item. Subscription extension is not available at this time.'); $this->setResponseError(': you already have an active subscription. Subscription extension is not available at this time.'); } } } } return $this->getResponse(); }
/** * Populate transaction items and required steps -- cart must be synced. * * @param void * @return void */ private function populateTransaction() { // Get all cart items $cartItems = $this->cart->items; // Add cart items to transaction $sqlValues = ''; // Initialize required steps, split it into logical parts $preSteps = array(); $postSteps = array(); $warehouse = $this->warehouse; $transactionSubtotalAmount = 0; //print_r($cartItems); die; foreach ($cartItems as $sId => $skuInfo) { if ($sqlValues) { $sqlValues .= ', '; } $sqlValues .= "({$this->cart->tId}, {$sId}, {$skuInfo['cartInfo']->qty}, {$skuInfo['info']->sPrice})"; $transactionSubtotalAmount += $skuInfo['info']->sPrice * $skuInfo['cartInfo']->qty; /* Steps */ // EULA: for software, license agreement may be needed, if so, add the step for each product // get product type $productInfo = $warehouse->getProductInfo($skuInfo['info']->pId); // if soft, check if EULA is needed if ($productInfo->ptModel == 'software') { $eulaRequired = Product::getMetaValue($skuInfo['info']->pId, 'eulaRequired'); // If EULA is needed, add step, note the EULA required for each SKU, so for multiple SKUs of the same product, multiple EULA will be required if ($eulaRequired) { $step = new \stdClass(); $step->name = 'eula'; $step->meta = $sId; $preSteps[] = $step; } } // shipping: if any of the products require shipping, add the shipping step if ($skuInfo['info']->ptId == 1 && !in_array('shipping', $postSteps)) { $step = new \stdClass(); $step->name = 'shipping'; $postSteps[] = $step; } // Reserve/lock items require_once PATH_CORE . DS . 'components' . DS . 'com_storefront' . DS . 'models' . DS . 'Sku.php'; $sku = \Components\Storefront\Models\Sku::getInstance($sId); //print_r($sku); die; $sku->reserveInventory($skuInfo['cartInfo']->qty); } // add commnets/notes step $step = new \stdClass(); $step->name = 'notes'; $postSteps[] = $step; // populate items $sql = "INSERT INTO `#__cart_transaction_items` (`tId`, `sId`, `tiQty`, `tiPrice`) VALUES {$sqlValues}"; $this->_db->setQuery($sql); $this->_db->query(); // merge pre- and post- steps to ensure the correct order $steps = array_merge($preSteps, $postSteps); // populate steps foreach ($steps as $step) { if (empty($step->meta)) { $step->meta = ''; } $sql = "INSERT INTO `#__cart_transaction_steps` (`tId`, `tsStep`, `tsMeta`)\n\t\t\t\t\tVALUES ({$this->cart->tId}, '{$step->name}', '{$step->meta}')"; $this->_db->setQuery($sql); $this->_db->query(); } // get perks $perks = $this->getCouponPerks(); $perksTotalDiscount = $perks['info']->discountsTotal; // get memberships $membershipInfo = $this->getMembershipInfo(); // Initialize Meta container for all related serialized info $meta['membershipInfo'] = $membershipInfo; // Update transaction info $sql = "UPDATE `#__cart_transaction_info`\n\t\t\t\tSET\n\t\t\t\t`tiPerks` = " . $this->_db->quote(serialize($perks)) . ",\n\t\t\t\t`tiMeta` = " . $this->_db->quote(serialize($meta)) . ",\n\t\t\t\t`tiItems` = " . $this->_db->quote(serialize($cartItems)) . ",\n\t\t\t\t`tiSubtotal` = " . $this->_db->quote($transactionSubtotalAmount) . ",\n\t\t\t\t`tiDiscounts` = " . $this->_db->quote($perksTotalDiscount) . "\n\t\t\t\tWHERE `tId` = " . $this->_db->quote($this->cart->tId); $this->_db->setQuery($sql); $this->_db->query(); }
/** * Set the state of an entry * * @param integer $state State to set * @return void */ public function stateTask($state = 0) { $ids = Request::getVar('id', array()); $ids = !is_array($ids) ? array($ids) : $ids; //print_r($ids); die; // Check for an ID if (count($ids) < 1) { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller), $state == 1 ? Lang::txt('COM_STOREFRONT_SELECT_PUBLISH') : Lang::txt('COM_STOREFRONT_SELECT_UNPUBLISH'), 'error'); return; } // Update record(s) $obj = new Archive(); foreach ($ids as $pId) { // Save product try { $product = new Product($pId); $product->setActiveStatus($state); $product->save(); } catch (\Exception $e) { $error = true; } } // Set message switch ($state) { case '-1': $message = Lang::txt('COM_STOREFRONT_ARCHIVED', count($ids)); break; case '1': $message = Lang::txt('COM_STOREFRONT_PUBLISHED', count($ids)); break; case '0': $message = Lang::txt('COM_STOREFRONT_UNPUBLISHED', count($ids)); break; } $type = 'message'; if (isset($error) && $error) { switch ($state) { case '1': $action = 'published'; break; case '0': $action = 'unpublished'; break; } $message = 'Product could not be ' . $action; if (sizeof($ids) > 1) { $message = 'Some products could not be ' . $action; } $type = 'error'; } // Redirect App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller), $message, $type); }
/** * Main handler. Does all the checks * * @param void * @return void */ public function audit() { /* If no user, some checks may be skipped... */ // Get user $jUser = User::getRoot(); // User specific checks if (!$jUser->get('guest')) { if ($sId = $this->getSku()) { // Check if the current user reached the max count of downloads for this SKU $sku = new Sku($sId); $skuDownloadLimit = $sku->getMeta('downloadLimit'); if ($skuDownloadLimit > 0) { // Get SKU download count $skuDownloadCount = CartDownload::countUserSkuDownloads($this->sId, $this->uId); // Check if the limit is reached if ($skuDownloadCount >= $skuDownloadLimit) { $this->setResponseStatus('error'); $this->setResponseNotice('You have reached the maximum number of allowed downloads for this product.'); $this->setResponseError(': you have reached the maximum number of allowed downloads for this product.'); } } return $this->getResponse(); } } // Check SKU-related stuff if this is a SKU if ($sId = $this->getSku()) { // Check if SKU is reached the download max count $sku = new Sku($sId); $skuDownloadLimit = $sku->getMeta('globalDownloadLimit'); if ($skuDownloadLimit > 0) { // Get SKU download count $skuDownloadCount = CartDownload::countSkuDownloads($this->sId); // Check if the limit is reached if ($skuDownloadCount >= $skuDownloadLimit) { $this->setResponseStatus('error'); $this->setResponseNotice('This product has reached the maximum number of allowed downloads and cannot be downloaded.'); $this->setResponseError(': this product has reached the maximum number of allowed downloads and cannot be downloaded.'); } } return $this->getResponse(); } // Get product download limit $productDownloadLimit = Product::getMeta($this->pId, 'globalDownloadLimit'); // Get product downloads count if ($productDownloadLimit > 0) { $productDownloadCount = CartDownload::countProductDownloads($this->pId); // Check if the limit is reached if ($productDownloadCount >= $productDownloadLimit) { $this->setResponseStatus('error'); $this->setResponseNotice('This product has reached the maximum number of allowed downloads and cannot be downloaded.'); $this->setResponseError(': this product has reached the maximum number of allowed downloads and cannot be downloaded.'); } } return $this->getResponse(); }
/** * Get a course * * @param int course ID * @return StorefrontModelCourse Instance of a product */ public function getCourse($courseId) { $course = \Components\Storefront\Models\Product::getInstance($courseId); // check if this is a course if (!$course instanceof Course) { throw new \Exception(Lang::txt('Invalid course')); } $course->getCollections(); $course->getSkus(); return $course; }
/** * Upload a file to the wiki via AJAX * * @return string */ public function ajaxRemoveTask() { // Check for request forgeries Request::checkToken(array('get', 'post')) or jexit('Invalid Token'); // Ensure we have an ID to work with $id = Request::getInt('id', 0); if (!$id) { echo json_encode(array('error' => Lang::txt('COM_STOREFRONT_ERROR_NO_ID'))); return; } $type = strtolower(Request::getWord('type', '')); $imgId = Request::getInt('currentfile', ''); // Instantiate a model, change some info and save switch ($type) { case 'product': $product = new Product($id); $product->removeImage($imgId); break; default: echo json_encode(array('error' => Lang::txt('COM_STOREFRONT_ERROR_INVALID_TYPE'))); return; break; } if (!$product->update()) { echo json_encode(array('error' => 'Error saving product')); return; } //echo result echo json_encode(array('success' => true, 'file' => '', 'id' => $id, 'size' => 0, 'width' => 0, 'height' => 0)); }
/** * Instantiate the correct Sku for a given product * * @return StorefrontModelProduct */ private function instantiateSkuForProduct($sId, $pId) { $warehouse = new Warehouse(); // If existing SKU, load the SKU, find the product, get the product type if ($sId) { $skuInfo = $warehouse->getSkuInfo($sId); $productType = $warehouse->getProductTypeInfo($skuInfo['info']->ptId)['ptName']; } else { $product = new Product($pId); $productType = $warehouse->getProductTypeInfo($product->getType())['ptName']; } // Initialize the correct SKU based on the product type if (!empty($productType) && $productType == 'Software Download') { require_once dirname(dirname(__DIR__)) . DS . 'models' . DS . 'SoftwareSku.php'; $sku = new \Components\Storefront\Models\SoftwareSku($sId); } else { require_once dirname(dirname(__DIR__)) . DS . 'models' . DS . 'Sku.php'; $sku = new \Components\Storefront\Models\Sku($sId); } // If this is a new SKU, set the product ID if (!$sId) { $sku->setProductId($pId); } return $sku; }
/** * User agreement acceptance * * @return void */ public function eulaTask() { $cart = new CurrentCart(); $errors = array(); $transaction = $cart->liftTransaction(); if (!$transaction) { // Redirect to cart if transaction cannot be lifted $cart->redirect('home'); } $nextStep = $cart->getNextCheckoutStep(); // Double check that the current step is indeed EULA, redirect if needed if ($nextStep->step != 'eula') { $cart->redirect($nextStep->step); } // Get the SKU id of the item being displayed (from meta) $sId = $nextStep->meta; // Get the eula text for the product or EULA (EULAs are assigned to products, and if needed, SKUS) $warehouse = new Warehouse(); $skuInfo = $warehouse->getSkuInfo($sId); $this->view->productInfo = $skuInfo['info']; // Check if there is SKU EULA set if (!empty($skuInfo['meta']['eula'])) { $productEula = $skuInfo['meta']['eula']; } else { // Get product id $pId = $skuInfo['info']->pId; // Get EULA $productEula = Product::getMetaValue($pId, 'eula'); } $this->view->productEula = $productEula; $eulaSubmitted = Request::getVar('submitEula', false, 'post'); if ($eulaSubmitted) { // check if agreed $eulaAccepted = Request::getVar('acceptEula', false, 'post'); if (!$eulaAccepted) { $errors[] = array(Lang::txt('COM_CART_MUST_ACCEPT_EULA'), 'error'); } else { // Save item's meta $itemMeta = new \stdClass(); $itemMeta->eulaAccepted = true; //$itemMeta->machinesInstalled = 'n/a'; $cart->setTransactionItemMeta($sId, json_encode($itemMeta)); // Mark this step as completed $cart->setStepStatus('eula', $sId); // All good, continue $nextStep = $cart->getNextCheckoutStep()->step; $cart->redirect($nextStep); } } if (!empty($errors)) { $this->view->notifications = $errors; } if (Pathway::count() <= 0) { Pathway::append(Lang::txt(strtoupper($this->_option)), 'index.php?option=' . $this->_option); } if ($this->_task) { Pathway::append(Lang::txt('EULA')); } $this->view->display(); }
/** * Set product meta information * * @param int Product ID * @param bool Flag whether to show inactive product info * @return object Product info */ public function setProductMeta($pId, $meta) { Product::setMeta($pId, $meta); }